import datetime

from django.db import models
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.views.decorators.cache import cache_page

from bios.models import Bio
from competitions.models import Competition
from games.models import Game, GameSource
from goals.models import Goal
from standings.models import Standing
from stats.models import Stat, CareerStat
from teams.models import Team

from collections import defaultdict, Counter
import json

def homepage(request):

    try:
        mls = Competition.objects.get(slug='major-league-soccer')
    except:
        mls = None

    context = {
        'mls': mls,
        }

    return render_to_response("homepage.html",
                              context,
                              context_instance=RequestContext(request))

@cache_page(60 * 60 * 12)
def homepage_old(request):
    """
    The site homepage. Currently badly underperfoming.
    """

    # Homepage fixes.
    # Shrink the size of the On This Day Box, move lower.
    # Add Standings.
    # Add tab for games from different competitions.
    # Add News
    # Add detailed links to different parts of the website.

    # What are the cool things you can get on the site?
    # Player +/-
    # Manager details
    # Career stats
    # Stats across competitions
    # Breadcrumbs?

    today = datetime.date.today()

    game_leaders = CareerStat.objects.exclude(games_played=None).order_by('-games_played')[:10]
    goal_leaders = CareerStat.objects.exclude(goals=None).order_by('-goals')[:10]

    recent_games = Game.objects.exclude(date=None).filter(date__lt=today).exclude(team1_result='').order_by('-date')[:10]

    goals = Goal.objects.count()

    try:
        mls_game = Game.objects.filter(competition__slug='major-league-soccer').order_by('date')[0]
    except:
        mls_game = None

    try:
        oc_game = Game.objects.get(competition__slug='us-open-cup', season__name='1924', round='f')
    except:
        oc_game = None

    context = {
        'today': today,
        'born': Bio.objects.born_on(today.month, today.day),
        'games': recent_games,
        'standings': Standing.objects.filter(season__competition__slug='major-league-soccer').count(),
        'game_leaders': game_leaders,
        'goal_leaders': goal_leaders,
        'game_count': Game.objects.count(),
        'bio_count': Bio.objects.count(),
        'team_count': Team.objects.count(),
        'competition_count': Competition.objects.count(),

        'mls_game': mls_game,
        'oc_game': oc_game,

        }
    return render_to_response("homepage.html",
                              context,
                              context_instance=RequestContext(request))

def bad_games(request):

    context = {
        'duplicate_games': Game.objects.duplicate_games(),
        }

    return render_to_response("games/bad.html",
                              context,
                              context_instance=RequestContext(request)
                              )

def games_index(request):
    # Add a paginator.
    # This is probably unnecesary.
    # Consider turning into a games analysis page.
    # Home/Away advantage, graphs, etc.

    games = Game.objects.order_by("-date").exclude(date=None)
    game_count = games.count()

    by_year = Counter([e.year for e in games.values_list('date', flat=True)])

    #gd = defaultdict(int)
    #ceiling = 8
    #for game in games.exclude(home_team=None).exclude(team1_score=None).exclude(team2_score=None):
    #    gd[(min(game.home_score(), ceiling), min(game.away_score(), ceiling))] += 1

    context = {
        'games': games,
        'game_count': game_count,
        'games_by_year': json.dumps(sorted(by_year.items())),
        'goal_distribution': json.dumps(gd),
        }

    return render_to_response("games/index.html",
                              context,
                              context_instance=RequestContext(request))

    """
    attendance_game_count = 0
    total_attendance = 0

    month_dict = defaultdict(int)
    team_dict = defaultdict(int)
    result_dict = defaultdict(int)

    game_year_dict = defaultdict(int)
    attendance_year_dict = defaultdict(int)

    # Pull this out.
    for date, t1, t2, t1s, t2s, stadium, city, attendance in games.values_list('date', 'team1', 'team2', 'team1_score', 'team2_score', 'stadium', 'city', 'attendance'):
        total_attendance += attendance or 0
        attendance_year_dict[date.year] += attendance or 0
        if attendance is not None:
            attendance_game_count += 1

        game_year_dict[date.year] += 1

        month_dict[date.month] += 1
        team_dict[t1] += 1
        team_dict[t2] += 1
        result = tuple(sorted([t1s, t2s]))
        result_dict[result] += 1
        """

    """{
        'total_attendance': total_attendance,
        'average_attendance': total_attendance / float(attendance_game_count),
        'teams': sorted(team_dict.items(), key=lambda t: -t[1]),
        'results': sorted(result_dict.items(), key=lambda t: t[0]),
        'months': sorted(month_dict.items(), key=lambda t: t[0]),
        'game_years': sorted(game_year_dict.items(), key=lambda t: t[0]),
        'attendance_years': sorted(attendance_year_dict.items(), key=lambda t: t[0]),
        'top_attendance_games': Game.objects.order_by('-attendance')[:20],
        }"""

def game_detail(request, game_id):
    game = get_object_or_404(Game, id=game_id)
    context = {
        'game': game,
        'goals': game.goal_set.order_by('minute'),
        'game_sources': GameSource.objects.filter(game=game),

        }
    return render_to_response("games/detail.html",
                              context,
                              context_instance=RequestContext(request))

def random_game_detail(request):
    import random
    games = Game.objects.count()
    game_id = random.randint(1, games)
    return game_detail(request, game_id)


import requests
from bs4 import BeautifulSoup

products_to_track = [

    {
        "URL":"https://www.nike.com/in/t/air-jordan-1-mid-se-shoes-CQ6f9G/DV1308-104",
        "Price":"12295.00",
        "Target_price":13000.00
    },
    {
        "URL":"https://www.nike.com/in/t/air-jordan-1-mid-shoes-SQf7DM/DQ8426-014",
        "Price":"11495.00",
        "Target_price":10000.00
    },
    {
        "URL":"https://www.nike.com/in/t/air-force-1-07-shoes-WrLlWX/CW2288-111",
        "Price":"7495.00",
        "Target_price":7000.00
    },
    {
        "URL":"https://www.nike.com/in/t/court-vision-low-next-nature-shoes-N2fFHb/DH2987-100",
        "Price":"4995.00",
        "Target_price":4500.00
    },
    {
        "URL":"https://www.nike.com/in/t/nikecourt-royale-2-next-nature-shoes-RRcr20/DH3160-001",
        "Price":"3995.00",
        "Target_price":4000.00
    }
]

def give_product_name(URL):
    headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36"
    }
    page = requests.get(URL, headers=headers)
    soup = BeautifulSoup(page.content, 'html.parser')
    product_name = soup.find(id="pdp_product_title")
    return product_name.getText()

result_file = open('my_result_file.txt','w')

try:
    for every_product in products_to_track:
        Product_name = give_product_name(every_product.get("URL"))
        print(Product_name + "  -  " + every_product.get("Price"))

        if float(every_product.get("Price"))<=every_product.get("Target_price"):
            print("Less than target price")
            result_file.write(Product_name+' - '+'Less than target price.\n'+'Previous price-'+ every_product.get("Price")+'\n')
        else:
            print("Still at current price")

finally:
    result_file.close()


from datetime import datetime

from bson import ObjectId

import ext_requests.mongodb_client as db

def mongo_upsert_cluster(cluster_ip, message):
    db.app.logger.info("MONGODB - upserting cluster...")
    clusters = db.mongo_clusters.db.clusters
    cluster_info = message['cluster_info']
    cluster_name = message['cluster_name']
    cluster_location = message['cluster_location']
    cluster_port = message['manager_port']
    result_obj = clusters.update_one({'cluster_name': cluster_name},
                                     {'$set': {'ip': cluster_ip, 'clusterinfo': cluster_info, 'port': cluster_port,
                                               'cluster_location': cluster_location}},
                                     upsert=True)

    cluster_obj = clusters.find_one({'cluster_name': cluster_name})

    db.app.logger.info("MONGODB - cluster_id: {0}".format(cluster_obj['_id']))
    return cluster_obj['_id']

def mongo_find_cluster_by_id(cluster_id):
    return db.mongo_clusters.db.clusters.find_one(ObjectId(cluster_id))

def mongo_find_cluster_by_ip(cluster_ip):
    return db.mongo_clusters.db.clusters.find_one({'ip': cluster_ip})

def mongo_get_all_clusters():
    return db.mongo_clusters.db.clusters.find()

def mongo_find_one_cluster():
    """Finds first cluster occurrence"""
    return db.mongo_clusters.db.clusters.find_one()

def mongo_find_all_active_clusters():
    db.app.logger.info('Finding the active cluster orchestrators...')
    now_timestamp = datetime.now().timestamp()
    return db.mongo_clusters.db.clusters.find(
        {'last_modified_timestamp': {'$gt': now_timestamp - db.CLUSTERS_FRESHNESS_INTERVAL}})

def mongo_find_cluster_by_id_and_incr_node(c_id):
    return db.mongo_clusters.db.clusters.update_one({'_id': c_id}, {'$inc': {'nodes': 1}}, upsert=True)

def mongo_find_cluster_by_id_and_set_number_of_nodes(c_id, number_of_nodes):
    return db.mongo_clusters.db.clusters.update_one({'_id': c_id}, {'$inc': {'nodes': number_of_nodes}}, upsert=True)

def mongo_find_cluster_by_id_and_decr_node(c_id):
    return db.mongo_clusters.db.clusters.update_one({'_id': c_id}, {'$inc': {'nodes': -1}}, upsert=True)

def mongo_find_cluster_by_location(location):
    try:
        return db.mongo_clusters.db.clusters.find_one({'cluster_location': location})
    except Exception as e:
        return "Error"

def mongo_update_cluster_information(cluster_id, data):
    """Save aggregated Cluster Information"""

    datetime_now = datetime.now()
    datetime_now_timestamp = datetime.timestamp(datetime_now)

    cpu_percent = data.get('cpu_percent')
    cpu_cores = data.get('cpu_cores')
    memory_percent = data.get('memory_percent')
    memory_in_mb = data.get('cumulative_memory_in_mb')
    nodes = data.get('number_of_nodes')
    gpu_cores = data.get('gpu_cores')
    gpu_percent = data.get('gpu_percent')
    # technology = data.get('technology')
    virtualization = data.get('virtualization')
    more = data.get('more')
    worker_groups = data.get('worker_groups')
    cpu_update = {'value': cpu_percent, 'timestamp': datetime_now_timestamp}
    memory_update = {'value': memory_percent, 'timestamp': datetime_now_timestamp}

    db.mongo_clusters.db.clusters.find_one_and_update(
        {'_id': ObjectId(cluster_id)},
        {
            '$push': {
                "cpu_history": {'$each': [cpu_update], '$slice': -100},
                "memory_history": {'$each': [memory_update], '$slice': -100}
            },
            '$set': {'aggregated_cpu_percent': cpu_percent, 'total_cpu_cores': cpu_cores,
                  'total_gpu_cores': gpu_cores, 'total_gpu_percent': gpu_percent,
                  'aggregated_memory_percent': memory_percent, 'memory_in_mb': memory_in_mb,
                  'active_nodes': nodes, 'virtualization': virtualization, 'more': more,
                  'last_modified': datetime_now, 'last_modified_timestamp': datetime_now_timestamp,
                  'worker_groups': worker_groups}},
        upsert=True)


# encoding=utf-8
__author__ = 'YiTao'

import os
import sys
import logging
from datetime import *

class LogHelper:
    def __init__(self):
        self.log = self.getlog()

    def info(self, message):
        self.log.info(message)

    def error(self, message):
        self.log.error(message)

    def getlog(self):
        logger = logging.getLogger("LogHelper")
        formatter = logging.Formatter('%(name)-12s %(asctime)s %(levelname)-8s %(message)s', '%a, %d %b %Y %H:%M:%S', )
        logpath = self.getcurrpath() + "/log"
        if not os.path.exists(logpath):
            os.mkdir(logpath)
        file_handler = logging.FileHandler(logpath + "/%s.log" % date.today())
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)
        logger.setLevel(logging.DEBUG)
        return logger

    def getcurrpath(self):
        #获取脚本路径
        path = sys.path[0]
        ##判断为脚本文件还是py2exe编译后的文件，如果是脚本文件，则返回的是脚本的目录，如果是py2exe编译后的文件，则返回的是编译后的文件路径
        if os.path.isdir(path):
            return path
        elif os.path.isfile(path):
            return os.path.dirname(path)


