import state
import objects
import itertools
import board
import copy
import time

class MDP:

    def __init__ (self, startingState, reward, livingReward, iterations = None):
        # Variables that change the AI behavior
        self.rewardDiscount = reward
        self.livingReward = livingReward
        self.iterations = iterations if iterations != None else 10

        self.intendedActionProbability = 0.8    # intended action succeeds 80% of the time
        self.unintendedActionProbability = 0.2  # unintended action occurs 20% of the time. This will be split by the number of unintended actions available in a state

        self.currentState = startingState

        self.states = list()                # contains all the valid states of the model
        self.policyTable = dict()           # this will be a dictionary of (state : action) pairs. This will be updated by value iteration and q-learning
        self.currentStateValues = dict()    # dictionary of (State : float) pairs. Used for value iteration. This will hold V_K values
        self.nextStates = dict()            # dictionary of (state, action) keys that returns the State that (s,a) will go to.
        self.transitionFunctions = dict()   # will contain (s,a) tuple for the key and returns a list of (action, probability) tuples
        self.rewardFunctions = dict()       # will contain (s,a,s') tuple for the key and a reward value

        self.initializeStates()                         # initialize all the states that exist in the MDP
        self.initializeNextStateTableAndRewardTable()   # initialize table of next states given original state and R(s,a,s') for all states and actions
        self.initializeTransitionFunctions()            # initialize T(s,a,s') for all states and actions

        start = time.time()
        self.valueIteration()
        end = time.time()
        print (end - start)

    def initializeStates(self):
        # iterates over the board and creates every valid state that exists in the MDP.
        # this is gonna be computationally expensive as shit.

        # get all possible player, and key positions. Positions are stored as a tuple of (x, y) coordinates.
        # Note that these are ALL positions each of these items can occupy.
        playerPos = list()
        keyPos = list()

        # get player positions
        for x in range(0, len(objects.board.tiles)):
            for y in range(0, len(objects.board.tiles[0])):

                if objects.board.tiles[x][y].isWall():
                    continue

                # if this tile is avalid player position, add it to list.
                playerPos.append((x, y))

        # get all valid combinations of key positions.
        keyList = self.getKeyPositionCombinations()

        # populate list of all possible states
        stateList = list(itertools.product(playerPos, keyList))

        for newState in stateList:
            stateObj = state.State(newState[0], newState[1])
            self.states.append(stateObj)
            self.currentStateValues[stateObj] = 0   # initialize state's value to 0 in the dictionary

        self.currentStateValues[None] = 0   # this will be used for the exit state

        # for key, val in self.currentStateValues.items():
        #     print key
        #     print val

    def initializeNextStateTableAndRewardTable(self):
        for currentState in self.states:
            # iterate over all states
            for action in self.getActionVector(currentState, objects.board):
                nextState, reward = self.getNextStateAndReward(currentState, action)
                self.nextStates[(currentState, action)] = nextState
                self.rewardFunctions[(currentState, action, nextState)] = reward

    def initializeTransitionFunctions(self):

        # iterate over all the states
        for newState in self.states:
            actionVector = self.getActionVector(newState, objects.board)

            if len(actionVector) == 1:
                transitionProbabilityList = [(actionVector[0], 0.8)]
                self.transitionFunctions[(newState, actionVector[0])] = transitionProbabilityList
            else:
                # set the main action to 80% probability and the rest to 20% / size of the remaining possible actions.
                for action in actionVector:
                    mainAction = (action, self.intendedActionProbability)

                    remainingProbability = self.unintendedActionProbability / (len(actionVector) - 1)    # calculates probability for any action that isn't the main action
                    transitionProbabilityList = [mainAction]

                    for newAction in actionVector:
                        if newAction == action:
                            continue

                    transitionProbabilityList.append((newAction, remainingProbability))

                    self.transitionFunctions[(newState, action)] = transitionProbabilityList

    def getActionVector(self, currentState, board):
        # helper function called by valueIteration() to get a vector of valid directions from the position passed.
        # NOTE: playerPos is a tuple of (x, y) type. So playerPos[0] gives x value and playerPos[1] gives y value
        x = currentState.playerPos[0]
        y = currentState.playerPos[1]

        validMoves = ["Left", "Right", "Up", "Down", "Stay"]

        if board.tiles[x][y].isExit() and all(val == None for val in currentState.keyPositions):
            validMoves = ["Exit"]   # player is on exit and has all the keys, exit is the only right move.
            return validMoves

		# rule out which actions we can take depending on current and next x, y positions. Based on implementation in key.py
        if x == 0 or board.tiles[x - 1][y].isWall():
            validMoves.remove("Left")
        if x == board.width - 1 or board.tiles[x + 1][y].isWall():
        	validMoves.remove("Right")
        if y == 0 or board.tiles[x][y - 1].isWall():
        	validMoves.remove("Up")
        if y == board.height - 1 or board.tiles[x][y + 1].isWall():
            validMoves.remove("Down")

        return validMoves

    def getNextStateAndReward(self, originalState, action):
        # calculates next state and reward value based on action taken in originalState
        # value is returned as a tuple (nextState, rewardValue)

        # these bools track if player died or got a key taking this action

        if action == "Exit":
            # if we can exit, return 100 reward
            return (None, 100)
        if action == "Stay":
            # if we stay, return the state we were just in
            return (originalState, self.livingReward)

        totalReward = 0 # track the reward we end up getting for taking this action
        xDirection = 0
        yDirection = 0

        # create temporary movement variables so player isn't actually effected
        playerX = originalState.playerPos[0]
        playerY = originalState.playerPos[1]
        tempBoard = copy.deepcopy(objects.board) # create a copy of the board
        nextState = None
        resultingKeyPositionList = copy.deepcopy(originalState.keyPositions) # this list will be updated if keys are acquired taking this action

        # assign keys to the board
        for key in tempBoard.keys:
            tempBoard.tiles[key.x][key.y].key = False
        for keyPos in originalState.keyPositions:
            if keyPos is None:
                continue
            tempBoard.tiles[keyPos[0]][keyPos[1]].key = True

        tempKeyCount = 0

        for key in originalState.keyPositions:
            if key == None:
                tempKeyCount += 1 # if a key is set to None in the key vector, add to the key count

        # note that the x, y origin is at the top-left, which is why UP is -1 in the y direction.
        xDirection = self.getXDirection(action)
        yDirection = self.getYDirection(action)

        while((yDirection != 0 or xDirection != 0)
		and (playerY + yDirection >= 0 and playerY + yDirection < objects.board.height)
		and (playerX + xDirection >= 0 and playerX + xDirection < objects.board.width)
		and not (objects.board.tiles[playerX + xDirection][playerY + yDirection].isWall())):
            playerX += xDirection
            playerY += yDirection

            if tempBoard.tiles[playerX][playerY].hasKey():
                totalReward += 10

                # iterate over key position list and set the key that was acquired to None
                for index, keyPos in enumerate(resultingKeyPositionList):
                    if keyPos is None:
                        continue

                    if keyPos[0] == playerX and keyPos[1] == playerY:
                        resultingKeyPositionList[index] = None

            if tempBoard.tiles[playerX][playerY].isLava():
                totalReward -= 1000

            if objects.board.tiles[playerX][playerY].isWormhole():
                wormhole = objects.board.tiles[playerX][playerY]
                playerX = wormhole.exit.exitX
                playerY = wormhole.exit.exitY
                xDirection = self.getXDirection(wormhole.translateDirection(action))
                yDirection = self.getYDirection(wormhole.translateDirection(action))
                continue

        totalReward += self.livingReward
        nextState = state.State((playerX, playerY), resultingKeyPositionList)
        # self.rewardFunctions[(originalState, action, nextState)] = totalReward
        return (nextState, totalReward)

    def getXDirection(self, newDirection):
        if newDirection == "Right":
            return 1
        elif newDirection == "Left":
            return -1

        return 0

    def getYDirection(self, newDirection):
        if newDirection == "Down":
            return 1
        elif newDirection == "Up":
            return -1

        return 0

    def valueIteration(self):
        # perform value iteration
        # iterate 100 times over all states and update values
        for i in range(0, self.iterations):
            # grab our kth dictionary of values
            previousStateValues = copy.deepcopy(self.currentStateValues)

            for currentState in self.states:
                actionVector = self.getActionVector(currentState, objects.board)
                actionValues = dict()   # will track (action : value) key-value pairs. Will take argmax after getting all values

                # iterate over each action and append values to actionValues dictionary
                for action in actionVector:
                    # calculate T(s, a, s') * (R(s, a, s') + rewardDiscount(V_K(s')))
                    actionValues[action] = 0

                    # T(s,a,s') returns 0.8 for intented action and the remaining actions that are possible take up the remaining 20% combined.
                    for newAction, probability in self.transitionFunctions[(currentState, action)]:
                        # if intended action is right, right will succeed at 0.8, up, down, left, and stay will succeed with 0.05
                        nextState = self.nextStates[(currentState, newAction)]
                        reward = self.rewardFunctions[(currentState, newAction, nextState)]
                        actionValues[action] += probability * (reward + (self.rewardDiscount * previousStateValues[nextState]))

                self.currentStateValues[currentState] = max(actionValues.values()) # Update state value to new values that were just calculated.
                self.policyTable[currentState] = max(actionValues, key=actionValues.get) # update policy of currentState to the best action from the calculation

    def getKeyPositionCombinations(self):
        # get key positions for each key. We have min and max x,y positions for each key that must be considered
        counter = 0
        keyPos = [list() for x in range(0, len(objects.board.keys))]

        for key in objects.board.keys:
            for x in range(key.xmin, key.xmax + 1):
                for y in range(key.ymin, key.ymax + 1):
                    if objects.board.tiles[x][y].isWall():
                        # wall tiles are not valid key positions
                        continue

                    keyPos[counter].append((x, y)) # add a position for this specific key.

            keyPos[counter].append(None)
            counter += 1

        # get cartesian product of all key positions. This gives us all possible key position combinations
        keyCombos = list(set(itertools.product(*keyPos)))

        # Find entries that contain duplicate positions. Keys cannot be on top of one another.
        removeList = list()
        for i in range(0, len(keyCombos)):
            for j in range(0, len(objects.board.keys)):
                for k in range(0, len(objects.board.keys)):
                    if j == k:
                        continue
                    if keyCombos[i][j] == keyCombos[i][k] and (keyCombos[i][j] and keyCombos[i][k] != None):
                        removeList.append(keyCombos[i])
                        break

        return [list(positions) for positions in keyCombos if positions not in removeList]
        # print keyList

    def updateCurrentState(self, player, keys):
        keyVector = list()
        for key in keys:
            # check if the key has been acquired. If it has, we want to append None so the state can keep track properly
            if key.acquired:
                keyVector.append(None)
            else:
                keyVector.append((key.x, key.y))

        newState = state.State((player.x, player.y), keyVector)
        self.currentState = newState

    def getCurrentStateActionFromPolicy(self):
        # returns the best action for the current state of the MDP
        # print str(self.currentState) + " = " + str(self.currentStateValues[self.currentState])
        return self.policyTable[self.currentState]


import requests
from bs4 import BeautifulSoup

URL = "https://web.archive.org/web/20200518073855/https://www.empireonline.com/movies/features/best-movies-2/"

response = requests.get(url=URL)
arch_web_page = response.text

soup = BeautifulSoup(arch_web_page, "html.parser")
all_movies = soup.find_all(name='h3', class_='title')
movie_titles = [movie.getText() for movie in all_movies]
top_100_movie = movie_titles[::-1]

with open('movies.txt', 'w', encoding='utf-8') as movies:
    for movie in top_100_movie:
        movies.write(f"{movie}\n")


# Functions mmd2 and polynomial_kernel are adapted from
#   https://github.com/mbinkowski/MMD-GAN/blob/master/gan/compute_scores.py
#   Distributed under BSD 3-Clause: https://github.com/mbinkowski/MMD-GAN/blob/master/LICENSE

import numpy as np
import torch
from tqdm import tqdm

from torch_fidelity.helpers import get_kwarg, vassert, vprint
from torch_fidelity.utils import create_feature_extractor, extract_featuresdict_from_input_id_cached, \
    resolve_feature_extractor, resolve_feature_layer_for_metric

