class Edge:
    def __init__(self,value,begin,end):
        self.value = value
        self.begin = begin
        self.end = end

def solve():
    tmp = input()
    line1 = []
    if tmp.endswith(' '):
        line1 = list(map(int,tmp[0:len(tmp) - 1].split(' ')))
    else:
        line1 = list(map(int,tmp.split(' ')))
    n = line1[0]
    m = line1[1]
    res = -1
    ways = [[100000000 for j in range(n)] for i in range(n)]
    for i in range(m):
        line2 = list(map(int,input().split(' ')))
        if line2[1] > n or line2[0] >n:
            print(5,end='')
            return
        ways[line2[0] -1][line2[1] - 1] = line2[2]
        ways[line2[1] - 1][line2[0] -1] = line2[2]

    edges = []
    low_cost = [100000 for i in range(n)]
    near_vex =[-1 for i in range(n)]
    for i in range(1,n):
        low_cost[i] = ways[0][i]
        near_vex[i] = 0

    mst = Edge

    for i in range(1,n):
        min_cost = 1000000
        v = 0
        for j in range(1,n):
            if near_vex[j] != -1 and low_cost[j] < min_cost:
                v = j
                min_cost = low_cost[j]
        if v > 0:
            mst.value = low_cost[v]
            mst.end = near_vex[v] + 1
            mst.begin = v + 1

            edges.append(mst)
            near_vex[v] = -1
            if min_cost > res:
                res = min_cost

            for j in range(1,n):
                if near_vex[j] != -1 and ways[v][j] < low_cost[j]:
                    low_cost[j] = ways[v][j]
                    near_vex[j] = v
    print(res,end='')

solve()


import logging
import json
import requests

from random import randint
from time import sleep

from django.conf import settings
import lxml.html
from urllib.parse import parse_qs, urlparse, unquote, urlencode

from crawl_engine.spiders.ya_search import YaSearch
from crawl_engine.spiders.rss_spider import RSSFeedParser
from crawl_engine.spiders.search_parser import SearchParser, ParserError

logger = logging.getLogger(__name__)

def xpath_first(item, path):
    """ method for safelly get first element """
    items = item.xpath(path)
    return items[0] if len(items) > 0 else ""

def xpath_first_text(item, path):
    """ method for safelly get first element text_content() """
    item = xpath_first(item, path)
    return item.text_content() if item != "" else ""

class GoogleGeneralParser(SearchParser):
    """
    BAse class for parsing google search results
    """
    def _parse_href(self, href):
        """
        Revise this method
        """
        # Method for normalising Google's result link. Receives the link, parse it and gets the direct
        # url from querystring. E.g.: google's result links look's like:
        # https://www.google.com/url?q=some+query&url=http://foo.bar.url
        # so we should get only q parameter from google's querystring
        try:
            url = parse_qs(urlparse(href).query)['q'][0]
            return unquote(url)
        except KeyError:
            return href

    def _get_tree(self, url, params):
        sleep(randint(1, 2))
        r = requests.get(url, params)
        tree = lxml.html.fromstring(r.text)

        if "Google" not in tree.findtext('.//title'):
            logger.info("I can't find Google in page title")

        return tree

class GoogleParser(GoogleGeneralParser):

    def run(self):
        base_url = 'https://google.com/search'
        result = []
        for count in range(0, self.depth):
            tree = self._get_tree(base_url, {'q': self.search_query, 'start': count * 10, 'sa': 'N'})

            for item in tree.xpath("//div[@class='g']"):
                result.append(self._new_article(
                    self._parse_href(xpath_first(item, ".//a/@href")),
                    xpath_first_text(item, ".//a"),
                    xpath_first_text(item, ".//span[@class='st']")
                ))

        return result

class GoogleScholarParser(GoogleGeneralParser):
    """
    Class for fetching results from google's scholar.google.com.
    Search query example: https://scholar.google.com.ua/scholar?start=30&q=robotics+ai&start=30
    start parameter responsible for results pagination
    :return: seed_links
    """
    def run(self):
        base_url = 'https://scholar.google.com/scholar'
        result = []
        for count in range(0, self.depth):
            tree = self._get_tree(base_url, {'q': self.search_query, 'start': count * 10, 'sa': 'N'})

            for item in tree.xpath("//div[@class='gs_ri']"):
                if (len(item.xpath(".//a/@href")) == 0) or (len(item.xpath(".//div[@class='gs_rs']")) == 0):
                    continue
                result.append(self._new_article(
                    self._parse_href(xpath_first(item, ".//a/@href")),
                    xpath_first_text(item, ".//a"),
                    xpath_first_text(item, ".//div[@class='gs_rs']")
                ))

        return result

class GoogleNewsParser(RSSFeedParser):
    """
    Gets results from google's news.google.com and parses all them by feedparser
    Search query example: https://news.google.com/news/feeds?output=rss&q=banking&num=30.
    num parameter responsible for the number of returned entries (max=30, default=30)
    output parameter responsible for response format (ATOM or RSS)
    :return: seed_links
    """
    def __init__(self, search_query='', depth=1, options={}):
        params = urlencode({'q': search_query, 'output': 'rss', 'num': depth * 10})
        url = 'https://news.google.com/news?%s' % params
        super(GoogleNewsParser, self).__init__(url)

    def _parse_href(self, href):
        """
        Revise this method
        """
        # Method for normalising Google's result link. Receives the link, parse it and gets the direct
        # url from querystring. E.g.: google's result links look's like:
        # https://www.google.com/url?q=some+query&url=http://foo.bar.url
        # so we should get only q parameter from google's querystring
        try:
            url = parse_qs(urlparse(href).query)['url'][0]
            return unquote(url)
        except KeyError:
            return href

    def _new_article(self, url, title, text):
        return super(GoogleNewsParser, self)._new_article(self._parse_href(url), title, text)

class GoogleCseParser(SearchParser):
    """
    Another method for getting google's search results but from CSE (custom search engine):
    https://developers.google.com/custom-search/json-api/v1/using_rest.
    Using Requests library
    :return: seed_links list
    """

    def __init__(self, search_query, depth, options):
        # Check search depth value if it higher than 10
        # redefine it to display only 100 first results
        # see: https://developers.google.com/custom-search/json-api/v1/using_rest
        if depth > 10:
            logger.warn("Only the first 100 results will be displayed, due to CSE search depth limit.")
            depth = 10

        # We store options at JSONField. So we need to load them.
        options = json.loads(options) if options else None

        super(GoogleCseParser, self).__init__(search_query, depth, options)

    def run(self):
        base_url = 'https://www.googleapis.com/customsearch/v1'
        result = []

        for count in range(0, self.depth):
            params = {
                'key': settings.GOOGLE_TRANSLATE_API_KEY,
                'cx': settings.CSE_ID,
                'q': self.search_query,
                'safe': 'medium',
                'start': count * 10 + 1
            }
            if self.options:
                params.update(self.options)

            r = requests.get(base_url, params=params)
            data = json.loads(r.text)
            if 'items' not in data:
                return []

            for item in data['items']:
                result.append(self._new_article(
                    item['link'],
                    item['title'],
                    item['snippet']
                ))

        return result

class GoogleBlogsParser(GoogleGeneralParser):

    def run(self):

        base_url = 'https://google.com/search'
        result = []
        for count in range(0, self.depth):
            tree = self._get_tree(base_url, {'q': self.search_query, 'start': count * 10, 'tbm': 'nws', 'tbs': 'nrt:b'})

            for item in tree.xpath("//div[@class='g']"):
                result.append(self._new_article(
                    self._parse_href(xpath_first(item, ".//a/@href")),
                    xpath_first_text(item, ".//a"),
                    xpath_first_text(item, ".//div[@class='st']")
                ))

        return result

class BingParser(SearchParser):

    def run(self):
        base_url = 'https://www.bing.com/search'
        result = []
        for count in range(0, self.depth):
            r = requests.get(base_url, {'q': self.search_query, 'first': count * 10 + 1})

            tree = lxml.html.fromstring(r.text)

            if "Bing" not in tree.findtext('.//title'):
                logger.info("I can't find Bing in page title")

            for item in tree.xpath("//li[contains(@class, 'b_algo')]"):
                result.append(self._new_article(
                    xpath_first(item, ".//a/@href"),
                    xpath_first_text(item, ".//a"),
                    xpath_first_text(item, ".//p")
                ))

        return result

class YandexParser(SearchParser):

    def run(self):
        search = YaSearch(settings.YANDEX_API_USER, settings.YANDEX_API_KEY, 'com')
        results = search.search(self.search_query)
        if results.error is not None:
            raise ParserError(results.error.description)

        return [self._new_article(i.url, i.title, i.snippet) for i in results.items]

class SocialParser(SearchParser):

    def run(self):
        base_url = 'https://api.social-searcher.com/v2/search'
        r = requests.get(base_url,
                         {'q': self.search_query,
                          'key': settings.SOCIAL_SEARCHER_API_KEY,
                          'limit': self.depth * 10}, verify=False)
        posts = json.loads(r.text).get('posts')
        if posts is None:
            raise ParserError('Social search returned empty result')
        return [self._new_article(
                    post.get('url'),
                    post.get('network') + ' - @' + post.get('user', {}).get('name'),
                    post.get('text'))
                for post in posts]

SEARCH_PARSERS = {
    'google': GoogleParser,
    'google_scholar': GoogleScholarParser,
    'google_news': GoogleNewsParser,
    'google_cse': GoogleCseParser,
    'google_blogs': GoogleBlogsParser,
    'bing': BingParser,
    'yandex': YandexParser,
    'social': SocialParser,
}

def get_search_parser(search_query, engine, depth=5, options=None):
    """ Init serach parser by name """
    if engine not in SEARCH_PARSERS:
        raise NameError('Search engine %s not found' % engine)
    return SEARCH_PARSERS[engine](search_query, depth, options)


print("Loading the Natural Language processor...")
from NLUModule import NLUAnalyser

print("Loading communication software...")
from ASRModule import ASRModuleV1
import OutputModule
from difflib import SequenceMatcher

# Load the ASR module
speech_recogniser = ASRModuleV1

# Load the NlU module
language_analyser = NLUAnalyser

# the main driver class - continously listens for commands
def main():
    # Initiate the output module
    output = OutputModule

    # Start the ASR module
    print("Starting the speech recognition system")
    listen()

    # Continuous listening loop
    # Listen for input from microphone
    # If value is found send to proccessing method

def listen():
    while (True):
        value = speech_recogniser.listen()
        if value != "Null":
            process(value)

def test():
    found_value = speech_recogniser.analyseFile(test_file)
    similarity = str(SequenceMatcher(None, actual_data, found_value).ratio())
    print(similarity)
    process(found_value)

def process(text):
    # print("Proccessing input..." + text)

    # pre process before sendning to be analysed
    # Send to NLU for processing
    model_output = language_analyser.analyse(text)

    print("Intention found: ")
    print(model_output["intent"]["name"])

    print("Instruction set generated: ")
    model_out_copy = model_output.copy()

    print(OutputModule.process(model_out_copy))
    OutputModule.verbally_respond(model_output)
    instruction_set = OutputModule.process(model_output)
    # Send to Output

main()


import numpy as np
import cv2
import cvlib as cv

# Capturing video through webcam
webcam = cv2.VideoCapture(2)

