import cv2
import numpy as np
from math_tool import conv2
from read_bin import BinFile

def preprocess(imageinput, bayerformat="rggb", outputformat="raw", mode=0, bitdepth=10, pedestal=64, FOV=0,
               whitebalance=True, signed=True, more_precise=False, custom_size=[0, 0], custom_encoding="H", for_SFR_test=False):

    if custom_encoding is "H":
        # 默认unsigned integer, 16位
        bin = BinFile(imageinput, datatype=np.uint16)
        header, ID = bin.get_realdata(2)
    else:
        bin = BinFile(imageinput, datatype=custom_encoding)
        header, ID = bin.get_realdata(2)

    if custom_size == [0, 0]:
        width = header[0]
        height = header[1]
    else:
        width = custom_size[0]
        height = custom_size[1]

    ID = np.asarray(ID).astype(np.double)

    if custom_size == [0, 0]:
        ID = ID[2:]

    ID = ID.reshape((height, width))

    # 按mode切片
    ID = crop_by_mode(ID, mode)

    # 增益
    ID = ID + pedestal
    if not signed:
        ID[ID < 0] = 0

    # 白平衡
    if whitebalance:
        ID = white_balance(ID, for_SFR_test)
        ID[ID > 2 ** bitdepth - 1] = 2 ** bitdepth - 1  # 防过饱和

    # 去镜头阴影
    if FOV is not 0:
        ID = lens_shading_correction(ID, 75)
        ID[ID > 2 ** bitdepth - 1] = 2 ** bitdepth - 1  # 防过饱和

    # 图像格式转换
    if outputformat is "raw":
        # 源格式输出
        if not more_precise:
            ID = np.round(ID)
        return ID

    elif outputformat is "bayer":
        # 分4层输出，强制转换到RGrGbB
        plane = np.zeros((int(ID.shape[0] / 2), int(ID.shape[1] / 2), 4))
        R = np.zeros((int(ID.shape[0] / 2), int(ID.shape[1] / 2)))
        Gr = np.zeros((int(ID.shape[0] / 2), int(ID.shape[1] / 2)))
        Gb = np.zeros((int(ID.shape[0] / 2), int(ID.shape[1] / 2)))
        B = np.zeros((int(ID.shape[0] / 2), int(ID.shape[1] / 2)))

        plane[:, :, 0] = ID[::2, ::2]
        plane[:, :, 1] = ID[::2, 1::2]
        plane[:, :, 2] = ID[1::2, ::2]
        plane[:, :, 3] = ID[1::2, 1::2]

        if bayerformat is "rggb":
            R = plane[:, :, 0]
            Gr = plane[:, :, 1]
            Gb = plane[:, :, 2]
            B = plane[:, :, 3]
        elif bayerformat is "bggr":
            B = plane[:, :, 0]
            Gb = plane[:, :, 1]
            Gr = plane[:, :, 2]
            R = plane[:, :, 3]
        elif bayerformat is "gbrg":
            Gb = plane[:, :, 0]
            B = plane[:, :, 1]
            R = plane[:, :, 2]
            Gr = plane[:, :, 3]
        elif bayerformat is "grbg":
            Gr = plane[:, :, 0]
            R = plane[:, :, 1]
            B = plane[:, :, 2]
            Gb = plane[:, :, 3]

        bayer = np.zeros((int(ID.shape[0] / 2), int(ID.shape[1] / 2), 4))
        bayer[:, :, 0] = R
        bayer[:, :, 1] = Gr
        bayer[:, :, 2] = Gb
        bayer[:, :, 3] = B

        if not more_precise:
            bayer = np.round(bayer)
        return bayer

    elif outputformat is "rgb":
        bgr = bilinear_interpolation_opencv(ID, bayerformat)
        if not more_precise:
            bgr = np.round(bgr)
        return bgr

    elif outputformat is "yuv":
        bgr = bilinear_interpolation(ID, bayerformat)

        # opencv solution
        yuv = cv2.cvtColor(bgr, cv2.COLOR_BGR2YUV)

        # numpy solution
        # yuv = np.zeros(rgb.shape)
        # yuv[:, :, 0] = 0.299 * rgb[:, :, 0] + 0.587 * rgb[:, :, 1] + 0.114 * rgb[:, :, 2]
        # yuv[:, :, 1] = 2 ** (bitdepth - 1) - 0.1687 * rgb[:, :, 0] - 0.3313 * rgb[:, :, 1] + 0.5 * rgb[:, :, 2]
        # yuv[:, :, 2] = 2 ** (bitdepth - 1) + 0.5 * rgb[:, :, 0] - 0.4187 * rgb[:, :, 1] - 0.0813 * rgb[:, :, 2]

        if not more_precise:
            yuv = np.round(yuv)
        return yuv

    return

def crop_by_mode(raw, mode):
    width = raw.shape[1]
    height = raw.shape[0]

    # 按mode切片
    if mode is 1:
        raw = raw[8:height - 8, 8:width - 8]
    elif mode is 2:
        raw = raw[int((height - (width - 16) / (16 / 9)) / 2): height - int((height - (width - 16) / (16 / 9)) / 2),
              8:width - 8]
    elif mode is 3:
        raw = raw[8:height - 8,
              int((width - (height - 16) * (3 / 2)) / 2): width - int((width - (height - 16) * (3 / 2)) / 2)]
    elif mode is 4:
        raw = raw[8:height - 8,
              int((width - (height - 16) * (4 / 3)) / 2): width - int((width - (height - 16) * (4 / 3)) / 2)]

    return raw

def white_balance(raw, for_SFR_test=False):
    width = raw.shape[1]
    height = raw.shape[0]

    # 分4层
    plane = np.zeros((int(height / 2), int(width / 2), 4))
    plane[:, :, 0] = raw[::2, ::2]
    plane[:, :, 1] = raw[::2, 1::2]
    plane[:, :, 2] = raw[1::2, ::2]
    plane[:, :, 3] = raw[1::2, 1::2]

    block_size_R = 100
    block_size_C = 100

    if not for_SFR_test:
        center = [plane.shape[0] / 2 - 1, plane.shape[1] / 2 - 1]
    else:
        center = [plane.shape[0] / 2 - 1, plane.shape[1] / 2 - 1 - 0.08 * plane.shape[1]]  # slightly dodge the dot on the very center of the SFR chart

    center_block = plane[int(center[0] - block_size_R / 2 + 1):int(center[0] + int(block_size_R / 2 + 1)),
                   int(center[1] - int(block_size_C / 2) + 1): int(center[1] + int(block_size_C / 2) + 1), :]

    center_mean = np.mean((np.mean(center_block, axis=0)), axis=0)
    balance = np.max(center_mean) / center_mean

    for i in range(4):
        plane[:, :, i] = plane[:, :, i] * balance[i]

    # 4合1
    post_wb = np.zeros(raw.shape)
    post_wb[::2, ::2] = plane[:, :, 0]
    post_wb[::2, 1::2] = plane[:, :, 1]
    post_wb[1::2, ::2] = plane[:, :, 2]
    post_wb[1::2, 1::2] = plane[:, :, 3]

    return post_wb

# 镜头阴影纠正
# 涉及遍历全像素，使用Numba加速
# @numba.jit()
def lens_shading_correction(raw, FOV):
    width = raw.shape[1]
    height = raw.shape[0]

    # 找出中心并计算外接圆半径。加0.5的原因：一般来说，真实的像素是方形的，而真正的图像中心是四个像素中间的间隙，而不是某个像素
    centerX = width / 2 + 0.5 - 1
    centerY = height / 2 + 0.5 - 1
    circumradius = (centerX ** 2 + centerY ** 2) ** 0.5

    # 求出所有点所在的视野（半）角对应程度
    # pure python, slow "for loop"
    # Old Method, relied on Numba to accelerate
    # for j in range(height):
    #     for i in range(width):
    #         if not more_precise:
    #             FOV_scale = (FOV / 2) * ((centerX - i) ** 2 + (centerY - j) ** 2) ** 0.5 / circumradius
    #         else:
    #             FOV_scale = 180 / np.pi * np.arctan(np.tan(np.pi / 180 * (FOV / 2)) * ((centerX - i) ** 2 + (centerY - j) ** 2) ** 0.5 / circumradius)
    #
    #         # 采用4次余弦因子增益，次方越大，纠正效果越强(具体函数，是根据图像对角线分布函数拟合的)
    #         lsc_factor = 1 / (np.cos(np.pi / 180 * FOV_scale)) ** 4
    #         raw[j, i] = raw[j, i] * lsc_factor

    # New Method, no more "for loop", don't relied on Numba
    x_points = (centerX - np.arange(0, width)) ** 2
    y_points = (centerY - np.arange(0, height)) ** 2

    x_grid = np.tile(x_points, [len(y_points), 1])
    y_grid = np.transpose(np.tile(y_points, [len(x_points), 1]))

    FOV_grid = 180 / np.pi * np.arctan(np.tan(np.pi / 180 * (FOV / 2)) * np.sqrt(x_grid + y_grid) / circumradius)
    lsc_grid = 1 / np.cos(np.pi / 180 * FOV_grid) ** 4

    # Apply correction coefficient
    raw = lsc_grid * raw

    return raw

# 线性插值
def bilinear_interpolation_opencv(raw_bayer, bayerformat="rggb"):
    if str.lower(bayerformat) is "rggb":
        raw_bayer = cv2.cvtColor(raw_bayer, cv2.COLOR_BAYER_BG2BGR)
    elif str.lower(bayerformat) is "bggr":
        raw_bayer = cv2.cvtColor(raw_bayer, cv2.COLOR_BAYER_RG2BGR)
    elif str.lower(bayerformat) is "gbrg":
        raw_bayer = cv2.cvtColor(raw_bayer, cv2.COLOR_BAYER_GR2BGR)
    elif str.lower(bayerformat) is "grbg":
        raw_bayer = cv2.cvtColor(raw_bayer, cv2.COLOR_BAYER_GB2BGR)

def bilinear_interpolation(raw_bayer, bayerformat="rggb"):
    w = raw_bayer.shape[1]
    h = raw_bayer.shape[0]
    if str.lower(bayerformat) is "rggb":
        red_mask = np.tile(([1, 0], [0, 0]), [int(h / 2), int(w / 2)])
        green_mask = np.tile(([0, 1], [1, 0]), [int(h / 2), int(w / 2)])
        blue_mask = np.tile(([0, 0], [0, 1]), [int(h / 2), int(w / 2)])
    elif str.lower(bayerformat) is "bggr":
        blue_mask = np.tile(([1, 0], [0, 0]), [int(h / 2), int(w / 2)])
        green_mask = np.tile(([0, 1], [1, 0]), [int(h / 2), int(w / 2)])
        red_mask = np.tile(([0, 0], [0, 1]), [int(h / 2), int(w / 2)])
    elif str.lower(bayerformat) is "gbrg":
        green_mask = np.tile(([1, 0], [0, 0]), [int(h / 2), int(w / 2)])
        blue_mask = np.tile(([0, 1], [1, 0]), [int(h / 2), int(w / 2)])
        red_mask = np.tile(([0, 0], [0, 1]), [int(h / 2), int(w / 2)])
    elif str.lower(bayerformat) is "grbg":
        green_mask = np.tile(([1, 0], [0, 0]), [int(h / 2), int(w / 2)])
        red_mask = np.tile(([0, 1], [1, 0]), [int(h / 2), int(w / 2)])
        blue_mask = np.tile(([0, 0], [0, 1]), [int(h / 2), int(w / 2)])

    # 分离RG（Gr + Gb）B
    R = raw_bayer * red_mask
    G = raw_bayer * green_mask
    B = raw_bayer * blue_mask

    # 给缺失区插值
    R = R + conv2(R, np.array([[1, 1, 1], [1, 0, 1], [1, 1, 1]]), mode="same")
    G = G + conv2(G, np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0]]), mode="same")
    B = B + conv2(B, np.array([[1, 1, 1], [1, 0, 1], [1, 1, 1]]), mode="same")

    # 计算每个像素由多少个像素合成
    Rpix = conv2(red_mask, np.ones((3, 3)), "same")
    Gpix = conv2(green_mask, np.ones((3, 3)), "same")
    Gpix = Gpix - green_mask * Gpix + green_mask
    Bpix = conv2(blue_mask, np.ones((3, 3)), "same")

    R = R / Rpix
    G = G / Gpix
    B = B / Bpix

    rgb = np.zeros((h, w, 3))
    rgb[:, :, 0] = R
    rgb[:, :, 1] = G
    rgb[:, :, 2] = B

    return rgb


