__author__ = 'David'

from PriorityQueue import minHeap

def bellman_ford(sourceVertexIndex, graph, destinationIndex):       # works :D
    routes = []
    startTarget = sourceVertexIndex
    endTraget = destinationIndex
    #print(destinationIndex)
    #print("TARGET: "+ str(destinationIndex))
    #print("SOURCE: " + str(sourceVertexIndex))
    #intialize
    for i in graph.array:
        i.dist = "INFINITY"
        #i.path = []
    # we dont need the notion of the cloud

    #  we know distance of source
    sourceNode = graph.getGraphNode(sourceVertexIndex)
    sourceNode.dist = 0

    noVert = len(graph.array)
    graphEdges = graph.getEdges()
    # main loop #v - 1 times

    # relax
    for i in range(noVert-1):   # loop no vertices -1 times

        for eachEdge in graphEdges:
            target = False
            # edges in edge array stored as (source, destination, cost) # coded
            nodeIindex = eachEdge[0]
            nodeI = graph.array[nodeIindex]
            nodeDindex = eachEdge[1]
            nodeD = graph.array[nodeDindex]
            cost = eachEdge[2]

            if nodeD.name == destinationIndex:
                # destination index, when update we should keep its info
                target = True
                #print("is true")
            relaxEdgesBF(nodeIindex, nodeDindex, cost, graph, target, routes, sourceVertexIndex)
            #print(nodeD.dist)
            #print(nodeI.dist)

    # check
    cycle = 0
    # once again to check for neg cycle
    for eachEdge in graphEdges:

        nodeIindex = eachEdge[0]
        nodeI = graph.array[nodeIindex]
        nodeDindex = eachEdge[1]
        nodeD = graph.array[nodeDindex]
        cost = eachEdge[2]

       # print(nodeD.dist)
        #print(nodeI.dist)

        if nodeD.dist == "INFINITY":
            #print("There is A negative weight cycle")
            cycle = -1
        elif nodeI.dist == "INFINITY":
            #print("is no negative weight cycle")
            cycle = 1
        elif int(nodeD.dist) > int(nodeI.dist) + int(cost):
            #print("There is a negative weight cycle")
            cycle = -1
        else:
            #print("No negative weight cycles")
            cycle = 1
    if cycle < 0:
        print("There is a negative weight cycle")
    else:
        print("No negative weight cycle")
    processRoutes(routes, graph)
    print("Routes: ", end="")
    print(routes)
    return routes
    #return  findShortestPath(graph, destinationIndex)
    #return findCheapRoutes(graph, destinationIndex)

'''
    if you have a vertex S and another D
    the shortest path b/w S & D
    there may be vertices along the way
    i.e. S - v1 - v2 - v3 - D
    the way to discover these is to relax all edges
    thus you will get the right dist value for v1, the relaxation of that edge gives the
    shortest path from S to v1
    as all sub paths of s shortest paths must be shortest paths, can find shortest paths
    along S-D

    relax all edges - max length of possible path - no vert -1 times

    if d[v] v.dist is -, then there is a neg cycle
'''
def processRoutes(routes, graph):
    totalRoutes = len(routes)

    for i in routes:                # append route cost to each route
        aRouteLen = len(i)
        aRouteCost = 0

        for x in range(aRouteLen-1):    # get total cost
            sourceIndex = i[x]
            destIndex = i[x+1]
            # 1 shortest path = mutate distance
            # find a bunch is fine to do like this
            vertex = graph.array[sourceIndex]
            linkedList = vertex.pointer
            for edge in linkedList:
                if edge[0] == destIndex:
                    cost = edge[1]
                    aRouteCost += int(cost)
                    break
        i.append(aRouteCost)

def relaxEdgesBF(nodeIindex, nodeDindex, edgeCost,graph, target, routes, sourceVertexIndex):

    # compare path s-node2 to s-node1-node2
    # nodeI = intermediate
    # nodeD = destination
    # look @ source - D vs source - I - D
    #print('START ' + str(nodeDindex) + ' ' + str(target))
    nodeI = graph.array[nodeIindex]
    nodeD = graph.array[nodeDindex]
    if nodeD.dist == "INFINITY":        # s-d >
        if nodeI.dist == "INFINITY":    # = s-i-d
            pass
        else:
            # s-d >, s-i-d smaller so make nodeD.dist = sid
            nodeD.dist = nodeI.dist + int(edgeCost)
            nodeD.path = nodeI

            if target:
                #print(nodeD.name)
                curNode = nodeD
                aRoute = []
                while curNode is not None:
                    if int(curNode.name) == int(sourceVertexIndex):
                        aRoute.insert(0, curNode.name)
                        break
                    aRoute.insert(0,curNode.name)
                    curNode = curNode.path
                routes.append(aRoute)

    elif nodeI.dist == "INFINITY":      # s-i-d always bigger
        pass                            # so dont do anything

    elif nodeD.dist > nodeI.dist + int(edgeCost):
        # s-d > s-i-d
        nodeD.dist = nodeI.dist + int(edgeCost)
        nodeD.path = nodeI
        if target:
            #print('nodeD ' + str(nodeD.name))
            #print('nodeI ' + str(nodeI.name))
            curNode = nodeD
            aRoute = []

            while curNode is not None:
                if int(curNode.name) == int(sourceVertexIndex):
                    aRoute.insert(0,curNode.name)
                    break
                aRoute.insert(0,curNode.name)
                #print("before next")
                curNode = curNode.path
                #print("after next")
            #print("out")
            routes.append(aRoute)

def findCheapRoutes(graph, destinationIndex):
    paths = []
    end = graph.array[destinationIndex]
    print("EP")
    print(end.path)

    another = graph.array[1]
    print(another.path)
    return end.path, 9

#-------------------------------------------------------------

def dijkstra(sourceVertexIndex, graph, destinationIndex):
    '''
    pass on source as vertexIndex
    pass on graph
    as arguments
    knwon field used to define A/V-A
    '''

    # for each GraphNode initialize dist & known for dijkstra
    for i in graph.array:
        i.dist = 'INFINITY' # set estimate of shortest path to peanut
        i.known = False     # all in set V-A as False
    # now all nodes are in V-A (some estimate of shortest path)
    # if v.known is False then the shortest path is not known and we need to find it

    # the set A is things that v.know = True meaning tha t the
    # shortest path is known, source added to set A
    sourceNode = graph.getGraphNode(sourceVertexIndex)
    sourceNode.dist = 0
    # sourceNode.known = True # source put in set A, dw the while loop will do this using PQ
    # now source is the first element in the PQ as dist is lowest and minHeap

    # set up Priority Queue add vertices to Priority Queue
    priorityQueue = minHeap()
    for i in graph.array:
        priorityQueue.add(i)
    # priorityQueue contains GraphNode objects
    # has all vertices in V-A, keyed (sorted) by dist field
    # WORKS UP TO HERE!

    # edges stored in LL pointed to by vertices
    # each element of LL has .item, .next
    # each .item store as (adjacentNodeIndex, cost)
    # vertex stored as an item in array, []--> (vertex object), vertex.name = index (need to decode for english)

    # main loop
    while not priorityQueue.is_empty():
        # still an unknown vertex as priorityQueue not empty
        # means there is a node in  V-A
        u = priorityQueue.getMin()  # chose node with smallest estimate (.dist)
        u.known = True              #  add to the set A, assume estimate = shortest path

        vertexLocation = u.name

        linkedList = u.pointer
        # note: iterators set up for linked list class
        for edgeBit in linkedList:    # for adjacent vertices stored in the linked list
            # edgeBit = 'vertexIndex', cost

            adjVertIndex = edgeBit[0]
            adjacentVertex = graph.array[adjVertIndex]
            if adjacentVertex.known is True:    # is in the set A - we know its shortest path
                pass
            else:                       # is in the set V-A, we only know an estimate
                relaxEdgesD(u, edgeBit, graph, priorityQueue)

    return  findShortestPath(graph, destinationIndex)

def findShortestPath(graph, destinationIndex):
    # go backwards to find path
    # returns array of shortest path and cost
    shortestPath = []
    destinationVertex = graph.array[destinationIndex]
    # start @ destination
    currentVertex = destinationVertex
    totalCost = 0

    while currentVertex is not None:
        #print(vertex.name)
        #print(vertex.known)
        #print(vertex.path)
        # add vertex name to the list
        shortestPath.insert(0, currentVertex.name)
        if currentVertex.path is None:
            break
        #print(shortestPath)
        possiblePaths = currentVertex.pointer
        if currentVertex.path is not None:
            nextVertex = graph.array[int(currentVertex.path.name)]
            # iterate over linked list to find cost of the edge

           # print(nextVertex.name)
            for i in possiblePaths:
            #    print(i)

                if str(nextVertex.name) == str(i[0]):
                    cost = i[1]
                    totalCost += int(cost)

                    break
            #print('once')
            currentVertex = nextVertex
    #print(shortestPath)
    return shortestPath, totalCost

def relaxEdgesD(chosenVertex, edgeObject, graph, Q=None):
    # edges stored in LL pointed to by vertices
    # each element of LL has .item, .next
    # each .item store as (adjacentNodeIndex, cost)
    # vertex stored as an item in array, []--> (vertex object), vertex.name = index (need to decode for english)

    # cost of chosen vertex --> adjacent vertex
    edgeCost= edgeObject[1]
    # vertex adjacent to chosen, destination of the edge, the index of that vertex
    adjVertexEdgeDestIndex = edgeObject[0]
    # actual vertex object
    adjVertexEdgeDest = graph.array[adjVertexEdgeDestIndex]
    # compare path s-v to s-u-v

    if adjVertexEdgeDest.dist == "INFINITY":
        if chosenVertex.dist == "INFINITY":
            pass
        else:

            adjVertexEdgeDest.dist = chosenVertex.dist + int(edgeCost)
            adjVertexEdgeDest.path = chosenVertex
            if Q:
                Q.decreasedKey(adjVertexEdgeDest, chosenVertex.dist + int(edgeCost))
    elif chosenVertex.dist == "INFINITY":
        pass

    elif adjVertexEdgeDest.dist > chosenVertex.dist + int(edgeCost):
        adjVertexEdgeDest.dist = chosenVertex.dist + int(edgeCost)
        adjVertexEdgeDest.path = chosenVertex
        if Q:
            Q.decreasedKey(adjVertexEdgeDest,chosenVertex.dist + int(edgeCost))

        '''
        for all vertices adj to u
            do following
            if already in A (known = true)
                pass # dont need to do anything
            otherwise
                if adjacent is not known (is in V-A)
                need to update
                relax

                update method
                if adj node already has a shortest path estimate (v.dist)
                compare that (v.dist) to the path we get if we go from
                the source (s) to removed node (u) then to this adjnode (v)

                if cost of s-u-v cheaper, set adjnode.dist = that shorter path
                v.path = u # keep track of back pointers
        '''
    '''
    while Q not empty
        u <-- extractMin(Q)
        for each vertex v such that u --> b
            relax (u,v)
    '''

FIT2004-Algorithms-And-Data-Structures/Lab 9 - week 10 [x]/ShortestPathFinder.py


# An example for quadratic knapsack problems

#### Authors: Lei Han, Handing Wang
#### Xidian University, China.
#### EMAIL: lhan_1@stu.xidian.edu.cn, hdwang@xidian.edu.cn
#### WEBSITE: https://sites.google.com/site/handingwanghomepage
#### DATE: January 2021
# ------------------------------------------------------------------------
# This code is part of the program that produces the results in the following paper:
#
# Lei Han, Handing Wang, A random forest assisted evolutionary algorithm using competitive neighborhood search for expensive constrained combinatorial optimization. Memetic Computing, accepted.
#
# You are free to use it for non-commercial purposes. However, we do not offer any forms of guarantee or warranty associated with the code. We would appreciate your acknowledgement.
# ------------------------------------------------------------------------
from problems import problem_quadratic_knapsack
from cns import CNS

def main():
    max_iter = 500  # Iterations
    var_num = 50  # Problem dimensions
    pop_size = 100  # Population size
    w = 200  # Knapsack size

    cns_new = CNS(max_iter, var_num, pop_size, problem_quadratic_knapsack, w)
    cns_new.run()
    cns_new.show_result()
    cns_new.print_result()

if __name__ == '__main__':
    main()


# uncompyle6 version 3.6.7
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]
# Embedded file name: /home/erwincoumans/dev/tmp/bullet3/examples/pybullet/gym/pybullet_envs/robot_locomotors.py
# Compiled at: 2020-04-29 23:02:34
# Size of source mod 2**32: 13872 bytes
from robot_bases import XmlBasedRobot, MJCFBasedRobot, URDFBasedRobot
import numpy as np, pybullet, os, pybullet_data
from robot_bases import BodyPart

