import cv2
from cvzone.HandTrackingModule import HandDetector
import math
import random as rd
import numpy as np
import time

capture = cv2.VideoCapture(0)
capture.set(3, 980)
capture.set(4, 750)

# Stone Paper Scissor
stone = cv2.imread("stone.png")
paper = cv2.imread("paper.png")
scissor = cv2.imread("scissors.png")
objectType =[1,2,3,1,2,1,2,3,1,3,1,2,3,1,2,3]
spsx = 110
spsy = 480

detector = HandDetector(maxHands=1, detectionCon=0.8)

def subX(point1, point2):
    return point1[0] - point2[0]

def subY(point1, point2):
    return point1[1] - point2[1]

def detectStonePaperScissor(img, target):
    a1, a2, a3, a4 = target[8::4]
    b1, b2, b3, b4 = target[5::4]

    hx1, hy1 = target[3][:2]
    hx2, hy2 = target[17][:2]
    d1 = math.hypot(subX(a1, b1), subY(a1, b1))
    d2 = math.hypot(subX(a2, b2), subY(a2, b2))
    d3 = math.hypot(subX(a3, b3), subY(a3, b3))
    d4 = math.hypot(subX(a4, b4), subY(a4, b4))
    h = math.hypot(hx1 - hx2, hy1 - hy2)

    mean = ((d1 + d2 + d3 + d4) / 4) / h

    if 0.20 < mean < 0.623:
        drawStone(img, target)
        return 1
    elif 0.63 < mean < 0.94:
        drawPaper(img, target)
        return 2
    elif mean > 1:
        drawScissor(img, target)
        return 3
    else:
        print(mean)
        return -1

def drawScissor(img, cursor):
    points = [8, 7, 6, 5, 9, 10, 11, 12]
    scissorColor = (170, 224, 130)
    # displayImage(img, scissor, spsx, spsy)
    for p in range(len(points) - 1):
        cv2.line(img, (cursor[points[p]][0], cursor[points[p]][1]),
                 (cursor[points[p + 1]][0], cursor[points[p + 1]][1]), scissorColor, 5)

def drawPaper(img, cursor):
    points = [0, 1, 2, 3, 4, 3, 2, 5, 6, 7, 8, 7, 6, 5, 9, 10, 11, 12, 11, 10, 9, 13, 14, 15, 16, 15, 14, 13, 17, 18,
              19, 20, 19, 18, 17, 0]
    paperColor = (233, 193, 133)
    # displayImage(img, paper, spsx, spsy)
    for p in range(len(points) - 1):
        cv2.line(img, (cursor[points[p]][0], cursor[points[p]][1]),
                 (cursor[points[p + 1]][0], cursor[points[p + 1]][1]),
                 paperColor, 5)

def drawStone(img, cursor):
    points = [4, 3, 2, 5, 6, 7, 8, 7, 6, 5, 9, 10, 11, 12, 11, 10, 9, 13, 14, 15, 16, 15, 14, 13, 17, 18, 19, 20, 19,
              18, 17]
    stoneColor = (0, 128, 255)
    # displayImage(img, stone, spsx, spsy)
    for p in range(len(points) - 1):
        cv2.line(img, (cursor[points[p]][0], cursor[points[p]][1]),
                 (cursor[points[p + 1]][0], cursor[points[p + 1]][1]),
                 stoneColor, 5)

