from audioop import tostereo
from email.mime import audio
from operator import is_
from tkinter import Widget
from turtle import width
import pygame
import math
import numpy
import matplotlib
import matplotlib.pyplot as plt
pygame.init()

WHITE=(255, 255, 255)
GREEN = (0, 128, 0)
RED = (188, 39, 50)
BLUE = (0, 40, 180)
PINK = (255, 182, 193)

font = pygame.font.SysFont("Helvetica", 16)

WIDTH, HEIGHT = 800, 800
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Debris Simulation")

apg_x, apg_y, apg_z = 0, 0, 0
prg_x, prg_y, prg_z= 0, 0, 0

apg_angles = []
apgangle = 0#-3.15 + 0.00287
prg_angles = []
prgangle = -0.3952# + 0.02 - 0.006 - 0.0142
apgpseudo = 0
prgpseudo = 0

apg0 = 0
prg0 = 0

apg0_x, apg0_y, apg0_z, prg0_x, prg0_y, prg0_z = 0, 0, 0, 0, 0, 0

anode = (0, 0)
dnode = (0, 0)
xn , yn = 0, 0

top = int(input("1 for side view \n0 for top view\n"))
def dist(xa, ya, za, xb, yb, zb):
    dx = xa-xb
    dy = ya-yb
    dz = za-zb
    distance = math.sqrt(dx**2 + dy**2 + dz**2)
    return distance
class body:
    AU = 149597871000
    RL = 384000000 # radius of the Moon's orbit

    c= 3*(10**8)
    G = 6.67428e-11
    SIR = 1361 # Solar irradiance
    MO = 25000000 # mean orbital radius of the debris
    px = 250
    SCALE = px/(MO)
    TIMESTEP = 10 # dt = 10s

    def __init__ (self, x, y, z, radius, color, mass, real_radius):
        self.x = x
        self.y = y
        self.z = z
        self.radius = radius
        self.real_radius = real_radius
        self.color = color
        self.mass = mass

        self.xvel = 0
        self.yvel = 0
        self.zvel = 0

        self.center = False
        self.is_debris = False
        self.colided = False
        self.distance_to_center = 0
        self.apg = 0
        self.prg = math.sqrt(self.x**2  + self.y**2 + self.z*2)*2
        self.orbit = []
        self.zs = [self.z]
        self.zi = 0

    def draw(self, win):
        x = self.x*self.SCALE + WIDTH/2
        y = self.y*self.SCALE + HEIGHT/2

        if len(self.orbit) > 2:
            updated_points = []

            for point in self.orbit:
                x, y = point
                x = x*self.SCALE+ WIDTH/2
                y = y*self.SCALE+ HEIGHT/2
                updated_points.append((x,HEIGHT - y))

            pygame.draw.lines(win, self.color, False, updated_points, 1)
        pygame.draw.circle(win, self.color, (x, HEIGHT-y), self.radius)

    def attraction(self, other):
        dist_x=(other.x- self.x)
        dist_y=(other.y -self.y)
        dist_z=(other.z - self.z)
        dist = math.sqrt(dist_x**2 + dist_y**2 + dist_z**2)

        if other.center:
            self.distance_to_center = dist
        force = self.G * self.mass * other.mass / dist**2
        psi = math.asin(dist_z/dist)
        theta = math.atan2(dist_y, dist_x)

        force_plane = force*math.cos(psi)
        force_z = force*math.sin(psi)
        force_y = force_plane*math.sin(theta)
        force_x = force_plane*math.cos(theta)

        return force_x, force_y, force_z
    def drag(self):
        t_kelv = 273.1 -131.21 + self.distance_to_center*0.00299
        pressure = 2.488 * (t_kelv/216.6)**(-11.388)
        rho = pressure/(0.2869 * t_kelv)

        vel = math.sqrt(self.xvel**2 + self.yvel**2 + self.zvel**2)
        area = math.pi * self.real_radius**2
        drag = -0.5 * 0.5 * area * (vel**2) * rho

        psi = math.asin(self.zvel/vel)
        theta = math.atan2(self.yvel, self.xvel)

        drag_plane = drag * math.cos(psi)
        drag_z = drag* math.sin(psi)
        drag_y = drag_plane * math.sin(theta)
        drag_x = drag_plane * math.cos(theta)

        return drag_x, drag_y, drag_z

    def update_position(self, bodies):
        total_fx = total_fy = total_fz = 0
        global anode, dnode
        for body in bodies:
            if self == body or self.center:
                continue

            fx, fy, fz = self.attraction(body)
            total_fx+= fx
            total_fy += fy
            total_fz += fz
            if self.is_debris == True:
                drx, dry, drz = self.drag() #applying drag!!
                total_fx+= drx
                total_fy+= dry
                total_fz+= drz
                #total_fx += self.G*self.mass*(1.9*(10**30))/(self.AU -self.x)**2 # applying the attraction from the Sun

        if self.is_debris:
            if math.sqrt(self.y**2 + self.z**2) > 6380000 or self.x > 0:
                total_fx -= self.SIR/self.c * math.pi *self.real_radius**2 # applying the force due to solar radiation pressure

        self.xvel += (total_fx/self.mass)*self.TIMESTEP
        self.yvel += (total_fy/self.mass)*self.TIMESTEP
        if self.is_debris: self.zvel += (total_fz/self.mass)*self.TIMESTEP

        self.x += self.xvel *self.TIMESTEP
        self.y += self.yvel * self.TIMESTEP
        if self.is_debris:
            self.z += self.zvel * self.TIMESTEP
            self.zi += 1
            self.zs.append(self.z)

        if self.is_debris and (numpy.sign(self.zs[self.zi]) == -numpy.sign(self.zs[self.zi-1]) or self.z == 0) and self.zvel != 0:
            if self.zvel > 0:
                anode = (self.x, self.y)
            elif self.zvel < 0:
                dnode = (self.x, self.y)

        if self.is_debris and top == 1:
            self.orbit.append((self.x, self.z))
        else:
            self.orbit.append((self.x, self.y))
        if self.distance_to_center < 6380000:
            self.colided = True

    def energy(self, other):
        distx = self.x - other.x
        disty = self.y - other.y
        distz = self.z - other.z
        dist = math.sqrt(distx**2 + disty**2 + distz**2)
        erg = -(self.G*self.mass*other.mass)/dist
        return erg
def toScale(x, y, body):
    x = x*body.SCALE + WIDTH/2
    y = HEIGHT/2 - y*body.SCALE
    return x, y
apg_neg_ang = 0
prg_neg_ang = 0

def elements(self):
    global prgpseudo, apgpseudo, apg_neg_ang, prg_neg_ang, apg_x, prg_x, apg_y, prg_y, apg_z, prg_z, apg_selected, prg_selected, apg0, prg0, apg_angles, prg_angles, apg0_x, apg0_y, apg0_z, prg0_x, prg0_y, prg0_z

    apgang = 0
    apgsgn = 0
    prgsgn = 0
    if self.distance_to_center > self.apg:
        if ((self.yvel > 0 and self.y < apg0_y) or (self.yvel < 0 and self.y > apg0_y)) and apg_neg_ang == 0:
            apgsgn = -1
        else:
            apg0 = self.apg
            apg0_x = apg_x
            apg0_y = apg_y
            apg0_z = apg_z
            apgsgn = +1
        self.apg = self.distance_to_center
        apg_x = self.x
        apg_y = self.y
        apg_z = self.z
        apgdistanc = dist(apg_x, apg_y, apg_z, apg0_x, apg0_y, apg0_z)
        if self.apg != 0 and apg0 != 0: apgang = math.acos((apg0**2 + self.apg**2 - apgdistanc**2)/(2*apg0*self.apg))
        if ((self.yvel > 0 and self.y < apg0_y) or (self.yvel < 0 and self.y > apg0_y)) and apg_neg_ang == 0:
            apg_neg_ang = -1 * apgang
            apgang = 0
            print("aici intra")

    elif apg_neg_ang != 0:
        apgang = apgpseudo + apg_neg_ang
        apg_neg_ang = 0
        apgpseudo = 0
    prgang = 0
    if self.distance_to_center <= self.prg:
        if ((self.yvel > 0 and self.y < prg0_y) or (self.yvel < 0 and self.y > prg0_y)) and prg_neg_ang == 0:
            print("yep yep")
            prgsgn = -1
        else:
            prg0 = self.prg
            prg0_x = prg_x
            prg0_y = prg_y
            prg0_z = prg_z
            prgsgn = +1
        self.prg = self.distance_to_center
        prg_x = self.x
        prg_y = self.y
        prg_z = self.z
        prgdistanc = dist(prg_x, prg_y, prg_z, prg0_x, prg0_y, prg0_z)
        if prg0 != 0 and self.prg != 0: prgang = math.acos((prg0**2 + self.prg**2 - prgdistanc**2)/(2*prg0*self.prg))
        if ((self.yvel > 0 and self.y < prg0_y) or (self.yvel < 0 and self.y > prg0_y)) and prg_neg_ang == 0:
            prg_neg_ang = -1*prgang
            prgang = 0

    elif prg_neg_ang != 0:
        prgang = prgpseudo + prg_neg_ang
        prgpseudo = 0
        prg_neg_ang = 0
    a = (self.apg + self.prg)/2
    e = (self.apg/a) - 1
    return a , e ,apgang, prgang

def line(a, b):
    xa, ya = a
    xb, yb = b
    if xa != xb and ya!= yb:
        m = (ya-yb)/(xa-xb)

        y0 = ya- m*xa
        x0 = -y0/m

        return x0, y0
    elif xa == xb:
        return xa, float('inf')
    elif ya == yb:
        return float('inf'), ya

earth = body(0, 0, 0, 15, GREEN, 5.972*(10**24), 6371000)
earth.center = True

moon = body(-1 * body.RL, 0,0, 8, WHITE, 7.34767309*(10**22), 1737400 )
moon.yvel = 1027.778

debris = body(-1*body.MO, 0,10000000, 5, RED, 0.0113, 0.001)
debris.yvel = 3938.88

debris.is_debris = True
apg0 = prg0 = math.sqrt(debris.x**2 + debris.y**2 + debris.z**2)
apg0_x = prg0_x = debris.x
apg0_y = prg0_y = debris.y
apg0_z = prg0_z = debris.z

