from __future__ import annotations
from typing import Iterator, Callable, Any
from .entities import (
    AcisEntity,
    NONE_REF,
    Face,
    Coedge,
    Loop,
    Vertex,
)
from . import sab

class AcisDebugger:
    def __init__(self, root: AcisEntity = NONE_REF, start_id: int = 1):
        self._next_id = start_id - 1
        self._root: AcisEntity = root
        self.entities: dict[int, AcisEntity] = dict()
        if not root.is_none:
            self._store_entities(root)

    @property
    def root(self) -> AcisEntity:
        return self._root

    def _get_id(self) -> int:
        self._next_id += 1
        return self._next_id

    def _store_entities(self, entity: AcisEntity) -> None:
        if not entity.is_none and entity.id == -1:
            entity.id = self._get_id()
        self.entities[entity.id] = entity
        for e in vars(entity).values():
            if isinstance(e, AcisEntity) and e.id == -1:
                self._store_entities(e)

    def set_entities(self, entity: AcisEntity) -> None:
        self.entities.clear()
        self._root = entity
        self._store_entities(entity)

    def walk(self, root: AcisEntity = NONE_REF) -> Iterator[AcisEntity]:
        def _walk(entity: AcisEntity):
            if entity.is_none:
                return
            yield entity
            done.add(entity.id)
            for e in vars(entity).values():
                if isinstance(e, AcisEntity) and e.id not in done:
                    yield from _walk(e)

        if root.is_none:
            root = self._root
        done: set[int] = set()
        yield from _walk(root)

    def filter(
        self, func: Callable[[AcisEntity], bool], entity: AcisEntity = NONE_REF
    ) -> Iterator[Any]:
        if entity.is_none:
            entity = self._root
        yield from filter(func, self.walk(entity))

    def filter_type(
        self, name: str, entity: AcisEntity = NONE_REF
    ) -> Iterator[Any]:
        if entity.is_none:
            entity = self._root
        yield from filter(lambda x: x.type == name, self.walk(entity))

    @staticmethod
    def entity_attributes(entity: AcisEntity, indent: int = 0) -> Iterator[str]:
        indent_str = " " * indent
        for name, data in vars(entity).items():
            if name == "id":
                continue
            yield f"{indent_str}{name}: {data}"

    def face_link_structure(self, face: Face, indent: int = 0) -> Iterator[str]:
        indent_str = " " * indent

        while not face.is_none:
            partner_faces = list(self.partner_faces(face))
            error = ""
            linked_partner_faces = []
            unlinked_partner_faces = []
            for pface_id in partner_faces:
                pface = self.entities.get(pface_id)
                if pface is None:
                    error += f" face {pface_id} does not exist;"
                if isinstance(pface, Face):
                    reverse_faces = self.partner_faces(pface)
                    if face.id in reverse_faces:
                        linked_partner_faces.append(pface_id)
                    else:
                        unlinked_partner_faces.append(pface_id)
                else:
                    error += f" entity {pface_id} is not a face;"
            if unlinked_partner_faces:
                error = f"unlinked partner faces: {unlinked_partner_faces} {error}"
            yield f"{indent_str}{str(face)} >> {partner_faces} {error}"
            face = face.next_face

    @staticmethod
    def partner_faces(face: Face) -> Iterator[int]:
        coedges: list[Coedge] = []
        loop = face.loop
        while not loop.is_none:
            coedges.extend(co for co in loop.coedges())
            loop = loop.next_loop
        for coedge in coedges:
            for partner_coedge in coedge.partner_coedges():
                yield partner_coedge.loop.face.id

    @staticmethod
    def coedge_structure(face: Face, ident: int = 4) -> list[str]:
        lines: list[str] = []
        coedges: list[Coedge] = []
        loop = face.loop

        while not loop.is_none:
            coedges.extend(co for co in loop.coedges())
            loop = loop.next_loop
        for coedge in coedges:
            edge1 = coedge.edge
            sense1 = coedge.sense
            lines.append(f"Coedge={coedge.id} edge={edge1.id} sense={sense1}")
            for partner_coedge in coedge.partner_coedges():
                edge2 = partner_coedge.edge
                sense2 = partner_coedge.sense
                lines.append(
                    f"    Partner Coedge={partner_coedge.id} edge={edge2.id} sense={sense2}"
                )
        ident_str = " " * ident
        return [ident_str + line for line in lines]

    @staticmethod
    def loop_vertices(loop: Loop, indent: int = 0) -> str:
        indent_str = " " * indent
        return f"{indent_str}{loop} >> {list(AcisDebugger.loop_edges(loop))}"

    @staticmethod
    def loop_edges(loop: Loop) -> Iterator[list[int]]:
        coedge = loop.coedge
        first = coedge
        while not coedge.is_none:
            edge = coedge.edge
            sv = edge.start_vertex
            ev = edge.end_vertex
            if coedge.sense:
                yield [ev.id, sv.id]
            else:
                yield [sv.id, ev.id]
            coedge = coedge.next_coedge
            if coedge is first:
                break

    def vertex_to_edge_relation(self) -> Iterator[str]:
        for vertex in (
            e for e in self.entities.values() if isinstance(e, Vertex)
        ):
            edge = vertex.edge
            sv = edge.start_vertex
            ev = edge.end_vertex
            yield f"{vertex}: parent edge is {edge.id}; {sv.id} => {ev.id}; {edge.curve}"

    def is_manifold(self) -> bool:
        for coedge in self.filter_type("coedge"):
            if len(coedge.partner_coedges()) > 1:
                return False
        return True

def dump_sab_as_text(data: bytes) -> Iterator[str]:
    def entity_data(e):
        for tag, value in e:
            name = sab.Tags(tag).name
            yield f"{name} = {value}"

    decoder = sab.Decoder(data)
    header = decoder.read_header()
    yield from header.dumps()
    index = 0
    try:
        for record in decoder.read_records():
            yield f"--------------------- record: {index}"
            yield from entity_data(record)
            index += 1
    except sab.ParsingError as e:
        yield str(e)


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

'''
作用：用于将下载所得的所有试卷数据合并，输出至单个文件中
输入：data_dir为下载的压缩包解压后的目录，其中有多个.csv试卷数据，为输入文件
输出：outfile_name为合并后输出文件的文件名（合并后每行数据的第一列会加上所属试卷名），输出文件与当前脚本同目录
'''

import os

data_dir="146406856066.byPaper.choice"
outfile_name="merged_"+data_dir+".csv"

filenames=os.listdir(data_dir)
outfile=open(outfile_name,"w")

title_flag=False

for fname in filenames:
    infile=open(data_dir+"/"+fname)
    title=infile.readline()
    if title_flag==False:
        outfile.write("试卷名,"+title)
        title_flag=True

    for line in infile.readlines():
        outfile.write(fname.decode("gbk").encode("utf-8").split(".")[0]+","+line)

    infile.close()

outfile.close()


numbers = [1, 45, 32, 12, 60]

# if any number is divisible by 8, we don't want it
for number in numbers:
    if number % 8 == 0:
        print("The numbers are unacceptable")
        break
else:   # pay attention to indent, the else is for "for" not "if"
    # used to do something if loop wasnt broken out of and runs its course
    # aka when loop terminates normally
    print("All those numbers are fine")


import sys

OPTIMAL_TIME_FOR_ONE_FRAME = 1.0

sys.path.append("../nx/networkx-1.7-py3.2.egg")

import matplotlib.pyplot as plt
import networkx as nx

from kruskal import KruskalAlgorithm
from time import clock, sleep

# labels represent nodes, numbers are weights
graphDescription = {
    ('a', 'b'): 3,
    ('a', 'c'): 2,
    ('c', 'd'): 1,
    ('y', 'z'): 1,
    ('c', 'y'): 3,
    ('d', 'z'): 100,
    ('a', 'y'): 21,
    ('q', 'a'): 100,
    ('v', 'a'): 23,
    ('v', 'x'): -3,
    ('x', 'a'): 5
}

graph = nx.Graph()

for (u, v) in graphDescription:
    graph.add_edge(u, v)

def weights(edge):
    try:
        return graphDescription[edge]
    except KeyError:
        (u, v) = edge
        return graphDescription[(v, u)]

import matplotlib.animation as animation

edgeLabels={}
for (u, v) in graph.edges():
    edgeLabels[(u, v)] = weights((u, v))

figure = plt.figure()
figure.set_facecolor('white')
pos=nx.spring_layout(graph)

def drawGraph(currentSpanningTreeEdges):
    plt.clf()
    plt.axis('off')
    figure.canvas.set_window_title("Kruskal algorithm for finding minimal spanning tree")
    nx.draw_networkx_nodes(graph, pos, node_size = 1000)
    nx.draw_networkx_edges(graph, pos, width=1, edge_color="b", alpha = 0.5)
    nx.draw_networkx_edges(graph, pos, edgelist=currentSpanningTreeEdges, edge_color="g", width=6)
    nx.draw_networkx_labels(graph, pos, font_size=20, font_family='sans-serif')
    nx.draw_networkx_edge_labels(graph, pos, edge_labels=edgeLabels)

alg = KruskalAlgorithm(graph, weights)

def animate(i):
    global alg
    if i == 0:
        alg = KruskalAlgorithm(graph, weights)

    start = clock()
    drawGraph(alg.getSelectedSpanningTreeEdges())
    alg.nextStep()
    timeShowingThisFrame = clock() - start
    if timeShowingThisFrame < OPTIMAL_TIME_FOR_ONE_FRAME:
        sleep(OPTIMAL_TIME_FOR_ONE_FRAME - timeShowingThisFrame)

ani = animation.FuncAnimation(figure, animate, len(graph.nodes()), repeat=True)
plt.show()


#%%
from operator import mod
import string

#%%
def egcd(a, b):
  if a == 0:
      return (b, 0, 1)
  g, y, x = egcd(b%a,a)
  return (g, x - (b//a) * y, y)

def modinv(a, m):
  return egcd(a, m)[1] % m

#%%

mapping = string.ascii_lowercase + string.digits + "_"
print(mapping)
#%%
with open("message.txt") as f:

    txt = f.readline().split()

    txt = [int(n) for n in txt]

    mod41 = [i%41 for i in txt]

    mod_inverse = [modinv(i, 41) for i in mod41]

    final_txt = [mapping[i-1] for i in mod_inverse]

    flag = "".join(final_txt)

    # All in one list comprehension
    #flag = "".join([mapping[modinv(int(i)%41, 41)-1] for i in txt])
#%%
print(flag)
# Add the flag text on picoCTF{}
#%%


#!/usr/bin/env python3

__doc__ = '''
Viết script get_version nhận vào ngày ở format <month>/<day>/<year>.
VD: 03/28/16 làm parameter và in ra một version được tính theo quy luật sau:
- Version ở dạng format: <MAJOR>.<MINOR>.<PATCH>, vd: "6.9.2"
- Cách đánh version này gọi là semver http://semver.org/
- Từ ngày 09 tháng 02 năm 2016, phiên bản bắt đầu là "1.0.0"
- Mỗi 28 ngày, MAJOR lại tăng thêm 1, MINOR và PATCH set về 0
- Mỗi 7 ngày, MINOR tăng thêm 1 và PATCH sẽ set về 0
- Cứ mỗi ngày, PATCH lại tăng thêm 1.

In ra phiên bản tương ứng.

Gợi ý: học viên sử dụng `sys.argv` hoặc module `argparse`
'''

import log
import sys
from datetime import datetime
from datetime import timedelta
logger = log.get_logger(__name__)

def your_function(input_data):  # gia su nhan vao: "02/03/16", "09/06/16"
    '''Trả về tên phiên bản như yêu cầu tại ``__doc__``

    :param input_data: ngày format ở dạng <month>/<day>/<year>,
                       ví dụ: "02/03/16"
    :rtype str:
    '''
    # Sửa tên và function cho phù hợp, trả về kết quả yêu cầu.
    result = None

    begin_day = '02/09/16'  # => version: 1.0.0
    begin_day = datetime.strptime(begin_day, '%m/%d/%y')
    # tim day co version 0.0.0
    delta_time = timedelta(28)
    zero_version_day = begin_day - delta_time  # => version: 0.0.0

    # convert the input_data to format
    current_version_day = datetime.strptime(input_data, '%m/%d/%y')

    # calculate the changed version:
    number_version_changed = 0
    number_version_changed = (current_version_day - zero_version_day).days + 1

    patch = 0
    minor = 0
    major = 0

    day_minor = 0
    day_major = 0

    for i in range(1, number_version_changed):
        day_minor += 1
        day_major += 1
        patch += 1

        if day_minor % 7 == 0:
            minor += 1
            patch = 0
            # day_minor = 1
        if day_major % 28 == 0:
            major += 1
            minor = 0
            patch = 0
            # day_major = 1

    result = '{}.{}.{}'.format(major, minor, patch)

    return result

def solve(input_data):

    '''Function `solve` dùng để `test`, học viên không cần chỉnh sửa gì thêm
    Chỉ thay đổi lại tên function của mình bên dưới cho phù hợp

    Gía trị trả về của hàm `solve` và `your_function` là như nhau

    :rtype str:
    '''
    result = your_function(input_data)
    # Xoá dòng sau và viết code vào đây set các giá trị phù hợp

    return result

def main():
    input_data = None

    # sử dụng `sys.argv` hoặc `argparse` để gán gía trị yêu cầu
    # vào biến `input_data`
    # Xoá dòng sau và viết code vào đây set các giá trị phù hợp
    input_data = sys.argv[1]
    # input_data = "02/03/16"

    logger.debug("Getting version for the day %s", input_data)
    print(input_data, solve(input_data))

    for d in "02/03/16", "09/06/16", "06/23/17":
        print(d, solve(d))

if __name__ == "__main__":
    main()


import dash
from dash import html, dcc, MATCH, ALL, Input, Output, State
import dash_bootstrap_components as dbc
import pandas as pd
from PIL import Image
import dash_auth
import csv

VALID_USERNAME_PASSWORD_PAIRS = {}

with open('users.csv', mode='r') as file:
    reader = csv.reader(file)
    next(reader)
    for row in reader:
        username, password = row
        VALID_USERNAME_PASSWORD_PAIRS[username] = password

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.SKETCHY])