def createRectangleText(text, cx, cy, sizex, sizey, fontSize=1, bold=2):
    cv2.rectangle(img, (cx - sizex, cy - sizey), (cx + sizex-50, cy + sizey), (255, 255, 255), cv2.FILLED)
    cv2.putText(img, f'{text}', (cx -10- sizex // 2, cy + sizey // 3), cv2.FONT_HERSHEY_DUPLEX,
                fontSize, (0, 0, 255), bold)

def displayImage(img, dispalyImg, x, y):
    desired_size = 64
    top,bottom,left,right = [10,10,10,10]

    dispalyImg = cv2.copyMakeBorder(dispalyImg, top, bottom, left, right, cv2.BORDER_CONSTANT,
                       value=(255,255,255))
    img[x:x + desired_size+20, y:y + desired_size+20, :] = dispalyImg[:desired_size+20,:desired_size+20,:]

def resultDisplay(result):
    x = 470
    y = 450
    cv2.rectangle(img, (450, 400), (630, 490), (255, 255, 255), cv2.FILLED)
    if result == "You Won":
        cv2.putText(img, f'{result}', (x,y), cv2.FONT_HERSHEY_DUPLEX,
            1, (0, 255, 0), 2)
    elif result == "You Loss":
        cv2.putText(img, f'{result}',(x,y), cv2.FONT_HERSHEY_DUPLEX,
            1, (0, 0, 255), 2)
    else:
        cv2.putText(img, f'{result}',(x,y), cv2.FONT_HERSHEY_DUPLEX,
            1, (255, 0, 0), 2)

def targetBox(img,colorCode):
    decisionBox = np.ones((200,200,3))*colorCode
    img[70:270,:200] = decisionBox

def startTimer(cx,cy,stop=False):
    cv2.circle(img, (cx, cy),30, (255, 255, 255), cv2.FILLED)
    if stop:
        cv2.putText(img, f'0', (cx-10, cy+10), cv2.FONT_HERSHEY_DUPLEX,
                1, (0, 0, 0), 1)
    else:
        cv2.putText(img, f'{int(totalTime-(time.time()-timeStart))}', (cx-10, cy+10), cv2.FONT_HERSHEY_DUPLEX,
                1, (0, 0, 0), 1)

def computerSPS(img):
    val = rd.choice(objectType)
    if val == 1:
        displayImage(img, stone, spsx, spsy)
        return 1
    elif val == 2:
        displayImage(img, paper, spsx, spsy)
        return 2
    else:
        displayImage(img, scissor, spsx, spsy)
        return 3

def lastPart():
    cv2.rectangle(img, (450, 50), (600, 250), (255, 255, 255), cv2.FILLED)
    if val == 1:
        displayImage(img, stone, spsx, spsy)
    elif val == 2:
        displayImage(img, paper, spsx, spsy)
    elif val == 3:
        displayImage(img, scissor, spsx, spsy)
    startTimer(530, 70, stop=True)
    resultDisplay(whoWin(playVal, val))
    if playVal == 1:
        drawStone(img, playerCood)
    elif playVal == 2:
        drawPaper(img, playerCood)
    else:
        drawScissor(img, playerCood)

def whoWin(userInput,systemInput):
    print(userInput,systemInput)
    if userInput == systemInput:
        print("draw")
        return "Draw"
    if userInput == 1 and systemInput == 2: # stone and paper
        print("System Win")
        return "You Loss"
    else:
        print("Player Win")
        return "You Won"

    if userInput == 2 and systemInput == 3: # paper and scissor
        print("System Win")
        return "You Loss"
    else:
        print("Player Loss")
        return "You Won"

    if userInput == 3 and systemInput == 1: # scissor and stone
        print("System Win")
        return "You Loss"
    else:
        print("Player Loss")
        return "You Won"

timeStart = time.time()
totalTime = 4
colorCode = 255

stop = 0
val = "Not selected"
playVal = -1
playerCood = []
while True:
    success, img = capture.read()
    img = cv2.flip(img, 1)
    hand = detector.findHands(img, draw=False)
    targetBox(img,colorCode)
    if stop == 1:
        lastPart()
    if hand:
        lmList = hand[0]['lmList']
        bx, by, bw, bh = hand[0]["bbox"]
        obj = detectStonePaperScissor(img, lmList)
        objText = {"1": "Stone", "2": "Paper", "3": "Scissor", "-1": "Hand not found"}
        createRectangleText(objText[str(playVal)], 100, 50, 150, 30)
        cv2.rectangle(img, (450, 50), (600, 250), (255, 255, 255), cv2.FILLED)
        if bx<200 and bx+bw < 200 and 70<by<270 and 70<by+bh<270:
            if int(totalTime-(time.time()-timeStart)) < 0:
                lastPart()
                stop = 1

            else:
                val = computerSPS(img)
                playVal = obj
                playerCood = lmList
                colorCode = 100
                startTimer(530, 70)
        else:
            colorCode = 255
            displayImage(img,stone,spsx,spsy)
            startTimer(530, 70)
            timeStart = time.time()

    else:
        createRectangleText("Hand not found", 100, 50, 150, 30, fontSize=0.7, bold=1)

    cv2.imshow("Stone Paper Scissor Detector", img)

    if cv2.waitKey(30) & 0xFF == ord('q'):
        break


"""Envoy API annotations."""

import re
from functools import partial

# Key-value annotation regex.
ANNOTATION_REGEX = re.compile('\[#([\w-]+?):\s*(.*?)\](\s?)', re.DOTALL)

# Page/section titles with special prefixes in the proto comments
DOC_TITLE_ANNOTATION = 'protodoc-title'

# Specify the type of extensions at extension points
EXTENSION_CATEGORY_ANNOTATION = 'extension-category'

# When documenting an extension, this should be used to specify the qualified
# name that the extension registers as in the static registry, e.g.
# envoy.filters.network.http_connection_manager.
EXTENSION_ANNOTATION = 'extension'

# Not implemented yet annotation on leading comments, leading to hiding of
# field.
NOT_IMPLEMENTED_HIDE_ANNOTATION = 'not-implemented-hide'

# For large protos, place a comment at the top that specifies the next free field number.
NEXT_FREE_FIELD_ANNOTATION = 'next-free-field'

# Comment that allows for easy searching for things that need cleaning up in the next major
# API version.
NEXT_MAJOR_VERSION_ANNOTATION = 'next-major-version'

# Comment. Just used for adding text that will not go into the docs at all.
COMMENT_ANNOTATION = 'comment'

# Annotation on leading comments that permits fields to be declared with the
# fully-qualified-name (FQN) type.
ALLOW_FULLY_QUALIFIED_NAME_ANNOTATION = 'allow-fully-qualified-name'

VALID_ANNOTATIONS = set([
    DOC_TITLE_ANNOTATION,
    EXTENSION_ANNOTATION,
    EXTENSION_CATEGORY_ANNOTATION,
    NOT_IMPLEMENTED_HIDE_ANNOTATION,
    NEXT_FREE_FIELD_ANNOTATION,
    NEXT_MAJOR_VERSION_ANNOTATION,
    COMMENT_ANNOTATION,
    ALLOW_FULLY_QUALIFIED_NAME_ANNOTATION,
])

# These can propagate from file scope to message/enum scope (and be overridden).
INHERITED_ANNOTATIONS = set([
    # Nothing here right now, this used to be PROTO_STATUS_ANNOTATION. Retaining
    # this capability for potential future use.
])

class AnnotationError(Exception):
    """Base error class for the annotations module."""

def extract_annotations(s, inherited_annotations=None):
    """Extract annotations map from a given comment string.

    Args:
        s: string that may contains annotations.
        inherited_annotations: annotation map from file-level inherited annotations
           (or None) if this is a file-level comment.

    Returns:
        Annotation map.
    """
    annotations = {
        k: v
        for k, v in (inherited_annotations or {}).items()
        if k in INHERITED_ANNOTATIONS
    }
    # Extract annotations.
    groups = re.findall(ANNOTATION_REGEX, s)
    for group in groups:
        annotation = group[0]
        if annotation not in VALID_ANNOTATIONS:
            raise AnnotationError('Unknown annotation: %s' % annotation)
        annotations[group[0]] = group[1].lstrip()
    return annotations

def append(s, annotation, content):
    return '%s[#%s: %s]\n' % (s, annotation, content)

def xform_sub(annotation_xforms, present_annotations, match):
    annotation, content, trailing = match.groups()
    present_annotations.add(annotation)
    annotation_xform = annotation_xforms.get(annotation)
    if annotation_xform:
        value = annotation_xform(annotation)
        return '[#%s: %s]%s' % (annotation, value, trailing) if value is not None else ''
    else:
        return match.group(0)

def xform_annotation(s, annotation_xforms):
    """Return transformed string with annotation transformers.

    The annotation will be replaced with the new value returned by the transformer.
    If the transformer returns None, then the annotation will be removed.
    If the annotation presented in transformers doesn't exist in the original string,
    a new annotation will be appended to the end of string.

    Args:
        annotation_xforms: a dict of transformers for annotations.

    Returns:
        transformed string.
    """
    present_annotations = set()

    xformed = ANNOTATION_REGEX.sub(partial(xform_sub, annotation_xforms, present_annotations), s)
    for annotation, xform in sorted(annotation_xforms.items()):
        if annotation not in present_annotations:
            value = xform(None)
            if value is not None:
                xformed = append(xformed, annotation, value)
    return xformed

def without_annotations(s):
    return re.sub(ANNOTATION_REGEX, '', s)


""""
set one number in program and give a chance to guess this set number to user,
take a input from user and check it greater or smaller than set number if less
then print increase a number and if greater than set number then print decrease
a number but u only give a 5 chance to guess this number after than game over.
"""
import random

while (True):
    print("\n\n\t\t\t GUESS THE NUMBER\n\t RULES\n>>You have 5 choices \n>>The number would be between 1 to 40\n\n")
    prize = random.randint(1,40)
    hint = random.randint(1,5)
    i = 1
    j = 0
    while i<=5:
        print("\nEnter your choice")
        guess = int(input())
        if guess == prize:
            print("\t\tCONGRATULATIONS !!! You have guessed the right number in just",i,"choices\n")
            break
        elif guess < prize :
            if guess < prize-5:
                print("Your guess is less than the answer but too far from the answer")
            else :
                print("You guess is less than the answer and very close to it ")
            print("You got",5-i,"choices left\n")
            i=i+1
        elif guess > prize :
            if guess > prize+5:
                print("Your guess is greator than the answer but too far from the answer")
            else :
                print("You guess is greator than the answer and very close to it ")
            print("You got",5-i,"choices left\n")
            i=i+1
        if j==0:
            po = input("Do you want to use a Hint ? ( y for yes and n for no )\n" )
            if po == 'y':
                print("The answer is close to",prize+hint,"\n")
                j=1

        if i==6:
            print("\n\tGAME OVER\nYou have used all your chances")
            print("The answer is ",prize)
    op = input("\nWant to play again ?\n Y for Yes\t N for No")
    if op == 'Y' or op== 'y':
        continue
    elif op == 'N' or op == 'n':
        break


import argparse
import tempfile
from pathlib import Path

import ffmpeg
import librosa
import movis as mv
import numpy as np
import openai
import pandas as pd
import soundfile as sf

def extract(args: argparse.Namespace):
    audio, sr = librosa.load(str(args.input))

    non_silent_slices = librosa.effects.split(
        audio, top_db=args.threshold, frame_length=args.frame_length)
    non_silent_regions = non_silent_slices / sr
    dst_audio = np.concatenate([audio[start:end] for start, end in non_silent_slices])
    with tempfile.TemporaryDirectory() as temp_dir:
        temp_dir = Path(temp_dir)
        audio_file = temp_dir / 'audio.wav'
        sf.write(str(audio_file), dst_audio, sr)
        ffmpeg.input(str(audio_file)).output(str(args.output), b='128k').run(overwrite_output=True)

    non_silent_frame = pd.DataFrame(non_silent_regions, columns=['start_time', 'end_time'])
    non_silent_frame.to_csv(args.region, sep='\t', index=False)

def transcribe(args: argparse.Namespace):
    client = openai.OpenAI()
    transcription = client.audio.transcriptions.create(
        model="whisper-1", file=open(args.input, 'rb'), response_format='verbose_json')
    rows = []
    for segment in transcription.segments:
        rows.append({
            'start_time': segment['start'],
            'end_time': segment['end'],
            'text': segment['text'],
        })
    frame = pd.DataFrame(rows)
    frame.to_csv(args.output, sep='\t', index=False)

def render(args: argparse.Namespace):
    subtitle = pd.read_csv(args.subtitle, sep='\t')
    region = pd.read_csv(args.region, sep='\t')
    font_name = 'M PLUS 1p'
    font_style = 'Medium'

    video = mv.trim(mv.layer.Video(args.input, audio=True), region['start_time'], region['end_time'])
    scene = mv.layer.Composition(video.size, video.duration)
    scene.add_layer(video)

    bg_layer = mv.layer.LuminanceMatte(
        mask=mv.layer.Gradient(
            size=(video.size[0], 200),
            start_point=(0.0, 0.0), end_point=(0.0, 200.0),
            start_color='#000000', end_color='#ffffff'),
        target=mv.layer.Image.from_color((video.size[0], 200), '#1b4290'))
    bg = scene.add_layer(
        bg_layer,
        position=(video.size[0] / 2, video.size[1]),
        origin_point=mv.Direction.BOTTOM_CENTER,
        opacity=0.75)
    bg.opacity.enable_motion().extend([0.0, 2.0], [0.0, bg.opacity.init_value], ['ease_out'])
    item = scene.add_layer(
        mv.layer.Text.from_timeline(
            subtitle['start_time'], subtitle['end_time'], subtitle['text'],
            font_size=64, font_family=font_name, font_style=font_style, line_spacing=100, contents=[
                mv.layer.StrokeProperty(color='#13557b', width=12),
                mv.layer.FillProperty(color='#ffffff')],
            duration=scene.duration, text_alignment='center'),
        position=(video.size[0] / 2, video.size[1] - 20.0),
        origin_point=mv.Direction.BOTTOM_CENTER)
    item.add_effect(mv.effect.DropShadow(offset=5.0, opacity=0.4, radius=3.0))

    with scene.preview(level=1):
        scene.write_video(args.output, audio=True)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()

    subparsers = parser.add_subparsers()
    parser_extract = subparsers.add_parser(
        'extract', help='Extract non-silent regions from audio and generate subtitle')
    parser_extract.add_argument('-i', '--input', default='video.mp4', type=Path)
    parser_extract.add_argument('-o', '--output', default='truncated_audio.m4a', type=Path)
    parser_extract.add_argument('--region', default='non_silent_regions.tsv', type=Path)
    parser_extract.add_argument('--threshold', default=30, type=int)
    parser_extract.add_argument('--frame_length', default=512, type=int)
    parser_extract.set_defaults(func=extract)

    parser_transcribe = subparsers.add_parser('transcribe', help='Transcribe audio with OpenAI API')
    parser_transcribe.add_argument('-i', '--input', default='truncated.m4a', type=Path)
    parser_transcribe.add_argument('-o', '--output', default='subtitle.tsv', type=Path)
    parser_transcribe.set_defaults(func=transcribe)

    parser_render = subparsers.add_parser('render', help='Render video with subtitle and non-silent regions')
    parser_render.add_argument('-i', '--input', default='video.mp4', type=Path)
    parser_render.add_argument('--region', default='non_silent_regions.tsv', type=Path)
    parser_render.add_argument('--subtitle', default='subtitle.tsv', type=Path)
    parser_render.add_argument('-o', '--output', default='video_truncated.mp4', type=Path)
    parser_render.set_defaults(func=render)

    args = parser.parse_args()
    if hasattr(args, 'func'):
        args.func(args)
    else:
        parser.print_help()


case=int(input())

for j in range(case):
    res=0
    c1=0
    c2=0
    temp=[int(x) for x in input().split(' ')]
    n=temp[0]
    x=temp[1]
    y=temp[2]
    test=input()
    if('' in test.split(' ')):
        test=test[:len(test)-1]
    rah=[int(x) for x in test.split(' ')]
    ank=[int(x) for x in input().split(' ')]
    dis1=[-1]*n
    dis2=[-1]*n
    for i in range(n):
        if(rah[i]>ank[i]):
            dis1[i]=rah[i]-ank[i]
        else:
            if(ank[i]>rah[i]):
                dis2[i]=ank[i]-rah[i]
    while(True):
        pre=max(dis1)
        if(pre==-1):
            break
        ind=dis1.index(pre)
        res+=rah[ind]
        dis1[ind]=-1
        c1+=1
        if(c1==x):
            break
    while(True):
        pre=max(dis2)
        if(pre==-1):
            break
        ind=dis2.index(pre)
        res+=ank[ind]
        dis2[ind]=-1
        c2+=1
        if(c2==y):
            break
    for i in range(n):
        if(rah[i]==ank[i]):
            res+=rah[i]
            if(c1<x):
                c1+=1
            else:
                c2+=1
        elif(not(dis1[i]==-1 and dis2[i]==-1)):
            if(c1<x):
                res+=rah[i]
                c1+=1
            else:
                res+=ank[i]
                c2+=1
    print(res)


import glob

import pandas as pd
import tqdm
from matplotlib import pyplot as plt, dates as mdates

tqdm.tqdm.pandas()

if __name__ == '__main__':
    file_list = glob.glob('../data/*.csv')

    statistics = pd.DataFrame()
    for i, file in enumerate(file_list):
        tmp = pd.read_csv(file)
        tmp = tmp[tmp.lon != 'lon']
        tmp['arrival_time'] = pd.to_datetime(tmp.arrival_time)
        statistics.loc[i, 'date'] = tmp.loc[i, 'arrival_time'].date()
        statistics.loc[i, 'records'] = len(tmp)
        statistics.loc[i, 'ID_num'] = len(tmp.M2M_MODEL_CD.unique())

    statistics = statistics.sort_values(by='date')

    fig = plt.figure(dpi=300, figsize=(15, 5))
    plt.plot(statistics.date, statistics.records, label='Total records', c='g', marker='o')
    plt.plot(statistics.date, statistics.ID_num, label='ID number', c='b', marker='x')
    ax = plt.gca()
    formatter = mdates.DateFormatter("%Y-%m-%d")
    ax.xaxis.set_major_formatter(formatter)
    # locator = mdates.DayLocator()
    # ax.xaxis.set_major_locator(locator)
    plt.gcf().autofmt_xdate()
    plt.legend()
    plt.savefig('./statistics.png')


import sys
import math
from collections import deque
sys.stdin = open('pg기능개발_in.txt', 'r')

# math.ceil(-3.14)
# progresses = [93, 30, 55]
# speeds = [1, 30, 5]

progresses = [95, 90, 99, 99, 80, 99]
speeds = [1, 1, 1, 1, 1, 1]

def solution(progresses, speeds):
    answer = []
    days = []
    completion = 100

    for i in range(len(progresses)):
        remain = completion - progresses[i]
        day = math.ceil(remain/speeds[i])
        days.append(day)

    deq = deque(days)

    while len(deq):
        value = deq.popleft()
        count = 1
        if len(deq) == 0:
            answer.append(count)
            break
        else:
            while value >= deq[0]:
                deq.popleft()
                count += 1
                if len(deq) == 0:
                    break

        answer.append(count)

    return answer

print(solution(progresses, speeds))


__doc__='''Problem 1: I want to print all items with hello in prifix but do not want to
 print hello with kiwi. kiwi should be only kiwi
 examp input: ["apple", "banana", "cherry", "kiwi", "mango"]
  output: ["hello apple", "hello banana", "hello cherry", "kiwi", "hello mango"] '''

#set all value of list with hello except kiwi
#fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
#newlist=['hello'+ " "+x for x in fruits if x!='kiwi']
#print(newlist)

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
myDict = {
    "anil",
    "rajeev"
}
fruits.append(myDict)

print(fruits)
newlist=[]
for i in fruits:
    if i != 'kiwi':
        i = 'hello ' + i
    newlist.append(i)

newlist.append(myDict)
print(newlist)


import logging
import os

from aminator.plugins.provisioner.base import BaseProvisionerPlugin
from aminator.util.linux import command, keyval_parse

__all__ = ('YumProvisionerPlugin',)
log = logging.getLogger(__name__)

class YumProvisionerPlugin(BaseProvisionerPlugin):
    """
    YumProvisionerPlugin takes the majority of its behavior from BaseProvisionerPlugin
    See BaseProvisionerPlugin for details
    """
    _name = 'yum'

    def _refresh_repo_metadata(self):
        config = self._config.plugins[self.full_name]
        return yum_clean_metadata(config.get('clean_repos', []))

    def _provision_package(self):
        result = self._refresh_repo_metadata()
        if not result.success:
            log.critical('Repo metadata refresh failed: {0.std_err}'.format(result.result))
            return False
        context = self._config.context
        if context.package.get('local_install', False):
            return yum_localinstall(context.package.arg)
        else:
            return yum_install(context.package.arg)

    def _store_package_metadata(self):
        context = self._config.context
        config = self._config.plugins[self.full_name]
        metadata = rpm_package_metadata(context.package.arg, config.get('pkg_query_format', ''),
                                        context.package.get('local_install', False))
        for x in config.pkg_attributes:
            metadata.setdefault(x, None)
        context.package.attributes = metadata

@command()
def yum_install(package):
    return 'yum --nogpgcheck -y install {0}'.format(package)

@command()
def yum_localinstall(path):
    if not os.path.isfile(path):
        log.critical('Package {0} not found'.format(path))
        return None
    return 'yum --nogpgcheck -y localinstall {0}'.format(path)

@command()
def yum_clean_metadata(repos=None):
    clean='yum clean metadata'
    if repos:
        return '{0} --disablerepo=\* --enablerepo={1}'.format(clean, ','.join(repos))
    return clean

@command()
def rpm_query(package, queryformat, local=False):
    cmd = 'rpm -q --qf'.split()
    cmd.append(queryformat)
    if local:
        cmd.append('-p')
    cmd.append(package)
    return cmd

@keyval_parse()
def rpm_package_metadata(package, queryformat, local=False):
    return rpm_query(package, queryformat, local)


import cv2
import imutils
import numpy as np
import os

def cv_show(name):
    cv2.imshow('name', name)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

# 统一的：mouse callback function
def draw_roi(img):
    # img = imutils.resize(img, width=500) 704 576
    # pts = [(249, 99), (475, 406), (497, 406), (497, 105), (249, 99)]  # 用于存放点

    pts = [(356, 130), (669, 576), (704, 576), (704, 130), (356, 130)]  # 用于存放点
    mask = np.zeros(img.shape, np.uint8)
    points = np.array(pts, np.int32)
    points = points.reshape((-1, 1, 2))
    # 画多边形
    mask = cv2.polylines(mask, [points], True, (255, 255, 255), 2)
    mask2 = cv2.fillPoly(mask.copy(), [points], (255, 255, 255))  # 用于求 ROI
    mask3 = cv2.fillPoly(mask.copy(), [points], (0, 255, 0))  # 用于 显示在桌面的图像

    show_image = cv2.addWeighted(src1=img, alpha=0.8, src2=mask3, beta=0.2, gamma=0)
    cv_show(show_image)

    ROI = cv2.bitwise_and(mask2, img)
    # res = np.hstack(show_image,ROI)
    cv_show(ROI)
    # cv2.imshow("res", res)
    cv2.waitKey(0)

# 创建图像与窗口并将窗口与回调函数绑定

img = cv2.imread("ori/1618310760.0999048.jpg")
draw_roi(img)


import os
import argparse as ap
import cv2
import numpy as np
import subprocess

def create_argparse():
    parser = ap.ArgumentParser(description="Detect abrupt scene change")
    parser.add_argument('frame_folder_path')
    parser.add_argument('output_folder_path')
    return parser.parse_args()

def compute_color_hist_diff(img1_path, img2_path):
    print(img1_path, img2_path)
    img1 = cv2.imread(img1_path, cv2.IMREAD_GRAYSCALE)
    img2 = cv2.imread(img2_path, cv2.IMREAD_GRAYSCALE)
    color_hist1 = np.bincount(img1.ravel(), minlength=256).astype(np.float32)
    color_hist1 /= np.linalg.norm(color_hist1)
    color_hist2 = np.bincount(img2.ravel(), minlength=256).astype(np.float32)
    color_hist2 /= np.linalg.norm(color_hist2)
    dist = np.sum((color_hist2 - color_hist1) ** 2)
    return dist

if __name__ == '__main__':
    args = create_argparse()
    img_paths = [os.path.join(args.frame_folder_path, item) for item in sorted(os.listdir(args.frame_folder_path))]
    num_imgs = len(img_paths)
    for i in range(1, num_imgs, 1):
        dist = compute_color_hist_diff(img_paths[i-1], img_paths[i])
        print(dist)


from bson.objectid import ObjectId

class Trade(object):
    """A class for storing Trade related information"""

    def __init__(self, trade_id=None, user=None, code=None, market=None, timeframe=None,\
                 strategy=None, description=None, open_at=0.0, qty=0, open_date=None, \
                target=0.0, stoploss=0.0, max_loss=0.0, close_at=0.0, qty_close=0, pl=0.0, review=None):
        if trade_id is None:
            self._id = ObjectId()
        else:
            self._id = trade_id
        self.user = user
        self.code = code
        self.market = market
        self.timeframe = timeframe
        self.strategy = strategy
        self.description = description
        self.open_at = open_at
        self.qty = qty
        self.open_date = open_date
        self.target = target
        self.stoploss = stoploss
        self.max_loss = max_loss
        self.close_at = close_at
        self.qty_close = qty_close
        self.pl = pl
        self.review = review

    def to_json(self):
        return json.dumps(self.__dict__)

    @classmethod
    def from_json(cls, json_str):
        json_dict = json.loads(json_str)
        return cls(**json_dict)


class Node:

    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None

def buildTree(level, ino):

    # If ino array is not empty
    if ino:
        # Check if that element exist in level order
        for i in range(0, len(level)):

            if level[i] in ino:
                node = Node(level[i])

                io_index = ino.index(level[i])
                break
    # Construction of the left and right subtree

        node.left = buildTree(level, ino[0:io_index])
        node.right = buildTree(level, ino[io_index+1: len(ino)])
        return node
    else:
        return None

def printInorder(node):
    if node is None:
        return

    printInorder(node.left)

    print(node.data, end=" ")
    printInorder(node.right)

# Driver Code
levelorder = [20, 8, 22, 4, 12, 10, 14]
inorder = [4, 8, 10, 12, 14, 20, 22]

ino_len = len(inorder)
root = buildTree(levelorder, inorder)

print("Inorder traversal of the constructed tree is")
printInorder(root)

Tree/Tree from Inorder and level order traversal.py


from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from django.urls import reverse

from .models import Article, TimePeriod, Photo, Album
from .forms import ArticleForm, TimePeriodForm, PhotoForm, AlbumForm
import datetime

def tape(request):
    articles = Article.objects.all()
    return render(request, 'tape.html', context={'articles': articles})

def view_article(request, pk):
    article = Article.objects.filter(id=pk)
    return render(request, 'view_article.html', context={'article': article})

@login_required
def write_article(request):
    form = ArticleForm
    if request.method == 'POST':
        article = Article()
        article.title = request.POST.get('title')
        article.prev = request.POST.get('prev')
        article.text = request.POST.get('text')
        if request.FILES.get('photo') is not None:
            article.photo = request.FILES.get('photo')
        article.create_preview()
        article.save()
        return redirect('/')
    return render(request, 'add_article.html', context={'form': form})

@login_required
def del_article(request, pk):
    article = Article.objects.filter(id=pk)
    article.delete()
    return redirect('/')

'''
@login_required
def edit_article(request, pk):
    ed_article = Article.objects.filter(id=pk)
    form = ArticleForm(instance=ed_article[0])
    if request.method == 'POST':
        form = ArticleForm(request.POST)
        article = form.save(commit=False)
        art_id = ed_article[0].id
        article.id = art_id
        article.photo = ed_article[0].photo
        ed_article[0].delete
        article.save()
        return redirect('tape')
    return render(request, 'add_article.html', context={'form': form})
'''

@login_required
def view_periods(request):
    form = TimePeriodForm
    if request.method == 'POST':
        form = TimePeriodForm(request.POST)
        if form.is_valid():
            period = form.save(commit=False)
            period.save()
            return redirect('periods_view')
    periods = TimePeriod.objects.all()
    return render(request, 'date_manager.html', context={'periods': periods, 'form': form})

@login_required
def del_period(request, pk):
    period = TimePeriod.objects.filter(id=pk)
    period.delete()
    return redirect('periods_view')

def view_timetable(request):
    periods = TimePeriod.objects.all()
    current_date = datetime.date.today()
    periods_to_show = []
    for period in periods:
        if period.start_date <= current_date <= period.end_date:
            periods_to_show.append(period)
    if 6 <= current_date.month <= 8:
        week = 'Лето'
    else:
        first_sep = datetime.date(current_date.year, 9, 1)
        days = int(str(current_date - first_sep).split()[0])
        week = days // 7
        if week % 2 == 0:
            week = 'четная'
        else:
            week = 'нечётная'
    return render(request, "timetable.html", context={'periods': periods_to_show, 'week': week})

def add_album(request):
    albums = Album.objects.all()
    form = AlbumForm
    if request.method == 'POST':
        form = AlbumForm(request.POST)
        if form.is_valid():
            album = form.save(commit=False)
            album.save()
            return redirect('albums')
    return render(request, "albums.html", context={'albums': albums, 'form': form})

def view_album(request, pk):
    album = Album.objects.filter(id=pk)
    photos = Photo.objects.filter(album__id=album[0].id)
    form = PhotoForm
    if request.method == 'POST':
        form = PhotoForm(request.POST, request.FILES)
        if form.is_valid():
            photo = form.save(commit=False)
            photo.album = album[0]
            photo.save()
    return render(request, "album.html", context={'form': form, 'photos': photos})

@login_required
def del_album(request, pk):
    album = Album.objects.filter(id=pk)
    album.delete()
    return redirect('/albums')


def validate_user_name(str):
    # print("Username provided inside the function is: {}".format(str))
    return_val = True
    try:
        countOfAt = str.count("@")
        countOfDot = str.count(".")
        indexOfAt = str.index("@")
        indexOfDot = str.index(".")
        lengthOfStr = indexOfDot - indexOfAt - 1

        if (countOfAt > 1) or (countOfDot > 1) or (indexOfAt < 3) or (lengthOfStr < 4):
            return_val = False
            print("Provide proper User name, Host name & Domain name")
            return return_val

        if str[0].isalpha() == False:
            return_val = False
            print("Provide User name starting with characters[a-z, A-Z]")
            return return_val

        # Returns True if username is proper else False is returned
        return return_val
    except:
        return_val = False
        print("Provide proper Username/Password")
        return return_val


from django.conf.urls import url
from . import views

app_name = 'auth'

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^loginVoter/$', views.loginVoter, name='loginVoter'),
    url(r'^validateVoter/$', views.validateVoter, name='validateVoter'),
    url(r'^logout/$', views.logout, name='logout'),
    url(r'^addAdmin/$', views.addAdmin, name='addAdmin'),
    url(r'^loginAdmin/$', views.loginAdmin, name='loginAdmin'),
    url(r'^validateAdmin/$', views.validateAdmin, name='validateAdmin'),
    #url(r'^profile/$', views.profileView, name='profileView'),

]


