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

from collections import defaultdict
import json
from typing import Any, DefaultDict, Dict, List

from django.core.serializers.json import DjangoJSONEncoder
from django.db import connection
from django.http import HttpRequest, JsonResponse

from guardian.utils import get_anonymous_user

from catmaid.models import UserRole, Review, ReviewerWhitelist
from catmaid.control.authentication import requires_user_role

def get_treenodes_to_reviews(treenode_ids=None, skeleton_ids=None,
                             umap=lambda r: r) -> DefaultDict[Any, List]:
    """ Returns a dictionary that contains all reviewed nodes of the
    passed <treenode_ids> and/or <skeleton_ids> lists as keys. The
    reviewer user IDs are kept in a list as values. A function can be
    passed to which is executed for every reviewer_id to change the
    value stored  result (e.g. to use user names instead of an ID. It
    defaults to the identity and therefore reviewer IDs.
    """
    # Set up filters
    reviews = Review.objects.all()
    if treenode_ids:
        reviews = reviews.filter(treenode_id__in=treenode_ids)
    if skeleton_ids:
        reviews = reviews.filter(skeleton_id__in=skeleton_ids)
    # Only request treenode ID and reviewer ID
    reviews = reviews.values_list('treenode_id', 'reviewer_id')
    # Build dictionary
    treenode_to_reviews:DefaultDict[Any, List] = defaultdict(list)
    for tid, rid in reviews:
        treenode_to_reviews[tid].append(umap(rid))

    return treenode_to_reviews

def get_treenodes_to_reviews_with_time(treenode_ids=None, skeleton_ids=None,
                             umap=lambda r: r) -> DefaultDict[Any, List]:
    """ Returns a dictionary that contains all reviewed nodes of the
    passed <treenode_ids> and/or <skeleton_ids> lists as keys. The
    reviewer user IDs are kept in a list as values. A function can be
    passed to which is executed for every reviewer_id to change the
    value stored  result (e.g. to use user names instead of an ID. It
    defaults to the identity and therefore reviewer IDs.
    """
    reviews = Review.objects.all()
    if treenode_ids:
        reviews = reviews.filter(treenode_id__in=treenode_ids)
    if skeleton_ids:
        reviews = reviews.filter(skeleton_id__in=skeleton_ids)
    # Only request treenode ID and reviewer ID
    reviews = reviews.values_list('treenode_id', 'reviewer_id', 'review_time')
    # Build dictionary
    treenode_to_reviews:DefaultDict[Any, List] = defaultdict(list)
    for tid, rid, rtime in reviews:
        treenode_to_reviews[tid].append( (umap(rid),rtime) )

    return treenode_to_reviews

def get_review_count(skeleton_ids) -> DefaultDict:
    """ Returns a dictionary that maps skeleton IDs to dictonaries that map
    user_ids to a review count for this particular skeleton.
    """
    # Count nodes that have been reviewed by each user in each partner skeleton
    cursor = connection.cursor()
    cursor.execute('''
        SELECT skeleton_id, reviewer_id, count(*)
        FROM review
        WHERE skeleton_id = ANY(%(skeleton_ids)s::bigint[])
        GROUP BY reviewer_id, skeleton_id
    ''', {
        'skeleton_ids': skeleton_ids,
    })
    # Build dictionary
    reviews:DefaultDict = defaultdict(lambda: defaultdict(int))
    for row in cursor.fetchall():
        reviews[row[0]][row[1]] = row[2]

    return reviews

def get_review_status(skeleton_ids, project_id=None, whitelist_id=False,
        user_ids=None, excluding_user_ids=None) -> Dict:
    """ Returns a dictionary that maps skeleton IDs to their review
    status as an array of total nodes and number of reviewed nodes
    (integers). If <whitelist_id> is not false, reviews are filtered
    according to the user's whitelist. Otherwise, if <user_ids>
    evaluates to false a union review is returned. Otherwise a list of
    user IDs is expected to create a review status for a sub-union or a
    single user.
    """
    if user_ids and excluding_user_ids:
        raise ValueError("user_ids and excluding_user_ids can't be used at the same time")
    if not skeleton_ids:
        raise ValueError("Need at least one skeleton ID")

    # We need to make sure skeletons are provides as a list like type for
    # PsycoPg.
    if type(skeleton_ids) not in (list, tuple):
        skeleton_ids = list(skeleton_ids)

    cursor = connection.cursor()

    skeletons = {}

    # Get node count for each skeleton
    cursor.execute('''
        SELECT skeleton_id, num_nodes
        FROM catmaid_skeleton_summary s
        WHERE s.skeleton_id = ANY(%(skeleton_ids)s::bigint[])
    ''', {
        'skeleton_ids': list(skeleton_ids)
    })
    for row in cursor.fetchall():
        skeletons[row[0]] = [row[1], 0]

    query_params = {
        'project_id': project_id,
        'skeleton_ids': skeleton_ids
    }

    query_joins = []
    extra_conditions = []
    # Optionally, add a filter
    if whitelist_id:
        query_params['whitelist_id'] = whitelist_id
        query_joins.append("""
            JOIN reviewer_whitelist wl
                ON (wl.user_id = %(whitelist_id)s AND wl.project_id = %(project_id)s
                    AND r.reviewer_id = wl.reviewer_id
                    AND r.review_time >= wl.accept_after)
        """)
    elif user_ids:
        # Count number of nodes reviewed by a certain set of users, per
        # skeleton.
        query_params['user_ids'] = list(user_ids)
        query_joins.append("""
            JOIN (
                SELECT * FROM UNNEST(%(user_ids)s::int[])
            ) allowed_user(id)
                ON r.reviewer_id = allowed_user.id
        """)
    elif excluding_user_ids:
        # Count number of nodes reviewed by all users excluding the
        # specified ones, per skeleton.
        query_params['excluding_user_ids'] = list(excluding_user_ids)
        extra_conditions.append("NOT (r.reviewer_id = ANY (%(excluding_user_ids)s::int[]))")

    # Using count(distinct treenode_id) is slightly faster than a nested
    # grouping by skeleton_id, treenode_id, because one HashAggregate node can
    # be avoided.
    cursor.execute('''
    SELECT query_skeleton.id, review_info.n_nodes
    FROM (
        SELECT * FROM UNNEST(%(skeleton_ids)s::bigint[])
    ) query_skeleton(id)
    JOIN LATERAL (
        SELECT COUNT(DISTINCT treenode_id)
        FROM review r
        {extra_joins}
        WHERE skeleton_id = query_skeleton.id
        {extra_conditions}
    ) review_info(n_nodes)
        ON n_nodes > 0
    '''.format(**{
        'extra_joins': '\n'.join(query_joins),
        # The extra empty list element is added to get the initial AND term from the list join.
        'extra_conditions': ' AND '.join([''] + extra_conditions) if extra_conditions else '',
    }), query_params)
    for row in cursor.fetchall():
        skeletons[row[0]][1] = row[1]

    return skeletons

@requires_user_role([UserRole.Annotate, UserRole.Browse])
def reviewer_whitelist(request:HttpRequest, project_id=None) -> JsonResponse:
    """ Allows users to retrieve (GET) or update (POST) the set of users whose
    reviews they trust for a given project.
    """
    # Ignore anonymous user
    if request.user == get_anonymous_user() or not request.user.is_authenticated:
        return JsonResponse({'success': "The reviewer whitelist " +
                "of  the anonymous user won't be updated"})

    if request.method == 'GET':
        # Retrieve whitelist
        whitelist = ReviewerWhitelist.objects.filter(project_id=project_id,
                user_id=request.user.id).values('reviewer_id', 'accept_after')
        # DjangoJSONEncoder is required to properly encode datetime to ECMA-262
        return JsonResponse(list(whitelist), safe=False)

    # Since this is a collections resource replacing all objects, PUT would be
    # correct, but POST is used for consistency with the rest of the API.
    if request.method == 'POST':
        # Update whitelist
        ReviewerWhitelist.objects.filter(
                project_id=project_id, user_id=request.user.id).delete()
        whitelist = [ReviewerWhitelist(
            project_id=project_id, user_id=request.user.id, reviewer_id=int(r),
            accept_after=t) for r,t in request.POST.items()]
        ReviewerWhitelist.objects.bulk_create(whitelist)

        return JsonResponse({
            'success': 'Updated review whitelist'
        })


import os
from dotenv import load_dotenv
import discord
from discord.ext import commands
from mcstatus import JavaServer

load_dotenv(".env")
token = os.environ["TOKEN"]
prefix = os.environ["PREFIX"]
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix=prefix, intents=intents)

servers = [
	"mc.hypixel.net",
	"us.mineplex.com",
	"play.cubecraft.net",
	"play.invadedlands.net",
]

@bot.event
async def on_ready():
	print(f"Logged in as {bot.user} (ID {bot.user.id})")

@bot.command(description="Sends bot round-trip latency.")
async def ping(ctx):
	await ctx.send(f"Pong! {round(bot.latency * 1000)}ms")

@bot.command(description="Sends server status.")
async def status(ctx):
	embed = discord.Embed()
	embed.title = "Server Statuses"
	embed.description = "TEST"
	await ctx.send(embed=embed)

bot.run(token)


from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe.model.mapper import get_mapped_doc
from siscohealth.utils import get_age
from frappe.utils import cint, cstr, nowdate, nowtime

