#! python3

from __future__ import print_function

import SimpleITK as sitk
import numpy as np
import NormalizedCrossCorrelationMetrics as NCC
import sys
import os

sys.path.append('..\MultiAtlasSegmentation')
import SitkImageManipulation as sitkIm

def DynamicLabelFusionWithLocalSimilarityWeights(targetImage, registeredAtlases, numLabels, numSelectedAtlases = 5,
                                                 expWeight=4, outputPath=".\\", debug = 0):
    """" Fuses the labels from a set of registered atlases using individual similarity metrics for each label.

    Arguments:
        targetImage: image being segmented:
        registeredAtlases: dictionary with a set of atlases having the fields image and labels for SimpleITK images with
                            the intensity image and the atlases
    """
    # If use background (=0) as another label:
    numLabels = numLabels

    # Generate a new image:
    fusedLabels = sitk.Image(targetImage.GetSize(), sitk.sitkUInt8)
    fusedLabels.SetSpacing(targetImage.GetSpacing())
    fusedLabels.SetOrigin(targetImage.GetOrigin())
    fusedLabels.SetDirection(targetImage.GetDirection())

    # Create a log file if debugging:
    if debug:
        if not os.path.exists(outputPath):
            os.mkdir(outputPath)
        logFilename = outputPath + 'log.txt'
        log = open(logFilename, 'w')

    # Get similarity weights for each label mask for each atlas
    lnccValues = np.zeros((numLabels+1,len(registeredAtlases['image'])))
    lnccValues2 = np.zeros((numLabels+1, len(registeredAtlases['image'])))
    # The background I count it as a label in the voting, so numLabels+1
    for i in range(0, numLabels+1):
        for j in range(0, len(registeredAtlases['image'])):
            # Get intensity and label images for this case:
            intensityImage = registeredAtlases['image'][j]
            labelsImage = registeredAtlases['labels'][j]
            # Get the mask for this label and atlas:
            maskThisLabel = sitk.Equal(sitk.Cast(labelsImage, sitk.sitkUInt8), i) #i because we consider the background (0) as a label.
            # Compute directly the normalized correlation:
            lncc = NCC.RoiNormalizedCrossCorrelationAsInITK(targetImage, intensityImage, maskThisLabel)
            lnccValues[i,j] = lncc
            if debug:
                imRegMethod = sitk.ImageRegistrationMethod()
                roiImage = sitk.Mask(intensityImage, maskThisLabel)
                roiTarget = sitk.Mask(targetImage, maskThisLabel)
                imRegMethod.SetMetricMovingMask(maskThisLabel)
                imRegMethod.SetMetricAsCorrelation()
                lncc2 = imRegMethod.MetricEvaluate(roiTarget, roiImage)
                # If in debug mode, show images:
                # Get centroid of the mask:
                labelStatisticFilter = sitk.LabelShapeStatisticsImageFilter()
                labelStatisticFilter.Execute(maskThisLabel)
                if labelStatisticFilter.GetNumberOfPixels(1) > 0:
                    boundingBox = labelStatisticFilter.GetBoundingBox(1)
                    slice = round(boundingBox[2] + boundingBox[5]/2)
                    targetImageOverlay = sitk.LabelOverlay(sitk.Cast(sitk.RescaleIntensity(targetImage[:, :, slice]), sitk.sitkUInt8), maskThisLabel[:, :, slice])
                    sitk.WriteImage(targetImageOverlay, outputPath + 'roiTarget_{0}_{1}.png'.format(i,j))
                    #sitk.WriteImage(sitk.Cast(sitk.RescaleIntensity(roiImage[:, :, slice]), sitk.sitkUInt8), outputPath + 'roiImage_{0}_{1}.png'.format(i, j))

                lnccValues2[i, j] = lncc2
                log.write('LNCC label {0} atlas {1}: {2} \t {3}\n'.format(i,j, lncc, lncc2))
                indicesSorted2 = np.argsort(lnccValues2, axis=1)
    # Sort indices for atlas selection and voting:
    indicesSorted = np.argsort(lnccValues, axis=1)

    if debug:
        log.write('Similarity order 1: {0}\n'.format(indicesSorted))
        log.write('Similarity order 2: {0}\n'.format(indicesSorted2))
        log.close()

    # Now do a majority voting with all the labels:
    # First apply the exponential to the sorted weights and normalize then:
    weightsForFusion = np.sort(lnccValues)
    weightsForFusion = weightsForFusion[:, 0:numSelectedAtlases]
    weightsForFusion = np.power(weightsForFusion, expWeight)
    weightsForFusion = weightsForFusion / np.sum(weightsForFusion, axis=1, keepdims=True)
    probImagesPerLabel = list()
    # The background I count it as a label in the voting, so numLabels+1
    for i in range(0, numLabels+1):
        probImageThisLabel = sitk.Image(registeredAtlases['labels'][0].GetSize(), sitk.sitkFloat32)
        probImageThisLabel.CopyInformation(registeredAtlases['labels'][0])
        for j in range(0, numSelectedAtlases):
            indexAtlas = indicesSorted[i, j]
            labelsImage = registeredAtlases['labels'][indexAtlas]
            # Get the mask for this label and atlas:
            weightsThisLabel = sitk.Image(registeredAtlases['labels'][0].GetSize(), sitk.sitkFloat32)
            weightsThisLabel.CopyInformation(registeredAtlases['labels'][0])
            maskFilter = sitk.MaskImageFilter()
            maskFilter.SetMaskingValue(i)
            maskFilter.SetOutsideValue(weightsForFusion[i,j])
            weightsThisLabel = maskFilter.Execute(weightsThisLabel, labelsImage)
            probImageThisLabel = sitk.Add(probImageThisLabel, weightsThisLabel)

        # Normalize, in order to be able to do dynamic labeling:
        probImageThisLabel = sitk.Divide(sitk.Cast(probImageThisLabel, sitk.sitkFloat32), numSelectedAtlases)
        probImagesPerLabel.append(probImageThisLabel)
        if debug:
            sitk.WriteImage(probImageThisLabel, outputPath + "ProbMap_label_{0}.mhd".format(i+1))
    fusedLabels = GetMajorityVotingFromProbMaps(probImagesPerLabel)
    return fusedLabels

def DynamicLabelFusionWithSimilarityWeights(targetImage, registeredAtlases, numLabels, numSelectedAtlases = 5,
                                            expWeight = 4, useOnlyLabelVoxels = False, outputPath=".\\", debug = 0):
    """" Fuses the labels from a set of registered atlases using the full atlas similarity.

    Arguments:
        targetImage: image being segmented:
        registeredAtlases: dictionary with a set of atlases having the fields image and labels for SimpleITK images with
                            the intensity image and the atlases
    """
    # If use background (=0) as another label:
    #numLabels = numLabels+1

    # if use only label voxels:
    if useOnlyLabelVoxels:
        minForMask = 1
    else:
        minForMask = 0

    # Generate a new image:
    fusedLabels = sitk.Image(targetImage.GetSize(), sitk.sitkUInt8)
    fusedLabels.SetSpacing(targetImage.GetSpacing())
    fusedLabels.SetOrigin(targetImage.GetOrigin())
    fusedLabels.SetDirection(targetImage.GetDirection())

    # Create a log file if debugging:
    if debug:
        if not os.path.exists(outputPath):
            os.mkdir(outputPath)
        logFilename = outputPath + 'log.txt'
        log = open(logFilename, 'w')

    # Get similarity weights for each label mask for each atlas
    lnccValues = np.zeros(len(registeredAtlases['image']))
    # Get a similarity metric for each label:
    for i in range(0, len(registeredAtlases['image'])):
        # Get intensity and label images for this case:
        intensityImage = registeredAtlases['image'][i]
        labelsImage = registeredAtlases['labels'][i]
        # Get the mask for this label and atlas:
        maskThisLabel = sitk.GreaterEqual(sitk.Cast(labelsImage, sitk.sitkUInt8), minForMask) #I check the similarity only using the voxels with labels.
        # Compute directly the normalized correlation:
        lncc = NCC.RoiNormalizedCrossCorrelationAsInITK(targetImage, intensityImage, maskThisLabel)
        lnccValues[i] = lncc
    # Sort indices for atlas selection and voting:
    indicesSorted = np.argsort(lnccValues)

    if debug:
        log.write('Similarity values: {0}\n'.format(lnccValues))
        log.write('Similarity order: {0}\n'.format(indicesSorted))

    # Now do a majority voting with all the labels, but using a different weight for each label based on similarity.
    # The similarity values goes from -1 (highest similarity) to 0 (lowest similarity). Now I will use a normalized
    # weighted average, but probably shouldn't be linear but based on the difference to the maximum.

    # First get the weights with the expoential amplification: normalized similarity weights:
    weightsForFusion = np.power(lnccValues[indicesSorted[0:numSelectedAtlases]], expWeight)
    weightsForFusion = weightsForFusion/np.sum(weightsForFusion)
    # Then obtain the probability maps and do the majority voting:
    probImagesPerLabel = list()
    # The background I count it as a label in the voting, so numLabels+1
    for i in range(0, numLabels+1):
        probImageThisLabel = sitk.Image(registeredAtlases['labels'][0].GetSize(), sitk.sitkFloat32)
        probImageThisLabel.CopyInformation(registeredAtlases['labels'][0])
        for j in range(0, numSelectedAtlases):
            indexAtlas = indicesSorted[j]
            labelsImage = registeredAtlases['labels'][indexAtlas]
            # Get the mask for this label and atlas:
            weightsThisLabel = sitk.Image(registeredAtlases['labels'][0].GetSize(), sitk.sitkFloat32)
            weightsThisLabel.CopyInformation(registeredAtlases['labels'][0])
            maskFilter = sitk.MaskImageFilter()
            maskFilter.SetMaskingValue(i)
            maskFilter.SetOutsideValue(weightsForFusion[j])
            weightsThisLabel = maskFilter.Execute(weightsThisLabel, labelsImage)
            # Now add the weights:
            probImageThisLabel = sitk.Add(probImageThisLabel, weightsThisLabel)

        # Normalize, in order to be able to do dynamic labeling:
        probImagesPerLabel.append(probImageThisLabel)
        if debug:
            sitk.WriteImage(probImageThisLabel, outputPath + "ProbMap_label_{0}.mhd".format(i+1))
    fusedLabels = GetMajorityVotingFromProbMaps(probImagesPerLabel)
    if debug:
        log.write('Weights for fusion: {0}\n'.format(weightsForFusion))
        log.close()
    return fusedLabels

# Gets the majority voting labels but from probability maps, instead of the segmented image.
# This can be useful when we have probability maps, because for different labels we have different
# amount of selected atlases.
# Receives probabilityMaps, that is a list where each element is an itk image for each label.
# A probabilityMap for the background is expected and it should be in probabilityMaps[0].
def GetMajorityVotingFromProbMaps(probabilityMaps, useBackgroundAsLabel = True):
    if probabilityMaps[0].GetDimension() == 3:
        ndaProbMaps = np.zeros((probabilityMaps[0].GetSize()[2],probabilityMaps[0].GetSize()[1],
                                probabilityMaps[0].GetSize()[0], len(probabilityMaps)))
        # Create a 4D array with all the probmaps.
        for i in range(0, len(probabilityMaps)):
            ndaProbMaps[:,:,:,i] = sitk.GetArrayFromImage(probabilityMaps[i])

        # Get the maximum for each label:
        labels = np.argmax(ndaProbMaps, axis = 3)
    elif probabilityMaps[0].GetDimension() == 2:
        ndaProbMaps = np.zeros((probabilityMaps[0].GetSize()[1], probabilityMaps[0].GetSize()[0], len(probabilityMaps)))
        # Create a 4D array with all the probmaps.
        for i in range(0, len(probabilityMaps)):
            ndaProbMaps[:,:,i] = sitk.GetArrayFromImage(probabilityMaps[i])
        # Get the maximum for each label:
        labels = np.argmax(ndaProbMaps, axis = 2)
    ##### THIS WAS NECESSARY WHEN A BACKGROUND LABEL WAS NOT EXPECTED ######################
    #labels = labels + 1 # Labels base index is 1
    ## Need to take into account the voxels with zeros as another label.
    ## get a Mask for the background:
    #backgroundMask = np.sum(ndaProbMaps, axis=3) == 0
    #labels[backgroundMask] = 0
    #######################################################################################
    # Create a new itk image with the labels
    labelsImage = sitk.Cast(sitk.GetImageFromArray(labels), sitk.sitkUInt8)
    labelsImage.CopyInformation(probabilityMaps[0])
    return labelsImage


