from django.urls import reverse
from django.shortcuts import render
from django.contrib.auth.decorators import login_required

from .forms import PostForm
from termcolor import colored
from django.utils import timezone
import pytz
from datetime import datetime, timedelta
from django.shortcuts import get_object_or_404, redirect
from .models import Post, Image
import os
import requests
from django.core.files import File

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import HttpResponse
from common.decorators import is_ajax
from common.decorators import ajax_required
from django.views.decorators.http import require_POST
from django.conf import settings
from django import http
# Create your views here.

def delta_time(time):
    delta = time + timezone.timedelta(minutes=1)
    if delta >= timezone.localtime(timezone.now()):
        return time
    else:
        return timezone.localtime(timezone.now())

def cover2_upload(url, creator_url, creator_name):
    timestamp = datetime.now().timestamp()
    imgname = f'{timestamp}.jpg'
    try:
        r = requests.get(url).content
        with open(imgname, 'wb') as f:
            f.write(r)
        fileimg = File(open(imgname, 'rb'))
        image = Image.objects.create(
            image=fileimg,
            creator_url=creator_url,
            creator_name=creator_name
        )
        os.remove(imgname)

        return image
    except:
        return None

@login_required
def create_post(request):

    if request.method == 'POST':
        form = PostForm(data=request.POST, files=request.FILES)
        try:
            cover = request.FILES.get('cover')
            title = request.POST.get('title')
            body = request.POST.get('body')
            status = request.POST.get('status')
            print(colored(request.POST, 'red'))
            print(colored(cover, 'blue'))
        except:
            return render(
                request,
                'posts/post_form.html', {
                    'form': form,
                }
            )

        post = Post.objects.create(
            title=title,
            body=body,
            status=status,
            author=request.user
        )
        post.cover = cover
        post.save()

        return redirect(post.get_absolute_url())

    else:
        form = PostForm(data=request.POST, files=request.FILES)
    return render(
        request,
        'posts/post_form.html', {
            'form': form,
        }
    )

def post_list(request):
    # print('\n\n',request.META.get('HTTP_REFERER'))
    # posts = Post.published.all()
    posts = Post.published.all().order_by('-updated')
    # print(translation.get_language_from_request(request))
    paginator = Paginator(posts, 5)
    page = request.GET.get('page')
    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        if is_ajax(request=request):
            return HttpResponse('')
        posts = paginator.page(paginator.num_pages)
    if is_ajax(request=request):
        return render(
            request,
            'posts/list_ajax.html', {
                'posts': posts,
            }
        )
    return render(
        request,
        'posts/list.html', {
            'posts': posts,

        }
    )

def post_detail(request, slug):

    try:
        post = Post.objects.get(slug=slug)

        # print(post, "aaa"*100)
    except Post.DoesNotExist:
        return HttpResponse("404")

    if post.status == "draft":

        if post.author != request.user:
            return HttpResponse("THis Is un published")
    return render(
        request,
        'posts/detail.html', {
            "post": post
        }
    )

from django.http import JsonResponse

@login_required
def date_ajax_get(req):
    # if req.method == 'POST':
    mytime = (timezone.now().astimezone(pytz.timezone(settings.mytimezone))+timedelta(minutes=10)).strftime('%Y-%m-%d %H:%M')
    # tmy = timezone.datetime.strptime(f'{mytime} {tz}', '%Y-%m-%d %H:%M %z')

    # from zoneinfo import ZoneInfo
    # date = datetime.now(tz=ZoneInfo('UTC')) + timedelta(minutes=5)
    # date_str = date.strftime('%Y-%m-%d %H:%M')
    # date_str = tmy.strftime('%Y-%m-%d %H:%M')

    return JsonResponse({'status': 'ok', 'date': mytime})

from django.utils.translation import gettext as _

@login_required
@ajax_required
@require_POST
def date_check_past(req):
    if req.method == 'POST':
        publish = req.POST.get('publish')
        # tz = req.POST.get('tz')
        try:
            tmy = timezone.datetime.strptime(f'{publish}', '%Y-%m-%d %H:%M')
            # tmy = timezone.datetime.strptime(f'{publish} {tz}', '%Y-%m-%d %H:%M %z')
            # t = tmy.astimezone(pytz.timezone('UTC'))
            # from termcolor import colored
            # print(colored(tmy, 'red'))
            # d_with_tz = timezone.datetime(year=t.year, month=t.month, day=t.day, hour=t.hour, minute=t.minute, tzinfo=pytz.UTC)
            # print('my to utc', d_with_tz)
            # print('now utc', timezone.now())
            # naive = t.replace(tzinfo=None)
            # humanize.activate(req.LANGUAGE_CODE)
            # message = humanize.naturaltime(naive)
            tnow = timezone.now().astimezone(pytz.timezone(settings.mytimezone))
            tnow2 = tnow.replace(tzinfo=None)
            # print(colored(tnow2, 'blue'))
            if tmy < tnow2:
                return JsonResponse({'status': 'ok', 'message': _("Please check your system's date. Its may be incorrect or You are entering date in past.")})

            else:
                return JsonResponse({'status': 'ok', 'message': _('It will be published at given time')})
        except :
            return JsonResponse({'status': 'ok', 'message': _('Wrong Formate, Correct are "YYYY-MM-DD HH:MM"')})

@login_required
def update_post(request, slug):
    try:
        post = Post.objects.get(slug=slug)
    except Post.DoesNotExist:
        return HttpResponse("404")

    if request.method == 'POST':
        form = PostForm(data=request.POST, files=request.FILES)
        try:
            cover = request.FILES.get('cover')
            title = request.POST.get('title')
            body = request.POST.get('body')
            status = request.POST.get('status')
            # print(colored(request.POST, 'red'))
            # print(colored(cover, 'blue'))
        except:
            return render(
                request,
                'posts/post_form.html', {
                    'form': form,
                }
            )

        post.title=title
        post.body=body
        post.status=status
        if cover != None:
            # print(colored(post.cover, 'green'))

            post.cover = cover

        post.save()

        return redirect(post.get_absolute_url())

    else:
        data = {
            "title": post.title,
            "body": post.body,
            "status": post.status,
        }
        files = {
            "cover": post.cover

        }
        form = PostForm(data=data, files=request.FILES, instance=post)
    if post.cover:
        imgcover = post.cover.url
    else:
        imgcover = None
    return render(
        request,
        'posts/post_form.html', {
            'form': form,
            "imgcover": imgcover
        }
    )

from .models import Category

@login_required
def category_list(request):
    posts = Category.objects.filter(created_by=request.user).order_by('-updated')
    paginator = Paginator(posts, 5)
    page = request.GET.get('page')
    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        if is_ajax(request=request):
            return HttpResponse('')
        posts = paginator.page(paginator.num_pages)
    if is_ajax(request=request):
        return render(
            request,
            'posts/category/list_ajax.html', {
                'posts': posts,
            }
        )
    return render(
        request,
        'posts/category/list.html', {
            'posts': posts,

        }
    )

@login_required
def delete_category(request, slug):
    try:

        post = Category.objects.get(slug=slug)
    except Category.DoesNotExist:
        return HttpResponse("404")
    if post.created_by != request.user:
        return HttpResponse("401 Unauthorized")
    post.delete()
    return http.HttpResponseRedirect(reverse('category_list'))

@login_required
def delete_post(request, slug):
    try:

        post = Post.objects.get(slug=slug)
    except Post.DoesNotExist:
        return HttpResponse("404")
    if post.author != request.user:
        return HttpResponse("401 Unauthorized")
    post.delete()
    return http.HttpResponseRedirect(reverse('dashboard'))

@login_required
def unpublish_post(request, slug):
    try:

        post = Post.objects.get(slug=slug)
    except Post.DoesNotExist:
        return HttpResponse("404")
    if post.author != request.user:
        return HttpResponse("401 Unauthorized")
    post.status = "draft"
    post.save()
    return http.HttpResponseRedirect(reverse('dashboard'))

@login_required
def publish_post(request, slug):
    try:

        post = Post.objects.get(slug=slug)
    except Post.DoesNotExist:
        return HttpResponse("404")
    if post.author != request.user:
        return HttpResponse("401 Unauthorized")
    post.status = "published"
    post.save()
    return http.HttpResponseRedirect(reverse('dashboard'))


class Solution:
    def mySqrt(self, x: int) -> int:
        #x0**2-a+2*x0*(x-x0)=0
        #2xx0-x0**2-a=0
        #x = 0.5*x0+0.5(a/x0) = 0.5*(x0+a/x0)
        # if x<=1:return x
        # x0=1
        # while True:
        #     cur = 0.5*(x0+x/x0)
        #     if abs(cur-x0)<=1e-5:
        #         return int(cur)
        #     x0=cur
        if x<=1:return x
        l,r = 0,x
        while l<=r:
            mid = (l+r)/2
            cur = mid**2
            if abs(cur-x)<=1e-5:
                return int(mid)
            if cur>x:
                r=mid
            else:
                l=mid


import csv
from collections import defaultdict

