from decimal import Decimal

import requests
from urllib.parse import urlencode
from typing import Union, List
from modules.utils import humanbitrate
from modules.discord_helper import emoji_numbers

sessions_message = """{stream_count} stream{plural}"""
transcodes_message = """{transcode_count} transcode{plural}"""
bandwidth_message = """🌐 {bandwidth}"""
lan_bandwidth_message = """(🏠 {bandwidth})"""

session_title_message = """{count}—{icon}-{media_type_icon}-{username}: *{title}*"""
session_player_message = """__Player__: {product} ({player})"""
session_details_message = """__Quality__: {quality_profile} ({bandwidth}){transcoding}"""

status_icons = {
        "playing": "▶",
        "paused": "⏸",
        "stopped": "⏹",
        "buffering": "⏳",
        "error": "⚠"
}

def build_overview_message(stream_count=0, transcode_count=0, total_bandwidth=0, lan_bandwidth=0):
    overview_message = ""
    if int(stream_count) > 0:
        overview_message += sessions_message.format(stream_count=stream_count,
                                                    plural=('s' if int(stream_count) > 1 else ''))
    if transcode_count > 0:
        overview_message += f" ({transcodes_message.format(transcode_count=transcode_count, plural=('s' if int(transcode_count) > 1 else ''))})"
    if total_bandwidth > 0:
        overview_message += f" | {bandwidth_message.format(bandwidth=humanbitrate(float(total_bandwidth)))}"
        if lan_bandwidth > 0:
            overview_message += f" {lan_bandwidth_message.format(bandwidth=humanbitrate(float(lan_bandwidth)))}"
    return overview_message

def build_stream_message(session_data,
                         count: int = 0,
                         state: str = "",
                         username: str = "",
                         title: str = "",
                         product: str = "",
                         player: str = "",
                         quality_profile: str = "",
                         bandwidth: str = "0",
                         stream_container_decision: str = "",
                         auto_decode: bool = False):
    if auto_decode:
        state = session_data.get('state')
        username = session_data.get('username')
        title = session_data.get('full_title')
        product = session_data.get('product')
        player = session_data.get('player')
        quality_profile = session_data.get('quality_profile')
        bandwidth = session_data.get('bandwidth')
        stream_container_decision = session_data.get('stream_container_decision')
    if session_data['media_type'] == 'episode':
        title = f"{session_data.get('grandparent_title', '')} - S{session_data.get('parent_title', '').replace('Season ', '').zfill(2)}E{session_data.get('media_index', '').zfill(2)} - {session_data['title']}"
    media_type_icons = {'episode': '📺', 'track': '🎧', 'movie': '🎞', 'clip': '🎬', 'photo': '🖼'}
    if session_data['media_type'] in media_type_icons:
        media_type_icon = media_type_icons[session_data['media_type']]
    else:
        media_type_icon = '🎁'
    return f"{session_title_message.format(count=emoji_numbers[count - 1], icon=select_icon(state=state), username=username, media_type_icon=media_type_icon, title=title)}\n" \
           f"{session_player_message.format(product=product, player=player)}\n" \
           f"{session_details_message.format(quality_profile=quality_profile, bandwidth=(humanbitrate(float(bandwidth)) if bandwidth != '' else '0'), transcoding=(' (Transcode)' if stream_container_decision == 'transcode' else ''))}"

def select_icon(state):
    return status_icons.get(state, "")

def _stat_category_to_number(stat_category: str) -> Union[int, None]:
    translations = {
        'movies': 0,
        'shows': 1,
        'artists': 2,
        'users': 7
    }
    return translations.get(stat_category, None)

class TautulliHomeStatsCategory:
    def __init__(self, data: dict):
        self._data = data
        self.name = data.get('stat_id')
        self.type = data.get('stat_type')
        self.rows = data.get('rows')

class TautulliHomeStats:
    def __init__(self, data: dict):
        self._data = data
        self.stats = [TautulliHomeStatsCategory(data=category) for category in data]

    def get_category(self, category_name: str) -> Union[TautulliHomeStatsCategory, None]:
        for category in self.stats:
            if category.name == category_name:
                return category
        return None

class TautulliWatchTimeStat:
    def __init__(self, data: dict):
        self._data = data
        self.days = data.get('query_days')
        self.plays = data.get('total_plays')
        self.time = data.get('total_time')

class TautulliWatchTimeStats:
    def __init__(self, data: dict):
        self._data = data
        self.stats = [TautulliWatchTimeStat(data=stat) for stat in data]

    def get_by_day(self, days: int) -> Union[TautulliWatchTimeStat, None]:
        for stat in self.stats:
            if stat.days == days:
                return stat
        return None

class TautulliUser:
    def __init__(self, data: dict, api):
        self._data = data
        self._api = api
        self.username = data.get('username')
        self.id = data.get('user_id')
        self.shared_libraries = data.get('shared_libraries').split(";")

class TautulliConnector:
    def __init__(self, url: str, api_key: str):
        if url.endswith("/"):
            url = url[:-1]
        self.url = f"{url}/api/v2?apikey={api_key}"

    def _create_url(self, command, params=None) -> str:
        url = f"{self.url}&cmd={command}"
        if params:
            url += f"&{urlencode(params)}"
        return url

    def _get(self, command, params=None) -> Union[requests.Response, None]:
        try:
            url = self._create_url(command=command, params=params)
            return requests.get(url=url)
        except:
            return None

    def _get_json(self, command, params=None) -> Union[dict, None]:
        try:
            return self._get(command=command, params=params).json()
        except:
            return None

    # USERS

    @property
    def users(self) -> List[TautulliUser]:
        json_data = self._get_json(command='get_users')
        if json_data:
            return [TautulliUser(data=user, api=self) for user in json_data['response']['data']]
        return []

    def get_user_watch_time_stats(self, user_id: str, days: List[int] = None) -> Union[TautulliWatchTimeStats, None]:
        params = {'user_id': user_id}
        if days:
            params['query_days'] = ','.join(map(str, days))
        json_data = self._get_json(command="get_user_watch_time_stats", params=params)
        if json_data:
            return TautulliWatchTimeStats(data=json_data['response']['data'])
        return None

    def get_user_ips(self, user_id: str) -> dict:
        json_data = self._get_json(command='get_user_ips', params={'user_id': user_id, 'order_column': 'last_seen'})
        if json_data:
            return json_data['response']['data']
        return {}

    def get_last_time_user_seen(self, user_id: str) -> int:
        user_ips = self.get_user_ips(user_id=user_id)
        if not user_ips:
            return 0
        return user_ips[0]['last_seen']

    def refresh_users(self) -> bool:
        if self._get(command='refresh_users_list'):
            return True
        return False

    def delete_user(self, plex_username: str) -> bool:
        if self._get(command='delete_user', params={'user_id': plex_username}):
            return True
        return False

    # ACTIVITY

    def home_stats(self, time_range: int = 30, stat_category: str = 'user', stat_type: str = 'duration', stat_count: int = 5) -> Union[TautulliHomeStats, None]:
        category_number = _stat_category_to_number(stat_category=stat_category)
        if not category_number:
            return None
        params = {'time_range': time_range,
                  'stats_type': stat_type,
                  'stats_count': stat_count}
        json_data = self._get_json(command='get_home_stats', params=params)
        if json_data:
            return TautulliHomeStats(data=json_data['response']['data'])
        return None

    @property
    def current_activity(self) -> dict:
        json_data = self._get_json(command="get_activity")
        if json_data:
            return json_data['response']['data']
        return {}

    # MEDIA

    @property
    def libraries(self) -> dict:
        json_data = self._get_json(command="get_libraries")
        if json_data:
            return json_data['response']['data']
        return {}

    def get_library_media_info(self, section_id: str) -> dict:
        json_data = self._get_json(command='get_library_media_info', params={'section_id': section_id})
        if json_data:
            return json_data['response']['data']
        return {}

    def recently_added(self, count: int = 5) -> dict:
        json_data = self._get_json(command='get_recently_added', params={'count': count})
        if json_data:
            return json_data['response']['data']
        return {}

    def image_thumb_url(self, thumb: str) -> str:
        return f'{self.url}&cmd=pms_image_proxy&img={thumb}'

    def delete_image_cache(self) -> bool:
        if self._get(command='delete_image_cache'):
            return True
        return False

    def search(self, keyword: str) -> dict:
        json_data = self._get_json(command='search', params={'query': keyword})
        if json_data:
            return json_data['response']['data']
        return {}

    # SESSIONS

    def terminate_session(self, session_id, message: str = None) -> bool:
        params = {'session_id': session_id}
        if message:
            params['message'] = message
        if self._get(command='terminate_session', params=params):
            return True
        return False


import logging
logging.basicConfig(filename="SwapNumber.py", filemode="w")
def swap_numbers(num1, num2):
    """
    :param num1:
    :param num2:
    :return:
    """
    temp = num1
    num1 = num2
    num2 = temp
    print("After swapping, number1 is %d and number2 is %d"% (num1, num2))

if __name__ == '__main__':
    try:
        num1 = int(input("Enter number1: "))
        num2 = int(input("Enter number2: "))
        print("Before swapping, number1 is %d and number2 is %d"% (num1, num2))
        swap_numbers(num1, num2)
    except:
        print("Enter valid number")


import dropbox
import csv

client = dropbox.Dropbox('XXXXXXXXXXXXXXXXXXXXXXXXX')
# print(client.users_get_current_account())
metadata = client.files_list_folder('/All onboard images').entries
# metadata = metadata.json()
#print(metadata)

