import copy
from os.path import dirname, exists, join

import numpy as np
import pytest
import torch

def _demo_mm_inputs(num_kernels=0, input_shape=(1, 3, 300, 300),
                    num_items=None):  # yapf: disable
    """Create a superset of inputs needed to run test or train batches.

    Args:
        input_shape (tuple): Input batch dimensions.

        num_items (None | list[int]): Specifies the number of boxes
            for each batch item.
    """

    (N, C, H, W) = input_shape
    rng = np.random.RandomState(0)
    imgs = rng.rand(*input_shape)

    img_metas = [{
        'img_shape': (H, W, C),
        'ori_shape': (H, W, C),
        'pad_shape': (H, W, C),
        'filename': '<demo>.png',
    } for _ in range(N)]
    relations = [torch.randn(10, 10, 5) for _ in range(N)]
    texts = [torch.ones(10, 16) for _ in range(N)]
    gt_bboxes = [torch.Tensor([[2, 2, 4, 4]]).expand(10, 4) for _ in range(N)]
    gt_labels = [torch.ones(10, 11).long() for _ in range(N)]

    mm_inputs = {
        'imgs': torch.FloatTensor(imgs).requires_grad_(True),
        'img_metas': img_metas,
        'relations': relations,
        'texts': texts,
        'gt_bboxes': gt_bboxes,
        'gt_labels': gt_labels
    }
    return mm_inputs

def _get_config_directory():
    """Find the predefined detector config directory."""
    try:
        # Assume we are running in the source mmocr repo
        repo_dpath = dirname(dirname(dirname(__file__)))
    except NameError:
        # For IPython development when this __file__ is not defined
        import mmocr
        repo_dpath = dirname(dirname(mmocr.__file__))
    config_dpath = join(repo_dpath, 'configs')
    if not exists(config_dpath):
        raise Exception('Cannot find config path')
    return config_dpath

def _get_config_module(fname):
    """Load a configuration as a python module."""
    from mmcv import Config
    config_dpath = _get_config_directory()
    config_fpath = join(config_dpath, fname)
    config_mod = Config.fromfile(config_fpath)
    return config_mod

def _get_detector_cfg(fname):
    """Grab configs necessary to create a detector.

    These are deep copied to allow for safe modification of parameters without
    influencing other tests.
    """
    config = _get_config_module(fname)
    config.model.class_list = None
    model = copy.deepcopy(config.model)
    return model

@pytest.mark.parametrize('cfg_file', [
    'kie/sdmgr/sdmgr_novisual_60e_wildreceipt.py',
    'kie/sdmgr/sdmgr_unet16_60e_wildreceipt.py'
])
def test_sdmgr_pipeline(cfg_file):
    model = _get_detector_cfg(cfg_file)
    model['pretrained'] = None

    from mmocr.models import build_detector
    detector = build_detector(model)

    input_shape = (1, 3, 128, 128)

    mm_inputs = _demo_mm_inputs(0, input_shape)

    imgs = mm_inputs.pop('imgs')
    img_metas = mm_inputs.pop('img_metas')
    relations = mm_inputs.pop('relations')
    texts = mm_inputs.pop('texts')
    gt_bboxes = mm_inputs.pop('gt_bboxes')
    gt_labels = mm_inputs.pop('gt_labels')

    # Test forward train
    losses = detector.forward(
        imgs,
        img_metas,
        relations=relations,
        texts=texts,
        gt_bboxes=gt_bboxes,
        gt_labels=gt_labels)
    assert isinstance(losses, dict)

    # Test forward test
    with torch.no_grad():
        batch_results = []
        for idx in range(len(img_metas)):
            result = detector.forward(
                imgs[idx:idx + 1],
                None,
                return_loss=False,
                relations=[relations[idx]],
                texts=[texts[idx]],
                gt_bboxes=[gt_bboxes[idx]])
            batch_results.append(result)

    # Test show_result
    results = {'nodes': torch.randn(1, 3)}
    boxes = [[1, 1, 2, 1, 2, 2, 1, 2]]
    img = np.random.rand(5, 5, 3)
    detector.show_result(img, results, boxes)


import argparse
import random
import torch
import torch.nn as nn
import torch.optim as optim
from model import CNN
from loss import Energy_Loss
from utils import *
import numpy as np
import time
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA

def build_batch(examples):
    inputs = torch.zeros(1, len(examples), max(len(examples[0])+5, min_len), dtype=torch.long)
    for i, ex in enumerate(examples, 0):
        vec_examples = [tok2index[tok] for tok in ex]
        inputs[0][i][:len(ex)] = torch.tensor(
            vec_examples, dtype=torch.long)
    return inputs

def plot_margins(args, model, vocab):
    model.eval()
    vocabset = set(vocab)
    with torch.no_grad():
        for edit in [1, 2, 3, 4]:
            margin_matrix = torch.zeros(args.num_samples, args.max_k+1)
            for i in range(args.num_samples):
                examples = []
                word = list(random.choice(vocab))
                # compute the k-edit.
                examples.append(word)
                for k in range(1, args.max_k+1):
                    neg = get_edit(word, k, edit)
                    if "".join(neg) in vocabset:
                        examples.append([])
                    else:
                        examples.append(neg)
                inputs = build_batch(examples)
                if args.use_cuda:
                    inputs = inputs.cuda(args.device, non_blocking=True)
                outputs, _ = model(inputs)
                margin = outputs - outputs[0][0]
                margin_matrix[i] = margin

            avgs = [0]
            lbs = [0]
            ubs = [0]
            for col in range(1, args.max_k+1):
                energies = margin_matrix[:,col]
                avgs.append(torch.mean(energies).item())
                lbs.append(np.percentile(energies, 5))
                ubs.append(np.percentile(energies, 95))
            print(avgs)
            print(lbs)
            print(ubs)
            avgs = np.array(avgs)
            lbs = np.array(lbs)
            ubs = np.array(ubs)

            plt.figure()
            plt.errorbar(range(0, args.max_k+1), avgs, yerr=[avgs-lbs, ubs-avgs], fmt='-s')
            plt.savefig('edit{}_margin.png'.format(edit))

def type_edit_pca(args, model, vocab):
    model.eval()
    vocabset = set(vocab)
    with torch.no_grad():
        data_matrix = torch.zeros(args.num_samples, 5, 1000)
        labels = torch.zeros(args.num_samples, 5)
        for i in range(args.num_samples):
            examples = []
            word = list(random.choice(vocab))
            # compute the k-edit.
            examples.append(word)
            for edit in [1, 2, 3, 4]:
                neg = get_edit(word, 1, edit)
                if "".join(neg) in vocabset:
                    examples.append([])
                else:
                    examples.append(neg)
            inputs = build_batch(examples)
            if args.use_cuda:
                inputs = inputs.cuda(args.device, non_blocking=True)
            outputs, reps = model(inputs)
            data_matrix[i] = reps
            labels[i] = torch.tensor([0, 1, 2, 3, 4], dtype=torch.long)
        data_matrix = data_matrix.view(args.num_samples*5,-1)
        labels = labels.view(args.num_samples*5,-1)
        print(data_matrix.size())
        print(labels.numpy().reshape((args.num_samples*5,)).tolist())
        pca = PCA(n_components=2)
        data_pca = pca.fit_transform(data_matrix)
        print(data_pca.shape)
        plt.scatter(data_pca[:,0], data_pca[:,1],s=1, alpha=0.75,
                    c=labels.numpy().reshape((args.num_samples*5,)).tolist(), cmap=plt.cm.get_cmap('Set1', 5))
        plt.colorbar()
        # plt.show()
        plt.savefig("edit_type_pca.png")

def k_edit_pca(args, model, vocab):
    model.eval()
    vocabset = set(vocab)
    with torch.no_grad():
        data_matrix = torch.zeros(args.num_samples, 5, 1000)
        labels = torch.zeros(args.num_samples, 5)
        for i in range(args.num_samples):
            examples = []
            word = list(random.choice(vocab))
            # compute the k-edit.
            examples.append(word)
            for k in range(1, args.max_k+1):
                neg = get_edit(word, k, 4)
                if "".join(neg) in vocabset:
                    examples.append([])
                else:
                    examples.append(neg)
            inputs = build_batch(examples)
            if args.use_cuda:
                inputs = inputs.cuda(args.device, non_blocking=True)
            outputs, reps = model(inputs)
            data_matrix[i] = reps
            labels[i] = torch.tensor([0, 1, 2, 3, 4], dtype=torch.long)
        data_matrix = data_matrix.view(args.num_samples*5,-1)
        labels = labels.view(args.num_samples*5,-1)
        print(data_matrix.size())
        print(labels.numpy().reshape((args.num_samples*5,)).tolist())
        pca = PCA(n_components=2)
        data_pca = pca.fit_transform(data_matrix)
        print(data_pca.shape)
        plt.scatter(data_pca[:,0], data_pca[:,1],s=1, alpha=0.75,
                    c=labels.numpy().reshape((args.num_samples*5,)).tolist(), cmap=plt.cm.get_cmap('Set1', 5))
        plt.colorbar()
        plt.savefig("rep_k_pca.png")

def main():
    parser = argparse.ArgumentParser(
        description='Visualizing margins for energy model')
    parser.add_argument('--vocab_file', type=str, default="data/wikipedia.vocab.txt",
                        help='vocabulary file path')
    parser.add_argument('--model_save_file', type=str, default='models/energy_cnn',
                        help='model save path')
    parser.add_argument('--topk', type=int, default=100000,
                        help="train on top k most common words in vocabulary")
    parser.add_argument('--max_k', type=int, default=4,
                        help="maximum number of edits 0-k")
    parser.add_argument('--num_samples', type=int, default=10000,
                        help="how many samples for each edit value")
    parser.add_argument('--log_rate', type=float, default=1000,
                        help='number of samples per log (default: 1000)')
    parser.add_argument('--no-cuda', action='store_true', default=False,
                        help='disables CUDA training')
    args = parser.parse_args()

    args.use_cuda = not args.no_cuda and torch.cuda.is_available()
    args.device = torch.device("cuda" if args.use_cuda else "cpu")
    print("Using Device: {}".format(args.device))

    # instantiate CNN, loss, and optimizer.
    print("Loading Model from {}".format(args.model_save_file))
    model = CNN(n_chars, 10, 1, 256, [1, 2, 3, 4, 5, 6, 7, 8], 0.25, 1000, 1).to(
        device=args.device)
    # some weird loading, TODO: test this out on gpu.
    if args.use_cuda:
        model.load_state_dict(torch.load(args.model_save_file))
    else:
        model.load_state_dict(torch.load(
            args.model_save_file, map_location=lambda storage, loc: storage))

    # load vocabulary.
    vocab, _ = read_vocab(args.vocab_file, topk=args.topk)

    # plot_margins(args, model, vocab)
    # type_edit_pca(args, model, vocab)
    k_edit_pca(args, model, vocab)

if __name__ == "__main__":
    main()


#Embedded file name: eve/devtools/script\graphstest.py
from carbonui.graphs.axislabels import VerticalAxisLabels
from carbonui.graphs.grid import Grid
import trinity
import random
import uicontrols
import carbonui.const as uiconst
from carbonui.primitives.container import Container
from eve.client.script.ui.control.eveLabel import Label
from carbonui.graphs.linegraph import LineGraph
from carbonui.graphs.donchianchannel import DonchianChannel
from carbonui.graphs.lowhighvaluegraph import LowHighValueGraph
import carbonui.graphs.gridlegends as gridlegends
import carbonui.graphs.graphsutil as graphsutil