KEY_METRIC_KID_MEAN = 'kernel_inception_distance_mean'
KEY_METRIC_KID_STD = 'kernel_inception_distance_std'

def mmd2(K_XX, K_XY, K_YY, unit_diagonal=False, mmd_est='unbiased'):
    vassert(mmd_est in ('biased', 'unbiased', 'u-statistic'), 'Invalid value of mmd_est')

    m = K_XX.shape[0]
    assert K_XX.shape == (m, m)
    assert K_XY.shape == (m, m)
    assert K_YY.shape == (m, m)

    # Get the various sums of kernels that we'll use
    # Kts drop the diagonal, but we don't need to compute them explicitly
    if unit_diagonal:
        diag_X = diag_Y = 1
        sum_diag_X = sum_diag_Y = m
    else:
        diag_X = np.diagonal(K_XX)
        diag_Y = np.diagonal(K_YY)

        sum_diag_X = diag_X.sum()
        sum_diag_Y = diag_Y.sum()

    Kt_XX_sums = K_XX.sum(axis=1) - diag_X
    Kt_YY_sums = K_YY.sum(axis=1) - diag_Y
    K_XY_sums_0 = K_XY.sum(axis=0)

    Kt_XX_sum = Kt_XX_sums.sum()
    Kt_YY_sum = Kt_YY_sums.sum()
    K_XY_sum = K_XY_sums_0.sum()

    if mmd_est == 'biased':
        mmd2 = ((Kt_XX_sum + sum_diag_X) / (m * m)
              + (Kt_YY_sum + sum_diag_Y) / (m * m)
              - 2 * K_XY_sum / (m * m))
    else:
        mmd2 = (Kt_XX_sum + Kt_YY_sum) / (m * (m-1))
        if mmd_est == 'unbiased':
            mmd2 -= 2 * K_XY_sum / (m * m)
        else:
            mmd2 -= 2 * (K_XY_sum - np.trace(K_XY)) / (m * (m-1))

    return mmd2

def polynomial_kernel(X, Y, degree=3, gamma=None, coef0=1):
    if gamma is None:
        gamma = 1.0 / X.shape[1]
    K = (np.matmul(X, Y.T) * gamma + coef0) ** degree
    return K

def polynomial_mmd(features_1, features_2, degree, gamma, coef0):
    k_11 = polynomial_kernel(features_1, features_1, degree=degree, gamma=gamma, coef0=coef0)
    k_22 = polynomial_kernel(features_2, features_2, degree=degree, gamma=gamma, coef0=coef0)
    k_12 = polynomial_kernel(features_1, features_2, degree=degree, gamma=gamma, coef0=coef0)
    return mmd2(k_11, k_12, k_22)

def kid_features_to_metric(features_1, features_2, **kwargs):
    assert torch.is_tensor(features_1) and features_1.dim() == 2
    assert torch.is_tensor(features_2) and features_2.dim() == 2
    assert features_1.shape[1] == features_2.shape[1]

    kid_subsets = get_kwarg('kid_subsets', kwargs)
    kid_subset_size = get_kwarg('kid_subset_size', kwargs)
    verbose = get_kwarg('verbose', kwargs)

    n_samples_1, n_samples_2 = len(features_1), len(features_2)
    vassert(
        n_samples_1 >= kid_subset_size and n_samples_2 >= kid_subset_size,
        f'KID subset size {kid_subset_size} cannot be smaller than the number of samples (input_1: {n_samples_1}, '
        f'input_2: {n_samples_2}). Consider using "kid_subset_size" kwarg or "--kid-subset-size" command line key to '
        f'proceed.'
    )

    features_1 = features_1.cpu().numpy()
    features_2 = features_2.cpu().numpy()

    mmds = np.zeros(kid_subsets)
    rng = np.random.RandomState(get_kwarg('rng_seed', kwargs))

    for i in tqdm(
            range(kid_subsets), disable=not verbose, leave=False, unit='subsets',
            desc='Kernel Inception Distance'
    ):
        f1 = features_1[rng.choice(n_samples_1, kid_subset_size, replace=False)]
        f2 = features_2[rng.choice(n_samples_2, kid_subset_size, replace=False)]
        o = polynomial_mmd(
            f1,
            f2,
            get_kwarg('kid_degree', kwargs),
            get_kwarg('kid_gamma', kwargs),
            get_kwarg('kid_coef0', kwargs),
        )
        mmds[i] = o

    out = {
        KEY_METRIC_KID_MEAN: float(np.mean(mmds)),
        KEY_METRIC_KID_STD: float(np.std(mmds)),
    }

    vprint(verbose, f'Kernel Inception Distance: {out[KEY_METRIC_KID_MEAN]} ± {out[KEY_METRIC_KID_STD]}')

    return out

def kid_featuresdict_to_metric(featuresdict_1, featuresdict_2, feat_layer_name, **kwargs):
    features_1 = featuresdict_1[feat_layer_name]
    features_2 = featuresdict_2[feat_layer_name]
    metric = kid_features_to_metric(features_1, features_2, **kwargs)
    return metric

def calculate_kid(**kwargs):
    kwargs['kid'] = True
    feature_extractor = resolve_feature_extractor(**kwargs)
    feat_layer_name = resolve_feature_layer_for_metric('kid', **kwargs)
    feat_extractor = create_feature_extractor(feature_extractor, [feat_layer_name], **kwargs)
    featuresdict_1 = extract_featuresdict_from_input_id_cached(1, feat_extractor, **kwargs)
    featuresdict_2 = extract_featuresdict_from_input_id_cached(2, feat_extractor, **kwargs)
    metric = kid_featuresdict_to_metric(featuresdict_1, featuresdict_2, feat_layer_name, **kwargs)
    return metric


import numpy as np
from graphing.special_graphs.neural_trigraph.path_cover\
            import min_cover_trigraph
from graphing.special_graphs.bipartite.rand_graph import bipartite_edges

def neur_trig_edges(left=5, c=4, r=7, shuffle_p=1.0):
    edges1 = bipartite_edges(left, c, shuffle_p)
    edges2 = bipartite_edges(c, r, shuffle_p)
    edges2[:, 0] += left
    edges2[:, 1] += left
    return edges1, edges2

def rep_graph(l_size=7, mid_size=5, r_size=7, reps=42):
    """
    Creates a bigger tri-graph by repeating smaller graphs
    and concatenating all of them a set number of times.
    """
    # The min path cover will be at-least this size.
    trivial_size = max(l_size, mid_size, r_size)
    edges1_fin = []
    edges2_fin = []
    paths1 = []
    for i in range(reps):
        k = 0
        # Only select challenging graphs where min-paths >= trivial_size+2
        while (len(paths1) < trivial_size+2 and k < 100) and (len(paths1) < trivial_size+1 and k < 300):
            k += 1
            edges1, edges2 = neur_trig_edges(l_size,
                                             mid_size,
                                             r_size,
                                             shuffle_p=0.94)
            paths1 = min_cover_trigraph(edges1, edges2)
        edges1[:, 0] += l_size*i
        edges1[:, 1] += l_size * reps + mid_size*i - l_size
        edges2[:, 0] += l_size * reps + mid_size*i - l_size
        edges2[:, 1] += l_size * (reps-1) + mid_size * (reps-1) + r_size*i
        paths1 = []
        if i == 0:
            edges1_fin = np.copy(edges1)
            edges2_fin = np.copy(edges2)
        else:
            edges1_fin = np.concatenate((edges1_fin, np.copy(edges1)))
            edges2_fin = np.concatenate((edges2_fin, np.copy(edges2)))
    return edges1_fin, edges2_fin

if __name__ == "__main__":
    be = bipartite_edges(5, 4)
    print(be)
    tri = neur_trig_edges(5, 4, 8)
    print(tri)


from flask import request
from flask_restplus import Resource

from ..util.dto import CompanyDto
from ..service.company_service import save_new_company, get_all_companies, get_a_company, update_company, delete_a_company

api = CompanyDto.api
_company = CompanyDto.company

@api.route('/')
class CompanyList(Resource):
    @api.doc('list_of_companies for a company')
    @api.marshal_list_with(_company, envelope='data')
    def get(self):
        """List all companies"""
        return get_all_companies()

    @api.response(201, 'Company successfully created.')
    @api.doc('create a new company')
    @api.expect(_company, validate=True)
    def post(self):
        """Creates a new Company """
        data = request.json
        return save_new_company(data=data)

@api.route('/<company_id>')
@api.param('company_id', 'The Company identifier')
@api.response(404, 'Company not found.')
class Company(Resource):
    @api.doc('get a company')
    @api.marshal_with(_company)
    def get(self, company_id):
        """get a company given its identifier"""
        company = get_a_company(company_id)
        if not company:
            api.abort(404)
        else:
            return company

    @api.response(201, 'company successfully created.')
    @api.doc('update a company')
    @api.expect(_company, validate=True)
    def put(self, company_id):
        """Update a company """
        data = request.json
        return update_company(company_id, data)

    @api.response(201, 'company successfully deleted.')
    @api.doc('delete a company')
    def delete(self, company_id):
        """Delete a company """
        return delete_a_company(company_id)


from xen.xend.server.blkif import BlkifController
from xen.xend.XendLogging import log

phantomDev = 0;
phantomId = 0;

blktap_disk_types = [
    'aio',
    'sync',
    'vmdk',
    'ram',
    'qcow'
    ]

class BlktapController(BlkifController):
    def __init__(self, vm):
        BlkifController.__init__(self, vm)

    def frontendRoot(self):
        """@see DevController#frontendRoot"""

        return "%s/device/vbd" % self.vm.getDomainPath()

    def getDeviceDetails(self, config):
        (devid, back, front) = BlkifController.getDeviceDetails(self, config)

        phantomDevid = 0
        wrapped = False

        try:
            imagetype = self.vm.info['image']['type']
        except:
            imagetype = ""

        if imagetype == 'hvm':
            tdevname = back['dev']
            index = ['c', 'd', 'e', 'f', 'g', 'h', 'i', \
                     'j', 'l', 'm', 'n', 'o', 'p']
            while True:
                global phantomDev
                global phantomId
                import os, stat

                phantomId = phantomId + 1
                if phantomId == 16:
                    if index[phantomDev] == index[-1]:
                        if wrapped:
                            raise VmError(" No loopback block \
                                       devices are available. ")
                        wrapped = True
                        phantomDev = 0
                    else:
                        phantomDev = phantomDev + 1
                    phantomId = 1
                devname = 'xvd%s%d' % (index[phantomDev], phantomId)
                try:
                    info = os.stat('/dev/%s' % devname)
                except:
                    break

            vbd = { 'mode': 'w', 'device': devname }
            fn = 'tap:%s' % back['params']

            # recurse ... by creating the vbd, then fallthrough
            # and finish creating the original device

            from xen.xend import XendDomain
            dom0 = XendDomain.instance().privilegedDomain()
            phantomDevid = dom0.create_phantom_vbd_with_vdi(vbd, fn)
            # we need to wait for this device at a higher level
            # the vbd that gets created will have a link to us
            # and will let them do it there

        # add a hook to point to the phantom device,
        # root path is always the same (dom0 tap)
        if phantomDevid != 0:
            front['phantom_vbd'] = '/local/domain/0/backend/tap/0/%s' \
                                   % str(phantomDevid)

        return (devid, back, front)


from django.shortcuts import render
from django.shortcuts import render, get_object_or_404,  redirect
from django.http import HttpResponse , HttpResponseRedirect
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.db.models import Q
from django.contrib.auth.decorators import login_required
from datetime import datetime
from django.contrib.auth import update_session_auth_hash
from django.urls import reverse_lazy
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth import login , logout
from django.views.generic import View, UpdateView
from django.contrib import messages
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from django.template.loader import render_to_string
from django.utils.encoding import force_text
from django.utils.http import urlsafe_base64_decode

from . models import Profile
from . form_user import (EditProfileForm, ProfileForm)
from . signup_form import SignUpForm
from . import form_user
from . tokens import account_activation_token

from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView , DetailView
from django.views.generic.edit import CreateView, DeleteView, UpdateView

