from unittest import TestCase, main
from project.library import Library

class LibraryTest(TestCase):
    def setUp(self) -> None:
        self.library = Library('Gosho')

    def test_init_creates_all_attributes(self):
        self.assertEqual('Gosho', self.library.name)
        self.assertEqual({}, self.library.books_by_authors)
        self.assertEqual({}, self.library.readers)

    def test_name_empty_string(self):
        with self.assertRaises(ValueError) as ex:
            library = Library('')

        expected_result = "Name cannot be empty string!"
        self.assertEqual(expected_result, str(ex.exception))

    def test_add_book(self):
        self.library.add_book('Gosho', 'Title1')
        self.library.add_book('Gosho', 'Title2')

        self.assertEqual(1, len(self.library.books_by_authors))
        self.assertTrue('Gosho', self.library.books_by_authors)
        self.assertEqual(['Title1', 'Title2'], self.library.books_by_authors['Gosho'])

    def test_add_readers(self):
        self.library.add_reader('Pesho')

        self.assertEqual(1, len(self.library.readers))
        self.assertTrue('Pesho' in self.library.readers)
        self.assertEqual([], self.library.readers['Pesho'])

    def test_add_readers_should_throw_an_error(self):
        self.library.add_reader('Pesho')
        result = self.library.add_reader('Pesho')
        expected_result = f"Pesho is already registered in the {self.library.name} library."

        self.assertEqual(expected_result, result)

    def test_rent_book_reader_name_not_in_readers(self):
        reader_name = 'Pesho'
        book_author = 'Goshka'
        book_title = 'Title'
        result = self.library.rent_book(reader_name, book_author, book_title)
        expected_result = f"{reader_name} is not registered in the {self.library.name} Library."

        self.assertEqual(expected_result, result)

    def test_rent_book_author_not_in_library(self):
        reader_name = 'Pesho'
        book_author = 'Goshka'
        book_title = 'Title'
        self.library.add_reader(reader_name)

        result = self.library.rent_book(reader_name, book_author, book_title)
        expected_result = f"{self.library.name} Library does not have any {book_author}'s books."

        self.assertEqual(expected_result, result)

    def test_rent_book_title_not_in_library(self):
        reader_name = 'Pesho'
        book_author = 'Goshka'
        book_title = 'Title'
        self.library.add_reader(reader_name)
        self.library.add_book(book_author, 'Title1')

        result = self.library.rent_book(reader_name, book_author, book_title)
        expected_result = f"""{self.library.name} Library does not have {book_author}'s "{book_title}"."""
        self.assertEqual(expected_result, result)

    def test_rent_book(self):
        reader_name = 'Pesho'
        book_author = 'Goshka'
        book_title = 'Title'
        book_title2 = 'Title2'

        self.library.add_reader(reader_name)
        self.library.add_book(book_author, book_title)
        self.library.add_book(book_author, book_title2)
        self.library.rent_book(reader_name, book_author, book_title)

        self.assertEqual([{book_author: book_title}], self.library.readers[reader_name])
        self.assertEqual(1, len(self.library.books_by_authors[book_author]))
        self.assertTrue(book_title not in self.library.books_by_authors[book_author])
        self.assertTrue(book_title2 in self.library.books_by_authors[book_author])

if __name__ == '__main__':
    main()


import os
import sys
import math
import pickle
import textstat
import tldextract
import numpy as np
import pandas as pd
from collections import defaultdict

import gibberish_train
import markov_generater
import ngram_freq_generater

# Information Entropy
def cal_entropy(data):
    if not data:
        return 0
    valid_chars = set(data)

    entropy = 0
    for x in valid_chars:
        p_x = float(data.count(x)) / len(data)
        if p_x > 0:
            entropy += - p_x * math.log(p_x, 2)

    return entropy

# Readability
def cal_readability(data):
    score = textstat.flesch_reading_ease(data)
    return score

# Ratio of vowel characters
def cal_vowels(data):
    vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']

    vowel_count = 0
    total_chars = 0

    for char in data:
        if char.isalpha():
            total_chars += 1
            if char in vowels:
                vowel_count += 1

    if total_chars > 0:
        vowel_ratio = vowel_count / total_chars
        return vowel_ratio
    else:
        return 0.0

# Gibberish probability
def load_gib_model(data_path):
    model_path = 'Outputs/Gibberish/gib_model.pickle'

    if not os.path.exists(model_path):
        gibberish_train.train(data_path)

    model = pickle.load(open(model_path, 'rb'))
    model_mat = model['mat']
    return model_mat

def cal_gibberish(data, model_mat):
    return gibberish_train.avg_transition_prob(data, model_mat)

# Ratio of numbers
def cal_numbers(data):
    numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

    number_count = 0
    for char in data:
        if char in numbers:
            number_count += 1

    number_ratio = number_count / len(data)
    return number_ratio

# Ratio of characters
def cal_characters(data):
    character_count = 0
    for char in data:
        if char.isalpha():
            character_count += 1

    character_ratio = character_count / len(data)
    return character_ratio

# Ratio of repeated characters
def cal_repeated_characters(data):
    char_count = {}

    for char in data:
        if char in char_count:
            char_count[char] += 1
        else:
            char_count[char] = 1

    repeated_char_count = sum(1 for count in char_count.values() if count > 1)
    repeated_char_ratio = repeated_char_count / len(data)
    return repeated_char_ratio

# Ratio of consecutive characters
def cal_consecutive_characters(data):
    consecutive_count = 0

    for i in range(len(data) - 1):
        if data[i] == data[i + 1] or data[i].lower() == data[i + 1].lower():
            consecutive_count += 1

    total_pairs = len(data) - 1
    if total_pairs > 0:
        consecutive_ratio = consecutive_count / total_pairs
        return consecutive_ratio
    else:
        return 0.0

# Ratio of consecutive consonants
def is_consonant(char):
    consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w','x', 'y', 'z']
    return char in consonants

def cal_consecutive_consonants(data):
    consecutive_consonants_count = 0

    for i in range(len(data) - 1):
        if is_consonant(data[i]) and is_consonant(data[i + 1]):
            consecutive_consonants_count += 1

    total_pairs = len(data) - 1
    if total_pairs > 0:
        consecutive_consonants_ratio = consecutive_consonants_count / total_pairs
        return consecutive_consonants_ratio
    else:
        return 0.0

# N-gram rank stats
def load_ngram_rank_file(data_path):
    ngram_rank_file_path = "Datasets/Words/N-gram/ngram-rank-freq.txt"
    if not os.path.exists(ngram_rank_file_path):
        ngram_freq_generater.train(data_path)

    ngram_rank_file = open(ngram_rank_file_path, 'r')
    ngram_rank_dict = dict()
    for i in ngram_rank_file:
        _, gram, _, rank = i.strip().split(',')
        ngram_rank_dict[gram] = int(rank)
    ngram_rank_file.close()
    return ngram_rank_dict

def ave(array_):
    if len(array_) > 0:
        return array_.mean()
    else:
        return 0

def std(array_):
    if len(array_) > 0:
        return array_.std()
    else:
        return 0

def cal_ngam_rank_stats(data, ngram_rank_dict):
    extract = tldextract.TLDExtract(include_psl_private_domains=True)
    ext = extract(data)

    main_domain = '$' + ext.domain + '$'
    unigram_rank_main = np.array([ngram_rank_dict[i] if i in ngram_rank_dict else 0 for i in main_domain[1:-1]])
    bigram_rank_main = np.array([ngram_rank_dict[''.join(i)] if ''.join(i) in ngram_rank_dict else 0 for i in ngram_freq_generater.bigrams(main_domain)])
    trigram_rank_main = np.array([ngram_rank_dict[''.join(i)] if ''.join(i) in ngram_rank_dict else 0 for i in ngram_freq_generater.trigrams(main_domain)])

    tld = ext.suffix
    tld_split = tld.split('.')
    if len(tld_split) > 1:
        tld = tld_split[-1]
        tld_domain = '$' + tld_split[-2] + '$'
        unigram_rank_tld = np.array([ngram_rank_dict[i] if i in ngram_rank_dict else 0 for i in tld_domain[1:-1]])
        bigram_rank_tld = np.array([ngram_rank_dict[''.join(i)] if ''.join(i) in ngram_rank_dict else 0 for i in ngram_freq_generater.bigrams(tld_domain)])
        trigram_rank_tld = np.array([ngram_rank_dict[''.join(i)] if ''.join(i) in ngram_rank_dict else 0 for i in ngram_freq_generater.trigrams(tld_domain)])

        unigram_rank = np.concatenate((unigram_rank_main, unigram_rank_tld))
        bigram_rank = np.concatenate((bigram_rank_main, bigram_rank_tld))
        trigram_rank = np.concatenate((trigram_rank_main, trigram_rank_tld))
    else:
        unigram_rank = unigram_rank_main
        bigram_rank = bigram_rank_main
        trigram_rank = trigram_rank_main

    subdomain = ext.subdomain
    subdomain_split = subdomain.split('.')
    if len(subdomain_split) > 0:
        for string in subdomain_split:
            string = '$' + string + '$'
            unigram_rank_sub = np.array([ngram_rank_dict[i] if i in ngram_rank_dict else 0 for i in string[1:-1]])
            bigram_rank_sub = np.array([ngram_rank_dict[''.join(i)] if ''.join(i) in ngram_rank_dict else 0 for i in ngram_freq_generater.bigrams(string)])
            trigram_rank_sub = np.array([ngram_rank_dict[''.join(i)] if ''.join(i) in ngram_rank_dict else 0 for i in ngram_freq_generater.trigrams(string)])

            unigram_rank = np.concatenate((unigram_rank, unigram_rank_sub))
            bigram_rank = np.concatenate((bigram_rank, bigram_rank_sub))
            trigram_rank = np.concatenate((trigram_rank, trigram_rank_sub))

    unigram_rank_ave = ave(unigram_rank)
    unigram_rank_std = std(unigram_rank)

    bigram_rank_ave = ave(bigram_rank)
    bigram_rank_std = std(bigram_rank)

    trigram_rank_ave = ave(trigram_rank)
    trigram_rank_std = std(trigram_rank)

    return unigram_rank_ave, unigram_rank_std, bigram_rank_ave, bigram_rank_std, trigram_rank_ave, trigram_rank_std

# Markov chain
def load_trans_matrix(data_path, n):
    trans_matrix_path = f"Outputs/Markov/trans_matrix_{n}.csv"
    if not os.path.exists(trans_matrix_path):
        markov_generater.train(data_path, n)

    transitions = defaultdict(lambda: defaultdict(float))
    f_trans = open(trans_matrix_path, 'r')
    for f in f_trans:
        key1, key2, value = f.rstrip().split('\t') # key1 can be '' so rstrip() only
        value = float(value)
        transitions[key1][key2] = value
    f_trans.close()
    return transitions

def cal_markov_probs(data, transitions, n):
    if n == 2:
        ngram = [''.join((i, j)) for i, j in ngram_freq_generater.bigrams(data) if not i == None]
    elif n == 3:
        ngram = [''.join((i, j, k)) for i, j, k in ngram_freq_generater.trigrams(data) if not i == None]
    else:
        print("N-length should be 2 or 3.")
        sys.exit(0)

    prob = transitions[''][ngram[0]]
    for x in range(len(ngram) - 1):
        next_step = transitions[ngram[x]][ngram[x + 1]]
        prob *= next_step

    return prob

# Length of domain
def cal_length(data):
    return len(data)

# TLD rank
def load_tld_rank_file(data_path):
    default_path = "Outputs/TLD-Rank/tld_top_rank.csv"
    if os.path.exists(default_path):
        tld_top_rank_df = pd.read_csv(default_path)
    else:
        tld_top_rank_df = pd.DataFrame()
        tld_rank_df = pd.read_csv(data_path, header=None)
        for _, row in tld_rank_df.iterrows():
            if len(row[1].strip().split('.')) == 1:
                temp = pd.DataFrame(
                    {
                        'rank': row[0],
                        'tld': row[1]
                    },
                    index = [tld_top_rank_df.size]
                )
                tld_top_rank_df = pd.concat([tld_top_rank_df, temp], ignore_index=True)
        tld_top_rank_df.to_csv("Outputs/TLD-Rank/tld_top_rank.csv")

    return tld_top_rank_df