def sum_and_count_values(csv_file):
    # Read the CSV file into a dictionary of lists
    with open(csv_file, 'r') as file:
        reader = csv.reader(file)
        rows = list(reader)

    # Create a dictionary to store the sums and counts
    sum_counts = defaultdict(lambda: [0, 0])  # [Sum, Count]

    # Calculate the HRI
    for row in rows[1:]:
        try:
            key = row[1] # owner is the key value
            value = int(row[2]) # the rank in the NFT collection
            sum_counts[key][0] += value  # Sum = running total of all rank values
            sum_counts[key][1] += 1      # Count aka Total Comboeys: is assigned to each owner bc that's our primary key
            # Do the Comverse special maths to calculate HRI
            # 1. Divide the Sum by Count, get Average
            sum_counts[key][0] = sum_counts[key][0]/sum_counts[key][1]
            # 2. Divide Average by 2x count
            sum_counts[key][0] = sum_counts[key][0]/(sum_counts[key][1]*2)
            # 3. if NFT count < 10, incur HRI balance penalty
            if sum_counts[key][1] < 10:
                sum_counts[key][0] = sum_counts[key][0] + (10 - sum_counts[key][1])
        except ValueError:
            continue
    # Create the new CSV file with three columns
    new_csv_file = 'HRI_combeys.csv'
    with open(new_csv_file, 'w', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(['Holder', 'HRI', 'Combeys'])
        for key, (sum_val, count) in sum_counts.items():
            writer.writerow([key, sum_val, count])

    return new_csv_file

# Usage example
csv_file = './combeys-holders-ranks.csv'
new_csv_file_path = sum_and_count_values(csv_file)
print(f"New CSV file created: {new_csv_file_path}")


import os
import numpy as np
from glob import glob
from CAMstars.Material.material import material
from CAMstars.Material.population import population

def parse(fname):
	fi = open(fname,'r')
	name = fname[fname.rfind('/')+1:fname.find('csv')-1]
	names = []
	logX = []
	dlogX = []

	# Load bulk stellar properties
	params = {}
	for i,line in enumerate(fi):
		if 'Element' in line:
			break
		ind = line.index(':')
		s = (line[:ind], line[ind+1:].strip())
		try:
			params[s[0]] = float(s[1])
		except ValueError:
			params[s[0]] = s[1]

	# Load abundance data
	for i,line in enumerate(fi):
		if 'References' in line:
			break
		s = line.rstrip().split(',')
		if len(s) == 3:
			names.append(s[0])
			logX.append(float(s[1]))
			dlogX.append(float(s[2]))

	logX = np.array(logX)
	dlogX = np.array(dlogX)

	# Calculate additional parameters
	if 'dlogmdotMinus' in params.keys() and 'dlogmdotPlus' in params.keys():
		params['dlogmdot'] = 0.5 * (params['dlogmdotMinus'] + params['dlogmdotPlus'])

	# Correct for different normalizations
	if params['Abundance Normalization'] == 'Ntot':
		nH = 1 - sum(10**w for i,w in enumerate(logX) if names[i] != 'H')
		logX = logX - np.log10(nH)
	elif params['Abundance Normalization'] == 'H12':
		logX -= 12

	# Correct for systematic uncertainties
	if 'General uncertainty' in params.keys():
		dlogX = (dlogX**2 + params['General uncertainty']**2)**0.5

	return material(name, names, logX, dlogX, params=params)

dir_path = os.path.dirname(os.path.realpath(__file__))
files = glob(dir_path + '/../../Data/Accreting Stars/*.csv')
materials = list([parse(f) for f in files])
accretingPop = population(materials)

files = glob(dir_path + '/../../Data/Field Stars/AJMartin/*.csv')
materials = list([parse(f) for f in files])
AJMartinPop = population(materials)

files = glob(dir_path + '/../../Data/Field Stars/LFossati/*.csv')
materials = list([parse(f) for f in files])
LFossatiPop = population(materials)

sol = parse(dir_path + '/../../Data/Field Stars/Sol.csv')


import torch._subclasses
from torch._subclasses.fake_tensor import DynamicOutputShapeException

def is_builtin(op):
    return op.namespace in ('aten', 'prims', 'prim')

def fake_check(op, args, kwargs, dynamic_only):
    with torch._subclasses.CrossRefFakeMode(ignore_op_fn=is_builtin):
        try:
            op(*args, **kwargs)
        except DynamicOutputShapeException:
            if not dynamic_only:
                raise
            return
        if dynamic_only:
            raise AssertionError(
                f"fake_check({op}, ..., dynamic_only={dynamic_only}): "
                f"dynamic_only means that the operator is expected to have "
                f"data-dependent output shape. We have not detected that this is "
                f"the case. Please check that your operator's FakeTensor "
                f"implementation is actually data dependent")


"""This module contains functions about retrieving of patients names,
 doctors names from Enrollment object, and lists all Enrollments connected
 to certain doctor(its owner). """

from django.shortcuts import render
from enrollment_system.models import Enrollment
from doctors_auth.models import DoctorProfile
from .forms import PatientFilterForm, DoctorFilterForm

def extract_filter_values(values):
    """It takes request param 'text' and returns its value"""
    text = values['text'] if 'text' in values else ''
    return text

def all_patients(request):
    """It retrieves patients names form Enrollments records. """

    text = extract_filter_values(request.GET)
    patient = Enrollment.objects.filter(patient_name__contains=text)
    context = {
        'patients': patient,
        'patient_filter_form': PatientFilterForm(initial={'text': text})
    }
    return render(request, 'hospital_units/patients_list.html', context)

def all_doctors(request):
    """It retrieves doctors names from DoctorProfile records. """

    text = extract_filter_values(request.GET)
    doctor = DoctorProfile.objects.filter(name__contains=text)
    context = {
        'doctors': doctor,
        'doctor_filter_form': DoctorFilterForm(initial={'text': text})
    }
    return render(request, 'hospital_units/doctors_list.html', context)

def doctors_records(request):
    """It filters Enrollment records by their owners. """

    context = {
        'enrollments': Enrollment.objects.filter(doctor_name_id=request.user.doctorprofile.id)
    }
    return render(request, 'hospital_units/doctors_enrollments.html', context)


import torch
import torch.nn as nn
import torchvision
from model import LogisticRegressionModel
from dataset_loader import load_data

# Hyper-parameters
input_size = 28 * 28    # 784
output_size = 10
num_epochs = 5
batch_size = 100
learning_rate = 0.001

def train(train_loader, input_size, num_epochs):

    try:

        total_step = len(train_loader)

        for epoch in range(num_epochs):
            for i, (images, labels) in enumerate(train_loader):
                # Reshape images to (batch_size, input_size)
                images = images.reshape(-1, input_size)

                # Forward pass
                outputs = model(images)
                loss = criterion(outputs, labels)

                # Backward and optimize
                optimizer.zero_grad()
                loss.backward()
                optimizer.step()

                if (i+1) % 100 == 0:
                    print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}' .format(epoch+1, num_epochs, i+1, total_step, loss.item()))

    except:
        print("An error occured while training")

def test(test_loader):

    try:

        with torch.no_grad():
            correct = 0
            total = 0
            for images, labels in test_loader:
                images = images.reshape(-1, input_size)
                outputs = model(images)
                _, predicted = torch.max(outputs.data, 1)
                total += labels.size(0)
                correct += (predicted == labels).sum()

            print('Accuracy of the model on the 10000 test images: {} %'.format(100 * correct / total))

    except:
        print("An error occured while testing")

def save_model(model):

    try:

        # Save the model checkpoint
        torch.save(model.state_dict(), 'model.ckpt')

    except:
        print("An Error Occured")

# checking type of device
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print('Using {} device'.format(device))
print()

# loading dataset
train_loader, test_loader = load_data()

# linear model
model = LogisticRegressionModel().to(device)
print(model)
print()

# loss function and optimization
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)

# training & testing
train(train_loader, input_size, num_epochs)
test(test_loader)

# saving model
save_model(model)


import unittest

from lambdo.Workflow import *
from lambdo.Table import *
from lambdo.Column import *

class TablesTestCase(unittest.TestCase):

    def setUp(self):
        pass

    def test_imports(self):
        wf_json = {
            "id": "My workflow",
            "imports": ["tests.udf", "os.path"],
            "tables": [
                {
                    "id": "My table",
                    "columns": [
                        {
                            "id": "A",
                            "inputs": ["A"],
                            "window": "1",
                            "extensions": [
                                {"function": "tests.udf:user_import_fn", "outputs": "Success"}
                            ]
                        }
                    ]
                }
            ]
        }

        wf = Workflow(wf_json)

        self.assertEqual(len(wf.modules), 2)
        self.assertTrue(hasattr(wf.modules[0], 'user_import_fn'))

        # Provide data directly (without table population)
        data = {'A': [1, 2, 3]}
        df = pd.DataFrame(data)
        tb = wf.tables[0]
        tb.data = df

        wf.execute()

        self.assertEqual(wf.tables[0].data['Success'][0], 'Success')
        self.assertEqual(wf.tables[0].data['Success'].nunique(), 1)

    def test_getset_pkl(self):
        value = "Value to be stored"
        json_field = "$file:_test_.pkl"

        set_value(json_field, value)
        value2 = get_value(json_field)

        self.assertEqual(value, value2)

if __name__ == '__main__':
    unittest.main()


Tile = [[0 for col in range(1001)] for row in range(1001)]

def fill_tile(x, y, x_size, y_size):
    x_len = int(x_size / 2)
    x_min = x - x_len
    x_max = x + x_len

    y_len = int(y_size / 2)
    y_min = y - y_len
    y_max = y + y_len
    for i in range(y_min, y_max+1):
        for j in range(x_min, x_max+1):
            Tile[i][j] = 1

class Back:
    def __init__(self):
        self.image = load_image('background.png')

    def draw(self):
        self.image.draw(400,300)

class Floor:
    def __init__(self):
        self.image = load_image('floor.png')
        self.x = 400
        self.y = 30
        self.x_size = 800

    def draw(self):
        self.image.clip_draw(0, 0, self.x_size, 60, self.x, self.y)

floors = [Floor() for i in range(3)]
floors[1].x, floors[1].y, floors[1].x_size = 400, 30, 800
floors[0].x, floors[0].y, floors[0].x_size = 600, 90, 400
floors[2].x, floors[2].y, floors[2].x_size = 700, 150, 200

mario = Mario()
running = True
run_right = False
run_left = False
jump_key_down = False

for floor in floors:
    fill_tile(floor.x, floor.y, floor.x_size, FLOOR_HEIGHT)

while running:
    handle_events()

    # game logic
    if run_right:
        mario.move_right()
    elif run_left:
        mario.move_left()
    else :
        mario.vel_reset()

    mario.falling()
    mario.update()

    # game drawing
    clear_canvas()
    back.draw()
    for floor in floors:
        floor.draw()
    mario.draw()
    update_canvas()
    delay(0.05)

# finalization code
close_canvas()


#!/usr/bin/env python

import re
import sys
import array, traceback
import pylab

class Data: pass
class Val(array.ArrayType):
    len=0
    dep=""