class UserView(View):
	model = Profile
	template_name = 'acc/user_index.html'

	def get(self,request,*args,**kwargs):
         Profile.objects.get_or_create(user=self.request.user)
         obj = Profile.objects.filter(user=request.user)
         context = {'obj' : obj}
         return render(request,self.template_name,context)

class EditProfile(View):
    model                    = Profile
    form_class               = EditProfileForm
    custom_form_classes      = ProfileForm
    template_name            = 'acc/edit_form.html'

    def get(self, request, *args, **kwargs):
        Profile.objects.get_or_create(user=self.request.user)
        form = self.form_class(instance=self.request.user)
        me = self.request.user
        if Profile.objects.filter(user=me).exists():
            custom_form  = self.custom_form_classes(instance=self.request.user.user)
        else:
            custom_form  = self.custom_form_classes()
        context = {
        'form':form,
        'custom_form': custom_form
        }
        return render(request, self.template_name, context)

    def post(self, request, *args, **kwargs):
        me = self.request.user
        if Profile.objects.filter(user=me).exists():
            custom_form = ProfileForm(request.POST, request.FILES,instance=self.request.user.user)
        else:
            custom_form = ProfileForm(request.POST, request.FILES)
        form = EditProfileForm(request.POST,instance=self.request.user)
        if form.is_valid() and custom_form.is_valid():
            django_form = form.save()
            custom_django_form = custom_form.save(False)
            custom_django_form.user = django_form
            custom_django_form.save()
            messages.success(request, ('Profile Updated successfully.'))
            return redirect('acc:index')

        return render(request, self.template_name, {'form' : form , 'custom_form' : custom_form})

class SignUpView(View):
    form_class = SignUpForm
    template_name = 'registration/signup.html'

    def get(self, request, *args, **kwargs):
        form = self.form_class()
        return render(request, self.template_name, {'form': form})

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        if form.is_valid():

            user = form.save(commit=False)
            user.is_active = False # Deactivate account till it is confirmed
            user.save()

            #create_custom_user_profile
            Profile.objects.get_or_create(user=user)

            current_site = get_current_site(request)
            site = current_site.domain
            subject = 'Activate Your %(site) Account'
            message = render_to_string('registration/account_activation_email.html', {
                'user': user,
                'domain': site,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'token': account_activation_token.make_token(user),
            })
            user.email_user(subject, message)

            messages.success(request, (''))
            messages.warning(request, ('The confirmation link was invalid, possibly because it has already been used.'))

            return redirect('login')

        return render(request, self.template_name, {'form': form})

class ActivateAccount(View):

    def get(self, request, uidb64, token, *args, **kwargs):
        try:
            uid = force_text(urlsafe_base64_decode(uidb64))
            user = User.objects.get(pk=uid)
        except (TypeError, ValueError, OverflowError, User.DoesNotExist):
            user = None

        if user is not None and account_activation_token.check_token(user, token):
            user.is_active = True
            Profile.user.email_confirmed = True
            user.save()
            login(request, user, backend='django.contrib.auth.backends.ModelBackend')
            messages.success(request, ('Your email has been confirmed.'))
            return redirect('home')
        else:
            messages.warning(request, ('The confirmation link was invalid, possibly because it has already been used.'))
            return redirect('home')

def DeactivateView(request):
    user = request.user
    user.is_active = False
    user.save()
    messages.success(request, ('Profile successfully disabled.'))
    return redirect('acc:index')

def DeleteAccView(request):
    user = request.user
    user.is_active = False
    user.delete()
    messages.success(request, ('Profile successfully deleted.'))
    return redirect('acc:index')

def Notice(request):
    return render(request, 'acc/notice.html')


from matplotlib import animation
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
import numpy as np
from numpy import pi, sqrt

import os, sys
sys.path.insert(0, os.path.abspath("./"))
from loadfiles import *

plt.rc("font", family="serif", size=16)
plt.rc("mathtext", fontset="cm")
plt.rc("lines", lw=2)

name = "3"
folder = "article/data/" + name + "/"
fnames = get_all_filenames_in_folder(folder)

for i, filename in enumerate(fnames):
    filename = filename[:-4]

    phit, param = load_file(folder, filename)

    u, a, b, phibar1, phibar2, N, L, T, dt = param
    dx = L / N
    x = np.linspace(0, L, N)

    fig = plt.figure(layout="constrained", figsize=(10,5))
    gs = GridSpec(2, 2, figure=fig)
    ax1 = fig.add_subplot(gs[0, 0])
    ax2 = fig.add_subplot(gs[:, 1])
    ax3 = fig.add_subplot(gs[1, 0])

    ax = [ax1, ax2, ax3]
    title = [filename_from_param(param).split('_')[i] for i in (0, 1, 3)]
    title[2] = "\\bar\\varphi" + title[2][3:]
    title[1] = "\\alpha" + title[1][1:]
    fig.suptitle("$" + ", ".join(title) + "$")

    sol1 = (1 + phibar1)*np.cos(2*x/L*2*np.pi) + phibar1
    sol2 = 2*np.sqrt(-phibar1-phibar1**2)*np.cos(x/L*2*np.pi)

    ax[0].plot(x, sol1, '-.', color='gray', alpha=1, label="sol", lw=5)
    ax[0].plot(x, sol2, '-.', color='gray', alpha=1, lw=5)

    p = phit[-1]
    ax[0].plot(x, p[:, 0], 'r-', label='$\\varphi_1$')
    ax[0].plot(x, p[:, 1], 'k-', label='$\\varphi_2$')
    ax[0].plot([0, L], [phibar1, phibar1], 'r--')
    ax[0].plot([0, L], [0, 0], 'k--')

    ax[0].set_xlim(0, L)
    ax[0].set_ylim(-1.2, 1.2)
    ax[0].set_ylabel("$\\varphi$")
    ax[0].legend(loc=1)

    d1 = p[:, 0] - sol1
    d2 = p[:, 1] - sol2
    dtot = (np.sum(np.abs(d1)) + np.sum(np.abs(d2))) * dx / L
    dmax = np.max([np.max(np.abs(d1)), np.max(np.abs(d2))])

    ax[2].plot(x, d1, 'r-', label='$\\Delta\\varphi_1$')
    ax[2].plot(x, d2, 'k-', label='$\\Delta\\varphi_2$')
    ax[2].set_xlim(0, L)
    ax[2].set_ylabel("$\\Delta\\varphi$")
    ax[2].set_xlabel("$x$")
    ax[2].legend()

    t = np.linspace(0, 2*pi)
    prange = 1.2
    ax[1].plot(0, phibar1, 'ro')
    ax[1].plot(np.cos(t), np.sin(t), 'k--')
    ax[1].set_xlim(-prange, prange)
    ax[1].set_ylim(-prange, prange)
    ax[1].plot([*p[:, 1], p[0, 1]], [*p[:, 0], p[0, 0]], 'r--.')
    ax[1].set_xlabel("$\\varphi_2$")
    ax[1].set_ylabel("$\\varphi_1$")

    ax[2].ticklabel_format(axis='y', scilimits=(1,-1))
    # plt.show()
    plt.savefig("fig/sol2_"+str(i)+".pdf")


#%% [markdown]
# # 灵活的数据读取

#%% [markdown]
# ## Dataset

#%%
from torch.utils.data import Dataset

#%%
# 定义一个子类叫 custom_dataset，继承与 Dataset
class custom_dataset(Dataset):
    def __init__(self, txt_path, transform=None):
        self.transform = transform # 传入数据预处理
        with open(txt_path, 'r') as f:
            lines = f.readlines()

        self.img_list = [i.split()[0] for i in lines] # 得到所有的图像名字
        self.label_list = [i.split()[1] for i in lines] # 得到所有的 label

    def __getitem__(self, idx): # 根据 idx 取出其中一个
        img = self.img_list[idx]
        label = self.label_list[idx]
        if self.transform is not None:
            img = self.transform(img)
        return img, label

    def __len__(self): # 总数据的多少
        return len(self.label_list)

#%%
txt_dataset = custom_dataset('./example_data/train.txt') # 读入 txt 文件

#%%
# 取得其中一个数据
data, label = txt_dataset[0]
print(data)
print(label)

#%%
# 再取一个
data2, label2 = txt_dataset[34]
print(data2)
print(label2)

#%% [markdown]
# 所以通过这种方式我们也能够非常方便的定义一个数据读入，同时也能够方便的定义数据预处理
#%% [markdown]
# ## DataLoader

#%%
from torch.utils.data import DataLoader

#%%
train_data1 = DataLoader(folder_set, batch_size=2, shuffle=True) # 将 2 个数据作为一个 batch

#%%
for im, label in train_data1: # 访问迭代器
    print(label)

#%% [markdown]
# 可以看到，通过训练我们可以访问到所有的数据，这些数据被分为了 5 个 batch，前面 4 个都有两个数据，最后一个 batch 只有一个数据，因为一共有 9 个数据，同时顺序也被打乱了
#%% [markdown]
# 下面我们用自定义的数据读入举例子

#%%
train_data2 = DataLoader(txt_dataset, 8, True) # batch size 设置为 8

#%%
im, label = next(iter(train_data2)) # 使用这种方式访问迭代器中第一个 batch 的数据

#%%
im

#%%
label

#%% [markdown]
# 现在有一个需求，希望能够将上面一个 batch 输出的 label 补成相同的长度，短的 label 用 0 填充，我们就需要使用 `collate_fn` 来自定义我们 batch 的处理方式，下面直接举例子

#%%
def collate_fn(batch):
    batch.sort(key=lambda x: len(x[1]), reverse=True) # 将数据集按照 label 的长度从大到小排序
    img, label = zip(*batch) # 将数据和 label 配对取出
    # 填充
    pad_label = []
    lens = []
    max_len = len(label[0])
    for i in range(len(label)):
        temp_label = label[i]
        temp_label += '0' * (max_len - len(label[i]))
        pad_label.append(temp_label)
        lens.append(len(label[i]))
    pad_label
    return img, pad_label, lens # 输出 label 的真实长度

#%% [markdown]
# 使用我们自己定义 collate_fn 看看效果

#%%
train_data3 = DataLoader(txt_dataset, 8, True, collate_fn=collate_fn) # batch size 设置为 8

#%%
im, label, lens = next(iter(train_data3))

#%%
im

#%%
label

#%%
lens

#%% [markdown]
# 可以看到一个 batch 中所有的 label 都从长到短进行排列，同时短的 label 都被补长了，所以使用 collate_fn 能够非常方便的处理一个 batch 中的数据，一般情况下，没有特别的要求，使用 pytorch 中内置的 collate_fn 就可以满足要求了


from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains

