# this implementation of deep q learning is highly specialized and integrated with this program and the environment it uses
# it cannot be used in general cases, or even exist in a separate file, because it makes many references to local variables
class OPIQ_Agent(DeepQAgent):

	def __init__(self, neural_architecture, observation_dim, action_dim):
		super(OPIQ_Agent, self).__init__(neural_architecture, observation_dim, action_dim)

		# this matrix will be used to hash state/action pairs
		self.A = torch.normal(mean = torch.zeros(32, 5))
		# this dict will hold the number of times each state/action has been visited, with the hashes as keys
		self.novelty_dict = {}
		# this param controls the rate of descent of the novelty score wrt the number of visits to each state, higher means novelty decays faster, lower means novelty decays slower
		self.novelty_decay = M

	def get_action(self, observation):
		# converts the observation into a tensor that the neural net can operate on
		obs = torch.tensor(observation, dtype=torch.float32).unsqueeze(dim=0)
		# gets the predicted q values as given by the neural net, and
		q_vals = self.model(obs)
		# gets the novelty score of eacha action
		novelty = self.novelty_tensor(observation)
		# selects the action as the maximum of a weighted combination of the action's q value and novelty
		action = torch.argmax(q_vals + C_action*novelty, dim=1)[0].item()

		return action

	def get_num_visits(self, state, action):
		n = None
		try:
			n = self.novelty_dict[self.hash_fn(state, action)]
		except(KeyError):
			n = 0
			self.novelty_dict[self.hash_fn(state, action)] = 0
		return n

	def hash_fn(self, observation, action):
		observation = torch.tensor(observation)
		action = torch.tensor(action)
		observation_flat = torch.reshape(observation, [torch.numel(observation)])
		action_flat = torch.reshape(action, [torch.numel(action)])
		flat = torch.cat([observation_flat, action_flat], axis=0)
		dot_prod = self.A*flat
		sign = torch.sign(dot_prod)
		return hash(str(sign.tolist()))

	def novelty_score(self, state, action):
		n = self.get_num_visits(state, action)
		return 1/((n+1)**self.novelty_decay)

	# calculates the novelty scores of all actions in a state, and returns it as a tensor.
	# does not multiply by C factor, as that is left for the caller
	def novelty_tensor(self, state):
		scores = []
		for action in range(self.action_dim):
			scores.append(self.novelty_score(state, action))
		return torch.tensor(scores)

	def train_from_replay(self):
		# checks that the replay buffer is full enough before we start sampling from it, else the agent will focus too much on a small set of transitions
		if len(self.replay_memory) < MIN_REPLAY_MEMORY_SIZE:
			return

		# batch should be a list of transitions
		# a transition is a tuple of: (observation, action, reward, next_observation, done)
		batch = random.sample(self.replay_memory, BATCH_SIZE)

		# transposes the batch and then separates out all the components of each transition
		# observations is a list that holds the agent's observation in each transition that was sampled from the replay buffer
		# actions is a list that holds the agent's action in each transition that was sampled from the replay buffer
		# rewards is a list that holds the reward that the agent received in each transition
		# next_observations is a list that holds the state that the state/action combination taken in the transition led to
		# state_is_terminal is a list of booleans that holds weather or not the corresponding transition was a terminal state
		(observations, actions, rewards, next_observations, state_is_terminal) = list(map(list, zip(*batch)))

		# turns everything into a tensor
		observations = torch.Tensor(observations)
		actions_tensor = torch.Tensor(actions)
		next_observations = torch.Tensor(next_observations)
		rewards = torch.Tensor(rewards)
		state_is_terminal_tensor = torch.Tensor(state_is_terminal)

		# gets the model's evaluations of the state, given the information available in the observation
		# note how we're using the target model, since that is the model we're training to match the observed q distribution
		q_values = self.target_model(observations)

		# this is the estimated "value" of the next state. That is, it is the model's estimated Q value for the optimal action
		q_values_next = self.model(next_observations)

		# we now adjust the model's estimation of the q values to match the observed reward, with the bellman equation
		# clone creates a copy for us to alter to the correct value
		# detach exempts this tensor from the gradient calculation below, without this call the model's parameters would be equally
		#  adjusted to bring it's estimates close to this figure, and to bring this figure closer to its estimates, and so it wouldn't
		#  learn anything
		true_q_values = q_values.clone().detach()
		# range(len(true_q_values)) selects all q vectors in the transition set
		# actions selects the q value for the specific action that was taken
		# ***we must get the actions that were taken in the future steps and use them in OPIQ calculation
		true_q_values[range(len(true_q_values)), actions] = rewards + GAMMA*torch.max(q_values_next, axis=1).values

		# we now begine adjustements for terminal states
		# firstly by finding the indices of the terminal states in the batch of transitions sampled from replay memory
		terminal_indices = torch.stack(torch.where(state_is_terminal_tensor == 1.0)).tolist()[0]

		# then by setting the target q values for each prediction to only the reward, ignoring the value of the state that follows it
		true_q_values[terminal_indices, actions_tensor[terminal_indices].tolist()] = rewards[terminal_indices]

		# we now adjust the q values with the novelty score, this is a crucial part of OPIQ and is unique to it
		future_novelty = torch.stack([self.novelty_tensor(observation) for observation in observations])
		true_q_values = true_q_values + C_bootstrap*future_novelty

		loss = self.criterion(q_values, true_q_values)

		# clears the gradients of the network's parameters in preparation for the following update
		self.optimizer.zero_grad()
		# performs backprop (w/ autograd) to get the gradient of the loss for each parameter in the DQN's neural net
		loss.backward()
		# updates the parameters
		self.optimizer.step()

	# counts the number of visits to each state
	def visited(self, state, action):
		try:
			self.novelty_dict[self.hash_fn(state, action)] += 1
		except(KeyError):
			self.novelty_dict[self.hash_fn(state, action)] = 1


import socket
import csv

address = 'localhost'
port = 8001
add = ((address,port))
clientSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientSock.connect(add)

with open('arquivoOut.csv', 'r',newline='') as csv_file:
    csv_reader = csv.reader(csv_file)
    #line = ['Rafael', 'Ramos']
    for line in csv_reader:
        clientSock.sendto(repr(line).encode('utf-8'),(address, port))
    csv_file.close()
clientSock.close()


# search.py
# ---------
# Licensing Information:  You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).

#####################################################
#####################################################
# Please enter the number of hours you spent on this
# assignment here
num_hours_i_spent_on_this_assignment = 0
#####################################################
#####################################################

#####################################################
#####################################################
# Give one short piece of feedback about the course so far. What
# have you found most interesting? Is there a topic that you had trouble
# understanding? Are there any changes that could improve the value of the
# course to you? (We will anonymize these before reading them.)
"""
I found that the course is very fun to learn and entertaining
This assignment is hard and requires too much time to finish
I truly found this assignment very interesting and fun because I learned a lot from it
However, I have spent more than 30 hours to finish this assignment

I hope the change that we are allowed to work the assignment in groups of 2 or 3 to lower the spending time on the assignment
"""
#####################################################
#####################################################

"""
In search.py, you will implement generic search algorithms which are called by
Pacman agents (in searchAgents.py).
"""
import util
from util import PriorityQueue
from util import Stack
from util import Queue
from game import Directions

class SearchProblem:
    """
    This class outlines the structure of a search problem, but doesn't implement
    any of the methods (in object-oriented terminology: an abstract class).

    You do not need to change anything in this class, ever.
    """

    def getStartState(self):
        """
        Returns the start state for the search problem.
        """
        util.raiseNotDefined()

    def isGoalState(self, state):
        """
          state: Search state

        Returns True if and only if the state is a valid goal state.
        """
        util.raiseNotDefined()

    def getSuccessors(self, state):
        """
          state: Search state

        For a given state, this should return a list of triples, (successor,
        action, stepCost), where 'successor' is a successor to the current
        state, 'action' is the action required to get there, and 'stepCost' is
        the incremental cost of expanding to that successor.
        """
        util.raiseNotDefined()

    def getCostOfActions(self, actions):
        """
         actions: A list of actions to take

        This method returns the total cost of a particular sequence of actions.
        The sequence must be composed of legal moves.
        """
        util.raiseNotDefined()

def tinyMazeSearch(problem):
    """
    Returns a sequence of moves that solves tinyMaze.  For any other maze, the
    sequence of moves will be incorrect, so only use this for tinyMaze.
    """
    from game import Directions
    s = Directions.SOUTH
    w = Directions.WEST
    return  [s, s, w, s, w, w, s, w]

def depthFirstSearch(problem):
    """
    Questoin 1.1
    Search the deepest nodes in the search tree first.

    Your search algorithm needs to return a list of actions that reaches the
    goal. Make sure to implement a graph search algorithm.

    To get started, you might want to try some of these simple commands to
    understand the search problem that is being passed in:

    print ( problem.getStartState() )
    print (problem.isGoalState(problem.getStartState()) )
    print ( problem.getSuccessors(problem.getStartState()) )

    """
    "*** YOUR CODE HERE ***"

    visited = []
    direction = []
    fringe = Stack()
    StartState = ((problem.getStartState(), "" , 0))
    fringe.push((0, StartState, direction, visited))

    # when the stack is not empty
    while not fringe.isEmpty():
        # pop the stack and get those values
        depth, current_node, direction, visited = fringe.pop()

        # if it reaches the goal then return direction
        if problem.isGoalState(current_node[0]) == True:
            return direction + current_node[1]

        # check whether the current position is in the visited list or not
        if current_node[0] not in visited:
            visited = visited + [current_node[0]]

            # loop to get successor
            for element in problem.getSuccessors(current_node[0]) :
                # if not in visited then push all the values to stack
                if element[0] not in visited:
                    if problem.isGoalState(element[0]) == True:
                        return direction + [element[1]]
                    depth_of_node = len(direction)
                    #push everything to the stack
                    fringe.push((-depth_of_node, element, direction + [element[1]], visited))
    return direction

def breadthFirstSearch(problem):
    """Questoin 1.2
     Search the shallowest nodes in the search tree first.
     """

    "*** YOUR CODE HERE ***"
    visited = []
    direction = []
    visited_node = []
    fringe = Queue()
    count = 0
    #StartState = ((problem.getStartState(), "" , 0))
    Startstate = problem.getStartState()
    fringe.push((Startstate, direction))
    Successor = []

    # while the queue is not empty
    while not fringe.isEmpty():

        # Get all the values from queue
        current_node, direction = fringe.pop()
        # if it reaches the goal then return direction
        if problem.isGoalState(current_node) == True:
            direction.append(Successor[1])
            return direction
        # if not reaches
        else:
            # check the current is in visited list or not
            if current_node not in visited:
                Successor = problem.getSuccessors(current_node)
                visited = visited + [current_node]

                # looping the successor to get the next node and direction
                for element in Successor :
                    # check whether the next node is in visited list or not
                    if element[0] not in visited:
                        if problem.isGoalState(element[0]) == True:
                            return direction + [element[1]]
                        else:
                            #push everything to the queque
                            fringe.push((element[0], direction + [element[1]]))
    return direction

def nullHeuristic(state, problem=None):
    """
    A heuristic function estimates the cost from the current state to the nearest
    goal in the provided SearchProblem.  This heuristic is trivial.
    """
    return 0