auth = dash_auth.BasicAuth(
    app,
    VALID_USERNAME_PASSWORD_PAIRS
)

tasks = pd.read_csv('tasks.csv')
courses = tasks['Course'].unique()
initial_course = courses[0]
initial_tasks = tasks[tasks['Course'] == initial_course]
pil_img = Image.open("download.png")

header = dbc.Navbar(
    dbc.Container([
        dbc.NavbarBrand('LEARNING MANAGEMENT SYSTEM', className='text-info'),
        html.A(dbc.NavbarBrand(html.Img(src=pil_img, height='30px'), className='ml-auto'), href='https://www.blend360.com/', style={'color': 'blue'}, target='_blank')
    ], fluid=True, style={'display': 'flex', 'justify-content': 'space-between', 'align-items': 'center'}),
    color='light',
    light=True,
    className='mt-3'
)

footer = dbc.Container([
    dbc.Row([
        dbc.Col(['COPYRIGHT © 2023 | DEVELOPED BY ', html.A('Mdadilfarooq', href='https://github.com/Mdadilfarooq/', style={'color': 'blue'}, target='_blank')])
    ], justify='center', className='py-3')
], fluid=True, className='bg-light')

app.layout = html.Div([
    header,
    html.Hr(),
    html.Div(id='progress-container'),
    html.Hr(),
    dcc.Dropdown(
        id={'type': 'course-dropdown', 'index': 0},
        options=[{'label': course, 'value': course} for course in courses],
        clearable=False,
        value=courses[0],
        persistence=True,
        ),
    html.Hr(),
    html.Div(id={'type': 'table-container', 'index': 0}),
    dbc.Button(
        'SHOW | UPDATE PROGRESS',
        id={'type': 'update-button', 'index': 0},
        className="btn btn-info float-end",
        n_clicks=None
    ),
    dbc.Toast(
        "YOUR PROGRESS HAS BEEN RECORDED",
        id="popup",
        header="BLEND360 | LMS",
        is_open=False,
        icon='info',
        duration=3000,
        style={"position": "fixed", "top": 10, "right": 10, "width": 350}
    ),
    footer
    ],className='container')

@app.callback(
    Output({'type': 'table-container', 'index': MATCH}, 'children'),
    Input({'type': 'course-dropdown', 'index': MATCH}, 'value'),
)
def display_tasks(course):
    tasks = pd.read_csv('tasks.csv')
    course_tasks = tasks[tasks['Course'] == course]
    return dbc.Table([
        html.Thead([html.Tr([html.Th('TASK'), html.Th('COMPLETION')])]),
        html.Tbody([
            html.Tr(
                [
                    html.Td(html.A(f'{task}', href=f'{url}', style={'color': 'blue'}, target='_blank')),
                    html.Td(
                        dcc.Slider(
                            id={'type': 'slide', 'index': idx},
                            value=value,
                            min=0,
                            max=3,
                            step=1
                        )
                    )
                ]
            )
            for idx, task, url, value in zip(
                range(len(course_tasks['Task'])),
                course_tasks['Task'],
                course_tasks['URL'],
                course_tasks['Completion']
            )
        ])
    ],
    className='mt-3 mb-3',
    striped=True
    )

@app.callback(
    Output('popup', 'is_open'),
    Output('progress-container', 'children'),
    Input({'type': 'update-button', 'index': ALL}, 'n_clicks'),
    State({'type': 'course-dropdown', 'index': ALL}, 'value'),
    State({'type': 'slide', 'index': ALL}, 'value'),
    prevent_initial_call=True
)
def update_tasks(update_click, drop_value, slide_values):
    df = tasks[tasks['Course'] == drop_value[0]]
    df['Completion'] = slide_values
    tasks.update(df)
    tasks.to_csv('tasks.csv', index=False)
    progress = (sum(tasks['Completion'])/(len(tasks)*3))*100
    return True, dbc.Progress(
        label='{0:.2f} %'.format(progress),
        value=progress,
        id="progress",
        color='info',
        animated=True,
        striped=True,
        style={"height": "30px"}
        )

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


from typing import List
import pandas as pd
import numpy as np
import math
import mgrs
import sys

from tqdm import tqdm
from scipy.spatial.transform import Rotation as R
from decimal import Decimal, ROUND_HALF_UP

def xyz2enu(ecef_xyz,org_xyz):
    org_llh = xyz2llh(org_xyz)
    phi = org_llh[0]
    lam = org_llh[1]
    sinphi = np.sin(phi)
    cosphi = np.cos(phi)
    sinlam = np.sin(lam)
    coslam = np.cos(lam)
    R = np.matrix([[-sinlam , coslam , 0],[-sinphi*coslam , -sinphi*sinlam , cosphi],[cosphi*coslam  , cosphi*sinlam , sinphi]])

    set_enu_data: List[float] = []
    for i in range(len(ecef_xyz)):
        if ecef_xyz['ecef_x'][i] == 0 and ecef_xyz['ecef_y'][i] == 0:
            set_enu_data.append([0,0,0])
            continue
        diff_xyz = np.array([[ecef_xyz['ecef_x'][i] - org_xyz[0]] , [ecef_xyz['ecef_y'][i] - org_xyz[1]] , [ecef_xyz['ecef_z'][i] - org_xyz[2]]])
        enu = R * diff_xyz
        x: float = float(enu[0])
        y: float = float(enu[1])
        z: float = float(enu[2])
        set_enu_data.append([x,y,z])
    set_enu = pd.DataFrame(set_enu_data,columns=['x','y','z'])
    return set_enu

def xyz2llh(xyz):
    x = xyz[0]
    y = xyz[1]
    z = xyz[2]
    x2 = x**2
    y2 = y**2
    z2 = z**2

    a = 6378137.0000    # earth radius in meters
    b = 6356752.3142    # earth semiminor in meters
    e = (1-(b/a)**2)**0.5
    b2 = b*b
    e2 = e**2
    ep = e*(a/b)
    r = (x2+y2)**0.5
    r2 = r*r
    E2 = a**2 - b**2
    F = 54*b2*z2
    G = r2 + (1-e2)*z2 - e2*E2
    c = (e2*e2*F*r2)/(G*G*G)
    s = ( 1 + c + (c*c + 2*c)**0.5 )**(1/3)
    P = F / (3 * (s+1/s+1)**2 * G*G)
    Q = (1+2*e2*e2*P)**0.5
    ro = -(P*e2*r)/(1+Q) + ((a*a/2)*(1+1/Q) - (P*(1-e2)*z2)/(Q*(1+Q)) - P*r2/2) ** 0.5
    tmp = (r - e2*ro)**2
    U = ( tmp + z2 )**0.5
    V = ( tmp + (1-e2)*z2 )**0.5
    zo = (b2*z)/(a*V)

    height = U*( 1 - b2/(a*V) )

    lat = math.atan( (z + ep*ep*zo)/r )
    temp = math.atan(y/x)
    if x >=0:
        long = temp
    elif (x < 0) & (y >= 0):
        long = math.pi + temp
    else:
        long = temp - math.pi

    llh = [lat,long,height]
    return llh

def llh2xyz(llh):
    set_xyz_data: List[float] = []
    for i in range(len(llh)):
        lat = llh['latitude'][i]
        lon = llh['longitude'][i]
        ht = llh['altitude'][i]

        PI_180 = math.pi / 180.0
        A      = 6378137.0
        ONE_F  = 298.257223563
        E2     = (1.0 / ONE_F) * (2 - (1.0 / ONE_F))

        n = lambda x: A / \
            math.sqrt(1.0 - E2 * math.sin(x * PI_180)**2)
        x = (n(lat) + ht) \
            * math.cos(lat * PI_180) \
            * math.cos(lon * PI_180)
        y = (n(lat) + ht) \
            * math.cos(lat * PI_180) \
            * math.sin(lon * PI_180)
        z = (n(lat) * (1.0 - E2) + ht) \
            * math.sin(lat * PI_180)
        set_xyz_data.append([x,y,z])
    set_xyz = pd.DataFrame(set_xyz_data,columns=['ecef_x','ecef_y','ecef_z'])
    return set_xyz

def change_anglel_limit(heading):
    set_output: List[float] = []
    for i in range(len(heading)):
        heading_tmp = heading[i]
        while heading_tmp < -math.pi or math.pi < heading_tmp:
            if heading_tmp < -math.pi:
                heading_tmp += math.pi * 2
            else:
                heading_tmp -= math.pi * 2
        set_output.append(heading_tmp)
    output = pd.DataFrame(set_output,columns=['yaw'])
    return output

def xyz2enu_vel(vel,org_xyz):
    set_vel_data: List[float] = []
    for i in range(len(vel)):
        x_vel = vel['vel_x'][i]
        y_vel = vel['vel_y'][i]
        z_vel = vel['vel_z'][i]

        org_llh = xyz2llh(org_xyz)
        phi = org_llh[0]
        lam = org_llh[1]

        sin_phi = math.sin(phi)
        cos_phi = math.cos(phi)
        sin_lam = math.sin(lam)
        cos_lam = math.cos(lam)

        e_vel = (-x_vel * sin_lam) + (y_vel * cos_lam)
        n_vel = (-x_vel * cos_lam * sin_phi) - (y_vel * sin_lam * sin_phi) + (z_vel * cos_phi)
        u_vel = (x_vel * cos_lam * cos_phi) +( y_vel * sin_lam * cos_phi) + (z_vel * sin_phi)
        vel_2d = (e_vel ** 2 + n_vel ** 2) ** 0.5

        set_vel_data.append([e_vel,n_vel,u_vel,vel_2d])
    df = pd.DataFrame(set_vel_data,columns=['east_vel','north_vel','up_vel','velocity'])
    return df

def calc_dopplor_heading(vel):
    heading = np.degrees(np.arctan2(vel['east_vel'], vel['north_vel']))
    df = pd.DataFrame(heading,columns=['yaw'])
    return df

def ll2mgrs(llh):
    set_mgrs: List[float] = []
    m = mgrs.MGRS()
    for i in range(len(llh)):
        ll = (llh['latitude'][i], llh['longitude'][i] , 4)
        coords = m.toMGRS(*ll)
        zone, x, y = coords[:5], float(coords[5:10]), float(coords[10:])
        height = llh['altitude'][i]
        set_mgrs.append([x,y,height])
    xyz = pd.DataFrame(set_mgrs,columns=['x','y','z'])
    return xyz