class Base:
    '''
    selenium api 封装
    '''
    def __init__(self, logger, driver=None):
        self.driver = driver
        self.timeout = 6
        self.t = 0.5
        self.logger = logger

    def _get_driver(self, driver):
        '''获取driver，判断用初始化的driver还是传入的driver，传入的优先级的driver优先级最高'''
        return driver or self.driver

    def _get_element(self, locator, element, driver):
        '''判断传入的是locator还是element；返回element; 只传其中一个'''
        if element:
            return element
        return self.find_element(locator, driver)

    def find_element(self, locator, driver=None):
        '''
        定位元素
        返回定位到的元素，没定位到则抛timeout异常
        locator： ('id', 'kw')/('css selector', 'input#kw')
         ID = "id"
        XPATH = "xpath"
        LINK_TEXT = "link text"
        PARTIAL_LINK_TEXT = "partial link text"
        NAME = "name"
        TAG_NAME = "tag name"
        CLASS_NAME = "class name"
        CSS_SELECTOR = "css selector"
        '''
        if not isinstance(locator, tuple):
            self.logger.error('locator参数类型错误，必须传元祖类型：loc = ("id", "value1")')
            raise Exception('locator参数类型错误，必须传元祖类型：loc = ("id", "value1")')
        driver = self._get_driver(driver)
        try:
            element = WebDriverWait(driver, self.timeout, self.t).until(EC.presence_of_element_located(locator))
            self.logger.info("定位元素信息：定位方式->%s, value值->%s"%(locator[0], locator[1]))
        except Exception:
            self.logger.error("定位方式报错->%s, value值->%s"%(locator[0], locator[1]), exc_info=True)
            #raise Exception("定位方式报错->%s, value值->%s"%(locator[0], locator[1]))
            return False
        else:
            return element

    def find_elements(self, locator, driver=None):
        # 定位元素, 返回元素[]
        if not isinstance(locator, tuple):
            self.logger.error('locator参数类型错误，必须传元祖类型：loc = ("id", "value1")')
            raise Exception('locator参数类型错误，必须传元祖类型：loc = ("id", "value1")')
        driver = self._get_driver(driver)
        try:
            elements = WebDriverWait(driver, self.timeout, self.t).until(EC.presence_of_all_elements_located(locator))
            self.logger.info("定位元素信息：定位方式->%s, value值->%s"%(locator[0], locator[1]))
            return elements
        except Exception:
            self.logger.error("查找元素报错->%s, value值->%s"%(locator[0], locator[1]), exc_info=True)

    def send_keys(self, locator=None, text='', element=None, driver=None):
        driver = self._get_driver(driver)
        element = self._get_element(locator, element, driver)
        element.send_keys(text)
        self.logger.info("输入信息：%s"% text)

    def click(self, locator=None, element=None, driver=None):
        driver = self._get_driver(driver)
        element = self._get_element(locator, element, driver)
        element.click()
        self.logger.info("点击元素")

    def clear(self, locator=None, element=None, driver=None):
        driver = self._get_driver(driver)
        element = self._get_element(locator, element, driver)
        element.clear()
        self.logger.info("清空输入框")

    def is_selected(self, locator=None, element=None, driver=None):
        '''判断元素是否被选中，返回bool值'''
        driver = self._get_driver(driver)
        element = self._get_element(locator, element, driver)
        r = element.is_selected()
        self.logger.info("元素是否被选中:%s" %r)
        return r

    def is_enabled(self, locator=None, element=None, driver=None):
        '''判断input\select等元素是否可编辑状态，返回bool值'''
        driver = self._get_driver(driver)
        element = self._get_element(locator, element, driver)
        r = element.is_enabled()
        self.logger.info("元素是否可编辑：%s" %r)
        return r

    def is_element_exist(self, locator=None, element=None, driver=None):
        '''判断元素是否存在，返回bool值'''
        driver = self._get_driver(driver)
        try:
            self._get_element(locator, element, driver)
            self.logger.info("元素存在")
            return True
        except:
            self.logger.info("元素不存在")
            return False

    def is_title(self, title='', driver=None):
        '''判断标题是否相同，返回bool'''
        driver = self._get_driver(driver)
        try:
            result = WebDriverWait(driver, self.timeout, self.t).until(EC.title_is(title))
            self.logger.info('标题相同：%s'%title)
            return result
        except:
            self.logger.info('标题不相同：%s' % title)
            return False

    def is_title_contains(self, title='', driver=None):
        '''判断标题是否包含，返回bool'''
        driver = self._get_driver(driver)
        try:
            result = WebDriverWait(driver, self.timeout, self.t).until(EC.title_contains(title))
            self.logger.info('标题包含：%s' % title)
            return result
        except:
            self.logger.info('标题没有包含：%s' % title)
            return False

    def is_element_contains_text(self, locator, text='', driver=None):
        '''判断元素是否包含预期的字符串，返回bool'''
        if not isinstance(locator, tuple):
            self.logger.error('locator参数类型错误，必须传元祖类型：loc = ("id", "value1")')
            raise Exception('locator参数类型错误，必须传元祖类型：loc = ("id", "value1")')
        driver = self._get_driver(driver)
        try:
            result = WebDriverWait(driver, self.timeout, self.t).until(EC.text_to_be_present_in_element(locator, text))
            self.logger.info('元素文本值包含：%s'%text)
            return result
        except:
            self.logger.info('元素文本值没有包含：%s' % text)
            return False

    def is_elementValue_contains_value(self, locator, value='', driver=None):
        '''判断元素的value属性值是否包含预期的value，返回bool'''
        if not isinstance(locator, tuple):
            self.logger.error('locator参数类型错误，必须传元祖类型：loc = ("id", "value1")')
            raise Exception('locator参数类型错误，必须传元祖类型：loc = ("id", "value1")')
        driver = self._get_driver(driver)
        try:
            result = WebDriverWait(driver, self.timeout, self.t).until(EC.text_to_be_present_in_element_value(locator, value))
            self.logger.info('元素的value属性值包含：%s'%value)
            return result
        except:
            self.logger.info('元素的value属性值没有包含：%s' % value)
            return False

    def is_alert(self, timeout=3, driver=None):
        '''判断alert,存在返回alert实例，不存在，返回false'''
        driver = self._get_driver(driver)
        try:
            result = WebDriverWait(driver, timeout, self.t).until(EC.alert_is_present())
            self.logger.info('有alert弹框')
            return result
        except:
            self.logger.info('没有alert弹框')
            return False

    def get(self, url, driver=None):
        '''打开地址'''
        driver = self._get_driver(driver)
        driver.get(url)
        self.logger.info('打开url：%s'%url)

    def refresh(self, driver=None):
        '''刷新页面'''
        driver = self._get_driver(driver)
        driver.refresh()
        self.logger.info('刷新页面')

    def forward(self, driver=None):
        '''跳转到下一页'''
        driver = self._get_driver(driver)
        driver.forward()
        self.logger.info('跳转下一页')

    def back(self, driver=None):
        '''跳转到下一页'''
        driver = self._get_driver(driver)
        driver.back()
        self.logger.info('跳转上一页')

    def maximize_window(self, driver=None):
        '''最大化浏览器'''
        driver = self._get_driver(driver)
        driver.maximize_window()
        self.logger.info('最大化浏览器')

    def set_window_size(self, x=100, y=50, driver=None):
        '''设置窗口大小'''
        driver = self._get_driver(driver)
        driver.set_window_size(x, y)
        self.logger.info('设置窗口大小%s，%s'%(x, y))

    def set_page_load_timeout(self, timeout=15, driver=None):
        '''设置页面加载超时时间'''
        driver = self._get_driver(driver)
        driver.set_page_load_timeout(timeout)
        self.logger.info('设置页面加载超时时间：%s' %timeout)

    def close(self, driver=None):
        '''关闭浏览器'''
        driver = self._get_driver(driver)
        driver.quit()
        self.logger.info('关闭浏览器')

    def get_screenshot(self, file_path, driver=None):
        '''截图;  file_path="/pictures/test.png" '''
        driver = self._get_driver(driver)
        driver.get_screenshot_as_file(file_path)
        self.logger.info('截图：%s'%file_path)

    def get_cookies(self, driver=None):
        '''获取所有cookies'''
        driver = self._get_driver(driver)
        cookies = driver.get_cookies()
        self.logger.info('获取所有cookies信息：%s' %cookies)
        return cookies

    def get_cookie(self, name, driver=None):
        '''获取cookies的某个值'''
        driver = self._get_driver(driver)
        cookie = driver.get_cookie(name)
        self.logger.info('获取%s的cookie信息：%s' %(name, cookie))
        return cookie

    def delete_cookie(self, name, driver=None):
        '''删除指定的cookie信息'''
        driver = self._get_driver(driver)
        driver.delete_cookie(name)
        self.logger.info('删除%s的cookie信息' %name)

    def delete_cookies(self, driver=None):
        '''删除所有的cookies信息'''
        driver = self._get_driver(driver)
        driver.delete_all_cookies()
        self.logger.info('删除所有的cookie信息')

    def add_cookie(self, cookie_dict, driver=None):
        '''添加cookies信息'''
        driver = self._get_driver(driver)
        driver.add_cookie(cookie_dict)
        self.logger.info('添加cookies信息：%s' %cookie_dict)

    def get_title(self, driver=None):
        '''获取title标题'''
        driver = self._get_driver(driver)
        title = driver.title
        self.logger.info('获取标题：%s'%title)
        return title

    def get_url(self, driver=None):
        '''获取当前url'''
        driver = self._get_driver(driver)
        url = driver.current_url
        self.logger.info('获取当前url：%s' % url)
        return url

    def get_element_text(self, locator=None, element=None, driver=None):
        '''获取元素的文本'''
        try:
            driver = self._get_driver(driver)
            element = self._get_element(locator, element, driver)
            text = element.text
            self.logger.info('获取元素的文本：%s'%text)
            return text
        except:
            self.logger.info("获取text失败，返回''")
            return ""

    def get_element_attribute(self, locator, name, element=None, driver=None):
        '''获取元素的属性'''
        driver = self._get_driver(driver)
        try:
            element = self._get_element(locator, element, driver)
            attribute = element.get_attribute(name)
            self.logger.info('获取元素的%s属性：' %(name,attribute))
            return attribute
        except:
            self.logger.info("获取元素的%s属性失败，返回''")
            return ""

    def js_focus_element(self, locator=None, element=None, driver=None):
        '''聚焦元素'''
        driver = self._get_driver(driver)
        target_element = self._get_element(locator, element, driver)
        driver.execute_script("arguments[0].scrollIntoView();", target_element)
        self.logger.info("聚焦元素")

    def js_scroll_top(self, driver=None):
        '''滚动到顶部'''
        driver = self._get_driver(driver)
        js = "window.scrollTo(0,0)"
        driver.execute_script(js)
        self.logger.info("滚动到顶部")

    def js_scroll_end(self, x=0, driver=None):
        '''滚动到底部'''
        driver = self._get_driver(driver)
        js = "window.scrollTo(%s,document.body.scrollHeight)" % x
        driver.execute_script(js)
        self.logger.info("滚动到底部")

    def js_play_video(self, locator=None, element=None, driver=None):
        '''播放视频'''
        driver = self._get_driver(driver)
        target_element = self._get_element(locator, element, driver)
        js = "arguments[0].play();"
        driver.execute_script(js, target_element)
        self.logger.info("播放视频")

    def select_by_index(self, locator, index=0, element=None, driver=None):
        '''下拉框，通过索引选择。index是索引第几个，从0开始，默认选第一个'''
        driver = self._get_driver(driver)
        target_element = self._get_element(locator, element, driver)
        Select(target_element).select_by_index(index)
        self.logger.info("下拉框选择索引%s的值"%index)

    def select_by_value(self, locator, value, element=None, driver=None):
        '''下拉框，通过value选择'''
        driver = self._get_driver(driver)
        target_element = self._get_element(locator, element, driver)
        Select(target_element).select_by_value(value)
        self.logger.info("下拉框选择value:%s的值"%value)

    def select_by_text(self, locator, text, element=None, driver=None):
        '''下拉框，通过文本值选择'''
        driver = self._get_driver(driver)
        target_element = self._get_element(locator, element, driver)
        Select(target_element).select_by_visible_text(text)
        self.logger.info("下拉框选择文本:%s的值" % text)

    def deselect_by_index(self, locator, index=0, element=None, driver=None):
        '''下拉框，通过索引,取消选择。index是索引第几个，从0开始，默认取消第一个'''
        driver = self._get_driver(driver)
        target_element = self._get_element(locator, element, driver)
        Select(target_element).deselect_by_index(index)
        self.logger.info("下拉框取消选择索引%s的值" % index)

    def deselect_by_value(self, locator, value, element=None, driver=None):
        '''下拉框，通过value，取消选择'''
        driver = self._get_driver(driver)
        target_element = self._get_element(locator, element, driver)
        Select(target_element).deselect_by_index(value)
        self.logger.info("下拉框取消选择value:%s的值"%value)

    def deselect_by_text(self, locator, text, element=None, driver=None):
        '''下拉框，通过文本值，取消选择'''
        driver = self._get_driver(driver)
        target_element = self._get_element(locator, element, driver)
        Select(target_element).deselect_by_visible_text(text)
        self.logger.info("下拉框取消选择文本:%s的值" % text)

    def deselect_all(self, locator=None, element=None, driver=None):
        '''下拉框，取消选择'''
        driver = self._get_driver(driver)
        target_element = self._get_element(locator, element, driver)
        Select(target_element).deselect_all()
        self.logger.info("下拉框取消选择")

    def get_select_options(self, locator=None, element=None, driver=None):
        '''获取下拉框的所有options ； 遍历之后 .text可以获取该文本值'''
        driver = self._get_driver(driver)
        target_element = self._get_element(locator, element, driver)
        options = Select(target_element).options()
        self.logger.info("获取下拉框的所有options")
        return options

    def get_first_selected_option(self, locator=None, element=None, driver=None):
        '''获取第一个被选中的option'''
        driver = self._get_driver(driver)
        target_element = self._get_element(locator, element, driver)
        first_option = Select(target_element).first_selected_option()
        self.logger.info("获取下拉框的第一个被选中的option")
        return first_option

    def get_selected_options(self, locator=None, element=None, driver=None):
        '''获取所有被选中的option'''
        driver = self._get_driver(driver)
        target_element = self._get_element(locator, element, driver)
        options = Select(target_element).all_selected_options()
        self.logger.info("获取下拉框的所有被选中的option")
        return options

    def switch_iframe(self, id_name_index_locator, driver=None):
        '''切换iframe ； 可以传入id、name、index以及selenium的WebElement对象'''
        driver = self._get_driver(driver)
        try:
            if isinstance(id_name_index_locator, tuple):
                element = self.find_element(id_name_index_locator)
                driver.switch_to.frame(element)
            driver.switch_to.frame(id_name_index_locator)
            self.logger.info("切换iframe")
        except:
            self.logger.error("切换iframe异常", exc_info=True)
            raise Exception("切换iframe异常")

    def switch_default_content(self, driver=None):
        '''释放iframe'''
        driver = self._get_driver(driver)
        driver.switch_to.default_content()
        self.logger.info("释放iframe")

    def switch_parent_iframe(self, driver=None):
        '''回到父级的iframe'''
        driver = self._get_driver(driver)
        driver.switch_to.parent_frame()
        self.logger.info("回到父级的iframe")

    def get_current_handle(self, driver=None):
        '''获取当前句柄窗口'''
        driver = self._get_driver(driver)
        handle = driver.current_window_handle()
        self.logger.info("获取当前句柄窗口")
        return handle

    def get_handles(self, driver=None):
        '''获取所有的句柄窗口'''
        driver = self._get_driver(driver)
        handles = driver.window_handles()
        self.logger.info("获取所有的句柄窗口")
        return handles

    def switch_handle(self, handle, driver=None):
        '''切换句柄窗口'''
        driver = self._get_driver(driver)
        driver.switch_to.window(handle)
        self.logger.info("切换句柄窗口")

    def switch_alert(self, driver=None):
        '''切换到alert ；'''
        driver = self._get_driver(driver)
        alert = driver.switch_to_alert()
        self.logger.info("切换到alert")
        return alert

    def accept_alert(self, driver=None):
        '''切换到alert ； 并且点击确认'''
        self.switch_alert(driver).accept()
        self.logger.info("点击确认alert")

    def dismiss_alert(self, driver=None):
        '''切换到alert ； 并且点击取消'''
        self.switch_alert(driver).dismiss()
        self.logger.info("点击取消alert")

    def execute_js(self, js, driver=None):
        '''执行js脚本'''
        driver = self._get_driver(driver)
        driver.execute_script(js)
        self.logger.info("执行js脚本--> %s"%js)

    def move_to_element(self, locator=None, element=None, driver=None):
        '''鼠标悬停到某个元素上'''
        driver = self._get_driver(driver)
        element = self._get_element(locator, element, driver)
        ActionChains(driver).move_to_element(element).perform()
        self.logger.info("鼠标悬停到元素上")

    def double_click(self, locator=None, element=None, driver=None):
        '''双击鼠标'''
        driver = self._get_driver(driver)
        element = self._get_element(locator, element, driver)
        ActionChains(driver).double_click(element).perform()
        self.logger.info("双击鼠标")

    def context_click(self, locator=None, element=None, driver=None):
        '''点击鼠标右键'''
        driver = self._get_driver(driver)
        element = self._get_element(locator, element, driver)
        ActionChains(driver).context_click(element).perform()
        self.logger.info("点击鼠标右键")

    def drag_element(self, from_locator, to_locator, driver=None):
        '''拖动元素（原元素--->目标元素）'''
        driver = self._get_driver(driver)
        from_element = self.find_element(from_locator, driver)
        to_element = self.find_element(to_locator, driver)
        ActionChains(driver).drag_and_drop(from_element, to_element).perform()
        self.logger.info("拖动元素")