def cal_tld_rank(data, tld_top_rank_df):
    tld = data.split('.')[-1]
    rank = 0
    for _, row in tld_top_rank_df.iterrows():
        if row['tld'] == tld:
            rank = int(row['rank'])
            break
    return rank


from collections import deque

def solution(people, limit):
    answer = 0
    a = deque(sorted(people))

    while a:
        if len(a) > 1:
            if a[0]+a[-1] <= limit:
                a.popleft()
                a.pop()
                answer+=1
            else:
                a.pop()
                answer+=1

        elif len(a) == 1:
            a.pop()
            answer+=1

        else:
            break

    return answer

print(solution([70, 50, 80, 50], 100))
print(solution([30, 30, 70, 70], 100))


import json
import os
from datetime import datetime, timedelta, date
from statistics import mean

from dateutil.relativedelta import relativedelta
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Count
from django.http import HttpResponseRedirect, HttpResponse, JsonResponse
from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse_lazy
from django.views.generic import DeleteView, UpdateView, CreateView
from icalendar import Calendar, Event
from pytz import timezone
from rest_framework import viewsets
from rest_framework.response import Response

from PlanningViewer.forms import WerktijdForm, UploadForm, AddFav, UserSettingsForm, YearSelectForm, PersoonSelectForm, \
    DateSelectForm, UrenAdjustForm
from .functions import get_period, get_period_now, maandelijkse_uren, get_period_data, calc_easter, next_payout
from .models import Werktijd, Favoriet, ApiKey, UserSettings, OverurenAjust
# Create your views here.
from .serializers import WerktijdSerializers

@login_required
def index(request):
    def is_familie(user):
        return user.groups.filter(name='familie').exists()

    fav = Favoriet.objects.filter(eigenaar=request.user)

    werktijden = []

    if not is_familie(request.user):
        werktijden_tmp = Werktijd.objects.filter(voornaam=request.user.first_name).filter(
            achternaam=request.user.last_name).filter(datum__gte=datetime.now().date()).order_by('datum')
        werktijden.append(werktijden_tmp)

    for f in fav:
        if f.show_tab:
            tmp = Werktijd.objects.filter(voornaam=f.f_voornaam).filter(
                achternaam=f.f_achternaam).filter(datum__gte=datetime.now().date()).order_by('datum')
            werktijden.append(tmp)

    context = {
        'werktijden': werktijden,
        'voornaam': request.user.get_short_name()
    }

    return render(request, 'PlanningViewer/index.html', context)

@login_required
def werktijden_details(request, w_id):
    werktijd = Werktijd.objects.get(pk=w_id)
    aanwezigen = werktijd.get_aanwezigen
    delete_permission = True if werktijd.voornaam == request.user.first_name and werktijd.achternaam == request.user.last_name else False

    fav = Favoriet.objects.filter(eigenaar=request.user).filter(show_marker=True)

    marker = False
    if fav:
        for f in fav:
            for a in aanwezigen:
                if f.f_voornaam == a.voornaam and f.f_achternaam == a.achternaam:
                    marker = True
    else:
        marker = False

    if request.method == 'POST':
        overwerk = int(request.POST['overwerk_range'])
        if 0 <= overwerk <= 120 and delete_permission:
            werktijd.overwerk = overwerk
            werktijd.save()

    def get_color_name(c):
        colormap = {
            "#00FF00": "Vleeswaren",
            "#00CCFF": "Zuivel / Kassa 1",
            "#003366": "Bedrijfsleiding",
            "#993300": "Slagerij",
            "#008000": "AGF",
            "#FF00FF": "Opleiding / Pizza",
            "#800080": "Kassa 4 / Bulk",
            "#FF99CC": "Schoonmaken",
            "#99CC00": "Kassa 3",
            "#FF0000": "Kassa",  # "Kassa 6 / Ombouw"
            "#33CCCC": "Kassa 1",
            "#FFFF00": "Kassa 2",
            "#0066CC": "Brood",
            "#FFCC00": "Magazijnmanager",
            "#e5e7e9": "DKW / Anders"
        }
        if c in colormap:
            return colormap[c]
        else:
            return "?"

    colors = json.loads(werktijd.colors.replace("#000000", "#e5e7e9"))
    kleuren = [[k, get_color_name(k)] for k in colors]

    context = {
        'werktijd': werktijd,
        'kleuren': kleuren,
        'aanwezigen': aanwezigen,
        'voornaam': request.user.get_short_name(),
        'delete_permission': delete_permission,
        'marker': marker
    }

    return render(request, 'PlanningViewer/details.html', context)

@login_required
def personen_intersect(request):
    persoonForm = PersoonSelectForm(request.GET)

    if persoonForm.is_valid():
        p_voornaam = persoonForm.cleaned_data['voornaam']
        p_achternaam = persoonForm.cleaned_data['achternaam']
        werktijden = []

        werktijden_1 = Werktijd.objects.filter(voornaam=p_voornaam).filter(achternaam=p_achternaam).filter(
            datum__gte=datetime.now()).order_by('datum')

        werktijden_2 = Werktijd.objects.filter(voornaam=request.user.first_name).filter(
            achternaam=request.user.last_name).filter(
            datum__gte=datetime.now()).order_by('datum')

        def in_interval(b1, b2, e1, e2):
            return b1 <= e2 and e1 >= b2

        for w in werktijden_1:
            for w2 in werktijden_2:
                if in_interval(w.begintijd, w2.begintijd, w.eindtijd, w2.eindtijd) and w.datum == w2.datum:
                    werktijden.append(w2)

        if not werktijden:
            messages.warning(request, 'Geen overlappende werktijden gevonden. Controleer de ingevoerde gegevens.')
            return redirect(tools)

        context = {
            'werktijden': werktijden,
            'voornaam': request.user.get_short_name()
        }

        return render(request, 'PlanningViewer/details_persoon.html', context)

    else:
        messages.warning(request, 'Er is iets misgegaan :(. Probeer opnieuw.')
        return redirect(index)

@login_required
def personen_details(request):
    persoonForm = PersoonSelectForm(request.GET)

    if persoonForm.is_valid():
        p_voornaam = persoonForm.cleaned_data['voornaam']
        p_achternaam = persoonForm.cleaned_data['achternaam']

    else:
        messages.warning(request, 'Persoon niet gevonden.')
        return redirect(index)

    werktijden = Werktijd.objects.filter(voornaam=p_voornaam).filter(achternaam=p_achternaam).filter(
        datum__gte=datetime.now() - timedelta(days=7)).order_by('datum')

    context = {
        'werktijden': werktijden,
        'voornaam': request.user.get_short_name()
    }

    return render(request, 'PlanningViewer/details_persoon.html', context)

@login_required
def upload_planning(request):
    if not request.user.is_staff:
        messages.warning(request, 'Deze pagina is niet toegankelijk.')
        return HttpResponseRedirect('/')

    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            data = request.FILES['file']
            # path = default_storage.save('tmp/' + str(data), ContentFile(data.read()))
            # tmp_file_path = os.path.join(settings.MEDIA_ROOT, path)
            tmp_file_path = data.temporary_file_path()
            f_name = data.name
            from subprocess import check_output
            import json
            out = check_output(['java', '-jar', '/jumbo_website/PlanningReader.main.jar', tmp_file_path])
            j = json.loads(out)

            werktijden = []
            for p in j:
                col = json.dumps(p['colors'])

                # Check for errors
                if p["eind"] < p["begin"]:
                    messages.error(request, f'Onjuiste werktijd voor {p["voornaam"]} {p["achternaam"]} op {p["datum"]}')
                    return HttpResponseRedirect('/')

                werktijden.append(
                    Werktijd(voornaam=p["voornaam"], achternaam=p["achternaam"], begintijd=p["begin"],
                             eindtijd=p["eind"],
                             pauze=p["pauze"], datum=p["datum"], colors=col))
            Werktijd.objects.bulk_create(werktijden)
            messages.success(request, 'Planning is met succes geÃ¼pload!')
            return HttpResponseRedirect('/')

    context = {
        'uploadform': UploadForm(),
        'voornaam': request.user.get_short_name()
    }

    return render(request, 'PlanningViewer/uploadplanning.html', context)

@login_required
def fav_toevoegen(request):
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = AddFav(request.POST)
        # check whether it's valid:
        if form.is_valid():
            if not Werktijd.objects.filter(voornaam=form.cleaned_data['f_voornaam']).filter(
                    achternaam=form.cleaned_data['f_achternaam']):
                messages.warning(request, 'Fout: de voor- en/of achternaam is niet gevonden. Probeer het opnieuw.')
            else:
                value = form.save(commit=False)
                value.eigenaar = request.user
                value.save()

    fav = Favoriet.objects.filter(eigenaar=request.user)

    context = {
        'voornaam': request.user.get_short_name(),
        'form': AddFav(),
        'favorieten': fav,
    }

    return render(request, 'PlanningViewer/fav_toevoegen.html', context)

class FavorietDelete(LoginRequiredMixin, DeleteView):
    model = Favoriet
    success_message = "Favoriet succesvol verwijderd."
    success_url = reverse_lazy('fav_toevoegen')

    def get_queryset(self):
        qs = super(FavorietDelete, self).get_queryset()
        return qs.filter(eigenaar=self.request.user)

class WerktijdDelete(LoginRequiredMixin, DeleteView):
    model = Werktijd
    success_message = "Werktijd succesvol verwijderd."
    success_url = reverse_lazy('index')

    def get_queryset(self):
        qs = super(WerktijdDelete, self).get_queryset()
        return qs.filter(voornaam=self.request.user.first_name).filter(
            achternaam=self.request.user.last_name)

class WerktijdUpdate(LoginRequiredMixin, UpdateView):
    model = Werktijd
    success_message = "Werktijd succesvol aangepast."
    success_url = reverse_lazy('index')
    template_name = "PlanningViewer/toevoegen.html"
    form_class = WerktijdForm

    def get_queryset(self):
        qs = super(WerktijdUpdate, self).get_queryset()
        return qs.filter(voornaam=self.request.user.first_name).filter(
            achternaam=self.request.user.last_name)

    def form_valid(self, form):
        form.instance.voornaam = self.request.user.first_name
        form.instance.achternaam = self.request.user.last_name
        return super().form_valid(form)

class WerktijdCreate(LoginRequiredMixin, CreateView):
    model = Werktijd
    success_message = "Werktijd succesvol toegevoegd."
    success_url = reverse_lazy('index')
    template_name = "PlanningViewer/toevoegen.html"
    form_class = WerktijdForm

    def form_valid(self, form):
        form.instance.voornaam = self.request.user.first_name
        form.instance.achternaam = self.request.user.last_name
        return super().form_valid(form)

@login_required
def stats_view(request):
    if request.method == 'POST':
        form = YearSelectForm(request.POST)
        if form.is_valid():
            yearS = int(form.cleaned_data['yearSelect'])
        else:
            yearS = datetime.now().year
    else:
        yearS = datetime.now().year

    context = {
        "m_uren": maandelijkse_uren(yearS, get_period_now(), request),
        "periode_now": get_period_now(),
        "yearselect": YearSelectForm()
    }

    return render(request, 'PlanningViewer/stats.html', context)

@login_required
def periode_view(request, year=2020, periode=1):
    start, eind = get_period(periode, year)
    werktijden = Werktijd.objects.filter(datum__gte=start).filter(datum__lte=eind).filter(
        voornaam=request.user.first_name).filter(achternaam=request.user.last_name).order_by('datum')

    context = {
        'werktijden': werktijden,
        'begin_p': start.date(),
        'eind_p': eind.date()
    }

    return render(request, 'PlanningViewer/periode_detail.html', context)