class GraphsTest(uicontrols.Window):
    __guid__ = 'form.GraphsTest'
    default_caption = 'Graphs Test'
    default_minSize = (400, 200)
    default_windowID = 'GraphsTest'

    def ApplyAttributes(self, attributes):
        uicontrols.Window.ApplyAttributes(self, attributes)
        self.SetTopparentHeight(0)
        self.topPanel = Container(parent=self.sr.main, align=uiconst.TOTOP, height=30)
        uicontrols.Button(parent=self.topPanel, align=uiconst.TOLEFT, label='Graph', width=120, height=30, func=self.Graph)
        self.main = Container(parent=self.sr.main, align=uiconst.TOALL)
        self.data = []

    def Graph(self, *args):
        self.data = self.RandomData(60)
        self.LineGraph()

    def RandomData(self, numValues = 30):
        values = []
        prev_low = random.randint(5, 300)
        for i in xrange(numValues):
            volume = random.randint(100, 100000)
            low = random.randint(max(prev_low - 30, 5), prev_low + 30)
            high = random.randint(low, low + 10)
            close = random.randint(low, high)
            timestamp = i
            values.append((timestamp,
             low,
             high,
             close,
             volume))
            prev_low = low

        return values

    def SplitData(self, values):
        timeStamps = []
        volData = []
        closeData = []
        lowData = []
        highData = []
        for x in values:
            timeStamps.append(x[0])
            volData.append(x[4])
            closeData.append(x[3])
            lowData.append(x[1])
            highData.append(x[2])

        return (timeStamps,
         volData,
         closeData,
         lowData,
         highData)

    def LineGraph(self):
        self.main.Flush()
        if not self.data:
            return
        self.minGridLineHeight = 32
        timeStamps, volData, closeData, lowData, highData = self.SplitData(self.data)
        width, height = self.main.GetAbsoluteSize()
        width = float(width)
        height = float(height)
        n = len(self.data)
        self.maxValue = float(max(highData))
        adjustedMaxValue, numGridLines = graphsutil.AdjustMaxValue(height, self.maxValue, self.minGridLineHeight)
        gridLineStep = height / numGridLines
        donchianHighData = graphsutil.MovingHigh(highData)
        donchianLowData = graphsutil.MovingLow(lowData)
        movingAvg = graphsutil.MovingAvg(closeData, n=20)
        labelsAndGrid = Container(parent=self.main, align=uiconst.TOALL)
        self.axisLabels = VerticalAxisLabels(parent=labelsAndGrid, align=uiconst.TORIGHT, width=80, padLeft=8, labelClass=Label, fontsize=16, maxValue=adjustedMaxValue, step=gridLineStep, count=numGridLines)
        gridAndGraphs = Container(parent=labelsAndGrid, align=uiconst.TOALL)
        self.graphContainer = Container(parent=gridAndGraphs, align=uiconst.TOALL)
        self.grid = Grid(parent=gridAndGraphs, maxValue=adjustedMaxValue, step=gridLineStep, count=numGridLines)
        self.lowHighValue = LowHighValueGraph(parent=self.graphContainer, data=(lowData, highData, closeData), maxValue=adjustedMaxValue, markerSize=6)
        self.donchianHigh = LineGraph(parent=self.graphContainer, lineWidth=1.25, data=donchianHighData, maxValue=adjustedMaxValue)
        self.donchianLow = LineGraph(parent=self.graphContainer, lineWidth=1.25, data=donchianLowData, maxValue=adjustedMaxValue)
        self.movingAvg = LineGraph(parent=self.graphContainer, lineWidth=1.25, data=movingAvg, maxValue=adjustedMaxValue)
        self.donchianChannel = DonchianChannel(parent=self.graphContainer, color=(0.25, 0, 0, 0.25), data=(donchianLowData, donchianHighData), maxValue=adjustedMaxValue)
        gridlegends.AddHorizontalGridLines(self.gridContainer, numGridLines, gridLineStep, height, width)

    def ResizeLineGraph(self):
        if not self.data:
            return
        width, height = self.graphContainer.GetAbsoluteSize()
        adjustedMaxValue, numGridLines = graphsutil.AdjustMaxValue(height, self.maxValue, self.minGridLineHeight)
        for graph in [self.donchianHigh,
         self.donchianLow,
         self.movingAvg,
         self.donchianChannel,
         self.lowHighValue]:
            graph.maxValue = adjustedMaxValue
            graph.Rebuild()

        gridLineStep = height / numGridLines
        self.axisLabels.maxValue = adjustedMaxValue
        self.axisLabels.count = numGridLines
        self.axisLabels.step = gridLineStep
        self.axisLabels.Rebuild()
        self.grid.count = numGridLines
        self.grid.step = gridLineStep
        self.grid.Rebuild()

    def _OnSizeChange_NoBlock(self, width, height):
        self.ResizeLineGraph()


weight = 10
day = 0
while weight > 0 :
    day += 1
    print(day, "일째")
    if day == 3 :
        print("다이어트 포기 !! ㅠㅠ")
        #break   # 여기서 while문을 빠져나온다.
        continue    #여기서 다이어트를 한 번 쉰다. 그래서 11일까지 가게 된다. 아래 문장들을 실행하지 않는 것.
    print("운동 열심히 !!")
    weight -= 1

print("살은 빼서 뭐해 ㅡ,.ㅡ")


from tests.base import BaseTest

from tenable_io.api.models import AssetsAsset, AssetsAssetList, AssetsAssetSource
from tenable_io.exceptions import TenableIOErrorCode, TenableIOApiException

class TestAssetsApi(BaseTest):

    def test_assets(self, client):
        assets_list = client.assets_api.list()
        assert isinstance(assets_list, AssetsAssetList), u'Get request returns type.'

        for a in assets_list.assets:
            isinstance(a, AssetsAsset), u'Assets property represents type.'
            for s in a.sources:
                isinstance(s, AssetsAssetSource), u'Sources property represents type.'

    def test_asset(self, client):
        try:
            client.assets_api.get('test_assets_asset_info')
            assert False, u'TenableIOApiException should have been thrown for bad ID.'
        except TenableIOApiException as e:
            assert e.code is TenableIOErrorCode.NOT_FOUND, u'Appropriate exception thrown.'


def find(list1,c):
    if(not c in list1):
        return([-1,-1])
    else:
        x=(list1.index(c))
        for i in range(x+1,len(list1)):
            if(list1[i]!=c):
                return[x,i-1]
        return[x,len(list1)-1]

temp=input().split(',')
b=map(eval,temp)
list1=list(b)
c=eval(input())
print(find(list1,c))


#!/usr/bin/python3
# -*- coding: utf-8 -*-
# -*- mode: Python -*-

'''
ccsliders

Midi fader sending cc messages

'''

from tkinter import *

import time
import rtmidi
from rtmidi.midiutil import open_midiinput
from rtmidi.midiconstants import (CHANNEL_PRESSURE, CONTROLLER_CHANGE, NOTE_ON, NOTE_OFF,
                                  PITCH_BEND, POLY_PRESSURE, PROGRAM_CHANGE)

from mido import MidiFile
import mido
import sys
sys.path.append('libs/')
import midi3
midi3.check()

#mididest = 'to Maxwell 1'
mididest =  'electribe2 SOUND'
mididest =  'BCR2000'
cc0 = 0
cc1 = 82
cc2 = 83
cc3 = 84
midichannel = 1

ccs = [0,0,0,0]

# /cc cc number value
def sendcc(ccnumber, value, dest):

    print("Sending Midi channel", midichannel, "cc", ccnumber, "value", value, "to", dest)
    midi3.MidiMsg([CONTROLLER_CHANGE+midichannel-1, ccnumber, value], dest)

class Interface(Frame):

    """Notre fenêtre principale.
    Tous les widgets sont stockés comme attributs de cette fenêtre."""

    def __init__(self, myframe, **kwargs):
        Frame.__init__(self, myframe, width=768, height=576, bg="black", **kwargs)
        self.pack(fill=NONE)
        self.nb_clic = 0

        # Création de nos widgets
        self.message = Label(self, text="Maxwellator",  bg="black", foreground="white")
        self.message.place(x = 0, y = 25)
        self.message.pack()
        #self.message.config(bg="black", foreground="white")

        self.w1 = Scale(self, from_=127, to=0,  bg="black", foreground="white")
        self.w1.pack(side="left")
        self.w2 = Scale(self, from_=127, to=0, bg="black", foreground="white")
        self.w2.pack(side="left")
        self.w3 = Scale(self, from_=127, to=0,  bg="black", foreground="white")
        self.w3.pack(side="left")
        self.w4 = Scale(self, from_=127, to=0,  bg="black", foreground="white")
        self.w4.pack(side="left")

        self.w5 = Scale(self, from_=127, to=0,  bg="black", foreground="white")
        self.w5.pack(padx =1, pady=30)

        self.quit_button = Button(self, text="Quit", command=self.quit)
        #self.quit_button.configure(background = "green")
        self.quit_button.pack(side="bottom")
        self.update_cc()
        '''
        self.bouton_cliquer = Button(self, text="Cliquez ici", fg="red",
                command=self.cliquer)
        self.bouton_cliquer.pack(side="right")
        '''

    def update_cc(self):

        cc0value = int(self.w1.get())
        cc1value = int(self.w2.get())
        cc2value = int(self.w3.get())
        cc3value = int(self.w4.get())

        if cc0value !=  ccs[0]:
            sendcc(cc0, cc0value, mididest)
            ccs[0] = cc0value
            newcc = "CC", cc0, ":", str(cc0value)
            #print(newcc)
            self.message.configure(text = newcc)

        if cc1value !=  ccs[1]:
            sendcc(cc1, cc1value, mididest)
            ccs[1] = cc1value
            newcc = "CC", cc1, ":", str(cc1value)
            #print(newcc)
            self.message.configure(text = newcc)

        if cc2value !=  ccs[2]:
            sendcc(cc2, cc2value, mididest)
            ccs[2] = cc2value
            newcc = "CC", cc2, ":", str(cc2value)
            #print(newcc)
            self.message.configure(text = newcc)

        if cc3value !=  ccs[3]:
            sendcc(cc3, cc3value, mididest)
            ccs[3] = cc3value
            newcc = "CC", cc3, ":", str(cc3value)
            print(newcc)
            self.message.configure(text = newcc)

        #print( 'CC', cc0,':', PrettyFloat(cc1value), ' CC', cc1, ":", PrettyFloat(cc1value),' CC', cc2, ":", PrettyFloat(cc2value)," CC",cc3,":",PrettyFloat(cc3value))
        '''
        with open('/tmp/ws.json', 'w') as outfile:
            json.dump(data, outfile)
        '''

        self.after(100, self.update_cc)
    '''
    def cliquer(self):
        """Il y a eu un clic sur le bouton.

        On change la valeur du label message."""

        self.nb_clic += 1
        self.message["text"] = "Vous avez cliqué {} fois.".format(self.nb_clic)
    '''

myframe = Tk()
interface = Interface(myframe)
interface.mainloop()
interface.destroy()


from django.conf.urls import url
from . import views

app_name = 'election'

urlpatterns = [
    url(r'^createElection/(?P<ecId>\w+)/$', views.createElection, name='createElection'),
    url(r'^candidateList/(?P<voterId>\w+)/$', views.candidateList, name='candidateList'),
    url(r'^adminPanel/(?P<ecId>\w+)$', views.adminPanel, name='adminPanel'),
    url(r'^addCandidate/(?P<ecId>\w+)$', views.addCandidate, name='addCandidate'),
    url(r'^resultAnalysis/(?P<ecId>\w+)$', views.resultAnalysis, name='resultAnalysis'),
]


import sys
from setuptools import setup

install_requires = ["h2>=2.2.0,<3.0.0"]
if sys.version_info < (3, 5):
    install_requires.append("typing")

setup(
    name='asyncio-apns',
    version='0.0.1',
    install_requires=install_requires,
    packages=['asyncio_apns'],
    url='https://github.com/etataurov/asyncio-apns',
    license='MIT',
    author='etataurov',
    author_email='tatauroff@gmail.com',
    description='asyncio client for Apple Push Notification Service'
)


'''
Created on 24 Jun 2016
@author: Andreagiovanni Reina.
University of Sheffield, UK.
'''

# import RungeKutta.bestOfN
import math
import numpy as np
import sys
import os
import copy
import random

# import matplotlib.pyplot as plt
# from plotting import plotit

