# This module uses the selenium library to scrape meterological data from
# https://rp5.ru/Weather_archive_in_Kolkata,_Dum_Dum_(airport),_METAR
# with the date given as input
# NOTE: scraping is done in headless mode and requires either Google Chrome
# or Mozilla Firefox installed on the system

import sys, os
root_path = __file__.split('\\')[:-1]
root_path = '\\'.join(root_path)
sys.path.append(os.path.abspath(root_path))

from selenium import webdriver
from selenium.common.exceptions import WebDriverException
import requests
import json

from datetime import datetime, timedelta
import time

class fetcher:
    def __init__(self, browser_path = 'undefined'):
        try:
            options = webdriver.ChromeOptions()
            options.add_argument('-headless')

            driver_path = root_path + '\\chromedriver.exe'
            if browser_path != 'undefined':
                options.binary_location = browser_path
                self.driver = webdriver.Chrome(executable_path = driver_path, options=options)
            else:
                self.driver = webdriver.Chrome(executable_path = driver_path, options=options)
            return
        except WebDriverException:
            pass

        try:
            options = webdriver.FirefoxOptions()
            options.add_argument('-headless')

            driver_path = root_path + '\\geckodriver.exe'
            if browser_path != 'undefined':
                options.binary_location = browser_path
                self.driver = webdriver.Firefox(executable_path = driver_path, options=options)
            else:
                self.driver = webdriver.Firefox(executable_path = driver_path, options=options)
            return
        except WebDriverException:
            pass
        print('Only Google Chrome and Mozilla Firefox is supported')

    def get(self, target_date):
        tdate = target_date
        driver = self.driver
        driver.get('https://rp5.ru/Weather_archive_in_Kolkata,_Dum_Dum_(airport),_METAR')
        time.sleep(0.5)

        driver.find_element_by_xpath('//*[@id="tabMetarArchive"]').click()

        text_field = driver.find_element_by_xpath('//*[@id="calender_archive"]')
       	text_field.clear()
       	text_field.send_keys(tdate)

       	driver.find_element_by_xpath('/html/body/div[4]/div[2]/div[1]/div[2]/div[8]/div[1]/form/table/tbody/tr/td[5]/div').click()
       	time.sleep(0.3)

        t1 = driver.find_elements_by_class_name('cl_rd')
        t2 = driver.find_elements_by_class_name('cl_rd_nt')

        temp = 0
        for e in t1 + t2:
            temp += float(e.text)
        temp = temp / (len(t1) + len(t2))

        p1 = t1 = driver.find_elements_by_class_name('cl')
        p2 = t1 = driver.find_elements_by_class_name('cl_nt')

        ph = []
        for e in p1 + p2:
            try:
                ph.append(float(e.text))
            except ValueError:
                pass

        pressure = 0
        hv = 0
        i = 0
        while i < len(ph):
            if(i % 2 == 0):
                pressure += float(ph[i])
            else:
                hv += float(ph[i])
            i += 1

        pressure /= (len(ph) / 2)
        hv /= (len(ph) / 2)

        rl1 = driver.find_elements_by_class_name('cl_bl')
        rl2 = driver.find_elements_by_class_name('cl_bl_nt')

        rl = rl1 + rl2

        hum = 0
        dt = 0

        i = 0
        while i < len(rl):
            if i % 2 == 0:
                hum += float(rl[i].text)
            else:
                dt += float(rl[i].text)
            i += 1
        hum /= (len(rl) / 2)
        dt /= (len(rl) / 2)

        data_dict = {}
        data_dict['Air Temperature'] = [temp]
        data_dict['Pressure Station Level'] = [pressure]
        data_dict['Relative Humidity'] = [hum]
        data_dict['Horizontal Visibility'] = [hv]
        data_dict['Dew Point Temperature'] = [dt]

        driver.find_element_by_xpath('//*[@id="tabMetarStatist"]').click()
        time.sleep(0.4)

        tf1 = driver.find_element_by_xpath('//*[@id="calender_stat"]')
        tf1.clear()
        tf1.send_keys(tdate)

        tf2 = driver.find_element_by_xpath('//*[@id="calender_stat2"]')
        tf2.clear()
        tf2.send_keys(tdate)

        driver.find_element_by_xpath('/html/body/div[4]/div[2]/div[1]/div[2]/div[10]/div/form/table/tbody/tr[3]/td/div[2]').click()

        driver.find_element_by_xpath('//*[@id="t_statist_synop_wv"]').click()

        data_dict['Wind Speed'] = [driver.find_element_by_xpath('/html/body/div[4]/div[2]/div[1]/div[2]/div[10]/div/div/div[7]/table/tbody/tr[2]/td[2]/div[1]').text]

        d_list = tdate.split('.')
        ob_date = datetime(int(d_list[2]), int(d_list[1]), int(d_list[0]))

        start_date = datetime(ob_date.year, 1, 1)
        one_day_delta = timedelta(days = 1)
        day_no = 0
        while start_date <= ob_date:
            day_no += 1
            start_date += one_day_delta
        data_dict['Day No.'] = [str(day_no)]
        data_dict['Year'] = [str(ob_date.year)]

        r = requests.get("http://emis.wbpcb.gov.in/airquality/JSP/aq/districtwiseReport.jsp")

        post_result = requests.post("http://emis.wbpcb.gov.in/airquality/JSP/aq/fetch_val_ajax.jsp?district=013&date={}&type=districtavg".format(ob_date.strftime('%d/%m/20%y')))
        post_json = json.loads(post_result.text)
        if(post_json['status'] != '0'):
            for val in post_json['list']:
                if(val['pname'] == 'PM10'):
                    data_dict['PM10'] = [val['value'].strip()]
                elif(val['pname'] == 'NO2'):
                    data_dict['NO2'] = [val['value'].strip()]
                elif(val['pname'] == 'SO2'):
                    data_dict['SO2'] = [val['value'].strip()]

        d_prev = ob_date - one_day_delta
        post_result = requests.post("http://emis.wbpcb.gov.in/airquality/JSP/aq/fetch_val_ajax.jsp?district=013&date={}&type=districtavg".format(d_prev.strftime('%d/%m/20%y')))
        post_json = json.loads(post_result.text)
        if(post_json['status'] != '0'):
            for val in post_json['list']:
                if(val['pname'] == 'PM10'):
                    data_dict['D-1 PM10'] = [val['value'].strip()]
                elif(val['pname'] == 'NO2'):
                    data_dict['D-1 NO2'] = [val['value'].strip()]
                elif(val['pname'] == 'SO2'):
                    data_dict['D-1 SO2'] = [val['value'].strip()]
        return data_dict

    def close(self):
        self.driver.close()

# {'Air Temperature': [16.979591836734695],
#  'Pressure Station Level': [763.0775510204081],
#  'Relative Humidity': [75.08163265306122],
#  'Horizontal Visibility': [2.8857142857142866],
#  'Dew Point Temperature': [12.244897959183673],
#  'Day No.': ['21'],
#  'Year': ['2020'],
#  'PM10': ['162.94'],
#  'NO2': ['42.81'],
#  'SO2': ['14.24'],
#  'D-1 PM10': ['180.89'],
#  'D-1 NO2': ['70.19'],
#  'D-1 SO2': ['19.14']}


from ROOT import *

nobs=30
n_asp=15
alpha=0.025

prob=0
for i in range(nobs):
    prob+=TMath.PoissonI(i,n_asp)

prob=1-prob
print("p-value={}".format(prob))
if prob<alpha:
    print("Ipotesi nulla rigettata")

n=0
while True:
    prob=0
    for i in range(nobs):
        prob+=TMath.PoissonI(i,n_asp+n)

    if prob<alpha:
        print("Upper limit al 95% di confidence level è {}".format(n-1))
        break

    n+=1

n=0
while True:
    prob=0
    for i in range(nobs):
        prob+=TMath.PoissonI(i,n_asp+n)

    if 1-prob>alpha:
        print("Lower limit al 95% di confidence level è {}".format(n-1))
        break

    n+=1

gApplication.Run(True)


import re

pattern = re.compile(r"(.+) bags contain (.*)")
pattern2 = re.compile(r"(\d+) (.*?) bag[s]?")

bags = {}

for l in open("input"):
    res = pattern.search(l)
    color, contents = res.groups()
    res2 = pattern2.findall(res.groups()[1])
    bags[color] = dict((color, int(count)) for count, color in res2)

def contains(color, bags):
    possible_bags = set()
    for c, sub_colors in bags.items():
        if color in sub_colors.keys():
            possible_bags.add(c)
            possible_bags = possible_bags.union(contains(c, bags))
    return possible_bags

print(len(contains("shiny gold", bags)))

def total_bags(color, bags):
    total = 0
    for c, num in bags[color].items():
        total += num + num * total_bags(c, bags)
    return total

print(total_bags("shiny gold", bags))


#!/usr/bin/env python3
import os
from PyInquirer import style_from_dict, Token, prompt, Separator
from clint.textui import puts, colored

def softwareChooser(categories, ID,  message):
	choices = []

	for j in categories:
		choices.append(Separator("\n== " + j.capitalize() + " =="))

		for s in categories[j]:
			choices.append({
				'name': s["display_name"].lower().capitalize()
			})

	questions = [
	    {
		'type': 'checkbox',
		'message': message,
		'name': ID,
		'choices': choices,
		'validate': lambda answer: 'You must choose at least one program.' \
		    if len(answer) == 0 else True
	    }
	]

	return questions

def swCategoryChooser(names, ID,  message):
	choices = []
	choices.append(Separator("\n== Categories =="))

	for i in names:
		choices.append({'name': i.capitalize()})

	questions = [
	    {
		'type': 'checkbox',
		'message': message,
		'name': ID,
		'choices': choices,
		'validate': lambda answer: 'You must choose at least one program.' \
		    if len(answer) == 0 else True
	    }
	]

	return questions

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

#		MAIN FUNCTION HERE

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

def installMenu(sw, style):

	if(len(sw) == 0):
		print(colored.red("[X] There isn't any supported software at the moment..."))
		print(colored.red(" -  Nothing will be installed"))
		return False

	avaiableSoftware = sw
	categories = []

	try:
		for key in avaiableSoftware:
			categories.append(key)

	except:
		pass

	answ = prompt(swCategoryChooser(categories,  "categories",  "Which categories are u interested in?"), style=style)

	# GET THE LIST OF PROGRAMS FROM SELECTED CATEGORIES
	choosenCategories = {}
	for i in answ["categories"]:
		key = i.lower()
		choosenCategories[key] = avaiableSoftware[key]

	# ASK FOR SPECIFIC SOFTWARE
	answ = prompt(softwareChooser(choosenCategories, "software", "Which software do u wanna install?"), style=style)

	software = []
	swHash = {}
	for key in avaiableSoftware:
		for s in avaiableSoftware[key]:
			value = s["display_name"].lower().capitalize()
			swHash[value] = s

	for s in answ["software"]:
		software.append(swHash[s])

	return software