def calc_distance_vel(velocity, time):
    last_distance = 0
    set_distance: List[float] = []
    for i in range(len(time)):
        if i == 0:
            last_time = time.iloc[i]
            continue
        distance = last_distance + velocity.iloc[i] * (time.iloc[i] - last_time)
        last_time = time.iloc[i]
        last_distance = distance
        set_distance.append([distance])
    distance = pd.DataFrame(set_distance,columns=['distance'])
    return distance

def calc_distance_xy(xy):
    last_distance = 0
    set_distance: List[float] = []
    for i in range(len(xy)):
        if i == 0:
            distance = 0
        else:
            distance = last_distance + (((xy.iloc[i]['x']-xy.iloc[i-1]['x']) ** 2) + (xy.iloc[i]['y']-xy.iloc[i-1]['y']) ** 2)** 0.5
            last_distance = distance
        set_distance.append([distance])
    distance = pd.DataFrame(set_distance,columns=['distance'])
    return distance

def sync_time(ref_data,csv_data,sync_threshold_time,leap_time): # Time synchronization
    sync_index = np.zeros(len(csv_data['TimeStamp']))

    set_target_index: List[float] = []
    set_ref_index: List[float] = []

    if ref_data['TimeStamp'][0] >  csv_data['TimeStamp'][0]:
        csv_data = csv_data[csv_data['TimeStamp'] > ref_data['TimeStamp'][0] - sync_threshold_time]
        csv_data = csv_data.reset_index(drop=True)
    else:
        ref_data = ref_data[ref_data['TimeStamp'] > csv_data['TimeStamp'][0] - sync_threshold_time]
        ref_data = ref_data.reset_index(drop=True)

    if len(csv_data) == 0 or len(ref_data) == 0:
        print("[ERROR] Target time and ref time ranges do not match.")
        sys.exit(1)

    if ref_data.iloc[-1]['TimeStamp'] < csv_data.iloc[-1]['TimeStamp']:
        csv_data = csv_data[csv_data['TimeStamp'] < ref_data.iloc[-1]['TimeStamp'] + sync_threshold_time]
        csv_data = csv_data.reset_index(drop=True)
    else:
        ref_data = ref_data[ref_data['TimeStamp'] < csv_data.iloc[-1]['TimeStamp'] + sync_threshold_time]
        ref_data = ref_data.reset_index(drop=True)

    if len(csv_data) == 0 or len(ref_data) == 0:
        print("[ERROR] Target time and ref time ranges do not match.")
        sys.exit(1)

    sync_ref_time_tmp = ref_data['TimeStamp']

    num = 0
    len_drop_num = 0
    for i in range(len(csv_data)):
        if i == 0: continue
        time_tmp: List[float] = []
        time_tmp = csv_data.iloc[i]['TimeStamp']-sync_ref_time_tmp + leap_time
        sync_index[i] = np.argmin(abs(time_tmp))
        sync_time_tmp = time_tmp[sync_index[i]]
        if sync_time_tmp < sync_threshold_time:
            tmp_num = int(sync_index[i])
            set_target_index.append(i)
            num = num + len_drop_num
            drop_num = list(range(0,tmp_num - len_drop_num - 1,1))
            if not drop_num == None:
                sync_ref_time_tmp = sync_ref_time_tmp.drop(drop_num, axis=0)
                len_drop_num = len(drop_num)
                sync_ref_time_tmp = sync_ref_time_tmp.reset_index(drop=True)
            set_ref_index.append(num)

    data_df_output = csv_data.iloc[set_target_index]
    data_df_output = data_df_output.reset_index(drop=True)
    data_df_output['elapsed_time'] = data_df_output['TimeStamp'] - data_df_output['TimeStamp'][0]
    ref_df_output = ref_data.iloc[set_ref_index]
    ref_df_output = ref_df_output.reset_index(drop=True)
    ref_df_output['elapsed_time'] = ref_df_output['TimeStamp'] - ref_df_output['TimeStamp'][0]

    return ref_df_output , data_df_output

def calc_error_xyz(elapsed_time,ref_time,eagleye_time,ref_xyz,data_xyz,ref_yaw):
    error_xyz = pd.DataFrame()
    error_xyz['elapsed_time'] = elapsed_time
    error_xyz['TimeStamp'] = ref_time - eagleye_time
    error_xyz['x'] = data_xyz['x'] - ref_xyz['x']
    error_xyz['y'] = data_xyz['y'] - ref_xyz['y']
    error_xyz['z'] = data_xyz['z'] - ref_xyz['z']
    error_xyz['2d'] = (error_xyz['x']**2 + error_xyz['y']**2)**0.5

    set_aa: List[float] = []
    for i in range(len(ref_yaw)):
        across =  error_xyz.iloc[i]['x'] * math.cos(math.radians(ref_yaw[i])) - error_xyz.iloc[i]['y'] * math.sin(math.radians(ref_yaw[i]))
        along =  error_xyz.iloc[i]['x'] * math.sin(math.radians(ref_yaw[i])) + error_xyz.iloc[i]['y'] * math.cos(math.radians(ref_yaw[i]))
        set_aa.append([across,along])
    error_aa = pd.DataFrame(set_aa,columns=['across','along'])

    error = pd.concat([error_xyz,error_aa],axis=1)
    return error

def calc_TraRate(diff_2d , eval_step_max): # Calculation of error , x_label , ErrTra_Rate rate
    ErrTra_cnt: List[int] = []
    set_ErrTra_middle: List[float] = []
    set_ErrTra: List[float] = []
    ErrTra_cnt = len(diff_2d)

    step = 0.01
    eval_step_middle = 0.1
    for i in np.arange(0, eval_step_middle, step):
        cnt = 0
        eval_step = i
        for data in diff_2d:
            if data < eval_step:
                cnt = cnt + 1
        rate = cnt / ErrTra_cnt
        set_ErrTra_middle.append([eval_step,rate,rate *100])
    ErrTra_Rate_middle = pd.DataFrame(set_ErrTra_middle,columns=['x_label','ErrTra_Rate','ErrTra'])

    step = 0.1
    for i in np.arange(eval_step_middle, eval_step_max, step):
        cnt = 0
        eval_step = i
        for data in diff_2d:
            if data < eval_step:
                cnt = cnt + 1
        rate = cnt / ErrTra_cnt
        set_ErrTra.append([eval_step,rate,rate *100])
    ErrTra_Rate_tmp = pd.DataFrame(set_ErrTra,columns=['x_label','ErrTra_Rate','ErrTra'])
    ErrTra_Rate = pd.concat([ErrTra_Rate_middle,ErrTra_Rate_tmp])
    return ErrTra_Rate

def quaternion_to_euler_zyx(ori):
    set_eular_angle: List[float] = []
    for i in range(len(ori)):
        q = [ori.iloc[i]['ori_x'],ori.iloc[i]['ori_y'],ori.iloc[i]['ori_z'],ori.iloc[i]['ori_w']]
        r = R.from_quat([q[0], q[1], q[2], q[3]])
        roll = r.as_euler('ZYX', degrees=True)[2]
        pitch = r.as_euler('ZYX', degrees=True)[1]
        yaw = r.as_euler('ZYX', degrees=True)[0]
        set_eular_angle.append([roll,pitch,yaw])
    euler_angle = pd.DataFrame(set_eular_angle,columns=['roll','pitch','yaw'])
    return euler_angle

def calc_error_rpy(ref_angle,eagleye_angle):
    error_rpy = pd.DataFrame()
    error_rpy['roll'] = eagleye_angle['roll'] - ref_angle['roll']
    error_rpy['pitch'] = eagleye_angle['pitch'] - ref_angle['pitch']
    error_rpy['yaw'] = eagleye_angle['yaw'] - ref_angle['yaw']
    for i in range(len(error_rpy)):
        if error_rpy['yaw'][i] > math.degrees(math.pi):
            error_rpy['yaw'][i] = error_rpy['yaw'][i] - 2 * math.degrees(math.pi)
        elif error_rpy['yaw'][i] < -math.degrees(math.pi):
            error_rpy['yaw'][i] = error_rpy['yaw'][i] + 2 * math.degrees(math.pi)
    return error_rpy

def calc_velocity(vel):
    velocity = pd.DataFrame()
    velocity['velocity'] = (vel['vel_x'] ** 2 + vel['vel_y'] ** 2 + vel['vel_z'] ** 2) ** 0.5
    return velocity

def calc_velocity_error(eagleye_velocity,ref_velocity):
    error_velocity = pd.DataFrame()
    error_velocity['velocity'] = eagleye_velocity - ref_velocity
    return error_velocity

def calc_dr(TimeStamp,distance,eagleye_vel_xyz,ref_xyz,distance_length,distance_step):
    last_distance = 0
    set_dr_trajcetory: List[float] = []
    set_calc_error: List[float] = []
    for i in range(len(TimeStamp)):
        if i == 0: continue
        if last_distance + distance_step < distance[i]:
            start_distance = distance[i]
            start_pos_x = ref_xyz['x'][i]
            start_pos_y = ref_xyz['y'][i]
            previous_pos_x = 0
            previous_pos_y = 0
            last_distance = start_distance
            last_time = TimeStamp[i]
            for j in range(i,len(TimeStamp)):
                if eagleye_vel_xyz['vel_x'][j] == 0 and eagleye_vel_xyz['vel_y'][j] == 0:
                    last_time = TimeStamp[j]
                    distance_data = distance[j] - start_distance
                    absolute_pos_x = ref_xyz['x'][j] - start_pos_x
                    absolute_pos_y = ref_xyz['y'][j] - start_pos_y
                    continue
                if distance[j] - start_distance < distance_length:
                    dr_pos_x = previous_pos_x + eagleye_vel_xyz['vel_x'][j] * (TimeStamp[j] - last_time)
                    dr_pos_y = previous_pos_y + eagleye_vel_xyz['vel_y'][j] * (TimeStamp[j] - last_time)
                    previous_pos_x = dr_pos_x
                    previous_pos_y = dr_pos_y
                    last_time = TimeStamp[j]
                    distance_data = distance[j] - start_distance
                    absolute_pos_x = ref_xyz['x'][j] - start_pos_x
                    absolute_pos_y = ref_xyz['y'][j] - start_pos_y
                    absolute_dr_pos_x = start_pos_x + dr_pos_x
                    absolute_dr_pos_y = start_pos_y + dr_pos_y
                    set_dr_trajcetory.append([absolute_dr_pos_x,absolute_dr_pos_y])
                else:
                    error_x = absolute_pos_x - dr_pos_x
                    error_y = absolute_pos_y - dr_pos_y
                    error_2d_fabs = math.fabs(error_x ** 2 + error_y ** 2)
                    error_2d= math.sqrt(error_2d_fabs)
                    set_calc_error.append([start_distance,distance_data,absolute_pos_x,dr_pos_x,absolute_pos_y,dr_pos_y,error_x,error_y,error_2d])
                    break
    calc_error = pd.DataFrame(set_calc_error,columns=['start_distance','distance','absolute_pos_x','absolute_pos_y','dr_pos_x','dr_pos_y','error_x','error_y','error_2d'])
    dr_trajcetory = pd.DataFrame(set_dr_trajcetory,columns=['x','y'])
    return calc_error,dr_trajcetory