import sys
sys.path.append('/Users/me/_Nutbox/UniversalMolecularSystem')

# The main function of this module, TopologyMatching, seeks to solve the problem of matching atoms between two
# identical molecules with different atom ordering.
from UniversalMolecularSystem import *
from collections import deque

class SolvingStatus:
    nAtoms: []   # number of atoms in each molecule, an array of length 2
    visited_order: [[]]   # 2 lists recording visited atoms and their order in each mole
                    # for example, visited = [ [0,3],[1,2] ] means that atoms 0,3 and 1,2 are visited in each molecule
                    # Here the word 'visited' also means that the atoms in two molecules are matched with each other
                    # In the above example, it means 0-3, 1-2 matching in these two molecules.
    to_visit: [deque] # 2 deques recording the to-be visited atoms in both atoms. Used for the BFS in each mole
    visited_or_in_queue: [[]]  # 2*NAtoms bool matrix indicating whether each atom is found ( either visited or in queue)

    def __init__(self,nAtoms1, nAtoms2=None):
        self.nAtoms = [nAtoms1, nAtoms2] if nAtoms2!=None else [nAtoms1,nAtoms1]
        self.visited_order = [[],[]]
        self.visited_or_in_queue = [None,None]
        for i in range(2):
            self.visited_or_in_queue[i] = [False for _ in range(self.nAtoms[i])]
        self.to_visit = [deque(),deque()]

    def Copy(self):
        ns = SolvingStatus(self.nAtoms[0],self.nAtoms[1])
        import copy
        ns.visited_order = copy.deepcopy(self.visited_order)
        ns.to_visit = [self.to_visit[_].copy() for _ in range(2)]
        ns.visited_or_in_queue = copy.deepcopy(self.visited_or_in_queue)
        return ns

    def Show(self):
        import sys
        sys.stdout.write("Matching Order: ")
        for i in range(len(self.visited_order[0])):
            sys.stdout.write("{}-{} ".format(self.visited_order[0][i],self.visited_order[1][i]))
        print("")
        sys.stdout.write("Deque of each molecule: (A) ")
        for i in range(len(self.to_visit[0])):
            sys.stdout.write("{} ".format(self.to_visit[0][i]))
        sys.stdout.write("(B) ")
        for i in range(len(self.to_visit[1])):
            sys.stdout.write("{} ".format(self.to_visit[1][i]))
        print("")

global_iter_counter = 0

def __Recursive__(mols,bondedMaps,status,level=0,__exit_on_first_match__ = True, __debugging__ = False):

    total_results = []

    if __debugging__:
        print("Level = {}".format(level))
        status.Show()
        global global_iter_counter
        global_iter_counter += 1
        print("Global Iter = {}".format(global_iter_counter))

    # Do a DFS on both molecules. In cases there are multiple choices, perform and branch-and-cut algorithm
    while len(status.to_visit[0]) > 0:  # Until the queue is empty
        candidates = [[], []]
        head = [None, None]
        for iMol in range(2):
            # Get the first node from the queue. popleft() is BFS by using a queue, while pop() is DFS by using a stack,
            # Testing shows DFS is faster
#            head[iMol] = status.to_visit[iMol].popleft()
            head[iMol] = status.to_visit[iMol].pop()

            status.visited_order[iMol].append(head[iMol])  # visit the node
            for next_node in bondedMaps[iMol][head[iMol]]:  # among its neighbors, add those un-visited and un-queued node to the queue
                if status.visited_or_in_queue[iMol][next_node] == False:
                    candidates[iMol].append(next_node)
                    status.visited_or_in_queue[iMol][next_node] = True  # Just flag those atoms, don't really add them into the queue,yet.

        if __debugging__:
            for iMol in range(2):
                print("Head For Mol{}: {}, Candidates = {}".format(iMol,head[iMol],candidates[iMol]))

        # Based on the visited node and the number of candidates, we should either branch, or cut:
        if mols[0].atoms[head[0]].element != mols[1].atoms[head[1]].element:
            # Cut because element type mismatch
            return []
        elif status.nAtoms[0] == status.nAtoms[1] and len(candidates[0]) != len(candidates[1]):
            # Cut because bonded atoms count mismatch in equivalent molecules
            return []
        elif status.nAtoms[0] < status.nAtoms[1] and len(candidates[0]) > len(candidates[1]):
            # Cut because bonded atoms count mismatch in fragmental match
            return []
        elif len(candidates[0]) == 0:
            # If there is no bonded atoms in mol1, the visit is finished
            pass
        # elif len(candidates[0]) == 1:
        #     for iMol in region(2):
        #         status.to_visit[iMol].append(candidates[iMol][0])
        else:
            # Branch!  Do a full permutation of mol[1]'s candidates
            # Keep in mind that since A may be a fragment of B, the candidates of A and B may be of different length
            import itertools
            candidates_permutated = list(itertools.permutations(candidates[1]))
            # For each possible permutation, there is a branch:
            candidates_of_mol0 = candidates[0]
            for candidates_of_mol1 in candidates_permutated:
                newStatus = status.Copy()
                pre_test_flag = True
                for iPerm in range(min(len(candidates_of_mol0),len(candidates_of_mol1))):

                    a0 = candidates_of_mol0[iPerm]
                    a1 = candidates_of_mol1[iPerm]

                    # Some simple tests to exclude impossible matches
                    if mols[0].atoms[a0].element != mols[1].atoms[a1].element:
                        pre_test_flag = False
                        break

                    # if two mols have identical # of atoms, we require the # of bonds to be equal
                    if status.nAtoms[0] == status.nAtoms[1] and len(bondedMaps[0][a0]) != len(bondedMaps[1][a1]):
                        pre_test_flag = False
                        break
                    # if mol1 is a possibly a fragment of mol2, we require differently
                    if status.nAtoms[0] < status.nAtoms[1] and len(bondedMaps[0][a0]) > len(bondedMaps[1][a1]):
                        pre_test_flag = False
                        break

                    newStatus.to_visit[0].append(a0)
                    newStatus.to_visit[1].append(a1)

                if not pre_test_flag:
                    continue

                results = __Recursive__(mols,bondedMaps,newStatus,level=level+1,\
                                        __exit_on_first_match__ = __exit_on_first_match__,__debugging__ = __debugging__)
                if len(results) > 0:
                    total_results.extend(results)
                    if __exit_on_first_match__:
                        break

            return total_results   # The return point for recursive levels other than the last

    # After the while, all matched. End of recursion
    return [status]

def TopologyMatching(mols:[Molecule], first_node):
    # mols[0] and mols[1] are two molecules. They should be identical but the order of atoms may be totally different in these
    # two molecules. This algorithm works by identifying bondings between atoms, so bonds must be properly set in both
    # molecules
    # Modified Feb 2021: mols[0] can be a fragment of mols[1]. This function works for this senario
    # without any modification.

    # If successful, returns a list of lists, each of which represents a matching.
    # For example, the return value of [  [1,3,2,0], [1,2,0,3] ] means that atoms 0,1,2,3 in the first molecule
    # can be either be matched to atoms 1,3,2,0 or atoms 1,2,0,3 in the second molecule.
    # All indexes for atoms in this module starts from 0! Atom's serials are not used here!
    # There may be multiple ways (or no way) to match atoms in the first molecule to those in the second molecule,
    # therefore the length of the list is not known beforehand. An empty list [] as the return value means that it is
    # impossible to find a match.

    # The 'first_node' parameter is a hint given by the caller, suggesting which two atoms in these two molecules are
    # equivalent. The subsequent search shall begin on these two atoms. If not given, the program will try all combinations
    # and the function may run NAtoms times longer.. To mandate the user to give an initial hint, this function will
    # refuse to work without it! If really necessary, the caller can write a loop to try all intial matching point.

    if len(mols[0].atoms) > len(mols[1].atoms):
        error("In TopologyMatching(), either the two molecules are identical, or mols[0] is a fragment of mols[1]")
        return []

    initial_status = SolvingStatus(len(mols[0].atoms),len(mols[1].atoms))

    bondedMaps = [ mols[_].BondedMap() for _ in range(2) ]

    if first_node == None:
        error("The caller must give a 'first_node' parameter such as [0,3] to suggest that\n"
        "atom index 0 in mol1 is matched to atom index 3 in mol2")

    for iMol in range(2):
        initial_status.to_visit[iMol].append(first_node[iMol])          # Put first node in queue
        initial_status.visited_or_in_queue[iMol][first_node[iMol]] = True     # Set the proper flag

    results = __Recursive__(mols,bondedMaps,initial_status,level=0,__exit_on_first_match__ = True,__debugging__= False)

    if len(results) == 0:
        return None

    result = results[0]
    matching_map = [-1 for _ in range(result.nAtoms[0])]
    for iAtom in range(result.nAtoms[0]):
        matching_map[result.visited_order[0][iAtom]] = result.visited_order[1][iAtom]

    def __verify__(bondedMaps,matching_map):
        passed = True
        for iAtomInMol0 in range(len(matching_map)):
            iAtomInMol1 = matching_map[iAtomInMol0]
            for iBondedToInMol0 in bondedMaps[0][iAtomInMol0]:
                iBondedToInMol1 = matching_map[iBondedToInMol0]
                # verify that iBondedToInMol1 is in bondedMaps[1][iAtomInMol1]
                if iBondedToInMol1 not in bondedMaps[1][iAtomInMol1]:
                    print("Verify Failed: atom {} in (A) is matched to atom {} in (B), which should be bonded to "
                          "atom {} in (A). According to matching, this is {} in (B), but this is not.".format(iAtomInMol0,iAtomInMol1,iBondedToInMol0,iBondedToInMol1))
                    passed = False
            if not passed:
                break
        return passed

    if not __verify__(bondedMaps,matching_map):
        error("Internal error in TopologyMatching(): Verification Not Passed !",False)

    # for i in region(result.nAtoms[0]):
    #     print("{},{}".format(i,matching_map[i]))

    return matching_map

def TestCase(mol):
    # This is a testing case by randomly permutating atoms within a molecule, and match them
    # with the original molecule
    from UniversalMolecularSystem import MolecularSystem
    from BondDetection import DefaultBondRules
    from random import shuffle

    originalSystem = MolecularSystem()
    originalSystem.molecules = [mol]
    originalSystem.AutoDetectBonds(DefaultBondRules(),flushCurrentBonds = True)

    permSystem = originalSystem.Copy()
    shuffle(permSystem.molecules[0].atoms)  # Shuffle all but the first atom
    permSystem.RenumberAtomSerials()
    permSystem.AutoDetectBonds(DefaultBondRules(),flushCurrentBonds = True)

    originalSystem.Summary()
    permSystem.Summary()

    for i in range(len(originalSystem.molecules[0].atoms)):
        result = TopologyMatching([originalSystem.molecules[0],permSystem.molecules[0]],[0,i])
        if result != None:
            print(i)
            print(result)
        else:
            print("{}: No Match".format(i))

if __name__ == '__main__':

    TestCase()


letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
           'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
           'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

# ignore_chars = ['0', '1', '2', '3', '4', '5', '6', '7',
#                 '8', '9', '!', '#', '$', '%', '&', '(', ')', '*', '+']

def encrypt(text, shift_value):
    encrypted = []

    shift_value = shift_value % 26

    for letter in text:
        if letter not in letters:
            encrypted.append(letter)
        else:
            index = letters.index(letter)
            encrypted.append(letters[index + shift_value])

    return "".join(encrypted)

def decrypt(str, shift_value):
    decrypted = []

    shift_value = shift_value % 26

    for letter in str:

        if letter not in letters:
            decrypted.append(letter)
        else:
            index = letters.index(letter)
            decrypted.append(letters[index - shift_value])

    return "".join(decrypted)

def run():
    mode = input(
        "Do you want to encrypt or decrypt ? write 'encrypt' or 'decrypt' ")

    if mode == "encrypt" or mode == "decrypt":

        text = input(f"Enter message to {mode} >>> ").lower()
        shift = int(input("Shift amount, [in number] >>> "))

        if mode == "encrypt":
            return encrypt(text, shift)
        else:
            return decrypt(text, shift)
    else:
        return "Invalid Input"

print(run())


import numpy as np
import scipy.sparse as sps
try:
    from petsc4py import PETSc
except ImportError:
    print("No PETSc. Bicstab solver wont work")

try:
    import pyamg
except ImportError:
    print("No pyamg. amg solver wont work")