class Solution(object):
    def ladderLength(self, beginWord, endWord, wordList):
        """
        :type beginWord: str
        :type endWord: str
        :type wordList: List[str]
        :rtype: int
        """
        if endWord not in wordList:
            return 0

        wordSet = set(wordList)
        charSet = set("abcdefghijklmnopqrstuvwxyz")

        def get_next(target_word, used_words):
            # 得到所有可能的下一个单词，要求如下：
            # 1. 与target_word的编辑距离为1
            # 2. 在wordSet中，且不再在uesd_words中
            next_words = []
            for i in range(len(target_word)):
                tmp_char_set = charSet.copy()
                tmp_char_set.remove(target_word[i])
                for c in tmp_char_set:
                    candidate = target_word[:i] + c + target_word[i + 1:]
                    if candidate in wordSet and candidate not in used_words:
                        next_words.append(candidate)
            return next_words

        forward = {beginWord}
        backword = {endWord}

        used_words = set()
        len_ = 2

        while forward:
            if len(forward) > len(backword):
                # 优先遍历较短的BFS
                forward, backword = backword, forward

            tmp = set()  # 用于更新forward
            used_words.update(forward)

            for end_word in forward:
                next_words = get_next(end_word, used_words)

                for next_word in next_words:
                    if next_word in backword:
                        return len_
                tmp.update(set(next_words))

            len_ += 1
            forward = tmp

        return 0

if __name__ == '__main__':
    beginWord = "dog"
    endWord = "hot"
    wordList = ["dog", "hot"]

    res = Solution().ladderLength(beginWord, endWord, wordList)
    print(res)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
from typing import List

# 给你两个整数数组 arr1 和 arr2，返回使 arr1 严格递增所需要的最小“操作”数（可能为 0）。

# 每一步“操作”中，你可以分别从 arr1 和 arr2 中各选出一个索引，分别为 i 和 j，0 <= i < arr1.length 和 0 <= j < arr2.length，然后进行赋值运算 arr1[i] = arr2[j]。

# 如果无法让 arr1 严格递增，请返回 -1。

# 示例 1：

# 输入：arr1 = [1,5,3,6,7], arr2 = [1,3,2,4]
# 输出：1
# 解释：用 2 来替换 5，之后 arr1 = [1, 2, 3, 6, 7]。
# 示例 2：

# 输入：arr1 = [1,5,3,6,7], arr2 = [4,3,1]
# 输出：2
# 解释：用 3 来替换 5，然后用 4 来替换 3，得到 arr1 = [1, 3, 4, 6, 7]。
# 示例 3：

# 输入：arr1 = [1,5,3,6,7], arr2 = [1,6,3,3]
# 输出：-1
# 解释：无法使 arr1 严格递增。
import bisect

class Solution:
    def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int:
        # 去重,排序
        arr2 = sorted(set(arr2))
        n, m = len(arr1), len(arr2)
        # dp[i][j] => arr1[:i]进行j次替换后的arr1[i-1]的最小值
        dp = [[float("inf")] * (min(m, n) + 1) for _ in range(n + 1)]
        dp[0][0] = -1
        for i in range(1, n + 1):
            for j in range(min(i, m) + 1):
                if arr1[i - 1] > dp[i - 1][j]:
                    dp[i][j] = arr1[i - 1]
                if j > 0 and dp[i - 1][j - 1] != float("inf"):
                    idx = bisect.bisect_right(arr2, dp[i - 1][j - 1], j - 1)
                    if idx < m:
                        dp[i][j] = min(dp[i][j], arr2[idx])
                if i == n and dp[i][j] != float("inf"):
                    return j
        return -1

def main():
    print(Solution().makeArrayIncreasing([1, 5, 3, 6, 7], [1, 3, 2, 4]))
    print(Solution().makeArrayIncreasing([1, 5, 3, 6, 7], [4, 3, 1]))
    print(Solution().makeArrayIncreasing([1, 5, 3, 6, 7], [1, 6, 3, 3]))

if __name__ == "__main__":
    main()


from enum import IntEnum

class Action(IntEnum):
    ROCK = 0
    PAPER = 1
    SCISSORS = 2

    @staticmethod
    def from_char(char: str) -> 'Action':
        if char in ['A', 'X']:
            return Action.ROCK
        elif char in ['B', 'Y']:
            return Action.PAPER
        else:
            return Action.SCISSORS

    @staticmethod
    def outcome(action: 'Action', response: 'Action') -> int:
        if action == response:
            return 3
        elif action == (response + 1) % 3:
            return 0
        else:
            return 6

    @staticmethod
    def target(action: 'Action', outcome: 'Action') -> 'Action':
        if outcome == Action.ROCK:    # loss
            return Action((action - 1) % 3)
        elif outcome == Action.PAPER: # draw
            return action
        else:                         # win
            return Action((action + 1) % 3)

if __name__ == '__main__':
    INPUT_FILE = 'Day 2-input.txt'
    with open(INPUT_FILE) as inputfile:
        input = inputfile.read()
    strategy = list(map(lambda s: tuple(Action.from_char(c) for c in s.split()), input.splitlines()))
    score = sum([Action.outcome(round[0], round[1]) + (round[1] + 1) for round in strategy])
    print(score) # Part 1
    score = sum([Action.outcome(round[0], Action.target(round[0], round[1])) + Action.target(round[0], round[1]) + 1 for round in strategy])
    print(score) # Part 2


import random
from Node import Node
from Function import Function
from Terminal import Terminal

class Individual(object):

    IDEAL_FITNESS = 0
    NOT_PLAYED_YET = -1

    def __init__(self, height):
        self.fitness = Individual.NOT_PLAYED_YET
        self.height = self.setHeight(height)
        self.tree = None
        self.generateFullTree(self.height)
        pass

    def __eq__(self, other):
        return self.getFitness() == other.getFitness()

    def __ne__(self, other):
        return self.getFitness() != other.getFitness()

    def __lt__(self, other):
        return self.getFitness() < other.getFitness()

    def evaluate(self):
        pass

    def getFitness(self):
        if self.fitness == Individual.NOT_PLAYED_YET:
            self.fitness = self.evaluate()
        return self.fitness

    def run(self, row, col, key, board, gradeboard, squareboard):
        return self.tree.run(row, col, key, board, gradeboard, squareboard)

    def setHeight(self, height):
        if height < 1:
            raise ValueError('height has to be greater or equal to 1')
        return height

    def isIdeal(self):
        return self.getFitness() == Individual.IDEAL_FITNESS

    def getTree(self):
        return self.tree

    def cloneFullTree(self):
        return self.copyFullTree(self.tree)

    def treeAsPrefixExpression(self):
        return self.ConvertTreeToPrefixExpression(self.tree)

    def treeAsInfixExpression(self):
        return self.ConvertTreeToInfixExpression(self.tree)

    def findHeight(self):
        return self.tree.findHeight()

    def generateFullTree(self, height):
        self.tree = self.createFullTree(height)
        pass

    def reGenerateFullTree(self):
        self.generateFullTree(self.height)

    def createFullTree(self, height):
        if height > 1:
            node = Function(random.choice(list(Function.functions.keys())))
            self.createSubTree(height - 1, node)
            pass
        else:
            if height == 1:
                node = Terminal(random.choice(list(Terminal.terminals.keys())))
                node.setLeft(None)
                node.setRight(None)
            else:
                raise ValueError('height has to be greater or equal to 1')
        node.setSize()
        node.findTreeHeight()
        return node

    def createSubTree(self, height, node):
        if height > 1:
            node.setLeft(Function(random.choice(list(Function.functions.keys()))))
            self.createSubTree(height - 1, node.getLeft())
            node.setRight(Function(random.choice(list(Function.functions.keys()))))
            self.createSubTree(height - 1, node.getRight())
        else:
            if height == 1:
                node.setLeft(Terminal(random.choice(list(Terminal.terminals.keys()))))
                node.setRight(Terminal(random.choice(list(Terminal.terminals.keys()))))
            else:
                raise ValueError('height has to be greater or equal to 1')

    def copyFullTree(self, cloneTree):
        copyTree = self.tree.clone()
        self.copySubTree(self.tree, copyTree)
        return cloneTree

    def copySubTree(self, sourceTree, cloneTree):
        if sourceTree.getLeft() is not None:
            cloneTree.setLeft(sourceTree.getLeft().clone())
            self.copySubTree(sourceTree.getLeft(), cloneTree.getLeft())
        if sourceTree.getRight() is not None:
            cloneTree.setRight(sourceTree.getRight().clone())
            self.copySubTree(sourceTree.getRight(), cloneTree.getRight())

    def ConvertTreeToPrefixExpression(self, tree):
        st = " " + tree.getOperationName()
        if tree.getLeft() is not None:
            st += "("
            st += " " + self.ConvertTreeToPrefixExpression(tree.getLeft()) + " "
        if tree.getRight() is not None:
            st += self.ConvertTreeToPrefixExpression(tree.getRight())
            st += ")"
        return st

    def ConvertTreeToInfixExpression(self, tree):
        st = ""
        if tree is None:
            return ""
        if tree.getLeft() is not None and tree.getLeft() is not Node:
            st += "( "
            st += self.ConvertTreeToInfixExpression(tree.getLeft())
        st += " " + self.ConvertFromFunctionToOperator(tree.getOperationName()) + " "
        if tree.getRight() is not None and tree.getRight() is not None:
            st += self.ConvertTreeToInfixExpression(tree.getRight())
            st += " )"
        return st

    def ConvertFromFunctionToOperator(self, operationName):
        operationsName = {
            "Plus": "+",
            "Minus": "-",
            "Multi": "*",
            "div": "/",
            "Mod": "%",
            "Maximum": "Max",
            "Minimum": "Min",
        }
        if operationsName.get(operationName) is None:
            return operationName
        return operationsName.get(operationName)

    @staticmethod
    def ConvertInfixStringToTree(str):
        tree, _ = Individual.__ConvertInfixStringToTree__(str.replace(" ", ""))
        tree.setSize()
        tree.findHeight()
        return tree

    @staticmethod
    def __ConvertInfixStringToTree__(str):
        if str.startswith('('):
            left, str = Individual.__ConvertInfixStringToTree__(str[1:])
        isTerminal = [str.startswith(terminal) for terminal in list(Terminal.terminals.keys())]
        if any(isTerminal):
            operationName = list(Terminal.terminals.keys())[isTerminal.index(True)]
            tree = Terminal(operationName)
            return tree, str.replace(operationName, "", 1)
        isFunction = [str.startswith(terminal) for terminal in ['*', "+"]]
        if any(isFunction):
            function = Function(['*', "+"][isFunction.index(True)])
            function.setLeft(left)
            right, str = Individual.__ConvertInfixStringToTree__(str[1:])
            function.setRight(right)
            return function, str[1:]

    def __str__(self):
        return "the tree as Prefix Sequence : \n" + self.treeAsPrefixExpression() + "\n\nthe tree as Infix Sequence : \n" + self.treeAsInfixExpression()