h,w,n = map(int, input().split())
k = 0
i = 1
j = 1
for i in range(w+1):
    i = str(i).zfill(2)

    for j in range(h+1):
        j = str(j)
        k= j+i
        print(k)


import os

from conan.internal.conan_app import ConanApp
from conan.internal.integrity_check import IntegrityChecker
from conans.errors import ConanException
from conans.model.package_ref import PkgReference
from conans.model.recipe_ref import RecipeReference
from conans.util.files import rmdir

class CacheAPI:

    def __init__(self, conan_api):
        self.conan_api = conan_api

    def export_path(self, ref: RecipeReference):
        app = ConanApp(self.conan_api.cache_folder)
        ref.revision = None if ref.revision == "latest" else ref.revision
        ref_layout = app.cache.recipe_layout(ref)
        return ref_layout.export()

    def recipe_metadata_path(self, ref: RecipeReference):
        app = ConanApp(self.conan_api.cache_folder)
        ref = _resolve_latest_ref(app, ref)
        ref_layout = app.cache.recipe_layout(ref)
        return ref_layout.metadata()

    def export_source_path(self, ref: RecipeReference):
        app = ConanApp(self.conan_api.cache_folder)
        ref.revision = None if ref.revision == "latest" else ref.revision
        ref_layout = app.cache.recipe_layout(ref)
        return ref_layout.export_sources()

    def source_path(self, ref: RecipeReference):
        app = ConanApp(self.conan_api.cache_folder)
        ref.revision = None if ref.revision == "latest" else ref.revision
        ref_layout = app.cache.recipe_layout(ref)
        return ref_layout.source()

    def build_path(self, pref: PkgReference):
        app = ConanApp(self.conan_api.cache_folder)
        pref = _resolve_latest_pref(app, pref)
        ref_layout = app.cache.pkg_layout(pref)
        return ref_layout.build()

    def package_metadata_path(self, pref: PkgReference):
        app = ConanApp(self.conan_api.cache_folder)
        pref = _resolve_latest_pref(app, pref)
        ref_layout = app.cache.pkg_layout(pref)
        return ref_layout.metadata()

    def package_path(self, pref: PkgReference):
        app = ConanApp(self.conan_api.cache_folder)
        pref = _resolve_latest_pref(app, pref)
        ref_layout = app.cache.pkg_layout(pref)
        return ref_layout.package()

    def check_integrity(self, package_list):
        """Check if the recipes and packages are corrupted (it will raise a ConanExcepcion)"""
        app = ConanApp(self.conan_api.cache_folder)
        checker = IntegrityChecker(app)
        checker.check(package_list)

    def clean(self, package_list, source=True, build=True, download=True, temp=True):
        """
        Remove non critical folders from the cache, like source, build and download (.tgz store)
        folders.
        :param package_list: the package lists that should be cleaned
        :param source: boolean, remove the "source" folder if True
        :param build: boolean, remove the "build" folder if True
        :param download: boolen, remove the "download (.tgz)" folder if True
        :param temp: boolean, remove the temporary folders
        :return:
        """

        app = ConanApp(self.conan_api.cache_folder)
        if temp:
            rmdir(app.cache.temp_folder)
            # Clean those build folders that didn't succeed to create a package and wont be in DB
            builds_folder = app.cache.builds_folder
            if os.path.isdir(builds_folder):
                for subdir in os.listdir(builds_folder):
                    folder = os.path.join(builds_folder, subdir)
                    manifest = os.path.join(folder, "p", "conanmanifest.txt")
                    info = os.path.join(folder, "p", "conaninfo.txt")
                    if not os.path.exists(manifest) or not os.path.exists(info):
                        rmdir(folder)

        for ref, ref_bundle in package_list.refs():
            ref_layout = app.cache.recipe_layout(ref)
            if source:
                rmdir(ref_layout.source())
            if download:
                rmdir(ref_layout.download_export())
            for pref, _ in package_list.prefs(ref, ref_bundle):
                pref_layout = app.cache.pkg_layout(pref)
                if build:
                    rmdir(pref_layout.build())
                if download:
                    rmdir(pref_layout.download_package())

def _resolve_latest_ref(app, ref):
    if ref.revision is None or ref.revision == "latest":
        ref.revision = None
        result = app.cache.get_latest_recipe_reference(ref)
        if result is None:
            raise ConanException(f"'{ref}' not found in cache")
        ref = result
    return ref

def _resolve_latest_pref(app, pref):
    pref.ref = _resolve_latest_ref(app, pref.ref)
    if pref.revision is None or pref.revision == "latest":
        pref.revision = None
        result = app.cache.get_latest_package_reference(pref)
        if result is None:
            raise ConanException(f"'{pref.repr_notime()}' not found in cache")
        pref = result
    return pref


def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n - 1)

if __name__ == '__main__':
    x = int(input('Enter A Positive Integer Number: '))
    num = factorial(x)
    print(f'Factorial of {x} is {num}')


from omegaconf import OmegaConf
import argparse

def parser():
    parser = argparse.ArgumentParser(description='Time-series representation framework')
    parser.add_argument('--model_name', type=str, help='model name for experiments')
    parser.add_argument('--default_cfg', type=str, help='configuration for default setting')
    parser.add_argument('--model_cfg', type=str, help='configuration for model')
    parser.add_argument(
        "opts",
        help="Modify config options using the command-line",
        default=None,
        nargs=argparse.REMAINDER,
    )

    args = parser.parse_args()

    # load configs
    cfg = OmegaConf.load(args.default_cfg)

    cfg = OmegaConf.merge(cfg, {'MODEL':{'modelname' : args.model_name}})

    if args.model_cfg:
        model_cfg = OmegaConf.load(args.model_cfg)
        modelname = cfg.MODEL.modelname

        # Check if the modelname is in the model_config
        if modelname in model_cfg:
            model_setting_conf = OmegaConf.create(model_cfg[modelname])
            # Merge the specific model config with the default config
            cfg = OmegaConf.merge(cfg, {'MODELSETTING' : model_setting_conf})
        else:
            print(f"Model '{modelname}' not found in the model_config.")
            return None

    # update cfg
    for k, v in zip(args.opts[0::2], args.opts[1::2]):
        try:
            # types except for int, float, and str
            OmegaConf.update(cfg, k, eval(v), merge=True)
        except:
            OmegaConf.update(cfg, k, v, merge=True)

    return cfg


#!flask/bin/python
from flask import Flask
from flask import jsonify
from flask import Flask, abort, request
import logging
import json
import os
import sys
import psycopg2
from pprint import pprint
import  plpygis
import simplejson
import psycopg2.extras

app = Flask(__name__)

connection = psycopg2.connect("dbname='projecty' user='vorl' host='localhost' password='' port='5432'") #Vlad
connection.set_session(autocommit=True)
logging.basicConfig(level=logging.INFO)

# postgres
########################################################################3
# update user
########################################################################################
@app.route('/api/game/user', methods=['POST'])
def user_registration():
	try:
		datauser=request.get_json()

		logging.info('registering new user {}'.format(datauser))

		cursor = connection.cursor()

		#check if userid exist
		cursor.execute("SELECT * FROM userdata WHERE userid=%s;" , [datauser['userid'],])

		if cursor.fetchone()==None:
			i=0
			create_string = "INSERT INTO userdata("
			for key in datauser:
				if i==0:
					create_string = create_string+str(key)
					i=1
				else:
					create_string = create_string+","+str(key)
			i=0
			create_string = create_string+ ") VALUES("+"'"
			for key in datauser:
				if i==0:
					create_string = create_string+str(datauser[key])
					i=1
				else:
					create_string = create_string+"'"+","+"'"+str(datauser[key])
			create_string = create_string +"'"+ ")"
			cursor.execute(create_string)

		else:
			def type_format(v):
				if isinstance(v, float) or isinstance(v, int):
					return v
				else:
					return "'{}'".format(v)

			keys = [k for k in datauser.keys() if k != 'userid']
			sql = """update userdata set {} where userid = '{}'""".format(', '.join(map(lambda k: k + '=' + type_format(datauser[k]), keys)), datauser['userid'])
			print(sql)
			cursor.execute(sql)

	except Exception as e:
		print("Error [%r]" % (e))
		sys.exit(1)
	finally:
		if cursor:
			cursor.close()

	return ''

###################################################################################################
# sync user data
########################################################################################

@app.route('/api/game/user/<userid>', methods=[ 'GET'])
def user(userid):

	logging.info('requested data for user with ID {}'.format(userid))

	cursor = connection.cursor(cursor_factory=psycopg2.extras.DictCursor)
	try:
		cursor.execute("SELECT * FROM userdata WHERE userid=%s" , [userid,])
		rows = cursor.fetchall()
		if not rows:
			name = 'Player 1'
			sql = """
			INSERT INTO userdata (userid, firstname)
			VALUES ('{userid}', '{firstname}')
			ON CONFLICT DO NOTHING
			""".format(userid=userid, firstname=name)

			cursor.execute(sql)

			return jsonify({'userid': userid, 'name': name})
		else:
			return jsonify({'userid': rows[0]['userid'], 'name': rows[0]['firstname']})

	except Exception as e:
		print("Error [%r]" % (e))
		sys.exit(1)
	finally:
		if cursor:
			cursor.close()

	return ''

###################################################################################################
# user current status
########################################################################################
@app.route('/api/game/user-score/<userid>', methods=[ 'GET'])
def user_info(userid):

	logging.info('requested scores of user with ID {}'.format(userid))

	global query_result
	cursor = connection.cursor(cursor_factory=psycopg2.extras.DictCursor)
	try:

		cursor.execute("""
		SELECT scorecategory, sum(userscore) as score
				FROM 	totalgamescore
				WHERE  userid='{userid}'
				group by scorecategory""".format(userid=userid))

		rows = cursor.fetchall()
		response = {}
		for row in rows:
			response[row['scorecategory']] = row['score']
		return jsonify(response)

	except Exception as e:
		print(e)
		return '', 500
	finally:
		if cursor:
			cursor.close()

##########################################################################################################3
# location registration
########################################################################################
@app.route('/api/game/location/<userid>', methods=['POST'])
def location(userid):

	logging.info('New location for user with ID {} reported'.format(userid))

	cursor = connection.cursor()
	try:
		location_data=request.get_json()

		sql = """
		INSERT INTO templocation (userid, longtitude, latitude)
			VALUES ('{userid}', {longtitude}, {latitude})
			ON CONFLICT (userid) DO UPDATE
			  SET longtitude = excluded.longtitude,
				  latitude = excluded.latitude
		""".format(userid=userid, longtitude=location_data['longtitude'], latitude=location_data['latitude'])

		cursor.execute(sql)

	except Exception as e:
		print(e)
		return '', 500

	finally:
		if cursor:
			cursor.close()

	return '', 200