def load_data(filename):
    state="end"
    dat=Data()
    valdep=[]
    infile=open(filename)
    for line in infile.readlines():
        tagfnd=re.search("\<([^<>]*)\>",line)
        if tagfnd:
            tag=tagfnd.group(1)
            tag.strip()
            if re.search("Qucs Dataset ",line):
                continue
            if tag[0]=="/":
                state="end"
                print("Number of Dimensions:",len(valdep))
                if len(valdep)>1:
                    shape=[]
                    for i in range(len(valdep),0,-1):
                        shape.append(dat.__dict__[valdep[i-1]].len)
                    val=pylab.array(val)
                    val=pylab.reshape(val,shape)
                dat.__dict__[name]=val
            else:
                state="start"
                words=tag.split()
                type=words[0]
                name=words[1].replace(".","_")
                name=name.replace(",","")
                name=name.replace("[","")
                name=name.replace("]","")
                if type=="indep":
                    val=Val("f")
                    val.len=int(words[2])
                else:
                    val=[]
                    valdep=words[2:]
        else:
            if state=="start":
                if "j" in line:
                    print(line)
                    line=line.replace("j","")
                    line="%sj"%line.strip()
                    try:
                        val.append(complex(line))
                    except:
                        traceback.print_exc()
                        print(line) # add nan check
                        print(name)
                        print(len(val))
                else:
                    val.append(float(line))
            else:
                print("Parser Error:",line)

    return dat

if __name__ == "__main__":

    dat=load_data(sys.argv[1])

    print("Variables in",sys.argv[1])

    for key in dat.__dict__.keys():
        print("\nName =",key)
        try:
            print("\tLen=",dat.__dict__[key].len)
        except:
            pass
        try:
            print("\tDep=",dat.__dict__[key].dep)
        except:
            pass


# -*- coding: utf-8 -*-

# (c) 2016 Marcos Dione <mdione@grulic.org.ar>

# This file is part of ayrton.
#
# ayrton is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ayrton is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ayrton.  If not, see <http://www.gnu.org/licenses/>.

from importlib.abc import MetaPathFinder, Loader
try:
    # py3.4
    from importlib.machinery import ModuleSpec
except ImportError:  # pragma: no cover
    # py3.3
    pass  # sorry, no support

import sys
import os
import os.path

import logging
logger= logging.getLogger ('ayrton.importer')

from ayrton.file_test import a, d
from ayrton import Ayrton
import ayrton.utils

class AyrtonLoader (Loader):

    @classmethod
    def exec_module (klass, module):
        # module is a freshly created, empty module
        # «the loader should execute the module’s code
        # in the module’s global name space (module.__dict__).»
        load_path= module.__spec__.origin
        logger.debug2 ('loading %s [%s]', module, load_path)
        # I *need* to polute the globals, so modules can use any of ayrton's builtins
        loader= Ayrton (g=module.__dict__)
        loader.run_file (load_path)

        # set the __path__
        # TODO: read PEP 420
        init_file_name= '__init__.ay'
        if load_path.endswith (init_file_name):
            # also remove the '/'
            module.__path__= [ load_path[:-len (init_file_name)-1] ]

        logger.debug3 ('module.__dict__: %s ', ayrton.utils.dump_dict (module.__dict__))

loader= AyrtonLoader ()

class AyrtonFinder (MetaPathFinder):

    @classmethod
    def find_spec (klass, full_name, paths=None, target=None):
        # full_name is the full python path (as in grandparent.parent.child)
        # and path is the path of the parent (in a list, see PEP 420);
        # if None, then we're loading a root module
        # let's start with a single file
        # TODO: read PEP 420 :)
        logger.debug2 ('searching for %s under %s for %s', full_name, paths, target)
        last_mile= full_name.split ('.')[-1]

        if paths is not None:
            python_path= paths  # search only there
        else:
            python_path= sys.path

        logger.debug2 (python_path)
        for path in python_path:
            full_path= os.path.join (path, last_mile)
            init_full_path= os.path.join (full_path, '__init__.ay')
            module_full_path= full_path+'.ay'

            logger.debug2 ('trying %s', init_full_path)
            if -d (full_path) and -a (init_full_path):
                logger.debug2 ('found package %s', full_path)
                return ModuleSpec (full_name, loader, origin=init_full_path)

            else:
                logger.debug2 ('trying %s', module_full_path)
                if -a (module_full_path):
                    logger.debug2 ('found module %s', module_full_path)
                    return ModuleSpec (full_name, loader, origin=module_full_path)

        logger.debug2 ('404 Not Found')
        return None

finder= AyrtonFinder ()

# I must insert it at the beginning so it goes before FileFinder
sys.meta_path.insert (0, finder)


from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QPushButton, QAction, QLineEdit, QMessageBox, QListWidget
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
from PyQt5 import QtCore
from PyQt5.QtWidgets import *
import sys

import time
import datetime

class List(QMainWindow):

    @pyqtSlot()
    def __init__(self):
        super().__init__()
        self.title = 'Sort the library'
        self.left = 0
        self.top = 0
        self.width = 1000
        self.height = 500
        self.initUI()

    @pyqtSlot()
    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        # self.setStyleSheet("""QMainWindow{ background: red; }""")

        # # Create textbox
        # self.textbox = QLineEdit(self)
        # self.textbox.move(20, 20)
        # self.textbox.resize(280, 40)

        # Create a button in the window
        self.button = QPushButton('Ascending', self)
        self.button.move(0, 0)

        # Create a button in the window
        self.button2 = QPushButton('Descending' , self)
        self.button2.move(100, 0)

        self.listwidget = QListWidget(self)
        self.listwidget.move(0, 30)
        self.listwidget.resize(200, 500)
        # self.setStyleSheet("""QListWidget{ background: red; }""")
        self.listwidget.addItem("Yousif");
        self.listwidget.addItem("Jake");
        self.listwidget.addItem("Mohamed");
        self.listwidget.addItem("Abdulla");
        self.listwidget.addItem("Omar");

        self.button.clicked.connect(self.sortAscending)
        self.button2.clicked.connect(self.sortDescending)

        # date

        self.button3 = QPushButton('Ascending', self)
        self.button3.move(300, 0)

        # Create a button in the window
        self.button4 = QPushButton('Descending', self)
        self.button4.move(400, 0)

        self.listwidget2 = QListWidget(self)
        self.listwidget2.move(300, 30)
        self.listwidget2.resize(200, 500)
        # self.setStyleSheet("""QListWidget{ background: red; }""")
        self.listwidget2.addItem("01/02/2019");
        self.listwidget2.addItem("04/30/2012");
        self.listwidget2.addItem("03/15/2015");
        self.listwidget2.addItem("10/19/2005");
        self.listwidget2.addItem("09/34/2009");
        self.button3.clicked.connect(self.sortDatAscending)
        self.button4.clicked.connect(self.sortDateDescending)

        # by chanle
        # Create a button in the window
        self.button5 = QPushButton('Ascending', self)
        self.button5.move(600, 0)

        # Create a button in the window
        self.button6 = QPushButton('Descending' , self)
        self.button6.move(700, 0)

        self.listwidget3 = QListWidget(self)
        self.listwidget3.move(600, 30)
        self.listwidget3.resize(200, 500)
        # self.setStyleSheet("""QListWidget{ background: red; }""")
        self.listwidget3.addItem("Ladysif1");
        self.listwidget3.addItem("Politeness");
        self.listwidget3.addItem("Chorus");
        self.listwidget3.addItem("Blarney");
        self.listwidget3.addItem("Fogcreep");

        self.button5.clicked.connect(self.sortChannelAscending)
        self.button6.clicked.connect(self.sortChanelDescending)

    @pyqtSlot()
    def sortAscending(self):
        self.listwidget.sortItems()
        self.show()
    @pyqtSlot()
    def sortDescending(self):
        self.listwidget.sortItems(QtCore.Qt.DescendingOrder)
        self.show()
    @pyqtSlot()
    def sortDatAscending(self):
        self.listwidget2.sortItems()
        self.show()
    @pyqtSlot()
    def sortDateDescending(self):
        self.listwidget2.sortItems(QtCore.Qt.DescendingOrder)
        self.show()

    @pyqtSlot()
    def sortChannelAscending(self):
        self.listwidget3.sortItems()
        self.show()

    @pyqtSlot()
    def sortChanelDescending(self):
        self.listwidget3.sortItems(QtCore.Qt.DescendingOrder)
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = List()
    ex.show()
    sys.exit(app.exec_())


# 时间复杂度 O (k ^ 2)

import heapq

class Solution(object):
    def kSmallestPairs(self, nums1, nums2, k):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :type k: int
        :rtype: List[List[int]]
        """
        queue, res = [], []
        for i in range(min(k, len(nums1))):
            for j in range(min(k, len(nums2))):
                heapq.heappush(queue, (nums1[i] + nums2[j], [nums1[i], nums2[j]]))
        for _ in range(k):
            if queue:
                res.append(heapq.heappop(queue)[1])
        return res

# 优化后的版本

class Solution_2(object):
    def kSmallestPairs(self, nums1, nums2, k):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :type k: int
        :rtype: List[List[int]]
        """
        queue, res = [], []
        for i in range(min(k, len(nums1))):
            heapq.heappush(queue, (nums1[i] + nums2[0], i, 0))
        while k and queue:
            cur, i, j = heapq.heappop(queue)
            res.append([nums1[i], nums2[j]])
            k -= 1
            if j + 1 < len(nums2):
                heapq.heappush(queue, (nums1[i] + nums2[j + 1], i, j + 1))
        return res

300-400/373-Find K Pairs with Smallest Sums.py


import re
import sys

def read_input(filename):
    with open(filename) as f:
        line = f.readline()

    pattern_x = '.+x=(-?[0-9]+)..(-?[0-9]+)'
    pattern_y = '.+y=(-?[0-9]+)..(-?[0-9]+)'

    result_x = re.match(pattern_x, line)
    result_y = re.match(pattern_y, line)

    return (int(result_x.group(1)), int(result_x.group(2))), (int(result_y.group(1)), int(result_y.group(2)))

def in_target(x, y):
    return target[0][0] <= x <= target[0][1] and target[1][0] <= y <= target[1][1]

def out_of_target(x, y):
    return x > target[0][1] or y < target[1][0]

def launch_probe():
    res = 0
    highest_y = -sys.maxsize
    for i in range(300):
        for j in range(300):
            x, y = 0, 0
            i_ = i
            j_ = j
            local_highest = 0
            while not out_of_target(x, y):
                if in_target(x, y):
                    if local_highest > highest_y:
                        highest_y = local_highest
                        res = highest_y
                x += i_
                y += j_
                if y > local_highest:
                    local_highest = y
                if i_ > 0:
                    i_ -= 1
                j_ -= 1
    return res