def aStarSearch(problem, heuristic=nullHeuristic):
    """Question 1.3
    Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"

    from util import PriorityQueue
    visited = []
    direction = []
    fringe = PriorityQueue()
    startState = (problem.getStartState(),"" ,0)
    d_end_current = 0
    total_cost = 0

    fringe.push((startState ,direction),total_cost)
    # while the priorityqueue is not empty
    while not fringe.isEmpty():
        item = fringe.pop()
        current_node = item[0]
        direction = item[1]

        #check whether the current is goal or not
        if(problem.isGoalState(current_node[0])):
            direction.append(current_node[1])
            return direction

        # check whether current posistion are in visited list or not
        if current_node[0] not in visited:
            visited.append(current_node[0])
            Successor = problem.getSuccessors((current_node[0]))

            #looping to get the each element from Successor
            for element in Successor:
                # if next position not in visisted....
                if element[0] not in visited:
                    if problem.isGoalState(element[0]):
                        direction.append(element[1])
                        return direction
                    else:
                        #call the heuristic function which is the node from end to current position
                        d_end_current = heuristic(element[0], problem)
                        # f = h + g
                        total_cost = problem.getCostOfActions(direction + [element[1]]) + int(d_end_current)
                        # push all the values to priority queue
                        fringe.push((element, direction + [element[1]]),total_cost)
    return direction

# Abbreviations
bfs = breadthFirstSearch
dfs = depthFirstSearch
astar = aStarSearch


__author__ = 'nickroth'

import numpy as np
from sim_utils import SimEvent

class Missile(object):
    def __init__(self, name, env, comm, times):
        self.id = name
        self.env = env
        self.comm_out = comm
        self.times = times
        self.position = np.linspace(100, 1000, num=len(times))
        self.propagate_process = env.process(self.propagate())

    def propagate(self):
        # wait until first time to start yielding position
        yield self.env.timeout(self.times[0])
        print('%s is launching at %d' % (self.id, self.env.now))

        for idx, time in enumerate(self.times):
            pos = self.position[idx]
            print('%s position event for t=%d at position=%d' % (self.id, self.env.now, pos))
            msg = SimEvent(origin_id=self.id, time=self.env.now, event='THREAT_POSITION', value=pos)
            self.publish(msg)
            yield self.env.timeout(1)

    def publish(self, msg):
        self.comm_out.publish(topic='THREAT_POSITION', msg=msg)


from flask import Blueprint, request, jsonify, redirect, render_template, url_for
from .short_url import ShortUrl
from .forms import ShortURLForm
from godisbilen.app import db
from godisbilen.user import roles_accepted

bp_short = Blueprint("short", __name__)

@bp_short.route("/short/<short_url>")
def redirect_to_url(short_url):
    short_url = ShortUrl.query.filter_by(short_url=short_url).first_or_404()
    short_url.visits = short_url.visits + 1
    db.session.commit()
    return redirect(short_url.original_url)

@bp_short.route("/short/add_link", methods=["GET", "POST"])
@roles_accepted("Admin")
def add_link():
    form = ShortURLForm()
    if(form.validate_on_submit() and request.method=="POST"):
        short_url = ShortUrl(original_url=form.original_url.data)
        db.session.add(short_url)
        db.session.commit()
        return render_template("short_url/create.html", form=form, result=url_for("short.redirect_to_url", short_url=short_url.short_url, _external=True))
    return render_template("short_url/create.html", form=form)


from dataclasses import dataclass
from enum import Enum, auto

class SpanType(Enum):
    PRAGMA = auto()
    TEST = auto()
    IMPORT = auto()

@dataclass
class Pragma:
    name: str
    required: bool = True

_pragmas = (
    Pragma('export'),
    Pragma('entrypoint'),
    Pragma('spec', required=False),
)
LC_PRAGMAS = {f'_LC_{pragma.name.upper()}_': pragma for pragma in _pragmas}

LC_TEMPLATE = '''
class Solution:
    {entrypoint} = staticmethod({export})
'''

LC_SKIP_IMPORTS = frozenset(
    (
        'hypothesis',
        'pytest',
        #
        'ppcg',
    )
)


import pandas as pd
from sqlalchemy import create_engine
from bs4 import BeautifulSoup as bs
import requests
import pymongo
from splinter import Browser
import pymysql
pymysql.install_as_MySQLdb()

#read CSV files into pandas
#to access the data: https://www.kaggle.com/pschale/mlb-pitch-data-20152018#atbats.csv
csv_atbats = "data/atbats.csv"
csv_games = "data/games.csv"
csv_pitches = "data/pitches.csv"
csv_playernames = "data/player_names.csv"

atbats_data_df = pd.read_csv(csv_atbats)
games_data_df = pd.read_csv(csv_games)
pitches_data_df = pd.read_csv(csv_pitches)
playernames_data_df = pd.read_csv(csv_playernames)

#create the url's for each player
playernames_data_df['name_url'] = playernames_data_df['last_name'].str[0:5].str.lower() + playernames_data_df['first_name'].str[0:2].str.lower()
playernames_data_df['name_url_edit'] = playernames_data_df['name_url'].str.replace("'","")
playernames_data_df['name_url_edit'] = playernames_data_df['name_url'].str.replace(" ","")
playernames_data_df['search_url'] =  "https://www.baseball-reference.com/players/" +playernames_data_df['name_url_edit'].str[0:1]+"/"+ playernames_data_df['name_url_edit'] + "01.shtml"

#See which url's connect successfully
connection = []
for index, row in playernames_data_df.iterrows():
    request = requests.get(playernames_data_df['search_url'][index])
    if request.status_code == 200:
        connection.append(1)
    else:
        connection.append(0)

#append connection column to existing dataframe
playernames_data_df['connection'] = connection

#remove 404 connection errors
#playernames_success_df = playernames_data_df.loc[(playernames_data_df['connection'] == 1),:]
playernames_success_df = playernames_data_df

#reindex
playernames_success_df = playernames_success_df.reset_index(drop=True)

weight = []
for index,row in playernames_success_df.iterrows():
    html = row['search_url']
    response = requests.get(html)
    soup = bs(response.text, 'html.parser')
    try:
        weight.append(soup.find('span', itemprop='weight').text)
    except(AttributeError):
        weight.append("NA")

#append weight data to existing dataframe
playernames_success_df['weight'] = weight

#remove NA's
#playernames_success_df = playernames_success_df.loc[(playernames_success_df['weight'] != "NA"),:]

#reindex
playernames_success_df = playernames_success_df.reset_index(drop=True)

#drop the connection column
playernames_success_df = playernames_success_df.drop(['connection'],axis=1)

#drop index from all dataframes
atbats_data_df.set_index(['ab_id'],inplace=True)
pitches_data_df.set_index(['ab_id'],inplace=True)
games_data_df.set_index(['g_id'],inplace=True)
playernames_success_df.set_index(['id'],inplace=True)

#connect to local database
rds_connection_string = "root:Banking5%@127.0.0.1/baseball_db"
engine = create_engine(f'mysql://{rds_connection_string}')

#Get sql code to create tables
print(pd.io.sql.get_schema(pitches_data_df.reset_index(), 'pitches'))
print(pd.io.sql.get_schema(atbats_data_df.reset_index(), 'atbats'))
print(pd.io.sql.get_schema(games_data_df.reset_index(), 'games'))
print(pd.io.sql.get_schema(playernames_success_df.reset_index(), 'player_names'))

#export all data into MySQL
atbats_data_df.to_sql(name='atbats', con=engine, if_exists='replace', index=True)
playernames_success_df.to_sql(name='player_names', con=engine, if_exists='replace', index=True)
games_data_df.to_sql(name='games', con=engine, if_exists='replace', index=True)
pitches_data_df.to_sql(name='pitches', con=engine, if_exists='replace', index=True)

#confirm sql query works
pd.read_sql_query('select * from games', con=engine).head()


# vim: set et nosi ai ts=2 sts=2 sw=2:
# coding: utf-8
from __future__ import absolute_import, print_function, unicode_literals
import collections
import functools
import operator
import itertools

import six

from .decoration import Decorator

__all__ = ['add_prev_next', 'build_index', 'build_multi_index', 'materialize_slices', 'reverse_slices', 'find_contained_slices', 'convert_slices', 'reverse_pointers']

def _attrsetter(attr):
  if attr is None:
    fn = lambda obj, val: None
  else:
    def fn(obj, val):
      setattr(obj, attr, val)
      return val

  # Set a default value like any other value
  fn.default = fn
  return fn

def _attrappender(attr):
  if attr is None:
    fn = lambda obj, val: None
    fn.default = fn
    return fn

  def fn(obj, val):
    try:
      getattr(obj, attr).append(val)
    except AttributeError:
      setattr(obj, attr, [val])
    return getattr(obj, attr)

  # Do not set a default value, just initialise the list
  def default_fn(obj, val):
    setattr(obj, attr, [])
  fn.default = default_fn
  return fn

def _attrgetter(attr):
  if callable(attr):
    return attr
  return operator.attrgetter(attr)

def _storegetter(store):
  """
  Allows decorator arguments referring to a store of objects either to be a
  named attribute of a document, or a function which returns a list of objects
  given a document.
  """
  if callable(store):
    return store
  else:
    return operator.attrgetter(store)

def _aggregator(mode, attr):
  if mode is None or mode == 'last':
    return _attrsetter(attr)
  elif mode == 'first':
    def fn(obj, val):
      try:
        return getattr(obj, attr)
      except AttributeError:
        pass
      setattr(obj, attr, val)
      return val
    return fn
  elif mode == 'append':
    return _attrappender(attr)
  elif mode == 'min':
    fn = min
    default = float('inf')
  elif mode == 'max':
    fn = max
    default = float('-inf')
  elif mode == 'add':
    fn = operator.add
    default = 0
  elif mode == 'mul':
    fn = operator.mul
    default = 1
  else:
    raise ValueError('Unknown aggregate type {0}'.format(mode))

  def agg(obj, val):
    prev = getattr(obj, attr, default)
    val = fn(prev, val)
    setattr(obj, attr, val)
    return val
  return agg

class add_prev_next(Decorator):
  """
  Adds prev and next pointers or None where N/A. Also may add index.
  """
  def __init__(self, store, prev_attr='prev', next_attr='next', index_attr=None):
    super(add_prev_next, self).__init__(self._build_key(store, prev_attr, next_attr, index_attr))
    self.get_store = _storegetter(store)
    self.set_prev = _attrsetter(prev_attr)
    self.set_next = _attrsetter(next_attr)
    self.set_index = _attrsetter(index_attr)
    self._set_affected_fields((store, prev_attr), (store, next_attr), (store, index_attr))

  def decorate(self, doc):
    prev = None
    for i, item in enumerate(self.get_store(doc)):
      self.set_prev(item, prev)
      self.set_index(item, i)
      if prev is not None:
        self.set_next(prev, item)
      prev = item
    if prev is not None:
      self.set_next(prev, None)

class build_index(Decorator):
  """
  Constructs an index over a selected field (key_attr) from a given object
  store, and stores it on the document at index_attr. By default the index
  maps from a keys to single object. If the extracted key is iterable and
  is not a string or tuple, multiple keys will be mapped for the object.

  Setting by_index=True will map to the object's offset in the given store
  instead of the object itself. The construct and add_entry arguments may define
  an arbitrary indexing structure.
  """
  def __init__(self, store, key_attr, index_attr, construct=dict, add_entry='__setitem__', by_index=False):
    super(build_index, self).__init__(self._build_key(index_attr, key_attr, store, construct, add_entry, by_index))
    self.get_objects = _storegetter(store)
    self.set_index = _attrsetter(index_attr)
    self.get_key = _attrgetter(key_attr)
    self.construct_index = construct
    self.get_add_entry = _attrgetter(add_entry)
    self.by_index = by_index
    self._set_affected_fields(index_attr)

  def decorate(self, doc):
    res = self.construct_index()
    self.set_index(doc, res)
    add_entry = self.get_add_entry(res)

    for i, obj in enumerate(self.get_objects(doc)):
      val = i if self.by_index else obj
      try:
        keys = self.get_key(obj)
      except AttributeError:
        # Is this correct behaviour?
        # Or should users ensure all objects in the store have the appropriate attribute?
        # WARNING: This behaviour may hide true AttributeErrors
        continue
      if isinstance(keys, (six.binary_type, six.text_type, tuple)) or not hasattr(keys, '__iter__'):
        keys = (keys,)
      for key in keys:
        add_entry(key, val)

class build_multi_index(build_index):
  def __init__(self, *args, **kwargs):
    kwargs['construct'] = functools.partial(collections.defaultdict, set)
    kwargs['add_entry'] = lambda index: lambda key, val: index[key].add(val)
    super(build_multi_index, self).__init__(*args, **kwargs)

class materialize_slices(Decorator):
  """
  Decorates entries in the source_store with deref_attr, the list of elements
  in target_store corresponding to the slice_attr value.
  """
  def __init__(self, source_store, target_store, slice_attr, deref_attr):
    super(materialize_slices, self).__init__(self._build_key(source_store, target_store, slice_attr, deref_attr))
    self.get_source_store = _storegetter(source_store)
    self.get_target_store = _storegetter(target_store)
    self.slice_attr = slice_attr
    self.deref_attr = deref_attr
    self._set_affected_fields((source_store, deref_attr))

  def decorate(self, doc):
    store = self.get_target_store(doc)
    for obj in self.get_source_store(doc):
      span = getattr(obj, self.slice_attr)
      if span is not None:
        setattr(obj, self.deref_attr, store[span])

class reverse_slices(Decorator):
  """
  Where objects in source_store point (through slice_attr) to slices over
  objects in target_store, this decorates the target_store objects with any or
  all of: a pointer to a target_store object, its offset within the slice
  range (counting from left and/or right), a tuple of all the above.

  If slices are not mutually exclusive, each attribute will be a list whose
  items correspond to source annotations.

  >>> from schwa import dr
  >>> class Token(dr.Ann):
  ...   norm = dr.Text()
  >>> class NounPhrase(dr.Ann):
  ...   span = dr.Slice(Token)
  ...   def __repr__(self):
  ...     return '<NP {}:{}>'.format(self.span.start, self.span.stop)
  >>> class Doc(dr.Doc):
  ...   tokens = dr.Store(Token)
  ...   nps = dr.Store(NounPhrase)
  ...
  >>> def make_doc():
  ...   doc = Doc()
  ...   for norm in 'The cat sat on the mat in the yard .'.split():
  ...     doc.tokens.create(norm=norm)
  ...   for start, stop in [(0, 2), (4, 9), (7, 9)]:
  ...     doc.nps.create(span=slice(start, stop))
  ...   return doc
  >>>
  >>> # With mark_outside=False, the attribute is set iff covered by a NounPhrase:
  >>> doc = make_doc()
  >>> reverse_slices('nps', 'tokens', 'span', 'np', mark_outside=False)(doc)
  >>> [hasattr(tok, 'np') for tok in doc.tokens]
  [True, True, False, False, True, True, True, True, True, False]
  >>> # some_token.np points to the covering NounPhrase
  >>> doc.tokens[0].norm, doc.tokens[0].np
  ('The', <NP 0:2>)
  >>> # with mutex=True, only one covering slice is recorded
  >>> doc.tokens[8].norm, doc.tokens[8].np
  ('yard', <NP 7:9>)
  >>>
  >>> # With mark_outside=True, the attribute is None unless covered by a NounPhrase:
  >>> doc = make_doc()
  >>> reverse_slices('nps', 'tokens', 'span', 'np', mark_outside=True)(doc)
  >>> [tok.np is not None for tok in doc.tokens]
  [True, True, False, False, True, True, True, True, True, False]
  >>>
  >>> # With mutex=False, a list of covering NPs is stored, and mark_outside stores an empty list
  >>> doc = make_doc()
  >>> reverse_slices('nps', 'tokens', 'span', 'nps', mutex=False, mark_outside=True)(doc)
  >>> doc.tokens[0].nps
  [<NP 0:2>]
  >>> doc.tokens[2].nps
  []
  >>> doc.tokens[8].nps
  [<NP 4:9>, <NP 7:9>]
  >>>
  >>> # With offset_attr or roffset_attr the position of the covered token is stored
  >>> # This allows us to know if the token is at the start or end of a phrase, for instance
  >>> doc = make_doc()
  >>> reverse_slices('nps', 'tokens', 'span', 'np',
  ...                offset_attr='np_offset', roffset_attr='np_roffset',
  ...                all_attr='np_data', mutex=False, mark_outside=True)(doc)
  >>> [tok.np_offset for tok in doc.tokens]
  [[0], [1], [], [], [0], [1], [2], [3, 0], [4, 1], []]
  >>> [tok.np_roffset for tok in doc.tokens]
  [[1], [0], [], [], [4], [3], [2], [1, 1], [0, 0], []]
  >>> # The all_attr stores a tuple of pointer and offset information
  >>> doc.tokens[8].np_data
  [(<NP 4:9>, 4, 0), (<NP 7:9>, 1, 0)]
  """

  def __init__(self, source_store, target_store, slice_attr, pointer_attr=None, offset_attr=None, roffset_attr=None, all_attr=None, mutex=True, mark_outside=False):
    super(reverse_slices, self).__init__(self._build_key(source_store, target_store, slice_attr, pointer_attr, offset_attr, roffset_attr, all_attr, mutex, mark_outside))
    self.get_source_store = _storegetter(source_store)
    self.get_target_store = _storegetter(target_store)
    self.slice_attr = slice_attr
    if mutex:
      setter = _attrsetter
    else:
      setter = _attrappender
    self.set_pointer = setter(pointer_attr)
    self.set_offset = setter(offset_attr)
    self.set_roffset = setter(roffset_attr)
    self.set_all = setter(all_attr)
    self.mark_outside = mark_outside
    self._set_affected_fields((target_store, pointer_attr), (target_store, offset_attr), (target_store, roffset_attr), (target_store, all_attr))

  def decorate(self, doc):
    target_items = self.get_target_store(doc)

    if self.mark_outside:
      for target in target_items:
        self.set_pointer.default(target, None)
        self.set_offset.default(target, None)
        self.set_roffset.default(target, None)
        self.set_all.default(target, (None, None, None))

    for source in self.get_source_store(doc):
      span = getattr(source, self.slice_attr)
      if span is None:
        continue
      n = span.stop - span.start
      for i, target in enumerate(target_items[span]):
        self.set_pointer(target, source)
        self.set_offset(target, i)
        roffset = n - i - 1
        self.set_roffset(target, roffset)
        self.set_all(target, (source, i, roffset))

class find_contained_slices(Decorator):
  """
  Adds collection_attr to each containing_store object O, being a list of the
  objects in contained_store with a contained_slice that is a sub-span of O's
  containing_slice value.

  If contained_store (or contained_slice) is None, the value is copied from
  containing_store (containing_slice). In this case, each O will not be
  included in its contained objects collection.
  """
  def __init__(self, containing_store, containing_slice, contained_store=None, contained_slice=None, collection_attr=None):
    if not collection_attr:
      raise ValueError('collection_attr must be a non-empty string')
    super(find_contained_slices, self).__init__(self._build_key(containing_store, containing_slice, contained_store, contained_slice, collection_attr))
    self.get_containing_store = _storegetter(containing_store)
    self.get_containing_slice = operator.attrgetter(containing_slice)
    self.get_contained_store = _storegetter(contained_store or containing_store)
    self.get_contained_slice = operator.attrgetter(contained_slice or containing_slice)
    self.set_collection = _attrsetter(collection_attr)
    self.get_collection = operator.attrgetter(collection_attr)
    self._set_affected_fields((containing_store, collection_attr))

  def _gen_tuples(self, store, get_slice, group):
    for obj in store:
      sl = get_slice(obj)
      if not sl:
        continue
      yield sl.start, -sl.stop, group, obj

  def decorate(self, doc, CONTAINING_GROUP=0, CONTAINED_GROUP=1):
    containing_tuples = self._gen_tuples(self.get_containing_store(doc), self.get_containing_slice, CONTAINING_GROUP)
    contained_tuples = self._gen_tuples(self.get_contained_store(doc), self.get_contained_slice, CONTAINED_GROUP)
    open_containers = []
    for tup in sorted(itertools.chain(containing_tuples, contained_tuples)):
      start, stop, group, obj = tup
      while open_containers and start >= open_containers[-1][1]:
        open_containers.pop()

      if group == CONTAINING_GROUP:
        collection = []
        self.set_collection(obj, collection)
        open_containers.append((start, -stop, obj, collection))
      else:
        for cstart, cstop, container, collection in open_containers:
          if container != obj:
            collection.append(obj)

class convert_slices(Decorator):
  """
  Augments source_store objects with new_slice_attr, whose value corresponds to
  source_slice_attr over the finer granularity indicated by target_slice_attr.

  For example, if Sentence.span is a Slice over Token objects, and Token.span
  indicates a Slice over raw text, this decorator could be used to augment
  Sentence objects with Slice attributes over raw text.
  """
  def __init__(self, source_store, target_store, source_slice_attr, target_slice_attr, new_slice_attr):
    super(convert_slices, self).__init__(self._build_key(source_store, target_store, source_slice_attr, target_slice_attr, new_slice_attr))
    self.get_source_store = _storegetter(source_store)
    self.get_target_store = _storegetter(target_store)
    self.get_source_slice = operator.attrgetter(source_slice_attr)
    self.get_target_slice = operator.attrgetter(target_slice_attr)
    self.set_new_slice = _attrsetter(new_slice_attr)
    self._set_affected_fields((source_store, new_slice_attr))

  def decorate(self, doc):
    targets = self.get_target_store(doc)
    for source in self.get_source_store(doc):
      source_slice = self.get_source_slice(source)
      try:
        start = source_slice.start
        stop = source_slice.stop
      except AttributeError:
        self.set_new_slice(source, None)
        continue

      try:
        start = self.get_target_slice(targets[start])
      except IndexError:
        # Have seen case where start == stop == len(targets)
        self.set_new_slice(source, None)
      stop = self.get_target_slice(targets[stop - 1])
      try:
        self.set_new_slice(source, slice(start.start, stop.stop))
      except AttributeError:
        self.set_new_slice(source, None)

class reverse_pointers(Decorator):
  """
  Where objects in source_store point (through pointer_attr) to objects in
  target_store, this decorates the target objects with a rev_attr attribute
  pointing back to the source object.
  """

  def __init__(self, source_store, target_store, pointer_attr, rev_attr, mutex=True, mark_outside=False):
    super(reverse_pointers, self).__init__(self._build_key(source_store, target_store, pointer_attr, rev_attr, mutex, mark_outside))
    self.get_source_store = _storegetter(source_store)
    self.get_target_store = _storegetter(target_store)
    self.pointer_attr = pointer_attr
    if mutex:
      setter = _attrsetter
    else:
      setter = _attrappender
    self.set_rev = setter(rev_attr)
    self.mark_outside = mark_outside
    self._set_affected_fields((target_store, rev_attr))

  def decorate(self, doc):
    if self.mark_outside:
      for target in self.get_target_store(doc):
        self.set_rev.default(target, None)

    for source in self.get_source_store(doc):
      target = getattr(source, self.pointer_attr)
      if target is None:
        continue
      if isinstance(target, list):
        for target_item in target:
          self.set_rev(target_item, source)
      else:
        self.set_rev(target, source)

class mark_depth(Decorator):
  """
  In a graph structure, mark the depth and height of each node, counted from root and leaf, respectively.

  Arguments:
  - store: the store of nodes on which depth and height attrs are set (required for undo)
  - get_starts: a function or attribute on the doc that returns the starting nodes for a depth-first search
  - child_attr: a function or attribute for traversing from one node to its immediate descendants
  - depth_attr: the attribute to set on each node indicating its distance from a start node
  - height_attr: the attribute to set on each node indicating its distance from an end node (one without children)
  - depth_aggregate: one of ('last', 'min', 'max'). 'last' adopts the last value in right traversal.

  """
  def __init__(self, store, get_starts, child_attr, depth_attr=None, height_attr=None, depth_aggregate=None, height_aggregate='max', max_depth=None):
    super(mark_depth, self).__init__(self._build_key(get_starts, child_attr, depth_attr, height_attr, depth_aggregate, height_aggregate, max_depth))
    self.get_starts = _storegetter(get_starts)
    self.get_children = _attrgetter(child_attr)
    self.set_depth = _aggregator(depth_aggregate, depth_attr)
    self.set_height = _aggregator(height_aggregate, height_attr)
    self.max_depth = max_depth
    self._set_affected_fields((store, depth_attr), (store, height_attr))

  def decorate(self, doc):
    for obj in self.get_starts(doc):
      self._decorate(obj, 0)

  def _decorate(self, obj, depth):
    self.set_depth(obj, depth)
    children = self.get_children(obj)
    if not children or depth == self.max_depth:
      return self.set_height(obj, 0)
    if not isinstance(children, (list, tuple)):
      children = [children]
    for child in children:
      ch_height = self._decorate(child, depth + 1)
      height = self.set_height(obj, ch_height + 1)
    return height

# Get min-height can be done more efficiently with breadth-first search


fname = input('Enter File: ')
if len(fname) < 1 : fname = 'clown.txt'
hand = open(fname)

di = dict()
for lin in hand:
    lin = lin.rstrip()
    wds = lin.split()
    for w in wds:
        # idiom: retrive/create/update counter
        di[w] = di.get(w,0) + 1

# print(di)

tmp = list()
for k,v in di.items() :
    newt = (v,k)
    tmp.append(newt)

# print('Flipped',tmp)
tmp = sorted(tmp, reverse=True)
# print('Sorted',tmp[:5])

for v,k in tmp[:5] :
    print(k,v)


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from sys import stderr

class ImageProcessor:

    # https://matplotlib.org/stable/tutorials/introductory/images.html
    @staticmethod
    def load(path: str) -> np.ndarray or None:
        image = None
        try:
            image = mpimg.imread(path)
            shape = image.shape
            print(f"Loading image of dimensions {shape[0]} x {shape[1]}")
        except (Exception) as e:
            print(f"Exception: {e.__class__.__name__} -- strerror: {e.strerror if hasattr(e, 'strerror') else e}", file=stderr)
            return None
        return (image)

    @staticmethod
    def display(array: np.ndarray):
        if (not isinstance(array, np.ndarray)):
            print("ImgProcessor.display: Parameter is not a numpy array", file=stderr)
        else:
            try:
                plt.figure("Loaded image")
                plt.axis("off")
                plt.imshow(array)
                plt.show()
            except (Exception) as e:
                print(f"Exception: {e.__class__.__name__} -- strerror: {e.strerror if hasattr(e, 'strerror') else e}", file=stderr)

# if __name__ == "__main__":
#     imp = ImageProcessor()
#     arr = imp.load("../empty_file.png")
#     arr = imp.load("non_existing_file.png")
#     arr = imp.load("../module03.en.subject.pdf")
#     arr = imp.load("../42AI.png")
#     imp.display(arr)
#     arr = imp.load("../elon_canaGAN.png")
#     imp.display(arr)
#     imp.display([[0.03921569, 0.10588235, 0.19998235],
#                           [0.03921569, 0.10588235, 0.26666668],
#                           [0.03921569, 0.10588235, 0.26666668]])
#     imp.display(np.array([[0.03921569, 0.10588235, 0.19998235],
#                           [0.03921569, 0.10588235, 0.26666668],
#                           [0.03921569, 0.10588235, 0.26666668]]))


def square(no):
    return no*no;

def main():
    Arr=[10,20,30,40,50]

    result = []

    for value in Arr:
        ans = square(value)
        result.append(ans)

    print(result);

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


def solution(s):
    answer = len(s)
    # len(s)//2 까지는 len(s)==16일 때 n이 1~7(8-1)까지만 가능하다는 것
    # 길이가 16이므로 절반인 8개까지 가능해야하므로 1을 더해줌
    for n in range(1,len(s)//2+1):
        tmp = ""
        cnt=1
        pattern = s[:n]
        for i in range(n, len(s) , n):
            if pattern == s[i:i+n]:
                cnt+=1
            else:
                if cnt > 1:
                    tmp+=str(cnt)
                tmp +=pattern
                pattern = s[i:i+n]
                cnt=1
        if cnt > 1:
            tmp += str(cnt)
        tmp+=pattern
        print(n,tmp)
        answer = min(answer, len(tmp))
    return answer

def main():
    s1 = "aabbaccc"
    s2 = "ababcdcdababcdcd"
    s = "abcabcdede"
    s = "aabbabcabcabcabcdedededededeaccc"
    s = "xababcdcdababcdcd"
    print(solution(s2))

if __name__=="__main__":
    main()


from typing import Any, Optional

import tomlkit
from tomlkit.items import InlineTable, Table

from .configuration_file import ConfigurationFileContentBuilder

class ConfigurationTOMLContentBuilder(ConfigurationFileContentBuilder):
    def __init__(self) -> None:
        self._doc = tomlkit.document()
        self._profiles_table = tomlkit.table(is_super_table=True)
        self._profile_name_profile_table: dict[str, Table] = {}

    def set_section(
        self,
        section_name: str,
        data: dict[str, Any],
        profile_name: Optional[str] = None,
    ):
        table = self._map_data_to_table(data)

        if not profile_name:
            self._doc.add(key=section_name, item=table)
        else:
            profile_table = self._create_profile_table(profile_name)
            profile_table.add(
                key=section_name,
                value=table,
            )

    def _create_profile_table(self, profile_name: str) -> Table:
        if profile_name in self._profile_name_profile_table:
            return self._profile_name_profile_table[profile_name]
        profile_table = tomlkit.table(is_super_table=True)
        self._profile_name_profile_table[profile_name] = profile_table
        self._profiles_table.add(profile_name, profile_table)
        return profile_table

    def _map_data_to_table(self, data: dict) -> Table:
        table = tomlkit.table()
        for key, value in data.items():
            if isinstance(value, dict):
                table.add(key, self._map_data_to_inline_table(value))
            else:
                table.add(key, value)
        return table

    def _map_data_to_inline_table(self, data: dict) -> InlineTable:
        inline_table = tomlkit.inline_table()
        for key, value in data.items():
            if isinstance(value, dict):
                inline_table.add(key, self._map_data_to_inline_table(value))
            else:
                inline_table.add(key, value)
        return inline_table

    def build(self) -> str:
        self._doc.add("profile", self._profiles_table)
        return tomlkit.dumps(self._doc)

    def get_content_format(self) -> str:
        return "toml"


import math
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
from lib.py_utils.kp_utils import make_kp_layer, _tranpose_and_gather_feat, make_cnv_layer
from lib.CornerNet import make_ct_layer, make_ct_layer_separable
from lib.utils import MemoryEfficientSwish, Swish

class DetectionNet(nn.Module):
    def __init__(self):
        super(DetectionNet, self).__init__()
        #yolov3 backbone
        self.conv_1 = ConvBNReLU(3, 32, 3, 1, 1, bias=False)

        self.conv_2 = ConvBNReLU(32, 64, 3, 2, 1, bias=False)
        self.res1 = ResBlock(32, 64, bias=False)

        self.conv_3 = ConvBNReLU(64, 128, 3, 2, 1, bias=False)
        self.res2_1 = ResBlock(64, 128, bias=False)
        self.res2_2 = ResBlock(64, 128, bias=False)

        self.conv_4 = ConvBNReLU(128, 256, 3, 2, 1, bias=False)
        self.res3_1 = ResBlock(128, 256, bias=False)
        self.res3_2 = ResBlock(128, 256, bias=False)
        self.res3_3 = ResBlock(128, 256, bias=False)
        self.res3_4 = ResBlock(128, 256, bias=False)
        self.res3_5 = ResBlock(128, 256, bias=False)
        self.res3_6 = ResBlock(128, 256, bias=False)
        self.res3_7 = ResBlock(128, 256, bias=False)
        self.res3_8 = ResBlock(128, 256, bias=False)

        self.conv_5 = ConvBNReLU(256, 512, 3, 2, 1, bias=False)
        self.res4_1 = ResBlock(256, 512, bias=False)
        self.res4_2 = ResBlock(256, 512, bias=False)
        self.res4_3 = ResBlock(256, 512, bias=False)
        self.res4_4 = ResBlock(256, 512, bias=False)
        self.res4_5 = ResBlock(256, 512, bias=False)
        self.res4_6 = ResBlock(256, 512, bias=False)
        self.res4_7 = ResBlock(256, 512, bias=False)
        self.res4_8 = ResBlock(256, 512, bias=False)

        self.conv_6 = ConvBNReLU(512, 1024, 3, 2, 1, bias=False)
        self.res5_1 = ResBlock(512, 1024, bias=False)
        self.res5_2 = ResBlock(512, 1024, bias=False)
        self.res5_3 = ResBlock(512, 1024, bias=False)
        self.res5_4 = ResBlock(512, 1024, bias=False)

        self.detection3 = DetectionBlock(512, 1024, bias=False)
        self.upconcat3 = UpsampleBlock(256, 512, bias=False)
        self.detection2 = DetectionBlock(256, 512, 256, bias=False)
        self.upconcat2 = UpsampleBlock(128, 256, bias=False)
        self.detection1 = DetectionBlock(128, 256, 128, bias=False)

        self.feature1 = nn.Sequential(
            self.conv_1, self.conv_2, self.res1,
            self.conv_3, self.res2_1, self.res2_2,
            self.conv_4, self.res3_1, self.res3_2, self.res3_3, self.res3_4, self.res3_5, self.res3_6, self.res3_7, self.res3_8,
        )

        self.feature2 = nn.Sequential(
            self.conv_5, self.res4_1, self.res4_2, self.res4_3, self.res4_4, self.res4_5, self.res4_6, self.res4_7, self.res4_8,
        )
        self.feature3 = nn.Sequential(
            self.conv_6, self.res5_1, self.res5_2, self.res5_3, self.res5_4,
        )
        self.module_list = nn.ModuleList()
        self.module_list.append(self.feature1)
        self.module_list.append(self.feature2)
        self.module_list.append(self.feature3)
        self.module_list.append(self.detection3)
        self.module_list.append(self.upconcat3)
        self.module_list.append(self.detection2)
        self.module_list.append(self.upconcat2)
        self.module_list.append(self.detection1)
        for p in self.parameters():
            p.requires_grad = False

    def forward(self, x):
        feature1 = self.feature1(x) #head1 256x52x52
        feature2 = self.feature2(feature1) # head2 512x26x26
        feature3 = self.feature3(feature2) # head3 1024x13x13
        feature3, det3 = self.detection3(feature3) #512x13x13
        feature2 = self.upconcat3(feature3, feature2) #(256+512)x26x26
        feature2, det2 = self.detection2(feature2) #256x26x26
        feature1_1 = self.upconcat2(feature2, feature1) #128+256
        feature1_1, det1 = self.detection1(feature1_1) #128x52x52

        return feature1, feature1_1, det1, det2, det3

class ConvBNReLU(nn.Module):
    def __init__(self, inchannel, outchannel, kernel_size, stride=1, padding=0, bias=True):
        super(ConvBNReLU, self).__init__()
        self.conv = nn.Sequential(
            nn.Conv2d(inchannel, outchannel, kernel_size, stride, padding, bias=bias),
            nn.BatchNorm2d(num_features=outchannel),
            nn.LeakyReLU(0.1, inplace=True),
        )

    def forward(self, x):
        x = self.conv(x)
        return x

class ResBlock(nn.Module):
    def __init__(self, channel1, channel2, bias=True):
        super(ResBlock, self).__init__()

        self.res_conv1 = nn.Sequential(
            nn.Conv2d(channel2, channel1, 1, 1, 0, bias=bias),
            nn.BatchNorm2d(num_features=channel1),
            nn.LeakyReLU(0.1, inplace=True),
        )
        self.res_conv2 = nn.Sequential(
            nn.Conv2d(channel1, channel2, 3, 1, 1, bias=bias),
            nn.BatchNorm2d(num_features=channel2),
            nn.LeakyReLU(0.1, inplace=True),
        )

    def forward(self, x):
        x1 = self.res_conv1(x)
        x1 = self.res_conv2(x1)
        x1 = x1 + x
        return x1

class DetectionBlock(nn.Module):
    def __init__(self, channel1, channel2, channel3=0, bias=True):
        super(DetectionBlock, self).__init__()
        self.Convset = nn.Sequential(
            nn.Conv2d(channel2+channel3, channel1, 1, 1, 0, bias=False),
            nn.BatchNorm2d(num_features=channel1),
            nn.LeakyReLU(0.1, inplace=True),
            nn.Conv2d(channel1, channel2, 3, 1, 1, bias=False),
            nn.BatchNorm2d(num_features=channel2),
            nn.LeakyReLU(0.1, inplace=True),
            nn.Conv2d(channel2, channel1, 1, 1, 0, bias=False),
            nn.BatchNorm2d(num_features=channel1),
            nn.LeakyReLU(0.1, inplace=True),
            nn.Conv2d(channel1, channel2, 3, 1, 1, bias=False),
            nn.BatchNorm2d(num_features=channel2),
            nn.LeakyReLU(0.1, inplace=True),
            nn.Conv2d(channel2, channel1, 1, 1, 0, bias=False),
            nn.BatchNorm2d(num_features=channel1),
            nn.LeakyReLU(0.1, inplace=True),
        )
        self.prediction = nn.Sequential(
            nn.Conv2d(channel1, channel2, 3, 1, 1, bias=False),
            nn.BatchNorm2d(num_features=channel2),
            nn.LeakyReLU(0.1, inplace=True),
            nn.Conv2d(channel2, 255, 1, 1, 0, bias=True),
        )

    def forward(self, x):
        feature = self.Convset(x)
        prediction = self.prediction(feature)
        return feature, prediction

class UpsampleBlock(nn.Module):
    def __init__(self, channel1, channel2, bias=True):
        super(UpsampleBlock, self).__init__()

        self.Upsample_conv = nn.Sequential(
            nn.Conv2d(channel2, channel1, 1, 1, 0, bias=bias),
            nn.BatchNorm2d(num_features=channel1),
            nn.LeakyReLU(0.1, inplace=True),
            nn.Upsample(scale_factor=2, mode="nearest"),
        )

    def forward(self, x, feature):
        x = self.Upsample_conv(x)
        x = torch.cat((x, feature), 1)
        return x

class SeparableConvBlock(nn.Module):
    def __init__(self, in_channels, out_channels=None, norm=True, activation=False, onnx_export=False):
        super(SeparableConvBlock, self).__init__()
        if out_channels is None:
            out_channels = in_channels
        self.depthwise_conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1, bias=False, groups=in_channels)
        self.pointwise_conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)

        self.norm = norm
        if self.norm:
            self.bn = nn.BatchNorm2d(num_features=out_channels, momentum=0.01, eps=1e-3)
        self.activation = activation
        if self.activation:
            self.swish = MemoryEfficientSwish() if not onnx_export else Swish()

    def forward(self, x):
        x = self.depthwise_conv(x)
        x = self.pointwise_conv(x)
        if self.norm:
            x = self.bn(x)
        if self.activation:
            x = self.swish(x)

        return x

class CtConvBlock(nn.Module):
    def __init__(self, in_channels, out_channels=None, norm=True, activation=False):
        super(CtConvBlock, self).__init__()
        if out_channels is None:
            out_channels = in_channels
        self.with_norm = norm
        self.activation = activation
        bias = not self.with_norm
        self.conv = nn.Conv2d(in_channels, out_channels, 3, padding=1, stride=1, bias=bias)
        if self.with_norm:
            self.bn = nn.BatchNorm2d(num_features=out_channels, momentum=0.01, eps=1e-3)
        if self.activation:
            self.relu = nn.LeakyReLU(0.1, inplace=True)

    def forward(self, x):
        x = self.conv(x)
        if self.with_norm:
            x = self.bn(x)
        if self.activation:
            x = self.relu(x)

        return x
class LPDetection(nn.Module):
    def __init__(self, channel1, channel2, bias=True):
        super(LPDetection, self).__init__()
        self.lp_wh_conv = nn.Sequential(
            nn.Conv2d(channel2, channel1, 1, 1, 0, bias=False),
            nn.BatchNorm2d(channel1),
            nn.LeakyReLU(0.1, inplace=True),
            nn.Conv2d(channel1, channel2, 3, 1, 1, bias=False),
            nn.BatchNorm2d(channel2),
            nn.LeakyReLU(0.1, inplace=True),
        )
        self.attention_conv = nn.Sequential(
            nn.Conv2d(channel2, 1, 1, 1, 0, bias=False),
            nn.LeakyReLU(0.1, inplace=True),
        )
    def forward(self, x):
        detection_feature = self.lp_wh_conv(x)
        attention_map = self.attention_conv(detection_feature)
        return detection_feature, attention_map

class AttentionBlock(nn.Module):
    def __init__(self):
        super(AttentionBlock, self).__init__()
        self.roiconv = nn.Sequential(
            nn.Conv2d(128+128, 128, 1, 1, 0, bias=False),
            nn.BatchNorm2d(128, momentum=0.01, eps=1e-3),
            nn.LeakyReLU(0.1, inplace=True),
            nn.Conv2d(128, 128, 3, 1, 1, bias=False),
            nn.BatchNorm2d(128, momentum=0.01, eps=1e-3),
            nn.LeakyReLU(0.1, inplace=True),
        )
    def forward(self, final_feature):
        final_feature = self.roiconv(final_feature)
        return final_feature

class AttentionBlock1(nn.Module):
    def __init__(self, in_channels, out_channels, SGE=True, groups=64):
        super(AttentionBlock1, self).__init__()
        self.SGE = SGE
        self._swish = MemoryEfficientSwish()
        self.downchannel = None
        if in_channels != out_channels:
            self.downchannel = nn.Sequential(
                nn.Conv2d(in_channels, out_channels, 1, 1, 0, bias=False),
                nn.BatchNorm2d(out_channels, momentum=0.01, eps=1e-3),
            )
        if self.SGE:
            self.groups = groups
            self.avg_pool = nn.AdaptiveAvgPool2d(1)
            self.weight = Parameter(torch.zeros(1, groups, 1, 1))
            self.bias = Parameter(torch.ones(1, groups, 1, 1))
            self.sig = nn.Sigmoid()

        self.LPconv = SeparableConvBlock(out_channels, norm=True, activation=True)

    def forward(self, input):
        if self.downchannel != None:
            input = self.downchannel(input)
        b, c, h, w = input.size()
        x = input
        x = self.LPconv(x)
        if self.SGE:
            x = x.view(b * self.groups, -1, h, w)
            xn = x * self.avg_pool(x)
            xn = xn.sum(dim=1, keepdim=True)
            t = xn.view(b * self.groups, -1)
            t = t - t.mean(dim=1, keepdim=True)
            std = t.std(dim=1, keepdim=True) + 1e-5
            t = t / std
            t = t.view(b, self.groups, h, w)
            t = t * self.weight + self.bias
            t = t.view(b * self.groups, 1, h, w)
            x = x * self.sig(t)
            x = x.view(b, c, h, w)
        # skip connection
        x = input + x
        return x

class ConvBlock(nn.Module):
    def __init__(self):
        super(ConvBlock, self).__init__()
        self.LPD1 = LPDetection(64, 128, bias=False)
        self.LPD2 = LPDetection(64, 128, bias=False)

    def forward(self, input1, input2):
        LP_D1, _ = self.LPD1(input1)
        LP_D2, _ = self.LPD2(input2)

        return LP_D1, LP_D2

class TransBlock(nn.Module):
    def __init__(self, channel1, channel2):
        super(TransBlock, self).__init__()
        self.attn_1 = AttentionLayer(64)
        self.attn_2 = AttentionLayer(64)
        self.pre_conv1 = nn.Sequential(
            nn.Conv2d(channel2, channel1, 1, 1, 0, bias=False),
            nn.BatchNorm2d(channel1),
            nn.LeakyReLU(0.1, inplace=True))
        self.final_conv1 = nn.Sequential(
            nn.Conv2d(channel1, channel2, 3, 1, 1, bias=False),
            nn.BatchNorm2d(channel2),
            nn.LeakyReLU(0.1, inplace=True))
        self.pre_conv2 = nn.Sequential(
            nn.Conv2d(channel2, channel1, 1, 1, 0, bias=False),
            nn.BatchNorm2d(channel1),
            nn.LeakyReLU(0.1, inplace=True))
        self.final_conv2 = nn.Sequential(
            nn.Conv2d(channel1, channel2, 3, 1, 1, bias=False),
            nn.BatchNorm2d(channel2),
            nn.LeakyReLU(0.1, inplace=True))

    def forward(self, input1, input2):
        LP_D1 = self.pre_conv1(input1)
        LP_D1 = self.attn_1(LP_D1)
        LP_D1 = self.final_conv1(LP_D1)

        LP_D2 = self.pre_conv1(input2)
        LP_D2 = self.attn_1(LP_D2)
        LP_D2 = self.final_conv1(LP_D2)

        return LP_D1, LP_D2

class AttentionLayer(nn.Module):
    def __init__(self, in_dim, ratio=1):
        super(AttentionLayer, self).__init__()
        self.query_conv = nn.Conv2d(
            in_channels=in_dim, out_channels=in_dim // ratio, kernel_size=1)
        self.key_conv = nn.Conv2d(
            in_channels=in_dim, out_channels=in_dim // ratio, kernel_size=1)
        self.value_conv = nn.Conv2d(
            in_channels=in_dim, out_channels=in_dim, kernel_size=1)
        self.softmax = nn.Softmax(dim=-1)
        self.gamma = nn.Parameter(torch.zeros(1))

    def forward(self, x, pos=None):
        B, _, H, W = x.size()
        if pos is not None:
            x += pos
        proj_query = self.query_conv(x).view(B, -1, W*H).permute(0, 2, 1)
        proj_key = self.key_conv(x).view(B, -1, W*H)
        energy = torch.bmm(proj_query, proj_key)
        attention = self.softmax(energy)
        proj_value = self.value_conv(x).view(B, -1, W*H)
        out = torch.bmm(proj_value, attention).view(B, -1, H, W)
        out_feat = self.gamma * out + x

        return out_feat

class PositionEmbeddingSine(nn.Module):
    """
    This is a more standard version of the position embedding, very similar to the one
    used by the Attention is all you need paper, generalized to work on images.
    """

    def __init__(self,
                 num_pos_feats=64,
                 temperature=10000,
                 normalize=False,
                 scale=None):
        super().__init__()
        self.num_pos_feats = num_pos_feats
        self.temperature = temperature
        self.normalize = normalize
        if scale is not None and normalize is False:
            raise ValueError("normalize should be True if scale is passed")
        if scale is None:
            scale = 2 * math.pi
        self.scale = scale

    def forward(self, mask):
        assert mask is not None
        not_mask = ~mask
        y_embed = not_mask.cumsum(1, dtype=torch.float32)
        x_embed = not_mask.cumsum(2, dtype=torch.float32)
        if self.normalize:
            eps = 1e-6
            y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale
            x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale

        dim_t = torch.arange(
            self.num_pos_feats, dtype=torch.float32, device=mask.device)
        dim_t = self.temperature**(2 * (dim_t // 2) / self.num_pos_feats)

        pos_x = x_embed[:, :, :, None] / dim_t
        pos_y = y_embed[:, :, :, None] / dim_t
        pos_x = torch.stack(
            (pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()),
            dim=4).flatten(3)
        pos_y = torch.stack(
            (pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()),
            dim=4).flatten(3)
        pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
        return pos

def build_position_encoding(hidden_dim, shape):
    mask = torch.zeros(shape, dtype=torch.bool)
    pos_module = PositionEmbeddingSine(hidden_dim // 2)
    pos_embs = pos_module(mask)
    return pos_embs

class AnchorFreePrediction(nn.Module):
    def __init__(self):
        super(AnchorFreePrediction, self).__init__()
        # CenterNet
        cnv_dim = 128
        curr_dim = 128

        self.cnvs = make_cnv_layer(curr_dim, cnv_dim)
        self.ct_cnvs = make_ct_layer(cnv_dim)
        ## keypoint heatmaps
        self.ct_heats = make_kp_layer(cnv_dim, curr_dim, 1)
        self.ct_heats[-1].bias.data.fill_(-2.19)

        self.ct_regrs = make_kp_layer(cnv_dim, curr_dim, 2)
        self.regboxes = make_kp_layer(cnv_dim, curr_dim, 2)
        self.affine = make_kp_layer(cnv_dim, curr_dim, 6)

    def forward(self, input, ct_inds = None):
        preds = []
        cnv = self.cnvs(input)

        ct_cnv = self.ct_cnvs(cnv)
        ct_heat = self.ct_heats(ct_cnv)
        ct_regr = self.ct_regrs(ct_cnv)

        reg_boxes = self.regboxes(cnv)
        boxes_affine = self.affine(cnv)

        if ct_inds:
            ct_regr = _tranpose_and_gather_feat(ct_regr, ct_inds)  # 1 128 2  tl_regr 1 2 28 28
            reg_boxes = _tranpose_and_gather_feat(reg_boxes, ct_inds)
            boxes_affine = _tranpose_and_gather_feat(boxes_affine, ct_inds)
        preds += [ct_heat, ct_regr, reg_boxes, boxes_affine]
        return preds

class AnchorFreePredictionWithSeparable(nn.Module):
    def __init__(self, num_layers=3, onnx_export=False):
        super(AnchorFreePredictionWithSeparable, self).__init__()
        self.num_layers = num_layers
        self.swish = MemoryEfficientSwish() if not onnx_export else Swish()
        # CenterNet
        cnv_dim = 128
        curr_dim = 128

        self.conv_block = nn.ModuleList(
            [SeparableConvBlock(curr_dim, curr_dim, norm=True, activation=False) for i in range(num_layers)])

        self.ct_cnv = make_ct_layer_separable(cnv_dim, SeparableConvBlock)
        ## keypoint heatmaps
        self.ct_heat = nn.Sequential(
            SeparableConvBlock(curr_dim, curr_dim, norm=False, activation=False),
            nn.BatchNorm2d(curr_dim, momentum=0.01, eps=1e-3),
            SeparableConvBlock(curr_dim, 1, norm=False, activation=False))
        self.ct_heat[-1].pointwise_conv.bias.data.fill_(-2.19)
        self.ct_regr = nn.Sequential(
            SeparableConvBlock(curr_dim, curr_dim, norm=False, activation=False),
            nn.BatchNorm2d(curr_dim, momentum=0.01, eps=1e-3),
            SeparableConvBlock(curr_dim, 2, norm=False, activation=False))

        self.regbox = nn.Sequential(
            SeparableConvBlock(curr_dim, curr_dim, norm=False, activation=False),
            nn.BatchNorm2d(curr_dim, momentum=0.01, eps=1e-3),
            SeparableConvBlock(curr_dim, 2, norm=False, activation=False))
        self.affine = nn.Sequential(
            SeparableConvBlock(curr_dim, curr_dim, norm=False, activation=False),
            nn.BatchNorm2d(curr_dim, momentum=0.01, eps=1e-3),
            SeparableConvBlock(curr_dim, 6, norm=False, activation=False))
    def forward(self, input, ct_inds=None):
        preds = []
        for i, conv in zip(range(self.num_layers), self.conv_block):
            cnv = conv(input)
            cnv = self.swish(cnv)

        ct_cnv = self.ct_cnv(cnv)
        ct_heat = self.ct_heat(ct_cnv)
        ct_regr = self.ct_regr(ct_cnv)

        reg_boxes = self.regbox(cnv)
        boxes_affine = self.affine(cnv)

        if ct_inds is not None:
            ct_regr = _tranpose_and_gather_feat(ct_regr, ct_inds)  # 1 128 2  tl_regr 1 2 28 28
            reg_boxes = _tranpose_and_gather_feat(reg_boxes, ct_inds)
            boxes_affine = _tranpose_and_gather_feat(boxes_affine, ct_inds)
        preds += [ct_heat, ct_regr, reg_boxes, boxes_affine]
        return preds


import curses

def square(stdscr):

  curses.curs_set(0)

  sh, sw = stdscr.getmaxyx()
  center = [sh // 2, sw // 2]

  # row, column pair
  size = [16, 50]

  for y in range(center[0] - size[0] // 2, center[0] + size[0] // 2):
    for x in range(center[1] - size[1], center[1] + size[1], 2):
      stdscr.addstr(y, x, chr(9608))

  stdscr.getch()

curses.wrapper(square)


from store.models import Collection
from rest_framework.test import APIClient
from rest_framework import status
from store_core.models import User
import pytest
from model_bakery import baker

@pytest.fixture
def create_collection(api_client):
    def perform_create(collection):
        return api_client.post('/store/collections/', collection)
    return perform_create

@pytest.mark.django_db
class TestCreateCollection:
    # @pytest.mark.skip
    def test_if_user_is_anonymous_returns_401(self, create_collection):
        # Arrange
        # Act
        response = create_collection({'title': 'a'})
        # Assert
        assert response.status_code == status.HTTP_401_UNAUTHORIZED

    # @pytest.mark.skip
    def test_if_user_is_authenticaed_but_not_admin_returns_403(self, authenticate_user, create_collection):
        # Act
        authenticate_user(is_staff=False)
        response = create_collection({'title': 'a'})
        # Assert
        assert response.status_code == status.HTTP_403_FORBIDDEN

    # @pytest.mark.skip
    def test_if_user_is_admin_but_data_invalid_returns_400(self, authenticate_user, create_collection):
        # Arrange
        # Act
        authenticate_user(is_staff=True)
        response = create_collection({'title': ''})
        # Assert
        assert response.status_code == status.HTTP_400_BAD_REQUEST
        assert response.data['title'] is not None

    # @pytest.mark.skip
    def test_if_user_is_admin_and_data_valid_returns_201(self, authenticate_user, create_collection):
        # Arrange
        input_collection = {'title': 'a'}
        # Act
        authenticate_user(is_staff=True)
        response = create_collection(input_collection)
        # Assert
        assert response.status_code == status.HTTP_201_CREATED
        assert response.data['id'] > 0
        for key in input_collection:
            assert response.data[key] == input_collection[key]

@pytest.fixture
def get_collection(api_client):
    def perform_get(collection_id):
        return api_client.get(f'/store/collections/{collection_id}/')
    return perform_get

@pytest.mark.django_db
class TestRetrieveCollection:
    def test_if_collection_exists_return_200(self, get_collection):
        collection = baker.make(Collection)

        response = get_collection(collection.id)

        assert response.data == {
            'id': collection.id,
            'title': collection.title,
            'product_count': 0,
        }

    def test_if_collection_not_exists_return_404(self, get_collection):
        response = get_collection(0)

        assert response.status_code == status.HTTP_404_NOT_FOUND


f1 = open('55.txt', 'r')
f2 = open('55_1.txt', 'w')

row_l = []
for row in f1:
    row_l.append(row)

print(row_l)
print(row_l[-1:])
f2.write(str(*row_l[-1:]))

f1.close()
f2.close()


# coding:utf8
"""
Created on 2018年5月4日
@author: changl
"""

from config.config_reader import configReader
from common.connect_db import connectDB
from common.log import mylog, mylog_except
import os

class getReportContent():
    def __init__(self):
        # 连接报表数据库
        self.conndb = connectDB()
        self.conn = self.conndb.connect(self.conndb.dbname_auditcenter)
        self.cur = self.conndb.getCursor(self.conn)

        # 从配置文件中获取SQL配置项
        self.confR = configReader()

    # 获取数据库中报表的report_id及data_dimension_value（数据维度的值）
    def getProjectID(self, projectName):

        try:

            self.sql = self.confR.get("projectsql", "projectID")

            self.cur.execute(self.sql, (projectName,))
            projectID = self.cur.fetchone()

            if projectID:
                return projectID
            else:
                mylog("项目名称不存在")

        except Exception as error:
            mylog("SQL执行错误")
            mylog_except(error)

    # 获取报表存放ES数据的表名
    def getReportDataName(self, reportID):
        reportDataName = "report_{}_data".format(reportID)
        return reportDataName

    # 获取报表中所有指标的ID
    def getReportItem(self, reportID):
        self.sql = self.confR.get("reportsql", "reportItemid")
        self.cur.execute(self.sql, (reportID,))
        return self.cur.fetchall()

    # 获取数据库中所有指标的ID与对应的指标名称
    def getAllItems(self):
        self.sql = self.confR.get("reportsql", "allItems")
        self.cur.execute(self.sql)
        return dict(self.cur.fetchall())

    # 获取数据库报表中指标的值
    def getESvalue(self, reportDataName):

        try:
            self.sql = self.confR.get("reportsql", "esValue")
            self.cur.execute(self.sql.format(reportDataName))  # 参见获取报表存放ES数据的表名
            result = self.cur.fetchall()[-1]
            return result

        except Exception as error:
            print("未生成报表数据", error)
            mylog("SQL执行错误")
            mylog_except(error)

    # 获取报表的数据维度
    def getDataDimensionName(self, reportDataName):
        self.sql = self.confR.get("reportsql", "dimension_name")
        self.cur.execute(self.sql, (reportDataName,))
        return self.cur.fetchone()[0]

    # 获取报表的数据维度
    def getBusinessDimensionName(self, reportDataName):
        self.sql = self.confR.get("reportsql", "business_dimension")
        self.cur.execute(self.sql, (reportDataName,))
        return self.cur.fetchone()[0]

    # 获取机构，科室，医生，医疗组的信息
    def getHospitalInfor(self, reportDataName):
        self.sql = self.confR.get("reportsql", "hospital")
        self.cur.execute(self.sql.format(reportDataName))
        return self.cur.fetchall()[-1]

    # 根据docid获取医生的username
    def getDocName(self, docid):
        self.sql = self.confR.get("reportsql", "docname")
        self.cur.execute(self.sql, (docid,))
        return self.cur.fetchone()[0]

    # 根据deptid获取科室的code
    def getDeptName(self, deptid):
        self.sql = self.confR.get("reportsql", "deptid")
        self.cur.execute(self.sql, (deptid,))
        return self.cur.fetchone()[0]

    # 获取报表的时间范围
    def getReportTime(self, record_id, reportDataName):

        try:
            self.sql = self.confR.get("reportsql", "reportDate")
            self.cur.execute(self.sql.format(record_id, reportDataName))
            return self.cur.fetchone()

        except Exception as error:
            mylog("SQL执行错误")
            mylog_except(error)

    # 获取数据库里面所有报表的名称
    def getAllReportNames(self):

        self.sql = self.confR.get('reportsql', 'allReportNames')
        self.cur.execute(self.sql)
        allNames = self.cur.fetchall()

        newAllNames = []

        for name in allNames:
            newAllNames.append(name[0].encode('utf8'))
        return newAllNames

    # 获取手术名称对应的手术编码
    def getOperationCode(self, operationName):
        self.sql = self.confR.get('reportsql', 'operation_code')
        self.cur.execute(self.sql, (operationName,))
        self.operationCode = self.cur.fetchall()[0]
        self.operationCode_convert = self.operationCode[0].decode('utf8')
        self.operationCode_str = '|'.join(self.operationCode_convert.split(','))
        return self.operationCode_str

if __name__ == "__main__":
    pass


#------------------------------------------------
#Dylan Friesen
#Writing to external files
#Friday October 18, 2019
#------------------------------------------------

#---------------Functions------------------------

def writing_to(): #importing the file so that it can be used
    file = open('Dangerous Randall.txt', 'w')
    print("the file is being opened") #showing the user that it is being opened
    choice1 = input("What do you want to put into the file?")
    file.write(choice1) #putting whatever it was that
    print("The file is being closed")
    file.close()

def appending_to(): #used to add to the file, without removing the text that was added with the previous action
    file = open('Dangerous Randall.txt', 'a')
    print("file is being opened")
    choice2 = input("What are you adding to the file?")
    file.write(choice2)
    print("the file is being closed")
    file.close()

def character_creation(): #used to create details of user's character.
    print("The file is being opened")
    name = input("What is the name of your character?")
    race = input("What race are you?")
    gender = input("What gender are you?")
    file = open('character creation.txt', 'w')
    file.write("User=") #using equals to clear up the writing a bit, stop it from being so clumped
    file.write(name + ",")
    file.write("Race=")
    file.write(race + ",")
    file.write("Gender=")
    file.write(gender + ",")
    print("The file is being closed")
    file.close()

#-----------------------Main---------------------

def main(): #putting all them defs to use
    writing_to()
    appending_to()
    character_creation()

main() #its time


#Cálculo do fatorial de um número com WHILE
num = int(input('Digite um número: '))
num_orig = num

if num <= 0:
    print('O número deve ser maior que zero.')
else:
    fatorial = 1
    while num >= 1:
        fatorial *= num
        num -= 1

print('O fatorial do número {} é {}.\n'.format(num_orig, fatorial))


# B3 coordinates is (0.5, 1)
# y 24 = 12, 11.5
# (coordinate minus 1) * .5 = coordinate number
# coordinateso of the problem  (1,0.5) (0.5,2) (12,12)
#import math library because you need square root
#sqrt((1-0.5)*(1-0.5)+(0.5-2)*(0.5-2))
#use str1 = 'B25' , str1[0], str[1:3] to extract key and value
import math
letterscoordinate = {'A':0 , 'B' : 0.5, 'C':1.0, 'D': 1.5, 'E': 2, 'F': 2.5, 'G': 3, 'H': 3.5, 'I': 4, 'J': 4.5, 'K': 5, 'L': 5.5, 'M': 6, 'N': 6.5, 'O': 7, 'P': 7.5, 'Q': 8, 'R': 8.5, 'S': 9, 'T': 9.5, 'U': 10, 'V': 10.5, 'W': 11, 'X': 11.5, 'Y': 12, 'Z': 12.5}
numberscoordinate = {'1':0 , '2' : 0.5, '3':1, '4': 1.5, '5': 2, '6': 2.5, '7': 3, '8': 3.5, '9': 4, '10': 4.5, '11': 5, '12': 5.5, '13': 6, '14': 6.5, '15': 7, '16': 7.5, '17': 8, '18': 8.5, '19': 9, '20': 9.5, '21': 10, '22': 10.5, '23': 11, '24': 11.5, '25': 12, '26': 12.5}

dictofnumbersforroot = {}
dictofdistances={}

references = input("Enter trip reference map: ")
inputcoordinatesstring = str.split(references)
lengthcoordinates = len(inputcoordinatesstring)

for c in range(lengthcoordinates):
    coord = inputcoordinatesstring[c]
    lettercoord = coord[0]
    numbercoord = coord[1:3]

    if lettercoord in letterscoordinate and numbercoord in numberscoordinate:
        letterequivalent = letterscoordinate.get(lettercoord)
        numberequivalent = numberscoordinate.get(numbercoord)
        dictofnumbersforroot[c] = [letterequivalent, numberequivalent]
    else:
        print("Bad Reference: ", end=' ')
        print(coord)
        exit()

#print(dictofnumbersforroot)
lengthofdicofnumberforroot = len(dictofnumbersforroot)

for cc in range(lengthofdicofnumberforroot):
    distance = 0
    coordinates1 = dictofnumbersforroot[cc]
    if cc < lengthofdicofnumberforroot - 1:
        coordinates2 = dictofnumbersforroot[cc + 1]
    else:
        break

    distance = math.sqrt(((coordinates2[0] - coordinates1[0])*(coordinates2[0] - coordinates1[0])) + ((coordinates2[1] - coordinates1[1])*(coordinates2[1] - coordinates1[1])))
    #print(distance)
    dictofdistances[cc] = distance

#print(dictofdistances)
lengthofdistancesdictionary = len(dictofdistances)
sumofdistance = 0

for d in range(lengthofdistancesdictionary):
    sumofdistance += dictofdistances.get(d)
print("Total distance = ", end=' ')
print('{:.1f}'.format(sumofdistance), end=' ')
print("km")


import sys
from io import StringIO
import unittest

class TestClass(unittest.TestCase):
    maxDiff = None
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)

    def test_Sample_Input_1(self):
        input = """4