def calc_dr_twist(TimeStamp,distance,twist_data,ref_heading,ref_xyz,distance_length,distance_step,based_heaing_angle):
    last_distance = 0
    last_heading_integtation = 0
    set_dr_trajcetory: List[float] = []
    set_calc_error: List[float] = []
    for i in range(len(TimeStamp)):
        if i == 0: continue
        if last_distance + distance_step < distance[i]:
            data_set_flag = True
            start_distance = distance[i]
            start_pos_x = ref_xyz['x'][i]
            start_pos_y = ref_xyz['y'][i]
            previous_pos_x = 0
            previous_pos_y = 0
            last_distance = start_distance
            last_time = TimeStamp[i]
            for j in range(i,len(TimeStamp)):
                if data_set_flag == True:
                    last_time = TimeStamp[j]
                    last_heading_integtation = ref_heading[j]
                    distance_data = distance[j] - start_distance
                    absolute_pos_x = ref_xyz['x'][j] - start_pos_x
                    absolute_pos_y = ref_xyz['y'][j] - start_pos_y
                    data_set_flag = False
                    continue
                else:
                    heading_integtation = last_heading_integtation + twist_data['angular_z'][j] * (TimeStamp[j] - last_time)
                    if based_heaing_angle == True:
                        usr_vel_x = math.sin(heading_integtation) * twist_data['velocity'][j]
                        usr_vel_y = math.cos(heading_integtation) * twist_data['velocity'][j]
                    else:
                        usr_vel_x = math.cos(heading_integtation) * twist_data['velocity'][j]
                        usr_vel_y = math.sin(heading_integtation) * twist_data['velocity'][j]
                if distance[j] - start_distance < distance_length:
                    dr_pos_x = previous_pos_x + usr_vel_x * (TimeStamp[j] - last_time)
                    dr_pos_y = previous_pos_y + usr_vel_y * (TimeStamp[j] - last_time)
                    last_heading_integtation = heading_integtation
                    previous_pos_x = dr_pos_x
                    previous_pos_y = dr_pos_y
                    last_time = TimeStamp[j]
                    distance_data = distance[j] - start_distance
                    absolute_pos_x = ref_xyz['x'][j] - start_pos_x
                    absolute_pos_y = ref_xyz['y'][j] - start_pos_y
                    absolute_dr_pos_x = start_pos_x + dr_pos_x
                    absolute_dr_pos_y = start_pos_y + dr_pos_y
                    set_dr_trajcetory.append([absolute_dr_pos_x,absolute_dr_pos_y])
                else:
                    error_x = absolute_pos_x - dr_pos_x
                    error_y = absolute_pos_y - dr_pos_y
                    error_2d_fabs = math.fabs(error_x ** 2 + error_y ** 2)
                    error_2d= math.sqrt(error_2d_fabs)
                    set_calc_error.append([start_distance,distance_data,absolute_pos_x,dr_pos_x,absolute_pos_y,dr_pos_y,error_x,error_y,error_2d])
                    break
    calc_error = pd.DataFrame(set_calc_error,columns=['start_distance','distance','absolute_pos_x','absolute_pos_y','dr_pos_x','dr_pos_y','error_x','error_y','error_2d'])
    dr_trajcetory = pd.DataFrame(set_dr_trajcetory,columns=['x','y'])
    return calc_error,dr_trajcetory

def calc_dr_eagleye(TimeStamp,distance,eagleye_twist_data,ref_heading,ref_xyz,distance_length,distance_step,based_heaing_angle):
    last_distance = 0
    last_heading_integtation = 0
    velocity_stop_threshold = 0.01
    velocity_slip_threshold = 1
    set_dr_trajcetory: List[float] = []
    set_calc_error: List[float] = []
    for i in range(len(TimeStamp)):
        if i == 0: continue
        if last_distance + distance_step < distance[i]:
            data_set_flag = True
            start_distance = distance[i]
            start_pos_x = ref_xyz['x'][i]
            start_pos_y = ref_xyz['y'][i]
            previous_pos_x = 0
            previous_pos_y = 0
            last_distance = start_distance
            last_time = TimeStamp[i]
            for j in range(i,len(TimeStamp)):
                if data_set_flag == True:
                    last_time = TimeStamp[j]
                    last_heading_integtation = ref_heading[j]
                    distance_data = distance[j] - start_distance
                    absolute_pos_x = ref_xyz['x'][j] - start_pos_x
                    absolute_pos_y = ref_xyz['y'][j] - start_pos_y
                    data_set_flag = False
                    continue
                if eagleye_twist_data['velocity'][j] > velocity_stop_threshold:
                    heading_integtation = last_heading_integtation + (eagleye_twist_data['angular_z'][j] + eagleye_twist_data['yaw_rate_offset'][j]) * (TimeStamp[j] - last_time)
                else:
                    heading_integtation = last_heading_integtation + (eagleye_twist_data['angular_z'][j] + eagleye_twist_data['yaw_rate_offset_stop'][j]) * (TimeStamp[j] - last_time)
                if eagleye_twist_data['velocity'][j] > velocity_slip_threshold:
                    heading_correction_slip = heading_integtation + eagleye_twist_data['slip'][j]
                else:
                    heading_correction_slip = heading_integtation
                if distance[j] - start_distance < distance_length:
                    if based_heaing_angle == True:
                        usr_vel_x = math.sin(heading_correction_slip) * eagleye_twist_data['velocity'][j]
                        usr_vel_y = math.cos(heading_correction_slip) * eagleye_twist_data['velocity'][j]
                    else:
                        usr_vel_x = math.cos(heading_correction_slip) * eagleye_twist_data['velocity'][j]
                        usr_vel_y = math.sin(heading_correction_slip) * eagleye_twist_data['velocity'][j]
                    dr_pos_x = previous_pos_x + usr_vel_x * (TimeStamp[j] - last_time)
                    dr_pos_y = previous_pos_y + usr_vel_y * (TimeStamp[j] - last_time)
                    last_heading_integtation = heading_correction_slip
                    previous_pos_x = dr_pos_x
                    previous_pos_y = dr_pos_y
                    last_time = TimeStamp[j]
                    distance_data = distance[j] - start_distance
                    absolute_pos_x = ref_xyz['x'][j] - start_pos_x
                    absolute_pos_y = ref_xyz['y'][j] - start_pos_y
                    absolute_dr_pos_x = start_pos_x + dr_pos_x
                    absolute_dr_pos_y = start_pos_y + dr_pos_y
                    set_dr_trajcetory.append([absolute_dr_pos_x,absolute_dr_pos_y])
                else:
                    error_x = absolute_pos_x - dr_pos_x
                    error_y = absolute_pos_y - dr_pos_y
                    error_2d_fabs = math.fabs(error_x ** 2 + error_y ** 2)
                    error_2d= math.sqrt(error_2d_fabs)
                    set_calc_error.append([start_distance,distance_data,absolute_pos_x,dr_pos_x,absolute_pos_y,dr_pos_y,error_x,error_y,error_2d])
                    break
    calc_error = pd.DataFrame(set_calc_error,columns=['start_distance','distance','absolute_pos_x','absolute_pos_y','dr_pos_x','dr_pos_y','error_x','error_y','error_2d'])
    dr_trajcetory = pd.DataFrame(set_dr_trajcetory,columns=['x','y'])
    return calc_error,dr_trajcetory

def error_evaluation_each(error, elem):
    data_max = max(error[elem])
    data_average = np.average(error[elem])
    data_std = np.std(error[elem])
    data_rms = np.sqrt(np.square(error[elem]).mean(axis = 0))
    digits_num = '0.01'
    return [elem, \
           (Decimal(str(data_max)).quantize(Decimal(digits_num), rounding=ROUND_HALF_UP) ), \
           (Decimal(str(data_average)).quantize(Decimal(digits_num), rounding=ROUND_HALF_UP) ), \
           (Decimal(str(data_std)).quantize(Decimal(digits_num), rounding=ROUND_HALF_UP) ), \
           (Decimal(str(data_rms)).quantize(Decimal(digits_num), rounding=ROUND_HALF_UP) )]

def error_evaluation(error):
    x = error_evaluation_each(error, 'x')
    y = error_evaluation_each(error, 'y')
    z = error_evaluation_each(error, 'z')
    xy = error_evaluation_each(error, '2d')
    roll = error_evaluation_each(error, 'roll')
    pitch = error_evaluation_each(error, 'pitch')
    yaw = error_evaluation_each(error, 'yaw')
    error_table = pd.DataFrame([x, y, z, xy, roll, pitch, yaw], columns = ['data', 'max', 'average', 'std', 'rms'])
    return error_table


#!flask/bin/python
from flask import Flask, jsonify, request, abort
from flask_cors import CORS
import torch
from PIL import Image
from io import BytesIO
import base64
from torchvision import transforms
import torch.nn.functional as F
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('agg')

app = Flask(__name__)
CORS(app)

loss_fn = nn.CrossEntropyLoss()