with open('dates.csv', mode='w') as metadata_file:
    writer = csv.writer(metadata_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

    writer.writerow(['date','filename'])

    for i in range(0, 10):
        #print(metadata[i].client_modified)
        #print(metadata[i].name)

        dates = metadata[i].client_modified

        files = metadata[i].name

        writer.writerow([dates,files])


# coding:UTF-8
import argparse
import os
import glob
import cv2
import numpy as np
import tqdm

import torch
import torchvision
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as data
from torch.utils.data import TensorDataset, DataLoader
from torchvision import models, transforms

from srcnn_model import srcnn_net
"""
画像を拡大するネットワーク
"""

class SrcnnDataSet(data.Dataset):
    """
    ジェネレータークラス
    """
    def __init__(self, file_list, transforms=None):
        self.img_file_list = file_list
        self.transform = transforms

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

    def __getitem__(self, index):
        anno_img = cv2.imread(self.img_file_list[index])
        #img = cv2.resize(img, (960, 1280)) #あまりに大きい画像が来るとエラーになるため
        o_h, o_w = anno_img.shape[0:2]
        anno_img = anno_img.astype(np.float32)
        anno_img = anno_img.T/255.

        img = cv2.imread(self.img_file_list[index])
        img = cv2.resize(img, (int(o_w/4), int(o_h/4)))
        img = cv2.resize(img, (o_w, o_h))
        img = img.astype(np.float32)
        img = img.T/255.

        return img, anno_img

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="srcnn")
    parser.add_argument('--train_dir', help="学習データがあるディレクトリ", default='train')
    parser.add_argument('--val_dir', help="検証用データがあるディレクトリ", default='val')
    parser.add_argument('--weights_dir', help="pthファイルの出力先ディレクトリ", default='weights')
    parser.add_argument('--batch_size', help="ミニバッチのサイズ", default=4, type=int)
    parser.add_argument('--device', help="GPU", default="cuda:1")
    parser.add_argument('--epochs', help="GPU", default=100, type=int)

    args = parser.parse_args()

    train_path = args.train_dir
    val_path = args.val_dir
    weights_path = args.weights_dir
    batch_size = args.batch_size
    device = args.device
    epochs = args.epochs

    # 訓練用画像のファイルリスト取得
    train_img_list = []
    tmp_img_list = glob.glob(os.path.join(train_path, "*.jpg"))
    for filename in tmp_img_list:
        s = os.path.getsize(filename)
        if s > 30*1000:
            train_img_list.append(filename)

    # 検証用画像のファイルリスト取得
    val_img_list = glob.glob(os.path.join(val_path, "*.jpg"))

    # ジェネレーター作成
    train_dataset = SrcnnDataSet(train_img_list, transforms=transforms.ToTensor())
    train_loader = DataLoader(train_dataset, batch_size, shuffle=True)

    net = srcnn_net().to(device)
    net.train()

    # 損失関数は最小二乗法
    loss_fn = nn.MSELoss()

    optimizer = optim.Adam(net.parameters())

    for epoch in range(epochs):
        print("epoch:{}/{}".format(epoch, epochs))
        loss_val = 0.0
        for i, (img, anno_img) in tqdm.tqdm(enumerate(train_loader), total=len(train_loader)):
            x = img.to(device)
            y = anno_img.to(device)
            p = net(x)
            loss = loss_fn(x, p)
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            loss_val += loss.item()

        print("loss:{:.05f}".format(loss_val))
        output_pth = os.path.join(weights_path, "srcnn-{}.pth".format(epoch))
        if not os.path.exists(weights_path):
            os.makedirs(weights_path)
        torch.save(net.state_dict(), output_pth)


from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()

# Create your models here.
class Url(models.Model):
    url = models.CharField(max_length=500)

    user = models.ForeignKey(
        to=User,
        on_delete=models.SET_NULL,
        null=True,
        blank=False,
    )

    interval = models.IntegerField(
        default=10,
        help_text="Interval of checking in seconds"
    )

    is_paused = models.BooleanField(default=False)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.url


from dajaxice.decorators import dajaxice_register
from dajax.core import Dajax
from userprofile.models import UserProfile
from userprofile.forms import UserProfileForm
from django.template.loader import render_to_string
from django.template.context import RequestContext
from dajaxice.utils import deserialize_form
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse, reverse_lazy
from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from project.permissions import PermissionHandler
from project.models import *
from project.views import *
import datetime

# some function decorators
def value_error_feedback( in_func ):
	def out_func( *args, **kwargs ):
		try:
			import pdb;pdb.set_trace()
			in_func( *args, **kwargs )
		except ValueError as e:
			if (len(e.args) == 2):	# intercept special value errors
				dajax = Dajax()
				# write scripts to be executed on the client side to inform the client of the value error in a proper manner.
				dajax.scripts('document.getElementById("'+e.args[1]+'").innerHTML = "'+e.args[0]+'"')
				return dajax.json()

	return out_func

@dajaxice_register
def create_blank_project( request, **kwargs):
  if( not PermissionHandler.create_project(request.user, **kwargs ) ): # check for permission using the permissions module.
    raise PermissionDenied( 'You do NOT have permission to create a project :P' )

  project = Project()
  project.desc = 'Detailed Writeup'
  project.brief = 'Brief Writeup'
  project.status = 'Sample Status'
  project.name = 'Sample Name'
  project.budget = 0
  project.year = str(datetime.datetime.today().year)
  project.club = get_object_or_404( Club, pk = kwargs['club'])
  project.save()

  dajax = Dajax()
  dajax.script('window.location=\''+reverse('project:project_detail', args=[project.pk])+'\'')
  return dajax.json()

@dajaxice_register
def add_core_to_club( request, **kwargs):
	#if( not PermissionHandler.add_cores_to_club(request.user, **kwargs ) ): # check for permission using the permissions module.
	#	raise PermissionDenied( 'You do NOT have permission to add cores :P' )

	#import pdb;pdb.set_trace()
	club = get_object_or_404( Club, pk = kwargs['club'] )
	core_list = kwargs['convenors']
	for core_id in core_list:
		core = get_object_or_404( User, pk=core_id )
		if not core in club.cores.all():
			club.cores.add(core)

	club.save()

	dajax = Dajax()
	dajax.alert('successfully added '+format(len(kwargs['convenors'])))
	return dajax.json()

@dajaxice_register
def add_user_to_project( request, **kwargs):
	#if( not PermissionHandler.add_cores_to_club(request.user, **kwargs ) ): # check for permission using the permissions module.
	#	raise PermissionDenied( 'You do NOT have permission to add cores :P' )

	#import pdb;pdb.set_trace()
	project = get_object_or_404( Project, pk = kwargs['project'] )
	user_list = kwargs['users']
	for user_id in user_list:
		user = get_object_or_404( User, pk=user_id )
		if not user in project.users.all():
			project.users.add(user)

	project.save()

	dajax = Dajax()
	dajax.alert('successfully added '+format(len(kwargs['users']))+ ' users')
	return dajax.json()

@dajaxice_register
def add_mentor_to_project( request, **kwargs):
	#if( not PermissionHandler.add_cores_to_club(request.user, **kwargs ) ): # check for permission using the permissions module.
	#	raise PermissionDenied( 'You do NOT have permission to add cores :P' )

	#import pdb;pdb.set_trace()
	project = get_object_or_404( Project, pk = kwargs['project'] )
	mentor_list = kwargs['mentors']
	for mentor_id in mentor_list:
		mentor = get_object_or_404( User, pk=mentor_id )
		if not mentor in project.mentors.all():
			project.mentors.add(mentor)

	project.save()

	dajax = Dajax()
	dajax.alert('Successfully added '+format(len(kwargs['mentors']))+ ' mentors')
	return dajax.json()

@dajaxice_register
def create_blank_club( request, **kwargs):
	if( not PermissionHandler.create_club(request.user, **kwargs ) ): # check for permission using the permissions module.
		raise PermissionDenied( 'You do NOT have permission to create a club :P' )

	club = Club()
	club.description = 'Detailed Writeup'
	club.name = 'Sample Name'
	club.save()

	dajax = Dajax()
	#dajax.script('window.location=\'http://localhost:8000/club/'+format(club.pk)+'/\'')
	dajax.script('window.location=\''+reverse('project:club_detail',args=[club.pk])+'\'')
	return dajax.json()

@dajaxice_register
def delete_document( request, **kwargs ):

	doc = get_object_or_404( Document, pk = kwargs['doc'] )

	if( (not PermissionHandler.delete_document(request.user, **kwargs )) ): # check for permission using the permissions module.
		raise PermissionDenied( 'You do NOT have permission to create a club :P' )

	doc.delete()

	dajax = Dajax()
	dajax.script('location.reload(true)')
	return dajax.json()

@dajaxice_register
def comment_on_update( request, **kwargs ):

	if( (not PermissionHandler.create_comment(request.user, **kwargs )) ): # check for permission using the permissions module.
		raise PermissionDenied( 'You do NOT have permission to make comments :P' )

	comment = Comment( user = request.user, content = kwargs['content'] )
	comment.save()

	update = get_object_or_404( Update, pk = kwargs['update'] )
	update.comments.add(comment)
	update.save()

	dajax = Dajax()
	dajax.script('location.reload(true)')
	return dajax.json()

@dajaxice_register
def comment_on_task( request, **kwargs ):

	if( (not PermissionHandler.create_comment(request.user, **kwargs )) ): # check for permission using the permissions module.
		raise PermissionDenied( 'You do NOT have permission to make comments :P' )

	comment = Comment( user = request.user, content = kwargs['content'] )
	comment.save()

	task = get_object_or_404( Task, pk = kwargs['task'] )
	task.comments.add(comment)
	task.save()

	dajax = Dajax()
	dajax.script('location.reload(true)')
	return dajax.json()

@dajaxice_register
def delete_update( request, **kwargs ):

	update = get_object_or_404( Update, pk = kwargs['update'] )

	if( (not PermissionHandler.delete_update(request.user, **kwargs )) ): # check for permission using the permissions module.
		dajax = Dajax()
		dajax.alert('You do NOT have this permission')
		return dajax.json()

	update.delete()

	dajax = Dajax()
	dajax.script('location.reload(true)')
	return dajax.json()

@dajaxice_register
def delete_task( request, **kwargs ):

	task = get_object_or_404( Task, pk = kwargs['task'] )

	if( (not PermissionHandler.delete_task(request.user, **kwargs )) ): # check for permission using the permissions module.
		dajax = Dajax()
		dajax.alert('You do NOT have this permission')
		return dajax.json()

	task.delete()

	dajax = Dajax()
	dajax.script('location.reload(true)')
	return dajax.json()