# @Author  : adairchan
# @Email   : adairchan.dream@gmail.com
# @Date    : 2019/4/5 22:38
# @IDE     : PyCharm

import requests

hd = {'User-agent': '123'}
r = requests.get('http://www.baidu.com', headers=hd)
print("返回状态码为:{}".format(r.status_code))
print("打印请求头:{}".format(r.request.headers))


 # -*- coding: utf-8 -*-
"""
@author: Savini Samarasinghe
"""

import data_helpers as data_helpers
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import cmasher as cmr
import shap
from sklearn.preprocessing import OneHotEncoder
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestRegressor
from sklearn.svm import SVR
from sklearn.kernel_ridge import KernelRidge
from sklearn.tree import DecisionTreeRegressor
from sklearn.decomposition import PCA
# import time
# import os
# from sklearn.inspection import permutation_importance
# from xgboost.sklearn import XGBRegressor
input_folder_path = '../Inputs'
output_folder_path = '../Outputs_no_file'

# =============================================================================
# Load and preprocess data
# =============================================================================

rho_fluid = 1
k_fluid = 2.2

k_quartz = 38  # Carmichael 1990
k_feldspar = 65  # Blangy's thesis
k_mica = 52  # Blangy's thesis
k_clay = 25  # Gluf clays (Han) Mavko's rock physics handbook

blangy_df = data_helpers.get_blangy_dataframe(
    input_folder_path, rho_fluid, k_fluid, k_quartz, k_clay, k_mica, k_feldspar)
strandenes_df = data_helpers.get_strandenes_df(
    input_folder_path, rho_fluid, k_fluid, k_quartz, k_clay, k_mica, k_feldspar)
han_df = data_helpers.get_han_df(
    input_folder_path, rho_fluid, k_quartz, k_clay, k_mica, k_feldspar, k_fluid)
mapeli_df = data_helpers.get_mapeli_df(
    input_folder_path, rho_fluid, k_quartz, k_clay, k_mica, k_feldspar, k_fluid)
yin_df = data_helpers.get_yin_df(input_folder_path, rho_fluid, k_quartz, k_clay,
                                  k_mica, k_feldspar, k_fluid)  # samples are brine saturated, but
# we are using rho_fluid = rho_water for the calculations

dataframes = [blangy_df, strandenes_df, han_df, mapeli_df, yin_df]
df_descriptions = ['Blangy, 1992', 'Strandenes, 1991',
                    'Han, 1986', 'Mapeli, 2018', 'Yin, 1993']
dataset_names =  ['Blangy', 'Strandenes',
                    'Han', 'Mapeli', 'Yin']
# dataframes = [blangy_df, strandenes_df, han_df,  yin_df]
# df_descriptions = ['Blangy, 1992', 'Strandenes, 1991',
#                     'Han, 1986', 'Yin, 1993']
# dataset_names =  ['Blangy', 'Strandenes',
#                     'Han',  'Yin']
all_data_df = pd.DataFrame()

for idx, df in enumerate(dataframes):

    print(df_descriptions[idx])
    data_helpers.print_k_sat_error(df)
    data_helpers.draw_cross_plot(x_data=df['k_sat'], y_data=df['k_sat_gassmann'], x_label='Measured K sat', y_label='Gassmann estimate',
                                  colorbar_label='|Measured - Gassmann|', show=False, color_by_var=np.abs(df['k_sat']-df['k_sat_gassmann']))
    plt.title(df_descriptions[idx])
    plt.show()

    # concatenate all data into a single dataframe
    df['file_info'] = idx+1
    all_data_df = pd.concat([all_data_df, df])

## Some EDA
error = all_data_df['k_sat']- all_data_df['k_sat_gassmann']
file_info =all_data_df['file_info']
plot_vars = [all_data_df['pressure'], all_data_df['porosity'], all_data_df['k_dry'], all_data_df['grain_density'], all_data_df['k_mineral'], all_data_df['g_dry']/all_data_df['g_sat'], all_data_df['clay']]
plot_vars_txt = ['pressure', 'porosity', 'K dry', 'grain density', 'K mineral', 'G dry/G sat', 'caly content']

colors = ['tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple']
file_names = [dataset_names[int(x-1)] for x in list(file_info)]

for i, qty in enumerate(plot_vars):
    plt.figure()
    sns.scatterplot(x = error, y = qty, hue = file_names, alpha = 0.7)
    plt.grid()
    plt.xlabel('K sat - K sat Gassmann')
    plt.ylabel(plot_vars_txt[i])
    plt.show()

# =============================================================================
# Get the data ready for machine learning
# =============================================================================

positive_error_only = False # to discard negative error samples
file_as_feature = True # to investigate experiment specific biases
num_repeats = 10
test_size = 0.1
nonlinear_method = 'random_forest'
assert(nonlinear_method in ['svr','kernel_ridge','random_forest','xgboost', 'decision_tree'])
input_features = ['pressure', 'porosity','k dry', 'k mineral','grain density', 'g ratio']
num_measurement_features = len(input_features)
standardize_inputs = True
decorrelate_inputs = False # use PCA to decorrelate measurement data

if file_as_feature:
    [input_features.append(name) for name in dataset_names]

all_shap_values = []
all_X_test = []
all_y_test = []
all_shap_interactions = []

for random_state in range(num_repeats):
    input_data = all_data_df[['pressure', 'porosity',
                              'k_dry', 'k_mineral', 'grain_density']].copy()
    input_data['g_ratio'] = all_data_df['g_dry']/all_data_df['g_sat']
    output_data = all_data_df['k_sat'] - all_data_df['k_sat_gassmann']
    #output_data = all_data_df['vp_sat'] - all_data_df['vp_sat_gassmann']

    # Standardize the inputs
    if standardize_inputs:
        scaler = StandardScaler(copy=True)
        scaler.fit(input_data.values)
        scaled_input_data = scaler.transform(input_data.values)
    else:
        scaled_input_data = input_data
    if decorrelate_inputs :
        pca = PCA()
        pca.fit(scaled_input_data )

        pc_names = ["PC" + str(x + 1) for x in range(pca.components_.shape[0])]
        x_pca = pca.transform(scaled_input_data)
        loadings = pd.DataFrame(pca.components_.T, columns=pc_names, index = input_features[:num_measurement_features])
        X_dummy = np.concatenate(
            (x_pca, all_data_df['file_info'].values[:, np.newaxis]), axis=1)
    else:
        X_dummy = np.concatenate(
            (scaled_input_data, all_data_df['file_info'].values[:, np.newaxis]), axis=1)

    if positive_error_only:
        data_id = (output_data>=0)
        X_train, X_test, y_train, y_test = train_test_split(X_dummy[data_id,:], output_data[data_id], random_state=random_state,test_size=test_size, stratify=all_data_df['file_info'][data_id])
        # A % of data from each dataset used for validation
    else:
        X_train, X_test, y_train, y_test = train_test_split(X_dummy, output_data, random_state=random_state,test_size=test_size, stratify=all_data_df['file_info'])

    # # becuase the different experiments can have biases and limitations that are not
    # # necessarily associated to the Gassman's model, we can also include the data source as an additional input feature. The file number will be one hot encoded as a categorical variable.
    # here I will use onehotencoding instead of binary because it will be easier for the explainability methods
    if file_as_feature:
        onehot_encoder = OneHotEncoder(sparse=False)
        train_file_info = onehot_encoder.fit_transform(np.expand_dims(X_train[:,-1], axis = 1))
        test_file_info = onehot_encoder.fit_transform(np.expand_dims(X_test[:,-1], axis = 1))
        X_train = np.hstack((X_train[:, :-1],train_file_info))
        X_test = np.hstack((X_test[:, :-1],test_file_info))
    else:
        X_train = X_train[:, :-1]
        X_test = X_test[:, :-1]

    # =============================================================================
    # Linear Regression
    # =============================================================================

    # if file is used the R2 squared is about 0.5, if not about 0.3 for the linear model
    model = LinearRegression()
    model.fit(X_train, y_train)
    coeff = model.coef_
    train_prediction = model.predict(X_train)
    test_prediction = model.predict(X_test)
    # print the coefficients
    for i,feature in enumerate(input_features):
        print("Coefficient for {} = {:.3f}".format(feature, coeff[i]))

    data_helpers.draw_cross_plot(x_data=y_train, y_data=train_prediction, x_label='Ground truth', y_label='Prediction',
                                  colorbar_label='|GT - Prediction|', show=False, color_by_var=np.abs(y_train-train_prediction))
    plt.title('Training R squared = {}'.format(model.score(X_train, y_train)))

    data_helpers.draw_cross_plot(x_data=y_test, y_data=test_prediction, x_label='Ground truth', y_label='Prediction',
                                  colorbar_label='|GT - Prediction|', show=False, color_by_var=np.abs(y_test-test_prediction))
    plt.title('Testing R squared = {}'.format(model.score(X_test, y_test)))
    print('Linear regression training R squared = {:.3f}'.format(model.score(X_train, y_train)))
    print('Linear regression testing R squared = {:.3f}'.format(model.score(X_test, y_test)))

    # =============================================================================
    # Non linear regression
    # =============================================================================

    # most authors advocate against the use of the R2 in nonlinear regression
    #analysis and recommend alternative measures, such as the Mean Squared Error
    #(MSE; see Ratkowsky, 1990) or the AIC and BIC
    if nonlinear_method == 'svr':
        model = SVR
        search = GridSearchCV(model(),
                    param_grid={"C": [1e0, 1e1, 1e2, 1e3], "epsilon": np.logspace(-2, 2, 5),
                                "kernel":["rbf"]},
                    scoring =  'neg_mean_squared_error',
                    n_jobs = 12, cv = 10)

    elif nonlinear_method == 'kernel_ridge':
        model = KernelRidge
        search = GridSearchCV(model(),
        param_grid={"alpha": [1e0, 0.1, 1e-2, 1e-3], "gamma": np.logspace(-2, 2, 5),
                    "kernel":["rbf"]},
        scoring =  'neg_mean_squared_error',
        n_jobs = 12, cv = 10 )
    elif nonlinear_method == 'decision_tree':
        model = DecisionTreeRegressor
        search= GridSearchCV( model(),
         param_grid={'max_depth':np.arange(2,21,2),
                     'min_samples_split':np.arange(2,10),
                     'min_samples_leaf':np.arange(1,8)},
         scoring =  'neg_mean_squared_error',
         n_jobs = 12, cv = 10)
    elif nonlinear_method == 'random_forest':
         model = RandomForestRegressor
         search = GridSearchCV(model(),
         param_grid={'max_depth':np.arange(5,21),
                     'n_estimators':[25,50,75,100,200],
                     'min_samples_leaf':np.arange(1,5)},
         n_jobs = 12, cv = 5,
         scoring = 'neg_mean_squared_error')

    search.fit(X_train, y_train)
    print(f"Best model params: {search.best_params_} and MSE score: {search.best_score_:.3f}")

    optimal_model = model(**search.best_params_)
    optimal_model.fit(X_train,y_train)
    print('Nonlinear regression pseudo R squared on training data= {:.3f}'.format(optimal_model.score(X_train, y_train)))
    print('Nonlinear regression pseudo R squared on testing data= {:.3f}'.format(optimal_model.score(X_test, y_test)))

    if((nonlinear_method == 'decision_tree') | (nonlinear_method == 'random_forest')):
        explainer = shap.Explainer(optimal_model)

        shap_values_test = explainer.shap_values(X_test)
        interaction = explainer.shap_interaction_values(X_test)

        if decorrelate_inputs:
            # aggregate shap values using the pca loadings to investigate the attributions of the original
            # measurement variables
            pca_shap_values = shap_values_test[:,:num_measurement_features]
            shap_values = shap_values_test
            for i in range(num_measurement_features):
                feature_loadings = loadings.loc[input_features[i]].values
                shap_values[:,i] = pca_shap_values@feature_loadings

        else:
            shap_values = shap_values_test

        my_cmap = plt.get_cmap('viridis')
        plt.figure()
        shap.summary_plot(shap_values,X_test,
                          feature_names=input_features, show=False)
        plt.title('Shap Values on test data')
        # Change the colormap of the artists
        for fc in plt.gcf().get_children():
            for fcc in fc.get_children():
                if hasattr(fcc, "set_cmap"):
                    fcc.set_cmap(my_cmap)
        plt.show()

        all_shap_values.append(shap_values)
        all_X_test.append(X_test)
        all_y_test.append(y_test)
        all_shap_interactions.append(interaction)
    else:
        raise NotImplementedError('Kernel SHAP required for models that are not based on trees')