time_elapsed =0
bodies = [earth, moon, debris]
e_tot = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
tstamp_tot = []
def main():
    run = True
    clock = pygame.time.Clock()

    while run:
        global time_elapsed, xn, yn, apgangle, prgangle, apgpseudo, prgpseudo
        clock.tick(60)
        millis = clock.get_time()
        time_elapsed += debris.TIMESTEP/millis

        time_elapsed = round(time_elapsed, 2)
        WIN.fill((0,0,0))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 4:
                    body.px+=5
                elif event.button == 5:
                    body.px-=5
        en = 0
        for body in bodies:
            if body == debris:
                continue
            else:
                en += debris.energy(body)

        for body in bodies:
            if not body.colided: body.update_position(bodies)
            body.draw(WIN)
        a, e, apgng, prgng = elements(debris)
        a = round(a, 3)

        if apg_neg_ang == 0:
            apgangle = apgangle+ apgng
        else:
            apgpseudo+= apgng
        if prg_neg_ang == 0:
            prgangle = prgangle+ prgng
        else:
            prgpseudo+= prgng
        apg_angles.append(apgangle)
        prg_angles.append(prgangle)

        e_tot[0].append(e)
        tstamp_tot.append(time_elapsed*20.16)
        e = round(e, 3)

        xan, yan = anode
        xdn, ydn = dnode
        xn, yn = line(anode, dnode)
        long = math.atan2(xn, yn)
        long2 = math.atan2(yn, xn)
        x_prime = (yn - debris.y) * math.tan(long)
        plane = math.cos(long) * (debris.x-x_prime)
        if plane!= 0:
            i_rn = math.atan(abs(debris.z)/ abs(plane))

        adisplay = font.render(str(a), 1, WHITE)
        edisplay = font.render(str(e), 1, WHITE)
        idisplay = font.render(str(i_rn), 1, WHITE)
        longdisplay = font.render(str(long2), 1, WHITE)
        endisplay = font.render(str(en), 1, WHITE)
        tdisplay = font.render(str(time_elapsed*20.16), 1, WHITE)

        aeq = font.render("a(m) = ", 1, WHITE)
        eeq = font.render("e = ", 1, WHITE)
        ieq = font.render("i(rad) = ", 1,  WHITE)
        leq = font.render('\u03A9' + "(rad) = ", 1, WHITE)
        eneq = font.render("E(J) = ", 1, WHITE)
        teq = font.render("t(s) = ", 1, WHITE)

        WIN.blit(aeq , (10, 10))
        WIN.blit(eeq, (10, 30))
        WIN.blit(ieq, (10, 50))
        WIN.blit(leq, (10, 70))
        #WIN.blit(eneq, (10, 90))
        WIN.blit(teq, (10, 90))
        WIN.blit(adisplay, (50, 10))
        WIN.blit(edisplay, (30, 30))
        WIN.blit(idisplay, (52, 50))
        WIN.blit(longdisplay, (60 ,70))
        #WIN.blit(endisplay, (50, 90))
        WIN.blit(tdisplay, (45, 90))

        if top == 0:
            #print(anode)
            #print(dnode)
            #print()
            pygame.draw.line(WIN, PINK, toScale(xan, yan, debris), toScale(xdn, ydn, debris), 1)
            pygame.draw.line(WIN, WHITE, (WIDTH/2, HEIGHT/2), toScale(apg_x, apg_y, debris) , 1)
            pygame.draw.line(WIN,BLUE, (WIDTH/2, HEIGHT/2), toScale(prg_x, prg_y, debris) , 1)
        elif top == 1:
            #print(anode)
            #print(dnode)
            #print()
            pygame.draw.line(WIN, PINK, toScale(xan, 0, debris), toScale(xdn, 0 ,debris), 1)
            pygame.draw.line(WIN, WHITE, (WIDTH/2, HEIGHT/2), toScale(apg_x, apg_z, debris) , 1)
            pygame.draw.line(WIN,BLUE, (WIDTH/2, HEIGHT/2), toScale(prg_x, prg_z, debris) , 1)
        #print(debris.z)
        #print(" ")
        pygame.display.update()
    pygame.quit()
main()

#sub = plt.subplot()
#fig, ax = plt.subplots()
plt.plot(tstamp_tot, apg_angles, label = "apogee")
plt.plot(tstamp_tot, prg_angles, label = "perigee")
plt.legend()
plt.xlabel("Timestamp (s)")
plt.ylabel("Shift angle (rad)")
plt.show()

delta_v = []
delta_e = [0]
def deltae():
    for i in range(20):
        run = True
        global time_elapsed, xn, yn
        time_elapsed = 0
        delta_v.append(100*(i))
        clock = pygame.time.Clock()

        while run:

            clock.tick(60)
            millis = clock.get_time()
            time_elapsed += debris.TIMESTEP/millis
            if time_elapsed * 20.16 > 30000:
                run = False
            WIN.fill((0,0,0))
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    run = False
            for body in bodies:
                if not body.colided: body.update_position(bodies)
            a, e = elements(debris)
            a = round(a, 3)

            e_tot[i].append(e)

            e = round(e, 3)
            progr = font.render("Tinkering... Progress so far: ", 1, WHITE)
            WIN.blit(progr , (10, 10))
            actualprogr = font.render(str(int(30000 - time_elapsed*20.16)), 1, WHITE)
            WIN.blit(actualprogr, (30, 30))
            iteration = font.render(str(i), 1, WHITE)
            WIN.blit(iteration, (30, 50))
            pygame.display.update()
    for i in range(1, 20):
        delta_e.append(abs(max(e_tot[0]) - max(e_tot[i])))
#deltae()

#figure, ax2 = plt.subplots()

#ax2.plot(delta_v, delta_e)

#plt.show()


from constants import PLAYER_ID, SPACE

def get_uint_input(msg, invalid_msg, min_int=1, max_int=4):
    while True:
        str_input = input(msg).strip()

        if str_input.isdigit():
            int_input = int(str_input)
            if min_int <= int_input <= max_int:
                return int_input

        print(invalid_msg)

def extend_int_to_string(i):
    assert 0 <= i < 100

    str_of_int = f"{i}"
    if i < 10:
        str_of_int = f"0{i}"

    return str_of_int

def gen_player_id():
    global PLAYER_ID
    PLAYER_ID += 1
    return PLAYER_ID

def format_string(string, length):
    assert 0 < length
    if len(string) < length:
        return string + SPACE * (length - len(string))
    return string[:length]

def is_string_plus_number(string, user_input):
    if SPACE not in user_input:
        return (False, None)
    split_input = user_input.split(SPACE)
    if len(split_input) != 2:
        return (False, None)
    if split_input[0] != string:
        return (False, None)
    if not split_input[1].isnumeric():
        return (False, None)
    return (True, int(split_input[1]))


class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        nums.sort()
        print(nums)
        arr=[]
        for i in range(len(nums)):

            for j in range(i+1,len(nums)):
                start=j+1
                end=len(nums)-1
                while start<end:

                    if nums[i]+nums[j]+nums[start]+nums[end]==target:
                        arr.append([nums[i],nums[j],nums[start],nums[end]])
                        start+=1
                        end-=1
                    elif nums[i]+nums[j]+nums[start]+nums[end]>target:
                        end-=1
                    else:
                        start+=1
        newarr=[]
        for i in arr:
            if i not in newarr:
                newarr.append(i)
        return newarr


"""Iterators for few-shot episode.

Author: Mengye Ren (mren@cs.toronto.edu)
"""
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import numpy as np
import tensorflow as tf

from fewshot.data.iterators.iterator import Iterator
from fewshot.data.registry import RegisterIterator

@RegisterIterator('episode')
class EpisodeIterator(Iterator):
  """Generates lifelong episodes."""

  def __init__(self,
               dataset,
               sampler,
               batch_size,
               nclasses,
               nquery,
               preprocessor=None,
               episode_processor=None,
               fix_unknown=False,
               maxlen=-1,
               prefetch=True,
               **kwargs):
    """Creates a lifelong learning data iterator.

    Args:
      dataset: A dataset object. See `fewshot/data/dataset.py`.
      sampler: A sampler object. See `fewshot/data/sampler.py`.
      batch_size: Number of episodes together.
      nclasses: Total number of new classes.
      nquery: Query period, number of query images per class.
      fix_unknown: Whether the unknown token is k+1 or fixed at K+1.
      maxlen: Maximum length of the sequence.
      preprocessor: Image preprocessor.
    """
    self._dataset = dataset
    self._sampler = sampler
    sampler.set_dataset(dataset)
    self._nclasses = nclasses
    self._batch_size = batch_size
    self._nclasses = nclasses
    self._nquery = nquery
    assert batch_size >= 1
    self._preprocessor = preprocessor
    self._episode_processor = episode_processor
    self._kwargs = kwargs
    self._maxlen = maxlen
    assert maxlen > 0
    self._fix_unknown = fix_unknown
    self._prefetch = prefetch
    self._tf_dataset = self.get_dataset()
    self._tf_dataset_iter = iter(self._tf_dataset)

  def process_one(self, collection):
    """Process one episode.

    Args:
      Collection dictionary that contains the following keys:
        support: np.ndarray. Image ID in the support set.
        query: np.ndarray. Image ID in the query set.
    """
    s, q = collection['support'], collection['query']
    del collection['support']
    del collection['query']
    dataset = self.dataset
    nclasses = self.nclasses
    img_s = dataset.get_images(s)
    lbl_s = collection['support_label']
    del collection['support_label']
    T = self.maxlen
    lbl_map, lbl_s = tf.unique(lbl_s)

    # np.unique returns a sorted lbl_map, but not according to appear order.
    # tf.unique returns according to appear order.
    # lbl_map, lbl_s = np.unique(lbl_s, return_index=True)
    # print('before', lbl_s2, lbl_map2)
    # print('after', lbl_s, lbl_map)
    # assert False

    def query_tf(x):
      x = tf.expand_dims(x, 1)  # [T, 1]
      x_eq = tf.cast(tf.equal(x, lbl_map), tf.float32)  # [T, N]
      x_valid = tf.reduce_sum(x_eq, [1])  # [T]

      # Everything that has not been found -> fixed unknown.
      # This means it's a distractor.
      x = tf.cast(tf.argmax(x_eq, axis=1), tf.float32)
      x = x_valid * x + (1 - x_valid) * nclasses
      x = tf.cast(x, tf.int32)
      return x

    def query_np(x):
      x = np.expand_dims(x, 1)  # [T, 1]
      x_eq = np.equal(x, lbl_map).astype(np.float32)  # [T, N]
      x_valid = np.sum(x_eq, axis=1)  # [T]

      # Everything that has not been found -> fixed unknown.
      # This means it's a distractor.
      x = np.argmax(x_eq, axis=1).astype(np.float32)
      x = x_valid * x + (1 - x_valid) * nclasses
      x = x.astype(np.int32)
      return x

    # Generates the groundtruth.
    if self._fix_unknown:
      # Make the first appearing image have the fixed UNK class.
      lbl_s_np = lbl_s.numpy()
      lbl_s_gt = np.zeros([len(lbl_s_np)], dtype=np.int32)
      cummax = np.maximum.accumulate(lbl_s_np)
      lbl_s_gt[0] = nclasses
      cond = lbl_s_np[1:] > cummax[:-1]
      lbl_s_gt[1:] = np.where(cond, nclasses, lbl_s_np[1:])
    else:
      lbl_s_gt = lbl_s

    if self.nquery > 0:
      img_q = dataset.get_images(q)
      lbl_q = collection['query_label']
      del collection['query_label']
      # lbl_q = dataset.get_labels(q)
      lbl_q = query_tf(lbl_q)
    else:
      img_q = None
      lbl_q = None
    epi = {
        'x_s': self.pad_x(img_s, T),
        'y_s': self.pad_y(lbl_s, T),
        'y_gt': self.pad_y(lbl_s_gt, T),
        'y_dis': tf.zeros([T], dtype=lbl_s.dtype),
        'y_full': self.pad_y(lbl_s, T),
        'flag_s': self.get_flag(lbl_s, T)
    }
    if self.nquery > 0:
      T2 = self.nquery * self.nclasses
      epi['x_q'] = self.pad_x(img_q, T2)
      epi['y_q'] = self.pad_y(lbl_q, T2)
      epi['flag_q'] = self.get_flag(lbl_q, T2)
      if 'stage_id_q' in collection:
        epi['stage_id_q'] = self.pad_y(collection['stage_id_q'], T2)
        del collection['stage_id_q']

    # For remaining additional info.
    for k in collection:
      epi[k] = self.pad_y(collection[k], T)

    if self.episode_processor is not None:
      epi = self.episode_processor(epi)
    return epi

  def _next(self):
    """Next example."""
    collection = self.sampler.sample_collection(self.nclasses, self.nquery,
                                                **self.kwargs)
    return self.process_one(collection)

  def pad_x(self, x, maxlen):
    """Pad image sequence."""
    T = x.shape[0]
    return np.pad(x, [[0, maxlen - T], [0, 0], [0, 0], [0, 0]], mode='reflect')

  def pad_y(self, y, maxlen):
    """Pad label sequence."""
    T = y.shape[0]
    return np.pad(y, [0, maxlen - T], mode='constant', constant_values=0)

  def get_flag(self, y, maxlen):
    """Get valid flag."""
    return (np.arange(maxlen) < y.shape[0]).astype(np.int32)

  def __iter__(self):
    return self._tf_dataset_iter

  def get_generator(self):
    """Gets generator function, for tensorflow Dataset object."""
    while True:
      yield self._next()

  def get_dataset(self):
    """Gets TensorFlow Dataset object."""
    dummy = self._next()
    self.sampler.reset()
    dtype_dict = dict([(k, dummy[k].dtype) for k in dummy])
    shape_dict = dict([(k, tf.shape(dummy[k])) for k in dummy])
    ds = tf.data.Dataset.from_generator(self.get_generator, dtype_dict,
                                        shape_dict)

    def preprocess(data):
      data['x_s'] = self.preprocessor(data['x_s'])
      if self.nquery > 0:
        data['x_q'] = self.preprocessor(data['x_q'])
      return data

    ds = ds.map(preprocess)
    ds = ds.batch(self.batch_size)
    if self._prefetch:
      ds = ds.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
    return ds

  def reset(self):
    """Resets sampler."""
    self.sampler.reset()

  @property
  def kwargs(self):
    """Additional parameters for the sampler."""
    return self._kwargs

  @property
  def preprocessor(self):
    """Image preprocessor."""
    return self._preprocessor

  @property
  def episode_processor(self):
    """Episode processor."""
    return self._episode_processor

  @property
  def sampler(self):
    """Episode sampler."""
    return self._sampler

  @property
  def dataset(self):
    """Dataset source."""
    return self._dataset

  @property
  def nclasses(self):
    """Number of classes per episode."""
    return self._nclasses

  @property
  def nquery(self):
    """Number of query examples per class per episode."""
    return self._nquery

  @property
  def batch_size(self):
    """Number of episodes."""
    return self._batch_size

  @property
  def maxlen(self):
    """Max length of the sequence."""
    return self._maxlen

  @property
  def tf_dataset(self):
    """TF dataset API."""
    return self._tf_dataset