#!/usr/bin/python3
"""
Square
"""

def print_square(size):
    """Function that print a square with a size specified.

    """
    if not isinstance(size, int):
        raise TypeError("size must be an integer")
    if size < 0:
        raise ValueError("size must be >= 0")
    if not isinstance(size, float) and size < 0:
        raise TypeError("size must be an integer")
    for i in range(0, size):
        for j in range(0, size):
            print("#", end="")
        if i < size:
            print(end="\n")


from prettytable import PrettyTable
from math import *

def funcion(expr, x_eval, y_eval):
    x = x_eval
    y = y_eval
    funcion = eval(expr)
    return funcion

def mEulerm(ecuacion, x0, x1, y0, n):
    n = int(n)
    h = (x1-x0)/n
    x = x0
    y = y0
    # Armado de la tabla
    enc_y = f'y({x1})'
    tabla = PrettyTable(["Iteracion", "xi", "yi", "y(i+1)", "fxy prom", enc_y])
    tabla.title = "METODO DE EULER MODIFICADO"
    for i in range(0, n):
        fxy = funcion(ecuacion, x, y)

        y_cal = y + h*fxy
        fxiyi = funcion(ecuacion, x+h, y_cal)
        yi_1 = (1/2)*(fxy+fxiyi)
        y_new = y+h*yi_1
        if i < 10:
            tabla.add_row(
                [i+1, "{0:.6f}".format(x), "{0:.6f}".format(y), "{0:.6f}".format(y_cal), "{0:.6f}".format(yi_1), "{0:.6f}".format(y_new)])
        x = x+h
        y = y_new
        # print(y_cal)
    if n > 10:
        tabla.add_row(['.', '.', '.', '.','.','.'])
        tabla.add_row([n, "{0:.6f}".format(
            x), "{0:.6f}".format(y), "{0:.6f}".format(y_cal), "{0:.6f}".format(yi_1), "{0:.6f}".format(y_new)])
    print("\n")
    print(tabla)
    print(f'                      y({x1}) = {"{0:.8f}".format(y_new)}')