DEBUG = False
listA = []
listB = []
opdir = '/scratch/data2/'  # os.getcwd()
data_files = []
statusofNA = "none"
time1 = "none"
time2 = "none"
totaltime = 0
alltimes = []
totallist = []

#################FUNCTIONS#########################
def gillespieStep(state, N, gammas, alphas, rhos, sigmas, vectorsOfChange, timeLeft):
    # Computing the probabilities of change
    probabilitiesOfChange = []
    ## A -(x)-> B
    ## x=5   1/s
    ## when the change will happen?
    ## 0.2s  # on average for one A
    ## but you have many A
    ## a is the number of guys in state A
    ## population level transition rate = a*x
    ## A -(x)-> B
    ## B -(y)-> A
    ## B+A -(y)-> A+A
    ## sum of all rates at population level Z = a*x + b*y + b*a*y / (N)^(number of agents involved minus 1)
    ## (N)^(number of agents involved minus 1) --> it means that for
    ###### number of agents involved=1 ---> a*x/ (N^0)  = a*x/1 = a*x
    ###### number of agents involved=2 ---> b*a*y/ (N^1)  = b*a*x/N
    ## sum of all rates at population level Z = a*x + b*y + b*a*y/N
    ## from Z we compute WHEN the change will happen
    ## what about which change (that is, if x or y)?
    ## probabilitiesOfChange = [ a*x , b*y , b*a*x/N ]
    numOptions = int((len(state) - 1) / 2)
    for i in range(0, numOptions):  # PAY ATTENTION THAT i IS NOT THE CORRECT state[i] BUT IT MUST BE state[i+1], WHILE WORKS FOR gammas[i], alphas[i], rhos[i]
        # Discovery
        # probabilitiesOfChange.append( state[0]*gammas[i]) # U -> A and U -> B
        # Abandonment
        # probabilitiesOfChange.append( state[i+1]*alphas[i] )# A -> U and B -> U

        #############Cross-inhibition#############
        # [ U, AD, BD, AE, BE ]
        # probabilitiesOfChange.append(state[1] * state[2] * ((1 - noisevalue) / (qualities[i] * t_d)) / (N - 1))
        if ((state[1] + state[2])) <= 1:
            probabilitiesOfChange.append(0)
        else:
            probabilitiesOfChange.append(
                state[1] * state[2] * ((1 - noisevalue) / (qualities[i] * t_d)) / ((state[1] + state[2]) - 1))

        ############Recruitment###################
        # probabilitiesOfChange.append(state[0] * state[i + 1] * rhos[i] / (N - 1))  # U + A -> A + A
        # U + Ad --(1-n/tu)-->  Ad + Ae
        # U + Bd  --(1-n/tu)-->  Bd + Be
        if ((state[1] + state[2])) == 0:
            probabilitiesOfChange.append(0)
        else:
            probabilitiesOfChange.append((state[0] * state[i + 1] * ((1 - noisevalue) / t_u)) / (state[1] + state[2]))

        ############# No Cross-inhibtion #############
        # probabilitiesOfChange.append(state[i+1] * state[i+1] * ((1-noisevalue)/(qualities[i]*t_d)) / (N - 1))
        if ((state[1] + state[2])) <= 1:
            probabilitiesOfChange.append(0)
        else:
            probabilitiesOfChange.append(
                state[i + 1] * state[i + 1] * ((1 - noisevalue) / (qualities[i] * t_d)) / ((state[1] + state[2]) - 1))

        ############# Go to Dissemination after Exploration #############
        probabilitiesOfChange.append(state[i + 3] * (1 / t_e))  # AE -> AD and BE -> BD

        #############Noisyyyy Cross-inhibition#############
        # [ U, AD, BD, AE, BE ]
        if ((state[1] + state[2])) <= 1:
            probabilitiesOfChange.append(0)
        else:
            probabilitiesOfChange.append(
                state[1] * state[2] * ((noisevalue) / (qualities[i] * t_d)) / ((state[1] + state[2]) - 1))

        ############Noisyyyy Recruitment###################
        # probabilitiesOfChange.append(state[0] * state[i + 1] * rhos[i] / (N - 1))  # U + A -> A + A
        if ((state[1] + state[2])) == 0:
            probabilitiesOfChange.append(0)
        else:
            probabilitiesOfChange.append((state[0] * state[i + 1] * ((noisevalue) / t_u)) / (state[1] + state[2]))

        ############# No Cross-inhibtion #############
        # probabilitiesOfChange.append(state[i+1] * state[i+1] * ((1-noisevalue)/(qualities[i]*t_d)) / (N - 1))
        if ((state[1] + state[2])) <= 1:
            probabilitiesOfChange.append(0)
        else:
            probabilitiesOfChange.append(
                state[i + 1] * state[i + 1] * ((noisevalue) / (qualities[i] * t_d)) / ((state[1] + state[2]) - 1))

       # probabilitiesOfChange.append(state[i + 1] * ((noisevalue) / (qualities[i] * t_d)))  # AD->BE and BD->AE
       # probabilitiesOfChange.append(state[i + 1] * ((noisevalue) / (qualities[i] * t_d)))  # AD->AE and BD->BE
       # probabilitiesOfChange.append(state[0] * ((noisevalue) / (t_u)))  # U->AE and U->BE

    #  print("PoC:", probabilitiesOfChange)

    probSum = sum(probabilitiesOfChange)
    timeInterval = np.random.exponential(1 / probSum)
    # print(timeInterval)
    # The transition happens after the maximum time length, so we do not include it and terminate the step
    if timeInterval > timeLeft:
        return True, timeLeft

    # Selecting the occurred reaction in a randomly, proportionally to their probabilities
    bottom = 0.0
    # Get a random between [0,1) (but we don't want 0!)
    reaction = 0.0
    while (reaction == 0.0):
        reaction = np.random.random_sample()
    # print("reaction is: ", reaction)

    ## probabilitiesOfChange = [ 0.5 , 0.7 , 0.1 ]  ->> WHICH? the first with prob 0.5/(0.5+0.7+0) and second with prob 0.7/(0.5+0.7+0)
    ## probabilitiesOfChange = [ 0.38 , 0.54 , 0.08 ]  ->> WHICH? the first with prob 0.5/(0.5+0.7+0) and second with prob 0.7/(0.5+0.7+0)
    ## random is 0.6
    ## pick 1 if random <0.38
    ## pick 2 if 0.38 < random < (0.38+0.54)
    ## pick 3 if (0.38+0.54) < random < (0.38+0.54+0.08)
    # Normalising probOfChange in the range [0,1]
    probabilitiesOfChange = [pc / probSum for pc in probabilitiesOfChange]
    #  print("Norm PoC:", probabilitiesOfChange)
    # print("Add Norm PoC:", sum(probabilitiesOfChange))

    index = -1
    for i, prob in enumerate(probabilitiesOfChange):
        #  print("prob in arr:", prob)
        if (reaction >= bottom and reaction < (bottom + prob)):
            index = i
            break
        bottom += prob
    #  print(i, prob, bottom)

    # print("timeInterval is", timeInterval)
    # print("reaction is", reaction)
    # print("index is ", index)

    if (index == -1):
        print("Transition not found. Error in the algorithm execution.")
        # sys.exit()
    # print(state)
    #  print(vectorsOfChange[index])
    state += np.array(vectorsOfChange[index])
    print(state)
    if (state[0] < 0):
        print("exittinngggg!!!!")
        print("len of poc", len(probabilitiesOfChange))
        print("len of vectors of change", len(vectorsOfChange))

        sys.exit()
    return False, timeInterval

def runGillespie(state, T, N, gammas, alphas, rhos, sigmas, rnd_seed, finalStateFile, temporalEvolution, plot_evo,
                 extraLog, quorum):
    np.random.seed(rnd_seed)
    n = len(gammas)
    state = np.array(state)
    print("State on enteringg: ", state)
    t = 0
    # if DEBUG:
    #    print("t: ", t, "state: ", state)

    # Opening output file if needed
    if (temporalEvolution != "none"):
        os.makedirs(os.path.dirname(temporalEvolution), exist_ok=True)
        evoStream = open(temporalEvolution, "w+")
        out = str(t) + "\t" + '\t'.join(str(x) for x in state) + "\t" + str(noisevalue) + "\n"
        evoStream.write(out)

    # Creating the list of vector of change
    vectorsOfChange = []
    for i in [1, 2]:
        if (i == 1):  # pop A
            # [U AD BD AE BE]  # the important thing is that sum is ZERO
            negative = [1, -1, 0, 0, 0]  # for cross inhibition
            plus = [-1, 0, 0, 1, 0]  # for recruitment
            sameplus = [0, -1, 0, 1, 0]  # for no-crossinhibition in voting
            expplorationend = [0, 1, 0, -1, 0] #for exploration to dissem

            noisecrossinhib = [0, -1, 0, 1, 0] # for noisy cross inhibition
            noiserecruitment = [-1, 0, 0, 0, 1] # for noisy recruitment
            noisenocross = [1, -1, 0, 0, 0] # for noisy no cross-inhibition recruitment

        if (i == 2):  # pop B
            negative = [1, 0, -1, 0, 0]
            plus = [-1, 0, 0, 0, 1]
            sameplus = [0, 0, -1, 0, 1]
            expplorationend = [0, 0, 1, 0, -1]

            noisecrossinhib = [0, 0, -1, 0, 1]
            noiserecruitment = [-1, 0, 0, 1, 0]
            noisenocross = [1, 0, -1, 0, 0]

        #         # Positive change
        #         plus = [-1] + [0]*n
        #         plus[i+1] = 1
        #         # Negative change
        #         negative = [1] + [0]*n
        #         negative[i+1] = -1

        # Discovery
        # vectorsOfChange.append( plus )
        # Abandonment
        # vectorsOfChange.append( negative )
        # Recruitment
        vectorsOfChange.append(negative)
        vectorsOfChange.append(plus)

        vectorsOfChange.append(sameplus)
        vectorsOfChange.append(expplorationend)
        vectorsOfChange.append(noisecrossinhib)
        vectorsOfChange.append(noiserecruitment)
        vectorsOfChange.append(noisenocross)
        ## vectorsOfChange for the case n=2        ## plusDicoveryOfA  minusAbandonmentOfA  plusRecruitA  plusInhibitionA plusRecruitFromZealotA  plusInhibitionFromZealotA  plusDicoveryOfB minusAbandonmentOfB  plusRecruitB  plusInhibitionB plusRecruitFromZealotB  plusInhibitionFromZealotB

    print("VoC:", vectorsOfChange)

    quorum_reached = False
    while t < T:
        previous_state = copy.deepcopy(state)

        sim_finished, time_step = gillespieStep(state, N, gammas, alphas, rhos, sigmas, vectorsOfChange, T - t)
        # update time variable
        print(state[1])
        t += time_step
        # update SPD matrix which keeps track of the time spent in each state
        spd[int(previous_state[1]) + int(previous_state[3])][
            int(previous_state[2]) + int(previous_state[4])] += time_step

        if (temporalEvolution != "none"):
            # if (t>1000000):#999000
            out = str(t) + "\t" + '\t'.join(str(x) for x in state) + "\t" + str(noisevalue) + "\n"
            evoStream.write(out)
        # print("out", out)
        # out = str(t) + "\t" + '\t'.join(str(x) for x in state) + "\t"
        # evoStream.write(out)
        #   #print("t: ", t, "state: ", state)
        """
        if whichAvg == "Aavg":
            if float(state[1] > S*0.5):
                listA.append(float(state[1]))
        else:
            if float(state[2] > S*0.5):
                listB.append(float(state[2]))
        """
        ## Checking each timestep if the quorum is reached
        if (quorum > 0):  # 0.79>0 true
            # quorum_reached = False
            for i in np.arange(1, len(state) - 2):
                # print (i);
                # if (int(state[i]) > (N-Z)*quorum):
                if ((state[i] + state[i + 2]) >= N * quorum):
                    # print("reaches quorum")
                    quorum_reached = True
                    break
        if sim_finished or quorum_reached:
            break
    # print((np.array(spd)).shape)
    out = str(t) + "\t" + '\t'.join(str(x) for x in state) + "\t" + str(noisevalue)
    # print(out)
    if (finalStateFile != "none"):
        os.makedirs(os.path.dirname(finalStateFile), exist_ok=True)
        with open(finalStateFile, "a") as f:
            out = '\t'.join(str(x) for x in extraLog)
            if (len(out) > 0): out += '\t'
            out += str(t) + "\t" + '\t'.join(str(x) for x in state) + "\n"
            f.write(out)
    # if DEBUG:
    #     out = '\t'.join(str(x) for x in extraLog)
    #     if (len(out)>0): out += '\t'
    #     out += str(t) + "\t" + '\t'.join(str(x) for x in state) + "\n"
    #     print(out)
    """
    theAavg = 0
    theBAvg = 0
    if whichAvg == "Aavg":
        if len(listA) !=0:
            theAavg = np.mean(listA)
            print("A-Average:",theAavg)
    else:
        if len(listB) !=0:
            theBAvg = np.mean(listB)
            print("B-Average:",theBAvg)
    """
    if (plot_evo):
        if (temporalEvolution == "none"):
            print(
                "WARNING! - to plot the temporal evolution, please specify a temporalEvolution file (e.g., a temp-file)")
        # else:
        #   plotit(temporalEvolution, T, state, N, evoStream, 0, state[1], state[2], state[3],state[4], qualities[0])