try:
    import pypardiso
except ImportError:
    print("No pypardis. pardiso solver won't work")

def amg(A, b, tol=1e-10):
    """Solve with AMG."""
    B = None  # no near-null spaces guesses for SA

    # use AMG based on Smoothed Aggregation (SA) and display info
    mls = pyamg.smoothed_aggregation_solver(A, B=B)
    print(mls)
    # # Solve Ax=b with no acceleration ('standalone' solver)
    # standalone_residuals = []
    # x = mls.solve(b, tol=1e-10, accel=None, residuals=standalone_residuals)

    # Solve Ax=b with Conjugate Gradient (AMG as a preconditioner to CG)
    residuals = []
    x = mls.solve(b, tol=tol, accel="cg", residuals=residuals)
    if residuals[-1] > 100 * tol:
        Warning("Iterative solver failed. Falling back to direct solver")
        return umfpack(A, b)
    print("Solved linear system with AMG. Residual is: {}".format(residuals[-1]))
    return x

def pardiso(A, b):
    "Solve with pardiso"
    return pypardiso.spsolve(A, b)

def gmres(A, b, x0, tol=1e-10):
    "Solve with gmres"
    M_iLU = sps.linalg.spilu(A, fill_factor=20, drop_tol=1e-5)
    M = sps.linalg.LinearOperator(A.shape, M_iLU.solve)

    def callback(res):
        print("Gmres residual: {}".format(res))

    x, info = sps.linalg.gmres(
        A, b, x0=x0, M=M, tol=tol, maxiter=200, callback=callback
    )
    if info != 0:
        Warning("Iterative solver failed. Falling back to direct solver")
        return umfpack(A, b)
    return x

def bicstab(A, b, tol=1e-10, gb=None):
    "Solve with bicstab"
    if gb is None:
        P = sps.identity(A.shape[0])
    else:
        nc = gb.num_cells()
        p_idx = np.arange(0, nc, 1)
        c_idx = np.arange(nc, 2 * nc, 1)
        col = np.ravel(np.vstack((p_idx, c_idx)), order='F')
        row = np.arange(0, 2 * nc)
        data = np.ones(2 * nc, dtype=int)
        P = sps.coo_matrix((data, (row, col)))

#    Ao = A.copy()
    A = P * A * P.T
    if A.format != "csr":
        A = A.tocsr()

    M = PETSc.Mat().createAIJ(size=A.shape,
                          csr=(A.indptr, A.indices,
                               A.data))
    x, rhs = M.getVecs()
    ksp = PETSc.KSP()
    ksp.create(PETSc.COMM_WORLD)
    ksp.setType('bcgs')
    ksp.getPC().setType('ilu')
    rhs.setArray(P * b)
    ksp.setOperators(M)
    ksp.setTolerances(1e-4, tol)
    ksp.solve(rhs, x)

#    print("linear it: ", ksp.getIterationNumber())
#    print("converged reason: ", ksp.getConvergedReason())
    return P.T * x.getArray()

def umfpack(A, b):
    "Solve with umfpack"
    if A.nnz > 500000:
        A.indices = A.indices.astype(np.int64)
        A.indptr = A.indptr.astype(np.int64)
    return sps.linalg.spsolve(A, b, use_umfpack=True)

def superlu(A, b):
    "Solve with superlu"
    return sps.linalg.spsolve(A, b)


#Tyler Robbins
#4/1/14
#Main 2
#Main file, runs the neccessary files from def_func

from def_func import *

if __name__ == '__main__':
	InternetCheck(CLI)
	Start(True)

nuclear = u'\u2622'


import urllib.request

url = "https://n.news.naver.com/article/421/0006200438?cds=news_media_pc&type=editn"
res = urllib.request.urlopen(url)

data = res.read()

text = data.decode("utf-8")

print(text)


from django.contrib.auth.views import LoginView
from django.urls import path

from cinema.views import (
    IndexView,
    MovieDetailView,
    SessionDetailView,
    CreateUserView,
    TicketListView,
    LogoutView,
)

urlpatterns = [
    path("", IndexView.as_view(), name="index"),
    path("accounts/login/", LoginView.as_view(), name="login"),
    path("accounts/logout/", LogoutView.as_view(), name="logout"),
    path("accounts/register/", CreateUserView.as_view(), name="register"),
    path("movie/<int:pk>/", MovieDetailView.as_view(), name="movie-detail"),
    path(
        "movie/session/<int:pk>/",
        SessionDetailView.as_view(),
        name="movie-session-detail",
    ),
    path("orders/", TicketListView.as_view(), name="ticket-listview"),
]

app_name = "cinema"


import json
#  результат матча
file_name1 = "processed_data (1).json"
#  исходники для матчера
file_name2 = "input_data.json"
with open(file_name1, 'r+', encoding='utf-8') as file1:
    with open(file_name2, 'r', encoding='utf-8') as file2:
        print(type(file1))
        file1 = json.load(file1)
        file2 = json.load(file2)
        for i in ["mismatched_pairs"]:

            for mismatch_pair in file1[i]:
                event_id1 = mismatch_pair["event1"]["event_id"]
                event_id2 = mismatch_pair["event2"]["event_id"]
                sport = mismatch_pair["sport"]
                date_event = mismatch_pair["date"]
                flag_event1 = 0
                flag_event2 = 0
                for date_events in file2:
                    if flag_event1 and flag_event2:
                        break
                    if date_event != date_events["date"]:
                        continue
                    for event_serch in date_events["data"]:
                        if event_serch["sport"] != sport:
                            continue
                        if event_id1 == event_serch["event1"]["event_id"]:
                            flag_event1 = 1
                            mismatch_pair["event1"]["true_pair"] = event_serch["event2"]
                        if event_id2 == event_serch["event2"]["event_id"]:
                            flag_event2 = 1
                            mismatch_pair["event2"]["true_pair"] = event_serch["event1"]

        with open('new_result.json', 'w') as fp:
            json.dump(file1, fp)
# unmatched_results, mismatched_pairs


import asyncio
from concurrent.futures import TimeoutError
import json
import logging
from typing import Optional

import aiohttp
from aiohttp import web
from multidict import CIMultiDictProxy

logger = logging.getLogger(__name__)

DEFAULT_REMOVED_RESPONSE_HEADERS = {"Content-Length", "Content-Encoding", "Transfer-Encoding"}

def clean_response_headers(request: web.Request) -> CIMultiDictProxy:
    """Removes HTTP headers from an upstream response and add auth header if present.

    :param request: A web.Request containing the request whose headers are to be cleaned.
    :return: A CIMultiDictProxy containing the clean headers.
    """
    clean_headers = request.headers.copy()
    for header in DEFAULT_REMOVED_RESPONSE_HEADERS:
        clean_headers.popall(header, None)
    try:
        auth_header = request.pop("auth_payload")
    except KeyError:
        pass
    else:
        clean_headers.add(*auth_header)
    return CIMultiDictProxy(clean_headers)

async def _instance_document() -> Optional[str]:
    """This is a wrapper around |aiohttp.request|_ to make it usable in a synchronous way.

    As only one request is done per proxy, there normally is no need to use a session.
    There is however a bug (`#3628`_) in ``aiohttp`` that leaks the session when an exception is raised.
    The manual session handling for only one request is a workaround while waiting for `PR #3640`_ to be merged.

    :return: The region name as a string

    .. |aiohttp.request| replace:: ``aiohttp.request``
    .. _aiohttp.request: https://docs.aiohttp.org/en/latest/client_reference.html#aiohttp.request
    .. _#3628: https://github.com/aio-libs/aiohttp/issues/3628
    .. _PR #3640: https://github.com/aio-libs/aiohttp/pull/3640
    """
    async with aiohttp.ClientSession(raise_for_status=True, timeout=aiohttp.ClientTimeout(total=1)) as session:
        try:
            async with session.get("http://169.254.169.254/latest/dynamic/instance-identity/document") as response:
                document = await response.text()
        except TimeoutError:
            logger.debug("Timeout while attempting to get instance document.")
        else:
            return json.loads(document)["region"]

def _aws_region() -> Optional[str]:
    """Attempts to query the AWS region where this instance is running.

    Returns None if endpoint is not available, which means we're probably not running on AWS.

    `Related Amazon docs <https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-identity-documents.html>`_
    """

    try:
        event_loop = asyncio.get_event_loop()
    except RuntimeError:
        event_loop = asyncio.new_event_loop()
        asyncio.set_event_loop(event_loop)

    return event_loop.run_until_complete(_instance_document())


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 18 11:12:00 2020

@author: yisupeng
"""

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar  1 22:10:26 2020

@author: yisupeng
"""

import os
import tarfile

import csv
import numpy as np
import matplotlib.pyplot as plt

import json

#%%

#species = 'c_elegans'
#species = 'drosophila'
#species = 'e_coli'
#species = 'human'
#species = 'mouse'
#species = 'yeast'

species_list = [
        'c_elegans',
        'drosophila',
        'e_coli',
        'human',
        'mouse',
        'yeast',
    ]

#%%

data_dir = 'test_search/nist/'

res_dir = 'test_search/est_results_nist/'

#%%
def split_comments(comment):
    ret = ''
    quote = False
    for c in comment:
        if c == ' ' and not quote:
            yield ret
            ret = ''
        elif c == '"':
            quote = not quote
        else:
            ret += c

#%%

def parse_msp(msplist):
    peaks = []
    item = {}
    for l in msplist:
        if not l:
            item['Peaks'] = peaks

            props = {k:v for k,v in map(lambda x: x.split('=', 1), split_comments(item['Comment']))}
            item['Props'] = props
#            print(len(peaks))
            yield item
            item = {}
            peaks = []
            continue

        if ': ' not in l:
            peak = l.split('\t')
    #        print(peak)
            peaks.append(peak)
            continue
    #        peaks.append()

        [k, v] = l.split(': ', 1)
    #    print(k,v)
        if not item:
            assert(k == 'Name')
        item[k] = v
    yield item

#%%

#%%

def get_first_psms(ss):
    prevspec = None

    for row in ss:
    #    print(row)

        if row['Protein'][0:3] == 'REV':
            continue

        ind = int(row['SpecID'].split('=')[1])
        if prevspec == ind:
            continue
        prevspec = ind

        qval = float(row['QValue'])
        if qval == 1:
            continue
        yield (ind, row['Peptide'], row['SpecEValue'])
#    break

def match_peptide(p_nist, p_msgf):
    i=0
    j=0
#    print(p_nist, p_msgf)
    if p_msgf[1] == '.':
        while p_msgf[j] != '.':
            j += 1
        j += 1
    while True:
#        print(p_nist[i])
        if p_nist[i] == '/':
            return True
        if j >= len(p_msgf):
            return False
        if p_msgf[j] in '-+.0123456789':
#            print(p_msgf[j], j, len(p_msgf))
            j += 1
            continue

        if p_nist[i] != p_msgf[j]:
            if p_nist[i] not in ['i', 'l'] or p_msgf[j] not in ['i', 'l']:
#                print(False, p_nist, p_msgf)
                return False

        i += 1
        j += 1

    return True

#%%

method_map = {
        '1S2D gamma & gaussian': '_1s2ca',
        '1S2D skew normal': '_1s2c',
        '2S3D skew normal': '_2s3c',
    }

def get_truefdr(species):
    species_dir = res_dir + species + '/'

    def get_peps(species):
        #mspfile = open('nist/human_consensus_final_true_lib.msp')
        mspfile = tarfile.open(data_dir+species+'_consensus_final_true_lib.tar.gz', 'r|gz')
        tarinfo = mspfile.next()
        mspfile = mspfile.extractfile(tarinfo)

        msplist = (l.decode("utf-8").rstrip() for l in mspfile)

        peps = []
        for item in parse_msp(msplist):
            if not item:
                continue
            peps.append(item['Name'])
        return peps

    peps = get_peps(species)

    def get_truefdr(species):
        f = open(data_dir+species+'_d.tsv')
        psmcsv = csv.DictReader(f, delimiter='\t')

        psms = get_first_psms(psmcsv)
        matches = []
        for spec, pep, score in psms:
        #    print(peps[spec], pep)
            matches.append((match_peptide(peps[spec], pep), score))
        #    print(match_peptide(peps[spec], pep))

        n = 0
        fc = 0
        qstart = 0
        qvals = np.zeros(len(matches))
        curv = []
        ncorr = 0
        nwrong = 0
        for m, score in matches:
        #    print(row)
            n += 1
            if not m:
                qval = fc / n
                curv.append((qval, n, score))
                qvals[qstart:n-1] = qval
                fc += 1
                qstart = n-1
                nwrong += 1
            else:
                ncorr += 1

            print(fc, n, fc/n)

        print('correct vs wrong', ncorr, nwrong)

        qval = fc / n
        qvals[qstart:n] = qval
        curv.append((qval, n, score))
        curv = np.array(curv, dtype=float)
        curv[:,2] = -np.log(curv[:,2])
        true_fdr = np.array(qvals)
        print(n)