if __name__ == '__main__':
    from selenium import webdriver
    from time import sleep
    from selenium.webdriver.chrome.options import Options
    from logger import Logger

    logger = Logger()

    chrome_options = Options()
    # 设置chrome浏览器无界面模式
    chrome_options.add_argument('--headless')
    driver = webdriver.Chrome(chrome_options=chrome_options)

    handle = Base(logger=logger, driver=driver) # logger是必传的，driver可以不传
    handle.maximize_window()
    handle.set_page_load_timeout()
    handle.get('http://www.baidu.com')
    handle.send_keys(('id', 'kw'), '哦哦哦哦')  # 初始化传了driver的，默认用初始化的driver
    sleep(1)

    handle.clear(('id', 'kw'), driver=driver)   # 初始化没有传driver，或者传了driver的；调方法时，传driver会优先用方法传的driver

    sleep(2)
    search_btn_ele = handle.find_element(('id', 'su'))
    handle.double_click(element=search_btn_ele) # 可以传locator或者element，其中一个，去操作
    sleep(2)
    handle.close()


# -------------------------------------------------------------------------------
# Name:        MainFile.py
# Purpose:     Branch and cut using X2PL, main file.
#
# Author:      ifragkos
#
# Created:     03/03/2015
# -------------------------------------------------------------------------------
# noinspection PyUnresolvedReferences
__author__ = 'ioannis'

from sys import argv

from gurobipy import GRB

import X2PLdata as Cdata
import esc
import LSModel as ls_Model

def main(filename, gurobi=False):
    my_data = Cdata.TrigeiroData(filename)

    model = ls_Model.make_model(my_data, print_lp=True)

    if gurobi:
        ls_Model.optimize(my_data, model, solve_relaxed=False, log=True)
        return

    esc_model = esc.ExtendedSimpleCovers()

    callback_closure(mdl=model, data=my_data, esc_model=esc_model)

def callback_closure(mdl, data, esc_model):
    def add_esc_callback(model, where):
        if where == GRB.callback.MIPNODE:
            status = model.cbGet(GRB.callback.MIPNODE_STATUS)
            if status == GRB.OPTIMAL:
                lp_solution = ls_Model.get_lp_solution(data, model, callback=True)
                for period1 in xrange(data.Periods - 1):
                    data.pointToSeparate.setup = lp_solution.setup
                    data.pointToSeparate.production = lp_solution.production
                    for period2 in xrange(period1 + 2, data.Periods):
                        data.period1 = period1
                        data.period2 = period2
                        data.pointToSeparate.inventory = lp_solution.inventory[period2, :]
                        if not esc_model.is_populated:
                            esc_model.populate_model(data)
                            esc_model.is_populated = True
                        else:
                            esc_model.update_model(data)
                        cover, complement, period = esc_model.optimize_model(write_lp=False, print_sol=False)
                        ls_Model.add_esc(data, cover, complement, period, period1, period2,
                                         callback=True, print_diag=True)

    mdl.optimize(add_esc_callback)

if __name__ == '__main__':
    if len(argv) > 1:
        main(argv[1], gurobi=argv[2] == 'True')
    else:
        main('instance_12_6_10.in', False)
        # 'instance_11_6_4.in'


#!/usr/bin/env python

import csv
import time
import datetime
import os

from logger.Logger import Logger
from services.ConfigService import config
class CSVService:
  log = Logger(__name__)

  def __init__(self, hw_monitor, perf_monitor):
    self.time = time.time()
    self.filename = ""
    self.fieldnames = ["time"]
    for hw_field_name in hw_monitor.get_field_names():
      self.fieldnames.append(hw_field_name)
    for perf_field_name in perf_monitor.get_field_names():
      self.fieldnames.append(perf_field_name)
    self.create()

  def append(self, data):
    """
    Appends data to the .csv
    """
    with open(self.filename, "a", newline="", encoding='utf-8') as csvfile:
      writer = csv.DictWriter(csvfile, fieldnames=self.fieldnames)
      writer.writerow(data)

  def create(self):
    """
    Creates a new .csv file
    """
    self.filename = "/tmp/monitors/RES/RES_{}".format(time.time()) + ".csv"
    with open(self.filename, "w", newline="", encoding='utf-8') as csvfile:
      writer = csv.DictWriter(csvfile, fieldnames=self.fieldnames)
      writer.writeheader()


#!/usr/bin/env python

from __future__ import absolute_import, division, print_function, unicode_literals

import os
import sys
import importlib
import numpy as np

from callbacks.report_time import TimeHistory
import debug_flag
# Set to True to get printouts
debug_flag.DEBUG = False

if __name__ == '__main__':
    from argparse import ArgumentParser

    parser = ArgumentParser(description='Train the keras model.')
    parser.add_argument('model', metavar='MODEL', help='Name of the module in the models directory.')
    parser.add_argument('weights_path', metavar='PATH', help='HDF5 file containing model weights.')
    parser.add_argument('data_path', metavar='PATH', nargs='+', help='Data files.')
    parser.add_argument('--input-type', '-i', metavar='TYPE', dest='input_type', default='h5', help='Input data format (h5, root, root-sparse).')
    parser.add_argument('--batch-size', '-b', metavar='N', dest='batch_size', type=int, default=32, help='Input batch size.')
    parser.add_argument('--num-batches', '-s', metavar='N', dest='num_batches', type=int, default=None, help='Number of batches to process.')
    parser.add_argument('--root-out', '-r', metavar='PATH', dest='root_out_path', help='Write prediction results to a ROOT file.')
    parser.add_argument('--h5-out', '-p', metavar='PATH', dest='h5_out_path', help='Write prediction results to a HDF5 file.')
    parser.add_argument('--ascii-out', '-a', metavar='PATH', dest='ascii_out_dir', help='Write prediction results to ASCII files in a directory.')
    parser.add_argument('--input-name', '-m', metavar='NAME', dest='input_name', default='events', help='Input dataset (TTree or HDF5 dataset) name.')

    args = parser.parse_args()
    del sys.argv[1:]

    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'

    modelmod = importlib.import_module('models.%s' % args.model)

    model = modelmod.make_model()
    model.load_weights(args.weights_path)

    if args.input_type == 'h5':
        from generators.h5 import make_generator
    elif args.input_type == 'root':
        from generators.uproot_fixed import make_generator
    elif args.input_type == 'root-sparse':
        from generators.uproot_jagged_keep import make_generator

    from generators.utils import make_dataset

    gen, n_steps = make_generator(args.data_path, args.batch_size, num_steps=args.num_batches, dataset_name=args.input_name, **modelmod.generator_args)

    timer = TimeHistory()

    prediction = model.predict(gen, verbose=1, callbacks=[timer])

    print('Prediction time: %fs' % (timer.stop - timer.start))

    need_dataset_x = (args.root_out_path or args.ascii_out_dir)

    dataset = make_dataset(gen, n_steps, truth_only=(not need_dataset_x))
    if need_dataset_x:
        inputs, truth = dataset
    else:
        truth = dataset

    modelmod.evaluate_prediction(prediction, truth)

    if args.root_out_path:
        import root_numpy as rnp
        import uproot

        try:
            os.makedirs(os.path.dirname(args.root_out_path))
        except OSError:
            pass

        dtype = modelmod.root_out_dtype
        entries = modelmod.make_root_out_entries(inputs, prediction, truth)

        ## more info for the HGCAL dataset
        #dtype += [('cl_pt', np.float32), ('gen_eta', np.float32)]
        #data = uproot.open(args.data_path)[args.input_name].arrays(['cl_pt', 'gen_eta'], namedecode='ascii')
        #entries += (data['cl_pt'], data['gen_eta'])

        array = np.empty((n_sample,), dtype=dtype)

        for ient, ent in enumerate(zip(*entries)):
            array[ient] = ent

        rnp.array2root(array, args.root_out_path, mode='recreate')

    if args.h5_out_path:
        import h5py

        try:
            os.makedirs(os.path.dirname(args.h5_out_path))
        except OSError:
            pass

        data = modelmod.make_h5_out_data(prediction, truth)

        with h5py.File(args.h5_out_path, 'w', libver='latest') as output:
            for key, value in data.items():
                dataset = output.create_dataset(key, value.shape, compression='gzip', dtype=value.dtype)
                dataset.write_direct(value)

    if args.ascii_out_dir:
        try:
            os.makedirs(args.ascii_out_dir)
        except OSError:
            pass

        in_file = open('%s/tb_input_features.dat' % args.ascii_out_dir, 'w')
        out_file = open('%s/tb_output_predictions.dat' % args.ascii_out_dir, 'w')
        truth_file = open('%s/truth.dat' % args.ascii_out_dir, 'w')

        modelmod.write_ascii_out(inputs, prediction, truth, in_file, out_file, truth_file)

        in_file.close()
        out_file.close()
        truth_file.close()