##################################################

if __name__ == '__main__':

    repetitions = 500

    # Computing input params
    #     valuesA = np.arange(7.5, 13, 0.5)
    noisevalue = float(sys.argv[7])
    ## noisetype = sys.argv[8]
    ##  if noisetype == "TypeA":
    ##      noisetype1 = noisevalue
    ##      noisetype2 = [0, 0]
    ##  else:
    ##      noisetype1 = 0
    ##      noisetype2 = [noisevalue, noisevalue]
    qualities = [1, float(sys.argv[6])]
    qa = [float(sys.argv[6])]
    print(qualities)
    #     valuesB = np.arange(6.5, 15.01, 0.1)
    n = 2
    k = 0
    h = 1

    # CHANGED
    # Experiment time length
    T = int(sys.argv[1])
    # Setup the initial state
    N = int(sys.argv[2])
    t_u = float(sys.argv[3])
    t_d = int(sys.argv[4])
    t_e = int(sys.argv[5])
   #### nr1 = [1 - float(sys.argv[9]), float(sys.argv[9])]
   #### nr2 = [float(sys.argv[9]), 1 - float(sys.argv[9])]

    quorum=0
    #quorum=0.7
    #quorum = float(1 - float(sys.argv[7]))
    ##whichrun = sys.argv[3]
    # SA = (N - Z) / 2
    # SB = (N - Z) / 2
    # create data structure of the size of all possible states
    spd = [[0] * (int(N) + 1) for _ in range(int(N) + 1)]
    # print(len(spd[2]))
    ## (keep in mind that it may not sum up to N for certain conditions... we may look at this later)
    #    state = [N-Z] + [0]*n + [Z/2] + [Z/2]

    if sys.argv[8].lower() == 'true':
        plot_evo = True
    elif sys.argv[8].lower() == 'false':
        plot_evo = False

    for valueA in qa:
        finalStateFile = 'none'
        finalStateFile = 'data/fs_0.00q_n_' + str(noisevalue) + '_h_' + str(N) + '_vA_' + str(qa) +'tutdte'+str(t_u)+str(t_d)+str(t_e)+ '_r1.txt'
        #         valuesB = np.arange(valueA-3, valueA+3.01, 0.1)
        valuesB = [1]
        for valueB in valuesB:
            gammas = [k * valueA] + [k * valueB] * (n - 1)
            alphas = [k / valueA] + [k / valueB] * (n - 1)
            # gammas = [0] + [0]
            # alphas = [0] + [0]
            rhos = [h * valueA] + [h * valueB] * (n - 1)
            sigmas = [h * valueA] + [h * valueB] * (n - 1)
            for i in range(0, repetitions):

                theexplorationstate = ((t_e / (t_e + t_d)) * N)
                state = [0, round((N - theexplorationstate) / 2), round((N - theexplorationstate) / 2),
                         round(theexplorationstate / 2), round(theexplorationstate / 2)]
               # state = [0,N/4,N/4,N/4,N/4]
                #print(state)
                # state = U, AD, BD, AE, BE
                """
                # Compute a random point in the 3-simplex [U,A,B]
                r1 = np.sqrt(np.random.rand())
                r2 = np.random.rand()
                SU = int(r1 * (1 - r2) * N)
                SA = int(r1 * r2 * N)
                SB = int((1 - r1 * (1 - r2) - r1 * r2) * N)
                while SU + SA + SB < N:
                    rnd = np.random.rand()
                    if rnd < 0.33333:
                        SU += 1
                    elif rnd < 0.66666:
                        SA += 1
                    else:
                        SB += 1
                n= 5
                total = N
                dividers = sorted(random.sample(range(1, total), n - 1))
                thelistofdivisions = [a - b for a, b in zip(dividers + [total], [0] + dividers)]
                state = [thelistofdivisions[0], thelistofdivisions[1], thelistofdivisions[2],thelistofdivisions[3],thelistofdivisions[4]]
                """
                print(N, "Finding CDCI:", "(", state, ")  QRatio: ", qualities)

                rnd_seed = np.random.randint(4325344)
                temporalEvolution = 'none'
                #temporalEvolution = 'evo'+'/popevoci_' + str(state) + str(t_u) + "td" + str(t_d) + "te" + str(t_e) + "_" + str(
                #    noisevalue) + "noise_" + "500ksteps_" + str(repetitions) + "runs_" + str(N) + "agents_" + str(
                #    qualities) + str(quorum) + '/' + 'evo-N_' + str(noisevalue)+"_"+str(qa)+"_" +str(i) + str(rnd_seed) + '.txt'
                rnd_seed = np.random.randint(4325344)
                # rnd_seed = 43431
                print(rnd_seed)
                # S = N
                """
                if whichrun == "Afull":
                    SA = S
                    SB = 0
                    SU = 0
                elif whichrun == "Bfull":
                    SA = 0
                    SB = S
                    SU = 0
                else:

                # Compute a random point in the 3-simplex [U,A,B]
                r1 = np.sqrt(np.random.rand())
                r2 = np.random.rand()
                SU = int(r1 * (1 - r2) * N)
                SA = int(r1 * r2 * N)
                SB = int((1 - r1 * (1 - r2) - r1 * r2) * N)
                while SU + SA + SB < N:
                    rnd = np.random.rand()
                    if rnd < 0.33333:
                        SU += 1
                    elif rnd < 0.66666:
                        SA += 1
                    else:
                        SB += 1
                n= 5
                total = N
                dividers = sorted(random.sample(range(1, total), n - 1))
                thelistofdivisions = [a - b for a, b in zip(dividers + [total], [0] + dividers)]
                state = [thelistofdivisions[0], thelistofdivisions[1], thelistofdivisions[2],thelistofdivisions[3],thelistofdivisions[4]]
                """
                # state = [0,12,12,12,13]
                # theexplorationstate = ((t_e / (t_e + t_d)) * N)
                # state = [0, round((N - theexplorationstate) / 2), round((N - theexplorationstate) / 2),
                #        round(theexplorationstate / 2), round(theexplorationstate / 2)]
                # state = [0,N/4,N/4,N/4,N/4]
                # print(state)
                # state = U, AD, BD, AE, BE
                print(N, "Finding CDCI:", "(", state, ")  QRatio: ", qualities)
                # state = [N-Z] + [0]*n + [Z/n]
                plt = runGillespie(state, T, N, gammas, alphas, rhos, sigmas, rnd_seed, finalStateFile,
                                   temporalEvolution, plot_evo, extraLog=[valueA, valueB], quorum=quorum)
# Normalise the SPD: divide every value by the maximum time T
for a in range(int(sum(state[0:3])) + 1):
    for b in range(int(sum(state[0:3])) + 1):
        spd[a][b] /= repetitions * T
print(np.array(spd))
randno = random.randint(0,9)
randno2 = random.randint(0,9)
randno3 = random.randint(0,9)
randno4 = random.randint(0,9)
outputname =  "/home/rzakir/Programs/gillespieaccnew/matrix/outputoftu"  + str(state) + str(t_u) + "td" + str(t_d) + "te" + str(t_e) + "_" + str(noisevalue) + "noise_" + "500ksteps_" + str(repetitions) + "runs_" + str(N) + "agents" + str(qualities)+"_"+str(randno)+str(randno2)+str(randno3)+str(randno4)+ ".txt"
print(spd, file=open(outputname, "a"))
# print(spd, file=open("outputoftu600td1300te3300_0.1noise_500ksteps_500runs_52agents.txt", "a"))


import const
import handler_game
import handler_magic
import merc
import state_checks

def spell_gate(sn, level, ch, victim, target):
    # RT ROM-style gate */
    victim = ch.get_char_world(handler_magic.target_name)
    if not victim \
            or victim == ch \
            or victim.in_room == None \
            or not ch.can_see_room(victim.in_room.instance_id) \
            or state_checks.IS_SET(victim.in_room.room_flags, merc.ROOM_SAFE) \
            or state_checks.IS_SET(victim.in_room.room_flags, merc.ROOM_PRIVATE) \
            or state_checks.IS_SET(victim.in_room.room_flags, merc.ROOM_SOLITARY) \
            or state_checks.IS_SET(victim.in_room.room_flags, merc.ROOM_NO_RECALL) \
            or state_checks.IS_SET(ch.in_room.room_flags, merc.ROOM_NO_RECALL) \
            or victim.level >= level + 3 \
            or (victim.is_clan() and not ch.is_same_clan(victim)) \
            or (not victim.is_npc() and victim.level >= merc.LEVEL_HERO) \
            or (victim.is_npc() and victim.imm_flags.is_set(merc.IMM_SUMMON)) \
            or (victim.is_npc() and handler_magic.saves_spell(level, victim, merc.DAM_OTHER) ):
        ch.send("You failed.\n")
        return

    if ch.pet and ch.in_room == ch.pet.in_room:
        gate_pet = True
    else:
        gate_pet = False

    handler_game.act("$n steps through a gate and vanishes.", ch, None, None, merc.TO_ROOM)
    ch.send("You step through a gate and vanish.\n")
    ch.in_room.get(ch)
    victim.in_room.put(ch)

    handler_game.act("$n has arrived through a gate.", ch, None, None, merc.TO_ROOM)
    ch.do_look("auto")

    if gate_pet:
        handler_game.act("$n steps through a gate and vanishes.", ch.pet, None, None, merc.TO_ROOM)
        instance.characters[ch.pet].send("You step through a gate and vanish.\n")
        instance.characters[ch.pet].in_room.get(instance.characters[ch.pet])
        ch.in_room.put(instance.characters[ch.pet])
        handler_game.act("$n has arrived through a gate.", ch.pet, None, None, merc.TO_ROOM)
        ch.pet.do_look("auto")

const.register_spell(const.skill_type("gate",
                          {'mage': 27, 'cleric': 17, 'thief': 32, 'warrior': 28},
                          {'mage': 1, 'cleric': 1, 'thief': 2, 'warrior': 2},
                          spell_gate, merc.TAR_IGNORE, merc.POS_FIGHTING, None, const.SLOT(83),
                          80, 12, "", "!Gate!", ""))


from estacionamento import Estacionamento
from exceptions import IntervaloInvalidoException