###################################################################################################
# pull list tokens around
########################################################################################
@app.route('/api/game/getlist/<userid>/<r>', methods=['GET'])
def getlist(userid,r):

	global query_result
	try:
		cursor = connection.cursor()

		cursor.execute("SELECT * FROM templocation WHERE userid=%s;" , [userid])

		query_result_location = [ dict(line)
			for line in [zip([ column[0]
				for column in cursor.description], row)
					for row in cursor.fetchall()] ]

		cursor.execute(
							"SELECT  obj.objectid, obj.objectcategory, pointlongtitude as longtitude, pointlatitude as latitude "
							"FROM 	objectlocation  as objloc, "
								"object as obj "
								"CROSS JOIN (SELECT ST_MakePoint(%s,%s)::geography AS ref_geom) AS r "
								"WHERE ST_DWithin(ST_MakePoint(pointlatitude, pointlongtitude)::geography, ref_geom, %s) "
								"and objloc.objectid=obj.objectid "
								"and obj.objectid not in (select totalgamescore.objectid from totalgamescore where userid=%s)" ,
			(query_result_location[0]['latitude'], query_result_location[0]['longtitude'],r, userid))

		query_result = [ dict(line)
			for line in [zip([ column[0]
				for column in cursor.description], row)
					for row in cursor.fetchall()] ]

	except Exception as e:
		print("Error [%r]" % (e))
		sys.exit(1)
	finally:
		if cursor:
			cursor.close()

	logging.info('Found {} objects around user with ID {}'.format(len(query_result), userid))

	return jsonify({'Token_List': query_result})

###################################################################################################
# collection acception
########################################################################################
@app.route('/api/game/collection_reg/<userid>', methods=['POST'])
def collection_reg(userid):

	global query_result
	cursor = connection.cursor(cursor_factory=psycopg2.extras.DictCursor)
	try:
		data=request.get_json()

		objectid = data['objectid'].strip()

		logging.info('User with ID {} reported a collision with {}!'.format(userid, objectid))

		sql = """
		insert into totalgamescore(userid, userscore, scorecategory, eventtime, objectid)
		(select '{userid}', objectbasescore, objectcategory, current_timestamp, objectid from object where objectid = '{objectid}')
		ON CONFLICT DO NOTHING
		""".format(userid=userid, objectid=objectid)

		cursor.execute(sql)

		cursor.execute("""
		SELECT scorecategory, sum(userscore) as score
				FROM 	totalgamescore
				WHERE  userid='{userid}'
				group by scorecategory""".format(userid=userid))

		rows = cursor.fetchall()
		scores = {}
		for row in rows:
			scores[row['scorecategory']] = row['score']

		sql = """
		select segmentid, storyfile from segment s
			left join
			(select scorecategory, sum(userscore) as userscore
				from totalgamescore
				where userid = '{userid}'
				group by scorecategory) gs
			on s.segmentcategory = gs.scorecategory
			where segmentthreshold <= userscore
			and s.segmentid not in (select segmentid from usersegment where userid='{userid}')
			order by s.segmentid""".format(userid=userid)

		cursor.execute(sql)

		data = cursor.fetchall()
		segment_ids = list(map(lambda x: x[0], data))
		text = ' '.join(list(map(lambda x: x[1], data)))

		scores['story'] = text

		for segmentid in segment_ids:
			sql = """
			insert into usersegment(userid, segmentid) VALUES ('{userid}', '{segmentid}')
			ON CONFLICT DO NOTHING
			""".format(userid=userid, segmentid=segmentid)
			cursor.execute(sql)

		return jsonify(scores)

	except Exception as e:
		print(e)
		return '', 500
	finally:
		if cursor:
			cursor.close()

## Starts the server for serving Rest Services
if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=False)


from readline import *
from parser import Parser
from state import State
import traceback
import sys

def repl():
    running = True
    state = State()
    while running:
        line = input('- > ')
        if line == '.exit':
            running = False
            break
        if line[0] == '.':
            exec((line[1:]))
        else:
            parser = Parser(line, state)
            try:
                parser.read()
                parser.eval()
                state = parser.state
            except Exception as e:
                traceback.print_exc(file=sys.stdout)
                print('Error at char {}'.format(parser.char_num))

if __name__ == '__main__':
    repl()
    '''s = State()
    p = Parser('`(print 2)', s)
    p.read()
    print(p.stack)
    q = p.stack[0]
    print(q)
    print(q.eval(s))'''


# In this kata we want to convert a string into an integer. The strings simply represent the numbers in words.

# Examples:

#     "one" => 1
#     "twenty" => 20
#     "two hundred forty-six" => 246
#     "seven hundred eighty-three thousand nine hundred and nineteen" => 783919

# Additional Notes:

#     The minimum number is "zero" (inclusively)
#     The maximum number, which must be supported is 1 million (inclusively)
#     The "and" in e.g. "one hundred and twenty-four" is optional, in some cases it's present and in others it's not
#     All tested numbers are valid, you don't need to validate them

import re
from functools import reduce
nums = {'zero':0, 'one':1, 'two':2, 'three':3, 'four':4, 'five':5, 'six':6, 'seven':7, 'eight':8, 'nine':9, 'ten':10, 'eleven':11, 'twelve':12, 'thirteen':13, 'fourteen':14, 'fifteen':15, 'sixteen':16,  'seventeen':17, 'eighteen':18, 'nineteen':19, 'twenty':20, 'thirty':30, 'forty':40, 'fifty':50, 'sixty':60, 'seventy':70, 'eighty':80, 'ninety':90, 'hundred':100, 'thousand':1000, 'million': 1000000}
mult = { 'hundred':100, 'thousand':1000, 'million': 1000000 }
def get_num(num):
	if(nums.get(num)):
		return nums.get(num)
	else:
		num = num.split('-')
		return sum([nums[x] for x in num])

def parse_int(string):
	arr = [get_num(x) for x in re.split(' ', string) if x != 'and']
	res = 0
	i = 0
	while i < len(arr):

		if(i < len(arr)-1):
			if arr[i+1] < 100:
				res += arr[i]

			else:
				res += arr[i+1] * arr[i]
				i+=1
		else:
			res += arr[i]
		i+=1
	print(string)
	return res


message = "EKZF{Hs'r snnn dzrx, itrs bzdrzq bhogdq}"
LETTERS = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'

# 跑 52 次
for key in range(len(LETTERS)):
    output = ''
    for symbol in message:
        if symbol in LETTERS:
            num = LETTERS.find(symbol)
            num -= key
            if num < 0:
                num += len(LETTERS)
            output += LETTERS[num]
        else:
            output += symbol
    print('%s. %s' % (key, output))


class BaseStation:
    """基站

    Attributes:
        id:
        address: latitude-longitude
        latitude:
        longitude:
        num_users:
        workload: the total used time (min)
    """

    def __init__(self, id, addr, lat, lng):
        self.id = id
        self.address = addr
        self.latitude = lat
        self.longitude = lng
        self.num_users = 0
        self.workload = 0

    def __str__(self):
        return "No.{0}: {1}".format(self.id, self.address)


#!/usr/bin/python3
"""This is the borrower class"""
from models.base_model import BaseModel, Base
from sqlalchemy import Column, String, Integer, ForeignKey
from sqlalchemy.orm import relationship

class Lender(BaseModel, Base):
    """This is the class for Lender
    Attributes:
    loan_size: amount looking to loan
    loan_duration: length of loan
    l_m_r_t: lowest interest rate WTA
    """
    __tablename__ = 'lenders'
    loan_size = Column(Integer, nullable=True)
    loan_duration = Column(Integer, nullable=True)
    interest = Column(Integer, nullable=False)
    email = Column(String(60), nullable=False)
    user_id = Column(String(60), ForeignKey('users.id'), nullable=False)
    user = relationship("User", back_populates="lender")


from django.urls import path
from . import views

urlpatterns =[
    path("",views.index, name="index"),
    path('list/',views.repolist,name='repos'),
    path('logout/', views.logout_page, name='logout'),
    path('<name>/repo_details/', views.repo_details, name='repos_details'),
    path('<name>/data/', views.data, name='data'),
    path('<name>/create_branch/', views.create_branch, name='create_branch'),
    path("<name>/file/", views.file, name="file"),
    path("<name>/file_details/", views.file_details, name='file_details'),
    path("<name>/pull_request/", views.pull_req, name="pull_req"),
    path("<name>/pull_details/", views.pull_details, name="pull_details"),
    path("<name>/merging/", views.merging, name="merging"),
    path("<name>/merge/", views.merge, name="merge"),
    path("<name>/del_branch/", views.del_branch, name="del_branch"),
    path("<name>/delete/", views.delete, name="delete"),
]


#!/usr/bin/python3
"""
Creates a BaseModel class that defines attributes and
methods for other classes
"""

import datetime
import uuid
import json
import models

class BaseModel:
    """Creates base model for other classes"""

    def __init__(self, *args, **kwargs):
        """class constructor"""
        if kwargs:
            for key, value in kwargs.items():
                if key == "__class__":
                    pass
                elif "updated_at" == key:
                    self.updated_at = datetime.datetime.strptime(
                        kwargs["updated_at"], "%Y-%m-%dT%H:%M:%S.%f")
                elif "created_at" == key:
                    self.created_at = datetime.datetime.strptime(
                        kwargs["created_at"], "%Y-%m-%dT%H:%M:%S.%f")
                else:
                    setattr(self, key, value)
        else:
            self.id = str(uuid.uuid4())
            self.created_at = datetime.datetime.now()
            self.updated_at = datetime.datetime.now()
            models.storage.new(self)

    def __str__(self):
        """string representation of the base class"""
        return "[{}] ({}) {}".format(
            self.__class__.__name__, self.id, self.__dict__)

    def save(self):
        """updates the updated_at instance attribute to current time"""
        self.updated_at = datetime.datetime.now()
        models.storage.save()

    def to_dict(self):
        """returns a dictionary containing keys/values of the instance"""
        dictionary = {}
        dictionary['__class__'] = self.__class__.__name__

        for key, value in self.__dict__.items():
            if key == "created_at" or key == "updated_at":
                dictionary[key] = value.isoformat()
            else:
                dictionary[key] = value
        return dictionary


import unittest
from typing import List, Optional

from common import TreeNode, create_binary_tree

class Solution:
    def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        return [] if not root else self.postorderTraversal(root.left) + self.postorderTraversal(root.right) + [root.val]

    def postorderTraversalIterative(self, root: Optional[TreeNode]) -> List[int]:
        res, stack = [], [(root, False)]
        while stack:
            node, visited = stack.pop()
            if node:
                if visited:
                    res.append(node.val)
                else:
                    stack.append((node, True))
                    stack.append((node.right, False))
                    stack.append((node.left, False))
        return res

class TestResult(unittest.TestCase):
    def run_test(self, data, expect):
        # result = Solution().postorderTraversal(create_binary_tree(data))
        result = Solution().postorderTraversalIterative(create_binary_tree(data))

        self.assertEqual(result, expect)

    def test_case1(self):
        data = [1, None, 2, 3]
        expect = [3, 2, 1]
        self.run_test(data, expect)

    def test_case2(self):
        data = []
        expect = []
        self.run_test(data, expect)

    def test_case3(self):
        data = [1]
        expect = [1]
        self.run_test(data, expect)

    def test_case4(self):
        data = [1, 4, 3, 2]
        expect = [2, 4, 3, 1]
        self.run_test(data, expect)

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


n = int(input())
res = 0
for i in range(n):
    tmp = input().split()
    tmp.sort()
    a, b, c = map(int, tmp)
    if a == b and b == c:
        money = 10000 + a*1000
    elif a==b or a==c: # 같은 애로 계산해야 되기 때문에 elif 나눔
        money = 1000 + a*100
    elif b==c:
        money = 1000 + b*100
    else:
        money = c*100
    if money > res:
        res = money
print(res)


from server.models.User import User, UserSchema
from flask import request
from flask_restful import Resource
from flask_jwt_extended import (
    create_access_token,
    set_access_cookies,
    create_refresh_token,
    get_csrf_token,
    set_refresh_cookies,
    jwt_required,
    get_jwt_identity,
    jwt_refresh_token_required
)
from server.helpers.api import custom_json_response
from server.helpers.image_uploads import upload_picture
from datetime import timedelta
from marshmallow import ValidationError
import os
import json

user_schema = UserSchema()
user_schema_private = UserSchema(exclude=['password', 'email', 'address'])

