import collections
import os
import glob

from Bio import AlignIO

from zwd2rnacentral import get_folders, get_not_for_rfam_info

def get_rfam_annotations():
    data = collections.defaultdict(dict)
    with open('zwd-vs-rfam-14.1-cms.tbl', 'r') as infile:
        for line in infile.readlines():
            if line.startswith('#'):
                continue
            seq_id, _, rfam_acc, rfam_id, rest = line.split(None, 4)
            data[seq_id] = {
                'rfam_acc': rfam_acc,
                'rfam_id': rfam_id,
            }
    return data

def main():
    location = '/data/zashaweinbergdata/'

    rfam_annotations = get_rfam_annotations()
    not_for_rfam = get_not_for_rfam_info(os.path.join(location, 'not-for-Rfam'))

    print('{}\t{}\t{}\t{}\t{}\t{}\t{}'.format('Folder', 'RNA', 'Rfam ID', 'Rfam accession', '% of sequences matching Rfam', '% of sequences not matching Rfam', 'not for Rfam'))

    for folder in get_folders():
        for filename in glob.glob(os.path.join(location, folder, '*.sto')):

            rna_name = os.path.basename(filename).replace('.sto', '')
            alignment = AlignIO.read(open(filename), 'stockholm')

            excluded = False
            if os.path.join(folder, rna_name + '.sto') in not_for_rfam:
                excluded = True

            families = set()
            accessions = set()
            matched = 0
            not_matched = 0
            num_records = 0

            for record in alignment:
                seq_id = record.id
                num_records += 1
                if seq_id in rfam_annotations:
                    families.add(rfam_annotations[seq_id]['rfam_id'])
                    accessions.add(rfam_annotations[seq_id]['rfam_acc'])
                    matched += 1
                else:
                    not_matched += 1

            line = '{}\t{}\t{}\t{}\t{}\t{}\t{}'.format(folder, rna_name, ', '.join(families),
                ', '.join(accessions), matched*100/num_records, not_matched*100/num_records,
                'Not for Rfam' if excluded else '')
            print(line)

if __name__ == '__main__':
    main()


from io import BytesIO
from operator import itemgetter
from random import shuffle

from PIL import Image
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.mixins import PermissionRequiredMixin, LoginRequiredMixin
from django.db import transaction
from django.db.models import ForeignObjectRel
from django.http import JsonResponse, HttpResponseRedirect, HttpResponseForbidden, HttpResponseBadRequest
from django.shortcuts import get_object_or_404
from django.urls import reverse_lazy
from django.views.generic import ListView, CreateView, UpdateView, DeleteView
from rest_framework.decorators import api_view, renderer_classes
from rest_framework.renderers import JSONRenderer
from rest_framework.response import Response

from account.models import CustomUser
from event.models import Action, Gift, RaffleEvent, _pick_next_person, RaffleParticipation
from event.serializers import RaffleEventSerializer

class EventView(LoginRequiredMixin, ListView):
    template_name = 'event.html'
    model = Gift

    def get_queryset(self):
        event = get_object_or_404(RaffleEvent, id=self.kwargs['event_id'])
        return Gift.objects.filter(event=event)

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(object_list=object_list, **kwargs)
        event = get_object_or_404(RaffleEvent, id=self.kwargs['event_id'])
        context['user_mapping'] = sorted(((u.id, u.display_name) for u in event.participants.all()), key=itemgetter(1))
        return context

class GiftIndexView(PermissionRequiredMixin, ListView):
    permission_required = 'view_gift'
    template_name = 'gift_index.html'
    model = Gift

    def get_queryset(self):
        return super().get_queryset().order_by('add_ts')

class MyGiftsView(LoginRequiredMixin, ListView):
    template_name = 'gift_index.html'
    model = Gift

    def get_queryset(self):
        return Gift.objects.filter(added_by=self.request.user).order_by('add_ts')

class GiftCreateView(LoginRequiredMixin, CreateView):
    model = Gift
    fields = ['description', 'image', 'event']
    template_name = 'gift_form.html'
    success_url = reverse_lazy('my_donations')

    def form_valid(self, form):
        gift = form.save(commit=False)
        gift.added_by = self.request.user
        gift.save()
        self.object = gift
        return HttpResponseRedirect(self.get_success_url())

class GiftUpdateView(LoginRequiredMixin, UpdateView):
    model = Gift
    fields = ['description', 'image', 'event']
    template_name = 'gift_form.html'
    success_url = reverse_lazy('my_donations')

    def get_queryset(self):
        base_qs = super(GiftUpdateView, self).get_queryset()
        return base_qs.filter(added_by=self.request.user)

class GiftDeleteView(LoginRequiredMixin, DeleteView):
    model = Gift
    success_url = reverse_lazy('my_donations')
    template_name = 'gift_delete_confirmation.html'

    def get_queryset(self):
        base_qs = super(GiftDeleteView, self).get_queryset()
        return base_qs.filter(added_by=self.request.user)

class MyTicketsView(LoginRequiredMixin, ListView):
    template_name = 'ticket_index.html'
    model = RaffleParticipation

    def get_queryset(self):
        return RaffleParticipation.objects.filter(user=self.request.user)

class RaffleParticipationCreateView(LoginRequiredMixin, CreateView):
    model = RaffleParticipation
    fields = ['event','number_of_tickets']
    template_name = 'ticket_form.html'
    success_url = reverse_lazy('my_tickets')

    def form_valid(self, form):
        raffle_participation = form.save(commit=False)
        raffle_participation.user = self.request.user
        raffle_participation.save()
        self.object = raffle_participation
        return HttpResponseRedirect(self.get_success_url())

class RaffleParticipationUpdateView(LoginRequiredMixin, UpdateView):
    model = RaffleParticipation
    fields = ['number_of_tickets']
    template_name = 'ticket_form.html'
    success_url = reverse_lazy('my_tickets')

    def get_queryset(self):
        base_qs = super(RaffleParticipationUpdateView, self).get_queryset()
        return base_qs.filter(user=self.request.user)

class RaffleParticipationDeleteView(LoginRequiredMixin, DeleteView):
    model = RaffleParticipation
    success_url = reverse_lazy('my_tickets')
    template_name = 'raffle_participation_delete_confirmation.html'

    def get_queryset(self):
        base_qs = super(RaffleParticipationDeleteView, self).get_queryset()
        return base_qs.filter(user=self.request.user)

@permission_required('change_raffleevent')
def change_current_gift_picker(request, event_id):
    raffle_event = get_object_or_404(RaffleEvent, id=event_id)
    current_user = request.user
    with transaction.atomic():
        _pick_next_person(current_user, raffle_event)
    return JsonResponse({'success': True})

@permission_required('change_raffleevent')
def permute_images(request, event_id):
    raffle_event = get_object_or_404(RaffleEvent, id=event_id)

    with transaction.atomic():
        gifts = Gift.objects.filter(event_id=raffle_event.id)
        container_ids = [r.id for r in gifts]
        shuffle(container_ids)
        for gift, container_id in zip(gifts, container_ids):
            gift.container_id = container_id
        Gift.objects.bulk_update(gifts, ['container_id'])
    return JsonResponse({'success': True})

@permission_required('change_raffleevent')
def reset_raffle(request, event_id):
    raffle_event = get_object_or_404(RaffleEvent, id=event_id)

    with transaction.atomic():
        raffle_event.phase = RaffleEvent.Phase.PRE_START
        raffle_event.current_user = None
        raffle_event.save()

        gifts = raffle_event.gift_set
        gifts.update(wrapped=True, container_id=None, given_to=None)

        participantions = raffle_event.raffleparticipation_set
        participantions.update(number_of_times_drawn=0)

        actions = raffle_event.action_set.all()
        actions.delete()

    return JsonResponse({'success': True})

@permission_required('change_raffleevent')
@api_view(('GET',))
@renderer_classes((JSONRenderer,))
def summarise_raffle(request,event_id):
    raffle_event = get_object_or_404(RaffleEvent, id=event_id)
    serializer = RaffleEventSerializer(raffle_event)
    return Response(serializer.data)

@login_required
def rotate_image(request, gift_id, angle):
    current_user = request.user
    gift = get_object_or_404(Gift, id=gift_id)
    if gift.added_by != current_user:
        if current_user.is_superuser is False:
            return HttpResponseForbidden()
    if angle not in (90, 180, 270):
        return HttpResponseBadRequest()
    image_stream = BytesIO()
    pixelated_image_stream = BytesIO()

    img = Image.open(BytesIO(gift.image.read()))
    img.rotate(angle, expand=1).save(image_stream, format=img.format)

    pixelated_image = Image.open(BytesIO(gift.pixelated_image.read()))
    pixelated_image.rotate(angle, expand=1).save(pixelated_image_stream, format=pixelated_image.format)

    gift.save(new_image_data=(image_stream, pixelated_image_stream))

    return HttpResponseRedirect(request.META.get('HTTP_REFERER') or reverse_lazy('my_donations'))