plot_data = np.array(all_X_test).reshape(-1,len(input_features))
inverse_transformed_data = scaler.inverse_transform(plot_data[:,:6])
if file_as_feature:
    rescaled_X_test = np.hstack((inverse_transformed_data, plot_data[:,6:]))
else:
    rescaled_X_test = inverse_transformed_data

y_data = np.array(all_y_test).reshape(-1,1)
shap = np.array(all_shap_values).reshape(-1,len(input_features))
shap_interactions = np.array(all_shap_interactions).reshape(-1,len(input_features),len(input_features))

for i in range(num_measurement_features):
    plt.figure()
    plt.grid()
    if (input_features[i] == 'g ratio'):
        c_delta = np.max([np.max(rescaled_X_test[:,i])-1, 1-np.min(rescaled_X_test[:,i])])
        c_delta = np.round(c_delta,1)
        plt.scatter(shap[:,i], y_data, c = rescaled_X_test[:,i], cmap = cmr.fusion_r, alpha = 0.8, vmin = 1-c_delta, vmax = 1+c_delta)
    else:
        plt.scatter(shap[:,i], y_data, c = rescaled_X_test[:,i], cmap = cmr.dusk, alpha = 0.8)

    plt.xlabel('SHAP values')
    plt.ylabel('K sat - K sat Gassmann')
    plt.colorbar(label =input_features[i] )
    plt.savefig(output_folder_path+'/Shap_'+input_features[i]+'.png', dpi =300)
    plt.show()

for i in range(num_measurement_features, len(input_features) ):
    plt.figure()
    plt.grid()

    plt.scatter(shap[:,i], y_data, c = plot_data[:,i], cmap = 'RdGy', alpha = 0.8)

    plt.xlabel('SHAP values')
    plt.ylabel('K sat - K sat Gassmann')
    plt.colorbar(label =input_features[i] )
    plt.savefig(output_folder_path+'/Shap_'+input_features[i]+'.png', dpi =300)
    plt.show()

# =============================================================================
#     Mean absolute SHAP plot
# =============================================================================

mean_abs_shap_values = np.mean(np.abs(shap), axis = 0)
sort_idx = np.argsort(mean_abs_shap_values)
std_abs_shap_values = np.std(np.abs(shap), axis = 0)

plt.figure()
plt.barh(np.array(input_features)[sort_idx],mean_abs_shap_values[sort_idx], xerr = std_abs_shap_values[sort_idx], color = 'grey', edgecolor = 'grey', label = 'mean abs SHAP value')
plt.legend()
plt.tight_layout()
plt.savefig(output_folder_path+'/Shap_mean_abs.png', dpi =300)
plt.show()

# =============================================================================
# SHAP interaction plot
# =============================================================================

# Get absolute mean of matrices
mean_shap = np.abs(shap_interactions).mean(0)
df = pd.DataFrame(mean_shap,index=input_features,columns=input_features)

# times off diagonal by 2
df.where(df.values == np.diagonal(df),df.values*2,inplace=True)

# Define mask used to cover squares above diagonal
mask = []
for i in range(len(input_features)):
    mask_i = []
    for j in range(len(input_features)):
        if i>=j:
            mask_i.append(1)
        else:
            mask_i.append(np.nan)
    mask.append(mask_i)
mask = np.array(mask)

# display
plt.figure(figsize=(12, 10), facecolor='w', edgecolor='k')
sns.set(font_scale=1.5)
sns.heatmap(np.round(df*mask,2),  cmap=cmr.lavender, annot=True, fmt='.2g', cbar=True)
plt.yticks(rotation=0)
plt.show()

# =============================================================================
# Visualize main effects (the values that are along the diagonal)
# =============================================================================

colorbar_lim = np.max(np.abs(y_data))
for feature1 in range(len(input_features)):
    for feature2 in range(len(input_features)):
        if (feature1==feature2) & (df.loc[input_features[feature1], input_features[feature2]]>=0.08):
            plt.figure()
            plt.scatter(rescaled_X_test[:,feature1], shap_interactions[:,feature1,feature2], c =y_data ,
                        cmap = cmr.fusion_r, alpha = 0.9, vmin = -colorbar_lim, vmax = colorbar_lim)
            plt.xlabel(input_features[feature1])
            plt.colorbar(label = 'K sat - K sat Gassmann')
            plt.show()


# -*- coding: utf-8 -*-
import asyncio
import time

from poke_env.player.player import Player
from poke_env.player.random_player import RandomPlayer
from max_damage_player import MaxDamagePlayer
from poke_env.environment.move_category import MoveCategory
from poke_env.player.env_player import Gen8EnvSinglePlayer

class SnivyPlayer(Gen8EnvSinglePlayer):
    def choose_move(self, battle):
        #If at full health, set up
        # If the player can attack, it will
        if battle.available_moves:
            # Picks first status move to spam
            if battle.active_pokemon.current_hp_fraction == 1:
                for moof in battle.available_moves:
                    if(moof.category == MoveCategory.STATUS):
                        return self.create_order(moof)
                #No status moves to choose from
                return self.choose_random_move(battle)
            else:
                best_move = max(battle.available_moves, key=lambda move: move.base_power)
                return self.create_order(best_move)

        # If no attack is available, a random switch will be made
        else:
            return self.choose_random_move(battle)

    def attempt_move(self, battle):
        #If at full health, set up
        # If the player can attack, it will
        if battle.available_moves:
            # Picks first status move to spam
            if battle.active_pokemon.current_hp_fraction == 1:
                for moof in battle.available_moves:
                    if(moof.category == MoveCategory.STATUS):
                        return self.create_order(moof)
                #No status moves to choose from
                return self.choose_random_move(battle)
            else:
                best_move = max(battle.available_moves, key=lambda move: move.base_power)
                return self.create_order(best_move)

        # If no attack is available, a random switch will be made
        else:
            return self.choose_random_move(battle)

    async def snivy_message(
        self, player, message
    ) -> None:
        await self.player_message(player, message)
        #await self._challenge("Archlei", "gen8randombattle")
        #USE /pm COMMAND TO MESSAGE ON SHOWDOWN

    def embed_battle(self, battle):
        # -1 indicates that the move does not have a base power
        # or is not available
        moves_base_power = -np.ones(4)
        moves_dmg_multiplier = np.ones(4)
        for i, move in enumerate(battle.available_moves):
            moves_base_power[i] = move.base_power / 100 # Simple rescaling to facilitate learning
            if move.type:
                moves_dmg_multiplier[i] = move.type.damage_multiplier(
                    battle.opponent_active_pokemon.type_1,
                    battle.opponent_active_pokemon.type_2,
                    #battle.opponent_active_pokemon.moves,#type_1,
                    #battle.opponent_active_pokemon.item,#type_2,
                )

        # We count how many pokemons have not fainted in each team
        remaining_mon_team = len([mon for mon in battle.team.values() if mon.fainted]) / 6
        remaining_mon_opponent = (
            len([mon for mon in battle.opponent_team.values() if mon.fainted]) / 6
        )

        # Final vector with 10 components
        return np.concatenate(
            [moves_base_power, moves_dmg_multiplier, [remaining_mon_team, remaining_mon_opponent]]
        )
    def compute_reward(self, battle) -> float:
        return self.reward_computing_helper(
            battle, fainted_value=2, hp_value=1, victory_value=30
        )

async def main():
    start = time.time()

    # We create two players.
    max_damage_player = MaxDamagePlayer()
    #mdp2 = MaxDamagePlayer()
    #await mdp2.battle_against(max_damage_player, n_battles=5)
    snivy_player = SnivyPlayer()

    # Now, let's evaluate our player
    await snivy_player.battle_against(max_damage_player, n_battles=5)
    #await snivy_player.snivy_message("Archlei","Hello world. I am Snivy")
    #for a in range(10):
    #    snivy_player = SnivyPlayer(battle_format="gen8randombattle")
    #    await snivy_player.snivy_message("Archlei","Hello world. I am Snivy")

    #await snivy_player.player_message(f"/challenge {name}, {format_}", "lobby")
    """print(
        "Snivy player won %d / 100 battles [this took %f seconds]"
        % (snivy_player.n_won_battles, time.time() - start)
    )"""

if __name__ == "__main__":
    asyncio.get_event_loop().run_until_complete(main())


# -*- coding: utf-8 -*-
import os
import scrapy
from scrapy.utils.project import get_project_settings
from ..common import hash_row, scraped_links

class FSitemapSpider(scrapy.Spider):
    custom_settings = {
        'REDIRECT_ENABLED': True,
    }
    name = 'fsitemap'
    allowed_domains = ['zen.yandex.ru', 'irecommend.ru', 'otvet.mail.ru', 'pikabu.ru', 'www.banki.ru', 'www.ivi.ru', 'banki.ru', 'ivi.ru', 'www.yaplakal.com']
    start_urls = []

    fs_links = None
    skip_lines = 0

    def __init__(self, *args, **kwargs):
        super(FSitemapSpider, self).__init__(*args, **kwargs)

        id = int(kwargs.pop('urlid', -1))
        if id < 0:
            self.logger.warning('Wrong "urlid"')
            return

        scraped_urls = scraped_links('sitemap_{}'.format(id))
        self.logger.info('Found {} scraped pages'.format(len(scraped_urls)))

        if 12 == id:
            scraped_urls_ = set('https://zen.yandex.ru/' + '/'.join(link.replace('https://zen.yandex.ru/', '').split('/')[:-1] + link.split('-')[-1:]) for link in scraped_urls)
        else:
            scraped_urls_ = set()

        storage_paths = get_project_settings().get('DEFAULT_EXPORT_STORAGES', [])
        for storage in storage_paths:
            if not os.path.exists(storage):
                continue
            feed = os.path.join(storage, 'fs_links', 'sitemap_{}.txt'.format(id))
            if not os.path.exists(feed):
                continue
            self.fs_links = feed
            break

        if self.fs_links is None:
            self.logger.warning('Not found links to scrape')
            return

        if len(scraped_urls):
            with open(self.fs_links, 'rt') as f:
                line = 0
                for row in f:
                    line += 1
                    row = row.strip()
                    if not len(row):
                        continue
                    if row in scraped_urls or row in scraped_urls_:
                        self.skip_lines = line

        del scraped_urls

        self.logger.info('Will skip {} lines'.format(self.skip_lines))

    def start_requests(self):
        if self.fs_links is None:
            return

        with open(self.fs_links, 'rt') as f:
            line = 0
            for row in f:
                line += 1
                if line < self.skip_lines:
                    continue
                row = row.strip()
                if not len(row):
                    continue

                yield scrapy.Request(row, dont_filter=True)

    def parse(self, response):
        yield {
            'hash': hash_row([response.url, response.text]),
            'url': response.url,
            'html': response.text
        }


# prefix to infix

def prefixToInfix(s):
    stack = []
    operators = ['+', '-', '*', '/', '^']
    s = s[::-1]

    for i in s:
        if i in operators:
            a = stack.pop()
            b = stack.pop()
            temp = '(' + a + i + b + ')'
            stack.append(temp)

        else:
            stack.append(i)

    return stack[0]