class UserResource(Resource):
    @jwt_required
    def get(self):
        all_users = User.get_all()
        return user_schema_private.dump(all_users, many=True)

    def post(self):
        req_body = request.get_json()
        try:
            # load method from marshmallow validates data according to schema definition
            valid_data = user_schema.load(req_body)
        except ValidationError as err:
            return custom_json_response(err.messages, 400)

        if User.get_user_by_email(req_body['email']):
            return custom_json_response({
                "error": "User already exists. Please supply a different email."
            }, 400)

        new_user = User(**valid_data)
        new_user.save()

        access_token = create_access_token(
            identity={"id": new_user.id}, expires_delta=timedelta(days=30))

        refresh_token = create_refresh_token(
            identity={"id": new_user.id}, expires_delta=timedelta(days=30))

        response_data = {
            "message": "Created",
            "user": user_schema.dump(new_user)
        }
        response = custom_json_response(response_data, 201)

        set_access_cookies(response, access_token)
        set_refresh_cookies(response, refresh_token)

        return response

    @jwt_required
    def put(self):
        current_userid = get_jwt_identity().get('id')
        req_body = request.form.to_dict()

        # convert cuisines from stringified json list to a python list
        if req_body.get('cuisines') and isinstance(req_body['cuisines'], str):
            req_body['cuisines'] = json.loads(req_body['cuisines'])

        req_image = request.files.get('profileImage')

        if req_image:
            s3_file_path = f'users/{current_userid}/profile_pic'
            profile_image_url = upload_picture(req_image, s3_file_path)

            if not profile_image_url:
                return custom_json_response({"error": "Error with uploading image"}, 400)

            req_body['profileImage'] = profile_image_url

        if req_body.get('email'):
            return custom_json_response({
                "error": "Cannot use this route to update email address."
            }, 403)

        try:
            valid_data = user_schema.load(req_body, partial=True)

        except ValidationError as err:
            return custom_json_response(err.messages, 400)

        user = User.get_by_id(current_userid)

        user.update(valid_data)
        data = {
            "user": user_schema.dump(user),
            "message": "Succesfully Edited."
        }
        return custom_json_response(data, 200)


from __future__ import annotations
import asyncio
import contextlib
import copy
import errno
import fcntl
import functools
import logging as __logging
import os
import pty
import select
import signal
import struct
import sys
import termios
import threading
import tty
import types
import typing

import rnsh.exception as exception

module_logger = __logging.getLogger(__name__)

CTRL_C = "\x03".encode("utf-8")
CTRL_D = "\x04".encode("utf-8")

def tty_add_reader_callback(fd: int, callback: callable, loop: asyncio.AbstractEventLoop = None):
    """
    Add an async reader callback for a tty file descriptor.

    Example usage:

        def reader():
            data = tty_read(fd)
            # do something with data

        tty_add_reader_callback(self._child_fd, reader, self._loop)

    :param fd: file descriptor
    :param callback: callback function
    :param loop: asyncio event loop to which the reader should be added. If None, use the currently-running loop.
    """
    if loop is None:
        loop = asyncio.get_running_loop()
    loop.add_reader(fd, callback)

def tty_read(fd: int) -> bytes:
    """
    Read available bytes from a tty file descriptor. When used in a callback added to a file descriptor using
    tty_add_reader_callback(...), this function creates a solution for non-blocking reads from ttys.
    :param fd: tty file descriptor
    :return: bytes read
    """
    if fd_is_closed(fd):
        raise EOFError

    try:
        run = True
        result = bytearray()
        while not fd_is_closed(fd):
            ready, _, _ = select.select([fd], [], [], 0)
            if len(ready) == 0:
                break
            for f in ready:
                try:
                    data = os.read(f, 4096)
                except OSError as e:
                    if e.errno != errno.EIO and e.errno != errno.EWOULDBLOCK:
                        raise
                else:
                    if not data:  # EOF
                        if data is not None and len(data) > 0:
                            result.extend(data)
                            return result
                        elif len(result) > 0:
                            return result
                        else:
                            raise EOFError
                    if data is not None and len(data) > 0:
                        result.extend(data)
        return result
    except EOFError:
        raise
    except Exception as ex:
        module_logger.error("tty_read error: {ex}")

def tty_read_poll(fd: int) -> bytes:
    """
    Read available bytes from a tty file descriptor. When used in a callback added to a file descriptor using
    tty_add_reader_callback(...), this function creates a solution for non-blocking reads from ttys.
    :param fd: tty file descriptor
    :return: bytes read
    """
    if fd_is_closed(fd):
        raise EOFError

    result = bytearray()
    try:
        flags = fcntl.fcntl(fd, fcntl.F_GETFL)
        fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
        try:
            data = os.read(fd, 4096)
            result.extend(data or [])
        except OSError as e:
            if e.errno != errno.EIO and e.errno != errno.EWOULDBLOCK:
                raise
            elif e.errno == errno.EIO:
                raise EOFError
    except EOFError:
        raise
    except Exception as ex:
        module_logger.error("tty_read error: {ex}")
    return result

def fd_is_closed(fd: int) -> bool:
    """
    Check if file descriptor is closed
    :param fd: file descriptor
    :return: True if file descriptor is closed
    """
    try:
        fcntl.fcntl(fd, fcntl.F_GETFL) < 0
    except OSError as ose:
        return ose.errno == errno.EBADF

def tty_unset_reader_callbacks(fd: int, loop: asyncio.AbstractEventLoop = None):
    """
    Remove async reader callbacks for file descriptor.
    :param fd: file descriptor
    :param loop: asyncio event loop from which to remove callbacks
    """
    with exception.permit(SystemExit):
        if loop is None:
            loop = asyncio.get_running_loop()
        loop.remove_reader(fd)

def tty_get_winsize(fd: int) -> [int, int, int, int]:
    """
    Ge the window size of a tty.
    :param fd: file descriptor of tty
    :return: (rows, cols, h_pixels, v_pixels)
    """
    packed = fcntl.ioctl(fd, termios.TIOCGWINSZ, struct.pack('HHHH', 0, 0, 0, 0))
    rows, cols, h_pixels, v_pixels = struct.unpack('HHHH', packed)
    return rows, cols, h_pixels, v_pixels

def tty_set_winsize(fd: int, rows: int, cols: int, h_pixels: int, v_pixels: int):
    """
    Set the window size on a tty.
    :param fd: file descriptor of tty
    :param rows: number of visible rows
    :param cols: number of visible columns
    :param h_pixels: number of visible horizontal pixels
    :param v_pixels: number of visible vertical pixels
    """
    if fd < 0:
        return
    packed = struct.pack('HHHH', rows, cols, h_pixels, v_pixels)
    fcntl.ioctl(fd, termios.TIOCSWINSZ, packed)

def process_exists(pid) -> bool:
    """
    Check For the existence of a unix pid.
    :param pid: process id to check
    :return: True if process exists
    """
    try:
        os.kill(pid, 0)
    except OSError:
        return False
    else:
        return True

class TTYRestorer(contextlib.AbstractContextManager):
    # Indexes of flags within the attrs array
    ATTR_IDX_IFLAG = 0
    ATTR_IDX_OFLAG = 1
    ATTR_IDX_CFLAG = 2
    ATTR_IDX_LFLAG = 4
    ATTR_IDX_CC    = 5

    def __init__(self, fd: int, suppress_logs=False):
        """
        Saves termios attributes for a tty for later restoration.

        The attributes are an array of values with the following meanings.

            tcflag_t c_iflag;      /* input modes */
            tcflag_t c_oflag;      /* output modes */
            tcflag_t c_cflag;      /* control modes */
            tcflag_t c_lflag;      /* local modes */
            cc_t     c_cc[NCCS];   /* special characters */

        :param fd: file descriptor of tty
        """
        self._log = module_logger.getChild(self.__class__.__name__)
        self._fd = fd
        self._tattr = None
        self._suppress_logs = suppress_logs
        self._tattr = self.current_attr()
        if not self._tattr and not self._suppress_logs:
            self._log.debug(f"Could not get attrs for fd {fd}")

    def raw(self):
        """
        Set raw mode on tty
        """
        if self._fd is None:
            return
        with contextlib.suppress(termios.error):
            tty.setraw(self._fd, termios.TCSANOW)

    def original_attr(self) -> [any]:
        return copy.deepcopy(self._tattr)

    def current_attr(self) -> [any]:
        """
        Get the current termios attributes for the wrapped fd.
        :return: attribute array
        """
        if self._fd is None:
            return None

        with contextlib.suppress(termios.error):
            return copy.deepcopy(termios.tcgetattr(self._fd))
        return None

    def set_attr(self, attr: [any], when: int = termios.TCSADRAIN):
        """
        Set termios attributes
        :param attr: attribute list to set
        :param when: when attributes should be applied (termios.TCSANOW, termios.TCSADRAIN, termios.TCSAFLUSH)
        """
        if not attr or self._fd is None:
            return

        with contextlib.suppress(termios.error):
            termios.tcsetattr(self._fd, when, attr)

    def isatty(self):
        return os.isatty(self._fd) if self._fd is not None else None

    def restore(self):
        """
        Restore termios settings to state captured in constructor.
        """
        self.set_attr(self._tattr, termios.TCSADRAIN)

    def __exit__(self, __exc_type: typing.Type[BaseException], __exc_value: BaseException,
                 __traceback: types.TracebackType) -> bool:
        self.restore()
        return False  #__exc_type is not None and issubclass(__exc_type, termios.error)

def _task_from_event(evt: asyncio.Event, loop: asyncio.AbstractEventLoop = None):
    if not loop:
        loop = asyncio.get_running_loop()

    #TODO: this is hacky
    async def wait():
        while not evt.is_set():
            await asyncio.sleep(0.1)
        return True

    return loop.create_task(wait())

class AggregateException(Exception):
    def __init__(self, inner_exceptions: [Exception]):
        super().__init__()
        self.inner_exceptions = inner_exceptions

    def __str__(self):
        return "Multiple exceptions encountered: \n\n" + "\n\n".join(map(lambda e: str(e), self.inner_exceptions))

async def event_wait_any(evts: [asyncio.Event], timeout: float  = None) -> (any, any):
    tasks = list(map(lambda evt: (evt, _task_from_event(evt)), evts))
    try:
        finished, unfinished = await asyncio.wait(map(lambda t: t[1], tasks),
                                                  timeout=timeout,
                                                  return_when=asyncio.FIRST_COMPLETED)

        if len(unfinished) > 0:
            for task in unfinished:
                task.cancel()
            await asyncio.wait(unfinished)

        exceptions = []

        for f in finished:
            ex = f.exception()
            if ex and not isinstance(ex, asyncio.CancelledError) and not isinstance(ex, TimeoutError):
                exceptions.append(ex)

        if len(exceptions) > 0:
            raise AggregateException(exceptions)

        return next(map(lambda t: next(map(lambda tt: tt[0], tasks)), finished), None)
    finally:
        unfinished = []
        for task in map(lambda t: t[1], tasks):
            if task.done():
                if not task.cancelled():
                    task.exception()
            else:
                task.cancel()
                unfinished.append(task)
        if len(unfinished) > 0:
            await asyncio.wait(unfinished)

async def event_wait(evt: asyncio.Event, timeout: float) -> bool:
    """
    Wait for event to be set, or timeout to expire.
    :param evt: asyncio.Event to wait on
    :param timeout: maximum number of seconds to wait.
    :return: True if event was set, False if timeout expired
    """
    await event_wait_any([evt], timeout=timeout)
    return evt.is_set()