"""
NLP Pipeline
============
The following example takes a raw extract of norwegian texts, removes stopwords and lemmatizes prior to analysing the
distribution of the words in the text.
"""

import matplotlib.pyplot as plt
plt.close('all') # very important for read the docs to avoid it crashing due to memory

from enlp.processing.stdtools import get_stopwords, tokenise
from enlp.pipeline import NLPPipeline
from enlp.visualisation.freq_distribution import wordcloud_plot

import spacy

###############################################################################
# Load Spacy's Norwegian language model and the example text
langmodel = spacy.load('nb_dep_ud_sm')
with open("example_data/no_den_stygge_andungen.txt", "r") as file:
    text = file.read()
text = text.replace('\n', ' ')

###############################################################################
# Get a list of stopwords to be removed from the text

# Get stopwords
all_stopwords, stopwords_nb, stopwords_en = get_stopwords()

###############################################################################
# Using NLP pipeline class to create a processing workflow. The pipeline shall involve:
# - remove punctuation
# - remove stopwords
# - stem remaining words

# Initialise object
processed_text = NLPPipeline(langmodel, text)

# Run processing as a pipeline
processed_text.rm_punctuation().rm_stopwords(stopwords=all_stopwords).nltk_stem_no()

#############################################################################
# Compare text strings of firs 80 characters of the original and processed.

print ('Original: ', text[:80], '...')
print ('Processed: ', processed_text.text[:80], '...')

#############################################################################
# Wordcloud comparison between most common words
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))
wordcloud_plot(tokenise(langmodel,text), ax=ax1)
wordcloud_plot(processed_text.tokenise().tokens, ax=ax2)
plt.tight_layout()


import app_constant as constant

from todo_service import Todo_Service
from todo_update import Todo_Update
import todo

class Todo_App_Update:

    def __init__(self, todo_service: Todo_Service):
        self.todo_service = todo_service

    def menu(self):
        print("\n")
        print('---------------App: Update Todo--------------------------')
        print("To Update type: " + constant.to_update + " and follow the prompt")
        print("To get another list type: " + constant.to_next_list)
        print("To get previous list type: " + constant.to_previous_list)
        print("To Go Back To Main Menu: " + constant.to_exit)
        # print("\n")

        self.todo_service.get_todo_list()

    def process(self):
        self.menu()

        input_text = ""
        while input_text != constant.to_exit:
            input_text = input("What would you like to do? ")
            if input_text == constant.to_update:
                self.update_process()
            elif input_text == constant.to_next_list:
                self.todo_service.balance_history(self.todo_service.last_id)
            elif input_text == constant.to_previous_list:
                self.todo_service.last_last_id()
            elif input_text == constant.to_exit:
                pass
            else:
                print("Not a valid entry")

            if input_text != constant.to_exit:
                self.menu()

    def update_process(self):
        print('---------------App: Updating Todo--------------------------')
        input_text = "start"
        while input_text != 'e':
            print(
                "Please enter a number from above list, next to a todo.\nTo Go Back To Menu: ")
            input_text = input(": ")

            if input_text == 'e':
                break

            try:
                selected_id = int(input_text)
                if type(selected_id) is int:
                    if str(selected_id) in self.todo_service.selected_id:
                        todo = self.todo_service.get_todo(selected_id)
                        update = Todo_Update(todo, self.todo_service)
                        update.set_todo(todo)
                        update.process()
                    else:
                        print('please select a number from above list\n')
            except Exception as e:
                print("Error: " + str(e))


import unittest
from test_stu.pythontest.fuction.calc import Calc

class TestCal(unittest.TestCase):
    def test_add1(self):
        self.calc = Calc()
        result=self.calc.add(1,2)
        print(result)
        self.assertEqual(3,result)