class PatientIntake(Document):

	def validate(self):
		self.validate_scheduling()
		self.validate_patient_contact()
		self.validate_patient_background_info()
		self.validate_comments()
		self.validate_exam_declined()
		self.make_or_update_patient()
		self.make_or_update_vital_signs()
		self.make_or_update_patient_encounter()
		self.make_or_update_insurances()

	def validate_scheduling(self):
		pass

	def validate_patient_contact(self):
		pass

	def validate_patient_background_info(self):
		pass

	def validate_comments(self):
		pass

	def validate_exam_declined(self):
		pass

	'''
		Create Patient as standard workflow in ERP
		and link with patient intake form
	'''
	def make_or_update_patient(self):
		patient = None
		if(self.patient and frappe.db.exists("Patient", self.patient)):
			patient = frappe.get_doc("Patient", self.patient)
		else:
			patient = frappe.new_doc("Patient")
		patient.update({
			"patient_name": "%s %s"%(self.patient_first_name, self.patient_last_name),
			"mobile": self.pc_cell_phone, "dob": self.date_of_birth,
			"sex": self.gender, "email": self.pc_email,
			"phone": self.patient_home_phone, "marital_status": self.marital_status
		})
		patient.save(ignore_permissions=True)
		self.patient = patient.name

	# Medicare Insurance
	def make_or_update_medicare_insurance(self):
		if(self.m_insurance_no):
			insurance = frappe._dict({
				"insurance_no": self.m_insurance_no,
				"insurance_provider": "Medicare Insurance",
				"insurance": self.m_insurance,
				"insurance_name": self.m_insurance or self.m_other_insurance_name,
				"insurance_type": self.m_insurance_type,
				"plan_no": self.m_plan_no, "patient_intake": self.name,
				"phone_no":self.m_phone_no, "patient_id": self.patient,
				"is_primary": self.m_is_primary
			})
			insurance = self.get_insurance_doc(self.medicare_insurance_link,
								insurance)
			insurance.save(ignore_permissions=True)
			self.medicare_insurance_link = insurance.name

	# PART D Insurance
	def make_or_update_part_d_insurance(self):
		if(self.pd_insurance):
			insurance = frappe._dict({
				"insurance_provider": "PART D Insurance",
				"insurnace": self.pd_insurance,
				"insurance_name": self.pd_insurance or self.pd_other_insurance_name,
				"plan_no": self.pd_plan_no, "insurance_type": "Other",
				"phone_no":self.pd_phone_no,"group_no": self.pd_group_no,
				"bin_no": self.pd_bin_no, "pcn_no": self.pd_pcn_no,
				"patient_id": self.patient, "patient_intake": self.name
			})
			insurance = self.get_insurance_doc(self.part_d_insurance_link,
								insurance)
			insurance.save(ignore_permissions=True)
			self.part_d_insurance_link = insurance.name

	# Medicaid Insurance
	def make_or_update_medicaid_insurance(self):
		if(self.md_insurance_no):
			insurance = frappe._dict({
				"insurance_name": "Medicaid Insurance", "plan_name": self.md_plan_name,
				"insurance_provider": "Medicaid Insurance",
				"insurance_no": self.md_insurance_no,
				"insurance_type": self.md_insurance_type,
				"bin_no": self.md_is_primary, "patient_id": self.patient,
				"patient_intake": self.name
			})
			insurance = self.get_insurance_doc(self.medicaid_insurance_link,
								insurance)
			insurance.save(ignore_permissions=True)
			self.medicaid_insurance_link = insurance.name

	# Private Insurance/ Can be any Insurance Provide
	def make_or_update_private_insurance(self):
		if(self.pr_insurance):
			insurance = frappe._dict({
				"insurance": self.pr_insurance,
				"insurance_provider": "Private Insurance",
				"is_primary": self.pr_is_primary,
				"include_rx_converage": self.pr_is_include_rx_coverage,
				"insurance_type": self.pr_insurance_type,
				"bin_no": self.md_is_primary,
				"phone_no": self.pr_phone_no,
				"group_no": self.pr_group_no,
				"bin_no": self.pr_group_no, "patient_intake": self.name,
				"pcn_no": self.pr_pcn_no, "patien_id": self.patient,
			})

			insurance = self.get_insurance_doc(self.private_insurance_link,
								insurance)
			insurance.save(ignore_permissions=True)
			self.private_insurance_link = insurance.name

	def make_or_update_insurances(self):
		insurances = []
		self.make_or_update_medicare_insurance()
		self.make_or_update_part_d_insurance()
		self.make_or_update_medicaid_insurance()
		self.make_or_update_private_insurance()

	def get_insurance_doc(self, insurance, _dict):

		insurance_doc = None
		if(insurance and frappe.db.exists("Insurance", insurance)):
			insurance_doc = frappe.get_doc("Insurance", insurance)
		else:
			insurance_doc = frappe.new_doc("Insurance")
		_dict.update({"patient_id": self.patient,"patient_intake": self.name})
		insurance_doc.update(_dict)
		return insurance_doc

	'''
		Make Vital Signs for Patient as a separate link
		Apply standard conversion factor
	'''
	def make_or_update_vital_signs(self):
		uom = 39.3700787
		vital_signs = None
		if(self.vital_signs and frappe.db.exists("Vital Signs", self.vital_signs)):
			vital_signs = frappe.get_doc("Vital Signs", self.vital_signs)
		else:
			vital_signs = frappe.new_doc("Vital Signs")
			vital_signs.signs_date = nowdate()
			vital_signs.signs_time = nowtime()
		vital_signs.update({
			"patient": self.patient,
			"height": self.height/uom if self.height else 0.0,
			"weight": self.weight/2.205 if self.weight else 0.0
		})
		vital_signs.save(ignore_permissions=True)
		self.vital_signs = vital_signs.name

	'''
		Make Patient Encounter to automize the process
	'''
	def make_or_update_patient_encounter(self):
		patient_encounter = None
		if(self.patient_encounter and(
			frappe.db.get_value("Patient Encounter", {
					"name": self.patient_encounter,
					"docstatus": 0}))):
			patient_encounter = frappe.get_doc("Patient Encounter", self.patient_encounter)
		else:
			patient_encounter = frappe.new_doc("Patient Encounter")
			patient_encounter.encounter_date = nowdate()
			patient_encounter.encounter_time = nowtime()
			patient_encounter.practitioner = ""
			patient_encounter.update({
				"patient": self.patient,
				"patient_sex": self.gender,
				"patient_intake": self.name,
				"patient_age": get_age(self.date_of_birth),
			})
			patient_encounter.insert(ignore_permissions=True, ignore_mandatory=True)

		patient_encounter.update({
			"patient": self.patient,
			"patient_sex": self.gender,
			"patient_intake": self.name,
			"patient_age": get_age(self.date_of_birth),
		})
		patient_encounter.flags.ingore_mandatory = True
		patient_encounter.save(ignore_permissions=True)
		self.patient_encounter = patient_encounter.name

@frappe.whitelist()
def make_patient_encounter(source_name, target_doc=None):

	def post_update(source_doc, target_doc):
		diagnosis = []
		target_doc.patient_sex = source_doc.gender
		target_doc.patient_age = get_age(source_doc.date_of_birth)

	doc = get_mapped_doc("Patient Intake", source_name, {
			"Patient Intake": {
				"doctype": "Patient Encounter",
				"gender": "patient_sex",
				"field_map":{
					"name": "patient_intake"
				}
			},
		},
		target_doc, post_update)
	return doc


"""
# 四，有序表的实现
# 有序表 数据相对位置取决于它们之间的 大小 比较
#    适用所有定义了 __gt__ (>)的方法
# next 链表实现

"""
from DisorderNode import Node

class OrderedList(object):
    def __init__(self):
        self.head = None

    def isEmpty(self):
        return self.items == []

    def removeFront(self):
        return self.items.pop()  # O(1) 队首尾移除

    def removeRear(self):
        return self.items.pop(0)  # O(n) 队尾移除

    def size(self):
        return len(self.items)

    def add(self, item):
        """必须保证有序性，必须添加到合适位置，以维护整个链表的有序性"""
        current = self.head
        previous = None
        stop = False
        while current != None and not stop:
            if current.getData() > item:    # 发现插入位置
                stop = True
            else:
                previous = current
                current = current.getData()
        temp = Node(item)
        if previous == None:    # 插入表头
            temp.setNext(self.head)
            self.head = temp
        else:   # 插入表中
            temp.setNext(current)
            previous.setNext(temp)

    def search(self, item):
        """当遇到比item大的 元素时，直接返回False"""
        current = self.head
        found = False
        stop = False
        while current != None and not found and not stop:
            if current.getData() == item:
                found = True
            else:
                if current.getData() > item:    # 遇到大于当前item的元素，因为是有序表，停止搜索
                    stop = True
                else:
                    current = current.getNext()
        return found


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

"""Console script for app."""
import sys
import click
from app import log
from app.main import main_function

from os.path import expanduser

default_config_path = expanduser("~/.config/app.conf")

@click.command()
@click.option("--config", default=default_config_path)
@click.option('--debug', is_flag=True, default=False, help='turn log level DEBUG on')
@click.option('--profile', is_flag=True, default=False, help='turn profiling on')
def main(config, debug, profile):
    """Console script for app."""
    if debug:
        import logging
        log.setLevel(logging.DEBUG)

        handler = logging.StreamHandler(sys.stdout)
        handler.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(message)s')
        handler.setFormatter(formatter)
        log.addHandler(handler)

    log.info("Started Kr15 Gtk App")

    try:
        main_function(config)
    except Exception as e:
        log.critical(str(e))
        sys.exit(1)

    sys.exit(0)

if __name__ == "__main__":
    sys.exit(main())  # pragma: no cover


my_file = open("Day 5 Task 2\input.txt", "r")
content_list = my_file.read().split("\n")
my_file.close()

content_list[0] = content_list[0].removeprefix("ď»ż")
grid = [[0]*1000 for _ in range(1000)]

overlapCounter = 0
# Add vents to the sea floor
for i in range(0, len(content_list)):
    [dot1, dot2] = content_list[i].split(" -> ")
    dot1 = list(map(int, dot1.split(",")))
    dot2 = list(map(int, dot2.split(",")))

    # Diagonal
    if abs(dot1[0] - dot2[0]) == abs(dot1[1] - dot2[1]):
        a = (int) ((dot2[1] - dot1[1]) / (dot2[0] - dot1[0]))
        b = dot1[1] - (a * dot1[0])
        start, end = min(dot1[0], dot2[0]), max(dot1[0], dot2[0])
        for x in range(start, end + 1):
            y = a*x + b
            grid[x][y] = grid[x][y] + 1
            if grid[x][y] == 2:
                overlapCounter += 1
    # Horizontal / vertical
    else:
        if dot1[0] != dot2[0] and dot1[1] != dot2[1]:
            continue
        #dot1 has to have smaller or equal coordinates
        if dot1[0] > dot2[0] or dot1[1] > dot2[1]:
            dot1, dot2 = dot2, dot1
        for x in range(dot1[0], dot2[0] + 1):
            for y in range(dot1[1], dot2[1] + 1):
                grid[x][y] = grid[x][y] + 1
                if grid[x][y] == 2:
                    overlapCounter += 1

print("Overlaps: ", overlapCounter)


"""
@Author         : yanyongyu
@Date           : 2021-05-14 17:09:12
@LastEditors    : yanyongyu
@LastEditTime   : 2023-10-18 16:22:15
@Description    : GitHub html renderer
@GitHub         : https://github.com/yanyongyu
"""

__author__ = "yanyongyu"

from pathlib import Path
from typing import Literal

import jinja2
from githubkit import rest, webhooks
from nonebot.adapters.github import OAuthBot, GitHubBot

from .context import set_context_bot
from .filters import (
    debug_event,
    markdown_gfm,
    review_state,
    left_truncate,
    relative_time,
    markdown_emoji,
    markdown_title,
)
from .globals import (
    REACTION_EMOJIS,
    scale_linear,
    get_issue_repo,
    get_pull_request,
    get_issue_timeline,
    find_dismissed_review,
    get_comment_reactions,
    get_issue_label_color,
    get_pull_request_diff,
)

env = jinja2.Environment(
    trim_blocks=True,
    lstrip_blocks=True,
    loader=jinja2.FileSystemLoader(Path(__file__).parent / "templates"),
    enable_async=True,
)
"""Jinja environment for rendering"""

env.filters["markdown_title"] = markdown_title
env.filters["markdown_emoji"] = markdown_emoji
env.filters["markdown_gfm"] = markdown_gfm
env.filters["relative_time"] = relative_time
env.filters["debug_event"] = debug_event
env.filters["review_state"] = review_state
env.filters["left_truncate"] = left_truncate

env.globals["get_issue_repo"] = get_issue_repo
env.globals["get_issue_timeline"] = get_issue_timeline
env.globals["get_pull_request"] = get_pull_request
env.globals["get_pull_request_diff"] = get_pull_request_diff
env.globals["get_comment_reactions"] = get_comment_reactions
env.globals["REACTION_EMOJIS"] = REACTION_EMOJIS
env.globals["get_issue_label_color"] = get_issue_label_color
env.globals["find_dismissed_review"] = find_dismissed_review
env.globals["scale_linear"] = scale_linear

async def issue_to_html(
    bot: GitHubBot | OAuthBot,
    issue: rest.Issue,
    theme: Literal["light", "dark"] = "light",
) -> str:
    """Render issue or pr with timeline to html

    Args:
        issue: the issue object
        theme: the theme of the html
    """
    template = env.get_template("views/issue.html.jinja")
    with set_context_bot(bot):
        return await template.render_async(issue=issue, theme=theme)

async def pr_diff_to_html(
    bot: GitHubBot | OAuthBot,
    issue: rest.Issue,
    theme: Literal["light", "dark"] = "light",
) -> str:
    """Render pr diff to html

    Args:
        issue: the issue object of the pr
        theme: the theme of the html
    """
    template = env.get_template("views/diff.html.jinja")
    with set_context_bot(bot):
        return await template.render_async(issue=issue, theme=theme)