@login_required
def process_image_click(request):
    raffle_event = get_object_or_404(RaffleEvent, id=request.POST['event_id'])
    if raffle_event.phase in (raffle_event.Phase.PRE_START, raffle_event.Phase.FINISHED):
        return JsonResponse({'error': 'Raffle not in progress'})

    gift_id = int(request.POST['image_id'].replace('image-', ''))
    gift = get_object_or_404(Gift, id=gift_id)

    if raffle_event.phase == raffle_event.Phase.NORMAL_RAFFLE:
        if raffle_event.current_user != request.user:
            return JsonResponse({'error': "It's not your turn to pick a gift!"})
        if raffle_event.gift_set.filter(wrapped=True).count() == 0:
            return JsonResponse({'error': "All gifts have been unwrapped."})

        if gift.event != raffle_event:
            return JsonResponse({'error': 'Gift: %s and RaffleEvent: %s are inconsistent' % (gift, raffle_event)})
        if not gift.wrapped:
            return JsonResponse({'error': 'Gift already unwrapped'})

        gift.given_to = request.user
        gift.wrapped = False
        action = Action(gift=gift,
                        from_user=gift.added_by,
                        to_user=request.user,
                        by_user=request.user,
                        action_type=Action.ActionType.CHOOSE_GIFT,
                        event=raffle_event,
                        )
        with transaction.atomic():
            gift.save()
            action.save()
            _pick_next_person(current_user=request.user, raffle_event=raffle_event)
        return JsonResponse({
            'error': None,
            'gift_description': gift.description,
            'gift_image_url': gift.image_url,
            'gift_id':gift.id,
        })
    elif raffle_event.phase == raffle_event.Phase.GIFT_SWAP:
        return JsonResponse({'modal_data': {
            'gift_id': gift.id,
            'gift_description': gift.description,
            'current_user_display_name': gift.given_to.display_name,
            'current_user_id': gift.given_to_id,
        }})

@login_required
def process_swap_gift(request):
    raffle_event = get_object_or_404(RaffleEvent, id=request.POST['event_id'])
    if raffle_event.phase != RaffleEvent.Phase.GIFT_SWAP:
        return JsonResponse({'error': 'Gift swap not in progress'})

    with transaction.atomic():
        gift = get_object_or_404(Gift, id=request.POST['gift_id'])
        if gift.given_to_id != int(request.POST['current_user_id']):
            return JsonResponse(
                {'error': 'Looks like someone else has already swapped the owner of %s' % gift.description})
        swap_to = get_object_or_404(CustomUser, id=request.POST['to_user_id'])
        action = Action(gift=gift,
                        from_user=gift.given_to,
                        to_user=swap_to,
                        by_user=request.user,
                        action_type=Action.ActionType.TRANSFERRED,
                        event=raffle_event,
                        )
        gift.given_to = swap_to
        action.save()
        gift.save()
    return JsonResponse({'error':None})

@login_required
def stream(request):
    event = get_object_or_404(RaffleEvent, id=request.POST['event_id'])

    last_processed_action = request.POST.get('last_processed_action', 0)
    activity = Action.objects.filter(id__gt=last_processed_action,
                                     event=event,
                                     )
    container_contents = {r.image_container_id:
        {
            'src_url': r.image_url,
            'gift_id': r.id,
            'unwrapped': not r.wrapped,
            'given_to': r.given_to.display_name if r.given_to else None,
            'gift_description': '' if r.wrapped else r.description,
        } for r in event.gift_set.all()}

    user_status_text = _get_user_status_text(event, request)

    return JsonResponse({
        'activity': [a.message for a in activity],
        'last_event': max(a.id for a in activity) if len(activity) > 0 else last_processed_action,
        'container_contents': container_contents,
        'user_status': user_status_text,
    })

def _get_user_status_text(event, request):
    user_status_template = '{user}: {tickets}{swaps} {cost}'
    ticket_details = request.user.raffleparticipation_set.filter(event_id=event.id).first()
    total_owed = 0
    if not ticket_details:
        tickets_text = 'No tickets for the raffle'
    else:
        tickets_text = '{} tickets of {} drawn'.format(
            ticket_details.number_of_times_drawn,
            ticket_details.number_of_tickets,
        )
        total_owed += 5 * ticket_details.number_of_tickets
    if event.phase in (RaffleEvent.Phase.GIFT_SWAP, RaffleEvent.Phase.FINISHED):
        swaps = request.user.initiated_actions.filter(
            action_type=Action.ActionType.TRANSFERRED,
            event=event.id).count()
        swaps_text = ', swapped {} gifts'.format(swaps)
        total_owed += 5 * swaps
    else:
        swaps_text = ''
    user_status_text = user_status_template.format(
        user=request.user,
        tickets=tickets_text,
        swaps=swaps_text,
        cost='(£{} owed)'.format(total_owed),
    )
    return user_status_text


#! /usr/bin/env python3 #
# -*- coding: utf-8 -*- #

## Implementação de Funções - - - - - - - - - - - - - - - - - - - - - #
def scale(data, factor):
    """
    """
    for j in range(len(data)):
        data[j] *= factor

def main(args):
    """
    """

    data = [1,2]
    factor = 3
    print(f'data: {data} \t factor: {factor}')

    scale(data, factor)
    print(f'data: {data}')
    # o código funciona, pois o parâmetro data faz referência ao mesmo
    # objeto da variável data, da função main

    return EX_OK

## Executa o script como módulo principal - - - - - - - - - - - - - - #
if __name__ == "__main__":
    import sys
    from os import EX_OK

    codigo_retorno = main(sys.argv)
    sys.exit(codigo_retorno)


# Define a class for nodes of the binary tree
class Node:
    def __init__(self, key):
        self.key = key # The value of the node
        self.left = None # The left child of the node
        self.right = None # The right child of the node

# Initialize min and max as None
min = None
max = None

# Define a recursive function to check if a tree is BST
def isBST(node, min, max):
    # If the node is None, return True (base case)
    if node is None:
        return True
    # If the node's key is less than min or greater than max, return False (violation of BST property)
    if (min is not None and node.key < min) or (max is not None and node.key > max):
        return False
    # Recursively check if the left subtree is BST with min as None and max as the node's key, and if the right subtree is BST with min as the node's key and max as None
    left = isBST(node.left, min, node.key)
    right = isBST(node.right, node.key, max)
    # Return the logical AND of the results of the recursive calls
    return left and right

# Example of a BST
root = Node(10)
root.left = Node(5)
root.right = Node(15)
root.left.left = Node(3)
root.left.right = Node(7)
root.right.left = Node(12)
root.right.right = Node(17)

# Example of a non-BST
root2 = Node(10)
root2.left = Node(5)
root2.right = Node(15)
root2.left.left = Node(3)
root2.left.right = Node(7)
root2.right.left = Node(8) # This violates the BST property
root2.right.right = Node(17)

# Test the function on the examples
print(isBST(root, min, max)) # True
print(isBST(root2, min, max)) # False


import random as rd
import os

logo = """
.------.            _     _            _    _            _
|A_  _ |.          | |   | |          | |  (_)          | |
|( \/ ).-----.     | |__ | | __ _  ___| | ___  __ _  ___| | __
| \  /|K /\  |     | '_ \| |/ _` |/ __| |/ / |/ _` |/ __| |/ /
|  \/ | /  \ |     | |_) | | (_| | (__|   <| | (_| | (__|   <
`-----| \  / |     |_.__/|_|\__,_|\___|_|\_\ |\__,_|\___|_|\_\\
      |  \/ K|                            _/ |
      `------'                           |__/
"""

def play_blackjack():
    try:
        os.system("cls")
        print(logo)
        while True:
            cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
            ai_card = rd.sample(cards, 2)
            user_card = rd.sample(cards, 2)
            print(f"\nUser: {user_card}\t\tAI: {ai_card}")
            if sum(user_card) == 21 and sum(ai_card) == 21:
                print("\n\n\t TIED :)\n")
                continue
            elif sum(user_card) == 21:
                print("\n\n\t Blackjack, You Won :)\n")
                break
            elif sum(ai_card) == 21:
                print("\n\n\t Blackjack, AI Won :(\n")
                break
            user_choice = input("\n\nStand or Hit (S/H): ")
            sequence = [0, 1]
            ai_choice = rd.choice(sequence)
            if user_choice == "h":
                user_card_2 = rd.sample(cards, 1)
                if user_card_2 == 11:
                    user_card_2 = input("\n(1 or 11): ")
                user_total_cards = user_card + user_card_2
            else:
                user_total_cards = user_card

            if ai_choice == 1:
                ai_card_2 = rd.sample(cards, 1)
                ai_total_cards = ai_card + ai_card_2
            else:
                ai_total_cards = ai_card

            print(f"\n\nUser: {user_total_cards}\t\tAI: {ai_total_cards}")

            ai_score = sum(ai_total_cards)
            user_score = sum(user_total_cards)

            if user_score > 21 and ai_score > 21:
                print("\n\n\t Bust ;( \n")
                proceed = input("\nDo you want to continue? (Y/N): ")
                if proceed == "n":
                    exit()
                else:
                    play_blackjack()
            elif user_score == ai_score:
                print("\n\n\t TIED ;) \n")
                continue
            elif user_score > 21:
                print("\n\n\t AI Won :(\n")
            elif ai_score > 21:
                print("\n\n\t You Won :)\n")
            elif user_score > ai_score and user_score <= 21:
                print("\n\n\t You Won :)\n")
                break
            elif ai_score > user_score and ai_score <= 21:
                print("\n\n\t AI Won :(\n")
                break
            else:
                print("\n\n\t Bust ;)\n")

        proceed = input("\nDo you want to continue? (Y/N): ")
        if proceed == "n":
            exit()
        else:
            play_blackjack()

    except KeyboardInterrupt:
        print("\n\n\t Operation cancelled by user :( \n".title())
    except ValueError:
        print("\n\n\t Please Enter the values carefully ;( \n".title())

if __name__ == "__main__":
    play_blackjack()


from __future__ import print_function
caffe_root = 'code/'
import sys
sys.path.insert(0, caffe_root + 'python')

import os
import numpy as np
from PIL import Image as PILImage
import caffe