class CalculaAcesso():
    def __init__(self,acesso):
        self.acesso = acesso

    def calculaAcesso(self,estacionamento: Estacionamento):
        if self.acesso.isEvento:
            self.acesso.totalArrecadado += estacionamento.valor_evento
            return estacionamento.valor_evento
        elif self.acesso.isMensalista:
            self.acesso.totalArrecadado += estacionamento.valor_mensalista
            return estacionamento.valor_mensalista

        if self.acesso.isHorarioInvalido(estacionamento.horario_min_funcionamento, estacionamento.horario_max_funcionamento):
            raise IntervaloInvalidoException()

        tempoEstacionado = self.acesso.calculoHoras(self.acesso.horaEntrada, self.acesso.horaSaida)
        if self.acesso.useDiariaNoturna(estacionamento.entrada_noturna, estacionamento.retirada_noturna):
            self.acesso.totalArrecadado += estacionamento.diaria_noturna
            return estacionamento.diaria_noturna
        elif tempoEstacionado < 540:
            valorHoraCheia = self.acesso.getPrecoHoraCheia(estacionamento.valor_fracao, estacionamento.valor_hora, tempoEstacionado)
            valorFracionado = self.acesso.getPrecoHoraFracionada(tempoEstacionado, estacionamento)
            self.acesso.totalArrecadado += valorFracionado + valorHoraCheia
            return valorFracionado + valorHoraCheia
        elif tempoEstacionado >= 540:
            valorDiariaDiurna = self.acesso.useDiariaDiurna(estacionamento)
            self.acesso.totalArrecadado += valorDiariaDiurna
            return valorDiariaDiurna


import csv

def save_pred_paths(folder_path, pred_paths, train_labels):
    print("Normalizing items scores...")
    #Get min and max score to performe normalization between 0 and 1
    score_list = []
    for uid, pid in pred_paths.items():
        for pid, path_list in pred_paths[uid].items():
            if pid in set(train_labels[uid]): continue
            for path in path_list:
                score_list.append(float(path[0]))
    min_score = min(score_list)
    max_score = max(score_list)

    print("Saving pred_paths...")
    with open(folder_path + "/pred_paths.csv", 'w+', newline='') as pred_paths_file:
        header = ["uid", "pid", "path_score", "path_prob", "path"]
        writer = csv.writer(pred_paths_file)
        writer.writerow(header)
        for uid, pid in pred_paths.items():
            for pid, path_list in pred_paths[uid].items():
                if pid in set(train_labels[uid]): continue
                for path in path_list:
                    path_score = str((float(path[0]) - min_score) / (max_score - min_score))
                    path_prob = path[1]
                    path_explaination = []
                    for tuple in path[2]:
                        for x in tuple:
                            path_explaination.append(str(x))
                    writer.writerow([uid, pid, path_score, path_prob, ' '.join(path_explaination)])
    pred_paths_file.close()

def save_best_pred_paths(folder_path, best_pred_paths):
    print("Normalizing items scores...")
    # Get min and max score to performe normalization between 0 and 1
    score_list = []
    for uid, pid_list in best_pred_paths.items():
        for path in pid_list:
            score_list.append(path[0])
    min_score = min(score_list)
    max_score = max(score_list)

    print("Saving best_pred_paths...")
    with open(folder_path + "/best_pred_paths.csv", 'w+', newline='') as best_pred_paths_file:
        header = ["uid", "rec item", "path_score", "path_prob", "path"]
        writer = csv.writer(best_pred_paths_file)
        writer.writerow(header)
        for uid, recs in best_pred_paths.items():
            for rec in recs:
                path_score = str((rec[0] - min_score) / (max_score - min_score))
                path_prob = rec[1]
                recommended_item_id = rec[2][-1][-1]
                path_explaination = []
                for tuple in rec[2]:
                    for x in tuple:
                        path_explaination.append(str(x))
                writer.writerow([uid, recommended_item_id, path_score, path_prob, ' '.join(path_explaination)])
    best_pred_paths_file.close()

def save_pred_labels(folder_path, pred_labels):
    print("Saving topks...")
    with open(folder_path +  "/uid_topk.csv", 'w+', newline='') as uid_topk:
        header = ["uid", "top10"]
        writer = csv.writer(uid_topk)
        writer.writerow(header)
        for uid, topk in pred_labels.items():
            writer.writerow([uid, ' '.join([str(x) for x in topk[::-1]])])
    uid_topk.close()

def save_pred_explainations(folder_path, pred_paths_top10, pred_labels):
    print("Saving topks' explanations")
    # Save explainations to load the uid-pid selected explaination
    with open(folder_path + "/uid_pid_explanation.csv", 'w+', newline='') as uid_pid_explaination:
          header = ["uid", "pid", "path"]
          writer = csv.writer(uid_pid_explaination)
          writer.writerow(header)
          for uid, paths in pred_paths_top10.items():
              for idx, path in enumerate(paths[::-1]):
                  path_explaination = []
                  for tuple in path:
                      for x in tuple:
                          path_explaination.append(str(x))
                  writer.writerow([uid, pred_labels[uid][idx], ' '.join(path_explaination)])
    uid_pid_explaination.close()

'''
def save_user_interactions(folder_path, user2timestamp):
    print("Saving list of users' interaction timestamps of train_set")
    with open(folder_path + "/user2timestamp.csv", 'w+', newline='') as user2timestamp_file:
          header = ["uid", "timestamps"]
          writer = csv.writer(user2timestamp_file)
          writer.writerow(header)
          for uid, timestamps in user2timestamp.items():
              writer.writerow([uid, ' '.join([str(timestamp) for timestamp in timestamps])])
    user2timestamp_file.close()

def save_interactions_timestamps(folder_path, interaction2timestamp):
    print("Saving uid pid interaction timestamps of train_set")
    with open(folder_path + "/uid_pid_timestamp.csv", 'w+', newline='') as uid_pid_timestamp_file:
        header = ["uid", "pid", "interaction_timestamp"]
        writer = csv.writer(uid_pid_timestamp_file)
        writer.writerow(header)
        for uid, pid_list in interaction2timestamp.items():
            for pid, timestamp in pid_list.items():
                writer.writerow([uid, pid, str(timestamp)])
    uid_pid_timestamp_file.close()
'''


from copy import deepcopy
from datetime import timedelta
from typing import Optional, Callable

from discord import FFmpegPCMAudio
from yt_dlp import YoutubeDL

FFMPEG_YT_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}

# Use factory pattern to embed different types of playable audio as a function
async def generate_youtube_song(yt_id: str, e_seek: Optional[int] = None) -> Callable[[], FFmpegPCMAudio]:
    outer_yt_query = YoutubeDL(
        {'format': 'bestaudio/best', 'quiet': True, 'noplaylist': True}
    ).extract_info(yt_id, download=False)
    if yt_id.startswith("ytsearch:"):
        outer_yt_query = outer_yt_query['entries'][0]
    e_title, e_duration, e_thumbnail = outer_yt_query.get('title'), outer_yt_query.get('duration'), outer_yt_query.get('thumbnail')

    def youtube_song(i_yt_id=yt_id, seek=e_seek, title=e_title, duration=e_duration, thumbnail=e_thumbnail, db_youtube_id=outer_yt_query.get('id')):  # Default params for early binding
        ffmpeg_options = deepcopy(FFMPEG_YT_OPTIONS)
        # Add seeking if requested
        if seek is not None:
            seek_time = timedelta(seconds=seek)
            ffmpeg_options['before_options'] += ''.join([
                ' -ss ',
                f'{seek_time.seconds // 3600}:',
                f'{seek_time.seconds // 60 % 60}:',
                f'{seek_time.seconds % 60}'
            ])

        yt_query = YoutubeDL(
            {'format': 'bestaudio/best', 'quiet': True, 'noplaylist': True}
        ).extract_info(i_yt_id, download=False)
        if i_yt_id.startswith("ytsearch:"):
            yt_query = yt_query['entries'][0]
        audio_format: str = yt_query['format_id']
        audio_url = [
            x for x in yt_query['formats']
            if x['format_id'] == audio_format
        ][0]['url']

        # Make it so this function returns the audio_url instead of the FFmpegPCMAudio to allow for faster seeking
        # Ignore previous comment, use a cache with the url
        return FFmpegPCMAudio(source=audio_url, **ffmpeg_options)
    return youtube_song

async def generate_url_song(url: str) -> Callable[[], FFmpegPCMAudio]:
    e_title = url.split('/')[-1].split('.')[0]

    def url_song(i_url=url, seek=0, title=e_title):
        ffmpeg_options = {}
        if seek is not None:
            seek_time = timedelta(seconds=seek)
            ffmpeg_options['before_options'] = ''.join([
                ' -ss ',
                f'{seek_time.seconds // 3600}:',
                f'{seek_time.seconds // 60 % 60}:',
                f'{seek_time.seconds % 60}'
            ])
        return FFmpegPCMAudio(source=i_url, **ffmpeg_options)
    return url_song


import numpy as np
from numpy.core.fromnumeric import size

'''
4) Crie uma função python que retorna o maior de dois números enviado por parâmetro.
   Ela irá funcionar de maneira regular, ou seja, operando sobre 2 escalares.
   Verifique o funcionamento da função NumPy vectorize, e crie então a função
   que opera sobre vetores.
   Teste sua função com dois arrays numpy de 10 posições sorteadas de números inteiros
   no intervalo [10, 100) (usando funções NumPy).
   Mostre os 3 vetores.
'''

def Maior(a, b):

    if a > b:
        return a
    else:
        return b

Maior_comp = np.vectorize(Maior) # Maior_comp é a função que vai permitir a manipulação dos 2 vetores
vect_a = np.random.randint(10, 100, size = (1,10)) # [low, up) = 100 excluso
print("1º vetor: ", vect_a)
vect_b = np.random.randint(10, 100, size = (1,10))
print("2º vetor: ", vect_b)

vect_res = Maior_comp(vect_a, vect_b)
print("vetor resultado: ", vect_res)
print()


from flask import request, render_template, redirect, url_for

from lib import template_list
from lib.auth import login_required, HR_ROLE, get_logged_user
from lib.core_integration import get_json_from_core
from routes.common.company import edit_company
from routes.hiring_manager.company_form import HMCompanyForm

@login_required(HR_ROLE)
def company_info():
    company_id = get_user_company_id()

    company = get_json_from_core('/api/company/' + company_id)

    form = HMCompanyForm(request.form)

    form.populate_form_from_core(company)

    return render_template(template_list.COMMON_EDIT_COMPANY,
                           form=form,
                           company_id=company_id,
                           form_action='hr_company_info_post')

@login_required(HR_ROLE)
def company_info_post():
    company_id = get_user_company_id()
    form = HMCompanyForm(request.form)

    edited = edit_company(form, company_id)

    if edited:
        return redirect(url_for('hr_company_info'))

    return render_template(template_list.COMMON_EDIT_COMPANY,
                           form=form,
                           company_id=company_id,
                           form_action='hr_company_info_post')

def get_user_company_id():
    user = get_logged_user()
    return user['company_id']


from IO_assign.IOHelper import countPorts, multilineComment
from IO_assign.PadClass import DigitalPad
from IO_assign.IOPad import IOPad, IOPadInst, IOPadSide
from IO_assign.IOGlobal import IOGlobal

class PadDef(IOPadInst):
    def __init__(self):
        IOPadInst.__init__(self)

class PadListDef(IOPadSide):
    def __init__(self,side):
        IOPadSide.__init__(self, side)
        self.row_max = 0

    @property
    def side(self):
        return self.root

    def addPad(self, pad):
        self.leaf_list.append(pad)
        return self

    def insertPad(self, pad, index):
        self.leaf_list.insert(index, pad)
        return self

    def setRowMax(self, ub):
        self.row_max = ub
        return self

    def isempty(self):
        return len(self.leaf_list) == 0

    def isfull(self):
        return len(self.leaf_list) == self.row_max