# -*- coding: gb18030 -*-
#
# $Id: Buff_1003.py,v 1.2 2007-12-13 04:59:55 huangyongwei Exp $

"""
持续性效果
"""

import BigWorld
import csconst
import csstatus
import csdefine
import time
from bwdebug import *
from SpellBase import *
from Buff_Normal import Buff_Normal

class Buff_22006( Buff_Normal ):
	"""
	日光浴buff，不断增加经验（当然，指的是有效时间内）
	"""
	def __init__( self ):
		"""
		构造函数。
		"""
		Buff_Normal.__init__( self )
		self._p1 = 0

	def init( self, dict ):
		"""
		读取技能配置
		@param dict: 配置数据
		@type  dict: python dict
		"""
		Buff_Normal.init( self, dict )
		self._p1 = ( dict[ "Param1" ] if len( dict[ "Param1" ] ) > 0 else "" ) 					# 增加经验的公式
		self._p2 = int( dict[ "Param2" ] if len( dict[ "Param2" ] ) > 0 else 0 ) 					# 每天最多可以晒多长时间（ 单位是秒 ）
		self._p3 = int( dict[ "LoopSpeed" ] if dict[ "LoopSpeed" ] > 0 else 0 ) 					# 增加经验相隔的时间
		self._hpVal = int( self._p1[ 3:len( self._p1 ) ] )	# 增加的经验值
		self._hpOpt = self._p1[ 2:3 ]						# 操作符

	def doBegin( self, receiver, buffData ):
		"""
		Virtual method; call only by real entity.
		效果开始的处理。

		@param receiver: 效果要影响的实体
		@type  receiver: BigWorld.Entity
		@param buffData: BUFF
		@type  buffData: BUFF
		@return: None
		"""
		actPet = receiver.pcg_getActPet()
		if actPet :													# 如果玩家携带有出征宠物
			actPet.entity.withdraw( csdefine.PET_WITHDRAW_COMMON )	# 则收回之
		Buff_Normal.doBegin( self, receiver, buffData )
		date = time.localtime()[2]
		if receiver.sunBathDailyRecord.date != date:
			receiver.sunBathDailyRecord.date = date
			receiver.sunBathDailyRecord.sunBathCount = 0
			receiver.sunBathDailyRecord.prayCount = 0

	def doReload( self, receiver, buffData ):
		"""
		Virtual method; call only by real entity.
		效果重新加载的处理。

		@param receiver: 效果要影响的实体
		@type  receiver: BigWorld.Entity
		@param buffData: BUFF
		@type  buffData: BUFF
		@return: None
		"""
		Buff_Normal.doReload( self, receiver, buffData )
		actPet = receiver.pcg_getActPet()
		if actPet :													# 如果玩家携带有出征宠物
			actPet.entity.withdraw( csdefine.PET_WITHDRAW_COMMON )	# 则收回之
		date = time.localtime()[2]
		if receiver.sunBathDailyRecord.date != date:
			receiver.sunBathDailyRecord.date = date
			receiver.sunBathDailyRecord.sunBathCount = 0

	def doLoop( self, receiver, buffData ):
		"""
		Virtual method; call only by real entity.
		用于buff，表示buff在每一次心跳时应该做什么。

		@param receiver: 效果要影响的实体
		@type  receiver: BigWorld.Entity
		@param buffData: BUFF
		@type  buffData: BUFF
		@return: BOOL；如果允许继续则返回True，否则返回False
		@rtype:  BOOL
		"""
		increaseEXP = self.getIncreaseEXP( receiver.level, self._hpOpt, self._hpVal )
		if receiver.queryTemp( "clean_sun_bath_exp", 0 ) != increaseEXP:
			# 记录玩家的纯净日光浴经验，一进地图的时候就设置一次了，这里还要设置一次，以防止玩家级别改变
			receiver.setTemp( "clean_sun_bath_exp", increaseEXP )

		# 判断角色是否在合法日光浴时间
		if receiver.isSunBathing() and receiver.sunBathDailyRecord.sunBathCount < self._p2:

			if receiver.queryTemp("btxy_exp_percent", 0.0) > 0:	# 如果角色有波涛汹涌buff
				increaseEXP = int( increaseEXP * (1 - ( receiver.queryTemp("btxy_exp_percent", 0.0) )/100) )

			gainedExp = 0
			#receiver.updateSunBathCount( self._p3 )	# 循环多长时间加一次，就加多少时间

			if receiver.queryTemp( "has_cleanlily_drink", 0 ) == 1:	# 如果有清爽饮料
				expRate = receiver.queryTemp( "drink_exp_rate", 0.0 )
				gainedExp = int( increaseEXP * expRate )			# 变成双倍经验（或其他倍数，具体要看给清爽饮料的配置了多少倍）

			if receiver.queryTemp( "sxym_exp_rate", 0.0 ) > 0:	# 如果有赏心悦目buff
				gainedExp += int( increaseEXP * receiver.queryTemp( "sxym_exp_rate", 0.0 ) )

			if receiver.queryTemp( "lwxl_exp_rate", 0.0 ) > 0:	# 如果有龙王显灵buff
				gainedExp += int( increaseEXP * receiver.queryTemp( "lwxl_exp_rate", 0.0 ) )

			if receiver.queryTemp( "scyy_exp_rate", 0.0 ) > 0:	# 如果有神采熠熠buff
				gainedExp += int( increaseEXP * receiver.queryTemp( "scyy_exp_rate", 0.0 ) )

			if receiver.queryTemp( "has_sun_bath_vip", 0 ) == 1:	# 如果是海滨VIP
				expRate = receiver.queryTemp( "vip_exp_rate", 0.0 )
				gainedExp += int( increaseEXP * expRate )			# 加上vip导致的经验翻倍（具体倍数同样要看给VIP卡的配置了多少倍）

			if gainedExp == 0:										# 说明什么经验翻倍的道具都没有用
				gainedExp = increaseEXP

			if receiver.queryTemp( "hssl_exp_stop", 0 ) != 1:	# 如果角色有海市蜃楼buff则不获得经验
				receiver.addExp ( gainedExp, csdefine.CHANGE_EXP_SUN_BATH )

			if receiver.queryTemp( "hsch_gain_potential", 0 ) == 1:	# 如果角色有海神赐福buff，则获得和经验值相同的潜能
				receiver.addPotential( gainedExp )
		else:
			receiver.statusMessage( csstatus.SKILL_NO_SUN_BATH_TIME_EXP )

		return Buff_Normal.doLoop( self, receiver, buffData )

	def doEnd( self, receiver, buffData ):
		"""
		Virtual method; call only by real entity.
		效果结束的处理。
		"""
		Buff_Normal.doEnd( self, receiver, buffData )
		receiver.removeTemp( "sun_bath_area_count" )	# 清除掉记录玩家身上有几个区域的标记

	def getIncreaseEXP( self, level, opration, value ):
		"""
		根据公式获得增加的Exp
		"""
		return level + value


from pathlib import Path

### Data provided by LG
# Head directory
data_dir = Path('/home/jaeho_ubuntu/SMILES/data/')
train_dir = data_dir / 'train'
test_dir = data_dir / 'test'
train_csv_dir = data_dir /'train.csv'
# train_modified contains information of the train/validation split in a pickle file format. I saved in pickle just for efficiency
train_pickle_dir = data_dir /'train_modified.pkl'
# Sample submission directory
sample_submission_dir = data_dir /'sample_submission.csv'

### Data directory generated by us
input_data_dir = data_dir / 'input_data'
base_file_name = 'seed_123_max75smiles'

### seed for train/val split
random_seed = 123

### Reversed_token_file used to map numbers to string.
reversed_token_map_dir = input_data_dir/ f'REVERSED_TOKENMAP_{base_file_name}.json'


def main():

    while True:
        change = input("How much change do you need? ")

        if change and not change.isalpha():
            if float(change) > 0:
                break

    change = int(float(change) * 100)

    quarters = change / 25

    remainder = change % 25

    dimes = remainder / 10

    remainder = remainder % 10

    nickels = remainder / 5

    remainder = remainder % 5

    print(int(quarters) + int(dimes) + int(nickels) + int(remainder))

if __name__ == '__main__':
    main()


from pyircd.message import Message

# Comments refer to variables in below strings.

class NumericReply():
    def __init__(self, number, message, final_multi=True):
        self.number = number
        self.num_str = str(self.number).zfill(3)
        self.message = message
        self.final_multi = final_multi

# nick!user@host
RPL_WELCOME = NumericReply(
        1,
        ":Welcome to the Internet Relay Network {}!{}@{}"
    )

# servername, version
RPL_YOURHOST = NumericReply(2, ":Your host is {}, running version {}")

# Launch time
RPL_CREATED = NumericReply(3, ":This server was created {}")

# servername, version, usermodes, channelmodes
RPL_MYINFO = NumericReply(4, "{} {} {} {}", False)

# Network name
RPL_ISUPPORT = NumericReply(5, "PREFIX=(ov)@+ CHANTYPES=#& NETWORK={}"
" CASEMAPPING=ascii CHANMODES=beI,k,l,imnst EXCEPTS=e CHANNELLEN=32"
":are supported by this server")

# Modes
RPL_UMODEIS = NumericReply(221, "+{}", False)

# nick, user, host, realname
RPL_WHOISUSER = NumericReply(311, "{} {} {} * :{}")

# nick, server host, server info
RPL_WHOISSERVER = NumericReply(312, "{} {} :{}")

# nick, time idle
RPL_WHOISIDLE = NumericReply(317, "{} {} :seconds idle")

# nick
RPL_ENDOFWHOIS = NumericReply(318, "{} :End of WHOIS list")

# nick, space seperated channel list
RPL_WHOISCHANNELS = NumericReply(319, "{} :{}")

# Channel, modes, mode params
RPL_CHANNELMODEIS = NumericReply(324, "{} +{} {}", False)

# Channel name
RPL_NOTOPIC = NumericReply(331, "{} :No topic is set")

# Channel name, topic
RPL_TOPIC = NumericReply(332, "{} :{}")

# Channel, user, host, server, nick, H is for here/gone, realname
RPL_WHOREPLY = NumericReply(352, "{} {} {} {} {} H{} :0 {}")

# WHO target
RPL_ENDOFWHO = NumericReply(315, "{} :End of WHO List")

# Channel name, space seperate list of nicks
RPL_NAMREPLY = NumericReply(353, "= {} :{}")

# Channel name
RPL_ENDOFNAMES = NumericReply(366, "{} :End of NAMES List")

# Server Name
RPL_MOTDSTART = NumericReply(375, ":- {} Message of the day - ")

# MOTD Component
RPL_MOTD = NumericReply(372, ":- {}")

RPL_ENDOFMOTD = NumericReply(376, ":End of MOTD")

RPL_YOUREOPER = NumericReply(381, ":You are now an IRC operator")

# Nick
ERR_NOSUCHNICK = NumericReply(401, "{} :No such nick/channel")

# Channel name
ERR_NOSUCHCHANNEL = NumericReply(403, "{} :No such channel")

# Failed command
ERR_UNKNOWNCOMMAND = NumericReply(421, "{} :Unknown command")