def main():
  net_path = "deploy.prototxt"
  model_path = "trained.caffemodel"
  gpu_id = 0

  net = Segmenter(net_path, model_path, gpu_id)
  img = np.zeros((505,505,3))

  # print(img)

  segm = net.predict([img])

  # print("result is")
  # print(segm)

  assert np.all(segm==img.astype(np.float32).transpose(2, 0, 1)), "ERROR: Deeplab did not return expected result"
  print("SUCCESS")

class Segmenter(caffe.Net):
  def __init__(self, prototxt, model, gpu_id=-1):
    caffe.Net.__init__(self, prototxt, model, caffe.TEST)
   # self.set_phase_test()

    if gpu_id < 0:
      caffe.set_mode_cpu()
    else:
      caffe.set_mode_gpu()
      caffe.set_device(gpu_id)

  def predict(self, inputs):
    # uses MEMORY_DATA layer for loading images and postprocessing DENSE_CRF layer
    img = inputs[0].transpose((2, 0, 1))
    img = img[np.newaxis, :].astype(np.float32)
    label = np.zeros((1, 1, 1, 1), np.float32)
    data_dim = np.zeros((1, 1, 1, 2), np.float32)
    data_dim[0][0][0][0] = img.shape[2]
    data_dim[0][0][0][1] = img.shape[3]

    img      = np.ascontiguousarray(img, dtype=np.float32)
    label    = np.ascontiguousarray(label, dtype=np.float32)
    data_dim = np.ascontiguousarray(data_dim, dtype=np.float32)

    self.set_input_arrays(img, label)
    out = self.forward()

    predictions = out[self.outputs[0]] # the output layer should be called crf_inf
    segm_result = predictions[0].argmax(axis=0).astype(np.uint8)

    return segm_result

if __name__ == '__main__':
  main()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 11 14:19:59 2021

@author: boettner
"""
import numpy as np
import pandas as pd

dicto = {}

# note: already dust corrected

for i in range(0,10):
    data_i = pd.read_csv('LF_Vmax_udFUV_z'+str(i)+'.dat',
                         delim_whitespace=True).values

    data = data_i.copy()

    data[:,1] = data[:,1] + np.log10(2.5) # change normalisation from per mag to per dex

    data[:,0] = data[:,0]

    data[:,2] = data_i[:,3] # lower error
    data[:,3] = data_i[:,2] # upper error

    #data = data[~np.isnan(data).any(axis=1)]

    dicto[str(i)] = data

dictz = {}
dictz['0'] = np.concatenate([dicto['0'], dicto['1']])
dictz['1'] = np.concatenate([dicto['2'], dicto['3'], dicto['4'], dicto['5'], dicto['6']])
dictz['2'] = dicto['7']
dictz['3'] = dicto['8']
dictz['4'] = dicto['9']

np.savez('Cucciati2012UVLF.npz', **dictz)

data/UVLFs/UVLF _ Madau _ z 0-5/data_processing.py


import unittest
import random

from bsearch import bsearch

class TestBinarySearch(unittest.TestCase):
    def test_bsearch_positive(self):
        for _ in range(100):
            arr = sorted(list(set([random.randint(0, 1000) for _ in range(100)])))
            idx = random.randint(0, len(arr) - 1)
            target = arr[idx]
            result = bsearch(arr, target)
            print(target)
            self.assertEqual(result, idx)

    def test_bsearch_negative(self):
        for _ in range(100):
            arr = sorted(list(set([random.randint(0, 1000) for _ in range(100)])))
            while True:
                target = random.randint(0, 10000)
                if target not in arr:
                    break
            result = bsearch(arr, target)
            self.assertEqual(result, None)


#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File         :   process_api_sequence.py
@Desc         :   process api sequence
'''

import os
import pandas as pd
from tqdm import tqdm
import numpy as np

def init_data(config, filepath):
    if(config.data_name == 'cuck'):
        data = pd.read_excel(filepath)
        data = data.sort_values('timestamp')
        api_names = data[config.api_header]
        pids = data[config.pid_header]
        status = data[config.status_header]
        status = [True if state == 'SUCCESS' else False for state in list(status)]

    return api_names, pids, status

def load_api_sequence_pid(config, filepath, api2idx):

    pid_order_list = []

    base_sequences = [] # 记录原始序列

    tpg_apisequence_dict = {} # pid: api_sequence
    pid_apit_dict = {} # pid: apit_sequence
    tag_extime_dict = {} # tag: extime

    api_names, pids, status = init_data(config, filepath)

    for t, (api_name, pid, state) in enumerate(zip(api_names, pids, status), 1):
        if('status' in config.params):
            api_name += ('_S' if state else '_F')

        if(api_name not in api2idx): api2idx[api_name] = len(api2idx)
        api_index = api2idx[api_name]
        base_sequences.append(api_index)

        # pid - 原始序列
        if(pid not in pid_order_list): pid_order_list.append(pid)

        # tag_node - min(extime)
        if(api_index not in tag_extime_dict): tag_extime_dict[api_index] = t

        # pid - api sequence
        # pid - time sequence
        if(pid not in tpg_apisequence_dict):
            tpg_apisequence_dict[pid] = [api_index, ]
            pid_apit_dict[pid] = [t, ]
        else:
            tpg_apisequence_dict[pid].append(api_index) # 按照 PID 划分 API calls
            pid_apit_dict[pid].append(t) # 同时记录每个 API call 的执行时间

    tag_edges = {} # pid - (api_s, api_e)
    tag_edget_dict = {} # pid - {(api_s, api_e): time sequence}
    for pid, api_sequence in tpg_apisequence_dict.items():
        edges = list(zip(api_sequence, api_sequence[1:]))
        tag_edges[pid] = list(set(edges))

        if(pid not in tag_edget_dict.keys()): tag_edget_dict[pid] = {}

        for edge, t in zip(edges, pid_apit_dict[pid][1:]):
            if(edge not in tag_edget_dict[pid].keys()):
                tag_edget_dict[pid][edge] = [t, ]
            else:
                tag_edget_dict[pid][edge].append(t)

    pid_api_sequences = [tpg_apisequence_dict[pid] for pid in pid_order_list]
    return pid_api_sequences, base_sequences, status, pid_apit_dict, (tag_edges, tag_edget_dict, tag_extime_dict), len(api_names), len(set(api_names))

def load_api_sequence_cuck(config):

    api2idx = {'<UNK>' : 0}
    idx2api = {0 : '<UNK>'}

    pid_api_sequences = []
    base_sequences = []
    status = []
    datanames = []
    labels = []

    tag_datas = [] # edges, edge_time_dict, node_extime_min
    tpg_datas = [] # edges, edge_time_dict

    for rootpath, _, filenames in os.walk(config.data_dir):

        file_type = os.path.split(rootpath)[-1] # 黑白样本的标识通过 文件夹名称来识别
        if(file_type not in ('black', 'white')): continue

        for filename in tqdm(filenames):

            pid_api_sequence_xml, base_sequence_xml, status_xml, tpg_data, tag_data, length, count = load_api_sequence_pid(config, os.path.join(rootpath, filename), api2idx)
            if(length >= config.sequence_length_min and count >= config.api_count_min):
                pid_api_sequences.append(pid_api_sequence_xml)
                base_sequences.append(base_sequence_xml)
                status.append(status_xml)
                tpg_datas.append(tpg_data)
                tag_datas.append(tag_data)
                datanames.append(str(os.path.join(rootpath, filename)))
                labels.append(0 if file_type == 'black' else 1)

    idx2api = {value: key for key, value in api2idx.items()}

    return pid_api_sequences, base_sequences, status, datanames, tpg_datas, tag_datas, labels, api2idx, idx2api, None

def load_api_sequence(config):
    return load_api_sequence_cuck(config)


# -*- coding: utf-8 -*-
"""
Created on Sun Sep 16 18:06:23 2018