class PadRingDef(IOPad):
    def __init__(self):
        IOPad.__init__(self)
        self.setLeafList(
            [
                PadListDef("top"),
                PadListDef("left"),
                PadListDef("right"),
                PadListDef("bottom"),
                PadListDef("topleft"),
                PadListDef("topright"),
                PadListDef("bottomleft"),
                PadListDef("bottomright")
            ]
        )
        self.row_max = 0

    @property
    def top(self):
        return self.leaf_list[0]

    @property
    def left(self):
        return self.leaf_list[1]

    @property
    def right(self):
        return self.leaf_list[2]

    @property
    def bottom(self):
        return self.leaf_list[3]

    @property
    def topleft(self):
        return self.leaf_list[4]

    @property
    def topright(self):
        return self.leaf_list[5]

    @property
    def bottomleft(self):
        return self.leaf_list[6]

    @property
    def bottomright(self):
        return self.leaf_list[7]

    def setRowMax(self, ub):
        self.top.setRowMax(ub)
        self.left.setRowMax(ub)
        self.right.setRowMax(ub)
        self.bottom.setRowMax(ub)
        self.row_max = ub
        return self

    def checkStatus(self):
        if not self.left.isfull():
            return 1
        elif not self.top.isfull():
            return 2
        elif not self.right.isfull():
            return 3
        elif not self.bottom.isfull():
            return 4
        else:
            return 0

    def addPad(self, pad):
        ring_status = self.checkStatus()
        if not ring_status:
            print("Ring Full!")
        elif ring_status == 1:
            self.left.addPad(pad)
        elif ring_status == 2:
            self.top.addPad(pad)
        elif ring_status == 3:
            self.right.addPad(pad)
        elif ring_status == 4:
            self.bottom.addPad(pad)
        else :
            print("Error")
        return self

class IOAssignDef(object):

    def __init__(self):
        self.pad_ring = PadRingDef()
        self.digital_pad = DigitalPad()
        self.ports = None
        self.driving_strength = "000"
        self.smt_port_list = []

    def inputPorts(self, ports):
        import math
        port_count = countPorts(ports)
        total_num = port_count["total"]
        self.pad_ring.setRowMax(math.ceil(total_num/4))
        for ii in range(0, len(port_count["ports"])):
            pad_dims = port_count["ports"][ii]["dims"]
            pad_width = port_count["ports"][ii]["width"]
            for jj in range(0, pad_dims):
                posfix_jj = "" if pad_dims==1 else "_"+str(jj)
                for kk in range(0, pad_width):
                    posfix_kk = "" if pad_width==1 else "_"+str(kk)
                    posfix = posfix_jj + posfix_kk
                    # pad_inst_name = port_count["ports"][ii]["name"] + "_PORT" + posfix
                    # pad_cell = self.digital_pad.io.BDIO if ports[ii]["direction"] == "inout" else self.digital_pad.io.DIO
                    pad_cell = ""
                    if ports[ii]["direction"] == "input":
                        pad_cell = self.digital_pad.io.DIO_I
                    elif ports[ii]["direction"] == "output":
                        pad_cell = self.digital_pad.io.DIO_O
                    elif ports[ii]["direction"] == "inout":
                        pad_cell = self.digital_pad.io.BDIO
                    else:
                        print("WARNING, unknown direction detected.")
                        pad_cell = self.digital_pad.io.DIO
                    pad_inst_name = pad_cell + "_" + ports[ii]["name"] + posfix + "_inst"
                    pad_def = PadDef()
                    pad_def.setName(pad_inst_name).setCell(pad_cell)
                    self.pad_ring.addPad(pad_def)
        self.pad_ring.right.leaf_list.reverse()
        self.pad_ring.bottom.leaf_list.reverse()

    def setCorner(self):
        self.pad_ring.topleft.setRowMax(1).addPad(
            PadDef().setName("TL_CORNER").setCell(self.digital_pad.supply.corner).setOrientation("R270")
        )
        self.pad_ring.topright.setRowMax(1).addPad(
            PadDef().setName("TR_CORNER").setCell(self.digital_pad.supply.corner).setOrientation("R180")
        )
        self.pad_ring.bottomleft.setRowMax(1).addPad(
            PadDef().setName("BL_CORNER").setCell(self.digital_pad.supply.corner).setOrientation("R0")
        )
        self.pad_ring.bottomright.setRowMax(1).addPad(
            PadDef().setName("BR_CORNER").setCell(self.digital_pad.supply.corner).setOrientation("R90")
        )

    def setPGPad(self, io_sup_num, core_sup_num, core_p, core_g, io_p, io_g):
        import math
        #core_sup_num_per_side = math.ceil(core_sup_num/4) * 2
        core_sup_num_per_side = math.ceil(core_sup_num/4)
        #io_sup_num_per_side = math.ceil(io_sup_num/4) * 2
        io_sup_num_per_side = math.ceil(io_sup_num/4)
        row_max_num_without_pg = self.pad_ring.row_max
        row_max_num = row_max_num_without_pg + core_sup_num_per_side + io_sup_num_per_side
        self.pad_ring.setRowMax(row_max_num)
        # pg_pad_skip = row_max_num // (core_sup_num_per_side + io_sup_num_per_side) + 1
        pg_pad_skip = math.ceil(row_max_num/(core_sup_num_per_side + io_sup_num_per_side))
        insert_position = [x for x in range(pg_pad_skip-1, row_max_num, pg_pad_skip)]
        count = 0
        for idx in insert_position:
            import copy
            if count % 2 == 0:
                # self.pad_ring.top.insertPad(vdd_pad_io_supply.deepCopy(), idx)
                print("now insert io supply")
                self.pad_ring.top.insertPad(
                    PadDef().setName(io_p).setCell(self.digital_pad.supply.io_supply.VDD),
                    idx
                )
                self.pad_ring.top.insertPad(
                    PadDef().setName(io_g).setCell(self.digital_pad.supply.io_supply.VSS),
                    idx + 1
                )
                self.pad_ring.left.insertPad(
                    PadDef().setName(io_p).setCell(self.digital_pad.supply.io_supply.VDD),
                    idx
                )
                self.pad_ring.left.insertPad(
                    PadDef().setName(io_g).setCell(self.digital_pad.supply.io_supply.VSS),
                    idx + 1
                )
                self.pad_ring.right.insertPad(
                    PadDef().setName(io_p).setCell(self.digital_pad.supply.io_supply.VDD),
                    idx
                )
                self.pad_ring.right.insertPad(
                    PadDef().setName(io_g).setCell(self.digital_pad.supply.io_supply.VSS),
                    idx + 1
                )
                self.pad_ring.bottom.insertPad(
                    PadDef().setName(io_p).setCell(self.digital_pad.supply.io_supply.VDD),
                    idx
                )
                self.pad_ring.bottom.insertPad(
                    PadDef().setName(io_g).setCell(self.digital_pad.supply.io_supply.VSS),
                    idx+1
                )
            else:
                print("now insert core supply")
                self.pad_ring.top.insertPad(
                    PadDef().setName(core_p).setCell(self.digital_pad.supply.core_supply.VDD),
                    idx
                )
                self.pad_ring.top.insertPad(
                    PadDef().setName(core_g).setCell(self.digital_pad.supply.core_supply.VSS),
                    idx + 1
                )
                self.pad_ring.left.insertPad(
                    PadDef().setName(core_p).setCell(self.digital_pad.supply.core_supply.VDD),
                    idx
                )
                self.pad_ring.left.insertPad(
                    PadDef().setName(core_g).setCell(self.digital_pad.supply.core_supply.VSS),
                    idx + 1
                )
                self.pad_ring.right.insertPad(
                    PadDef().setName(core_p).setCell(self.digital_pad.supply.core_supply.VDD),
                    idx
                )
                self.pad_ring.right.insertPad(
                    PadDef().setName(core_g).setCell(self.digital_pad.supply.core_supply.VSS),
                    idx + 1
                )
                self.pad_ring.bottom.insertPad(
                    PadDef().setName(core_p).setCell(self.digital_pad.supply.core_supply.VDD),
                    idx
                )
                self.pad_ring.bottom.insertPad(
                    PadDef().setName(core_g).setCell(self.digital_pad.supply.core_supply.VSS),
                    idx+1
                )
            count += 1
        # uniquify all the pg pad
        idx = 0
        pg_cell_list = [
            self.digital_pad.supply.core_supply.VDD,
            self.digital_pad.supply.core_supply.VSS,
            self.digital_pad.supply.io_supply.VDD,
            self.digital_pad.supply.io_supply.VSS
        ]
        for side in self.pad_ring.leaf_list:
            for pad in side.leaf_list:
                pad_cell = pad.cell[1:-1]
                pad_name = pad.name[1:-1]
                if pad_cell in pg_cell_list:
                    pad.setName(pad_name + "_" + str(idx))
                    idx += 1

    # ???
    def setOrientation(self):
        pass

    def writeIOFile(self, io_file):
        io_global = IOGlobal().setVersion(3).setIOOrder("clockwise").setTotalEdge(4)
        self.setCorner()
        io_pad = str(self.pad_ring)
        io_content = str(io_global) + '\n' + io_pad
        with open(io_file, "w") as f:
            f.write(io_content)

    def __str__(self):
        # io_global = IOGlobal().setVersion(3).setIOOrder("clockwise").setTotalEdge(4)
        return str(self.pad_ring)


from subprocess import Popen, PIPE

class SimpleCMDWrapper(object):

    _command = None
    _options = None
    _process = None

    def __init__(self, command, options=None, **kwargs):
        """
        Initialization.

        @param command: Command name.
        @type command: str
        @param options: List of options/parameters.
        @type options: list

        @keyword stdin: Standard input.
        @keyword stdout: Standard output.
        @keyword stderr: Standard error.
        """
        self._command = command
        self._options = []
        if options and isinstance(options, (list, tuple)):
            self._options = list(options)

        self.stdin = kwargs.get('stdin')
        self.stdout = kwargs.get('stdout', PIPE)
        self.stderr = kwargs.get('stderr', PIPE)

    def __enter__(self):
        return self

    def __exit__(self, exc_type=None, exc_value=None, traceback=None):
        if self._process is not None:
            self._process.terminate()
        self.exc_type = exc_type
        self.exc_value = exc_value
        self.traceback = traceback

    def __call__(self, stdin=None):
        """
        Call class object.

        @param stdin: Standard input.
        @return: Result from self.execute()
        """
        self.stdin = stdin
        return self.execute()

    @property
    def command(self):
        """
        Get command with options.

        @return: List of command with options.
        @rtype: list
        """
        return [self._command] + self._options

    def reset_options(self):
        """
        Remove defined options.
        """
        del self._options[:]

    def set_options(self, *args, **kwargs):
        """
        Set new options.

        @param args: List of keys.
        @type args: list
        @param kwargs: Dict of options.
        @type kwargs: dict
        """
        self.reset_options()
        self.add_options(*args, **kwargs)

    def add_option(self, key, value=None):
        """
        Add command option (e.g., key/value pair).

        @param key: Key name.
        @type key: str
        @param value: Key value.
        @type value: str
        """
        self._options.append(key)
        if value:
            self._options.append(value)

    def add_options(self, *args, **kwargs):
        """
        Add command options.

        @param args: List of keys.
        @type args: list
        @param kwargs: Dict of options.
        @type kwargs: dict
        """
        for option in args:
            if isinstance(option, (list, tuple)) and len(option) > 1:
                self.add_option(key=option[0], value=option[1])
            else:
                self.add_option(key=option)
        for (key, value) in kwargs.iteritems():
            self.add_option(key=key, value=value)

    def execute(self):
        """
        Execute CLI command.
        @return: Return code, output data, error message.
        @rtype: tuple
        """
        self._process = Popen([self._command] + self._options,
                              shell=False,
                              stdin=self.stdin,
                              stdout=self.stdout,
                              stderr=self.stderr)
        (stdoutdata, stderrdata) = self._process.communicate(self.stdin)
        returncode = self._process.returncode
        return returncode, stdoutdata, stderrdata


import graphene

def get_node(info, id, only_type=None):
    """Return node or throw an error if the node does not exist."""
    node = graphene.Node.get_node_from_global_id(info, id, only_type=only_type)
    if not node:
        raise Exception(
            "Could not resolve to a node with the global id of '%s'." % id)
    return node