# Driver code
if __name__=="__main__":
    s = "*-A/BC-/AKL"
    print(prefixToInfix(s))   # ((A-(B/C))*((A/K)-L))


from stst.data import dict_utils
from stst.modules.features import Feature

class NegativeFeature(Feature):
    def extract(self, train_instance):
        negation = dict_utils.DictLoader().load_dict('negation_terms')
        lemma_sa, lemma_sb = train_instance.get_word(type='lemma', lower=True)
        na = sum([1 if w in negation else 0 for w in lemma_sa])
        nb = sum([1 if w in negation else 0 for w in lemma_sb])

        features = [(na - nb) % 2]
        infos = [na, nb]
        return features, infos

class EnNegativeFeature(Feature):
    def __init__(self, penalty, **kwargs):
        super(EnNegativeFeature, self).__init__(**kwargs)
        self.load = False
        self.penalty = penalty

    def extract(self, train_instance):
        negation = dict_utils.DictLoader().load_dict('negation_terms')
        lemma_sa, lemma_sb = train_instance.get_word(type='lemma', lower=True)
        na = sum([1 if w in negation else 0 for w in lemma_sa])
        nb = sum([1 if w in negation else 0 for w in lemma_sb])

        if (na - nb) % 2 != 0:
            score = self.penalty
        else:
            score = 0.0
        features = [score]
        infos = [na, nb]
        return features, infos


from django.db import models
from comentarios.models import Comentario
from avaliacoes.models import Avaliacao
from atracoes.models import Atracao
from enderecos.models import Endereco

class PontoTuristico(models.Model):
    name = models.CharField(max_length=150)
    description = models.TextField()
    is_approved = models.BooleanField(default=False)
    atracoes = models.ManyToManyField(Atracao)
    comentarios = models.ManyToManyField(Comentario)
    avaliacoes = models.ManyToManyField(Avaliacao)
    enderecos = models.ForeignKey(Endereco, on_delete=models.CASCADE, null=True, blank=True)
    photo = models.ImageField(upload_to='pontos_turisticos', null=True, blank=True)

    class Meta:
        verbose_name = 'Ponto Turístico'
        verbose_name_plural = 'Pontos Turísticos'

    def __str__(self):
        return self.name


import sys

N = int(input())

tip = 0
tip_list = []

for _ in range(N):
    tip_list.append(int(sys.stdin.readline().rstrip()))

tip_list.sort(reverse=True)

for index in range(N):
    calculated_tip = tip_list[index] - index
    if (calculated_tip > 0):
        tip = tip + calculated_tip

print(tip)


"""
You are working in a ball factory where you have n balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit - lowLimit + 1), and an infinite number of boxes numbered from 1 to infinity.

Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number 321 will be put in the box number 3 + 2 + 1 = 6 and the ball number 10 will be put in the box number 1 + 0 = 1.

Given two integers lowLimit and highLimit, return the number of balls in the box with the most balls.
"""

"""
Using a dictionary and a counter to track the largest value
"""
def countBalls(self, lowLimit: int, highLimit: int) -> int:

    d = {}
    largest_value = 0
    for num in range(lowLimit, highLimit+1):
        s = 0
        while num > 0:
            reminder = num % 10
            s += reminder
            num = num // 10
        if s not in d:
            d[s] = 1
        else:
            d[s] += 1
        if d[s] > largest_value:
            largest_value = d[s]

    return largest_value


import mraa

__all__ = ['GPIO']

class GPIO(mraa.Gpio):
    OUT = mraa.DIR_OUT
    IN = mraa.DIR_IN

    def __init__(self, pin, direction = None):
        mraa_pin = mraa.getGpioLookup("GPIO%02d" % pin)
        super(GPIO, self).__init__(mraa_pin, raw = False)
        self.pin = pin

        if direction is not None:
            if direction == self.OUT:
                self.edge(mraa.EDGE_NONE)
            self.dir(direction)

        self._event_handle = None

    @staticmethod
    def _on_event(self):
        value = self.read()
        if self._event_handle:
            self._event_handle(self.pin, value)

    @property
    def on_event(self):
        return self._event_handle

    @on_event.setter
    def on_event(self, handle):
        if not callable(handle):
            return
        if self._event_handle is None:
            self.isr(mraa.EDGE_BOTH, self._on_event, self)

        self._event_handle = handle


from numpy import *
from matplotlib.mlab import find
from pylab import *

B = loadtxt("77000000.txt")
x = B[:,0]
y = B[:,1]
u = B[:,2]
v = B[:,3]

x = x[x!=0]
ux = unique(x)
minx = min(ux)
maxx = max(ux)

y = y[y!=0]
uy = unique(y)
miny= min(uy)
maxy = max(uy)

xx,yy = meshgrid(linspace(minx,maxx,ux.shape[0]),linspace(miny,maxy,uy.shape[0]))
rows,cols = xx.shape

uu = zeros_like(xx)
vv = zeros_like(yy)

for i,n in enumerate(x):
    m,n = unravel_index(find(logical_and((xx==x[i]),(yy==y[i]))),(rows,cols))
    uu[m,n] = u[i]
    vv[m,n] = v[i]

ux,uy = gradient(uu)
vx,vy = gradient(vv)
vort = vx - uy

M = zeros(uu.shape, dtype='bool')
M[xx<900] = True
M[xx>1550] = True
M[abs(vort)>2]=True
M[yy<200] = True

uu = ma.masked_array(uu,mask=M)
vv = ma.masked_array(vv,mask=M)
vort = ma.masked_array(vort,mask=M)

figure()
im = imread('000077RA.TIF')
imshow(im,origin='lower',cmap=cm.gray)
hold('on')
Q = quiver(xx,yy,uu,vv,vort,pivot='middle',scale=400,width=.0015)
clim(-1.5,1.5)
colorbar()
# clim(-.1,.1)


import requests
from pathlib import Path
from django.contrib import admin
from django.core.files.base import ContentFile
from django.shortcuts import render, redirect
from django.db import IntegrityError
from django.urls import path
from .models import Movie
from django.forms import *
import csv
from django.contrib import messages
from io import TextIOWrapper
from zipfile import ZipFile
from cinema.settings import MEDIA_ROOT

# Register your models here.

class CsvForm(forms.Form):
    csv_file = forms.FileField()

class ZipFileForm(forms.Form):
    zip_file = forms.FileField()

@admin.register(Movie)
class MovieAdmin(admin.ModelAdmin):
    change_list_template = "movies/movie_admin.html"

    def get_urls(self):
        urls = super().get_urls()
        defined_urls = [
            path("import_csv/", self.import_movies),
            path("import_zip/", self.import_movies_from_zip),
        ]
        return defined_urls + urls

    def import_movies(self, request):
        form = CsvForm(request.POST, request.FILES)
        if form.is_valid():
            csv_file = TextIOWrapper(request.FILES['csv_file'], encoding=request.encoding)
            movies = csv.DictReader(csv_file)
            added_movies = []
            updated_movies = []
            system_list = Movie.objects.values_list('pk', flat=True)
            for movie in movies:
                created_movie = Movie(**movie)
                try:
                    name = movie["poster"].split("/")[-1]
                    response = requests.get(created_movie.poster)

                    if response.status_code == 200:
                        created_movie.poster.save(
                            name, ContentFile(response.content), save=False
                        )
                    if int(movie['pk']) not in system_list:
                        added_movies.append(Movie(**movie))
                    elif int(movie['pk']) in system_list:
                        updated_movies.append(Movie(**movie))
                except (requests.exceptions.MissingSchema, IntegrityError) as e:
                    messages.error(
                        request=request,
                        message=f"\nFailed to add movie: {movie} to the DB due to following error: {e}",
                    )

            Movie.objects.bulk_create(added_movies)
            Movie.objects.bulk_update(updated_movies,
                                      fields=['name', 'poster', 'description', 'imdb_id', 'length_min',
                                              'trailer_url'])

            return redirect("admin:movies_movie_changelist")

        return render(request, 'movies/import_movies.html', {'form': form})

    def import_movies_from_zip(self, request):
        form = ZipFileForm(request.POST, request.FILES)
        if form.is_valid():
            zip_file = ZipFile(request.FILES['zip_file'])
            files = zip_file.namelist()
            for csv_file in files:
                path = MEDIA_ROOT

                if csv_file.endswith('.csv'):
                    zip_file.extractall(path=path)
                    with open(f'{path}/{csv_file}', 'r') as csv_file:
                        csv_data = csv.DictReader(csv_file)
                        added_movies = []
                        updated_movies = []
                        system_list = Movie.objects.values_list('pk', flat=True)
                        for movie_data in csv_data:
                            try:
                                created_movie = Movie(**movie_data)
                                poster_path = Path(path + movie_data['poster'])
                                created_movie.poster = poster_path.name
                                if int(movie_data['pk']) not in system_list:
                                    added_movies.append(created_movie)
                                elif int(movie_data['pk']) in system_list:
                                    updated_movies.append(created_movie)
                            except (requests.exceptions.MissingSchema, IntegrityError) as e:
                                messages.error(
                                    request=request,
                                    message=f"\nFailed to add movie: {created_movie} to the DB due to following error: {e}",
                                )

                        Movie.objects.bulk_create(added_movies)
                        Movie.objects.bulk_update(updated_movies,
                                                  fields=['name', 'poster', 'description', 'imdb_id', 'length_min',
                                                          'trailer_url'])
                return redirect('admin:movies_movie_changelist')

        return render(request, 'movies/import_movies.html', {'form': form})


# coding=utf8
class Persion:
    name = []

p1 = Persion()
p2 = Persion()
p1.name.append("小美")
print(p1.name)
print(p2.name)
print(Persion.name)

# 单例模式

class Singleton(object):
    """
    单例模式
    """
    class _A(object):
        """
        真正干活类，对外隐藏
        """
        def __init__(self):
            pass
        def display(self):
            """返回当前实例的 ID，是全局唯一的"""
            return id(self)

    # 类变量，用于存储 _A的实例

    _instance = None

    def __init__(self):
        if Singleton._instance is None:
            Singleton._instance = Singleton._A()

    def __getattr__(self, item):
        """所有的属性都应该从 Singleton._instance 获取"""
        return getattr(self._instance,item)

if __name__ == '__main__':
    s1 = Singleton()
    s2 = Singleton()
    print(id(s1),s1.display())
    print(id(s2),s2.display())


from torch.utils.data import Dataset
import faiss
import torch
from variables import *

class SADataset(Dataset):

        def __init__(self, sents_original, sents_ids, lens, labels, bert_model):
            self.sents_original = sents_original
            self.sents_ids = sents_ids
            self.lens = lens
            self.len_dataset = len(sents_ids)
            self.labels = labels
            self.model = bert_model

        def __getitem__(self, i):
            bert_text = self.model.encode(self.sents_original[i][:MAX_LEN])

            return bert_text, torch.tensor(self.sents_ids[i]).long(), torch.tensor(self.lens[i]).long(), torch.tensor(
                self.labels[i], dtype=torch.float64)

        def __len__(self):
            return self.len_dataset

class TrainRetrievalDataset(Dataset):

        def __init__(self, train_sents, bert_model):
            if DEBUG:
                self.train_sents=train_sents[:40]
            else:
                self.train_sents=train_sents
            self.dataset_size = len(self.train_sents)
            self.model = bert_model

        def __getitem__(self, i):
            bert_text = self.model.encode(self.train_sents[i][:MAX_LEN])
            return bert_text

        def __len__(self):
            return self.dataset_size