"""empty message

Revision ID: 7daad4519c97
Revises:
Create Date: 2021-11-28 19:55:54.895960

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '7daad4519c97'
down_revision = None
branch_labels = None
depends_on = None

def upgrade():
    """
    importance
    due date
    urgency
    affects reputation
    amortized cost (e.g. test environment)
    estimated seconds
    unknowns
    waiting (follow-up?)
    """
    op.create_table(
        'task',
        sa.Column('id', sa.Integer, primary_key=True),
        sa.Column('title', sa.Text, nullable=False),
        sa.Column('description', sa.Text),
        sa.Column('importance', sa.SmallInteger),
        sa.Column('due_time', sa.DateTime),
        sa.Column('urgency', sa.SmallInteger),
        sa.Column('reputation', sa.SmallInteger),
        sa.Column('amortized_cost', sa.SmallInteger),
        sa.Column('estimated_seconds', sa.Interval),
        sa.Column('unknowns', sa.Text),
        sa.Column('waiting', sa.Text, default=None),
    )

def downgrade():
    op.drop_table('task')


'''
 rmtoo
   Free and Open Source Requirements Management Tool

 Command line parameter handling.

 (c) 2011 by flonatel GmhH & Co. KG

 For licensing details see COPYING
'''

from optparse import OptionParser

class CmdLineParams:
    '''Utility class for handling the old style command line
       parameters (like -f, -m and -c) as well as the new
       command line parameters.'''

    def __init__(self):
        '''Utility class with 'hidden' constructor'''
        assert(False)

    @staticmethod
    def initialize_parser():
        '''Initializases the command line parser.'''
        return OptionParser()

    @staticmethod
    def add_deprecated_parameters(parser):
        '''Add the deprecated parameters to the given option parser.'''
        parser.add_option("-f", "--file-config", dest="config_file",
                          help="Configuration file")
        parser.add_option("-m", "--modules-directory", dest="modules_directory",
                          help="Directory with modules")
        parser.add_option("-c", "--create-makefile-dependencies",
                          dest="create_makefile_dependencies",
                          help="Create makefile dependencies")

    @staticmethod
    def add_deprecated_values(options):
        '''Add all the values to the dictionary which were specified
           with the help of the old and deprecated command line options.'''
        ldict = {}

        if options.config_file != None:
            ldict['configuration'] = {'deprecated':
                                      {'config_file': options.config_file }}

        if options.modules_directory != None:
            ldict['global'] = {'modules': {'directories':
                                           [options.modules_directory]}}
        else:
            # If there is no modules directory given, use the pyshared one.
            ldict['global'] = {'modules': {'directories':
                                           ["/usr/share/pyshared"]}}

        if options.create_makefile_dependencies != None:
            ldict['actions'] = {'create_makefile_dependencies':
                                options.create_makefile_dependencies }

        return ldict

    @staticmethod
    def add_parameters(parser):
        '''Add the command line parameters to the given parser.'''
        parser.add_option("-j", "--json", dest="json",
                          action="append",
                          help="JSON string or file which is merged into the "
                          "existing configuration. Can be specified multiple "
                          "times.")

    @staticmethod
    def add_values(options):
        '''Add all the new command line parameter values.'''
        if options.json == None:
            return {}

        jopts = []
        for jopt in options.json:
            if jopt.startswith("file://"):
                jopts.append(jopt)
            elif jopt.startswith("json:"):
                jopts.append(jopt)
            else:
                jopts.append("json:" + jopt)
        return {'configuration': {'json': jopts }}

    @staticmethod
    def add_args(args):
        '''Add the arguments to the configuration.'''
        if args == None or args == []:
            return {}
        return {'general': {'command_line_arguments': args}}

    @staticmethod
    def create_dicts(args):
        '''Creates a dictionary from all the command line parameters.'''
        parser = CmdLineParams.initialize_parser()
        CmdLineParams.add_deprecated_parameters(parser)
        CmdLineParams.add_parameters(parser)

        (options, args) = parser.parse_args(args=args)

        lresult = []
        lresult.append(CmdLineParams.add_args(args))
        lresult.append(CmdLineParams.add_deprecated_values(options))
        lresult.append(CmdLineParams.add_values(options))
        return lresult


#! /usr/bin/env python

"""This is a Python file."""

import os
import unittest
import processing

__author__ = "Nick Pascucci (npascut1@gmail.com)"

TEST_FILE = "portal.wav"

class WaveTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.wave = processing.Wave()
        cls.wave.load(TEST_FILE)

    def setUp(self):
        self.wave1 = processing.Wave()
        self.wave2 = processing.Wave()
        self.wave1.audio = range(11)
        self.wave2.audio = range(10, 0, -1)
        self.wave1.frames = 10
        self.wave2.frames = 10

    def tearDown(self):
        pass

    def test_load(self):
        assert self.wave.channels == 2
        assert self.wave.sample_width == 2
        assert self.wave.sample_rate == 44100
        assert self.wave.frames == 967680
        assert len(self.wave.audio) == 2 * self.wave.frames # Two channels
        for frame in self.wave.audio:
            assert (frame.channel == 0 or frame.channel == 1)
        assert self.wave.max_amplitude > 0

    def test_normalize(self):
        old_max = self.wave.max_amplitude
        self.wave.normalize()
        new_max = self.wave.max_amplitude
        assert new_max > old_max

    def test_get_max_val(self):
        assert processing._get_max_value(1) == 255
        assert processing._get_max_value(2) == 32767

    def test_add(self):
        self.wave1 += self.wave2
        for frame in self.wave1.audio:
            assert frame == 10

    def test_raises_error_if_waves_differ(self):
        self.wave1.sample_width = 32
        self.wave2.sample_width = 16
        with self.assertRaises(processing.FormatError):
            self.wave1 += self.wave2

    def test_slice(self):
        w1_slice = self.wave1[2:5]
        assert w1_slice == range(2, 5)

    def test_set_and_get_item(self):
        self.wave1[3] = 4
        assert self.wave1[3] == 4

    # This test is being ignored, because while the two files may differ,
    # the saved file is still playable. The difference might be due to
    # additional metadata stored by Audacity.
    def ign_test_save(self):
        self.wave.save("test.wav")
        f1 = open(TEST_FILE)
        f2 = open("test.wav")
        data1 = f1.read()
        data2 = f2.read()
        f1.close()
        f2.close()
        os.remove("test.wav")
        assert data1 == data2

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


from pathlib import Path
import json

import numpy as np
from seal import Ciphertext

from .participant import Participant

class Server(Participant):

    def __init__(self):
        super().__init__()
        self._fence = None
        self._flag_is_left = None
        self._flag_dy = None

    @property
    def fence(self):
        return self._fence

    @fence.setter
    def fence(self, fence):
        self._fence = fence

    def load_fence(self, file_path):
        """ import coordinates from file
            Args:
              file_path -- file path
                example .txt file:
                    59.4048184072506,17.9478923473923
                    59.4043815528131,17.9485360775559
                    59.404422508156,17.9486433659165
                example .json file can be created at http://geo.jasparke.net/
                    [
                        {
                            "name": "sics",
                            "color": "#6CB1E1",
                            "id": 0,
                            "path": [[59.4048182070281, 17.9478945561005],
                                    [59.4043772570510, 17.9485382862641],
                                    [59.4046025108524, 17.9491310544564],
                                    [59.4046598479445, 17.949050588186],]
                        }
                    ]
            Returns:
                name of the site from .json files or "site" as default for .txt files
                geo coordinates of the vertices [[lat0, lon0], [lat1, lon1], ...]
            """
        try:
            with open(file_path) as file:
                if Path(file_path).suffix == '.json':
                    data = json.load(file)[0]
                    self.fence = data.get('path')
                elif Path(file_path).suffix == '.txt':
                    lines = file.readlines()
                    self.fence = []
                    for line in lines:
                        self.fence.append([float(x) for x in line.strip().split(',')])
                else:
                    raise ValueError("File type not supported")
        except FileNotFoundError:
            raise
        except ValueError:
            raise

    # def get_parms(self):
    #     return self._parms

    # def load_parms(self, path: str, print_parms=False):
    #     super().load_parms(path, print_parms)

    def compute_intermediate(self, cipher_point):
        assert self.fence is not None, "Geo fence not set"
        assert self._context is not None, "Parameters not set"
        y, x = cipher_point
        vertices = self.fence
        num = len(vertices)

        latitudes = np.array([vertices[i][0] for i in range(num)])
        longitudes = np.array([vertices[i][1] for i in range(num)])

        dx = self.sub_array_with_c(longitudes, x)
        dy = self.sub_array_with_c(latitudes, y)

        is_left = self.compute_is_left(dx, dy)

        return is_left, dy

    def sub_array_with_c(self, arr, cipher):
        """
        Utility function for compute differentials dx and dy
        :param arr: Numpy array
        :param cipher: Integer in Ciphertext
        :return: array of ciphertext of (cipher-arr)
        """
        num = len(arr)
        delta = np.empty(num, Ciphertext)
        for i in range(num):
            c = Ciphertext()
            self._evaluator.sub_plain(cipher, self._encoder.encode(arr[i]), c)
            delta[i] = c
        return delta

    def compute_is_left(self, dx, dy):
        """
        Compute is_left = dx[i]*dy[j] - dx[j]*dy[i]
        # >0 left, wn++ if direction up
        # =0 line, wn does not change
        # <0 right, wn-- if direction down
        :param dx: Array of Ciphertext
        :param dy: Array of Ciphertext
        :return: Arry of Ciphertext is_left
        """
        assert len(dx) == len(dy)
        num = len(dx)
        is_left = np.empty(num, Ciphertext)
        for i in range(num):
            j = (i + 1) % num
            c1 = Ciphertext()
            c2 = Ciphertext()
            self._evaluator.multiply(dx[i], dy[j], c1)
            self._evaluator.multiply(dx[j], dy[i], c2)
            self._evaluator.sub_inplace(c1, c2)
            is_left[i] = c1
        return is_left

    def masking(self, cipher_arr):
        """
        Mask the cipher_arr with a sign change
        :param cipher_arr: the cipher_arr to mask
        :return: masked cipher_arr
        """
        num = len(cipher_arr)
        flag = np.random.choice([-1, 1], num)

        for i in range(num):
            self._evaluator.multiply_plain_inplace(cipher_arr[i], self._encoder.encode(flag[i]))
        return flag, cipher_arr

    def demasking(self, flag, arr):
        """
        Demask the arr masked with the flag that was used to mask the cipher array
        :param flag: Array of integers in {-1, 1}, same length as cipher_arr
        :param arr: Numpy array to demask
        :return: demasked arr
        """
        assert len(flag) == len(arr), "Flag and the cipher array must have the same length"
        return flag * arr

    def detect_inclusion(self, is_left_p, dy_p, is_left_flag=None, dy_flag=None):
        if (type(is_left_flag) is np.ndarray) and (type(dy_flag) is np.ndarray):
            assert len(is_left_flag) == len(dy_flag), "Length of the flag arrays must match"
            assert len(is_left_p) == len(is_left_flag) or len(dy_p) == len(dy_flag), \
                "Length of arrays must match"
            is_left_p = is_left_p * is_left_flag
            dy_p = dy_p * dy_flag

        wn = self.compute_wn(is_left_p, dy_p)
        return wn != 0

    # noinspection DuplicatedCode
    @staticmethod
    def compute_wn(is_left_p, dy_p):
        dy_p_next = np.roll(dy_p, -1)
        clockwise = (dy_p <= 0) * (dy_p_next > 0) * np.sign(is_left_p)
        countercl = (dy_p > 0) * (dy_p_next <= 0) * np.sign(is_left_p)

        wn = np.sum(clockwise) + np.sum(countercl)
        return wn


from django.shortcuts import render
from django.shortcuts import redirect
from django.utils import timezone
from django.http import HttpResponse
from django.http import JsonResponse
from django.template import RequestContext
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from kv_messages.models import Message

# Create your views here.

def message_listing(request):
	if request.method == 'POST':
		new_message = Message()
		new_message.uname = request.user
		new_message.umessage = request.POST.get('comment')
		new_message.created_datetime = timezone.now()
		new_message.save()
	kv_messages = Message.objects.all().order_by('-id')
	page_number = request.GET.get('page')
	paginator = Paginator(kv_messages, 10)
	try:
		kv_messages = paginator.page(page_number)
	except PageNotAnInteger:
		kv_messages = paginator.page(1)
	except EmptyPage:
		kv_messages = paginator.page(paginator.num_pages)
	context = {'kv_messages': kv_messages}
	return render(request, 'kv_messages/wall.html', context)

def message_details(request, message_id):
	kv_message = Message.objects.get(pk=message_id)
	context = {'kv_message': kv_message}
	return render(request, 'kv_messages/details.html', context)

def give_thumbs_up(request, message_id):
	kv_message = Message.objects.get(pk=message_id)
	kv_message.thumbs_up = kv_message.thumbs_up+1
	kv_message.save()
	data = {'thumbs_up': kv_message.thumbs_up}
	return JsonResponse(data)


import pyautogui as pg  # type: ignore[import]

from ark.exceptions import ServerNotFoundError
from ark.server.server import Server

from .._ark import Ark

class SessionList(Ark):
    """Represents the main menu Session List in Ark.

    Provides the ability to rejoin a specific server.
    """

    _FILTERS = {"Official Servers": (369, 863), "Favorites": (373, 925)}
    _SESSION_LIST_REGION = (110, 100, 230, 80)
    _TOP_SERVER_REGION = (90, 200, 430, 90)
    _JOINING_FAILED = (712, 354, 486, 76)

    def refresh(self) -> None:
        """Clicks the refresh button"""
        self.click_at(1229, 941, delay=0.5)

    def join_server(self) -> None:
        self.click_at(990, 943, delay=0.5)

    def open(self) -> None:
        while not self.is_open():
            self.click_at(117, 528, delay=0.5)
            self.sleep(2)

    def connect(self, server: Server) -> None:
        """Joins the given server by the servers search name attribute.

        Parameters:
        ----------
        server :class:`Server`:
            The server to join as a Server object.
        """
        try:
            self.search_server(server)
        except ServerNotFoundError:
            print("Failed to find the server after 15min!")

        while self.is_open():
            self.join_server()
            self.sleep(45)

            if not self._server_is_ghosting():
                continue

            self.sleep(300)
            self.connect(server)

    def search_server(self, server: Server) -> None:
        """Searches for the given server, waits for it to pop up.

        Parameters:
        ----------
        server :class:`Server`:
            The server to search for as a Server object.
        """
        self.click_at(616, 143, delay=0.5)
        with pg.hold("ctrl"):
            pg.press("a")
            pg.press("backspace")

        pg.typewrite(server.name, interval=0.01)
        self.press("enter")
        self.sleep(5)

        # attempt to find the server up to 30 times, waiting 30 seconds each time.
        # after each 30 seconds the session list is refreshed
        attempts = 0
        for _ in range(30):
            count = 0
            while not self.server_found():
                self.sleep(1)
                count += 1

                if count > 30:
                    attempts += 1
                    self.refresh()
                    break
            else:
                self.click_at(959, 237, delay=0.5)
                return

        raise ServerNotFoundError(f"Failed to find {server.name}!")

    def is_open(self) -> bool:
        """Checks if the session list menu is open"""
        return (
            self.window.locate_template(
                f"{self.PKG_DIR}/assets/interfaces/session_list.png",
                region=self._SESSION_LIST_REGION,
                confidence=0.8,
            )
            is not None
        )

    def server_found(self) -> bool:
        """Checks if the favorited server has been found"""
        return (
            self.window.locate_template(
                f"{self.PKG_DIR}/assets/interfaces/server_favorite.png",
                region=self._TOP_SERVER_REGION,
                confidence=0.75,
            )
            is not None
        )

    def _server_is_ghosting(self) -> bool:
        return (
            self.window.locate_template(
                f"{self.PKG_DIR}/assets/interfaces/joining_failed.png",
                region=self._JOINING_FAILED,
                confidence=0.7,
            )
            is not None
        )


import numpy as np
from time import time
t0 = time()

# function to find the partition position
def partition(array, low, high):
  pivot = array[high]
  i = low - 1
  for j in range(low, high):
    if array[j] <= pivot:
      i = i + 1
      (array[i], array[j]) = (array[j], array[i])
  (array[i + 1], array[high]) = (array[high], array[i + 1])
  return i + 1

# function to perform quicksort
def quickSort(array, low, high):
  if low < high:
    pi = partition(array, low, high)
    quickSort(array, low, pi - 1)
    quickSort(array, pi + 1, high)

N = 10000000
data = np.zeros(N, dtype="int")
data = np.random.randint(low=0,high=N,size=N)
print("Unsorted Array")
print(data)

size = len(data)

quickSort(data, 0, size - 1)

print('Sorted Array in Ascending Order:')
print(data)
t1 = time()

print('sync takes {}'.format(t1-t0))


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('api', '0005_auto_20150815_1039'),
    ]

    operations = [
        migrations.AddField(
            model_name='station',
            name='address',
            field=models.CharField(unique=True, max_length=200, default='not available'),
            preserve_default=False,
        ),
    ]


import copy
import math
import networkx as nx
import numpy as np

import graph_utils

def WD(G: nx.DiGraph):
    # Retrieve all the node delays
    node_delays = np.array([int(G.nodes[node]['d']) for node in G.nodes])
    node_dict = dict(zip(list(G.nodes), list(range(len(node_delays)))))
    node_dict_inv = dict(zip(list(range(len(node_delays))), list(G.nodes)))

    class Weight:
        def __init__(self, w, d):
            self.w = w
            self.d = d

        def __add__(self, other):
            return Weight(self.w + other.w, self.d + other.d)

        def __le__(self, other):
            if self.w < other.w:
                return True
            elif self.w == other.w and self.d > other.d:
                return True
            else:
                return False

        def __str__(self):
            return f"[{self.w}, {self.d}]"

        def __repr__(self):
            return self.__str__()

    A = np.matrix(nx.to_numpy_matrix(G, weight='w', nonedge=np.inf))
    A = A.astype(np.object)

    for u, v in G.edges:
        A[node_dict[u], node_dict[v]] = Weight(G[u][v]['w'], G[u][v]['d'])

    n, m = A.shape

    _edges = set([(node_dict[u], node_dict[v]) for u,v in G.edges])
    for row in range(n):
        for col in range(m):
            if (row, col) not in _edges:
                A[row, col] = Weight(np.inf, np.inf)
            else:
                u = node_dict_inv[row]
                v = node_dict_inv[col]
                A[row, col] = Weight(G[u][v]['w'], G[u][v]['d'])

    n, m = A.shape
    A[np.identity(n) == 1] = Weight(0,0)  # diagonal elements should be zero
    for i in range(n):
        A = np.minimum(A, A[i, :] + A[:, i])

    W = np.empty(shape=A.shape, dtype=int)
    D = np.empty(shape=A.shape, dtype=int)
    for row in range(n):
        for col in range(m):
            W[row, col] = A[row, col].w
            D[row, col] = A[row, col].d

    # Add the starting delay
    for x in range(D.shape[0]):
        D[x] = D[x] + node_delays

    return W, D

def CP(G: nx.DiGraph):

    # Retrieve the edges where w is equal to zero
    relevant_edges = [(u, v) for u, v in G.edges if G.get_edge_data(u, v)['w'] == 0]

    # Create a new graph in order to avoid side effects on the current one
    X = nx.DiGraph()

    # Add only the relevant edges to the new graph
    [X.add_edge(u, v, w=G[u][v]['w']) for u, v in relevant_edges]

    # Topological sort the graph
    sorted_vertices = nx.topological_sort(X)

    # DELTA (as described in the paper)
    delta = {}

    # Compute the starting DELTA for each vertex
    for vertex in G.nodes:
        delta[vertex] = int(G.nodes[vertex]['d'])

    # Declare a function that compute incrementally DELTA
    def compute_delay(G, vertex, delay):
        in_vertices = [u for u, v in G.in_edges(vertex)]
        if len(in_vertices) == 0:
            delta[vertex] = delay
        else:
            delta[vertex] = max(delta[vertex] for vertex in in_vertices) + delay

    # Compute DELTA delay
    [compute_delay(X, vertex, int(G.nodes[vertex]['d'])) for vertex in sorted_vertices]

    # Return DELTA
    return delta

def OPT_1(G: nx.DiGraph, W: np.matrix, D: np.matrix, verbose=False):
    # Initiliaze returned value
    r = {}
    best_r = {}
    best_c = np.inf

    # Auxiliary structures
    node_names = np.array(G.nodes, np.object)
    tested_c = set([])

    # Initialize binary search data structure
    binary_search_array = np.array(sorted(D.flat))
    binary_search_array = np.unique(binary_search_array)
    binary_search_step = int(binary_search_array.size / 2)
    binary_search_index = binary_search_step

    # Binary search
    for _ in range(math.ceil(math.log2(binary_search_array.size)) + 1):

        # Check exit condition:
        if binary_search_index >= len(binary_search_array) or binary_search_index < 0:
            break

        # Retrieve a clock and try it if feasible
        c = binary_search_array[binary_search_index]

        if c not in tested_c:
            # c = 10
            # Retrieve the index of the path with delay greater than c
            indices = np.where(D > c, D, 0).nonzero()

            # Create a graph to solve the ILP
            bellman_ford_solver_graph = nx.DiGraph()

            # Add constraints
            for x, y in zip(indices[0], indices[1]):
                u = node_names[x]
                v = node_names[y]
                w = W[x, y] - 1
                # print(f"{x} - {y} <= {w}")
                if bellman_ford_solver_graph.has_edge(v,u):
                    if bellman_ford_solver_graph[v][u]['w'] > w:
                        bellman_ford_solver_graph[v][u]['w'] = w
                else:
                    bellman_ford_solver_graph.add_edge(v, u, w=w)

            # Add constraints
            for nodes, edge_property in G.edges.items():
                u = nodes[0]
                v = nodes[1]
                w = edge_property['w']
                # print(f"{u} - {v} <= {w}")
                if bellman_ford_solver_graph.has_edge(v,u):
                    if bellman_ford_solver_graph[v][u]['w'] > w:
                        bellman_ford_solver_graph[v][u]['w'] = w
                else:
                    bellman_ford_solver_graph.add_edge(v, u, w=w)

            # print(len(G.edges))
            # print(len(indices[0]))
            # print(len(bellman_ford_solver_graph.edges))

            # graph_utils.print_graph(bellman_ford_solver_graph)
            bellman_ford_solver_graph.add_node('root_node')
            for node in G.nodes:
                bellman_ford_solver_graph.add_edge('root_node', node, w=0)
            # break
            # graph_utils.draw_graph(bellman_ford_solver_graph)
            tested_c.add(c)

            # Solve the graph
            is_feasible = True
            try:
                # graph_utils.draw_graph(bellman_ford_solver_graph)
                r = nx.single_source_bellman_ford_path_length(bellman_ford_solver_graph, 'root_node', weight='w')
                # print(r)
            except nx.NetworkXUnbounded:
                is_feasible = False

            if verbose:
                print(f"Clock {c} {'is' if is_feasible else 'is NOT'} feasible")

            if is_feasible:
                if best_c > c:
                    best_c = c
                    best_r = r

        else:
            is_feasible = c >= best_c

        # Move the index
        binary_search_step = binary_search_step / 2
        if is_feasible:
            binary_search_index = binary_search_index - math.ceil(binary_search_step)
        else:
            binary_search_index = binary_search_index + math.ceil(binary_search_step)
    Gr = graph_utils.retime_graph(G, best_r)

    return Gr

def FEAS(G: nx.DiGraph, c: int):
    r = dict(zip(G.nodes, [0 for _ in G.nodes]))

    # Clone the graph
    Gr = copy.deepcopy(G)

    for i in range(len(Gr.nodes) - 1):
        path = CP(Gr)
        for node in Gr.nodes:
            if path.get(node, 0) > c:
                r[node] = r[node] + 1
        # Move the registers
        for u, v in list(Gr.edges):
            Gr[u][v]['w'] = G[u][v]['w'] + r[v] - r[u]
    if max(CP(Gr).values()) > c:
        return None
    else:
        return Gr

def OPT_2(G: nx.DiGraph, D: np.matrix, verbose=False):

    tested_c = set([])
    best_c = np.inf

    # Initialize binary search data structure
    binary_search_array = np.array(sorted(D.flat))
    binary_search_array = np.unique(binary_search_array)
    binary_search_step = int(binary_search_array.size / 2)
    binary_search_index = binary_search_step

    Gr = copy.deepcopy(G)

    # Binary search
    for _ in range(math.ceil(math.log2(binary_search_array.size)) + 1):

        # Check exit condition:
        if binary_search_index >= len(binary_search_array) or binary_search_index < 0:
            break

        # Retrieve a clock and try it if feasible
        c = binary_search_array[binary_search_index]

        if c not in tested_c:

            FEAS_result = FEAS(G, c)

            # Solve the graph
            is_feasible = FEAS_result is not None

            if verbose:
                print(f"Clock {c} {'is' if is_feasible else 'is NOT'} feasible")
            tested_c.add(c)

            if is_feasible:
                if best_c > c:
                    best_c = c
                    Gr = FEAS_result

        else:
            is_feasible = c >= best_c

        # Move the index
        binary_search_step = binary_search_step / 2
        if is_feasible:
            binary_search_index = binary_search_index - math.ceil(binary_search_step)
        else:
            binary_search_index = binary_search_index + math.ceil(binary_search_step)

    return Gr


# -*- coding: utf-8 -*-
# @Time   : 2021/9/26 16:49
# @Author : Gang
# @File   : psdStaticDataProcessUtils.py
import numpy as np
from gangLogger.myLog import MyLog
from psdStaticConst import *
# from scipy.fft import fft
# from scipy import integrate
from numpy.fft import fft
import matplotlib.mlab as mlab

# TODO
# 注意此处的两个scipy的包都可以换成nunpy的！！

class PSDStaticDataProcessUtils:
    logger = MyLog("PSDStaticDataProcessUtils", BASEDIR)

    @classmethod
    def loadData(cls, keyPara):
        filePath = keyPara["FILE_PATH"]
        logGArray = np.load(filePath)["conductance_array"]
        cls.logger.debug("数据读取完成...")
        return logGArray

    @classmethod
    def getIntegPSD(cls, GArray, freqLow, freqHigh, keyPara, mode="mlab"):
        """
        使用mlab.psd()或幅度谱平方求psd；并返回电导均值
        :param keyPara: 界面配置参数
        :param condData: 对数电导单条曲线
        :param mode:计算模式
        :return: psd的积分, 平均电导
        """
        windowSize = int(keyPara["le_WindowSize"])
        if np.count_nonzero(GArray) < windowSize:
            return 0.0, 0.0
        else:
            try:
                GArray = GArray[GArray != 0][:windowSize]
                gMean = np.mean(GArray)
                N = len(GArray)
                sampFreq = keyPara["le_Frequence"]
                if mode == "mlab":
                    psd, freqs = mlab.psd(GArray, NFFT=N, sides='onesided',
                                          Fs=sampFreq, window=mlab.window_hanning,
                                          pad_to=N, scale_by_freq=False)
                    psd *= 2  # 与手算的相差系数2
                else:
                    fftRes = fft(GArray)
                    fftResAbs = np.abs(fftRes)
                    resNorm = fftResAbs / (N / 2)
                    resNorm[0] /= 2

                    freqs = np.linspace(0, sampFreq // 2, N // 2)
                    oneSideFFT = resNorm[:N // 2]
                    psd = oneSideFFT ** 2

                integRangeIdx = np.where((freqs >= freqLow) & (freqs <= freqHigh))[0]
                # integPSD = integrate.trapz(psd[integRangeIdx], freqs[integRangeIdx])
                integPSD = np.trapz(psd[integRangeIdx], freqs[integRangeIdx])
            except Exception as e:
                errMsg = f"单条psd计算异常{e}"
                cls.logger.error(errMsg)
                return 0.0, 0.0
            else:
                return integPSD, gMean

    @classmethod
    def getIntegInterval(cls, keyPara):
        """
        这个函数是整个数组进行求解
        :param keyPara:
        :return:
        """
        logGArray = cls.loadData(keyPara)

        logGHigh, logGLow = keyPara["le_CondHigh"], keyPara["le_CondLow"]
        logGArraySelect = np.where((logGArray >= logGLow) & (logGArray <= logGHigh), logGArray, -np.inf)
        gArraySelect = np.power(10.0, logGArraySelect)
        resultTemp = np.apply_along_axis(cls.getIntegPSD, 1, gArraySelect, 100, 1000, keyPara)
        integPSD, gMean = resultTemp[:, 0], resultTemp[:, 1]

        finalIdx = np.where(integPSD != 0.0)
        gMean = gMean[finalIdx]
        integPSD = integPSD[finalIdx]

        return gMean, integPSD

    @classmethod
    def getMinNInterval(cls, gMean, integPSD):
        """

        :param gMean:
        :param integPSD:
        :return:
        """
        if gMean.shape[0] == 0:
            raise Exception("无符合条件数据")
        exponentIdx = np.arange(0.5, 2.5, 0.005)
        minNIdx = [cls.getMinHelper(gMean, integPSD, k) for k in exponentIdx]
        return sorted(minNIdx)[0][1]

    @classmethod
    def getMinHelper(cls, gMean, integPSD, exponent):
        try:
            gMeanPower = np.power(gMean, exponent)
            scaledPSD = integPSD / gMeanPower
            coef = np.corrcoef(scaledPSD, gMean)[0, 1]
        except Exception as e:
            errMsg = f"minNIdx计算异常：{e}"
            cls.logger.error(errMsg)
            return np.inf, exponent
        else:
            return np.abs(coef), exponent


"""
:Author: DOHMATOB Elvis Dopgima <gmdopp@gmail.com> <elvis.dohmatob.inia.fr>