class WalkerBase(MJCFBasedRobot):

    def __init__(self, fn, robot_name, action_dim, obs_dim, power):
        MJCFBasedRobot.__init__(self, fn, robot_name, action_dim, obs_dim)
        self.power = power
        self.camera_x = 0
        self.start_pos_x, self.start_pos_y, self.start_pos_z = (0, 0, 0)
        self.walk_target_x = 1000.0
        self.walk_target_y = 0
        self.body_xyz = [0, 0, 0]

    def robot_specific_reset(self, bullet_client):
        self._p = bullet_client
        for j in self.ordered_joints:
            j.reset_current_position(self.np_random.uniform(low=(-0.1), high=0.1), 0)

        self.feet = [self.parts[f] for f in self.foot_list]
        self.feet_contact = np.array([0.0 for f in self.foot_list], dtype=(np.float32))
        self.scene.actor_introduce(self)
        self.initial_z = None

    def apply_action(self, a):
        assert np.isfinite(a).all()
        for n, j in enumerate(self.ordered_joints):
            j.set_motor_torque(self.power * j.power_coef * float(np.clip(a[n], -1, 1)))

    def calc_state(self):
        j = np.array([j.current_relative_position() for j in self.ordered_joints], dtype=(np.float32)).flatten()
        self.joint_speeds = j[1::2]
        self.joints_at_limit = np.count_nonzero(np.abs(j[0::2]) > 0.99)
        body_pose = self.robot_body.pose()
        parts_xyz = np.array([p.pose().xyz() for p in self.parts.values()]).flatten()
        self.body_xyz = (parts_xyz[0::3].mean(), parts_xyz[1::3].mean(), body_pose.xyz()[2])
        self.body_real_xyz = body_pose.xyz()
        self.body_rpy = body_pose.rpy()
        z = self.body_xyz[2]
        if self.initial_z == None:
            self.initial_z = z
        r, p, yaw = self.body_rpy
        self.walk_target_theta = np.arctan2(self.walk_target_y - self.body_xyz[1], self.walk_target_x - self.body_xyz[0])
        self.walk_target_dist = np.linalg.norm([
         self.walk_target_y - self.body_xyz[1], self.walk_target_x - self.body_xyz[0]])
        angle_to_target = self.walk_target_theta - yaw
        rot_speed = np.array([[np.cos(-yaw), -np.sin(-yaw), 0],
         [np.sin(-yaw),
          np.cos(-yaw), 0], [0, 0, 1]])
        vx, vy, vz = np.dot(rot_speed, self.robot_body.speed())
        more = np.array([
         z - self.initial_z,
         np.sin(angle_to_target),
         np.cos(angle_to_target),
         0.3 * vx,
         0.3 * vy,
         0.3 * vz,
         r,
         p],
          dtype=(np.float32))
        return np.clip(np.concatenate([more] + [j] + [self.feet_contact]), -5, 5)

    def calc_potential(self):
        debugmode = 0
        if debugmode:
            print('calc_potential: self.walk_target_dist')
            print(self.walk_target_dist)
            print('self.scene.dt')
            print(self.scene.dt)
            print('self.scene.frame_skip')
            print(self.scene.frame_skip)
            print('self.scene.timestep')
            print(self.scene.timestep)
        return -self.walk_target_dist / self.scene.dt

class Hopper(WalkerBase):
    foot_list = [
     'foot']

    def __init__(self):
        WalkerBase.__init__(self, 'hopper.xml', 'torso', action_dim=3, obs_dim=15, power=0.75)

    def alive_bonus(self, z, pitch):
        if z > 0.8:
            if abs(pitch) < 1.0:
                return 1
        return -1

class Walker2D(WalkerBase):
    foot_list = [
     'foot', 'foot_left']

    def __init__(self):
        WalkerBase.__init__(self, 'walker2d.xml', 'torso', action_dim=6, obs_dim=22, power=0.4)

    def alive_bonus(self, z, pitch):
        if z > 0.8:
            if abs(pitch) < 1.0:
                return 1
        return -1

    def robot_specific_reset(self, bullet_client):
        WalkerBase.robot_specific_reset(self, bullet_client)
        for n in ('foot_joint', 'foot_left_joint'):
            self.jdict[n].power_coef = 30.0

class HalfCheetah(WalkerBase):
    foot_list = [
     'ffoot', 'fshin', 'fthigh', 'bfoot', 'bshin',
     'bthigh']

    def __init__(self):
        WalkerBase.__init__(self, 'half_cheetah.xml', 'torso', action_dim=6, obs_dim=26, power=0.9)

    def alive_bonus(self, z, pitch):
        if np.abs(pitch) < 1.0:
            if not self.feet_contact[1]:
                if not self.feet_contact[2]:
                    if not self.feet_contact[4]:
                        if not self.feet_contact[5]:
                            return 1
        return -1

    def robot_specific_reset(self, bullet_client):
        WalkerBase.robot_specific_reset(self, bullet_client)
        self.jdict['bthigh'].power_coef = 120.0
        self.jdict['bshin'].power_coef = 90.0
        self.jdict['bfoot'].power_coef = 60.0
        self.jdict['fthigh'].power_coef = 140.0
        self.jdict['fshin'].power_coef = 60.0
        self.jdict['ffoot'].power_coef = 30.0

class Ant(WalkerBase):
    foot_list = [
     'front_left_foot', 'front_right_foot', 'left_back_foot', 'right_back_foot']

    def __init__(self):
        WalkerBase.__init__(self, 'ant.xml', 'torso', action_dim=8, obs_dim=28, power=2.5)

    def alive_bonus(self, z, pitch):
        if z > 0.26:
            return 1
        else:
            return -1

class Humanoid(WalkerBase):
    self_collision = True
    foot_list = ['right_foot', 'left_foot']

    def __init__(self):
        WalkerBase.__init__(self, 'humanoid_symmetric.xml',
          'torso',
          action_dim=17,
          obs_dim=44,
          power=0.41)

    def robot_specific_reset(self, bullet_client):
        WalkerBase.robot_specific_reset(self, bullet_client)
        self.motor_names = ['abdomen_z', 'abdomen_y', 'abdomen_x']
        self.motor_power = [100, 100, 100]
        self.motor_names += ['right_hip_x', 'right_hip_z', 'right_hip_y', 'right_knee']
        self.motor_power += [100, 100, 300, 200]
        self.motor_names += ['left_hip_x', 'left_hip_z', 'left_hip_y', 'left_knee']
        self.motor_power += [100, 100, 300, 200]
        self.motor_names += ['right_shoulder1', 'right_shoulder2', 'right_elbow']
        self.motor_power += [75, 75, 75]
        self.motor_names += ['left_shoulder1', 'left_shoulder2', 'left_elbow']
        self.motor_power += [75, 75, 75]
        self.motors = [self.jdict[n] for n in self.motor_names]
        if self.random_yaw:
            position = [
             0, 0, 0]
            orientation = [0, 0, 0]
            yaw = self.np_random.uniform(low=(-3.14), high=3.14)
            if self.random_lean:
                if self.np_random.randint(2) == 0:
                    cpose.set_xyz(0, 0, 1.4)
                    if self.np_random.randint(2) == 0:
                        pitch = np.pi / 2
                        position = [0, 0, 0.45]
                    else:
                        pitch = np.pi * 3 / 2
                        position = [0, 0, 0.25]
                    roll = 0
                    orientation = [roll, pitch, yaw]
            else:
                position = [
                 0, 0, 1.4]
                orientation = [0, 0, yaw]
            self.robot_body.reset_position(position)
            self.robot_body.reset_orientation(orientation)
        self.initial_z = 0.8

    random_yaw = False
    random_lean = False

    def apply_action(self, a):
        assert np.isfinite(a).all()
        force_gain = 1
        for i, m, power in zip(range(17), self.motors, self.motor_power):
            m.set_motor_torque(float(force_gain * power * self.power * np.clip(a[i], -1, 1)))

    def alive_bonus(self, z, pitch):
        if z > 0.78:
            return 2
        else:
            return -1

def get_cube(_p, x, y, z):
    body = _p.loadURDF(os.path.join(pybullet_data.getDataPath(), 'cube_small.urdf'), [x, y, z])
    _p.changeDynamics(body, (-1), mass=1.2)
    part_name, _ = _p.getBodyInfo(body)
    part_name = part_name.decode('utf8')
    bodies = [body]
    return BodyPart(_p, part_name, bodies, 0, -1)

def get_sphere(_p, x, y, z):
    body = _p.loadURDF(os.path.join(pybullet_data.getDataPath(), 'sphere2red_nocol.urdf'), [x, y, z])
    part_name, _ = _p.getBodyInfo(body)
    part_name = part_name.decode('utf8')
    bodies = [body]
    return BodyPart(_p, part_name, bodies, 0, -1)

class HumanoidFlagrun(Humanoid):

    def __init__(self):
        Humanoid.__init__(self)
        self.flag = None

    def robot_specific_reset(self, bullet_client):
        Humanoid.robot_specific_reset(self, bullet_client)
        self.flag_reposition()

    def flag_reposition(self):
        self.walk_target_x = self.np_random.uniform(low=(-self.scene.stadium_halflen), high=(+self.scene.stadium_halflen))
        self.walk_target_y = self.np_random.uniform(low=(-self.scene.stadium_halfwidth), high=(+self.scene.stadium_halfwidth))
        more_compact = 0.5
        self.walk_target_x *= more_compact
        self.walk_target_y *= more_compact
        if self.flag:
            self._p.resetBasePositionAndOrientation(self.flag.bodies[0], [
             self.walk_target_x, self.walk_target_y, 0.7], [
             0, 0, 0, 1])
        else:
            self.flag = get_sphere(self._p, self.walk_target_x, self.walk_target_y, 0.7)
        self.flag_timeout = 600 / self.scene.frame_skip

    def calc_state(self):
        self.flag_timeout -= 1
        state = Humanoid.calc_state(self)
        if self.walk_target_dist < 1 or self.flag_timeout <= 0:
            self.flag_reposition()
            state = Humanoid.calc_state(self)
            self.potential = self.calc_potential()
        return state

class HumanoidFlagrunHarder(HumanoidFlagrun):

    def __init__(self):
        HumanoidFlagrun.__init__(self)
        self.flag = None
        self.aggressive_cube = None
        self.frame = 0

    def robot_specific_reset(self, bullet_client):
        HumanoidFlagrun.robot_specific_reset(self, bullet_client)
        self.frame = 0
        if self.aggressive_cube:
            self._p.resetBasePositionAndOrientation(self.aggressive_cube.bodies[0], [-1.5, 0, 0.05], [
             0, 0, 0, 1])
        else:
            self.aggressive_cube = get_cube(self._p, -1.5, 0, 0.05)
        self.on_ground_frame_counter = 0
        self.crawl_start_potential = None
        self.crawl_ignored_potential = 0.0
        self.initial_z = 0.8

    def alive_bonus(self, z, pitch):
        if self.frame % 30 == 0 and self.frame > 100 and self.on_ground_frame_counter == 0:
            target_xyz = np.array(self.body_xyz)
            robot_speed = np.array(self.robot_body.speed())
            angle = self.np_random.uniform(low=(-3.14), high=3.14)
            from_dist = 4.0
            attack_speed = self.np_random.uniform(low=20.0,
              high=30.0)
            time_to_travel = from_dist / attack_speed
            target_xyz += robot_speed * time_to_travel
            position = [
             target_xyz[0] + from_dist * np.cos(angle), target_xyz[1] + from_dist * np.sin(angle),
             target_xyz[2] + 1.0]
            attack_speed_vector = target_xyz - np.array(position)
            attack_speed_vector *= attack_speed / np.linalg.norm(attack_speed_vector)
            attack_speed_vector += self.np_random.uniform(low=(-1.0), high=1.0, size=(3, ))
            self.aggressive_cube.reset_position(position)
            self.aggressive_cube.reset_velocity(linearVelocity=attack_speed_vector)
        if z < 0.8:
            self.on_ground_frame_counter += 1
        else:
            if self.on_ground_frame_counter > 0:
                self.on_ground_frame_counter -= 1
        self.frame += 1
        if self.on_ground_frame_counter < 170:
            return self.potential_leak()
        else:
            return -1

    def potential_leak(self):
        z = self.body_xyz[2]
        z = np.clip(z, 0, 0.8)
        return z / 0.8 + 1.0

    def calc_potential(self):
        flag_running_progress = Humanoid.calc_potential(self)
        if self.body_xyz[2] < 0.8:
            if self.crawl_start_potential is None:
                self.crawl_start_potential = flag_running_progress - self.crawl_ignored_potential
            self.crawl_ignored_potential = flag_running_progress - self.crawl_start_potential
            flag_running_progress = self.crawl_start_potential
        else:
            flag_running_progress -= self.crawl_ignored_potential
            self.crawl_start_potential = None
        return flag_running_progress + self.potential_leak() * 100