def launch_all_probe_posibilities():
    all_posibilities = []
    for i in range(500):
        # if i % 10 == 0:
        #     print(i)
        for j in range(-100,500):
            # print(i, j)
            x, y = 0, 0
            i_ = i
            j_ = j
            while not out_of_target(x, y):
                if in_target(x, y):
                    all_posibilities.append((i, j))
                    break
                x += i_
                y += j_
                if i_ > 0:
                    i_ -= 1
                j_ -= 1
    return all_posibilities

if __name__ == '__main__':
    target = read_input('input.txt')
    # print(launch_probe())
    print(launch_all_probe_posibilities())
    print(len(launch_all_probe_posibilities()))


from threading import Lock

import numpy as np
import sklearn
import tensorflow as tf
from tensorflow.keras.models import model_from_json
import tensorflow.keras.backend as K

class LocalModel(object):
    """
    Local Model
    Each Client has its own model. The Weights will be sent to the Server.
    The Server updates a Global Model and sends this back to the clients.
    """

    def __init__(self, model_config, data_collected, optimizer):
        """
        Create Local Modal.
        Retrieved Configuration from server and local client data are applied here.
        :param model_config:
        :param data_collected:
        :param optimizer:
        """
        assert optimizer is not None, "please prove a optimizer dict"
        assert optimizer['loss'] is not None, "a loss function must be set in the optimizer dict"
        assert optimizer['metrics'] is not None, "a metric must be defined in the optimizer dict"
        assert optimizer['optimizer'] is not None, "a optimizer must be defined in the optimizer dict"
        assert data_collected["x_train"] is not None, "X matrix for training must be provided"
        assert data_collected["y_train"] is not None, "y vector for training must be provided"
        assert data_collected["x_test"] is not None, "X matrix for testing must be provided"
        assert data_collected["y_test"] is not None, "y vector for testing must be provided"
        self.model_config = model_config
        self.update_lock = Lock()
        self.graph = tf.Graph()
        with self.graph.as_default():
            self.session = tf.Session()
            with self.session.as_default():
                self.model = model_from_json(model_config['model_json'])
                if len(self.model.layers) >= 32: # hardcoded if model is lfw
                    for l in self.model.layers[:-4]:
                        l.trainable = False
                self.optimizer = optimizer
                self.model.compile(loss=optimizer['loss'],
                                   optimizer=optimizer['optimizer'](),
                                   metrics=optimizer['metrics'])
                self.model._make_predict_function()

        self.x_train = np.array(data_collected["x_train"])
        self.y_train = np.array(data_collected["y_train"])
        self.x_test = np.array(data_collected["x_test"])
        self.y_test = np.array(data_collected["y_test"])

    def get_weights(self):
        """
        Get Keras Model Weights
        :return: weights
        """
        return self.model.get_weights()

    def set_weights(self, new_weights):
        """
        Sets the Keras model Weights
        :param new_weights:
        :return:
        """
        with self.update_lock:
            with self.graph.as_default():
                with self.session.as_default():
                    self.model.set_weights(new_weights)

    def get_batch(self, x, y):
        """
        Returns a random training batch
        :return: Training Batch
        """
        x, y = sklearn.utils.shuffle(x, y)
        residual = (len(x) % self.model_config['batch_size'])
        return x[:-residual], y[:-residual]

    def train_one_round(self):
        """
        Train one round
        :return: weights and score
        """

        x_train, y_train = self.get_batch(self.x_train, self.y_train)
        with self.update_lock:
            with self.graph.as_default():
                with self.session.as_default():
                    self.model.fit(x_train, y_train,
                                   epochs=self.model_config['epoch_per_round'],
                                   batch_size=self.model_config['batch_size'],
                                   verbose=1,
                                   validation_data=(x_train, y_train))
                    score = self.model.evaluate(x_train, y_train, batch_size=self.model_config['batch_size'], verbose=0)
                    score[0] = np.mean(score[0])
                    print('Train loss:', score[0])
                    print('Train accuracy:', score[1])
                    return self.model.get_weights(), score[0], score[1]

    def evaluate(self):
        """
        Evaluation fo Test set after global model converged
        :return:
        """
        with self.update_lock:
            with self.graph.as_default():
                with self.session.as_default():
                    x_test, y_test = self.get_batch(self.x_test, self.y_test)
                    score = self.model.evaluate(x_test, y_test, batch_size=self.model_config['batch_size'], verbose=0)
                    score[0] = np.mean(score[0])
                    print('Test loss:', score[0])
                    print('Test accuracy:', score[1])
                    return score

    def save_model(self, path, cid):
        print(f'saving local model to {path}/{cid}_local_model.h5')
        with self.update_lock:
                with self.graph.as_default():
                    with self.session.as_default():
                        self.model.save(f'{path}/{cid}_local_model.h5')

    def save(self, path, cid, train_indices, test_indices):
        """
        Save Global Model wrt. to client
        :param path:
        :param cid:
        :param train_indices:
        :param test_indices:
        :param validation_indices:
        :return:
        """
        save_indices = {"train": train_indices, "test": test_indices}
        print(f'saving indices to {path}/{cid}_indices.npy')
        np.save(f'{path}/{cid}_indices.npy', save_indices)
        self.save_model(path, cid)


import asyncio
import atexit
import os
import shutil
import socket
import subprocess
import sys
import tempfile
import time
import urllib
from base64 import b64decode, b64encode
from concurrent.futures import ThreadPoolExecutor
from io import BytesIO
from pathlib import Path

import lxml.etree as E
from jupyterlab.commands import get_app_dir
from PIL import Image
from requests import Session
from requests_cache import CachedSession
from tornado.concurrent import run_on_executor
from traitlets import Bool, Dict, Instance, Int, Unicode, default
from traitlets.config import LoggingConfigurable

try:
    from PyPDF2 import PdfMerger, PdfReader, PdfWriter
except ImportError:  # pragma: no cover
    from PyPDF2 import (
        PdfFileMerger as PdfMerger,
        PdfFileReader as PdfReader,
        PdfFileWriter as PdfWriter,
    )

from .constants import (
    DRAWIO_APP,
    ENV_IPYDRAWIO_DATA_DIR,
    ENV_JUPYTER_DATA_DIR,
    PNG_DRAWIO_INFO,
    WORK_DIR,
)

VEND = Path(__file__).parent / "vendor/draw-image-export2"

DRAWIO_STATIC = (Path(get_app_dir()) / DRAWIO_APP).resolve()

JLPM = Path(shutil.which("jlpm")).resolve()

NODE = Path(
    shutil.which("node") or shutil.which("node.exe") or shutil.which("node.cmd")
).resolve()