#        true_thres = 0
#        for fdr,n,s in curv:
#            if fdr > 0.01:
#                break
#        #    nmatches = n
#            true_thres = s

#        ttfile = open(species_dir + 'true_thres_tda.txt', 'w')
#        ttfile.write("%f\n"%true_thres)
#        ttfile.close()

        return true_fdr

    true_fdr = get_truefdr(species)

    fdr_dir = species_dir + 'fdr/'
    truefdr_file = fdr_dir + 'true_tda.csv'

    np.savetxt(truefdr_file, true_fdr)

    return true_fdr

#%%
for species in species_list:
    get_truefdr(species)


a=int(input("Enter a number:-"))
j= 1
i=1
while i <= a:

    if j <= 10:
        mul = i*j
        print(f"{i} * {j} = {mul}")
        j+=1
    else:
        print("")
        i+=1
        j=1

loop questions/universal 1 loop range table .py


# coding=utf-8
import codecs
import os
import pymssql
import sys
import uuid
from com.database.ConnectDataBase import ConnectionDatabase

# 设置默认编码
from xml.etree import ElementTree

import xlrd

'''
    数据库连接
'''
def getConnect_new():
    __conn = ConnectionDatabase("localhost", "sa", "11111", "EpointOATest3")
    return __conn

def getConnect_old():
    __conn = ConnectionDatabase("localhost", "sa", "11111", "oa_old")
    return __conn

##########################################################
#############遍历目录，读取xml文件，导入附件信息
##########################################################

# 遍历指定目录
def eachfile(filepath, sql, outputfile, state, count, conn):
    pathdir = os.listdir(filepath)
    for dir in pathdir:
        child = os.path.join('%s\%s' % (filepath, dir))
        if os.path.isfile(child):
            if child.find("basicInfo") != -1:
                readfile(child, sql, outputfile, count, state, conn)
            continue
        eachfile(child, sql, outputfile, state, count, conn)

# 遍历结果
def readfile(filenames, sql, filepath, count, state, conn):
    with codecs.open(filenames, 'r', encoding='gbk') as fp:
        text = fp.read().replace('<?xml version="1.0" encoding="GBK"?>', '<?xml version="1.0" encoding="UTF-8"?>')

    element = ElementTree.fromstring(text.encode('utf-8'))

    for doc in element:
        # 定义参数
        clientguid = ""
        for key in doc.attrib:
            clientguid = doc.attrib[key]
            filepath += (clientguid + "/")
        for items in doc:
            # 定义参数
            attachguid = uuid.uuid1()
            attachname = ""
            contenttype = ""
            # 附件
            storagetype = "NasShareDirectory"
            # attachtag = "leaderApprove_feedback"
            attachtag = "wd25_attach"

            if parse_xml_node(items):
                attachname = parse_xml_node(items)

            if os.path.splitext(attachname)[-1]:
                contenttype = os.path.splitext(attachname)[-1]
            # 插入附件表
            params = (attachguid, attachname, contenttype, clientguid, attachtag, filepath, storagetype, clientguid)
            # 过滤参数为空的数据
            if params is None:
                continue
            # 执行sql语句
            try:
                effect = conn.mssql_exe_sql(sql, params)
                if effect:
                    count += 1
                    print("导入第" + str(count) + "条成功*********" + attachname)
                else:
                    print("sql语句执行失败")

            except Exception as e:
                print(e)
                print(sql%params)
                return

# 解析节点
def parse_xml_node(node):
    if len(node.getchildren()) == 0:
        return node.text if node.text is not None else ''
    else:
        node_dict = {}
        for child in node.getchildren():
            if child.tag in node_dict.keys():
                if not isinstance(node_dict[child.tag], list):
                    node_dict[child.tag] = [node_dict[child.tag]]
                node_dict[child.tag].append(parse_xml_node(child))
            else:
                node_dict[child.tag] = parse_xml_node(child)
        return node_dict

def handleFile():
    conn = getConnect_old()
    count = 0
    # 通知
    type="leaderApprove"
    # filenames = "F:\松江OA\OA数据解析\老OA数据\附件\领导批示反馈"
    filenames = "F:\松江OA\OA数据解析\收文数据\收文管理"
    oupputfile = "D:\OA9Attach\BigFileUpLoadStorage/wd25/"

    # 发文
    # type="fawen"
    # filenames = "E:\\work\\project\\2018\\importdata\\fawen\\BigFileUpLoadStorage"
    # oupputfile="D:\OA9Attach\BigFileUpLoadStorage/fawen/"

    sql = '''
        insert into Frame_AttachInfo_wd25(attachguid,attachfilename,contenttype,CliengGuid,CliengTag,filepath,storagetype,attachstorageguid)
            values(%s,%s,%s,%s,%s,%s,%s,%s)
    '''
    eachfile(filenames, sql, oupputfile, type, count, conn)

    # 关闭连接
    conn.commitData()
    conn.closeConn()

if __name__ == '__main__':
    handleFile()


class Solution:
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """

        maxDist = 0
        for i in range(len(nums)):
            if i > maxDist:
                return False
            dist = i + nums[i]
            maxDist = max(maxDist, dist)
        return True

if __name__ == '__main__':
    print(Solution().canJump([2,3,1,1,4]))


"""J&M, CH2, Task # 2.6 Implement a minimum edit distance algorithm"""

import numpy as np

def min_edit_dist(source: str, target: str, sub_cost:int=2,
                  del_cost:int=1, ins_cost:int=1) -> int:
    """Calculate the minimum edit distance between a source string and a target
    string.

    Parameters:
		source (str): The source string.
        target (str): The target string.
        sub_cost (int): The cost of substitution; default is 2
        del_cost (int): The cost of deletion; default is 1
        ins_cost (int): The cost of insertion; default is 1

    Returns:
		med (int): the minimum edit distance between the source and target
        	strings

    Detailed Explanation:
	The minimum edit distance between two strings is the minimum number of
    operations (insertions, deletions, or substitutions) required to transform
    the source string into the target string. This function utilizes the dynamic
    programming approach to	solve the problem efficiently.
    """
    operations = ["delete", "insert", "substitute"]
    n = len(source)
    m = len(target)

	# Create a distance matrix
    d = np.zeros((m+1, n+1), dtype=int)

    # Create backpointer
    backpointers = [{op:None for op in operations}
                            for i in range(m + 1)]

	# Initialization: first row and column is coming from an empty string
    for row in range(m + 1):
        d[row,0] = row

    for col in range(n + 1):
        d[0, col] = col

    for i in range(1, n + 1):
        for j in range(1, m + 1):
            sub_cost_tmp = sub_cost
            if source[i-1] == target[j-1]:
                sub_cost_tmp = 0

            # min_edit = min(costs)
            # d[i, j] = min_edit
            # backpointers[i][costs[min_edit]] = costs[min_edit]

    med = d[m,n]

    return med, d

min_edit_dist("duck", "dock")


from api_yamdb.settings import REGEX_USERNAME
from django.core.exceptions import ValidationError

class ValidateUsername:
    """
    Валидатор для username.
    """
    def validate_username(self, username):
        if not REGEX_USERNAME.fullmatch(username):
            raise ValidationError(
                f'Некорректные символы в username: {REGEX_USERNAME}'
            )
        if username == 'me':
            raise ValidationError('Ник "me" нельзя регистрировать!')
        return username


class one():
    a:int
    b:int
    def __init__(self):
        self.a=12
        self.b=13
        print("constructer is called")
    def dis(self):
        print("a=",self.a)
        print("b=",self.b)

ob1=one()
ob1.dis()
ob2=one()
ob2.dis()


from selenium import webdriver
import time

browser = webdriver.Chrome('C://Users//20143//Desktop//chromedriver.exe')
browser.get("https://basecamp.robolink.com/cwists/category#products=%5B1%5D&selected_sort_by=alphabetical")

time.sleep(5)
button = browser.find_element_by_xpath('//*[@id="activity-search-results"]/div/div[2]/button')
button.click()
time.sleep(5)

cards = browser.find_elements_by_class_name("card__img-wrap")
links = []
for card in cards:
    links.append(card.get_attribute('href'))
for link in links:
    browser.get(link)
    time.sleep(5)

    buttons = browser.find_elements_by_class_name('cpy-clip-txtarea')
    if len(buttons) == 0:
        continue

    title = browser.find_element_by_css_selector('.titlebar__title.u-flex')
    subtitle = browser.find_elements_by_css_selector('.step-content-h3.u-hide-print')
    title_name = title.get_attribute("textContent")

    try:
        wf = open(title_name[:2] + ".txt", "w", encoding='UTF-8')

        wf.write(title_name + "\n\n\n")
        for i in subtitle:
            wf.write(i.get_attribute("textContent")+"\n")
        wf.write("\n\n\n")
        for i in buttons:
            wf.write(i.get_attribute("textContent")+"\n\n\n\n\n")
        wf.write("\n\n\n")
        wf.close()
    except:
        print("FU"+title_name)

    time.sleep(1)
    print(link)

time.sleep(5)
browser.quit()


import json

from tqdm import tqdm

from anlp_project.datasets.europarl import EuroParlRaw

def main():
    """
    Converts dataset to jsonlines format

    needed for baseline++ training
    """
    dataset = EuroParlRaw()
    with open("dataset.jsonl", "w") as f:
        for de, en in tqdm(dataset):
            f.write(json.dumps({"translation": {"en": en, "de": de}}) + "\n")

if __name__ == "__main__":
    main()


from PyQt5.QtWidgets import QMainWindow, QApplication, QFileDialog, QMessageBox, QLabel, QDialog
from PyQt5 import uic
from PyQt5.QtGui import *
from PyQt5.QtCore import QRect, Qt, QPoint
import os, glob, cv2, sys

form_class = uic.loadUiType("Image_loader2.ui")[0]

class Label_Dialog(QDialog):
    def __init__(self, parent):
        super(Label_Dialog, self).__init__(parent)
        uic.loadUi('/Users/picardy/PycharmProjects/pythonProject/Label.ui', self)
        self.Green.setStyleSheet('background-color: #7cfc00')
        self.Yellow.setStyleSheet('background-color: yellow')
        self.Blue.setStyleSheet('background-color: #0066ff')
        self.parent = parent
        self.show()
        self.Green.clicked.connect(parent.greenColor)
        self.Yellow.clicked.connect(parent.yellowColor)
        self.Blue.clicked.connect(parent.blueColor)
        self.Green_line.textChanged.connect(self.func_G)
        self.Yellow_line.textChanged.connect(self.func_Y)
        self.Blue_line.textChanged.connect(self.func_B)
        self.Path_line.textChanged.connect(self.labelPath)
        self.toolButton.clicked.connect(self.path)

    def path(self):
        dir_path = QFileDialog.getExistingDirectory(self, 'open')
        for file in dir_path:
            exist = self.Path_line.text()
            self.Path_line.setText(exist + file)
        print(dir_path)

    def func_G(self):
        self.parent.Label_G = self.Green_line.text()

    def func_Y(self):
        self.parent.Label_Y = self.Yellow_line.text()

    def func_B(self):
        self.parent.Label_B = self.Blue_line.text()

    def labelPath(self):
        self.parent.path = self.Path_line.text()