@dajaxice_register
def delete_comment( request, **kwargs ):

	comment = get_object_or_404( Comment, pk = kwargs['comment'] )

	if( (not PermissionHandler.delete_comment(request.user, **kwargs )) ): # check for permission using the permissions module.
		dajax = Dajax()
		dajax.alert('You do NOT have this permission')
		return dajax.json()

	for update in Update.objects.filter( comments__in = [comment] ):
		update.commments.remove(comment)

	for task in Task.objects.filter( comments__in = [comment] ):
		task.commments.remove(comment)

	comment.delete()

	dajax = Dajax()
	dajax.script('location.reload(true)')
	return dajax.json()

@dajaxice_register
def remove_user_from_project( request, **kwargs ):

	user = get_object_or_404( User, pk = kwargs['user'] )
	project = get_object_or_404( Project, pk = kwargs['project'] )

	if( (not PermissionHandler.remove_user_from_project( request.user, **kwargs )) ): # check for permission using the permissions module.
		dajax = Dajax()
		dajax.alert('You do NOT have this permission')
		return dajax.json()

	if user in project.users.all():
		project.users.remove( user )
	else:
		raise ValueError('User does not belong to this project')

	dajax = Dajax()
	dajax.script('location.reload(true)')
	return dajax.json()

@dajaxice_register
def remove_mentor_from_project( request, **kwargs ):

	mentor = get_object_or_404( User, pk = kwargs['mentor'] )
	project = get_object_or_404( Project, pk = kwargs['project'] )

	if( (not PermissionHandler.remove_mentor_from_project( request.user, **kwargs )) ): # check for permission using the permissions module.
		dajax = Dajax()
		dajax.alert('You do NOT have this permission')
		return dajax.json()

	if mentor in project.mentors.all():
		project.mentors.remove( mentor )
	else:
		raise ValueError('User does not belong to this project')

	dajax = Dajax()
	dajax.script('location.reload(true)')
	return dajax.json()

@dajaxice_register
def remove_core_from_club( request, **kwargs ):

	core = get_object_or_404( User, pk = kwargs['core'] )
	project = get_object_or_404( Project, pk = kwargs['project'] )

	if( (not PermissionHandler.remove_core_from_club( request.user, **kwargs )) ): # check for permission using the permissions module.
		dajax = Dajax()
		dajax.alert('You do NOT have this permission')
		return dajax.json()

	if core in club.cores.all():
		club.cores.remove( core )
	else:
		raise ValueError('User does not belong to this club')

	dajax = Dajax()
	dajax.script('location.reload(true)')
	return dajax.json()

@dajaxice_register
def add_update( request, **kwargs ):

	import pdb;pdb.set_trace()
	project = get_object_or_404( Project, pk = kwargs['project'] )

	if( (not PermissionHandler.create_update( request.user, **kwargs )) ): # check for permission using the permissions module.
		dajax = Dajax()
		dajax.alert('You do NOT have this permission')
		return dajax.json()

	# error handling for form data
	# controller input data checking

	try:
		if 'content' not  in kwargs.keys() or kwargs['content'] == '':
			raise ValueError('Content missing..',kwargs['content_feedback_field']) # controller feedback

		if 'title' not in kwargs.keys() or kwargs['title'] == '':
			raise ValueError('Title missing..',kwargs['title_feedback_field']) # controller feedback
	except ValueError as e:
		if (len(e.args) == 2):	# intercept special value errors
			dajax = Dajax()
			# prepare the feedback handles.
			for x in ['content','title']:
				dajax.script('document.getElementById("'+kwargs[x+'_feedback_field']+'").innerHTML = ""')

			# write scripts to be executed on the client side to inform the client of the value error in a proper manner.
			dajax.script('document.getElementById("'+e.args[1]+'").innerHTML = "'+e.args[0]+'"')
			return dajax.json()

	# controller operation
	update = Update()
	update.parent = project
	update.content = kwargs['content']
	update.title = kwargs['title']
	update.user = request.user
	update.save()

	dajax = Dajax()
	dajax.script('location.reload(true)')
	return dajax.json()

@value_error_feedback
@dajaxice_register
def add_task( request, **kwargs ):

	project = get_object_or_404( Project, pk = kwargs['project'] )

	# controller auth checking.
	if( (not PermissionHandler.create_update( request.user, **kwargs )) ): # check for permission using the permissions module.
		dajax = Dajax()	# controller feedback
		dajax.alert('You do NOT have this permission')
		return dajax.json()

	# error handling for form data
	# controller input data checking
	try:
		for x in ['content','title','deadline']:
			if x not in kwargs.keys() or kwargs[x] == '':
				if x+'_feedback_field' in kwargs.keys():
					raise ValueError(x+' missing..',kwargs[x+'_feedback_field']) # controller feedback
				else:
					raise ValueError(x+' missing..')
	except ValueError as e:
		if (len(e.args) == 2):	# intercept special value errors
			dajax = Dajax()
			# clear feedback fields. controller feedback initialization
			for x in ['content','title','deadline']:
				dajax.script('document.getElementById("'+kwargs[x+'_feedback_field']+'").innerHTML = ""')
			# write scripts to be executed on the client side to inform the client of the value error in a proper manner.
			dajax.script('document.getElementById("'+e.args[1]+'").innerHTML = "'+e.args[0]+'"')
			return dajax.json()

	# controller operation
	task = Task()
	task.content = kwargs['content']
	task.title = kwargs['title']
	task.deadline = kwargs['deadline']
	task.parent = project

	if 'assignees' in kwargs.keys():
		for i in kwargs['assignees']:
			user = get_object_or_404( User, pk=i )
			task.assigned.add(user)

	task.user = request.user
	task.save()

	# controller response on success.
	dajax = Dajax()
	dajax.script('location.reload(true)')
	return dajax.json()

@dajaxice_register
def search( request, *args, **kwargs ):
	pass


from typing import List, Dict

import nltk
import scipy
from sentence_transformers import SentenceTransformer

from text_api.models import Text

class SentenceEmbedding:
    top_amount_results: int = 20

    def __init__(self, sentence: str, slug: str):
        """sentence to compare with"""
        self.sentence: str = sentence
        # slug of sentence text
        self.slug: str = slug
        self.texts: List[Text] = self._get_texts()
        # Sentence Embedding used with SentenceBERT model
        self.model: SentenceTransformer = SentenceTransformer('bert-base-nli-mean-tokens')
        self.results: List[Dict[str, str]] = []

    @classmethod
    def run(cls, sentence: str, slug: str) -> List[Dict[str, str]]:
        """starting point"""
        obj = cls(sentence, slug)
        obj.search()
        obj.sort_results()

        return obj.results

    def _get_texts(self) -> List[Text]:
        """find all texts except current"""
        return Text.query.filter(Text.slug != self.slug).all()

    @staticmethod
    def _convert_text_sentences(text: str) -> List[str]:
        """convert text to sentences"""
        return nltk.tokenize.sent_tokenize(text)

    def search(self) -> None:
        """define search query and embed into vector"""
        query = self.model.encode(self.sentence)
        # iterate through texts
        for text in self.texts:
            self._calculate_text_result(text, query)

    def _calculate_text_result(self, text: Text, query: List):
        """create vector from sentence we try to compare with needed"""
        corpus = self._convert_text_sentences(text.content)
        corpus_embeddings = self.model.encode(corpus)
        # compute the cosine similarity with scipy
        distances = scipy.spatial.distance.cdist([query], corpus_embeddings, 'cosine')[0]

        # merge distances with ids and sort
        results = zip(range(len(distances)), distances)
        results = sorted(results, key=lambda x: x[1])

        # create result's dictionary with top distance
        for idx, distance in results[:self.top_amount_results]:
            self.results.append({
                'sentence': corpus[idx].strip(),
                'distance': 1 - distance,
                'slug': text.slug,
            })

    def sort_results(self) -> None:
        """sort reverse results"""
        self.results = sorted(self.results, key=lambda r: r['distance'], reverse=True)


import datetime
from unittest import TestCase
from unittest.mock import patch

from backend import slack_util, db, match_making, configs
from backend.commands import user_stats
from backend.commands.command_message import CommandMessage
from backend.league_context import LeagueContext
from tests import test_league_setup

lctx = None