async def issue_opened_to_html(
    bot: GitHubBot | OAuthBot,
    repo: webhooks.Repository,
    issue: webhooks.IssuesOpenedPropIssue | webhooks.PullRequestOpenedPropPullRequest,
    theme: Literal["light", "dark"] = "light",
) -> str:
    """Render issue or pr opened webhook event to html

    Args:
        repo: the webhook repository object
        issue: the webhook issue object
        theme: the theme of the html
    """
    template = env.get_template("views/issue-opened.html.jinja")
    with set_context_bot(bot):
        return await template.render_async(repo=repo, issue=issue, theme=theme)

async def issue_commented_to_html(
    bot: GitHubBot | OAuthBot,
    repo: webhooks.Repository,
    issue: webhooks.IssueCommentCreatedPropIssue,
    comment: webhooks.IssueComment,
    theme: Literal["light", "dark"] = "light",
) -> str:
    """Render issue commented webhook event to html

    Args:
        repo: the webhook repository object
        issue: the webhook issue object
        comment: the webhook issue comment object
        theme: the theme of the html
    """
    template = env.get_template("views/issue-commented.html.jinja")
    with set_context_bot(bot):
        return await template.render_async(
            repo=repo, issue=issue, comment=comment, theme=theme
        )

async def issue_closed_to_html(
    bot: GitHubBot | OAuthBot,
    repo: webhooks.Repository,
    issue: webhooks.IssuesClosedPropIssue | webhooks.PullRequestClosedPropPullRequest,
    theme: Literal["light", "dark"] = "light",
) -> str:
    """Render issue or pr closed webhook event to html

    Args:
        repo: the webhook repository object
        issue: the webhook issue object
        theme: the theme of the html
    """
    # 直接用issue-opened.html.jinja感觉就行
    template = env.get_template("views/issue-opened.html.jinja")
    with set_context_bot(bot):
        return await template.render_async(repo=repo, issue=issue, theme=theme)


import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
# https://www.effectiveperlprogramming.com/2011/08/know-the-difference-between-utf8-and-utf-8/
import datetime
import pprint
dataset = pd.read_csv("dataset.csv")
# print(repr(dataset))
# print(dataset.describe(include='all'))
# dataset_with_dummies = pd.get_dummies(dataset,prefix_sep='--')
# dataset_with_dummies = pd.get_dummies(dataset,prefix_sep='--')
# print(dataset_with_dummies.head())
# print(dataset.keys())
attributes = ['URL', 'URL_LENGTH', 'NUMBER_SPECIAL_CHARACTERS', 'CHARSET', 'SERVER',
       'CONTENT_LENGTH', 'WHOIS_COUNTRY', 'WHOIS_STATEPRO', 'WHOIS_REGDATE',
       'WHOIS_UPDATED_DATE', 'TCP_CONVERSATION_EXCHANGE',
       'DIST_REMOTE_TCP_PORT', 'REMOTE_IPS', 'APP_BYTES', 'SOURCE_APP_PACKETS',
       'REMOTE_APP_PACKETS', 'SOURCE_APP_BYTES', 'REMOTE_APP_BYTES',
       'APP_PACKETS', 'DNS_QUERY_TIMES', 'Type']

encoding = ["CHARSET", "SERVER", "WHOIS_COUNTRY", "WHOIS_STATEPRO", 'WHOIS_REGDATE',
       'WHOIS_UPDATED_DATE']

dict_charset = dict()
dict_server = dict()
dict_whois_country = dict()
dict_whois_statepro = dict()
dict_whois_regdate = dict()
dict_whois_updated_date = dict()

dataset["CHARSET"], uniq_charset = dataset['CHARSET'].factorize(sort = True)
dataset["SERVER"], uniq_server  = dataset['SERVER'].factorize(sort = True)
dataset["WHOIS_COUNTRY"], uniq_whois_country = dataset['WHOIS_COUNTRY'].factorize(sort = True)
dataset["WHOIS_STATEPRO"], uniq_whois_statepro = dataset['WHOIS_STATEPRO'].factorize(sort = True)
dataset["WHOIS_REGDATE"], uniq_whois_regdate = dataset['WHOIS_REGDATE'].factorize(sort = True)
dataset["WHOIS_UPDATED_DATE"], uniq_whois_updated_date = dataset['WHOIS_UPDATED_DATE'].factorize(sort = True)

# print(list(a))
# dict_server[list(a)] = list(b)
index = 0
for i in list(uniq_charset):
	# print()
	dict_charset[index] = i
	index += 1

index = 0
for i in list(uniq_server):
	# print()
	dict_server[index] = i
	index += 1

index = 0
for i in list(uniq_whois_country):
	# print()
	dict_whois_country[index] = i
	index += 1

index = 0
for i in list(uniq_whois_statepro):
	# print()
	dict_whois_statepro[index] = i
	index += 1

index = 0
for i in list(uniq_whois_regdate):
	# print()
	dict_whois_regdate[index] = i
	index += 1

index = 0
for i in list(uniq_whois_updated_date):
	# print()
	dict_whois_updated_date[index] = i
	index += 1

pprint.pprint("charset")
pprint.pprint(dict_charset)
pprint.pprint("server")
pprint.pprint(dict_server)
pprint.pprint("whois country")
pprint.pprint(dict_whois_country)
pprint.pprint("whois statepro")
pprint.pprint(dict_whois_statepro)
pprint.pprint("whois regdate")
pprint.pprint(dict_whois_regdate)
pprint.pprint("whois updated date")
pprint.pprint(dict_whois_updated_date)

#dataset.to_csv("dataset_encoded.csv")


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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('geo', '0001_initial'),
        ('profile', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='FeedItem',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('date', models.DateTimeField(db_index=True)),
                ('item_type', models.CharField(max_length=16, choices=[(b'post', b'Post'), (b'profile', b'Profile Update'), (b'acknowledgement', b'Acknowledgement'), (b'endorsement', b'Endorsement')])),
                ('item_id', models.PositiveIntegerField()),
                ('public', models.BooleanField()),
                ('location', models.ForeignKey(blank=True, to='geo.Location', null=True)),
                ('poster', models.ForeignKey(related_name='posted_feed_items', to='profile.Profile')),
                ('recipient', models.ForeignKey(related_name='received_feed_items', blank=True, to='profile.Profile', null=True)),
            ],
        ),
        migrations.AlterUniqueTogether(
            name='feeditem',
            unique_together=set([('item_type', 'item_id')]),
        ),
    ]


import cv2
import numpy as np

class ImagePreprocessor:
    def __init__(self,
                 image_size,
                 crop_mode=None,
                 precrop_size=None,
                 image_augmenter=None):
        self.image_size = image_size # width, height
        self.crop_mode = crop_mode
        self.precrop_size = precrop_size if precrop_size is not None else (int(image_size[0]*1.25),
                                                                           int(image_size[1]*1.25))
        self.image_augmenter = image_augmenter

    def preprocess_image(self, im):

        if self.crop_mode == "random":
            im = cv2.resize(im, self.precrop_size)
            row_max_offset = int((im.shape[0] - self.image_size[0]))
            col_max_offset = int((im.shape[1] - self.image_size[1]))
            row_offset = np.random.randint(0, row_max_offset)
            col_offset = np.random.randint(0, col_max_offset)
            im = im[row_offset:row_offset+self.image_size[0], col_offset:col_offset+self.image_size[1], :]
        elif self.crop_mode == "center":
            im = cv2.resize(im, self.precrop_size)
            row_offset = int((im.shape[0] - self.image_size[0])/2)
            col_offset = int((im.shape[1] - self.image_size[1])/2)
            im = im[row_offset:row_offset+self.image_size[0], col_offset:col_offset+self.image_size[1], :]
        else:
            im = cv2.resize(im, self.image_size)

        if self.image_augmenter is not None:
            self.image_augmenter.augment(im)

        im = im.astype(np.float32).transpose(2,0,1)
        im -= 128.0

        return im

    def load_image(self, image_path):
        im = cv2.imread(image_path)

        return self.preprocess_image(im)


from db.database import DataBase
import json

class BigKindRawDao:
  def __init__(self):
    self.db = DataBase()

  def saveMeta(self, year, total, page, doc_count):

    self.db.insert("""
      INSERT INTO bigkind_meta (
        year, total_count, page, doc_count
      ) VALUES (
        %s, %s, %s, %s
      )
    """, (year, total, page, doc_count))

  def completedListMeta(self, year):
    self.db.update("""
      UPDATE bigkind_meta
      SET list_completed = true
      WHERE year = %s
    """, (year))

  def saveRaw(self, year, page, params):

    def dict_to_tuple(x):
      date = ''
      if(x.get("DATE") == ''):
        date = None
      else:
        date = x.get("DATE")

      return (year, page, x.get("TITLE"), x.get("NEWS_ID"), date,
              x.get("CONTENT"), x.get("CATEGORY_NAMES"), x.get("PROVIDER"), x.get("BYLINE"),
              json.dumps(x))

    binding = [dict_to_tuple(i) for i in params]

    self.db.insert_many("""
      INSERT INTO bigkind_raw (
        year, page, title, news_id, press_date,
        content_abbr, category_names, provider, byline, checked,
        data
      ) VALUES (
        %s, %s, %s, %s, %s,
        %s, %s, %s, %s, false,
        %s
      )
    """, binding)

  def updateRaw(self, news_id, content):
    self.db.update("""
      UPDATE bigkind_raw
      SET content = %s
      WHERE news_id = %s
      AND content is null
    """, (content, news_id))

  def findRaw(self, year, page):
    query = """
      SELECT
        year, page, title, news_id
      FROM bigkind_raw
      WHERE year = %s
        AND content is null
    """

    if page != None:
      query = query + f" AND page = '{page}'"

    return self.db.queryList(query,(year))