class ViewerClass(QMainWindow, form_class):
    def __init__(self, parent=None):
        super().__init__()
        self.setupUi(self)
        self.qPixmapVar = QPixmap()
        self.Image_label = QLabel()
        self.actionFile.triggered.connect(self.fileSelect)
        self.actionDirectory.triggered.connect(self.folderSelect)
        self.NextButton.clicked.connect(self.NextClick)
        self.PreviousButton.clicked.connect(self.PreviousClick)
        self.actionClose.triggered.connect(self.close)
        self.actionOpen_Tool.triggered.connect(self.openTool)

        self.idx = 0
        self.flag = 0
        self.start, self.end = QPoint(), QPoint()
        self.Label_G = ()
        self.Label_Y = ()
        self.Label_B = ()
        self.path = ()
        self.image = None

    # def imageSave(self):
    #     filename = QFileDialog.getSaveFileName(filter="JPG(*.jpg);;PNG(*.png);;TIFF(*.tiff);;BMP(*.bmp)")[0]
    #     cv2.imwrite(filename, self.image)

    def fileSelect(self):
        filename = QFileDialog.getOpenFileName(self, 'open', '/Users/picardy/Downloads/Seungkyu/copied/')[0]
        if filename:
            self.image = cv2.imread(filename)
            self.dir_h, self.dir_w, channel = self.image.shape
            self.qPixmapVar.load(filename)
            self.Image_label.setPixmap(self.qPixmapVar)
            QMainWindow.resize(self, self.dir_w, self.dir_h)
            print(self.dir_w, self.dir_h)

            # folderName = self.image
            self.name = filename[filename.rfind("/"): - 4]
            self.savename = str(self.path) + str(self.name) + '.txt'
            try:
                if str(self.path) == self.savename:
                    print(self.savename)
                    self.write = open(self.savename, 'w', encoding='utf8')
                else:
                    os.mkdir(str(self.path))
                    self.savename = str(self.path) + str(self.name) + '.txt'
                    self.write = open(self.savename, 'w', encoding='utf8')
            except:
                self.Path_error()

    def folderSelect(self):
        dirName = QFileDialog.getExistingDirectory(self, 'open', '/Users/picardy/Downloads/Seungkyu/copied/')
        self.files = []
        if dirName:
            for file in glob.glob(os.path.join(dirName, '*.png')):
                self.files.append(file)
            for file in glob.glob(os.path.join(dirName, '*.jpg')):
                self.files.append(file)
            self.image = cv2.imread(self.files[self.idx])
            self.dir_h, self.dir_w, channel = self.image.shape
            self.qPixmapVar.load(self.files[0])
            self.Image_label.setPixmap(self.qPixmapVar)
            QMainWindow.resize(self, self.dir_w, self.dir_h)

            folderName = self.files[self.idx]
            self.name = folderName[folderName.rfind("/"): - 4]
            self.savename = str(self.path) + str(self.name) + '.txt'
            try:
                if str(self.path) == self.savename:
                    print(self.savename)
                    self.write = open(self.savename, 'w', encoding='utf8')
                else:
                    os.mkdir(str(self.path))
                    self.savename = str(self.path) + str(self.name) + '.txt'
                    self.write = open(self.savename, 'w', encoding='utf8')
            except:
                self.Path_error()

    def NextClick(self):
        try:
            if self.idx < len(self.files):
                self.idx += 1
                self.qPixmapVar.load(self.files[self.idx])
                self.Image_label.setPixmap(self.qPixmapVar)
                self.cv_file = cv2.imread(self.files[self.idx])
                self.dir_h, self.dir_w, channel = self.cv_file.shape
                QMainWindow.resize(self, self.dir_w, self.dir_h)

                folderName = self.files[self.idx]
                self.name = folderName[folderName.rfind("/"): - 4]
                self.savename = str(self.path) + str(self.name) + '.txt'
                self.write = open(self.savename, 'w', encoding='utf8')
                # print(self.idx)
                print(self.dir_w, self.dir_h)

        except IndexError:
            self.endOfimage()
            self.idx -= 1
        except AttributeError:
            self.endOfimage()
            self.idx -= 1

    def endOfimage(self):
        msg = QMessageBox()
        msg.setWindowTitle('Error!')
        msg.setIcon(QMessageBox.Warning)
        msg.setText('마지막 이미지 입니다.')
        msg.setStandardButtons(QMessageBox.Ok)
        result = msg.exec_()

    def PreviousClick(self):
        if self.idx > 0:
            self.idx -= 1
            self.qPixmapVar.load(self.files[self.idx])
            self.Image_label.setPixmap(self.qPixmapVar)
            self.cv_file = cv2.imread(self.files[self.idx])
            self.dir_h, self.dir_w, channel = self.cv_file.shape
            QMainWindow.resize(self, self.dir_w, self.dir_h)
            folderName = self.files[self.idx]
            self.name = folderName[folderName.rfind("/"): - 4]
            self.savename = str(self.path) + str(self.name) + '.txt'
            self.write = open(self.savename, 'w', encoding='utf8')
            # print(self.idx)
            print(self.dir_w, self.dir_h)
        else:
            self.firstImage()

    def firstImage(self):
        msg = QMessageBox()
        msg.setWindowTitle('Error!')
        msg.setIcon(QMessageBox.Warning)
        msg.setText('첫 번째 이미지 입니다.')
        msg.setStandardButtons(QMessageBox.Ok)
        result = msg.exec_()

# mouse Draw Event

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.drawPixmap(QPoint(), self.qPixmapVar)

        if not self.start.isNull() and not self.end.isNull():
            rect = QRect(self.start, self.end)
            painter.setPen(QPen(Qt.red, 2, Qt.SolidLine))
            painter.drawRect(rect.normalized())

    def mousePressEvent(self, event):
        if event.buttons() & Qt.LeftButton:
            self.start = event.pos()
            self.end = self.start
            self.update()

    def mouseMoveEvent(self, event):
        if event.buttons() & Qt.LeftButton:
            self.end = event.pos()
            self.update()

    def mouseReleaseEvent(self, event):
        if not event.buttons() & Qt.LeftButton:
            if self.flag == 0:
                rect = QRect(self.start, self.end)
                painter = QPainter(self.qPixmapVar)
                painter.setPen(QPen(Qt.green, 2, Qt.SolidLine))
                painter.drawRect(rect.normalized())
                self.fileName()
                print('x0, y0 =', self.start.x(), self.start.y())
                print('x1, y1 =', self.end.x(), self.end.y())
                self.start, self.end = QPoint(), QPoint()
                self.update()
            elif self.flag == 1:
                rect = QRect(self.start, self.end)
                painter = QPainter(self.qPixmapVar)
                painter.setPen(QPen(Qt.yellow, 2, Qt.SolidLine))
                painter.drawRect(rect.normalized())
                self.fileName()
                print('x0, y0 =', self.start.x(), self.start.y())
                print('x1, y1 =', self.end.x(), self.end.y())
                self.start, self.end = QPoint(), QPoint()
                self.update()
            elif self.flag == 2:
                rect = QRect(self.start, self.end)
                painter = QPainter(self.qPixmapVar)
                painter.setPen(QPen(Qt.blue, 2, Qt.SolidLine))
                painter.drawRect(rect.normalized())
                self.fileName()
                print('x0, y0 =', self.start.x(), self.start.y())
                print('x1, y1 =', self.end.x(), self.end.y())
                self.start, self.end = QPoint(), QPoint()
                self.update()

    def fileName(self):
        # folderName = self.files[self.idx]
        # self.name = folderName[folderName.rfind("/"): - 4]
        # self.savename = str(self.path) + str(self.name) + '.txt'
        # if self.flag == 0:
        #     with open(self.savename, 'w', encoding='utf8') as self.write:
        if self.flag == 0:
            self.write.write('{4} 0 0 0 {0} {1} {2} {3} 0 0 0 0 0 0 0\n'
                             .format(self.start.x(), self.start.y(), self.end.x(), self.end.y(), self.Label_G))

        if self.flag == 1:
            self.write.write('{4} 0 0 0 {0} {1} {2} {3} 0 0 0 0 0 0 0\n'
                             .format(self.start.x(), self.start.y(), self.end.x(), self.end.y(), self.Label_Y))

        if self.flag == 2:
            self.write.write('{4} 0 0 0 {0} {1} {2} {3} 0 0 0 0 0 0 0\n'
                             .format(self.start.x(), self.start.y(), self.end.x(), self.end.y(), self.Label_B))

    def Path_error(self):
        msg = QMessageBox()
        msg.setWindowTitle('Error!')
        msg.setIcon(QMessageBox.Warning)
        msg.setText('Label 경로를 설정하세요')
        msg.setStandardButtons(QMessageBox.Ok)
        msg.buttonClicked.connect(self.msg_Button)
        result = msg.exec_()

    def msg_Button(self):
        self.close()

    def openTool(self):
        Label_Dialog(self)

#change_Color

    def greenColor(self):
        self.flag = 0
        self.update()
        print(self.flag)

    def yellowColor(self):
        self.flag = 1
        self.update()
        print(self.flag)

    def blueColor(self):
        self.flag = 2
        self.update()
        print(self.flag)

app = QApplication(sys.argv)
myWindow = ViewerClass(None)
myWindow.show()
app.exec_()


# Licensed under a 3-clause BSD style license - see LICENSE.rst

import numpy as np
from sofia_redux.toolkit.resampling.resample_utils import (
    scale_coordinates, scale_forward_scalar, scale_reverse_scalar,
    scale_forward_vector, scale_reverse_vector)

def test_scale_coordinates():
    random = np.random.RandomState(41)
    dvec = random.rand(3, 32) + 1
    dscalar = dvec[:, 0]

    scale = np.arange(3) + 1.0
    offset = np.arange(3) + 10.0

    # scale_forward_scalar
    x = scale_coordinates(dscalar, scale, offset, reverse=False)
    assert np.allclose(x, (dscalar - offset) / scale)

    # scale_reverse_scalar
    x = scale_coordinates(dscalar, scale, offset, reverse=True)
    assert np.allclose(x, dscalar * scale + offset)

    # scale_forward_vector
    x = scale_coordinates(dvec, scale, offset, reverse=False)
    assert np.allclose(x, (dvec - offset[:, None]) / scale[:, None])

    # scale_reverse_vector
    x = scale_coordinates(dvec, scale, offset, reverse=True)
    assert np.allclose(x, dvec * scale[:, None] + offset[:, None])

def test_forward_scalar():
    coordinates = np.arange(3, dtype=np.float64) + 1
    offset = np.full(3, 10.0)
    scale = np.full(3, 2.0)
    assert np.allclose(scale_forward_scalar(coordinates, scale, offset),
                       [-4.5, -4, -3.5])

def test_forward_vector():
    coordinates = np.repeat(np.arange(3, dtype=np.float64)[None] + 1,
                            3, axis=0)
    offset = np.full(3, 10.0)
    scale = np.full(3, 2.0)
    result = scale_forward_vector(coordinates, scale, offset)
    assert np.allclose(result, [[-4.5, -4, -3.5]])
    assert result.shape == (3, 3)

def test_reverse_scalar():
    coordinates = np.arange(3, dtype=np.float64) + 1
    offset = np.full(3, 10.0)
    scale = np.full(3, 2.0)
    result = scale_reverse_scalar(coordinates, scale, offset)
    assert np.allclose(result, [12, 14, 16])

def test_reverse_vector():
    coordinates = np.repeat(np.arange(3, dtype=np.float64)[None] + 1,
                            3, axis=0)
    offset = np.full(3, 10.0)
    scale = np.full(3, 2.0)
    result = scale_reverse_vector(coordinates, scale, offset)
    assert np.allclose(result, [[12, 14, 16]])
    assert result.shape == (3, 3)


# coding=utf-8
import json
import re
import requests,os

# TODO 可以用

dir = "H:\\11-快手单个视频\\"
def get(url: str) -> dict:
    """
    title、imgs、videos
    """
    data = {}
    failed = {'msg': 'failed...'}
    headers = {
        "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25",
        "Cookie": "did=web_f3915064ee334c508642888137f27598;"
    }
    # rewrite desktop url
    temp = re.findall(r'live\.kuaishou\.com/u/\w+/(\w+)', url)
    # print(temp)
    if temp:
        url = 'https://c.kuaishou.com/fw/photo/{}'.format(temp[0])

    rep = requests.get(url, headers=headers, timeout=10)
    if rep.status_code != 200:
        return failed
    page_data = re.findall(r'<script type="text/javascript">window\.pageData= (\{.*?\})</script>', rep.text)
    # print(page_data)
    if not page_data:
        return failed
    try:
        page_data = json.loads(page_data[0])
    except Exception:
        print('kuaishou loads json failed')
        return failed

    video_info = page_data['video']
    data['title'] = video_info['caption']
    # 获取主播名字
    data['user'] = page_data['user']['name']
    # 时间
    data['time'] = page_data['rawPhoto']['timestamp']
    # 获取视频
    try:  # 如果出错，则可能是长图视频
        data['videos'] = [video_info['srcNoMark']]
    except Exception:
        pass
    else:
        data['videoName'] = data['title']
        data['msg'] = '如果快手视频下载出错请尝试更换网络'
    # 获取图片
    try:  # 如果出错，则可能是普通视频；
        images = video_info['images']
        imageCDN: str = video_info['imageCDN']
        # 如果是长图视频，则这几项一定存在
        assert images is not None
        assert imageCDN is not None
    except Exception:
        pass
    else:
        if not imageCDN.startswith('http'):
            imageCDN = 'http://' + imageCDN
        data['imgs'] = [imageCDN + i['path'] for i in images]
    return data