@author: breezefay
"""

import csv
import prettytable as pt;

csv_file=csv.reader(open("E:\zoePY\hw3\Data\Grade.csv",'r'))
lines = csv_file;

#df = pd.read_csv(csv_file)

#df.head()

###get data from Grade.csv and find the id in case of being unable to get value
list1 = []
for line in lines:
    list1.append(line)
    #mandGra = line[1]
    #engGra = line[2]
   # mathGra = line[3]
    #linej = line[1][1]

    #a = np.array(line[1])
    #b = np.array(line[2])
    #c = a + b

##not finish yet TT

aveGG = ["平均"]
for j in range(1,4):
    temp =0
    cont =0
    for i in range(1,9):

        temp = int(list1[i][j])
        cont = cont + temp
        ave = cont/8
        if i == 8:
            aveGG.append(str(ave))

       # '''
        #if j == 1:
         #   ave = cont / 8
       # else:
         #   ave = cont /(8*(j-1))
       # '''

    #aveGG.append(str(cont))

print(aveGG)

avePPerG = []
for j in range(1,9):
    tempp = 0
    contt = 0
    for i in range(1,4):

        tempp = int(list1[j][i])
        contt = contt + tempp
        avePGG = contt / 3
        if i == 3:
            avePGG = round((avePGG)+0.01,2)
            avePPerG.append(str(avePGG))
print(avePPerG)

## calculate the value

'''
temp1 = 0
cont1 = 0

for i in range(1,9):
    temp1 = int(list1[i][1])
    cont1 = cont1 + temp1

aveMand = cont1/8

temp2 = 0
cont2 = 0

for i in range(1,9):
    temp2 = int(list1[i][2])
    cont2 = cont2 + temp2
aveEng = cont2 / 8

temp3 = 0
cont3 = 0
for i in range(1,9):
    temp3 = int(list1[i][3])
    cont3 = cont3 + temp3
aveMath = cont3 / 8

aveManEngMat = (aveMand + aveEng + aveMath) /3

aveG =["平均",str(aveMand),str(aveEng),str(aveMath)]

#print(aveG)

temp4 = 0
cont4 = 0
for i in range(1,4):
    temp4 = int(list1[1][i])
    cont4 = cont4 + temp4
BluePerG = round(cont4 / 3+0.01,2)
temp5 = 0
cont5 = 0
for i in range(1,4):
    temp5 = int(list1[2][i])
    cont5 = cont5 + temp5
fishPerG = round(cont5 /3+0.01,2)
temp6 = 0
cont6 = 0
for i in range(1,4):
    temp6 = int(list1[3][i])
    cont6 = cont6 + temp6
HHPerG = round(cont6/3+0.01,2)
temp7 = 0
cont7 = 0
for i in range(1,4):
    temp7 = int(list1[4][i])
    cont7 = cont7 + temp7
ZoePerG = round(cont7/3+0.01,2)
temp8 = 0
cont8 = 0
for i in range(1,4):
    temp8 = int(list1[5][i])
    cont8 = cont8 + temp8
YenPerG = round(cont8/3+0.01,2)
temp9 = 0
cont9 = 0
for i in range(1,4):
    temp9 = int(list1[6][i])
    cont9 = cont9 + temp9
KaiPerG = round(cont9/3+0.01,2)
temp10 = 0
cont10 = 0
for i in range(1,4):
    temp10 = int(list1[7][i])
    cont10 = cont10 + temp10
XianPerG= round(cont10/3+0.01,2)
temp11 = 0
cont11 = 0
for i in range(1,4):
    temp11 = int(list1[8][i])
    cont11 = cont11 + temp11
ShihPerG = round(cont11/3+0.001,2)

avePerG =[str(BluePerG),str(fishPerG),str(HHPerG),str(ZoePerG),str(YenPerG),str(KaiPerG),str(XianPerG),str(ShihPerG),str(aveManEngMat)]

#print(avePerG)
'''
from prettytable import from_csv
fp = open("E:\zoePY\hw3\Data\Grade.csv", "r")

pt = csv.reader(fp)
pt = from_csv(fp)
pt.add_row(aveG)
pt.add_column("個人平均",avePerG)
print(pt)
fp.close()


# 모든 숫자를 미리 구해놓고 차례대로

from collections import deque

def convert(converted, number, n):
    dic = {10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F'}
    if number == 0:
        converted.append('0')
        return
    tmp = deque()
    while number:
        k = number % n
        if k >= 10:
            tmp.appendleft(dic[k])
        else:
            tmp.appendleft(str(number % n))
        number = number // n
    converted.extend(tmp)

def solution(n, t, m, p):
    answer = []

    numbers = [num for num in range(50000)]
    converted = []
    for number in numbers:
        convert(converted, number, n)
    for i in range(t):
        answer.append(converted[m * i + p-1])
    # print(''.join(converted))

    return ''.join(answer)

프로그래머스/lv2/17687. ［3차］ n진수 게임/［3차］ n진수 게임.py

［3차］ n진수 게임.py


'''
Given an array A of positive lengths, return the largest perimeter of a triangle with non-zero area, formed from 3 of these lengths.

If it is impossible to form any triangle of non-zero area, return 0.
'''

class Solution:
    def largestPerimeter(self, A: List[int]) -> int:
        s = 0
        A.sort(reverse = True)
        while len(A) >= 3:
            if (A[0] < A[1] + A[2]) and (A[0] - A[2] < A[1]):
                s = sum(A[:3])
                break
            else:
                A = A[1:]

        return s


from __future__ import annotations

from pathlib import Path

from click.testing import CliRunner
from hypothesis import given
from hypothesis.strategies import integers

from utilities.hypothesis import text_ascii
from utilities.pathlib import temp_cwd
from utilities.scripts.luigi_server import _get_args, main

class TestLuigiServer:
    @given(
        pid_file=text_ascii(min_size=1),
        log_dir=text_ascii(min_size=1),
        state_path=text_ascii(min_size=1),
        port=integers(),
    )
    def test_get_args(
        self, *, pid_file: Path, log_dir: str, state_path: str, port: int
    ) -> None:
        _ = _get_args(
            pid_file=pid_file, log_dir=log_dir, state_path=state_path, port=port
        )

    def test_dry_run(self, *, tmp_path: Path) -> None:
        runner = CliRunner()
        args = ["--dry-run"]
        with temp_cwd(tmp_path):
            result = runner.invoke(main, args)
        assert result.exit_code == 0


from flask import (
	Blueprint,
	jsonify,
	request,
	session
)
from flask.views import MethodView
from src.database import db
from src.services.colors import ColorsService
from src.services.users import UsersService

bp = Blueprint('colors', __name__)

class ColorsView(MethodView):
	def get(self):
		account_id = session.get('user_id')
		if not account_id:
			return '', 401

		with db.connection as con:
			service = ColorsService(con)
			colors = service.get_color()
			return jsonify(colors), 200

	def post(self):
		account_id = session.get('user_id')
		if not account_id:
			return '', 401

		request_json = request.json
		name = request_json['name']
		hex = request_json['hex']

		if not name or not hex:
			return '', 400
		with db.connection as con:
			user_service = UsersService(con)
			is_seller = user_service.account_is_seller(account_id)
			if not is_seller:
				return '', 403
			service = ColorsService(con)
			try:
				service.add_color(name, hex)
			except:
				color = service.get_color(name)
				return jsonify(color), 208
			color = service.get_color(name)
			return jsonify(color), 200

bp.add_url_rule('/', view_func=ColorsView.as_view('colors'))


'''
# Mac mini -
from gpt4all import GPT4All
gptj = GPT4All(model_path="/Volumes/SSD/GPT4All",
		model_name="ggml-gpt4all-j.bin",
		model_type='gptj')
messages = [{"role": "user", "content": "I will call you GLaDOS"}]

result = gptj.chat_completion(messages)
print(type(result))
print(result)
'''
from gpt4allj import Model

model = Model("/mnt/models/gpt4all-ui/models/gpt_4all/ggml-gpt4all-j-v1.3-groovy.bin")

result = model.generate('Tell me about CO2 lasers')
print(type(result))
print(result)


products = {
    '001': {
        'name': 'Masło Extra',
        'price': 6.5
    },
    '002': {
        'name': 'Chleb wiejski',
        'price': 4.50
    },
    '003': {
        'name': 'Makaron Babuni',
        'price': 9.20
    },
    '004': {
        'name': 'Dżem truskawkowy',
        'price': 8.10
    },
    '005': {
        'name': 'Kiełbasa myśliwska',
        'price': 29.00
    },
    '006': {
        'name': 'Szynka konserwowa',
        'price': 22.00
    },
    '007': {
        'name': 'Chipsy paprykowe',
        'price': 6.00
    },
    '008': {
        'name': 'Serek wiejski',
        'price': 3.50
    },
    '009': {
        'name': 'Sól kuchenna',
        'price': 2.70
    },
    '010': {
        'name': 'Cukier kryształ',
        'price': 3.20
    }
}


###############################################################################
# Functions to perform Spearman N-lag cross correlation of the sentiment time #
# lines. Saves the obtained correlation matrices as SVG files. Also obtains   #
# the Granger causality between the time series.                              #
#                                                                             #
# @author Jorge Ciprián                                                       #
# Last updated: 21-05-2021.                                                   #
###############################################################################

# Imports.
import numpy as np
import pandas as pd
import seaborn as sns
import pandasql as ps
from pylab import rcParams
import matplotlib.pyplot as plt
from statsmodels.tsa.api import VAR
from statsmodels.stats.stattools import durbin_watson
from statsmodels.tsa.stattools import grangercausalitytests
from statsmodels.tsa.stattools import adfuller, zivot_andrews

# Main class. Contains the methods for N-lag Spearman cross-correlation and
# Granger causality.
class CorrCausAnalyzer():
    def __init__(self, in_path_tweets, in_path_news, out_path):
        # Assigning attributes.
        self.in_dir_tweets = in_path_tweets
        self.in_dir_news = in_path_news
        self.out_dir = out_path

    # Method for loading the datasets and doing the required pre-processing
    # for correlation and causality analysis.
    def load_datasets(self):
        print("Loading datasets...")
        # Getting source paths.
        news_source_path = self.in_dir_news
        tweets_source_dir = self.in_dir_tweets
        # Loading dataframes.
        news_df = pd.read_csv(news_source_path)
        tweets_df = pd.read_csv(tweets_source_dir)
        print("... done.")

        # For the news dataset.
        print("Pre-processing news...")
        # Dropping unnecessary columns.
        news_df = news_df.drop(['Show','Snippet','NOUN','ADJ','VERB','PROPN',
                                'SENT','SIZE','blob score', 'vader score'],1)
        # Defining query for generating the time series.
        query_news = """SELECT     year, month,
                      SUM(CASE WHEN `vader category`='pos' THEN 1 ELSE 0 END) AS pos_count,
                      SUM(CASE WHEN `vader category`='neg' THEN 1 ELSE 0 END) AS neg_count,
                      SUM(CASE WHEN `vader category`='neu' THEN 1 ELSE 0 END) AS neu_count
           FROM       news_df
           GROUP BY   year, month;"""
        # Applying query and getting results.
        result_news = ps.sqldf(query_news, locals())
        # Generating date index.
        result_news["date"] = pd.to_datetime(result_news['year'].astype(str) + "-" + result_news['month'].astype(str) + "-1", format='%Y-%m-%d')
        # Dropping month and year.
        result_news = result_news.drop(['year','month'],1)
        # Setting date as index.
        result_news = result_news.set_index('date')
        # We don't have full data for the first and last months: remove them.
        result_news = result_news.loc['2015-05-01':'2018-01-31']
        # Getting the column list.
        news_col_list = result_news.columns.tolist()
        print("... done.")

        # For the Tweets dataset.
        print("Pre-processing tweets...")
        # Dropping unnecessary columns.
        tweets_df = tweets_df.drop(['i','id','day','tweet','NOUN','ADJ','VERB',
                                   'PROPN','SENT','SIZE','blob score', 'vader score'],1)
        # Defining query for generating the time series.
        query_tweets = """SELECT     year, month,
                      SUM(CASE WHEN `vader category`='pos' THEN 1 ELSE 0 END) AS pos_count,
                      SUM(CASE WHEN `vader category`='neg' THEN 1 ELSE 0 END) AS neg_count,
                      SUM(CASE WHEN `vader category`='neu' THEN 1 ELSE 0 END) AS neu_count
           FROM       tweets_df
           GROUP BY   year, month;"""
        # Applying query and getting results.
        result_tweets = ps.sqldf(query_tweets, locals())
        # Generating date index.
        result_tweets["date"] = pd.to_datetime(result_tweets['year'].astype(str) + "-" + result_tweets['month'].astype(str) + "-1", format='%Y-%m-%d')
        # Dropping month and year.
        result_tweets = result_tweets.drop(['year','month'],1)
        # Setting date as index.
        result_tweets = result_tweets.set_index('date')
        # We don't have full data for the first and last months: remove them.
        result_tweets = result_tweets.loc['2015-05-01':'2018-01-31']
        # Getting the column list.
        tweets_col_list = result_tweets.columns.tolist()
        print("... done.")

        # Generating sentiment dataframes with news and tweets.
        pos_df = result_tweets[[tweets_col_list[0]]].join(result_news[[news_col_list[0]]],
                                                          lsuffix='_tweets',
                                                          rsuffix='_news')
        # Negative sentiment.
        neg_df = result_tweets[[tweets_col_list[1]]].join(result_news[[news_col_list[1]]],
                                                          lsuffix='_tweets',
                                                          rsuffix='_news')
        # Neutral sentiment.
        neu_df = result_tweets[[tweets_col_list[2]]].join(result_news[[news_col_list[2]]],
                                                          lsuffix='_tweets',
                                                          rsuffix='_news')
        # Returning readied dataframes.
        return pos_df, neg_df, neu_df

    # Method that checks for stationarity in the time series.For the news
    # time series, it does the ADF test. For the tweets dataset it performs the
    # Zivot-Andrews test to account for the potential structural break in this
    # time series. Assumes it receives the dataframes generated by the
    # load_datasets method; a dataframe with datetime index, a column for tweets
    # and a column of news, in that order.
    def check_stationarity(self, df):
        # Initializing flags.
        flag_news = False
        flag_tweets = False
        # Getting column list.
        col_list = df.columns.tolist()
        # Checking for tweets.
        result_tweets = zivot_andrews(df[col_list[0]])
        # Checking for news.
        result_news = adfuller(df[col_list[1]])

        # Displaying results.
        print("Result for news:")
        print("P-value: ", result_news[1])
        if(result_news[1]<=0.05):
            flag_news = True
            print("Stationary: True")
        else:
            print("Stationary: False")
        print("Result for tweets:")
        print("P-value: ", result_tweets[1])
        if(result_tweets[1]<=0.05):
            flag_tweets = True
            print("Stationary: True")
        else:
            print("Stationary: False")
        print("--------------------------------------")
        return flag_news, flag_tweets

    # Method to differentiate a time series to make it stationary. You may
    # need to call this method more than once until the stationary test
    # checks out. Performs the operation in the indicated column and adjusts
    # all the dataframe to eliminate NA values.
    def diff_df(self, df, col_name):
        # Generating an internal copy of the dataframe.
        df_trans = df.copy()
        # Differentiating.
        df_trans[col_name] = df_trans[col_name].diff()
        # Dropping rows with NA values from the dataframe.
        df_trans = df_trans.dropna()
        return df_trans

    # Method that searches for the best max lag value for the VAR model while
    # ensuring it stays in within a given margin of the Durbin-Watson ideal
    # test scores. Takes into account the AIC as information metric. It assumes
    # stationary data.
    def best_lag_dw(self, df, threshold=0.2):
        model = VAR(df, freq="MS")
        # Assumes stationary data.
        best_aic = 99999
        best_lag = None
        best_dw = None
        # Searching for best lag order.
        for i in range(1,16):
            result = model.fit(i)
            #print("Lag order: ", i, " AIC: ", result.aic)
            # Checking with Durbin-Watson test for autocorrelation as well.
            dw_out = durbin_watson(result.resid)
            #print("DW test: ", dw_out)
            #print(abs(2.0-dw_out[0]))
            if((result.aic < best_aic) and (abs(2.0-round(dw_out[0],2))<=threshold) and (abs(2.0-round(dw_out[1],2))<=threshold)):
                #print("ENTRA")
                best_aic = result.aic
                best_lag = i
                best_dw = dw_out
        print("Best lag order: ", best_lag, " with an AIC score of: ", best_aic)
        print("Durbin-Watson results:")
        for col, val in zip(df.columns, best_dw):
          print(col, ':', round(val, 2))
        print("-------------------------------------------------")
        return best_aic, best_lag, best_dw

    # Method that performs the Granger causality test.
    def grangers_causation_matrix(self, data, variables, maxlag, test='ssr_chi2test', verbose=False):
        # Obtaining the results matrix.
        df = pd.DataFrame(np.zeros((len(variables), len(variables))), columns=variables, index=variables)
        for c in df.columns:
            for r in df.index:
                test_result = grangercausalitytests(data[[r, c]], maxlag=maxlag, verbose=False)
                p_values = [round(test_result[i+1][0][test][1],4) for i in range(maxlag)]
                if verbose: print(f'Y = {r}, X = {c}, P Values = {p_values}')
                min_p_value = np.min(p_values)
                df.loc[r, c] = min_p_value
        df.columns = [var + '_x' for var in variables]
        df.index = [var + '_y' for var in variables]
        # Providing feedback.
        print("Granger causality test results: ")
        print(df)
        print("-------------------------------------------------")
        return df

    # Method to generate the N-lagged dataframe for cross-correlation.
    def df_derived_by_shift(self, df, lag=0, NON_DER=[]):
        df = df.copy()
        if not lag:
            return df
        cols ={}
        for i in range(1,lag+1):
            for x in list(df.columns):
                if x not in NON_DER:
                    if not x in cols:
                        cols[x] = ['{}_{}'.format(x, i)]
                    else:
                        cols[x].append('{}_{}'.format(x, i))
        for k,v in cols.items():
            columns = v
            dfn = pd.DataFrame(data=None, columns=columns, index=df.index)
            i = 1
            for c in columns:
                dfn[c] = df[k].shift(periods=i)
                i+=1
            df = pd.concat([df, dfn], axis=1)
        return df

    # Method to generate the N-lag Spearman cross-correlation, saving the
    # correlation matrices as SVG files. "n" refers to the number of lags.
    def n_lag_corr(self, df, filename, n=6):
        lag_df = self.df_derived_by_shift(df, n)
        corr_df = lag_df.corr(method='spearman')
        # Plotting and saving SVG file.
        plt.figure(figsize=(25,25))
        title = str(n) + " months"
        plt.title(title, y=1.05, size=16)
        mask = np.zeros_like(corr_df)
        mask[np.triu_indices_from(mask)] = True
        svm = sns.heatmap(corr_df, mask=mask, linewidths=0.1,vmax=1.0, vmin=-1.0,
                          square=True, cmap='coolwarm', linecolor='white', annot=True)
        img_path = self.out_dir + filename
        plt.savefig(img_path, bbox_inches='tight')


def validateLists(rules, d):

    for (key, value) in d.items():
        isInRules = False
        for rule in rules:
            if rule[0] == key:
                isInRules = True
        if isInRules == False:
            return False

    for (key, value) in d.items():
        for rule in rules:
            if rule[0] == key:
                if not value.startswith(rule[1]):
                    return False
                if rule[2] not in value:
                    return False
                if not value.endswith(rule[3]):
                    return False

    return True

print(validateLists({("key1", "", "inside", ""), ("key2", "start", "middle", "winter")}, {
    "key1": "come inside, it's too cold out", "key2": "start test middle in the winter"}))


from myhdl import block, Signal

from Hello2 import ClkDriver
from Hello1 import Hello

@block
def Greetings():

    clk1 = Signal(0)
    clk2 = Signal(0)

    clkdriver_1 = ClkDriver(clk1)
    clkdriver_2 = ClkDriver(clk=clk2, period=19)
    hello_1 = Hello(clk=clk1)
    hello_2 = Hello(to="MyHDL", clk=clk2)

    return clkdriver_1, hello_1, clkdriver_2, hello_2


# class Node:
#     def __init__(self, value, next = None) -> None:
#         self.value = value
#         self.next = next

# class LinkedList:
#     def __init__(self, head =None) -> None:
#         self.head = head

#     def append(self, value):
#         if self.head == None:
#             self.head=Node(value)

#         else:
#             current_node = self.head
#             while current_node.next is not None:
#                 current_node=current_node.next
#             current_node.next=Node(value)

#     def display(self):
#         current = self.head
#         while current is not None:
#             print(current.value)
#             current=current.next

#     def rerverse(self):
#         prev = None
#         current = self.head
#         while current is not None:
#             next = current.next
#             current.next = prev
#             prev=current
#             current = next
#         self.head=prev

# list1 = LinkedList()
# list1.append(1)
# list1.append(2)
# list1.append(3)
# list1.append(5)
# list1.rerverse()
# list1.display()

class Node:
    def __init__(self, value) -> None:
        self.value= value
        self.next = None

class LinkedList:
    def __init__(self) -> None:
        self.head=None
        self.size=0

    def append(self, value):
        if self.head is None:
            self.head = Node(value)
            self.size+=1
        else:
            current=self.head
            while current.next is not None:
                current = current.next
            current.next=Node(value)
            self.size+=1
    def __len__(self):
        return self.size

    def display(self):
        curr = self.head
        while curr is not None:
            print(curr.value,end="=>")
            curr=curr.next

    def reverse(self):
        prev=None
        curr=self.head
        while curr is not None:
            next= curr.next
            curr.next = prev
            prev= curr
            curr=next
        self.head=prev

    def insertAt(self, value, pos):
        if pos>self.size:
            raise IndexError('invalid position')

        #if user want to insert at first
        curr= self.head
        if pos==0:
            self.head=Node(value)
            self.head.next=curr
            self.size+=1
        #if user wants to insert at last
        elif pos==self.size:
            if self.head is None:
                self.head = Node(value)
                self.size+=1
            else:
                current=self.head
                while current.next is not None:
                    current = current.next
                current.next=Node(value)
                self.size+=1

        #if the insertion at anywhere in the middle
        else:
            curr=self.head
            currCount=0
            while currCount<pos-1:
                currCount+=1
                curr=curr.next
            temp=curr.next
            curr.next=Node(value)
            curr.next.next=temp
            self.size+=1
    def removeNthFromEnd(self, n: int):
        size=0
        curr=self.head
        while curr is not None:
            curr=curr.next
            size+=1

        rloc= size-n
        curr=self.head
        #if removal is at first
        if n==size:
            self.head=curr.next
        #if removal is at last
        elif n==1:
            prev=None
            while curr.next is not None:
                # print(curr.value)
                prev=curr
                curr=curr.next
            prev.next=None
        #removal is at the middle
        else:
            curr=self.head
            rloc=size-n
            pos=0
            prev=None
            while pos<rloc:
                prev=curr
                curr=curr.next
                pos+=1
            prev.next=curr.next

            # curr.next=curr.next.next
            # curr.value=None
            # curr.next=None

ll=LinkedList()
ll.append(1)
ll.append(2)
ll.append(3)
ll.append(4)
ll.append(5)

ll.removeNthFromEnd(2)
ll.display()


"""
dambreak 2-D
"""
from __future__ import division
from past.utils import old_div
import numpy as np
from proteus import (Domain, Context)
from proteus.Profiling import logEvent
from proteus.mprans.SpatialTools import Tank2D
from proteus.mprans import SpatialTools as st
import proteus.TwoPhaseFlow.TwoPhaseFlowProblem as TpFlow
from proteus.Gauges import PointGauges, LineIntegralGauges, LineGauges
import os

# *************************** #
# ***** GENERAL OPTIONS ***** #
# *************************** #
opts= Context.Options([
    ("final_time",3.0,"Final time for simulation"),
    ("dt_output",0.01,"Time interval to output solution"),
    ("cfl",0.25,"Desired CFL restriction"),
    ("he",0.01,"he relative to Length of domain in x"),
    ("refinement",3,"level of refinement"),
    ("adapt",0,"will adapt?")
    ])

# ****************** #
# ***** GAUGES ***** #
# ****************** #
height_gauges1 = LineGauges(gauges=((("phi",),
                                        (((2.724, 0.0, 0.0),
                                          (2.724, 1.8, 0.0)), # We consider this one in our paper
                                         ((2.228, 0.0, 0.0),
                                          (2.228, 1.8, 0.0)), # We consider this one in our paper
                                         ((1.732, 0.0, 0.0),
                                          (1.732, 1.8, 0.0)),
                                         ((0.582, 0.0, 0.0),
	                                  (0.582, 1.8, 0.0)))),),
                                        fileName="height1.csv")

height_gauges2 = LineGauges(gauges=((("phi",),
                                     (((0.0, 0.0, 0.0),
                                       (0.0, 0.0, -0.01)),
                                      ((0.0, 0.0, 0.0),
                                        (3.22, 0.0, 0.0)))),),
                            fileName="height2.csv")

pressure_gauges = PointGauges(gauges=((('p',),
                                      ((3.22, 0.16, 0.0), #P1
                                       (3.22, 0.584, 0.0), #P3
                                       (3.22, 0.12, 0.0))),), # This is the one considered in our paper
                                       fileName="pressure.csv")

# *************************** #
# ***** DOMAIN AND MESH ***** #
# ****************** #******* #
tank_dim = (3.22,1.8)
refinement = opts.refinement
structured=False
if structured:
    nny = 5*(2**refinement)+1
    nnx = 2*(nnx-1)+1
    domain = Domain.RectangularDomain(tank_dim)
    boundaryTags = domain.boundaryTags
    triangleFlag=1
else:
    nnx = nny = None
    domain = Domain.PlanarStraightLineGraphDomain()

he = tank_dim[0]*opts.he

domain = Domain.PUMIDomain(dim=2) #initialize the domain
#read the geometry and mesh
from proteus import MeshTools
parallelPartitioningType = MeshTools.MeshParallelPartitioningTypes.element
domain.MeshOptions.setParallelPartitioningType('element')
domain.AdaptManager.PUMIAdapter.loadModelAndMesh(b"Reconstructed.dmg", b"Reconstructed.smb")
domain.AdaptManager.modelDict = {'flow':0,'phase':1}
domain.AdaptManager.sizeInputs = [b'pseudo']
domain.AdaptManager.adapt = opts.adapt
domain.AdaptManager.hmax = he*4.0
domain.AdaptManager.hmin= he/2.0
domain.AdaptManager.hphi= he/2.0
domain.AdaptManager.numAdaptSteps= 10
domain.AdaptManager.numIterations= 5
domain.AdaptManager.targetError= 0.2
domain.AdaptManager.gradingFactor= 1.5
domain.AdaptManager.logging= 0

# ----- TANK ----- #
tank = Tank2D(domain, tank_dim)

# ----- EXTRA BOUNDARY CONDITIONS ----- #
tank.BC['y+'].setAtmosphere()
tank.BC['y-'].setFreeSlip()
tank.BC['x+'].setFreeSlip()
tank.BC['x-'].setFreeSlip()

he = tank_dim[0]*opts.he
domain.MeshOptions.he = he
st.assembleDomain(domain)
domain.MeshOptions.triangleOptions = "VApq30Dena%8.8f" % (old_div((he ** 2), 2.0),)
domain.polyfile=os.path.dirname(os.path.abspath(__file__))+"/"+"meshDambreak"
domain.MeshOptions.genMesh=False

#domain.writePoly("meshDambreak")

# ****************************** #
# ***** INITIAL CONDITIONS ***** #
# ****************************** #
class zero(object):
    def uOfXT(self,x,t):
        return 0.0

waterLine_y = 0.6
waterLine_x = 1.2
class clsvof_init_cond(object):
    def uOfXT(self,x,t):
        if x[0] < waterLine_x and x[1] < waterLine_y:
            return -1.0
        elif x[0] > waterLine_x or x[1] > waterLine_y:
            return 1.0
        else:
            return 0.0

############################################
# ***** Create myTwoPhaseFlowProblem ***** #
############################################
boundaryConditions = {
    # DIRICHLET BCs #
    'pressure_DBC': lambda x, flag: domain.bc[flag].p_dirichlet.init_cython(),
    'pressure_increment_DBC': lambda x, flag: domain.bc[flag].pInc_dirichlet.init_cython(),
    'vel_u_DBC': lambda x, flag: domain.bc[flag].u_dirichlet.init_cython(),
    'vel_v_DBC': lambda x, flag: domain.bc[flag].v_dirichlet.init_cython(),
    'vel_w_DBC': lambda x, flag: domain.bc[flag].w_dirichlet.init_cython(),
    'clsvof_DBC': lambda x, flag: domain.bc[flag].vof_dirichlet.init_cython(),
    # ADVECTIVE FLUX BCs #
    'pressure_AFBC': lambda x, flag: domain.bc[flag].p_advective.init_cython(),
    'pressure_increment_AFBC': lambda x, flag: domain.bc[flag].pInc_advective.init_cython(),
    'vel_u_AFBC': lambda x, flag: domain.bc[flag].u_advective.init_cython(),
    'vel_v_AFBC': lambda x, flag: domain.bc[flag].v_advective.init_cython(),
    'vel_w_AFBC': lambda x, flag: domain.bc[flag].w_advective.init_cython(),
    'clsvof_AFBC': lambda x, flag: domain.bc[flag].vof_advective.init_cython(),
    # DIFFUSIVE FLUX BCs #
    'pressure_increment_DFBC': lambda x, flag: domain.bc[flag].pInc_diffusive.init_cython(),
    'vel_u_DFBC': lambda x, flag: domain.bc[flag].u_diffusive.init_cython(),
    'vel_v_DFBC': lambda x, flag: domain.bc[flag].v_diffusive.init_cython(),
    'vel_w_DFBC': lambda x, flag: domain.bc[flag].w_diffusive.init_cython(),
    'clsvof_DFBC': lambda x, flag: None}

myTpFlowProblem = TpFlow.TwoPhaseFlowProblem()
myTpFlowProblem.domain=domain

myTpFlowProblem.outputStepping.final_time = opts.final_time
myTpFlowProblem.outputStepping.dt_output = opts.dt_output
myTpFlowProblem.outputStepping.systemStepExact = True

myTpFlowProblem.SystemPhysics.setDefaults()
myTpFlowProblem.SystemPhysics.useDefaultModels(flowModel=0,interfaceModel=1)

myTpFlowProblem.SystemPhysics.modelDict['flow'].p.initialConditions['p'] = zero()
myTpFlowProblem.SystemPhysics.modelDict['flow'].p.initialConditions['u']=zero()
myTpFlowProblem.SystemPhysics.modelDict['flow'].p.initialConditions['v']=zero()
myTpFlowProblem.SystemPhysics.modelDict['clsvof'].p.initialConditions['clsvof'] = clsvof_init_cond()
#myTpFlowProblem.SystemPhysics.modelDict['pressure'].p.initialConditions['p'] = zero()
#myTpFlowProblem.SystemPhysics.modelDict['pressureInc'].p.initialConditions['pInc'] = zero()
#myTpFlowProblem.SystemPhysics.modelDict['pressureInit'].p.initialConditions['pInit'] = zero()

myTpFlowProblem.SystemNumerics.cfl=opts.cfl
myTpFlowProblem.SystemNumerics.useSuperlu=True

myTpFlowProblem.SystemPhysics.g = np.array([0.0,-9.8,0.0])
m = myTpFlowProblem.SystemPhysics.modelDict
m['clsvof'].p.coefficients.disc_ICs = True
m['clsvof'].auxiliaryVariables = [height_gauges1, height_gauges2]
m['flow'].auxiliaryVariables = [pressure_gauges]
m['flow'].n.ShockCapturingOptions.shockCapturingFactor = 0.0
m['clsvof'].n.ShockCapturingOptions.shockCapturingFactor = 0.0

#adaptivity currently relies on element-based partitioning which will not work with conservativeFlux right now
m['flow'].n.conservativeFlux= None


import io
import shutil
import sys

from io import StringIO
from pathlib import Path
from typing import Generator
from unittest import mock

import pytest

from pytest import MonkeyPatch

from socon.utils import terminal
from socon.utils.terminal import TerminalWriter, colorize

# This code was initially copied from pytest 7.2, file src/_pytest/terminal.py.
# Link to the project: https://github.com/pytest-dev/pytest

def test_terminal_width_COLUMNS(monkeypatch: MonkeyPatch) -> None:
    monkeypatch.setenv("COLUMNS", "42")
    assert terminal.get_terminal_width() == 42
    monkeypatch.delenv("COLUMNS", raising=False)

def test_terminalwriter_width_bogus(monkeypatch: MonkeyPatch) -> None:
    monkeypatch.setattr(shutil, "get_terminal_size", mock.Mock(return_value=(10, 10)))
    monkeypatch.delenv("COLUMNS", raising=False)
    tw = terminal.TerminalWriter()
    assert tw.fullwidth == 80

def test_terminalwriter_computes_width(monkeypatch: MonkeyPatch) -> None:
    monkeypatch.setattr(terminal, "get_terminal_width", lambda: 42)
    tw = terminal.TerminalWriter()
    assert tw.fullwidth == 42

def test_terminalwriter_not_unicode() -> None:
    """If the file doesn't support Unicode, the string is unicode-escaped (#7475)."""
    buffer = io.BytesIO()
    file = io.TextIOWrapper(buffer, encoding="cp1252")
    tw = terminal.TerminalWriter(file)
    tw.write("hello 🌀 wôrld אבג", flush=True)
    assert buffer.getvalue() == rb"hello \U0001f300 w\xf4rld \u05d0\u05d1\u05d2"