import datetime as dt
from itertools import islice

from flask_restful import Resource, abort, inputs
from flask_restful import reqparse
from sqlalchemy import desc, asc

from db import db
from model.books import BooksModel
from model.transactions import TransactionsModel
from model.users import auth, Roles
from utils.lock import lock

def parse_book(minimal=False):
    str_variable = "" if minimal else ", cannot be left blank"
    parser = reqparse.RequestParser(bundle_errors=True)

    parser.add_argument('isbn', type=int, required=not minimal,
                        help="In this field goes the isbn of the book" + str_variable)
    parser.add_argument('stock', type=int, required=not minimal,
                        help="In this field goes the stock of the book" + str_variable)
    parser.add_argument('vendible', type=inputs.boolean, required=False,
                        help="In this field goes if the book is available" + str_variable)
    parser.add_argument('precio', type=float, required=not minimal,
                        help="In this field goes the price of the book" + str_variable)
    parser.add_argument('titulo', type=str, required=not minimal,
                        help="In this field goes the title of the book" + str_variable)
    parser.add_argument('autor', type=str, required=False,
                        help="In this field goes the author of the book")
    parser.add_argument('editorial', type=str, required=False,
                        help="In this field goes the editorial of the book")
    parser.add_argument('sinopsis', type=str, required=False,
                        help="In this field goes the sinopsis of the book")
    parser.add_argument('url_imagen', type=str, required=False,
                        help="In this field goes the url of the image associated to the book")
    parser.add_argument('fecha_de_publicacion', type=str, required=False,
                        help="In this field goes the date of the book in YYYY-MM-DD format")
    data = parser.parse_args()
    if data["fecha_de_publicacion"] is not None:
        try:
            data["fecha_de_publicacion"] = dt.datetime.strptime(data["fecha_de_publicacion"], '%Y-%m-%d')
        except ValueError:
            abort(400, message={"message": "'fecha_de_publicacion' should have the sytnax: YYYY-MM-DD"})

    return data

def parse_reviews():
    parser = reqparse.RequestParser(bundle_errors=True)
    parser.add_argument('reviews', type=inputs.boolean, required=False,
                        help="Indicates if returning the reviews of the book is needed.")
    parser.add_argument('score', type=inputs.boolean, required=False,
                        help="Indicates if returning the score of the book is needed .")
    return parser.parse_args()

def check_constraints_book(data):
    if data.get("isbn", None) is not None and len(str(data["isbn"])) != 13:
        abort(400, message={"message": "'isbn' should be made by 13 digits"})
    if data.get("stock", None) is not None and data["stock"] < 0:
        abort(400, message={"message": "'stock' can't be negative"})
    if data.get("precio", None) is not None and data["precio"] < 0:
        abort(400, message={"message": "'precio' can't be negative"})
    if data.get("titulo", None) is not None and not data["titulo"]:
        abort(400, message={"message": "'titulo' can't be empty"})
    if data.get("autor", None) is not None and not data["autor"]:
        abort(400, message={"message": "'autor' can't be empty. Use None instead"})
    if data.get("editorial", None) is not None and not data["editorial"]:
        abort(400, message={"message": "'editorial' can't be empty. Use None instead"})
    if data.get("url_imagen", None) is not None and not data["url_imagen"]:
        abort(400, message={"message": "'url_imagen' can't be empty. Use None instead"})
    if data.get("sinopsis", None) is not None and not data["sinopsis"]:
        abort(400, message={"message": "'sinopsis' can't be empty. Use None instead"})

class Books(Resource):

    def get(self, isbn):
        data = parse_reviews()
        with lock:
            book = BooksModel.find_by_isbn(isbn)
        if not book:
            return {"message": f"Book with ['isbn':{isbn}] not found"}, 404
        return {"book": book.json(**data)}, 200

    @auth.login_required(role=Roles.Admin)
    def post(self):
        data = parse_book()
        check_constraints_book(data)
        with lock:
            book = BooksModel.find_by_isbn(data["isbn"])
            if book:
                return {"message": f"A book with same isbn {data['isbn']} already exists"}, 409
            try:
                del data['vendible']  # always set to True when post
                book = BooksModel(**data)
                book.save_to_db()
            except Exception as e:
                return {"message": str(e)}, 500

        return book.json(), 201

    @auth.login_required(role=Roles.Admin)
    def put(self, isbn):
        data = parse_book(minimal=True)
        check_constraints_book(data)
        with lock:
            book = BooksModel.find_by_isbn(isbn)
            if book is None:
                return {"message": "Book with ['isbn': " + str(isbn) + "] Not Found"}, 404
            try:
                book.update_from_db(data)
            except Exception as e:
                return {"message": str(e)}, 500

            return {"book": book.json()}, 200

    @auth.login_required(role=Roles.Admin)
    def delete(self, isbn):
        with lock:
            book = BooksModel.find_by_isbn(isbn)

            if book is None:
                return {"message": f"Book with ['isbn': {isbn}] Not Found"}, 404

            if not book.vendible:
                return {"message": f"Book with ['isbn': {isbn}] was previously removed"}, 409

            try:
                book.delete_from_db()
            except Exception as e:
                return {"message": str(e)}, 500

        return {"message": f"Book with ['isbn': {isbn}] deleted"}, 200

class BooksList(Resource):
    def get(self):
        parser = reqparse.RequestParser(bundle_errors=True)

        parser.add_argument('numBooks', type=int, required=False,
                            help="In this field goes the number of the books to show")
        parser.add_argument('param', type=str, required=False,
                            help="In this field goes the param you want to order")
        parser.add_argument('order', type=str, required=False,
                            help="In this field goes the order (asc, desc) of what you would like to show")
        parser.add_argument('reviews', type=inputs.boolean, required=False,
                            help="Indicates if returning the reviews of the book is needed.")
        parser.add_argument('score', type=inputs.boolean, required=False,
                            help="Indicates if returning the score of the book is needed .")
        parser.add_argument('showOnlyVendibles', type=inputs.boolean, required=False)
        data = parser.parse_args()
        with lock:
            books = db.session.query(BooksModel)
            if data['showOnlyVendibles'] is None or data['showOnlyVendibles']:
                books = books.filter_by(vendible=True)
            if data['param'] is None:
                books = books.limit(data['numBooks']).all()
            else:
                if data['order'] == "asc":
                    books = books.order_by(asc(data['param'])).limit(data['numBooks']).all()
                else:
                    books = books.order_by(desc(data['param'])).limit(data['numBooks']).all()
        return {'books': [book.json(reviews=data['reviews'], score=data['score']) for book in books]}, 200

class SearchBooks(Resource):
    def get(self):
        parser = reqparse.RequestParser(bundle_errors=True)

        parser.add_argument('isbn', type=int, required=False,
                            help="In this field goes the isbn of the book")
        parser.add_argument('titulo', type=str, required=False,
                            help="In this field goes the tittle of the book")
        parser.add_argument('autor', type=str, required=False,
                            help="In this field goes the author of the book")
        parser.add_argument('editorial', type=str, required=False,
                            help="In this field goes the editorial of the book")
        parser.add_argument('reviews', type=inputs.boolean, required=False,
                            help="Indicates if returning the reviews of the book is needed.")
        parser.add_argument('score', type=inputs.boolean, required=False,
                            help="Indicates if returning the score of the book is needed .")
        parser.add_argument('showOnlyVendibles', type=inputs.boolean, required=False)
        data = parser.parse_args()
        check_constraints_book(data)
        if not any(v is not None for k, v in data.items() if k not in ['reviews', 'score', 'showOnlyVendibles']):
            return {"message": "Missing parameters to search by."}, 406

        with lock:
            books = db.session.query(BooksModel)
            if data['showOnlyVendibles'] is None or data['showOnlyVendibles']:
                books = books.filter_by(vendible=True)
            for k, v in data.items():
                if v is not None and k not in ['reviews', 'score', 'showOnlyVendibles']:
                    books = books.filter(getattr(BooksModel, k).like(f"%{v}%"))

        return {'books': [book.json(reviews=data['reviews'], score=data['score']) for book in books]}, 200

class BestSellers(Resource):

    def get(self):
        parser = reqparse.RequestParser(bundle_errors=True)
        parser.add_argument('numBooks', type=int, required=False,
                            help="In this field goes the number of the books to show")
        data = parser.parse_args()
        isbns = TransactionsModel.best_sellers()

        return {'books': list(islice(
            filter(lambda book: book['vendible'], map(lambda x: BooksModel.find_by_isbn(x).json(score=True), isbns)),
                              data['numBooks']))}, 200


import requests
import re
from bs4 import BeautifulSoup
from papago_translation import papago
import math
#url_.py, fetch.py 필요없어서 빼버림. 내가 직접 수동으로 입력해야함 아래 thread_url과 list_를.
thread_url = "https://girlschannel.net/topics/2001112/"
list_ = ['1','3','6','8','200','400','600','800','1000','1001','1040','1400','1499','1500','1501','1999','2000', '2', '5400', '5500']
list_.sort(key=int)
list__ = [ [i for i in list_ if int(i) <= 500*n and int(i) > 500*(n-1)] for n in range(1, math.ceil(int(list_[-1])/500) + 1) ]
#list__ = [ [i for i in list_ if int(i) <= 500*n and int(i) > 500*(n-1)] for n in range(1, int(int(list_[-1])/500) + 2) ] #이건 위에것보다 부정확함. 이걸로해도 상관없긴함. 단지 케이스에따라 마지막에 []빈 list가 생길수있음. 근데 생겨도 상관없음.
print(list__)
res = [ requests.get(f'{thread_url}{i}') for i, j in enumerate(list__, 1) if j ]
soup = [ BeautifulSoup(i.text, 'lxml') for i in res ]
thread_title = soup[0].select(".head-area h1")[0].get_text(strip=True)

thread_opId = set() #걸찬에는 이거 필요없음 어차피 싹다 익명이라 <---다시조사해보니 틀렸음. 익명아니게할수도있음. 근데 모두 익명만 사용하는듯?
def comment_extract(num, soup):
    box = soup.find(id=f'comment{num}')
    datetime = box.p.a.get_text()
    contentbox = box.find("div", class_="body")
    text_jp = contentbox.get_text("\n", strip=True)
    text_kr = papago(text_jp)
    #anchor = contentbox.find("span", class_="res-anchor").get_text() 이걸로할까?아래껄로할까? 상관없을듯...이건 근데 앵커 하나만잡음
    anchor = re.findall(r'>>\d+', text_jp)
    #추천비추천
    updownbox = box.find("div", id=f'vbox{num}')
    plus = updownbox.find("div", class_="icon-rate-wrap-plus").p.get_text()
    minus = updownbox.find("div", class_="icon-rate-wrap-minus").p.get_text()
    #미디어
    media = []
    for i in re.finditer(r'h?ttp.*(jpg|jpeg|png|mp4|gif)', text_jp, re.I):#나중에 확장자 더 필요하면 추가하기
        media.append(i.group(0))
    return num, datetime, text_jp, text_kr, anchor, plus, minus, media,

####아래는 다른것들과 거의 비슷#####
import json
def comment_jsonify(num, datetime, text_jp, text_kr, anchor, plus, minus, media): #위에선 comment_num을 걍 num이라고해버림...
    return {"comment_num": num, "comment_datetime": datetime, "comment_authorId": "익명", "comment_anchor": anchor, "comment_media": media, "comment_text": text_jp, "comment_text_kr": text_kr, "plus": plus, "minus": minus}
def thread_jsonify(thread_url, thread_title, thread_opId, comments):
    thread_title_kr = papago(thread_title)
    return {"thread_url": thread_url, "thread_title": thread_title, "thread_title_kr": thread_title_kr, "thread_opId": thread_opId, "comments": comments}
def comments_jsonify(list__): #나눌수도있겠지만 걍 한번에 1~99999까지 여기서 해결해버리게 짰음. 나중에 나눌려면 나누셈...한 soup(한페이지)만 받아서 하고 다른곳에서 for loop으로 이 함수 불러와서 다시금 append하는식으로 #참고로 list__는없어도됌 그냥 넣음..
    list___ = [i for i in list__ if i] #맨위에 list__를 [['1','250','500'],[],['1001','1444']]처럼 남겨놓은것은, 변수 res때문에, 빈 list를 버릴수가없었다. 하지만 여기서는 버려야한다. list___는 [['1','250','500'], ['1001','1444']] 이런식
    i = [ comment_jsonify(*comment_extract(p, soup[r])) for r, q in enumerate(list___) for p in q ]
    global thread_opId
    thread_opId = list(thread_opId) #set은 JSON파일에 부적합 #global선언하는거 좋지않은거같다. 코드 수정하자?
    return i