class TextRetrieval():

    def __init__(self, train_dataloader, labels):
        dim_examples = 768
        self.datastore = faiss.IndexFlatL2(dim_examples)

        if MODEL_TYPE== "SAR_bert":
            self.labels = labels
            self.neg_bert_embedding = torch.zeros(dim_examples)
            self.pos_bert_embedding = torch.zeros(dim_examples)
            self.number_of_neg = 0.0
            self.number_of_pos = 0.0
            self._add_examples_SAR_bert(train_dataloader)
            self.neg_bert_embedding = self.neg_bert_embedding/self.number_of_neg
            self.pos_bert_embedding = self.pos_bert_embedding/self.number_of_pos

        else:
            self._add_examples(train_dataloader)

    def _add_examples(self, train_dataloader):

        print("\nAdding input examples to datastore (retrieval)")
        for i, (text_bert) in enumerate(train_dataloader):
            self.datastore.add(text_bert.cpu().numpy())
            if i%5==0:
                print("batch, n of examples", i, self.datastore.ntotal)
        print("finish retrieval")

    def _add_examples_SAR_bert(self, train_dataloader):

        print("\nAdding input examples to datastore (retrieval)")

        for i, (text_bert) in enumerate(train_dataloader):
            batch_size = text_bert.size()[0]

            neg_sentences = text_bert[torch.tensor(self.labels[i*batch_size:i*batch_size+batch_size])==0]
            self.number_of_neg +=neg_sentences.size()[0]
            self.neg_bert_embedding += torch.sum(neg_sentences, dim=0)

            pos_sentences = text_bert[torch.tensor(self.labels[i*batch_size:i*batch_size+batch_size])==1]
            self.number_of_pos += pos_sentences.size()[0]
            self.pos_bert_embedding += torch.sum(pos_sentences, dim=0)

            self.datastore.add(text_bert.cpu().numpy())
        print("finish retrieval")

    def retrieve_nearest_for_train_query(self, query_text, k=2):

        D, I = self.datastore.search(query_text, k)
        nearest_input = I[:,1]

        return nearest_input

    def retrieve_nearest_for_val_or_test_query(self, query_text, k=1):

        D, I = self.datastore.search(query_text, k)
        nearest_input = I[:,0]

        return nearest_input


#!/usr/bin/python3

import os
import sqlite3
import sys

def create_db_table():
    conn = sqlite3.connect(os.environ.get("HOME") + "/mfa.db")
    cursor = conn.cursor()

    cursor.execute(''' CREATE TABLE IF NOT EXISTS secrets(email TEXT PRIMARY KEY, secret TEXT); ''')

    conn.commit()

def create_db_record(email, secret_key):
    create_db_table()

    conn = sqlite3.connect(os.environ.get("HOME") + "/mfa.db")
    cursor = conn.cursor()

    cursor.execute(''' INSERT INTO secrets(email, secret) VALUES(?,?) ''', (email, secret_key))

    conn.commit()

def remove_db_record(email):
    conn = sqlite3.connect(os.environ.get("HOME") + "/mfa.db")
    cursor = conn.cursor()

    cursor.execute(''' DELETE FROM secrets WHERE email=? ''', (email,))

    conn.commit()

def check_if_email_exists(email):
    conn = sqlite3.connect(os.environ.get("HOME") + "/mfa.db")
    cursor = conn.cursor()

    result = cursor.execute(''' SELECT * FROM secrets WHERE email=? ''', (email,)).fetchall()

    return len(result)

def check_if_any_record_exists():
    conn = sqlite3.connect(os.environ.get("HOME") + "/mfa.db")
    cursor = conn.cursor()

    result = cursor.execute(''' SELECT COUNT(*) FROM secrets ''').fetchall()[0][0]

    return result

def read_secret_from_db(email):
    try:
        conn = sqlite3.connect(os.environ.get("HOME") + "/mfa.db")
        cursor = conn.cursor()

        cursor.execute(''' SELECT secret FROM secrets WHERE email=? ''', (email,))

        return cursor.fetchall()[0][0]
    except sqlite3.Error as err:
        print(err)
        return None

def list_all_records(with_secrets=False):
    conn = sqlite3.connect(os.environ.get("HOME") + "/mfa.db")
    cursor = conn.cursor()

    if with_secrets:
        result = cursor.execute(''' SELECT * FROM secrets ''').fetchall()
    else:
        result = cursor.execute(''' SELECT email FROM secrets ''').fetchall()

    print(result)


import sys
import math
from collections import deque

n, m, k, x = map(int, sys.stdin.readline().split(" "))

graph = {}

for i in range(1, n+1):
    graph[i] = []
for i in range(m):
    a, b = map(int, sys.stdin.readline().split(" "))
    graph[a].append(b)
    graph[b].append(a)

visit = [False for _ in range(n)]

distance = [math.inf for _ in range(n)]

distance[x-1] = 0

q = deque()
q.append(x-1)
minIdx = 300001

while q:
    node = q.popleft()
    if visit[node] == False:
        visit[node] = True
        for i in range(len(graph[node+1])):
            q.append(graph[node+1][i]-1)
            distance[graph[node+1][i]-1] = min(distance[graph[node+1][i]-1], distance[node] + 1)
answer = []
for i in range(len(distance)):
    if distance[i] == k:
        answer.append(i+1)
print(distance)
if answer:
    for i in range(len(answer)):
        print(answer[i])
else:
    print(-1)


"""Contains the Effect class and several Effect subclass ABCs."""

from typing import TYPE_CHECKING, Callable

if TYPE_CHECKING:
    from lib.logic.Player import Player
    from lib.logic.Game import Game

# TODO: add user-facing names for statuses

status_list = [
    "poisoned",  # The player is poisoned.
    "drunk",  # The player is drunk.
    "dead",  # The player is dead.
    "not_functioning",  # The player's ability is not functioning.
    "safe",  # The player is generally protected.
    "safe_from_demon",  # The player is protected from the demon.
    "thiefed",  # Vote counts negative (caused by thief).
    "bureaucrated",  # Vote counts thrice (caused by bureaucrat).
    "used_ability",  # A one-time-use character has used their ability.
    "can_dead_vote_without_token",  # Voting while dead won't use or need a dead vote.
    "can_nominate_while_dead",  # The player can nominate while dead.
    "can_nominate_twice",  # The player can nominate twice.
    "can_vote_twice",  # The player can vote twice.
    "good",  # The player is good.
    "evil",  # The player is evil.
    "townsfolk",  # The player is a Townsfolk.
    "outsider",  # The player is an Outsider.
    "minion",  # The player is a Minon.
    "demon",  # The player is a Demon.
    "traveler",  # The player is a Traveler.
    "storyteller",  # The player is a Storyteller.
]

class Effect:
    """Stores information about a game effect.

    Parameters
    ----------
    affected_player : Player
        The player affected by the effect.
    source_player : Player
        The player who is causing the effect, or None if a storyteller.

    Attributes
    ----------
    disabled: bool
        Whether the effect is currently disabled.
    affected_player
    source_player
    """

    _name: str = "Effect"
    appears: bool = True

    def __init__(
        self, affected_player: "Player", source_player: "Player",
    ):
        self.affected_player = affected_player
        self.source_player = source_player
        self.disabled = False

    @property
    def name(self):
        """Determine the effect's name."""
        return f"{self._name} ({self.source_player.character.name})"

    def status(self, game: "Game", status_name: str) -> bool:
        """Determine whether the effect causes a status.

        Parameters
        ----------
        game : Game
            The current game.
        status_name : str
            The status to be checked.

        Returns
        -------
        bool
            Whether the effect causes the status.
        """
        if self.disabled:
            return False

        assert status_name in status_list

        try:
            return getattr(self, status_name)(game)

        except AttributeError:
            if status_name == "not_functioning":
                return (
                    self.status(game, "poisoned")
                    or self.status(game, "drunk")
                    or self.status(game, "dead")
                )

            if status_name == "safe_from_demon":
                return self.status(game, "safe")

            return False

    def registers_status(self, game: "Game", status_name: str) -> bool:
        """Determine whether the effect causes registering as a status.

        Parameters
        ----------
        game : Game
            The current game.
        status_name : str
            The status to be checked.

        Returns
        -------
        bool
            Whether the effect causes registering as the status.
        """
        if self.disabled:
            return False

        assert status_name in status_list
        return getattr(self, "registers_" + status_name, lambda x: False)(game)

    def morning_cleanup(self, game: "Game"):
        """Call at the start of each day.

        Primarily used to delete effects, when appropriate.
        """
        pass

    # noinspection PyUnusedLocal
    @staticmethod
    async def nomination(game: "Game", nominee: "Player", nominator: "Player") -> bool:
        """Call at the start of each nomination.

        Parameters
        ----------
        game : Game
            The current game.
        nominee : Player
            The nominee.
        nominator : Player
            The nominator.

        Returns
        -------
        bool
            Whether to go through with the nomination.
        """
        return True

    def evening_cleanup(self, game: "Game"):
        """Call at the end of each day.

        Primarily used to delete effects, when appropriate.
        """
        pass

    def source_drunkpoisoned_cleanup(self, game: "Game"):
        """Call when source_player stops functioning.

        Primarily used to disable effects, when appropriate.
        """
        pass

    def source_death_cleanup(self, game: "Game"):
        """Call when source_player dies.

        Primarily used to delete effects, when appropriate.
        """
        pass

    def turn_on(self, game: "Game", enabler_func: Callable[[], None]) -> "Effect":
        """Turn on the effect.

        Parameters
        ----------
        game : Game
            The current game.
        enabler_func : Callable [[], None]
            A function which enables the effect in some way.

        Notes
        -----
        The effect should be disabled in some way (either by not being a in
        affected_player.effects, or because self.disabled = True) before this method id
        called. This checks if the effect being enabled causes the player to die or stop
        functioning via checking the player's state before enabler_func is called and
        then comparing it to the state after. If it causes death or drunkpoisoning, the
        appropriate modifiers are also called.
        """
        originally_functioning = self.affected_player.functioning(game)
        originally_dead = self.affected_player.ghost(game)

        enabler_func()

        if originally_functioning and not self.affected_player.functioning(game):

            if not originally_dead and self.affected_player.ghost(game):
                effect_list = [x for x in self.affected_player.source_effects(game)]
                for effect in effect_list:
                    # can't call it on self because of recursion errors
                    if not self == effect:
                        effect.source_death_cleanup(game)

            else:
                effect_list = [x for x in self.affected_player.source_effects(game)]
                for effect in effect_list:
                    if not self == effect:
                        effect.source_drunkpoisoned_cleanup(game)

        return self

    def disable(self, game: "Game"):
        """Handle disabling of the effect."""

        def disabler_func():
            """Disable the effect."""
            self.disabled = True

        self.turn_off(game, disabler_func)

    def delete(self, game: "Game"):
        """Handle deletion of the effect."""

        def disabler_func():
            """Delete the effect."""
            try:
                self.affected_player.effects.remove(self)
            except ValueError:
                pass
            # TODO: this is only a temp fix

        self.turn_off(game, disabler_func)

    def turn_off(self, game: "Game", disabler_func: Callable[[], None]):
        """Turn off the effect.

        For more details, see the turn_on documentation.
        """
        originally_functioning = self.affected_player.functioning(game)

        disabler_func()

        if not originally_functioning and self.affected_player.functioning(game):
            effect_list = [x for x in self.affected_player.source_effects(game)]
            for effect in effect_list:
                effect.source_starts_functioning(game)

    def source_starts_functioning(self, game: "Game"):
        """Call when source_player restarts functioning.

        Modified by decorators (defined in logic.tools) to call self.turn_on.
        """
        pass

# Some generic single-status effects that can be caused by storytellers
class Drunk(Effect):
    """Makes the player drunk."""

    _name = "Drunk"

    # noinspection PyUnusedLocal
    @staticmethod
    def drunk(game: "Game") -> bool:
        """Determine whether the effect causes drunkenness."""
        return True

class Poisoned(Effect):
    """Makes the player poisoned."""

    _name = "Poisoned"

    # noinspection PyUnusedLocal
    @staticmethod
    def poisoned(game: "Game") -> bool:
        """Determine whether the effect causes poisoning."""
        return True