win32 = int(sys.platform == "win32")

class TerminalWriterTests:
    @pytest.fixture(params=["path", "stringio"])
    def tw(self, request, test_dir: Path) -> Generator[TerminalWriter, None, None]:
        if request.param == "path":
            p = test_dir.joinpath("tmpfile")
            f = open(str(p), "w+", encoding="utf8")
            tw = TerminalWriter(f)

            def getlines():
                f.flush()
                with open(str(p), encoding="utf8") as fp:
                    return fp.readlines()

        elif request.param == "stringio":
            f = StringIO()
            tw = TerminalWriter(f)

            def getlines():
                f.seek(0)
                return f.readlines()

        tw.getlines = getlines  # type: ignore
        tw.getvalue = lambda: "".join(getlines())  # type: ignore

        with f:
            yield tw

    def test_line(self, tw) -> None:
        tw.line("hello")
        lines = tw.getlines()
        assert len(lines) == 1
        assert lines[0] == "hello\n"

    def test_line_unicode(self, tw) -> None:
        msg = "b\u00f6y"
        tw.line(msg)
        lines = tw.getlines()
        assert lines[0] == msg + "\n"

    def test_sep_no_title(self, tw) -> None:
        tw.sep("-", fullwidth=60)
        lines = tw.getlines()
        assert len(lines) == 1
        assert lines[0] == "-" * (60 - win32) + "\n"

    def test_sep_with_title(self, tw) -> None:
        tw.sep("-", "hello", fullwidth=60)
        lines = tw.getlines()
        assert len(lines) == 1
        assert lines[0] == "-" * 26 + " hello " + "-" * (27 - win32) + "\n"

    @mock.patch("sys.platform", "linux")
    def test_sep_not_win32_terminal(self, tw):
        tw.sep("-", "hello", fullwidth=60)
        lines = tw.getlines()
        assert len(lines) == 1
        assert lines[0] == "-" * 26 + " hello " + "-" * (27) + "\n"

    def test_sep_longer_than_width(self, tw) -> None:
        tw.sep("-", "a" * 10, fullwidth=5)
        (line,) = tw.getlines()
        # even though the string is wider than the line, still have a separator
        assert line == "- aaaaaaaaaa -\n"

    @pytest.mark.parametrize(
        "newline, index",
        [
            (
                "before",
                [
                    (
                        0,
                        None,
                    ),
                    1,
                ],
            ),
            (
                "after",
                [
                    (
                        None,
                        1,
                    ),
                    0,
                ],
            ),
            (
                "both",
                [
                    (
                        0,
                        2,
                    ),
                    1,
                ],
            ),
        ],
        ids=["before", "after", "both"],
    )
    def test_sep_with_newline(self, tw, newline, index) -> None:
        # Test before
        tw.sep("-", "hello", fullwidth=60, newline=newline)
        lines = tw.getlines()
        before = index[0][0]
        after = index[0][1]
        if before:
            assert lines[before] == "\n"
        assert lines[0 + index[1]] == "-" * 26 + " hello " + "-" * (27 - win32) + "\n"
        if after:
            assert lines[after] == "\n"

    def test_rewrite_with_erase(self) -> None:
        f = StringIO()
        tr = TerminalWriter(f)
        tr.fullwidth = 10
        tr.write("hello")
        tr.rewrite("hey", erase=True)
        assert f.getvalue() == "hello" + "\r" + "hey" + (6 * " ")

    def test_rewrite_no_erase(self) -> None:
        f = StringIO()
        tr = TerminalWriter(f)
        tr.fullwidth = 10
        tr.write("hello")
        tr.rewrite("hey")
        assert f.getvalue() == "hello\rhey"

    def test_attr_fullwidth(self, tw) -> None:
        tw.sep("-", "hello", fullwidth=70)
        tw.fullwidth = 70
        tw.sep("-", "hello")
        lines = tw.getlines()
        assert len(lines[0]) == len(lines[1])

    def test_write_no_msg(self, tw) -> None:
        f = StringIO()
        tr = TerminalWriter(f)
        tr.write("")
        assert f.getvalue() == ""