def _launch_child(cmd_line: list[str], env: dict[str, str], stdin_is_pipe: bool, stdout_is_pipe: bool,
                  stderr_is_pipe: bool) -> tuple[int, int, int, int]:
    # Set up PTY and/or pipes
    child_fd = parent_fd = None
    if not (stdin_is_pipe and stdout_is_pipe and stderr_is_pipe):
        parent_fd, child_fd = pty.openpty()
    child_stdin, parent_stdin = (os.pipe() if stdin_is_pipe else (child_fd, parent_fd))
    parent_stdout, child_stdout = (os.pipe() if stdout_is_pipe else (parent_fd, child_fd))
    parent_stderr, child_stderr = (os.pipe() if stderr_is_pipe else (parent_fd, child_fd))

    # Fork
    pid = os.fork()

    if pid == 0:
        try:
            # We are in the child process, so close all open sockets and pipes except for the PTY and/or pipes
            max_fd = os.sysconf("SC_OPEN_MAX")
            for fd in range(3, max_fd):
                if fd not in (child_stdin, child_stdout, child_stderr):
                    try:
                        os.close(fd)
                    except OSError:
                        pass

            # Set up PTY and/or pipes
            os.dup2(child_stdin, 0)
            os.dup2(child_stdout, 1)
            os.dup2(child_stderr, 2)
            # Make PTY controlling if necessary
            if child_fd is not None:
                os.setsid()
                try:
                    tmp_fd = os.open(os.ttyname(0 if not stdin_is_pipe else 1 if not stdout_is_pipe else 2), os.O_RDWR)
                    os.close(tmp_fd)
                except:
                    pass
                # fcntl.ioctl(0 if not stdin_is_pipe else 1 if not stdout_is_pipe else 2), os.O_RDWR, termios.TIOCSCTTY, 0)

            # Execute the command
            os.execvpe(cmd_line[0], cmd_line, env)
        except Exception as err:
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(f"Unable to start {cmd_line[0]}: {err} ({fname}:{exc_tb.tb_lineno})")
            sys.stdout.flush()
        # don't let any other modules get in our way, do an immediate silent exit.
        os._exit(255)

    else:
        # We are in the parent process, so close the child-side of the PTY and/or pipes
        if child_fd is not None:
            os.close(child_fd)
        if child_stdin != child_fd:
            os.close(child_stdin)
        if child_stdout != child_fd:
            os.close(child_stdout)
        if child_stderr != child_fd:
            os.close(child_stderr)
        # # Close the write end of the pipe if a pipe is used for standard input
        # if not stdin_is_pipe:
        #     os.close(parent_stdin)
        # Return the child PID and the file descriptors for the PTY and/or pipes
        return pid, parent_stdin, parent_stdout, parent_stderr

class CallbackSubprocess:
    # time between checks of child process
    PROCESS_POLL_TIME: float = 0.1

    def __init__(self, argv: [str], env: dict, loop: asyncio.AbstractEventLoop, stdout_callback: callable,
                 stderr_callback: callable, terminated_callback: callable, stdin_is_pipe: bool, stdout_is_pipe: bool,
                 stderr_is_pipe: bool):
        """
        Fork a child process and generate callbacks with output from the process.
        :param argv: the command line, tokenized. The first element must be the absolute path to an executable file.
        :param env: environment variables to override
        :param loop: the asyncio event loop to use
        :param stdout_callback: callback for data, e.g. def callback(data:bytes) -> None
        :param terminated_callback: callback for termination/return code, e.g. def callback(return_code:int) -> None
        """
        assert loop is not None, "loop should not be None"
        assert stdout_callback is not None, "stdout_callback should not be None"
        assert terminated_callback is not None, "terminated_callback should not be None"

        self._log = module_logger.getChild(self.__class__.__name__)
        # self._log.debug(f"__init__({argv},{term},...")
        self._command: [str] = argv
        self._env = env or {}
        self._loop = loop
        self._stdout_cb = stdout_callback
        self._stderr_cb = stderr_callback
        self._terminated_cb = terminated_callback
        self._pid: int = None
        self._child_stdin: int = None
        self._child_stdout: int = None
        self._child_stderr: int = None
        self._return_code: int = None
        self._stdout_eof: bool = False
        self._stderr_eof: bool = False
        self._stdin_is_pipe = stdin_is_pipe
        self._stdout_is_pipe = stdout_is_pipe
        self._stderr_is_pipe = stderr_is_pipe

    def _ensure_pipes_closed(self):
        self._log.debug("Ensuring pipes are closed")
        stdin = self._child_stdin
        stdout = self._child_stdout
        stderr = self._child_stderr
        fds = list(filter(lambda x: x is not None, list({stdin, stdout, stderr})))
        for fd in fds:
            self._log.debug(f"Closing fd {fd}")
            with contextlib.suppress(OSError):
                os.close(self._child_stdin)
            with contextlib.suppress(OSError):
                tty_unset_reader_callbacks(fd)
        self._child_stdin = None
        self._child_stdout = None
        self._child_stderr = None

    def terminate(self, kill_delay: float = 1.0):
        """
        Terminate child process if running
        :param kill_delay: if after kill_delay seconds the child process has not exited, escalate to SIGHUP and SIGKILL
        """

        self._log.debug("terminate()")
        if not self.running:
            return

        with exception.permit(SystemExit):
            os.kill(self._pid, signal.SIGTERM)

        def kill():
            if process_exists(self._pid):
                self._log.debug("kill()")
                with exception.permit(SystemExit):
                    os.kill(self._pid, signal.SIGHUP)
                    os.kill(self._pid, signal.SIGKILL)

        self._loop.call_later(kill_delay, kill)

        def wait():
            self._log.debug("wait()")
            with contextlib.suppress(OSError):
                os.waitpid(self._pid, 0)
            self._ensure_pipes_closed()
            self._log.debug("wait() finish")

        threading.Thread(target=wait, daemon=True).start()

    def close_stdin(self):
        with contextlib.suppress(Exception):
            os.close(self._child_stdin)

    @property
    def started(self) -> bool:
        """
        :return: True if child process has been started
        """
        return self._pid is not None

    @property
    def running(self) -> bool:
        """
        :return: True if child process is still running
        """
        return self._pid is not None and process_exists(self._pid)

    def write(self, data: bytes):
        """
        Write bytes to the stdin of the child process.
        :param data: bytes to write
        """
        os.write(self._child_stdin, data)

    def set_winsize(self, r: int, c: int, h: int, v: int):
        """
        Set the window size on the tty of the child process.
        :param r: rows visible
        :param c: columns visible
        :param h: horizontal pixels visible
        :param v: vertical pixels visible
        :return:
        """
        self._log.debug(f"set_winsize({r},{c},{h},{v}")
        tty_set_winsize(self._child_stdout, r, c, h, v)

    def copy_winsize(self, fromfd: int):
        """
        Copy window size from one tty to another.
        :param fromfd: source tty file descriptor
        """
        r, c, h, v = tty_get_winsize(fromfd)
        self.set_winsize(r, c, h, v)

    def tcsetattr(self, when: int, attr: list[any]):  # actual type is list[int | list[int | bytes]]
        """
        Set tty attributes.
        :param when: when to apply change: termios.TCSANOW or termios.TCSADRAIN or termios.TCSAFLUSH
        :param attr: attributes to set
        """
        termios.tcsetattr(self._child_stdin, when, attr)

    def tcgetattr(self) -> list[any]:  # actual type is list[int | list[int | bytes]]
        """
        Get tty attributes.
        :return: tty attributes value
        """
        return termios.tcgetattr(self._child_stdout)

    def ttysetraw(self):
        tty.setraw(self._child_stdout, termios.TCSADRAIN)

    def start(self):
        """
        Start the child process.
        """
        self._log.debug("start()")

        # # Using the parent environment seems to do some weird stuff, at least on macOS
        # parentenv = os.environ.copy()
        # env = {"HOME": parentenv["HOME"],
        #        "PATH": parentenv["PATH"],
        #        "TERM": self._term if self._term is not None else parentenv.get("TERM", "xterm"),
        #        "LANG": parentenv.get("LANG"),
        #        "SHELL": self._command[0]}

        env = os.environ.copy()
        for key in self._env:
            env[key] = self._env[key]

        program = self._command[0]
        assert isinstance(program, str)

        # match = re.search("^/bin/(.*sh)$", program)
        # if match:
        #     self._command[0] = "-" + match.group(1)
        #     env["SHELL"] = program
        #     self._log.debug(f"set login shell {self._command}")

        self._pid, \
            self._child_stdin, \
            self._child_stdout, \
            self._child_stderr = _launch_child(self._command, env, self._stdin_is_pipe, self._stdout_is_pipe,
                                               self._stderr_is_pipe)

        def poll():
            # self.log.debug("poll")
            try:
                pid, self._return_code = os.waitpid(self._pid, os.WNOHANG)
                if self._return_code is not None:
                    self._return_code = self._return_code & 0xff
                if self._return_code is not None and not process_exists(self._pid):
                    self._log.debug(f"polled return code {self._return_code}")
                    self._terminated_cb(self._return_code)
                if self.running:
                    self._loop.call_later(CallbackSubprocess.PROCESS_POLL_TIME, poll)
                else:
                    self._ensure_pipes_closed()
            except Exception as e:
                if not hasattr(e, "errno") or e.errno != errno.ECHILD:
                    self._log.debug(f"Error in process poll: {e}")

        self._loop.call_later(CallbackSubprocess.PROCESS_POLL_TIME, poll)

        def stdout():
            try:
                with exception.permit(SystemExit):
                    data = tty_read_poll(self._child_stdout)
                    if data is not None and len(data) > 0:
                        self._stdout_cb(data)
            except EOFError:
                self._stdout_eof = True
                tty_unset_reader_callbacks(self._child_stdout)
                self._stdout_cb(bytearray())

        def stderr():
            try:
                with exception.permit(SystemExit):
                    data = tty_read_poll(self._child_stderr)
                    if data is not None and len(data) > 0:
                        self._stderr_cb(data)
            except EOFError:
                self._stderr_eof = True
                tty_unset_reader_callbacks(self._child_stderr)
                self._stdout_cb(bytearray())

        tty_add_reader_callback(self._child_stdout, stdout, self._loop)
        if self._child_stderr != self._child_stdout:
            tty_add_reader_callback(self._child_stderr, stderr, self._loop)

    @property
    def stdout_eof(self):
        return self._stdout_eof or not self.running

    @property
    def stderr_eof(self):
        return self._stderr_eof or not self.running

    @property
    def return_code(self) -> int:
        return self._return_code

    @property
    def pid(self) -> int:
        return self._pid

async def main():
    """
    A test driver for the CallbackProcess class.
    python ./process.py /bin/zsh --login
    """

    log = module_logger.getChild("main")
    if len(sys.argv) <= 1:
        print(f"Usage: {sys.argv} <absolute_path_to_child_executable> [child_arg ...]")
        exit(1)

    loop = asyncio.get_event_loop()
    # asyncio.set_event_loop(loop)
    retcode = loop.create_future()

    def stdout(data: bytes):
        # log.debug("stdout")
        os.write(sys.stdout.fileno(), data)
        # sys.stdout.flush()

    def terminated(rc: int):
        # log.debug(f"terminated {rc}")
        retcode.set_result(rc)

    process = CallbackSubprocess(argv=sys.argv[1:],
                                 env={"TERM": os.environ.get("TERM", "xterm")},
                                 loop=loop,
                                 stdout_callback=stdout,
                                 terminated_callback=terminated)

    def sigint_handler(sig, frame):
        # log.debug("KeyboardInterrupt")
        if process is None or process.started and not process.running:
            raise KeyboardInterrupt
        elif process.running:
            process.write("\x03".encode("utf-8"))

    def sigwinch_handler(sig, frame):
        # log.debug("WindowChanged")
        process.copy_winsize(sys.stdin.fileno())

    signal.signal(signal.SIGINT, sigint_handler)
    signal.signal(signal.SIGWINCH, sigwinch_handler)

    def stdin():
        try:
            data = tty_read(sys.stdin.fileno())
            # log.debug(f"stdin {data}")
            if data is not None:
                process.write(data)
                # sys.stdout.buffer.write(data)
        except EOFError:
            tty_unset_reader_callbacks(sys.stdin.fileno())
            process.write(CTRL_D)

    tty_add_reader_callback(sys.stdin.fileno(), stdin)
    process.start()
    # call_soon called it too soon, not sure why.
    loop.call_later(0.001, functools.partial(process.copy_winsize, sys.stdin.fileno()))

    val = await retcode
    log.debug(f"got retcode {val}")
    return val