@login_required
def api_key(request):
    def newKey(string_length=32):
        """Generate a random string with the combination of lowercase and uppercase letters """
        import string
        import random
        letters = string.ascii_letters
        return ''.join(random.choice(letters) for i in range(string_length))

    key = ApiKey.objects.filter(user=request.user)

    if not key:
        # Key needs to be generated
        apikey = newKey()
        saveKey = ApiKey(user=request.user, apikey=apikey)
        saveKey.save()
        pass
    else:
        # Key exists
        apikey = key[0].apikey

    context = {
        "apikey": apikey,
        "host": os.getenv("SERVER_HOST")
    }

    return render(request, 'PlanningViewer/api/create_key.html', context)

def ical_api(request):
    key = request.GET.get("key", None)

    if key is None:
        # Check if a key is passed
        return HttpResponse('Unauthorized', status=401)

    api_key_obj = ApiKey.objects.filter(apikey=key).first()

    if not api_key_obj:
        # Check if the key belongs to a user
        return HttpResponse('Unauthorized', status=401)

    user = api_key_obj.user
    api_key_obj.lastused = datetime.now()
    api_key_obj.save()

    werktijden = Werktijd.objects.filter(voornaam=user.first_name).filter(achternaam=user.last_name).filter(
        datum__gte=datetime.now() - timedelta(days=14))

    def create_ical(werktijden):
        amsterdam = timezone('Europe/Amsterdam')

        cal = Calendar()

        # Add requierd iCal parameters
        cal.add('prodid', '-//Werkijden Calendar//{}//'.format(os.getenv("SERVER_HOST")))
        cal.add('version', '2.0')
        cal.add('calscale', 'GREGORIAN')
        cal.add('name', 'Werktijden Calendar')

        dtstamp = datetime.now().replace(tzinfo=amsterdam)

        for werktijd in werktijden:
            event = Event()

            event.add('uid', '{}-{}@{}'.format(werktijd.id, datetime.now().year, os.getenv("SERVER_HOST")))
            event.add('dtstamp', dtstamp)

            dtstart = datetime(werktijd.datum.year, werktijd.datum.month, werktijd.datum.day,
                               werktijd.begintijd.hour, werktijd.begintijd.minute, 0, tzinfo=amsterdam)
            dtend = datetime(werktijd.datum.year, werktijd.datum.month, werktijd.datum.day,
                             werktijd.eindtijd.hour, werktijd.eindtijd.minute, 0, tzinfo=amsterdam)

            event.add('summary', 'Werken')
            event.add('dtstart', dtstart)
            event.add('dtend', dtend)
            event.add('description',
                      'Werken bij Jumbo van {} tot {}'.format(werktijd.begintijd, werktijd.eindtijd))
            event.add('location', os.getenv("CALENDAR_LOCATION"))
            cal.add_component(event)

        payout_event = Event()
        closest, ndays = next_payout()

        payout_event.add('uid', 'payout-{}-{}-{}@{}'.format(closest.year, closest.month, closest.day, os.getenv("SERVER_HOST")))
        payout_event.add('dtstamp', dtstamp)
        payout_event.add('summary', 'Salaris uitbetaling ðŸ’°')
        payout_event.add('dtstart', datetime(closest.year, closest.month, closest.day, 9, 0, tzinfo=amsterdam))
        payout_event.add('dtend', datetime(closest.year, closest.month, closest.day, 10, 0, tzinfo=amsterdam))
        payout_event.add('description', 'Salaris uitbetaling! ðŸ’°')
        cal.add_component(payout_event)
        return cal

    response = HttpResponse(create_ical(werktijden).to_ical(), content_type="text/calendar")
    response['Content-Disposition'] = 'attachment; filename=werktijden.ics'
    return response

@login_required
def export_data(request):
    # Create the HttpResponse object with the appropriate CSV header.
    import csv
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="werktijden.csv"'

    werktijden = Werktijd.objects.filter(voornaam=request.user.first_name, achternaam=request.user.last_name)

    writer = csv.writer(response)
    for wt in werktijden:
        # datum, begin, eind, week, extra, pauze, totaal
        writer.writerow([wt.datum, wt.begintijd, wt.eindtijd, wt.week, wt.extra, wt.pauze, wt.totaal])

    return response

@login_required
def tools(request):
    closest, ndays = next_payout()
    start_d = datetime.today().replace(day=1).date() - relativedelta(months=1)
    end_d = datetime.today().replace(day=1).date()
    wvdm = Werktijd.objects.filter(datum__gte=start_d).filter(datum__lt=end_d).values('voornaam', 'achternaam').annotate(num=Count('datum')).order_by('-num')[:3]

    context = {
        'voornaam': request.user.get_short_name(),
        'closest': closest,
        'ndays': ndays,
        'intersectfrom': PersoonSelectForm(),
        'wvdm': wvdm,
        'eerste_d': f"{start_d} - {end_d}"
    }

    return render(request, 'PlanningViewer/tools.html', context)

@login_required
def nu_aanwezig(request):
    now = datetime.now().time()
    aanwezigen = Werktijd.objects.filter(datum=datetime.now().date(), begintijd__lte=now, eindtijd__gte=now)

    context = {
        'aanwezigen': aanwezigen
    }
    return render(request, 'PlanningViewer/nu_aanwezig.html', context)

class UserSettingsUpdate(UpdateView):
    model = UserSettings
    success_message = "Instellingen succesvol aangepast."
    success_url = reverse_lazy('index')
    template_name = "PlanningViewer/instellingen.html"
    form_class = UserSettingsForm

    def get_queryset(self):
        qs = super(UserSettingsUpdate, self).get_queryset()
        return qs.filter(user=self.request.user)

@login_required
def zoeken(request):
    context = {
        'zoekpersoonform': PersoonSelectForm(),
        'zoekdateform': DateSelectForm()
    }

    if request.method == 'POST':
        zoekpersoonform = PersoonSelectForm(request.POST)
        zoekdateform = DateSelectForm(request.POST)
        if zoekpersoonform.is_valid():
            context['zoekpersoonform'] = zoekpersoonform
            voornaam = zoekpersoonform.cleaned_data['voornaam']
            achternaam = zoekpersoonform.cleaned_data['achternaam']
            response = redirect(personen_details)
            response['Location'] += '?voornaam=' + voornaam + '&achternaam=' + achternaam
            return response

        elif zoekdateform.is_valid():
            context['zoekdateform'] = zoekdateform
            date = zoekdateform.cleaned_data['date']
            werktijden = Werktijd.objects.filter(datum=date).order_by('colors')
            wt = []
            for w in werktijden:
                wt.append([w, json.loads(w.colors.replace("#000000", "#e5e7e9"))])
            context['dateoutput'] = wt

            return render(request, 'PlanningViewer/zoeken.html', context)
    # else:
    #     zoekpersoonform = PersoonSelectForm()
    #     zoekdateform = DateSelectForm()

    return render(request, 'PlanningViewer/zoeken.html', context)

def next_api(request):
    key = request.GET.get("key", None)

    if key is None:
        # Check if a key is passed
        return HttpResponse('Unauthorized', status=401)

    api_key_obj = ApiKey.objects.filter(apikey=key).first()

    if not api_key_obj:
        # Check if the key belongs to a user
        return HttpResponse('Unauthorized', status=401)

    user = api_key_obj.user
    api_key_obj.lastused = datetime.now()
    api_key_obj.save()

    werktijd = Werktijd.objects.filter(voornaam=user.first_name).filter(achternaam=user.last_name).filter(
        datum__gte=datetime.now()).order_by('datum').first()

    if werktijd:
        # locale.setlocale(locale.LC_ALL, "nl_NL.utf8")
        datum = werktijd.datum.strftime("%A %-d %b")
        btijd = werktijd.begintijd.strftime("%H:%M")
        etijd = werktijd.eindtijd.strftime("%H:%M")

        nextw = {
            "next": datum + " " + btijd + " - " + etijd
        }

    else:
        nextw = {"next": "Onbekend"}

    return JsonResponse(nextw)

class OverurenAdjustDelete(LoginRequiredMixin, DeleteView):
    model = OverurenAjust
    success_message = "Aanpassing succesvol verwijderd."
    success_url = reverse_lazy('overuren')

    def get_queryset(self):
        qs = super(OverurenAdjustDelete, self).get_queryset()
        return qs.filter(user=self.request.user)

@login_required
def overuren(request):
    if request.method == 'POST':
        form = UrenAdjustForm(request.POST)
        if form.is_valid():
            value = form.save(commit=False)
            value.user = request.user
            if value.reason == 'UB':
                value.uren_change = value.uren_change * -1.0
            value.save()
        else:
            messages.warning(request, 'Ongeldige gegevens ingevoerd! Probeer opnieuw.')

    c_uren = request.user.usersettings.contract_uren

    if c_uren == 0:  # Niet in vast contract modus
        messages.warning(request,
                         'U heeft geen aantal contracturen ingesteld, hierdoor is de overuren optie niet beschikbaar. U kunt dit aanpassen onder instellingen.')
        return redirect(index)

    start_date = request.user.usersettings.start_contract_uren
    # s_year, s_periode = date_to_period(start_date)  # date_to_period(date(2020, 9, 8))
    s_year = 2020
    s_periode = 11
    p_data = []
    acc = 0

    adjustments = OverurenAjust.objects.filter(user=request.user)

    def get_adjust(year, per):
        adj = 0.0
        res = ""
        aid = -1
        for a in adjustments:
            if a.year == year and a.periode == per:
                adj = a.uren_change
                res = a.reason
                aid = a.id
        return adj, res, aid

    for y in range(s_year, datetime.now().year + 1):
        start_p = s_periode if s_year == y else 1
        stop_p = get_period_now() if y == datetime.now().year else 14

        for i in range(start_p, min(stop_p + 2, 14)):
            totaal_uur, totaal_pauze, totaal_zondag = get_period_data(i, y, request)
            netto_uur = totaal_uur - totaal_pauze
            overuur = (totaal_uur - totaal_pauze) - 4 * c_uren
            acc = acc + overuur
            start_d, end_d = get_period(i, y)

            p_data.append({"totaal_uur": totaal_uur,
                           "totaal_pauze": totaal_pauze,
                           "totaal_zondag": totaal_zondag,
                           "netto_uur": netto_uur,
                           "overuren": overuur,
                           "periode": str(y) + "/" + str(i),
                           "datum": str(start_d.date().strftime("%d %b")) + " - " + str(end_d.date().strftime("%d %b")),
                           "acc": acc,
                           })

            adj, res, aid = get_adjust(y, i)
            if adj != 0:
                acc = acc + adj
                p_data.append({"totaal_uur": "-",
                               "totaal_pauze": aid,  # also used to pass id :P
                               "totaal_zondag": "-",
                               "netto_uur": res,
                               "overuren": adj,
                               "periode": str(y) + "/" + str(i),
                               "datum": str(start_d.date().strftime("%d %b")) + " - " + str(
                                   end_d.date().strftime("%d %b")),
                               "acc": acc,
                               })

    context = {
        "p_data": reversed(p_data),
        "form": UrenAdjustForm()
    }

    return render(request, 'PlanningViewer/overuren_view.html', context)

class WerktijdViewSet(viewsets.ViewSet):
    """
    A simple ViewSet for listing or retrieving werktijden.
    """

    def list(self, request):
        queryset = Werktijd.objects.filter(voornaam=request.user.first_name).filter(
            achternaam=request.user.last_name).filter(datum__gte=datetime.now().date()).order_by('datum')
        serializer = WerktijdSerializers(queryset, many=True)
        return Response(serializer.data)

    def retrieve(self, request, pk=None):
        queryset = Werktijd.objects.all()
        werktijd = get_object_or_404(queryset, pk=pk)
        serializer = WerktijdSerializers(werktijd)
        return Response(serializer.data)