def completed(list__):
    comments = comments_jsonify(list__)
    return thread_jsonify(thread_url, thread_title, thread_opId, comments)

def get_valid_filename(s):
    s = str(s).strip().replace(' ', '_')
    return re.sub(r'[\\/*?:"<>|]', '-', s)

def save_completed(list_):
    #with open(f'{save_path}/{get_valid_filename(thread_title)}.json', 'w', encoding="utf-8") as f: #파일명.json으로하면 파일명에 들어가면안되는 문자가 들어갈수도있지않나...
    import datetime
    with open(f'{save_path}/{datetime.datetime.today().strftime("%Y%m%d")}.json', 'w', encoding="utf-8") as f:#위에꺼는 json파일명이 일본어합쳐져서 나오는버전이고, 걍 이거 싫어서 이제는 날짜.json으로 할꺼..그게 이거
        json.dump(completed(list_), f, ensure_ascii=False, indent=2)

#저장경로 configuration
from pathlib import Path
relative_path = "jsons"
save_path = (Path(__file__).parent / relative_path).resolve()

save_completed(list__)


#!/usr/bin/env python

# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
#   Copyright 2009-2018 DataONE
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Parse a PEM (Base64) encoded X.509 v3 certificate.

This is an example on how to use the DataONE Client and Common libraries for Python. It
shows how to:

- Parse a PEM (Base64) encoded X.509 v3 certificate, optionally containing a DataONE
  SubjectInfo extension, to determine which DataONE subjects are authenticated by it.

- Process the lists of equivalent identities and group memberships in a DataONE
  SubjectInfo extension into a list of authenticated DataONE subjects.

Notes:

- This does not require the private key of the certificate and does not validate the
  certificate.