"""empty message

Revision ID: 97ce805e5e4d
Revises: dcecaaf2ef4f
Create Date: 2020-11-09 19:35:15.584519

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '97ce805e5e4d'
down_revision = 'dcecaaf2ef4f'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('payments', sa.Column('phone_number', sa.String(length=12), nullable=True))
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('payments', 'phone_number')
    # ### end Alembic commands ###


from unicodedata import category
from app import app

import os
import cv2 as cv
import numpy as np
from werkzeug.utils import secure_filename
from flask import request, render_template, url_for, jsonify, redirect, session

from ..model.UserDB import UserDB
from .SystemController import SystemController

ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'tif'}

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def rgb_to_gray(input_path, file_name):
    # Processing img uploaded
    img = cv.imread(input_path)         # Read image
    if img is None:
        print("Không tìm thấy file ảnh")

    # Processing img
    img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

    # Create link img render
    fname = file_name.split(".")[0]
    output_path = "./app/static/img_Render/" + fname + "_RgbToGray.jpg"
    cv.imwrite(output_path, img)
    send_path = "../static/img_Render/" + fname + "_RgbToGray.jpg"

    cv.destroyAllWindows()
    return send_path

def get_images_by_class(image_class):
    objDb = UserDB()
    sql = "SELECT * FROM db_cbir.tb_image WHERE Image_Class = %s;"
    val = [image_class]
    res = objDb.query_get(sql, val)
    return res

def get_images_path_per_page(start, end):
    objDb = UserDB()
    sql = "SELECT * FROM db_cbir.tb_image LIMIT %s, %s;"
    val = (start, end)
    res = objDb.query_get(sql, val)
    return res

def count_total_images():
    objDb = UserDB()
    sql = "SELECT COUNT(Image_Id) FROM db_cbir.tb_image;"
    val = ()
    res = objDb.query_get(sql, val)
    return res

@app.route('/gray', methods=['POST'])
def gray():
    file = request.files['file']
    if file and allowed_file(file.filename):
        fileName = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], fileName))

        file_path = "./app/static/img_Uploads/" + str(fileName)
        res = rgb_to_gray(file_path, fileName)
        res = str(res)
        return jsonify(data=res)

@app.route("/images/category/<string:image_class>", endpoint="show_image_category")
@SystemController.check_acl
def show_image_category(image_class):
    # if logged in before
    if 'auth' in session:
        if session['auth']['Role_Name'] == 'admin':
            return redirect(f"/admin/images/category/{image_class}")
        elif session['auth']['Role_Name'] == 'user':
            return redirect(f"/user/images/category/{image_class}")
    images = get_images_by_class(image_class)
    db_images = []
    for info in images:
        image_class = info[1]
        image_name = info[2]
        image_info = {
            "class": image_class,
            "name": image_name
        }
        db_images.append(image_info)
    return render_template('unlogedview/unloged_images_category.html', db_images=db_images, category=image_class)

@app.route("/page/<int:page_index>", endpoint="show_image_page")
@SystemController.check_acl
def show_image_page(page_index):
    # if logged in before
    if 'auth' in session:
        if session['auth']['Role_Name'] == 'admin':
            return redirect(f"/admin/home/page/{page_index}")
        elif session['auth']['Role_Name'] == 'user':
            return redirect(f"/user/home/page/{page_index}")
    if page_index == 1:
        return redirect("/")
    no_images_per_page = 200
    total_no_images = count_total_images()[0][0]
    total_no_pages = int(np.ceil(total_no_images / no_images_per_page))
    current_page = page_index

    if current_page > total_no_pages:
        return redirect(f"/page/{total_no_pages}")

    start = (current_page - 1) * no_images_per_page
    images = get_images_path_per_page(start, no_images_per_page)
    db_images = []
    for info in images:
        image_class = info[1]
        image_name = info[2]
        image_info = {
            "class": image_class,
            "name": image_name
        }
        db_images.append(image_info)
    return render_template('unlogedview/unloged_home.html', db_images=db_images)

@app.route("/profile", endpoint="profile")
def profile():
    if 'auth' in session:
        if session['auth']['Role_Name'] == 'admin':
            return redirect("/admin/profile")
        elif session['auth']['Role_Name'] == 'user':
            return redirect("/user/profile")
    return render_template('exceptionview/404.html')

@app.route("/about-us", endpoint="aboutus")
@SystemController.check_acl
def aboutus():
    if 'auth' in session:
        if session['auth']['Role_Name'] == 'admin':
            return redirect("/admin/about-us")
        elif session['auth']['Role_Name'] == 'user':
            return redirect("/user/about-us")
    return render_template('unlogedview/unloged_aboutus.html')

@app.route("/favicon.ico")
def favicon():
    return "", 200

@app.route("/")
@SystemController.check_acl
def home():
    # if logged in before
    if 'auth' in session:
        if session['auth']['Role_Name'] == 'admin':
            return redirect("/admin/home")
        elif session['auth']['Role_Name'] == 'user':
            return redirect("/user/home")
    images = get_images_path_per_page(0, 200)
    db_images = []
    for info in images:
        image_class = info[1]
        image_name = info[2]
        image_info = {
            "class": image_class,
            "name": image_name
        }
        db_images.append(image_info)
    return render_template('unlogedview/unloged_home.html', db_images=db_images)


from __future__ import unicode_literals
from __future__ import absolute_import

__version__ = '0.1'

#<----------------------------------------------------------------------------->

import json

try:
    from urllib.parse import urlencode, unquote
except ImportError:
    from urllib import urlencode, unquote

try:
    from urllib.request import urlopen, Request
except ImportError:
    from urllib2 import urlopen, Request

try:
    from urllib.parse import urlunparse
except ImportError:
    from urlparse import urlunparse

#<----------------------------------------------------------------------------->

MAPQUEST_API_URLS = {
    'netloc': {
        'licensed': 'www.mapquestapi.com',
        'open': 'open.mapquestapi.com',
    },
    'path': {
        'geocode': '/geocoding/v1/address',
        'reverse_geocode': '/geocoding/v1/reverse',
        'batch_geocode': '/geocoding/v1/batch',
    },
}

#<----------------------------------------------------------------------------->

class MapQuest(object):
    """
    Toplevel class for interacting with the MapQuest developer API.

    :param str key: MapQuest developer API key.
    :param str data: Specifies which MapQuest data to use. Options are either 'open' or 'licensed'.
    :param bool ssl: Specifies whether to use Secure Socket Layer (SSL) when fetching data from the MapQuest API (i.e. http vs https).
    :param int timeout: Specifies how long the http request should wait (in seconds) for a response before timing out.
    :param dict headers: Allows for the modification of the http request headers (i.e. specify a custom User-Agent).

    Usage::

        from mapquest import MapQuest
        mq = MapQuest('mapquest_api_key')

    Methods:
    """

    def __init__(self, key, data='open', ssl=False, timeout=60, headers={}):
        super(MapQuest, self).__init__()

        # mapquest api key
        self.key = unquote(key) if '%' in key else key

        # mapquest data, options [open, licensed]
        self.data = 'licensed' if data == 'licensed' else 'open'

        # optional request parameters
        self.timeout = timeout
        self.headers = headers
        self.ssl = ssl

    #<------------------------------------------------------------------------->

    def _fetch(self, type, query):

        # build the url attributes
        scheme = 'https' if self.ssl else 'http'
        netloc = MAPQUEST_API_URLS['netloc'][self.data]
        path = MAPQUEST_API_URLS['path'][type]

        # convert query dictionary to a url encoded string
        query = urlencode(query)

        # build the url
        url = urlunparse((scheme, netloc, path, '', query, ''))

        # build the request object
        request = Request(url, headers=self.headers)

        # fetch the response
        response = urlopen(request, timeout=self.timeout)

        return response

    #<------------------------------------------------------------------------->

    def _geocode(self, type, location, limit=-1, thumbnails=True, bounding_box=[]):

        # build the json query
        json_query = {}

        # build the options dictionary
        options = {}

        if limit != -1:
            options['maxResults'] = limit

        if not thumbnails:
            options['thumbMaps'] = thumbnails

        if bounding_box:

            if isinstance(bounding_box, str):
                bounding_box = [float(i) for i in bounding_box.split(',')]

            bbox = {
                'ul': {
                    'lat': bounding_box[0],
                    'lng': bounding_box[1],
                },
                'lr': {
                    'lat': bounding_box[2],
                    'lng': bounding_box[3],
                }
            }

            options['boundingBox'] = bbox

        # add the options dictionary to the json query if present
        if options:
            json_query['options'] = options

        # build the location dictionary
        if type == 'reverse_geocode':

            if isinstance(location, str):
                location = [float(i) for i in location.split(',')]

            loc = {
                'latLng': {
                    'lat': location[0],
                    'lng': location[1],
                }
            }

            json_query['location'] = loc

        elif type == 'batch_geocode':
            locations = [{'street': loc} if isinstance(loc, str) else loc for loc in location]
            json_query['locations'] = locations

        else:

            if isinstance(location, str):
                location = {'street': location}

            json_query['location'] = location

        # build the key, value pairs for the query
        query = (
            ('key', self.key),
            ('inFormat', 'json'),
            ('outFormat', 'json'),
            ('json', json.dumps(json_query)),
        )

        # fetch the results from mapquest and convert them to a python dictionary
        response = self._fetch(type, query)
        response = json.loads(response.read().decode('utf-8'))

        return response

    #<------------------------------------------------------------------------->

    def geocode(self, address, limit=-1, thumbnails=True, bounding_box=[]):
        """
        Returns geocode data for a specified address. Useful for finding the relative latitude and longitude of an address.

        :param address: The address the geocoder should look up.
        :type address: str or dict
        :param int limit: Limits the number of results returned by the geocoder service. Specify -1 for unlimited results.
        :param bool thumbnails: Specifies whether the geocoder service should return a URL to a map thumbnail image in the results for the location being geocoded.
        :param bounding_box: Moves any locations within the bounding box to the top of the results list when ambiguous results are returned (i.e. the provided address coresponds to multiple locations). See Bounding Boxes for more info.
        :type bounding_box: list or tuple

        The **address** may be specified as either a string or dictionary as follows::

            address = '1555 Blake St,Denver,CO,80202'

            address = {
                'street': '1555 Blake St',
                'city': 'Denver',
                'state': 'CO',
                'postalCode': '80202'
            }

        :returns: :ref:`MapQuest Geocode Response <responses-label>`
        """

        return self._geocode('geocode', address, limit, thumbnails, bounding_box)

    #<------------------------------------------------------------------------->

    def reverse_geocode(self, latlng, limit=-1, thumbnails=True, bounding_box=[]):
        """
        Returns geocode data for a specified latitude and longitude. Useful for finding the relative address of a latitude and longitude.

        :param latlng: The latitude and longitude the geocoder should look up.
        :type latlng: str, list, or tuple
        :param int limit: Limits the number of results returned by the geocoder service. Specify -1 for unlimited results.
        :param bool thumbnails: Specifies whether the geocoder service should return a URL to a map thumbnail image in the results for the location being geocoded.
        :param bounding_box: Moves any locations within the bounding box to the top of the results list when ambiguous results are returned (i.e. the provided address coresponds to multiple locations). See Bounding Boxes for more info.
        :type bounding_box: list or tuple

        The **latlng** may be specified as either a string or list as follows::

            latlng = '39.7505568,-104.9996268'

            latlng = [39.7505568,-104.9996268]

        :returns: :ref:`MapQuest Geocode Response <responses-label>`
        """

        return self._geocode('reverse_geocode', latlng, limit, thumbnails, bounding_box)

    #<------------------------------------------------------------------------->

    def batch_geocode(self, locations, limit=-1, thumbnails=True, bounding_box=[]):
        """
        Returns the geocode data for multiple addresses. Useful for finding the relative latitude and longitude of multiple addresses.

        :param locations: A list of addresses the geocoder should look up.
        :type locations: list or tuple
        :param int limit: Limits the number of results returned by the geocoder service per address. Specify -1 for unlimited results.
        :param bool thumbnails: Specifies whether the geocoder service should return a URL to a map thumbnail image in the results for the location being geocoded.
        :param bounding_box: Moves any locations within the bounding box to the top of the results list. See Bounding Boxes for more info.
        :type bounding_box: list or tuple

        **Locations** may be specified as either a list of strings or a list of dictionaries as follows::

            locations = [
                '1555 Blake St,Denver,CO,80202',
                '2590 Pearl St,Boulder,CO,80302'
            ]

            locations = [
                {
                    'street': '1555 Blake St',
                    'city': 'Denver',
                    'state': 'CO',
                    'postalCode': '80202'
                },
                {
                    'street': '2590 Pearl St',
                    'city': 'Boulder',
                    'state': 'CO',
                    'postalCode': '80302'
                }
            ]

        :returns: :ref:`MapQuest Geocode Response <responses-label>`
        """

        return self._geocode('batch_geocode', locations, limit, thumbnails, bounding_box)


N = int(input())

e = []  # 파일의 확장자를 담을 리스트 생성
dict = {}

for _ in range(N):
    file = input().split('.')  # 알바펫 소문자와 .으로 구성된 파일명 입력 받는다.
    # print(file[1]) ==> txt ; 파일명의 [1] 인덱스는 확장자 의미
    e.append(file[1])  # file[1]를 확장자 리스트 e에 추가

for i in e:
    if dict.get(i):  # 딕셔너리의 key를 (e를 순회하는) i로 불러올 수 있으면
        dict[i] += 1  # 확장자 파일의 개수에 1을 더한다.
    else:
        dict[i] = 1  # 확장자 파일의 개수는 1이다.

    # print(dict[i]) ==> 1

dict = sorted(dict.items())  # 키 값(확장자 이름) 기준으로 정렬

# print(dict) [('txt', 1)]

for i, j in dict:
    print(i, j)  # 확장자 이름과 확장자 파일의 개수 출력


import torch.nn as nn

class SRCNN(nn.Module):

    def __init__(self):
        super(SRCNN, self).__init__()
        self.conv1 = nn.Conv2d(3, 64, kernel_size=9, stride=1,padding=9//2)
        self.conv2 = nn.Conv2d(64, 32, kernel_size=1, stride=1)
        self.conv3 = nn.Conv2d(32, 3, kernel_size=5, stride=1,padding=5//2)

    def forward(self, data):
        out = self.conv1(data)
        out = self.conv2(out)
        out = self.conv3(out)
        return out


# -*- coding: utf-8 -*-
#!/usr/local/bin/python
from utils import *

ATTRIBUTE_Type  = 'Type'
TYPE_PERSON     = "1"
TYPE_CAR        = "2"
TYPE_FACE       = "3"
TYPE_BIKE       = "4"
#######################################################
# 车辆
# 需要映射项
CAR_ATTRIBUTE_Angle                 = 'Angle'
CAR_ATTRIBUTE_VehicleClass          = 'VehicleClass'
CAR_ATTRIBUTE_HasPlate              = 'HasPlate'
CAR_ATTRIBUTE_PlateClass            = 'PlateClass'
CAR_ATTRIBUTE_PlateColor            = 'PlateColor'
CAR_ATTRIBUTE_PlateNeatness         = 'PlateNeatness'
CAR_ATTRIBUTE_Sunvisor              = 'Sunvisor'
CAR_ATTRIBUTE_Paper                 = 'Paper'
CAR_ATTRIBUTE_Decoration            = 'Decoration'
CAR_ATTRIBUTE_Drop                  = 'Drop'
CAR_ATTRIBUTE_HasCall               = 'HasCall'
CAR_ATTRIBUTE_HasSkylight           = 'HasSkylight'
CAR_ATTRIBUTE_HasBaggage            = 'HasBaggage'
CAR_ATTRIBUTE_HasAerial             = 'HasAerial'
CAR_ATTRIBUTE_HasCrash              = 'HasCrash'
CAR_ATTRIBUTE_HasDanger             = 'HasDanger'
CAR_ATTRIBUTE_HighwayTollVehicles   = 'HighwayTollVehicles'
# 透传项
CAR_ATTRIBUTE_VehicleBrand          = 'VehicleBrand'
CAR_ATTRIBUTE_PlateNo               = 'PlateNo'
CAR_ATTRIBUTE_VehicleColorNums      = 'VehicleColorNums'
CAR_ATTRIBUTE_Tag                   = 'Tag'
# 坐标矩形框项（需特殊处理）
CAR_ATTRIBUTE_ObjectBoundingBox     = 'ObjectBoundingBox'
# 颜色数组（需特殊处理）
CAR_ATTRIBUTE_VehicleColor          = 'VehicleColor'
# 安全带项（需特殊处理）
CAR_ATTRIBUTE_SafetyBelt            = 'SafetyBelt'
CAR_ATTRIBUTE_MainDriver            = 'MainDriver'
CAR_ATTRIBUTE_CoDriver              = 'CoDriver'
#######################################################
# 骑行
# 需要映射项
BIKE_ATTRIBUTE_BikeClass = "BikeClass"
BIKE_ATTRIBUTE_Gender = "Gender"
BIKE_ATTRIBUTE_Age = "Age"
BIKE_ATTRIBUTE_Angle = "Angle"
BIKE_ATTRIBUTE_HasBackpack = "HasBackpack"
BIKE_ATTRIBUTE_HasGlasses = "HasGlasses"
BIKE_ATTRIBUTE_HasCarrybag = "HasCarrybag"
BIKE_ATTRIBUTE_HasUmbrella = "HasUmbrella"
BIKE_ATTRIBUTE_HasPassenger = "HasPassenger"
BIKE_ATTRIBUTE_CoatLength = "CoatLength"
BIKE_ATTRIBUTE_SocialAttribute = "SocialAttribute"
BIKE_ATTRIBUTE_Enterprise = "Enterprise"

BIKE_ATTRIBUTE_HasPlate = "HasPlate"
BIKE_ATTRIBUTE_HasHelmet = "HasHelmet"
BIKE_ATTRIBUTE_HelmetColor = "HelmetColor"
BIKE_ATTRIBUTE_HasMask = "HasMask"
BIKE_ATTRIBUTE_CoatTexture = "CoatTexture"
# 透传项
BIKE_ATTRIBUTE_CoatColorNums          = 'CoatColorNums'
# 坐标矩形框项（需特殊处理）
BIKE_ATTRIBUTE_ObjectBoundingBox      = 'ObjectBoundingBox'
BIKE_ATTRIBUTE_FaceBoundingBox        = 'FaceBoundingBox'
# 颜色数组（需特殊处理）
BIKE_ATTRIBUTE_CoatColor              = 'CoatColor'
#######################################################
# 行人
# 需要映射项
PERSON_ATTRIBUTE_Gender = "Gender"
PERSON_ATTRIBUTE_Age = "Age"
PERSON_ATTRIBUTE_Angle = "Angle"
PERSON_ATTRIBUTE_HasBackpack = "HasBackpack"
PERSON_ATTRIBUTE_HasGlasses = "HasGlasses"
PERSON_ATTRIBUTE_HasCarrybag = "HasCarrybag"
PERSON_ATTRIBUTE_HasUmbrella = "HasUmbrella"
PERSON_ATTRIBUTE_CoatLength = "CoatLength"
PERSON_ATTRIBUTE_TrousersLength = "TrousersLength"
PERSON_ATTRIBUTE_HasHat = "HasHat"
PERSON_ATTRIBUTE_HasMask = "HasMask"
PERSON_ATTRIBUTE_HairStyle = "HairStyle"
PERSON_ATTRIBUTE_CoatTexture = "CoatTexture"
PERSON_ATTRIBUTE_TrousersTexture = "TrousersTexture"
PERSON_ATTRIBUTE_HasTrolley = "HasTrolley"
PERSON_ATTRIBUTE_HasLuggage = "HasLuggage"
# 透传项
PERSON_ATTRIBUTE_LuggageColorNums       = 'LuggageColorNums'
PERSON_ATTRIBUTE_CoatColorNums          = 'CoatColorNums'
PERSON_ATTRIBUTE_TrousersColorNums      = 'TrousersColorNums'
# 坐标矩形框项（需特殊处理）
PERSON_ATTRIBUTE_ObjectBoundingBox      = 'ObjectBoundingBox'
PERSON_ATTRIBUTE_HeadBoundingBox        = 'HeadBoundingBox'
PERSON_ATTRIBUTE_UpperBoundingBox       = 'UpperBoundingBox'
PERSON_ATTRIBUTE_LowerBoundingBox       = 'LowerBoundingBox'
PERSON_ATTRIBUTE_FaceBoundingBox        = 'FaceBoundingBox'
# 颜色数组（需特殊处理）
PERSON_ATTRIBUTE_TrousersColor          = 'TrousersColor'
PERSON_ATTRIBUTE_CoatColor              = 'CoatColor'
PERSON_ATTRIBUTE_LuggageColor           = 'LuggageColor'
#######################################################
# 人脸
# 需要映射项
FACE_ATTRIBUTE_Gender = "Gender"
FACE_ATTRIBUTE_Age = "Age"
FACE_ATTRIBUTE_HasGlasses = "HasGlasses"
FACE_ATTRIBUTE_HasHat = "HasHat"
FACE_ATTRIBUTE_HasMask = "HasMask"
FACE_ATTRIBUTE_HairStyle = "HairStyle"
# 透传项
# 坐标矩形框项（需特殊处理）
FACE_ATTRIBUTE_HeadBoundingBox        = 'HeadBoundingBox'
FACE_ATTRIBUTE_FaceBoundingBox        = 'FaceBoundingBox'
# 颜色数组（需特殊处理）

ThreeStateType = {
    "0": "无",
    "1": "有",
    "-1": "未知",
}
ObjectType = {
    TYPE_FACE: "人脸",
    TYPE_BIKE: "非机动车",
    TYPE_PERSON: "行人",
    TYPE_CAR: "机动车",
}
GenderType = {
    "1": "男性",
    "2": "女性",
    "-1": "未知",
}
AgeType = {
    "4": "小朋友",
    "8": "青年",
    "16": "中年",
    "32": "老年",
    "-1": "未知",
}
AngleType = {
    "128": "正面",
    "256": "侧面",
    "512": "背面",
    "-1": "未知",
}
CoatType = {
    "1": "长袖",
    "2": "短袖",
    "-1": "未知",
}
SocialAttributeType = {
    "1": "普通",
    "2": "外卖车",
    "3": "快递车",
    "-1": "未知",
}
EnterpriseType = {
    "1": "中通",
    "2": "韵达",
    "3": "圆通",
    "4": "申通",
    "5": "中国邮政",
    "6": "顺丰",
    "7": "京东",
    "8": "百世汇通",
    "9": "美团",
    "10": "饿了么",
    "-1": "未知",
}
TrousersType = {
    "1": "长裤",
    "2": "短裤",
    "3": "裙子",
    "-1": "未知",
}
ObjectColorType = {
    "1": "黑",
    "2": "蓝",
    "3": "棕",
    "4": "绿",
    "5": "灰",
    "6": "橙",
    "7": "粉",
    "8": "紫",
    "9": "红",
    "10": "银",
    "11": "白",
    "12": "黄",
    "13": "金",
    "14": "混合色",
    "-1": "未知",
}
VehicleClassType = {
    "1":	"轿车",
    "2":	"越野车/SUV类",
    "3":	"商务车/MPV类",
    "4":	"小型货车",
    "5":	"中型货车",
    "6":	"大型货车",
    "7":	"轻客",
    "8":	"中型客车",
    "9":	"大型客车",
    "10":	"面包车",
    "11":	"皮卡",
    "12":	"罐车",
    "13":	"渣土车",
    "14":	"校车",
    "15":	"公交车",
    "16":	"车辆运输车",
    "98":	"三轮车",
    "99":	"其他（专用车）",
    "-1":	"未知",
}
PlateClassType = {
    "1": "普通蓝牌",
    "2": "普通黑牌",
    "3": "普通黄牌",
    "4": "警车车牌",
    "5": "武警车牌",
    "6": "军队车牌",
    "7": "使馆车牌",
    "8": "港澳车牌",
    "9": "农用车牌",
    "10": "驾校车牌",
    "11": "新能源小车",
    "12": "新能源大车",
    "99": "其他车牌",
    "-1": "未知",
}
PlateColorType = {
    "1": "黄",
    "2": "蓝",
    "3": "黑",
    "4": "白",
    "5": "绿",
    "6": "黄绿",
    "7": "渐变绿",
    "-1": "未知",
}
PlateNeatnessType = {
    "1": "正常",
    "2": "遮挡",
    "3": "污损",
    "4": "无牌",
    "-1": "未知",
}
VehicleColorType = {
    "1": "黑",
    "2": "蓝",
    "3": "棕",
    "4": "绿",
    "5": "灰",
    "6": "橙",
    "7": "粉",
    "8": "紫",
    "9": "红",
    "10": "银",
    "11": "白",
    "12": "黄",
    "13": "金",
    "14": "混合色",
    "-1": "未知",
}
BikeClassType = {
    "1": "二轮摩托车",
    "2": "自行车",
    "3": "三轮车",
    "-1": "未知",
}
HairStyle = {
    "1" :"长发",
    "2"	:"短发",
    "-1": "未知",
}
CoatTexture = {
    "1":	"净色",
    "2":	"间条",
    "3":	"格子",
    "4":	"图案",
    "5":	"拼接",
    "-1":	"未知",
}
TrousersTexture = {
    "1"	: "净色",
    "2"	: "间条",
    "3"	: "图案",
    "-1": "未知",
}
HighwayTollVehiclesType = {
    "1": "1类客车",
    "2": "2类客车",
    "3": "3类客车",
    "4": "4类客车",
    "5": "1类货车",
    "6": "2类货车",
    "7": "3类货车",
    "8": "4类货车",
    "9": "5类货车",
    "10": "6类货车",
    "11": "1类专业作业车",
    "12": "2类专业作业车",
    "13": "3类专业作业车",
    "14": "4类专业作业车",
    "15": "5类专业作业车",
    "16": "6类专业作业车",
}

class IOESBikeMapping():
    listMappableShortText = [
        BIKE_ATTRIBUTE_BikeClass,
        BIKE_ATTRIBUTE_Gender,
        BIKE_ATTRIBUTE_Age,
        BIKE_ATTRIBUTE_Angle,
        BIKE_ATTRIBUTE_HasBackpack,
        BIKE_ATTRIBUTE_HasGlasses,
        BIKE_ATTRIBUTE_HasCarrybag,
        BIKE_ATTRIBUTE_HasUmbrella,
        BIKE_ATTRIBUTE_HasPassenger,
        BIKE_ATTRIBUTE_CoatLength,
        BIKE_ATTRIBUTE_SocialAttribute,
        BIKE_ATTRIBUTE_Enterprise,
        BIKE_ATTRIBUTE_HasPlate,
        BIKE_ATTRIBUTE_HasHelmet,
        BIKE_ATTRIBUTE_HelmetColor,
        BIKE_ATTRIBUTE_HasMask,
        BIKE_ATTRIBUTE_CoatTexture,
    ]
    listMappableLongText = []
    listMirrorableShortText = [
        BIKE_ATTRIBUTE_CoatColorNums
    ]
    listMirrorableLongText = []
    listBoxKey = [
        BIKE_ATTRIBUTE_ObjectBoundingBox,
        BIKE_ATTRIBUTE_FaceBoundingBox,
    ]
    listColorKey = [
        BIKE_ATTRIBUTE_CoatColor
    ]
    mapAttribute2Name = {
        BIKE_ATTRIBUTE_BikeClass: "骑行类型",
        BIKE_ATTRIBUTE_Gender: "性别",
        BIKE_ATTRIBUTE_Age: "年龄",
        BIKE_ATTRIBUTE_Angle: "角度",
        BIKE_ATTRIBUTE_HasBackpack: "背包",
        BIKE_ATTRIBUTE_HasGlasses: "眼镜",
        BIKE_ATTRIBUTE_HasCarrybag: "手提包",
        BIKE_ATTRIBUTE_HasUmbrella: "打伞",
        BIKE_ATTRIBUTE_HasPassenger: "载客",
        BIKE_ATTRIBUTE_CoatLength: "上衣类型",
        BIKE_ATTRIBUTE_SocialAttribute: "社会属性",
        BIKE_ATTRIBUTE_Enterprise: "所属企业",
        BIKE_ATTRIBUTE_HasPlate: "挂车牌",
        BIKE_ATTRIBUTE_HasHelmet: "戴头盔",
        BIKE_ATTRIBUTE_HelmetColor: "头盔颜色",
        BIKE_ATTRIBUTE_HasMask: "口罩",
        BIKE_ATTRIBUTE_CoatTexture: "上身衣着款式",
        BIKE_ATTRIBUTE_ObjectBoundingBox: "位置",
        BIKE_ATTRIBUTE_FaceBoundingBox: "面部位置",
        BIKE_ATTRIBUTE_CoatColorNums: "上身颜色数目",
        BIKE_ATTRIBUTE_CoatColor: "上衣颜色数组",
    }
    mapMappable2Mapper = {
        BIKE_ATTRIBUTE_BikeClass: BikeClassType,
        BIKE_ATTRIBUTE_Gender: GenderType,
        BIKE_ATTRIBUTE_Age: AgeType,
        BIKE_ATTRIBUTE_Angle: AngleType,
        BIKE_ATTRIBUTE_HasBackpack: ThreeStateType,
        BIKE_ATTRIBUTE_HasGlasses: ThreeStateType,
        BIKE_ATTRIBUTE_HasCarrybag: ThreeStateType,
        BIKE_ATTRIBUTE_HasUmbrella: ThreeStateType,
        BIKE_ATTRIBUTE_HasPassenger: ThreeStateType,
        BIKE_ATTRIBUTE_CoatLength: CoatType,
        BIKE_ATTRIBUTE_SocialAttribute: SocialAttributeType,
        BIKE_ATTRIBUTE_Enterprise: EnterpriseType,
        BIKE_ATTRIBUTE_HasPlate: ThreeStateType,
        BIKE_ATTRIBUTE_HasHelmet: ThreeStateType,
        BIKE_ATTRIBUTE_HelmetColor: ObjectColorType,
        BIKE_ATTRIBUTE_HasMask: ThreeStateType,
        BIKE_ATTRIBUTE_CoatTexture: CoatTexture,
        # 特殊映射(如二级内容)
        BIKE_ATTRIBUTE_CoatColor: ObjectColorType,
    }
class IOESPersonMapping():
    listMappableShortText = [
        PERSON_ATTRIBUTE_Gender,
        PERSON_ATTRIBUTE_Age,
        PERSON_ATTRIBUTE_Angle,
        PERSON_ATTRIBUTE_HasBackpack,
        PERSON_ATTRIBUTE_HasGlasses,
        PERSON_ATTRIBUTE_HasCarrybag,
        PERSON_ATTRIBUTE_HasUmbrella,
        PERSON_ATTRIBUTE_CoatLength,
        PERSON_ATTRIBUTE_TrousersLength,
        PERSON_ATTRIBUTE_HasHat,
        PERSON_ATTRIBUTE_HasMask,
        PERSON_ATTRIBUTE_HairStyle,
        PERSON_ATTRIBUTE_CoatTexture,
        PERSON_ATTRIBUTE_TrousersTexture,
        PERSON_ATTRIBUTE_HasTrolley,
        PERSON_ATTRIBUTE_HasLuggage,
    ]
    listMappableLongText = []
    listMirrorableShortText = [
        PERSON_ATTRIBUTE_CoatColorNums,
        PERSON_ATTRIBUTE_TrousersColorNums,
        PERSON_ATTRIBUTE_LuggageColorNums,
    ]
    listMirrorableLongText = []
    listBoxKey = [
        PERSON_ATTRIBUTE_ObjectBoundingBox,
        PERSON_ATTRIBUTE_HeadBoundingBox,
        PERSON_ATTRIBUTE_UpperBoundingBox,
        PERSON_ATTRIBUTE_LowerBoundingBox,
        PERSON_ATTRIBUTE_FaceBoundingBox,
    ]
    listColorKey = [
        PERSON_ATTRIBUTE_CoatColor,
        PERSON_ATTRIBUTE_TrousersColor,
        PERSON_ATTRIBUTE_LuggageColor,
    ]
    mapAttribute2Name = {
        PERSON_ATTRIBUTE_Gender: "性别",
        PERSON_ATTRIBUTE_Age: "年龄",
        PERSON_ATTRIBUTE_Angle: "角度",
        PERSON_ATTRIBUTE_HasBackpack: "背包",
        PERSON_ATTRIBUTE_HasGlasses: "眼镜",
        PERSON_ATTRIBUTE_HasCarrybag: "手提包",
        PERSON_ATTRIBUTE_HasUmbrella: "打伞",
        PERSON_ATTRIBUTE_CoatLength: "上衣类型",
        PERSON_ATTRIBUTE_TrousersLength: "下身类型",
        PERSON_ATTRIBUTE_HasHat: "帽子",
        PERSON_ATTRIBUTE_HasMask: "口罩",
        PERSON_ATTRIBUTE_HairStyle: "发型",
        PERSON_ATTRIBUTE_CoatTexture: "上身衣着款式",
        PERSON_ATTRIBUTE_TrousersTexture: "下身衣着款式",
        PERSON_ATTRIBUTE_HasTrolley: "手推车",
        PERSON_ATTRIBUTE_HasLuggage: "行李箱",

        PERSON_ATTRIBUTE_CoatColorNums: "上衣颜色数目",
        PERSON_ATTRIBUTE_TrousersColorNums: "下身颜色数目",
        PERSON_ATTRIBUTE_LuggageColorNums: "行李箱颜色数",

        PERSON_ATTRIBUTE_ObjectBoundingBox: "位置",
        PERSON_ATTRIBUTE_HeadBoundingBox: "头部位置",
        PERSON_ATTRIBUTE_UpperBoundingBox: "上半身位置",
        PERSON_ATTRIBUTE_LowerBoundingBox: "下半身位置",
        PERSON_ATTRIBUTE_FaceBoundingBox: "面部位置",

        PERSON_ATTRIBUTE_CoatColor: "上衣颜色数组",
        PERSON_ATTRIBUTE_TrousersColor: "下身颜色数组",
        PERSON_ATTRIBUTE_LuggageColor: "行李箱颜色数组",
    }
    mapMappable2Mapper = {
        PERSON_ATTRIBUTE_Gender: GenderType,
        PERSON_ATTRIBUTE_Age: AgeType,
        PERSON_ATTRIBUTE_Angle: AngleType,
        PERSON_ATTRIBUTE_HasBackpack: ThreeStateType,
        PERSON_ATTRIBUTE_HasGlasses: ThreeStateType,
        PERSON_ATTRIBUTE_HasCarrybag: ThreeStateType,
        PERSON_ATTRIBUTE_HasUmbrella: ThreeStateType,
        PERSON_ATTRIBUTE_CoatLength: CoatType,
        PERSON_ATTRIBUTE_TrousersLength: TrousersType,
        PERSON_ATTRIBUTE_HasHat: ThreeStateType,
        PERSON_ATTRIBUTE_HasMask: ThreeStateType,
        PERSON_ATTRIBUTE_HairStyle: HairStyle,
        PERSON_ATTRIBUTE_CoatTexture: CoatTexture,
        PERSON_ATTRIBUTE_TrousersTexture: TrousersTexture,
        PERSON_ATTRIBUTE_HasTrolley: ThreeStateType,
        PERSON_ATTRIBUTE_HasLuggage: ThreeStateType,

        # 特殊映射(如二级内容)
        PERSON_ATTRIBUTE_TrousersColor: ObjectColorType,
        PERSON_ATTRIBUTE_CoatColor: ObjectColorType,
        PERSON_ATTRIBUTE_LuggageColor: ObjectColorType,
    }
class IOESFaceMapping():
    listMappableShortText = [
        FACE_ATTRIBUTE_Gender,
        FACE_ATTRIBUTE_Age,
        FACE_ATTRIBUTE_HasGlasses,
        FACE_ATTRIBUTE_HasHat,
        FACE_ATTRIBUTE_HasMask,
        FACE_ATTRIBUTE_HairStyle,

    ]
    listMappableLongText = []
    listMirrorableShortText = []
    listMirrorableLongText = []
    listBoxKey = [
        PERSON_ATTRIBUTE_HeadBoundingBox,
        PERSON_ATTRIBUTE_FaceBoundingBox,
    ]
    listColorKey = []
    mapAttribute2Name = {
        PERSON_ATTRIBUTE_Gender: "性别",
        PERSON_ATTRIBUTE_Age: "年龄",
        PERSON_ATTRIBUTE_HasGlasses: "眼镜",
        PERSON_ATTRIBUTE_HasHat: "帽子",
        PERSON_ATTRIBUTE_HasMask: "口罩",
        PERSON_ATTRIBUTE_HairStyle: "发型",

        PERSON_ATTRIBUTE_HeadBoundingBox: "头部位置",
        PERSON_ATTRIBUTE_FaceBoundingBox: "面部位置",
    }
    mapMappable2Mapper = {
        PERSON_ATTRIBUTE_Gender: GenderType,
        PERSON_ATTRIBUTE_Age: AgeType,
        PERSON_ATTRIBUTE_HasGlasses: ThreeStateType,
        PERSON_ATTRIBUTE_HasHat: ThreeStateType,
        PERSON_ATTRIBUTE_HasMask: ThreeStateType,
        PERSON_ATTRIBUTE_HairStyle: HairStyle,
        # 特殊映射(如二级内容)
    }
class IOESCarMapping():
    listMappableShortText = [
        CAR_ATTRIBUTE_Angle,
        CAR_ATTRIBUTE_VehicleClass,
        CAR_ATTRIBUTE_HasPlate,
        CAR_ATTRIBUTE_PlateClass,
        CAR_ATTRIBUTE_PlateColor,
        CAR_ATTRIBUTE_PlateNeatness,
        CAR_ATTRIBUTE_Sunvisor,
        CAR_ATTRIBUTE_Paper,
        CAR_ATTRIBUTE_Decoration,
        CAR_ATTRIBUTE_Drop,
        CAR_ATTRIBUTE_HasCall,
        CAR_ATTRIBUTE_HasSkylight,
        CAR_ATTRIBUTE_HasBaggage,
        CAR_ATTRIBUTE_HasAerial,
        CAR_ATTRIBUTE_HasCrash,
        CAR_ATTRIBUTE_HasDanger,
    ]
    listMappableLongText = [
        CAR_ATTRIBUTE_HighwayTollVehicles,
    ]
    listMirrorableShortText = [
        CAR_ATTRIBUTE_PlateNo,
        CAR_ATTRIBUTE_VehicleColorNums,
        CAR_ATTRIBUTE_Tag,
    ]
    listMirrorableLongText = [
        CAR_ATTRIBUTE_VehicleBrand,
    ]
    listBoxKey = [
        CAR_ATTRIBUTE_ObjectBoundingBox,
    ]
    listColorKey = [
        CAR_ATTRIBUTE_VehicleColor,
    ]

    mapAttribute2Name = {
        CAR_ATTRIBUTE_Angle: "角度",
        CAR_ATTRIBUTE_VehicleClass: "车辆类型",
        CAR_ATTRIBUTE_VehicleColorNums: "车辆颜色数目",
        CAR_ATTRIBUTE_HasPlate: "车牌",
        CAR_ATTRIBUTE_PlateClass: "车牌种类",
        CAR_ATTRIBUTE_PlateColor: "车牌颜色",
        CAR_ATTRIBUTE_PlateNeatness: "车牌污浊遮挡",
        CAR_ATTRIBUTE_Sunvisor: "遮阳板状态",
        CAR_ATTRIBUTE_Paper: "纸巾盒",
        CAR_ATTRIBUTE_Decoration: "摆饰",
        CAR_ATTRIBUTE_Drop: "挂饰",
        CAR_ATTRIBUTE_Tag: "年检标数量",
        CAR_ATTRIBUTE_HasCall: "打电话状态",
        CAR_ATTRIBUTE_HasSkylight: "天窗",
        CAR_ATTRIBUTE_HasBaggage: "行李架",
        CAR_ATTRIBUTE_HasAerial: "天线",
        CAR_ATTRIBUTE_HasCrash: "是否有撞损",
        CAR_ATTRIBUTE_HasDanger: "是否危化车",
        CAR_ATTRIBUTE_HighwayTollVehicles: "收费车型",
        CAR_ATTRIBUTE_VehicleBrand: "车辆品牌",
        CAR_ATTRIBUTE_PlateNo: "车牌号码",
        CAR_ATTRIBUTE_ObjectBoundingBox: "位置",
        CAR_ATTRIBUTE_VehicleColor: "车辆颜色数组",
        CAR_ATTRIBUTE_SafetyBelt: "安全带",
    }

    mapMappable2Mapper = {
        CAR_ATTRIBUTE_Angle: AngleType,
        CAR_ATTRIBUTE_VehicleClass: VehicleClassType,
        CAR_ATTRIBUTE_HasPlate: ThreeStateType,
        CAR_ATTRIBUTE_PlateClass: PlateClassType,
        CAR_ATTRIBUTE_PlateColor: PlateColorType,
        CAR_ATTRIBUTE_PlateNeatness: PlateNeatnessType,
        CAR_ATTRIBUTE_Sunvisor: ThreeStateType,
        CAR_ATTRIBUTE_Paper: ThreeStateType,
        CAR_ATTRIBUTE_Decoration: ThreeStateType,
        CAR_ATTRIBUTE_Drop: ThreeStateType,
        CAR_ATTRIBUTE_HasCall: ThreeStateType,
        CAR_ATTRIBUTE_HasSkylight: ThreeStateType,
        CAR_ATTRIBUTE_HasBaggage: ThreeStateType,
        CAR_ATTRIBUTE_HasAerial: ThreeStateType,
        CAR_ATTRIBUTE_HasCrash: ThreeStateType,
        CAR_ATTRIBUTE_HasDanger: ThreeStateType,
        CAR_ATTRIBUTE_HighwayTollVehicles: HighwayTollVehiclesType,

        # 特殊映射(如二级内容)
        CAR_ATTRIBUTE_VehicleColor: VehicleColorType,
        CAR_ATTRIBUTE_SafetyBelt: ThreeStateType,
    }

if __name__ == '__main__':
    carMapping = IOESCarMapping()
    PersonMapping = IOESPersonMapping()
    BikeMapping = IOESBikeMapping()
    print("===== Car =====")
    for (key,value) in carMapping.mapAttribute2Name.items():
        print("%s \t\t\t %s" %(key, value))

    print("===== Person =====")
    for (key,value) in PersonMapping.mapAttribute2Name.items():
        print("%s \t\t\t %s" %(key, value))

    print("===== Bike =====")
    for (key,value) in BikeMapping.mapAttribute2Name.items():
        print("%s \t\t\t %s" %(key, value))


# BUJUR SANGKAR
# Membuat program yang menghitung luas bujur sangkar (persegi) dengan rumus sisi * sisi, dari masukan
# berupa sisi (dalam bentuk integer). Input sisi harus divalidasi sehingga selalu > 0. Jika sisi yang
# dimasukkan <= 0, program akan mengeluarkan pesan error.

# KAMUS
# sisi = integer

# ALGORITMA
sisi = int(input())
if sisi <= 0:
    print("Sisi harus > 0")
else:
    print(sisi * sisi)


import random
import math

lower = int(input("Enter a number: "))
upper = int(input("Enter another number: "))
x = random.randint(lower, upper)
max_of_guess = round(math.log2(upper - lower + 1))

count = 0
while True:
    guess_num = int(input("Guess a number:"))
    count += 1
    if count > max_of_guess:
        print("Better Luck, Next Time!")
        break
    elif guess_num > x:
        print("Try again, Too high!")
        continue
    elif guess_num < x:
        print("Try again, Too small!")
        continue
    else:
        print("Congratulation! it's correct.")
        print(f"The number of guesses: {count}")
        break


from bs4 import BeautifulSoup
import urllib2

def get_url_title(data):
    start = data.find('http')
    stop = data.find(' ', start)
    if stop == -1:
        stop = len(data)
    url = data[start:stop]

    if url.find('i.imgur') != -1 and not url.find('/a/') != -1:
        url = fix_imgur_url(url)
        if return_title(url).find('the simple image sharer') != -1:
            return 'That Imgur link does not seem to have a proper title'
        return return_title(url)
    else:
        if url.find('twitch.tv') != -1:
            return get_twitch_title(url)

        return return_title(url)

def get_twitch_title(URL):
    nomnom = get_soup(URL)
    stream_title = nomnom.findAll(attrs={'property': 'og:description'})
    streamer = nomnom.findAll(attrs={'property': 'og:title'})

    title = 'Twitch > ' + streamer[0]['content'] + ' - ' + stream_title[0]['content']
    return title

def fix_imgur_url(url):
    tempurl = url.split('.')
    url = tempurl[0]
    url = 'http://' + tempurl[1] + '.' + tempurl[2]
    return url

def return_title(url):
    try:
        soup = get_soup(url)
        title = soup.title.contents[0]
        return 'URL > ' + title.lstrip().encode("utf-8")
    except:
        return "Couldn't find a proper title and/or something went wrong :("

def get_soup(url):
    soup = BeautifulSoup(urllib2.urlopen(url).read())
    return soup


#!/bin/python3

# import sys
def reverse_sublist(lst, start, end):
    lst[ start:end + 1 ] = lst[ start:end + 1 ][ ::-1 ]
    return lst

def calculate(program):
    initial = 1
    total = 0
    for i in program:
        if i == 'C':
            initial = initial * 2
        else:
            total += initial
    return total

def findnext(program):
    for i in range(len(program) - 1, 0, -1):
        if program[ i ] == 'S' and program[ i - 1 ] == 'C':
            program[ i - 1:i + 1 ] = program[ i - 1:i + 1 ][ ::-1 ]
            return program

def save(damage, program):
    # Complete this function
    c = program.count('S')
    if c > damage:
        return "IMPOSSIBLE"
    if c == 0:
        return 0
    p = list(program)
    c = 0
    while True:
        if calculate(p) <= damage:
            return c
        else:
            for i in range(len(p) - 1, 0, -1):
                if p[ i ] == 'S' and p[ i - 1 ] == 'C':
                    p = reverse_sublist(p, i - 1, i)
                    c += 1
                    break

if __name__ == "__main__":
    t = int(input().strip())
    lst = []
    for a0 in range(t):
        damage, program = input().strip().split(' ')
        damage = int(damage)
        lst.append([damage,program])
    for i in range(len(lst)):
        print("Case #", i + 1, ": ", save(lst[i][0], lst[i][1]), sep="")


import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import time

def read_dataset(feature_file, label_file):
    ''' Read data set in *.csv to data frame in Pandas'''
    df_X = pd.read_csv(feature_file)
    df_y = pd.read_csv(label_file)
    X = df_X.values # convert values in dataframe to numpy array (features)
    y = df_y.values # convert values in dataframe to numpy array (label)
    return X, y

def normalize_features(X_train, X_test):
    from sklearn.preprocessing import StandardScaler #import libaray
    scaler = StandardScaler() # call an object function
    scaler.fit(X_train) # calculate mean, std in X_train
    X_train_norm = scaler.transform(X_train) # apply normalization on X_train
    X_test_norm = scaler.transform(X_test) # we use the same normalization on X_test
    return X_train_norm, X_test_norm

class Kmeans():
    def __init__(self, k = 2, n_interation = 500):
        self.k = k
        self.n_interation = n_interation

    def _distance(p1,p2):
        """
        Return Eclud distance between two points.
        """
        tmp = np.sum((p1-p2)**2)
        return np.sqrt(tmp)

    def rand_Cluster_Centroid(self, X):
        """Generate k center within the range of data set."""
        n_features = X.shape[1]
        centroids = np.zeros((self.k,n_features))
        for i in range(n_features):
            dmin, dmax = np.min(X[:,i]), np.max(X[:,i])
            centroids[:,i] = dmin + (dmax - dmin) * np.random.rand(self.k)
        return centroids

    def if_converge(self,centroids1, centroids2):
        # if centroids not changed, we say 'converged'
         set1 = set([tuple(c) for c in centroids1])
         set2 = set([tuple(c) for c in centroids2])
         return (set1 == set2)

    def Find_closest_centroid(self, sample, centroids):
        """ Return the index of the closest centroid to the sample """
        closest_i = 0
        closest_dist = float('inf')
        for i, centroid in enumerate(centroids):
            distance = np.linalg.norm(sample-centroid)
            if distance < closest_dist:
                closest_i = i
                closest_dist = distance
        return closest_i

    def predict(self, X):
        """
        repeate N times
        """
        centroids = self.rand_Cluster_Centroid(X)
        n_samples, n_features = X.shape
        ypred = np.zeros((n_samples,1))
        converge = False

        for i in range(self.n_interation):
            clusters = [[] for i in range(self.k)]
            for sample_i, sample in enumerate(X):
                centroid_i = self.Find_closest_centroid(sample, centroids)
                clusters[centroid_i].append(sample_i)
            old_centroids = centroids
            centroids = np.zeros((self.k, n_features))
            for i, cluster in enumerate(clusters):
                centroid = np.mean(X[cluster], axis=0)
                centroids[i] = centroid
            converge = self.if_converge(old_centroids,centroids)
            if converge:
                break

        for cluster_i, cluster in enumerate(clusters):
            for sample_i in cluster:
                ypred[sample_i] = cluster_i
        return ypred, centroids

def Cluster_show(X, centroids, ypred):
    X0 = X[np.where(ypred==0)[0],:]
    X1 = X[np.where(ypred==1)[0],:]

    fig, (ax1,ax2) = plt.subplots(1,2,figsize=(12,5))
    ax1.scatter(X[:,0],X[:,1],c='c',s=30,marker='o')
    ax2.scatter(X0[:,0],X0[:,1],c='r')
    ax2.scatter(X1[:,0],X1[:,1],c='y')
    ax2.scatter(centroids[:,0],centroids[:,1],c='b',s=120,marker='o')
    plt.show()

X_train, y_train = read_dataset('Iris_X_train.csv', 'Iris_y_train.csv')
X_test, y_test = read_dataset('Iris_X_test.csv', 'Iris_y_test.csv')
X_train_norm, X_test_norm = normalize_features(X_train, X_test)

X = np.append(X_train, X_test, axis = 0)
y = np.append(y_train, y_test, axis = 0)
print(X.shape)

print('===============================Start===================================')
tic = time.process_time()

myKmeans = Kmeans(k = 2, n_interation = 200)
ypred, centroids= myKmeans.predict(X)

toc = time.process_time()
print('Totol time:' + str((toc - tic)) + 's')
print('===============================Finish===================================')

Cluster_show(X, centroids, ypred)
# Cluster_show(X, centroids, y)


class Solution:
    def pivotIndex(self, nums: list[int]) -> int:
        left_sum = 0
        total_sum = sum(nums)

        for i, x in enumerate(nums):
            if left_sum == (total_sum - left_sum - x):
                return i
            left_sum += x
        return -1

if __name__ == "__main__":
    sol = Solution()
    input = [1,7,3,6,5,6]
    ans = sol.pivotIndex(input)
    print(ans)


import tensorflow as tf
from sklearn.preprocessing import MinMaxScaler
import numpy as np
train_x_str = []
train_y_str = []
test_x_str = []
test_y_str = []
with open('Train_major.csv', "r") as rf:
    for i in rf.readlines():
        train_x_str.append(i.split(',')[3:5]+i.split(',')[5:26])
with open('Train_major.csv', "r") as rf:
    for i in rf.readlines():
        train_y_str.append(i.split(',')[5:6])
with open('Test_major.csv', "r") as rf:
    for i in rf.readlines():
        test_x_str.append(i.split(',')[3:5]+i.split(',')[5:26])
with open('Test_major.csv', "r") as rf:
    for i in rf.readlines():
        test_y_str.append(i.split(',')[5:6])

def xavier_init(n_inputs, n_outputs, uniform =True):
    if uniform:
        init_range = tf.sqrt(6.0/(n_inputs+n_outputs))
        return tf.random_uniform_initializer(-init_range, init_range)
    else:
        stddev = tf.sqrt(3.0/(n_inputs+n_outputs))
        return tf.truncated_normal_initializer(stddev = stddev)

train_x = [list(map(lambda x: float(x),train_x_str[i])) for i in range(len(train_x_str))]
train_y = [list(map(lambda x: float(x),train_y_str[i])) for i in range(len(train_y_str))]
test_x = [list(map(lambda x: float(x),test_x_str[i])) for i in range(len(test_x_str))]
test_y = [list(map(lambda x: float(x),test_y_str[i])) for i in range(len(test_y_str))]

scaler = MinMaxScaler(feature_range=(0,100))
data_x = scaler.fit_transform(train_x)
data_y = scaler.fit_transform(train_y)
X = tf.placeholder(tf.float32, shape =[None,23])
Y = tf.placeholder(tf.float32, shape = [None,1])

w = tf.get_variable("W1", shape = [23,1], initializer = xavier_init(23,1))
b = tf.Variable(tf.random_normal([1]), name = 'bias')

hypothesis = tf.matmul(X,w) +b

cost = tf.reduce_mean(tf.square(hypothesis - Y))

optimizer = tf.train.AdamOptimizer(learning_rate = 0.000005)
train = optimizer.minimize(cost)

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

for s in range(200000):
    cost_val, hy_val, _ = sess.run([cost, hypothesis, train],feed_dict = {X:data_x,Y:data_y})
    if s % 50000 == 0:
        print (s, "Cost:",cost_val,"\nPrediction\n",hy_val)
        print ("ssss",sess.run(hypothesis,feed_dict = {X : test_x}))


from typing import List

class Solution:
    def twoSumLessThanK1099(self, A: List[int], K: int) -> int:
        if len(A) < 2:
            return -1
        i, j = 0, len(A) - 1
        maxv = -1
        A.sort()
        while i < j:
            m = A[i] + A[j]
            if m >= K:
                j -= 1
            else:
                maxv = max(maxv, m)
                i += 1
        return maxv

    def sortArrayByParity905(self, A: List[int]) -> List[int]:
        i, j = 0, len(A) - 1
        while i < j:
            while i < j and A[i] % 2 == 0:
                i += 1
            while i < j and A[j] % 2:
                j -= 1
            A[i], A[j] = A[j], A[i]
            i, j = i + 1, j - 1
        return A

    def triangleNumber611(self, nums: List[int]) -> int:
        # like 3sum. each time we set outer loop from large -> small, then two pointers on left. For making a
        # triagle, need two edges sum > third edge.
        if len(nums) < 3:
            return 0
        nums.sort()
        res = 0
        for i in reversed(range(2, len(nums))):
            j, k = 0, i - 1
            while j < k:
                if nums[j] + nums[k] > nums[i]:
                    res += k - j
                    k -= 1
                else:
                    j += 1
        return res


import parameters as params

class DataBase:

    def __init__(self):
        self.Parties = []
        self.People = []

        # Updates every election
        self.AverageHappiness = []
        self.AverageConfidence = []
        self.curNumberOfParties = [params.nParties]
        self.VotingForIdealParty = []
        self.SwingVoteFrac = []

    def PostElectionEvaluations(self):

        aveHapp, aveConf, aveVoteIdealParty, aveSwing = self.__ComputeAverages()

        self.AverageHappiness.append(aveHapp)
        self.AverageConfidence.append(aveConf)
        self.VotingForIdealParty.append(aveVoteIdealParty)
        self.SwingVoteFrac.append(aveSwing)

        self.curNumberOfParties.append(len(self.Parties))

    def __ComputeAverages(self):

        average_happiness = 0
        average_Confidence_In_Leader_Voted_For = 0
        average_Voting_For_ideal_Party = 0
        average_Swing_Voter = 0

        for person in self.People:

            # Add a necessary redundancy check to see so no voter is voting for a party that
            # has been eliminated. If so, we update the his vote so that we votes for nothing.
            # Ideally this should not be needed, but for some reason the model fucks up sometimes...
            if person.VotedFor is not None:
                if person.VotedFor.id > len(person.ConfidenceInLeader) - 1:
                    self.People[person.id].UpdateVote(None)

            person.ComputeHappiness()
            average_happiness += person.CurHappiness

            if person.VotedFor != None:
                average_Confidence_In_Leader_Voted_For += person.ConfidenceInLeader[person.VotedFor.id]

            if person.VotedFor == person.IdealParty:
                average_Voting_For_ideal_Party += 1

            if person.SwingVoteFactor < params.swingVoteLimit:
                average_Swing_Voter += 1

        return ( average_happiness / params.nPeople,
                 average_Confidence_In_Leader_Voted_For / params.nPeople,
                 average_Voting_For_ideal_Party / params.nPeople * 100,
                 average_Swing_Voter / params.nPeople * 100)


class Solution:
    def countBits(self, n: int) -> List[int]:
        output = []
        for i in range(n+1):
            cur = 0
            while i:
                cur += i&1
                i = i>>1
            output.append(cur)
        return output


import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# Load the datasets
path_CrossSpecies = '/data1/fsong/py_proj/prot_algo/DeepSS2GO/Analysis/CrossSpecies_HeatMap/'  # /mnt/data/

# path_CrossSpecies = '/mnt/data/'
df_aa = pd.read_csv(path_CrossSpecies + 'CrossSpecies_results_aa.csv')
df_ss8 = pd.read_csv(path_CrossSpecies + 'CrossSpecies_results_ss8.csv')

# Species for train and test
species = ["ARATH", "ECOLI", "HUMAN", "MOUSE", "MYCTU", "YEAST"]

# Set metric choice to 'Fmax' since we are using that data
metric_choice = 'Smin'

# Define a function to create a heatmap data matrix
def create_heatmap_matrix(df, feature):
    matrix = []
    for test_species in species:
        row = []
        for train_species in species:
            value = df.loc[
                (df['Train'] == train_species) & (df['Test'] == test_species),
                feature
            ].values[0]
            row.append(value)
        matrix.append(row)
    return matrix

# Create heatmap matrices for the chosen metric
heatmap_data = {
    f'bp_{metric_choice}_aa': create_heatmap_matrix(df_aa, f'bp_{metric_choice}'),
    f'bp_{metric_choice}_ss8': create_heatmap_matrix(df_ss8, f'bp_{metric_choice}'),
    f'cc_{metric_choice}_aa': create_heatmap_matrix(df_aa, f'cc_{metric_choice}'),
    f'cc_{metric_choice}_ss8': create_heatmap_matrix(df_ss8, f'cc_{metric_choice}'),
    f'mf_{metric_choice}_aa': create_heatmap_matrix(df_aa, f'mf_{metric_choice}'),
    f'mf_{metric_choice}_ss8': create_heatmap_matrix(df_ss8, f'mf_{metric_choice}')
}

# Find min and max for each pair of heatmaps to set the color bar range

# original:
# bp_min = min(map(min, heatmap_data['bp_Fmax_aa'] + heatmap_data['bp_Fmax_ss8']))
# bp_max = max(map(max, heatmap_data['bp_Fmax_aa'] + heatmap_data['bp_Fmax_ss8']))
#
# cc_min = min(map(min, heatmap_data['cc_Fmax_aa'] + heatmap_data['cc_Fmax_ss8']))
# cc_max = max(map(max, heatmap_data['cc_Fmax_aa'] + heatmap_data['cc_Fmax_ss8']))
#
# mf_min = min(map(min, heatmap_data['mf_Fmax_aa'] + heatmap_data['mf_Fmax_ss8']))
# mf_max = max(map(max, heatmap_data['mf_Fmax_aa'] + heatmap_data['mf_Fmax_ss8']))

# FS change
bp_min = min(map(min, heatmap_data[f'bp_{metric_choice}_aa'] + heatmap_data[f'bp_{metric_choice}_ss8']))
bp_max = max(map(max, heatmap_data[f'bp_{metric_choice}_aa'] + heatmap_data[f'bp_{metric_choice}_ss8']))

cc_min = min(map(min, heatmap_data[f'cc_{metric_choice}_aa'] + heatmap_data[f'cc_{metric_choice}_ss8']))
cc_max = max(map(max, heatmap_data[f'cc_{metric_choice}_aa'] + heatmap_data[f'cc_{metric_choice}_ss8']))

mf_min = min(map(min, heatmap_data[f'mf_{metric_choice}_aa'] + heatmap_data[f'mf_{metric_choice}_ss8']))
mf_max = max(map(max, heatmap_data[f'mf_{metric_choice}_aa'] + heatmap_data[f'mf_{metric_choice}_ss8']))

# Set up the matplotlib figure and axes
fig, axes = plt.subplots(2, 3, figsize=(18, 12))
fig.suptitle(metric_choice, fontsize=16)

# Titles for the heatmaps
titles = [f'bp_{metric_choice}_aa', f'cc_{metric_choice}_aa', f'mf_{metric_choice}_aa',
          f'bp_{metric_choice}_ss8', f'cc_{metric_choice}_ss8', f'mf_{metric_choice}_ss8']

# Define the colormap for each set of heatmaps
cmap_dict = {
    'bp': 'Greens',
    'cc': 'Blues',
    'mf': 'Oranges'
}

# Determine the number format based on the metric choice
fmt = ".3f"
sns.set(font_scale=1.2)

# Create a list to order the axes properly (3 columns by 2 rows)
axes_order = [(i, j) for i in range(2) for j in range(3)]

# Plot each heatmap
for ((row, col), title) in zip(axes_order, titles):
    ax = axes[row, col]
    category = title.split('_')[0]
    vmin, vmax = eval(f'{category}_min'), eval(f'{category}_max')
    sns.heatmap(heatmap_data[title], ax=ax, cmap=cmap_dict[category], annot=True, fmt=fmt,
                xticklabels=species, yticklabels=species, vmin=vmin, vmax=vmax)
    ax.set_title(title.replace('_', ' '))
    ax.xaxis.set_ticks_position('top')  # Set the x-axis labels to the top
    ax.xaxis.set_label_position('top')  # Set the x-axis labels' position to the top
    ax.set_xlabel('Train')
    ax.set_ylabel('Test')

plt.tight_layout(rect=[0, 0.03, 1, 0.95])  # Adjust for main title
plt.show()