class TerminalColorTests:
    @pytest.fixture()
    def tw(self):
        f = StringIO()
        tw = TerminalWriter(f)

        def getlines():
            f.seek(0)
            return f.readlines()

        tw.getlines = getlines  # type: ignore
        tw.getvalue = lambda: "".join(getlines())  # type: ignore

        with f:
            yield tw

    def test_colorize_empty_msg(self):
        assert colorize(msg=None) == ""
        assert colorize(msg="") == ""

        assert colorize(msg=None, opts=("noreset",)) == "\x1b[m"
        assert colorize(msg="", opts=("noreset",)) == "\x1b[m"

    def test_colorize_reset(self):
        assert colorize(msg="", opts=("reset",)) == "\x1b[0m"

    def test_colorize_fg_bg(self):
        assert colorize(msg="Test", fg="red") == "\x1b[31mTest\x1b[0m"
        assert colorize(msg="Test", bg="red") == "\x1b[41mTest\x1b[0m"
        # Ignored kwarg.
        assert colorize(msg="Test") == "Test"

    def test_colorize_opts(self):
        assert (
            colorize(msg="Test", opts=("bold", "underscore")) == "\x1b[1;4mTest\x1b[0m"
        )
        assert colorize(msg="Test", opts=("blink",)) == "\x1b[5mTest\x1b[0m"
        # Ignored opts.
        assert colorize(msg="Test", opts=("not_an_option",)) == "\x1b[mTest\x1b[0m"

    def test_terminal_markup_on_write(self, tw):
        tw.write("Test", fg="red")
        assert tw.getvalue() == "\x1b[31mTest\x1b[0m"

    def test_terminal_markup_on_line(self, tw):
        tw.line("Test", fg="red")
        assert tw.getvalue() == "\x1b[31mTest\x1b[0m\n"