# datos de ejemplo
""" x0 = 0
x1 = 1
y = 2
ecuacion = 'x-y'
n = 100
mEulerm(ecuacion, x0, x1, y, n) """

src/6. Ecuaciones diferenciales ordinarias/Metodos/Euler_modificado.py


import pandas as pd
import os
from sqlalchemy import create_engine, MetaData, Table, select
import warnings
from sqlalchemy import exc as sa_exc

class SqlConnection:
    type_db = 'sqlite'
    directory_db = '\\'.join(os.getcwd().split('\\')[0:-1])
    filename_db = 'db.sqlite3'
    path_db = type_db + ':///' + directory_db + '\\' + filename_db

    def __init__(self, db_table):
        self.engine = create_engine(self.path_db)
        self.connection = self.engine.connect()
        self.metadata = MetaData()
        self.query = None
        self.results = None
        self.rowcount = 0
        self.table = Table(db_table, self.metadata, autoload=True, autoload_with=self.engine)

    def select_query(self, sqlalchemy_query, output='df'):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", category=sa_exc.SAWarning)
            self.query = sqlalchemy_query
            self.results = self.connection.execute(self.query).fetchall()
            # get rowcount and put to self.rowcount
            if output == 'df':
                return pd.DataFrame.from_records(self.results, columns=self.query.columns.keys())
            if output == 'records':
                return self.results

    def insert_query(self, sqlalchemy_query, insert_values):
        values_list = [x for x in insert_values.T.to_dict().values()]
        self.results = self.connection.execute(sqlalchemy_query, values_list)
        # get rowcount and put to self.rowcount

    def update_query(self, sqlalchemy_query):
        self.results = self.connection.execute(sqlalchemy_query)
        # get rowcount and put to self.rowcount