if __name__ == "__main__":
    tr = TTYRestorer(sys.stdin.fileno())
    try:
        tr.raw()
        asyncio.run(main())
    finally:
        tty_unset_reader_callbacks(sys.stdin.fileno())
        tr.restore()


totIdade = 0
maiorIdadeHomem = 0
nomeVelho = 0
totMulher = 0
for p in range(1, 5):
    print(f'----- {p}ª PESSOA -----')
    nome = str(input('Nome: ')).strip().upper()
    idade = int(input('Idade: '))
    sexo = str(input('Sexo [M/F]: ')).strip().upper()
    totIdade += idade
    if idade > maiorIdadeHomem and sexo == 'M':
        maiorIdadeHomem = idade
        nomeVelho = nome
    if sexo == 'F' and idade < 20:
        totMulher += 1
mediaIdade = totIdade / 4
print(f'A média de idade do grupo é de {mediaIdade} anos.')
print(f'O nome do Homem mais velho é {nomeVelho} e ele tem {maiorIdadeHomem} anos.')
if totMulher == 0:
    print('Não temos mulheres menores de 20 anos no grupo')
else:
    print(f'Nesse grupo possuí {totMulher} mulheres menores de 20 anos.')


from typing import Iterable, Mapping, Optional, Tuple

from django.http import Http404

from sentry.models import (
    Identity,
    IdentityProvider,
    IdentityStatus,
    Integration,
    Organization,
    User,
)
from sentry.types.integrations import EXTERNAL_PROVIDERS, ExternalProviders

def get_identity_or_404(
    provider: ExternalProviders,
    user: User,
    integration_id: int,
    organization_id: Optional[int] = None,
) -> Tuple[Organization, Integration, IdentityProvider]:
    """For endpoints, short-circuit with a 404 if we cannot find everything we need."""
    try:
        integration = Integration.objects.get(id=integration_id)
        idp = IdentityProvider.objects.get(
            external_id=integration.external_id, type=EXTERNAL_PROVIDERS[provider]
        )
        organization_filters = dict(
            member_set__user=user,
            organizationintegration__integration=integration,
        )
        # If provided, ensure organization_id is valid.
        if organization_id:
            organization_filters.update(dict(id=organization_id))
        organization = Organization.objects.filter(**organization_filters)[0]
    except Exception:
        raise Http404
    return organization, integration, idp

def get_identities_by_user(idp: IdentityProvider, users: Iterable[User]) -> Mapping[User, Identity]:
    identity_models = Identity.objects.filter(
        idp=idp,
        user__in=users,
        status=IdentityStatus.VALID,
    )
    return {identity.user: identity for identity in identity_models}


# Python program to calculate time
class Time(object):
    def __init__(self,hours,minutes):
        self.hours = hours
        self.minutes = minutes

    def addTime(time1,time2):
        res_time = Time(0,0)
        res_time.hours = time1.hours+time2.hours
        res_time.minutes = time1.minutes + time2.minutes
        if res_time.minutes>=60:
            res_time.hours+=1
            res_time.minutes-=60
            return res_time

    def displayTime(self):
        print("The resultant time is {} hours and {} minutes.".format(self.hours,self.minutes))

    def displayMinutes(self):
        print("The total minutes are {}".format(self.hours*60+self.minutes))

h1 = int(input("Enter hour 1:  "))
m1 = int(input("enter minutes after hour 1:  "))
h2 = int(input("Enter hour 2:  "))
m2 = int(input("Enter minutes after hour 2:  "))

t1 = Time(h1,m1)
t2 = Time(h2,m2)
res_time = Time.addTime(t1,t2)

res_time.displayTime()
res_time.displayMinutes()


import os
import sys
import tkinter as tk
from tkinter import filedialog, messagebox

import pandas as pd

class InsertNewData(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        search_frame = tk.Frame(self)
        search_frame.pack(pady=10, padx=10)

        label = tk.Label(search_frame, text="Search for a grape variety:")
        label.grid(row=0, column=0, sticky='w')

        # Entry field for user input
        self.variety_entry = tk.Entry(search_frame)
        self.variety_entry.grid(row=0, column=1)

        # Button to perform the search
        search_button = tk.Button(search_frame, text="Search", command=self.search_variety)
        search_button.grid(row=0, column=2)

        # Label to display the result
        self.result_label = tk.Label(self, text="")
        self.result_label.pack()

        # Create a frame for the upload section
        upload_frame = tk.Frame(self)
        upload_frame.pack()

        # Flag to keep track whether the edit button is visible or not
        self.edit_button_visible = False

        # Label to explain what the "Upload File" button does
        upload_text = tk.Label(upload_frame, text="Upload a file to bulk add varieties to the database:")
        upload_text.pack(side=tk.LEFT)  # Place it on the left

        # Button to upload an external file
        upload_button = tk.Button(upload_frame, text="Upload File", command=self.load_external_file)
        upload_button.pack(side=tk.LEFT)  # Place it on the left

        welcome_button = tk.Button(self, text="🏠 Go to Home Page", command=lambda: controller.show_frame("WelcomePage"))
        welcome_button.place(x=0, y=0)

        # label that confirms that the value is updated
        self.edit_successful = tk.Label(self, text="")
        self.edit_successful.pack()

        # Get the directory where the script is running, considering pyinstaller
        self.script_directory = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))

    def search_variety(self):
        # Get the user input from the entry field
        user_input = self.variety_entry.get()

        # Remove any existing edit button
        for widget in self.winfo_children():
            if isinstance(widget, tk.Button) and widget.cget("text") == "Edit":
                widget.destroy()

        # Construct the full path to the CSV file
        csv_file_path = os.path.join(os.path.join(os.path.expanduser("~"), "Vinesco"), "database",
                                     "Varieties_Ground_Truth.csv")

        # Load the CSV file and search for the variety
        try:
            df = pd.read_csv(csv_file_path)
            result = df[df['Variety'] == user_input]

            if not result.empty:
                self.result_label.config(text=result.to_string(index=False))
                edit_button = tk.Button(self, text="Edit", command=lambda: self.edit_result(user_input))
                edit_button.pack()
            else:
                response = messagebox.askyesno("Variety Not Found",
                                               "Variety not found in database. Do you want to add it?")
                if response:
                    # Add the new variety to the database
                    new_row = pd.DataFrame({'Variety': [user_input]})
                    df = pd.concat([df, new_row], ignore_index=True)
                    df.to_csv(csv_file_path, index=False)
                    self.result_label.config(text="Variety added to database.")
        except FileNotFoundError:
            self.result_label.config(text="File not found. Make sure the database exists.")

    def load_external_file(self):
        # Prompt the user to select a CSV file
        file_path = filedialog.askopenfilename()

        if file_path:
            try:
                # Read the file type and handle the case appropriately
                if file_path.endswith(".csv"):
                    df = pd.read_csv(file_path)
                elif file_path.endswith(".xlsx"):
                    df = pd.read_excel(file_path)
                elif file_path.endswith(".txt"):
                    df = pd.read_csv(file_path, sep="\t")
                elif file_path.endswith(".json"):
                    df = pd.read_json(file_path)
                elif file_path.endswith(".xls"):
                    df = pd.read_excel(file_path)
                else:
                    raise FileNotFoundError

                # Load the selected CSV file
                csv_file_path = os.path.join(self.script_directory, "database", "Varieties_Ground_Truth.csv")
                try:
                    db = pd.read_csv(csv_file_path)
                    merged_db = pd.concat([db, df], ignore_index=True)
                    merged_db.to_csv(csv_file_path, index=False)
                except FileNotFoundError:
                    # If the database doesn't exist yet, create a new one
                    df.to_csv(csv_file_path, index=False)

                self.result_label.config(text="File uploaded and merged with the database.")

            except FileNotFoundError:
                self.result_label.config(text="Selected file not found or is not in appropriate format.")

    def edit_result(self, user_input):
        # Remove any existing edit fields
        for widget in self.winfo_children():
            if isinstance(widget, tk.Entry) and widget.winfo_parent() == self.winfo_id():
                widget.destroy()

        if not self.edit_button_visible:
            # Create a label to display the result
            result_label = tk.Label(self, text=f"Variety: {user_input}")
            result_label.pack()
            # Create a text input to search for the column
            column_entry = tk.Entry(self)
            column_entry.pack()

            # Create a text input to edit the value
            value_entry = tk.Entry(self)
            value_entry.pack()

            # Create a button to perform the search
            search_button = tk.Button(self, text="Enter DNA marker/value",
                                      command=lambda: self.edit_result_search(column_entry.get(), value_entry.get(),
                                                                              user_input))
            search_button.pack()

            self.edit_button_visible = True

    def edit_result_search(self, column, value, user_input):
        """Search for the column in the dataset. If the column is found, the user should be able to edit the value. If
        not, a new column should be created."""
        try:
            csv_file_path = os.path.join(os.path.join(os.path.expanduser("~"), "Vinesco"), "database",
                                         "Varieties_Ground_Truth.csv")
            df = pd.read_csv(csv_file_path)
            result = df[df['Variety'] == user_input]

            if not result.empty:
                # If the column exists, edit the value
                df.loc[df['Variety'] == user_input, column] = value
                df.to_csv(csv_file_path, index=False)
                self.edit_successful.config(text="Value updated.")
            else:
                # If the column doesn't exist, create a new one
                df[column] = value
                df.to_csv(csv_file_path, index=False)
                self.edit_successful.config(text="Column created.")
        except FileNotFoundError:
            self.edit_successful.config(text=f"File not found.Make sure the database exists.")

if __name__ == "__main__":
    app = tk.Tk()
    app.geometry("800x400")  # Set the window size
    app.title("Grape Variety Search")

    frame = InsertNewData(app, None)
    frame.pack(fill="both", expand=True)

    app.mainloop()


from torch.utils.data import DataLoader
import torch.utils.data as data
import torch
import os
import os.path
from torchvision import transforms
import numpy as np
from PIL import Image, ImageFile
import matplotlib.pyplot as plt

ImageFile.LOAD_TRUNCATED_IMAGES = True
IMG_EXTENSIONS = [
    '.jpg', '.JPG', '.jpeg', '.JPEG',
    '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP',
]

class_weight = [5.603479582009111, 4.29526217910912, 33.5735969320392, 3.335498275510207, 15.485574406695266, 8.738715632316753,
              31.541973276563166, 32.01203384130015, 12.828815882297924, 38.01410671061199, 43.907386358778936]
mean = (0.41189488770418226, 0.4251328066237724, 0.432670702070482)
std = (0.3070734955953852, 0.3116110784489235, 0.3072184293428751)

def is_image_file(filename):
    return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)

def make_dataset(d):
    images = []
    annot = []

    for root, _, fnames in sorted(os.walk(d)):
        for fname in fnames:
            if is_image_file(fname):
                path = os.path.join(root, fname)
                item = path
                images.append(item)

    for root, _, fnames in sorted(os.walk("%sannot" % d)):
        for fname in fnames:
            if is_image_file(fname):
                path = os.path.join(root, fname)
                item = path
                annot.append(item)

    return images, annot

# transform label images to floattensor
class MaskToTensor(object):
    def __call__(self, img):
        return torch.from_numpy(np.array(img, dtype=np.int32)).float()

class Loaddata(data.Dataset):

    def __init__(self, root, transform=None, target_transform=None, joint_transform=None):

        imgs, annot = make_dataset(root)
        if len(imgs) == 0:
            raise(RuntimeError("Found 0 images in subfolders of: " + root + "\n"
                               "Supported image extensions are: " + ",".join(IMG_EXTENSIONS)))

        self.root = root
        self.imgs = imgs
        self.annot = annot
        self.transform = transform
        self.target_transform = target_transform
        self.joint_transform = joint_transform
        self.n_classes = 12

    def __getitem__(self, index):
        path_to_img = self.imgs[index]
        path_to_target = self.annot[index]
        img = Image.open(path_to_img)