CBAA"""
        output = """CAAB"""
        self.assertIO(input, output)

    def test_Sample_Input_2(self):
        input = """1
A"""
        output = """A"""
        self.assertIO(input, output)

    def test_Sample_Input_3(self):
        input = """6
BBBCBB"""
        output = """ABCA"""
        self.assertIO(input, output)

    def test_Sample_Input_4(self):
        input = """6
BBBBBB"""
        output = """AAA"""
        self.assertIO(input, output)

    def test_Sample_Input_5(self):
        input = """6
BBBBBA"""
        output = """AAAB"""
        self.assertIO(input, output)

    def test_Sample_Input_6(self):
        input = """6
AAABBA"""
        output = """AAAAA"""
        self.assertIO(input, output)

def resolve():
  from collections import deque

  N = int(input())
  S = list(input())
  stack = deque()
  stack.append({"A": 0, "B": 0})
  # BB はそのまま A にする
  # BA となってる場合は位置を入れ替えることができる。
  for i in range(N):
    if S[i] == "C":
      stack.append({"A": 0, "B": 0})
    else:
      val = stack.pop()
      val[S[i]]+=1
      stack.append(val)

  ans = []
  while stack:
    temp = ""
    val = stack.popleft()
    temp += "A"*(val["A"]+val["B"]//2)
    temp += "B"*(val["B"]%2)
    ans.append(temp)
  print(*ans, sep="C")
import sys
if sys.argv[-1] == './Main.py':
  resolve()

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


# find smallest positive number

"""
Given an unsorted array containing numbers, find the smallest missing positive number in it.