if __name__ == '__main__':
    s = SqlConnection('stockindex_app_stock')
    q = select([s.table])

    test_records_update = [(1, 'BUI', 'Buhler Industries',   3.69,  0, 0, 9.22500000e+07, 'TSX', 'TSX:BUI', '',
                            3.69,  3.69,  3.69, 3.94, 3.53, 25000000),
                         (2, 'BYD-UN', 'The Boyd Group', 111.1,  7.68, 0, 2.33681536e+09, 'TSX', 'TSX:BYD-UN', '',
                          118.78, 115.97, 121.21, 133, 102.59,  19673475),
                         (3, 'GWO', 'Great West Life Company',  27.87,  2.13, 0, 2.96515036e+10, 'TSX', 'TSX:GWO', '',
                          30,  30.55,  30.59, 33.1,  28.37, 988383452),
                         (4, 'IGM', 'IGM Financial',  22.37, 12.47, 0, 8.39154568e+09, 'TSX', 'TSX:IGM', '',
                          34.84,  34.26,  34.84, 39.95, 31.54, 240859520),
                         (5, 'PBL', 'Pollard Banknote',  19.53,  2.84, 0, 5.73245969e+08, 'TSX', 'TSX:PBL', '',
                          22.37,  22.1,  22.37, 27.75,  19.91,  25625658),
                         (6, 'NFI', 'New Flyer Industries',  34.31,  3.05, 0, 2.32951738e+09, 'TSX', 'TSX:NFI', '',
                          37.36,  38.21,  38.42, 52.48,  32.95,  62353249),
                         (7, 'NWC', 'Northwest Company',  28,  1.3, 0, 1.42685108e+09, 'TSX', 'TSX:NWC', '',
                          29.3 ,  29.29,  29.44, 30.6 ,  27.03,  48697989),
                         (8, 'EIF', 'Exchange Income Corp',  30.23,  0.76, 0, 9.72296840e+08, 'TSX', 'TSX:EIF', '',
                          30.99,  31.3,  31.48, 35.34,  26.87,  31374535),
                         (9, 'AFN', 'Ag Growth International',  50,  3.63, 0, 9.84849521e+08, 'TSX', 'TSX:AFN', '',
                          53.63,  54.44,  54.44, 64.72,  47.84,  18363780)]


#Circle Recursion
#By Daniel Graham

import turtle
import math

color_list = ['red', 'orange', 'yellow', 'green', 'blue', 'purple']

turtle.penup()
turtle.forward(400)
turtle.pendown()
turtle.right(90)
turtle.forward(1)
turtle.pencolor('red')
def circle(n):
    turtle.pencolor(color_list[int((n % 6))])
    turtle.right(n)
    turtle.forward(10)
    if n <= 500:
        circle(n + .1)

circle(0)


#imports
from openmsistream.utilities.argument_parsing import existing_dir, OpenMSIStreamArgumentParser

class OpenMSIPythonArgumentParser(OpenMSIStreamArgumentParser) :

    ARGUMENTS = {**OpenMSIStreamArgumentParser.ARGUMENTS,
        'pdv_plot_type':
            ['optional',{'choices':['spall','velocity'],'default':'spall',
                         'help':'Type of analysis to perform ("spall" or "velocity")'}],
        'gemd_json_dir':
            ['positional',{'type':existing_dir,
                           'help':'Directory containing all of the GEMD JSON dump files that should be uploaded'}]
    }


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def goodNodes(self, root: TreeNode) -> int:

        ans = 0

        def dfs(node, mx):
            if not node: return

            if node.val >= mx:
                nonlocal ans
                ans += 1
                mx = node.val

            dfs(node.left, mx)
            dfs(node.right, mx)

        dfs(root, float('-inf'))

        return ans


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

# # Analysis of the particle sizes from segmentation output
# You should have an output file named `Results.csv` from FIJI/ImageJ segmentation. If you are using Google Colab to run this code, you will need to upload the file manually to Google using the `File` menu to the left.

# In[7]:

import pandas as pd
import numpy as np
import seaborn as sns

# In[2]:

get_ipython().system('pip install pandas')