# Start a while loop
while(1):

    # Reading the video from the
    # webcam in image frames
    _, imageFrame = webcam.read()

    imageFrame = cv2.resize(imageFrame, (1020, 600))
    bbox, label, conf = cv.detect_common_objects(imageFrame, enable_gpu=True)

    output_image = cv.object_detection.draw_bbox(imageFrame, bbox, label, conf)

    # Program Termination
    cv2.imshow("Object detection", imageFrame)
    if cv2.waitKey(10) & 0xFF == ord('q'):
        webcam.release()
        cv2.destroyAllWindows()
        break


import solver
import json
import sys
import os

from csvUtils.writer import writeToCsv
from mpl.plotter     import plot

from shapes.logSpiral import *
from shapes.triangle  import *
from shapes.point     import *
from shapes.line      import *

def prettify(d):
    '''Prettifies dictionary'''
    return json.dumps(
        d,
        sort_keys = False,
        indent = 4,
        separators = (
            ',',
            ': '
        )
    )

engine = 'mpl'
if len(sys.argv) > 1:
    if sys.argv[1] == '-manim':
        engine = 'manim'
    elif sys.argv[1] == '-noplot':
        engine = None
    else:
        raise ValueError('Argument should be -manim or -noplot')

f = solver.f

x1, y1, solver.a = map(
    float,
    input("Enter x1, y1 & a\t").split()
)

solver.init = list(map(
    int,
    input('Enter initial values\t').split()
))

assert len(solver.init) == 2 * solver.b, f"Length has to be {2 * b}"
assert 0 < solver.a, "a has to be greater than 0"
assert 0 < solver.b, "b has to be greater than 0"

n = int(input("Enter the number of points\t"))

assert n <= 1400,   "Too Large for computing f(n)"

if engine is not None:
    n1 = int(input("Enter the number of points to plot\t"))

I0 = Point(x1, y1)
I1 = Point(f(0) + x1, y1)
points.append(Point(f(0) + x1, f(1) + y1))
makePoints(n)

lines.append(Line(I0, points[0]))
lines.append(Line(I1, points[1]))
makeLines(n + 1)

T0 = Triangle(
    Line(I0, I1),
    Line(I1, points[0]),
    lines[0]
)
triangles.append(T0)
makeTriangles(n + 1)

print(prettify(
    dict([
        limitizeLine(),
        limitizeTriangle(),
        limitizeLogSpiral(I0, n)
    ])
))

I0.x, I0.y = 0, 0
I1.x, I1.y = f(0), 0
shiftPoints(x1, y1)

if engine is not None:
    if engine == 'mpl':
        plot(n1 - 2, [I0, I1])
    if engine == 'manim':
        writeToCsv(
            [I0, I1] + points,
            lines,
            triangles,
            Spiral()
        )
        os.system(
            f'manim ./manim/allAnim.py {n1} Shapes -pl'
        )


from dataclasses import dataclass, field

from canvasdl.utils.path import Path

from ..utils import config
from .base import Item

@dataclass(order=True)
class Course(Item):
    name: str
    id: str
    video_id: str = None
    drive_name: str = None
    piazza_id: str = None
    websites: dict = field(default_factory=dict)

    @property
    def sort_index(self):
        return -Path.content_path(self.name).size

    @property
    def abbreviation(self):
        removes = ("Topics in", "Introduction to", "and")
        name = self.name
        for r in removes:
            name = name.replace(r, "")
        return "".join(word[0].capitalize() for word in name.split(" ") if word)

    def assignment_name(self, name: str):
        return f"{self.abbreviation}: {name} due"

@dataclass
class Courses:
    courses: list[Course]

    @classmethod
    def from_dict(cls, courses):
        if config.one_course_nr:
            courses = [courses[config.one_course_nr - 1]]
        return Courses(sorted([Course(**c) for c in courses]))


import numpy as np
import sys
from datetime import datetime
import joblib
import torch
from loguru import logger

sys.path.append("../")
# from utils.data import data
from utils.evaluate import evaluate_sklearn
# from utils.evaluate import write_evaluation_result
from utils.config import config

DEVICE = torch.device('cpu')
normal_samples = torch.tensor([])
predict_label_file = "./normal_dataset_predict.label"
wordpress_svm_model = joblib.load('220513-1515_wordpress_albert_svm_joblib.model')

# 读取正常样本
for file in config["datasets"]["wordpress"][5]["albert_file"]:
    normal_samples = torch.cat((normal_samples, torch.load(file, map_location=DEVICE)))
logger.info("[Wordpress] Normal samples count: {}", normal_samples.shape)

# 创建真实标签
actual_label = np.array(len(normal_samples) * [5])
logger.info("Actual labels count: {}", np.shape(actual_label))

# 预测
logger.debug("Predicting ...")
start_time = datetime.now()
predict_label = wordpress_svm_model.predict(normal_samples.detach().numpy()) # 得到预测标签
end_time = datetime.now()
time_diff = end_time - start_time                                            # 时间差
milliseconds = time_diff.seconds * 1000 + time_diff.microseconds / 1000      # 毫秒级时间差
logger.info("Predict time: {} ms, {} s, {} min", milliseconds, time_diff.seconds, time_diff.seconds / 60)

# 保存预测标签
logger.info("Save predict label to file: {}", predict_label_file)
predict_label = np.array(predict_label, dtype=np.int8)
predict_label.tofile(predict_label_file)

# 评估
logger.debug("Evaluating ...")
evaluate_sklearn(predict_label, actual_label, 'test.png')


# Log File:
# /Users/[your name]/Library/Preferences/Ableton/Live 11.2.6
import random

p = {'name': ['kick', 'snare', 'hi-hat'],
     'points': [16, 5, 8],
     'start': [0, 3, 5],
     'size': 32,
     'length': 4}

def polygon(names, points, starts, size):
    return {
        name: list(range(size))
        if num_points == size
        else sorted(
            [start] + random.sample(range(start + 1, size), num_points - 1)
        )
        for name, num_points, start in zip(names, points, starts)
    }

d = polygon(p['name'], p['points'], p['start'], p['size'])

print(d)

print(sorted([2, 7, 4, 9, 1, 5, 3]))
print(random.sample([1, 2, 3, 4, 5, 6, 7], 3))

print(list(range(32)))
animals = ['Bear', 'Python', 'Mouse']
count = [14, 3, 6]

result = zip(animals, count)
print(result)
print(list(result))


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

import json

from flask import Flask, render_template, request

from MatplotCCG import make_plot_plotly

# static_folder = r"/home/Victorus/mysite/"
static_folder = r"C:/Users/Victorus/PycharmProjects/Fixed2/Personal/CCG2/"

app = Flask(__name__, static_folder=static_folder)

@app.route("/", methods=("GET", "POST"), strict_slashes=False)
def home():
    return render_template("home.html")

@app.route("/ccg", methods=("GET", "POST"), strict_slashes=False)
def ccg():
    data = json.load(open(f"{static_folder}cinemas.json", encoding='utf-8'))
    return render_template("grabberSelector.html", cinemas=data)

@app.route("/pattern", methods=("GET", "POST"), strict_slashes=False)
def pattern():
    return render_template("patternMaker.html")

@app.route("/jason", methods=("GET", "POST"), strict_slashes=False)
def jason():
    req_cinema = request.args.get('cinema')
    req_date = request.args.get('date')
    req_chosen = request.args.get('chosen')

    try:
        data = json.load(open(f"{static_folder}screenings/{req_cinema}.json", encoding='utf-8'))[req_date]
    except:
        print('No screenings for selected day')
        data = []

    fig, titles = make_plot_plotly(data, req_chosen)
    fig.update_layout(height=800)
    div = fig.to_html(full_html=False)

    return render_template("grabberPlotter.html", plot_div=div, titles=titles)

if __name__ == "__main__":
    app.secret_key = 'super secret key'
    app.config['SESSION_TYPE'] = 'filesystem'
    app.run()


import heapq

def solution(scoville, K):
    answer = 0
    pq = []
    for s in scoville:
        heapq.heappush(pq, s)

    while(len(pq)!=0):
        data1 = heapq.heappop(pq)
        if(data1 >= K):
            break
        data2 = None
        if(len(pq)!=0):
            data2 = heapq.heappop(pq)
        else:
            return -1
        newScoville = data1 + (data2 * 2)
        heapq.heappush(pq, newScoville)
        answer += 1

    return answer

print(solution([1, 2, 3, 9, 10, 12], 7))


from django.core.validators import MaxValueValidator, MinValueValidator
from django.utils.translation import gettext_lazy as _
from django.core.exceptions import ObjectDoesNotExist
from courses.models import Content
from django.utils import timezone
from django.urls import reverse
from operator import itemgetter
from users.models import User
from django.db import models
import ast

class Exam(models.Model):

    user = models.ForeignKey(User, default=None, on_delete=models.CASCADE)
    content = models.OneToOneField(
        Content, blank=True, null=True, default=None, on_delete=models.SET_DEFAULT
    )
    name = models.CharField(
        ("Exam name"),
        max_length=150,
        unique=False,
        blank=False,
        help_text=("Required. 150 characters or fewer."),
    )
    description = models.TextField()
    approved = models.DecimalField(
        ("minimun points to approved"),
        default=None,
        max_digits=5,
        decimal_places=2,
        validators=[MinValueValidator(0), MaxValueValidator(100)],
        blank=False,
        null=False,
        help_text=(
            "Put here the minimum points necessary to pass this exam. Max 5 digits: 3 for en integer part and 2 for decimal part"
        ),
        error_messages={
            "blank": ("you must provied the minimun points."),
            "null": ("you must provied the minimun points."),
        },
    )
    create_date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return "Quiz: " + self.name

    def save(self, *args, **kwargs):
        questionlistForms = kwargs.pop("questionlist", None)
        if kwargs.pop("update", None):
            Question.objects.filter(exam=self).delete()
        super(Exam, self).save(*args, **kwargs)
        if questionlistForms:
            for questionForm in questionlistForms:
                question_instance = questionForm.save(commit=False)
                question_instance.exam = self
                question_instance.save(
                    answerlist=questionForm.answersForms(),
                    familyInstance={"Exam": self},
                )

    def get_owner(self):
        return self.user.get_full_name()

    def get_questions_instances(self):
        questions = Question.objects.filter(exam=self)
        numbers_of_questions = [index + 1 for index in range(questions.count())]

        return zip(numbers_of_questions, questions)

    def get_take_url(self):
        # return reverse("courses:course-home-week-content", kwargs={'id':self.course.id, 'idModule':self.module.id, 'idContent':self.id})
        # return reverse("exams:exam-take", kwargs={'id':self.content.belongs_to_the_course().id, 'idModule':self.content.belongs_to_the_module().id, 'idContent':self.content.id, 'idExam':self.id})
        return reverse("exams:exam-take", kwargs={"idExam": self.id})

    def get_detail_url(self):
        return reverse("exams:exam-detail", kwargs={"id": self.id})

    def get_edit_url(self):
        return reverse("exams:exam-update", kwargs={"id": self.id})

    def get_delete_url(self):
        return reverse("exams:exam-delete", kwargs={"id": self.id})

    def get_evaluated_url(self):
        return reverse("exams:exam-evaluated", kwargs={"idExam": self.id})

    def evaluate(self, questions):
        if not questions:
            raise "they must provide the questions with their answers to evaluate"
        for question in questions.values():
            question["Answers"] = sorted(question["Answers"], key=itemgetter(0))
        questions_instances = [
            question for _, question in self.get_questions_instances()
        ]
        if len(questions_instances) != len(questions):
            raise "must provide all questions associated with this exam"
        validation = {}
        for question_instance, question in zip(questions_instances, questions.values()):
            validation["Questionid"] = question_instance.id
            answers_instances = question_instance.get_answers_instances()
            if len(answers_instances) != len(question["Answers"]):
                raise "must provide all answers associated with this exam"
            question["validate"] = True
            for answer_instance, answer in zip(answers_instances, question["Answers"]):
                if answer_instance.correct_answer != answer[1]:
                    question["validate"] = False
                    continue
            del question["Answers"]
            question["points"] = (
                float(question_instance.question_value)
                if question["validate"]
                else float(0)
            )
        questions["approved"] = float(self.approved)
        return questions