model = torch.hub.load('pytorch/vision:v0.4.2', 'resnet34', pretrained=True)
model.eval()
preprocess = transforms.Compose([
    transforms.Resize(256),
    transforms.CenterCrop(224),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
trans = transforms.ToPILImage()
use_cuda = False
device = torch.device("cuda" if use_cuda else "cpu")

with open('imagenet1000_clsidx_to_labels.txt', 'r') as f:
    classes = eval(f.read())

def proj_grad_desc(x, y, model, step_size=0.05, epsilon=4 * 1/255, steps=50, target=None):
    adversary = x.clone().detach().requires_grad_(True).to(x.device)
    max_diff = x + epsilon
    min_diff = x - epsilon
    # actual_prob = []
    # target_prob = []
    # iters = []
    for i in range(steps + 1):
        curr = adversary.clone().detach().requires_grad_(True).to(adversary.device)
        output = model(curr)
        loss = loss_fn(output, target if target else y)
        prob_dist = torch.nn.functional.softmax(output[0], dim=0)
        # actual_prob.append(prob_dist[y].item())
        # target_prob.append(prob_dist[target].item())
        # iters.append(i)

        loss.backward()
        with torch.no_grad():
            curr_grad = curr.grad * step_size
            if target:
                adversary -= curr_grad
            else:
                adversary += curr_grad
        adversary = torch.max(torch.min(adversary, max_diff), min_diff)
    # plt.plot(iters, actual_prob, 'g-.', label='actual class: ' + classes[y.item()])
    # plt.plot(iters, target_prob, 'r-.',label='targeted class: ' + classes[target.item()])
    # plt.xlabel('step number')
    # plt.ylabel('% classification')
    # plt.legend(loc="upper left")
    # plt.savefig('analysis.png')
    return adversary.detach()

@app.route('/images', methods=['POST'])
def create_task():
    # print(request.json)
    if not request.json or 'content' not in request.json:
        abort(400)
    # parses request
    content = request.json['content']
    epsilon = float(request.json['epsilon'])
    step_size = float(request.json['step_size'])
    num_steps = int(request.json['num_steps'])
    target = int(request.json['target'])
    target = torch.tensor([target]) if target != -1 else None
    content = Image.open(BytesIO(base64.b64decode(content.split(',',1)[1])))
    json_obj = {}

    # Gets initial prediction on image
    input_tensor = preprocess(content).unsqueeze(0)

    output = model(input_tensor)
    prob_dist = torch.nn.functional.softmax(output[0], dim=0)
    init_prob, init_pred = prob_dist.topk(5)
    json_obj['init_prob'] = init_prob.tolist()
    json_obj['init_pred'] = init_pred.tolist()
    best_label = torch.tensor([init_pred[0]])

    # Getting adversarial image
    adv = proj_grad_desc(input_tensor, best_label, model, step_size=step_size, epsilon=epsilon, steps=num_steps, target=target)

    input_tensor[:, 0, :, :] = input_tensor[:, 0, :, :] * 0.229 + 0.485
    input_tensor[:, 1, :, :] = input_tensor[:, 1, :, :] * 0.224 + 0.456
    input_tensor[:, 2, :, :] = input_tensor[:, 2, :, :] * 0.225 + 0.406
    byteArr = BytesIO()
    trans(input_tensor.to('cpu')[0]).save(byteArr, format='JPEG')
    json_obj['orig_image'] = ('data:image/format;base64,' + base64.b64encode(byteArr.getvalue()).decode('ascii'))

    # Getting prediction on adversarial image
    output = model(adv)
    prob_dist = torch.nn.functional.softmax(output[0], dim=0)
    adv_prob, adv_pred = prob_dist.topk(5)
    json_obj['adv_prob'] = adv_prob.tolist()
    json_obj['adv_pred'] = adv_pred.tolist()

    adv[:, 0, :, :] = adv[:, 0, :, :] * 0.229 + 0.485
    adv[:, 1, :, :] = adv[:, 1, :, :] * 0.224 + 0.456
    adv[:, 2, :, :] = adv[:, 2, :, :] * 0.225 + 0.406

    byteArr = BytesIO()
    trans(adv.to('cpu')[0]).save(byteArr, format='JPEG')

    content = ('data:image/format;base64,' + base64.b64encode(byteArr.getvalue()).decode('ascii'))

    json_obj['adv_image'] = content
    # output = robust_model(adv)
    # prob_dist = torch.nn.functional.softmax(output[0], dim=0)
    # robust_prob, robust_pred = prob_dist.topk(5)
    # json_obj['robust_prob'] = robust_prob.tolist()
    # json_obj['robust_pred'] = robust_pred.tolist()

    return jsonify(json_obj), 200

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


#문제 설명
"""
입력: 여러 줄을 입력 받으므로 sys.stdin.readline 사용
+)한 줄에 점수 5개를 받으므로 끊어서 입력값을 받는 map 함수 사용
최고점과 최저점을 뺀 나머지 3명 점수
-> 리스트에 입력값 저장 후 오름차순으로 정렬/나머지 3명 점수 = x[1]~x[3]이 됨
나머지 3명 점수의 최고점과 최저점의 차이가 4점 이상 나게 되면 KIN 출력
-> x[3]-x[1]>=4일 경우 KIN 출력/조건문 사용
-> else: x[1]+x[2]+x[3]
"""

import sys

T = int(input())
for i in range(T):
    x = list(map(int,sys.stdin.readline().split()))
    #임의의 개수의 정수를 한줄에 입력받아 리스트에 저장할 때
    x.sort()
    if x[3]-x[1]>=4:
        print("KIN")
    else:
        print(x[1]+x[2]+x[3])

#input() 대신 sys.stdin.readline 쓰는 이유
#반복문으로 여러줄을 입력 받아야 할 때 시간초과가 발생할 수 있기 때문

#어렵거나 헷갈린 점 - 딱히 없음


from __future__ import print_function

from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

import Constants
import utils

def getMembersPaid(sheet) -> (list, list):
    data = sheet.values().get(spreadsheetId=Constants.SPREADSHEET_ID_FORM, range=Constants.FORM_DATA_RANGE).execute()
    data_values = data.get('values', [])

    if not data_values:
            print('No data found!')
            quit()

    paid_list = []

    for data_value in data_values:
        if data_value[Constants.FORM_TELE_ID][0] != '@':
            data_value[Constants.FORM_TELE_ID] = '@' + data_value[Constants.FORM_TELE_ID]

        person_name = data_value[Constants.FORM_NAME_ID].strip()
        person_year = ''
        person_tele = data_value[Constants.FORM_TELE_ID].strip().lower()
        person_date = data_value[Constants.FORM_DATE_ID]

        if ' ' in data_value[Constants.FORM_YEAR_ID].strip():
            person_year = data_value[Constants.FORM_YEAR_ID].strip().split(" ")[1]
        else:
            person_year = data_value[Constants.FORM_YEAR_ID].strip()

        paid_list.append([person_name, person_year, person_tele, person_date])

    return paid_list

def updateMembersPaid(sheet, paid_list, mon_idx, wed_idx) -> None:
    print("Updating Members Paid!")
    names = sheet.values().get(spreadsheetId=Constants.SPREADSHEET_ID_MASTER, range=Constants.MASTER_NAME_RANGE).execute()
    names_values = names.get('values', [])

    if not names_values:
        print('Tracking Sheet Name Empty!')
        quit()

    telegram_values = [i[Constants.MASTER_ID_TELE_LIST].lower().strip() for i in names_values]
    update_list = []

    for paid_value in paid_list:
        if paid_value[Constants.FORM_TELE_ID] in telegram_values:

            date_idx = []
            if paid_value[Constants.FORM_DATE_ID] == Constants.MON:
                date_idx = [mon_idx]
            elif paid_value[Constants.FORM_DATE_ID] == Constants.WED:
                date_idx = [wed_idx]
            else:
                date_idx = [mon_idx, wed_idx]

            for date in date_idx:
                member_idx_raw = telegram_values.index(paid_value[Constants.FORM_TELE_ID])
                member_idx = str(member_idx_raw + int(Constants.MASTER_DATA_START))
                member_date_range = Constants.MASTER_SHEET_NAME + "!" + date + member_idx + ":" + date + member_idx
                update_list.append({"range": member_date_range, "values": [[Constants.PAID]]})

                if len(names_values[member_idx_raw][Constants.FORM_NAME_ID]) == 0:
                    member_name_range = Constants.MASTER_SHEET_NAME + "!" + Constants.MASTER_ID_NAME + member_idx + ":" + Constants.MASTER_ID_NAME + member_idx
                    update_list.append({"range": member_name_range, "values": [[paid_value[Constants.FORM_NAME_ID]]]})

                if len(names_values[member_idx_raw][Constants.FORM_YEAR_ID]) == 0:
                    member_year_range = Constants.MASTER_SHEET_NAME + "!" + Constants.MASTER_ID_YEAR + member_idx + ":" + Constants.MASTER_ID_YEAR + member_idx
                    update_list.append({"range": member_year_range, "values": [[paid_value[Constants.FORM_YEAR_ID]]]})

        else:
            print(paid_value[Constants.FORM_TELE_ID] + " not in list!")

    update_values_request = {
        "valueInputOption": "USER_ENTERED",
        "data": update_list,
    }

    sheet.values().batchUpdate(
        spreadsheetId=Constants.SPREADSHEET_ID_MASTER,
        body=update_values_request,
    ).execute()

def main() -> None:
    creds = utils.auth()

    nextMon = utils.next_weekday(0)
    nextWed = utils.next_weekday(2)

    try:
        service = build('sheets', 'v4', credentials=creds)
        # Call the Sheets API
        sheet = service.spreadsheets()

        paid_list = getMembersPaid(sheet)
        monIdx = utils.parseColumnByDate(sheet, nextMon)
        wedIdx = utils.parseColumnByDate(sheet, nextWed)

        updateMembersPaid(sheet, paid_list, monIdx, wedIdx)

    except HttpError as err:
        print(err)

    print("Finished! Cleaning up...")

if __name__ == '__main__':
    main()


import time

import pytest
from selenium.webdriver.common.action_chains import ActionChains

from ui.steps import support_steps
from ui.pages.locators import *
from ui.pages.main_page import MainPage

@pytest.mark.parametrize('region',
                         [
                             'Московская',
                             'Ростов',
                             'Ростовская об',
                             'РоСт',
                             'карелия'
                         ],
                         ids=['Moscow', 'Rostov', 'Part of region', 'CamelCase', 'region']
                         )
def test_check_geoposition(driver, region):
    page = MainPage(driver, 'http://www.sberbank.ru/')
    # Открываем страницу
    page.open()
    # Нажимаем на смену региона
    page.geoposition_link()
    # Вводим название региона
    page.fill_text_region_name_field(region)
    # Нажимаем на найденный регион
    page.click_on_region_name(region)
    # Проверяем изменение региона
    page.assert_region_name_in_geo_link(region)

def test_exchange_rate_button(driver):
    page = MainPage(driver, 'http://www.sberbank.ru/')
    # Открываем страницу
    page.open()
    # Находим и проверяем наличие кнопки "Курсы валют"
    page.should_be_exchange_rate_link()
    # Кликаем по кнопке
    page.click_on_exchange_rate_link()
    # Проверяем, что мы на нужной странице
    page.assert_exchange_rate_title()

# Проверка функциональных кнопок хедера главной строницы
def test_sber_main(driver):
    try:
        # Переходим на главную страницу
        driver.get('http://www.sberbank.ru/')
        # Меняем язык
        driver.find_element.HEADER_LANGUAGE_CHANGE.click()
        time.sleep(1)
        # Возвращаем русский язык
        driver.find_element.HEADER_ENG_LANGUAGE_CHANGE.click()
        time.sleep(1)
        # Нажимаем на кнопку поиска
        driver.find_element.HEADER_SEARCH_BUTTON.click()
        # Ставим каретку в инзут поиска
        find_button = driver.find_element.HEADER_SEARCH_INPUTLINE
        find_button.click()
        # Вводим тестовый запрос
        find_button.send_keys(support_steps.generate_random_string(7))
        # Нажимаем на кнопку поиска
        driver.find_element.HEADER_SEARCH_FIND_BUTTON.click()
        time.sleep(1)
        driver.find_element.HEADER_SEARCH_BUTTON.click()
        find_button = driver.find_element.HEADER_SEARCH_INPUTLINE
        find_button.click()
        find_button.send_keys('')
        driver.find_elementHEADER_SEARCH_FIND_BUTTON.click()
        time.sleep(2)
    finally:
        driver.quit()

# Проверка изменения цвета кнопок при наведении курсора
def test_text_color_header_button(driver):
    try:
        # Переходим на главную страницу
        driver.get('http://www.sberbank.ru/')
        # Курсы валют
        button = driver.find_elementHEADER_EXCHANGE_RATE_BUTTON
        ActionChains(driver).move_to_element(button).perform()
        time.sleep(2)
        # Офисы
        button = driver.find_element.HEADER_OFFICES_BUTTON
        ActionChains(driver).move_to_element(button).perform()
        time.sleep(2)
        # Банкоматы
        button = driver.find_element.HEADER_ATMS_BUTTON
        ActionChains(driver).move_to_element(button).perform()
        time.sleep(2)
        # Смена региона
        button = driver.find_element.HEADER_REGION_CHANGE_BUTTON
        ActionChains(driver).move_to_element(button).perform()
        time.sleep(2)
        # Кнопка поиска
        button = driver.find_element.HEADER_SEARCH_BUTTON
        ActionChains(driver).move_to_element(button).perform()
        time.sleep(2)
    finally:
        driver.quit()

def test_sber_main_negative(driver):
    try:
        driver.get('http://www.sberbank.ru/')
        driver.find_element(By.XPATH, "(//test").click()
        time.sleep(1)
    finally:
        driver.quit()


import torch
import numpy as np
from torchvision import datasets
import torchvision.transforms as transforms
from torch.utils.data.sampler import SubsetRandomSampler
import matplotlib.pyplot as plt

# # 检查是否可以利用GPU
# train_on_gpu = torch.cuda.is_available()
#
# if not train_on_gpu:
#     print('CUDA is not available.')
# else:
#     print('CUDA is available!')

# number of subprocesses to use for data loading
num_workers = 0
# 每批加载16张图片
batch_size = 16
# percentage of training set to use as validation
valid_size = 0.2

# 将数据转换为torch.FloatTensor，并标准化。
transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
    ])

# 选择训练集与测试集的数据
train_data = datasets.CIFAR10('data', train=True,
                              download=True, transform=transform)
test_data = datasets.CIFAR10('data', train=False,
                             download=True, transform=transform)

# obtain training indices that will be used for validation
num_train = len(train_data)
indices = list(range(num_train))
np.random.shuffle(indices)
split = int(np.floor(valid_size * num_train))
train_idx, valid_idx = indices[split:], indices[:split]

# define samplers for obtaining training and validation batches
train_sampler = SubsetRandomSampler(train_idx)
valid_sampler = SubsetRandomSampler(valid_idx)

# prepare data loaders (combine dataset and sampler)
train_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size,
    sampler=train_sampler, num_workers=num_workers)
valid_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size,
    sampler=valid_sampler, num_workers=num_workers)
test_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size,
    num_workers=num_workers)

# 图像分类中10类别
classes = ['airplane', 'automobile', 'bird', 'cat', 'deer',
           'dog', 'frog', 'horse', 'ship', 'truck']


"""
utility for conversion.
"""
import re
import ast
import numpy as np
from sympy.parsing.sympy_parser import parse_expr, standard_transformations, implicit_multiplication, rationalize
from sympy import SympifyError, latex
from gcoreutils.basic_util import apply, get_variable
from gcoreutils.list_util import flatten

# ==================================================
def text_to_list(text):
    """
    convert single text to list.

    Args:
        text (str): text to convert.

    Returns:
        list or str: converted list.

    Notes:
        - if format error occurs, return None.
    """
    if not isinstance(text, str):
        return None

    lb = text.count("[")
    rb = text.count("]")
    if lb != rb:
        return None
    elif lb == 0 and rb == 0:
        return text

    text = re.sub(r"\s*\[\s*", "[", text)
    text = re.sub(r"\s*\]\s*", "]", text)

    text = text.replace("[", "['").replace("]", "']").replace(",", "','").replace("'[", "[").replace("]'", "]")
    try:
        lst = ast.literal_eval(text)
    except (SyntaxError, ValueError):
        return None

    return lst

# ==================================================
def text_to_sympy(text, local=None, check_var=None, rational=True):
    """
    convert single text to sympy list.

    Args:
        text (str): text to convert.
        local (dict, optional): variables to replace.
        check_var (set, optional): set of variables to accept.
        rational (bool, optional): replace floating number with rational one ?

    Returns:
        list or sympy: converted list.

    Notes:
        - if format error occurs, return None.
        - if an element cannot be converted to sympy, it becomes None.
    """
    lst = text_to_list(text)
    if lst is None:
        return None

    if check_var is None:
        check_var = []
    check_var = set(check_var)

    transformations = standard_transformations + (implicit_multiplication,)
    if rational:
        transformations += (rationalize,)

    def to_sympy(t):  # converter for each element.
        try:
            expression = parse_expr(t, transformations=transformations, local_dict=local)
        except (SympifyError, SyntaxError, TypeError):
            return None
        var = set(get_variable(expression))
        if len(check_var) != 0 and not (var <= check_var):
            return None

        return expression

    s = apply(to_sympy, lst)

    return s