# Write code below to read the `Results.csv` file as a pandas DataFrame and store it in the object named `measurements`. Show the head of the DataFrame.

# In[4]:

get_ipython().system('pip install numpy')

# In[6]:

get_ipython().system('pip install seaborn')

# In[18]:

# Code to read Results and show head
measurements = pd.read_csv('Results.csv')
measurements.head()

# In[22]:

# Code to plot a histogram of the Area
sns.histplot(measurements, x="Area")

# Calculate the mean and the standard deviation of the distribution and show them below. (HINT: pandas can do this easily)

# In[27]:

# Calculate mean
measurements['Area'].mean()

# In[29]:

# Calculate standard deviation
measurements['Area'].std()

# #### Describe your interpretation of the distribution of the measurements of nuclear area below.
# Based on what you see, would you choose different value ranges of particle sizes for counting? Explain why.
#

# The current mean has a very high standard deviation (65.5), which should not really be the case for nuclei areas. The range of particle sizes should be set to lower to segment nuclei close together seperately.

# In[ ]:


def mutate_string(string, position, character):
    l =[]
    for i in string:
        l.append(i)
    l[position] = character
    st = "".join(l)
    return st

if __name__ == '__main__':
    s = input()
    i, c = input().split()
    s_new = mutate_string(s, int(i), c)
    print(s_new)


import numpy as np
import matplotlib.pyplot as plt
class NoamOpt:
    "Optim wrapper that implements rate."

    def __init__(self, model_size, factor, warmup, initial_lr, optimizer):
        self.optimizer = optimizer
        self._step = 0
        self.warmup = warmup
        self.factor = factor
        self.model_size = model_size
        self._rate = 0
        self.initial_lr = initial_lr

    def step(self):
        "Update parameters and rate"
        self._step += 1
        rate = self.rate()
        for p in self.optimizer.param_groups:
            p['lr'] = rate
        self._rate = rate
        self.optimizer.step()

    def rate(self, step=None):
        "Implement `lrate` above"
        if step is None:
            step = self._step
        return self.initial_lr + self.factor * \
               (self.model_size ** (-0.5) *
                min(step ** (-0.5), step * self.warmup ** (-1.5)))

if __name__ == '__main__':
    opts = [NoamOpt(512, 1, 4000, 0.01, None),
            NoamOpt(512, 1, 8000, 0.01, None),
            NoamOpt(256, 1, 4000, 0.01, None)]
    plt.plot(np.arange(1, 20000), [[opt.rate(i) for opt in opts] for i in range(1, 20000)])
    plt.legend(["512:4000", "512:8000", "256:4000"])
    plt.show()


import numpy as np
import csv
import sys
from sklearn.metrics import mean_squared_error

"""
Predicts the target values for data in the file at 'test_X_file_path', using the weights learned during training
Writes the predicted values to the file named "predicted_test_Y.csv". It should be created in the same directory where this code file is present.
This code is provided to help you get started and is NOT a proper implementation. Modify it based on the requirements of the project.
"""
def predict(test_X_file_path):

    # Load Test Data
    Xi = np.genfromtxt(test_X_file_path, delimiter=',', skip_header=1)
    test_X = np.ones((len(Xi), 5))
    test_X[:, 1:] = Xi
    W = np.array([-153.91168068, -22.98896794, 60.9467379, 31.81349104, 3.79769093])

    # Predict Target Variables
    """
    You can make use of any other helper functions which might be needed.
    Make sure all such functions are submitted in SubmissionCode.zip and imported properly.
    """

    # Write Outputs to 'predicted_test_Y.csv' file

    predicted_Y_values = np.matmul(test_X, W)
    with open('predicted_test_Y.csv', 'w') as csv_file:
        writer = csv.writer(csv_file)
        for y in predicted_Y_values:
            writer.writerow([y])

    Y = np.genfromtxt("train_Y_lr.csv", delimiter=',')
    print(mean_squared_error(Y, predicted_Y_values))

if __name__ == "__main__":
    predict(sys.argv[1])


li=[]
c=0
sum=0
for i in range(6):
    li.append(float(input()))
    if li[i]>0:
        c=c+1
        sum=sum+li[i]
print(str(c) +" valores positivos")
average=sum/c
print("%.1f"%average)


#!/usr/bin/python3.8
# -*- coding:utf-8 -*-
import shapely
import random
import math
from shapely.ops import split, nearest_points
from multiprocessing import Pool

from .compute_kernel import GetKernel
from .compute_visibility import GetVisibilityPolygon
from ..Test.draw_pictures import *
def SelectMaxPolygon(polygons):
    MaxPolygon = None
    if polygons is None:
        print("polygons is None")
        return None
    elif (type(polygons) == shapely.Polygon):
        MaxPolygon = polygons
    else:
        for p in list(polygons.geoms):
            if (type(p) == shapely.MultiPolygon) or (type(p) == shapely.GeometryCollection):
                p = SelectMaxPolygon(p)
            elif MaxPolygon == None or ((type(p) == shapely.Polygon) and p.area > MaxPolygon.area):
                MaxPolygon = p
    if(MaxPolygon) == None:
        print("SelectMaxPolygon Failed",type(polygons))
    return MaxPolygon

def SelectPointFromPolygon(polygon):
    minx, miny, maxx, maxy = polygon.bounds
    tempPolygon = polygon.buffer(-1)
    while True:
        p = shapely.Point(random.uniform(minx, maxx),
                          random.uniform(miny, maxy))
        if tempPolygon.contains(p):
            return p
def FindVisibleRegion(polygon, watcher, d = 32, useCPP = False):

    visiblePolygon = GetVisibilityPolygon(polygon, watcher)

    dVisibility = watcher.buffer(d)  # d范围视距
    visiblePolygon = visiblePolygon.intersection(dVisibility)  # 有限视距下的可视范围

    visiblePolygon = SelectMaxPolygon(visiblePolygon)
    if(visiblePolygon == None):
        print("failed find visibile polygon")

    return visiblePolygon.simplify(1, preserve_topology=False)

def GetKernelPolygon(visiblePolygon):
    xList, yList = GetKernel(visiblePolygon)
    kernel = list(zip(xList, yList))
    return shapely.Polygon(kernel)

def GetRayLine(watcher, vertex):
    xGap = vertex[0] - watcher[0]
    yGap = vertex[1] - watcher[1]
    rate = (1/(math.hypot(xGap, yGap)))*1e10
    extendPoint1 = (watcher[0] + xGap*rate,watcher[1] + yGap*rate)
    extendPoint2 = (watcher[0] - xGap*rate,watcher[1] - yGap*rate)
    return shapely.LineString([extendPoint1, extendPoint2])

def GetSingleReflexChord(visiblePolygonPointList, reflexPoint, kernel):

    prependicular = None
    kernelPointList = list(kernel.exterior.coords)
    kernelPointList.pop()
    kernelPointList.reverse()
    if (reflexPoint in list(kernelPointList)):  # 如果反射点在kernel上
        numOfKernelPoints = len(kernelPointList)
        reflex_kernel_pos = visiblePolygonPointList.index(reflexPoint)
        reflexKernelLeft = kernelPointList[(reflex_kernel_pos - 1) % numOfKernelPoints]
        reflexKernelRight = kernelPointList[(reflex_kernel_pos + 1) % numOfKernelPoints]
        # 和弦的斜率应为 反射点临边斜率的平均值
        if (abs(reflexPoint[0] - reflexKernelLeft[0]) < 1e-2 or abs(reflexKernelRight[0] - reflexPoint[0]) < 1e-2):
            extendPoint = (reflexPoint[0], reflexPoint[1] + 1)
        else:
            prependicular1 = (reflexKernelRight[1] - reflexPoint[1]) / (reflexKernelRight[0] - reflexPoint[0])
            prependicular2 = (reflexPoint[1] - reflexKernelLeft[1]) / (reflexPoint[0] - reflexKernelLeft[0])

            prependicular = (prependicular1 + prependicular2) / 2
            extendPoint = (reflexPoint[0]+1, reflexPoint[1] + prependicular)
    else:
        point = shapely.Point(reflexPoint)  # 如果反射点不在kernel上
        nearestPoint = (nearest_points(point, kernel))[1]
        # 和弦的斜率应为 点连线的垂线的斜率
        if abs(point.y - nearestPoint.y) < 1e-6:  # 斜率判断
            extendPoint = (reflexPoint[0], reflexPoint[1] + 1)

        else:
            prependicular = (nearestPoint.x - point.x) / (point.y - nearestPoint.y)
            extendPoint = (reflexPoint[0]+1, reflexPoint[1] + prependicular)
    return GetRayLine(reflexPoint, extendPoint)