class IPyDrawioExportManager(LoggingConfigurable):
    """manager of (currently) another node-based server"""

    drawio_server_url = Unicode().tag(config=True)
    drawio_port = Int().tag(config=True)
    drawing_name = Unicode("drawing.dio.xml").tag(config=True)
    core_params = Dict().tag(config=True)
    drawio_export_workdir = Unicode().tag(config=True)
    pdf_cache = Unicode(allow_none=True).tag(config=True)
    attach_xml = Bool().tag(config=True)
    attachment_name = Unicode("diagram.drawio").tag(config=True)
    is_provisioning = Bool(False)
    is_starting = Bool(False)
    init_wait_sec = Int(2).tag(config=True)
    _server = Instance(subprocess.Popen, allow_none=True)
    _session = Instance(Session)

    executor = ThreadPoolExecutor(1)

    def initialize(self):
        atexit.register(self.stop_server)

    @run_on_executor
    def _pdf(self, pdf_request):
        """TODO: enable more customization... I guess over HTTP headers?
        X-JPYDIO-embed: 1
        """
        data = dict(pdf_request)
        data.update(**self.core_params)
        status_code = None
        pdf_text = None
        res = None

        retries = 3

        while retries:
            status_code = None

            if self._server.returncode is not None:  # pragma: no cover
                self.start_server()
                time.sleep(self.init_wait_sec)
            try:
                self.log.warning(f"[ipydrawio-export] exporting ({retries} retries)...")
                res = self._session.post(self.url, timeout=None, data=data)
                pdf_text = res.text
                status_code = res.status_code
            except Exception as err:  # pragma: no cover
                self.log.warning(f"[ipydrawio-export] Pre-HTTP Error: {err}")
                time.sleep((3 - retries) * self.init_wait_sec)

            if status_code is not None:
                if status_code <= 400:
                    break
                elif res:  # pragma: no cover
                    self.log.warning(
                        f"[ipydrawio-export] HTTP {res.status_code}: {res.text}"
                    )
                else:  # pragma: no cover
                    self.log.warning("[ipydrawio-export] retrying...")

            retries -= 1  # pragma: no cover

        if res:
            self.log.debug(f"[ipydrawio-export] {len(res.text)} bytes")

        if pdf_text and self.attach_xml and self.attachments:
            self.log.info(
                f"[ipydrawio-export] attaching drawio XML as {self.attachment_name}"
            )
            with tempfile.TemporaryDirectory() as td:
                tdp = Path(td)
                output_pdf = tdp / "original.pdf"
                output_pdf.write_bytes(b64decode(pdf_text))
                final_pdf = tdp / "final.pdf"
                final = PdfWriter()
                final.appendPagesFromReader(PdfReader(str(output_pdf), "rb"))
                xml = pdf_request["xml"]
                if hasattr(xml, "encode"):
                    xml = xml.encode("utf-8")
                final.addAttachment(self.attachment_name, xml)
                with final_pdf.open("wb") as fpt:
                    final.write(fpt)

                pdf_text = b64encode(final_pdf.read_bytes())
                self.log.debug(
                    f"[ipydrawio-export] {len(pdf_text)} bytes (with attachment)"
                )

        return pdf_text

    @run_on_executor
    def _merge(self, pdf_requests):
        tree = E.fromstring("""<mxfile version="13.3.6"></mxfile>""")
        with tempfile.TemporaryDirectory() as td:
            tdp = Path(td)
            merger = PdfMerger()
            for i, pdf_request in enumerate(pdf_requests):
                self.log.warning("adding page %s", i)
                for diagram in self.extract_diagrams(pdf_request):
                    tree.append(diagram)
                next_pdf = tdp / f"doc-{i}.pdf"
                if pdf_request.get("pdf") is None:  # pragma: no cover
                    raise ValueError("PDF request is empty")
                wrote = next_pdf.write_bytes(b64decode(pdf_request["pdf"]))
                if wrote:
                    merger.append(PdfReader(str(next_pdf)))
            output_pdf = tdp / "output.pdf"
            final_pdf = tdp / "final.pdf"
            merger.write(str(output_pdf))
            composite_xml = E.tostring(tree).decode("utf-8")
            final = PdfWriter()
            final.appendPagesFromReader(PdfReader(str(output_pdf), "rb"))
            if self.attach_xml:
                final.addAttachment(self.attachment_name, composite_xml.encode("utf-8"))
            with final_pdf.open("wb") as fpt:
                final.write(fpt)
            return b64encode(final_pdf.read_bytes()).decode("utf-8")

    async def pdf(self, pdf_requests):
        if not self._server:  # pragma: no cover
            await self.start_server()

        for pdf_request in pdf_requests:
            pdf_request["pdf"] = await self._pdf(pdf_request)

        if len(pdf_requests) == 1:
            return pdf_requests[0]["pdf"]

        return await self._merge(pdf_requests)

    def stop_server(self):
        if self._server is not None:
            self.log.warning("[ipydrawio-export] shutting down")
            self._server.terminate()
            self._server.wait()
            self._server = None

    async def status(self):
        return {
            "has_jlpm": JLPM is not None,
            "is_provisioned": self.is_provisioned,
            "is_provisioning": self.is_provisioning,
            "is_starting": self.is_starting,
            "is_running": self.is_running,
        }

    @property
    def url(self):
        return f"http://localhost:{self.drawio_port}"

    @default("drawio_port")
    def _default_drawio_port(self):
        port = self.get_unused_port()
        self.log.debug(f"[ipydrawio-export] port: {port}")
        return port

    @default("drawio_server_url")
    def _default_drawio_server_url(self):
        url = DRAWIO_STATIC.as_uri()
        self.log.debug(f"[ipydrawio-export] URL: {url}")
        return url

    @default("_session")
    def _default_session(self):  # pragma: no cover
        if self.pdf_cache is not None:
            self.log.debug("[ipydrawio-export] requests session: cached")
            return CachedSession(self.pdf_cache, allowable_methods=["POST"])

        self.log.debug("[ipydrawio-export] requests session: regular")
        return Session()

    @default("core_params")
    def _default_core_params(self):
        return dict(format="pdf", base64="1")

    @default("drawio_export_workdir")
    def _default_drawio_export_workdir(self):
        data_root = Path(sys.prefix) / "share/jupyter"

        if ENV_JUPYTER_DATA_DIR in os.environ:
            data_root = Path(os.environ[ENV_JUPYTER_DATA_DIR])

        if ENV_IPYDRAWIO_DATA_DIR in os.environ:
            data_root = Path(os.environ[ENV_IPYDRAWIO_DATA_DIR])

        workdir = str(data_root if data_root.name == WORK_DIR else data_root / WORK_DIR)

        self.log.debug(f"[ipydrawio-export] workdir: {workdir}")
        return workdir

    @default("attach_xml")
    def _default_attach_xml(self):
        return True

    def extract_diagrams(self, pdf_request):
        node = None

        errors = []
        try:
            node = E.fromstring(pdf_request["xml"])
        except Exception as err:
            errors += [err]

        if node is None:
            try:
                img = Image.open(BytesIO(b64decode(pdf_request["xml"].encode("utf-8"))))
                node = E.fromstring(urllib.parse.unquote(img.info[PNG_DRAWIO_INFO]))
            except Exception as err:
                errors += [err]

        if node is None:
            self.log.warning("errors encountered extracting xml %s", errors)
            return

        tag = node.tag

        if tag == "mxfile":
            for diagram in node.xpath("//diagram"):
                yield diagram
        elif tag == "mxGraphModel":
            diagram = E.Element("diagram")
            diagram.append(node)
            yield diagram
        elif tag == "{http://www.w3.org/2000/svg}svg":
            diagrams = E.fromstring(node.attrib["content"]).xpath("//diagram")
            for diagram in diagrams:
                yield diagram

    def _start_process(self):
        env = dict(os.environ)
        env_updates = dict(
            PORT=str(self.drawio_port),
            DRAWIO_SERVER_URL=self.drawio_server_url,
            NODE_ENV="production",
        )
        env.update(env_updates)

        self.log.debug(f"[ipydrawio-export] extra env: {env_updates}")

        args = [NODE, self.drawio_export_app / "export.js"]
        self._server = subprocess.Popen([*map(str, args)], env=env)
        return self._server

    async def start_server(self):
        self.stop_server()
        self.log.debug("[ipydrawio-export] starting")
        self.is_starting = True

        if not self.is_provisioned:  # pragma: no cover
            await self.provision()

        self._start_process()

        self.log.warning(
            f"[ipydrawio-export] waiting {self.init_wait_sec}s for server to start"
        )

        await asyncio.sleep(self.init_wait_sec)

        self.log.warning("[ipydrawio-export] server started")

        self.is_starting = False

    @property
    def is_provisioned(self):
        return self.drawio_export_integrity.exists()

    @property
    def is_running(self):
        return self._server is not None and self._server.returncode is None

    @property
    def drawio_export_app(self):
        return Path(self.drawio_export_workdir) / VEND.name

    @property
    def drawio_export_node_modules(self):
        return self.drawio_export_app / "node_modules"

    @property
    def drawio_export_integrity(self):
        return self.drawio_export_node_modules / ".yarn-integrity"

    @run_on_executor
    def provision(self, force=False):  # pragma: no cover
        self.is_provisioning = True
        if not self.drawio_export_app.exists():
            if not self.drawio_export_app.parent.exists():
                self.drawio_export_app.parent.mkdir(parents=True)
            self.log.info(
                "[ipydrawio-export] initializing drawio export app %s",
                self.drawio_export_app,
            )
            shutil.copytree(VEND, self.drawio_export_app)
        else:
            self.log.info(
                "[ipydrawio-export] using existing drawio export folder %s",
                self.drawio_export_app,
            )

        if not self.drawio_export_node_modules.exists() or force:
            self.log.info(
                "[ipydrawio-export] installing drawio export dependencies %s",
                self.drawio_export_app,
            )
            subprocess.check_call(
                [str(JLPM), "--silent", "--ignore-optional"],
                cwd=str(self.drawio_export_app),
            )
        self.is_provisioning = False

    def get_unused_port(self):
        """Get an unused port by trying to listen to any random port.

        Probably could introduce race conditions if inside a tight loop.
        """
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.bind(("localhost", 0))
        sock.listen(1)
        port = sock.getsockname()[1]
        sock.close()
        return port

    def attachments(self, pdf_path):
        """iterate over the name, attachment pairs in the PDF"""
        reader = PdfReader(str(pdf_path), "rb")
        attachments = []
        try:
            attachments = reader.trailer["/Root"]["/Names"]["/EmbeddedFiles"]["/Names"]
        except KeyError:
            pass
        for i, name in enumerate(attachments, 1):
            if not isinstance(name, str):
                continue
            yield name, attachments[i].getObject()["/EF"]["/F"].getData()


import sys
import numpy as np
from scipy.linalg import eigh
import molecule

# read coordinate
input_geom = np.loadtxt(sys.argv[-1], comments='#')
mol = molecule.Molecule(input_geom)
print('***Cartesian Coordinates (a.u.)***')
mol.print_coord()

# read hessian
hess_file = sys.argv[-1].split("_")[0] + "_hessian.txt"
input_hess = np.loadtxt(hess_file, comments='#')
mol.hessian = input_hess.reshape( (mol.natom*3, mol.natom*3) )
print(mol.hessian)

# build mass weighted hessian
mol.mass_mat = np.repeat(mol.atms_mass, 3)
mol.mw_hess = np.einsum('ij,i,j->ij',
                        mol.hessian, mol.mass_mat**-.5, mol.mass_mat**-.5)

print(mol.mw_hess)

la, v = eigh(mol.mw_hess)
print(la)


import os

from catalog.models import Entry, License, EntryType, Tag
from filestorage.models import FileSet
from django.core.files.base import ContentFile

def import_dir(dir_name):
    for f in os.listdir(dir_name):
        fn = os.path.join(dir_name, f)
        if os.path.isfile(fn):
            import_file(fn)

def import_file(file_name):
    f = open(file_name, 'rb')
    try:
        data = f.read()
    finally:
        f.close()

    info = {}
    files = {}
    target = None

    lines = data.splitlines(True)
    for line in lines:
        handled = False
        for q in ['title', 'description', 'license', 'author', 'created',
                  'modified', 'change_comments', 'entry_type', 'tags',
                  'maturity', 'url', 'pypi_name', 'pypi']:
            if line.upper().rstrip() == "***" + q.upper():
                target = (info, q)
                handled = True
        if handled:
            continue

        if line.startswith('***FILE:'):
            fn = line[8:].strip()
            if not fn:
                raise ValueError("Invalid file name %s (%s)" % (fn, file_name))
            target = (files, fn)
            continue
        elif line.startswith('***SNIPPET'):
            target = (files, 'snippet.py')
            continue
        else:
            target[0].setdefault(target[1], "")
            target[0][target[1]] += line

    if 'pypi' in info:
        info['pypi_name'] = info.pop('pypi')
    if 'snippet.py' in files:
        info['entry_type'] = 'snippet'

    info.setdefault('entry_type', 'module')
    info.setdefault('license', 'public-domain')
    info.setdefault('maturity', 0.0)

    if 'entry_type' in info:
        info['entry_type'] = EntryType.objects.get(name=info['entry_type'])
    if 'license' in info:
        info['license'] = License.objects.get(slug=info['license'])
    if 'tags' in info:
        info['tags'] = [Tag.objects.get(name=name) for name in
                        [x.strip() for x in info['tags'].split(',')]]

    entry = Entry.new_from_title(**info)
    fileset = FileSet.new_from_title(entry.slug)
    fileset.save()

    entry.files = fileset

    if 'snippet.py' in files:
        fileset.snippet = files['snippet.py']
    else:
        for name, data in files.items():
            fileset.write_file(name, ContentFile(data))

    fileset.save()
    entry.save()