Example 1:

Input: [-3, 1, 5, 4, 2]
Output: 3
Explanation: The smallest missing positive number is '3'
Example 2:

Input: [3, -2, 0, 1, 2]
Output: 4
Example 3:

Input: [3, 2, 5, 1]
Output: 4
"""

# the key is to ignore out of range numbers: negative and larger than array size
# sort the good ones using cyclic sort
# finally, traverse the array to find the smallest missing

def find_smallest_positive(nums):
    i = 0
    while i < len(nums):
        # ignore out of bound nums
        if nums[i] < 0 or nums[i] > len(nums):
            i += 1
            continue

        # sort the good ones
        j = nums[i] - 1
        if nums[i] != nums[j]:
            nums[i], nums[j] = nums[j], nums[i]

        else:
            i += 1

    # traverse the array until we find a mismatch
    for i in range(len(nums)):
        if nums[i] != i + 1:
            return i + 1

    return len(nums) + 1

t1 = [-3, 1, 5, 4, 2]
t2 = [3, -2, 0, 1, 2]
t3 = [3, 2, 5, 1]

assert find_smallest_positive(t1) == 3
assert find_smallest_positive(t2) == 4
assert find_smallest_positive(t3) == 4

print("all tests passed.")


import calendar
import errno
import json
import locale
import optparse
import os
import re
import sys
import time
import urllib
from io import StringIO

import urllib3

DEFAULT_CONFIG_FILES = filter(os.path.isfile, ('/etc/dnsdb-query.conf', os.path.expanduser('~/.dnsdb-query.conf')))
DEFAULT_DNSDB_SERVER = 'https://api.dnsdb.info'
DEFAULT_HTTP_PROXY = ''
DEFAULT_HTTPS_PROXY = ''

cfg = None
options = None
debug = False  # set to True to print raw queries and responses

locale.setlocale(locale.LC_ALL, '')

class QueryError(Exception):
    pass

class DnsdbClient(object):
    def __init__(self, server, apikey, limit=None, http_proxy=None, https_proxy=None):
        self.server = server
        self.apikey = apikey
        self.limit = limit
        self.http_proxy = http_proxy
        self.https_proxy = https_proxy

    def query_rrset(self, oname, rrtype=None, bailiwick=None, before=None, after=None):
        if bailiwick:
            if not rrtype:
                rrtype = 'ANY'
            path = 'rrset/name/%s/%s/%s' % (quote(oname), rrtype, quote(bailiwick))
        elif rrtype:
            path = 'rrset/name/%s/%s' % (quote(oname), rrtype)
        else:
            path = 'rrset/name/%s' % quote(oname)
        return self._query(path, before, after)

    def query_rdata_name(self, rdata_name, rrtype=None, before=None, after=None):
        if rrtype:
            path = 'rdata/name/%s/%s' % (quote(rdata_name), rrtype)
        else:
            path = 'rdata/name/%s' % quote(rdata_name)
        return self._query(path, before, after)

    def query_rdata_ip(self, rdata_ip, before=None, after=None):
        path = 'rdata/ip/%s' % rdata_ip.replace('/', ',')
        return self._query(path, before, after)

    def _query(self, path, before=None, after=None):
        res = []
        url = '%s/lookup/%s' % (self.server, path)

        params = {}
        if self.limit:
            params['limit'] = self.limit
        if before and after:
            params['time_first_after'] = after
            params['time_last_before'] = before
        else:
            if before:
                params['time_first_before'] = before
            if after:
                params['time_last_after'] = after
        if params:
            url += '?{0}'.format(urllib.parse.urlencode(params))

        if self.https_proxy:
            manager = urllib3.ProxyManager(self.https_proxy)
        elif self.http_proxy:
            manager = urllib3.ProxyManager(self.http_proxy)
        else:
            manager = urllib3.PoolManager()

        headers = {
            'Accept': 'application/json',
            'X-Api-Key': self.apikey
        }

        if debug:
            sys.stderr.write(";; query URL =" + url)

        try:
            r = manager.request(method='GET', url=url, headers=headers)
            if r.status == 200:
                json_data = r.data.decode('utf-8')
                if json_data:
                    json_list = json_data.splitlines()
                    for line in json_list:
                        yield json.loads(line)
            else:
                raise QueryError(r.text)

        except (urllib3.exceptions.HTTPError) as e:
            raise QueryError(str(e))

def quote(path):
    return urllib.parse.quote(path, safe='')

def sec_to_text(ts):
    return time.strftime('%Y-%m-%d %H:%M:%S -0000', time.gmtime(ts))

def rrset_to_text(m):
    s = StringIO()

    try:
        if 'bailiwick' in m:
            s.write(';;  bailiwick: %s\n' % m['bailiwick'])

        if 'count' in m:
            s.write(';;      count: %s\n' % locale.format('%d', m['count'], True))

        if 'time_first' in m:
            s.write(';; first seen: %s\n' % sec_to_text(m['time_first']))
        if 'time_last' in m:
            s.write(';;  last seen: %s\n' % sec_to_text(m['time_last']))

        if 'zone_time_first' in m:
            s.write(';; first seen in zone file: %s\n' % sec_to_text(m['zone_time_first']))
        if 'zone_time_last' in m:
            s.write(';;  last seen in zone file: %s\n' % sec_to_text(m['zone_time_last']))

        if 'rdata' in m:
            for rdata in m['rdata']:
                s.write('%s IN %s %s\n' % (m['rrname'], m['rrtype'], rdata))

        s.seek(0)
        return s.read()
    finally:
        s.close()

def rdata_to_text(m):
    return '%s IN %s %s' % (m['rrname'], m['rrtype'], m['rdata'])

def parse_config(cfg_files):
    config = {}

    if not cfg_files:
        raise IOError(errno.ENOENT, 'dnsdb_query: No config files found')

    for fname in cfg_files:
        for line in open(fname):
            key, eq, val = line.strip().partition('=')
            val = val.strip('"')
            config[key] = val

    return config

def time_parse(s):
    try:
        epoch = int(s)
        return epoch
    except ValueError:
        pass

    try:
        epoch = int(calendar.timegm(time.strptime(s, '%Y-%m-%d')))
        return epoch
    except ValueError:
        pass

    try:
        epoch = int(calendar.timegm(time.strptime(s, '%Y-%m-%d %H:%M:%S')))
        return epoch
    except ValueError:
        pass

    m = re.match(r'^(?=\d)(?:(\d+)w)?(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s?)?$', s, re.I)
    if m:
        return -1 * (int(m.group(1) or 0) * 604800 + \
                     int(m.group(2) or 0) * 86400 + \
                     int(m.group(3) or 0) * 3600 + \
                     int(m.group(4) or 0) * 60 + \
                     int(m.group(5) or 0))

    raise ValueError('Invalid time: "%s"' % s)

def epipe_wrapper(func):
    def f(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except IOError as e:
            if e.errno == errno.EPIPE:
                sys.exit(e.errno)
            raise

    return f

@epipe_wrapper
def main():
    global cfg
    global options
    global debug

    parser = optparse.OptionParser(
        epilog='Time formats are: "%Y-%m-%d", "%Y-%m-%d %H:%M:%S", "%d" (UNIX timestamp), "-%d" (Relative time in seconds), BIND format (e.g. 1w1h, (w)eek, (d)ay, (h)our, (m)inute, (s)econd)')
    parser.add_option('-c', '--config', dest='config',
                      help='config file', action='append')
    parser.add_option('-r', '--rrset', dest='rrset', type='string',
                      help='rrset <ONAME>[/<RRTYPE>[/BAILIWICK]]')
    parser.add_option('-n', '--rdataname', dest='rdata_name', type='string',
                      help='rdata name <NAME>[/<RRTYPE>]')
    parser.add_option('-i', '--rdataip', dest='rdata_ip', type='string',
                      help='rdata ip <IPADDRESS|IPRANGE|IPNETWORK>')
    parser.add_option('-t', '--rrtype', dest='rrtype', type='string',
                      help='rrset or rdata rrtype')
    parser.add_option('-b', '--bailiwick', dest='bailiwick', type='string',
                      help='rrset bailiwick')
    parser.add_option('-s', '--sort', dest='sort', type='string', help='sort key')
    parser.add_option('-R', '--reverse', dest='reverse', action='store_true', default=False,
                      help='reverse sort')
    parser.add_option('-j', '--json', dest='json', action='store_true', default=False,
                      help='output in JSON format')
    parser.add_option('-l', '--limit', dest='limit', type='int', default=0,
                      help='limit number of results')
    parser.add_option('-d', '--debug', dest='debug', action='store_true', default=False,
                      help='print debug output')

    parser.add_option('', '--before', dest='before', type='string', help='only output results seen before this time')
    parser.add_option('', '--after', dest='after', type='string', help='only output results seen after this time')

    options, args = parser.parse_args()
    if args:
        parser.print_help()
        sys.exit(1)

    debug = options.debug

    try:
        if options.before:
            options.before = time_parse(options.before)
    except ValueError as e:
        print('Could not parse before: {}'.format(options.before))

    try:
        if options.after:
            options.after = time_parse(options.after)
    except ValueError as e:
        print('Could not parse after: {}'.format(options.after))

    try:
        cfg = parse_config(options.config or DEFAULT_CONFIG_FILES)
    except IOError as e:
        sys.stderr.writable(str(e))
        sys.exit(1)

    if not 'DNSDB_SERVER' in cfg:
        cfg['DNSDB_SERVER'] = DEFAULT_DNSDB_SERVER
    if not 'HTTP_PROXY' in cfg:
        cfg['HTTP_PROXY'] = DEFAULT_HTTP_PROXY
    if not 'HTTPS_PROXY' in cfg:
        cfg['HTTPS_PROXY'] = DEFAULT_HTTPS_PROXY
    if not 'APIKEY' in cfg:
        sys.stderr.write('dnsdb_query: APIKEY not defined in config file\n')
        sys.exit(1)

    client = DnsdbClient(cfg['DNSDB_SERVER'], cfg['APIKEY'],
                         limit=options.limit,
                         http_proxy=cfg['HTTP_PROXY'],
                         https_proxy=cfg['HTTPS_PROXY'])
    if options.rrset:
        if options.rrtype or options.bailiwick:
            qargs = (options.rrset, options.rrtype, options.bailiwick)
        else:
            qargs = (options.rrset.split('/', 2))

        results = client.query_rrset(*qargs, before=options.before, after=options.after)
        fmt_func = rrset_to_text
    elif options.rdata_name:
        if options.rrtype:
            qargs = (options.rdata_name, options.rrtype)
        else:
            qargs = (options.rdata_name.split('/', 1))

        results = client.query_rdata_name(*qargs, before=options.before, after=options.after)
        fmt_func = rdata_to_text
    elif options.rdata_ip:
        results = client.query_rdata_ip(options.rdata_ip, before=options.before, after=options.after)
        fmt_func = rdata_to_text
    else:
        parser.print_help()
        sys.exit(1)

    if options.json:
        fmt_func = json.dumps

    try:
        if options.sort:
            results = list(results)
            if len(results) > 0:
                if not options.sort in results[0]:
                    sort_keys = results[0].keys()
                    sort_keys.sort()
                    sys.stderr.write('dnsdb_query: invalid sort key "%s". valid sort keys are %s\n' % (
                        options.sort, ', '.join(sort_keys)))
                    sys.exit(1)
                results.sort(key=lambda r: r[options.sort], reverse=options.reverse)
        for res in results:
            sys.stdout.write('%s\n' % fmt_func(res))
    except QueryError as e:
        sys.stderr.write(e)
        sys.exit(1)

if __name__ == '__main__':
    main()


#!/usr/bin/python3
"""
5-text_indentation module
"""

def text_indentation(text):
    """
    function that prints text with 2 new lines after the characters
    '.', '?' and ':'
    """
    if type(text) is not str:
        raise TypeError("text must be a string")
    flag = False
    special = ['.', '?', ':']
    for i in text:
        if flag is False:
            if i == " ":
                continue
            else:
                flag = True
        if flag is True:
            if i in special:
                print(i)
                print()
                flag = False
            else:
                print(i, end="")


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

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import csv

from hongsewenxue.items import HongsewenxueItem, ChapterItem

def write_book_info(item):
    with open('hongxue_book.csv', 'a', encoding="utf-8", newline='') as file_obj:
        writer = csv.writer(file_obj)
        row = [item["name"], item["author"], item['img']]
        writer.writerow(row)

def write_chapter_info(item):
    with open('hongxue_chapter.csv', 'a', encoding="utf-8", newline='') as file_obj:
        writer = csv.writer(file_obj)
        row = [item["book_name"], item["chapter_num"], item['chapter_name'], item['content']]
        writer.writerow(row)

class HongsewenxuePipeline(object):
    def process_item(self, item, spider):
        if isinstance(item, HongsewenxueItem):
            write_book_info(item)
        if isinstance(item, ChapterItem):
            write_chapter_info(item)


import unittest
import MachineSettings as MS

class TestMachineSettings(unittest.TestCase):
    """
    Tests for the class MachineSettings

    .. moduleauthor:: Albert Heinle <albert.heinle@uwaterloo.ca>
    """

    def setUp(self):
        """
        Our setup is a typical one where we have three computer algebra systems in
        in the input dictionary and "time -p" as our time command
        """
        casDict = {"Singular":"Singular", "Magma":"magma", "Maple":"maple"}
        timeCommand = "time -p"
        self.msTest = MS.MachineSettings(casDict,timeCommand)

    def testStringRepresentation(self):
        """
        Tests if the string representation is valid.
        """
        strRep = str(self.msTest)
        expectedStrRep = "Computer algebra systems and commands:\n\
    Magma : magma\n\
    Maple : maple\n\
    Singular : Singular\n\
Time Command: time -p"
        self.assertEqual(strRep,expectedStrRep,
                         "Something was wrong with the string representation of\
an instance of the class MachineSettings")

    def testCasDict(self):
        """
        Tests if the dictionary with the respective computer algebra systems was
        initialized in a valid way.
        """
        casDict = {"Singular":"Singular", "Magma":"magma", "Maple":"maple"}
        self.assertEqual(casDict, self.msTest.getCASDict(),
                     "The dictionary inside the MachineSettings was not validly initialized")

    def testTimeCommand(self):
        """
        Tests whether the time command was saved as expected.
        """
        timeCommand = "time -p"
        self.assertEqual(timeCommand,self.msTest.getTimeCommand(),
                         "The time command inside the MachineSettings was not validly initialized")

    def testCasCommand(self):
        """
        Tests whether the right execution command for a certain computer algebra system
        is returned.
        """
        self.assertEqual(None, self.msTest.getCASCommand("abc123"),
                    "\"abc123\" was not a valid computer algebra system in the list, but\
our machine settings instance returned it as one.")
        self.assertEqual("magma", self.msTest.getCASCommand("Magma"),
                    "Could not receive command for valid computer algebra system (Magma)")

    def testXMLRepresentation(self):
        """
        Tests whether the XML Representation of the Machine Settings is correct.
        """
        expectedXMLRep='<?xml version="1.0" ?><machinesettings><othervars><timecommand>\
time -p</timecommand></othervars><casdictionary><entry><key>Magma</key><value>magma</value>\
</entry><entry><key>Maple</key><value>maple</value></entry><entry><key>Singular</key><value>\
Singular</value></entry></casdictionary></machinesettings>'
        actualXMLRep = self.msTest.toXML().toxml()
        self.assertEqual(expectedXMLRep,actualXMLRep,
                         "The representation of the machine settings as XML was not correct.")

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