class Dead(Effect):
    """Makes the player dead."""

    _name = "Dead"

    # noinspection PyUnusedLocal
    @staticmethod
    def dead(game: "Game") -> bool:
        """Determine whether the effect causes death."""
        return True

class Safe(Effect):
    """Makes the player safe."""

    _name = "Safe"

    # noinspection PyUnusedLocal
    @staticmethod
    def safe(game: "Game") -> bool:
        """Determine whether the effect causes safety."""
        return True

class SafeFromDemon(Effect):
    """Makes the player safe from the demon."""

    _name = "Safe From Demon"

    # noinspection PyUnusedLocal
    @staticmethod
    def safe_from_demon(game: "Game") -> bool:
        """Determine whether the effect causes safety from the Demon."""
        return True

class UsedAbility(Effect):
    """For one-time-use characters who have used their ability."""

    _name = "Used Ability"

    # noinspection PyUnusedLocal
    @staticmethod
    def used_ability(game: "Game") -> bool:
        """Determine whether the effect causes the ability to be used."""
        return True

class NoDeadVoteNeeded(Effect):
    """For effects which allow voting without a dead vote."""

    _name = "Infinite Dead Votes"

    # noinspection PyUnusedLocal
    @staticmethod
    def can_dead_vote_without_token(game: "Game") -> bool:
        """Determine whether the effect allows dead voting without a token."""
        return True

# Alignment and character type classes for lib.logic.Character
class Good(Effect):
    """Makes the player good."""

    _name = "Good"
    appears = False

    # noinspection PyUnusedLocal
    @staticmethod
    def good(game: "Game") -> bool:
        """Determine whether the effect makes the player good."""
        return True

class Evil(Effect):
    """Makes the player evil."""

    _name = "Evil"
    appears = False

    # noinspection PyUnusedLocal
    @staticmethod
    def evil(game: "Game") -> bool:
        """Determine whether the effect makes the player evil."""
        return True

class TownsfolkEffect(Effect):
    """Makes the player a Townsfolk."""

    _name = "Townsfolk"
    appears = False

    # noinspection PyUnusedLocal
    @staticmethod
    def townsfolk(game: "Game") -> bool:
        """Determine whether the effect makes the player a townsfolk."""
        return True

class OutsiderEffect(Effect):
    """Makes the player an Outsider."""

    _name = "Outsider"
    appears = False

    # noinspection PyUnusedLocal
    @staticmethod
    def outsider(game: "Game") -> bool:
        """Determine whether the effect makes the player an outsider."""
        return True

class MinionEffect(Effect):
    """Makes the player a Minion."""

    _name = "Minion"
    appears = False

    # noinspection PyUnusedLocal
    @staticmethod
    def minion(game: "Game") -> bool:
        """Determine whether the effect makes the player a minion."""
        return True

class DemonEffect(Effect):
    """Makes the player a Demon."""

    _name = "Demon"
    appears = False

    # noinspection PyUnusedLocal
    @staticmethod
    def demon(game: "Game") -> bool:
        """Determine whether the effect makes the player a demon."""
        return True

class TravelerEffect(Effect):
    """Makes the player a Traveler."""

    _name = "Traveler"
    appears = False

    # noinspection PyUnusedLocal
    @staticmethod
    def traveler(game: "Game") -> bool:
        """Determine whether the effect makes the player a traveler."""
        return True

class StorytellerEffect(Effect):
    """Makes the player a Storyteller."""

    _name = "Storyteller"
    appears = False

    # noinspection PyUnusedLocal
    @staticmethod
    def storyteller(game: "Game") -> bool:
        """Determine whether the effect makes the player a storyteller."""
        return True

class RegistersGood(Effect):
    """Makes a character register as Good."""

    _name = "Registers as Good"

    # noinspection PyUnusedLocal
    @staticmethod
    def registers_good(game: "Game"):
        """Determine whether the effect makes the player register as good."""
        return True

class RegistersEvil(Effect):
    """Makes a character register as Good."""

    _name = "Registers as Evil"

    # noinspection PyUnusedLocal
    @staticmethod
    def registers_evil(game: "Game"):
        """Determine whether the effect makes the player register as evil."""
        return True

class RegistersTownsfolk(Effect):
    """Makes a character register as a Townsfolk."""

    _name = "Registers as a Townsfolk"

    # noinspection PyUnusedLocal
    @staticmethod
    def registers_townsfolk(game: "Game"):
        """Determine whether the effect makes the player register as a townsfolk."""
        return True

class RegistersOutsider(Effect):
    """Makes a character register as a Outsider."""

    _name = "Registers as an Outsider"

    # noinspection PyUnusedLocal
    @staticmethod
    def registers_outsider(game: "Game"):
        """Determine whether the effect makes the player register as an outsider."""
        return True

class RegistersMinion(Effect):
    """Makes a character register as a Minion."""

    _name = "Registers as a Minion"

    # noinspection PyUnusedLocal
    @staticmethod
    def registers_minion(game: "Game"):
        """Determine whether the effect makes the player register as a minion."""
        return True

class RegistersDemon(Effect):
    """Makes a character register as a Demon."""

    _name = "Registers as a Demon"

    # noinspection PyUnusedLocal
    @staticmethod
    def registers_demon(game: "Game"):
        """Determine whether the effect makes the player register as a demon."""
        return True


import sys

from asyncore import read
from checker import site_is_online
from cli import read_user_cli_args

def main():
    user_args = read_user_cli_args()
    urls = user_args.urls
    file = user_args.file

    if urls:
        _site_check(urls)
    elif file:
        _site_check(file)
    else:
        print("Você não digitou nem a URL e nem um arquivo...")
        sys.exit(1)

def _site_check(urls):
    for url in urls:
        result = site_is_online(url.rstrip('\n'))

if __name__ == "__main__":
    main()


from .Answers import Answers

class Student(Answers):
  def __init__(self, answers_obj, student_obj) -> None:
    super().__init__(answers_obj)
    super().total_answers
    super().predominant_options

    self.id: int = student_obj['id']
    self.fullname: str = student_obj['fullname']
    self.age: int = student_obj['age']
    self.grade: str = student_obj['grade']
    self.status: str = student_obj['status']
    self.genre: str = student_obj['genre']

  def __repr__(self) -> str:
    return f"""
    Id: {self.id}
    Name: {self.fullname}
    Age: {self.age}
    Grade: {self.grade}
    Status: {self.status}
    Genre: {self.genre}
    Predominant options: {self.predominant_options}
    """


from SoftRealtimeLoop import SoftRealtimeLoop
from sys import path
path.append("/home/pi/TControl")
from TControl import TMotorManager
import numpy as np
import time

logvars = [
    "output_angle",
    "output_velocity",
    "output_acceleration",
    "current",
    "output_torque",
    "motor_angle",
    "motor_velocity",
    "motor_acceleration",
    "motor_torque"
]

with TMotorManager(motor_type='AK80-9', motor_ID=3, CSV_file="log.csv",log_vars=logvars) as dev:
    dev.zero_position() # has a delay!
    time.sleep(1.5)
    dev.set_current_gains()

    loop = SoftRealtimeLoop(dt = 0.01, report=True, fade=0)
    for t in loop:
        dev.update()
        if t < 1.0:
            dev.τm = 0.0
        else:
            dev.τm = 0.1

    del loop


"""Utilities for dealing with the ADO REST API."""

import logging
from typing import Callable, Optional

import requests

from simple_ado.exceptions import ADOHTTPException

def boolstr(value: bool) -> str:
    """Return a boolean formatted as string for ADO calls

    :param value: The value to format

    :returns: A string representation of the boolean value
    """
    return str(value).lower()

def download_from_response_stream(
    *,
    response: requests.Response,
    output_path: str,
    log: logging.Logger,
    callback: Optional[Callable[[int, int], None]] = None
) -> None:
    """Downloads a file from an already open response stream.

    :param requests.Response response: The response to download from
    :param str output_path: The path to write the file out to
    :param logging.Logger log: The log to use for progress updates
    :param callback: If supplied, this will be called on every new chunk to update progress to the caller

    :raises ADOHTTPException: If we fail to fetch the file for any reason
    """

    # A sensible modern value
    chunk_size = 1024 * 16

    if response.status_code < 200 or response.status_code >= 300:
        raise ADOHTTPException("Failed to fetch file", response)

    with open(output_path, "wb") as output_file:

        content_length_string = response.headers.get("content-length", "0")

        total_size = int(content_length_string)
        total_downloaded = 0

        for data in response.iter_content(chunk_size=chunk_size):
            total_downloaded += len(data)
            output_file.write(data)

            if callback is not None:
                callback(total_downloaded, total_size)

            if total_size != 0:
                progress = int((total_downloaded * 100.0) / total_size)
                log.info(f"Download progress: {progress}%")


from __future__ import annotations
from typing import TextIO, Optional, Type, TYPE_CHECKING

import sys
import os

if TYPE_CHECKING:
    from types import TracebackType

class RedirectedStdStreams:
    """
    Temporarily redirects stdout/stderr

    Usage:
    with RedirectStdStreams(stderr=open(os.devnull, 'w')):
        # do something that spams stderr

    """
    def __init__(self, stdout: TextIO = None, stderr: TextIO = None) -> None:
        self._stdout = stdout or sys.stdout
        self._stderr = stderr or sys.stderr

    def __enter__(self) -> None:
        self.old_stdout, self.old_stderr = sys.stdout, sys.stderr
        self.old_stdout.flush()
        self.old_stderr.flush()
        sys.stdout, sys.stderr = self._stdout, self._stderr

    def __exit__(self, t: Optional[Type[BaseException]], e: Optional[BaseException], tb: TracebackType) -> None:
        self._stdout.flush()
        self._stderr.flush()
        sys.stdout = self.old_stdout
        sys.stderr = self.old_stderr

class SilencedStreams(RedirectedStdStreams):
    """
    Temporarily redirects stdout/stderr to nothing (dev/null)

    Usage:
    with SilencedStream(False, True):
        # do something that spams stderr

    """
    def __init__(self, silence_stdout: bool = True, silence_stderr: bool = True):
        self.silence_stdout = silence_stdout
        self.silence_stderr = silence_stderr
        super().__init__(
            open(os.devnull, 'w') if self.silence_stdout else sys.stdout,
            open(os.devnull, 'w') if self.silence_stderr else sys.stderr
        )

    def __exit__(self, t: Optional[Type[BaseException]], e: Optional[BaseException], tb: TracebackType) -> None:
        super().__exit__(t, e, tb)
        if self.silence_stdout:
            self._stdout.close()
        if self.silence_stderr:
            self._stderr.close()


''' Crie um programa que leia o nome e a idade de 9 pessoas e guarde esses
valores em dois vetores, em posições relacionadas. No final, mostre uma listagem
contendo apenas os dados das pessoas menores de idade.'''
nomes = []
idades = []
for pessoa in range(9):
    nomes.append(input('Nome: '))
    idades.append(int(input('Idade: ')))
print('As pessoas menores de idade são:')
for posicao in range(9):
    if idades[posicao] < 18:
         print(f'{nomes[posicao]}',end=' ')


#!/usr/bin/env python3
import serial
import select
import struct
import sys
import time
import math
##############################################################################
# Below initializes pygame for Moonlight input and defines functions for
# translating XBOX 360 commands from Moonlight to appropriate Switch Hex.
##############################################################################

ser = serial.Serial(port='COM3', baudrate=19200,timeout=1)

STATE_OUT_OF_SYNC   = 0
STATE_SYNC_START    = 1
STATE_SYNC_1        = 2
STATE_SYNC_2        = 3
STATE_SYNC_OK       = 4