# Nick
ERR_NICKNAMEINUSE = NumericReply(433, "{} :Nickname already in use")

# Nick, channel
ERR_USERNOTINCHANNEL = NumericReply(441, "{} {} :They aren't on that channel")

# Channel
ERR_NOTONCHANNEL = NumericReply(442, "{}: You're not on that channel")

# Command attempted
ERR_NEEDMOREPARAMS = NumericReply(461, "{} :Not enough parameters")

ERR_PASSWDMISMATCH = NumericReply(464, ":Password incorrect")

# Channel
ERR_CHANNELISFULL = NumericReply(471, "{} :Cannot join channel (+l)")

# Channel
ERR_BADCHANNELKEY = NumericReply(475, "{} :Cannot join channel (+k)")

# Channel
ERR_BADCHANMASK = NumericReply(476, "{} :Bad Channel Mask")

# Channel
ERR_CHANOPRIVSNEEDED = NumericReply(482, "{} :You're not channel operator")

ERR_USERSDONTMATCH = NumericReply(502, ":Cannot change mode for other users")


#!/usr/bin/env python3
"""
GRN related tools

author: jy, nkmtmsys
"""

import re
import pandas as pd
import networkx as nx
import statistics as sta
import ageas.tool as tool
import ageas.tool.json as json

class GRN(object):
	"""
	docstring for Meta_GRN.
	"""

	def __init__(self, id = None, **kwargs):
		super(GRN, self).__init__()
		self.id = id
		self.genes = dict()
		self.grps = dict()
		for key in kwargs:
			setattr(self, key, kwargs[key])

	def update_grn(self, source, target, gem1, gem2, correlation_thread):
		# Skip if processing self-regulating pathway
		if source == target: return
		grp_id = GRP(source, target).id
		if grp_id in self.grps:
			if not self.grps[grp_id].reversable:
				self.grps[grp_id].reversable = True
			return

		# Test out global scale correlation
		cor_class1 = None
		cor_class2 = None
		passed = False

		# check cor_class1
		if source in gem1.data.index and target in gem1.data.index:
			cor_class1 = tool.Get_Pearson(
				gem1.data.loc[[source]].values[0],
				gem1.data.loc[[target]].values[0]
			)

		# check cor_class2
		if source in gem2.data.index and target in gem2.data.index:
			cor_class2 = tool.Get_Pearson(
				gem2.data.loc[[source]].values[0],
				gem2.data.loc[[target]].values[0]
			)

		# Go through abs(correlation) threshold check
		if cor_class1 is None and cor_class2 is None:
			return
		if cor_class1 is None and abs(cor_class2) > correlation_thread:
			passed = True
			cor_class1 = 0
		elif cor_class2 is None and abs(cor_class1) > correlation_thread:
			passed = True
			cor_class2 = 0
		elif cor_class1 is not None and cor_class2 is not None:
			if abs(cor_class1 - cor_class2) > correlation_thread:
				passed = True

		# update GRN if passed correlation filter
		if passed:
			correlations = {
				'class1':float(cor_class1),
				'class2':float(cor_class2)
			}
			self.add_grp(grp_id, source, target, correlations)
			if source not in self.genes:
				self.add_gene(source, gem1, gem2)
			if target not in self.genes:
				self.add_gene(target, gem1, gem2)

	def add_grp(self, id, source, target, correlations):
		assert id not in self.grps
		# may change it to a class later
		self.grps[id] = GRP(
			id = id,
			regulatory_source = source,
			regulatory_target = target,
			correlations = correlations
		)
		return

	def add_gene(self, id, gem1, gem2):
		assert id not in self.genes
		# get expression sum values
		class1_exp = 0
		class2_exp = 0
		if id in gem1.data.index:
			class1_exp = sum(gem1.data.loc[[id]].values[0])
		if id in gem2.data.index:
			class2_exp = sum(gem2.data.loc[[id]].values[0])
		# may change it to a class later
		self.genes[id] = Gene(
			id = id,
			expression_sum = {
				'class1': float(class1_exp),
				'class2': float(class2_exp)
			}
		)
		return

	def as_dict(self):
		return {
			'genes': {id:record.as_dict() for id, record in self.genes.items()},
			'grps':{id:record.as_dict() for id, record in self.grps.items()}
		}

	def as_digraph(self, grp_ids = None):
		graph = nx.DiGraph()
		# Use all GRPs if not further specified
		if grp_ids is None: grp_ids = self.grps.keys()
		for grp_id in grp_ids:
			source = self.grps[grp_id].regulatory_source
			target = self.grps[grp_id].regulatory_target

			# add regulatory source and target genes to nodes
			if not graph.has_node(source):
				graph.add_node(source, **self.genes[source].as_dict())
			if not graph.has_node(target):
				graph.add_node(target, **self.genes[target].as_dict())

			# add GRP as an edge
			graph.add_edge(source, target, **self.grps[grp_id].as_dict())
			if self.grps[grp_id].reversable:
				graph.add_edge(target, source, **self.grps[grp_id].as_dict())
		return graph

	# recursively add up impact score with GRP linking gene to its target
	def get_grps_from_gene(self,
				   		   gene = None,
				   		   depth = 3,
				   		   dict = dict(),
				  		  ):
		"""
		Recursively find GRPs able to link with root_gene in given depth.

		depth: <int> Default = 3
			When assessing a TF's regulatory impact on other genes,
			how far the distance between TF and potential regulatory source
			can be.

			The correlation strength of stepped correlation strength of TF
			and gene still need to be greater than correlation_thread.
		"""
		if depth > 0:
			depth -= 1
			for target in self.genes[gene].target + self.genes[gene].source:
				link_grp = GRP(gene, target).id
				if link_grp not in dict and link_grp in self.grps:
					dict[link_grp] = self.grps[link_grp]
				dict = self.get_grps_from_gene(target, depth, dict)
		return dict

	def list_grp_as_df(self):
		answer = list()
		for id,rec in self.grps.items():
			answer.append([
				rec.regulatory_source,
				self.genes[rec.regulatory_source].symbol,
				rec.regulatory_target,
				self.genes[rec.regulatory_target].symbol,
				rec.reversable,
				rec.type,
				rec.correlations['class1'],
				rec.correlations['class2'],
				rec.score,
			])
		answer = pd.DataFrame(sorted(answer, key=lambda x:x[-1], reverse=True))
		answer.columns = [
			'Regulatory source ID',
			'Regulatory source Gene Symbol',
			'Regulatory target ID',
			'Regulatory target Gene Symbol',
			'Reversable',
			'Type',
			'Correlation in Class 1',
			'Correlation in Class 2',
			'Score'
		]
		return answer

	def save_json(self, path):
		json.encode(self.as_dict(), path)
		return

	def load_dict(self, dict):
		self.genes = {id: Gene(**dict['genes'][id]) for id in dict['genes']}
		self.grps = {id: GRP(**dict['grps'][id]) for id in dict['grps']}
		return

class Gene(object):
	"""
	Object to store information of a Gene in Gene Regulatory Network(GRN).
	"""

	def __init__(self,
				 id:str = None,
				 type:str = 'Gene',
				 expression_sum:float = None,
				 **kwargs
				):
		"""
		Initialize a object.

		:param id:str = None

		:param type:str = 'Gene'

		:param expression_sum:float = None

		:param **kwargs
		"""
		self.id = id
		self.type = type
		self.symbol = id
		self.source = list()
		self.target = list()
		self.expression_sum = expression_sum
		for key in kwargs:
			setattr(self, key, kwargs[key])

	def as_dict(self): return self.__dict__

	def add_ens_id(self, ens_id):
		if not hasattr(self, 'ens_id'):
			self.ens_id = ens_id

	def add_uniprot_id(self, uniprot_id):
		if not hasattr(self, 'uniprot_ids'): self.uniprot_ids = list()
		self.uniprot_ids.append(uniprot_id)

class GRP(object):
	"""
	Object to store information of a Gene Regulatory Pathway(GRP).
	"""

	def __init__(self,
				 regulatory_source:str = None,
				 regulatory_target:str = None,
				 id:str = None,
				 type:str = None,
				 score:str = None,
				 reversable:bool = False,
				 correlations:float = None,
				 **kwargs
				):
		"""
		Initialize a object.

		:param regulatory_source:str = None

		:param regulatory_target:str = None

		:param id:str = None

		:param type:str = None

		:param score:str = None

		:param reversable:bool = False

		:param correlations:float = None

		:param **kwargs

		"""
		self.id = id
		self.type = type
		self.score = score
		self.reversable = reversable
		self.correlations = correlations
		self.regulatory_source = regulatory_source
		self.regulatory_target = regulatory_target
		if self.id is None:
			self.id = self.cast_id(regulatory_source, regulatory_target)
		for key in kwargs:
			setattr(self, key, kwargs[key])

	def as_dict(self):
		"""
		Switch object to a dict.
		"""
		return self.__dict__

	def cast_id(self, source:str = None, target:str = None):
		"""
		Cast the id for GRP according to name of regulatory source and target.

		:param source:str = None
		:param target:str = None
		:return:str ID of GRP

		"""
		if source > target:
			return source + '_' + target
		else:
			return target + '_' + source


"""

Filename: torch_wrappers.py

Author: Nicolas Raymond
        Hakima Laribi

Description: This file is used to define the abstract classes
             used as wrappers for custom torch models
"""

import os
from typing import Any, Callable, Dict, List, Optional, Union, Tuple

import torch
from torch import tensor, save

from src.data.processing.datasets import HOMRDataset
from src.models.abstract_models.base_models import BinaryClassifier

class TorchBinaryClassifierWrapper(BinaryClassifier):
    """
    Class used as a wrapper for binary classifier inheriting from TorchCustomModel
    """

    def __init__(self,
                 model: Callable,
                 classification_threshold: float = 0.5,
                 weight: float = 0.5,
                 train_params: Optional[Dict[str, Any]] = None):

        """
        Sets the model protected attribute and other protected attributes via parent's constructor

        Args:
            model: classification model inheriting from TorchCustomModel
            classification_threshold: threshold used to classify a sample in class 1
            weight: weight attributed to class 1
            train_params: evaluating parameters proper to model for fit function
        """
        self._model = model
        super().__init__(classification_threshold=classification_threshold,
                         weight=weight,
                         train_params=train_params)

    @property
    def model(self) -> Callable:
        return self._model

    def fit(self, dataset: Union[HOMRDataset, Tuple[HOMRDataset, tensor, tensor]]) -> None:
        """
        Fits the model to the evaluating data

        Args:
            dataset: HOMRDataset which its items are tuples (x, y, idx) where
                           - x : (N,D) tensor or array with D-dimensional samples
                           - y : (N,) tensor or array with classification labels
                           - idx : (N,) tensor or array with idx of samples according to the whole dataset

        Returns: None
        """

        # We extract all labels
        _, y_train, _ = dataset[list(range(len(dataset)))]

        # Store the model in the appropriate device
        self._model = self._model.to(self._model._device)

        # Call the fit method
        self._model.fit(dataset, sample_weights=None, **self.train_params)

    def plot_evaluations(self, save_path: Optional[str] = None) -> None:
        """
        Plots the evaluating and valid curves saved

        Args:
            save_path: path where the figures will be saved

        Returns: None
        """
        if hasattr(self._model, 'plot_evaluations'):
            self._model.plot_evaluations(save_path=save_path)

    def predict_proba(self,
                      dataset: HOMRDataset,
                      mask: Optional[List[int]] = None) -> tensor:
        """
        Returns the probabilities of being in class 1 (OYM = 1) for all samples
        in a particular set (default = test)

        Args:
             dataset: HOMRDataset which its items are tuples (x, y, idx) where
                     - x : (N,D) tensor or array with D-dimensional samples
                     - y : (N,) tensor or array with classification labels
                     - idx : (N,) tensor or array with idx of samples according to the whole dataset
            mask: List of dataset idx for which we want to predict proba

        Returns: (N,) tensor
        """

        # Call predict_proba method, takes the prediction for class 1 and squeeze the array
        proba = self._model.predict_proba(dataset, mask)

        if isinstance(proba, tuple):
            proba, embeddings = proba
            return proba.squeeze(), embeddings
        return proba.squeeze()

    def save_model(self, path: str) -> None:
        """
        Saves the model to the given path

        Args:
            path: save path

        Returns: None
        """

        save(self._model, os.path.join(path, "torch_model.pt"))