def readconfig():
    f = open(r'config.txt', "r", encoding='utf-8')
    for x in f:
        geturl(x)
    f.close()

def geturl(config:str)-> list:
    pattern = re.compile('(https:.*?) 复制此消息，打开【快手】直接观看！.*?',re.S)
    # pattern = re.compile('.*?发了一个快手作品，一起来看！(.*?) 复制此消息，打开【快手】直接观看！.*?',re.S)
    v_url = re.findall(pattern, config)
    print(v_url)
    if v_url!= [] :
        req = get(v_url[0])
        download(req)
def download(req):
    try:
        v_name = req.get('user') + str(req.get('time')) + ".mp4"
        video = dir + v_name
        print(video)
        print(req.get('videos'))
        if not os.path.exists(video):
            r = requests.get(req.get('videos')[0])
            r.raise_for_status()
            with open(video, "wb") as f:
                f.write(r.content)
            print("    视频 " + v_name + " 下载成功 √")
        else:
            print("    视频 " + v_name + " 已存在 √")
    except:
        print("  这里似乎有点小错误，已跳过")
if __name__ == "__main__":
    # print(get(url="https://live.kuaishou.com/u/kissyou696773/3x9vpmn3n4ihvg6"))
    # print(get(url="https://v.kuaishou.com/7x1fql"))
    readconfig()


import numpy as np
import math

def initialize_zeros(layers: np.array) -> dict:
    """
    Initializes parameters as arrays of zeros
    """
    # initialize variables
    parameters = {}

    # create parameters
    for l in range(1, len(layers)):
        parameters['W' + str(l)] = np.zeros((layers[l], layers[l-1]))
        parameters['b' + str(l)] = np.zeros((layers[l], 1))

    return parameters

def initialize_random(layers: np.array) -> dict:
    """
    Initializes parameters as arrays of small random values and
    zeros respectively
    """
    # initialize variables
    parameters = {}

    # start creating parameters
    for l in range(1, len(layers)):
        parameters['W' + str(l)] = np.random.randn(layers[l], layers[l-1]) * .01
        parameters['b' + str(l)] = np.zeros((layers[l], 1))

    return parameters

def initialize_he(layers: np.array) -> dict:
    """
    Initializes parameters as arrays containing values according to
    He Initialization method, specifically, multiplies the initial random
    values by the sqaure root of 2 / previous layer
    """
    # initialize variables
    parameters = {}

    # start creating parameters
    for l in range(1, len(layers)):
        x = np.sqrt(2. / layers[l-1])
        parameters['W' + str(l)] = np.random.randn(layers[l], layers[l-1]) * x
        parameters['b' + str(l)] = np.zeros((layers[l], 1))

    return parameters

def mini_batches(X, Y, batch_size=64) -> list:
    """
    Create mini-batches for mini-batch gradient descent
    """
    m = X.shape[1]
    batches = []

    shuffle = list(np.random.permutation(m))
    shuffled_X = X[:, shuffle]
    shuffled_Y = Y[:, shuffle].reshape((1, m))

    complete_batches = math.floor(m / batch_size)
    for b in range(complete_batches):
        mini_x = shuffled_X[:, batch_size*b:batch_size*(b+1)]
        mini_y = shuffled_Y[:, batch_size*b:batch_size*(b+1)]
        batches.append((mini_x, mini_y))

    if m % batch_size != 0:
        mini_x = shuffled_X[:, -(m-batch_size*complete_batches):]
        mini_y = shuffled_Y[:, -(m-batch_size*complete_batches):]
        batches.append((mini_x, mini_y))

    return batches

def initialize_velocity(parameters: dict) -> dict:
    """
    Initialize velocity parameter for gradient descent with momentum
    """
    velocity = {}
    L = len(parameters) // 2

    for l in range(L):
        velocity["dW" + str(l+1)] = np.zeros(parameters['W' + str(l+1)].shape)
        velocity["db" + str(l+1)] = np.zeros(parameters['b' + str(l+1)].shape)

    return velocity

def initialize_rms(parameters: dict) -> dict:
    """
    Initialize RMS parameter for RMSProp optimization
    """
    L = len(parameters) // 2
    rms = {}

    for l in range(L):
        rms["dW" + str(l+1)] = np.zeros(parameters['W' + str(l+1)].shape)
        rms["db" + str(l+1)] = np.zeros(parameters['b' + str(l+1)].shape)

    return rms

def initialize_adam(parameters: dict) -> tuple:
    """
    Initialize parameters for Adam optimization algorithm
    """
    L = len(parameters) // 2
    velocity = {}
    rms = {}

    for l in range(L):
        velocity["dW" + str(l+1)] = np.zeros(parameters['W' + str(l+1)].shape)
        velocity["db" + str(l+1)] = np.zeros(parameters['b' + str(l+1)].shape)
        rms["dW" + str(l+1)] = np.zeros(parameters['W' + str(l+1)].shape)
        rms["db" + str(l+1)] = np.zeros(parameters['b' + str(l+1)].shape)

    return velocity, rms


#!/usr/bin/python

from gi.repository import Gtk, GObject, Gdk
import sys

class CommonAPI(Gtk.Window):

	def __init__ (self, Title, Length, Breadth):
		Gtk.Window.__init__(self, title = Title )
		self.set_size_request(Length, Breadth)
		self.fixed = Gtk.Fixed()
		self.grid = Gtk.Grid()
		self.radioButton1 = None
		#self.Show()

	def CreateButton(self, xPos, yPos, Title ):
		button = Gtk.Button( label = Title )
		self.fixed.put(button, xPos, yPos )

	def CreateRadioButton(self, xPos, yPos, Title ):
		radioButton = Gtk.RadioButton.new_with_label_from_widget(self.radioButton1, Title)
		self.radioButton1 = radioButton
		self.fixed.put(radioButton, xPos, yPos )

	def CreateCheckBox(self, xPos, yPos, Title ):
		checkButton = Gtk.CheckButton( label = Title )
		self.fixed.put(checkButton, xPos, yPos)

	def CreateTextBox(self, xPos, yPos):
		textField = Gtk.Entry()
		self.fixed.put(textField, xPos, yPos)

	def CreateList(self, xPos, yPos, List):
		#Creating a model from treeview
		store = Gtk.ListStore(str)
		for i in range(len(List)):
			listiter = store.append([List[i]])
		tree = Gtk.TreeView(store)

		vbox = Gtk.VBox(spacing = 1)
		label = Gtk.Label("Your list is here");
		vbox.pack_start(label, False, False, 0)
		vbox.pack_start(tree, False, False, 0)

		#column for name
		renderer = Gtk.CellRendererText()
		column = Gtk.TreeViewColumn(" ", renderer, text = 0)
		tree.append_column(column)
		self.fixed.put(vbox, xPos, yPos)

	def Show(self):
		self.add(self.fixed)
		self.connect("delete-event", Gtk.main_quit)
		self.show_all()
		Gtk.main()


import sys
from collections import deque

dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]

input = sys.stdin.readline

n, m = map(int, input().split())
# 치즈가 있는 부분 1, 치즈가 없는 부분 0
map = [list(map(int, input().split())) for _ in range(n)]

def melted():
    queue = deque()
    visited = [[0] * m for _ in range(n)]

    # 모눈종이의 맨 가장자리에는 치즈가 놓이지 않는 것으로 가정한다
    queue.append([0,0])
    visited[0][0] = 1

    while queue:
        x, y = queue.popleft()
        for i in range(4):
            nx, ny = x + dx[i], y + dy[i]

            if 0 <= nx < n and 0 <= ny < m:
                # 외부 공기
                if not map[nx][ny] and not visited[nx][ny]:
                    visited[nx][ny] = 1
                    queue.append([nx, ny])

                # 치즈
                else:
                    visited[nx][ny] += 1

    sum = 0
    for i in range(n):
        for j in range(m):
            if visited[i][j] >= 2:
                map[i][j] = 0

            sum += map[i][j]
    return sum

ans = 0
while True:
    result = melted()
    ans += 1

    if not result:
        break

print(ans)


#Calculation of BMI in m2 with user inputs

Weight = float(input("Enter weight in kg: "))
Height = float(input("Enter height in cm: "))

HeightMsq = (Height/100)**2

bmi = Weight / HeightMsq

BMI = round(bmi,2)

print("Your BMI is {} m2".format(bmi))


class Solution(object):
    def isPowerOfFour(self, num):
        """
        :type num: int
        :rtype: bool
        """
        import math
        if num<=0:
        	return False
        logx = math.log10(num)/math.log10(4)
        return True if logx-int(logx) == 0 else False

if __name__ == '__main__':
	test = Solution()
	print(test.isPowerOfFour(5))


# 게리맨더링
import sys
sys.stdin = open('input.txt', 'r')
from collections import deque

def dfs(cnt, s, end):
    global mn
    # 종료조건
    if cnt == end:  # 재귀횟수가 목표횟수에 도달
        group1, group2 = deque(), deque()   # 그룹1, 2로 나누기

        # 방문 한 지점 group1, # 방문 안 한 지점 group2
        for i in range(1, N+1):
            if visited[i]:
                group1.append(i)
            else:
                group2.append(i)

        # 연결되어 있는지 확인
        ans1 = bfs(group1)
        if not ans1:
            return
        ans2 = bfs(group2)
        if not ans2:
            return

        mn = min(mn, abs(ans1-ans2))
        return

    # end개수에 도달하지 못 했을 때는 그 다음 구역부터 조합 더하기
    for i in range(s, N+1):
        if not visited[i]:  # 방문하지 않은 지점
            visited[i] = 1
            dfs(cnt+1, i, end)
            visited[i] = 0

def bfs(group):
    q = deque([group[0]])   # 첫 지점 enqueue
    check = [0] * (N+1)
    check[group[0]] = 1     # 방문 표시

    cnt, answer = 1, 0      # cnt: 방문 지점 수, answer: 인구 수 합
    while q:
        t = q.popleft()
        answer += nums[t]
        for i in adjL[t]:
            # 인접하고 group 안에 속하며 방문한 적이 없으면 계속 진행
            if i in group and not check[i]:
                check[i] = 1
                cnt += 1
                q.append(i)

    if cnt == len(group):
        return answer
    else:
        return 0

N = int(input())
nums = [0] + list(map(int, input().split()))    # 인구수 배열
visited = [0] * (N+1)
adjL = [[] for _ in range(N+1)]     # 인접 리스트
for i in range(1, N+1):
    x, *lst = map(int, input().split())
    for c in lst:
        adjL[i].append(c)