#        img = np.array(img, dtype=np.uint8)

        target = Image.open(path_to_target)

        if self.joint_transform is not None:
            img, target = self.joint_transform(img, target)
        if self.transform is not None:
            img = self.transform(img)
        if self.target_transform is not None:
            target = self.target_transform(target)

        return img, target

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

    def decode_segmap(self, temp):
        Sky = [128, 128, 128]
        Building = [128, 0, 0]
        Pole = [192, 192, 128]
        Road = [128, 64, 128]
        Pavement = [60, 40, 222]
        Tree = [128, 128, 0]
        SignSymbol = [192, 128, 128]
        Fence = [64, 64, 128]
        Car = [64, 0, 128]
        Pedestrian = [64, 64, 0]
        Bicyclist = [0, 128, 192]
        Unlabelled = [0, 0, 0]

        label_colours = np.array([Sky, Building, Pole, Road,
                                  Pavement, Tree, SignSymbol, Fence, Car,
                                  Pedestrian, Bicyclist, Unlabelled])
        r = temp.copy()
        g = temp.copy()
        b = temp.copy()
        for l in range(0, self.n_classes):
            r[temp == l] = label_colours[l, 0]
            g[temp == l] = label_colours[l, 1]
            b[temp == l] = label_colours[l, 2]

        rgb = np.zeros((temp.shape[0], temp.shape[1], 3))
        rgb[:, :, 0] = r / 255.0
        rgb[:, :, 1] = g / 255.0
        rgb[:, :, 2] = b / 255.0
        return rgb

if __name__ == '__main__':
    local_path = 'C:/Users/mchiwml4/dataset/segmentation/camvid/train'
    joint_transform = jointtransform.Compose([
                jointtransform.RandomCrop(224),
                jointtransform.RandomHorizontallyFlip()
                ])
    transform = transforms.Compose([
                transforms.ToTensor()
                ])
    dst = Loaddata(local_path, transform=transform, target_transform=MaskToTensor(), joint_transform= joint_transform)
    bs = 4
    trainloader = DataLoader(dst, batch_size=bs)
    for i, image in enumerate(trainloader):
        imgs, labels = image
        imgs = imgs.numpy()
        imgs = np.transpose(imgs, [0,2,3,1])
        labels.squeeze_()
        f, axarr = plt.subplots(bs, 2)
        for j in range(bs):
            axarr[j][0].imshow(imgs[j])
            axarr[j][1].imshow(dst.decode_segmap(labels.numpy()[j]))
        plt.show()
        if i == 0:
            break


import json

from django.shortcuts import render
import execjs
from django.http import HttpResponse

def get_js():
    # f = open("D:/WorkSpace/MyWorkSpace/jsdemo/js/des_rsa.js",'r',encoding='UTF-8')
    f = open("static/decode.js", 'r', encoding='UTF-8')
    line = f.readline()
    htmlstr = ''
    while line:
        htmlstr = htmlstr + line
        line = f.readline()
    return htmlstr

def upload(request):
    jsstr = get_js()
    ctx = execjs.compile(jsstr)
    v = ctx.call('decodeMessage', request.GET['data'])

    print(v)
    return HttpResponse(json.dumps(v), content_type="application/json")
    # return render(request, 'index.html', content)


#!/usr/bin/env python3
from django.core.management.base import BaseCommand

from workshops.models import Tag

TAGS = [
    {
        'name': 'automated-email' ,
        'priority': 0,
        'details': 'Only for automated emails',
    },
    {
        'name': 'online',
        'priority': 7,
        'details': 'Events taking place entirely online.',
    },
    {
        'name': 'Instructor Training',
        'priority': 8,
        'details': 'Instructor Trainer',
    },
    {
        'name': 'cancelled',
        'priority': 9,
        'details': 'Events that were supposed to happen but due to some circumstances got cancelled',
    },
    {
        'name': 'unresponsive',
        'priority': 10,
        'details': "Events whose hosts and/or organizers aren't going to send data",
    },
    {
        'name': 'stalled',
        'priority': 11,
        'details': "Events with lost contact with the host or TTT events that aren't running.",
    },
    {
        'name': 'hackathon',
        'priority': 15,
        'details': 'Event is a hackathon',
    },
    {
        'name': 'CW',
        'priority': 16,
        'details': 'Curriculum Workshop',
    },
    {
        'name': 'HIC',
        'priority': 100,
        'details': 'Event being done in a High Income Country',
    },
    {
        'name': 'LMIC',
        'priority': 130,
        'details': 'Event occurring in a Low or Middle Income Country',
    },
    {
        'name': 'ECR',
        'priority': 140,
        'details': 'Event is a school for ECRs',
    },
    {
        'name': 'Data Steward',
        'priority': 110,
        'details': 'Event is a Data Steward training event',
    },

]

class Command(BaseCommand):

    help = "Setup tags according to what's desired"

    def handle(self, *args, **options):
        sords_tags_names = [sords_tag['name'] for sords_tag in TAGS]
        for tag in Tag.objects.all():
            if tag.name not in sords_tags_names:
                tag.delete()
            if tag.name in sords_tags_names:
                for entry in TAGS:
                    if entry['name'] == tag.name:
                        correct_tag = entry
                        tag.priority = correct_tag['priority']
                        tag.details = correct_tag['details']
                        tag.save()
        for tag_object in TAGS:
            obj, created = Tag.objects.get_or_create(**tag_object)
            if created:
                print(f"Created {obj.name}")
            if not created:
                print(f"{obj.name} already created, skipping.")


# from tensorflow.keras.datasets import mnist
from keras.datasets import mnist
from sklearn.preprocessing import OneHotEncoder
import tensorflow as tf
import numpy as np
from sklearn.metrics import accuracy_score

(x_train, y_train), (x_test, y_test) = mnist.load_data()

x_train = x_train.reshape(60000, 28*28)
x_test = x_test.reshape(10000, 28*28)

# OneHotEncoder

y_train = y_train[:,np.newaxis]
y_test = y_test[:,np.newaxis]

enc = OneHotEncoder()
y_train = enc.fit_transform(y_train).toarray()
y_test = enc.transform(y_test).toarray()

# 모델 구성

x = tf.compat.v1.placeholder(tf.float32, shape=[None, 28*28])
y = tf.compat.v1.placeholder(tf.float32, shape=[None, 10])

# 히든 레이어

w = tf.Variable(tf.random_normal([28*28,512]), name='weight')
b = tf.Variable(tf.random_normal([512]), name='bias')

layers = tf.nn.relu(tf.matmul(x, w) + b)

# 히든 레이어

w = tf.Variable(tf.random_normal([512,256]), name='weight')
b = tf.Variable(tf.random_normal([256]), name='bias')

layers = tf.nn.relu(tf.matmul(layers, w) + b)

# 히든 레이어

w = tf.Variable(tf.random_normal([256,64]), name='weight')
b = tf.Variable(tf.random_normal([64]), name='bias')

layers = tf.nn.relu(tf.matmul(layers, w) + b)

# 아웃풋 레이어

w = tf.Variable(tf.random_normal([64,10]), name='weight')
b = tf.Variable(tf.random_normal([10]), name='bias')

# hyporthesis = x * w + b
# layers = tf.nn.relu(tf.matmul(x, w) + b)
# layers = tf.nn.elu(tf.matmul(x, w) + b)
# layers = tf.nn.selu(tf.matmul(x, w) + b)
# layers = tf.nn.dropout(layer, keep_prob=0.3)
# hypothesis = tf.sigmoid(tf.matmul(layers, w) + b)
hypothesis = tf.nn.softmax(tf.matmul(layers, w) + b)

# cost  = tf.reduce_mean(tf.square(hypothesis-y)) # mse
# cost = -tf.reduce_mean(y*tf.log(hypothesis)+(1-y)*tf.log(1-hypothesis)) # binary_crossentropy
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(hypothesis), axis=1))    # categorical_crossentropy

# optimizer  = tf.train.GradientDescentOptimizer(learning_rate=1e-5)
optimizer  = tf.train.GradientDescentOptimizer(learning_rate=1e-1)
train = optimizer.minimize(cost)

# predicted = tf.cast(hypothesis > 0.5, dtype=tf.float32)
# accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, y), dtype=tf.float32))

sess = tf.compat.v1.Session()
sess.run(tf.global_variables_initializer())

for epochs in range(1001):
    cost_val, hy_val, _ = sess.run([cost, hypothesis, train],
            feed_dict={x:x_train, y:y_train})
    if epochs % 200 == 0:
        print(epochs, "cost :", cost_val, '\n', hy_val)

predict = sess.run(hypothesis, feed_dict={x:x_test})
y_pred = np.argmax(predict, axis=1)
y_test = np.argmax(y_test, axis=1)

print('acc_score :', accuracy_score(y_test, y_pred))

# acc_score : 0.098

sess.close()


n, m, k, x = 4, 4, 1, 1
graph = [[],
         [2,3],
         [3,4],
         [],
         []]

# "모든 도로의 거리가 1" 이라는 조건 덕분에 BFS를 이용하여 간단히 해결
# 출발점으로 가까이 있는게 최단거리니까

from collections import deque

distance = [-1] * (n+1)
distance[x] = 0

q = deque([x])
while q:
    now = q.popleft()
    for next_node in graph[now]:
        if distance[next_node] == -1:
            distance[next_node] = distance[now] + 1
            q.append([next_node])

check = False
for i in range(distance):
    if i == k:
        print(i)
        check = True

if not check:
    print(-1)

[Coding Test] 이코테/기출문제/15 특정 거리의 도시 찾기.py

15 특정 거리의 도시 찾기.py


import General as general
import bruteforce as brute
import naive as naiveDivideConquer
import enhanced as enhancedDivideConquer
import time as timer

# summary: produces lists of size numInputs and run each algorithm
# @param numInputs: number of inputs
def measureRunTime(numInputs):

  bruteForceTimes = []
  naiveTimes = []
  enhancedTimes = []

  for i in range (10):
    testList = general.genFloats(numInputs)

    #start measuring brute force
    start = timer.clock()
    brute.bruteForce(testList)
    end = timer.clock()
    time = end - start
    bruteForceTimes.append(time)

    #start measuring naive
    start = timer.clock()
    testListNaive = general.sortList(testList)
    naiveDivideConquer.naiveDivideConquer(testListNaive)
    end = timer.clock()
    time = end - start
    naiveTimes.append(time)

    #start measuring enhanced
    start = timer.clock()
    ySorted = general.sortY(testList)
    testListEnhanced = general.sortList(testList)
    enhancedDivideConquer.EnhancedDivideConquer(testListEnhanced, ySorted)
    end = timer.clock()
    time = end - start
    enhancedTimes.append(time)

  averageBrute = sum(bruteForceTimes)/len(bruteForceTimes)
  averageNaive = sum(naiveTimes)/len(naiveTimes)
  averageEnhanced = sum(enhancedTimes)/len(enhancedTimes)

  return averageBrute, averageNaive, averageEnhanced

# summary: Test time without running brute force
# @param numInputs: number of inputs
def measureNoBruteForce(numInputs):

  naiveTimes = []
  enhancedTimes = []

  for i in range (10):
    testList = general.genFloats(numInputs)

    #start measuring brute force
    #start = timer.clock()
    #brute.bruteForce(testList)
    #end = timer.clock()
    #time = end - start
    #bruteForceTimes.append(time)

    #start measuring naive
    start = timer.clock()
    testListNaive = general.sortList(testList)
    naiveDivideConquer.naiveDivideConquer(testListNaive)
    end = timer.clock()
    time = end - start
    naiveTimes.append(time)

    #start measuring enhanced
    start = timer.clock()
    ySorted = general.sortY(testList)
    testListEnhanced = general.sortList(testList)
    enhancedDivideConquer.EnhancedDivideConquer(testListEnhanced, ySorted)
    end = timer.clock()
    time = end - start
    enhancedTimes.append(time)

  averageNaive = sum(naiveTimes)/len(naiveTimes)
  averageEnhanced = sum(enhancedTimes)/len(enhancedTimes)

  return averageNaive, averageEnhanced