"""
import argparse
import os
import sys

import d1_common.cert.subject_info
import d1_common.cert.x509
import d1_common.util
import d1_common.utils.ulog

def main():
    parser = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument("--debug", action="store_true", help="Debug level logging")
    parser.add_argument(
        "cert_pem_path", help="Path to the .PEM certificate file to check"
    )

    args = parser.parse_args()

    d1_common.utils.ulog.setup(args.debug)

    if not os.path.exists(args.cert_pem_path):
        raise ValueError("No such file: {}".format(args.cert_pem_path))

    with open(args.cert_pem_path, "rb") as f:
        primary_str, subject_info_xml = d1_common.cert.x509.extract_subjects(f.read())

    print("DN: {}".format(primary_str))

    print("SubjectInfo XML doc:")
    if not subject_info_xml:
        print("Not present in certificate")
        return

    print(subject_info_xml)

    subject_set = d1_common.cert.subject_info.extract_subjects(
        subject_info_xml, primary_str
    )

    print("List of authenticated subjects:")

    for subject_str in sorted(subject_set):
        print(subject_str)

if __name__ == "__main__":
    sys.exit(main())


# Default configuration variables

# Files with these extensions will be added to the shop
valid_ext = ['nsp', 'nsz', 'xci', 'zip']

# Shop template file to use
template_name = 'shop_template.jsonc'

# Default shop content if no template is provided
default_shop = {
    'files' : {},
    'directories': []
}

# Scan interval, in minutes
scan_interval = 5


import argparse, pickle
from glob import glob
from os.path import join, isfile, dirname

import numpy as np

import sys; sys.path.insert(0, '..'); sys.path.insert(0, '.')
from util import mkdir2

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--time-info', type=str, required=True)
    parser.add_argument('--out-path', type=str, required=True)
    parser.add_argument('--method-type', type=str, default='det')
    parser.add_argument('--overwrite', action='store_true', default=False)

    opts = parser.parse_args()
    return opts

def main():
    opts = parse_args()
    if not opts.overwrite and isfile(opts.out_path):
        return
    mkdir2(dirname(opts.out_path))

    time_info = pickle.load(open(opts.time_info, 'rb'))
    if opts.method_type == 'det':
        rt_samples = time_info['runtime_all']
        rt_dist = {'type': 'empirical', 'samples': rt_samples}
    elif opts.method_type == 'dat':
        which_cfg_all = np.array(time_info['which_cfg_all'])
        rt_samples = np.array(time_info['runtime_all'])[which_cfg_all == 1]
        rt_samples = rt_samples[rt_samples > 0.002] # ignore zero detection trivial cases
        rt_dist = {'type': 'empirical', 'samples': rt_samples.tolist()}
    else:
        raise ValueError(f'Unknown method type "{opts.method_type}"')
    pickle.dump(rt_dist, open(opts.out_path, 'wb'))

if __name__ == '__main__':
    main()


import time

class Rocket:

    def __init__(self, stages=[], payload=None):
        self.stages = stages
        self.payload = payload

        self.situation = 'LANDED'
        self.activeStage = 0
        self.height = 0

    def launch(self, countdown=0):
        print('NEW MISSON: {}'. format(self.payload.name.upper()))

        self.activeStage = 0

        if self.stages[self.activeStage].thrust > self.getMass():
            print('LIFTOFF IN...')
            for i in range(countdown, 0, -1):
                print(i)
                time.sleep(1)
            print('Successful Liftoff. Rocket currently has mass of {} tons and is producing a thrust of {} kN.'.format(self.getMass(), self.stages[self.activeStage].getThrust()))
            self.situation = 'FLYING'

            time.sleep(3)
            self.burnStage(self.stages[self.activeStage]) # go a distance
        else:
            print('Failure - insufficient thrust!')

    def stageSep(self):
        self.activeStage += 1
        print('Stage {} Burnout. Current Mass is {} tons'.format(self.activeStage, self.getMass()))
        time.sleep(1)
        print('STAND BY FOR STAGE SEPARATION...')

        if len(self.stages) > self.activeStage:
            print('Rocket is now in stage {} burn with thrust of {} KN.'.format(self.activeStage + 1, self.stages[self.activeStage].getThrust()))
            time.sleep(3)
            self.burnStage(self.stages[self.activeStage]) # go a distance
        else:
            print('Payload is now in a parabolic trajectory of {} KM'.format(self.height))

    def burnStage(self, stage):
        self.height += stage.dV
        self.stageSep()

    def getMass(self):
        n = 0
        for i in range(len(self.stages)):
            if i >= self.activeStage:
                n += self.stages[i].mass
        return n + self.payload.mass

class Stage:
    def __init__(self, fuel=0, mass=0, thrust = 0):
        self.mass = mass
        self.fuel = fuel
        self.thrust = thrust
        self.dV = 50

    def getThrust(self):
        return self.thrust if self.fuel > 0 else 0 # only thrust if stage has thrust

class Payload:
    def __init__(self, name='', mass=0):
        self.name = name
        self.mass = mass
    def deploy(self):
        print('Deployment of {} successful!'.format(self.name))

if __name__ == "__main__":
    r = Rocket([Stage(100, 150, 500), Stage(50, 70, 200), Stage(20, 30, 100)], Payload('K1 Sounding Probe', 5))
    r.launch(5)


import tensorflow as tf

from tensorpack.tfutils.argscope import argscope
from tensorpack.models import Conv2D,layer_register,Conv2DTranspose
from tensorpack.tfutils.scope_utils import under_name_scope
from tensorpack.tfutils.summary import add_moving_summary

from basemodel import GroupNorm
from config import config as cfg

class model_mrcnn(object):
    """description of class"""
    pass

@under_name_scope()
def maskrcnn_loss(mask_logits,fg_labels,fg_target_masks):
    num_fg=tf.size(fg_labels)
    indices=tf.stack([tf.range(num_fg),tf.to_int32(fg_labels)-1],axis=1)
    mask_logits=tf.gather_nd(mask_logits,indices)
    mask_probs=tf.sigmoid(mask_logits)

    with tf.name_scope('mask_viz'):
        viz=tf.concat([fg_target_masks,mask_probs],axis=1)
        viz=tf.expand_dims(viz,3)
        viz=tf.cast(viz*255,tf.uint8,name='viz')
        tf.summary.image('mask_truth|pred',viz,max_outputs=10)

    loss=tf.nn.sigmoid_cross_entropy_with_logits(labels=fg_target_masks,logits=mask_logits)
    loss=tf.reduce_mean(loss,name='maskrcnn_loss')

    pred_label=mask_probs>0.5
    truth_label=fg_target_masks>0.5
    accuracy=tf.reduce_mean(tf.to_float(tf.equal(pred_label,truth_label)),name='accuracy')
    pos_accuracy=tf.logical_and(tf.equal(pred_label,truth_label),tf.equal(truth_label,True))
    pos_accuracy=tf.reduce_mean(tf.to_float(pos_accuracy),name='pos_accuracy')
    fg_pixel_ratio=tf.reduce_mean(tf.to_float(truth_label,name='fg_pixel_ratio'))

    add_moving_summary(loss,accuracy,fg_pixel_ratio,pos_accuracy)
    return loss

@layer_register(log_shape=True)
def maskrcnn_upXconv_head(feature,num_category,num_convs,norm=None):
    assert norm in [None,'GN'],norm
    l=feature
    with argscope([Conv2D,Conv2DTranspose],data_format='channels_first',kernel_initializer=tf.variance_scaling_initializer(scale=2.0,mode='fan_out',distribution='normal')):
        for k in range(num_convs):
            l=Conv2D('fcn{}'.format(k),l,cfg.MRCNN.HEAD_DIM,3,activation=tf.nn.relu)
            if norm is not None:
                l=GroupNorm('gn{}'.format(k),l)
        l=Conv2DTranspose('deconv',l,cfg.MRCNN.HEAD_DIM,2,strides=2,activation=tf.nn.relu)
        l=Conv2D('conv',l,num_category,1)
    return l


import shutil
import uuid
import requests
import os

def load_file(path):
    '''
    Returns path of input file. If given parameter 'path' is an url,
    first downloads the file
    '''

    if path.startswith(('https://', 'http://')):
        fileName = path.split('/')[-1]
        filePath = 'data/input/'
        os.makedirs(filePath, exist_ok=True)
        data = requests.get(path, stream=True)
        data.raw.decode_content = True
        with open(filePath+fileName, 'wb+') as f: shutil.copyfileobj(data.raw, f)
        return filePath+fileName
    else:
        path = path.replace('file://', '')
        return path

def expose_file(path):
    '''
    Saves file to make it accessible to API.
    '''
    fileExtension = path.split('.')[-1]
    filePath = 'data/output/'
    fileName = uuid.uuid4().hex + '.' + fileExtension
    new_path = filePath+fileName
    os.makedirs(os.path.dirname(filePath), exist_ok=True)
    shutil.move(path, new_path)
    return new_path


#!/usr/bin/env python
############################################################################
## This software is distributed for free, without warranties of any kind. ##
## Send bug reports or suggestions to hackbarth@gmail.com                 ##
############################################################################

import sys, os, json, audioguide
defaultpath, libpath = audioguide.setup(os.path.dirname(__file__))
sys.path.append(libpath)
# import other audioguide submodules
from audioguide import sfsegment, concatenativeclasses, anallinkage

#######################
## find options file ##
#######################
if len(sys.argv) < 3:
	print('\nPlease specify a soundfile as the first argument, and a json dict to create as a second argument\n')
	sys.exit(1)

file = os.path.realpath(sys.argv[1])
outputfile = os.path.realpath(sys.argv[2])
if not os.path.exists(file):
	print('\nCouldn\'t find a soundfile called "%s"\n'%file)
	sys.exit(1)

# setup analysis parameters
ops = concatenativeclasses.parseOptions(defaults=defaultpath, scriptpath=os.path.dirname(__file__))
AnalInterface = anallinkage.AnalInterface(pm2_bin=ops.PM2_BIN, supervp_bin=ops.SUPERVP_BIN, userWinLengthSec=ops.DESCRIPTOR_WIN_SIZE_SEC, userHopLengthSec=ops.DESCRIPTOR_HOP_SIZE_SEC, resampleRate=ops.IRCAMDESCRIPTOR_RESAMPLE_RATE, windowType=ops.IRCAMDESCRIPTOR_WINDOW_TYPE, F0MaxAnalysisFreq=ops.IRCAMDESCRIPTOR_F0_MAX_ANALYSIS_FREQ, F0MinFrequency=ops.IRCAMDESCRIPTOR_F0_MIN_FREQUENCY, F0MaxFrequency=ops.IRCAMDESCRIPTOR_F0_MAX_FREQUENCY, F0AmpThreshold=ops.IRCAMDESCRIPTOR_F0_AMP_THRESHOLD, forceAnal=ops.DESCRIPTOR_FORCE_ANALYSIS, searchPaths=ops.SEARCH_PATHS)

# load soundfile
handle = sfsegment.sfsegment(file, None, None, AnalInterface.allDescriptors, AnalInterface)
handle.midiPitchMethod = 'f0-seg'

descriptorData = handle.desc.getdict()
descriptorData['f2s'] = AnalInterface.f2s(1)
fh = open(outputfile, 'w')
json.dump(descriptorData, fh)
fh.close()


def dialog_1(mapa_1, plecak_bohatera):
    if "zardzewialy_klucz" in plecak_bohatera:
        print("posiada klucz")
        print("moge dzieki niemu otworzyc drzwi")
        mapa_1[4][5] = " "
        plecak_bohatera.remove("zardzewialy_klucz")
        return mapa_1
    else:
        print("przynies mi klucz a bede mogl otworzyc drzwi")

def dialog_2(plecak_bohatera):
    print("posiadam zwyczajny klucz, wymienie sie z toba w zamian za ksiege czarow")
    print("czy chcesz dokonac wymiany?")
    if input() == "tak":
        if "ksiega_czarow" in plecak_bohatera:
            plecak_bohatera.append("zwyczajny_klucz")
            plecak_bohatera.remove("ksiega_czarow")

        else:
            print("nie posiadasz ksiegi czarow, przynies mi ja na wymiane")
    else:
        print("w takim wypadku zegnaj, do zobaczenia pozniej")

def dialog_3(zycie):
    print("nie podchodz do mnie!")
    zycie = zycie[:-1]
    zycie = zycie[:-1]
def dialog_4():
    print("1")


from django.urls import include, path
from rest_framework.routers import DefaultRouter
from blogs.api import views as qv

router = DefaultRouter()
router.register(r"blogs", qv.BlogViewSet)

urlpatterns = [
    path("", include(router.urls)),

    path("blogs/<slug:slug>/comments/",
         qv.CommentListAPIView.as_view(),
         name="comments-list"),

    path("blogs/<slug:slug>/comment/",
         qv.CommentCreateAPIView.as_view(),
         name="create-comments"),

    path("comments/<int:pk>/",
         qv.CommentRUDAPIView.as_view(),
         name="comment-detail"),

    path("comments/<int:pk>/like/",
         qv.CommentLikeAPIView.as_view(),
         name="comment-like"),

    path("comments/<int:pk>/dislike/",
         qv.CommentDisLikeAPIView.as_view(),
         name="comment-dislike"),

    path("blogs/<int:pk>/like/",
         qv.BlogLikeAPIView.as_view(),
         name="blog-like"),

    path("blogs/<int:pk>/dislike/",
         qv.BlogDisLikeAPIView.as_view(),
         name="blog-dislike"),

]


import csv
import json

def write_csv(file_like, fieldnames, rows):
    writer = csv.DictWriter(file_like, fieldnames=fieldnames)
    writer.writeheader()
    for row in rows:
        writer.writerow(row)

def write_json(file_like, mapping):
    json.dump(mapping, file_like)
    file_like.flush()


from collections import deque
def resolve():
    N = int(input())
    As = list(map(int, input().split(" ")))
    pos = []
    neg = []
    for a in As:
        if a >= 0:
            pos.append(a)
        else:
            neg.append(a)
    pos = deque(sorted(pos))
    neg = deque(sorted(neg))
    x = 0
    y = 0
    ops = []
    while True:
        if len(pos) > 0 and len(neg) > 0:
            if len(pos) > len(neg):
                x = neg.popleft()
                y = pos.pop()
            else:
                x = pos.pop()
                y = neg.popleft()
        elif len(pos) > 1 and len(neg) == 0:
                x = pos.popleft()
                y = pos.pop()
        elif len(neg) > 1 and len(pos) == 0:
                x = neg.pop()
                y = neg.popleft()
        else:
            raise Exception("Unreachable?")

        ops.append("{} {}".format(x, y))
        xmy = x - y

        if len(pos) == 0 and len(neg) == 0:
            print(xmy)
            break

        if xmy >= 0:
            pos.append(xmy)
        else:
            neg.appendleft(xmy)

    [print(i) for i in ops]

if '__main__' == __name__:
    resolve()


import numpy as np
import pandas as pd
import os

root_dir = os.path.abspath('../Dataset')
data_dir = os.path.join(root_dir,'fer2013')

def fer2013():
    """
    Load fer2013 data
    """

    data = pd.read_csv(os.path.join(root_dir,data_dir,'fer2013.csv'))
    train_y = []
    train_x = []
    val_x = []
    val_y = []
    test_x = []
    test_y = []
    for i in range(data.shape[0]):
        if data.Usage[i] == 'Training':
            train_x.append(map(int,data.pixels[i].split(" ")))
            train_y.append(data.emotion[i])
        elif data.Usage[i] == 'PublicTest':
            val_x.append(map(int,data.pixels[i].split(" ")))
            val_y.append(data.emotion[i])
        else:
            test_x.append(map(int,data.pixels[i].split(" ")))
            test_y.append(data.emotion[i])

    train_x = np.asarray(train_x)
    val_x = np.asarray(val_x)
    test_x = np.asarray(test_x)

    train_y = onehot(train_y)
    val_y = onehot(val_y)
    test_y = onehot(test_y)

    train_x = scale(train_x)
    val_x = scale(val_x)
    test_x = scale(test_x)

    train_x = train_x.reshape((train_x.shape[0], 48, 48, 1))
    val_x = val_x.reshape((val_x.shape[0], 48, 48, 1))
    test_x = test_x.reshape((test_x.shape[0], 48, 48, 1))

    return (train_x, train_y), (val_x,val_y), (test_x, test_y)

def onehot(y):
    """
    Transform vector into one-hot representation
    """
    y_oh = np.zeros((len(y), np.max(y)+1))
    y_oh[np.arange(len(y)), y] = 1
    return y_oh

def scale(x):
    """
    Scale data to be between -0.5 and 0.5
    """
    x = x.astype('float') / 255.
    x = x - 0.5
    x = x.reshape(-1, 48*48)
    return x


from utils import backup as bk
from datetime import datetime
from utils.conf_loader import config
import os

def backup():
    backup_blog()

def backup_blog():
    conf = config.get_backup_conf()
    print("[STEP 1] start to compress file")
    now = datetime.now()
    com_file = os.path.join(conf['backup_dir'], '%s_blog.zip' % now.strftime('%Y_%m_%d_'))
    bk.compress_specified_files_in_dir(conf['blog_dir'], ['tale.db', 'upload'], com_file)
    print("[STEP 2] start to upload file")
    r = bk.backup_upload(com_file, bk.BackupType.BLOG)
    print('Upload Result:')
    print(r)
    print("[STEP 3] start to delete old files")
    r = bk.list_backup_cos_files(bk.BackupType.BLOG)
    files_to_delete = {}
    max_days = conf['max_days']
    for bucket, keys in r.items():
        files_to_delete[bucket] = []
        for k in keys:
            if is_file_to_delete(k, max_days):
                files_to_delete[bucket].append(k)
    print('Files to be deleted:')
    print(files_to_delete)
    for bucket, files in files_to_delete.items():
        r = bk.delete_cos_files(bucket, files)
        if r:
            print("delete successfully: %s" % bucket)
        else:
            print("delete failed: %s" % bucket)
    print("[STEP] FINISHED")

def is_file_to_delete(filename, max_days):
    filename = os.path.basename(filename)
    t = datetime.strptime(filename[:10], '%Y_%m_%d')
    now = datetime.now()
    interval = now - t
    if interval.days > max_days:
        return True
    else:
        return False


import xlrd

import matplotlib.pyplot as plt

def open_file(male_path,female_path,country_name):
    """
    Open and read an Excel file
    """
    years = []
    male_population = []
    female_population = []

    book = xlrd.open_workbook(male_path)
    first_sheet = book.sheet_by_index(0)

    i = 0
    for row_value in first_sheet.col_values(2):
        i += 1
        if row_value == country_name:
            break

    j = 5
    while j < 71:
    	years.append(first_sheet.cell(16,j).value)
    	male_population.append(first_sheet.cell(i - 1,j).value)
    	j += 1

    book = xlrd.open_workbook(female_path)
    first_sheet = book.sheet_by_index(0)

    i=0
    for row_value in first_sheet.col_values(2):
        i += 1
        if row_value == country_name:
            break

    j = 5
    while j < 71:
    	female_population.append(first_sheet.cell(i - 1,j).value)
    	j += 1

    data = {}
    data['years'] = years
    data['male_population'] = male_population
    data['female_population'] = female_population

    return data

country_name = input("Please enter country name: ")

data = open_file("Data/WPP2015_POP_F01_2_TOTAL_POPULATION_MALE.XLS", "Data/WPP2015_POP_F01_3_TOTAL_POPULATION_FEMALE.XLS", country_name)

plt.plot(data['years'], data['male_population'], '-o', label='Male')
plt.plot(data['years'], data['female_population'], '-o', color='red', label='Female')
plt.legend(loc='lower right')
plt.savefig('plot3.pdf')
plt.show()


#!/usr/bin/env python

# Copyright 2013 The Chromium Authors. All rights reserved.
# Copyright (c) 2014 Intel Corporation. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import optparse
import os
import sys

GYP_ANDROID_DIR = os.path.join(os.path.dirname(__file__),
                               os.pardir, os.pardir, os.pardir,
                               'build',
                               'android',
                               'gyp')
sys.path.append(GYP_ANDROID_DIR)

import jar
from util import build_utils

def main():
  parser = optparse.OptionParser()
  parser.add_option('--jars', help='The jars to merge.')
  parser.add_option('--jar-path', help='The output merged jar file.')

  options, _ = parser.parse_args()

  with build_utils.TempDir() as temp_dir:
    for jar_file in build_utils.ParseGypList(options.jars):
      build_utils.ExtractAll(jar_file, path=temp_dir, pattern='*.class')
    jar.JarDirectory(temp_dir, [], options.jar_path)

if __name__ == '__main__':
  sys.exit(main())


import os
from ranalyze import scrape

subs = []
with open(os.environ["OPENSHIFT_DATA_DIR"]+"/config.txt", "r") as config_file:
  for line in config_file:
    subs.append(line.strip())
print(subs)
scrape(subs)


import sys
from setuptools import setup, find_packages

version = '1.4.9'

if not '2.5' <= sys.version < '3.0':
    raise ImportError('Python version not supported')

tests_require = ['nose']

setup(name="Searchpy",
      version=version,
      install_requires=['mechanize >= 0.2.4', 'pyquery >= 0.6.1'],

      description="A google interface library",
      long_description="""\ SearchPy simplifies the process of
accessing search engine providers programmatically and also provides useful
tools..

It has a `mercurial repository
<https://ixmatus@bitbucket.org/ixmatus/searchpy>`_ that
you can install from with ``easy_install searchpy``

""",
      classifiers=["Intended Audience :: Developers",
                   "License :: OSI Approved :: Python Software Foundation License",
                   "Programming Language :: Python",
                   "Topic :: Software Development :: Libraries :: Python Modules",
                   ],
      author="Parnell Springmeyer",
      author_email="ixmatus@gmail.com",
      url="http://bitbucket.org/ixmatus/searchpy",
      license="PSF",
      zip_safe=False,
      packages=find_packages(),
      include_package_data=True,
      test_suite='nose.collector',
      tests_require=tests_require
      )


"""
오늘은 스타트링크에 다니는 사람들이 모여서 축구를 해보려고 한다.
축구는 평일 오후에 하고 의무 참석도 아니다.
축구를 하기 위해 모인 사람은 총 N명이고 신기하게도 N은 짝수이다.
이제 N/2명으로 이루어진 스타트 팀과 링크 팀으로 사람들을 나눠야 한다.

BOJ를 운영하는 회사 답게 사람에게 번호를 1부터 N까지로 배정했고,
아래와 같은 능력치를 조사했다.
능력치 Sij는 i번 사람과 j번 사람이 같은 팀에 속했을 때, 팀에 더해지는 능력치이다.
팀의 능력치는 팀에 속한 모든 쌍의 능력치 Sij의 합이다.
Sij는 Sji와 다를 수도 있으며, i번 사람과 j번 사람이 같은 팀에 속했을 때, 팀에 더해지는 능력치는 Sij와 Sji이다.

N=4이고, S가 아래와 같은 경우를 살펴보자.