from flask import Blueprint, url_for, render_template, request, session, jsonify, abort, redirect
from market.models import MarketOrderDetail, MarketOrderMain, db
from market.utils import hash_password, apply_query_filter
from market.views.manage import manage

@manage.route("/orderinfo/<order_id>", methods=['GET', 'POST'])
def order_home(order_id):
    if request.method == 'GET':
        order = MarketOrderMain.query.filter(MarketOrderMain.order_id==order_id).first_or_404()
        details = MarketOrderDetail.query.filter(MarketOrderDetail.order_id==order_id).all()
        details_list = []
        for d in details:
            details_list.append(d.todict())
        return jsonify({
            'order':order.todict(),
            'details': details_list
        })
    elif request.method == 'POST':
        if request.form.get('hiddenidinput') != '':
            print('-------')
            print(request.form.get('hiddenidinput'))
            id = int(request.form.get('hiddenidinput'))  # this is update
            update_dict = dict(request.form)
            update_dict.pop('hiddenidinput')
            print(update_dict)
            for k in update_dict:
                update_dict[k] = update_dict[k][0]
            print(update_dict)
            MarketOrderMain.query.filter(
                MarketOrderMain.id == id).update(update_dict)
            try:
                db.session.commit()
                return jsonify({"success": True})
            except Exception as e:
                print(e)
                db.session.rollback()
                return jsonify({"success": False})
        _m = MarketOrderMain(
            order_id=request.form.get("order_id"),
            staff_id=request.form.get("staff_id"),
            gross_quantity=request.form.get('gross_quantity'),
            gross_price=request.form.get('gross_price'),
            time=request.form.get('time'),
            comment=request.form.get('comment')
        )
        db.session.add(_m)
        print('==========')
        try:
            db.session.commit()
            return jsonify({"success": True})
        except Exception as e:
            print(e)
            db.session.rollback()
            return jsonify({"success": False})
    else:
        pass

@manage.route('/order', methods=['POST', 'GET'])
def manage_order():
    if request.method == 'POST':
        if request.values.get('delete'):
            order_id = request.values.get('del_order_id')
            order = MarketOrderMain.query.filter_by(order_id=order_id).first()
            order.delete = True
            try:
                db.session.commit()
            except Exception as e:
                print(e)
                db.session.rollback()
                return jsonify({"success": False, "details": "fail"})

            details = MarketOrderDetail.query.filter_by(
                order_id=order_id, delete=False).all()
            for i in range(len(details)):
                details[i].delete = True
            try:
                db.session.commit()
            except Exception as e:
                print(e)
                db.session.rollback()
                return jsonify({"success": False, "details": "fail"})
        return redirect(url_for('manage.manage_order'))
    args_dict = dict(request.values)
    orders = apply_query_filter(
        query_filter=args_dict,
        target_class=MarketOrderMain,
        target_query=MarketOrderMain.query.filter(MarketOrderMain.delete == False)
    ).all()
    details = apply_query_filter(
        args_dict,
        MarketOrderDetail,
        MarketOrderDetail.query.filter(MarketOrderDetail.delete == False),
    ).all()
    # MarketOrderMain.query.filter(MarketOrderMain.delete==False).all()
    #details = MarketOrderDetail.query.filter(MarketOrderDetail.delete == False).all()
    result = []
    details_result = []
    for i, order in enumerate(orders):
        this_order = {}
        this_order['main'] = order
        this_order['details'] = []
        for detail in details:
            if detail.order_id == order.order_id:
                this_order['details'].append(detail)
        result.append(this_order)
    return render_template('manage_order.html', result=result, title="订单查询")

@manage.route("/order/add", methods=['POST', 'GET'])
def manage_order_add():
    if request.method == 'GET':
        return render_template('manage_order_add.html', title="添加订单")
    elif request.method == 'POST':
        if request.values.get('isupdate')=='123':
            print('is update')
            this_order = request.values.get('updateorderid')
            MarketOrderMain.query\
                .filter(MarketOrderMain.order_id==this_order)\
                    .delete()
            MarketOrderDetail.query\
                .filter(MarketOrderDetail.order_id==this_order)\
                    .delete()
            try:
                db.session.commit()
            except Exception as e:
                print(e)
                db.session.rollback()
                abort(500)
        order, details = get_order(request.values)
        db.session.add(order)
        for detail in details:
            db.session.add(detail)

        try:
            db.session.commit()
            return jsonify({"success": True, "data": "success"})
        except Exception as e:
            print(e)
            db.session.rollback()
            return jsonify({"success": False, "details": "fail"})

@manage.route("/order/modify", methods=['POST'])
def manage_order_modify():
    if request.values.get('modify') == "true":
        order, details = get_order(request.values)

        return "mangae order modify"
    else:
        print(request.values.get('updateid'))
        order = MarketOrderMain.query.filter_by(
            order_id=request.values.get('order_id')
        )[0]
        details = MarketOrderDetail.query.filter_by(order_id=order.order_id)\
            .order_by(MarketOrderDetail.order_detail_id.asc()).all()
        order.details = details
        return render_template("manage_order_modify.html", title="修改订单", order=order)

@manage.route('/order/batchadd', methods=['POST'])
def order_batchadd():
    batch = request.get_json().get('info')
    print(batch)
    orders = batch.split(';')
    print(orders)

    for order in orders:
        order=order.split('\n')
        print(order)
        i = 0
        while order[i] == '':
            i += 1
        orderinfo = order[i].split(',')
        print(orderinfo)
        db.session.add(MarketOrderMain(
            order_id=orderinfo[0],
            staff_id=orderinfo[1],
            gross_quantity=orderinfo[2],
            gross_price=orderinfo[3],
            time=orderinfo[4],
            comment=orderinfo[5]
        ))
        order_id = orderinfo[0]
        i += 1
        while i < len(order):
            detail = order[i].split(',')
            print(detail)
            db.session.add(MarketOrderDetail(
                order_detail_id=detail[0],
                order_id=order_id,
                merchandise_id=detail[1],
                merchandise_quantity=detail[2],
                unit_price=detail[3],
                gross_price=detail[4],
                comment=detail[5]
            ))
            i += 1
    try:
        db.session.commit()
        return jsonify({"success":True})
    except Exception as e:
        print(e)
        db.session.rollback()
        return jsonify({"success":False})

def get_order(order_form):
    order = MarketOrderMain(
        order_id=order_form.get("order_id"),
        staff_id=order_form.get("staff_id"),
        gross_quantity=order_form.get('gross_quantity'),
        gross_price=order_form.get('gross_price'),
        time=order_form.get('time'),
        comment=order_form.get('comment')
    )

    order_id = order_form.get("order_id")
    order_detail_id = order_form.getlist("order_detail_id[]")
    merchandise_id = order_form.getlist("merchandise_id[]")
    merchandise_quantity = order_form.getlist("merchandise_quantity[]")
    unit_price = order_form.getlist("unit_price[]")
    detail_gross_price = order_form.getlist("detail_gross_price[]")
    detail_comment = order_form.getlist("detail_comment[]")
    details = []
    for i in range(len(order_detail_id)):
        print(i)
        detail = MarketOrderDetail(
            order_detail_id=order_detail_id[i],
            order_id=order_id,
            merchandise_id=merchandise_id[i],
            merchandise_quantity=merchandise_quantity[i],
            unit_price=unit_price[i],
            gross_price=detail_gross_price[i],
            comment=detail_comment[i]
        )
        details.append(detail)
    return order, details


"""
208. Implement a Trie

https://leetcode.com/problems/implement-trie-prefix-tree/solution/

"""

"""
Implement a trie with insert, search, and startsWith methods.

Example:

Trie trie = new Trie();

trie.insert("apple");
trie.search("apple");   // returns true
trie.search("app");     // returns false
trie.startsWith("app"); // returns true
trie.insert("app");
trie.search("app");     // returns true
Note:

You may assume that all inputs are consist of lowercase letters a-z.
All inputs are guaranteed to be non-empty strings.
"""

class TrieNode:
    # Initialize your data structure here.
    def __init__(self):
        self.word = False
        self.children = {}

class Trie:

    def __init__(self):
        self.root = TrieNode()

    # @param {string} word
    # @return {void}
    # Inserts a word into the trie.
    def insert(self, word):
        node = self.root
        for i in word:
            if i not in node.children:
                node.children[i] = TrieNode()
            node = node.children[i]
        node.word = True

    # @param {string} word
    # @return {boolean}
    # Returns if the word is in the trie.
    def search(self, word):
        node = self.root
        for i in word:
            if i not in node.children:
                return False
            node = node.children[i]
        return node.word

    # @param {string} prefix
    # @return {boolean}
    # Returns if there is any word in the trie
    # that starts with the given prefix.
    def startsWith(self, prefix):
        node = self.root
        for i in prefix:
            if i not in node.children:
                return False
            node = node.children[i]
        return True

"""
["Trie","insert","search","search","startsWith","insert","search"]
[[],["apple"],["apple"],["app"],["app"],["app"],["app"]]

Expected - [null,null,true,false,true,null,true]
"""
trie = Trie()
print(None)
print(trie.insert("apple"))
print(trie.search("apple"))
print(trie.search("app"))
print(trie.startsWith("app"))
print(trie.insert("app"))
print(trie.search("app"))
print('\n\n\n')
"""
["Trie","insert","search","search","search","startsWith","startsWith","startsWith"]
[[],["hello"],["hell"],["helloa"],["hello"],["hell"],["helloa"],["hello"]]

Expected - [null,null,false,false,true,true,false,true]
"""

trie = Trie()
print(None)
print(trie.insert("hello"))
print(trie.search("hell"))
print(trie.search("helloa"))
print(trie.search("hello"))
print(trie.startsWith("hell"))
print(trie.startsWith("helloa")) # expected to be false
print(trie.startsWith("hello"))
print('\n\n\n')
"""
["Trie","insert","search","startsWith"]
[[],["a"],["a"],["a"]]

Expected - [null,null,true,true]
"""
trie = Trie()
print(trie.insert("a"))
print(trie.search("a"))
print(trie.startsWith("a"))


from collections import defaultdict

 ####发现上面的代码有点问题（不知道是不是我的问题），所以我自己写了一个，同时也加深下对于拓扑的了解