# -*- coding: utf-8 -*-
from __future__ import division
import numpy as np
from procedural_city_generation.additional_stuff.Singleton import Singleton

singleton=Singleton("roadmap")

def getRule(vertex):
    """
    Gets the correct growth_rule for a Vertex, depending on that objects'
    xy coordinates and the growth_rule_image

    Parameters
    ----------
    vertex : Vertex object

    Returns
    -------
    tuple(int, np.ndarray(3, ) , float)
        (int) for choosing the correct growth rule,
        (np.ndarray) for center in case that the radial rule is chosen,
        (float) for population_density
    """
    x = (vertex.coords[0]+singleton.border[0])/(singleton.border[0]*2)
    y = (vertex.coords[1]+singleton.border[1])/(singleton.border[1]*2)

    population_density = np.sqrt((singleton.img2[singleton.img2.shape[0]-y*singleton.img2.shape[0]][x*singleton.img2.shape[1]][0])/255)
    if vertex.seed:
        return (4, None, population_density)

    if not vertex.minor_road:
        #Finds the relative position of the vertex on the growth_rule_image
        intrule=np.argmax(singleton.img[singleton.img.shape[0]-y*singleton.img.shape[0]][x*singleton.img.shape[1]])
        z=(0, 0)

        #If the rule is radial, find the closest radial center
        if intrule == 2:
            z=singleton.center[np.argmin(np.linalg.norm(vertex.coords-singleton.center, axis=1))]
        return (intrule, z, population_density)
    else:
        return (3, None, population_density)


from BinaryTree import BinaryTree

def ParseTree(expression):
	expressionList = expression.split()
	stack = Stack() #Stack needs to be imported
	expressionTree = BinaryTree('') #BinaryTree needs to be imported
	stack.push(expressionTree)
	currentTree = expressionTree

	for i in expressionList:
		if i == "(":
			expressionTree.insertLeft('')
			stack.push(currentTree)
			currentTree = currentTree.getLeftChild()
		elif i not in ['*', '+', '-', '/', ')']:
			currentTree.setRootValue(int(i))
			parent = stack.pop()
			currentTree = parent
		elif i in ['*', '+', '-', '/']:
			currentTree.setRootValue(i)
			currentTree.insertRight('')
			stack.push(currentTree)
			currentTree = currentTree.getRightChild()
		elif i == ')':
			currentTree = stack.pop()
		else:
			raise ValueError
	return expressionTree

	pt = ParseTree("( ( 2 * 2 ) + 1 ) ")
	pt.postOrder()


# https://www.welcomekakao.com/learn/courses/30/lessons/42629?language=python3

import heapq

import heapq

def solution(stock, dates, supplies, k):
    curr = stock
    supplies_minus = map(lambda x: -x, supplies)
    heap = list(zip(supplies_minus, dates)) # max heap을 이용하기 위해 supply를 음수로 저장
    heapq.heapify(heap)
    count = 0

    while curr < k:
        arr = []
        while True:
            supply, date = heapq.heappop(heap)
            # 해당 date에 사용 가능
            if date <= curr:
                count += 1
                curr += supply * -1
                break

            else:
                arr.append((supply, date))

        for (supply, date) in arr:
            heapq.heappush(heap, (supply, date))

    return count


from etherscan.contracts import Contract
from EtherscanAPI import EtherscanAPI

import os
import json

DATA_DIR = './ContractData'
api = EtherscanAPI()
API_KEY = api.key
api._create_data_folder(DATA_DIR)

def save_json(data, filename, save):
    if save:
        filepath = os.path.join(DATA_DIR, filename)
        with open(filepath, 'w') as json_file:
            json.dump(data, json_file, indent=4)

def save_sol(data, filename, save):
    if save:
        filepath = os.path.join(DATA_DIR, filename)
        with open(filepath, 'w') as sol_file:
            sol_file.write(data)

if __name__=='__main__':
    test_address = '0xfb6916095ca1df60bb79ce92ce3ea74c37c5d359'

    contract = Contract(address=test_address, api_key=API_KEY)
    abi = contract.get_abi()
    js = json.loads(abi)
    abi_filename = f'abi-address-{test_address}.json'
    save_json(js, abi_filename, save=True)

    sourcecode = contract.get_sourcecode()
    sourcecode_filename = f'contract-sourcecode-address-{test_address}.sol'
    save_sol(sourcecode[0]['SourceCode'], sourcecode_filename, save=True)


import numpy as np
from Decision_Problems.decision_problem import Decision_Problem
from Decision_Problems.training_data import *
import math
#import matplotlib.pyplot as plt

## WARNING! This decision problem has a  non-standard internal structure

class Sleeping_Beauty_by_bet(Decision_Problem):

    # Reward given by bet, should result in SIA/thirder

    def __init__(self):
        self.actions = ["GUESS HEADS", "GUESS TAILS"]

        self.states = [(coin, day, bet) for coin in ["Heads","Tails"]
                                        for day in ["Monday", "Tuesday", "END"]
                                        for bet in ["Heads","Tails", "_"]
                                        ]

        self.epistemic_states = ["Awake","END"]

        self.description = "Sleeping Beauty, reward by bet"

    def reset_with(self, agent):
        self.finished = False
        HEADS = np.random.choice([True, False], 1, p=[0.5, 0.5])[0]
        if HEADS:
            self.state = ("Heads", "Monday", "_")
        else:
            self.state = ("Tails", "Monday", "_")

    def utility(self, state):
        coin, day, bet = state
        if coin == bet:
            return 1
        else:
            return 0

    def epistemic_state(self):
        coin, day, bet = self.state
        if day == "END":
            return "END"
        else:
            return "Awake"

    def cause(self, state, action):

        coin, day, bet = state

        if action == "GUESS HEADS":
            bet = "Heads"
        elif action == "GUESS TAILS":
            bet = "Tails"
        else:
            print("Something is wrong in sleeping beauty cause")

        if (day == "Monday" and coin == "Heads") or (day == "Tuesday"):
            day = "END"
        elif (day == "Monday" and coin == "Tails"):
            day = "Tuesday"
        else:
            print("Something is wrong in sleeping beauty cause")

        return coin, day, bet

    def is_final_state(self, state):
        coin, day, bet = state
        return day == "END"

class Sleeping_Beauty_by_game(Sleeping_Beauty_by_bet):

    # Reward given by game, should result in SSA/halfer

    def __init__(self):
        Sleeping_Beauty_by_bet.__init__(self)
        self.description = "Sleeping Beauty, reward by game"

    def play(self, agent):

            self.reset_with(agent)
            while not self.finished:

                epistemic_state = self.epistemic_state()
                action_distribution = agent.get_action_distribution(epistemic_state)
                action = np.random.choice(self.actions, 1, p=action_distribution)[0]
                _, reward = self.do(action)
                step = Step(epistemic_state, action, reward)

            episode = Episode(reward, [step])
            return episode


# Sudoku Killer/Sandwich Calculator

#   This program will calculate all possible combinations that a pool of digits add or multiply to a given number

import itertools                            # Import library needed for calculating all combinations
import math                                 # Import library for calculating product of all elements in an iterable

totalNum = ""                               # The number to sum/multiple to
totalPrompt = False                         # Track if user was prompted to enter the total, yet
poolList = [1, 2, 3, 4, 5, 6, 7, 8, 9]      # The pool of numbers to sum/multiply
excludePrompt = False                       # Track if user was prompted to exclude, yet
excludeConf = ""                            # Yes/no if numbers should be excluded from pool
excludeTemp = ""                            # Temporary storage of numbers to exclude
excludelist = ""                            # The numbers we want to exclude from the pool
multList = ""                               # The list of combinations that multiply to numFinal
operConf = ""                               # Choice of operation to complete at end of program
operPrompt = False                          # Track if user entered valid operation

# This function adds up all combinations of digits in pool and prints all that add to total
def summate(total, pool):

    sumsList = [""]                         # The list of combinations that sum to numFinal

    sums = itertools.chain(itertools.combinations(pool, r=n) for n in range(1,len(pool)+1))

    for it in  sums:
        for s in it:
            #print ( f"sum{s} = {s if isinstance(s,int) else sum(s)}")
            if sum(s) == total:
                sumsList.append(s)

    print(sumsList)

# This function multiplies all combinations of digits in pool and prints all that multiply to total
def multimate(total, pool):

    multiList = [""]                            # The list of combinations that multiply to numFinal

    products = itertools.chain(itertools.combinations(pool, r=n) for n in range(1,len(pool)+1))

    for it in  products:
        for s in it:
            if math.prod(s) == total:
                multiList.append(s)

    print(multiList)

# Ask user for the final number to sum/mult to and check if its a valid entry
while totalNum.isnumeric() == False or totalNum == 0:

    if totalPrompt == False: # The first prompt

        totalNum = input("Please enter the non-negative whole number you want to sum/multiply to: ")

        totalPrompt = True

    else: # Subsequent prompts

        totalNum = input("Invalid entry. Please enter a non-negative whole number: ")

        totalPrompt = True

totalNum = int(totalNum) # Typecast the total to an integer for comparing later

while excludePrompt == False:

    print("The current pool:", poolList) # Display the current pool before each prompt

    excludeTemp = input("Enter a digit to exclude from the pool (enter 0 to continue): ")

    if excludeTemp.isnumeric() == True: # Test if the input is a positive whole number

        if excludeTemp == "0": # If input is 0, exit loops and continue with program

            excludePrompt = True
            excludeConf = "no"

        elif int(excludeTemp) in poolList: # If the input is in the current pool list, remove it

            excludeTemp = int(excludeTemp)
            poolList.remove(excludeTemp)

        elif int(excludeTemp) not in poolList: # If input isn't found in the pool, prompt again

            print("Entry not found in the pool.")

    else: print("Invalid entry.")

while operPrompt == False:
    operConf = input("Please enter what operation you would like to use (Sum, Multiply, Both): ")

    if operConf.lower() == "sum":

        summate(totalNum, poolList)
        operPrompt = True

    elif operConf.lower() == "multiply":

        multimate(totalNum, poolList)
        operPrompt = True

    elif operConf.lower() == "both":

        summate(totalNum, poolList)
        multimate(totalNum, poolList)
        operPrompt = True


__author__ = 'pretymoon'

g = [[1], [-1, 2], [2, -1, -1], [5, 5, 1, 3], [-1, -1, 4, -1, 1]]
# g = [[4], [1, -1], [-1, 1, 1]]

n_nodes = len(g) + 1  # number of nodes
n_rows = n_nodes
n_col = n_nodes - 1
n_k = n_nodes + 1   # number of iteration before finding all_pair_shortest_path, one for direct connection without
                    # any nodes in between, and after that add one node at at time ( in each iteration)

dist = []
for i in range(n_rows):
    dist.append([])
    if i < n_rows - 1:
        dist[-1] = [float("inf") for j in range(i+1)]
        dist[-1][i] = 0
    else:
        dist[-1] = [float("inf") for j in range(i)]

for i in range(len(g)):  # iteration number 0, only direct connections through direct edge between two nodes
    for j in range(len(g[i])):
        if g[i][j] > 0:
            dist[i+1][j] = g[i][j]

for k in range(1, n_k):     # iterate over (number of) valid nodes to be used in this iteration
                            # add one node at each iteration to valid nodes
    for i in range(len(dist)):  # for all nodes
        for j in range(len(dist[i])):  # calculate distance from only nodes with smaller index
            if k == n_k - 1 and i == len(dist) - 1:  # no need to compare very last node with itself
                print(k, i)
                break

            if i < k - 1:  # in order to refer to table dist correctly, the larger index has to come first
                left = dist[k-1][i]
            else:
                left = dist[i][k-1]

            if j < k - 1:  # in order to refer to table dist correctly, the larger index has to come first
                right = dist[k-1][j]
            else:
                right = dist[j][k-1]

            tmp = left + right
            if tmp < dist[i][j]:
                dist[i][j] = tmp

for i in range(len(dist)):
    print(dist[i])