예를 들어, 1, 2번이 스타트 팀, 3, 4번이 링크 팀에 속한 경우에 두 팀의 능력치는 아래와 같다.
스타트 팀: S12 + S21 = 1 + 4 = 5
링크 팀: S34 + S43 = 2 + 5 = 7

1, 3번이 스타트 팀, 2, 4번이 링크 팀에 속하면, 두 팀의 능력치는 아래와 같다.
스타트 팀: S13 + S31 = 2 + 7 = 9
링크 팀: S24 + S42 = 6 + 4 = 10

축구를 재미있게 하기 위해서 스타트 팀의 능력치와 링크 팀의 능력치의 차이를 최소로 하려고 한다.
위의 예제와 같은 경우에는 1, 4번이 스타트 팀, 2, 3번 팀이 링크 팀에 속하면 스타트 팀의 능력치는 6,
링크 팀의 능력치는 6이 되어서 차이가 0이 되고 이 값이 최소이다.

> input
첫째 줄에 N(4 ≤ N ≤ 20, N은 짝수)이 주어진다. 둘째 줄부터 N개의 줄에 S가 주어진다.
각 줄은 N개의 수로 이루어져 있고, i번 줄의 j번째 수는 Sij 이다.
Sii는 항상 0이고, 나머지 Sij는 1보다 크거나 같고, 100보다 작거나 같은 정수이다.

6
0 1 2 3 4 5
1 0 2 3 4 5
1 2 0 3 4 5
1 2 3 0 4 5
1 2 3 4 0 5
1 2 3 4 5 0

> output
첫째 줄에 스타트 팀과 링크 팀의 능력치의 차이의 최솟값을 출력한다.

2