class Graph:
    # 构造函数
    def __init__(self,vertices):
        # 创建用处存储图中点之间关系的dict{v: [u, i]}(v,u,i都是点,表示边<v, u>, <v, i>)：边集合
        self.graph = defaultdict(list)
        # 存储图中点的个数
        self.V = vertices

    # 添加边
    def add_edge(self,u,v):
        # 添加边<u, v>
        self.graph[u].append(v)

    # 获取一个存储图中所有点的状态:dict{key: Boolean}
    # 初始时全为False
    def set_keys_station(self):
        keyStation = {}
        key = list(self.graph.keys())
        # 因为有些点，没有出边，所以在key中找不到，需要对图遍历找出没有出边的点
        if len(key) < self.V:
            for i in key:
                for j in self.graph[i]:
                    if j not in key:
                        key.append(j)
        for ele in key:
            keyStation[ele] = False
        return keyStation

    # 拓扑排序
    def topological_sort(self):
        # 拓扑序列
        queue = []
        # 点状态字典
        station = self.set_keys_station()
        # 由于最坏情况下每一次循环都只能排序一个点，所以需要循环点的个数次
        for i in range(self.V):
            # 循环点状态字典，elem：点
            for elem in station:
                # 这里如果是已经排序好的点就不进行排序操作了
                if not station[elem]:
                    self.topological_sort_util(elem, queue, station)
        return queue

    # 对于点进行排序
    def topological_sort_util(self, elem, queue, station):
        # 设置点的状态为True，表示已经排序完成
        station[elem] = True
        # 循环查看该点是否有入边，如果存在入边，修改状态为False
        # 状态为True的点，相当于排序完成，其的边集合不需要扫描
        for i in station:
            if elem in self.graph[i] and not station[i]:
                station[elem] = False
        # 如果没有入边，排序成功，添加到拓扑序列中
        if station[elem]:
            queue.append(elem)

if __name__ == "__main__":
    """
       5     4
     ↙  ↘  ↙  ↘
    2     0     1
      ↘      ↗
          3
    """
    g = Graph(6)
    g.add_edge(5, 2);
    g.add_edge(5, 0);
    g.add_edge(4, 0);
    g.add_edge(4, 1);
    g.add_edge(2, 3);
    g.add_edge(3, 1);

    print ("拓扑排序结果：")
    print(g.topological_sort())


from PyQt5 import QtWidgets , QtCore, QtGui
from PyQt5.QtGui import QPalette, QColor
from PyQt5.QtCore import QUrl, QDirIterator, Qt
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QPushButton, QFileDialog, QAction, QHBoxLayout, QVBoxLayout, QSlider,QMessageBox
from pyqtgraph import PlotWidget, plot, PlotItem
from Gui import Ui_MainWindow
import numpy as np
import pyqtgraph as pg
import matplotlib.pyplot as plt
import logging
import sys
import wave
import pydub
import pyaudio
import os
import sounddevice as sd
from songdata import song_data

class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(ApplicationWindow, self).__init__()
        pg.setConfigOption('background', 'w')
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.Song1 = []
        self.Song2 = []

        self.mixedArray = []
        self.mixedArray_Duration=0

        self.mixedsong = song_data()

        self.songsArray = []
        self.song_index = 0

        self.Ext_1=None
        self.Ext_2=None

        self.Input_X_1=[]
        self.Input_Y_1=[]
        self.Input_X_2=[]
        self.Input_Y_2=[]
        self.durationF_1=0
        self.durationF_2=0

        self.similarityIndex = []
        self.similarityIndexID = []
        self.topTenSimilarityIndex = []

        LOG_FILENAME = 'LOGFILE.txt'
        file = open(LOG_FILENAME,"r+")
        file.truncate(0)
        file.close()

        self.generate_spectrograms()

        logging.basicConfig(filename=LOG_FILENAME,format='%(asctime)s - %(message)s ',datefmt='%d-%b-%y %H:%M:%S',level=logging.INFO)

    #----------------------------------------------------------------------------------------------------------------
        self.graphic_View_Array=[self.ui.Spectrogram_1,self.ui.Spectrogram_2]
        for x in self.graphic_View_Array:
            x.setMouseEnabled(x=False, y=False)
            pass
        #------------------

        self.playArray=[self.ui.Play_1,self.ui.Play_2]
    #----------------------------------------------------------------------------------------------------------------
        self.browseArray=[self.ui.BrowseButton,self.ui.BrowseButton_2]
        self.ui.BrowseButton.clicked.connect(lambda : self.Import(0))
        self.ui.BrowseButton_2.clicked.connect(lambda : self.Import(1))
        self.ui.GenerateButton.clicked.connect(self.start_compare)
    #----------------------------------------------------------------------------------------------------------------
        self.ui.MixerSlider.sliderReleased.connect(self.ValueChanged)
    #----------------------------------------------------------------------------------------------------------------
        self.stopArray=[self.ui.Stop_Button,self.ui.Stop_Button_2]
        for x in self.stopArray:
            x.clicked.connect(self.Stop)
    #----------------------------------------------------------------------------------------------------------------

    def Import(self,num):
        filePaths = QtWidgets.QFileDialog.getOpenFileNames(self, 'Multiple File',"~/Desktop",'*.mp3 && *.wav')
        for filePath in filePaths:
            for f in filePath:
                if f == "*" or f == None:
                    break
                ext = os.path.splitext(f)[-1].lower()  # Check file extension

                if ext == ".wav":
                    self.X_Y_Data = self.ReadFromWav(f,num)
                    if num==0:
                        self.Ext_1=ext
                        self.Input_X_1=self.X_Y_Data[0]
                        self.Input_Y_1=self.X_Y_Data[1]
                        self.ui.Play_1.clicked.connect(lambda : self.Play_Wav(self.Input_Y_1[0],self.durationF_1))
                        logging.info('User Imported wav file from Browse 1')

                    if num==1:
                        self.Ext_2=ext
                        self.Input_X_2=self.X_Y_Data[0]
                        self.Input_Y_2=self.X_Y_Data[1]
                        self.ui.Play_2.clicked.connect(lambda : self.Play_Wav(self.Input_Y_2[0],self.durationF_2))
                        logging.info('User Imported wav file from Browse 2')

                if ext == ".mp3" :

                    pydub.AudioSegment.converter = r"C:\ffmpeg\ffmpeg\bin\ffmpeg.exe"
                    songFile = pydub.AudioSegment.from_mp3(f)
                    if num==0:
                        self.Ext_1=ext
                        self.Song1 = np.array(songFile.get_array_of_samples())
                        self.Song1 = self.Song1.reshape((-1, 2))
                        self.ui.Play_1.clicked.connect(lambda : self.Play(self.Song1))
                        logging.info('User Imported mp3 file from Browse 1')
                    if num==1:
                        self.Ext_2=ext
                        self.Song2 = np.array(songFile.get_array_of_samples())
                        self.Song2 = self.Song2.reshape((-1, 2))
                        self.ui.Play_2.clicked.connect(lambda : self.Play(self.Song2))
                        logging.info('User Imported mp3 file from Browse 2')

   #----------------------------------------------------------------------------------------------------------------

   #----------------------------------------------------------------------------------------------------------------

    def ReadFromWav(self,file,num):

        p = pyaudio.PyAudio()
        self.waveFile = wave.open(file,'rb')

        self.format = p.get_format_from_width(self.waveFile.getsampwidth())
        channel = self.waveFile.getnchannels()
        self.rate = self.waveFile.getframerate()
        self.frame = self.waveFile.getnframes()
        self.stream = p.open(format=self.format,  # DATA needed for streaming
                            channels=channel,
                            rate=self.rate,
                            output=True)
        if num==0:
            self.durationF_1 = self.frame / float(self.rate) # For playing the sound

        if num==1:
            self.durationF_2 = self.frame / float(self.rate) # For playing the sound

        self.data_int = self.waveFile.readframes(self.frame)
        self.data_plot = np.fromstring(self.data_int, 'Int16')
        self.data_plot.shape = -1, 2

        self.data_plot = self.data_plot.T
        self.time = np.arange(0, self.frame) * (1.0 / self.rate)

        return self.time,self.data_plot

    #------------------------------------------------------------------------------------------------------------------------

    #------------------------------------------------------------------------------------------------------------------------
    def ValueChanged(self):
        userChoice=self.ui.SelectedSong.currentText()
        value= (self.ui.MixerSlider.value())/10
        self.mixedArray=[]

        if (self.Ext_1==self.Ext_2) and (self.Ext_2==".mp3"):
            if len(self.Song2)!=0 and len(self.Song1)!=0:
                if(userChoice=="First_Song"):
                    if len(self.Song1) >= len(self.Song2):
                        self.mixedArray=((self.Song1[0:len(self.Song2)]*value)+(self.Song2*(1-value)))/10000
                    else:
                        self.mixedArray=((self.Song1*value)+(self.Song2[0:len(self.Song1)]*(1-value)))/10000

                elif(userChoice=="Second-Song"):
                    if len(self.Song2) >= len(self.Song1):
                        self.mixedArray=((self.Song2[0:len(self.Song1)]*value)+(self.Song1*(1-value)))/10000
                    else:
                        self.mixedArray=((self.Song2*value)+(self.Song1[0:len(self.Song2)]*(1-value)))/10000

                self.ui.Play_Mix.clicked.connect(lambda : self.Play(self.mixedArray))
                logging.info('User Created a mix with mp3 files ')
            else:
                QMessageBox.warning(self,'Warning',"ADD TWO SONGS", QMessageBox.Ok )
                logging.info('User tried to Create a mix while there is No 2 Songs imported')

        elif (self.Ext_1==self.Ext_2) and (self.Ext_2==".wav") :
            if len(self.Input_Y_1)!=0 and len(self.Input_Y_2)!=0:
                if(userChoice=="First_Song"):
                    if len(self.Input_Y_1[0]) >= len(self.Input_Y_2[0]):
                        self.mixedArray.append(((self.Input_Y_1[0][0:len(self.Input_Y_2[0])]*value)+(self.Input_Y_2[0]*(1-value)))/10000)
                        self.mixedArray.append(((self.Input_Y_1[1][0:len(self.Input_Y_2[1])]*value)+(self.Input_Y_2[1]*(1-value)))/10000)
                        self.mixedArray_Duration=self.durationF_1
                    else:
                        self.mixedArray.append(((self.Input_Y_1[0]*value)+(self.Input_Y_2[0][0:len(self.Input_Y_1[0])]*(1-value)))/10000)
                        self.mixedArray.append(((self.Input_Y_1[1]*value)+(self.Input_Y_2[1][0:len(self.Input_Y_1[1])]*(1-value)))/10000)
                        self.mixedArray_Duration=self.durationF_2
                elif(userChoice=="Second-Song"):
                    if len(self.Input_Y_2[0]) >= len(self.Input_Y_1[0]):
                        self.mixedArray.append(((self.Input_Y_2[0][0:len(self.Input_Y_1[0])]*value)+(self.Input_Y_1[0]*(1-value)))/10000)
                        self.mixedArray.append(((self.Input_Y_2[1][0:len(self.Input_Y_1[1])]*value)+(self.Input_Y_1[1]*(1-value)))/10000)
                        self.mixedArray_Duration=self.durationF_2
                    else:
                        self.mixedArray.append(((self.Input_Y_2[0]*value)+(self.Input_Y_1[0][0:len(self.Input_Y_2[0])]*(1-value)))/10000)
                        self.mixedArray.append(((self.Input_Y_2[1]*value)+(self.Input_Y_1[1][0:len(self.Input_Y_2[1])]*(1-value)))/10000)
                        self.mixedArray_Duration=self.durationF_1

                self.ui.Play_Mix.clicked.connect(lambda : self.Play_Wav(self.mixedArray[0],self.mixedArray_Duration))
                logging.info('User Created a mix with wav files ')

                self.mixedsong.song_data = self.mixedArray
        else:
            QMessageBox.warning(self,'Warning',"add songs with the same extension", QMessageBox.Ok )
            logging.info('User tried to Create a mix while the two songs is not the same extension')

    #------------------------------------------------------------------------------------------------------------------------

    #------------------------------------------------------------------------------------------------------------------------
    def Play(self,array):
        sd.play(array)

    def Play_Wav(self,array,D):
        if ((len(self.Input_X_1) != 0 and len(self.Input_Y_1) != 0) or ((len(self.Input_X_2) != 0 and len(self.Input_Y_2) != 0))):
            sd.play(array,len(array)/D)
        else:
            pass

    def Stop(self):
        sd.stop()
    #------------------------------------------------------------------------------------------------------------------------

    #------------------------------------------------------------------------------------------------------------------------

    def generate_spectrograms(self):
        path = '/Songs'
        filepaths = [os.path.join(r,file) for r,d,f in os.walk(os.getcwd() + path) for file in f]
        filepaths = [x for x in filepaths if x.endswith(".wav")]
        for f in filepaths:
            tempSong = song_data()
            tempSong.set_Data(f,self.song_index)
            self.songsArray.append(tempSong)
            self.song_index = self.song_index + 1

    #------------------------------------------------------------------------------------------------------------------------

    #------------------------------------------------------------------------------------------------------------------------

    def start_compare(self):
        for i in range(len(self.songsArray)):
            print(len(self.songsArray))
            percent_hashes = self.mixedArray.compareHashes(self.songsArray[i])
            percent_peaks = self.mixedArray.comparePeakFeaturesGenerateDifference(self.songsArray[i])

            tempSimilarityIndex = (percent_hashes + percent_peaks )/2
            self.similarityIndex.append(tempSimilarityIndex * 100)
            self.similarityIndexID.append(self.songsArray[i].songID)

        tempSimilarityIndex = self.similarityIndex
        print("---------------------------------")
        print(self.similarityIndexID)
        print(self.similarityIndex)
        print("---------------------------------")

        numpyArr=np.array(self.similarityIndex)
        self.TopTenSimilarIDs=numpyArr.argsort()[::-1]

        tempSimilarityIndex.sort(reverse = True)

        if len(tempSimilarityIndex) < 10 :
            for i in tempSimilarityIndex:
                self.topTenSimilarityIndex.append(i)
        else:
            for i in range(10):
                self.topTenSimilarityIndex.append(tempSimilarityIndex[i])
        print("Top Similar IDs")
        print (self.TopTenSimilarIDs)
        print(self.topTenSimilarityIndex)

        for i in range(len(self.topTenSimilarityIndex)):
            self.Fill_Similarity_Table(self.TopTenSimilarIDs[i],i)

        self.topTenSimilarityIndex = [ ]
        self.similarityIndex = [ ]
        self.similarityIndexID = [ ]

    #------------------------------------------------------------------------------------------------------------------------

    #------------------------------------------------------------------------------------------------------------------------

    def Fill_Similarity_Table(self,songIndex,normalIndex):
        rowPosition = self.ui.SongsTable.rowCount()
        self.ui.SongsTable.insertRow(rowPosition)
        numrows = self.ui.SongsTable.rowCount()
        self.ui.SongsTable.setRowCount(numrows)
        self.ui.SongsTable.setColumnCount(2)
        self.ui.SongsTable.setItem(numrows - 1, 0 ,QtGui.QSongsTableItem(self.songsArray[songIndex].songName))
        self.ui.SongsTable.setItem(numrows - 1, 1 ,QtGui.QSongsTableItem(str(round(self.topTenSimilarityIndex[normalIndex],2))+"%"))

        self.ui.SongsTable.setHorizontalHeaderItem(0,QtGui.QSongsTableItem("Song Name"))
        self.ui.SongsTable.setHorizontalHeaderItem(1,QtGui.QSongsTableItem("Similarity Index"))

    #------------------------------------------------------------------------------------------------------------------------

    #------------------------------------------------------------------------------------------------------------------------