class Question(models.Model):
    exam = models.ForeignKey(Exam, default=None, on_delete=models.CASCADE)
    question = models.CharField(
        ("question"),
        max_length=600,
        blank=False,
        unique=False,
        help_text=("Required. 600 characters or fewer."),
        error_messages={"unique": ("A question with that name already exists."),},
    )
    correct_answers = models.IntegerField(
        ("number of correct answers for this question"),
        help_text=("number of correct answers for this question"),
        default=0,
    )
    question_value = models.DecimalField(
        ("points"),
        default=None,
        max_digits=5,
        decimal_places=2,
        validators=[MinValueValidator(0), MaxValueValidator(100)],
        help_text=('Max 5 digits: same as "minimun points to approved"'),
        # help_text=('point value of the question. Max 5 digits: 3 for en integer part and 2 for decimal part'),
        blank=False,
        null=False,
        error_messages={
            "blank": ("you must provied the point value."),
            "null": ("you must provied the point value."),
        },
    )

    def __str__(self):
        return "Question: " + self.question

    def save(self, *args, **kwargs):
        answerlistForms = kwargs.pop("answerlist", None)
        familyInstance = kwargs.pop("familyInstance", None)
        super(Question, self).save(*args, **kwargs)
        if answerlistForms:
            for answerForm in answerlistForms:
                answer_instance = answerForm.save(commit=False)
                answer_instance.exam = familyInstance["Exam"]
                answer_instance.question = self
                answer_instance.save()

    def get_answers_instances(self):
        return Answer.objects.filter(question=self)

    def get_altAnswers_instances(self):
        return Answer.objects.filter(question=self).order_by("?")

class Answer(models.Model):
    exam = models.ForeignKey(Exam, default=None, on_delete=models.CASCADE)
    question = models.ForeignKey(Question, default=None, on_delete=models.CASCADE)
    answer = models.CharField(("answer"), max_length=600, blank=False,)
    correct_answer = models.BooleanField(
        default=False, help_text=("the answer is correct?."),
    )

    def __str__(self):
        return "answer for question, " + str(self.question_id)