class Solution(object):
    def combinationSum2(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """

s = Solution()
can = [10,1,2,7,6,1,5]
target = 8
s.combinatiionSum2(can, target)


import sys
import subprocess

from . import ShellInterface

class PowerShell(ShellInterface):
    """Microsoft Powershell interface."""
    def __init__(self, cmd:str):
        self.process = subprocess.Popen(["powershell", "-Command", cmd], stdout=sys.stdout)
        super().__init__()

    def run(self) -> subprocess.Popen:
        self.process.communicate()
        return self.process


from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from . import details , price , forms

# Create your views here.
def home(request):
    return render(request,'home.html')

@login_required
def balance(request):
    form2 = forms.Balance
    balance = 0
    context = {
        'form2':form2,
    }
    if request.method == 'POST':
        form2 = form2(request.POST)
        if form2.is_valid():
            Address = form2.cleaned_data['Address']
            Coin = form2.cleaned_data['Coin']
        if details.checkaddress(Address) == True:
            if Coin == 'ETH':
                balance = details.getbalanceeth(Address)
                balanceedit = str(balance) + ' ' + Coin
                context_edit = {
                    'balance': balanceedit,
                    'Address': Address,
                }
            else:
                print('1',Address,Coin)
                balance = details.getbalance(Address,Coin)
                balanceedit = str(balance) + ' ' + Coin
                print(balance,balanceedit)
                context_edit = {
                    'balance': balanceedit,
                    'Address': Address,
                }
        else:
            context_edit = {
                'balance': 'Invalid Address',
                'Address': Address,
            }
        context.update(context_edit)

    return render(request,'balance.html',context)

#price = price.getPrice('BTC','INR')

currency = [
    'USD',
    'AUB',
    'CAD',
    'CNY',
    'EUR',
    'INR',
    'JPY',
    'SGD'
]

@login_required
def converter(request):
    price1 = 0
    price2 = 0
    form = forms.Converter
    context = {
    'form': form,
    }
    if request.method == 'POST':
        form = form(request.POST)
        if form.is_valid():
            ConvertFrom = form.cleaned_data['ConvertFrom']
            ConvertTo = form.cleaned_data['ConvertTo']
            Quantity = form.cleaned_data['Quantity']
            if ConvertTo in currency:
                convert = ConvertTo
                symbol = ConvertFrom
                price1 = price.getPrice(symbol,convert)
                convertedamount = Quantity*price1
            else:
                convert = 'USD'
                symbol = ConvertFrom
                price1 = price.getPrice(symbol,convert)
                symbol = ConvertTo
                price2 = price.getPrice(symbol,convert)
                convertedamount = Quantity*(price1/price2)
            print('convertedamount-',convertedamount)

            print('convert from',ConvertFrom,'convert to',ConvertTo,'quantity',Quantity)
            context_edit = {
                    'convert': convert,
                    'symbol': symbol,
                    'convertedamount' : convertedamount,
                    'convertFrom': ConvertFrom,
                    'convertTo': ConvertTo,
                    'Quantity': Quantity,
                    'price1': price1,
                    'price2':price2,
                            }
            context.update(context_edit)

    return render(request,'converter.html',context)

@login_required
def dashboard(request):
    return render(request,'dashboard.html')


from tiles import *
from character import *
from places import *

from battle import *

clock = pygame.time.Clock()  # setting fps (clock pygame)
items = pygame.sprite.Group()  # pygame sprite's group for maps

def window_setter(layer_wid, layer_len, type_of_map):
    if type_of_map == "MINI":
        x = (settings.WIDTH - layer_wid) / 2
        y = (settings.HEIGHT - layer_len) / 2
        return x, y
    else:
        x = (settings.WIDTH - 39 * settings.block_size) / 2
        y = (settings.HEIGHT - 23 * settings.block_size) / 2
        return x, y

def place_loading_from_file(code):
    if code == "TestHouse":
        return TileMap('resources/map/testhouse.json')
    elif code == "TestMap":
        return TileMap('resources/map/test_map.json')
    elif code == "TestHouse2":
        return TileMap('resources/map/testhouse2.json')

class CurrentGame:
    def __init__(self, place_for_map, player_x_pos=None, player_y_pos=None):
        self.current_place = CurrentMap(place_for_map, player_x_pos, player_y_pos)
        place_loading(items, settings.current_location)

    @staticmethod
    def teleport_setter(place):  # teleporting player function
        if place == "from_TestHouse_to_TestMap":
            settings.current_location = "TestMap"
        elif place == "from_TestMap_to_TestHouse":
            settings.current_location = "TestHouse"
        elif place == "from_TestHouse_to_TestHouse2":
            settings.current_location = "TestHouse2"
        elif place == "from_TestHouse2_to_TestHouse":
            settings.current_location = "TestHouse"

    def map_changer(self, place_to_move, player_standing_animation, player_x_pos=None, player_y_pos=None):
        # noinspection PyGlobalUndefined
        global player, right, left, down, up, f_button, land_poke
        del self.current_place, land_poke
        self.teleport_setter(place_to_move)  # setting new class (location)

        # setting player position
        player.rect.x = player_x_pos
        player.rect.y = player_y_pos - 16

        # updating screen
        loading_video.preview()  # start loading video
        screen.fill(settings.BLACK)  # clearing screen
        right = left = down = up = False  # stop movement player in transporting
        f_button = False
        player.standing_animation(player_standing_animation)  # staying animation
        land_poke = LandPoke(settings.player_pokes.poke_1.id_pokedex,
                             settings.player_pokes.poke_1.type_poke, player)  # creating poke (land)
        land_poke.standing_animation(player_standing_animation)  # start position of poke

        # setting current place (map)
        self.current_place = CurrentMap(place_loading_from_file(settings.current_location),
                                        player_x_pos, player_y_pos)
        place_loading(items, settings.current_location)  # loading items (additionally items)

        self.current_place.blit_background_to_layer()  # bliting layers

class CurrentMap:

    def __init__(self, place, player_x_pos=None, player_y_pos=None):
        self.type_of_map = None
        self.current_map = place  # loading current map
        self.layer_internal = Surface((place.width * settings.block_size, place.height * settings.block_size))
        self.layer_external = Surface((place.width * settings.block_size, place.height * settings.block_size),
                                      pygame.SRCALPHA)  # create external surface

        if place.width * settings.block_size > 1248 or place.height * settings.block_size > 736:
            # field for moving
            self.field = Surface((39 * settings.block_size, 23 * settings.block_size), pygame.SRCALPHA)
            self.field = Surface((39 * settings.block_size, 23 * settings.block_size), pygame.SRCALPHA)
            self.field_rect = self.field.get_rect()
            self.layer_internal.blit(self.field, (0, 0))
            self.type_of_map = "MAX"
        else:
            self.type_of_map = "MINI"

        self.coordinate = window_setter(place.width * settings.block_size, place.height * settings.block_size,
                                        self.type_of_map)
        self.field_x = None  # if max map, use this method
        self.field_y = None  # if max map, use this method
        self.player_x_pos = player_x_pos  # if max map, use this method
        self.player_y_pos = player_y_pos  # if max map, use this method
        self.field_setter()  # setting field configuration

        self.top_cord = self.current_map.top_cord
        self.bottom_cord = self.current_map.bottom_cord
        self.left_cord = self.current_map.left_cord
        self.right_cord = self.current_map.right_cord

    def field_setter(self):
        self.field_x = self.player_x_pos - (19 * settings.block_size)
        self.field_y = self.player_y_pos - (11 * settings.block_size)

        if self.field_x < 0:
            self.field_x = 0
        elif self.field_x + (39 * 32) >= self.current_map.width * 32:
            self.field_x = self.current_map.width * 32 - (39 * 32)
        if self.field_y < 0:
            self.field_y = 0
        elif self.field_y + (23 * 32) >= self.current_map.height * 32:
            self.field_y = self.current_map.height * 32 - (23 * 32)

    def blit_background_to_layer(self):
        self.layer_internal.blit(self.current_map.background_internal, (0, 0))
        self.layer_external.blit(self.current_map.background_external, (0, 0))

    def map_draw(self, window):  # draw function for mini map
        window.blit(self.layer_internal, self.coordinate)
        window.blit(self.layer_external, self.coordinate)

    def field_draw(self, window):  # draw function for max map
        self.field.blit(self.layer_internal, (0, 0), (self.field_x, self.field_y,
                                                      39 * settings.block_size, 23 * settings.block_size))
        self.field.blit(self.layer_external, (0, 0), (self.field_x, self.field_y,
                                                      39 * settings.block_size, 23 * settings.block_size))
        window.blit(self.field, self.coordinate)

    def draw_setter(self, window):  # function for choosing draw method (result depends on the map)
        if self.type_of_map == "MAX":
            return self.field_draw(window)
        else:
            return self.map_draw(window)

pygame.init()  # initialize pygame module

try:  # here we try loading save file
    with open("savepoint.pkl", "rb") as fp:  # open saved file
        current_location, player_x, player_y, last_move_p = pickle.load(
            fp)  # loading current_place where we stayed last time
        settings = Setting(player_x, player_y, current_location)
        # world creation in that place
        settings.last_move_setter(last_move_p)
except FileNotFoundError:  # if we don't save world before (or just create new world), creating new world
    settings = Setting()

screen = pygame.display.set_mode((settings.WIDTH, settings.HEIGHT), DOUBLEBUF)  # create main window
pygame.display.set_caption("Pokemon Red")  # name of game
font_standart = pygame.font.SysFont('Times New Roman', 30)  # setting font
font = pygame.font.Font(resource_path("resources/font/Pixel_Times.ttf"), 30)  # setting font

world1 = CurrentGame(place_loading_from_file(settings.current_location),
                     player_x_pos=settings.player_x, player_y_pos=settings.player_y)  # world creation

world1.current_place.blit_background_to_layer()  # bliting items and background from layers to our world-class

player = CharacterMain(settings.player_x, settings.player_y, settings.last_move)  # creating player
player.standing_animation(settings.last_move)  # start position of player
# creating poke (land)
land_poke = LandPoke(settings.player_pokes.poke_1.id_pokedex, settings.player_pokes.poke_1.type_poke, player)
land_poke.standing_animation(settings.last_move)  # start position of poke
left = right = up = down = False  # player is staying when start game
f_button = False  # action button

mouse_cursor = None  # value for setting sprite, which will be clicked by mouse
mouse_sprite_group = pygame.sprite.Group()
x_diff = 0  # difference between clicked pos and sprite (std-0)
y_diff = 0  # difference between clicked pos and sprite (std-0)

while True:
    world1.current_place.draw_setter(screen)
    world1.current_place.layer_internal.blit(world1.current_place.current_map.background_internal,
                                             (0, 0))  # clearing image after animations

    # if the event is quit means we clicked on the close window button
    is_settled = False  # mouse set action (std-False)
    collided_item = None  # collided item ( its mean when we collide 2 system sprite )

    pos = pygame.mouse.get_pos()
    for e in pygame.event.get():
        # check for closing window
        if e.type == pygame.QUIT:
            with open("savepoint.pkl", "wb") as fp:  # saving our world
                player_x = player.cord_of_player[0]
                player_y = player.cord_of_player[1]
                last_move_p = player.last_move
                pickle.dump([settings.current_location, player_x, player_y, last_move_p], fp)
            pygame.quit()
            sys.exit()

        if e.type == KEYDOWN and e.key == K_LEFT:
            left = True
        if e.type == KEYDOWN and e.key == K_RIGHT:
            right = True
        if e.type == KEYDOWN and e.key == K_UP:
            up = True
        if e.type == KEYDOWN and e.key == K_DOWN:
            down = True
        if e.type == KEYDOWN and e.key == K_f:
            f_button = True

        if e.type == KEYUP and e.key == K_RIGHT:
            right = False
            if settings.world_status == "MAIN":
                player.standing_animation("right")
        if e.type == KEYUP and e.key == K_LEFT:
            left = False
            if settings.world_status == "MAIN":
                player.standing_animation("left")
        if e.type == KEYUP and e.key == K_UP:
            up = False
            if settings.world_status == "MAIN":
                player.standing_animation("up")
        if e.type == KEYUP and e.key == K_DOWN:
            down = False
            if settings.world_status == "MAIN":
                player.standing_animation("down")
        if e.type == KEYUP and e.key == K_f:
            f_button = False

        if e.type == pygame.MOUSEBUTTONDOWN:
            # Из всех имеющих спрайтов в system_mech определяется, нажата ли мышка на какой-либо спрайт.
            # если да, тов курсор записывается данный спрайт, а затем выполняется дальнейшее указания.
            for sprite in system_mech:  # getting all sprites from system_mech
                # getting sprites type
                if sprite.type_system == "icon_poke" or sprite.type_system == "poke_info" \
                        or sprite.type_system == "battle_system":
                    if sprite.rect.collidepoint(pos):  # getting clicked sprite
                        mouse_cursor = sprite  # getting mouse_cursor
                        x_diff = e.pos[0] - mouse_cursor.rect.x
                        y_diff = e.pos[1] - mouse_cursor.rect.y
            if mouse_cursor:
                # fg sprite
                system_mech.remove(mouse_cursor)
                system_mech.add(mouse_cursor)

        if pygame.mouse.get_pressed()[0] and mouse_cursor:
            if mouse_cursor.type_system == "icon_poke" or "poke_info" or "battle_system":
                try:
                    mouse_cursor.rect.x = e.pos[0] - x_diff
                    mouse_cursor.rect.y = e.pos[1] - y_diff
                except AttributeError:
                    pass

        if e.type == pygame.MOUSEBUTTONUP:
            if mouse_cursor:
                if mouse_cursor.type_system == "icon_poke":
                    # if we just clicked on "icon_poke"
                    if mouse_cursor.rect.x == mouse_cursor.x_standart and mouse_cursor.rect.y == mouse_cursor.y_standart:
                        # if poke_info is not exist (sprite) => create
                        if not settings.poke_info:
                            if mouse_cursor.poke_exist:
                                poke_info = Poke_info(125, 50, mouse_cursor.id_db_poke, mouse_cursor.db)
                                system_mech.poke_info_sprite = poke_info
                                system_mech.add(poke_info)
                                settings.poke_info = True
                        # if poke_info is exist (sprite) => update
                        else:
                            if mouse_cursor.poke_exist:
                                system_mech.poke_info_sprite_x = system_mech.poke_info_sprite.rect.x  # copying last x
                                system_mech.poke_info_sprite_y = system_mech.poke_info_sprite.rect.y  # copying last y
                                system_mech.remove(system_mech.poke_info_sprite)  # deleting poke_info
                                system_mech.poke_info_sprite = None  # clearing poke_info

                                # updating current poke_info (sprite)
                                poke_info = Poke_info(system_mech.poke_info_sprite_x, system_mech.poke_info_sprite_y,
                                                      mouse_cursor.id_db_poke, mouse_cursor.db)
                                system_mech.add(poke_info)
                                system_mech.poke_info_sprite = poke_info
                                settings.poke_info = True
                    # if we collide it with other sprites
                    else:
                        for sprite in system_mech:
                            if sprite.type_system == "icon_poke":
                                if sprite != mouse_cursor:  # except itself
                                    if sprite.poke_exist:  # if there is poke in slot
                                        if mouse_cursor.poke_exist:
                                            if sprite.rect.collidepoint(pos):
                                                is_settled = True
                                                collided_item = sprite

                        if is_settled and settings.world_status == "MAIN":
                            settings.player_pokes.changer_poke_icon(collided_item, mouse_cursor, system_mech)
                            del land_poke  # delete current land poke
                            # And create a new land poke
                            land_poke = LandPoke(settings.player_pokes.poke_1.id_pokedex,
                                                 settings.player_pokes.poke_1.type_poke, player)
                            land_poke.standing_animation(player.last_move)  # start position of poke
                        else:
                            mouse_cursor.rect.x = mouse_cursor.x_standart
                            mouse_cursor.rect.y = mouse_cursor.y_standart
                elif mouse_cursor.type_system == "poke_info":
                    # checking, which button we pressed

                    # if we're closing sprite (close it)
                    if mouse_cursor.press_checker(e.pos[0], e.pos[1]) == "close_sprite":
                        system_mech.remove(mouse_cursor)
                        settings.poke_info = False
                    # if we're updating sprite (change its moves)
                    elif mouse_cursor.press_checker(e.pos[0], e.pos[1]) == "update_sprite":
                        system_mech.poke_info_sprite_x = system_mech.poke_info_sprite.rect.x  # copying last x
                        system_mech.poke_info_sprite_y = system_mech.poke_info_sprite.rect.y  # copying last y
                        system_mech.remove(system_mech.poke_info_sprite)  # deleting poke_info
                        system_mech.poke_info_sprite = None  # clearing poke_info

                        # updating current poke_info (sprite)
                        poke_info = Poke_info(system_mech.poke_info_sprite_x, system_mech.poke_info_sprite_y,
                                              mouse_cursor.id_db_poke, mouse_cursor.db)
                        system_mech.add(poke_info)
                        system_mech.poke_info_sprite = poke_info
                        settings.poke_info = True
                elif mouse_cursor.type_system == "battle_system":
                    # checking, which button we pressed
                    mouse_cursor.press_checker(e.pos[0], e.pos[1])

            mouse_cursor = None
            x_diff = 0
            y_diff = 0

    player.update(world1.current_place,
                  left, right, up, down, f_button, world1.current_place.top_cord,
                  world1.current_place.left_cord, world1.current_place.right_cord, world1.current_place.bottom_cord,
                  world1.current_place.current_map.background_internal_items_with_rect, items, world1, settings)
    land_poke.update(left, right, up, down, player.poke_move, player.poke_last_move, player.speed, player.last_move)
    land_poke.draw(world1.current_place.layer_internal)
    player.draw(world1.current_place.layer_internal)

    items.update(player, world1.current_place.layer_internal, font, system_mech, settings)
    system_mech.update(screen, pos, settings, world1)

    clock.tick(settings.FPS)
    pygame.display.update()


import pygame
import sys
import time
import random
from pygame.locals import *

redColour = pygame.Color(255, 0, 0)
blackColour = pygame.Color(0, 0, 0)
whiteColour = pygame.Color(255, 255, 255)
greyColour = pygame.Color(150, 150, 150)

def gameOver(playSurface, score):
    gameOverFont = pygame.font.SysFont("arial.ttf", 54)
    gameOverSurf = gameOverFont.render("Game Over!", True, greyColour)
    gameOverRect = gameOverSurf.get_rect()
    gameOverRect.midtop = (300, 10)
    playSurface.blit(gameOverSurf, gameOverRect)
    scoreFont = pygame.font.SysFont("arial.ttf", 54)
    scoreSurf = scoreFont.render("Score:" + str(score), True, greyColour)
    scoreRect = scoreSurf.get_rect()
    scoreRect.midtop = (300, 50)
    playSurface.blit(scoreSurf, scoreRect)
    pygame.display.flip()
    time.sleep(5)
    pygame.quit()
    sys.exit()

def main():
    pygame.init()
    fpsClock = pygame.time.Clock()
    playSurface = pygame.display.set_mode((600, 460))
    pygame.display.set_caption("Snake Game")
    snakePosition = [100, 100]
    snakeSegments = [[100, 100]]
    raspberryPosition = [300, 300]
    raspberrySpawned = 1
    direction = "right"
    changeDirection = direction
    score = 0
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN:
                if event.key == K_RIGHT or event.key == ord("d"):
                    changeDirection = "right"
                if event.key == K_LEFT or event.key == ord("a"):
                    changeDirection = "left"
                if event.key == K_UP or event.key == ord("w"):
                    changeDirection = "up"
                if event.key == K_DOWN or event.key == ord("s"):
                    changeDirection = "down"
                if event.key == K_ESCAPE:
                    pygame.event.post(pygame.event.Event(QUIT))

        if changeDirection == "right" and not direction == "left":
            direction = changeDirection
        if changeDirection == "left" and not direction == "right":
            direction = changeDirection
        if changeDirection == "up" and not direction == "down":
            direction = changeDirection
        if changeDirection == "down" and not direction == "up":
            direction = changeDirection

        if direction == "right":
            snakePosition[0] += 20
        if direction == "left":
            snakePosition[0] -= 20
        if direction == "up":
            snakePosition[1] -= 20
        if direction == "down":
            snakePosition[1] += 20

        snakeSegments.insert(0, list(snakePosition))

        if (
            snakePosition[0] == raspberryPosition[0]
            and snakePosition[1] == raspberryPosition[1]
        ):
            raspberrySpawned = 0
        else:
            snakeSegments.pop()

        if raspberrySpawned == 0:
            x = random.randrange(1, 30)
            y = random.randrange(1, 23)
            raspberryPosition = [int(x * 20), int(y * 20)]
            raspberrySpawned = 1
            score += 1

        playSurface.fill(blackColour)
        for position in snakeSegments:
            pygame.draw.rect(
                playSurface, whiteColour, Rect(position[0], position[1], 20, 20)
            )
            pygame.draw.rect(
                playSurface,
                redColour,
                Rect(raspberryPosition[0], raspberryPosition[1], 20, 20),
            )

        pygame.display.flip()

        if snakePosition[0] > 600 or snakePosition[0] < 0:
            gameOver(playSurface, score)
            if snakePosition[1] > 460 or snakePosition[1] < 0:
                gameOver(playSurface, score)
        for snakeBody in snakeSegments[1:]:
            if snakePosition[0] == snakeBody[0] and snakePosition[1] == snakeBody[1]:
                gameOver(playSurface, score)

        fpsClock.tick(5)

if __name__ == "__main__":
    main()


# Exercício 7
# Sua trajetória no curso foi um sucesso e agora você está trabalhando para a
# Trybe! Em um determinado módulo, os estudantes precisam entregar dois
# trabalhos para seguir adiante. Cada vez que um dos trabalhos é entregue, o
# nome da pessoa fica registrado. Precisamos saber como está o andamento da
# entrega das listas. Para isso, você tem acesso aos nomes das pessoas da
# turma, bem como ao log de quem já entregou qual lista. A partir das listas
# abaixo, crie quatro funções que respondem às perguntas a seguir.

estudantes = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
lista1_entregues = ['a', 'd', 'g', 'c']
lista2_entregues = ['c', 'a', 'f']

conjunto_estudantes = set(estudantes)
# Quem ainda não entregou a lista1?
print(conjunto_estudantes.difference(lista1_entregues))

# Quem já entregou as duas listas?
conjunto_lista1 = set(lista1_entregues)
print(conjunto_lista1.intersection(lista2_entregues))

# Quem já entregou qualquer uma das duas listas?
qualquer_lista_entregue = conjunto_lista1.union(lista2_entregues)
print(qualquer_lista_entregue)

# Quem ainda não entregou nenhuma das listas?
print(conjunto_estudantes.difference(qualquer_lista_entregue))

4 - Ciência da Computação/Bloco_36 (Estrutura de Dados I - Arrays, Hashmaps e Sets)/dia_4 (Set)/fixacao3.py


# Determine if an array can be divided into pairs such that the sum of elements
# in each pair is divisible by the given integer `k`
def findPairs(arr, k):

    # base case: input contains an odd number of elements
    # (an odd number of elements cannot be paired)
    if len(arr) & 1:
        return 0

    # create a boolean array to mark elements that formed a pair
    visited = [0] * len(arr)

    # consider each element as the first element of a pair
    for i in range(len(arr) - 1):

        # ignore the current element if it is already part of another pair
        if visited[i]:
            continue

        # find the first non-visited element `arr[j]` that forms a pair with `arr[i]`
        j = i + 1
        while j < len(arr):
            if not visited[j] and (arr[j] + arr[i]) % k == 0:
                # pair found `(arr[i], arr[j])`
                visited[j] = 1
                break
            j += 1

        # return 0 if pair not found for the current element
        if j == len(arr):
            return 0

    # we reach here only when each element forms a pair
    return 1

if __name__ == '__main__':

    arr = [2, 9, 4, 1, 3, 5]
    k = 6

    if findPairs(arr, k):
        print("Pairs can be formed")
    else:
        print("Pairs cannot be formed")

Determine whether an array can be divided into pairs with a sum divisible by `k`/Python.py