#////////////////////////////// Main /////////////////////////////////////

def main():
    app = QtWidgets.QApplication(sys.argv)
    application = ApplicationWindow()
    application.show()
    app.exec_()

if __name__ == "__main__":
    main()


# ProblemURL: https://projecteuler.net/problem=19
daysInYear = 365
daysInLeapYear = 366
day = {0: "monday", 1: "tuesday", 2: "wednesday", 3: "thursday", 4: "friday", 5: "saturday", 6: "sunday"}
monthLength = {0: 31, 1: 28, 2: 31, 3: 30, 4: 31, 5: 30, 6: 31, 7: 31, 8: 30, 9: 31, 10: 30, 11: 31}
monthLengthLeapYear = {0: 31, 1: 29, 2: 31, 3: 30, 4: 31, 5: 30, 6: 31, 7: 31, 8: 30, 9: 31, 10: 30, 11: 31}

def isleapyear(x):
    if x % 4 == 0:
        if x % 100 == 0:
            if x % 400 == 0:
                return True
            return False
        return True
    return False

class Month:
    def __init__(self, year, monthnumber):
        self.year = year
        self.monthnumber = monthnumber
        days = 0
        for x in range(1900, year, 1):
            if isleapyear(x):
                days += daysInLeapYear
            else:
                days += daysInYear
        for x in range(monthnumber - 1):
            if isleapyear(year):
                days += monthLengthLeapYear[x]
            else:
                days += monthLength[x]
        self.monthFirstDay = days % 7

sundayList = []
for i in range(1901, 2001, 1):
    for j in range(1, 13, 1):
        sundayList.append(Month(i, j))

sundayammount = 0
for m in sundayList:
    if m.monthFirstDay == 6:
        sundayammount += 1
print(sundayammount)


import dm2022exp
import numpy as np
import pandas as pd
import copy
import math
import collections
import functools
from sklearn.preprocessing import LabelEncoder
from typing import List, Union, Tuple

class Apriori:
    score = {}

    def __init__(self, min_sup: float = 0.2):
        self.min_sup = min_sup
        self.min_conf = 0.5

    def fit(self, X: List[List[str]]):
        f = LabelEncoder()
        k = 1
        tmp = []
        rst = []
        rule = {}
        for i in X:
            for j in i:
                if j not in tmp:
                    tmp.append(j)
        f.fit(tmp)
        for i in range(len(tmp)):
            tmp[i] = list(f.transform([tmp[i]]))
        tmp = sorted(tmp)
        new_x = list(map(set, [f.transform(i) for i in copy.deepcopy(X)]))
        tmp2 = self.scan(new_x, tmp, rst, f)

        while len(tmp2) != 0:
            tmp = self.scan2(tmp2, k)
            tmp2 = self.scan(new_x, tmp, rst, f)
            self.UpdateRule(tmp2, rule, f)
            k += 1
        return rst, rule

    def UpdateRule(self, freq, rule, f):
        for value in freq:
            element = self.get_sub_set(value)
            support = self.score[str(value)]
            for number in element:
                number_set = set(number)
                no_number_set = set(value).difference(number_set)
                number_support = self.score[str(number)]
                conf = support / number_support
                if conf >= self.min_conf:
                    temp1_set = set([i for i in f.inverse_transform([i for i in number_set])])
                    temp2_set = set([i for i in f.inverse_transform([i for i in no_number_set])])
                    rule[str(temp1_set) + '->' + str(temp2_set)] = conf

    def scan(self, dataset, ck, rst, f):
        tmp = []
        for j in ck:
            support = self.calc_sup(j, dataset)
            if support >= self.min_sup:
                rst.append([frozenset(f.inverse_transform(j)), support])
                tmp.append(j)
        return tmp

    def scan2(self, lk, k):
        new_can = []
        for i in range(len(lk)):
            for j in range(i + 1, len(lk)):
                if k == 1 or lk[i][:k - 1] == lk[j][:k - 1]:
                    new_can.append(lk[i] + lk[j][-1:])
        return new_can

    def get_sub_set(self, nums):
        sub_sets = [[]]
        for x in nums:
            sub_sets.extend([item + [x] for item in sub_sets])
            pass
        sub_sets.remove([])
        sub_sets.remove(nums)
        return sub_sets

    def calc_sup(self, x, dataset):

        if str(x) in self.score.keys():
            return self.score[x]
        count = 0
        for affair in dataset:
            if set(x).issubset(affair):
                count += 1
        self.score[str(x)] = count / len(dataset)
        return count / len(dataset)

m = Apriori(0.005)
data = dm2022exp.load_ex5_data()
rst, rule = m.fit(data)
print(rst)
print(rule)