"""RealEstate URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from webscrape import views as scrape_views
from dataprocess import views as proc_views
from django.contrib.auth import views as auth_views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', proc_views.home, name ='home'),
    path('model', proc_views.model, name ='model'),
    path('analysis', proc_views.analysis, name ='analysis'),
    path('update', proc_views.update, name ='update'),
    path('scrape/', scrape_views.land_scrape, name ='scrape'),
    path('price-form/', proc_views.get_land, name ='price-form'),
    path('report/<int:search_id>/', proc_views.show_report, name='price-report'),
    path('register/', proc_views.register, name='register'),
    path('login/', auth_views.LoginView.as_view(template_name='dataprocess/login.html'), name='login'),
    path('logout/', auth_views.LogoutView.as_view(template_name='dataprocess/logout.html'), name='logout')

]


# HackNJIT 2022 - Adrianna Rust, Andrew Dickman, Dustin La, and Hrishikesh Sakunala
import pygame
import ctypes
import header
from pygame.locals import *
from pygame import mixer
import sys

from button import Button

pygame.init()

width = 1280
height = 720
global currentStreak
currentStreak = False
SCREEN = pygame.display.set_mode((width, height), pygame.FULLSCREEN)

BG = pygame.image.load("assets/camping_background.jpg")

def get_font(size):  # Returns Press-Start-2P in the desired size
    return pygame.font.Font("assets/font.ttf", size)

# pressing play leads to the duration screen
def play(): # Play Screen
    while True:
        header.getLimit()
        PLAY_MOUSE_POS = pygame.mouse.get_pos()

        SCREEN.fill("#7d7992")
        # Background
        DEFAULT_IMAGE_POSITION = (70, 250)
        DEFAULT_IMAGE_SIZE = (400, 500)
        image = pygame.image.load("assets/art_timer.jpg").convert()
        image = pygame.transform.scale(image, DEFAULT_IMAGE_SIZE)
        SCREEN.blit(image, DEFAULT_IMAGE_POSITION)

        # Play info
        PLAY_TEXT = get_font(16).render("How long of a duration would you like to hold your marshmallow over the fire?", True,
                                        "White")
        PLAY_RECT = PLAY_TEXT.get_rect(center=(640, 100))
        SCREEN.blit(PLAY_TEXT, PLAY_RECT)

        # Short button
        PLAY_SHORT = Button(image=None, pos=(640, 260), text_input="Short", font=get_font(50), base_color="#d7fcd4",
                            hovering_color="White")
        PLAY_SHORT.changeColor(PLAY_MOUSE_POS)
        PLAY_SHORT.update(SCREEN)

        # Medium button
        PLAY_MEDIUM = Button(image=None, pos=(640, 360), text_input="Medium", font=get_font(50), base_color="#d7fcd4",
                             hovering_color="White")
        PLAY_MEDIUM.changeColor(PLAY_MOUSE_POS)
        PLAY_MEDIUM.update(SCREEN)

        # Long button
        PLAY_LONG = Button(image=None, pos=(640, 460), text_input="Long", font=get_font(50), base_color="#d7fcd4",
                           hovering_color="White")
        PLAY_LONG.changeColor(PLAY_MOUSE_POS)
        PLAY_LONG.update(SCREEN)

        # Displays Highscore
        highscore = "HIGHSCORE: " + str(header.getHighScore())
        HIGHSCORE_TEXT = get_font(20).render(highscore, True, "White")
        HIGHSCORE_RECT = HIGHSCORE_TEXT.get_rect(center=(640, 550))
        SCREEN.blit(HIGHSCORE_TEXT,HIGHSCORE_RECT)

        # Events for Short, Medium, Long
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                if PLAY_SHORT.checkForInput(PLAY_MOUSE_POS):
                    header.toastMarshmallow(1)
                    cont()
                if PLAY_MEDIUM.checkForInput(PLAY_MOUSE_POS):
                    header.toastMarshmallow(2)
                    cont()
                if PLAY_LONG.checkForInput(PLAY_MOUSE_POS):
                    header.toastMarshmallow(3)
                    cont()
        pygame.display.update()

def cont(): # Continue Screen
    while True:
        CONT_MOUSE_POS = pygame.mouse.get_pos()

        # Changes background base on marshmalow status
        if header.case == 1: # Squishy
            SCREEN.fill("#ab6589")
        if header.case == 2: # Starting to get brown
            SCREEN.fill("#bb6977")
        if header.case == 3: # Very nice brown
            SCREEN.fill("#c86a68")
        if header.case == 4: # Golden Brown
            SCREEN.fill("#df7555")
        if header.case == 5: # Burnt
            SCREEN.fill("#886372")

        # Seconds toasted
        currResult = "Your marshmallow has been toasted for " + str(header.randTime) + " seconds"
        CONT_TEXT = get_font(20).render(currResult, True, "White")
        CONT_RECT = CONT_TEXT.get_rect(center=(640, 50))
        SCREEN.blit(CONT_TEXT, CONT_RECT)

        # Total seconds toasted
        total = "Total: " + str(header.marshToast) + " seconds"
        CONT_TEXT2 = get_font(20).render(total, True, "White")
        CONT_RECT2 = CONT_TEXT2.get_rect(center=(640, 100))
        SCREEN.blit(CONT_TEXT2, CONT_RECT2)

        # Checks if Marshallow has been burnt
        status, case = header.checkIfBurnt(header.limit, header.marshToast)

        # If burnt, immediately go to results
        if case == 5:
            results()

        # Status message of marshmallow
        CONT_TEXT3 = get_font(15).render(str(status), True, "White")
        CONT_RECT3 = CONT_TEXT3.get_rect(center=(640, 150))
        SCREEN.blit(CONT_TEXT3, CONT_RECT3)

        # Continue and Stop Buttons
        CONTINUE_BUTTON = Button(image=None, pos=(320, 650),
                             text_input="CONTINUE", font=get_font(50), base_color="#d7fcd4", hovering_color="White")
        STOP_BUTTON = Button(image=None, pos=(960, 650),
                             text_input="STOP", font=get_font(50), base_color="#d7fcd4", hovering_color="White")

        CONTINUE_BUTTON.changeColor(CONT_MOUSE_POS)
        CONTINUE_BUTTON.update(SCREEN)

        STOP_BUTTON.changeColor(CONT_MOUSE_POS)
        STOP_BUTTON.update(SCREEN)

        # Changes image based on marshmallow status
        if case == 1: # Squishy
            DEFAULT_IMAGE_POSITION = (435, 180)
            DEFAULT_IMAGE_SIZE = (400, 400)
            image = pygame.image.load("assets/art_squishy_white.jpg").convert()
            image = pygame.transform.scale(image, DEFAULT_IMAGE_SIZE)
            SCREEN.blit(image, DEFAULT_IMAGE_POSITION)
        if case == 2: # Starting to get brown
            DEFAULT_IMAGE_POSITION = (435, 180)
            DEFAULT_IMAGE_SIZE = (400, 400)
            image = pygame.image.load("assets/little_brown.jpg").convert()
            image = pygame.transform.scale(image, DEFAULT_IMAGE_SIZE)
            SCREEN.blit(image, DEFAULT_IMAGE_POSITION)
        if case == 3: # Very nice brown
            DEFAULT_IMAGE_POSITION = (435, 180)
            DEFAULT_IMAGE_SIZE = (400, 400)
            image = pygame.image.load("assets/very_nice_brown.jpg").convert()
            image = pygame.transform.scale(image, DEFAULT_IMAGE_SIZE)
            SCREEN.blit(image, DEFAULT_IMAGE_POSITION)
        if case == 4: # Golden Brown
            DEFAULT_IMAGE_POSITION = (435, 180)
            DEFAULT_IMAGE_SIZE = (400, 400)
            image = pygame.image.load("assets/golden_brown.jpg").convert()
            image = pygame.transform.scale(image, DEFAULT_IMAGE_SIZE)
            SCREEN.blit(image, DEFAULT_IMAGE_POSITION)
        if case == 5: # Burnt
            DEFAULT_IMAGE_POSITION = (435, 180)
            DEFAULT_IMAGE_SIZE = (400, 400)
            image = pygame.image.load("assets/art_burnt.jpg").convert()
            image = pygame.transform.scale(image, DEFAULT_IMAGE_SIZE)
            SCREEN.blit(image, DEFAULT_IMAGE_POSITION)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

            if event.type == pygame.MOUSEBUTTONDOWN:
                if CONTINUE_BUTTON.checkForInput(CONT_MOUSE_POS):
                    play()
                if STOP_BUTTON.checkForInput(CONT_MOUSE_POS):
                    results()

        pygame.display.update()

def results(): # Results Screen
    global currentStreak
    status,case = header.checkIfBurnt(header.limit, header.marshToast)
    finalStatus = header.stopToasting(case, header.marshToast)

    # plays a success jingle if marshmallow is not burnt, else plays a fail jingle
    if case != 5:
        RESULTS_TEXT2 = get_font(16).render(finalStatus[1], True, "White")
        RESULTS_RECT2 = RESULTS_TEXT2.get_rect(center=(640, 150))
        SCREEN.blit(RESULTS_TEXT2, RESULTS_RECT2)
        channel3.play(pygame.mixer.Sound('assets/results.mp3'))
    else:
        channel4.play(pygame.mixer.Sound('assets/failresults.mp3'))
    while True:
        global checkStreak
        DEFAULT_IMAGE_POSITION = (0, 0)
        DEFAULT_IMAGE_SIZE = (1280, 720)
        image = pygame.image.load("assets/camping_background.jpg").convert()
        image = pygame.transform.scale(image, DEFAULT_IMAGE_SIZE)
        SCREEN.blit(image, DEFAULT_IMAGE_POSITION)

        RESULTS_MOUSE_POS = pygame.mouse.get_pos()
        # Shows correct marshmallow state
        if header.case == 1:
            DEFAULT_IMAGE_POSITION = (850, 180)
            DEFAULT_IMAGE_SIZE = (400, 400)
            image = pygame.image.load("assets/transparent_squishy_white.png").convert_alpha()
            image = pygame.transform.scale(image, DEFAULT_IMAGE_SIZE)
            SCREEN.blit(image, DEFAULT_IMAGE_POSITION)
        if header.case == 2:
            DEFAULT_IMAGE_POSITION = (850, 180)
            DEFAULT_IMAGE_SIZE = (400, 400)
            image = pygame.image.load("assets/transparent_little_brown.png").convert_alpha()
            image = pygame.transform.scale(image, DEFAULT_IMAGE_SIZE)
            SCREEN.blit(image, DEFAULT_IMAGE_POSITION)
        if header.case == 3:
            DEFAULT_IMAGE_POSITION = (850, 180)
            DEFAULT_IMAGE_SIZE = (400, 400)
            image = pygame.image.load("assets/transparent_very_nice_brown.png").convert_alpha()
            image = pygame.transform.scale(image, DEFAULT_IMAGE_SIZE)
            SCREEN.blit(image, DEFAULT_IMAGE_POSITION)
        if header.case == 4:
            DEFAULT_IMAGE_POSITION = (850, 180)
            DEFAULT_IMAGE_SIZE = (400, 400)
            image = pygame.image.load("assets/transparent_golden_brown.png").convert_alpha()
            image = pygame.transform.scale(image, DEFAULT_IMAGE_SIZE)
            SCREEN.blit(image, DEFAULT_IMAGE_POSITION)
        if header.case == 5:
            DEFAULT_IMAGE_POSITION = (850, 180)
            DEFAULT_IMAGE_SIZE = (400, 400)
            image = pygame.image.load("assets/transparent_burnt.png").convert_alpha()
            image = pygame.transform.scale(image, DEFAULT_IMAGE_SIZE)
            SCREEN.blit(image, DEFAULT_IMAGE_POSITION)

        # Increases Streak if it was golden brown
        if header.checkStreak == False:
            currentStreak = header.incrStreak(case)
            header.checkStreak = True

        # Results Text
        RESULTS_TEXT = get_font(17).render(finalStatus[0], True, "White")
        RESULTS_RECT = RESULTS_TEXT.get_rect(center=(640, 100))
        SCREEN.blit(RESULTS_TEXT, RESULTS_RECT)

        # Creator Text
        CREATOR_TEXT = get_font(15).render("HackNJIT 2022", True, "#b68f40")
        CREATOR_RECT = CREATOR_TEXT.get_rect(center=(640, 670))
        CREATOR_TEXT2 = get_font(15).render("Adrianna Rust, Andrew Dickman, Dustin La, and Hrishikesh Sakunala", True, "#b68f40")
        CREATOR_RECT2 = CREATOR_TEXT2.get_rect(center=(640, 690))
        SCREEN.blit(CREATOR_TEXT, CREATOR_RECT)
        SCREEN.blit(CREATOR_TEXT2, CREATOR_RECT2)

        # Highscore Text
        highscore = "Highscore: " + str(header.getHighScore())
        HIGHSCORE_TEXT = get_font(20).render(highscore, True, "White")
        HIGHSCORE_RECT = HIGHSCORE_TEXT.get_rect(center=(640, 500))
        SCREEN.blit(HIGHSCORE_TEXT,HIGHSCORE_RECT)

        # Streak Text
        streak = "Your streak is: " + str(currentStreak)
        header.scoreArray.append(currentStreak)
        STREAK_TEXT = get_font(20).render(streak, True, "White")
        STREAK_RECT = STREAK_TEXT.get_rect(center=(640, 450))
        SCREEN.blit(STREAK_TEXT, STREAK_RECT)

        # Restart Button and Menu Button
        RESTART_BUTTON = Button(image=None, pos=(300, 600),
                             text_input="PLAY AGAIN", font=get_font(45), base_color="#d7fcd4", hovering_color="White")
        MENU_BUTTON = Button(image=None, pos=(960, 600),
                             text_input="QUIT", font=get_font(50), base_color="#d7fcd4", hovering_color="White")

        RESTART_BUTTON.changeColor(RESULTS_MOUSE_POS)
        RESTART_BUTTON.update(SCREEN)

        MENU_BUTTON.changeColor(RESULTS_MOUSE_POS)
        MENU_BUTTON.update(SCREEN)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                if MENU_BUTTON.checkForInput(RESULTS_MOUSE_POS):
                    main_menu()
                if RESTART_BUTTON.checkForInput(RESULTS_MOUSE_POS):
                    header.reset()
                    play()

        pygame.display.update()

def main_menu(): # Main Menu
    while True:
        SCREEN.blit(BG, (0, 0))

        # text on page
        MENU_MOUSE_POS = pygame.mouse.get_pos()
        MENU_TEXT = get_font(30).render("Welcome to Marshmallow Toast Simulator!", True, "#b68f40")
        MENU_RECT = MENU_TEXT.get_rect(center=(640, 80))

        menu_text = get_font(20).render("Press play to grab a marshmallow!", True, "White")
        SCREEN.blit(menu_text, (330, 130))

        menu_instructions = get_font(20).render("Your goal is to get your marshmallow",True, "White")
        SCREEN.blit(menu_instructions,(290,200))
        menu_instructions2 = get_font(20).render("to a scrumptious golden brown color.",True,"White")
        SCREEN.blit(menu_instructions2,(295,230))

        # Play Button and Quit Button
        PLAY_BUTTON = Button(image=None, pos=(320, 600),
                             text_input="PLAY", font=get_font(50), base_color="#d7fcd4", hovering_color="White")
        QUIT_BUTTON = Button(image=None, pos=(960, 600),
                             text_input="QUIT", font=get_font(50), base_color="#d7fcd4", hovering_color="White")

        # Creator Text
        CREATOR_TEXT = get_font(15).render("HackNJIT 2022", True, "#b68f40")
        CREATOR_RECT = CREATOR_TEXT.get_rect(center=(640, 670))
        CREATOR_TEXT2 = get_font(15).render("Adrianna Rust, Andrew Dickman, Dustin La, and Hrishikesh Sakunala", True, "#b68f40")
        CREATOR_RECT2 = CREATOR_TEXT2.get_rect(center=(640, 690))

        SCREEN.blit(MENU_TEXT, MENU_RECT)
        SCREEN.blit(CREATOR_TEXT, CREATOR_RECT)
        SCREEN.blit(CREATOR_TEXT2, CREATOR_RECT2)

        for button in [PLAY_BUTTON, QUIT_BUTTON]:
            button.changeColor(MENU_MOUSE_POS)
            button.update(SCREEN)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                if PLAY_BUTTON.checkForInput(MENU_MOUSE_POS):
                    play()
                if QUIT_BUTTON.checkForInput(MENU_MOUSE_POS):
                    pygame.quit()
                    sys.exit()

        pygame.display.update()

# Plays Background Music
mixer.init()
mixer.music.load('assets/background.mp3')
channel1 = pygame.mixer.Channel(0)
channel1.play(pygame.mixer.Sound('assets/background.mp3'),-1)
channel1.set_volume(0.5)
mixer.music.load('assets/firecrackle.mp3')
channel2 = pygame.mixer.Channel(1)
channel2.play(pygame.mixer.Sound('assets/firecrackle.mp3'),-1)
channel2.set_volume(0.3)

channel3 = pygame.mixer.Channel(2)
channel4 = pygame.mixer.Channel(3)

main_menu()


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

from __future__ import print_function

'''A script that sends out a multicast packet to the group and port that the listener is listening to.'''

__author__ = 'Russel Winder'
__date__ = '2013-09-06'
__version__ = '1.1'
__copyright__ = 'Copyright © 2007, 2013  Russel Winder'
__licence__ = 'GNU Public Licence (GPL) v3'

from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor

from multicastGroupSpecification import group, port

class MulticastSender(DatagramProtocol):
    def startProtocol(self):
        print('Sending to {}:{} with TTL {}.'.format(group, port, self.transport.getTTL()))
        self.transport.write(b'Sent using Twisted.', (group, port))

if __name__ == '__main__':
    reactor.listenMulticast(0, MulticastSender())


import RPi.GPIO as GPIO
import time

GPIO.setwarnings(False) # sets weird warnings to false
leds = [38, 40] # list with both LED pins
GPIO.setmode(GPIO.BOARD)
GPIO.setup(leds, GPIO.OUT) # sets board pins 38 and 40 to output

for i in range(0, 10): # blinks the LED's 10 times
	GPIO.output(leds, 1)
	time.sleep(0.5)
	GPIO.output(leds, 0)
	time.sleep(0.5)


"""
Created on Sat Nov 30 11:12:39 2019