# ==================================================
def is_valid_sympy(text, check_var=None):
    """
    check whether text is valid as sympy expression.

    Args:
        text (str): text to check.
        check_var (list, optional): acceptable variable strings. if None is given, do not check.

    Returns:
        bool: return True if valid.
    """
    try:
        lst = text_to_sympy(text, check_var=check_var)
    except Exception:
        return False
    lst = flatten(lst)
    if lst is None or (type(lst) == list and lst.count(None) > 0):
        return False
    else:
        return True

# ==================================================
def sympy_to_str(lst):
    """
    convert list to str list.

    Args:
        lst (list or ndarray or sympy): list to convert.

    Returns:
        list or str: converted list.

    Notes:
        - if an element cannot be converted to float, it becomes None.
    """
    if isinstance(lst, np.ndarray):
        lst = lst.tolist()

    def to_str(t):  # converter for each element.
        try:
            t = str(t)
        except TypeError:
            return None
        return t

    s = apply(to_str, lst)
    return s

# ==================================================
def sympy_to_float(lst):
    """
    convert list to float list.

    Args:
        lst (list or ndarray or sympy): list to convert.

    Returns:
        list or float: converted list.

    Notes:
        - if an element cannot be converted to float, it becomes None.
    """
    if isinstance(lst, np.ndarray):
        lst = lst.tolist()

    def to_float(t):  # converter for each element.
        try:
            t = float(t)
        except TypeError:
            return None
        return t

    s = apply(to_float, lst)
    return s

# ==================================================
def sympy_to_complex(lst):
    """
    convert list to complex list.

    Args:
        lst (list or ndarray or sympy): list to convert.

    Returns:
        list or complex: converted list.

    Notes:
        - if an element cannot be converted to complex, it becomes None.
    """
    if isinstance(lst, np.ndarray):
        lst = lst.tolist()

    def to_complex(t):  # converter for each element.
        try:
            t = complex(t)
        except TypeError:
            return None
        return t

    s = apply(to_complex, lst)
    return s

# ==================================================
def sympy_to_latex(lst):
    """
    convert list to latex list.

    Args:
        lst (list or ndarray or sympy): list to convert.

    Returns:
        list or str: converted list.

    Notes:
        - if an element cannot be converted to complex, it becomes None.
    """
    if isinstance(lst, np.ndarray):
        lst = lst.tolist()

    def to_latex(t):  # converter for each element.
        try:
            if t is not None:
                t = latex(t)
        except TypeError:
            return None
        return t

    s = apply(to_latex, lst)
    return s

# ==================================================
def sympy_to_mathematica(lst):
    """
    convert sympy to Mathematica. (simple version)

    Args:
        lst (list or ndarray or sympy): list to convert.

    Returns:
        list or str: converted list.

    Notes:
        - if an element cannot be converted to complex, it becomes None.
    """
    key_list = [  # (sympy, mathematica)
        ("sqrt", "Sqrt"),
        ("sin", "Sin"),
        ("cos", "Cos"),
        ("tan", "Tan"),
        ("exp", "Exp"),
        ("log", "Log"),
        ("pi", "Pi"),
        ("None", ""),
        ("[", "{"),
        ("]", "}"),
        ("(", "["),
        (")", "]"),
    ]

    if isinstance(lst, np.ndarray):
        lst = lst.tolist()

    def to_str(t):  # converter for each element.
        try:
            t = str(t)
        except TypeError:
            return None
        return t

    s = apply(to_str, lst)
    s = str(s).replace("'", "")

    for x in key_list:
        s = s.replace(*x)

    return s


# rotate 2d array x degrees
def rotate(arr: list, degree: int):
    # rotate 90 degrees
    degree = degree % 360
    if degree == 0:
        return arr
    if degree == 90:
        return list(zip(*arr[::-1]))
    if degree == 180:
        return arr[::-1]
    if degree == 270:
        return list(zip(*arr)[::-1])
    return arr