class Test(TestCase):
    def setUp(self):
        test_league_setup.teardown_test_league()
        test_league_setup.create_test_league()

        league_name = 'unittest'
        global lctx
        lctx = LeagueContext.load_from_db(league_name)

        for g in ['A', 'B', 'C']:
            for i in range(1, 9):
                db.add_player(lctx.league_name, 'player{}{}'.format(g, i), 'Player {}{}'.format(g, i), g)

        match_making.create_matches_for_season(lctx.league_name, datetime.date(2022, 1, 3), 3, [])

        for i in range(2, 9):
            db.update_match_by_id(lctx.league_name, 'playerA1', 'playerA{}'.format(i), 3, 0, 0)
        for i in range(2, 9):
            db.update_match_by_id(lctx.league_name, 'playerB1', 'playerB{}'.format(i), 3, 1, 0)
        for i in range(2, 9):
            db.update_match_by_id(lctx.league_name, 'playerC1', 'playerC{}'.format(i), 3, 2, 0)

        # new season with more sets needed
        match_making.create_matches_for_season(lctx.league_name, datetime.date(2022, 1, 3), 4, [])
        for i in range(2, 9):
            db.update_match_by_id(lctx.league_name, 'playerA1', 'playerA{}'.format(i), 4, 1, 0)
        for i in range(2, 9):
            db.update_match_by_id(lctx.league_name, 'playerB1', 'playerB{}'.format(i), 4, 2, 0)
        for i in range(2, 9):
            db.update_match_by_id(lctx.league_name, 'playerC1', 'playerC{}'.format(i), 4, 3, 0)

    def test_handles_message(self):
        self.assertEqual(True, user_stats.handles_message(lctx, CommandMessage('My ToTaL StAtS', 'Dchannel', 'any_user', 'any_timestamp')))
        self.assertEqual(False, user_stats.handles_message(lctx, CommandMessage('My ToTaL StAtS', 'any_channel', 'any_user', 'any_timestamp')))
        self.assertEqual(False, user_stats.handles_message(lctx, CommandMessage('a my total stats', 'any_channel', 'any_user', 'any_timestamp')))
        self.assertEqual(False, user_stats.handles_message(lctx, CommandMessage('my total stats and more', 'any_channel', 'any_user', 'any_timestamp')))
        self.assertEqual(False, user_stats.handles_message(lctx, CommandMessage('just stats', 'any_channel', 'any_user', 'any_timestamp')))

        db.set_config(lctx.league_name, configs.ENABLE_COMMAND_USER_STATS, 'FALSE')
        fresh_lctx = LeagueContext.load_from_db(lctx.league_name)
        self.assertEqual(False, user_stats.handles_message(fresh_lctx, CommandMessage('My ToTaL StAtS', 'Dchannel', 'any_user', 'any_timestamp')))

    def test_build_stat_message(self):
        matches = db.get_matches(lctx.league_name)
        result = user_stats.build_stat_message(matches, 'playerA1')
        self.assertEqual('\n Matches Won: 14 | Matches Lost: 0 | Sets Won: 49 | Sets Lost: 7', result)

        result = user_stats.build_stat_message(matches, 'playerA2')
        self.assertEqual('\n Matches Won: 0 | Matches Lost: 2 | Sets Won: 1 | Sets Lost: 7', result)

    @patch.object(slack_util, 'post_message')
    def test_handle_message(self, mock_post_message):
        matches = db.get_matches(lctx.league_name)
        msg = CommandMessage('help', 'Dchannel', 'playerA1', 'any_timestamp')
        user_stats.handle_message(lctx, msg)
        mock_post_message.assert_called_once_with(lctx, user_stats.build_stat_message(matches, 'playerA1'), 'Dchannel')


# -*- coding: utf-8 -*-
# File: predict_cam.py
# @Author: 黄文俊

# @Time: 2021/12/10 15:58
import joblib
import numpy as np
import cv2
from numpy import ndarray

from webcam_base import CameraThread, thread_lock

class CameraThreadPredict(CameraThread):
    """
    实时颜色识别类，继承CameraThread父类
    """

    def __init__(self, *args, **kwargs):
        super(CameraThreadPredict, self).__init__(*args, **kwargs)
        # 预加载模型
        self.clf = joblib.load("../imgs/svm.model")

    def pretreatment_frame(self, img: ndarray) -> ndarray:
        """
        对视频帧预处理
        :param img:视频帧
        :return 绘制完轮廓矩形框后的视频帧
        """
        contours = self.find_counters(img)
        img = img.copy()
        for cnt in contours:
            try:
                l_corner, r_corner, mid, rect_area = self._find_img_mid_point(cnt)
                # img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
                print(rect_area)
                if 8000  > rect_area > 5000:
                    res = self.predict_color(mid['x'], mid['y'], img)
                    # 圈出颜色块
                    img = cv2.rectangle(img, l_corner, r_corner, (0, 255, 0), 2)
                    # 在色块上打上识别结果
                    img = cv2.putText(img, res, (mid['x'], mid['y']), cv2.FONT_HERSHEY_SIMPLEX, 2.0, (255, 255, 255), 5,
                                      cv2.LINE_AA, False)
                else:
                    continue
            except Exception as e:
                print(e)
                continue
        return img

    def predict_color(self, mid_x: int, mid_y: int, img: ndarray) -> str:
        """
        截取基于中点的 25*25*3的截图与模型匹配获取识别结果并在原图绘制轮廓矩形框以及识别结果
        :param mid_x:轮廓中点x轴坐标
        :param mid_y:轮廓中点y轴坐标
        :param img:视频帧
        :return 识别结果
        """
        # 基于中点要检测的位置
        check_img = img[mid_y - 12:mid_y + 13, mid_x - 12:mid_x + 13]
        # 图片归一化处理
        img_normalization = (check_img - np.min(check_img)) / (np.max(check_img) - np.min(check_img))
        # 二维向量转为一维向量
        one_vector = np.reshape(img_normalization, (1, -1))
        # 模型匹配结果
        res = self.clf.predict(one_vector)
        print(res)
        return res[0]