"""
import sys
sys.stdin = open('14889.txt', 'r')

def CalPoint(nums):
    side_sum = 0
    for i in range(half_leng - 1):
        for j in range(i + 1, half_leng):
            side_sum += mat[nums[i]][nums[j]] + mat[nums[j]][nums[i]]
    return side_sum

def comb(n, r):
    global total_min
    if r == 0:
        other_side = list(set(range(side_N)) - set(one_side))
        one_point = CalPoint(one_side)
        other_point = CalPoint(other_side)
        diff = abs(one_point - other_point)
        if diff < total_min:
            total_min = diff
    elif n < r:
        return
    else:
        one_side[r - 1] = n - 1
        comb(n - 1, r - 1)
        comb(n - 1, r)

side_N = int(input())
mat = [0] * side_N
for i in range(side_N):
    mat[i] = list(map(int, input().split()))

total_min = 100000000
half_leng = side_N // 2
one_side = [0] * half_leng
comb(side_N, half_leng)

print(total_min)

# idea
# 1. combination


##pauseAndUnpauseProgramOnSpaceBarPresses用空白鍵執行與暫停程式
import keyboard
import pyautogui
import random
import string
import time

phrase = str()
n = 0

class Get(object):
    wait = False
    def do_this(self, e):
        self.wait = not self.wait

a = Get()
keyboard.on_press_key("space", a.do_this)
while True:
    if  a.wait:
        if n > 5:
            pyautogui.keyDown("alt")
            pyautogui.press("tab")
            pyautogui.press("tab")
            pyautogui.press("tab")
            pyautogui.keyUp("alt")
            n = 0
        else:
            for i in range(random.randint(1,10)):
                letter = random.choice(string.ascii_letters)
                phrase = phrase + letter
            print(phrase)
            pyautogui.typewrite(phrase)
            pyautogui.press("enter")
            phrase = str()
            n = n + 1
            time.sleep(0.005+0.001*random.randint(1,10))


"""Implements a Bioloid IO Adapter running on an Espruino Pico."""

import pyb
import packet
from bus import BusError

from stm_usb_port import USB_Port
from stm_uart_port import UART_Port

from bus import Bus
from dump_mem import dump_mem
from log import log, log_to_uart

import os
import struct
import sys

RED_LED = pyb.LED(1)
GREEN_LED = pyb.LED(2)

machine = os.uname().machine
if machine.startswith('Espruino Pico'):
    repl_uart_num = 1
    device_uart_num = 2
elif machine.startswith('PYB'):
    repl_uart_num = 4
    device_uart_num = 6
else:
    print("Unrecognized board: '{}'".format(machine))
    sys.exit(1)

repl_uart = pyb.UART(repl_uart_num, 115200)
log_to_uart(repl_uart)
# By putting the REPL on the logging UART, it means that any tracebacks will
# go to the uart.
pyb.repl_uart(repl_uart)

class LedSequence:

    def __init__(self, led, sequence, continuous=True):
        self.led = led
        self.last_toggle = 0
        self.sequence = sequence
        self.continuous = continuous
        self.seq_idx = -1
        self.led.off()
        if self.continuous:
            self.kick()

    def process(self):
        if self.seq_idx >= 0 and pyb.elapsed_millis(self.last_toggle) > self.sequence[self.seq_idx]:
            self.led.toggle()
            self.last_toggle = pyb.millis()
            self.seq_idx += 1
            if self.seq_idx >= len(self.sequence):
                if self.continuous:
                    self.seq_idx = 0
                else:
                    self.seq_idx = -1
                    self.led.off()      # Just in case we got an odd length

    def kick(self):
        if self.seq_idx < 0:
            self.seq_idx = 0
            self.led.on()
            self.last_toggle = pyb.millis()

class HeartBeat(LedSequence):

    def __init__(self, led):
        super().__init__(led, (20, 180, 20, 780), continuous=True)

class Activity(LedSequence):

    def __init__(self, led):
        super().__init__(led, (20, 20), continuous=False)

class Scanner(object):

    def __init__(self, bus):
        self.bus = bus
        self.ids = []

    def dev_found(self, bus, dev_id):
        # We want to read the model and version, which is at offset 0, 1,
        # and 2 so we do it with a single read.
        try:
            data = bus.read(dev_id, 0, 3)
        except BusError:
            log('Device {} READ timed out'.format(dev_id))
            return
        model, version = struct.unpack('<HB', data)
        log('  ID: {:3d} Model: {:5d} Version: {:5d}'.format(dev_id, model, version))
        self.ids.append(dev_id)

    def scan_range(self, start_id=1, num_ids=32):
        log('Scanning IDs from', start_id, 'to', start_id + num_ids)
        try:
            self.bus.scan(start_id, num_ids, self.dev_found, None)
        except BusError:
            log('Timeout')

    def scan(self):
        self.ids = []
        self.scan_range(0, 32)
        self.scan_range(100, 32)
        if len(self.ids) == 0:
            log('No devices found')
        else:
            log('Scan done')

heartbeat = HeartBeat(RED_LED)
activity = Activity(GREEN_LED)
host_uart = USB_Port()
device_uart = UART_Port(device_uart_num, baud=1000000)

button = pyb.Switch()

pkt = packet.Packet()
rsp = packet.Packet()

log('Pico Adapter - Bioloid Packet Forwarder')
log('Control-C - Quit')
log('s - Scan Bus')
log('d - Debug - Show Packets')
show = Bus.SHOW_NONE
while True:
    heartbeat.process()
    activity.process()
    byte = host_uart.read_byte()
    if byte is not None:
        rc = pkt.process_byte(byte)
        if rc != packet.ErrorCode.NOT_DONE:
            activity.kick()
            device_uart.write_packet(pkt.pkt_bytes)
            if show & Bus.SHOW_PACKETS:
                dump_mem(pkt.pkt_bytes, prefix='  H->D', show_ascii=False, log=log)

    if device_uart.any():
        byte = device_uart.read_byte()
        rc = rsp.process_byte(byte)
        if rc != packet.ErrorCode.NOT_DONE:
            activity.kick()
            host_uart.write_packet(rsp.pkt_bytes)
            if show & Bus.SHOW_PACKETS:
                dump_mem(rsp.pkt_bytes, prefix='  D->H', show_ascii=False, log=log)

    if repl_uart.any():
        byte = repl_uart.readchar()
        if byte == 3:  # Control-C
            log('Control-C')
            raise KeyboardInterrupt
        elif byte == ord('d'):
            show ^= Bus.SHOW_PACKETS
            log('Show Packets:', bool(show & Bus.SHOW_PACKETS))
        elif byte == ord('s'):
            Scanner(Bus(device_uart, show=show)).scan()
    if button():
        log('Control-C via Button')
        raise KeyboardInterrupt
    pyb.wfi()


import unittest

import os
import time
import itertools
import threading
import Queue as queue
import weakref
import pdb

import sys
sys.path += [os.path.normpath(os.path.join(os.path.dirname(__file__), ".."))]
import cachelib # Module-under-test

#
# -----------------------------------------------------------------------------
#
# Helper classes
#

class MethodTask(object):
  def __init__(self, instance, methodName):
    self.instance = weakref.ref(instance)
    self.methodName = methodName
    return

  def is_alive(self):
    return not self.instance() is None

  def __call__(self):
    instance = self.instance()
    if instance is None:
      return # We have a dead ref -- simply do nothing
    return  getattr(instance, self.methodName)()

class BackgroundExecuter(object):
  """A dummy background executer

  Normally, background tasks run on their own thread, and run e.g. at specific
  intervals / times.
  """
  def __init__(self):
    self.tasks = []
    return

  def register_method(self, instance, methodName):
    self.tasks += [MethodTask(instance, methodName)]
    return

  def execute(self):
    # Remove dead tasks
    self.tasks = [t for t in self.tasks if t.is_alive()]
    for t in self.tasks:
      t()
    return
#
# -----------------------------------------------------------------------------
#
class TestExpiringMemCache(unittest.TestCase):
  def test_insert_expire_clear(self):
    EXPIRE_SECS = 0.1
    cache = cachelib.ExpiringMemCache(EXPIRE_SECS, None)

    # Do this multiple times to make sure things are working after clear()
    for i in xrange(3):
      f = itertools.count().next
      assert len(cache) == 0
      self.assertEqual(cache.get_cached(0, f), 0)

      time.sleep(0.5*EXPIRE_SECS)
      self.assertEqual(cache.get_cached(1, f), 1)
      self.assertEqual(cache.get_cached(0, f), 0)
      self.assertEqual(cache.get_cached(0, f), 0)
      self.assertEqual(cache.get_cached(1, f), 1)

      time.sleep(0.6*EXPIRE_SECS)
      self.assertEqual(cache.get_cached(0, f), 2)
      self.assertEqual(cache.get_cached(1, f), 1)

      time.sleep(0.6*EXPIRE_SECS)
      self.assertEqual(cache.get_cached(0, f), 2)
      self.assertEqual(cache.get_cached(1, f), 3)

      time.sleep(1.1*EXPIRE_SECS)
      self.assertEqual(cache.get_cached(0, f), 4)
      self.assertEqual(cache.get_cached(1, f), 5)

      self.assertEqual(len(cache), 2)
      self.assertTrue(0 in cache)
      self.assertTrue(1 in cache)
      self.assertFalse("abc" in cache)

      cache.clear()
    return

  def test_insert_expire_args(self):
    def echo(*pargs, **kwargs):
      return pargs, kwargs

    EXPIRE_SECS = 0.1
    cache = cachelib.ExpiringMemCache(EXPIRE_SECS, None)
    f = echo
    pargs, kwargs = (0,),dict(a=0)
    self.assertEqual(cache.get_cached(0, f, pargs, kwargs),
                     (pargs, kwargs))

    time.sleep(0.5*EXPIRE_SECS)
    pargs2, kwargs2 = (1,),dict(b=1)
    self.assertEqual(cache.get_cached(1, f, pargs, kwargs),
                     (pargs, kwargs))
    self.assertEqual(cache.get_cached(0, f, pargs2, kwargs2),
                     (pargs, kwargs))
    self.assertEqual(cache.get_cached(0, f, pargs2, kwargs2),
                     (pargs, kwargs))
    self.assertEqual(cache.get_cached(1, f, pargs2, kwargs2),
                     (pargs, kwargs))

    time.sleep(0.6*EXPIRE_SECS)
    pargs3, kwargs3 = (3,),dict(c=3)
    self.assertEqual(cache.get_cached(0, f, pargs3, kwargs3),
                     (pargs3, kwargs3))
    self.assertEqual(cache.get_cached(1, f, pargs3, kwargs3),
                     (pargs, kwargs))

    time.sleep(0.6*EXPIRE_SECS)
    pargs4, kwargs4 = (4,),dict(d=4)
    self.assertEqual(cache.get_cached(0, f, pargs4, kwargs4),
                     (pargs3, kwargs3))
    self.assertEqual(cache.get_cached(1, f, pargs4, kwargs4),
                     (pargs4, kwargs4))

    time.sleep(1.1*EXPIRE_SECS)
    pargs5, kwargs5 = (5,),dict(e=5)
    self.assertEqual(cache.get_cached(0, f, pargs5, kwargs5),
                     (pargs5, kwargs5))
    self.assertEqual(cache.get_cached(1, f, pargs5, kwargs5),
                     (pargs5, kwargs5))

    self.assertEqual(len(cache), 2)
    self.assertTrue(0 in cache)
    self.assertTrue(1 in cache)
    self.assertFalse("abc" in cache)
    return

  def test_insert_expire_multi(self):
    EXPIRE_SECS = 0.1
    cache = cachelib.ExpiringMemCache(EXPIRE_SECS, None)
    f = itertools.count().next

    self.assertEqual(cache.get_cached_multi([0,1], f), [0,1])

    time.sleep(1.1*EXPIRE_SECS)
    self.assertEqual(cache.get_cached(0, f), 2)

    time.sleep(0.6*EXPIRE_SECS)
    self.assertEqual(cache.get_cached_multi([0,1], f), [2,3])

    time.sleep(0.6*EXPIRE_SECS)
    self.assertEqual(cache.get_cached_multi([0,1], f), [4,3])

    self.assertEqual(len(cache), 2)
    self.assertTrue(0 in cache)
    self.assertTrue(1 in cache)
    self.assertFalse("abc" in cache)
    return

  def test_maxNumKeys(self):
    EXPIRE_SECS = 0.1
    maxNumKeys = 2
    cache = cachelib.ExpiringMemCache(EXPIRE_SECS, maxNumKeys)
    f = itertools.count().next

    self.assertEqual(cache.get_cached(0, f), 0)
    self.assertEqual(len(cache), 1)
    self.assertTrue(0 in cache)
    self.assertFalse(1 in cache)

    self.assertEqual(cache.get_cached(1, f), 1)
    self.assertEqual(len(cache), 2)
    self.assertTrue(0 in cache)
    self.assertTrue(1 in cache)

    self.assertEqual(cache.get_cached(0, f), 0)
    self.assertEqual(len(cache), 2)
    self.assertTrue(0 in cache)
    self.assertTrue(1 in cache)

    # Overflow here
    self.assertEqual(cache.get_cached(2, f), 2)
    self.assertEqual(len(cache), 2)

    self.assertFalse(0 in cache)
    self.assertTrue(1 in cache)
    self.assertTrue(2 in cache)

    time.sleep(1.1*EXPIRE_SECS)
    self.assertEqual(cache.get_cached(0, f), 3)
    self.assertEqual(len(cache), 1)

    return

  def test_maxNumKeys_cleanup(self):
    EXPIRE_SECS = 0.1
    maxNumKeys = 2

    cache1 = cachelib.ExpiringMemCache(EXPIRE_SECS, maxNumKeys)
    f1 = itertools.count().next
    cache2 = cachelib.ExpiringMemCache(EXPIRE_SECS, maxNumKeys,
                                       selfCleanup=False)
    f2 = itertools.count().next

    for cache,f,cleaned in [(cache1,f1,True), (cache2,f2,False)]:
      self.assertEqual(cache.get_cached(0, f), 0)
      self.assertEqual(len(cache), 1)
      self.assertTrue(0 in cache)
      self.assertFalse(1 in cache)

      self.assertEqual(cache.get_cached(1, f), 1)
      self.assertEqual(len(cache), 2)
      self.assertTrue(0 in cache)
      self.assertTrue(1 in cache)

      self.assertEqual(cache.get_cached(0, f), 0)
      self.assertEqual(len(cache), 2)
      self.assertTrue(0 in cache)
      self.assertTrue(1 in cache)

      # Overflow here
      self.assertEqual(cache.get_cached(2, f), 2)
      if cleaned:
        self.assertEqual(len(cache), 2)
        self.assertFalse(0 in cache)
      else:
        self.assertEqual(len(cache), 3)
        self.assertTrue(0 in cache)

      self.assertTrue(1 in cache)
      self.assertTrue(2 in cache)

      time.sleep(1.1*EXPIRE_SECS)
      self.assertEqual(cache.get_cached(0, f), 3)
      if cleaned:
        self.assertEqual(len(cache), 1)
      else:
        self.assertEqual(len(cache), 3)

    return

  def test_threaded_parallel(self):
    """Test basica parallel access to a cache

    This test uses threads and tries to time certain events. Timing is a bit
    inaccurate, so we use fudge factors. This test may actually fail if the
    fudge factors are not sufficient.
    """
    flock = threading.Lock()
    EXPIRE_TIME = 1.0
    CALC_TIME = 0.2
    T1_START_TIME = 0.1

    def f(cnt, key):
      """Takes about 0.2s to calculate"""
      time.sleep(CALC_TIME)
      with flock:
        return count.next()

    def worker(slp, cache, func, cnt, key, q):
      time.sleep(slp)
      res = cache.get_cached(key, func, (cnt,key))
      q.put((key,res))
      return

    cache = cachelib.ExpiringMemCache(expireSecs=EXPIRE_TIME, maxNumKeys=None)
    count = itertools.count()
    q = queue.Queue()

    # 0,0
    t0 = threading.Thread(target=worker, args=(0., cache, f, count,0, q))
    # 1,1 -- while t0 is busy calculating
    t1 = threading.Thread(target=worker, args=(T1_START_TIME, cache, f, count,1, q))

    threads = [t0,t1]
    for t in threads:
      t.daemon = True

    startTime = time.time()
    for t in threads:
      t.start()
    for t in threads:
      t.join()
    endTime = time.time()

    result = []
    sentinel = object()
    q.put(sentinel)
    x = q.get()
    while not x is sentinel:
      result += [ x ]
      x = q.get()

    self.assertEqual(result, [(0,0), (1,1)])

    # Need fudge factor 0.001?!?!
    self.assertTrue( endTime-startTime >= T1_START_TIME + CALC_TIME - 0.001 ,
                     msg="startTime: %s, endTime: %s, endTime-startTime:%s" % (
                       startTime, endTime, endTime-startTime))
    self.assertEqual( len(cache), 2 )
    # Use implementation details :-(
    t0StartTime = cache.data[0].expireTime - EXPIRE_TIME
    t1StartTime = cache.data[1].expireTime - EXPIRE_TIME
    self.assertTrue( t0StartTime < t1StartTime )
    self.assertTrue( t1StartTime < t0StartTime + CALC_TIME )
    self.assertAlmostEqual(t1StartTime-t0StartTime, T1_START_TIME, places=2)
    return

  def test_bg_cleanup(self):
    bgExecuter = BackgroundExecuter()

    EXPIRE_SECS = 0.1
    maxNumKeys = 2
    cache = cachelib.ExpiringMemCache(EXPIRE_SECS, maxNumKeys,
                                      selfCleanup=False,
                                      bgCleanup=bgExecuter)
    f = itertools.count().next

    self.assertEqual(cache.get_cached(0, f), 0)
    self.assertEqual(cache.get_cached(1, f), 1)
    self.assertEqual(cache.get_cached(2, f), 2)
    time.sleep(0.06)
    self.assertEqual(cache.get_cached(3, f), 3)

    self.assertEqual(len(cache), 4)
    bgExecuter.execute()
    self.assertEqual(len(cache), 2)
    assert 2 in cache
    assert 3 in cache

    time.sleep(0.06)
    self.assertEqual(len(cache), 2)
    assert 2 in cache
    assert 3 in cache
    bgExecuter.execute()

    self.assertEqual(len(cache), 1)
    assert 3 in cache

    time.sleep(0.06)
    self.assertEqual(len(cache), 1)
    assert 3 in cache
    self.assertEqual(cache.get_cached(0, f), 4)
    self.assertEqual(len(cache), 2)
    assert 3 in cache
    bgExecuter.execute()
    assert not 3 in cache

    del cache
    self.assertEqual(len(bgExecuter.tasks), 1)
    bgExecuter.execute()
    self.assertEqual(len(bgExecuter.tasks), 0)
    return

  #
  # Decorator tests
  #
  def test_dec_insert_expire(self):
    count = itertools.count()
    EXPIRE_SECS = 0.1

    @cachelib.ExpiringMemCache.cached(EXPIRE_SECS, None)
    def f(key, cnt, z):
      if not z=="z":
        raise KeyError(z)
      return cnt.next()

    kwargs = dict(z="z")

    self.assertRaises(KeyError, f, 0,count, z="a")

    self.assertEqual(f(0, count, **kwargs), 0)

    time.sleep(0.5*EXPIRE_SECS)
    self.assertEqual(f(0, count, **kwargs), 0)
    self.assertEqual(f(0, count, **kwargs), 0)
    self.assertEqual(f(1, count, **kwargs), 1)

    time.sleep(0.6*EXPIRE_SECS)
    self.assertEqual(f(0, count, **kwargs), 2)
    self.assertEqual(f(1, count, **kwargs), 1)

    time.sleep(0.6*EXPIRE_SECS)
    self.assertEqual(f(0, count, **kwargs), 2)
    self.assertEqual(f(1, count, **kwargs), 3)

    time.sleep(1.1*EXPIRE_SECS)
    self.assertEqual(f(0, count, **kwargs), 4)
    self.assertEqual(f(1, count, **kwargs), 5)

    return

  def test_dec_threaded(self):
    """Multiple threads using a cached function

    This test is all about timing. Note that there are 3 time parameters of
    interest: 1. start time of a query, 2. duration of calculation, 3. expire
    time.

    Consider the following diagram with 2 threads:

      T_0                   T_1
       |                     |
       | query key A         |
       |   calc result       |
       |         ^           |
       |         |           | query key B
       |      calc time      | return cached result
       |         |           |
       |         |           |
       |         v           |
       |   cache result      |
       |                     |
       | return result       |
       |                     |

    As shown above, a thread that queries first may gets its result later if
    another thread asks for a cached result. Note that results only expire
    relative to the *cache time* of the result, and *not* the start time of
    the associated query.
    """
    flock = threading.Lock()

    @cachelib.ExpiringMemCache.cached(expireSecs=1.0, maxNumKeys=None)
    def f(cnt, key):
      """Takes about 0.2s to calculate"""
      time.sleep(0.2)
      with flock:
        return count.next()

    def worker(slp, func, cnt, key, q):
      time.sleep(slp)
      res = func(cnt,key)
      q.put((key,res))
      return

    count = itertools.count()
    q = queue.Queue()

    # 0,0
    t0 = threading.Thread(target=worker, args=(0., f, count,0, q))
    # 1,1 -- while t0 is busy calculating
    t1 = threading.Thread(target=worker, args=(0.1, f, count,1, q))
    # 0,0 -- wait for result,cached, returned before t1
    t2 = threading.Thread(target=worker, args=(0.15, f, count,0, q))
    # 0,0 -- no waiting for result, cached, returned before t1
    t3 = threading.Thread(target=worker, args=(0.22, f, count,0, q))
    # 0,2 -- expired
    t4 = threading.Thread(target=worker, args=(1.22, f, count,0, q))

    threads = [t0,t1,t2,t3,t4]
    for t in threads:
      t.daemon = True

    for t in threads:
      t.start()

    for t in threads:
      t.join()

    result = []
    sentinel = object()
    q.put(sentinel)
    x = q.get()
    while not x is sentinel:
      result += [ x ]
      x = q.get()

    self.assertEqual(result, [(0,0), (0,0), (0,0), (1,1), (0,2)])
    return

  def test_shared_cached(self):
    flock = threading.Lock()
    glock = threading.Lock()

    EXPIRE_SECS = 1.0
    cache = cachelib.ExpiringMemCache(EXPIRE_SECS, maxNumKeys=4)

    @cachelib.cached(cache)
    def f(cnt, key):
      """Takes about 0.2s to calculate"""
      time.sleep(0.2)
      with flock:
        return count.next()

    @cachelib.cached(cache)
    def g(cnt, key):
      """Takes about 0.3s to calculate"""
      time.sleep(0.3)
      with glock:
        return count.next()

    count = itertools.count()

    self.assertEqual(f(count, 0), 0) # @ 0.0s
    self.assertEqual(g(count, 0), 1) # @ 0.2s
    self.assertEqual(f(count, 0), 0) # @ 0.5s
    self.assertEqual(f(count, 1), 2) # @ 0.5s
    self.assertEqual(g(count, 1), 3) # @ 0.7s

    self.assertEqual(len(cache), 4)

    time.sleep(0.25) # @ 1.0 s
    self.assertEqual(f(count, 0), 4) # @ 1.25s
    self.assertEqual(g(count, 0), 1) # @ 1.45s

    time.sleep(0.10) # @ 1.45 s
    self.assertEqual(g(count, 0), 5) # @ 1.55s
    self.assertEqual(len(cache), 4)

    return

#
# -----------------------------------------------------------------------------
#
class TestParallelExpiringMemCache(unittest.TestCase):
  def test_multi(self):
    CALC_TIME = 1.0
    EXPIRE_SECS = 1.2

    flock = threading.Lock()
    def f(cnt, key):
      """Takes about 0.2s to calculate"""
      time.sleep(CALC_TIME)
      with flock:
        return count.next()

    count = itertools.count()
    cache = cachelib.ExpiringParallelMemCache(EXPIRE_SECS, maxNumKeys=4)

    t0 = time.time()
    key = range(5)
    pargs = [(count, i) for i in key]

    result = cache.get_cached_multi(key, f, pargs)
    t1 = time.time()

    assert set(result) == set(key)
    assert t1-t0 < 1.1*CALC_TIME # Serial would take 5 * CALC_TIME

    n = count.next()
    time.sleep(EXPIRE_SECS + 0.01)
    r1 = cache.get_cached(1, f, (count,1))
    r3 = cache.get_cached(3, f, (count,3))
    assert r1 == n+1
    assert r3 == n+2

    t2 = time.time()
    result = cache.get_cached_multi(key, f, pargs)
    t3 = time.time()
    assert result[1] == r1
    assert result[3] == r3

    for x in [0,2,4]:
      assert result[x] > r3
    assert t3-t2 < 1.1*CALC_TIME # Serial would take 3 * CALC_TIME
    return

#
# =============================================================================
#
if __name__ == '__main__':
  unittest.main()


# Create a method that decrypts reversed-order.txt
def decrypt(file_name):
    try:
        file = open(file_name, 'r')
        lines = file.readlines()
        file.close()

        lines.reverse()

        file = open("normal-order.txt", 'a')
        for line in lines:
            file.write(line)
        file.close()
    except:
        print("any problem")

decrypt("reversed-order.txt")


# https://www.geeksforgeeks.org/radix-sort/

def counting_sort(arr, base):
  n = len(arr)
  result = [0] * n
  counts = [0] * 10

  for i in range(n):
    index = int(arr[i] / base) % 10
    counts[index] += 1

  for i in range(1, 10):
    counts[i] += counts[i-1]

  for i in range(n):
    index = int(arr[i] / base) % 10
    result[counts[index]-1] = arr[i]
    counts[index] -= 1

  for i in range(n):
    arr[i] = result[i]

def sort(arr):
  val = max(arr)
  i = 1
  while 0 < int(val / i):
    counting_sort(arr, i)
    i *= 10

if __name__ == '__main__':
  arr = [170, 45, 75, 90, 802, 24, 2, 66]
  sort(arr)
  print(arr)


class Talker:
    def __init__(self):
        self.text = ''
        self.volume = 80
        self.pitch_voice = 50
        self.voice_speed = 50
        self.voice = 'Microsoft Irina Desktop'

    def set_par(self, par:str, value:int):
        if par == 'volume':
            self.volume = value
            return
        if par == 'pitch_voice':
            self.pitch_voice = value
            return
        if par == 'voice_speed':
            self.voice_speed = value
            return


import tensorflow as tf
import numpy as np

class img_pred:
    def __init__(self, opt_addr):
        # initialize/ load
        self.saver=tf.train.import_meta_graph(opt_addr+".meta")
        self.sess = tf.InteractiveSession()
        print("Meta_Graph Imported")

        # parameters save
        self.saver.restore(self.sess, opt_addr)
        print("Parameters Restored")

        # variables
        self.graph=tf.get_default_graph()
        self.X=self.graph.get_tensor_by_name('X:0')
        self.pred=self.graph.get_tensor_by_name('pred:0')
        self.p_keep_conv=self.graph.get_tensor_by_name('p_keep_conv:0')
        self.p_keep_hidden=self.graph.get_tensor_by_name('p_keep_hidden:0')
        print("Variables Saved")

    def number(self, dataarray):
        data = dataarray
        #classification result
        self.result=self.sess.run(self.pred, feed_dict={self.X: data, self.p_keep_conv: 1.0, self.p_keep_hidden: 1.0})
        return(self.result)

A=img_pred("/Users/kimseunghyuck/desktop/git/KYLius-method/x_ksh/optmnist/optmnist")

import pandas as pd
result=[]
arrayx=pd.read_csv("/Users/kimseunghyuck/desktop/git/KYLius-method/x_ksh/testmnist.csv")
arrayx[:5]
arrayx.shape #(28000, 784)
arrayx.iloc[1,:].reshape(-1, 784)

for i in range(28000):
    result.append(A.number(arrayx.iloc[i,:].reshape(-1, 784)))

path='/Users/kimseunghyuck/desktop/'

submission={}
i=0
for k in range(28000):
    submission[k+1]=result[i][0]
    i+=1

#파일 아웃풋
mnist1=pd.DataFrame([[k,v] for k,v in iter(submission.items())],columns=["ImageId","Label"])

mnist1.to_csv(path+'mnist1.csv', header=True, index=False, sep='\t')


def min_length_pattern_match(string, pattern):
    # takes complete string and find the smallest window in which pattern can be found
    n = int(len(string))
    m = int(len(pattern))

    if n < m:
        print("No such window exists")
        return ""

    # first we create a hash map to store the occurences of characters in pattern and string
    hash_str = [0]*256
    hash_pat = [0]*256

    # fill the map for patern
    for i in pattern:
        hash_pat[ord(i)] += 1

    # traverse through the string to get a window
    min_len = 50000000
    start = 0
    start_ind = -1
    count = 0

    # print(string, pattern)

    for i in range(0, n):

        # add the current character to the hash_str
        hash_str[ord(string[i])] += 1

        # if string's character matches with
        # pattern character then increment count
        if(hash_pat[ord(string[i])] != 0 and hash_str[ord(string[i])] <= hash_pat[ord(string[i])]):
            count += 1

        if(count == m):

            # Try to minimize the window i.e., check if
            # any character is occurring more no. of times
            # than its occurrence in pattern, if yes
            # then remove it from starting and also remove
            # the useless characters.

            while(hash_str[ord(string[start])] > hash_pat[ord(string[start])] or hash_pat[ord(string[start])] == 0):

                if(hash_str[ord(string[start])] > hash_pat[ord(string[start])]):
                    hash_str[ord(string[start])] -= 1
                start += 1

            # update window size
            len_window = i-start+1
            if min_len > len_window:

                min_len = len_window
                start_ind = start

    if start_ind == -1:
        print("No such window exists")
        return ""

    # return substring starting from
    # start_ind and length min_len
    return string[start_ind:start_ind + min_len]

# main function
if __name__ == "__main__":

    com_str = input()
    patter_find = input()
    print(min_length_pattern_match(com_str, patter_find))


# Colocar em ordem crescente sem sort()

valores = list()

for c in range(0, 5):
    num = int(input(f"Digite o {c}° número: "))
    if c == 0 or num > valores[-1]:
        valores.append(num)
    else:
        pos = 0
        while pos < len(valores):
            if num <= valores[pos]:
                valores.insert(pos, num)
                break
            pos += 1
print(f"Você digitou os valores {valores}")


import random
import csv
import copy
import sys, tty, termios
from termcolor import colored

def roll_a_dice(k):

    roll = random.randint(1,k)

    return roll

def spawn():
##set up base stats

    character_stats = [
    {"strenght" : roll_a_dice(20)},
    {"endurance" : roll_a_dice(20)},
    {"agility" : roll_a_dice(20)},
    {"dexterity" : roll_a_dice(20)},
    {"perception" : roll_a_dice(20)},
    {"intelligence" : roll_a_dice(20)},
    {"focus" : roll_a_dice(20)},
    {"health" : roll_a_dice(100)}
    ]
##info screen

    # with open('class_specifikation.txt', 'r') as chars:
    #     chars.readlines()
    #     for lines in chars:
    #         print(lines)
##basic stats
    strenght = "strenght"
    endurance = "endurance"
    agility = "agility"
    dexterity = "dexterity"
    perception = "perception"
    intelligence = "intelligence"
    focus = "focus"
###CHOOSE CLASS """BERSERKER, MAGE, ASSASIN"""
    index_correction = -1
    print("""
                [1] BERSERKER
                [2] MAGE
                [3] ASSASIN
                                """)

    school = int(input('_from 1-3__:')) + index_correction

    print("""
                [1] AN ELDER
                [2] A YOUNG ADVENTURER
                [3] AN EXPERIENCED WITCH
                [4] A YOUNG MISTRESS
                                """)

    age = int(input('_from 1-4__:')) + index_correction

    print("""
                [1] VAMPIRE
                [2] NIGHTELF
                [3] HUMAN
                [4] AQUIR
                                """)

    race = int(input('_from 1-4__:')) + index_correction

##guilde, #school<-
    berserker = [strenght , endurance , agility]
    mage = [dexterity , intelligence , focus]
    assasin = [agility , dexterity, perception]

    guilde = [berserker, mage, assasin]

##gender #age<-
    man = [strenght , endurance , agility , dexterity]
    woman = [dexterity , perception, intelligence , focus]
    boy = [agility , dexterity , perception]
    girl = [perception , intelligence , focus]

    gender = [man, woman, boy, girl]

##species #<--race
    vampire = [strenght, endurance, agility, perception]
    nightelf = [endurance, agility, dexterity, focus]
    human = [endurance, intelligence]
    aquir = [dexterity, perception, intelligence, focus]

    species = [vampire, nightelf, human, aquir]

    for stats in range(len(character_stats)):
        for keys in character_stats[stats]:
            if keys in species[race]:
                character_stats[stats][keys] += 10
                print(keys, 'has raised by born')
        # else:
        #     character_stats[stats] -= 5
        #     print(stats, 'lower')
            if keys in gender[age]:
                character_stats[stats][keys] += 10
                print(keys, 'has raised by experience')
        # else:
        #     character_stats[stats] -= 5
        #     print(stats, 'lower')
            if keys in guilde[school]:
                character_stats[stats][keys] += 10
                print(keys, 'has raised by train')
                print()
        # else:
        #     character_stats[stats] -= 5
        #
    # print(character_stats)

    return character_stats

def battle_stats(character_stats):
#{'strenght'}, {'endurance'}, {'agility'}, {'dexterity'}, {'perception'}, {'intelligence'}, {'focus'}, {'health'}

    strenght = character_stats[0]
    endurance = character_stats[1]
    agility = character_stats[2]
    dexterity = character_stats[3]
    perception = character_stats[4]
    intelligence = character_stats[5]
    focus = character_stats[6]

##BASIC ATTACK AND DEFENSE STATS
    physical_speed = {"physical_speed" : int(agility["agility"]) + int(dexterity["dexterity"]) + int(perception["perception"]) // (int(strenght["strenght"])*2)}
    character_stats.append(physical_speed)

    magic_speed = {"magic_speed" : int(perception["perception"]) + int(intelligence["intelligence"]) // int(focus["focus"])}
    character_stats.append(magic_speed)

    melee_attack = {"melee_attack" : int(strenght["strenght"]) + (int(endurance["endurance"]) - 10) + int(agility["agility"]) + (int(dexterity["dexterity"]) - 10) + (int(perception["perception"]) - 10)}
    character_stats.append(melee_attack)

    melee_defense = {"melee_defense" : int(strenght["strenght"]) + (int(endurance["endurance"]) - 10) + int(agility["agility"]) + (int(dexterity["dexterity"]) - 5) + (int(perception["perception"]) - 5)}
    character_stats.append(melee_defense)

    ranged_attack = {"ranged_attack" : (int(strenght["strenght"]) - 10) + (int(agility["agility"]) - 10) + int(dexterity["dexterity"]) + int(perception["perception"]) + (int(focus["focus"]) - 10)}
    character_stats.append(ranged_attack)

    ranged_defense = {"ranged_defense" : (int(strenght["strenght"]) - 15) + int(agility["agility"]) + (int(dexterity["dexterity"]) - 10) + int(perception["perception"]) + (int(focus["focus"]) - 10)}
    character_stats.append(ranged_defense)

    magic_attack = {"magic_attack" : (int(agility["agility"]) - 10) + (int(dexterity["dexterity"]) - 10) + (int(perception["perception"]) - 10) + int(intelligence["intelligence"]) + int(focus["focus"])}
    character_stats.append(magic_attack)

    magic_defense = {"magic_defense" : (int(endurance["endurance"]) - 10) + (int(agility["agility"]) - 15) + (int(dexterity ["dexterity"]) - 10) + int(perception["perception"]) + (int(intelligence["intelligence"]) - 10) + (int(focus["focus"]) - 10)}
    character_stats.append(magic_defense)

    return character_stats