##############Measuring Average Running Times####################

brute100, naive100, enhanced100 = measureRunTime(100)
brute500, naive500, enhanced500 = measureRunTime(500)
brute1000, naive1000, enhanced1000 = measureRunTime(1000)
brute5000, naive5000, enhanced5000 = measureRunTime(5000)
#brute10000, naive10000, enhanced10000 = measureRunTime(10000)

# don't plot times for brute force for n > 100000 because
# that takes too much time
naive10000, enhanced10000 = measureNoBruteForce(10000)
naive50000, enhanced50000 = measureNoBruteForce(50000)
naive100000, enhanced100000 = measureNoBruteForce(100000)

bruteTimes = [brute100, brute500, brute1000, brute5000]
naiveTimes = [naive100, naive500, naive1000, naive5000, naive10000, naive50000, naive100000]
enhancedTimes = [enhanced100, enhanced500, enhanced1000, enhanced5000, enhanced10000, enhanced50000, enhanced100000]

#write to external file and plot in matlab
bruteFile = open('brutetimes.txt', 'w+')
numInput = [100, 500, 1000, 5000]
arrayElement = 0
for item in bruteTimes:
  bruteFile.write("%s %f\n" % (numInput[arrayElement], item))
  arrayElement = arrayElement + 1
bruteFile.close()

naiveFile = open('naivetimes.txt', 'w+')
numInput = [100, 500, 1000, 5000, 10000, 50000, 100000]
arrayElement = 0
for item in naiveTimes:
  naiveFile.write("%s %f\n" % (numInput[arrayElement], item))
  arrayElement = arrayElement + 1
naiveFile.close()

enhancedFile = open('enhancedtimes.txt', 'w+')
numInput = [100, 500, 1000, 5000, 10000, 50000, 100000]
arrayElement = 0
for item in enhancedTimes:
  enhancedFile.write("%s %f\n" % (numInput[arrayElement], item))
  arrayElement = arrayElement + 1
enhancedFile.close()

print("Done")


from django.contrib import admin
from django.shortcuts import reverse
from django.templatetags.static import static
from django.utils.html import format_html
from burgershop.apps.restaurants.models import Restaurant
from burgershop.apps.restaurants.admin import RestaurantMenuItemInline

from .models import Product, ProductCategory

class ProductsFilterByRestaurant(admin.SimpleListFilter):
    title = 'Доступны в Ресторане'
    parameter_name = 'restaurant_pk'

    def lookups(self, request, model_admin):
        queryset = Restaurant.objects.all()
        restaurants = {
            (
                str(restaurant.pk),
                restaurant.name,
            )
            for restaurant in queryset
        }
        return restaurants

    def queryset(self, request, queryset):
        restaurant_pk = self.value()
        if restaurant_pk:
            return queryset.filter(
                menu_items__restaurant__pk=restaurant_pk,
                menu_items__availability=True
            ).distinct()

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = (
        'get_image_list_preview',
        'name',
        'category',
        'price',
    )
    list_display_links = (
        'name',
    )
    list_filter = (
        'category',
        ProductsFilterByRestaurant,
    )
    search_fields = (
        # FIXME SQLite can not convert letter case for cyrillic words properly, so search will be buggy.
        # Migration to PostgreSQL is necessary
        'name',
        'category__name',
    )

    inlines = (
        RestaurantMenuItemInline,
    )
    fieldsets = (
        ('Общее', {
            'fields': [
                'name',
                'category',
                'image',
                'get_image_preview',
                'price',
            ]
        }),
        ('Подробно', {
            'fields': [
                'special_status',
                'description',
            ],
            'classes': [
                'wide'
            ],
        }),
    )

    readonly_fields = (
        'get_image_preview',
    )

    class Media:
        css = {
            "all": (
                static("admin/products.css")
            )
        }

    def get_image_preview(self, obj):
        if not obj.image:
            return 'выберите картинку'
        return format_html(
            '',
            url=obj.image.url
        )
    get_image_preview.short_description = 'превью'

    def get_image_list_preview(self, obj):
        if not obj.image or not obj.id:
            return 'нет картинки'
        edit_url = reverse('admin:products_product_change', args=(obj.id,))
        return format_html(
            '',
            edit_url=edit_url, src=obj.image.url
        )
    get_image_list_preview.short_description = 'превью'

@admin.register(ProductCategory)
class ProductCategoryAdmin(admin.ModelAdmin):
    pass


# spiral
from sense_hat import SenseHat
from time import sleep
from random import randint

sense = SenseHat()
sense.clear()

while True:
    minx=0
    maxx=7
    miny=0
    maxy=7

    r=randint(0,255)
    g=randint(0,255)
    b=255
    step=3

    sense.low_light = True

    j=miny
    for a in range(4):
        for i in range(minx,maxx+1):
            sense.set_pixel(i,j,[r,g,b])
            b-=step
            sleep(0.2)
        miny+=1
        for j in range(miny,maxy+1):
            sense.set_pixel(i,j,[r,g,b])
            b-=step
            sleep(0.2)
        maxx-=1
        for i in range(maxx,minx-1,-1):
            sense.set_pixel(i,j,[r,g,b])
            b-=step
            sleep(0.2)
        maxy-=1
        for j in range(maxy,miny-1,-1):
            sense.set_pixel(i,j,[r,g,b])
            b-=step
            sleep(0.2)
        minx+=1


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

"""This script tests that layout primitives geometries work properly."""

from typing import Dict, Any, Set

import yaml

from bag import BagProject
from bag.layout.util import BBox
from bag.layout.objects import Path, Blockage, Boundary, Polygon, TLineBus
from bag.layout.template import TemplateBase, TemplateDB

class Test1(TemplateBase):
    def __init__(self, temp_db, lib_name, params, used_names, **kwargs):
        # type: (TemplateDB, str, Dict[str, Any], Set[str], **Any) -> None
        super(Test1, self).__init__(temp_db, lib_name, params, used_names, **kwargs)

    @classmethod
    def get_params_info(cls):
        return dict()

    def draw_layout(self):
        res = self.grid.resolution

        # simple rectangle
        self.add_rect('M1', BBox(100, 60, 180, 80, res, unit_mode=True))

        # a path
        width = 20
        points = [(0, 0), (2000, 0), (3000, 1000), (3000, 3000)]
        path = Path(res, 'M2', width, points, 'truncate', 'round', unit_mode=True)
        self.add_path(path)

        # set top layer and bounding box so parent can query those
        self.prim_top_layer = 3
        self.prim_bound_box = BBox(0, 0, 400, 400, res, unit_mode=True)

class Test2(TemplateBase):
    def __init__(self, temp_db, lib_name, params, used_names, **kwargs):
        # type: (TemplateDB, str, Dict[str, Any], Set[str], **Any) -> None
        super(Test2, self).__init__(temp_db, lib_name, params, used_names, **kwargs)

    @classmethod
    def get_params_info(cls):
        return dict()

    def draw_layout(self):
        res = self.grid.resolution

        # instantiate Test1
        master = self.template_db.new_template(params={}, temp_cls=Test1)
        self.add_instance(master, 'X0', loc=(-100, -100), orient='MX', unit_mode=True)

        # add via, using BAG's technology DRC calculator
        self.add_via(BBox(0, 0, 100, 100, res, unit_mode=True),
                     'M1', 'M2', 'x')

        # add a primitive pin
        self.add_pin_primitive('mypin', 'M1', BBox(-100, 0, 0, 20, res, unit_mode=True))

        # add a polygon
        points = [(0, 0), (300, 200), (100, 400)]
        p = Polygon(res, 'M3', points, unit_mode=True)
        self.add_polygon(p)

        # add a blockage
        points = [(-1000, -1000), (-1000, 1000), (1000, 1000), (1000, -1000)]
        b = Blockage(res, 'placement', '', points, unit_mode=True)
        self.add_blockage(b)

        # add a boundary
        points = [(-500, -500), (-500, 500), (500, 500), (500, -500)]
        b = Boundary(res, 'PR', points, unit_mode=True)
        self.add_boundary(b)

        # add a parallel path bus
        widths = [100, 50, 100]
        spaces = [80, 80]
        points = [(0, -3000), (-3000, -3000), (-4000, -2000), (-4000, 0)]
        bus = TLineBus(res, ('M2', 'drawing'), points, widths, spaces, end_style='round',
                       unit_mode=True)
        for p in bus.paths_iter():
            self.add_path(p)

        self.prim_top_layer = 3
        self.prim_bound_box = BBox(-10000, -10000, 10000, 10000, res, unit_mode=True)

if __name__ == '__main__':
    with open('specs_test/geometry_test.yaml', 'r') as f:
        block_specs = yaml.load(f)

    local_dict = locals()
    if 'bprj' not in local_dict:
        print('creating BAG project')
        bprj = BagProject()

    else:
        print('loading BAG project')
        bprj = local_dict['bprj']

    bprj.generate_cell(block_specs, Test2, gen_lay=True, gen_sch=False, run_lvs=False,
                       debug=True)


from django.urls import path
from .views import index, add_forum, index_json, add_api_forum
from comment.views import index as index_comment

urlpatterns = [
    path('', index, name='forum_list'),
    path('add/', add_forum, name='add'),
    path('add-api/', add_api_forum, name='add'),
    path('json/', index_json, name='json api'),
    path('<int:id>', index_comment, name='comment'),
]


N = int(input())
row = list(map(int, input().split()))

dp = [1] * N

for i in range(N):
    for j in range(i):
        if row[i] > row[j] :
            dp[i] = max(dp[i], dp[j]+1)

answer = max(dp)
answer_list = []
print(answer)
for i in range(N-1,-1,-1):
    if dp[i] == answer :
        answer_list.append(row[i])
        answer -= 1
answer_list.reverse()
print(*answer_list)

백준/Gold/14002. 가장 긴 증가하는 부분 수열 4/가장 긴 증가하는 부분 수열 4.py

가장 긴 증가하는 부분 수열 4.py


import os
import sys
# This program gets the total size of files in a folder

dir_path = input('Input a folder path: ')

# If it isn't a file path alert the user
if os.path.isdir(dir_path):
	# convert input to a directory path that works for all systems
	dir_path = os.path.join(dir_path)
else:
    print(f'The input path: {dir_path} isn\'t a folder or directory')
    sys.exit()

# get all the filenames filtered from the directory
file_names = list(filter(lambda names: os.path.isfile(os.path.join(dir_path, names)), os.listdir(dir_path)))

# for each file_names in the directory path create a file_path for it
file_paths = [os.path.join(dir_path, name) for name in file_names]

# get the size of each file
file_sizes = [os.path.getsize(file) for file in file_paths]

# get the sum of the file sizes
total_size = sum(file_sizes)

print(f"Size of files in {dir_path}: {total_size} bytes")


from flask import Flask, jsonify
import requests
from bs4 import BeautifulSoup

app = Flask(__name__)

@app.route('/get_latest_stories', methods=['GET'])
def get_latest_stories():
    try:
        url = 'https://time.com/'
        response = requests.get(url)

        if response.status_code == 200:
            soup = BeautifulSoup(response.text, 'html.parser')

            story_elements = soup.find_all('li', class_='latest-stories__item')

            stories = []

            for story in story_elements[:6]:
                title = story.text.strip()
                link = story.find('a')['href']
                stories.append({'Title': title, 'Link': link})

            return jsonify({'stories': stories})
        else:
            return jsonify({'error': 'Failed to fetch data from Time.com'}), 500
    except Exception as e:
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    app.run(debug=True)