@login_required
def vandaag(request):
    dtm = datetime.now().date()

    if 'date' in request.GET:
        dtm = datetime.strptime(request.GET.get("date"), "%d-%m-%Y")
    else:
        dtm = datetime.now().date()

    if request.method == 'POST':
        zoekdateform = DateSelectForm(request.POST)
        if zoekdateform.is_valid():
            dtm = zoekdateform.cleaned_data['date']

    aanwezigen = Werktijd.objects.filter(datum=dtm).order_by('begintijd')

    personen = []
    uren = []

    def t_to_float(time):
        return time.hour + time.minute / 60.0

    for w in aanwezigen:
        personen.append(w.fullname())
        uren.append([t_to_float(w.begintijd), t_to_float(w.eindtijd)])

    context = {
        'data': [personen, uren],
        'zoekdateform': DateSelectForm(request.POST),
        'next': datetime.strftime(dtm + timedelta(days=1), "%d-%m-%Y"),
        'prev': datetime.strftime(dtm - timedelta(days=1), "%d-%m-%Y"),
        'date': datetime.strftime(dtm, "%Y-%m-%d"),
    }
    return render(request, 'PlanningViewer/vandaag.html', context)

@login_required
def geldterug(request):
    vnaam = request.GET.get("voornaam", request.user.first_name)
    anaam = request.GET.get("achternaam", request.user.last_name)
    year = int(request.GET.get("jaar", 2022))

    if vnaam == "" or anaam == "":
        vnaam = request.user.first_name
        anaam = request.user.last_name

    pasen1 = calc_easter(year)
    feestdagen = [
        pasen1,  # Pasen 1
        pasen1 + timedelta(days=1),  # Pasen 2
        pasen1 + timedelta(days=39),  # hemelvaart
        pasen1 + timedelta(days=49),  # pinksteren1
        pasen1 + timedelta(days=50),  # pinksteren2
        date(year, 1, 1),  # nieuwjaarsdag
        date(year, 4, 27),  # koningsdag
        date(year, 12, 25),  # kerst1
        date(year, 12, 26)  # kerst2
    ]

    # get the requierd date ranges
    dateranges = []
    for f in feestdagen:
        dateranges.append(Werktijd.objects.filter(voornaam=vnaam, achternaam=anaam,
                                                  datum__lte=f, datum__gt=f-timedelta(weeks=12)))

    # calculate the amount of worked days on that particular date
    results = []
    for day, daterange in zip(feestdagen, dateranges):
        feestday = day.weekday()
        count = 0
        debug = []
        for d in daterange:
            if d.datum.weekday() == feestday:
                count = count + 1
                debug.append(d)
        gem_uren_l = [(x.totaal_int - x.pauze_int) for x in debug]
        gem_uren = mean(gem_uren_l) if len(gem_uren_l) >= 1 else 0
        results.append([day, count, [x.datum.strftime("%d %b %Y wk %W") for x in debug], gem_uren])

    context = {'results': results,
               'fname': f'{vnaam} {anaam} in {year}',
               'vnaam': vnaam,
               'anaam': anaam,
               'years': reversed(range(2020, datetime.now().year+1))
               }

    return render(request, 'PlanningViewer/geldterug.html', context)

'''
accounts/login/ [name='login']
accounts/logout/ [name='logout']
accounts/password_change/ [name='password_change']
accounts/password_change/done/ [name='password_change_done']
accounts/password_reset/ [name='password_reset']
accounts/password_reset/done/ [name='password_reset_done']
accounts/reset/<uidb64>/<token>/ [name='password_reset_confirm']
accounts/reset/done/ [name='password_reset_complete']
'''


from django.urls import path
from home import views

urlpatterns = [
    path('',views.home,name="home"),
    path('contact/',views.contact,name="contact"),
    path('about/',views.about,name="about"),
    path('viewProfile/',views.viewProfile,name="viewProfile"),
    path('editUserProfile/',views.editUserProfile,name="editUserProfile"),
    path('handleEditProfile/',views.handleEditProfile,name="handleEditProfile"),
    path('privacyPolicy/',views.privacyPolicy,name="privacyPolicy"),
    path('termsconditions/',views.termsconditions,name="termsconditions"),
    path('faqs/',views.faqs,name="faqs"),
    path('userDashboard/',views.userDashboard,name="userDashboard"),
]


import torch

class EmotionDataset(torch.utils.data.Dataset):
    def __init__(self, tokenizer, texts, targets=None, label_list=None, max_len=128):
        self.texts = texts
        self.targets = targets
        self.has_target = isinstance(targets, list) or isinstance(targets, np.ndarray)
        self.tokenizer = tokenizer
        self.max_len = max_len

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

    def __getitem__(self, item):
        text = str(self.texts[item])
        if self.has_target:
          target = self.targets[item]
        encoding = self.tokenizer.encode_plus(
            text,
            add_special_tokens=True,
            truncation=True,
            max_length=self.max_len,
            return_token_type_ids=True,
            padding='max_length',
            return_attention_mask=True,
            return_tensors='pt')
        inputs = {
            'text': text,
            'input_ids': encoding['input_ids'].flatten(),
            'attention_mask': encoding['attention_mask'].flatten(),
            'token_type_ids': encoding['token_type_ids'].flatten(),
        }
        if self.has_target:
            inputs['targets'] = torch.tensor(target, dtype=torch.long)
        return inputs

def create_data_loader(x, y, tokenizer, max_len, batch_size, label_list):
    dataset = EmotionDataset(
        texts=x,
        targets=y,
        tokenizer=tokenizer,
        max_len=max_len,
        label_list=label_list)

    return torch.utils.data.DataLoader(dataset, batch_size=batch_size)


def day_of_year(month, day, year):
    """
    returns the day of year given a date
    """

    days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    day_num = day + sum(days_in_month[0:month-1])
    if year % 4 == 0 and month>2: #leap year
        day_num +=1

    return day_num

if __name__ == "__main__":
    print(day_of_year(4, 1, 2022))


from django.contrib.auth.models import User
from django.test import TestCase

from apps.auction.models import Auction, Bid

class AuctionModelTest(TestCase):
    """Unit tests for Auction model"""

    def setUp(self):
        """Creating Auction instance for testing. No saving actions on DB"""
        self.auction_data = {
            "id": 1,
            "amount": 100
        }
        self.auction_test = Auction(**self.auction_data)

    def test_str_return_correctly(self):
        """Verifies if __str__ method works correctly"""
        expected = f"Id: {self.auction_data.get('id')} - Amount: {self.auction_data.get('amount')}"
        self.assertEqual(str(self.auction_test), expected)

    def test_status_is_open_in_creation(self):
        """Verify that status field is set correctly"""
        expected = "open"
        self.assertEqual(self.auction_test.status, expected)

class BidModelTest(TestCase):
    """Unit tests for Bid model"""

    def setUp(self):
        """Creating Bid instance for testing. No saving actions on DB"""
        user_data = {
            "username": "username1",
            "email": "email1@test.com"
        }
        user_test = User(**user_data)

        auction_data = {
            "id": 1,
            "amount": 100
        }
        self.auction_test = Auction(**auction_data)

        self.fake_data = {
            "id": 1,
            "user": user_test,
            "auction": self.auction_test,
            "amount": 100
        }
        self.bid_test = Bid(**self.fake_data)

    def test_str_return_correctly(self):
        """Verifies if __str__ method works correctly"""
        expected = f"Auction: {self.auction_test.amount} - Amount: {self.bid_test.amount} - DR: {self.bid_test.discount_rate} - Winner: {self.bid_test.winner}"
        self.assertEqual(str(self.bid_test), expected)

    def test_winner_is_false_in_creation(self):
        """Verify that winner field is set correctly"""
        self.assertFalse(self.bid_test.winner)


import random
import json
import pickle
import os

from pico2d import *
import game_framework
import game_world

import main_state

from boy import Boy
from zombie import Zombie

boy = None

zombies = []

name = "WorldBuildState"

menu = None

def enter():
    global menu
    menu = load_image('menu.png')
    hide_cursor()
    hide_lattice()

def exit():
    global menu
    del menu

def pause():
    pass

def resume():
    pass

def get_boy():
    return boy

def get_zombies():
    return zombies

def create_new_world():
    global boy , zombies
    boy = Boy()
    zombies = [Zombie() for i in range(100)]

    game_world.add_object(boy, 1)
    game_world.add_objects(zombies, 1)
    # fill hereN

def load_saved_world():
    global boy

    # fill here
    game_world.load()
    for o in game_world.all_objects():
        if isinstance(o, Boy):
            boy = o
            break
            #조건에 맞으면 보이로 설정한다.
            #소년 객체가 하나뿐이라서..break

def handle_events():
    events = get_events()
    for event in events:
        if event.type == SDL_QUIT:
            game_framework.quit()
        elif event.type == SDL_KEYDOWN and event.key == SDLK_ESCAPE:
                game_framework.quit()
        elif event.type == SDL_KEYDOWN and event.key == SDLK_n:
            create_new_world()
            game_framework.change_state(main_state)
        elif event.type == SDL_KEYDOWN and event.key == SDLK_l:
            load_saved_world()
            game_framework.change_state(main_state)

def update():
    pass