n = int(input())  # 가지고 있는 카드의 개수
cards = list(map(int, input().split()))
cards.sort()
cardsDic = {}  # 키-밸류
for c in cards:
    if c not in cardsDic:
        cardsDic[c] = 1  # 초기엔 1
    else:
        cardsDic[c] += 1  # 딕셔너리에 존재하는 키일 경우 1씩 더해주기

m = int(input())
search = list(map(int, input().split()))

for i in search:
    start = 0
    end = n-1

    while start <= end:
        mid = (start+end)//2
        if cards[mid] == i:
            break
        if cards[mid] > i:
            end = mid - 1
        else:
            start = mid + 1
    if cards[mid] == i:
        print(cardsDic[i], end=' ')
    else:
        print(0, end=' ')

'''
def binarySearch(array, target, start, end):
    if start > end:
        return None
    mid = (start+end) // 2
    if array[mid] == target:
        return array[start:end+1].count(target)
    elif array[mid] > target:
        return binarySearch(array, target, start, mid-1)
    else:
        return binarySearch(array, target, mid+1, end)

for i in range(m):
    result = binarySearch(search, i, 0, n-1)
    if result != None:
        print(result, end=' ')
    else:
        print(0, end=' ')
'''


#!/usr/bin/env python

from pylab import *
import numpy
import time
import os