def main():
    camera_id = "rtsp://admin:admin@192.168.101.5:8554/live"

    thread = CameraThreadPredict(camera_id)
    thread.start()

    while True:
        thread_lock.acquire()
        frame = thread.get_frame()
        thread_lock.release()

        frame = thread.pretreatment_frame(frame)
        cv2.imshow('Video', frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            thread_lock.acquire()
            thread.set_thread_exit(True)
            thread_lock.release()
            break

    thread.join()
    cv2.destroyAllWindows()

if __name__ == "__main__":
    main()


import pandas as pd
from datetime import date

df = pd.read_csv('./basic_per_game_player_stats_2013_2018.csv')

df = df.fillna(0)

stats_column_names = 'GS,MP,FG,FGA,"FG%","2P","2PA","2P%","3P","3PA","3P%",FT,FTA,"FT%",ORB,DRB,TRB,AST,STL,BLK,TOV,PF,PTS'

season_dict = {
    "13-14": {
        "start": "2013-10-29",
        "end": "2014-05-12"
    },
    "14-15": {
        "start": "2014-10-21",
        "end": "2015-05-04"
    },
    "15-16": {
        "start": "2015-10-14",
        "end": "2016-04-26"
    },
    "16-17": {
        "start": "2016-10-05",
        "end": "2017-04-18"
    },
    "17-18": {
        "start": "2017-09-28",
        "end": "2018-04-11"
    },
}

match_list = []

def get_season(target_date):
    for season in season_dict:
        start_date = season_dict[season]["start"]
        end_date = season_dict[season]["end"]
        if (date.fromisoformat(start_date) <= date.fromisoformat(target_date) <= date.fromisoformat(end_date)):
            return season

def check_match_existence(target_date, home_team, away_team):
    if len(match_list) == 0:
        return False

    for match in match_list:
        if date.fromisoformat(match["date"]) == date.fromisoformat(target_date) and home_team == match["home_team"] and away_team == match["away_team"]:
            return True

    return False

with open('load.sql', 'w') as file:
    # Insert Team data
    teams = pd.unique(df['Tm'])

    file.write("delete from match;\n")
    file.write("delete from player;\n")
    file.write("delete from playerstats;\n")
    file.write("delete from season;\n")
    file.write("delete from team;\n\n")

    for team in teams:
        file.write(f"insert into Team(name) values ('{team}');")
        file.write("\n")

    file.write("\n")

    # Insert Season data
    for season in season_dict:
        start_date = season_dict[season]["start"]
        end_date = season_dict[season]["end"]
        file.write(
            f"insert into Season(name, start_date, end_date) values ('{season}', '{start_date}', '{end_date}');")
        file.write("\n")

    file.write("\n")

    # Insert Player data
    players = pd.unique(df['Player'])

    for player in players:
        player_wo_nickname = player.split("\\")[0]

        if "'" in player_wo_nickname:
            split_name = player_wo_nickname.split("'")
            player_wo_nickname = split_name[0] + "''" + split_name[1]

        file.write(
            f"insert into Player(name) values ('{player_wo_nickname}');")
        file.write("\n")

    file.write("\n")

    # Insert Match data
    for index, row in df.iterrows():
        player_wo_nickname = row["Player"].split("\\")[0]
        home_team = ''
        away_team = ''
        target_date = row["Date"]
        home_or_away = ''
        age = row["Age"]

        if "'" in player_wo_nickname:
            split_name = player_wo_nickname.split("'")
            player_wo_nickname = split_name[0] + "''" + split_name[1]

        if row['At'] == '@':
            home_team = row['Opp']
            away_team = row['Tm']
            home_or_away = 'away'
        else:
            home_team = row['Tm']
            away_team = row['Opp']
            home_or_away = 'home'

        season = get_season(target_date)
        if not check_match_existence(target_date, home_team, away_team):
            match_list.append({
                "date": target_date,
                "home_team": home_team,
                "away_team": away_team
            })
            file.write(
                (
                    f'insert into Match (date, season_id, home_team_id, away_team_id)\n'
                    f"select '{target_date}', s.id, t1.id, t2.id\n"
                    f'from Season s, Team t1, Team t2\n'
                    f"where s.name = '{season}' AND t1.name = '{home_team}' AND t2.name = '{away_team}';\n\n"
                )
            )

        # Insert Player Stats
        stats_str = ','.join(list(row[9:32].apply(str)))
        # print(",".join(row[9:33].index.tolist()))
        file.write(
            (
                f'insert into PlayerStats (player_id, match_id, home_or_away, age, {stats_column_names})\n'
                f"select p.id, m.id, '{home_or_away}', '{age}', {stats_str}\n"
                f'from Player p, Match m, Team t1, Team t2\n'
                f'where m.home_team_id = t1.id AND m.away_team_id = t2.id\n'
                f"AND m.date = '{target_date}'\n"
                f"AND p.name = '{player_wo_nickname}' AND t1.name = '{home_team}' AND t2.name = '{away_team}';\n\n"
            )
        )

        file.write('\n')


import warnings

from django.core.exceptions import ImproperlyConfigured
from django.forms.widgets import MediaDefiningClass
from django.template.loader import get_template
from django.utils import six, translation
from django.utils.text import slugify

class LayoutNode(six.with_metaclass(MediaDefiningClass, object)):
    """Base class for self-rendered nodes."""

    span_columns = 1
    template_name = None

    def get_template(self):
        if self.template_name is None:
            raise ImproperlyConfigured(
                "Dasbboard node requires either a definition of "
                "'template_name' or an implementation of 'get_template()'")
        return get_template(self.template_name)

    def get_context_data(self):
        """Additional context data to render node template.
        Subclasses could override it.
        """
        return {
            'parent': self
        }

    def render(self, context, **options):
        with context.push(**self.get_context_data()):
            template = self.get_template()
            return template.render(context.flatten())

class Callable(LayoutNode):
    def __init__(self, handler):
        self.handler = handler

    def render(self, context, **options):
        return self.handler(context)

def _convert_to_nodes(children):
    result = []
    for child in children:
        if isinstance(child, LayoutNode):
            result.append(child)
        elif isinstance(child, (list, tuple)):
            result.append(Row(*child))
        elif callable(child):
            result.append(Callable(child))
        else:
            raise ImproperlyConfigured('Unknown child type {}'.format(child))
    return result

class Row(LayoutNode):
    template_name = 'dashboard/row.html'

    def __init__(self, *children):
        self.children = _convert_to_nodes(children)

    @property
    def media(self):
        """Return all media required to render the element on this dashboard."""
        media = self.media
        for child in self.chipdren:
            media = media + child.media
        return media

    def children_span(self):
        total_span = sum(
            child.span_columns for child in self.children
        )
        if 12 % total_span != 0:
            warnings.warn(
                "Can't equally divide container {} for {} span elements"
                .format(12, self.elements)
            )

        span_multiplier = 12 // total_span
        for child in self.children:
            yield child, child.span_columns * span_multiplier

class Column(LayoutNode):
    template_name = 'dashboard/column.html'

    def __init__(self, *children):
        self.children = _convert_to_nodes(children)

    @property
    def media(self):
        """Return all media required to render the element on this dashboard."""
        media = self.media
        for child in self.chipdren:
            media = media + child.media
        return media

class Dashboard(LayoutNode):
    template_name = 'dashboard/dashboard.html'

    def __init__(self, name, children, permission=None, permission_obj=None):
        self.name = name
        self.children = _convert_to_nodes(children)
        self.permission = permission
        self.permission_obj = permission_obj

    @property
    def slug(self):
        with translation.override('en'):
            return slugify(self.name)

    @property
    def media(self):
        """Return all media required to render the element on this dashboard."""
        media = self.media
        for child in self.chipdren:
            media = media + child.media
        return media

    def has_perm(self, user):
        if self.permission is None:
            return True
        elif self.permission_obj is None:
            return user.has_perm(self.permission)
        elif callable(self.permission_obj):
            pass


import json
from pathlib import Path

import torch
from torchvision import io

import wsiprocess as wp
from wsiprocess.cli import Args

class ClassificationDataset(torch.utils.data.Dataset):

    def __init__(self, dataset):
        self.dataset = dataset
        self.read_labels(self.dataset.coords)

    def read_labels(self, coords):
        normal_column = ["x", "y", "w", "h", "mask"]
        columns = list(set(coords.columns) - set(normal_column))
        self.labels = coords[columns]

    def __len__(self):
        return len(self.dataset.coords)

    def __getitem__(self, idx):
        coord = self.dataset.coords.iloc[idx]
        label = torch.tensor(self.labels.iloc[idx].tolist())
        return self.dataset.read_patch(**coord), label

class SegmentationDataset(torch.utils.data.Dataset):

    def __init__(self, dataset):
        if dataset.patch_config["no_patches"]:
            msg = "SegmentationDataset needs wsiprocess to have run without"
            msg += "no_patches because wsiprocess generates segmentation mask"
            msg += "from global view."
            raise NotImplementedError(msg)
        self.dataset = dataset
        self.path = Path(dataset.patch_config["save_to"]).parent
        self.read_masks(self.dataset.coords)

    def read_masks(self, coords):
        masks = coords.masks.str.replace("'", "\"")
        masks = masks.apply(lambda x: json.loads(x))

        self.masks = masks.apply(lambda x: x[0]["coords"])
        self.dataset.coords["label"] = masks.apply(lambda x: x[0]["class"])

    def __len__(self):
        return len(self.dataset.coords)

    def __getitem__(self, idx):
        coord = self.dataset.coords.iloc[idx]
        mask_path = str(self.path/self.masks.iloc[idx])
        mask = io.read_image(mask_path, mode=io.ImageReadMode.UNCHANGED)
        return self.dataset.read_patch(**coord), mask

def main(command, foreground_fn):
    args = Args(command)
    slide = wp.slide(args.wsi)
    rule = wp.rule(args.rule) if hasattr(args, "rule") and args.rule else False

    if args.method == "evaluation":
        annotation = wp.annotation()
    else:
        annotation = wp.annotation(args.annotation, slidename=slide.filename)
    annotation.dot_to_bbox(args.dot_bbox_width, args.dot_bbox_height)

    if foreground_fn:
        annotation.make_masks(slide, rule, foreground_fn=foreground_fn)
    elif hasattr(args, "minmax") and args.minmax:
        min_, max_ = map(int, args.minmax.split("-"))
        annotation.make_masks(
            slide, rule, foreground_fn="minmax", min_=min_, max_=max_)
    else:
        annotation.make_masks(slide, rule, foreground_fn="otsu")

    if hasattr(args, "extract_foreground"):
        if not (args.extract_foreground and "foreground" in annotation.classes):
            annotation.classes.remove("foreground")

    if hasattr(args, "export_thumbs") and args.export_thumbs:
        thumbs_dir = args.save_to/slide.filestem/"thumbs"
        if not thumbs_dir.exists():
            thumbs_dir.mkdir(parents=True)
        annotation.export_thumb_masks(thumbs_dir)

    if args.method == "evaluation":
        on_annotation = False
    else:
        on_annotation = args.on_annotation
    crop_bbox = args.crop_bbox if hasattr(args, "crop_bbox") else False

    patcher = wp.patcher(
        slide, args.method,
        annotation=annotation,
        save_to=args.save_to,
        patch_width=args.patch_width,
        patch_height=args.patch_height,
        overlap_width=args.overlap_width,
        overlap_height=args.overlap_height,
        on_foreground=args.on_foreground,
        on_annotation=on_annotation,
        offset_x=args.offset_x,
        offset_y=args.offset_y,
        ext=args.ext,
        magnification=args.magnification,
        start_sample=args.start_sample,
        finished_sample=args.finished_sample,
        no_patches=args.no_patches,
        crop_bbox=crop_bbox,
        verbose=args.verbose,
        dryrun=args.dryrun)
    patcher.get_patch_parallel(
        annotation.classes, max_workers=args.max_workers)

    if args.method == "detection":
        converter = wp.converter(
            args.save_to/slide.filestem,
            args.save_to/slide.filestem,
            args.ratio)
        if args.voc_style:
            converter.to_voc()
        if args.coco_style:
            converter.to_coco()
        if args.yolo_style:
            converter.to_yolo()

        if args.crop_bbox:
            patcher.get_mini_patch_parallel(annotation.classes)


"""
Manages the list of addresses for the wallet, including labels and derivation paths
"""
import os
from ..persistence import write_csv, read_csv
import logging

logger = logging.getLogger(__name__)

def to_bool(v):
    if isinstance(v, bool):
        return v
    if isinstance(v, int):
        return bool(v)
    return v == "True"

class Address(dict):
    columns = [
        "address",  # str, address itself
        "index",  # int, derivation index
        "change",  # bool, change or receive
        "label",  # str, address label
        "used",  # bool, does this address have a transaction?
        "service_id",  # str, reserved for or used by Service.id
    ]
    type_converter = [
        str,
        int,
        to_bool,
        str,
        to_bool,
        str,
    ]

    def __init__(self, rpc, **kwargs):
        self.rpc = rpc
        # copy
        kwargs = dict(**kwargs)
        # replace with None or convert
        for i, k in enumerate(self.columns):
            v = kwargs.get(k, "")
            kwargs[k] = None if v in ["", None] else self.type_converter[i](v)

        super().__init__(**kwargs)

    def set_label(self, label):
        if self["label"] == label:
            return
        self["label"] = label
        self.rpc.setlabel(self.address, label)

    def set_service_id(self, service_id: str):
        if service_id:
            # Declares that this Address is associated with a Service
            self["service_id"] = service_id
        else:
            # Frees a reserved Address; reset its label
            self["service_id"] = None
            if not self.used and self["label"]:
                self.set_label("")

    @property
    def is_external(self):
        return self.index is None

    @property
    def is_mine(self):
        return not self.is_external

    @property
    def is_receiving(self):
        return self.is_mine and not self.change

    @property
    def is_change(self):
        return self.is_mine and self.change

    @property
    def index(self):
        return self["index"]

    @property
    def address(self):
        return self["address"]

    @property
    def change(self):
        return self["change"]

    @property
    def used(self):
        return self["used"]

    @property
    def label(self):
        if self["label"]:
            return self["label"]
        if self["change"] is not None and self["index"] is not None:
            prefix = "Change #" if self.change else "Address #"
            index = self["index"]
            return f"{prefix}{index}"
        return self.address

    @property
    def is_labeled(self):
        return bool(self["label"])

    @property
    def is_reserved(self):
        return bool(self["service_id"])

    @property
    def service_id(self):
        return self["service_id"]

    def __str__(self):
        return self.address

    def __repr__(self):
        if self.label != self.address:
            return f"Address({self.label}, {self.address})"
        else:
            return f"Address({self.address})"

class AddressList(dict):
    AddressCls = Address

    def __init__(self, path, rpc):
        super().__init__()
        self.path = path
        self.rpc = rpc
        file_exists = False
        if os.path.isfile(self.path):
            try:
                addresses = read_csv(self.path, self.AddressCls, self.rpc)
                # dict allows faster lookups
                for addr in addresses:
                    self[addr.address] = addr
                file_exists = True
            except Exception as e:
                logger.exception(e)
        self._file_exists = file_exists

    def save(self):
        if len(list(self.keys())) > 0:
            write_csv(self.path, list(self.values()), self.AddressCls)
        self._file_exists = True

    def set_labels(self, arr):
        """
        Sets the labels for existing addresses

        arr should be a list with dicts, example:
            [{'address':'bc1qabc...', 'label':'mylabel1'}, {'address':'bc1qabd...', 'label':'mylabel2'}, ...]
        """
        for addr in arr:
            if addr["address"] in self:
                self[addr["address"]].set_label(addr["label"])
        self.save()

    def add(self, arr, check_rpc=False):
        """
        arr should be a list with dicts, example:
            [{'address':'bc1qabc...', 'label':'mylabel1'}, {'address':'bc1qabd...', 'label':'mylabel2'}, ...]
        """
        labeled_addresses = {}
        if check_rpc:
            # get all available labels
            labels = self.rpc.listlabels()
            if "" in labels:
                labels.remove("")
            # get addresses for all labels
            res = self.rpc.multi([("getaddressesbylabel", label) for label in labels])
            for i, result in enumerate(res):
                label = labels[i]
                # go through all addresses and assign labels
                for k in result["result"].keys():
                    labeled_addresses[k] = label
        # go through all addresses and assign
        for addr in arr:
            if addr["address"] in self:
                continue
            # if we found a label for it - import
            if addr["address"] in labeled_addresses:
                addr["label"] = labeled_addresses[addr["address"]]
            self[addr["address"]] = self.AddressCls(self.rpc, **addr)
        # add all labeled addresses but not from the array (destination)
        for addr in labeled_addresses:
            if addr not in self:
                self[addr] = self.AddressCls(
                    self.rpc,
                    address=addr,
                    label=labeled_addresses[addr],
                    change=None,
                    index=None,
                )
        self.save()

    def get_address(self, address: str) -> Address:
        if address not in self:
            self[address] = self.AddressCls(self.rpc, address=address)
        return self[address]

    def set_label(self, address, label):
        addr_obj = self.get_address(address)
        addr_obj.set_label(label)
        self.save()

    def get_labels(self):
        labels = {}
        for addr in self.values():
            lbl = addr.get("label", "")
            if lbl:
                labels[lbl] = labels.get(lbl, []) + [addr.address]
        return labels

    def associate_with_service(
        self, address: str, service_id: str, label: str, autosave: bool = True
    ):
        """
        Associates the Address (i.e. sets Address.service_id) with the specified
        Service.id.
        """
        addr_obj = self.get_address(address)
        addr_obj.set_service_id(service_id)
        addr_obj.set_label(label)
        if autosave:
            self.save()

    def deassociate(self, address: str, autosave: bool = True):
        """
        Removes the Address's association with a Service (i.e. sets
        Address.service_id to None and resets Address.label).
        """
        addr_obj = self.get_address(address)
        addr_obj.set_service_id(None)
        if autosave:
            self.save()

    def set_used(self, addresses):
        need_save = False
        for address in addresses:
            if address not in self:
                # external maybe???
                continue
            addr = self[address]
            # doesn't make sense to set used for external addresses
            if addr.is_external or addr.used:
                continue
            addr["used"] = True
            need_save = True
        if need_save:
            self.save()

    def max_index(self, change=False):
        return max(
            0,
            0,
            *[
                addr.index or 0
                for addr in self.values()
                if addr.is_mine and addr.change == change
            ],
        )

    def max_used_index(self, change=False):
        return max(
            -1,
            -1,
            *[
                addr.index or -1
                for addr in self.values()
                if addr.is_mine and addr.used and addr.change == change
            ],
        )

    @property
    def file_exists(self):
        return self._file_exists and os.path.isfile(self.path)


import matplotlib.pyplot as plt
import numpy as np
from sympy import Symbol, Integral, exp, log
from threading import Thread
from scipy.special import roots_legendre

def function(x):
    f = np.exp(x) * np.log(x)
    return f

def foo():
    _x = Symbol('x')
    return Integral(exp(_x) * log(_x), (_x, 1, 2))

def method_middle_rect(a, b, h):
    res = 0
    x = a
    while True:
        x += h
        res += function(x - h / 2)
        if x >= b:
            break

    res *= h
    print(str('Method of middle rectangles: ') + str(res))

def method_trapezoid(a, b, h):
    res = (function(a) + function(b)) / 2

    x = a + h
    while x < b:
        res += function(x)
        x += h

    res *= h
    print(str('Trapezoidal method: ') + str(res))

def method_Simpson(a, b, h):
    y_odd = 0.0
    y_even = 0.0

    x_s = []

    n = int(1 / h)

    for i in range(n + 1):
        x_s.append(a + i * h)

    for j in range(1, n, 2):
        y_odd += function(x_s[j])

    for k in range(2, n, 2):
        y_even += function(x_s[k])

    res = h / 3 * (function(a) + 4 * y_odd + 2 * y_even + function(b))
    print(str('Simpson\'s Method (Parabola Method): ') + str(res))

def method_Gaussian(a, b, n):
    b_a_half_size = (b - a) / 2
    a_b_half_sum = (a + b) / 2

    roots, weights = roots_legendre(n)

    _sum = 0
    for i in range(n):
        _sum += weights[i] * function(a_b_half_sum + b_a_half_size * roots[i])
    _sum *= b_a_half_size

    print(str('Gaussian quadrature: ') + str(_sum))

def draw_function():
    x = np.arange(0.1, 2.5, 0.07)
    f = function(x)

    line = plt.plot(x, f, color='limegreen')

    plt.fill_between(x, f, color='palegreen', where=(x < 2) & (f > 0))
    plt.grid()

    plt.setp(line, color="limegreen", linewidth=1.5)
    plt.gca().spines["left"].set_position("zero")
    plt.gca().spines["bottom"].set_position("zero")
    plt.gca().spines["top"].set_visible(False)
    plt.gca().spines["right"].set_visible(False)

    plt.show()

def main():
    # _eps = 1 / 6
    _eps = 0.000001
    _a = 1
    _b = 2
    _n = 6

    print('\n' + str(foo()) + '\n')
    print('================================================================================================\n')

    thread1 = Thread(target=method_middle_rect, args=(_a, _b, _eps))
    thread2 = Thread(target=method_trapezoid, args=(_a, _b, _eps))
    thread3 = Thread(target=method_Simpson, args=(_a, _b, _eps))
    thread4 = Thread(target=method_Gaussian, args=(_a, _b, _n))

    thread1.start()
    thread2.start()
    thread3.start()
    thread4.start()

    thread1.join()
    thread2.join()
    thread3.join()
    thread4.join()

    print('\n================================================================================================\n')

    draw_function()

if __name__ == '__main__':
    main()


from __future__ import annotations

from dynaconf import settings
from dynaconf.loaders.toml_loader import write

# Get the potato
original = str(settings.POTATO)  # str() to force a copy
modern = "Modern Potato"
print("Original data:", original)
assert settings.POTATO == settings.get("potato") == original

# Change the Toml file
print("Change POTATO to `Modern Potato` in settings.toml file...")
write(settings.path_for("settings.toml"), {"default": {"potato": modern}})

# Print the original
print("Dynaconf knows:", settings.POTATO)
assert settings.POTATO == settings.get("potato") == original

# Get it freshly
print("Read it freshly to get changed value...")
print("Changed data:", settings.get_fresh("POTATO"))
assert settings.POTATO == settings.get_fresh("potato") == modern

# Get it again
print("Now read again without the get_fresh method")
print("Still the new value no?", settings.POTATO)
assert settings.POTATO == settings.get("potato") == modern

# Restore it
write(settings.path_for("settings.toml"), {"default": {"potato": original}})


"""
    PyProfiler/tests/test_utils.py

"""
# Python Dependencies
import pytest

from pstats import SortKey

from PyProfiler import get_default_args
from PyProfiler.utils import default_arg
from PyProfiler.utils import check_keyword
from PyProfiler.utils import is_valid_mode
from PyProfiler.utils import is_valid_sortkey
from PyProfiler.errors import InvalidMode
from PyProfiler.errors import InvalidSortingMethod

from .functions import example
from .functions import example_2
from .functions import Example

@pytest.mark.parametrize("value, expected", [
    (SortKey.CALLS, True), ("calls", True),
    (SortKey.PCALLS, True), ("pcalls", True),
    (SortKey.CUMULATIVE, True), ("cumulative", True), ("cumtime", True),
    (SortKey.NFL, True), ("nfl", True),
    (SortKey.NAME, True), ("name", True),
    (SortKey.STDNAME, True), ("stdname", True),
    (SortKey.FILENAME, True), ("filename", True), ("module", True),
    (SortKey.LINE, True), ("line", True),
    (SortKey.TIME, True), ("time", True), ("tottime", True),
    pytest.param("INVALID", False, marks=pytest.mark.xfail(raises=InvalidSortingMethod)),
    ("file", True),
])
def test_sortkey(value, expected):
    assert is_valid_sortkey(value) is expected

@pytest.mark.parametrize("function, keyword, args, kwargs, expected", [
    # Function without Default Value
    (example, "debug", (), {"debug": True}, True),  # Keyword Arg is True
    (example, "debug", (0, 0, True), {}, True),  # Positional Arg is True

    (example, "debug", (0, 0, False), {}, False),  # Positional Arg is False
    (example, "debug", (), {}, False),  # No Default Value Specified
    (example, "verbose", (), {"verbose": True}, False),  # Wrong Keyword (Keyword not present)
    (example, "debug", (), {"debug": False}, False),  # Keyword Arg is False

    # Function with Default Value (True)
    (example_2, "verbose", (), {}, True),  # Default Value is True
    (example_2, "verbose", (0, 0, True), {}, True),  # Positional Arg is True

    (example_2, "verbose", (), {"verbose": False}, False),  # Keyword Arg is False
    (example_2, "verbose", (0, 0, False), {}, False),  # Positional Arg is False
    (example_2, "debug", (0, 0, True), {}, False),  # Wrong Keyword (Keyword not present)
    (example_2, "verbose", (0, 0, 1), {}, False),  # Positional Arg is not bool
    (example_2, "verbose", (0, 0), {"verbose": False}, False),  # Keyword Arg is False
    (example_2, "verbose", (0, 0), {"verbose": 1}, False),  # Positional Arg is not bool

    # Method with Default (True)
    (Example().magic, "profile", ("self", 0, True), {}, True),  # Positional Arg is True
    (Example().magic, "profile", ("self", 0), {}, True),  # Default Value is True
    (Example().magic, "profile", ("self",), {}, True),  # Default Value is True
    (Example().magic, "profile", ("self",), {"profile": True}, True),  # Keyword Arg is True

    (Example().magic, "profile", ("self",), {"profile": False}, False),  # Keyword Arg is False
    (Example().magic, "profile", ("self", 0, False), {}, False),  # Positional Arg is False
    (Example().magic, "wrong", ("self", 0, True), {}, False),  # Wrong Keyword (Keyword not present)
    (Example().magic, "profile", ("self", 0, 1), {}, False),  # Positional Arg is not bool

    # Class Method (wrapper) with Default (False)
    (Example().black, "debug", ("cls", 0, True), {}, True),  # Positional Arg is True
    (Example().black, "debug", ("cls", 0), {"debug": True}, True),  # Keyword Arg is True
    (Example().black, "debug", ("cls", 0, False), {"debug": True}, True),  # Keyword Arg is True

    (Example().black, "debug", ("cls", 0, False), {}, False),  # Positional Arg is False
    (Example().black, "debug", ("cls", 0, 1), {}, False),  # Positional Arg is not bool
    (Example().black, "debug", ("cls", 0), {}, False),  # Default Value is False
    (Example().black, "debug", ("cls",), {"debug": False}, False),  # Keyword Arg is False

    # Static Method (wrapper) without Default Value
    (Example().lady, "profile", (0, True), {}, True),  # Positional Arg is True
    (Example().lady, "profile", (), {"profile": True}, True),  # Keyword Arg is True

    (Example().lady, "profile", (0, False), {}, False),  # Positional Arg is False
    (Example().lady, "profile", (0,), {}, False),  # No Default Value --> False
    (Example().lady, "profile", (0, 1), {}, False),  # Positional Arg is not bool
    (Example().lady, "profile", (), {}, False),  # No Default Value --> False
    (Example().lady, "profile", (), {"profile": False}, False),  # Keyword Arg is False
])
def test_keyword(function, keyword, args, kwargs, expected):
    assert check_keyword(function, keyword, *args, **kwargs) is expected

@pytest.mark.parametrize("function, expected", [
    (example, dict(zip(["a", "b", "debug"], [None] * 3))),
    (example_2, dict(zip(["a", "b", "verbose"], [1, 2, True]))),
    (Example.magic, dict(zip(["self", "a", "profile"], [None, None, True]))),
    (Example.black, dict(zip(["b", "debug"], [None, False]))),  # classmethod wrapper modifies inspection of method
    (Example.lady, dict(zip(["a", "profile"], [None] * 2))),
])
def test_default_values(function, expected):
    assert get_default_args(function, None) == expected

@pytest.mark.parametrize("function, keyword, default, expected", [
    (example, "debug", True, True),
    (example, "debug",  False, False),
    (example_2, "verbose", True, True),
    (example_2, "verbose", False, True),
    (example_2, "", True, True),
    (example_2, "", False, False),
    (Example.magic, "profile", True, True),
    (Example.magic, "profile", False, True),
    (Example.magic, "", True, True),
    (Example.magic, "", False, False),
    (Example.black, "debug", False, False),
    (Example.black, "debug", True, False),
    (Example.black, "", False, False),
    (Example.black, "", True, True),
    (Example.lady, "profile", True, True),
    (Example.lady, "profile", False, False),
    (Example.lady, "", True, True),
    (Example.lady, "", False, False),
])
def test_default_keyvalue(function, keyword, default, expected):
    assert default_arg(function, keyword, default) is expected

@pytest.mark.parametrize("value, expected", [
    ("a", True),
    ("w", True),
    ("ab", True),
    ("wb", True),
    ("at", True),
    ("wt", True),
    pytest.param("r", False, marks=pytest.mark.xfail(raises=InvalidMode)),
    pytest.param("rb", False, marks=pytest.mark.xfail(raises=InvalidMode))
])
def test_mode(value, expected):
    assert is_valid_mode(value) is expected


import json

# Load JSONs
f_new = open('./public/music_list_taoji.json')
f_old = open('./song_list_legacy.json')

data_new = json.load(f_new)
data_old = json.load(f_old)

f_new.close()
f_old.close()

# Create Simple List

song_new = []
song_old = []
added = []

for song in data_new:
    song_new.append({'name': song['song_name'], 'artist': song['artist']})

for song in data_old:
    song_old.append({'name': song['song_name'], 'artist': song['artist']})

# 新增
print("新增")
for song in song_new:
    if song not in song_old:
        print("\t" + song["artist"] + " - " + song["name"])
        added.append(song)

# 去除
print("去除")
for song in song_old:
    if song not in song_new:
        print("\t" + song["artist"] + " - " + song["name"])

with open("./public/added_songs.json", 'w') as file:
    file.write(json.dumps(added))


#!/usr/bin/env python

import itertools

from collections import defaultdict, Counter
from typing import List, Set, Tuple

def gen_primes(n):
    primes = [2]
    for p in range(3, n+1, 2):
        if not any(p % q == 0 for q in primes):
            primes.append(p)
    return primes

def print_set_short_repr(l, count=10) -> str:
    if len(l) <= count:
        return str(l)
    return " ".join(map(str, l[:count//2])) + " ... " + " ".join(map(str, l[-count//2:]))

def enumerate_quadratic_form(a: int, b: int, c: int, n: int) -> Set[int]:
    """Enumerate all numbers a x^2 + b y^2 <= n."""
    population = set()
    stop = n if c >= 0 else abs(c) * n

    for x in range(n):
        temp_x = a * x*x
        if temp_x > n:
            break

        for y in range(n):
            temp = temp_x + c*x*y +  b * y*y
            if temp > n:
                break

            if temp > 0:
                population.add(temp)

    return population

def merge_primes(primes: List[int], n: int) -> Tuple[int, ...]:
    """
    Merge "primes" (some are prime^2)

    Similar to Smooth Numbers
    Returns all numbers ( <= n) composed only of primes from primes

    Can be speed up if so desired
    """
    gen = [1]
    for prime in primes:
        if prime == 1:
            continue
        nextGen = gen[:]
        primePower = prime
        while primePower <= n:
            for i in gen:
                number = i * primePower
                if number > n:
                    break
                nextGen.append(number)
            primePower *= prime
        gen = sorted(nextGen)
    #gen.remove(1)
    return tuple(gen)

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return itertools.chain.from_iterable(itertools.combinations(s, r) for r in range(len(s)+1))

def raise_to_power(l: List[int], p: int) -> List[int]:
    """Raise each item in l to p"""
    return tuple([a ** p for a in l])

def enumerate_prime_splits(n: int):
    primes = gen_primes(n)
    print("primes:", print_set_short_repr(primes))

    prime_splits = set()

    # Exclude 2
    test_pop = merge_primes([p for p in primes if p > 2], n)
    yield test_pop, "p > 2"

    # Exclude 2/3
    test_pop = merge_primes([p for p in primes if p > 3], n)
    yield test_pop, "p > 3"

    # TODO how to enumerate more / better splits
    for modulo in range(3, 100+1):
        mods = tuple(sorted(set(p % modulo for p in primes)))
        # TODO maybe loosen this later
        if len(mods) > 13:
            continue

        common_mods = tuple(sorted(m for m, c in Counter(p % modulo for p in primes).items() if c > 3))
        extra_mods = tuple(sorted(set(mods) - set(common_mods)))
        print("\t", modulo, "\tmods", common_mods, " + ", extra_mods)

        # Exclude common mods
        test_pop = merge_primes([p for p in primes if p % modulo not in extra_mods], n)
        yield test_pop, f"exclude p % {modulo} not in {extra_mods}"

        # Exclude a single prime (modulo)
        if modulo in primes:
            test_pop = merge_primes([p for p in primes if p != modulo], n)
            yield test_pop, f"p != {modulo}"

        for m_split in powerset(mods):
            # Don't allow the full / empty set
            if not m_split or m_split == mods:
                continue

            # Consider itertool partition recipe
            a_primes = []
            b_primes = []
            for p in primes:
                if p % modulo in m_split:
                    a_primes.append(p)
                else:
                    b_primes.append(p)
            a_primes = tuple(a_primes)
            b_primes = tuple(b_primes)

            if a_primes in prime_splits:
                continue
            prime_splits.add(a_primes)

            """
            Try only a primes
            Try a^1, b^2
            Inverses are tested with the inverse m_split
            """

#            print()
#            print(f"\t{m_split!s:12}", print_set_short_repr(a_primes))
#            print(f"\t{' ':12}", print_set_short_repr(b_primes))

            test_pop = merge_primes(a_primes, n)
            yield test_pop, f"p % {modulo} in {m_split}"

            test_pop = merge_primes(raise_to_power(a_primes, 2) + b_primes, n)
            yield test_pop, f"p % {modulo} in {m_split} to an even power"

            if a_primes[0] ** 3 <= n and b_primes[0] ** 2 <= n:
                test_pop = merge_primes(raise_to_power(a_primes, 3) + b_primes, n)
                yield test_pop, f"p % {modulo} in {m_split} higher powers (3, 1)"

                test_pop = merge_primes(raise_to_power(a_primes, 3) + raise_to_power(b_primes, 2), n)
                yield test_pop, f"p % {modulo} in {m_split} higher powers (3, 2)"

            if a_primes[0] ** 4 <= n:
                test_pop = merge_primes(raise_to_power(a_primes, 4) + b_primes, n)
                yield test_pop, f"p % {modulo} in {m_split} higher powers (4, 1)"

                test_pop = merge_primes(raise_to_power(a_primes, 4) + raise_to_power(b_primes, 2), n)
                yield test_pop, f"p % {modulo} in {m_split} higher powers (4, 1)"

            #test_pop = merge_primes([a ** 2 for a in a_primes] + [b ** 2 for b in b_primes], n)
            #yield test_pop, f"p % {modulo} all even power"

def find_brute(n = 1000):

    """
    Can find some of these with searches like
        "even exponent" "prime" "quadratic form"
        "even power" "prime" "quadratic form"
        "quadratic form" "prime" "representation"
    """

    names = {
        (1, -2, 0): "A035251 / A000047",
        (1, 1, 0): "A001481 / A000050",
        (1, 2, 0): "A002479 / A000067",

        (1, 3, 0): "A003136 / A000205",
        (1, 1, -1): "A003136 / A000205",
        (1, 1, 1): "A003136 / A000205",

        (5, -1, 0): "A031363",
        (1, 1, 3): "A031363",
    }

    min_n = 20

    forms = defaultdict(list)

    # TODO: Negative sequences are hard to enumerate
    # Find some general trick?
    for a in range(1, 100+1):
        for b in range(a, 100+1):
            for cross in (-1, 0, 1, 2, 3):

                # Repeated forms not needed
                if (a, b, cross) in [(1, 1, 1), (1, 2, 2), (1, 1, -1), (1, 3, 3), (2, 2, -1)]:
                    continue

                population = enumerate_quadratic_form(a, b, cross, n)
                if not population:
                    continue

                population = tuple(sorted(p for p in population if p >= min_n))
                default_name = f"{a} x^2 {cross:+} xy + {b} y^2" if cross != 0 else f"{a} x^2 + {b} y^2"
                name = names.get((a, b, cross), default_name)

                other_name = forms.get(population)
                #assert other_name is None, f"{name} same as {other_name}"
                if other_name:
                    print(f"\t{name} same as {other_name}")

                forms[population].append(name)

    print(f"Enumerated {len(forms)} Quadratic Forms")
    print()
    for test, split_name in enumerate_prime_splits(n):
        test = tuple(sorted(p for p in test if p >= min_n))
        if test in forms:
            print()
            print("Match!", split_name, "  <==>  ", " | ".join(forms[test]))
            print("\tsequence:", print_set_short_repr(test, 24))
            if not any("A" in seq for seq in forms[test]):
                print("\t", test)
            print()

def subgroups():
    comb_with_repl = itertools.combinations_with_replacement

    primes = gen_primes(1000)
    Zp = 9

    def is_closed(subgroup):
        return all(a * b % Zp in subgroup for a, b in itertools.product(subgroup, repeat=2))

    all_mods = tuple(sorted(set(p % Zp for p in primes) - {0}))
    minus_two = tuple(m for m in all_mods if m != 2)
    minus_three = tuple(m for m in all_mods if m != 3)
    minus_two_three = tuple(m for m in all_mods if m > 3)

    for mods in [all_mods, minus_two, minus_three, minus_two_three]:
        missing = sorted(set(all_mods) - set(mods))

        sub_groups = [g for g in powerset(mods) if is_closed(g)]
        # empty sub_group is kinda boring
        sub_groups.remove(tuple())

        for g1, g2 in itertools.combinations(sub_groups, 2):
            if set(g1) | set(g2) == set(mods) and (not (set(g1) & set(g2))):
                print("\tA", g1, g2)

        for g in powerset(mods):
            if not g: continue

            inv = tuple(sorted(set(mods) - set(g)))
            # Check if g^2 -> !g
            if all(a * b % Zp in inv for a, b in comb_with_repl(g, 2)):
                if inv in sub_groups:
                    g_a = tuple([p for p in primes if p % Zp in g])
                    g_b = tuple([p for p in primes if p % Zp in inv])
                    m_p = tuple([p for p in primes if p % Zp in missing])
                    print("\tA^2 -> B, B^2 -> B:", g, inv, "\tmissing:", m_p)
                    print()

                    # Could try powerset(m_p) if it contains more than one
                    print("merged a^2          :", merge_primes(raise_to_power(g_a, 2) + g_b + m_p, 100))
                    print("merged b^2          :", merge_primes(g_a + m_p + raise_to_power(g_b, 2), 100))
                    if m_p:
                        print("merged (a+missing)^2:", merge_primes(raise_to_power(g_a + m_p, 2) + g_b, 100))
                        print("merged (b+missing)^2:", merge_primes(g_a + raise_to_power(g_b + m_p, 2), 100))
                    print()
                    print()

def find_quadratic_with_primes():
    n = 5
    present = [11, 19, 31, 59, 71, 79, 131, 139, 151, 179, 191, 199]
    not_present = [29, 41, 61, 89, 101, 109, 149, 181]

    present = set(present)
    not_present = set(not_present)
    assert not (present & not_present)

    # TODO: Negative sequences are hard to enumerate
    # Find some general trick?
    for a in range(-100, 100+1):
        for b in range(-100, 100+1):
            for cross in range(-100, 100+1):
                if cross*cross - 4*a*b != -4 * n:
                    continue
                print(a, cross, b)

                population = enumerate_quadratic_form(a, b, cross, max(max(present), max(not_present)))
                population = set(population)
                if (population & present) == set(present) and len(population | not_present) == 0:
                    print("Found!", (a,b,cross))

if __name__ == "__main__":
    #find_brute(8000)
    #subgroups()
    find_quadratic_with_primes()


import os
import requests
import yaml
import sys

def importNewRoutes(yaml_file):
    emails = yaml.load(yaml_file) # yaml file with `source: target` format
    for source in emails:
        target = emails[source]
        print(("Creating route for %s -> %s")%(source, target))
        createRoute(source, target)

def createRoute(source, target):
    print("Creating Route...")
    provider = session.post(
        "https://api.mailgun.net/v3/routes",
        auth=(username, api_key),
        data={"priority": 10,
              "description": "%s - %s"%(source, target),
              "expression": "match_recipient('%s')" %source,
              "action": ["forward('%s')" %target, "stop()"]}
    )
    print(provider.status_code)
    print(provider.text)

if __name__ == "__main__":

    username = "api"
    api_key = os.environ.get('MAILGUN_API_KEY')

    if api_key is None:
        print("Please define your MAILGUN_API_KEY as an environment variable.")
        exit()

    session = requests.Session()
    with open(sys.argv[1], 'r') as input_file:
        importNewRoutes(input_file.read())


from accounts.services import UserService
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save, pre_delete
from friendships.listeners import friendship_changed
from utils.memcached_helper import MemcachedHelper

class Friendship(models.Model):
    from_user = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,  # when record deleted, set this field to true instead of deleting it
        null=True,  # allow this field to be null
        related_name='following_friendship_set',
    )
    to_user = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        related_name='followed_friendship_set',
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        index_together = (
            # all followings of a user, order by following time asc
            ('from_user_id', 'created_at'),
            # all follower of a user, order by following time asc
            ('to_user_id', 'created_at'),
        )
        unique_together = (
            ('from_user_id', 'to_user_id')
        )

    def __str__(self):
        return '{} followed {}'.format(self.from_user_id, self.to_user_id)

    @property
    def cached_from_user(self):
        return MemcachedHelper.get_object_through_cache(User, self.from_user_id)

    @property
    def cached_to_user(self):
        return MemcachedHelper.get_object_through_cache(User, self.to_user_id)

# hook up with listeners to invalidate cache
pre_delete.connect(friendship_changed, sender=Friendship)
post_save.connect(friendship_changed, sender=Friendship)


import typing

from gungnir.utils.Blueprint import Blueprint

class TestUtil:
    @staticmethod
    def view_func(blueprint: Blueprint, rule: str, method: str, *args: str) -> str:
        for detail in blueprint.detail():
            if rule == detail["rule"] and method in detail["methods"]:
                return detail["view_func"](*args)

    @staticmethod
    def catch(method: typing.Callable[[], str]) -> typing.Union[str, typing.Type[Exception]]:
        try:
            return method()
        except Exception as exception:
            return exception.__class__


from gensim.models import word2vec
from gensim.models import keyedvectors
from gensim.models.keyedvectors import load_word2vec_format
import pandas as pd
from gensim.models.word2vec import Word2Vec
from gensim.models import KeyedVectors
from gensim import models

# data = pd.read_csv('./test7.csv', encoding='CP949')
# cont = data['nouns']
# cn = data['isbn']
# book_val = cont.values.tolist()
# isbn_val = cn.values.tolist()

# corpus = [sent.strip().split(" ") for sent in book_val]
# model = Word2Vec(sentences = corpus, vector_size = 100, window = 5, min_count = 2, workers = 4, sg = 0)
model = Word2Vec.load('ehlwk.model')

book_val = ['메타 버스 에듀 테크 게더 타운 이프 랜드 제페토 가상현실 코스 페이시스 를 교육 현장 활용 혁신 교육 에듀 테크 실현 수 가장 실용 지침 가상현실 증강현실 거울 세계 라이프 깅 인공 지능 미래 인재 위 교육 행사 기획 활용 가이드 요즘 메타 버스 게더 타운 제페토 이프 랜드 이용 온라인 행사 학교 수업 기업 기관 대학 성과 홍보 학술 대회 성과 전시회 신제품 발표회 메타 버스 구축 성공 운영 게더 타운 제페토 이프 랜드 메타 버스 플랫폼 참여자 아바타 이용 상호작용 메타 버스 에듀 테크 메타 버스 분야 가상현실 증강현실 거울 세계 라이프 깅 메타 버스 교육 기획 행사 기획 활용 가이드 기획 메타 버스 에듀 테크 실현 혁신 교육 행사 기획 여러분 도움 네이버 블로그 마련 교육 현장 분 서로 사례 공유 수 ']
# new_model = Word2Vec()

document_list=[]
# i = 0

for line in book_val:
    doc2vec = None
    count = 0
    for word in line.split():
        if word in model.wv.index_to_key:
            count += 1

            if doc2vec is None:
                doc2vec = model.wv[word]
            else:
                doc2vec = doc2vec + model.wv[word]

    if doc2vec is not None:
        doc2vec = doc2vec / count
        document_list.append(doc2vec)

print(document_list[0]);

# new_model.save('test_model10.model')
# print(document_list[0]);
# print(new_model.wv.most_similar(9791162243008))

# import numpy as np
new_model = KeyedVectors.load_word2vec_format('test_model10')

new_model["t"] =document_list[0];

print(new_model.most_similar("t"))

# # import numpy as np

# # # new_model = Word2Vec()
# # # new_model.wv.load_word2vec_format('test_model10')

# # new_model.wv["t"] = np.random.rand(100)
# # new_model.wv.save_word2vec_format('test_model10')