def GetSplitedPolygon(chord, visiblePolygon, watcher):
    polygon = shapely.Point(1,1)
    tempVisiblePolygon = visiblePolygon
    polygons = list(split(tempVisiblePolygon, chord).geoms)
    for polygon in polygons:
        if type(polygon) == (shapely.Polygon) and polygon.contains(watcher):
            return polygon
    # print(polygons)
    return polygon

def MaximallyCoveringConvexSubset(args):  # MCCS
    unCoveredPolygon = args[0]
    initialPolygon = args[1]
    watcher = args[2]
    d = args[3]
    visiblePolygon = FindVisibleRegion(
        initialPolygon, watcher, d,False)  # d为可视距离

    kernelPolygon, reflexPointList = GetKernel(visiblePolygon, watcher)
    reflexPointList.sort(key=lambda watcher: shapely.distance(
        kernelPolygon, shapely.Point(watcher)))  # 列表排序
    polygon = visiblePolygon
    numOfReflexPoints = len(reflexPointList)

    for i in range(numOfReflexPoints):

        polygonPointList = list(polygon.exterior.coords)
        polygonPointList.pop()
        numOfPolygonPoints = len(polygonPointList)
        reflexPoint1 = reflexPointList[i]
        reflexPoint2 = reflexPointList[(i+1) % numOfReflexPoints]

        if (reflexPoint1 not in polygonPointList):
            continue
        r1Pos = polygonPointList.index(reflexPoint1)
        r1Left = polygonPointList[(r1Pos - 1) % numOfPolygonPoints]
        r1Right = polygonPointList[(r1Pos + 1) % numOfPolygonPoints]

        # extremal chords
        chord = GetRayLine(reflexPoint1, r1Left)
        ePolygon1 = GetSplitedPolygon(chord, polygon, watcher)

        chord = GetRayLine(reflexPoint1, r1Right)
        ePolygon2 = GetSplitedPolygon(chord, polygon, watcher)

        # two reflex chord
        if (len(reflexPointList) > 1):
            chord = GetRayLine(reflexPoint1, reflexPoint2)
            tPolygon = GetSplitedPolygon(chord, polygon, watcher)
        else:
            tPolygon = shapely.Point(1, 1)  # area of point is 0

        # single reflex chord
        chord = GetSingleReflexChord(
            polygonPointList, reflexPoint1, kernelPolygon)
        sPolygon = GetSplitedPolygon(chord, polygon, watcher)
        polygon = max(ePolygon1, ePolygon2, tPolygon, sPolygon, key=lambda inptPolygon: (
            unCoveredPolygon.intersection(inptPolygon)).area)
    return polygon

def PolygonCover(polygon, d, coverage, iterations=32):
    polygonCoverList = []
    unCoverPolygon = shapely.Polygon(polygon)
    pool = Pool(8)
    while ((unCoverPolygon.area / polygon.area) > (1-coverage)):

        point = SelectPointFromPolygon(unCoverPolygon)
        R0 = MaximallyCoveringConvexSubset((unCoverPolygon, polygon, point, d))
        bestR = R0
        #迭代开始
        num = iterations
        pointList = []
        while num > 0:
            pointList.append(SelectPointFromPolygon(R0))
            num -= 1
        RList =(pool.map(MaximallyCoveringConvexSubset,[(unCoverPolygon, polygon, point, d) for point in pointList]))
        RList.append(R0)
        bestR = max(RList,key=lambda R:(R.intersection(unCoverPolygon)).area)
        bestR = bestR.simplify(0.05,False)

        polygonCoverList.append(bestR)
        unCoverPolygon = unCoverPolygon.difference(bestR)
        if(type(unCoverPolygon) == shapely.GeometryCollection):
            polygonList = []
            for geoms in unCoverPolygon.geoms:
                if type(geoms) == shapely.Polygon:
                    polygonList.append(geoms)
            unCoverPolygon = shapely.GeometryCollection(polygonList)

    return polygonCoverList


# Python program to get the Fibonacci series between 0 to 50
print("Fibonacci Series")
desired_number = int(input("Enter Any Number Between 0-50 : "))

# first two numbers of the Fibonacci series
fib1 = 0
fib2 = 1

count = 0

if desired_number <= 0: #when input is a negative integer or Zero
   print("Please enter a positive integer")
elif desired_number == 1: #when input is equal to 1
   print("Fibonacci sequence upto",desired_number,":")
   print(fib1)
elif desired_number > 50: # when input is greater than 50
    print("Wrong Input, Please enter Number from 0-50")
else:
   print("Fibonacci sequence for",desired_number,":")
   while count < desired_number:
       print(fib1,end = " ")
       num1 = fib1 + fib2
       fib1 = fib2
       fib2 = num1
       count += 1


from typing import Any, Dict

import attr
import numpy as np

from nlisim.coordinates import Voxel
from nlisim.diffusion import apply_diffusion
from nlisim.grid import RectangularGrid
from nlisim.module import ModuleModel, ModuleState
from nlisim.modules.molecules import MoleculesState
from nlisim.random import rg
from nlisim.state import State
from nlisim.util import activation_function, turnover_rate

def molecule_grid_factory(self: 'TGFBState') -> np.ndarray:
    return np.zeros(shape=self.global_state.grid.shape, dtype=float)

@attr.s(kw_only=True, repr=False)
class TGFBState(ModuleState):
    grid: np.ndarray = attr.ib(
        default=attr.Factory(molecule_grid_factory, takes_self=True)
    )  # units: atto-mols
    half_life: float  # units: min
    half_life_multiplier: float  # units: proportion
    macrophage_secretion_rate: float  # units: atto-mol * cell^-1 * h^-1
    macrophage_secretion_rate_unit_t: float  # units: atto-mol * cell^-1 * step^-1
    k_d: float  # aM

class TGFB(ModuleModel):
    """TGFB"""

    name = 'tgfb'
    StateClass = TGFBState

    def initialize(self, state: State) -> State:
        tgfb: TGFBState = state.tgfb

        # config file values
        tgfb.half_life = self.config.getfloat('half_life')  # units: min
        tgfb.macrophage_secretion_rate = self.config.getfloat(
            'macrophage_secretion_rate'
        )  # units: atto-mol * cell^-1 * h^-1
        tgfb.k_d = self.config.getfloat('k_d')  # units: aM

        # computed values
        tgfb.half_life_multiplier = 0.5 ** (
            self.time_step / tgfb.half_life
        )  # units in exponent: (min/step) / min -> 1/step
        # time unit conversions
        tgfb.macrophage_secretion_rate_unit_t = tgfb.macrophage_secretion_rate * (
            self.time_step / 60
        )  # units: atto-mol/(cell*h) * (min/step) / (min/hour)

        return state

    def advance(self, state: State, previous_time: float) -> State:
        """Advance the state by a single time step."""
        from nlisim.modules.macrophage import MacrophageCellData, MacrophageState
        from nlisim.modules.phagocyte import PhagocyteStatus

        tgfb: TGFBState = state.tgfb
        molecules: MoleculesState = state.molecules
        macrophage: MacrophageState = state.macrophage
        voxel_volume: float = state.voxel_volume
        grid: RectangularGrid = state.grid

        for macrophage_cell_index in macrophage.cells.alive():
            macrophage_cell: MacrophageCellData = macrophage.cells[macrophage_cell_index]
            macrophage_cell_voxel: Voxel = grid.get_voxel(macrophage_cell['point'])

            if macrophage_cell['status'] == PhagocyteStatus.INACTIVE:
                tgfb.grid[tuple(macrophage_cell_voxel)] += tgfb.macrophage_secretion_rate_unit_t
                if (
                    activation_function(
                        x=tgfb.grid[tuple(macrophage_cell_voxel)],
                        k_d=tgfb.k_d,
                        h=self.time_step / 60,  # units: (min/step) / (min/hour)
                        volume=voxel_volume,
                        b=1,
                    )
                    > rg.uniform()
                ):
                    macrophage_cell['status_iteration'] = 0

            elif macrophage_cell['status'] not in {
                PhagocyteStatus.APOPTOTIC,
                PhagocyteStatus.NECROTIC,
                PhagocyteStatus.DEAD,
            }:
                if (
                    activation_function(
                        x=tgfb.grid[tuple(macrophage_cell_voxel)],
                        k_d=tgfb.k_d,
                        h=self.time_step / 60,  # units: (min/step) / (min/hour)
                        volume=voxel_volume,
                        b=1,
                    )
                    > rg.uniform()
                ):
                    macrophage_cell['status'] = PhagocyteStatus.INACTIVATING
                    macrophage_cell[
                        'status_iteration'
                    ] = 0  # Previously, was no reset of the status iteration

        # Degrade TGFB
        tgfb.grid *= tgfb.half_life_multiplier
        tgfb.grid *= turnover_rate(
            x=np.array(1.0, dtype=np.float64),
            x_system=0.0,
            base_turnover_rate=molecules.turnover_rate,
            rel_cyt_bind_unit_t=molecules.rel_cyt_bind_unit_t,
        )

        # Diffusion of TGFB
        tgfb.grid[:] = apply_diffusion(
            variable=tgfb.grid,
            laplacian=molecules.laplacian,
            diffusivity=molecules.diffusion_constant,
            dt=self.time_step,
        )

        return state

    def summary_stats(self, state: State) -> Dict[str, Any]:
        tgfb: TGFBState = state.tgfb
        voxel_volume = state.voxel_volume

        return {
            'concentration (nM)': float(np.mean(tgfb.grid) / voxel_volume / 1e9),
        }

    def visualization_data(self, state: State):
        tgfb: TGFBState = state.tgfb
        return 'molecule', tgfb.grid