print(rotate([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 270))


import os
import multiprocessing

def main():
    import argparse
    import torch
    from utils.str2bool import str2bool
    from utils.inference import inference
    from utils.load_dataset import load_dataset
    from utils.save import TrainingState
    from utils.instantiate_model import instantiate_model

    parser = argparse.ArgumentParser(description='Train', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--dataset',                default='CIFAR10',      type=str,       help='Set dataset to use')
    parser.add_argument('--parallel',               default=False,          type=str2bool,  help='Device in  parallel')
    parser.add_argument('--test_batch_size',        default=512,            type=int,       help='Test batch size')
    parser.add_argument('--arch',                   default='resnet18',     type=str,       help='Network architecture')
    parser.add_argument('--suffix',                 default='erm_1_std_tinyimagenet',
                                                                            type=str,       help='Appended to model name')

    global args
    args = parser.parse_args()
    print(args)

    # Setup right device to run on
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

    # Use the following transform for training and testing
    print('\n')
    dataset = load_dataset(dataset=args.dataset,
                           test_batch_size=args.test_batch_size,
                           device=device,
                           val_split=0.1)

    # Instantiate model
    net, model_name = instantiate_model(dataset=dataset,
                                        arch=args.arch,
                                        suffix=args.suffix,
                                        device=device,
                                        path='./pretrained/',
                                        load=True)

    net.eval()
    test_correct, test_total, test_accuracy = inference(net=net, data_loader=dataset.test_loader, device=device)
    print(' Test set: Accuracy: {}/{} ({:.2f}%)'.format(test_correct, test_total, test_accuracy))

    train_correct, train_total, train_accuracy = inference(net=net, data_loader=dataset.train_loader, device=device)
    print(' Train set: Accuracy: {}/{} ({:.2f}%)'.format(train_correct, train_total, train_accuracy))

    val_correct, val_total, val_accuracy = inference(net=net, data_loader=dataset.val_loader, device=device)
    print(' Val set: Accuracy: {}/{} ({:.2f}%)'.format(val_correct, val_total, val_accuracy))

if __name__ == "__main__":
    if os.name == 'nt':
        # On Windows calling this function is necessary for multiprocessing
        multiprocessing.freeze_support()

    main()


import random
import math

# Run types
PROBETESTING  = 0
SAMPLETESTING = 1
FULLINPUTRUN  = 3
# Log levels
DEBUG     = 0
PROFILING = 1
INFO      = 2
WARNING   = 3
ERROR     = 4
SOLUTION  = 5

# -------------------------------------------------
# Global Configurations for the program and testing
# -------------------------------------------------
RunLevel                  = FULLINPUTRUN
FullInputFileName         = 'input.txt'
SampleInputFileName       = 'sample.txt'
PrintInput                = False
WriteRunResults           = True
RemoveEOLFromInputLines   = True
resultsOutputFileName     = 'out_1.txt'
LogPrintLevel             = SOLUTION
LogWriteLevel             = DEBUG
GenerateRandomInputSample = False
RandomSampleSize          = 500
# -------------------------------------------------

# ----------------------------------------------------
# Functions and globals specific to the current puzzle
# ----------------------------------------------------
def puzzleSolution(lines):

    departureTimestamp = int(lines[0])
    log(INFO, "Earliest departure time: " + str(departureTimestamp))
    strBusIDs = lines[1]
    log(DEBUG, strBusIDs)

    busIDs = getBusIDsFromStr(strBusIDs)
    log(DEBUG, "Bus IDs: " + str(busIDs))

    smallestTimestamps = []
    for busID in busIDs:
        smallestTimestamps.append(getSmallestTimestampForID(departureTimestamp, busID))

    #print("Smallest available bus ID : " + str(min(smallestTimestamps)))

    minutesToWait = min(smallestTimestamps) - departureTimestamp
    log(INFO, " Time to wait: " + str(minutesToWait))
    log(SOLUTION, "day 13 Part 1: TODO")
    pass

def getSmallestTimestampForID(departureTimestamp, busID):
    integerPart = math.ceil(departureTimestamp/busID)
    smallestTimestamp = busID * integerPart
    log(DEBUG, str(busID) + ": " + str(integerPart) + "->" + str(smallestTimestamp))
    return smallestTimestamp

def getBusIDsFromStr(strBusIDs):
    busIDs = []
    busIDsTokens = strBusIDs.rsplit(',')
    log(DEBUG, str(busIDsTokens))
    for token in busIDsTokens:
        if (token == 'x'):
            continue
        else:
            busIDs.append(int(token))
    return busIDs

# ------------------
# Global definitions
# ------------------
logStr = ""

def main():
    # Probe testing
    if (RunLevel == PROBETESTING):
        log(INFO, "******* Running Probe Testing")

    fileLines = readRawLines(RemoveEOLFromInputLines)

    if (GenerateRandomInputSample):
        fileLines = generateRandomInputSubset(fileLines)

    puzzleSolution(fileLines)

# Implement this function to write specific results to a text file
def writeRunResults(seatIDs):
    log(INFO, "******* Writing results to specified output file")
    s = ""
    for id in seatIDs:
        s += str(id) + "\n"

    with open(resultsOutputFileName, "w") as file:
        # Writing data to a file
        file.write(s)

# Implement this function. Currently only takes random lines.
def generateRandomInputSubset(input_lines):
    RandomLines = []
    for i in range(RandomSampleSize):
        RandomLines.append(random.choice(input_lines))

def readRawLines(stripEOL=False):

    if (RunLevel == SAMPLETESTING):
        filename = SampleInputFileName
    if (RunLevel == FULLINPUTRUN):
        filename = FullInputFileName

    log(INFO, "******* Reading from file " + filename)
    with open(filename,'r') as file:
        raw_lines = file.readlines()

    # remove EOL from lines
    stripped_lines = []
    for line in raw_lines:
        stripped_lines.append(line.rstrip('\n'))

    if (PrintInput):
        log(INFO, "******* Input:")
        for line in raw_lines:
            log(INFO, line.rstrip("\n"))
        log(INFO, "")
    log(INFO, "******* Read " + str(len(raw_lines)) + " lines.")

    if (stripEOL):
        return stripped_lines
    else:
        return raw_lines

def log(type, message):
    global logStr

    if (not type < LogPrintLevel):
        print(message)

    if (not type < LogWriteLevel):
        logStr += message + "\n"

def writeLogFile():
    global logStr
    log(INFO, "******* Writing results to run_logfile.txt.")
    with open("run_logfile.txt", "w") as file:
        # Writing data to a file
        file.write(logStr)

if __name__ == "__main__":
    main()
    writeLogFile()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 10 10:57:54 2020

@author: zhaoyu
"""

from SimGridWorld import GridWorld
from PG import Reinforce
import matplotlib.pyplot as plt

if __name__ == '__main__':
    print('Policy Graident Demo', '\n=======================')

    env = GridWorld()
    print('Init State: \n', env)
    pg = Reinforce(env, gamma=1)

    n_rollout = 1000
    g0 = pg.train(rollout=n_rollout, init_lr=2**-9)
    plt.plot(g0)


import pytesseract
from pdf2image import convert_from_path
import glob
from selenium import webdriver
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
import pandas as pd
from newspaper import Config, Article, Source
import newspaper
from selenium.webdriver.common.keys import Keys
import time

QUERY = "bayview"
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
driver = webdriver.Chrome('/Users/bocarwade/Downloads/chromedriver')
#driver.get(webiste)

def search(driver, query):
	driver.get("https://www.proquest.com/publication/46852?OpenUrlRefId=info:xri/sid:primo")
	driver.find_element_by_name("publicationQuery").send_keys(query)
	driver.find_element_by_name("publicationQuery").send_keys(Keys.RETURN)

def select_pages(driver):
	time.sleep(4)
	select = Select(driver.find_element_by_id('itemsPerPage'))
	select.select_by_value('100')

def get_links(driver):
	full_text_elems = driver.find_elements_by_link_text('Full text')
	full_text_links = []
	for elem in full_text_elems:
		full_text_links.append(elem.get_attribute('href'))
		collect_info(elem.get_attribute('href'))
		break
	return full_text_links

def collect_info(link):
	document = {}
	driver.get(link)
	text = driver.find_element_by_id('fullTextZone')
	paras = driver.find_elements_by_css_selector('p')
	text = ''
	for p in paras:
		text += p.text
	print(text)

def download_texts(links):
	for url in links:
		article = Article(url)
		title = article.title
		#author = article.author
		keywords = article.keywords
		print(title, keywords)
search(driver, "woodlawn")
select_pages(driver)
links = get_links(driver)
download_texts(links)

def convert_pdfs(path):
	pdfs = glob.glob(r"yourPath\*.pdf")
	for pdf_path in pdfs:
	    pages = convert_from_path(pdf_path, 500)
	    for pageNum,imgBlob in enumerate(pages):
	        text = pytesseract.image_to_string(imgBlob,lang='eng')
	        with open(f'{pdf_path[:-4]}_page{pageNum}.txt', 'w') as the_file:
	            the_file.write(text)


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

# In[1]:

import requests
from bs4 import BeautifulSoup
import pandas as pd
import datetime
import time
from hashlib import sha1
import hmac
from wsgiref.handlers import format_date_time
from datetime import datetime
from time import mktime
import base64

# In[2]:

app_id = '****'
app_key = '*****'
class Auth():

    def __init__(self, app_id, app_key):
        self.app_id = app_id
        self.app_key = app_key

    def get_auth_header(self):
        xdate = format_date_time(mktime(datetime.now().timetuple()))
        hashed = hmac.new(self.app_key.encode('utf8'), ('x-date: ' + xdate).encode('utf8'), sha1)
        signature = base64.b64encode(hashed.digest()).decode()

        authorization = 'hmac username="' + self.app_id + '", ' +                         'algorithm="hmac-sha1", ' +                         'headers="x-date", ' +                         'signature="' + signature + '"'
        return {
            'Authorization': authorization,
            'x-date': format_date_time(mktime(datetime.now().timetuple())),
            'Accept - Encoding': 'gzip'
        }

# In[4]:

city=['NewTaipei','Taoyuan','Taichung','Tainan','Kaohsiung','Keelung','Hsinchu','HsinchuCounty','MiaoliCounty','ChanghuaCounty'
,'NantouCounty','YunlinCounty','ChiayiCounty','Chiayi','PingtungCounty','YilanCounty','HualienCounty','TaitungCounty'
,'KinmenCounty','PenghuCounty','LienchiangCounty','Taipei']
Bike_allshape=pd.DataFrame(columns = ['路線名稱','業管機關名稱','路線所在縣市代碼',"路線所在縣市名稱"
                                   ,"路線所在鄉鎮名稱",'路線起點描述','路線迄點描述',"自行車道車行方向"
                                   ,"自行車道長度","自行車道完工日期時間","資料更新日期時間",'路線軌跡資料'])
for j in city:
    print(j)
    a = Auth(app_id, app_key)
    r=requests.get("https://ptx.transportdata.tw/MOTC/v2/Cycling/Shape/"+str(j)+"?$format=xml", headers= a.get_auth_header())
    r.close()
    soup = BeautifulSoup(r.text, "html.parser")
    #for i in soup.find_all('busstation'): #每次跑一個站的資料
    #print(soup.prettify())
        #print(j)
    #print(j)
    #for j in i.find_all("stops"):
    routename = [routename.text for routename in soup.find_all('routename')]
    authorityname = [authorityname.text for authorityname in soup.find_all('authorityname')]
    citycode = [citycode.text for citycode in soup.find_all('citycode')]
    city = [i.text for i in soup.find_all('city')]
    town = [town.text for town in soup.find_all('town')]
    roadsectionstart = [roadsectionstart.text for roadsectionstart in soup.find_all('roadsectionstart')]
    roadsectionend = [roadsectionend.text for roadsectionend in soup.find_all('roadsectionend')]
    Direction = [direction.text for direction in soup.find_all('direction')]

    cyclinglength = [cyclinglength.text for cyclinglength in soup.find_all('cyclinglength')]
    finishedtime = [i.text for i in soup.find_all('finishedtime')]
    updatetime = [i.text for i in soup.find_all('updatetime')]
    geometry = [geometry.text for geometry in soup.find_all('geometry')]
    #srcupdatetime = [srcupdatetime.text for srcupdatetime in soup.find_all('srcupdatetime')]
    #UpdateTime = [updatetime.text for updatetime in soup.find_all('updatetime')]
    #VersionID = [versionid.text for versionid in i.find_all('versionid')]

    Bike_shape={'路線名稱':routename,'業管機關名稱':authorityname,'路線所在縣市代碼':citycode
        ,"路線所在縣市名稱":city,"路線所在鄉鎮名稱":town,'路線起點描述':roadsectionstart
        ,'路線迄點描述':roadsectionend,"自行車道車行方向":Direction,"自行車道長度":cyclinglength
        ,"自行車道完工日期時間":finishedtime,"資料更新日期時間":updatetime,'路線軌跡資料':geometry}
    #print(Bus_information)
    Bike_shape = pd.DataFrame.from_dict(Bike_shape, orient='index')
    Bike_shape=Bike_shape.transpose()#把欄位顛倒過來
    Bike_allshape=Bike_allshape.append(Bike_shape)
    time.sleep(5)
    #print(Bike_shape)
    #break

# In[5]:

Bike_allshape.to_csv(r'C:\Users\指定縣市之自行車道路網圖資.txt', index=False,encoding="utf_8_sig" )

# In[ ]:

指定縣市之自行車道路網圖資.py

指定縣市之自行車道路網圖資.py


#!/usr/bin/env python3
# pylint: disable-msg=line-too-long,missing-module-docstring,missing-function-docstring,missing-class-docstring,no-else-return,invalid-name,multiple-statements,wrong-import-position

"""

# doctest
# old format defaults for test
>>> from EngineeringTools.quantities import qnt
>>> qnt.FORMAT_DEFAULT['totalWidth'] = 8
>>> qnt.FORMAT_DEFAULT['decimalPosition'] = 4
>>> qnt.FORMAT_DEFAULT['thousands_sep'] = ''
"""

__author__  = 'Martin Hochwallner <marthoch@users.noreply.github.com>'
__email__   = "marthoch@users.noreply.github.com"
__license__ = "BSD 3-clause"

# run doctest, workaround relative import
if __name__ == '__main__':
    import sys
    import doctest # pylint: disable=import-outside-toplevel
    from EngineeringTools import quantities as ETQ             # pylint: disable=reimported,import-outside-toplevel
    ETQ.Quantity.set_displayUnitSystem('mechanicalEngineering')
    module_name = 'EngineeringTools.tools.functions'      # pylint: disable=invalid-name
    module = __import__(module_name, fromlist=['*'], level=0)  # pylint: disable=invalid-name
    module._setup_doctest()                                    # pylint: disable=protected-access
    print(doctest.testmod(module, optionflags=doctest.ELLIPSIS))
    sys.exit()

# $Source$

from fractions import Fraction
import numpy as _np
from .. import quantities as ETQ

################################################################################
#  exceptions
################################################################################
class EngineeringTools_tools_Error(Exception):
    """Exception: tools"""

class EngineeringTools_tools_Error_units(EngineeringTools_tools_Error):
    """Exception: tools"""

################################################################################
#  constants
################################################################################
PI = ETQ.Scalar(_np.pi, '1.0', displayUnit='1.0')

################################################################################
# functions
################################################################################
def sin(angle):
    """ sin

    >>> angle = ETQ.Angle(30.0, 'deg')
    >>> print(angle)
      30.000 deg (Angle)
    >>> print(round(sin(angle.get_value('rad')), 3))
    0.5
    >>> sin(angle.get_uval())
    UVal(0.49999999999999..., {})
    >>> print(sin(angle.get_uval()))
    0.5000 {}
    >>> print(sin(angle))
       0.500  (Scalar)
    >>> print(sin(ETQ.Distance(0.5, 'm')))
    Traceback (most recent call last):
        ...
    EngineeringTools.tools.functions.EngineeringTools_tools_Error_units: wrong type : <class 'EngineeringTools.quantities.mechanics.Distance'>

    """
    if isinstance(angle, float):
        return _np.sin(angle)
    elif isinstance(angle, ETQ.UVal):
        angle.check_units({})
        return ETQ.UVal(_np.sin(angle.get_value()), {})
    elif isinstance(angle, ETQ.Angle):
        return ETQ.Scalar(_np.sin(angle.get_value()))
    else:
        raise EngineeringTools_tools_Error_units('wrong type : %s' % type(angle))

def arcsin(scalar):
    """ arcsin

    >>> scalar = ETQ.Scalar(0.5, '1.0')
    >>> print(scalar)
       0.500  (Scalar)
    >>> print(asin(scalar.get_value()))  # rad
    0.52359877559...
    >>> asin(scalar.get_uval())
    UVal(0.5235987755982989, {})
    >>> print(asin(scalar.get_uval()))
    0.5236 {}
    >>> a=asin(scalar); _ = a.set_displayUnit('deg'); print(a)
      30.000 deg (Angle)
    >>> print(asin(ETQ.Distance(0.5, 'm')))
    Traceback (most recent call last):
        ...
    EngineeringTools.tools.functions.EngineeringTools_tools_Error_units: wrong type : <class 'EngineeringTools.quantities.mechanics.Distance'>

    """
    if isinstance(scalar, float):
        return _np.arcsin(scalar)
    elif isinstance(scalar, ETQ.UVal):
        scalar.check_units({})
        return ETQ.UVal(_np.arcsin(scalar.get_value()), {})
    elif isinstance(scalar, ETQ.Scalar):
        return ETQ.Angle(_np.arcsin(scalar.get_value()), 'rad')
    else:
        raise EngineeringTools_tools_Error_units('wrong type : %s' % type(scalar))

asin = arcsin   # compatibility with math module

def cos(angle):
    """ cos

    >>> angle = ETQ.Angle(30.0, 'deg')
    >>> print(angle)
      30.000 deg (Angle)
    >>> print(cos(angle.get_value('rad')))
    0.866025403784...
    >>> cos(angle.get_uval()) # doctest: +ELLIPSIS
    UVal(0.8660254037844..., {})
    >>> print(cos(angle.get_uval()))
    0.8660 {}
    >>> print(cos(angle))
       0.866  (Scalar)
    >>> print(cos(ETQ.Distance(0.5, 'm')))
    Traceback (most recent call last):
        ...
    EngineeringTools.tools.functions.EngineeringTools_tools_Error_units: wrong type : <class 'EngineeringTools.quantities.mechanics.Distance'>

    """
    if isinstance(angle, float):
        return _np.cos(angle)
    elif isinstance(angle, ETQ.UVal):
        angle.check_units({})
        return ETQ.UVal(_np.cos(angle.get_value()), {})
    elif isinstance(angle, ETQ.Angle):
        return ETQ.Scalar(_np.cos(angle.get_value()), '1.0')
    else:
        raise EngineeringTools_tools_Error_units('wrong type : %s' % type(angle))

def arccos(scalar):
    """ arccos

    >>> scalar = ETQ.Scalar(0.5, '1.0')
    >>> print(scalar)
       0.500  (Scalar)
    >>> print((arccos(scalar.get_value())))  # rad
    1.047197551...
    >>> print(arccos(scalar.get_uval()))
    1.047 {}
    >>> print(arccos(scalar.get_uval()))
    1.047 {}
    >>> a=arccos(scalar); _ = a.set_displayUnit('deg'); print(a)
      60.000 deg (Angle)
    >>> print(arccos(ETQ.Distance(0.5, 'm')))
    Traceback (most recent call last):
        ...
    EngineeringTools.tools.functions.EngineeringTools_tools_Error_units: wrong type : <class 'EngineeringTools.quantities.mechanics.Distance'>

    """
    if isinstance(scalar, float):
        return _np.arccos(scalar)
    elif isinstance(scalar, ETQ.UVal):
        scalar.check_units({})
        return ETQ.UVal(_np.arccos(scalar.get_value()), {})
    elif isinstance(scalar, ETQ.Scalar):
        return ETQ.Angle(_np.arccos(scalar.get_value()), 'rad')
    else:
        raise EngineeringTools_tools_Error_units('wrong type : %s' % type(scalar))

acos = arccos  # compatibility with math module

def tan(angle):
    """ tan

    >>> angle = ETQ.Angle(30.0, 'deg')
    >>> print(angle)
      30.000 deg (Angle)
    >>> print(tan(angle.get_value('rad')))
    0.5773502691...
    >>> tan(angle.get_uval())
    UVal(0.5773502691896..., {})
    >>> print(tan(angle.get_uval()))
    0.5774 {}
    >>> print(tan(angle))
       0.577  (Scalar)
    >>> print(tan(ETQ.Distance(0.5, 'm')))
    Traceback (most recent call last):
        ...
    EngineeringTools.tools.functions.EngineeringTools_tools_Error_units: wrong type : <class 'EngineeringTools.quantities.mechanics.Distance'>

    """
    if isinstance(angle, float):
        return _np.tan(angle)
    elif isinstance(angle, ETQ.UVal):
        angle.check_units({})
        return ETQ.UVal(_np.tan(angle.get_value()), {})
    elif isinstance(angle, ETQ.Angle):
        return ETQ.Scalar(_np.tan(angle.get_value()), '1.0')
    else:
        raise EngineeringTools_tools_Error_units('wrong type : %s' % type(angle))

def atan(scalar):
    """ atan

    >>> scalar = ETQ.Scalar(0.5)
    >>> print(scalar)
       0.500  (Scalar)
    >>> print(atan(scalar.get_value()))  # rad
    0.46364760900...
    >>> print(atan(scalar.get_uval()))
      26.565 deg (Angle)
    >>> a=atan(scalar); _ = a.set_displayUnit('deg'); print(a)
      26.565 deg (Angle)
    >>> print(atan(ETQ.Distance(0.5, 'm')))
    Traceback (most recent call last):
        ...
    EngineeringTools.tools.functions.EngineeringTools_tools_Error_units: wrong type : <class 'EngineeringTools.quantities.mechanics.Distance'>

    """
    if isinstance(scalar, float):
        return _np.arctan(scalar)
    elif isinstance(scalar, ETQ.UVal):
        scalar.check_units({})
        return ETQ.Angle(_np.arctan(scalar.get_value()), 'rad')
    elif isinstance(scalar, ETQ.Scalar):
        return ETQ.Angle(_np.arctan(scalar.get_value()), 'rad')
    else:
        raise EngineeringTools_tools_Error_units('wrong type : %s' % type(scalar))

def atan2(y, x):
    """ atan2

    >>> y = ETQ.Distance(1/3.0**(0.5), 'm')
    >>> x = ETQ.Distance(1.0, 'm')
    >>> print(y, x)
     577.350 mm (Distance) 1000.000 mm (Distance)
    >>> print(atan2(y, x))
      30.000 deg (Angle)
    >>> atan2(y.uval, x.uval)
    UVal(0.5235987755982989, {})
    >>> print(atan2(y.value, x.value) / _np.pi * 180.0)
    30.0...

    """
    if isinstance(y, float) and isinstance(x, float):
        return _np.arctan2(y, x)
    elif isinstance(y, ETQ.UVal) and isinstance(x, ETQ.UVal):
        y.check_units(x)
        return ETQ.UVal(_np.arctan2(y.get_value(), x.get_value()), {})
    elif y.match_quantities(x):
        return ETQ.Angle(_np.arctan2(y.get_value(), x.get_value()), 'rad')
    else:
        raise EngineeringTools_tools_Error_units('wrong type or combination : %s, %s' % (type(y), type(x)))

def sqrt(uvalue):
    """square root of uval, wurzel

        >>> uv = ETQ.UVal(9.0, {}); print(uv)
        9.000 {}
        >>> print(sqrt(uv))
        3.000 {}
        >>> print(sqrt(9.0))
        3.0

    """
    if isinstance(uvalue, ETQ.UVal):
        return pow(uvalue, (1, 2))
    elif  isinstance(uvalue, (float, int)):
        return uvalue**(1.0/2.0)
    elif isinstance(uvalue, ETQ.Quantity):
        return pow(uvalue.uval, (1, 2))
    else:
        raise EngineeringTools_tools_Error_units('type not recognized: {}'.format(type(uvalue)))

def sqrtSigned(val):
    """square root of uval, wurzel, keeping the sign

    >>> a = ETQ.Area(4, 'm2')
    >>> sqrtSigned(a)
    UVal(2.0, {'meter': Fraction(1, 1)})

    >>> a = ETQ.Area(-4, 'm2')
    >>> sqrtSigned(a)
    UVal(-2.0, {'meter': Fraction(1, 1)})

    """
    return val.sign()*sqrt(val.abs())

def log10(scalar):
    """log to basis 10
    """
    if isinstance(scalar, int):
        scalar = float(scalar)
    if isinstance(scalar, float):
        return _np.log10(scalar)
    elif isinstance(scalar, ETQ.UVal):
        scalar.check_units({})
        return ETQ.UVal(_np.log10(scalar.get_value()), {})
    else:
        raise EngineeringTools_tools_Error_units('type not recognized: {}'.format(type(scalar)))

def log(scalar):
    """log to basis e
    """
    if isinstance(scalar, int):
        scalar = float(scalar)
    if isinstance(scalar, float):
        return _np.log(scalar)
    elif isinstance(scalar, ETQ.UVal):
        scalar.check_units({})
        return ETQ.UVal(_np.log(scalar.get_value()), {})
    else:
        raise EngineeringTools_tools_Error_units('type not recognized: {}'.format(type(scalar)))

def exp(scalar):
    """exp
    """
    if isinstance(scalar, int):
        scalar = float(scalar)
    if isinstance(scalar, float):
        return _np.exp(scalar)
    elif isinstance(scalar, ETQ.UVal):
        scalar.check_units({})
        return ETQ.UVal(_np.exp(scalar.get_value()), {})
    else:
        raise EngineeringTools_tools_Error_units('type not recognized: {}'.format(type(scalar)))

def power(value, exp):
    """  value**exp
    """
    if isinstance(value, ETQ.QuantityNumeric):
        value = value.uval
    if isinstance(exp, (ETQ.Number, ETQ.Scalar)):
        exp = exp.get_value()

    if isinstance(exp, int):
        exp = float(exp)

    if isinstance(value, (float, int)) and isinstance(exp, float):
        return _np.power(value, exp)
    elif isinstance(value, ETQ.UVal) and isinstance(exp, float):
        units = {k:v*exp for k,v in value._units.items()}
        return ETQ.UVal(_np.power(value.get_value(), exp), units)
    else:
        raise EngineeringTools_tools_Error_units('type not recognized: {}, {}'.format(type(value), type(exp)))

def limitTo(x, limitLower, limitUpper):
    if x < limitLower:
        x = limitLower.set_properties_from(x)
    elif x > limitUpper:
        x = limitUpper.set_properties_from(x)
    return x

def physical_constants(name):
    """return a physical constant from sp.constants.physical_constants as uval
    """
    unittable = {'m':ETQ.UVal(1, {'meter':Fraction(1,1)}),
                 'K':ETQ.UVal(1, {'kelvin':Fraction(1,1)}),
                 'W':ETQ.Power(1, 'W').uval,
                 'Hz':ETQ.Frequency(1,'Hz').uval,
                 'ohm':ETQ.Resistance(1,'Ohm').uval}
    try:
        import scipy as _sp
        phConst = _sp.constants.physical_constants[name]
    except KeyError as e:
        raise e

    value = phConst[0]
    unitStr = phConst[1]
    ul = unitStr.split(' ')
    uval = ETQ.UVal(value, {})
    for ui in ul:
        ux = ui.split('^')
        if len(ux) < 2:
            ux.append(1)
        try:
            uval *= power(unittable[ux[0]], int(ux[1]))
        except KeyError:
            raise KeyError('{} : {}'.format(ux[0], ui))
    return uval

################################################################################
# test
################################################################################
def _setup_doctest():
    ETQ.Quantity.set_displayUnitSystem('mechanicalEngineering')

#eof


def parse_fromstring(self, s, parser=None, context=None):
        """
        Parse an HTML or XML document and
        return the extacted object following the Parsley rules give at instantiation.

        :param string s: an HTML or XML document as a string
        :param parser: *lxml.etree._FeedParser* instance (optional); defaults to lxml.etree.HTMLParser()
        :param context: user-supplied context that will be passed to custom XPath extensions (as first argument)
        :rtype: Python :class:`dict` object with mapped extracted content
        :raises: :class:`.NonMatchingNonOptionalKey`

        """
        if parser is None:
            parser = lxml.etree.HTMLParser()
        doc = lxml.etree.fromstring(s, parser=parser)
        return self.extract(doc, context=context)


import csv
fpath = "C:\\Users\\means\\Desktop\\Shahzaib University Assignments\\CSSE 305 Lab\\Python-Code\\GradingRules.txt"
gradeAndPoint = []
with open(fpath, "r") as f:
    while True:
        list1 = []
        content = f.readline()
        if content != "":
            split = content.split(",")

            list1.append(split)
            gradeAndPoint.append(list1)
        else:
            break
data = []
headerLine = ["S.No", "Seat Number", "Name",
              "Father Name", "Theory Marks", "Lab Marks", "Total", "Marks In Words", "Alphabetic Grade"]
x = 0
while True:
    a = input("Enter Seat Number:")
    if a != "":
        recordList = []
        x = x+1
        b = input("Enter Name:")
        c = input("Enter Father's Name:")
        d = int(input("Enter Marks in Theory:"))
        e = int(input("Enter Marks in Lab:"))
        f = d+e
        recordList.append(x)
        recordList.append(a)
        recordList.append(b)
        recordList.append(c)
        recordList.append(str(d))
        recordList.append(str(e))
        recordList.append(f)
        for i in range(len(gradeAndPoint)):
            if gradeAndPoint[i][0][0] == str(f):
                numberalpha = gradeAndPoint[i][0][1]
                alphagrade = gradeAndPoint[i][0][2]
                recordList.append(numberalpha)
                recordList.append(alphagrade)

        data.append(recordList)
        print(recordList)

    else:
        break

with open("forSemesterCell.csv", "w", encoding="UTF8", newline="") as ft:
    writer = csv.writer(ft)
    writer.writerow(headerLine)
    writer.writerows(data)


import numpy as np
import pandas as pd
from tqdm import tqdm
from utils.data import get_sorted_filepaths
from utils.paths import (path_clutter, path_cooccurrence, path_metadata,
    path_mids, path_objdet, path_wnids)

wnids = np.loadtxt(path_wnids, dtype=str)
mids = np.loadtxt(path_mids, dtype=str)
mid2ind = {mid:ind for ind, mid in enumerate(mids)}
cooccurrence = np.loadtxt(path_cooccurrence)
cooccurrence /= np.sum(cooccurrence, axis=1, keepdims=True) # make rows sum to 1
shorten_filepath = lambda filepath: '/'.join(filepath.split('/')[-2:])
clutter, filepaths = [], []

for i, wnid in enumerate(tqdm(wnids)):
    filepaths_wnid = get_sorted_filepaths('train', 'image', wnid)
    path_scores = path_objdet/f'{wnid}_scores.txt'
    path_class_names = path_objdet/f'{wnid}_class_names.txt'
    scores_wnid = np.loadtxt(path_scores)
    class_names_wnid = np.loadtxt(path_class_names, dtype=str)
    for scores, class_names in zip(scores_wnid, class_names_wnid):
        clutter_image = 0
        for class_name in np.unique(class_names):
            # If WNID `i` and MID `j` commonly cooccur, `cooccurrence[i, j]` is
            # high and MID `j` is relevant to WNID `i`
            j = mid2ind[class_name]
            irrelevance = 1 - cooccurrence[i, j]
            scores_j = scores[np.flatnonzero(class_names == class_name)]
            clutter_image += irrelevance * np.max(scores_j)
        clutter.append(clutter_image)
    filepaths.extend(filepaths_wnid)
    df_clutter = pd.DataFrame({'filepath':filepaths, 'clutter':clutter})
    df_clutter['filepath'] = df_clutter['filepath'].apply(shorten_filepath)
    df_clutter.to_csv(path_metadata/'imagenet_image_clutter.csv', index=False)

df_clutter['wnid'] = df_clutter['filepath'].str.split('_', expand=True)[0]
df_clutter_median = df_clutter.groupby('wnid').median()
df_clutter_median.reset_index(inplace=True)
np.savetxt(path_clutter, list(df_clutter_median['clutter']), fmt='%.18f')