@author: Bogdan
"""
import os
import sys
import numpy as np
from scipy.signal import convolve2d
project_path = os.getcwd()
while os.path.basename(project_path) != 'image-tinkering':
    project_path = os.path.dirname(project_path)
sys.path.append(project_path)
from backend import utils

def apply_kernel(image, kernel):
    """ Performs convolution between the given image and kernel """
    if utils.is_color(image):
        result_b = convolve2d(image[:, :, 0], kernel, mode='same', fillvalue=np.median(image[:, :, 0]))
        result_g = convolve2d(image[:, :, 1], kernel, mode='same', fillvalue=np.median(image[:, :, 1]))
        result_r = convolve2d(image[:, :, 2], kernel, mode='same', fillvalue=np.median(image[:, :, 2]))
        channels_list = []

        # Trim values lower than 0 or higher than 255 and convert to uint8 for openCV compatibility
        for channel in 'bgr':
            underflow_mask = locals()['result_' + channel] < 0
            result_temp = np.where(underflow_mask, 0, locals()['result_' + channel])
            result_temp = np.where(result_temp > 255, 255, result_temp)
            result_temp = result_temp.astype(np.uint8)
            channels_list.append(result_temp)

        filtered_image = utils.merge_channels(channels_list)
    else:
        # Trim values lower than 0 or higher than 255 and convert to uint8 for openCV compatibility
        filtered_image = convolve2d(image, kernel, mode='same')
        filtered_image = np.where(filtered_image < 0, 0, filtered_image)
        filtered_image = np.where(filtered_image > 255, 255, filtered_image)
        filtered_image = filtered_image.astype(np.uint8)

    return filtered_image

def generate_box_kernel(size):
    """ Generates a kernel having the given size and giving equal weights to all
    elements surrounding the current pixel """
    return (1 / size ** 2) * np.ones((size, size), dtype=np.uint8)

def generate_gaussian_kernel(size, sigma=3):
    """ Generates an one-sum kernel having the given size, containing samples
    from a gaussian distribution having the given standard deviation """
    size = size // 2
    x, y = np.mgrid[-size: size + 1, -size: size + 1]
    normalization_factor = 1 / (2.0 * np.pi * sigma**2)
    g = np.exp(-((x ** 2 + y ** 2) / (2.0 * sigma ** 2))) * normalization_factor
    g = g / (np.sum(g))    # Normalize the kernel so the sum of elements is 1

    return g

def get_thresholds(image, method, kernel_size):
    """ Performs convolution between the image and the kernel of the specified
    size. The resulting values are the thresholds used in binarization """
    if method == 'mean':
        kernel = generate_box_kernel(kernel_size)
    else:
        kernel = generate_gaussian_kernel(kernel_size)

    thresholds = apply_kernel(image, kernel)

    return thresholds

def generate_emboss_kernels(size, direction, kernel_type):
    """ Generates the kernels of the specified type (mask or filter), size and
    direction, needed for the embossing operation """
    kernel1 = np.zeros((size, size), dtype=np.int8)

    if direction == 'horizontal':
        kernel1[: size // 2, size // 2] = 1
        kernel1[size // 2 + 1:, size // 2] = -1
        if kernel_type == 'filter':
            kernel1[size // 2, size // 2] = 1

        kernel2 = np.flipud(kernel1)
    elif direction == 'vertical':
        kernel1[size // 2, : size // 2] = 1
        kernel1[size // 2, size // 2 + 1:] = -1
        if kernel_type == 'filter':
            kernel1[size // 2, size // 2] = 1

        kernel2 = np.fliplr(kernel1)
    else:
        for i in range(size):
            if i < size // 2:
                kernel1[i, i] = 1
            elif i > size // 2:
                kernel1[i, i] = -1
            elif kernel_type == 'filter':
                kernel1[i, i] = 1

        kernel2 = np.flipud(kernel1)

    return kernel1, kernel2


import os
import tqdm
import yaml
import torch
import inspect
import numpy as np
import datetime
import torch.nn as nn
import torch.optim as optim

from torch.utils.tensorboard import SummaryWriter
from copy import deepcopy
from gym_unity.envs import UnityToGymWrapper
from mlagents_envs.environment import UnityEnvironment
from mlagents_envs.side_channel.engine_configuration_channel import EngineConfigurationChannel

from core import ReplayBuffer, get_action, setup_pytorch_for_mpi
from agents import DDPGActorCritic

class DDPG:
    def __init__(self, ac, env, epochs=100, steps_per_epoch=4000, batch_size=32,
        lr=1e-3, polyak=0.995, start_steps=10000, noise_scale=0.1, gamma=0.99,
        max_ep_len=1000, update_after=1000, update_every=50, model_path=None):

        self.ac = ac
        self.env = env
        self.epochs = epochs
        self.steps_per_epoch = steps_per_epoch
        self.batch_size = batch_size
        self.lr = lr
        self.polyak = polyak
        self.start_steps = start_steps
        self.noise_scale = noise_scale
        self.gamma = gamma
        self.max_ep_len = max_ep_len
        self.update_after = update_after
        self.update_every = update_every

        self.ac_targ = deepcopy(self.ac)
        for p in self.ac_targ.parameters():
            p.requires_grad = False

        if model_path is None:
            # New Model
            now = datetime.datetime.now()
            now_str = now.strftime("%Y%m%d_%H:%M:%S")
            self.model_path = f"experiments/{now_str}"
        else:
            # Existing model
            self.model_path = model_path
            self.load_model(self.model_path)

        self.writer = SummaryWriter(log_dir=self.model_path)
        self.pi_optimizer = optim.Adam(ac.pi.parameters(), lr=self.lr)
        self.q_optimizer = optim.Adam(ac.q.parameters(), lr=self.lr)

    def compute_loss_q(self, data):
        s, a, r, s2, d = (
            data["state"],
            data["action"],
            data["reward"],
            data["next_state"],
            data["done"],
        )

        q = self.ac.q(s, a)

        with torch.no_grad():
            q_pi_targ = self.ac_targ.q(s2, self.ac_targ.pi(s2))
            backup = r + self.gamma * (1 - d) * q_pi_targ

        loss_q = ((q - backup) ** 2).mean()
        return loss_q

    def compute_loss_pi(self, data):
        s = data["state"]
        q_pi = self.ac.q(s, self.ac.pi(s))
        return -q_pi.mean()

    def update(self, data):  # First run one gradient descent step for Q.
        self.q_optimizer.zero_grad()
        loss_q = self.compute_loss_q(data)
        loss_q.backward()
        self.q_optimizer.step()

        # Freeze Q-network so you don't waste computational effort
        # computing gradients for it during the policy learning step.
        for p in self.ac.q.parameters():
            p.requires_grad = False

        # Next run one gradient descent step for pi.
        self.pi_optimizer.zero_grad()
        loss_pi = self.compute_loss_pi(data)
        loss_pi.backward()
        self.pi_optimizer.step()

        # Unfreeze Q-network so you can optimize it at next DDPG step.
        for p in self.ac.q.parameters():
            p.requires_grad = True

        # Finally, update target networks by polyak averaging.
        with torch.no_grad():
            for p, p_targ in zip(self.ac.parameters(), self.ac_targ.parameters()):
                # NB: We use an in-place operations "mul_", "add_" to update target
                # params, as opposed to "mul" and "add", which would make new tensors.
                p_targ.data.mul_(self.polyak)
                p_targ.data.add_((1 - self.polyak) * p.data)

        return loss_pi.detach().numpy(), loss_q.detach().numpy()

    def log_params(self):
        os.makedirs(self.model_path, exist_ok=True)
        attributes = inspect.getmembers(self, lambda a: not(inspect.isroutine(a)) and type(a) in (int, str, float))
        config = [a for a in attributes if not(a[0].startswith("__") and a[0].endswith("__"))]
        config = dict(config)
        config["algorithm"] = "ddpg"
        with open(f"{self.model_path}/config.yaml", "w") as f:
            f.write(yaml.dump(config))

    def train(self):
        setup_pytorch_for_mpi()
        self.log_params()
        ep_len = 0
        ep_ret = 0
        s = self.env.reset()
        replay_buffer = ReplayBuffer()

        episode_lengths = []
        pi_losses = []
        q_losses = []

        pbar = tqdm.tqdm(range(self.epochs * self.steps_per_epoch), ncols=100)
        for t in pbar:
            # Encourage exploration
            if t < self.start_steps:
                a = self.env.action_space.sample()
            else:
                a = get_action(self.ac, s, self.noise_scale)

            s2, r, d, info = self.env.step(a)
            ep_len += 1
            ep_ret += r
            d = False if ep_len == self.max_ep_len else d

            record = dict(
                state=s,
                action=np.array([a]),
                reward=np.array([r]),
                next_state=s2,
                done=np.array([d], dtype=np.float32),
            )
            replay_buffer.push(record)

            s = s2

            if d or (ep_len == self.max_ep_len):
                episode_lengths.append(ep_len)
                s, ep_ret, ep_len = env.reset(), 0, 0

            if t >= self.update_after and t % self.update_every == 0:
                pbar.set_postfix(
                    dict(avg_epsiode_length=f"{np.mean(episode_lengths): .2f}")
                )
                for _ in range(self.update_every):
                    batch = replay_buffer.sample_batch(self.batch_size)
                    loss_pi, loss_q = self.update(batch)
                    q_losses.append(loss_q)
                    pi_losses.append(loss_pi)

            if (t + 1) % self.steps_per_epoch == 0:
                epoch = (t + 1) // self.steps_per_epoch
                metrics = dict(
                    eps_len=np.mean(episode_lengths),
                    loss_pi=np.mean(pi_losses),
                    loss_q=np.mean(q_losses),
                )
                episode_lengths = []
                pi_losses = []
                q_losses = []
                self.log_summary(epoch, metrics)

                if (epoch + 1) % 10 == 0:
                    self.save_model()

    def save_model(self):
        torch.save(self.ac.state_dict(), f"{self.model_path}/actor_critic")
        torch.save(self.ac_targ.state_dict(), f"{self.model_path}/actor_critic_targ")

    def log_summary(self, epoch, metrics):
        for name, value in metrics.items():
            self.writer.add_scalar(name, value, epoch)

    def load_model(self, path):
        self.ac.load_state_dict(torch.load(f"{path}/actor_critic"))
        self.ac_targ.load_state_dict(torch.load(f"{path}/actor_critic_targ"))

    def test_agent(self, test_episodes):
        s = self.env.reset()
        for _ in range(test_episodes):
            s, d, ep_ret, ep_len = self.env.reset(), False, 0, 0
            while not(d or (ep_len == self.max_ep_len)):
                # Take deterministic actions at test time (noise_scale=0)
                s, r, d, _ = self.env.step(get_action(self.ac, s, 0))
                ep_ret += r
                ep_len += 1

def combined_shape(length, shape=None):
    if shape is None:
        return (length,)
    return (length, shape) if np.isscalar(shape) else (length, *shape)

if __name__ == "__main__":
    agent_file = "3DBall_single/3DBall_single.x86_64"
    no_graphics = True
    channel = EngineConfigurationChannel()
    unity_env = UnityEnvironment(
        file_name=agent_file,
        seed=1,
        no_graphics=no_graphics,
        side_channels=[channel]
    )
    channel.set_configuration_parameters(
        time_scale=50.,
    )
    env = UnityToGymWrapper(unity_env)

    l1, l2 = 256, 256
    activation = nn.ReLU
    output_activation = nn.Tanh
    ac = DDPGActorCritic(env.observation_space, env.action_space, l1, l2, activation=activation)

    config = dict(
        gamma = 0.99,
        polyak = 0.995,
        noise_scale = 0.1,
        epochs = 100,
        steps_per_epoch = 4000,
        start_steps = 10000,
        batch_size = 128,
        update_after = 1000,
        update_every = 50,
    )
    model = DDPG(ac=ac, env=env, **config)
    model.train()


#!/usr/bin/python3
import random
number = random.randint(-10000, 10000)
if number < 0:
    renum = number % -10
else:
    renum = number % 10
print("Last digit of {:d} is {:d}".format(number, renum), end=" ")
if((renum) > 5):
    print("and is greater than 5")
elif((renum) == 0):
    print("and is 0")
elif((renum) < 6 and not 0):
    print("and is less than 6 and not 0")


class Column:
    def __init__(self, line):
        parts = line.strip().split()
        self.columnName = parts[0]
        self.isUnique = len(parts) == 3
        columnType = parts[-1]
        if 'CHAR' in columnType:
            self.columnType = 'CHAR'
            self.columnLimit = int(columnType.split('(')[-1][:-1])
        else:
            self.columnType = columnType


import numpy as np
import random
from .utils import rescale_size, imresize, imflip_, imnormalize_, to_tensor

class PyAVInit:
    def __init__(self):
        pass

    def __call__(self, results):
        try:
            import av
        except ImportError:
            raise ImportError('pip install av 即可解決問題')
        video_path = results.get('filename', None)
        assert video_path is not None, '缺少影片路徑'
        container = av.open(video_path)
        results['video_reader'] = container
        results['total_frames'] = container.streams.video[0].frames
        return results

class SampleFrames:
    def __init__(self, clip_len, frame_interval=1, num_clips=1, out_of_bound_opt='loop', test_mode=False):
        self.clip_len = clip_len
        self.frame_interval = frame_interval
        self.num_clips = num_clips
        self.out_of_bound_opt = out_of_bound_opt
        self.test_mode = test_mode
        assert out_of_bound_opt in ['loop', 'repeat_last']

    def _get_train_clips(self, num_frames):
        ori_clip_len = self.clip_len * self.frame_interval
        avg_interval = (num_frames - ori_clip_len + 1) // self.num_clips
        if avg_interval > 0:
            base_offsets = np.arange(self.num_clips) * avg_interval
            clip_offsets = base_offsets + np.random.randint(avg_interval, size=self.num_clips)
        elif num_frames > max(self.num_clips, ori_clip_len):
            clip_offsets = np.sort(np.random.randint(num_frames - ori_clip_len + 1, size=self.num_clips))
        elif avg_interval == 0:
            ratio = (num_frames - ori_clip_len + 1.0) / self.num_clips
            clip_offsets = np.around(np.arange(self.num_clips) * ratio)
        else:
            clip_offsets = np.zeros((self.num_clips,), dtype=np.int)
        return clip_offsets

    def _get_test_clips(self, num_frames):
        ori_clip_len = self.clip_len * self.frame_interval
        avg_interval = (num_frames - ori_clip_len + 1) / float(self.num_clips)
        if num_frames > ori_clip_len - 1:
            base_offset = np.arange(self.num_clips) * avg_interval
            clip_offsets = (base_offset + avg_interval / 2.0).astype(np.int)
        else:
            clip_offsets = np.zeros((self.num_clips, ), dtype=np.int)
        return clip_offsets

    def _sample_clips(self, num_frames):
        if self.test_mode:
            clip_offsets = self._get_test_clips(num_frames)
        else:
            clip_offsets = self._get_train_clips(num_frames)
        return clip_offsets

    def __call__(self, results):
        total_frames = results['total_frames']
        clip_offsets = self._sample_clips(total_frames)
        frame_inds = clip_offsets[:, None] + np.arange(self.clip_len)[None, :] * self.frame_interval
        if self.out_of_bound_opt == 'loop':
            frame_inds = np.mod(frame_inds, total_frames)
        elif self.out_of_bound_opt == 'repeat_last':
            safe_inds = frame_inds < total_frames
            unsafe_inds = 1 - safe_inds
            last_ind = np.max(safe_inds * frame_inds, axis=1)
            new_inds = (safe_inds * frame_inds + (unsafe_inds.T * last_ind).T)
            frame_inds = new_inds
        else:
            raise ValueError('不合法操做對於out_of_bound')
        start_index = results['start_index']
        frame_inds = np.concatenate(frame_inds) + start_index
        results['frame_inds'] = frame_inds.astype(np.int)
        results['clip_len'] = self.clip_len
        results['frame_interval'] = self.frame_interval
        results['num_clips'] = self.num_clips
        return results

class PyAVDecode:
    def __init__(self, mode='accurate'):
        self.mode = mode
        assert mode in ['accurate', 'efficient']

    @staticmethod
    def frame_generator(container, stream):
        for packet in container.demux(stream):
            for frame in packet.decode():
                if frame:
                    return frame.to_rgb().to_ndarray()

    def __call__(self, results):
        container = results['video_reader']
        imgs = list()
        if results['frame_inds'].ndim != 1:
            results['frame_inds'] = np.squeeze(results['frame_inds'])
        if self.mode == 'accurate':
            max_inds = max(results['frame_inds'])
            i = 0
            for frame in container.decode(video=0):
                if i > max_inds + 1:
                    break
                imgs.append(frame.to_rgb().to_ndarray())
                i += 1
            results['imgs'] = [imgs[i % len(imgs)] for i in results['frame_inds']]
        elif self.mode == 'efficient':
            for frame in container.decode(video=0):
                backup_frame = frame
                break
            stream = container.streams.video[0]
            for idx in results['frame_inds']:
                pts_scale = stream.average_rate * stream.time_base
                frame_pts = int(idx / pts_scale)
                container.seek(frame_pts, any_frame=False, backward=True, stream=stream)
                frame = self.frame_generator(container, stream)
                if frame is not None:
                    imgs.append(frame)
                    backup_frame = frame
                else:
                    imgs.append(backup_frame)
            results['imgs'] = imgs
        results['original_shape'] = imgs[0].shape[:2]
        results['img_shape'] = imgs[0].shape[:2]
        results['video_reader'] = None
        del container
        return results

class Resize:
    def __init__(self, scale, keep_ratio=True, interpolation='bilinear'):
        if isinstance(scale, float):
            if scale <= 0:
                raise ValueError('Scale不可以小於0')
        elif isinstance(scale, tuple):
            max_long_edge = max(scale)
            max_short_edge = min(scale)
            if max_short_edge == -1:
                scale = (np.inf, max_long_edge)
        else:
            raise TypeError(f'Scale must be float or tuple of int, but got {type(scale)}')
        self.scale = scale
        self.keep_ratio = keep_ratio
        self.interpolation = interpolation

    def _resize_imgs(self, imgs, new_w, new_h):
        return [imresize(img, (new_w, new_h), interpolation=self.interpolation) for img in imgs]

    def __call__(self, results):
        if 'scale_factor' not in results:
            results['scale_factor'] = np.array([1, 1], dtype=np.float32)
        img_h, img_w = results['img_shape']
        if self.keep_ratio:
            new_w, new_h = rescale_size((img_w, img_h), self.scale)
        else:
            new_w, new_h = self.scale
        self.scale_factor = np.array([new_w / img_w, new_h / img_h], dtype=np.float32)
        results['img_shape'] = (new_h, new_w)
        results['keep_ratio'] = self.keep_ratio
        results['scale_factor'] = results['scale_factor'] * self.scale_factor
        if 'imgs' in results:
            results['imgs'] = self._resize_imgs(results['imgs'], new_w, new_h)
        return results

class MultiScaleCrop:
    def __init__(self, input_size, scales=(1, ), max_wh_scale_gap=1, random_crop=False, num_fixed_crops=5):
        self.input_size = (input_size, input_size)
        assert num_fixed_crops in [5, 13]
        self.scales = scales
        self.max_wh_scale_gap = max_wh_scale_gap
        self.random_crop = random_crop
        self.num_fix_crops = num_fixed_crops

    @staticmethod
    def _crop_imgs(imgs, crop_bbox):
        x1, y1, x2, y2 = crop_bbox
        return [img[y1:y2, x1:x2] for img in imgs]

    def __call__(self, results):
        img_h, img_w = results['img_shape']
        base_size = min(img_h, img_w)
        crop_sizes = [int(base_size * s) for s in self.scales]
        candidate_sizes = list()
        for i, h in enumerate(crop_sizes):
            for j, w in enumerate(crop_sizes):
                if abs(i - j) <= self.max_wh_scale_gap:
                    candidate_sizes.append([w, h])
        crop_size = random.choice(candidate_sizes)
        for i in range(2):
            if abs(crop_size[i] - self.input_size[i]) < 3:
                crop_size[i] = self.input_size[i]
        crop_w, crop_h = crop_size
        if self.random_crop:
            x_offset = random.randint(0, img_w - crop_w)
            y_offset = random.randint(0, img_h - crop_h)
        else:
            w_step = (img_w - crop_w) // 4
            h_step = (img_h - crop_h) // 4
            candidate_offsets = [
                (0, 0), (4 * w_step, 0), (0, 4 * h_step), (4 * w_step, 4 * h_step), (2 * w_step, 2 * h_step)
            ]
            if self.num_fix_crops == 13:
                extra_candidate_offsets = [
                    (0, 2 * h_step),
                    (4 * w_step, 2 * h_step),
                    (2 * w_step, 4 * h_step),
                    (2 * w_step, 0 * h_step),
                    (1 * w_step, 1 * h_step),
                    (3 * w_step, 1 * h_step),
                    (1 * w_step, 3 * h_step),
                    (3 * w_step, 3 * h_step)
                ]
                candidate_offsets.extend(extra_candidate_offsets)
            x_offset, y_offset = random.choice(candidate_offsets)
        new_h, new_w = crop_h, crop_w
        crop_bbox = np.array([x_offset, y_offset, x_offset + new_w, y_offset + new_h])
        results['crop_bbox'] = crop_bbox
        results['img_shape'] = (new_h, new_w)
        results['scales'] = self.scales
        if 'crop_quadruple' not in results:
            results['crop_quadruple'] = np.array([0, 0, 1, 1], dtype=np.float32)
        x_ratio, y_ratio = x_offset / img_w, y_offset / img_h
        w_ratio, h_ratio = new_w / img_w, new_h / img_h
        old_crop_quadruple = results['crop_quadruple']
        old_x_ratio, old_y_ratio = old_crop_quadruple[0], old_crop_quadruple[1]
        old_w_ratio, old_h_ratio = old_crop_quadruple[2], old_crop_quadruple[3]
        new_crop_quadruple = [
            old_x_ratio + x_ratio * old_w_ratio, old_y_ratio + y_ratio * old_h_ratio,
            w_ratio * old_w_ratio, h_ratio * old_h_ratio
        ]
        results['crop_quadruple'] = np.array(new_crop_quadruple, dtype=np.float32)
        results['imgs'] = self._crop_imgs(results['imgs'], crop_bbox)
        return results

class Flip:
    def __init__(self, flip_ratio=0.5, direction='horizontal'):
        self.flip_ratio = flip_ratio
        self.direction = direction

    def _flip_imgs(self, imgs, modality):
        _ = [imflip_(img, self.direction) for img in imgs]
        if modality == 'Flow':
            raise NotImplementedError('目前不支持光流')
        return imgs

    def __call__(self, results):
        modality = results['modality']
        if modality == 'Flow':
            assert self.direction == 'horizontal'
        flip = np.random.rand() < self.flip_ratio
        results['flip'] = flip
        results['flip_direction'] = self.direction
        if flip:
            if 'imgs' in results:
                results['imgs'] = self._flip_imgs(results['imgs'], modality)
        return results

class Normalize:
    def __init__(self, mean, std, to_bgr=False, adjust_magnitude=False):
        self.mean = np.array(mean, dtype=np.float32)
        self.std = np.array(std, dtype=np.float32)
        self.to_bgr = to_bgr
        self.adjust_magnitude = adjust_magnitude

    def __call__(self, results):
        modality = results['modality']
        if modality == 'RGB':
            n = len(results['imgs'])
            h, w, c = results['imgs'][0].shape
            imgs = np.empty((n, h, w, c), dtype=np.float32)
            for i, img in enumerate(results['imgs']):
                imgs[i] = img
            for img in imgs:
                imnormalize_(img, self.mean, self.std, self.to_bgr)
            results['imgs'] = imgs
            results['img_norm_cfg'] = dict(mean=self.mean, std=self.std, to_bgr=self.to_bgr)
            return results
        if modality == 'Flow':
            raise NotImplementedError('目前不支持光流')

class FormatShape:
    def __init__(self, input_format, collapse=False):
        self.input_format = input_format
        self.collapse = collapse
        if self.input_format not in ['NCTHW', 'NCHW', 'NCHW_Flow', 'NPTCHW']:
            raise ValueError('Not support format shape')

    def __call__(self, results):
        if not isinstance(results['imgs'], np.ndarray):
            results['imgs'] = np.array(results['imgs'])
        imgs = results['imgs']
        if self.collapse:
            assert results['num_clips'] == 1
        if self.input_format == 'NCTHW':
            num_clips = results['num_clips']
            clip_len = results['clip_len']
            imgs = imgs.reshape((-1, num_clips, clip_len) + imgs.shape[1:])
            imgs = np.transpose(imgs, (0, 1, 5, 2, 3, 4))
            imgs = imgs.reshape((-1, ) + imgs.shape[2:])
        elif self.input_format == 'NCHW':
            imgs = np.transpose(imgs, (0, 3, 1, 2))
        elif self.input_format == 'NCHW_Flow':
            raise NotImplementedError('目前不支持光流')
        elif self.input_format == 'NPTCHW':
            raise NotImplementedError
        if self.collapse:
            assert imgs.shape[0] == 1
            imgs = imgs.squeeze(0)
        results['imgs'] = imgs
        results['input_shape'] = imgs.shape
        return results

class ToTensor:
    def __init__(self, keys):
        self.keys = keys

    def __call__(self, results):
        for key in self.keys:
            results[key] = to_tensor(results[key])
        return results

class ThreeCrop:
    def __init__(self, crop_size):
        self.crop_size = (crop_size, crop_size)

    def __call__(self, results):
        imgs = results['imgs']
        img_h, img_w = results['imgs'][0].shape[:2]
        crop_w, crop_h = self.crop_size
        assert crop_h == img_h or crop_w == img_w
        offsets = [(0, 0)]
        if crop_h == img_h:
            w_step = (img_w - crop_w) // 2
            offsets = [(0, 0), (2 * w_step, 0), (w_step, 0)]
        elif crop_w == img_w:
            h_step = (img_h - crop_h) // 2
            offsets = [(0, 0), (0, 2 * h_step), (0, h_step)]
        cropped = list()
        crop_bboxes = list()
        for x_offset, y_offset in offsets:
            bbox = [x_offset, y_offset, x_offset + crop_w, y_offset + crop_h]
            crop = [img[y_offset:y_offset + crop_h, x_offset:x_offset + crop_w] for img in imgs]
            cropped.extend(crop)
            crop_bboxes.extend([bbox for _ in range(len(imgs))])
        crop_bboxes = np.array(crop_bboxes)
        results['imgs'] = cropped
        results['crop_bbox'] = crop_bboxes
        results['img_shape'] = results['imgs'][0].shape[:2]
        return results


tc = 3
tc = -1
tc = 0

def main(n):
    # 将列表中的数字打印出来，但是不打印前面的补位0
    def print_list(l):
        first_non_0_index = 0
        for i in range(len(l)):
            if l[i] != '0':
                first_non_0_index = i
                break
            # 如果已经到了最后一位依然是0，说明这个数是0，不打印
            if i == len(l) - 1:
                return
        real_num = ''.join(l[first_non_0_index:])
        print(real_num)

    def generate_int(num_list, index):
        if index == len(num_list):
            print_list(num_list)
            return
        for i in range(10):
            num_list[index] = str(i)
            generate_int(num_list, index+1)
    if n <= 0:
        print('非法输入')
        return
    generate_int([0]*n, 0)

if __name__ == '__main__':
    main(tc)

17列表大数+递归全排列.py


# This probably doesn't work
import setuptools

with open("README.md", "r") as fh:
    long_description = fh.read()

setuptools.setup(
    name="resurgence_renderer-Jellohunter7",
    version="0.0.1",
    author="Rachit Kakkar",
    author_email="",
    description="resurgance_renderer is an easy to use library used to generate 3D scenes, and can be easily scripted/extended with python",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/rachitkakkar/resurgence_renderer",
    packages=setuptools.find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    python_requires='>=3.6',
)


import math

print("Введите длины гипотенузы")
a = int(input())
b = int(input())
if a <= 0 | b <= 0:
    print("Нет такого треугольника")
else:
    c = math.sqrt(pow(a, 2) + pow(b, 2))
    print("Гипотенуза =  ", c)

Гипотенуза.py


#!/usr/bin/env python3
import sys
import re
import q
import itertools as it
import math
import aocd
from typing import List, Tuple
from dataclasses import dataclass
from collections import defaultdict

if len(sys.argv) > 1:
    filename = sys.argv[1]
    with open(filename) as file:
        lines = [l.strip("\n") for l in file]
else:
    filename = "input"
    lines = aocd.get_data(year=2022, day=9).split("\n")

print("len(lines)", len(lines))
ans1 = 0
ans2 = 0

visited = set()

@dataclass
class Point:
    x: int = 0
    y: int = 0

    def step(self, d):
        if d == "R":
            self.x += 1
        if d == "L":
            self.x -= 1
        if d == "U":
            self.y += 1
        if d == "D":
            self.y -= 1

    def follow(self, h: "Point"):
        if abs(self.x - h.x) <= 1 and abs(self.y - h.y) <= 1:
            return
        if self.x == h.x:
            if self.y < h.y:
                self.y += 1
            else:
                self.y -= 1
        elif self.y == h.y:
            if self.x < h.x:
                self.x += 1
            else:
                self.x -= 1
        else:
            # diagonal
            if self.x < h.x and self.y < h.y:
                self.x += 1
                self.y += 1
            elif self.x < h.x and self.y > h.y:
                self.x += 1
                self.y -= 1
            elif self.x > h.x and self.y < h.y:
                self.x -= 1
                self.y += 1
            elif self.x > h.x and self.y > h.y:
                self.x -= 1
                self.y -= 1

h = Point()
t = Point()

for move in lines:
    d, c = move.split()
    c = int(c)
    for _ in range(c):
        h.step(d)
        t.follow(h)
        visited.add((t.x, t.y))

ans1 = len(visited)

visited2 = set()

rope = [Point() for _ in range(10)]
for move in lines:
    d, c = move.split()
    c = int(c)
    for _ in range(c):
        rope[0].step(d)
        for i in range(9):
            rope[i + 1].follow(rope[i])
        t = rope[-1]
        visited2.add((t.x, t.y))

ans2 = len(visited2)

print("1:", ans1)
print("2:", ans2)

if filename == "input":
    submit = input("submit?")
    if "y" in submit.lower():
        if ans1 != 0:
            aocd.submit(ans1, year=2022, day=9, part="a")
        if ans2 != 0:
            aocd.submit(ans2, year=2022, day=9, part="b")


import random

# Creates a function for the computer to guess a number

def computerGuess(x):
    low = 1
    high = x
    feedback = ""
    while feedback != "c":
        if low != high:
            guess = random.randint(low,high)
        else:
            guess = low # could be high instead, because in this case, low and high are equal.
        feedback = input(f"Is {guess} too high (h), too low (l), or it is correct (c)? ").lower()
        if feedback == "h":
            high = guess - 1
        elif feedback == 'l':
            low = guess + 1

    print(f"The computer guessed your number {guess}, correctly!")

computerGuess(10)


'''
输入一个英文句子，翻转句子中单词的顺序，但单词内字符的顺序不变。为简单起见，标点符号和普通字母一样处理。例如输入字符串"I am a student. "，则输出"student. a am I"。

示例 1：

输入: "the sky is blue"
输出: "blue is sky the"
示例 2：

输入: "  hello world!  "
输出: "world! hello"
解释: 输入字符串可以在前面或者后面包含多余的空格，但是反转后的字符不能包括。
示例 3：

输入: "a good   example"
输出: "example good a"
解释: 如果两个单词间有多余的空格，将反转后单词间的空格减少到只含一个。
'''

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        if not s:
            return s
        res = []
        i, j = 0, 0
        while i < len(s):
            while i < len(s) and s[i] == " ":
                i += 1
            j = i + 1
            while j < len(s) and s[j] != " ":
                j += 1
            if s[i:j]:
                res.append(s[i: j])
            i = j + 1
        return " ".join(res[::-1])

a = Solution()
print(a.reverseWords("  hello world!  "))

61-反转单词顺序.py


# 제곱 ㄴㄴ 수
# 일반적인 반복문으로 풀면 시간 초과 남
# 에라토스테네스의 체 방식으로 접근하여 시간 최소화해야 함

import sys
import math
sys.stdin = open('input.txt', 'r')
input = sys.stdin.readline

Min, Max = map(int, input().split())
Check = [False] * (Max - Min + 1)

for i in range(2, int(math.sqrt(Max) + 1)):
  pow = i * i
  start_index = int(Min / pow)
  if Min % pow != 0:
    start_index += 1
  for j in range(start_index, int(Max/pow) + 1):
    Check[int((j*pow) - Min)] = True

count = 0

for i in range(0, Max - Min + 1):
  if not Check[i]:
    count += 1

print(count)


from subprocess import call
### to clean the terminal.
from time import sleep
### too show the winner.
from pyfiglet import figlet_format
### display more beautiful!

class Game(object):

    """
    This is a class that that can basically initialize the game!
    it includes the table and some methods to work with.
    """

    def __init__(self, X='X', O='O'):
        self.OCHAR = O
        self.XCHAR = X
        ### maybe the players wanted to know about their score!
        self.SCOREBOARD = {self.XCHAR: int(), self.OCHAR: int()}

    def set_table(self):

        """
        by running this method, you'v just created a table that players
        can play on it!
        """

        self.TABLE = [['-' for i in range(3)] for j in range(3)]
        self.COUNTER = 0

    def display_table(self):

        """
        yeah it just prints the table you created before!
        """

        call('clear', shell=True)
        ### now the terimnal is clean af!
        print(figlet_format('{}: {}, {}: {}'.format(self.XCHAR, self.SCOREBOARD[self.XCHAR], self.OCHAR, self.SCOREBOARD[self.OCHAR])))
        print('\n')
        tmp = str()
        for i in self.TABLE:
            for j in i:
                tmp += j
                tmp += '     '
            tmp += '\n'
        print(figlet_format(tmp))

    def check_the_table(self):

        """
        one of the most important methods of the hole class;
        by running this method, you will analyze the table and
        look for the winner.
        """

        win = False
        ### did anybody win?!
        ### analyzing horizontal & vertical lines: {
        if not win:
            for i in self.TABLE:
                if i.count(i[0]) == 3:
                    if i[0] != '-':
                        win = True
                        self.SCOREBOARD[i[0]] += 1
                        self.display_table()
                        print(figlet_format('{} won the game!'.format(i[0])))
                        self.set_table()
                        sleep(2)
        if not win:
            for i in range(3):
                tmp = list()
                for j in self.TABLE:
                    tmp.append(j[i])
                    if tmp.count(tmp[0]) == 3:
                        if tmp[0] != '-':
                            win = True
                            self.SCOREBOARD[tmp[0]] += 1
                            self.display_table()
                            print(figlet_format('{} won the game!'.format(tmp[0])))
                            self.set_table()
                            sleep(2)
        ### }
        ### analyzing diagonal lines{
        if not win:
            tmp = [self.TABLE[i][i] for i in range(3)]
            if tmp.count(tmp[0]) == 3:
                if tmp[0] != '-':
                    win = True
                    self.SCOREBOARD[tmp[0]] += 1
                    self.display_table()
                    print(figlet_format('{} won the game!'.format(tmp[0])))
                    self.set_table()
                    sleep(2)
        if not win:
            tmp = [self.TABLE[0][2], self.TABLE[1][1], self.TABLE[2][0]]
            if tmp.count(tmp[0]) == 3:
                if tmp[0] != '-':
                    win = True
                    self.SCOREBOARD[tmp[0]] += 1
                    self.display_table()
                    print(figlet_format('{} won the game!'.format(tmp[0])))
                    self.set_table()
                    sleep(2)
        ### }
        ### what if nobody couldn't win!?
        if not win:
            if self.COUNTER >= 9:
                win = True
                self.display_table()
                print(figlet_format('no one won!'))
                self.set_table()
                sleep(2)


#importing the required libraries
import cv2
import numpy as np
import pytesseract

def put_number(image, table, ans):

    """ Function to compare unsolved table
        with a solved sudoku table and the answer
        will be written on the image

    Arguments:
        image {numpy.ndarray} --
        table {numpy.array} -- unsolved array
        ans {numpy.array} -- solved array

    Returns:
        numpy.ndarray -- final image
    """
    image = cv2.resize(image, (450, 450))
    width = image.shape[0]
    height = image.shape[1]
    w = width//9
    h = height//9
    c = 0

    for i in range(0, 9):
        for j in range(0, 9):
            if table[i][j] == 0:
                x = j*w
                y = i*h
                cv2.putText(image, str(ans[i][j]), (int((x+w/3)), int((y+h/1.5)))\
                    ,cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
    return image
# -----------------------------------------------------------
def solve(board):

    find = find_empty(board)

    if not find:
        return True
    else:
        row, col = find

    for i in range(1, 10):
        if valid(board, i, (row, col)):
            board[row][col] = i
            if solve(board):
                return True
            board[row][col] = 0
    return False

def find_empty(board):
    for i in range(len(board)):
        for j in range(len(board[i])):
            if board[i][j] == 0:
                return (i, j)

    return None
# -----------------------------------------------------------
def valid(board, num, pos):
    # check row
    for i in range(len(board[0])):
        if board[pos[0]][i] == num and pos[1] != i:
            return False

    # check column
    for i in range(len(board)):
        if board[i][pos[1]] == num and pos[0] != i:
            return False

    # check box
    box_x = pos[1] // 3
    box_y = pos[0] // 3

    for i in range(box_y * 3, box_y * 3 + 3):
        for j in range(box_x * 3, box_x * 3 + 3):
            if board[i][j] == num and (i, j) != pos:
                return False

    return True
# -----------------------------------------------------------
def table_analyze(image):

    """The function divide image into 9x9
        equal parts.
      Google OCR engine (Pytesseract) reads every section.

    Arguments:
        image {numpy.ndarray} -- prepared image

    Returns:
        list -- intger table values
    """

    image = cv2.resize(image, (900, 900))
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    ret, thresh = cv2.threshold(gray, 140, 255, cv2.THRESH_BINARY)

    width = image.shape[0]
    height = image.shape[1]
    w = width//9
    h = height//9

    list = []
    i = 0
    for x in range(0, width, w):
        for y in range(0, height, h):

            number_image = thresh[x + 10:x+w - 10, y + 10:y+h - 10]

            number = pytesseract.image_to_string(number_image, lang='eng',\
            config='--psm 7 --oem 3 -c tessedit_char_whitelist=0123456789')

            print('index[{}] = {}'.format(i, number))
            try:
                number = int(number)
            except:
                number = 0

            list.append(number)
            i = i + 1

    return list
# -----------------------------------------------------------
def arrange(n, size):

    """align 4 corners for undistort

    Arguments:
        n {list} -- x, y lsit of 4 corners
        size {int} -- size of dst

    Returns:
        src
        dst
    """
    # alignment of src and dst --> [[left],[top left], [top right][right]]
    points = np.float32([
        [n[0], n[1]],
        [n[2], n[3]],
        [n[4], n[5]],
        [n[6], n[7]]
    ])
    sum_list = []
    res = points.copy()

    for m in points:
        sum = 0
        sum = m[0] + m[1]
        sum_list.append(sum)
    sum_list.sort()

    for i in range(0, len(sum_list)):
        for point in points:
            if point[0] + point[1] == sum_list[i]:
                if i == 0:
                    res[1] = [point[0], point[1]]
                elif i == 1:
                    res[2] = [point[0], point[1]]
                elif i == 2:
                    res[0] = [point[0], point[1]]
                elif i == 3:
                    res[3] = [point[0], point[1]]
                else:
                    print('somthing went wrong')
    size = 250 # optional

    dst = np.float32([
        [0, size],
        [0, 0],
        [size ,0],
        [size, size]
    ])
    return res, dst
# -----------------------------------------------------------
def preprocess(image):

    """
        Function to apply preprocessing on image includes
        denoising and finding contours to
        undistort the image and remove useless parts
        of the image!
    """

    # Resize for more control over the image.
    image = cv2.resize(image, (500, 600))
    # no need for colouring the details
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    denoised = cv2.fastNlMeansDenoising(gray, h=3, templateWindowSize=6, searchWindowSize=21)
    thresh = cv2.adaptiveThreshold(denoised, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
    canny = cv2.Canny(thresh, 120, 150, apertureSize=3)
    contours, _ = cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    # Largest area belongs to largest rectangle in the image.
    # Largest rectangle actually is sudoku table border
    largest_area = 0
    largest_cnt = contours[0]
    for cnt in contours:
        approx = cv2.approxPolyDP(cnt, .01*cv2.arcLength(cnt, True), True)
        # Rectangle
        if len(approx == 4):
            area = cv2.contourArea(cnt)
            if largest_area <= area:
                largest_area = area
                largest_cnt = approx
    # finding 4 corners of the table.
    n = largest_cnt.ravel()
    # size of dst image
    size = 250
    src, dst = arrange(n, size)
    # undistort the image
    m = cv2.getPerspectiveTransform(src, dst)
    undistorted = cv2.warpPerspective(image, m, (size, size))

    print('preprocess completed')
    return undistorted
# -----------------------------------------------------------
"""
    main   |  |  |
           V  V  V
"""
# getting the image from the user as input
path = input('Please enter the sudku table path:')
image = cv2.imread(path, cv2.IMREAD_COLOR)

image = preprocess(image)
table = table_analyze(image) # reading sudoku table

ans = np.array(table).reshape((9, 9)).tolist()
table = np.array(table).reshape((9, 9)).tolist()

solve(ans)
# casting ans and table to the numpy.array to present answers on image and presenting a better print.
ans = np.array(ans)
table = np.array(table)
print(table)
print(ans)

image = put_number(image, table, ans)
cv2.imshow('my image', image)

cv2.waitKey(0)
cv2.destroyAllWindows()