class ExamUserRelations(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    exam = models.ForeignKey(Exam, on_delete=models.CASCADE)
    user_answer = models.TextField(default=None, blank=True, null=True)
    points = models.DecimalField(
        default=0,
        max_digits=5,
        decimal_places=2,
        validators=[MinValueValidator(0), MaxValueValidator(100)],
    )
    number_of_try = models.IntegerField(
        default=0, validators=[MinValueValidator(0), MaxValueValidator(3)]
    )
    last_try = models.DateTimeField(default=None, blank=True, null=True)

    def __str__(self):
        return self.exam.name + ": " + self.user.get_full_name()

    def can_take_exam(self):
        if self.number_of_try >= 3:
            if self.time().days > 0 or self.time().seconds > (8 * 60 * 60):
                self.number_of_try = 0
                self.save()
                return True
            return False
        return True

    def get_user_answer(self):
        user_answer = ast.literal_eval(self.user_answer)
        del user_answer["approved"]
        for question in user_answer.values():
            question["id"] = int(question["id"])
        return user_answer

    def time(self):
        return timezone.now() - self.last_try

    def time_until_take(self):
        time = (
            timezone.timedelta(days=0, seconds=8 * 60 * 60, microseconds=0)
            - self.time()
        )
        return "%s hour(s) and %s minut(s)" % (
            time.seconds // 3600,
            (time.seconds // 60) % 60,
        )

    def try_exam(self, userQuestions):
        self.number_of_try += 1
        self.last_try = timezone.now()
        self.user_answer = userQuestions
        new_points = 0
        for key, question in userQuestions.items():
            if key != "approved":
                new_points += question["points"]
        if new_points > self.points:
            self.points = new_points
        self.save()


temp=[int(x) for x in input().split(',')]
res=[0]*2

for i in range(1,len(temp)+1):
    if(not(i in temp)):
        res[1]=i
    elif(temp.count(i)>1):
        res[0]=i

print(res)


import random
import math
import ardulight.cdc_rgb_controller as controller
import ardulight.color_utils as color_utils

NUMPIXELS = 20

def lightning(connection, color=color_utils.Colors.white, max_duration=3):
        # count iterations
    i = 0
    # brightness
    b = 100
    last = -1
    thresh = 0.5
    step_size = 5
    time_step = 0.02
    while b > 0 and i < max_duration / time_step:
        n = random.random()

        if last == -1:
            thresh = 0.7
        elif last == 1:
            thresh = 0.4

        if n > thresh:
            b = min(100, b + step_size)
            last = 1
        else:
            last = -1
            b = max(b - step_size, 0)

        connection.write_frame([color_utils.scale_brightness(
            color, b / 100)] * NUMPIXELS)
        connection.sleep_alive(time_step)
        i += 1

        # print(i, b)
    connection.fade_to([color_utils.Colors.black] * NUMPIXELS, duration=0.1)

def present_mtg_colors(connection, colors='wubrg'):
    chosen = colors.lower()
    if len(set('wubrg') | set(chosen)) > 5:
        raise ValueError("Only wubrg allowed.")
    xlat = {
        'w': color_utils.Colors.mtg_white,
        'u': color_utils.Colors.mtg_blue,
        'b': color_utils.Colors.mtg_black,
        'r': color_utils.Colors.mtg_red,
        'g': color_utils.Colors.mtg_green,
    }
    num_repeat = math.ceil(NUMPIXELS / len(chosen))
    frame = [xlat[c] for c in (chosen * num_repeat)[:NUMPIXELS]]
    # connection.write_frame(frame)
    for c in chosen:
        lightning(connection, xlat[c], max_duration=(5 / 2) / len(chosen))

def main():
    global NUMPIXELS
    connection = controller.interactive_choose_serial_device()
    NUMPIXELS = int(input("How many pixels?"))

    # present_mtg_colors(connection, 'bg')
    while True:
        lightning(connection, color=color_utils.randcolor())
    print("done")

if __name__ == '__main__':
    main()


def cal_num(x):
    count = 0
    while x > 0:
        if x%2 == 1:
            count += 1
        else:
            pass
        x = int(x / 2)
    return count

arr = '2、3、5、7、11、13'
prime_nums = [int(i) for i in arr.split('、')]
n = int(input())
for i in range(n):
    arr = input().split()
    l = int(arr[0])
    r = int(arr[1])
    count = 0
    for k in range(l,r+1):
        temp = cal_num(k)
        if temp in prime_nums:
            count += 1
    print(count)


import sys
import os
import time
import pickle
import webbrowser

from PyQt5.QtCore import QPropertyAnimation
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QFileDialog, QMessageBox

import _recognizer as recognizer

# Globals
main_bg = "rgb(7,44,80)"
secondary_bg = "rgb(8,8,82)"
ternary_bg = "rgb(210,48,44)"
sketch = None

# Dialog Box
def dialog_box(ico, title, body):
    dialog = QMessageBox()
    dialog.setWindowTitle(title)
    dialog.setText(body)
    if ico == "error":
        dialog.setIcon(QMessageBox.Critical)
    elif ico == "warn":
        dialog.setIcon(QMessageBox.Warning)
    elif ico == "question":
        dialog.setIcon(QMessageBox.Question)
        dialog.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
    else:
        dialog.setIcon(QMessageBox.Information)
    return dialog.exec_()

# Choose image/ video from explorer
def get_img(vid=0):
    # If video
    if vid:
        source = QFileDialog.getOpenFileName(None, "Select Video", r"C:/")[0]
        if source.split(".")[-1] == "mp4":
            return source
        else:
            dialog_box("error", "Invalid File !", "Please choose a video of .mp4 format only")
            return None
    source = list(QFileDialog.getOpenFileName(None, "Select image", r"C:/"))[0]
    img_format = ["jpg", "jpeg", "png", "jfif", "bmp", "ico"]
    # Error if file is not an Image
    if source.split(".")[-1] not in img_format:
        dialog_box("error", "Invalid File !", "Please choose an image of "
                                              ".jpg, .jpeg, .jfif, .png, .bmp, or .ico format only")
        return None
    return source

# Upload an image into DB
def move_to_database():
    source = get_img()
    if source:
        database = "image_database/"
        if dialog_box("question", "Sure ?", "Do you want to upload your selection?") == 16384:
            if os.path.exists(f"{database}{source.split('/')[-1]}"):
                replace = dialog_box("question", "File already exists!",
                           "The filename that you are trying to upload currently exists in the database."
                           "Would you like to replace it")

                if replace == 16384:
                    try:
                        encodings_file = open("encodings_pickle.txt", "rb")
                        known_encodings_file = pickle.load(encodings_file)
                        encodings_file.close()
                        known_encodings_file.pop(source.split('/')[-1], 0)
                        encodings_file = open("encodings_pickle.txt", "wb")
                        pickle.dump(known_encodings_file, encodings_file)
                        encodings_file.close()
                        source, database = source.replace("/", "\\"), database.replace("/", "\\")
                        error = os.system(f'copy "{source}" "{database}"')
                    except Exception:
                        dialog_box("error", "File not found !",
                                   "Please create a file named 'encodings_pickle.txt' in the application directory")
                        return
                else:
                    return

            else:
                source, database = source.replace("/", "\\"), database.replace("/", "\\")
                error = os.system(f'copy "{source}" "{database}"')

            if not error:
                dialog_box("success", "Success !", "The image has been uploaded into the database successfully")
            else:
                dialog_box("error", "Error !", "There was some error while accessing the database")

    return None

# Upload sketch
def upload_sketch():
    global sketch
    sketch = get_img()
    if sketch:
        dialog_box("success", "Success !", "The Sketch has been uploaded successfully")
    else:
        dialog_box("error", "Failure !", "There was some error while adding the sketch")

# Sketch Recognition
def sketch_recognition(flag):
    if not sketch:
        dialog_box("warn", "No Sketch found !", "Please upload a sketch first")
        return

    print(sketch)
    if flag == "live":
        if dialog_box("question", "Requesting camera access !", "Do you allow the app to open camera?") == 16384:
            recognizer.live_sketch_recognizer(sketch, 0)
        return

    elif flag == "video":
        video = get_img(1)
        if not video:
            return
        location = QFileDialog.getExistingDirectory(None, "Select a folder to save all the Matches", r"C:/")

        if location:
            dialog_box("success", "Processing !", "This may take a while. Please click OK and wait")
            MainWindow.setWindowTitle("Processing --- Please wait ")
            match = recognizer.video_sketch_recognizer(sketch, video, location)
            if match == "no_match" or match == 0:
                dialog_box("success", "No match !", "No match found for the uploaded sketch")
            else:
                dialog_box("success", f"{match} Matches found !", f"All matches are saved in {location}")
            MainWindow.setWindowTitle("Sketch and Emotion Recognition")

    else:
        dialog_box("success", "Processing !", "This may take a while. Please click OK and wait")
        MainWindow.setWindowTitle("Processing --- Please wait ")
        result = recognizer.image_sketch_recognizer(sketch)
        if result == "no_match":
            dialog_box("success", "No match !", "No match found for the uploaded sketch")
        if result == "no_pickle":
            dialog_box("error", "File not found !",
                       "Please create a file named 'encodings_pickle.txt' in the application directory")
        MainWindow.setWindowTitle("Sketch and Emotion Recognition")

# Emotion Recognition
def emotion_recognition(flag):
    if flag == "image":
        dialog_box("success", "Processing !", "This may take a while. Please choose an image and wait")
        MainWindow.setWindowTitle("Processing --- Please wait ")
        recognizer.image_emotion_recognizer(get_img())
        MainWindow.setWindowTitle("Sketch and Emotion Recognition")
    else:
        if dialog_box("question", "Requesting camera access !", "Do you allow the app to open camera?") == 16384:
            recognizer.live_emotion_recognizer()
        return

# Exit Application
def exit_app():
    MainWindow.setWindowTitle("Exiting ---")
    time.sleep(2)
    sys.exit(app.exec_())

# Goto project source
def goto_resources():
    dialog_box("success", "Please wait", "You will be redirected to the project resources shortly")
    try:
        webbrowser.open("https://github.com/presidency-group-8/sketchRecognise")
    except Exception:
        time.sleep(3)
        dialog_box("error", "Something went wrong !", "Sorry we couldn't access your browser. You can visit "
                                                      "https://github.com/presidency-group-8/sketchRecognise "
                                                      "to access resources.")

def goto_page(self, page):
    self.slide_left_panel()
    if page == "home":
        self.stacked_widget.setCurrentWidget(self.home_page)
    if page == "sketch":
        self.stacked_widget.setCurrentWidget(self.sketch_page)
    if page == "emotion":
        self.stacked_widget.setCurrentWidget(self.emotion_page)
    if page == "about":
        self.stacked_widget.setCurrentWidget(self.about_page)

# Main Class
class UserInterface(object):
    # Constructor
    def __init__(self, main_window):
        self.central_widget = QtWidgets.QWidget(main_window)
        self.header = QtWidgets.QFrame(self.central_widget)
        self.body = QtWidgets.QFrame(self.central_widget)

        self.ham_btn = QtWidgets.QPushButton(self.header)
        self.leftPanel = QtWidgets.QFrame(self.body)
        self.panel_animation = QPropertyAnimation(self.leftPanel, b"minimumWidth")
        self.ham_animation = QPropertyAnimation(self.leftPanel, b"styleSheet")
        self.content = QtWidgets.QFrame(self.body)

        self.home_button = QtWidgets.QPushButton(self.leftPanel)
        self.sketch_button = QtWidgets.QPushButton(self.leftPanel)
        self.emotion_button = QtWidgets.QPushButton(self.leftPanel)
        self.about_button = QtWidgets.QPushButton(self.leftPanel)

        self.stacked_widget = QtWidgets.QStackedWidget(self.content)

        self.home_page = QtWidgets.QWidget()
        self.home_head = QtWidgets.QLabel(self.home_page)
        self.home_body = QtWidgets.QLabel(self.home_page)
        self.upload = QtWidgets.QPushButton(self.home_page)
        self.exit_button = QtWidgets.QPushButton(self.home_page)
        self.pixmap = QtGui.QPixmap("static/logo.png")
        self.logo = QtWidgets.QLabel(self.home_page)

        self.sketch_page = QtWidgets.QWidget()
        self.sketch_head = QtWidgets.QLabel(self.sketch_page)
        self.sketch_body = QtWidgets.QLabel(self.sketch_page)
        self.sketch_browse_btn = QtWidgets.QPushButton(self.sketch_page)
        self.sketch_start_btn = QtWidgets.QPushButton(self.sketch_page)
        self.sketch_vid_btn = QtWidgets.QPushButton(self.sketch_page)
        self.sketch_live_btn = QtWidgets.QPushButton(self.sketch_page)

        self.emotion_page = QtWidgets.QWidget()
        self.emotion_head = QtWidgets.QLabel(self.emotion_page)
        self.emotion_body = QtWidgets.QLabel(self.emotion_page)
        self.emotion_browse_btn = QtWidgets.QPushButton(self.emotion_page)
        self.emotion_live_btn = QtWidgets.QPushButton(self.emotion_page)

        self.about_page = QtWidgets.QWidget()
        self.about_head = QtWidgets.QLabel(self.about_page)
        self.about_body = QtWidgets.QLabel(self.about_page)
        self.project_link = QtWidgets.QPushButton(self.about_page)

        self.vertical_layout = QtWidgets.QVBoxLayout(self.central_widget)
        self.horizontal_layout = QtWidgets.QHBoxLayout(self.body)

    # UI Body
    def ui_body(self, main_window):
        # Main window
        main_window.setFixedSize(800, 700)
        main_window.setWindowTitle("Sketch and Emotion Recognition")
        main_window.setObjectName("main_window")
        self.central_widget.setStyleSheet(f"background-color: {main_bg};")
        # Vertical Layout
        self.vertical_layout.setContentsMargins(0, 0, 0, 0)
        self.vertical_layout.setSpacing(0)
        self.vertical_layout.setObjectName("vertical_layout")

        # Header
        self.header.setMaximumSize(QtCore.QSize(16777215, 65))  # width, height
        self.header.setStyleSheet(f"background-color: {main_bg};")
        self.header.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.header.setFrameShadow(QtWidgets.QFrame.Raised)
        self.header.setObjectName("header")
        # Hamburger Button
        self.ham_btn.setGeometry(QtCore.QRect(15, 15, 50, 250))
        self.ham_btn.setStyleSheet("background:url('static/ham1.png') no-repeat; border: none;")
        self.ham_btn.clicked.connect(lambda: self.slide_left_panel())
        self.ham_btn.setObjectName("ham_btn")

        # Body
        self.body.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.body.setFrameShadow(QtWidgets.QFrame.Raised)
        self.body.setObjectName("body")
        # Horizontal Layout
        self.horizontal_layout.setContentsMargins(0, 0, 0, 0)
        self.horizontal_layout.setSpacing(0)
        self.horizontal_layout.setObjectName("horizontal_layout")
        # Left Panel
        self.leftPanel.setMaximumSize(QtCore.QSize(0, 16777215))
        self.leftPanel.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.leftPanel.setFrameShadow(QtWidgets.QFrame.Raised)
        self.leftPanel.setStyleSheet(f"background-color: {secondary_bg}; margin-top: 15px;")
        self.leftPanel.setObjectName("leftPanel")
        # Center of the body
        self.content.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.content.setFrameShadow(QtWidgets.QFrame.Raised)
        self.content.setStyleSheet(f"background-color: {main_bg};")
        self.content.setObjectName("content")

        # Styling for Buttons
        btn_style_1 = f"QPushButton{{" \
                      f"color: rgb(255,255,255); " \
                      f"background-color: {secondary_bg}; " \
                      f"border: none; " \
                      f"outline: none; " \
                      f"border-radius: 5px; font-size: 15px;" \
                      f"}}" \
                      f" QPushButton:hover{{" \
                      f"color: {secondary_bg}; " \
                      f"background-color: rgb(255,255,255);" \
                      f"}}"
        btn_style_2 = f"QPushButton{{" \
                      f"color: rgb(255,255,255); " \
                      f"background-color: {ternary_bg}; " \
                      f"border-radius: 20px; " \
                      f"font-size: 18px" \
                      f"}} " \
                      f"QPushButton:hover{{" \
                      f"color: {ternary_bg}; " \
                      f"background-color: rgb(255,255,255);" \
                      f"}}"

        # Button for HOME PAGE
        self.home_button.setGeometry(QtCore.QRect(10, 70, 95, 60))
        self.home_button.setStyleSheet(btn_style_1)
        self.home_button.setText("Home")
        self.home_button.clicked.connect(lambda: goto_page(self, "home"))
        self.home_button.setObjectName("home_button")
        # Home Page
        self.home_page.setStyleSheet(f"background-color: {main_bg};")
        self.home_page.setObjectName("home_page")
        # Home Head
        self.home_head.setGeometry(QtCore.QRect(90, 10, 610, 55))
        self.home_head.setStyleSheet(f"border:none; font-size:45px; color: rgb(255,255,0); font-variant: small-caps")
        self.home_head.setText("Sketch and Emotion Recognition")
        self.home_head.setObjectName("home_head")
        # Home Body
        self.home_body.setGeometry(QtCore.QRect(90, 80, 750, 200))
        self.home_body.setStyleSheet(f"border:none; font-size:20px; color: rgb(255,255,0);")
        self.home_body.setText("Welcome to Sketch and Emotion recognizer. "
                               "To recognize Sketch\nand Emotion choose from the Hamburger Menu."
                               "\n\nYou can upload an image into the database, upload a sketch to\nrecognize "
                               "or recognize form live cam")
        self.home_body.setObjectName("home_body")
        # Upload Image Button
        self.upload.setGeometry(QtCore.QRect(150, 280, 500, 50))
        self.upload.setStyleSheet(btn_style_2)
        self.upload.setText("UPLOAD AN IMAGE INTO THE DATABASE")
        self.upload.clicked.connect(lambda: move_to_database())
        self.upload.setObjectName("upload")
        # Exit Button
        self.exit_button.setGeometry(QtCore.QRect(150, 350, 500, 50))
        self.exit_button.setStyleSheet(btn_style_2)
        self.exit_button.setText("EXIT THE APPLICATION")
        self.exit_button.clicked.connect(lambda: exit_app())
        self.exit_button.setObjectName("exit_button")
        # Logo
        self.logo.setGeometry(QtCore.QRect(130, 440, 550, 150))
        self.logo.setObjectName("logo")
        self.logo.setPixmap(self.pixmap)

        # Button for SKETCH PAGE
        self.sketch_button.setGeometry(QtCore.QRect(10, 140, 95, 60))
        self.sketch_button.setStyleSheet(btn_style_1)
        self.sketch_button.setText("Sketch\nRecognition")
        self.sketch_button.clicked.connect(lambda: goto_page(self, "sketch"))
        self.sketch_button.setObjectName("sketch_button")
        # Sketch Page
        self.sketch_page.setStyleSheet(f"background-color: {main_bg};")
        self.sketch_page.setObjectName("sketch_page")
        # Sketch Head
        self.sketch_head.setGeometry(QtCore.QRect(90, 10, 571, 55))
        self.sketch_head.setStyleSheet(f"border:none; font-size:45px; color: rgb(255,255,0); font-variant: small-caps")
        self.sketch_head.setText("Sketch Recognition")
        self.sketch_head.setObjectName("sketch_head")
        # Sketch Body
        self.sketch_body.setGeometry(QtCore.QRect(90, 80, 750, 200))
        self.sketch_body.setStyleSheet(f"border:none; font-size:20px; color: rgb(255,255,0);")
        self.sketch_body.setText("Please upload the Sketch first using UPLOAD SKETCH."
                                 "\nTo recognize the person in the sketch use START RECOGNITION."
                                 "\nTo recognize the person in the sketch in a video use VIDEO RECOGNITION."
                                 "\nTo recognize the sketch live use LIVE RECOGNITION.")
        self.sketch_body.setObjectName("sketch_body")
        # Sketch Browse Button
        self.sketch_browse_btn.setGeometry(QtCore.QRect(150, 270, 500, 50))
        self.sketch_browse_btn.setStyleSheet(btn_style_2)
        self.sketch_browse_btn.setText("UPLOAD SKETCH")
        self.sketch_browse_btn.clicked.connect(lambda: upload_sketch())
        self.sketch_browse_btn.setObjectName("sketch_browse_btn")
        # Sketch Start Button
        self.sketch_start_btn.setGeometry(QtCore.QRect(150, 340, 245, 50))
        self.sketch_start_btn.setStyleSheet(btn_style_2)
        self.sketch_start_btn.setText("START RECOGNITION")
        self.sketch_start_btn.clicked.connect(lambda: sketch_recognition("image"))
        self.sketch_start_btn.setObjectName("sketch_start_btn")
        # Sketch Video Button
        self.sketch_vid_btn.setGeometry(QtCore.QRect(400, 340, 245, 50))
        self.sketch_vid_btn.setStyleSheet(btn_style_2)
        self.sketch_vid_btn.setText("VIDEO RECOGNITION")
        self.sketch_vid_btn.clicked.connect(lambda: sketch_recognition("video"))
        self.sketch_vid_btn.setObjectName("sketch_vid_btn")
        # Sketch Live sketch_start_btn
        self.sketch_live_btn.setGeometry(QtCore.QRect(150, 410, 500, 50))
        self.sketch_live_btn.setStyleSheet(btn_style_2)
        self.sketch_live_btn.setText("LIVE RECOGNITION")
        self.sketch_live_btn.clicked.connect(lambda: sketch_recognition("live"))
        self.sketch_live_btn.setObjectName("sketch_live_btn")

        # Button for EMOTION PAGE
        self.emotion_button.setGeometry(QtCore.QRect(10, 210, 95, 60))
        self.emotion_button.setStyleSheet(btn_style_1)
        self.emotion_button.setText("Emotion\nRecognition")
        self.emotion_button.clicked.connect(lambda: goto_page(self, "emotion"))
        self.emotion_button.setObjectName("emotion_button")
        # Emotion Page
        self.emotion_page.setStyleSheet(f"background-color: {main_bg});")
        self.emotion_page.setObjectName("emotion_page")
        # Emotion Head
        self.emotion_head.setGeometry(QtCore.QRect(90, 10, 571, 55))
        self.emotion_head.setStyleSheet(f"border:none; font-size:45px; color: rgb(255,255,0); font-variant: small-caps")
        self.emotion_head.setText("Emotion Recognition")
        self.emotion_head.setObjectName("emotion_head")
        # Emotion Body
        self.emotion_body.setGeometry(QtCore.QRect(90, 80, 750, 200))
        self.emotion_body.setStyleSheet(f"border:none; font-size:20px; color: rgb(255,255,0);")
        self.emotion_body.setText("To recognize the emotion of a Human in an image, click on\nBrowse Image."
                                  "\n\nTo recognize emotions Live, click on LIVE Recognition.\n")
        self.emotion_body.setObjectName("emotion_body")
        # Emotion Browse Button
        self.emotion_browse_btn.setGeometry(QtCore.QRect(150, 280, 500, 50))
        self.emotion_browse_btn.setStyleSheet(btn_style_2)
        self.emotion_browse_btn.setText("BROWSE IMAGE TO RECOGNIZE EMOTION")
        self.emotion_browse_btn.clicked.connect(lambda: emotion_recognition("image"))
        self.emotion_browse_btn.setObjectName("emotion_browse_btn")
        # Emotion Live Button
        self.emotion_live_btn.setGeometry(QtCore.QRect(150, 350, 500, 50))
        self.emotion_live_btn.setStyleSheet(btn_style_2)
        self.emotion_live_btn.setText("LIVE RECOGNITION")
        self.emotion_live_btn.clicked.connect(lambda: emotion_recognition("live"))
        self.emotion_live_btn.setObjectName("emotion_live_btn")

        # Button for ABOUT PAGE
        self.about_button.setGeometry(QtCore.QRect(10, 450, 95, 50))
        self.about_button.setStyleSheet(btn_style_1)
        self.about_button.setText("About")
        self.about_button.clicked.connect(lambda: goto_page(self, "about"))
        self.about_button.setObjectName("about_button")
        # About Page
        self.about_page.setStyleSheet(f"background-color: {main_bg};")
        self.about_page.setObjectName("about_page")
        # About Head
        self.about_head.setGeometry(QtCore.QRect(90, 0, 571, 55))
        self.about_head.setStyleSheet(f"border:none; font-size:45px; color: rgb(255,255,0); font-variant: small-caps;")
        self.about_head.setText("About Us")
        self.about_head.setObjectName("home_head")
        # About Body
        self.about_body.setGeometry(QtCore.QRect(90, 50, 600, 450))
        self.about_body.setStyleSheet(f"border:none; font-size:18px; color: rgb(255,255,0);")
        self.about_body.setText("This application is a University Project developed by "
                                "the Students\nof Presidency University."
                                "\n\nThis application can be used to recognize the Human in a given\nsketch"
                                " and can also be used to recognize the emotion of a Human."
                                "\n\nTo recognize sketch use the SKETCH RECOGNITION menu."
                                "\nTo recognize emotion use the EMOTION RECOGNITION menu."
                                "\n\nThis application is built using OpenCV, DLib, Keras, PyQt."
                                "\n\nAuthors: Prakyath S Arya\n\tPrathyaksh NP\n\tPrajwal Gowda S\n\t"
                                "Pasang Gurung\n\tPreetham CD\nMail: presidency.group8@gmail.com")
        self.about_body.setObjectName("home_body")
        # Link to Project
        self.project_link.setGeometry(QtCore.QRect(90, 490, 300, 50))
        self.project_link.setStyleSheet(btn_style_2)
        self.project_link.setText("Goto to project resources")
        self.project_link.clicked.connect(lambda: goto_resources())
        self.project_link.setObjectName("project_link")

        # Add widgets into Vertical Layout
        self.vertical_layout.addWidget(self.header)
        self.vertical_layout.addWidget(self.body)

        # Add widgets into Horizontal Layout
        self.horizontal_layout.addWidget(self.leftPanel)
        self.horizontal_layout.addWidget(self.content)

        # Add Window into Central Layout
        main_window.setCentralWidget(self.central_widget)

        # Stack Pages
        self.stacked_widget.setGeometry(QtCore.QRect(-1, 9, 1500, 1500))
        self.stacked_widget.setCurrentWidget(self.home_page)
        self.stacked_widget.setObjectName("stacked_widget")
        self.stacked_widget.addWidget(self.home_page)
        self.stacked_widget.addWidget(self.sketch_page)
        self.stacked_widget.addWidget(self.emotion_page)
        self.stacked_widget.addWidget(self.about_page)
        self.stacked_widget.setCurrentIndex(0)

        # Apply everything on Main Window
        QtCore.QMetaObject.connectSlotsByName(main_window)

    # Left Panel Animation
    def slide_left_panel(self):
        width = self.leftPanel.width()
        if width == 0:
            new_width = 110
            style = "background:url('static/ham2.png') no-repeat; border: none;"
        else:
            new_width = 0
            style = "background:url('static/ham1.png') no-repeat; border: none;"
        self.panel_animation.setDuration(600)
        self.panel_animation.setStartValue(width)
        self.panel_animation.setEndValue(new_width)
        self.panel_animation.setEasingCurve(QtCore.QEasingCurve.InOutQuart)
        self.panel_animation.start()
        self.ham_btn.setStyleSheet(style)

if __name__ == "__main__":
    # Create App
    app = QtWidgets.QApplication(sys.argv)

    # Add Icon
    icon = QtGui.QIcon()
    icon.addFile("static/icon.png")
    app.setWindowIcon(icon)

    # Create Main Window
    MainWindow = QtWidgets.QMainWindow()
    # MainWindow.setWindowFlags(QtCore.Qt.FramelessWindowHint)

    # Create UI
    ui = UserInterface(MainWindow)

    # Add UI into Main Window
    ui.ui_body(MainWindow)

    # Display the App
    MainWindow.show()
    sys.exit(app.exec_())


import flask
from ..authenticated_blueprint_preparator import AuthenticatedBlueprintPreparator
from .decorators import rest_endpoint

name = 'confidence'
app = AuthenticatedBlueprintPreparator(name, __name__, template_folder=None)

@app.route('/confidence-values', role=['user', 'visitor'])
@rest_endpoint
def get_confidence_list(c):
    '''
    Get a list of all confidence values.

    @returns        application/json

    Example return value:

      ['false', 'uncertain', 'contested', 'probable', 'certain']

    '''
    c.execute('SELECT unnest(enum_range(NULL::confidence_value));')
    return flask.jsonify(list(map(lambda x: x[0], c.fetchall())))


import unittest

import chainer
import chainer.functions as F
import chainer.links as L
import numpy as np
from ada_loss.chainer_impl.ada_loss_chainer import AdaLossChainer
from chainer import testing

np.random.seed(0)

class AdaLossChainerTest(unittest.TestCase):
    """ Test the AdaLossChainerLinear. """

    def test_element_wise_multiply(self):
        """ Element-wise multiplication """
        ada_loss = AdaLossChainer()

        g = chainer.Variable(np.random.normal(size=(2, 2)).astype("float32"))
        W = chainer.Variable(np.random.normal(size=(2, 2)).astype("float32"))
        r = ada_loss.get_element_wise_multiply(g, W)

        # expected sequence
        self.assertEqual(r[0], g.data[0, 0] * W.data[0, 0])
        self.assertEqual(r[1], g.data[0, 1] * W.data[1, 0])
        self.assertEqual(r[2], g.data[0, 0] * W.data[0, 1])
        self.assertEqual(r[3], g.data[0, 1] * W.data[1, 1])
        self.assertEqual(r[4], g.data[1, 0] * W.data[0, 0])
        self.assertEqual(r[5], g.data[1, 1] * W.data[1, 0])
        self.assertEqual(r[6], g.data[1, 0] * W.data[0, 1])
        self.assertEqual(r[7], g.data[1, 1] * W.data[1, 1])

        # manually insert zeros into g and W
        g.data[0, 0] = 0
        W.data[1, 1] = 0
        r = ada_loss.get_element_wise_multiply(g, W)
        self.assertEqual(len(r), 4)
        r = ada_loss.get_element_wise_multiply(g, W, filter_zero=False)
        self.assertEqual(len(r), 8)

    def test_get_loss_scale_by_element_wise_range(self):
        """ Test how the loss scale works """
        u_max, u_min = 1e3, 1e-3
        ada_loss = AdaLossChainer(u_max=u_max, u_min=u_min)

        g = chainer.Variable(np.random.normal(size=(32, 32)).astype("float32"))
        W = chainer.Variable(np.random.normal(size=(32, 32)).astype("float32"))
        s = ada_loss.get_loss_scale_by_element_wise_range(g, W)

        # no overflow will happen
        self.assertTrue((np.dot(g.array, W.array) * s < u_max).all())

        # will overflow
        g = chainer.Variable(
            np.random.normal(scale=16, size=(32, 32)).astype("float32")
        )
        W = chainer.Variable(
            np.random.normal(scale=16, size=(32, 32)).astype("float32")
        )
        s = ada_loss.get_loss_scale_by_element_wise_range(g, W)

        self.assertLessEqual(s, 1.0)
        # no overflow will happen still
        self.assertTrue((np.dot(g.array, W.array) * s < u_max).all())

    def test_get_prev_scale(self):
        """ Check how prev_scale is implemented.
            Should extract correctly the loss_scale from the previous layer. """
        g = chainer.Variable(np.random.normal(size=1).astype("float32"))
        g.__dict__["loss_scale"] = 2.0

        ada_loss = AdaLossChainer()
        self.assertEqual(ada_loss.get_prev_scale(g), 2.0)

    def test_unscaled_gradient(self):
        """ Check whether the unscaled performs correctly. """
        g_data = np.random.normal(size=16).astype("float32")
        g = chainer.Variable(g_data)

        ada_loss = AdaLossChainer(dtype="float32", debug_level=1)
        ug = ada_loss.get_unscaled_gradient(g, 2.0)
        self.assertTrue(np.allclose(ug.array * 2.0, g_data))

        # float16
        g_data = np.random.normal(size=16).astype("float16") * 100
        g = chainer.Variable(g_data)
        ada_loss = AdaLossChainer(dtype="float16", debug_level=1)
        ug = ada_loss.get_unscaled_gradient(g, np.array(2.0, dtype="float32"))
        self.assertTrue(np.allclose(ug.array * 2.0, g_data))
        # cause overflow
        loss_scale = 1e-6
        with self.assertRaises(ValueError):
            ada_loss.get_unscaled_gradient(g, np.array(loss_scale, dtype="float32"))

    def test_get_scaled_gradient(self):
        """ Test the scaling """
        g = chainer.Variable(np.random.normal(size=1).astype("float32"))
        scale = 2.0

        # NOTE: float32 is necessary
        ada_loss = AdaLossChainer(dtype="float32")
        s_grad = ada_loss.get_scaled_gradient(g, scale)
        self.assertTrue(np.allclose(g.array * 2, s_grad.array))
        self.assertEqual(getattr(s_grad, "loss_scale"), 2.0)

    def test_power_of_two_in_get_loss_scale(self):
        """ Check the switch of power_of_two """
        # turn ON
        dtype = np.float16
        ada_loss = AdaLossChainer(
            dtype=dtype, loss_scale_method="element_wise_range", use_bound=False
        )
        g = chainer.Variable(np.array([[1e-5]], dtype=dtype))
        W = chainer.Variable(np.array([[1e-4]], dtype=dtype))
        s = ada_loss.get_loss_scale(g, W)
        self.assertEqual(s, 32)

        # turn OFF
        ada_loss = AdaLossChainer(
            dtype=dtype,
            loss_scale_method="element_wise_range",
            power_of_two=False,
            use_bound=False,
        )
        g = chainer.Variable(np.array([[1e-5]], dtype=dtype))
        W = chainer.Variable(np.array([[1e-4]], dtype=dtype))
        s = ada_loss.get_loss_scale(g, W)
        self.assertFalse(s == 32)

    def _test_scaled_grad(self, scale_val, dtype, prev_scale):
        g_data = np.random.normal(size=16).astype(dtype)
        g = chainer.Variable(g_data)
        scale = np.array(scale_val, dtype=dtype)

        ada_loss = AdaLossChainer(dtype=dtype)
        sg = ada_loss.get_scaled_gradient(g, scale, prev_scale=prev_scale)

        self.assertTrue(np.allclose(sg.array, g_data * scale_val))
        self.assertEqual(ada_loss.grad_loss_scale(sg), scale_val * prev_scale)

    def test_scaled_gradient(self):
        """ Test how the scaling works. """
        self._test_scaled_grad(2.0, np.float16, 1.0)
        self._test_scaled_grad(2.0, np.float16, 2.0)

        with self.assertRaises(AssertionError):
            self._test_scaled_grad(1e4, np.float16, 1e4)

    # approx method
    def test_get_mean_and_std(self):
        """ """
        dtype = np.float16
        x_data = np.random.normal(size=16).astype(dtype)
        x = chainer.Variable(x_data)
        ada_loss = AdaLossChainer(dtype=dtype)
        mu, sigma = ada_loss.get_mean_and_std(x)

        self.assertTrue(np.allclose(mu, x_data.astype(np.float32).mean()))
        self.assertTrue(np.allclose(sigma, x_data.astype(np.float32).std()))
        self.assertEqual(mu.dtype, np.float32)
        self.assertEqual(sigma.dtype, np.float32)

        # test numerical issue
        ada_loss = AdaLossChainer(dtype=dtype, debug_level=1)
        with self.assertRaises(AssertionError):
            x_data[0] = np.nan
            mu, sigma = ada_loss.get_mean_and_std(x)

    def test_get_mean_and_std_of_product(self):
        dtype = np.float16
        X_data = np.random.normal(size=100, loc=0.1).astype(dtype)
        Y_data = np.random.normal(size=100, loc=0.1).astype(dtype)
        X = chainer.Variable(X_data)
        Y = chainer.Variable(Y_data)

        ada_loss = AdaLossChainer(dtype=dtype)
        mu, sigma = ada_loss.get_mean_and_std_of_product(X, Y)

        X_mu, X_sigma = (
            X_data.astype(np.float32).mean(),
            X_data.astype(np.float32).std(),
        )
        Y_mu, Y_sigma = (
            Y_data.astype(np.float32).mean(),
            Y_data.astype(np.float32).std(),
        )

        self.assertEqual(mu.dtype, np.float32)
        self.assertEqual(sigma.dtype, np.float32)

        print(X_mu * Y_mu)
        print(mu)
        self.assertTrue(np.allclose(X_mu * Y_mu, mu))

        sigma_ = (
            np.sqrt(
                (X_sigma ** 2 + X_mu ** 2) * (Y_sigma ** 2 + Y_mu ** 2)
                - (X_mu * Y_mu) ** 2
            ),
        )
        print(sigma_, sigma)
        self.assertTrue(np.allclose(sigma_, sigma, rtol=1e-3))

    def _test_get_loss_scale_by_approx_range(self, g_sigma, W_sigma, dtype):
        g_data = np.random.normal(scale=g_sigma, size=(32, 32)).astype(dtype)
        W_data = np.random.normal(scale=W_sigma, size=(32, 32)).astype(dtype)
        g = chainer.Variable(g_data)
        W = chainer.Variable(W_data)

        ada_loss = AdaLossChainer(dtype=dtype, debug_level=1)

        scale = ada_loss.get_loss_scale_by_approx_range(g, W)
        self.assertEqual(scale.dtype, ada_loss.full_dtype)

        nnz1 = np.count_nonzero(np.dot(g_data, W_data))
        nnz2 = np.count_nonzero(np.dot(scale * g_data, W_data))
        if scale > 1:  # scaling is effective
            self.assertTrue(nnz1 < nnz2)
            self.assertFalse(np.isinf(np.dot(scale * g_data, W_data)).any())
        elif scale == 1:  # scaling has no effect
            self.assertTrue(nnz1 == nnz2)
        else:  # prevent overflow
            self.assertTrue(np.isinf(np.dot(g_data, W_data)).any())
            self.assertFalse(np.isinf(np.dot(scale * g_data, W_data)).any())

    def test_get_loss_scale_by_approx_range(self):
        """ """
        np.random.seed(0)
        self._test_get_loss_scale_by_approx_range(1e-6, 1e-6, np.float16)
        self._test_get_loss_scale_by_approx_range(1e-3, 1e-3, np.float16)
        self._test_get_loss_scale_by_approx_range(1e-2, 1e-2, np.float16)
        self._test_get_loss_scale_by_approx_range(100, 100, np.float16)
        self._test_get_loss_scale_by_approx_range(10000, 10000, np.float16)

    def test_bound_loss_scale_by_norm(self):
        """ """
        # g_in = np.random.normal(size=(32, 32)).astype(np.float32)
        # W = np.random.normal(size=(32, 32)).astype(np.float32)
        # g_out = np.dot(W, g_in)
        # _, s, _ = np.linalg.svd(W)
        # print(s, np.linalg.norm(W))
        # print(np.linalg.norm(W) * np.linalg.norm(g_in))
        # print(np.linalg.norm(g_in) / np.linalg.norm(np.linalg.inv(W)))
        # print(np.linalg.norm(W) / np.linalg.norm(np.linalg.inv(g_in)))
        # print(np.linalg.norm(g_out))

        # assert False

    def test_bound_loss_scale_by_heuristics(self):
        """ Heuristics testing """

    def test_rescaling(self):
        """ Test the rescaling method """
        # case 1: none scale will cause overflow
        gs = [
            chainer.Variable(np.random.normal(size=16)),
            chainer.Variable(np.random.normal(size=16)),
        ]
        gs[0].__dict__["loss_scale"] = np.float32(1)
        gs[1].__dict__["loss_scale"] = np.float32(2)

        ada_loss = AdaLossChainer()
        gs = ada_loss.rescaling(gs)

        # scale to the larger one
        self.assertEqual(gs[0].__dict__["loss_scale"], 2)

        # case 2: now we have overflow problem
        gs = [
            chainer.Variable(np.random.normal(size=16)),
            chainer.Variable(np.random.normal(size=16)),
        ]
        gs[0].__dict__["loss_scale"] = np.float32(65536)
        gs[1].__dict__["loss_scale"] = np.float32(2)
        gs = ada_loss.rescaling(gs)
        self.assertEqual(gs[0].__dict__["loss_scale"], 2)

testing.run_module(__name__, __file__)


from array import array
import struct
import numpy

label_file=open('labels.txt', 'r')
cost_file=open('mutationEnergiesMin.txt', 'r')
out_file=open('matrices.bin', 'wb')

labels=label_file.readline().split('\t')
costs=[map(float,line.split('\t')[:-1]) for line in cost_file]

numpoints=len(costs[0])
print("numpoints: "+str(numpoints))

numlabels=len(labels)
print("numlabels: "+str(numlabels))

internals=[int(round(costs[i][i])) for i in xrange(len(costs[0]))]
internals[0]=10000
lcosts=[item for item in internals*len(costs[0])]
print("lcosts: "+str(len(lcosts)))

for i in xrange(len(costs)):
	costs[i][i]=0
pairs=array('l', [item for sublist in [[(i,j) for j in xrange(i+1, len(costs[0]))] for i in xrange(len(costs[0]))][:-1] for pair in sublist for item in pair])
print("pairs: "+str(len(pairs)))
print(pairs)

numpairs=len(pairs)/2
print("numpairs: "+str(numpairs))

dist = [0 for i in xrange(numlabels*numlabels)]
for i in xrange(len(costs)):
	for j in xrange(len(costs[i])):
		dist[i*numlabels + j] = int(round(costs[i][j]))
print("dist: "+str(len(dist)))

max_iters=30
print("max_iters: "+str(max_iters))

wcosts=array('l', [1 for i in xrange(numpairs)])

# The input binary file is assumed to contain all the necessary data for
# defining the energy of a discrete MRF.
# More specifically, it should contain the following variables according
# to the order indicated below:
#  *  numpoints
#  *  numlabels
#  *  numpairs
#  *  max_iters
#  *  lcosts
#  *  pairs
#  *  dist
#  *  wcosts

out_file.write(struct.pack('=l', numpoints))
out_file.write(struct.pack('=l', numpairs))
out_file.write(struct.pack('=l', numlabels))
out_file.write(struct.pack('=l', max_iters))
out_file.write(struct.pack('='+'l'*len(lcosts), *lcosts))
out_file.write(struct.pack('='+'l'*len(pairs), *pairs))
out_file.write(struct.pack('='+'l'*len(dist), *dist))
out_file.write(struct.pack('='+'l'*len(wcosts), *wcosts))
out_file.close()


# -*- coding: utf-8 -*-
"""
Created on Fri Jun  8 11:14:24 2018

@author: hp
"""

import cv2
import matplotlib.pyplot as plt

def emptyfunction():
    pass

def main():
    path="C:\\Users\\hp\\Downloads\\forsk ml project\\opencv program\\image\\standard_test_images\\"

    imgpath2=path +"peppers_color.tif"
    imgpath1=path +"mandril_color.tif"

    img1=cv2.imread(imgpath1,1)
    img2=cv2.imread(imgpath2,1)

    #add two images by weight and give blending effect to image
    output=cv2.addWeighted(img1,0.5,img2,0.5,0)
    windowName="Transition Demo"
    cv2.namedWindow(windowName)
    # it only create trackbar on window but doesnot give blending effect
    cv2.createTrackbar('Alpha',windowName,0,100,emptyfunction)

    while True:
        cv2.imshow(windowName,output)
        if cv2.waitKey(1)==27:
            break
        # blending effect provide by this 'trackbarpos'
        alpha=cv2.getTrackbarPos('Alpha',windowName)/100
        beta=1-alpha

        #finally give blending effect to two images
        output=cv2.addWeighted(img1,alpha,img2,beta,0)
        print(alpha,beta)

    cv2.destroyAllWindows()
if __name__=="__main__":
    main()

openCV3 tutorial/opencv13 mini project  trackbar blending app.py


from core_io.pascal_voc_io import XML_EXT
from core_io.pascal_voc_io import PascalVocWriter
from core_io.pascal_voc_io import PascalVocReader
from core_io.yolo_io import YoloReader
from core_io.yolo_io import YOLOWriter
import os.path
import sys

try:
    from PyQt5.QtGui import QImage
except ImportError:
    from PyQt4.QtGui import QImage

# Search all pascal annotation (xml files) in this folder
def voc2yolo(voc_dir):
    for file in os.listdir(voc_dir):
        if file.endswith(".xml"):
            annotation_no_xml = os.path.splitext(file)[0]

            imagePath = voc_dir + "/" + annotation_no_xml + ".jpg"

            image = QImage()
            image.load(imagePath)
            imageShape = [image.height(), image.width(), 1 if image.isGrayscale() else 3]
            imgFolderName = os.path.basename(voc_dir)
            imgFileName = os.path.basename(imagePath)

            writer = YOLOWriter(imgFolderName, imgFileName, imageShape, localImgPath=imagePath)

            # Read classes.txt
            classListPath = voc_dir + "/" + "classes.txt"
            classesFile = open(classListPath, 'r')
            classes = classesFile.read().strip('\n').split('\n')
            classesFile.close()

            # Read VOC file
            filePath = voc_dir + "/" + file
            tVocParseReader = PascalVocReader(filePath)
            shapes = tVocParseReader.getShapes()
            num_of_box = len(shapes)

            for i in range(num_of_box):
                label = classes.index(shapes[i][0])
                xmin = shapes[i][1][0][0]
                ymin = shapes[i][1][0][1]
                x_max = shapes[i][1][2][0]
                y_max = shapes[i][1][2][1]

                writer.addBndBox(xmin, ymin, x_max, y_max, label, 0)

            writer.save(targetFile=voc_dir + "/" + annotation_no_xml + ".txt")

if __name__ == '__main__':
    voc_dir=''
    if voc_dir=='':
        voc_dir = sys.argv[1]
    voc2yolo(voc_dir)


import time
#initialise a previous input variable to 0 (assume button not pressed last)
prev_input = 0
while True:
  #take a reading
  input = GPIO.input(17)
  #if the last reading was low and this one high, print
  if ((not prev_input) and input):
    print("Button pressed")
  #update previous input
  prev_input = input
  #slight pause to debounce
  time.sleep(0.05)


#!/usr/bin/env python3
# Atcoder necoak answer
# https://atcoder.jp/contests/diverta2019/tasks/diverta2019_a
import itertools

intext = input()
[n, k] = map(int, intext.split())

int_list = [v for v in range(1, n+1)]
nk_combis = itertools.combinations(int_list, k)
ans_nk_combis_cnt = 0

for nk_combi in nk_combis:
    # nk_list = list(nk_combi)

    prev_item = None
    is_renzoku = True

    for nk_item in nk_combi:
        if (prev_item != None) and (prev_item + 1 != nk_item):
            is_renzoku = False
            break
        prev_item = nk_item

    if is_renzoku:
        ans_nk_combis_cnt += 1

print(ans_nk_combis_cnt)


class Canape:
    def __init__(self,n=0,t=""):
        self.nbPlaces=n
        self.type=t

    def description(self):
        return "Canape de "+str(self.nbPlaces)+" places, en "+self.type

class Appartement:
    def __init__ (self,c,t):
        self.couleurMur=c
        self.typeSol=t
        self.listeCanapes=[]

    def description(self):
        s="Appartement avec des murs "+self.couleurMur+" et un sol en "+self.typeSol+".\n"
        if (len(self.listeCanapes)==0):
            s+="Sans canape.\n"
        else:
            s+="Avec "+str(len(self.listeCanapes))+" canape(s):\n"
            for canape in self.listeCanapes:
                s+=canape.description()+"\n"
        return s

    def ajoutCanape(self,n=3,t="cuir"):
        self.listeCanapes.append(Canape(n,t))

appart=Appartement("blanc","parquet")
print (appart.description())
appart.couleurMur="rouge"
print (appart.description())
appart.ajoutCanape()
print (appart.description())
appart.ajoutCanape(2,"tissu")
print (appart.description())


import html
from .freshness import Freshness

DOT_GRAPH_TEMPLATE = """\
digraph {{
  layout=dot
  rankdir="LR"
  pad="1"
  // pack/packmode removes edge labels, see https://gitlab.com/graphviz/graphviz/issues/1616
  // re-enable for possibly prettier output if the above issue is solved
  // pack="true"
  // packmode="node"

  // clustered node definitions
{bead_clusters}

  // edges: input links
  edge [headport="w" tailport="e"]
  // edge [weight="100"]
  // edge [labelfloat="true"]
  edge [decorate="true"]

{bead_inputs}
}}
"""

def node_cluster(bead):
    id = bead.name.replace('"', '\\"')
    return f'"cluster_{id}"'

BEAD_COLOR = {
    Freshness.PHANTOM: "red",
    Freshness.SUPERSEDED: "grey",
    Freshness.UP_TO_DATE: "green",
    Freshness.OUT_OF_DATE: "orange",
}

def bead_color(bead):
    return BEAD_COLOR[bead.freshness]

class Port:
    def __init__(self, bead):
        content_id = bead.content_id
        self.input = f"in_{content_id}"
        self.output = f"out_{content_id}"

def dot_cluster_as_fragments(cluster_name, beads, indent='  '):
    assert beads
    # beads are sorted in descending order by freeze_time
    freeze_times = [b.freeze_time for b in beads]
    assert freeze_times == sorted(freeze_times, reverse=True)
    # they have the same name
    assert {bead.name for bead in beads} == {cluster_name}

    label = html.escape(cluster_name)

    yield indent
    yield node_cluster(beads[0])
    yield '[shape="plaintext" color="grey" '
    yield 'label=<
\n'
    yield indent
    yield '
'
    yield '	'
    yield ''
    yield f'{label}'
    yield '	'
    yield '
\n'
    for bead in beads:
        color = f'BGCOLOR="{bead_color(bead)}:none" style="radial"'
        yield indent
        yield '
'
        yield f'	'
        yield f''
        yield f'{bead.freeze_time}'
        yield '	'
        yield '
\n'
    yield indent
    yield '
>'
    yield ']'

class Context:

    def __init__(self):
        self.__unique_node_counter = 0

    def _get_unique_node_id(self):
        """
        Generate unique graphviz dot node ids.
        """
        self.__unique_node_counter += 1
        return f"unique_{self.__unique_node_counter}"

    def dot_edge(self, bead_src, bead_dest, name, is_auxiliary_edge, indent='  '):
        """
        Create an edge with a label in the DOT language between two beads.

        This is more complicated, than one might think,
        because GraphViz's output is unreadable for DAGs with several parallel paths:
        edges are overlapped, producing a messy graph.
        To amend this a conceptual edge is implemented with
        a series of extra nodes and edges between them.
        """
        src = f'{node_cluster(bead_src)}:{Port(bead_src).output}:e'
        dest = f'{node_cluster(bead_dest)}:{Port(bead_dest).input}:w'
        before_label = [src]
        after_label = [dest]
        silent_helper_nodes = []
        color = bead_color(bead_src) if not is_auxiliary_edge else 'grey90'
        label = html.escape(name)

        # add auxiliary nodes before label
        for _ in range(4):
            unique_node = self._get_unique_node_id()
            before_label.append(unique_node)
            silent_helper_nodes.append(unique_node)

        def long_path(nodes):
            if len(nodes) > 1:
                return ' -> '.join(nodes) + f'[color={color}];'
            return ''

        return ''.join(
            [indent]
            + [f'{node}[shape=plain label=""];' for node in silent_helper_nodes]
            + [indent, '\n']
            + [indent, long_path(before_label)]
            + [indent, '\n']
            + [
                indent,
                f'{before_label[-1]} -> {after_label[0]} ',
                '[',
                f'fontcolor="{color}" color="{color}" fontsize="10" label="{label}" weight="100"',
                ']',
                ';'
            ]
            + [indent, '\n']
            + [indent, long_path(after_label)])


from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from .forms import registrationForm
from .models import cust_details
from django.core.urlresolvers import reverse
from django.template import loader, Context
# from django.templatetags.static import static
from django.views import generic
from django.conf import settings
from django.core.files.storage import FileSystemStorage

def display(request):
    # return HttpResponseRedirect("bankWebApp/demo.html")
    t = loader.get_template('bankWebApp/demo.html')
    return HttpResponse(t.render())

def registration(request):
    if request.method == 'POST':

        form = registrationForm(data=request.POST,files=request.FILES)
        # myfile = request.FILES['cust_picture']
        if form.is_valid():
            form.save()
            # cust_account_id =request.POST.get('cust_account_id')
            # cust_name =request.POST.get('cust_name')
            # cust_address =request.POST.get('cust_address')
            # cust_dob =request.POST.get('cust_dob')
            # cust_email =request.POST.get('cust_email')
            # cust_balance =request.POST.get('cust_balance')
            # cust_picture=request.POST.get('cust_picture')
            # print(cust_picture)
            # registrationObj=cust_details(cust_account_id=cust_account_id,cust_name=cust_name,cust_address=cust_address,cust_dob=cust_dob,cust_email=cust_email,cust_balance=cust_balance,cust_picture=cust_picture)
            # registrationObj.save()

            return HttpResponseRedirect(reverse("login"))
        else:
            print(form.errors)
            print("Invalid form")
            # return HttpResponseRedirect(reverse('registration'))
    else:
        form=registrationForm()

    return render(request,"bankWebApp/Form.html", {"form": form})

def login(request):
    t = loader.get_template('bankWebApp/login.html')
    return HttpResponse(t.render())

class DetailView(generic.DetailView):
    model = cust_details
    pk_url_kwarg = 'detail'
    template_name = 'bankWebApp/details.html'

    # /home/monish/WEEK-7[MONISH]/My Banksrcsrc/home/monish/WEEK-7[MONISH]/My Bank/src


import sys

import numpy
from tqdm import tqdm

class NelderMead:
    x_points = None
    y_points = None
    min_element = -1
    max_element = 1
    end_method = 'max_iter'
    end_cond = None
    dim = None
    alpha = 1
    beta = 0.5
    gamma = 2
    func = None
    h_index, g_index, l_index = None, None, None
    x_center = None
    x_reflected = None

    def __init__(self, min_element=-1, max_element=1):
        self.min_element = min_element
        self.max_element = max_element
        self.end_method = 'max_iter'
        self.alpha = 1
        self.beta = 0.5
        self.gamma = 2
        self.method_types = [0, 0, 0, 0]
        self.types_list = []
        self.cost_list = []

    def set_params(self, alpha, beta, gamma):
        self.alpha = alpha
        self.beta = beta
        self.gamma = gamma

    def set_end_method(self, end_method):
        self.end_method = end_method

    def optimize(self, func, dim, end_cond):
        # func - оптимизируемая функция, должна принимать numpy.array соотвесвтующей размерности в качесвте параметра
        # dim - размерность функции
        # end_method - условие останова
        # 'variance' - дисперсия набора значений функции симплкса должна быть меньше end_cond
        # 'max_iter' - остановка при достижении end_cond итераций
        self.func = func
        self.dim = dim
        self.x_points = self.create_points()  # Создаем точки
        self.y_points = numpy.array(list(map(func, self.x_points)))  # Вычисляем значение функции
        # в созданых точках
        if self.end_method == 'max_iter':  # Если условием выхода является достижение некого числа итераций
            for _ in tqdm(range(end_cond)):
                method_type = self.iteration()
                self.types_list.append(method_type)
                self.cost_list.append(numpy.min(self.y_points))
                self.method_types[method_type] += 1

        elif self.end_method == 'variance':  # Условие выхода - дисперсия значений функции не больше заданной величины
            var = end_cond + 1
            while var >= end_cond:
                method_type = self.iteration()
                self.method_types[method_type] += 1
                var = NelderMead.variance(self.y_points)

        else:
            print('Error in end_method param')
            return -1

        _, _, l_index = self.find_points()  # Определяем точку с нименьшим значением функции
        return self.x_points[l_index]

    def iteration(self):
        self.h_index, self.g_index, self.l_index = self.find_points()  # Находим точки h, g и l
        self.x_center = self.calculate_center()  # Вычисляем центр масс
        self.x_reflected = self.calculate_reflected_point()  # Вычисляем отраженную
        # точку
        y_reflected = self.func(self.x_reflected)
        # Далее мы делаем ряд действий, в зависимости от соотношения между значениями функции в найденных точках
        # Объяснять подробно нет смысла, так что смотри просто "Метод Нелдера - Мида" в вики
        if y_reflected < self.y_points[self.l_index]:
            method_type = 0
            x_stretch = self.calculate_stretched_point()
            y_stretch = self.func(x_stretch)
            if y_stretch < self.y_points[self.l_index]:
                self.x_points[self.h_index] = x_stretch
                self.y_points[self.h_index] = y_stretch
            else:
                self.x_points[self.h_index] = self.x_reflected
                self.y_points[self.h_index] = y_reflected

        elif y_reflected <= self.y_points[self.g_index]:
            method_type = 1
            self.x_points[self.h_index] = self.x_reflected
            self.y_points[self.h_index] = y_reflected

        else:
            if y_reflected < self.y_points[self.h_index]:
                self.x_points[self.h_index] = self.x_reflected
                self.y_points[self.h_index] = y_reflected

            x_compress = self.calculate_compressed_point()
            y_compress = self.func(x_compress)
            if y_compress < self.y_points[self.h_index]:
                method_type = 2
                self.x_points[self.h_index] = x_compress
                self.y_points[self.h_index] = y_compress
            else:
                method_type = 3
                self.compress_simplex()
                self.y_points = numpy.array(list(map(self.func, self.x_points)))
        return method_type

    def create_points(self):
        points = []
        for i in range(self.dim + 1):  # Создаем массив точек размера dim + 1 (так требуется по методу)
            points.append(numpy.random.uniform(self.min_element, self.max_element, self.dim))
        return numpy.array(points)

    def find_points(self):
        # В данном методе мы находим три точки: h - точка с наибользим значением оптимизируемой функции,
        # g - следующая за точкой с наибольишм значение, l - с наименьшим значением.
        # Далее мы задаем начальные парамтры...
        h_point = -sys.maxsize
        g_point = -sys.maxsize
        l_point = sys.maxsize
        h_index = 0
        g_index = 0
        l_index = 0
        # ...и проводим стандарнтый поиск.
        for index, item in enumerate(self.y_points):
            if item > h_point:
                g_point = h_point
                h_point = item
                g_index = h_index
                h_index = index
            elif (item > g_point) and (item != h_point):
                g_point = item
                g_index = index
            if item < l_point:
                l_point = item
                l_index = index

        return h_index, g_index, l_index

    def calculate_center(self):
        # Вычисляем "центр масс" всех точек, за исключением h
        sum_data = 0
        n = len(self.x_points) - 1
        for index, item in enumerate(self.x_points):
            if index != self.h_index:
                sum_data += item

        return sum_data / n

    def calculate_reflected_point(self):
        # В данной функции выполняется отражение точки h относительно центра масс
        x_h = self.x_points[self.h_index]
        x_reflected = ((1 + self.alpha) * self.x_center) - (self.alpha * x_h)
        return x_reflected

    def calculate_stretched_point(self):
        # В данной функции выполняется растяжение в направлении, соединяющим h, center и reflected
        x_stretch = (self.gamma * self.x_reflected) + ((1 - self.gamma) * self.x_center)
        return x_stretch

    def calculate_compressed_point(self):
        x_h = self.x_points[self.h_index]
        # В данной функции выполняется сжатие к center
        x_compress = (self.beta * x_h) + ((1 - self.beta) * self.x_center)
        return x_compress

    def compress_simplex(self):
        # В данной функции происходит схатие всего симплекса к l
        x_l = self.x_points[self.l_index]
        for index, x_i in enumerate(self.x_points):
            self.x_points[index] = 0.5 * (x_i + x_l)

    def return_method_types(self):
        return self.method_types

    def return_types_list(self):
        return self.types_list

    def return_cost_list(self):
        return self.cost_list

    @staticmethod
    def average(data):
        # Вычисление среднего значения
        return sum(data) / len(data)

    @staticmethod
    def variance(data):
        # Вычисление дисперсии
        mean_data = NelderMead.average(data)
        sum_var = 0
        for item in data:
            sum_var += (item - mean_data) ** 2
        return sum_var / len(data)


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

import matplotlib.pyplot as pl
import pandas as pd
from math import pi

from pybemt.solver import Solver

s = Solver('tmotor28.ini')

df, sections = s.run_sweep('rpm', 20, 1000.0, 3200.0)

ax = df.plot(x='rpm', y='T')
ax2 = df.plot(x='rpm', y='P')

df_exp = pd.read_csv("tmotor28_data.csv", delimiter=';')

df_exp.plot(x='RPM',y='T(N)',style='o',ax=ax)
pl.figure(1)
pl.ylabel('Thrust (N)')
pl.legend(('BEMT','Experiment'))
df_exp.plot(x='RPM',y='P(W)',style='o',ax=ax2)
pl.figure(2)
pl.ylabel('Power (W)')
pl.legend(('BEMT','Experiment'))

pl.show()


import numpy as np
import cv2

image = cv2.imread("Assets/InputImage.bmp");
w, h = image.shape[:2];

xNew = int(w * 512/ 220);
yNew = int(h * 512 / 260);

xScale = xNew/(w-1);
yScale = yNew/(h-1);

newImage = np.zeros([xNew, yNew, 3]);

for i in range(xNew-1):
   for j in range(yNew-1):
       newImage[i + 1, j + 1]= image[1 + int(i / xScale),1 + int(j / yScale)]

cv2.imwrite('Output/Im_NNI.jpg', newImage)


# This file preps data to be taken by svm and decision tree sorting

import word
import numpy
from csv import writer
import csv
import spacy
import json

PHRASE_LENGTH = 10
nlp = spacy.load("en_core_web_lg")
lemmatizer = nlp.get_pipe("lemmatizer")

chosen_verbs = {"speration":["split","part"], "body_movement":["roll","throw"],"filling":["cover","stuff"]}

#determine the overlapping percentage of two phrases
def phraseOverlap(phrase1, phrase2):
    if (phrase1 == (1000,-1)):
        return 0
    print("obj/subj ", phrase1, "judgedPhrase ", phrase2)
    length = phrase1[1]-phrase1[0] + 1#obj or subj
    #check if outside
    if( phrase1[1] < phrase2[0] ):
        return 0
    elif( phrase1[0] > phrase2[1]):
        return 0
    if( phrase1[0] < phrase2[0] ):
        length2 = (min(phrase1[1],phrase2[1])-phrase2[0]+1)
        if length2 <= 0:
            return 0
        else:
            return length2/length
    elif (phrase1[1] > phrase2[1] ):
        length2 = (max(phrase1[0], phrase2[0])-phrase1[0]+1)
        if length2 <= 0:
            return 0
        else:
            return length2/length

    else:
        return 1

def getPhrase(sentence, outputSetence):
    start,end = -1,-1
    for i in outputSetence:
        if i.token_text == "phraseTag":
            if start == -1:
                start = i.token_index
            else:
                end = i.token_index
    #print(start,end)
    return (start,end-2)

#getting frame of the word
def correctVerb(sentence, verb):
    verbPhrase = ""
    for i in range(verb[0], verb[1] + 1):
        verbPhrase += (sentence[i].token_text + " ")
    doc = nlp(verbPhrase)
    for w in doc:
        if w.lemma_ in chosen_verbs["speration"]:
            return 1
        elif w.lemma_ in chosen_verbs["body_movement"]:
            return 2
        elif w.lemma_ in chosen_verbs["filling"]:
            return 3
    return -1
def getVectors(sentence, phrase):
    i = 0
    sentenceVector = []
    padding = [0] * 303
    for j in range(phrase[0],phrase[1]+1):
        sentenceVector += (sentence[j].embedding + sentence[j].pos)
        i+=1
    while i < PHRASE_LENGTH:
        sentenceVector += padding
        i += 1
    return sentenceVector

def prepData(sentence, verb, outputSentence, subjs, objs, isAgent):
    frame = correctVerb(sentence, verb)
    if (frame == -1):
        return None,None
    else:
        phrase = getPhrase(sentence, outputSentence)
        isSubj = 0
        for subj in subjs:
            isSubj = max(isSubj, phraseOverlap(subj, phrase))
            print("isSubj",isSubj)

        isObj = 0
        #print("this is phrase ", phrase)
        #print("this is objs ", objs)
        for obj in objs:
            isObj = max(isObj, phraseOverlap(obj, phrase))
            print("isObj",isObj)
        if isAgent == "TRUE\n":
            isAgent = 1
        else:
            isAgent = 0
        row = [str(frame),str(isSubj),str(isObj),str(isAgent)]
        with open("data_frame.csv", 'a', newline='') as csvfile:
            csvwriter = csv.writer(csvfile)

            # writing the fields
            csvwriter.writerow(row)
        if phrase[1]-phrase[0]<=PHRASE_LENGTH:
            vec = getVectors(sentence, phrase)
            return vec, isAgent
        return None, None