mn = 1000
for i in range(1, N//2 + 1):    # 1개/N-1개, 2개/N-2개, ... N//2개/N//2개 -> 조합
    visited = [0] * (N+1)
    dfs(0, 1, i)                # 현재까지 재귀 횟수, 시작지점, target 재귀횟수

if mn == 1000:
    print(-1)
else:
    print(mn)


#!/usr/bin/env python
import portfoliofuncs as pf
import numpy as np

data = np.loadtxt("./logdiffdata.csv",delimiter=",")

window_size = 110
r0=0.01
inportfolio_thre = 0.01

emp_roling_dict = pf.roling_portfolio(data,r0=r0,window_size=window_size,\
										methods='empirical',inportfolio_thre=inportfolio_thre)
emp_diag_roling_dict = pf.roling_portfolio(data,r0=r0,window_size=window_size,\
										methods='empirical_diag',inportfolio_thre=inportfolio_thre)
lasso_roling_dict = pf.roling_portfolio(data,r0=r0,window_size=window_size,methods='lasso',\
                       		           inportfolio_thre=inportfolio_thre,using_sklearn_glasso=True,\
                       		           shrunk_param=0.01)
lasso_optim_roling_dict = pf.roling_portfolio(data,r0=r0,window_size=window_size,methods='lasso',\
                       		           inportfolio_thre=inportfolio_thre,using_sklearn_glasso=True,\
                       		           shrunk_param=0.0035)
shrunk_roling_dict = pf.roling_portfolio(data,r0=r0,window_size=window_size,\
										methods='shrunk',inportfolio_thre=inportfolio_thre)
sindex_roling_dict = pf.roling_portfolio(data,r0=r0,window_size=window_size,\
										methods='singleindex',inportfolio_thre=inportfolio_thre)
equal_roling_dict = pf.equal_rolling_portfolio(data, window_size=110)

pf.evaluation(emp_roling_dict)
pf.evaluation(emp_diag_roling_dict)
pf.evaluation(lasso_roling_dict)
pf.evaluation(lasso_optim_roling_dict)
pf.evaluation(shrunk_roling_dict)
pf.evaluation(sindex_roling_dict)
pf.evaluation(equal_roling_dict)

pf.plot_test_return(emp_roling_dict, lasso_optim_roling_dict, emp_diag_roling_dict)
pf.plot_turnover(emp_roling_dict, lasso_optim_roling_dict, emp_diag_roling_dict)
pf.plot_abs_change(emp_roling_dict, lasso_optim_roling_dict, emp_diag_roling_dict)
pf.plot_stock_num(0.01, emp_roling_dict, lasso_optim_roling_dict, emp_diag_roling_dict)

pf.plot_test_return(sindex_roling_dict, lasso_optim_roling_dict,equal_roling_dict)
pf.plot_turnover(sindex_roling_dict, lasso_optim_roling_dict)
pf.plot_abs_change(sindex_roling_dict, lasso_optim_roling_dict)
pf.plot_stock_num(0.01, sindex_roling_dict, lasso_optim_roling_dict)

pf.plot_efficient_frontier(data)

"""
lasso_optim_dict, lasso_param_range = pf.lasso_param_optim(data)
#pf.save_dic(lasso_optim_dict, "/Users/kazeto/Desktop/GradThesis/nikkei/output/lasso_optim_dict_48range.pkl")
pf.plot_lasso_param_optim_return(lasso_optim_dict, lasso_param_range)
pf.plot_lasso_param_optim_risk(lasso_optim_dict, lasso_param_range)

#####
##single index
#market portfolio
S_single_index_diag = pf.make_single_index_diagonal_covariance_matrix(data)
S_single_index = pf.make_single_index_covariance_matrix(data)

ticker_dic = { 1801:"大成建設",1803:"清水建設",1963:"日揮",2502:"アサヒグループホールディングス",2801:"キッコーマン",\
            2802:"味の素",2914:"日本たばこ産業",4021:"日産化学工業",4151:"協和発酵キリン",4452:"花王",4503:"アステラス製薬",4507:"塩野義製薬",\
            4543:"テルモ",5101:"横浜ゴム",5108:"ブリヂストン",5406:"神戸製鋼所",5541:"大平洋金属",5631:"日本製鋼所",5713:"",6301:"コマツ",\
            6302:"住友重機械工業",6326:"クボタ",6305:"日立建機",6366:"千代田化工建設",6367:"ダイキン工業",6479:"ミネベア",6770:"アルプス電気",6773:"パイオニア",\
            6954:"ファナック",7202:"いすゞ自動車",7270:"富士重工業",8001:"",8002:"丸紅",8015:"豊田通商",8028:"ユニー・ファミリーマートホールディングス",\
            8830:"住友不動産",9007:"小田急電鉄",9009:"京成電鉄",9433:"KDDI",9503:"関西電力",9531:"東京ガス",9983:"ファーストリテイリング",\
            9984:"ソフトバンクグループ" }

import pandas as pd
names = np.loadtxt("/Users/kazeto/Desktop/GradThesis/nikkei/from2000name.csv")
m = data.mean(0)
std = data.std(0)
covmat = np.cov(data, rowvar=0, bias=0)
flontier = pd.DataFrame(efficient_frontier(data, m, covmat),columns=["mean","std"])

df = pd.DataFrame(data=np.c_[m,std],index=np.arange(len(m)),columns=["mean","std"])
df_mean_sorted = df.sort(columns="mean",ascending=False)
df_std_sorted = df.sort(columns="std",ascending=True)
df_rank_mean = df_mean_sorted.index
df_rank_std = df_std_sorted.index
#m_sorted = np.sort(m)[::-1]

fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(x=df["std"],y=df["mean"])
plt.xlabel("std")
plt.ylabel("mean")
plt.title("Mean - Standard Deviation")
#rank = df_rank_mean[0] #The top of mean index.
#plt.text(x=df.loc[rank]['std'], y=df.loc[rank]['mean'], s=str(names[rank]), ha = 'center', va = 'bottom')
ax.plot(flontier['std'],flontier['mean'],c="r")
fig.show()

for rank in df_rank_mean[0:5]:
	#np.sort(m)[::-1][rank-1]
	print("mean : {}".format(df['mean'][rank]))
	rank_ticker = names[rank]
	print(rank_ticker)
	try:
		rank_name = ticker_dic[int(rank_ticker)]
	except KeyError:
		rank_name = "None in dict"

	print(rank_name)
	text(, 1, rank_name, ha = 'center', va = 'bottom')

r0_list = np.linspace(0.005,0.01,num=100)

for i in r0_list[0:1]:
	sol,x = pf.mean_variance_model_optim(data,r=None,S=None,r0=i)
	weight = np.array(x).flatten()
	p_mean = np.dot(weight.T,m)
	p_std = np.sqrt(np.dot(np.dot(weight.T,covmat),weight))
"""


# https://www.codingninjas.com/codestudio/problems/longest-common-subsequence_624879
from sys import stdin

# def lcs(s, t) :
# 	#Your code goes here
#     m = len(s)
#     n = len(t)
#     dp = [[-1 for _ in range(n+1)] for _ in  range(m+1)]

#     # if s == ""
#     for i in range(n):
#         dp[0][i] = 0
#     # if t == ""
#     for i in range(m):
#         dp[i][0] = 0

#     for i in range(1, m+1):
#         for j in range(1, n+1):
#             if s[i-1] == t[j-1]:
#                 dp[i][j] = dp[i-1][j-1] + 1
#             else:
#                 dp[i][j] = max(dp[i-1][j], dp[i][j-1])
#     return dp[m][n]

# I had already solved this problem, for this week, I am counting them, but from next week, I will not count those questions, this is personal promize

dp1 =  [[-1]*(5+1)]*(7+1)
dp2 = [[-1 for _ in range(5+1)] for _ in  range(7+1)]
print(dp1 == dp2)


path=r"sequences.txt"
file=open(path,"w")

#write
file.write("ATGATAGTAGAAGTAGATA\n")
file.write("ATGATAGAGA\n")
file.write("ATGATAGATATA\n")
#writeline
file.writelines("ATGATAGATAATAATTA\n")
file.writelines("ATGATAGATATAAAA\n")
file.writelines("ATGATAGATATAATTATAT\n")

#Additional Functionality
list_seq=["TATAGATAA\n","ATAATTAAAA\n"]
file.writelines(list_seq)
file.writelines(["Anand\n","Kumar"])
#At the end
file.close()


#!/usr/bin/python3

def addDigits(s):
    val = 0
    for c in s:
        val += int(c)
    return val

print(addDigits("1234"))

def fact_iter(n):
    prod = 1
    for i in range(1, n + 1):
        prod *= i
    return prod

print(fact_iter(4))


import sys
import numpy as np
import pandas as pd

import data
from analysis import full_entropy_calculation_bpw

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print(f'USAGE: {sys.argv[0]} <filename>')
        exit(-1)
    # Variables related to the location of the data and the type of system
    bibles_path = '/home/pablo/Documents/GitHubRepos/paralleltext/bibles/corpus/'
    bible_filename = sys.argv[1]
    #bible_filename = 'eng-x-bible-world.txt'
    output_path = '/home/pablo/Documents/GitHubRepos/WordOrderBibles/output/MontemurroZanette/'
    # Variables related to the processing of text for GPT-2
    prompt = ''
    separator = ' '
    # Variables related to the processing of text for unigram entropies
    remove_punctuation = False
    lowercase = False

    bible = data.parse_pbc_bible(bibles_path + bible_filename)

    """For each of these hierarchical orders, we can compute the entropy per word and the unigram entropy."""
    by_bible, _, by_book, _, _ = bible.join_by_toc()
    by_level = {'bible': by_bible, 'book': by_book}

    eos_token = ''
    level_text = {level_name: data.join_texts_in_dict(id_texts, prompt, eos_token, separator) \
                  for level_name, id_texts in by_level.items()}

    raw_name = output_path + bible_filename
    level_entropies = {level_name: full_entropy_calculation_bpw(id_text,
                                                                remove_punctuation,
                                                                lowercase,
                                                            f'{raw_name}_{level_name}') \
                       for level_name, id_text in level_text.items()}

    level_avg_text_len = {level_name: np.mean([len(data.tokenize(text, remove_punctuation, lowercase)) \
                                               for text in id_text.values()]) \
                          for level_name, id_text in level_text.items()}

    # Save all these values to a Pandas dataframe that we can use to make histograms and compute statistics
    df = pd.DataFrame(columns=('level', 'n_tokens', 'H', 'H_s', 'H_r', 'id'))
    for level_name, section_entropies in level_entropies.items():
        for section_id, entropies in section_entropies.items():
            row = (level_name, len(data.tokenize(level_text[level_name][section_id], remove_punctuation, lowercase)),
                   entropies[0], entropies[1], entropies[2], str(section_id))
            df.loc[len(df)] = row

    # Compute the word-order entropies
    df['D_r'] = df['H_r'] - df['H']
    df['D_s'] = df['H_s'] - df['H']

    df.to_csv(output_path + bible_filename.replace('.txt', '_entropies.csv'), index=False)


import numpy as np
import copy
from scipy import sparse

file = "day_12_input.txt"
# file = "day_12_input_test.txt"

with open(file) as f:
    lines = f.readlines()
    f.close()

lines_letters = [l.replace("\n", "") for l in lines]
lines_elevation = [
    [ord(x) % 32 if x not in ["S", "E"] else 0 for x in l] for l in lines_letters
]

elevation = np.stack([np.array([*l], dtype=int) for l in lines_elevation], axis=1)
letters = np.stack([np.array([*l], dtype=str) for l in lines_letters], axis=1)

elevation = elevation.T
letters = letters.T

start = tuple(np.argwhere(letters == "S")[0])
end = tuple(np.argwhere(letters == "E")[0])

elevation[letters == "E"] = 26
elevation[letters == "S"] = 0
directions = ["u", "d", "l", "r"]

width = elevation.shape[1]
length = elevation.shape[0]

global directions
global elevation
global width
global length

def next_location(state, direction):
    if direction == "u":
        new = (state[0] - 1, state[1])
    if direction == "d":
        new = (state[0] + 1, state[1])
    if direction == "l":
        new = (state[0], state[1] - 1)
    if direction == "r":
        new = (state[0], state[1] + 1)
    return new

def is_in_map(state):
    max_x = elevation.shape[0]
    max_y = elevation.shape[1]
    x_valid = (state[0] >= 0) & (state[0] < max_x)
    y_valid = (state[1] >= 0) & (state[1] < max_y)
    return x_valid & y_valid

def is_possible(state, new):
    return elevation[new] - elevation[state] <= 1

def get_adjacent(state):
    adjacent = []
    for direction in directions:
        new = next_location(state, direction)
        if is_in_map(new):
            if is_possible(state, new):
                adjacent.append(new)
    return adjacent

def idx(position):
    return position[0] * width + position[1]

n = elevation.shape[0] * elevation.shape[1]
A = np.zeros((n, n), dtype=int)

for i in range(length):
    for j in range(width):
        adjacent = get_adjacent((i, j))
        for a in adjacent:
            A[idx((i, j)), idx(a)] = 1

B = A.copy()
A @ A
AA = sparse.csr_matrix(A)
BB = sparse.csr_matrix(B)

## test solution works
## Normal solution does not
## why?
## https://galaxyinferno.com/how-to-solve-advent-of-code-2022-day-12-with-python/

steps = 1
while BB.toarray()[idx(start), idx(end)] == 0 and steps < 1000:
    BB = BB @ AA
    steps += 1
    if steps % 50 == 0:
        print(steps)

steps


# 整数N
N = int(input())

# 5N人の特典
X = list(map(int, input().split()))

# 最小値をN回削除
[X.remove(min(X)) for _ in range(N)]

# 最大値をN回削除
[X.remove(max(X)) for _ in range(N)]

print(sum(X) / len(X))


import graph_tool as gt
import json
from random import sample

net = gt.load_graph('citenet0.out.gt')

core_pmap = net.vp['core']
core = [vertex for vertex in net.vertices() if core_pmap[vertex]]
downstream = core_pmap.copy()
gt.infect_vertex_property(net, downstream, vals = [True])

boundary_pmap = net.new_vp('bool',
							vals = [downstream[vertex] and not core_pmap[vertex]
									for vertex in net.vertices()])
boundary = [vertex for vertex in net.vertices() if boundary_pmap[vertex]]

core_dois = [net.vp['doi'][vertex] for vertex in core]
core_sids = [net.vp['sid'][vertex] for vertex in core]

core_refs = {}
for paper in boundary:
	core_ref_sids = [sid for sid in net.vp['references'][paper] if sid in core_sids]
	core_ref_papers = [paper for paper in core if net.vp['sid'][paper] in core_ref_sids]
	core_ref_dois = {net.vp['doi'][paper]: 0 for paper in core_ref_papers}

	core_refs[net.vp['doi'][paper]] = core_ref_dois

print('Total boundary items: ' + str(len(boundary)))

boundary_subset = sample(boundary, 25)
boundary_subset_dois = [net.vp['doi'][paper] for paper in boundary_subset]
core_refs_subset = {key:value for key, value in core_refs.items() if key in boundary_subset_dois}
print('Total subset items: ' + str(len(boundary_subset)))

with open('boundary.output.json', 'w') as outfile:
	json.dump(core_refs_subset, outfile, indent = 4)


import configparser, os

PATH = 'config.cfg'
DEFAULTS = {
    'main': {
        'debug': True,
        'interpreter': False,
    },
        'graphics': {
            'hwaccel': True,
    }
}
skip_file = False

config = configparser.ConfigParser()

if os.path.isfile(PATH) and not skip_file:
    config.read_file(open('config.cfg'))
else:
    config.read_dict(DEFAULTS)


import datetime

class Restaurant:
    def __init__(self, restaurant_name, cuisine_type):
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type
        self.number_served = 0

    def describe_restaurant(self):
        print('------------------------------------------------')
        print(f'Restaurant name: {self.restaurant_name}')
        print(f'Cuisine type: {self.cuisine_type}')
        print(f'Clients served: {self.number_served}')
        print('------------------------------------------------')
        print()

    def open_restaurant(self):
        print('------------------ NOW OPEN --------------------')
        print(f'{self.restaurant_name:^48s}')
        print('------------------------------------------------')
        print()

    def set_number_served(self, value):
        self.number_served = value

    def increment_number_served(self, increment):
        self.number_served += increment

def task01():
    print("=========================\nTask 1\n-------------------------")
    restaurant = Restaurant('Colombian Express', 'Typical colombian food')
    restaurant.describe_restaurant()
    restaurant.open_restaurant()

def task02():
    print("=========================\nTask 2\n-------------------------")
    restaurants = [
        Restaurant('Colombian Express', 'Typical colombian food'),
        Restaurant('Sushi bar', 'Japanese food'),
        Restaurant('Canadian Hub', 'Poutine and Canadian food'),
    ]
    for restaurant in restaurants:
        restaurant.describe_restaurant()
        restaurant.open_restaurant()

class User:
    instance_count = 0

    def __init__(self, user_id, first_name, last_name):
        self.user_id = user_id
        self.first_name = first_name
        self.last_name = last_name
        self.created_on = datetime.date(2019, 11, 15)
        self.last_login_date = datetime.date(2020, 10, 28)
        self.active = True
        self.login_attempts = 0
        User.instance_count += 1

    def summary(self):
        print(f'User id: {self.user_id}')
        print(f'First Name: {self.first_name}')
        print(f'Last Name: {self.last_name}')
        print(f'Last login: {self.last_login_date}')
        print(f'Login attempts: {self.login_attempts}')
        print(f'Status: {"Active" if self.active else "Inactive"}')
        print(f'Created on: {self.created_on.isoformat()}')
        print('------------------------------------------------')

    def greet(self):
        time_from_last_login = datetime.date.today() - self.last_login_date
        print(f'Welcome back {self.first_name} {self.last_name}')
        print(f'Has been {time_from_last_login.days} days since your last login.')
        print('------------------------------------------------')

    def increment_login_attempts(self):
        self.login_attempts += 1

    def reset_login_attempts(self):
        self.login_attempts = 0

def task03():
    print("=========================\nTask 3\n-------------------------")
    users = [
        User('diegoortizmatajira', 'Diego', 'Ortiz'),
        User('mr_robot', 'Elliot', 'Alderson'),
        User('neo', 'Thomas', 'Anderson'),
    ]
    for user in users:
        print('\n************************************************')
        user.summary()
        user.greet()

class Car:
    def __init__(self, make, model, year):
        """Initialize attributes to describe a car."""
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_descriptive_name(self):
        """Return a neatly formatted descriptive name."""
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()  # titleCased value

    def read_odometer(self):
        """Print a statement showing the car's mileage."""
        print(f"This car has {self.odometer_reading} miles on it. ")

    def drive_distance(self, distance):
        self.odometer_reading += distance

def task_odometer():
    print("=========================\nTask Odometer\n-------------------------")
    my_new_car = Car('audi', 'a4', 2019)
    print(my_new_car.get_descriptive_name())
    my_new_car.read_odometer()
    my_new_car.drive_distance(50)
    my_new_car.read_odometer()
    my_new_car.drive_distance(140)
    my_new_car.read_odometer()

def task04():
    print("=========================\nTask 4\n-------------------------")
    restaurant = Restaurant('Colombian Express', 'Typical colombian food')
    restaurant.describe_restaurant()
    print('Set number served = 150')
    restaurant.set_number_served(150)
    restaurant.describe_restaurant()
    print('Increment number served by 10')
    restaurant.increment_number_served(10)
    restaurant.describe_restaurant()

def task05():
    print("=========================\nTask 5\n-------------------------")
    user = User('diegoortizmatajira', 'Diego', 'Ortiz')
    user.summary()
    print('Perform one login attempt\n')
    user.increment_login_attempts()
    user.summary()
    print('Perform one login attempt\n')
    user.increment_login_attempts()
    user.summary()
    print('Perform reset to login attempts counter\n')
    user.reset_login_attempts()
    user.summary()

def task06():
    print("=========================\nTask 6\n-------------------------")
    users = [
        User('diegoortizmatajira', 'Diego', 'Ortiz'),
        User('mr_robot', 'Elliot', 'Alderson'),
        User('neo', 'Thomas', 'Anderson'),
    ]
    print(f'Number of instances: {users[0].instance_count}')

task01()
task02()
task03()
task_odometer()
task04()
task05()
task06()


import pytest

from api.community import choices, factories, selectors

@pytest.mark.django_db
class TestCommunitySelectors:
    def test_filter_company_hashtags(self):
        h_1 = factories.HashtagFactory(slug="a")
        h_2 = factories.HashtagFactory(slug="b")

        _ = factories.CompanyFactory(slug="a", current_revision__hashtags=[h_1])
        company_2 = factories.CompanyFactory(slug="b", current_revision__hashtags=[h_2])
        company_3 = factories.CompanyFactory(
            slug="c", status=choices.ModerationStatus.REJECTED.name
        )

        qs = selectors.get_companies()

        rv = selectors.filter_companies(qs, None, ["b"], None)
        assert rv.count() == 1
        assert rv.first().slug == company_2.slug

        rv = selectors.filter_companies(qs, company_2.current_revision.name, None, None)
        assert rv.count() == 1
        assert rv.first().slug == company_2.slug

        rv = selectors.filter_companies(
            qs, None, None, choices.ModerationStatus.REJECTED.name
        )
        assert rv.count() == 1
        assert rv.first().slug == company_3.slug


# do analysis on the layer

from fileIterables import allFilesInRecurseByType, getNameFromPath
from statistics import pstdev as stddev
from statistics import mean

Layer_DIR = "layerSampleSet"
LFILE_TYPE = "lyr"

class Stats:
    def __init__(self):
        self.segments = 0
        self.pointsMean = 0
        self.pointsDev = 0

statsList = []
#how many times is the most visited point visited?
mostVisitedPointQty = 0
mostVisitedPointPoint = (None, None)
mostVisitedPointFile = ""

for filePath in allFilesInRecurseByType(Layer_DIR, LFILE_TYPE):
    with open(filePath) as f:
        stats = Stats()

        segCounter = 0

        uniquePoints = 0
        pointsDict = {}

        for line in f:
            tokens = line.strip().split(" ")

            tokens_int = list(map(lambda x: round(float(x)*10000), tokens))

            for t in tokens_int:
                if t%10 != 0:
                    print(tokens)
                    raise ValueError(f"need more rounding precision: {t} {filePath}")

            p1 = (tokens_int[0], tokens_int[1])
            p2 = (tokens_int[2], tokens_int[3])

            for p in [p1,p2]:
                if p not in pointsDict:
                    pointsDict[p] = 1
                    uniquePoints += 1
                else:
                    pointsDict[p] += 1

            segCounter += 1

        for k in pointsDict:
            if(pointsDict[k] > mostVisitedPointQty):
                mostVisitedPointQty = pointsDict[k]
                mostVisitedPointFile = filePath
                mostVisitedPointPoint = k

        stats.segments = segCounter
        stats.pointsMean = mean(map(lambda x: pointsDict[x], pointsDict))
        stats.pointsDev = stddev(map(lambda x: pointsDict[x], pointsDict))
        statsList.append(stats)

segMean = mean(map(lambda x: x.segments, statsList))
segDev = stddev(map(lambda x: x.segments, statsList))
pointsMeanMean = mean(map(lambda x: x.pointsMean, statsList))
pointsMeanDev = stddev(map(lambda x: x.pointsMean, statsList))
pointsDevMean = mean(map(lambda x: x.pointsDev, statsList))
pointsDevDev = stddev(map(lambda x: x.pointsDev, statsList))

print(f"SM : {segMean}")
print(f"SD : {segDev}")
print(f"PMM: {pointsMeanMean}")
print(f"PMD: {pointsMeanDev}")
print(f"PDM: {pointsDevMean}")
print(f"PDD: {pointsDevDev}")
print("")
print(f"MVPQ: {mostVisitedPointQty}")
print(f"MVPP: {mostVisitedPointPoint}")
print(f"MVPF: {mostVisitedPointFile}")


import os

from src.lib.io import file_read

def reader(filename):
    datafile = []
    with open(filename, "r") as file:
        for line in file.read().splitlines():
            datafile.append(line)
    return datafile

NAME = "ZLN170_2-6_neg"
BAD_HEADER = "28Si\t\t\t\t\t31P"
BAD_POINTS = [
    "4.53333E-002\t\t9.40730E+006\t8.93333E-002\t\t1.27277E+005",
    "1.78667E-001\t\t7.83114E+007\t2.06667E-001\t\t2.21947E+005",
    "2.96000E-001\t\t9.50838E+007\t3.24000E-001\t\t2.93436E+005",
]
HEADER = ["Time", "28Si", "31P"]
POINTS = [
    [4.53333e-002, 9.40730e006, 1.27277e005],
    [1.78667e-001, 7.83114e007, 2.21947e005],
    [2.96000e-001, 9.50838e007, 2.93436e005],
]

test_file = os.path.join(os.path.dirname(__file__), "files/simple.dp_rpc_asc")

def test_find_file_name():
    expected = NAME
    assert file_read._find_file_name(reader(test_file)) == expected

def test_cut_header_and_points():
    expected = (BAD_HEADER, BAD_POINTS)
    assert file_read._cut_header_and_points(reader(test_file)) == expected

def test_reshape_ion_string():
    expected = HEADER
    assert file_read._reshape_ion_string(BAD_HEADER) == expected

def test_reshape_points():
    expected = POINTS
    assert file_read._reshape_points(BAD_POINTS) == expected