def ext_euclid(a, b):
    # 互いに素なa,bに対して、方程式ax+by=1の整数解を1つ求める
    x0, y0, r0 = 1, 0, a
    x1, y1, r1 = 0, 1, b
    while r0:
        x0, x1 = x1 - x0 * (r1 // r0), x0
        y0, y1 = y1 - y0 * (r1 // r0), y0
        r0, r1 = r1 % r0, r0
    return x1, y1, r1

t = int(input())
query = [map(int, input().split()) for _ in range(t)]
for n, s, k in query:
    _, _, r = ext_euclid(k, n)
    if s % r != 0:
        print(-1)
        continue
    k, n, s = k // r, n // r, s // r
    x, _, _ = ext_euclid(k, n)
    print(-s * x % n)


import pytest

@pytest.fixture
def create_overdue_books_query(library_ma_tables, get_uid, client):
    checkouts = library_ma_tables["Checkouts"]
    patrons = library_ma_tables["Patrons"]
    items = library_ma_tables["Items"]
    publications = library_ma_tables["Publications"]
    request_data = {
        "name": get_uid(),
        "base_table": checkouts.id,
        "initial_columns": [
            {
                "id": checkouts.get_column_by_name("id").id,
                "alias": "Checkout id"
            }, {
                "id": checkouts.get_column_by_name("Due Date").id,
                "alias": "Due Date"
            }, {
                "id": checkouts.get_column_by_name("Check In Time").id,
                "alias": "Check In Time"
            }, {
                "id": patrons.get_column_by_name("Email").id,
                "alias": "email",
                "display_name": "Patron Email",
                "jp_path": [
                    [
                        checkouts.get_column_by_name("Patron").id,
                        patrons.get_column_by_name("id").id,
                    ]
                ]
            }, {
                "id": publications.get_column_by_name("Title").id,
                "alias": "Book Title",
                "jp_path": [
                    [
                        checkouts.get_column_by_name("Item").id,
                        items.get_column_by_name("id").id,
                    ], [
                        items.get_column_by_name("Publication").id,
                        publications.get_column_by_name("id").id,
                    ]
                ]
            },
        ],
        "transformations": [
            {
                "spec": {
                    "lesser": [
                        {"column_name": ["Due Date"]},
                        {"literal": ["2022-08-10"]}
                    ]
                },
                "type": "filter"
            },
            {
                "spec": {
                    "empty": [{"column_name": ["Check In Time"]}]
                },
                "type": "filter"
            },
            {
                "spec": {
                    "grouping_expressions": [{"input_alias": "email"}],
                    "aggregation_expressions": [
                        {
                            "input_alias": "Book Title",
                            "output_alias": "Title List",
                            "function": "aggregate_to_array"
                        }
                    ]
                },
                "type": "summarize",
                "display_names": {
                    "Title List": "Titles"
                }
            }
        ],

    }
    response = client.post('/api/db/v0/queries/', data=request_data)
    assert response.status_code == 201
    return response

@pytest.fixture
def check_overdue_books_columns(create_overdue_books_query, client):
    query_id = create_overdue_books_query.json()['id']
    expect_response_data = [
        {
            'alias': 'Title List',
            'display_name': 'Titles',
            'type': '_array',
            'type_options': {'item_type': 'text'},
            'display_options': None
        }, {
            'alias': 'email',
            'display_name': 'Patron Email',
            'type': 'mathesar_types.email',
            'type_options': None,
            'display_options': None
        }
    ]
    actual_response_data = client.get(f'/api/db/v0/queries/{query_id}/columns/').json()
    assert sorted(actual_response_data, key=lambda x: x['alias']) == expect_response_data
    return query_id

@pytest.fixture
def run_overdue_books_scenario(check_overdue_books_columns, client):
    query_id = check_overdue_books_columns
    expect_records = [
        {
            'email': 'eduardorojas13@peterson-curry.com',
            'Title List': ['Bar Order Might Per', 'Hand Raise Son Probably Do']
        }, {
            'email': 'heatherwheeler@peterson-delgado.com',
            'Title List': ['Bar Order Might Per', 'I Worker Suffer Likely']
        }, {
            'email': 'jhooper@bowers.com',
            'Title List': ['Military Myself Sport Wrong']
        }, {
            'email': 'kathyb@le.org',
            'Title List': ['Pass Street Year']
        }, {
            'email': 'kwright@odonnell.com',
            'Title List': ['Day Beyond Property', 'On Letter Experience']
        }, {
            'email': 'tevans46@thompson.net',
            'Title List': ['Space Music Rest Crime']
        }, {
            'email': 'y.ho@johnson.info',
            'Title List': ['Mention Add Size City Kid', 'Economic Too Level']
        }
    ]
    actual_records = sorted(
        client.get(f'/api/db/v0/queries/{query_id}/records/').json()['results'],
        key=lambda x: x['email']
    )
    for rec_pair in zip(actual_records, expect_records):
        assert rec_pair[0]['email'] == rec_pair[1]['email']
        assert sorted(rec_pair[0]['Title List']) == sorted(rec_pair[1]['Title List'])

@pytest.fixture
def create_monthly_checkouts_query(run_overdue_books_scenario, get_uid, client):
    _ = run_overdue_books_scenario
    checkouts = {
        t["name"]: t for t in client.get("/api/db/v0/tables/").json()["results"]
    }["Checkouts"]
    columns = {
        c["name"]: c for c in checkouts["columns"]
    }
    request_data = {
        "name": get_uid(),
        "base_table": checkouts["id"],
        "initial_columns": [
            {"id": columns["id"]["id"], "alias": "id"},
            {"id": columns["Checkout Time"]["id"], "alias": "Checkout Time"},
        ],
        "transformations": [
            {
                "spec": {
                    "grouping_expressions": [
                        {
                            "input_alias": "Checkout Time",
                            "output_alias": "Checkout Month",
                            "preproc": "truncate_to_month",
                        }
                    ],
                    "aggregation_expressions": [
                        {
                            "input_alias": "id",
                            "output_alias": "Count",
                            "function": "count",
                        }
                    ]
                },
                "type": "summarize",
                "display_names": {
                    "Checkout Month": "Month",
                    "Count": "Number of Checkouts"
                }
            }
        ]
    }
    response = client.post('/api/db/v0/queries/', data=request_data)
    assert response.status_code == 201
    return response

@pytest.fixture
def check_monthly_checkouts_columns(create_monthly_checkouts_query, client):
    query_id = create_monthly_checkouts_query.json()['id']
    expect_repsonse_data = [
        {
            'alias': 'Checkout Month',
            'display_name': 'Month',
            'type': 'text',
            'type_options': None,
            'display_options': None
        }, {
            'alias': 'Count',
            'display_name': 'Number of Checkouts',
            'type': 'integer',
            'type_options': None,
            'display_options': None
        }
    ]
    actual_response_data = client.get(f'/api/db/v0/queries/{query_id}/columns/').json()
    assert sorted(actual_response_data, key=lambda x: x['alias']) == expect_repsonse_data
    return query_id

def test_monthly_checkouts_scenario(check_monthly_checkouts_columns, client):
    query_id = check_monthly_checkouts_columns
    expect_records = [
        {'Checkout Month': '2022-05', 'Count': 39},
        {'Checkout Month': '2022-06', 'Count': 26},
        {'Checkout Month': '2022-07', 'Count': 29},
        {'Checkout Month': '2022-08', 'Count': 10},
    ]
    actual_records = client.get(f'/api/db/v0/queries/{query_id}/records/').json()['results']
    assert sorted(actual_records, key=lambda x: x['Checkout Month']) == expect_records