def draw():
    clear_canvas()
    menu.draw(get_canvas_width() // 2, get_canvas_height() // 2)
    update_canvas()


from django.contrib import admin
from django import forms
from django.utils.safestring import mark_safe

from .models import Actor, Category, Rating, RatingStar, Movie, MovieShots, Genre, Review
from ckeditor_uploader.widgets import CKEditorUploadingWidget

class MovieAdminForm(forms.ModelForm):
    description = forms.CharField(label="Описание", widget=CKEditorUploadingWidget())

    class Meta:
        model = Movie
        fields = '__all__'

admin.site.site_title = "Django movie"
admin.site.site_header = "Django movie"

class CategoryAdmin(admin.ModelAdmin):
    list_display = ("id", "url", "title")
    list_display_links = ("title",)

class ReviewInline(admin.TabularInline):
    """Отзывы на админ. странице фильмов"""
    readonly_fields = ('email', 'name')
    model = Review
    extra = 1

class MovieShotsInLine(admin.TabularInline):
    model = MovieShots
    extra = 1
    readonly_fields = ("get_image",)

    def get_image(self, obj):
        return mark_safe(f'')

    get_image.short_description = "Изображение"

class MovieAdmin(admin.ModelAdmin):
    list_display = ("title", "category", "url", "draft")
    list_filter = ("category", "year")
    search_fields = ("title", "category__title")
    inlines = [MovieShotsInLine, ReviewInline]
    save_on_top = True
    save_as = True
    readonly_fields = ("get_image",)
    list_editable = ("draft",)
    actions = ['publish', 'unpublish']
    form = MovieAdminForm
    fieldsets = (
        (
            None, {
                "fields": (("title", "tagline"),)
            }
        ),
        (None, {
            "fields": ("description", ("get_image", "poster"))
        }),
        (None, {
            "fields": (("year", "world_premiere", "country"),)
        }),
        ("Действующие лица", {
            "classes": ("collapse",),
            "fields": (("actors", "director", "genre", "category"),)
        }),
        (None, {
            "fields": (("budget", "fees_in_usa", "fees_in_world"),)
        }),
        ("Служебные поля", {
            "fields": (("url", "draft"),)
        }),
    )

    def get_image(self, obj):
        return mark_safe(f'')

    get_image.short_description = "изображение"

    def unpublish(self, request, queryset):
        """Опубликовать"""
        row_update = queryset.update(draft=True)
        if row_update == 1:
            message_bit = "запись обновлена"
        else:
            message_bit = f'{row_update} записей были обновлены'
        self.message_user(request, f"{message_bit}")

    def publish(self, request, queryset):
        """Снять с публикации"""
        row_update = queryset.update(draft=False)
        if row_update == 1:
            message_bit = "запись обновлена"
        else:
            message_bit = f'{row_update} записей были обновлены'
        self.message_user(request, f"{message_bit}")

    publish.short_description = "Опубликовать"
    publish.allowed_permission = ('change',)

    unpublish.short_description = "Снять с публикации"
    unpublish.allowed_permission = ('change',)

class ReviewAdmin(admin.ModelAdmin):
    list_display = ("name", "email", "parent", "movie", "id")
    readonly_fields = ("email", "name")

class GenreAdmin(admin.ModelAdmin):
    list_display = ("name", "description", "url")

class ActorAdmin(admin.ModelAdmin):
    list_display = ("name", "description", "age", "get_image")
    readonly_fields = ("get_image",)

    def get_image(self, obj):
        return mark_safe(f'')

    get_image.short_description = "Изображение"

class RatingAdmin(admin.ModelAdmin):
    list_display = ("movie", "ip")

class MovieShotsAdmin(admin.ModelAdmin):
    list_display = ("title", "id_movie", "get_image")
    readonly_fields = ("get_image",)

    def get_image(self, obj):
        return mark_safe(f'')

    get_image.short_description = "Изображение"

admin.site.register(Actor, ActorAdmin)
admin.site.register(Category, CategoryAdmin)
admin.site.register(Rating, RatingAdmin)
admin.site.register(RatingStar)
admin.site.register(Movie, MovieAdmin)
admin.site.register(MovieShots, MovieShotsAdmin)
admin.site.register(Genre, GenreAdmin)
admin.site.register(Review, ReviewAdmin)


import os
import glob
import sys

class CAPSProfile:
    def __init__(self):
        self.streams = [] # List of strings, e.g. XY.ABCD.*.*
        self.stations = [] # List of network, station tuples, e.g. (XY,ABCD)
        self.oldStates = [] # Content of old state file

'''
Plugin handler for the CAPS plugin.
'''

class SeedlinkPluginHandler:
    # Create defaults
    def __init__(self):
        self.profiles = {}

    def push(self, seedlink):
        try:
            maxTimeDiff = float(seedlink._get('plugins.caps.maxTimeDiff', False))
        except:
            maxTimeDiff = 86400

        inOrder = ""
        try:
            if seedlink._get('plugins.caps.inOrder', False):
                inOrder = " --in-order"
        except:
            pass

        # Check and set defaults
        try:
            address = seedlink.param('sources.caps.address')
        except KeyError:
            address = "localhost:18002"

        try:
            streams = [chaId.strip() for chaId in seedlink.param(
                'sources.caps.streams').split(',')]
        except KeyError:
            seedlink.setParam('sources.caps.streams', "*.*")
            streams = ["*.*"]

        try:
            encoding = seedlink.param('sources.caps.encoding')
        except KeyError:
            seedlink.setParam('sources.caps.encoding', "STEIM2")

        # parse address URL and create capsId of form:
        # host[.port][_user]
        addressFormatError = "Error: invalid address format, expected " \
                             "[[caps|capss]://][user:pass@]host[:port]"

        # protocol
        toks = address.split("://")
        if len(toks) > 2:
            raise Exception(addressFormatError)
        elif len(toks) == 2:
            protocol = toks[0]
            address = toks[1]
            if protocol != "caps" and protocol != "capss":
                raise Exception(addressFormatError)
        else:
            protocol = "caps"

        # authentication
        toks = address.split("@")
        if len(toks) > 2:
            raise Exception(addressFormatError)
        elif len(toks) == 2:
            capsId = "%s_%s" % (toks[1].replace(
                ":", "."), toks[0].split(":")[0])
        else:
            capsId = address.replace(":", ".")

        address = "%s://%s" % (protocol, address)

        if capsId not in self.profiles:
            profile = CAPSProfile()
            self.profiles[capsId] = profile
        else:
            profile = self.profiles[capsId]

        for chaId in streams:
            toks = chaId.split('.')
            if len(toks) != 2:
                raise Exception(
                    "Error: invalid stream format, expected [LOC.CHA]")

            streamID = seedlink.net + "." + seedlink.sta + "." + chaId
            profile.streams.append(streamID)
            profile.stations.append((seedlink.net, seedlink.sta))

        log = os.path.join(seedlink.config_dir, "caps2sl.%s.state" % capsId)
        streamsFile = os.path.join(
            seedlink.config_dir, "caps2sl.%s.req" % capsId)
        seedlink.setParam('sources.caps.address', address)
        seedlink.setParam('sources.caps.log', log)
        seedlink.setParam('sources.caps.streamsFile', streamsFile)
        seedlink.setParam('sources.caps.maxTimeDiff', maxTimeDiff)
        seedlink.setParam('sources.caps.inOrder', inOrder)
        seedlink.setParam('seedlink.caps.id', capsId)

        return capsId

    def flush(self, seedlink):
        # Populate request file per address
        for id, profile in self.profiles.items():
            caps2slreq = os.path.join(
                seedlink.config_dir, "caps2sl.%s.req" % id)
            fd = open(caps2slreq, "w")
            for streamId in profile.streams:
                fd.write("%s\n" % streamId)
            fd.close()

            try:
                caps2slstate = os.path.join(seedlink.config_dir, "caps2sl.%s.state" % id)
                # Read existing state file
                fd = open(caps2slstate, "r")
                profile.oldStates = [line.strip() for line in fd.readlines()]
            except:
                pass

        # Delete all existing state files
        for fl in glob.glob(os.path.join(seedlink.config_dir, "caps2sl.*.state")):
            try:
                os.remove(fl)
            except:
                sys.stderr.write("Failed to remove old state file: %s\n" % str(fl))

        # Clean up state file to contain only configured stations
        for id, profile in self.profiles.items():
            caps2slstate = os.path.join(seedlink.config_dir, "caps2sl.%s.state" % id)

            newStates = []

            for (net, sta) in profile.stations:
                for line in profile.oldStates:
                    if line.startswith(net + "." + sta + "."):
                        newStates.append(line)

            if len(newStates) > 0:
                fd = open(caps2slstate, "w")
                for line in newStates:
                    fd.write(line + "\n")
                fd.close()


from tkinter import *
import random
# general set ups
GAME_WIDTH = 850      # window width size
GAME_HEIGHT = 850     # window height size
SPEED = 200           # snake speed set up
SPACE_SIZE = 25       # set space size
BODY_PARTS = 3        # set up snake start body parts
SNAKE_COLOR = "#00FF00"  # set up snake color
FOOD_COLOR = "#FF0000"   # set up food color
BACKGROUND_COLOR = "#000000"   # set background color

class Snake:      # define snake

    def __init__(self):
        self.body_size = BODY_PARTS
        self.coordinates = []                   # coordinates of snake
        self.squares = []

        for i in range(0, BODY_PARTS):
            self.coordinates.append([0, 0])

        for x, y in self.coordinates:
            square = canvas.create_rectangle(x, y, x + SPACE_SIZE,
                                             y + SPACE_SIZE, fill=SNAKE_COLOR,
                                             tag="snake")
            self.squares.append(square)     # to create snake body

class Food:  # define food

    def __init__(self):  # coordinate of food
        x = random.randint(0, (GAME_WIDTH / SPACE_SIZE)-1) * SPACE_SIZE
        y = random.randint(0, (GAME_HEIGHT / SPACE_SIZE) - 1) * SPACE_SIZE

        self.coordinates = [x, y]

        canvas.create_oval(x, y, x + SPACE_SIZE, y + SPACE_SIZE,
                           fill=FOOD_COLOR, tag="food")  # create food

def next_turn(snake, food):  # define snake, food when snake eat or snake move

    x, y = snake.coordinates[0]

    if direction == "up":                               # keep snake move
        y -= SPACE_SIZE

    elif direction == "down":
        y += SPACE_SIZE

    elif direction == "left":
        x -= SPACE_SIZE

    elif direction == "right":
        x += SPACE_SIZE

    snake.coordinates.insert(0, (x, y))

    square = canvas.create_rectangle(x, y, x + SPACE_SIZE,
                                     y + SPACE_SIZE, fill=SNAKE_COLOR)

    snake.squares.insert(0, square)

    if x == food.coordinates[0] and y == food.coordinates[1]:

        global score

        score += 1                          # add score when food been eat

        label.config(text="Score:{}".format(score))

        canvas.delete("food")           # when food been eat delete food

        food = Food()

    else:
        del snake.coordinates[-1]

        canvas.delete(snake.squares[-1])  # when snake crash the wall,game over

        del snake.squares[-1]
    if check_collisions(snake):
        game_over()

    else:
        window.after(SPEED, next_turn, snake, food)

def change_direction(new_direction):            # change directions of snake

    global direction
    if new_direction == 'left':
        if direction != 'right':
            direction = new_direction
    elif new_direction == 'right':
        if direction != 'left':
            direction = new_direction
    elif new_direction == 'up':
        if direction != 'down':
            direction = new_direction
    elif new_direction == 'down':
        if direction != 'up':
            direction = new_direction

def check_collisions(snake):

    x, y = snake.coordinates[0]             # to check if user lose or not

    if x < 0 or x >= GAME_WIDTH:
        return True
    elif y < 0 or y >= GAME_HEIGHT:
        return True

    for body_part in snake.coordinates[1:]:  # when snake crash body game over
        if x == body_part[0] and y == body_part[1]:
            print("GAME OVER")
            return True

    return False

def game_over():
    canvas.delete(ALL)     # when game over, delete window

    canvas.create_text(canvas.winfo_width()/2, canvas.winfo_height()/2,
                       font=('consolas', 70), text="GAME OVER", fill="red",
                       tag="gameover")
window = Tk()
window.title("Snake game")
window.resizable(False, False)                 # create window

score = 0              # count score

direction = 'down'

label = Label(window, text="Score:{}".format(score), font=('consolas', 40))
label.pack()     # window set up

canvas = Canvas(window, bg=BACKGROUND_COLOR,
                height=GAME_HEIGHT, width=GAME_WIDTH)
canvas.pack()

window.update()                                # updating window

window_width = window.winfo_width()
window_height = window.winfo_height()                        # set up screen
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()

x = int((screen_width/2) - (window_width/2))
y = int((screen_height/2) - (screen_height/2))

window.geometry(f"{window_width}x{window_height}+{x}+{y}")

window.bind('<Left>', lambda event: change_direction('left'))
window.bind('<Right>', lambda event: change_direction('right'))
window.bind('<Up>', lambda event: change_direction('up'))  # change direction
window.bind('<Down>', lambda event: change_direction('down'))

snake = Snake()
food = Food()

next_turn(snake, food)

window.mainloop()


def merge(A1,A2, A3):
    i = 0
    j = 0
    while i<len(A1) and j<len(A2):
        if A1[i]<=A2[j]:
            A3.append(A1[i])
            i+=1
        else:
            A3.append(A2[j])
            j+=1
    if i<len(A1):
        for ele in A1[i:]:
            A3.append(ele)
    elif j<len(A2):
        for ele in A2[j:]:
            A3.append(ele)

    return A3

def mergeSort(A,n):
    if n==1:
        return A

    else:
        A1 = mergeSort(A[0:n//2],n//2)
        A2 = mergeSort(A[n//2:], n//2 + n%2)
        A3 = []
        #print(A1,A2)
        return merge(A1,A2,A3)


class Solution:
    """
    @param arrays: k sorted integer arrays
    @return: a sorted array
    """

    def mergekSortedArrays(self, arrays):
        if not arrays:
            return []

        return self.merge_range_arrays(arrays, 0, len(arrays) - 1)

    def merge_range_arrays(self, arrays, left, right):
        if left >= right:
            return arrays[left]

        mid = (left + right) // 2
        sorted_L = self.merge_range_arrays(arrays, left, mid)
        sorted_R = self.merge_range_arrays(arrays, mid + 1, right)
        return self.merge_two_arrays(sorted_L, sorted_R)

    def merge_two_arrays(self, arr_a, arr_b):
        i, j, result = 0, 0, []

        while i < len(arr_a) and j < len(arr_b):
            if arr_a[i] < arr_b[j]:
                result.append(arr_a[i])
                i += 1
            else:
                result.append(arr_b[j])
                j += 1

        while i < len(arr_a):
            result.append(arr_a[i])
            i += 1
        while j < len(arr_b):
            result.append(arr_b[j])
            j += 1

        return result

Sorting/LNT_no486_Merge K Sorted Arrays (merge sort).py


#!/usr/bin/env python
# coding: utf-8

# In[10]:

#Importing libraries
from scipy.spatial import distance as dist
from imutils.video import VideoStream
from imutils import face_utils
from threading import Thread
import numpy as np
import argparse
import imutils
import time
import dlib
import cv2

def eye_aspect_ratio(eye):
    #distance between vertical landmark
    A = dist.euclidean(eye[1], eye[5])
    B = dist.euclidean(eye[2], eye[4])
    #distance between horizintal landmark
    C = dist.euclidean(eye[0], eye[3])
    # Getting average score
    ear = (A+B)/(2.0 * C)
    return ear

def mouth_aspect_ratio(inner):
    #Vertical mouth distance
    A = dist.euclidean(inner[13], inner[19])
    B = dist.euclidean(inner[14], inner[18])
    C = dist.euclidean(inner[15], inner[17])
    #Horizontal mouth dist
    D = dist.euclidean(inner[11], inner[16])
    #getting average score
    mar = (A + B + C)/(3.0 * D)
    return mar

#Setting threshold and readme
EYE_AR_THRESH = 0.2
MOUTH_AR_THRESH = 0.35
EYE_AR_CONSEC_FRAMES = 30
MAR_AR_Counter = 20
counter = 0
yawn_count = 0
yawn_status=False
eye_status=False
yawn_run_status = False

#Load the Face Landmark File and load algorithm
path = 'shape_predictor_68_face_landmarks.dat'
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(path)

#Load the facial landmark points for left eye, right eye and mouth
(lStart, lEnd) = face_utils.FACIAL_LANDMARKS_IDXS["left_eye"]
(rStart, rEnd) = face_utils.FACIAL_LANDMARKS_IDXS["right_eye"]
(iStart, iEnd) = face_utils.FACIAL_LANDMARKS_IDXS["mouth"]

vs = VideoStream(src=0).start()
time.sleep(1.0)

while True:
    prev_yawn_status = yawn_status
    frame = vs.read()
    frame = imutils.resize(frame, width=450)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    rects = detector(gray, 0)

    for rect in rects:
        shape = predictor(gray, rect)
        shape = face_utils.shape_to_np(shape)

        leftEye = shape[lStart:lEnd]
        rightEye = shape[rStart:rEnd]
        inner = shape[iStart:iEnd]

        leftEAR = eye_aspect_ratio(leftEye)
        rightEAR = eye_aspect_ratio(rightEye)
        mouthMAR = mouth_aspect_ratio(inner)

        ear = (leftEAR+rightEAR)/2.0

        leftEyeHull = cv2.convexHull(leftEye)
        rightEyeHull = cv2.convexHull(rightEye)
        innerHull =  cv2.convexHull(inner)

        cv2.drawContours(frame, [leftEyeHull], -1,(0,255,0),1)
        cv2.drawContours(frame, [rightEyeHull], -1,(0,255,0),1)
        cv2.drawContours(frame, [innerHull], -1,(255,255,0),1)

        if mouthMAR>MOUTH_AR_THRESH and yawn_run_status == False:
            yawn_count += 1
            yawn_run_status = True
            if yawn_count>MAR_AR_Counter:
                yawn_status=True
                cv2.putText(frame, "Yawn Alert!!!",(10,70),cv2.FONT_HERSHEY_SIMPLEX,0.7, (0,0,255),2)
        else:
            yawn_run_status = False

        if ear< EYE_AR_THRESH:
            counter += 1
            if counter>=EYE_AR_CONSEC_FRAMES:
                eye_status=True
                cv2.putText(frame,"Drowsiness Alert!!!",(10,30),cv2.FONT_HERSHEY_SIMPLEX,0.7, (0,0,255),2)
        else:
            counter = 0

    cv2.imshow("Frame",frame)
    key = cv2.waitKey(1)&0xFF
    if key== ord("q"):
        break

cv2.destroyAllWindows()
vs.stop()

# In[ ]:


from PyQt5.QtWidgets import *

__all__ = ["launchSaveFileDialog", "launchLoadFileDialog"]

FILE_TYPES = "SysEx Files (*.syx);;All Files (*)"
DEFAULT_EXT = ".syx"

def launchSaveFileDialog(parent):

    options = QFileDialog.Options()
    options |= QFileDialog.DontUseNativeDialog

    dialog = QFileDialog(parent)
    dialog.setOptions(options)
    dialog.setNameFilter(FILE_TYPES)
    dialog.setDefaultSuffix(DEFAULT_EXT)
    dialog.setFileMode(QFileDialog.AnyFile)
    dialog.setAcceptMode(QFileDialog.AcceptSave)
    dialog.fileSelected.connect(parent.saveFileCallback)
    dialog.open()

def launchLoadFileDialog(parent):

    options = QFileDialog.Options()
    options |= QFileDialog.DontUseNativeDialog

    dialog = QFileDialog(parent)
    dialog.setOptions(options)
    dialog.setNameFilter(FILE_TYPES)
    dialog.setDefaultSuffix(DEFAULT_EXT)
    dialog.setFileMode(QFileDialog.ExistingFile)
    dialog.setAcceptMode(QFileDialog.AcceptOpen)
    dialog.fileSelected.connect(parent.loadFileCallback)
    dialog.open()


import pycron
import time
import os
import logging
logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S:')
logger = logging.getLogger()

class CronJobs:

    def __init__(self):
        self.jobs = [
            #{"schedule": '* * * * *', "module": 'test.py'},  # Execute every minute "test.py"
            {"schedule": '0 * * * *', "module": 'spiegelOnlineScraper.py'},  # Execute every hour at x:00
            {"schedule": '15 * * * *', "module": 'weltScraper.py'},  # Execute every hour at x:15
            {"schedule": '30 * * * *', "module": 'FazScraper.py'},  # Execute every hour at x:30
        ]

    def cronInit(self):
        logger.info("CronJobs successfully initiated")
        data_collectors_path = '/usr/src/app/dataCollectors/'
        while True:
            for job in self.jobs:
                if pycron.is_now(job["schedule"]):
                    logger.info("Firing CronJob: " + job["module"])
                    os.system('python3 -u ' + data_collectors_path + job["module"] + '&')
            time.sleep(60)


from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.views import View
from django.shortcuts import get_object_or_404
from django.shortcuts import redirect
from django.views.generic.detail import SingleObjectMixin
from django.views.generic import FormView
from django.urls import reverse
from django.http import HttpResponseForbidden
from . import forms
from questions.forms import QuestionForm
from comments.forms import AnswerCommentForm,QuestionCommentForm
from tags.forms import SelectTagForm
from answers.forms import AnswerForm
from django.views import generic
from questions.models import Question
from tags.models import Tag
from votes.models import QuestionVote
from answers.models import Answer
from braces.views import SelectRelatedMixin
from django.core.urlresolvers import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from django.http import Http404,JsonResponse
from django.contrib.auth import get_user_model
User = get_user_model()

class CreateQuestion(generic.TemplateView,SelectRelatedMixin,LoginRequiredMixin):
    template_name = "questions/create_question.html"

    def get(self, request, *args, **kwargs):
        question_form = QuestionForm(self.request.GET or None)
        select_tag_form = SelectTagForm(self.request.GET or None)
        context = self.get_context_data(**kwargs)
        context['question_form'] = question_form
        context['select_tag_form'] = select_tag_form
        return self.render_to_response(context)

    def post(self, request, *args, **kwargs):
        def add_tag_to_question(request):
            questionform = QuestionForm(request.POST)
            if questionform.is_valid():
                question = questionform.save(commit=False)
                question.user_id = request.user.id
                question.save()
            tagform = SelectTagForm(request.POST)
            if tagform.is_valid():
                tags = tagform.cleaned_data.get('Tags')
                for tag_instance in tags:
                    tag = get_object_or_404(Tag, pk=int(tag_instance))
                    tag.question.add(question)
                    tag.save()
        view = add_tag_to_question(request)
        return redirect('questions:list')

class QuestionList(generic.ListView):
    model = Question
    template_name = 'questions/list.html'

    def get_context_data(self,**kwargs):
        context = super().get_context_data(**kwargs)
        context['question_list'] = super().get_queryset().order_by('-created_at')
        return context

@login_required
def DeleteQuestion(request, **kwargs):
    question = get_object_or_404(Question, pk=kwargs['pk'])
    question.delete()
    if request.is_ajax():
        response_data = {}
        response_data['pk'] = kwargs['pk']
        return JsonResponse(response_data)
    return redirect('questions:list')

class UserQuestions(generic.ListView):
    model = Question
    template_name = "questions/user_questions.html"

    def get_queryset(self):
        try:
            self.question_user = User.objects.prefetch_related("questions").get(username__iexact=self.request.user.username)
        except User.DoesNotExist:
            raise Http404
        else:
            return self.question_user.questions.all()

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["user_questions"] = self.question_user.questions.all().order_by('-created_at')
        return context

class QuestionDetail(View):

    def get(self, request, *args, **kwargs):
        view = QuestionDisplay.as_view()
        return view(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        pk = kwargs['pk']
        def add_answer_to_question(request, pk):
            question = get_object_or_404(Question, pk=pk)
            if request.method == "POST":
                form = AnswerForm(request.POST)
                if form.is_valid():
                    answer = form.save(commit=False)
                    answer.question = question
                    answer.user_id = request.user.id
                    answer.save()
        view = add_answer_to_question(request, pk)
        return redirect('questions:detail', pk=kwargs['pk'])

class QuestionDisplay(generic.DetailView):
    model = Question
    template_name = 'questions/question_detail.html'

    def get_context_data(self, **kwargs):
        context = super(QuestionDisplay, self).get_context_data(**kwargs)
        Q = get_object_or_404(Question, pk=self.kwargs['pk'])
        self.questions_tags = Tag.objects.prefetch_related("question").filter(question=Q)
        self.questions_comments = Question.objects.prefetch_related("question_comment").get(id=Q.pk)
        context['answer_form'] = AnswerForm()
        context['answer_comment_form'] = AnswerCommentForm()
        context['question_comment_form'] = QuestionCommentForm()
        context['questionstags'] = self.questions_tags
        context['question_comments'] = self.questions_comments.question_comment.all()
        return context

def UpVoteQuestion(request, **kwargs):
    # grab our question instance
    question = get_object_or_404(Question, pk=kwargs['pk'])
    # check for a validated user
    if request.user.is_authenticated():
        user = request.user
    # get all question votes this user has made
    users_question_votes = User.objects.prefetch_related('user_question_vote').get(username__iexact=request.user.username)
    # check if the user has voted on this question
    if users_question_votes.user_question_vote.all().filter(question = question).exists():
        # if it does, we set it equal to a nicely named variable
        user_vote_for_this_question = users_question_votes.user_question_vote.all().filter(question = question).get()
        # if the user has upvoted this question
        if user_vote_for_this_question.upvote == True:
            # we return the view with a message that you can only upvote once
            if request.is_ajax():
                response_data = {}
                response_data['pk'] = kwargs['pk']
                response_data['count'] = 0
                return JsonResponse(response_data)
            return redirect('questions:detail', pk=kwargs['pk'])
        # if the user has downvoted this question
        if user_vote_for_this_question.downvote == True:
            # we set downvote to false and upvote to true
            user_vote_for_this_question.upvote = True
            user_vote_for_this_question.downvote = False
            # we save this change in state!!!!!!!
            user_vote_for_this_question.save()
            question.votes += 2
            question.save()
            if request.is_ajax():
                response_data = {}
                response_data['pk'] = kwargs['pk']
                response_data['count'] = 2
                return JsonResponse(response_data)
            return redirect('questions:detail', pk=kwargs['pk'])
    # if they haven't voted on the question yet
    # create a new vote for this question, linked to this user
    new_question_vote = QuestionVote.objects.create_question_vote(user, question)
    new_question_vote.upvote = True
    new_question_vote.save()
    question.votes += 1
    question.save()
    if request.is_ajax():
        response_data = {}
        response_data['pk'] = kwargs['pk']
        response_data['count'] = 1
        return JsonResponse(response_data)
    return redirect('questions:detail', pk=kwargs['pk'])

def DownVoteQuestion(request, **kwargs):
    question = get_object_or_404(Question, pk=kwargs['pk'])
    if request.user.is_authenticated():
        user = request.user
    users_question_votes = User.objects.prefetch_related('user_question_vote').get(username__iexact=request.user.username)
    if users_question_votes.user_question_vote.all().filter(question = question).exists():
        user_vote_for_this_question = users_question_votes.user_question_vote.all().filter(question = question).get()
        if user_vote_for_this_question.downvote == True:
            if request.is_ajax():
                response_data = {}
                response_data['pk'] = kwargs['pk']
                response_data['count'] = 0
                return JsonResponse(response_data)
            return redirect('questions:detail', pk=kwargs['pk'])
        if user_vote_for_this_question.upvote == True:
            user_vote_for_this_question.downvote = True
            user_vote_for_this_question.upvote = False
            user_vote_for_this_question.save()
            question.votes -= 2
            question.save()
            if request.is_ajax():
                response_data = {}
                response_data['pk'] = kwargs['pk']
                response_data['count'] = 2
                return JsonResponse(response_data)
            return redirect('questions:detail', pk=kwargs['pk'])
    new_question_vote = QuestionVote.objects.create_question_vote(user, question)
    new_question_vote.downvote = True
    new_question_vote.save()
    question.votes -= 1
    question.save()
    if request.is_ajax():
        response_data = {}
        response_data['pk'] = kwargs['pk']
        response_data['count'] = 1
        return JsonResponse(response_data)
    return redirect('questions:detail', pk=kwargs['pk'])


#!/usr/bin/python3
'''implements queries to the reddit API.'''

import requests

def recurse(subreddit, hot_list=[]):
    '''prints the titles of the first 10 hot posts listed for a given
       subreddit.
    '''
    base_url = f'https://www.reddit.com/r/{subreddit}/hot/.json'
    headers = {"User-Agent": "linux:0x16.api.advanced:v1.0.0"}
    params = {"limit": 10, "after": after, "count": count}
    r = requests.get(base_url, headers=headers, params=params,
                     allow_redirects=False)
    if r.status_code == 404:
        return None
    result = r.json().get("data")
    after = result.get("after")
    count += result.get("dist")
    for c in result.get("children"):
        hot_list.append(c.get("data").get("title"))

    if after is not None:
        return recurse(subreddit, hot_list=[])
    return hot_list


import sys #, cgitb
# import asyncio
# from qasync import QEventLoop
from dotenv import load_dotenv
from PyQt5.QtWidgets import QApplication

from Modules import RootWindow

load_dotenv('.env')

def except_hook(cls, exception, traceback):
    sys.__excepthook__(cls, exception, traceback)

if __name__ == '__main__':
    # cgitb.enable(format='text')
    sys.excepthook = except_hook

    ## sequential ##
    app = QApplication(sys.argv)
    ex = RootWindow()
    ex.show()
    app.exec_()
    sys.exit()

    # ## async ##
    # app = QApplication(sys.argv)
    # loop = QEventLoop(app)
    # asyncio.set_event_loop(loop)
    # ex = RootWindow()
    # ex.show()
    # loop.run_forever()

    # import cv2
    # from Modules.BusinessLogic.card_detection import detect_video
    # capture = cv2.VideoCapture(0)
    # detect_video(capture, display=True, debug=True, filtering=False)
    # capture.release()


# -*- coding: utf-8 -*-
# @Time    : 2020-10-22 15:53
# @Author  : xiaorui su
# @Email   :  suxiaorui19@mails.ucas.edu.cn
# @File    : ddkg.py
# @Software : PyCharm

from keras.layers import *
from keras.regularizers import l2
from keras.models import Model
from keras import backend as K  # use computable function
from sklearn.metrics import roc_auc_score, accuracy_score, f1_score, precision_recall_curve
import sklearn.metrics as m
from layers import Aggregator
from callbacks import KGCNMetric
import tensorflow as tf
from models.base_model import BaseModel
from keras.layers import Input,LSTM
from yoctol_utils.hash import consistent_hash

class DDKG(BaseModel):

    def __init__(self, config):
        super(DDKG, self).__init__(config)

    def build(self):

        input_drug_one = Input(
            # drug_one id
            shape=(1,), name='input_drug_one',dtype='int64')
        input_drug_two = Input(
            # drug_two_id
            shape=(1,), name='input_drug_two', dtype='int64')

        #embedding container
        entity_embedding = Embedding(input_dim=self.config.entity_vocab_size,
                                     output_dim=self.config.embed_dim,
                                     embeddings_initializer='glorot_normal',
                                     embeddings_regularizer=l2(
                                         self.config.l2_weight),
                                     name='entity_embedding')
        # relation are supposed to feet into a encoder-decoder layer
        relation_embedding = Embedding(input_dim=self.config.relation_vocab_size,
                                       output_dim=self.config.embed_dim,
                                       embeddings_initializer='glorot_normal',
                                       embeddings_regularizer=l2(
                                           self.config.l2_weight),
                                       name='relation_embedding')

        # drug encoder-decoder embedding results
        #match id to smiles
        #original hash embedding
        print("smile")
        ##using layer
        #drug_one_embedding = self.drug_embedding(self.get_hash(input_drug_one))
        drug_hash = Lambda(lambda x: self.get_hash(x),name="get_drug_smile_hash")(input_drug_one) #batch_size,8,64
        drug_one_embedding = Lambda(lambda x: self.drug_embedding(x),name="get_drug_embedding")(drug_hash)

        #get list
        receptive_list_drug_one = Lambda(lambda x: self.get_receptive_field(x),
                                         name='receptive_filed_drug_one')(input_drug_one)
        neineigh_ent_list_drug_one = receptive_list_drug_one[:self.config.n_depth + 1]
        neigh_rel_list_drug_one = receptive_list_drug_one[self.config.n_depth + 1:]

        #get embeded
        neigh_ent_embed_list_drug_one = [entity_embedding(
            neigh_ent) for neigh_ent in neineigh_ent_list_drug_one]
        neigh_rel_embed_list_drug_one = [relation_embedding(
            neigh_rel) for neigh_rel in neigh_rel_list_drug_one]
        neighbor_embedding = Lambda(lambda x: self.get_neighbor_info(x[0], x[1], x[2]),
                                    name='neighbor_embedding_drug_one')

        for depth in range(self.config.n_depth):
            aggregator = Aggregator[self.config.aggregator_type](
                activation='tanh' if depth == self.config.n_depth-1 else 'relu',
                regularizer=l2(self.config.l2_weight),
                name=f'aggregator_{depth+1}_drug_one'
            )

            next_neigh_ent_embed_list_drug_one = []
            for hop in range(self.config.n_depth-depth):
                neighbor_embed = neighbor_embedding([drug_one_embedding, neigh_rel_embed_list_drug_one[hop],
                                                     neigh_ent_embed_list_drug_one[hop + 1]])
                next_entity_embed = aggregator(
                    [neigh_ent_embed_list_drug_one[hop], neighbor_embed])
                next_neigh_ent_embed_list_drug_one.append(next_entity_embed)
            neigh_ent_embed_list_drug_one = next_neigh_ent_embed_list_drug_one

        ###for second drug
        #drug_embedding = self.drug_embedding(self.get_hash(input_drug_two))
        drug_hash = Lambda(lambda x:self.get_hash(x),name='get_drug2_smile_hash')(input_drug_two)#?,8,64
        drug_embedding = Lambda(lambda x: self.drug_embedding(x), name="get_drug2_embedding")(drug_hash)

        # get list
        receptive_list_drug = Lambda(lambda x: self.get_receptive_field(x),
                                         name='receptive_filed_drug_two')(input_drug_two)
        neineigh_ent_list_drug = receptive_list_drug[:self.config.n_depth + 1]
        neigh_rel_list_drug = receptive_list_drug[self.config.n_depth + 1:]

        # get embeded
        neigh_ent_embed_list_drug = [entity_embedding(
            neigh_ent) for neigh_ent in neineigh_ent_list_drug]
        neigh_rel_embed_list_drug = [relation_embedding(
            neigh_rel) for neigh_rel in neigh_rel_list_drug]
        neighbor_embedding = Lambda(lambda x: self.get_neighbor_info(x[0], x[1], x[2]),
                                    name='neighbor_embedding_drug_two')

        for depth in range(self.config.n_depth):
            aggregator = Aggregator[self.config.aggregator_type](
                activation='tanh' if depth == self.config.n_depth - 1 else 'relu',
                regularizer=l2(self.config.l2_weight),
                name=f'aggregator_{depth + 1}_drug'
            )

            next_neigh_ent_embed_list_drug = []
            for hop in range(self.config.n_depth - depth):
                neighbor_embed = neighbor_embedding([drug_embedding, neigh_rel_embed_list_drug[hop],
                                                     neigh_ent_embed_list_drug[hop + 1]])
                next_entity_embed = aggregator(
                    [neigh_ent_embed_list_drug[hop], neighbor_embed])
                next_neigh_ent_embed_list_drug.append(next_entity_embed)
            neigh_ent_embed_list_drug = next_neigh_ent_embed_list_drug

        ##model

        drug1_squeeze_embed = Lambda(lambda x: K.squeeze(
            x, axis=1))(neigh_ent_embed_list_drug_one[0])
        drug2_squeeze_embed = Lambda(lambda x: K.squeeze(
            x, axis=1))(neigh_ent_embed_list_drug[0])
        drug_drug_score = Lambda(
            lambda x: K.sigmoid(K.sum(x[0] * x[1], axis=-1, keepdims=True))
        )([drug1_squeeze_embed, drug2_squeeze_embed])

        model = Model([input_drug_one, input_drug_two], drug_drug_score)
        model.compile(optimizer=self.config.optimizer,
                      loss='binary_crossentropy', metrics=['acc'])
        return model

    def get_hash(self, drugid):

        ##load smile matrix

        drug_smile_matrix =  K.variable(
            self.config.smile_hash, name='smile_hash')

        drug_smile_entity = K.gather(drug_smile_matrix, K.cast(
                drugid, dtype='int64')) #get drug's hash
        print(drug_smile_entity)

        drug_hash_embed = K.reshape(drug_smile_entity, (-1,int(self.config.timestep),int(self.config.latent_dim/self.config.timestep),))#?,8,64

        return drug_hash_embed

    def drug_embedding(self, input_drug):

        ##encoder-decoder
        drug_embed = input_drug
        print(drug_embed)
        encoder = LSTM(self.config.latent_dim, return_state=True)  #64->512
        encoder_outputs, state_h, state_c = encoder(drug_embed)
        print("encoder_outputs")
        print(encoder_outputs) #1,512
        encoder_states = [state_h, state_c]
        # We set up our decoder to return full output sequences,
        # and to return internal states as well. We don't use the
        # return states in the training model, but we will use them in inference.
        encoder_outputs = K.reshape(encoder_outputs,(-1,1,self.config.latent_dim))
        decoder_lstm = LSTM(self.config.latent_dim, return_sequences=True, return_state=True)
        decoder_outputs, _, _ = decoder_lstm(encoder_outputs,
                                             initial_state=encoder_states)
        decoder_outputs = Dense(self.config.embed_dim, activation='softmax')(decoder_outputs)  # drug_emebdding_end

        print("decoder_outputs")
        print(decoder_outputs)

        return decoder_outputs

    def get_receptive_field(self, entity):
        """Calculate receptive field for entity using adjacent matrix

        :param entity: a tensor shaped [batch_size, 1]
        :return: a list of tensor: [[batch_size, 1], [batch_size, neighbor_sample_size],
                                   [batch_size, neighbor_sample_size**2], ...]
        """
        neigh_ent_list = [entity]
        neigh_rel_list = []
        adj_entity_matrix = K.variable(
            self.config.adj_entity, name='adj_entity', dtype='int64')
        adj_relation_matrix = K.variable(self.config.adj_relation, name='adj_relation',
                                         dtype='int64')
        n_neighbor = K.shape(adj_entity_matrix)[1]

        for i in range(self.config.n_depth):
            new_neigh_ent = K.gather(adj_entity_matrix, K.cast(
                neigh_ent_list[-1], dtype='int64'))  # cast function used to transform data type
            new_neigh_rel = K.gather(adj_relation_matrix, K.cast(
                neigh_ent_list[-1], dtype='int64'))
            neigh_ent_list.append(
                K.reshape(new_neigh_ent, (-1, n_neighbor ** (i + 1))))
            neigh_rel_list.append(
                K.reshape(new_neigh_rel, (-1, n_neighbor ** (i + 1))))

        return neigh_ent_list + neigh_rel_list

    def get_neighbor_info(self, drug, rel, ent):
        """Get neighbor representation.

        :param user: a tensor shaped [batch_size, 1, embed_dim]
        :param rel: a tensor shaped [batch_size, neighbor_size ** hop, embed_dim]
        :param ent: a tensor shaped [batch_size, neighbor_size ** hop, embed_dim]
        :return: a tensor shaped [batch_size, neighbor_size ** (hop -1), embed_dim]
        """
        # [batch_size, neighbor_size ** hop, 1] drug-entity score
        drug_rel_score = K.sum(drug * rel, axis=-1, keepdims=True)

        # [batch_size, neighbor_size ** hop, embed_dim]
        ###类似于attention机制
        weighted_ent = drug_rel_score * ent

        # [batch_size, neighbor_size ** (hop-1), neighbor_size, embed_dim]
        weighted_ent = K.reshape(weighted_ent,
                                 (K.shape(weighted_ent)[0], -1,
                                  self.config.neighbor_sample_size, self.config.embed_dim))

        neighbor_embed = K.sum(weighted_ent, axis=2)
        return neighbor_embed

    def add_metrics(self, x_train, y_train, x_valid, y_valid):
        self.callbacks.append(KGCNMetric(x_train, y_train, x_valid, y_valid,
                                         self.config.aggregator_type, self.config.dataset, self.config.K_Fold))

    def fit(self, x_train, y_train, x_valid, y_valid):
        self.callbacks = []
        self.add_metrics(x_train, y_train, x_valid, y_valid)
        self.init_callbacks()

        print('Logging Info - Start training...')
        self.model.fit(x=x_train, y=y_train, batch_size=self.config.batch_size,
                       epochs=self.config.n_epoch, validation_data=(
                           x_valid, y_valid),
                       callbacks=self.callbacks)
        print('Logging Info - training end...')

    def predict(self, x):
        return self.model.predict(x).flatten()

    def score(self, x, y, threshold=0.5):
        y_true = y.flatten()
        y_pred = self.model.predict(x).flatten()
        auc = roc_auc_score(y_true=y_true, y_score=y_pred)
        from sklearn.metrics import roc_curve
        fpr,tpr,thr = roc_curve(y_true=y_true, y_score=y_pred)
        p, r, t = precision_recall_curve(y_true=y_true, probas_pred=y_pred)
        aupr = m.auc(r, p)
        y_pred = [1 if prob >= threshold else 0 for prob in y_pred]
        acc = accuracy_score(y_true=y_true, y_pred=y_pred)
        f1 = f1_score(y_true=y_true, y_pred=y_pred)

        return auc, acc, f1, aupr, fpr.tolist(), tpr.tolist()


import numpy as np

class vent:
    def __init__(self, p1, p2):
        self.p1 = p1
        self.p2 = p2
    def show_points(self):
        print (self.p1, self.p2)
class vent_map:
    def __init__(self):
        self.map = np.array([[0 for i in range(10)] for j in range(10)])
        print(self.map)

input_file = open('example5.txt', 'r')
vents = []

v_map = vent_map()

for l in input_file:
    l = l.split('\n')[0]

    l = l.split(" -> ")
    l = [l[0].split(','), l[1].split(',')]
    v = vent(l[0], l[1])
    vents.append(v)


import sys
import json
import logging

def main():
    logging.basicConfig(format='%(asctime)s [%(levelname)s] %(message)s', datefmt='%Y/%m/%d %H:%M:%S', level=logging.INFO)
    if len(sys.argv) < 2:
        logging.error("Usage: {} path/to/grafana.json".format(sys.argv[0]))
        return 1

    infile = sys.argv[1]
    j = json.load(open(infile))
    panels = j['panels']
    existing_ids = {}

    ok = True

    if j["title"] != "Test-Cluster-TiFlash-Summary":
        ok = False
        logging.error("key={} actual={}".format("title", j["title"]))
    if j["uid"] != "SVbh2xUWk":
        ok = False
        logging.error("key={} actual={}".format("uid", j["uid"]))
    if j["__inputs"][0]["name"] != "DS_TEST-CLUSTER" or j["__inputs"][0]["label"] != "Test-Cluster":
        ok = False
        logging.error("key={} actual={}".format("__inputs", j["__inputs"]))

    for panel in panels:
        ok &= handle_panel(panel, j["title"], existing_ids)
    if not ok:
        logging.error("!!!Error detected!!!")
        return 2
    else:
        logging.info("All checks passed")
        return 0

def handle_panel(panel, parent_title, existing_ids):
    logging.debug('title: {} type: {}'.format(parent_title, panel["type"]))
    if panel["type"] == "row":
        # Check sub panels recursively
        logging.info("Checking panels under row '{}'".format(panel["title"]))
        sub_panels = panel["panels"]
        ok = True
        for p in sub_panels:
            ok &= handle_panel(p, panel["title"], existing_ids)
        logging.info("Check done for panels under row '{}'".format(panel["title"]))
        return ok

    # Check whether there exist duplicate id
    if panel["id"] not in existing_ids:
        existing_ids[panel["id"]] = {
            "panel": panel,
            "parent_title": parent_title,
        }
        return True
    else:
        current_title = panel["title"]
        existing_panel = existing_ids[panel["id"]]
        logging.error("Found duplicated id {}".format(panel["id"]))
        logging.error("Original panel title: '{}' under row '{}'".format(existing_panel["panel"]["title"], existing_panel["parent_title"]))
        logging.error("Duplicate panel title: '{}' under row '{}'".format(current_title, parent_title))
        return False

if __name__ == '__main__':
    sys.exit(main())


def task(n):
    n -= 1
    sum_3 = 3 * (n // 3 * (n // 3 + 1) // 2)
    sum_5 = 5 * (n // 5 * (n // 5 + 1) // 2)
    sum_15 = 15 * (n // 15 * (n // 15 + 1) // 2)
    return sum_3 + sum_5 - sum_15

n = int(input("Введите n: "))
result = task(n)
print(f"Сумма чисел от 1 до {n}, делящихся на 3 или 5: {result}")


def CYKParser(CNF, string):
    S = string.split(" ")
    N = len(S)
    T = [[set([]) for j in range(N)] for i in range(N)]

    for j in range(N):
        for head, body in CNF.items():
            for rule in body:
                if len(rule) == 1 and rule[0] == S[j]:
                    T[j][j].add(head)

        for i in range(j, -1, -1):
            for k in range(i, j):
                for head, body in CNF.items():
                    for rule in body:
                        if len(rule) == 2 and rule[0] in T[i][k] and rule[1] in T[k + 1][j]:
                            T[i][j].add(head)

    return len(T[0][N - 1]) != 0


from rest_framework import serializers
from controleonibus.ionibus.models import Eventos

from django.contrib.auth.models import User

class EventosTaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Eventos
        fields = ['id', 'tipo', 'data_evento', 'circuito', 'parte', 'texto_base', 'owner']

class UserSerializer(serializers.ModelSerializer):
	tasks = serializers.PrimaryKeyRelatedField(many=True, queryset=Eventos.objects.all())

	class Meta:
		model = User
		fields = ('id','username','tasks')


class Solution:
    # ===============================================
    # 2022/02/14
    # Greedy [O(nlogn): 56%]
    def twoCitySchedCost(self, costs: List[List[int]]) -> int:
        print("Code3")
        costs.sort(key = lambda x: x[0] - x[1])
        res = 0
        n = len(costs) // 2
        for i in range(n):
            res += costs[i][0] + costs[i+n][1]
        return res

    # ===============================================
    # 2022/02/14
    # Greedy [O(nlogn): 57%]
    def twoCitySchedCost2(self, costs: List[List[int]]) -> int:
        print("Code2")
        diffCosts = []
        for i, cost in enumerate(costs):
            diff = cost[0] - cost[1]
            if diff >= 0:
                diffCosts.append((diff, i, True))
            else:
                diffCosts.append((-diff, i, False))

        diffCosts.sort(reverse=True)
        res = 0
        count0 = count1 = len(costs) //2
        for i in range(len(costs)):
            if count0 == 0:
                res += costs[diffCosts[i][1]][1]
                count1 -= 1
            elif count1 == 0:
                res += costs[diffCosts[i][1]][0]
                count0 -= 1
            else:
                if diffCosts[i][2]:
                    res += costs[diffCosts[i][1]][1]
                    count1 -= 1
                else:
                    res += costs[diffCosts[i][1]][0]
                    count0 -= 1
        return res

    # ===============================================
    # 2022/02/14
    # DP [O(n2): 5%]
    def twoCitySchedCost1(self, costs: List[List[int]]) -> int:
        print("Code1")
        n = len(costs) // 2
        dp = [ [inf for _ in range(n+1) ] for _ in range(2*n)]

        dp[0][0] = costs[0][1]
        dp[0][1] = costs[0][0]

        for i in range(1, 2*n):
            for j in range(n+1):
                if j == 0:
                    dp[i][j] = dp[i-1][j] + costs[i][1]
                else:
                    dp[i][j] = min(dp[i-1][j-1] + costs[i][0], dp[i-1][j] + costs[i][1])
        return dp[2*n-1][n]


src     = Split('''
        startup.s
        main.c
''')

component = aos_component('mx1101_sdk', src)
component.add_includes('CMSIS/Include', 'O18B_SDK_GCC/MVs_new/MVs18_SDK/Libraries/driver/inc')
component.add_prebuilt_libs('O18B_SDK_GCC/lib/libdriver.a')
aos_global_config.add_ld_files('link.ld')


import json
# JSON (JavaScript Object Notation).

 # indent=4
# x = 10
# x_json = json.dumps(x)

# y = 5.5
# y_json = json.dumps(y)

# m = True
# m_json = json.dumps(m)

# familiya = "alimov"
# familiya_json = json.dumps(familiya)
# ism_json = json.dumps('olimbek')

sonlar = (12, 45, 23, 67)
# sonlar_json = json.dumps(sonlar)

# # python file qaytarish
# son2 = json.loads(sonlar_json)

bemor = {
    "ism": "Alijon Valiyev",
    "yosh": 30,
    "oila": True,
    "farzandlar": ("Ahmad", "Bonu"),
    "allergiya": None,
    "dorilar": [
        {"nomi": "Tremol", "miqdori": 0.5},
        {"nomi": "Panadol", "miqdori": 1.2},
    ],
}

# bemor_json = json.dumps(bemor)
# print(bemor_json)

#yozish
with open("bemor_j.json", "w") as f:
    json.dump(bemor, f)

with open("sonlar_j.json", "w") as f:
    json.dump(sonlar, f)

filename = "bemor_j.json"
with open(filename) as f:
    bemor = json.load(f)
print(bemor)
print(type(bemor))