figure()

while True:
    os.system("grep Mean /tmp/testcase2.log | awk '{print $3}' > /tmp/testcase.nums")

    els = numpy.fromfile('/tmp/testcase.nums', sep="\n");
    clf()
    timevals = transpose(range(len(els)))
    plot(timevals / 6.0, els/1000) # 10s intervals
    xlabel('time - min')
    ylabel('elapsed command-response (ms)')
    draw()

    savefig('/tmp/plot-fig.png', format='png')

    time.sleep(5)


import numpy as np
import cv2

cap = cv2.VideoCapture(1)

while(True):
    # Capture frame-by-frame
    ret, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Initiate FAST object with default values
    fast = cv2.FastFeatureDetector_create(50)

    # find and draw the keypoints
    kp = fast.detect(gray,None)
    img2 = img.copy()
    cv2.drawKeypoints(img, kp, img2, color=(255,0,0))
    cv2.imshow('keypoints',img2)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()


import os
import sys
import unittest
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import detektor

import test_helpers

class TestDetektorCompare(unittest.TestCase):
    def setUp(self):
        self.a1 = test_helpers.Assignment('test/pyfiles/helloworldplus.py')
        self.a2 = test_helpers.Assignment('test/pyfiles/helloworldplus2.py')
        self.assignments = [self.a1, self.a2]
        detektor.set_detektor_signature('python', self.assignments, 'fileclass.filepath')

    def test_compare_2_equal_files(self):
        detektor.compare(self.assignments)
        self.assertTrue(hasattr(self.a1, 'detektor_signature'))

    def test_compare_but_sending_empty_list(self):
        res = detektor.compare([])
        self.assertTrue(type(res) == list)
        self.assertEqual(len(res), 0)

    def test_compare_3_equal_files(self):
        a3 = test_helpers.Assignment('test/pyfiles/helloworldplus3.py')
        self.assignments.append(a3)
        detektor.set_detektor_signature('python', self.assignments, 'fileclass.filepath')
        res = detektor.compare(self.assignments)
        self.assertEqual(len(res), 3)

    def test_compare_4_equal_files(self):
        a3 = test_helpers.Assignment('test/pyfiles/helloworldplus3.py')
        self.assignments.append(a3)
        a4 = test_helpers.Assignment('test/pyfiles/helloworldplus4.py')
        self.assignments.append(a4)
        detektor.set_detektor_signature('python', self.assignments, 'fileclass.filepath')
        res = detektor.compare(self.assignments)
        self.assertEqual(len(res), 6)


import torch.nn as nn

class HybridModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.out_features = 256
        self.conv = nn.Sequential(
            nn.Conv1d(4, 256, 20),
            nn.ReLU(),
            nn.MaxPool1d(15),
            nn.Dropout(0.5),
        )
        self.rnn = nn.LSTM(256, hidden_size=128, bidirectional=True, batch_first=True)

    def forward(self, x):
        x = x.transpose(2, 1)
        x = self.conv(x)
        x = x.transpose(2, 1)
        output, (h_n, c_n) = self.rnn(x)
        x = h_n.transpose(0, 1)
        return x.reshape(x.shape[0], -1)

def hybrid(*args, **kwargs):
    return HybridModel(*args, **kwargs)


import json
from os import getcwd, mkdir
from os.path import exists

class FileHelper:
    def __init__(self, filename: str = False, directory: str = False):

        root = getcwd()

        if not directory:
            directory = f"{root}//datasets//"

        if not filename:
            filename = "output.json"

        self.filename = filename
        self.directory = directory

    def write(self, content: str):
        if not exists(self.directory):
            mkdir(self.directory)

        with open(self.directory + self.filename, 'a') as file:
            file.write(content)


#!/usr/bin/env python3

import os
import sys

import numpy as np
import pandas as pd

np.set_printoptions(edgeitems=3)
np.core.arrayprint._line_width = 80

fname = "res/output_360_merged_2.50.vcf.gz_summary.bin"
# fname = "res/output_360_merged_2.50.vcf.gz_chromosomes.bin"

def readIbrowserBinary(infile):
    dt0 = np.dtype([
        ('hasData'    , bool    ),
        ('serial'     , np.int64),
        ('counterBits', np.int64),
        ('dataLen'    , np.int64),
        ('sumData'    , np.uint64)
    ])

    fileSize = os.stat(infile).st_size

    with open(infile, 'rb') as fhd:
        d = np.fromfile(fhd, dtype=dt0, count=1)[0]

        counterBits = d["counterBits"]
        dataLen = d["dataLen"]

        dataFmt = None
        dataFmtLen = None

        if counterBits == 16:
            dataFmt = np.uint16
            dataFmtLen = 2
        elif counterBits == 32:
            dataFmt = np.uint32
            dataFmtLen = 4
        elif counterBits == 64:
            dataFmt = np.uint64
            dataFmtLen = 8
        else:
            print("unknown counter bits", counterBits)
            sys.exit(1)

        dataSize     = dataLen * dataFmtLen
        registerSize = 1 + 8 + 8 + 8 + 8 + dataSize

        dt = np.dtype([
            ('hasData'    , bool     ), #1  1
            ('serial'     , np.int64 ), #8  9
            ('counterBits', np.int64 ), #8 17
            ('dataLen'    , np.int64 ), #8 25
            ('sumData'    , np.uint64), #8 33
            ('data', dataFmt, dataLen)
        ])

        assert (fileSize % registerSize) == 0, "wrong file size: fileSize {} % registerSize {} != 0. {}".format(fileSize, registerSize, fileSize % registerSize)

        numRegisters = int(fileSize / registerSize) - 1

    memmap = np.memmap(infile, dtype=dt, mode='r')

    return numRegisters, memmap

def registerToDataframe(regs):
    matrix = None

    for reg in regs:
        if matrix is None:
            matrix = pd.DataFrame({reg['serial']: reg['data']}, copy=False)
        else:
            matrix[reg['serial']] = reg['data']

    return matrix

if __name__ == "__main__":
    print("memmap")

    numRegisters, memmap = readIbrowserBinary(fname)

    # for i in range(numRegisters):
    #     reg = memmap[i]
    #     # print(str(reg)[:50])
    #     # print("  ", reg['data'][:10])
    #     print(".", end="")
    #     if ((i+1) % 100) == 0:
    #         print(" ", i+1)
    # print()

    # df = registerToDataframe(memmap[1:5])

    # print(df)

    # pd.DataFrame(memmap)

    matrix = pd.DataFrame({reg['serial']: reg['data'] for reg in memmap}, copy=False)

    print(matrix)


import math
from tkinter import*

root = Tk()
pin = DoubleVar()
spl = DoubleVar()
nf = DoubleVar()
span = DoubleVar()
osnr = StringVar()
def calc_osnr():
    k = 58 + pin.get() - spl.get() - nf.get() - math.log10(span.get())
    osnr.set(f"OSNR is: {round(k,2)} dB")
window = root.geometry("400x400")
Label(root, text="OSNR calculation application", font="calibri 15").pack()
Label(root, text="Enter I/P dBm").pack(pady=3)
Entry(root, textvariable=pin).pack(pady=3)
Label(root, text="Enter Span Loss dB").pack(pady=3)
Entry(root, textvariable=spl).pack(pady=3)
Label(root, text="Enter Noise figure dB").pack(pady=3)
Entry(root, textvariable=nf).pack(pady=3)
Label(root, text="Enter Number of Span").pack(pady=3)
Entry(root, textvariable=span).pack(pady=3)

Button(root, text="Calculate OSNR", command=calc_osnr).pack(pady=7)
Entry(root, textvariable=osnr).pack(pady=3)
root.mainloop()


flower_kind = input()
qty_flowers = int(input())
budget = int(input())

price = 0

if flower_kind == "Roses":
    price = 5
    if qty_flowers > 80:
        price *= 0.9
elif flower_kind == "Dahlias":
    price = 3.8
    if qty_flowers > 90:
        price *= 0.85
elif flower_kind == "Tulips":
    price = 2.80
    if qty_flowers > 80:
        price *= 0.85
elif flower_kind == "Narcissus":
    price = 3
    if qty_flowers < 120:
        price *= 1.15
elif flower_kind == "Gladiolus":
    price = 2.5
    if qty_flowers < 80:
        price *= 1.20

end_price = qty_flowers * price
result = abs(budget - end_price)
if budget >= end_price:
    print(f"Hey, you have a great garden with {qty_flowers} {flower_kind} and {result:.2f} leva left.")
elif budget < end_price:
    print(f"Not enough money, you need {result:.2f} leva more.")