"""

import itertools
import numpy as np
import networkx as nx
import pylab as pl

# number of variable nodes in Tanner graph
_tanner_nvar_nodes = lambda checks: len(set.union(*map(set, checks)))

def rotate_list (l, r=1):
    """
    Rotates list (l) r places to the right.

    """

    l = list(l)
    return l[-r:] + l[:-r]

def parmat2graph(h):
    nchecks, nvars = h.shape
    checks =[r.nonzero()[0] for r in h]
    graph = nx.Graph()
    graph.add_nodes_from(xrange(nvars), bipartite=0)
    graph.add_nodes_from(xrange(nvars, nvars + nchecks), bipartite=1)
    for cn, check in enumerate(checks):
        for vn in check: graph.add_edge(cn + nvars, vn)

    return graph, xrange(nvars), xrange(nvars, nvars + nchecks)

def _tanner_iter_nodes(checks):
    for node in xrange(_tanner_nvar_nodes(checks) + len(checks)): yield node

def _tanner_iter_edges(checks):
    nvars = _tanner_nvar_nodes(checks)
    for cn, check in enumerate(checks):
        for vn in check: yield vn, cn + nvars

def tanner_graph(checks):
    G = nx.Graph()
    G.add_edges_from(_tanner_iter_edges(checks))
    return G

def tanner_cycle(n):
    return [[j, (j + 1) % n] for j in xrange(n)]

def tanner_cartesian_product(checks1, checks2, split=False):
    """
    Cartesian product G1 x G2 of two Tanner graphs Gi = (Vi, Ci, Ei),
    i = 1, 2, where for each of the lists checksi has been defined
    as follows: for each ci \in Ci, checks1[ci] is the support of the
    ci-th row of the parity matrix of the cyclic code represented by Gi.

    Note that the cartesian product G1 x G2 is again a Tanner graph since the
    following chromatic equation holds:

        chrom(G1 x G2) = max(chrom(G1), chrom(G2)) = 2.

    Returns
    -------
    checks: list of lists
        compact representation for the cyclic code represented by the Tanner
        graph G1 x G2.

    """

    nvars1, nvars2 = _tanner_nvar_nodes(checks1), _tanner_nvar_nodes(checks2)
    nchecks1, nchecks2 = len(checks1), len(checks2)
    var_nodes1, var_nodes2 = xrange(nvars1), xrange(nvars2)
    check_nodes1 = xrange(nvars1, nvars1 + nchecks1)
    check_nodes2 = xrange(nvars2, nvars2 + nchecks2)
    var_nodes = list(set(itertools.product(var_nodes1, var_nodes2)).union(
            itertools.product(check_nodes1, check_nodes2)))
    if split:
        iX, iZ = [], []
        check_nodesX = list(itertools.product(check_nodes1, var_nodes2))
        check_nodesZ = list(itertools.product(var_nodes1, check_nodes2))
        check_nodes = list(set(check_nodesX).union(check_nodesZ))
    else:
        check_nodes = list(set(itertools.product(
                    check_nodes1, var_nodes2)).union(
                itertools.product(var_nodes1, check_nodes2)))
    checks = [[] for _ in xrange(len(check_nodes))]
    for (x, y), z in itertools.product(_tanner_iter_edges(checks1),
                                       _tanner_iter_nodes(checks2)):
        if (x, z) in check_nodes:
            cn, vn = check_nodes.index((x, z)), var_nodes.index((y, z))
            if split and not (cn in iX or cn in iZ): iX.append(cn)
        else:
            cn, vn = check_nodes.index((y, z)), var_nodes.index((x, z))
            if split and not (cn in iX or cn in iZ): iZ.append(cn)
        checks[cn].append(vn)
    for x, (y, z) in itertools.product(_tanner_iter_nodes(checks1),
                                       _tanner_iter_edges(checks2)):
        if (x, y) in check_nodes:
            cn, vn = check_nodes.index((x, y)), var_nodes.index((x, z))
            if split and not (cn in iX or cn in iZ): iX.append(cn)
        else:
            cn, vn = check_nodes.index((x, z)), var_nodes.index((x, y))
            if split and not (cn in iZ or cn in iX): iZ.append(cn)
        checks[cn].append(vn)

    return ([checks[i] for i in iX], [checks[i] for i in iZ]
            ) if split else checks

def tanner_cartesian_power(checks, n, split=False):
    """
    Cartesian power of Tanner graph G. Note that G^n is again a Tanner graph.

    Returns
    -------
    Compact representation checks_, for G^n.

    """

    checks_ = checks
    for _ in xrange(n - 2):
        checks_ = tanner_cartesian_product(checks_, checks)
    return tanner_cartesian_product(checks_, checks, split=split)

def css_code(GX, GZ):
    """
    CSS code construction.

    """

    # XXX use scipy.linalg sparse constructs (csr_matrix, etc.) !!!
    return np.vstack((np.hstack((GX, np.zeros((GX.shape[0], GZ.shape[1])))),
                      np.hstack((np.zeros((GZ.shape[0], GX.shape[1])), GZ))))

def kovalev_code(H1, H2):
    """
    Kovalev et al's kron product construction.

    """

    r1, n1 = H1.shape
    r2, n2 = H2.shape
    E1 = np.eye(r1)
    E1_ = np.eye(n1)
    E2 = np.eye(r2)
    E2_ = np.eye(n2)

    return css_code(np.hstack((np.kron(E2, H1), np.kron(H2, E1))),
                    np.hstack((np.kron(H2.T, E1_), np.kron(E2_, H1.T))))

def repetition_code_circulant_matrix(d):
    """
    Returns circulant matrix of repetition code (Hc), where:

        g = 1 + x + x^2 + ... + x^(n - 1)
        h = (x^n - 1) / g = 1 + x (mod 2)
        Hc = [h, hx, hx^2, ..., hx^(n - 1)]^T

    """

    assert d >= 2
    h = np.append([1, 1], np.zeros(d - 2))
    return np.vstack([rotate_list(h, r=r) for r in xrange(d)])

def kovalev_toric_code_construction(d):
    G = repetition_code_circulant_matrix(d)
    return kovalev_code(G, G)

if __name__ == "__main__":
    pl.close("all")
    d = 7

    # gridded torus
    pl.figure()
    pl.title("%i-by-%i regular paving of the torus" % (d, d))
    nx.draw_graphviz(tanner_graph(tanner_cartesian_power(tanner_cycle(d), 2)),
                     node_size=30, with_labels=False)

    # Tillich-Zemor hypergraph-product constructions
    s1 = s2 = tanner_cycle(d)
    s = tanner_cartesian_product(s1, s2, split=True)
    t = nx.cartesian_product(tanner_graph(s1), tanner_graph(s2))
    pl.figure()
    pl.suptitle("Sum decomposition of Tanner graph products")
    for j, support in enumerate([s1, s2]):
        ax = pl.subplot("32%i" % (j + 1))
        ax.set_title("t%i = tanner(%s)" % (j + 1, support))
        tj = tanner_graph(support)
        nx.draw_graphviz(tj, with_labels=0, node_size=30)
    ax = pl.subplot("312")
    ax.set_title("t1 x t2 =: t =: t1' + t2'")
    nx.draw_graphviz(t, with_labels=0, node_size=30)
    for j, sj in enumerate(s):
        ax = pl.subplot("32%i" % (4 + j + 1))
        ax.set_title("t%i'" % (j + 1))
        tj = tanner_graph(sj)
        nx.draw_graphviz(tj, with_labels=0, node_size=30)

    # Kovalev et al's kron constructions
    title = ("Toric [%i, 2, %i]-code H using Kovalev et al's kron "
             "product trick") % (2 * d ** 2, d)
    toric = kovalev_toric_code_construction(d)
    pl.figure()
    pl.title(title)
    nx.draw_graphviz(parmat2graph(toric)[0], with_labels=False, node_size=30)
    pl.matshow(toric)
    pl.title(title)
    pl.gray()
    pl.axis('off')

    pl.show()


from logging import exception
import matplotlib.pyplot as plt
import ezdxf
from ezdxf.addons.drawing import RenderContext, Frontend
from ezdxf.addons.drawing.matplotlib import MatplotlibBackend
import cv2
import numpy as np
import os

def dxf2img(dxf, nestID=None, reverse=False, mirror=False):
    doc = ezdxf.readfile(dxf)
    img_path = "output/sample_{}.png".format(nestID) if nestID is not None else "output/sample.png"
    msp = doc.modelspace()
    margin = 5

    text_for_parts = []
    textp = msp.query('TEXT[layer!="plane"]')
    for t in textp:
        text_for_parts.append(t.dxf.text)

    redundants = msp.query('*[layer!="plane"]')
    for e in redundants:
        msp.delete_entity(e)
        e.destroy()

    textdb = {}
    textsz = {}
    texts = msp.query('TEXT[layer=="plane"]')
    print("There should be {} parts.".format(len(texts)))
    num_expected = len(texts)
    for t in texts:
        key = t.dxf.text
        height = t.dxf.height
        if key not in textdb.keys():
            textdb[key] = []
        textdb[key] = textdb[key] + [(t.get_pos()[1][0], t.get_pos()[1][1])]
        textsz[key] = height
        msp.delete_entity(t)
        t.destroy()

    lines = msp.query('LINE[layer=="plane"]')
    lf_x = 99999999
    lf_y = 99999999
    hr_x = -9999999
    hr_y = -9999999
    for l in lines:
        point1 = l.dxf.start
        point2 = l.dxf.end

        lf_x = min(point1[0], point2[0], lf_x)
        lf_y = min(point1[1], point2[1], lf_y)
        hr_x = max(point1[0], point2[0], hr_x)
        hr_y = max(point1[1], point2[1], hr_y)

    # print("The lower left point is {}, the higher right point is {}".format((lf_x, lf_y), (hr_x, hr_y)))

    resize = (np.round(hr_x - lf_x).astype(np.int), np.round(hr_y - lf_y).astype(np.int))

    auditor = doc.audit()
    if len(auditor.errors) != 0:
        raise exception("The DXF document is damaged and can't be converted!")
    else:
        fig = plt.figure()
        ax = fig.add_axes([0, 0, 1, 1])
        ctx = RenderContext(doc)
        ctx.set_current_layout(msp)
        ctx.current_layout.set_colors(bg='#FFFFFF')
        out = MatplotlibBackend(ax)
        Frontend(ctx, out).draw_layout(msp, finalize=True)
        # Frontend(ctx, out).draw_entities(lines)
        # fig.savefig(img_path)

        fig.savefig(img_path, dpi=1500)

    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret, thresh = cv2.threshold(gray, 210, 255, 1)
    contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    rect = cv2.boundingRect(contours[0])
    img = img[rect[1]+margin: rect[1] + rect[3]-margin, rect[0]+margin: rect[0] + rect[2]-margin]
    img = cv2.copyMakeBorder(img, margin, margin, margin, margin, cv2.BORDER_CONSTANT, value=(255, 255, 255))

    img = cv2.resize(img, (resize))
    for k in list(textdb.keys()):
        for i in range(len(textdb[k])):
            textdb[k][i] = (np.round(textdb[k][i][0] - lf_x).astype(int),
                            np.round(hr_y - textdb[k][i][1]).astype(int))

    if reverse:
        img = cv2.flip(img, 1)
        img = cv2.flip(img, 0)
        for k in list(textdb.keys()):
            for i in range(len(textdb[k])):
                textdb[k][i] = (np.round(resize[0] - textdb[k][i][0]).astype(int),
                                np.round(resize[1] - textdb[k][i][1]).astype(int))
    elif mirror:
        img = cv2.flip(img, 1)
        for k in list(textdb.keys()):
            for i in range(len(textdb[k])):
                textdb[k][i] = (np.round(resize[0] - textdb[k][i][0]).astype(int), textdb[k][i][1])

    cv2.imwrite(img_path, img)
    return img, textdb, textsz, num_expected

def inner_level(index, hierarchy):
    level = 0
    while hierarchy[0][index][2] != -1:
        level += 1
        index = hierarchy[0][index][2]
    return level

def inner_level_target(index, hierarchy, target):
    level = 0
    while hierarchy[0][index][2] != -1:
        level += 1
        index = hierarchy[0][index][2]
    return level == target

def outer_level(index, hierarchy):
    level = 0
    while hierarchy[0][index][-1] != -1:
        level += 1
        index = hierarchy[0][index][-1]
    return level

def outer_level_target(index, hierarchy, target):
    level = 0
    while hierarchy[0][index][-1] != -1:
        level += 1
        index = hierarchy[0][index][-1]
    return level == target

def count_max_level(contours, hierarchy):
    level_global = 0
    for i in range(len(contours)):
        level = 0
        index = i
        while hierarchy[0][index][-1] != -1:
            level += 1
            index = hierarchy[0][index][-1]
        level_global = max(level, level_global)
    return level_global

def segmentPieces(img, textDB, textSZ, num_expected):
    thickness = 1

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret, thresh = cv2.threshold(gray, 180, 255, 1)
    canvas = np.zeros_like(gray)
    # thresh = cv2.GaussianBlur(thresh, (3, 3), 1.5)
    contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    cv2.imwrite("./output/thresh.png", thresh)

    externals = []
    pieces = []
    origins = []
    rects = []

    # max_level = count_max_level(contours, hierarchy)  # 3/5/7/9
    # print("LCH:: Max level is ", max_level)

    # while max_level > 1:
    for max_level in [11, 7, 3]:
        temp = np.zeros_like(gray)
        inverse = temp.copy()
        for i in range(len(contours)):
            if outer_level_target(i, hierarchy, max_level-1):
                cv2.drawContours(temp, contours, i, 255, thickness)
                cv2.drawContours(inverse, contours, i, 255, -1)
                cv2.drawContours(canvas, contours, i, 255, thickness)
        for i in range(len(contours)):
            if outer_level_target(i, hierarchy, max_level-3):
                temp_local = temp.copy()
                inverse_local = np.zeros_like(temp_local)
                cv2.drawContours(canvas, contours, i, 255, thickness)
                cv2.drawContours(temp, contours, i, 255, thickness)
                cv2.drawContours(temp_local, contours, i, 255, thickness)
                cv2.drawContours(inverse_local, contours, i, 255, -1)
                cv2.drawContours(inverse, contours, i, 255, -1)
                temp_local = cv2.bitwise_and(temp_local, inverse_local)
                rect = cv2.boundingRect(contours[i])
                piece = temp_local[rect[1]: rect[1] + rect[3], rect[0]: rect[0] + rect[2]].copy()
                piece = cv2.bitwise_not(piece, piece)
                pieces.append(piece)
                externals.append(contours[i])
                origins.append((rect[0], rect[1]))
                rects.append(rect)
        inverse = cv2.bitwise_not(inverse, inverse)
        thresh = cv2.bitwise_and(thresh, inverse)
        contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        # cv2.imwrite("./output/thresh_cut.png", thresh)

    print("Detected {} parts".format(len(pieces)))
    num_detected = len(pieces)

    canvas = cv2.bitwise_not(canvas, canvas)
    canvas = cv2.cvtColor(canvas, cv2.COLOR_GRAY2BGR)
    for n in list(textDB.keys()):
        for p in textDB[n]:
            cv2.circle(canvas, (p[0], p[1]), 5, (255, 0, 0), -1)

    zipped = sorted(zip(externals, pieces, origins, rects), key=lambda x: cv2.contourArea(x[0]))
    text_keys = sorted(list(textDB.keys()), key=lambda x: textSZ[x])

    # Assign ID to the pieces
    partDB = {}
    textleft = []
    count = 0
    pop_count = 0
    for n in list(text_keys):
        for p in textDB[n]:
            assigned = False
            i = 0
            for epo in zipped:
                contour, piece, origin, rect = epo
                if cv2.pointPolygonTest(contour, p, False) >= 1:
                    partDB[count] = {
                        'PartID': n,
                        'Part': piece,
                        'Origin': origin,
                        'PartHeight': piece.shape[0],  # 使用从dxf解析出的图形尺寸，不使用表格中的尺寸
                        'PartWidth': piece.shape[1],
                    }
                    count += 1
                    assigned = True
                    break
                i += 1
            if assigned:
                zipped.pop(i)
                pop_count += 1
            else:
                textleft.append((n, p))

    if len(zipped) > 0 and len(textleft) > 0:
        assert len(zipped) == len(textleft), "Error: the parts left doesn't match the text left"
        for epo in zipped:
            contour, piece, origin, rect = epo
            for n, p in textleft:
                if rect[0] <= p[0] <= rect[0] + rect[2] and rect[1] <= p[1] <= rect[1] + rect[3]:
                    partDB[count] = {
                        'PartID': n,
                        'Part': piece,
                        'Origin': origin,
                        'PartHeight': piece.shape[0],  # 使用从dxf解析出的图形尺寸，不使用表格中的尺寸
                        'PartWidth': piece.shape[1],
                    }
                    count += 1

    if not os.path.exists("./output/pieces"):
        os.makedirs("./output/pieces")
    for k in partDB.keys():
        cv2.imwrite("./output/pieces/{0:03d}_id{1:03d}.png".format(k, int(partDB[k]['PartID'])), partDB[k]['Part'])

    print("Assigned {} parts.".format(len(list(partDB.keys()))))
    num_assigned = len(list(partDB.keys()))

    cv2.imwrite("./output/canvas.png", canvas)
    assert num_expected == num_assigned == num_detected, "The nest is parsed illegally."

    return partDB

def parse_dxf_by_info(dxf, partInfo, nestID, reverse=False, mirror=False):
    '''
    reverse=True代表翻转180度，reverse=False代表不翻转
    mirror=True代表水平镜像，mirror=False代表不镜像
    reverse和mirror不可同时为True
    :param dxf:
    :param partInfo:
    :param nestID:
    :return:
    '''
    img, textDB, textSZ, num = dxf2img(dxf, nestID, reverse=reverse, mirror=mirror)
    partDB = segmentPieces(img, textDB, textSZ, num)
    for key in partDB.keys():
        partID = partDB[key]['PartID']
        partDB[key].update(partInfo[partID])
    height, width, _ = img.shape
    return partDB, height, width

if __name__ == "__main__":
    # dxf = "data/dxf/O210811SG100015A02.dxf"
    # dxf = "data/dxf/O210812Q345B8A01.dxf"
    # dxf = "data/dxf/O210812Q345B8A03.dxf"
    # dxf = "data/dxf/O210908Q235B10A01.dxf"
    # dxf = "data/dxf/O210811SG100015AT22.dxf"
    # dxf = "data/dxf/O210917SG10008A07T1.dxf"
    # dxf = "data/dxf/O210918SG100035A01.dxf"
    # dxf = "data/dxf/O210918SG100020A01.dxf"
    # dxf = "data/dxf/O210919SG100010A01.dxf"
    # dxf = "data/dxf/O210924SG100015A03R.dxf"
    # dxf = "data/dxf/O210811SG100015A05.dxf"
    # dxf = "data/dxf/O210929SG10008A01.dxf"  # level 3
    # dxf = "data/dxf/O210919SG100010A02.dxf"  # level 9
    # dxf = "data/dxf/O211005SG10005A03M.dxf"
    # dxf = "data/dxf/O211006SG10005A12.dxf"
    dxf = "data/dxf/O211007SG10006A22.dxf"

    img, textDB, textSZ, num = dxf2img(dxf, reverse=False, mirror=False)
    partDB = segmentPieces(img, textDB, textSZ, num)
    print(textDB)


# Problem Description: https://practice.geeksforgeeks.org/problems/josephus-problem/1

import math

def josephus(n, k):
    if(n == 1):
        return 1

    return((josephus(n-1, k)+k-1) % n+1)

def main():

    T = int(input())

    while(T > 0):

        nk = [int(x) for x in input().strip().split()]
        n = nk[0]
        k = nk[1]

        print(josephus(n, k))

        T -= 1

if __name__ == "__main__":
    main()


from functools import wraps
from http import HTTPStatus

from flask import request

def verify_some_keys(trusted_keys: "list[str]"):
    def test_key(func):
        @wraps(func)
        def wraped_function(*args, **kargs):
            try:
                data = request.get_json()
                for key in data.keys():
                    if key not in trusted_keys:
                        raise KeyError
                return func(*args, **kargs)
            except KeyError:
                return {
                        "error": "incorrect key(s)",
                        "expected to be in": trusted_keys,
                        "received": list(data.keys())
                        }, HTTPStatus.BAD_REQUEST
        return wraped_function
    return test_key


from django.db import models

# Create your models here.
from django.db import models

# Create your models here.
class cat_editoriales(models.Model):
    cod_editorial = models.IntegerField(primary_key=True)
    des_editorial = models.CharField(max_length=255)

class cat_autores(models.Model):
    cod_autor = models.IntegerField(primary_key=True)
    des_autor = models.CharField(max_length=255)

class cat_libros(models.Model):
    cod_libro = models.IntegerField(primary_key=True)
    tit_libro = models.CharField(max_length=255)
    cod_autor = models.ForeignKey(cat_autores, on_delete=models.CASCADE, related_name="codigoAutor" )
    cod_editorial = models.ForeignKey(cat_editoriales, related_name="codigoEditorial", on_delete=models.CASCADE)
    anio = models.SmallIntegerField()
    tema = models.CharField(max_length=255)
    cant_plu = models.SmallIntegerField()
    cant_disponible = models.SmallIntegerField()

class cat_libros_plu(models.Model):
    cod_libro = models.ForeignKey(cat_libros, related_name="codigoLibro", on_delete=models.RESTRICT)
    plu = models.CharField(max_length=25, primary_key=True)
    cant_disponible = models.SmallIntegerField()


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

'''
    Cerebro ShowBox Scraper

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

import re, urllib, urlparse, json, base64
from resources.lib.modules import cleantitle
from resources.lib.modules import client
from resources.lib.modules import aadecoder
from resources.lib.modules import directstream
from resources.lib.modules import jsunpack
from resources.lib.modules import dom_parser2
from resources.lib.modules import source_utils

class source:
    def __init__(self):
        self.priority = 1
        self.language = ['en']
        self.domains = ['freemoviesz.to']
        self.base_link = 'https://freemoviesz.to/'
        self.search_link = 'search?q=%s'
        self.token_link = 'https://embed.streamdor.co/token.php?v=5'
        self.source_link = 'https://api.streamdor.co/sources'

    def movie(self, imdb, title, localtitle, aliases, year):
        try:
            url = {'imdb': imdb, 'title': title, 'year': year, 'aliases': aliases}
            url = urllib.urlencode(url)
            return url
        except:
            return

    def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year):
        try:
            url = {'imdb': imdb, 'tvdb': tvdb, 'tvshowtitle': tvshowtitle, 'year': year, 'aliases': aliases}
            url = urllib.urlencode(url)
            return url
        except:
            return

    def episode(self, url, imdb, tvdb, title, premiered, season, episode):
        try:
            if url == None: return
            url = urlparse.parse_qs(url)
            url = dict([(i, url[i][0]) if url[i] else (i, '') for i in url])
            url['title'], url['premiered'], url['season'], url['episode'] = title, premiered, season, episode
            url = urllib.urlencode(url)
            return url
        except:
            return

    def searchShow(self, title, season):
        try:
            sea = '%s Season %d' % (title, int(season))
            query = self.search_link % urllib.quote_plus(cleantitle.getsearch(sea))
            url = urlparse.urljoin(self.base_link, query)
            r = client.request(url)
            r = client.parseDOM(r, 'div', attrs={'class': 'block_1__info uk-position uk-position-bottom uk-overlay uk-overlay-primary'})
            r = [(dom_parser2.parse_dom(i, 'a', req='href')[0],
                  client.parseDOM(i, 'small')[0]) for i in r if i]
            r = [(i[0].attrs['href']) for i in r if  cleantitle.get_simple(sea) in cleantitle.get_simple(i[0].content)]

            url = r[0]
            return url
        except:
            return

    def searchMovie(self, title, year):
        try:
            query = self.search_link % urllib.quote_plus(cleantitle.getsearch(title+' '+year))
            url = urlparse.urljoin(self.base_link, query)
            r = client.request(url)
            r = client.parseDOM(r, 'div', attrs={'class': 'block_1__info uk-position uk-position-bottom uk-overlay uk-overlay-primary'})
            r = [(dom_parser2.parse_dom(i, 'a', req='href')[0],
                  client.parseDOM(i, 'small')[0]) for i in r if i]
            r = [(i[0].attrs['href'], i[0].content) for i in r if year in i[1]]
            r = [i[0] for i in r if cleantitle.get_simple(i[1]) == cleantitle.get_simple(title)]
            url = r[0]
            return url
        except:
            return

    def sources(self, url, hostDict, hostprDict):
        try:
            sources = []

            if url is None: return sources

            data = urlparse.parse_qs(url)
            data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data])
            try:
                if 'tvshowtitle' in data:
                    episode = int(data['episode'])
                    url = self.searchShow(data['tvshowtitle'], data['season'])
                    url = url.replace('film', 'watch')
                    r = client.request(url)
                    links = client.parseDOM(r, 'div', attrs={'class': 'block_7'})
                    links = dom_parser2.parse_dom(r, 'option', req='value')
                    links = [(i.attrs['value'], i.content) for i in links if 'Episode %02d' % int(episode) in i.content]
                    links = [i[0] for i in links if i]

                else:
                    url = self.searchMovie(data['title'], data['year'])
                    url = url.replace('film', 'watch')
                    r = client.request(url)
                    links = client.parseDOM(r, 'div', attrs={'class':'block_7'})
                    links = client.parseDOM(links, 'div', attrs={'class':'uk-width-expand'})
                    links = [dom_parser2.parse_dom(i, 'a', req='href')[0] for i in links if i]
                    links = [(i.attrs['href'], i.attrs['title'], i.content) for i in links if i]
                    links = [(i[0])for i in links if i]
            except:
                pass

            for url in links:
                data = client.request(url)
                vid = aadecoder.decode(data)
                vid = client.parseDOM(vid, 'iframe', ret='src')[0]
                vid_id = re.findall('video/\w+$', vid)[0]
                p = client.request(vid, referer=url)
                try:
                    p = re.findall(r'JuicyCodes.Run\(([^\)]+)', p, re.IGNORECASE)[0]
                    p = re.sub(r'\"\s*\+\s*\"', '', p)
                    p = re.sub(r'[^A-Za-z0-9+\\/=]', '', p)
                    p = base64.b64decode(p)
                    p = jsunpack.unpack(p)
                    p = unicode(p, 'utf-8')
                except:
                    continue

                try:

                    fl = re.findall(r'file"\s*:\s*"([^"]+)', p)
                    if len(fl) > 0:
                        fl = fl[0]
                        post = {'episodeID': vid_id, 'file': fl, 'subtitle': 'false',
                                'referer': urllib.quote_plus(url)}
                        p = client.request(self.source_link, post=post, referer=vid, XHR=True)
                        js = json.loads(p)
                        src = js['sources']
                        p = client.request('http:' + src, referer=src)
                        js = json.loads(p)[0]
                        ss = js['sources']
                        ss = [(i['file'], i['label']) for i in ss if 'file' in i]

                    else:
                        try:
                            post = {'id': vid_id}
                            p2 = client.request(self.token_link, post=post, referer=vid, XHR=True)
                            js = json.loads(p2)
                            tok = js['token']
                            p = re.findall(r'var\s+episode=({[^}]+});', p)[0]
                            js = json.loads(p)
                            ss = []
                            if 'eName' in js and js['eName'] != '':
                                quali = source_utils.label_to_quality(js['eName'])
                            if 'fileEmbed' in js and js['fileEmbed'] != '':
                                ss.append([js['fileEmbed'], quali])
                            if 'fileHLS' in js and js['fileHLS'] != '':
                                ss.append(['https://hls.streamdor.co/%s%s' % (tok, js['fileHLS']), quali])
                        except:
                            pass

                    for i in ss:
                        try:
                            valid, hoster = source_utils.is_host_valid(i[0], hostDict)
                            direct = False
                            if not valid:
                                hoster = 'CDN'
                                direct = True
                            sources.append({'source': hoster, 'quality': quali, 'language': 'en', 'url': i[0],
                                            'direct': direct, 'debridonly': False})
                        except:
                            pass

                except:
                    url = re.findall(r'embedURL"\s*:\s*"([^"]+)', p)[0]
                    valid, hoster = source_utils.is_host_valid(url, hostDict)
                    if not valid: continue
                    urls, host, direct = source_utils.check_directstreams(url, hoster)
                    for x in urls:
                        sources.append(
                            {'source': host, 'quality': 'SD', 'language': 'en', 'url': x['url'], 'direct': direct,
                             'debridonly': False})

            return sources
        except:
            return sources

    def resolve(self, url):
        try:
            if self.embed_link in url:
                result = client.request(url, XHR=True)
                url = json.loads(result)['embed_url']
                return url
            elif 'google' in url and not 'googleapis' in url:
                return directstream.googlepass(url)
            else:
                return url
        except:
            return


#-----IMPORT OTHER NECESSARY MODULES-----#
import datetime
import queue
from queue import Queue
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
#-----IMPORT BACKTESTING COMPONENTS-----#
import event
from broker import BasicBroker
from data import AlpacaDataFrame
from portfolio import SamplePortfolio
from strategy import PortfolioSharpeMaximization

#---SET ASSETS TO BE TRADED AND LOCATION TO IMPORT ASSETS DATA---#

symbols = ['SPY','MSFT','AAPL','AMZN','BRK.B','JNJ',
           'JPM','GOOG','FB','GOOGL','XOM','BAC',
           'UNH','V','PFE','PG','INTC','CVX','VZ','BA','T']
csv_path = os.path.join(os.getcwd(),'database')

#---INITIALIZING COMPONENTS TO READY FOR BACKTEST---#

Events = Queue()

DataFrame = AlpacaDataFrame(events = Events, csv_path = csv_path,
                         symbols = symbols,interval='1D')

Portfolio = SamplePortfolio(bars = DataFrame, events = Events)
Strategy = PortfolioSharpeMaximization(bars = DataFrame, events = Events,
                            portfolio = Portfolio)
Broker = BasicBroker(events = Events)

#--------START TRADING--------#

print('BACKTESTING IN PROGRESS...')
while True:
    if DataFrame.continue_backtest == True:
        DataFrame.update_bars()
    else:
        break
    while True:
        try:
            event = Events.get(False)
        except queue.Empty:
            break

        if event is not None:
            if event.type == 'MARKET':
                Portfolio.update_holdings(event)
                Strategy.calculate_signals(event)
            elif event.type == 'SIGNAL':
                Portfolio.update_signal(event)
            elif event.type == 'ORDER':
                Broker.execute_order(event)
            elif event.type == 'FILL':
                Portfolio.update_portfolio(event)


import pygame
from update_screen import update_screen
from Background import Background
from Player import Player
from check_events import check_events
# from Monster import Monster
from Troll import Troll
from Ork import Ork
import random
from Treasure import Treasure
from GameButton import GameButton

clock = pygame.time.Clock()
# print("Pygame successfully imported!")
pygame.init() #initialize all the pygame stuff
#get the display info... Info is a class!
display_info = pygame.display.Info()
screen_size = (1920, 1080)
screen = pygame.display.set_mode(screen_size)
game_on = True #a boolean for our game loop
game_over_screen = False #boolean for game_over loop
background = Background(screen, screen_size)
player_score_button = GameButton(
    screen = screen,
    button_text = "Monsters Taken Down: 0",
    text_color = (255,255,255),
    background_color = None,
    location_x = 75,
    location_y = 25,
    button_height = 100,
    button_width = 200,
    font_size = 24,
    center_on_screen = False
)
player = Player(screen)
# troll = Monster()
#a Group is a list-like thing in pygame
#it holds Sprites
monsters = pygame.sprite.Group()
treasures = pygame.sprite.Group()
treasures.add(Treasure(display_info),Treasure(display_info),Treasure(display_info),Treasure(display_info),Treasure(display_info))
tick = 0
random_number = random.randint(0,1)
if(random_number == 0):
    monsters.add(Troll()) #start the game with a monster
else:
    monsters.add(Ork()) #start the game with a monster
#this is the main game loop... run until quit
while(game_on):
    tick += 1
    if(tick % 500 == 0):
        random_number = random.randint(0,1)
        #every 1000 ticks add a monster
        if(random_number == 0):
            monsters.add(Troll())
        else:
            monsters.add(Ork())
    #run check_events where we have moved all our event logic
    #check_events returns a dictionary, with a "game_on" key
    event_data = check_events(player,tick)
    game_on = event_data["game_on"]
    # screen.fill("red") #fill changes the color of the screen
    #run update_screen which is where we draw, and update stuff
    is_game_over = update_screen(screen = screen,player = player, background = background, tick = tick, display_info = display_info, monsters = monsters, treasures=treasures,player_score_button=player_score_button)
    if(is_game_over):
        game_on = False
        game_over_screen = True
    clock.tick(60) #the number is the fps (frame per second)
    pygame.display.flip() #DRAW OUR STUFF

# another "game" loop
game_over_button = GameButton(screen = screen,
                    button_text = "Game Over!",
                    text_color = (255,255,255),
                    background_color = (0,0,0),
                    location_x = 100,
                    location_y = 100,
                    button_height = 100,
                    button_width = 200,
                    font_size = 36,
                    center_on_screen = True)
while(game_over_screen):
    game_over_button.draw_me()
    for event in pygame.event.get():
        if(event.type == pygame.QUIT):
            game_over_screen = False #this gives Python a way out
    pygame.display.flip()


"""
Contains API's related to Student
"""
import traceback

from flask_restplus import Namespace
from flask_restplus import Resource
from flask_restplus import fields

from flask_restplus_app.services.common import token_required
from flask_restplus_app.services.student_services import add_student
from flask_restplus_app.services.student_services import get_student

api = Namespace("student", description="Operations related to student")

student_model = api.model(
    "Student",
    {
        "id": fields.Integer,
        "name": fields.String(description="student name", min_length=3, required=True),
    },
)

@api.route("/")
class StudentAPI(Resource):
    """
    Get all students and insert a new student
    """

    parser = api.parser()
    parser.add_argument(
        "name",
        type=str,
        required=True,
        help="student name cannot be blank!",
        location="json",
    )

    @api.response(500, "Error in getting students")
    @api.marshal_list_with(student_model)
    def get(self):
        """
        Get all the students from DB
        """
        try:
            students = []  # get_students()
            return students
        except Exception:
            traceback.print_exc()
            api.abort(500, "Error in getting students")

    @api.response(409, "Student already exists")
    @api.response(201, "Student successfully added.")
    @api.response(500, "Error in adding a student")
    @api.expect(student_model, validate=True)
    @token_required
    @api.doc(security="apikey")
    def post(self):
        """
        Insert a new student
        """
        args = self.parser.parse_args(strict=True)
        student_name = args["name"].strip()

        student = add_student(student_name)
        if student:
            return api.marshal(student, student_model), 201
        else:
            api.abort(409, "Student alreday exists")

@api.route("/<string:name>")
@api.param("name", "student name")
class StudentCheckAPI(Resource):
    """
    Get the student object when student name is supplied
    """

    @api.response(404, "Student not found")
    @api.response(500, "Error in getting student")
    @api.marshal_with(student_model)
    def get(self, name):
        """
        Returns the student object for the supplied student name
        """
        student = get_student(name)
        if student:
            return student
        else:
            api.abort(404, "Student not found")


import numpy as np
from ocr import OCRNeuralNetwork
from sklearn.model_selection import train_test_split

def test(data_matrix, data_labels, test_indices, nn):
    avg_sum = 0

    for j in range(100):
        correct_guess_count = 0

        for i in test_indices:
            test = data_matrix[i]
            prediction = nn.predict(test)

            if data_labels[i] == prediction:
                correct_guess_count += 1

        avg_sum += (correct_guess_count / float(len(test_indices)))

    return avg_sum / 100

# Load data samples and labels into matrix
data_matrix = np.loadtxt(open('data/data.csv', 'rb'), delimiter=',').tolist()
data_labels = np.loadtxt(open('data/dataLabels.csv', 'rb')).tolist()

# Create training and testing sets
train_indices, test_indices = train_test_split(list(range(5000)))

print(">>>>>>>>>>> PERFORMANCE <<<<<<<<<<<")
print("-----------------------------------")

# Try various number of hidden nodes and see what performs best
for i in range(5, 50, 5):
    nn = OCRNeuralNetwork(i, data_matrix, data_labels, train_indices, False)
    performance = str(test(data_matrix, data_labels, test_indices, nn))
    print('{i} Hidden Nodes: {val}'.format(i=i, val=performance))

print("-----------------------------------")


import os

import iscc_samples as samples
import requests
from django.core.files.uploadedfile import SimpleUploadedFile

def test_media_post_empty(live_server):
    url = live_server.url + "/api/media"
    response = requests.post(url)
    assert response.status_code == 400
    assert response.json() == {"detail": "No file sent"}

def test_media_post_image(live_server):
    url = live_server.url + "/api/media"
    with samples.images("jpg")[0].open("rb") as file:
        response = requests.post(url, files={"source_file": file})
        assert response.status_code == 201
        assert "media_id" in response.json()

def test_media_post_unsupported(live_server, tmp_path):
    tf = tmp_path / "raw.bin"
    tf.write_bytes(os.urandom(1024))
    url = live_server.url + "/api/media"
    with tf.open("rb") as file:
        response = requests.post(url, files={"source_file": file})
        assert response.status_code == 500
        assert "detail" in response.json()

def test_media_get_none(live_server):
    url = live_server.url + "/api/media/05VN6J5C067J4"
    resp = requests.get(url)
    assert resp.status_code == 404

def test_media_get_image(live_server):
    url = live_server.url + "/api/media"
    with samples.images("jpg")[0].open("rb") as file:
        resp = requests.post(url, files={"source_file": file})
        media_id = resp.json().get("media_id")
    resp = requests.get(url + "/" + media_id)
    assert resp.headers["content-type"] == "image/jpeg"

def test_media_metadata(live_server):
    # upload asset
    url = live_server.url + "/api/media"
    with samples.images("jpg")[0].open("rb") as file:
        resp = requests.post(url, files={"source_file": file})
        media_id = resp.json().get("media_id")
    # get pre-existing metadata
    meta_endpoint = url + f"/metadata/{media_id}"
    resp = requests.get(meta_endpoint)
    assert resp.json() == {"creator": "Some Cat Lover", "name": "Concentrated Cat"}
    # embed new metadata
    meta = {
        "name": "new name",
        "description": "new description",
        "rights": "some copyright notice",
    }
    resp = requests.post(meta_endpoint, json=meta)
    new_media_id = resp.json().get("media_id")
    # get newly embedded metadata
    resp = requests.get(url + f"/metadata/{new_media_id}")
    assert resp.json() == {
        "creator": "Some Cat Lover",
        "description": "new description",
        "name": "new name",
        "rights": "some copyright notice",
    }


import requests
from bs4 import BeautifulSoup

def get_external_links(url):
    if url is not None:
        page = requests.get(url).text
        soup = BeautifulSoup(page, 'html.parser')

        for link in soup.find_all('link', rel="canonical", href=True):
            external_link = link.get('href')
            return external_link

        for bandcamp_link in soup.find_all('a', href=True):
            bandcamp = bandcamp_link.get('href')
            if bandcamp != '#':
                return bandcamp

if __name__ == "__main__":
    print(get_external_links(
        'https://w.soundcloud.com/player/?url=https%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F75234063&visual=true&liking=false&sharing=false&auto_play=false&show_comments=false&continuous_play=false&origin=tumblr'))


import numpy as np
import cv2
import time
import math

def letterbox(img, new_shape=(416, 416), color=(114, 114, 114), auto=False, scaleFill=False, scaleup=True, stride=32):
    # Resize and pad image while meeting stride-multiple constraints
    shape = img.shape[:2]  # current shape [height, width]
    if isinstance(new_shape, int):
        new_shape = (new_shape, new_shape)

    # Scale ratio (new / old)
    r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
    if not scaleup:  # only scale down, do not scale up (for better test mAP)
        r = min(r, 1.0)

    # Compute padding
    ratio = r, r  # width, height ratios
    new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
    dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1]  # wh padding
    if auto:  # minimum rectangle
        dw, dh = np.mod(dw, stride), np.mod(dh, stride)  # wh padding
    elif scaleFill:  # stretch
        dw, dh = 0.0, 0.0
        new_unpad = (new_shape[1], new_shape[0])
        ratio = new_shape[1] / shape[1], new_shape[0] / shape[0]  # width, height ratios

    dw /= 2  # divide padding into 2 sides
    dh /= 2

    if shape[::-1] != new_unpad:  # resize
        img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)
    top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
    left, right = int(round(dw - 0.1)), int(round(dw + 0.1))

    img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color)  # add border
    return img, ratio, (dw, dh)

def generate_FT(image):
    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    f = np.fft.fft2(image)
    fshift = np.fft.fftshift(f)
    fimg = np.log(np.abs(fshift) + 1)
    maxx = -1
    minn = 100000
    for i in range(len(fimg)):
        if maxx < max(fimg[i]):
            maxx = max(fimg[i])
        if minn > min(fimg[i]):
            minn = min(fimg[i])
    fimg = (fimg - minn + 1) / (maxx - minn + 1)
    return fimg

def softmax(z):
    assert len(z.shape) == 2
    s = np.max(z, axis=1)
    s = s[:, np.newaxis] # necessary step to do broadcasting
    e_x = np.exp(z - s)
    div = np.sum(e_x, axis=1)
    div = div[:, np.newaxis] # dito
    return e_x / div


#korzystam z tego, że z potencjalnego uniwersalnego ujścia nie mogą wychodzić krawędzie, a muszą wchodzić
#jeśli warunek nie jest spełniony to zmieniam potencjalne uniwersalne ujście
#dzięki dwóm wskaźniokom złożoność to O(n)

def universal_output(G):
    n = len(G)
    potential_v = 0
    j = 1
    while potential_v < n and j < n:
        if G[potential_v][j] == 1 and G[j][potential_v] == 0:
            potential_v = j
            j += 1
        elif G[potential_v][j] == 0 and G[j][potential_v] == 1:
            j += 1
        else:
            potential_v = j
            j += 1

    for i in range(n): #sprawdzam czy kandydat ma wszystkie krawedzie
        if G[i][potential_v] == 0 and potential_v != i:
            return False

    return potential_v

# 0
graph = [[0, 0, 0, 0],
         [1, 0, 0, 0],
         [1, 0, 0, 0],
         [1, 0, 1, 0]]
print(universal_output(graph))
# None
graph = [[0, 0, 0, 0, 0],
         [1, 0, 0, 0, 1],
         [1, 0, 0, 0, 1],
         [1, 0, 1, 0, 1],
         [0, 0, 0, 0, 0]]
print(universal_output(graph))
# 4
graph = [[0, 0, 0, 0, 1],
         [1, 0, 0, 0, 1],
         [1, 0, 0, 0, 1],
         [1, 0, 1, 0, 1],
         [0, 0, 0, 0, 0]]
print(universal_output(graph))

#2
graph = [[0,0,1,1,0],
         [1,0,1,0,1],
         [0,0,0,0,0],
         [0,0,1,0,1],
         [0,0,1,0,0]]
print(universal_output(graph))

#4
graph = [[0,0,0,1,1],
         [1,0,1,0,1],
         [0,0,0,0,1],
         [0,0,1,0,1],
         [0,0,0,0,0]]
print(universal_output(graph))


from collections import defaultdict
import sys
input = sys.stdin.readline
MOD = 10000003
def gcd(a, b) :
  while b > 0 :
    a, b = b, a % b
  return a

N = int(input())
num_list = [int(input()) for _ in range(N)]
count_one = lambda x : x.count(1)
dp = [defaultdict(int) for _ in range(N)]
dp[0][num_list[0]] = 1

for i in range(1, N) :
  for j in dp[i-1].keys() :
    val = gcd(num_list[i], j)
    dp[i][j] = (dp[i][j] + dp[i-1][j]) % MOD
    dp[i][val] = ( dp[i][val] + dp[i-1][j] ) % MOD
  dp[i][num_list[i]] += 1

print(dp[-1][1] % MOD)

백준/Gold/1750. 서로소의 개수/서로소의 개수.py


def file_verification(filename,hash=False):
	if not os.path.exists(cachefolder):
		os.makedirs(cachefolder)
	tempfolder=os.path.join(cachefolder, 'temp')
	if not os.path.exists(tempfolder):
		os.makedirs(tempfolder)
	verdict=False;isrestored=False;cnmt_is_patched=False
	if filename.endswith('.nsp') or filename.endswith('.nsx') or filename.endswith('.nsz') or filename.endswith('.xcz') or filename.endswith('.xci'):
		try:
			if filename.endswith('.nsp') or filename.endswith('.nsx') or filename.endswith('.nsz'):
				f = squirrelNSP(filename, 'rb')
			elif filename.endswith('.xci') or filename.endswith('.xcz'):
				f = factory(filename)
				f.open(filename, 'rb')
			check,feed=f.verify()
			if filename.endswith('.nsp') or filename.endswith('.nsx') or filename.endswith('.nsz'):
				verdict,headerlist,feed=f.verify_sig(feed,tempfolder,cnmt='nocheck')
			else:
				verdict,headerlist,feed=f.verify_sig(feed,tempfolder)
			output_type='nsp';multi=False;cnmtcount=0
			if verdict == True:
				isrestored=True
				for i in range(len(headerlist)):
					entry=headerlist[i]
					if str(entry[0]).endswith('.cnmt.nca'):
						cnmtcount+=1
						if cnmt_is_patched==False:
							status=entry[2]
							if status=='patched':
								cnmt_is_patched=True
					if entry[1]!=False:
						if int(entry[-1])==1:
							output_type='xci'
						isrestored=False
					else:
						pass
				if	isrestored == False:
					if cnmt_is_patched !=True:
						print('\nFILE VERIFICATION CORRECT.\n -> FILE WAS MODIFIED BUT ORIGIN IS CONFIRMED AS LEGIT\n')
					else:
						print('\nFILE VERIFICATION CORRECT. \n -> FILE WAS MODIFIED AND CNMT PATCHED\n')
				else:
					print("\nFILE VERIFICATION CORRECT. FILE IS SAFE.\n")
			if verdict == False:
				print("\nFILE VERIFICATION INCORRECT. \n -> UNCONFIRMED ORIGIN FILE HAS BEEN TAMPERED WITH\n")
			if 	hash==True and verdict==True:
				if filename.endswith('.nsp') or filename.endswith('.nsx') or filename.endswith('.xci'):
					verdict,feed=f.verify_hash_nca(65536,headerlist,verdict,feed)
				elif filename.endswith('.nsz'):
					verdict,feed=f.nsz_hasher(65536,headerlist,verdict,feed)
				elif filename.endswith('.xcz'):
					verdict,feed=f.xcz_hasher(65536,headerlist,verdict,feed)
			f.flush()
			f.close()
		except BaseException as e:
			Print.error('Exception: ' + str(e))
	return verdict,isrestored,cnmt_is_patched

def check_xci_certs(ifolder,tfile,tfile2):
	from listmanager import folder_to_list,striplines,read_lines_to_list
	from Fs import Xci
	import os
	if not os.path.exists(tfile):
		xci_files=folder_to_list(ifolder,['xci'])
		with open(tfile,"w", encoding='utf8') as t:
			for file in xci_files:
				t.write(file+'\n')
	else:
		xci_files=read_lines_to_list(tfile,all=True)
	counter=len(xci_files)
	for file in xci_files:
		try:
			xci=Xci(file)
			if not xci.gamecardCert.Cert_is_fake:
				print(f"{file} has personalized certificate")
				with open(tfile2,"a", encoding='utf8') as t:
					t.write(file+'\n')
			else:
				print(f"{file} has a wiped certificate")
			xci.close()
			counter-=1
			striplines(tfile,1,True)
		except:
			try:
				with open(tfile2,"a", encoding='utf8') as t:
					t.write("Error:"+file+'\n')
			except:pass
			counter-=1
			striplines(tfile,1,True)
	try:
		os.remove(tfile)
	except:pass


from collections import deque
from copy import deepcopy
from math import nextafter
import re
from itertools import combinations, chain

def read_file() -> list:
    with open(f"{__file__.rstrip('main.py')}input.txt", "r") as f:
        return [str(line) for line in f.readlines()]

def print_board(b):
    columns = ['F', *sorted(b.keys())]
    print(f"Board after move: {b['@']}")
    for i in range(4, 0, -1):
        tmp_print = []
        for col in columns:
            if col == '@':
                continue
            if col == 'F':
                tmp_print.append(f'F{i}')
            else:
                if b[col] == i:
                    tmp_print.append(col)
                else:
                    tmp_print.append('.')
        print(''.join(['{0:3}'.format(str(x)) for x in tmp_print]))

def check_floor(b, f):
    generators = set()
    microchips = set()
    for name, floor in b.items():
        if floor == f:
            if 'G' in name:
                generators.add(name[0])
            if 'M' in name:
                microchips.add(name[0])
    if (len(generators) == 0) or (len(microchips) == 0):
        return True
    if len(microchips.difference(generators)) == 0:
        return True
    return False

def is_final_floor(b):
    all_final_floor = True
    for name, floor in b.items():
        if name in ['#', '@']:
            continue
        if floor != 4:
            all_final_floor = False
            break
    return all_final_floor

def available_moves(b):
    tmp_moves = []
    elevator_floor = b['#']
    for name, floor in b.items():
        if name == '#':
            continue
        if floor == elevator_floor:
            tmp_moves.append(name)
    all_moves = chain(combinations(tmp_moves, 2), combinations(tmp_moves, 1))
    for move in all_moves:
        for direction in [-1, 1]:
            next_floor = elevator_floor + direction
            if 1 <= next_floor <= 4:
                nb = deepcopy(b)
                for m in move:
                    nb[m] = next_floor
                nb['#'] = next_floor
                if check_floor(
                        nb, elevator_floor) and check_floor(
                        nb, next_floor):
                    nb['@'] += 1
                    yield nb

def num_elem_per_floor(b):
    # 4 floors
    floors = [[0, 0], [0, 0], [0, 0], [0, 0]]
    for name, floor in b.items():
        if 'G' in name:
            floors[floor - 1][0] += 1
        if 'M' in name:
            floors[floor - 1][1] += 1
    return (b['#'], tuple(tuple(f) for f in floors))

def solve_board(b):
    already_seen = set()
    q = deque([b])

    while q:
        board = q.popleft()
        if is_final_floor(board):
            return board['@']

        for next_b in available_moves(board):
            k = num_elem_per_floor(next_b)
            if k not in already_seen:
                already_seen.add(k)
                q.append(next_b)

def read_board(inp, part_2):
    last_letter_used = 'O'
    lookup_table = {}
    floors_lookup = {
        'first': 1,
        'second': 2,
        'third': 3,
        'fourth': 4,
    }
    board = {
        '@': 0,
        '#': 1,
    }
    for line in inp:
        floor = line.split()[1]
        if (part_2) and (floors_lookup[floor] == 1):
            line = line + 'elerium generator elerium-compatible microchip dilithium generator dilithium-compatible microchip'
        generators = re.findall(r'\w+(?= generator)', line)
        for name in generators:
            if name not in lookup_table:
                lookup_table[name] = last_letter_used
                last_letter_used = chr(ord(last_letter_used) + 1)
            board[lookup_table[name] + 'G'] = floors_lookup[floor]
        microchips = re.findall(r'\w+(?=-compatible microchip)', line)
        for name in microchips:
            if name not in lookup_table:
                lookup_table[name] = last_letter_used
                last_letter_used = chr(ord(last_letter_used) + 1)
            board[lookup_table[name] + 'M'] = floors_lookup[floor]
    return board

def part_1(inp):
    board = read_board(inp, False)
    moves = solve_board(board)
    return moves

def part_2(inp):
    board = read_board(inp, True)
    moves = solve_board(board)
    return moves

def main():
    inp = read_file()
    res_1 = part_1(inp)
    print(f"res_1: {res_1}")
    res_2 = part_2(inp)
    print(f"res_2: {res_2}")

if __name__ == '__main__':
    main()