# Actual Switch DPAD Values
A_DPAD_CENTER    = 0x08
A_DPAD_U         = 0x00
A_DPAD_U_R       = 0x01
A_DPAD_R         = 0x02
A_DPAD_D_R       = 0x03
A_DPAD_D         = 0x04
A_DPAD_D_L       = 0x05
A_DPAD_L         = 0x06
A_DPAD_U_L       = 0x07

# Enum DIR Values
DIR_CENTER    = 0x00
DIR_U         = 0x01
DIR_R         = 0x02
DIR_D         = 0x04
DIR_L         = 0x08
DIR_U_R       = DIR_U + DIR_R
DIR_D_R       = DIR_D + DIR_R
DIR_U_L       = DIR_U + DIR_L
DIR_D_L       = DIR_D + DIR_L

BTN_NONE         = 0x0000000000000000
BTN_Y            = 0x0000000000000001
BTN_B            = 0x0000000000000002
BTN_A            = 0x0000000000000004
BTN_X            = 0x0000000000000008
BTN_L            = 0x0000000000000010
BTN_R            = 0x0000000000000020
BTN_ZL           = 0x0000000000000040
BTN_ZR           = 0x0000000000000080
BTN_MINUS        = 0x0000000000000100
BTN_PLUS         = 0x0000000000000200
BTN_LCLICK       = 0x0000000000000400
BTN_RCLICK       = 0x0000000000000800
BTN_HOME         = 0x0000000000001000
BTN_CAPTURE      = 0x0000000000002000

DPAD_CENTER      = 0x0000000000000000
DPAD_U           = 0x0000000000010000
DPAD_R           = 0x0000000000020000
DPAD_D           = 0x0000000000040000
DPAD_L           = 0x0000000000080000
DPAD_U_R         = DPAD_U + DPAD_R
DPAD_D_R         = DPAD_D + DPAD_R
DPAD_U_L         = DPAD_U + DPAD_L
DPAD_D_L         = DPAD_D + DPAD_L

LSTICK_CENTER    = 0x0000000000000000
LSTICK_R         = 0x00000000FF000000 #   0 (000)
LSTICK_U_R       = 0x0000002DFF000000 #  45 (02D)
LSTICK_U         = 0x0000005AFF000000 #  90 (05A)
LSTICK_U_L       = 0x00000087FF000000 # 135 (087)
LSTICK_L         = 0x000000B4FF000000 # 180 (0B4)
LSTICK_D_L       = 0x000000E1FF000000 # 225 (0E1)
LSTICK_D         = 0x0000010EFF000000 # 270 (10E)
LSTICK_D_R       = 0x0000013BFF000000 # 315 (13B)

RSTICK_CENTER    = 0x0000000000000000
RSTICK_R         = 0x000FF00000000000 #   0 (000)
RSTICK_U_R       = 0x02DFF00000000000 #  45 (02D)
RSTICK_U         = 0x05AFF00000000000 #  90 (05A)
RSTICK_U_L       = 0x087FF00000000000 # 135 (087)
RSTICK_L         = 0x0B4FF00000000000 # 180 (0B4)
RSTICK_D_L       = 0x0E1FF00000000000 # 225 (0E1)
RSTICK_D         = 0x10EFF00000000000 # 270 (10E)
RSTICK_D_R       = 0x13BFF00000000000 # 315 (13B)

NO_INPUT       = BTN_NONE + DPAD_CENTER + LSTICK_CENTER + RSTICK_CENTER

# Commands to send to MCU
COMMAND_NOP        = 0x00
COMMAND_SYNC_1     = 0x33
COMMAND_SYNC_2     = 0xCC
COMMAND_SYNC_START = 0xFF

# Responses from MCU
RESP_USB_ACK       = 0x90
RESP_UPDATE_ACK    = 0x91
RESP_UPDATE_NACK   = 0x92
RESP_SYNC_START    = 0xFF
RESP_SYNC_1        = 0xCC
RESP_SYNC_OK       = 0x33

# Compute x and y based on angle and intensity
def angle(angle, intensity):
    # y is negative because on the Y input, UP = 0 and DOWN = 255
    x =  int((math.cos(math.radians(angle)) * 0x7F) * intensity / 0xFF) + 0x80
    y = -int((math.sin(math.radians(angle)) * 0x7F) * intensity / 0xFF) + 0x80
    return x, y

# Edited to determine which stick to use via input (defined in stick_move)
def stick_angle(angle, intensity, stick):
    if stick == 0:
        return (intensity + (angle << 8)) << 24
    elif stick == 1:
        return (intensity + (angle << 8)) << 44

# Precision wait
def p_wait(waitTime):
    t0 = time.perf_counter()
    t1 = t0
    while (t1 - t0 < waitTime):
        t1 = time.perf_counter()

# Wait for data to be available on the serial port
def wait_for_data(timeout = 1.0, sleepTime = 0.1):
    t0 = time.perf_counter()
    t1 = t0
    inWaiting = ser.in_waiting
    while ((t1 - t0 < sleepTime) or (inWaiting == 0)):
        time.sleep(sleepTime)
        inWaiting = ser.in_waiting
        t1 = time.perf_counter()

# Read X bytes from the serial port (returns list)
def read_bytes(size):
    bytes_in = ser.read(size)
    return list(bytes_in)

# Read 1 byte from the serial port (returns int)
def read_byte():
    bytes_in = read_bytes(1)
    if len(bytes_in) != 0:
        byte_in = bytes_in[0]
    else:
        byte_in = 0
    return byte_in

# Discard all incoming bytes and read the last (latest) (returns int)
def read_byte_latest():
    inWaiting = ser.in_waiting
    if inWaiting == 0:
        inWaiting = 1
    bytes_in = read_bytes(inWaiting)
    if len(bytes_in) != 0:
        byte_in = bytes_in[0]
    else:
        byte_in = 0
    return byte_in

# Write bytes to the serial port
def write_bytes(bytes_out):
    ser.write(bytearray(bytes_out))
    return

# Write byte to the serial port
def write_byte(byte_out):
    write_bytes([byte_out])
    return

# Compute CRC8
# https://www.microchip.com/webdoc/AVRLibcReferenceManual/group__util__crc_1gab27eaaef6d7fd096bd7d57bf3f9ba083.html
def crc8_ccitt(old_crc, new_data):
    data = old_crc ^ new_data

    for i in range(8):
        if (data & 0x80) != 0:
            data = data << 1
            data = data ^ 0x07
        else:
            data = data << 1
        data = data & 0xff
    return data

# Send a raw packet and wait for a response (CRC will be added automatically)
def send_packet(packet=[0x00,0x00,0x08,0x80,0x80,0x80,0x80,0x00], debug=False):
    if not debug:
        bytes_out = []
        bytes_out.extend(packet)

        # Compute CRC
        crc = 0
        for d in packet:
            crc = crc8_ccitt(crc, d)
        bytes_out.append(crc)
        write_bytes(bytes_out)
        # print(bytes_out)

        # Wait for USB ACK or UPDATE NACK
        byte_in = read_byte()
        commandSuccess = (byte_in == RESP_USB_ACK)
    else:
        commandSuccess = True
    return commandSuccess

# Convert DPAD value to actual DPAD value used by Switch
def decrypt_dpad(dpad):
    if dpad == DIR_U:
        dpadDecrypt = A_DPAD_U
    elif dpad == DIR_R:
        dpadDecrypt = A_DPAD_R
    elif dpad == DIR_D:
        dpadDecrypt = A_DPAD_D
    elif dpad == DIR_L:
        dpadDecrypt = A_DPAD_L
    elif dpad == DIR_U_R:
        dpadDecrypt = A_DPAD_U_R
    elif dpad == DIR_U_L:
        dpadDecrypt = A_DPAD_U_L
    elif dpad == DIR_D_R:
        dpadDecrypt = A_DPAD_D_R
    elif dpad == DIR_D_L:
        dpadDecrypt = A_DPAD_D_L
    else:
        dpadDecrypt = A_DPAD_CENTER
    return dpadDecrypt

# Convert CMD to a packet
def cmd_to_packet(command):
    cmdCopy = command
    low              =  (cmdCopy & 0xFF)  ; cmdCopy = cmdCopy >>  8
    high             =  (cmdCopy & 0xFF)  ; cmdCopy = cmdCopy >>  8
    dpad             =  (cmdCopy & 0xFF)  ; cmdCopy = cmdCopy >>  8
    lstick_intensity =  (cmdCopy & 0xFF)  ; cmdCopy = cmdCopy >>  8
    lstick_angle     =  (cmdCopy & 0xFFF) ; cmdCopy = cmdCopy >> 12
    rstick_intensity =  (cmdCopy & 0xFF)  ; cmdCopy = cmdCopy >>  8
    rstick_angle     =  (cmdCopy & 0xFFF)
    dpad = decrypt_dpad(dpad)
    left_x, left_y   = angle(lstick_angle, lstick_intensity)
    right_x, right_y = angle(rstick_angle, rstick_intensity)

    packet = [high, low, dpad, left_x, left_y, right_x, right_y, 0x00]
    # print (hex(command), packet, lstick_angle, lstick_intensity, rstick_angle, rstick_intensity)
    return packet

# Send a formatted controller command to the MCU
def send_cmd(command=NO_INPUT):
    commandSuccess = send_packet(cmd_to_packet(command))
    return commandSuccess

# Force MCU to sync
def force_sync():
    # Send 9x 0xFF's to fully flush out buffer on device
    # Device will send back 0xFF (RESP_SYNC_START) when it is ready to sync
    write_bytes([0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF])

    # Wait for serial data and read the last byte sent
    wait_for_data()
    byte_in = read_byte_latest()

    # Begin sync...
    inSync = False
    if byte_in == RESP_SYNC_START:
        write_byte(COMMAND_SYNC_1)
        byte_in = read_byte()
        if byte_in == RESP_SYNC_1:
            write_byte(COMMAND_SYNC_2)
            byte_in = read_byte()
            if byte_in == RESP_SYNC_OK:
                inSync = True
    return inSync

# Start MCU syncing process
def sync():
    inSync = False

    # Try sending a packet
    inSync = send_packet()
    if not inSync:
        # Not in sync: force resync and send a packet
        inSync = force_sync()
        if inSync:
            inSync = send_packet()
    return inSync

##############################################################################
# Needs to run to ensure connectivity upon disconnect of physical hardware
##############################################################################
def serial_connect():
    if not sync():
        print('Could not sync!')


from heapq import *
import sys
input = sys.stdin.readline

n, m = map(int, input().split())
edge = []
parent = [i for i in range(n+1)]
rank = [0 for _ in range(n+1)]

for _ in range(m):
    a, b, c = map(int, input().split())
    edge.append((c, a, b))
edge.sort()

def find(node):
    if parent[node] == node:
        return node
    parent[node] = find(parent[node])
    return parent[node]

def union(node1, node2):
    root1, root2 = find(node1), find(node2)
    if root1 == root2:
        return False
    if rank[root1] > rank[root2]:
        parent[root2] = root1
    else:
        parent[root1] = root2
        if rank[root1] == rank[root2]:
            rank[root2] += 1
    return True

def kruskal(egde):
    r = 0
    max_edge = 0
    for c, a, b in edge:

        if union(a, b):
            r += c
            max_edge = max(max_edge, c)
    return max_edge, r

max_edge, r = kruskal(edge)
print(r-max_edge)


import collections

class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        size_search = len(s1)
        f_search = collections.Counter(s1)
        size_string = len(s2)

        for i in range(size_string-size_search+1):
            f_group = collections.Counter(s2[i:i+size_search])
            search_keys = list(f_search)
            group_keys = list(f_group)
            search_keys.sort()
            group_keys.sort()
            if search_keys == group_keys:
                match = all(f_search[key] == f_group[key] for key in f_search)
                if match:
                    return True
        return False

print(Solution().checkInclusion("adc","dcda"))