# Released under the MIT License. See LICENSE for details.
#
"""Defines ScoreBoard Actor and related functionality."""

from __future__ import annotations

import weakref
from typing import TYPE_CHECKING

import bascenev1 as bs

if TYPE_CHECKING:
    from typing import Any, Sequence

class _Entry:
    def __init__(
        self,
        scoreboard: Scoreboard,
        team: bs.Team,
        do_cover: bool,
        scale: float,
        label: bs.Lstr | None,
        flash_length: float,
    ):
        # pylint: disable=too-many-statements
        self._scoreboard = weakref.ref(scoreboard)
        self._do_cover = do_cover
        self._scale = scale
        self._flash_length = flash_length
        self._width = 140.0 * self._scale
        self._height = 32.0 * self._scale
        self._bar_width = 2.0 * self._scale
        self._bar_height = 32.0 * self._scale
        self._bar_tex = self._backing_tex = bs.gettexture('bar')
        self._cover_tex = bs.gettexture('uiAtlas')
        self._mesh = bs.getmesh('meterTransparent')
        self._pos: Sequence[float] | None = None
        self._flash_timer: bs.Timer | None = None
        self._flash_counter: int | None = None
        self._flash_colors: bool | None = None
        self._score: float | None = None

        safe_team_color = bs.safecolor(team.color, target_intensity=1.0)

        # FIXME: Should not do things conditionally for vr-mode, as there may
        #  be non-vr clients connected which will also get these value.
        vrmode = bs.app.env.vr

        if self._do_cover:
            if vrmode:
                self._backing_color = [0.1 + c * 0.1 for c in safe_team_color]
            else:
                self._backing_color = [0.05 + c * 0.17 for c in safe_team_color]
        else:
            self._backing_color = [0.05 + c * 0.1 for c in safe_team_color]

        opacity = (0.8 if vrmode else 0.8) if self._do_cover else 0.5
        self._backing = bs.NodeActor(
            bs.newnode(
                'image',
                attrs={
                    'scale': (self._width, self._height),
                    'opacity': opacity,
                    'color': self._backing_color,
                    'vr_depth': -3,
                    'attach': 'topLeft',
                    'texture': self._backing_tex,
                },
            )
        )

        self._barcolor = safe_team_color
        self._bar = bs.NodeActor(
            bs.newnode(
                'image',
                attrs={
                    'opacity': 0.7,
                    'color': self._barcolor,
                    'attach': 'topLeft',
                    'texture': self._bar_tex,
                },
            )
        )

        self._bar_scale = bs.newnode(
            'combine',
            owner=self._bar.node,
            attrs={
                'size': 2,
                'input0': self._bar_width,
                'input1': self._bar_height,
            },
        )
        assert self._bar.node
        self._bar_scale.connectattr('output', self._bar.node, 'scale')
        self._bar_position = bs.newnode(
            'combine',
            owner=self._bar.node,
            attrs={'size': 2, 'input0': 0, 'input1': 0},
        )
        self._bar_position.connectattr('output', self._bar.node, 'position')
        self._cover_color = safe_team_color
        if self._do_cover:
            self._cover = bs.NodeActor(
                bs.newnode(
                    'image',
                    attrs={
                        'scale': (self._width * 1.15, self._height * 1.6),
                        'opacity': 1.0,
                        'color': self._cover_color,
                        'vr_depth': 2,
                        'attach': 'topLeft',
                        'texture': self._cover_tex,
                        'mesh_transparent': self._mesh,
                    },
                )
            )

        clr = safe_team_color
        maxwidth = 130.0 * (1.0 - scoreboard.score_split)
        flatness = (1.0 if vrmode else 0.5) if self._do_cover else 1.0
        self._score_text = bs.NodeActor(
            bs.newnode(
                'text',
                attrs={
                    'h_attach': 'left',
                    'v_attach': 'top',
                    'h_align': 'right',
                    'v_align': 'center',
                    'maxwidth': maxwidth,
                    'vr_depth': 2,
                    'scale': self._scale * 0.9,
                    'text': '',
                    'shadow': 1.0 if vrmode else 0.5,
                    'flatness': flatness,
                    'color': clr,
                },
            )
        )

        clr = safe_team_color

        team_name_label: str | bs.Lstr
        if label is not None:
            team_name_label = label
        else:
            team_name_label = team.name

            # We do our own clipping here; should probably try to tap into some
            # existing functionality.
            if isinstance(team_name_label, bs.Lstr):
                # Hmmm; if the team-name is a non-translatable value lets go
                # ahead and clip it otherwise we leave it as-is so
                # translation can occur..
                if team_name_label.is_flat_value():
                    val = team_name_label.evaluate()
                    if len(val) > 10:
                        team_name_label = bs.Lstr(value=val[:10] + '...')
            else:
                if len(team_name_label) > 10:
                    team_name_label = team_name_label[:10] + '...'
                team_name_label = bs.Lstr(value=team_name_label)

        flatness = (1.0 if vrmode else 0.5) if self._do_cover else 1.0
        self._name_text = bs.NodeActor(
            bs.newnode(
                'text',
                attrs={
                    'h_attach': 'left',
                    'v_attach': 'top',
                    'h_align': 'left',
                    'v_align': 'center',
                    'vr_depth': 2,
                    'scale': self._scale * 0.9,
                    'shadow': 1.0 if vrmode else 0.5,
                    'flatness': flatness,
                    'maxwidth': 130 * scoreboard.score_split,
                    'text': team_name_label,
                    'color': clr + (1.0,),
                },
            )
        )

    def flash(self, countdown: bool, extra_flash: bool) -> None:
        """Flash momentarily."""
        self._flash_timer = bs.Timer(
            0.1, bs.WeakCall(self._do_flash), repeat=True
        )
        if countdown:
            self._flash_counter = 10
        else:
            self._flash_counter = int(20.0 * self._flash_length)
        if extra_flash:
            self._flash_counter *= 4
        self._set_flash_colors(True)

    def set_position(self, position: Sequence[float]) -> None:
        """Set the entry's position."""

        # Abort if we've been killed
        if not self._backing.node:
            return

        self._pos = tuple(position)
        self._backing.node.position = (
            position[0] + self._width / 2,
            position[1] - self._height / 2,
        )
        if self._do_cover:
            assert self._cover.node
            self._cover.node.position = (
                position[0] + self._width / 2,
                position[1] - self._height / 2,
            )
        self._bar_position.input0 = self._pos[0] + self._bar_width / 2
        self._bar_position.input1 = self._pos[1] - self._bar_height / 2
        assert self._score_text.node
        self._score_text.node.position = (
            self._pos[0] + self._width - 7.0 * self._scale,
            self._pos[1] - self._bar_height + 16.0 * self._scale,
        )
        assert self._name_text.node
        self._name_text.node.position = (
            self._pos[0] + 7.0 * self._scale,
            self._pos[1] - self._bar_height + 16.0 * self._scale,
        )

    def _set_flash_colors(self, flash: bool) -> None:
        self._flash_colors = flash

        def _safesetcolor(node: bs.Node | None, val: Any) -> None:
            if node:
                node.color = val

        if flash:
            scale = 2.0
            _safesetcolor(
                self._backing.node,
                (
                    self._backing_color[0] * scale,
                    self._backing_color[1] * scale,
                    self._backing_color[2] * scale,
                ),
            )
            _safesetcolor(
                self._bar.node,
                (
                    self._barcolor[0] * scale,
                    self._barcolor[1] * scale,
                    self._barcolor[2] * scale,
                ),
            )
            if self._do_cover:
                _safesetcolor(
                    self._cover.node,
                    (
                        self._cover_color[0] * scale,
                        self._cover_color[1] * scale,
                        self._cover_color[2] * scale,
                    ),
                )
        else:
            _safesetcolor(self._backing.node, self._backing_color)
            _safesetcolor(self._bar.node, self._barcolor)
            if self._do_cover:
                _safesetcolor(self._cover.node, self._cover_color)

    def _do_flash(self) -> None:
        assert self._flash_counter is not None
        if self._flash_counter <= 0:
            self._set_flash_colors(False)
        else:
            self._flash_counter -= 1
            self._set_flash_colors(not self._flash_colors)

    def set_value(
        self,
        score: float,
        max_score: float | None = None,
        countdown: bool = False,
        flash: bool = True,
        show_value: bool = True,
    ) -> None:
        """Set the value for the scoreboard entry."""

        # If we have no score yet, just set it.. otherwise compare
        # and see if we should flash.
        if self._score is None:
            self._score = score
        else:
            if score > self._score or (countdown and score < self._score):
                extra_flash = (
                    max_score is not None
                    and score >= max_score
                    and not countdown
                ) or (countdown and score == 0)
                if flash:
                    self.flash(countdown, extra_flash)
            self._score = score

        if max_score is None:
            self._bar_width = 0.0
        else:
            if countdown:
                self._bar_width = max(
                    2.0 * self._scale,
                    self._width * (1.0 - (float(score) / max_score)),
                )
            else:
                self._bar_width = max(
                    2.0 * self._scale,
                    self._width * (min(1.0, float(score) / max_score)),
                )

        cur_width = self._bar_scale.input0
        bs.animate(
            self._bar_scale, 'input0', {0.0: cur_width, 0.25: self._bar_width}
        )
        self._bar_scale.input1 = self._bar_height
        cur_x = self._bar_position.input0
        assert self._pos is not None
        bs.animate(
            self._bar_position,
            'input0',
            {0.0: cur_x, 0.25: self._pos[0] + self._bar_width / 2},
        )
        self._bar_position.input1 = self._pos[1] - self._bar_height / 2
        assert self._score_text.node
        if show_value:
            self._score_text.node.text = str(score)
        else:
            self._score_text.node.text = ''

class _EntryProxy:
    """Encapsulates adding/removing of a scoreboard Entry."""

    def __init__(self, scoreboard: Scoreboard, team: bs.Team):
        self._scoreboard = weakref.ref(scoreboard)

        # Have to store ID here instead of a weak-ref since the team will be
        # dead when we die and need to remove it.
        self._team_id = team.id

    def __del__(self) -> None:
        scoreboard = self._scoreboard()

        # Remove our team from the scoreboard if its still around.
        # (but deferred, in case we die in a sim step or something where
        # its illegal to modify nodes)
        if scoreboard is None:
            return

        try:
            bs.pushcall(bs.Call(scoreboard.remove_team, self._team_id))
        except bs.ContextError:
            # This happens if we fire after the activity expires.
            # In that case we don't need to do anything.
            pass

class Scoreboard:
    """A display for player or team scores during a game.

    category: Gameplay Classes
    """

    _ENTRYSTORENAME = bs.storagename('entry')

    def __init__(self, label: bs.Lstr | None = None, score_split: float = 0.7):
        """Instantiate a scoreboard.

        Label can be something like 'points' and will
        show up on boards if provided.
        """
        self._flat_tex = bs.gettexture('null')
        self._entries: dict[int, _Entry] = {}
        self._label = label
        self.score_split = score_split

        # For free-for-all we go simpler since we have one per player.
        self._pos: Sequence[float]
        if isinstance(bs.getsession(), bs.FreeForAllSession):
            self._do_cover = False
            self._spacing = 35.0
            self._pos = (17.0, -65.0)
            self._scale = 0.8
            self._flash_length = 0.5
        else:
            self._do_cover = True
            self._spacing = 50.0
            self._pos = (20.0, -70.0)
            self._scale = 1.0
            self._flash_length = 1.0

    def set_team_value(
        self,
        team: bs.Team,
        score: float,
        max_score: float | None = None,
        countdown: bool = False,
        flash: bool = True,
        show_value: bool = True,
    ) -> None:
        """Update the score-board display for the given bs.Team."""
        if team.id not in self._entries:
            self._add_team(team)

            # Create a proxy in the team which will kill
            # our entry when it dies (for convenience)
            assert self._ENTRYSTORENAME not in team.customdata
            team.customdata[self._ENTRYSTORENAME] = _EntryProxy(self, team)

        # Now set the entry.
        self._entries[team.id].set_value(
            score=score,
            max_score=max_score,
            countdown=countdown,
            flash=flash,
            show_value=show_value,
        )

    def _add_team(self, team: bs.Team) -> None:
        if team.id in self._entries:
            raise RuntimeError('Duplicate team add')
        self._entries[team.id] = _Entry(
            self,
            team,
            do_cover=self._do_cover,
            scale=self._scale,
            label=self._label,
            flash_length=self._flash_length,
        )
        self._update_teams()

    def remove_team(self, team_id: int) -> None:
        """Remove the team with the given id from the scoreboard."""
        del self._entries[team_id]
        self._update_teams()

    def _update_teams(self) -> None:
        pos = list(self._pos)
        for entry in list(self._entries.values()):
            entry.set_position(pos)
            pos[1] -= self._spacing * self._scale


from itertools import product

import networkx as nx
import numpy as np
import pandas as pd
from sklearn.metrics import mean_squared_error

from .tools import transform_ts
from .generator import node_name

class VAR():

    def __init__(self, p):
        self.p = p
        self.is_fitted = False

    def fit(self, ts_data):
        _, data_matrix = transform_ts(ts_data, self.p)
        self.dim = ts_data.shape[1]
        self.length = data_matrix.shape[0]

        y = data_matrix[:, :self.dim]
        X = data_matrix[:, self.dim:]
        X_ = np.insert(X, 0, 1, axis=1)

        self.params = np.linalg.lstsq(X_, y, rcond=1e-15)[0]
        self.free_params = self.params.size
        self.residuals = y - np.dot(X_, self.params)
        self.sse = np.dot(self.residuals.T, self.residuals)
        # self.sigma_u = self.sse/(self.length - self.dim*self.p - 1)
        self.sigma_u = self.sse/self.length
        self.is_fitted = True

    def fit_from_graph(self, dim, data_matrix, graph, mapping=None):
        self.dim = dim
        self.length = data_matrix.shape[0]
        self.inputs = []
        self.params = np.zeros((self.dim, self.dim * self.p + 1))
        self.free_params = 0

        if mapping is None:
            mapping = {i: n for i, n in enumerate(graph.nodes())}
        inverted_mapping = {v: k for k, v in mapping.items()}

        for x_t in range(self.dim):
            input_nodes = list(graph.predecessors(mapping[x_t]))

            inputs = np.array([inverted_mapping[x] for x in input_nodes])
            y = data_matrix[:, x_t]
            if input_nodes:
                X = data_matrix[:, inputs]
                positions = np.insert(inputs - self.dim + 1, 0, 0)
            else:
                X = np.array([[]]*len(data_matrix))
                positions = np.array([0])
            X_ = np.insert(X, 0, 1, axis=1)
            params = np.linalg.lstsq(X_, y, rcond=1e-15)[0]

            self.params[x_t, positions] = params
            self.free_params += params.size

        self.params = self.params.T
        y = data_matrix[:, :self.dim]
        X = data_matrix[:, self.dim: self.dim*(self.p+1)]
        X_ = np.insert(X, 0, 1, axis=1)
        self.residuals = y - np.dot(X_, self.params)
        self.sse = np.dot(self.residuals.T, self.residuals)
        # not sure whether this is ok
        self.sigma_u = self.sse/self.length
        self.is_fitted = True

    def to_graph(self, threshold=0.1):
        end_nodes = ['X{}_t'.format(i) for i in range(self.dim)]
        start_nodes = ['X{}_t-{}'.format(j, i) for i, j in product(range(self.p, 0, -1), range(self.dim))]

        A = self.params[1:]
        assert A.shape == (len(start_nodes), len(end_nodes))

        estimated_graph = nx.DiGraph()
        node_ids = np.array([[(d, l) for l in range(self.p, -1, -1)] for d in range(self.dim)])
        estimated_graph.add_nodes_from([node_name(d, l) for d, l in
                                       np.reshape(node_ids, (self.dim * (self.p+1), 2))])

        for i in range(len(start_nodes)):
            for j in range(len(end_nodes)):
                if np.abs(A[i][j]) > threshold:
                    estimated_graph.add_edge(start_nodes[i], end_nodes[j], weight=A[i][j])
        return estimated_graph

    def evaluate_test_set(self, start_values, test_data):
        dim = test_data.shape[1]
        variables = pd.concat([start_values, test_data])
        _, data_matrix = transform_ts(variables, self.p)
        y = data_matrix[:, :dim]
        X_ = np.insert(data_matrix[:, dim:], 0, 1, axis=1)

        predictions = np.dot(X_, self.params)
        mse = mean_squared_error(y, predictions)

        residuals = y - predictions
        sse = np.dot(residuals.T, residuals)
        sigma_u = sse / len(test_data)
        _, ll = np.linalg.slogdet(sigma_u)
        bic = self._bic(ll, self.free_params, len(test_data))

        return mse, bic

    def information_criterion(self, ic, offset=0, free_params=None):
        if not self.is_fitted:
            raise Exception('model is not fitted')
        ll = self._log_likelihood()
        if free_params is None:
            free_params = self.free_params
        nobs = self.length-offset

        if ic == 'bic':
            return self._bic(ll, free_params, nobs)
        elif ic == 'aic':
            return self._aic(ll, free_params, nobs)
        elif ic == 'hqic':
            return self._hqic(ll, free_params, nobs)
        else:
            raise Exception('unknown information criterion')

    def _bic(self, ll, free_params, nobs):
        return ll + (np.log(nobs) / nobs) * free_params

    def _aic(self, ll, free_params, nobs):
        return ll + (2. / nobs) * free_params

    def _hqic(self, ll, free_params, nobs):
        return ll + (2. * np.log(np.log(nobs)) / nobs) * free_params

    def _log_likelihood(self):
        _, logdet = np.linalg.slogdet(self.sigma_u)
        return logdet


#!/usr/bin/env python3

# f = open("puzzle_test.txt","r")
f = open("puzzle.txt","r")
lines = f.readlines()

paths = {}
for line in lines:
	v1, v2 = line[:-1].split("-")
	if v1 not in paths:
		paths[v1] = []
	paths[v1].append(v2)
	if v2 not in paths:
		paths[v2] = []
	paths[v2].append(v1)

numPaths = 0
visited = {}
isTwo = False
path = []
def dfs(v):
	global numPaths
	global visited
	global isTwo
	global path

	if v == "end":
		path.append(v)
		# print(path)
		path.pop()
		numPaths += 1
		return
	if v.islower():
		if v not in visited:
			visited[v] = 0
		if visited[v] > 1:
			return
		if visited[v] == 1:
			if isTwo or v == "start" or v == "end":
				return
			else:
				visited[v] += 1
				isTwo = True
		else:
			visited[v] += 1

	path.append(v)
	for neigh in paths[v]:
		dfs(neigh)

	path.pop()
	if v.islower():
		if visited[v] == 2:
			isTwo = False
		visited[v] -= 1

dfs("start")

print(numPaths)


import arxiv
import urllib
import pdfx
import re
import spacy
from spacy.lang.fr.examples import sentences
from xml.sax.saxutils import escape
import sys

def after_references(mypdftext):
    keyword1 = 'References'
    keyword2 = 'REFERENCES'
    keyword3 = 'R EFERENCES'
    keyword4 = 'Reference'
    keyword5='[1]'

    if keyword1 in mypdftext :
            before_keyword, keyword, after_keyword = mypdftext.partition(keyword1)
    elif keyword2 in mypdftext :
            before_keyword, keyword, after_keyword = mypdftext.partition(keyword2)
    elif keyword3 in mypdftext :
            before_keyword, keyword, after_keyword = mypdftext.partition(keyword3)
    elif keyword4 in mypdftext :
            before_keyword, keyword, after_keyword = mypdftext.partition(keyword4)
    elif keyword5 in mypdftext :
            before_keyword, keyword, after_keyword = mypdftext.partition(keyword5)
    else:
        after_keyword = mypdftext[:10000]
    return after_keyword

def extract(text:str) :
    nlp = spacy.load('en_core_web_sm')
    doc = nlp(text.strip())
    named_entities = []

    for i in doc.ents:
        entry = str(i.lemma_).lower()
        text = text.replace(str(i).lower(), "")
        if i.label_ in ["PERSON"]:
            named_entities.append(entry.title().replace(" ", "_").replace("\n","_"))
        named_entities = list(dict.fromkeys(named_entities))
    return named_entities

def pdf_arxiv():
    search = arxiv.Search(
        query = "computer science &  ai",
        # id_list=["1605.08386v1"]
        max_results = 1,
        sort_by = arxiv.SortCriterion.SubmittedDate
    )

    for result in search.results():
        print ("Titre :", result.title)
        print ("Lien :", result.pdf_url)

    for result in search.results():
        author = result.authors
        author_list = [re.sub("[^A-Za-z0-9]","_",str(i)) for i in author]

    print("Autheurs :", author_list)

    response = urllib.request.urlopen(result.pdf_url)
    file = open("Test" + ".pdf", 'wb')
    file.write(response.read())
    file.close()

    # Leture du PDF
    pdf = pdfx.PDFx("Test.pdf")
    metadata = pdf.get_metadata()
    references_dict = pdf.get_references_as_dict()
    text = pdf.get_text()

    return text

text=pdf_arxiv()
references = after_references(text)
references_list = extract(references)

print("5 premiers noms cités dans les références :", references_list[:5])


'''
Created on Sep 20, 2015

@author: Cuyler Quint <deanquint@gmail.com>

Tic Tac Toe
    Requirements
        -python version 1.7
        -pygame version 1.9

    Description:
        This is a clone of the famous tic tac Toe
        with implemetation of a computer to play agaisnt
        at three different levels.

        level 1: random moves
        level 2: blocks winning moves
        level 3: level 2 and attemps to win

        command line arguments are very straigt forward. Enjoy!

'''

import random
import pygame

class Player:

    def __init__(self, name, letter):
        self.name = name
        self.letter = letter

class Game:
    '''
    classdocs
    '''

    def __init__(self,user,AI):
        self.user = user
        self.AI = AI
        self.Difficulty = input("Welcome to Tic Tac Toe\n\nSelect Difficulty\n1)level 0\n2)level 1\n3)level 2\n")
        self.TTTbox = [' '] * 9
        self.Playing = True
        self.turnCount = 0
        self.UserLetter = 'X'
        self.AILetter = 'O'
        self.turn = 'user'

        '''
        Constructor
        '''
    def gameName(self):
        print(self.AI.letter)
        print(self.user.letter)
        print(self.Difficulty)

    def setGame(self):
        '''
        Sets the Game for starting play
        '''
        self.TTTbox[0] = '1'
        self.TTTbox[1] = '2'
        self.TTTbox[2] = '3'
        self.TTTbox[3] = '4'
        self.TTTbox[4] = '5'
        self.TTTbox[5] = '6'
        self.TTTbox[6] = '7'
        self.TTTbox[7] = '8'
        self.TTTbox[8] = '9'
        self.Playing = True
        self.turn = 'user'
        self.turnCount = 0

    def printBox(self,box):
        '''
        prints the updated board with user and computer moves
        '''
        print(' ' + box[0] + ' | ' + box[1] + ' | ' + box[2])
        print('-----------')
        print(' ' + box[3] + ' | ' + box[4] + ' | ' + box[5])
        print('-----------')
        print(' ' + box[6] + ' | ' + box[7] + ' | ' + box[8])

    def copyBox(self,box):
        '''
        copys a temporary board and returns that board
        '''
        copyBox = []
        for i in box:
            copyBox.append(i)
        return copyBox

    def userPick(self,TTTbox,Char):
        '''
        goes throught a users turn and promts them to make
        a move and updates ther choice if valid
        '''
        print('Pick a avaible space')
        pick = input()
        if (self.openSpace(TTTbox, pick) == False ):
            print('spot already taken, pick again')
            self.printBox(TTTbox)
            self.userPick(TTTbox,Char)
        self.paintBox(TTTbox,Char , pick)
        return pick

    def getPossibleMoves(self,box):
        '''
        determines all possible moves that a user
        can pick from and returns array of them
        '''
        pMoves = [1,2,3,4,5,6,7,8,9]
        for i in range(1,10):
            if ((box[i-1] == 'X') or (box[i-1] == 'O')):
                pMoves.remove(i)
        return pMoves

    def getWinningMove(self,box):
        '''
        copys a box for all possible moves
        and test if a winning move can be made
        '''
        for i in range(1,10):
            cBox = self.copyBox(box)
            if (self.openSpace(cBox, i) == True):
                self.paintBox(cBox,'O' , i)
                if self.Win(cBox, 'O'):
                    return i
        return 0

    def getBlockingMove(self,box):
        '''
        copys a box for all possible moves
        and tests if a blocking move can be made
        '''

        for i in range(1,10):
            cBox = self.copyBox(box)
            if (self.openSpace(cBox, i) == True):
                self.paintBox(cBox,'X' , i)
                if self.Win(cBox, 'X'):
                    return i
        return 0

    def openSpace(self,TTTbox, move):
        '''
        determines if a positon is a open space or not
        '''
        temp = move - 1
        if ((TTTbox[temp] ==  'O') or (TTTbox[temp] ==  'X')):
            return False
        else:
            return True

    def getPendingMove(self,box):
        '''
        logic to place best move by computer in
        early game that was not chosen by human
        '''
        if((box[5] == 'O') and((box[1] == 'O') or (box[3] == 'O') or (box[7] == 'O') or (box[9] == 'O'))):
            for i in range(1,9):
                if (i == 2):  # take middle
                    if (self.openSpace(box, 2) == True):
                        return i;
                if (i == 4):  # take middle
                    if (self.openSpace(box, 4) == True):
                        return i;
                if (i == 6):  # take korner
                    if (self.openSpace(box, 6) == True):
                        return i;
                if (i == 8):  # take korner
                    if (self.openSpace(box, 8) == True):
                        return i;
                else:
                    return 0;

#  made random move at 2 4 6 or 8
        if (self.openSpace(box, 5) == True):
            return 5
        else:
            for i in range(1,9):
                if (i == 1):  # take korner
                    if (self.openSpace(box, 1) == True):
                         return 1;
                if (i == 3):  # take korner
                    if (self.openSpace(box, 3) == True):
                         return 3;
                if (i == 7):  # take korner
                    if (self.openSpace(box, 7) == True):
                         return 7;
                if (i == 9):  # take korner
                    if (self.openSpace(box, 9) == True):
                        return 9;

            else:
                return 0;

    def makeAIMove(self,box,char,difficulty):
        '''
        depending on the computers difficulty, this function decides
        what type of move the computer will make based of the
        known played postions.
        '''
        if self.Difficulty == 1:
            pMoves = self.getPossibleMoves(box)
            move = random.choice(pMoves)
            self.paintBox(box, char, move)
        elif self.Difficulty == 2 :#see if can finsish, make random
            wMove = self.getWinningMove(box)
            if(wMove == 0):
                pMoves = self.getPossibleMoves(box)
                move = random.choice(pMoves)
                self.paintBox(box, char, move)
            else:
                self.paintBox(box, char, wMove)
        elif self.Difficulty == 3:#make pending move  do three board copys and make each use and comp move
            wMove = self.getWinningMove(box)
            if(wMove == 0):
                bMove = self.getBlockingMove(box)
                if(bMove == 0):
                    pendingMove = self.getPendingMove(box)
                    if(pendingMove == 0):
                        pMoves = self.getPossibleMoves(box)
                        move = random.choice(pMoves)
                        self.paintBox(box, char, move)
                    else:
                        self.paintBox(box, char, pendingMove)
                else:
                    self.paintBox(box, char, bMove)
            else:
                self.paintBox(box, char, wMove)

    def fullBox(self,box):
        '''
        determines if a game has all postions filled
        '''
        for i in range(1,10):
            if (self.openSpace(box, i)):
                return False
            return True

    def paintBox(self,box, letter, move):
        '''
        paints the desginated postion to the
        board with the correct player letter
        '''

        if (move == 9):
            box[8] = letter
        temp = move - 1
        box[temp] = letter

    def Win(self,box,char):
        '''
        checks made to see if a player has won
        '''
        if((box[0] == char and box[1] == char and box[2] == char) or
        (box[3] == char and box[4] == char and box[5] == char ) or
        (box[6] == char and box[7] == char and box[8] == char ) or #hori
        (box[0] == char and box[3] == char and box[6] == char ) or
        (box[1] == char and box[4] == char and box[7] == char ) or
        (box[2] == char and box[5] == char and box[8] == char ) or #vert
        (box[0] == char and box[4] == char and box[8] == char ) or
        (box[6] == char and box[4] == char and box[2] == char )):
            return True#diag
        else:
            return False


def find_it(seq):
    odd_n=None
    for x in seq:
        n=seq.count(x)
        if n%2 !=0:
            odd_n=x
    return odd_n

def find_it2(seq):
    return [x for x in seq if seq.count(x)%2!=0][0]

if __name__ == '__main__':
    sqe=[20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]
    print(find_it2(sqe))


import json
import math
import sys
import operator

model_file = sys.argv[1]
test_file = sys.argv[2]

f_test = open(test_file, 'r')
f_model = open(model_file, 'r')
#sys.stdout = open("spam.out", 'w')

Dict = json.load(f_model)

d = {}
P_c = {}
classes = []
N = 0 #total number of documents
correct = 0
k = int(Dict['~_VocabularySize'])

for t, v in Dict.items():
  ClassName, WordName = t.split('_',1)
  if ClassName == '*':
     i, j = WordName.split('_', 1)
     if i not in classes:
        classes.append(i)

for CLASS1 in classes:
    N = N + Dict['*_' + CLASS1 + '_' + 'Count']

for CLASS in classes:
    d[CLASS] = 0
    P_c[CLASS] = math.log(Dict['*_' + CLASS + '_' + 'Count']/N)

for x, y in Dict.items(): #total number for each class
  ClassName1, WordName1 = x.split('_',1)
  if ClassName1 != '*' and ClassName1 != '~':
     d[ClassName1] = d[ClassName1] + y

for line in f_test:
   P = {}
   w1 = ''
   for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~':
       line = line.replace(ch, ' ')
   line = line.lower()
   words = line.split()
   for s in classes:
       P_d_c =0
       for w in words:
          w1 = s + '_' + w
          if w1 in Dict:
             P_w1_c = math.log((Dict[w1] + 1) / (d[s] + k))
             P_d_c = P_d_c + P_w1_c
          else:
             P_w1_c = math.log(1 / (d[s] + k + 1 ))
             P_d_c = P_d_c + P_w1_c
       P[s] = P_d_c + P_c[s]

   Result = max(P.items(), key=operator.itemgetter(1))[0]
   print(Result)#modify

#sys.stdout.close()
f_test.close()
f_model.close()

dingyi567


def cost(cave, y, x):
    return cave[y][x][1] if x>=0 and y>=0 else 9999999999999999999999999

def printCave(cave, costOnly):
    for r in cave:
        if costOnly:
            for v in r:
                print(v[0], end="")
            print()
        else:
            print(r)

def computePathCost(cave):
    # printCave(cave, True)
    for y in range(len(cave)):
        for x in range(len(cave[y])):

            #corner case (should be skipped)
            if y==0 and x==0:
                continue

            #update support values
            p = cave[y][x]  #create a reference
            left, up = [cost(cave,y,x-1), cost(cave,y-1,x)]
            if left<up:
                p[1] = left + p[0]
                p[2], p[3] = x-1, y
            else:
                p[1] = up + p[0]
                p[2], p[3] = x, y-1

    # printCave(cave, False)
    print("The cost of shortest path is:", cave[-1][-1][1])

def computePath(cave):
    path=[]
    p=[0, 0, len(cave)-1, len(cave[0])-1]
    while p[2]!=-1 and p[3]!=-1:
        path.append((p[2], p[3]))
        p = cave[p[3]][p[2]]

    path.reverse()
    print("Path:", path)

if __name__=="__main__":
    #read input
    fin = open("in.txt", 'r') # "in.txt" "inEx.txt"

    cave = [] #x*y: [local_cost, path_cost, paren_x, parent_y)]
    for line in fin:
        row = []
        for c in line.strip("\n"): #cost
            row.append( [int(c), 0, -1, -1] )
        cave.append(row)

    #quintuplicate(N) the map
    N=5
    X = len(cave[0])
    Y = len(cave)
    caveXN = [[[0]*4 for i in range(N*X)] for i in range(N*Y)]

    for yN in range(N):
        YN=yN*Y
        for xN in range(N):
            XN=xN*X
            for y in range(len(cave)):
                for x in range(len(cave[y])):
                    v = (cave[y][x][0] +yN +xN)
                    caveXN[YN+y][XN+x][0] = (v-1)%9 +1 #strange module operation

    cave[0][0] = [0, 0, -1, -1] #set the initial point at no cost
    computePathCost(cave)
    computePath(cave)

    caveXN[0][0] = [0, 0, -1, -1] #set the initial point at no cost
    computePathCost(caveXN)
    # computePath(caveXN)


# -*- coding: utf-8 -*-
"""
Created on Mon Feb 11 14:41:11 2019

@author: Kumail
"""

import pandas
import numpy as np
from sklearn import model_selection
from sklearn.linear_model import LogisticRegression

dataset = pandas.read_csv("../datasets/iris.csv")
array = dataset.values
X = array[:,0:4]
Y = array[:,4]

validation_size = 0.29
seed = 7

X_train, X_test, Y_train, Y_test = model_selection.train_test_split(X, Y, test_size=validation_size, random_state=seed)

clf = LogisticRegression(max_iter=1000, random_state=seed, solver='lbfgs', multi_class='multinomial').fit(X_train, Y_train)

predict = clf.predict(X_test[:5, :])
actual = Y_test[:5]
scoreTest = round(clf.score(X_test, Y_test)*100, 1)
scoreTrain= round(clf.score(X_train, Y_train)*100, 1)

print(f"Prediction: {predict}")
print(f"Actual: {actual}")
print(f"Training Score: {scoreTrain}%")
print(f"Test Score: {scoreTest}%")

sepal_length = int(input("Enter sepal length: "))
sepal_width = int(input("Enter sepal width: "))
petal_length = int(input("Enter petal length: "))
petal_width = int(input("Enter petal width: "))
inputData = np.array([sepal_length, sepal_width, petal_length, petal_width]).reshape(1,-1)

newPredict = clf.predict(inputData)[0]
print(f"Prediction is: {newPredict}")


from django.conf.urls import patterns, url
from users import views

urlpatterns = patterns('',
    url(r'^$',views.index, name='index'),
    url(r'^(?P<user_id>\d+)/$', views.detail, name='detail'),
    url(r'^attendance/$', views.attendance, name='attendance'),
    url(r'^notifications/$', views.notifications, name='notification'),
    url(r'^dues/$', views.dues, name='dues'),
    #url(r'^inbox/$', views.inbox, name='inbox'),
)


import mesa
from agents import TreeAgent, Seed
from model import DispersalModel
from mesa.visualization.modules import CanvasGrid, ChartModule
from pointpats import PointPattern
import pointpats.quadrat_statistics as qs

def get_mean_nnd(self):
        coords_seeds = []
        for (agents, x, y) in self.grid.coord_iter():
            if Seed in (type(agent) for agent in agents):
                coords_seeds.append([x, y])

        pp = PointPattern(coords_seeds)

        return f"Distância Média do Vizinho Mais Próximo: {round(pp.mean_nnd,1)}"

def get_max_nnd(self):
        coords_seeds = []
        for (agents, x, y) in self.grid.coord_iter():
            if Seed in (type(agent) for agent in agents):
                coords_seeds.append([x, y])

        pp = PointPattern(coords_seeds)
        return f"Distância Máxima do Vizinho Mais Próximo: {round(pp.max_nnd,1)}"

def get_min_nnd(self):
        coords_seeds = []
        for (agents, x, y) in self.grid.coord_iter():
            if Seed in (type(agent) for agent in agents):
                coords_seeds.append([x, y])

        pp = PointPattern(coords_seeds)
        return f"Distância Mínima do Vizinho Mais Próximo: {round(pp.min_nnd,1)}"

COLORS = {"Fine": "darkgreen", "Contaminated": "yellow"}

def seed_dispersal_portrayal(agent):
    if agent is None:
        return

    portrayal = {}
    if type(agent) is TreeAgent:
        portrayal["Shape"] =  "resources/tree.png"
        portrayal["Filled"] = "true"
        portrayal["Layer"] = 0
        portrayal["w"] = 1
        portrayal["h"] = 1

    elif type(agent) is Seed:
        portrayal["Color"] = COLORS[agent.condition]
        portrayal["Shape"] = "circle"
        portrayal["r"] = 0.4
        portrayal["Filled"] = "true"
        portrayal["Layer"] = 0
        portrayal["w"] = 1
        portrayal["h"] = 1

    return portrayal

canvas_element = CanvasGrid(seed_dispersal_portrayal, 20, 20, 500, 500)

#chart_element = ChartModule([{"Label": "mdvp", "Color": "black"}])

server = mesa.visualization.ModularServer(
    DispersalModel, [get_min_nnd, get_mean_nnd, get_max_nnd, canvas_element],
    "Dispersão de Propágulos - Mortalidade Dependente de Densidade")
server.port = 8521


from tkinter import Tk
__all__=['copy','paste','clear']

__author__='Calvin(Martin)Adyezik  adyezik@gmail.com'

__doc__="""simple Module to work with clipboard based on tkinter -Python 3"""

__name__='Xclipboard'

def copy(text):
    """copy text to clipboard """
    try:
        root=Tk()
        root.withdraw()
        root.clipboard_append(text)
    except Exception as e:
        print ('Error: ',e)
    finally:
        root.destroy()

def paste():
    """paste text from clipboad"""
    try:
        root=Tk()
        root.withdraw()
        return root.clipboard_get()
    except Exception as e:
        print ('Error: ',e)
    finally:
        root.destroy()

def clear():
    """clear clipboard"""
    try:
        root=Tk()
        root.withdraw()
        root.clipboard_clear()
    except Exception as e:
        print ('Error: ',e)
    finally:
        root.destroy()


import cv2
import numpy as np
import dlib
import matplotlib.pyplot as plt
import sys
import face_recognition
import imutils.face_utils
from imutils import face_utils

#import imutils.face_utils
#image read
imq = cv2.imread('C:\\Users\\moham\\Pictures\\cv_DP2jpg.jpg', 0)
#image show
cv2.imshow('image', img)
#image show without hanging up
cv2.waitKey(0)
#converting dtype of numpy.ndarray into float(32 bit) /255 ????
im = np.float32(imq)/255.0
#depth command ????
depth = cv2.CV_32F

#Calculating gradient
#The Sobel Operator is a discrete differentiation operator.
#It computes an approximation of the gradient of an image intensity function.
gx = cv2.Sobel(im, depth, 1, 0, ksize=1)
gy = cv2.Sobel(im, depth, 0, 1, ksize=1)
#computing the magnitude and angle of the gradient(2D vectors)
mag, angle = cv2.cartToPolar(gx, gy, angleInDegrees=True)

#plotting the picture
plt.figure(figsize=(12,8))
plt.imshow(mag)
plt.show()

#face detection
# HOG + Linear SVM = dlib.get_frontal_face_detector()
#MMOD CNN = dlib.cnn_face_detection_model_v1(modelPath)
#WE are using HOG

#The get_frontal_face_detector function does not accept any parameters. A call to it returns the pre-trained HOG +
#Linear SVM face detector included in the dlib library.
#Dlib’s HOG + Linear SVM face detector is fast and efficient. By nature of how the Histogram of Oriented Gradients (HOG)
#descriptor works, it is not invariant to changes in rotation and viewing angle.

#For more robust face detection, you can use the MMOD CNN face detector, available via the cnn_face_detection_model_v1 function
#this method accepts a single parameter, modelPath, which is the path to the pre-trained MMOD-Model_FaceDetection.dat
#file residing on disk.

face_detect = dlib.get_frontal_face_detector()
rects = face_detect(imq, 1) #gettinf the coordinates for the rectangle on the front face
for (i, rect) in enumerate(rects): #actually getting the coordinates from their tuple format
    (x, y, w, h) = face_utils.rect_to_bb(rect)
cv2.rectangle(imq, (x, y), (x + w, y + h), (0, 255, 128), 3)  #plotting the rect over the image

plt.figure(figsize=(12, 8))
plt.imshow(imq, cmap='gray')  #cmap is colormap instance
plt.show()

# RdBu_r, RdGy  RdGy_r RdYlBu_r RdYlBu


# -*-coding:utf-8-*-
__author__ = 'hank'

import os
import json

class ReadConfig(object):
    def __init__(self):
        self.local = os.path.abspath('.')
        self.father_path = os.path.dirname(self.local)
        self.json_path = self.father_path + "/config/"

    def read_json(self, json_name):
        json_name = self.json_path + json_name
        with open(json_name, "r", encoding='utf8', errors='ignore') as f:
            body_json = json.load(f)
        return body_json


import logging
from typing import List

from volatility3.framework import renderers, exceptions, interfaces
from volatility3.framework.configuration import requirements
from volatility3.framework.interfaces import plugins
from volatility3.framework.layers import intel

vollog = logging.getLogger(__name__)

class Statistics(plugins.PluginInterface):
    """Lists statistics about the memory space."""

    _required_framework_version = (2, 0, 0)

    @classmethod
    def get_requirements(cls) -> List[interfaces.configuration.RequirementInterface]:
        return [
            requirements.TranslationLayerRequirement(
                name="primary",
                description="Memory layer for the kernel",
                architectures=["Intel32", "Intel64"],
            )
        ]

    def _generator(self):
        # Do mass mapping and determine the number of different layers and how many pages go to each one
        layer = self.context.layers[self.config["primary"]]

        page_count = (
            swap_count
        ) = (
            invalid_page_count
        ) = (
            large_page_count
        ) = large_swap_count = large_invalid_count = other_invalid = 0

        if isinstance(layer, intel.Intel):
            page_addr = 0
            expected_page_size = 1 << layer.bits_per_register

            while page_addr < layer.maximum_address:
                try:
                    _, _, _, page_size, layer_name = list(
                        layer.mapping(page_addr, 2 * expected_page_size)
                    )[0]
                    if layer_name != layer.config["memory_layer"]:
                        swap_count += 1
                    else:
                        page_count += 1
                    if page_size > expected_page_size:
                        large_page_count += 1
                except exceptions.SwappedInvalidAddressException as excp:
                    swap_count += 1
                    page_size = 1 << excp.invalid_bits
                    if page_size != expected_page_size:
                        large_swap_count += 1
                except exceptions.PagedInvalidAddressException as excp:
                    invalid_page_count += 1
                    page_size = 1 << excp.invalid_bits
                    if page_size != expected_page_size:
                        large_invalid_count += 1
                except exceptions.InvalidAddressException as excp:
                    other_invalid += 1
                    page_size = expected_page_size
                    vollog.debug(
                        "A non-page lookup invalid address exception occurred at: {} in layer {}".format(
                            hex(excp.invalid_address), excp.layer_name
                        )
                    )

                page_addr += page_size
                self._progress_callback(
                    (page_addr * 100) / layer.maximum_address, "Reading memory"
                )

        yield (
            0,
            (
                page_count,
                large_page_count,
                swap_count,
                large_swap_count,
                invalid_page_count,
                large_invalid_count,
                other_invalid,
            ),
        )

    def run(self):
        return renderers.TreeGrid(
            [
                ("Valid pages (all)", int),
                ("Valid pages (large)", int),
                ("Swapped Pages (all)", int),
                ("Swapped Pages (large)", int),
                ("Invalid Pages (all)", int),
                ("Invalid Pages (large)", int),
                ("Other Invalid Pages (all)", int),
            ],
            self._generator(),
        )


import os, unittest, numpy as np
from saspt.parameters import StateArrayParameters
from saspt.constants import RBME

class TestStateArrayParameters(unittest.TestCase):
    def setUp(self):
        self.kwargs = dict(pixel_size_um=0.16, frame_interval=0.01,
            focal_depth=0.7, splitsize=10, sample_size=200,
            start_frame=10, max_iter=50, conc_param=2.0,
            progress_bar=False)

    def test_init(self):
        SAP = StateArrayParameters(**self.kwargs, nothing=0)
        for k, v in self.kwargs.items():
            assert getattr(SAP, k) == v, k

    def test_eq(self):
        SAP1 = StateArrayParameters(**self.kwargs)
        SAP2 = StateArrayParameters(**self.kwargs)
        kwargs = self.kwargs.copy()
        kwargs.update(max_iter=70)
        SAP3 = StateArrayParameters(**kwargs)
        assert SAP1 == SAP2
        assert SAP1 != SAP3


from time import time
import pennylane as qml
from scipy.optimize import minimize
import networkx as nx
from .unitaries import (
    hypercube_mixer,
    phase_shift,
    circulant_mixer,
    diagonal_pauli_decompose,
    complete_eigenvalues,
)

def gen_graph(qubits, seed, prob = 0.25):
    # for smaller graphs, increase the probability of edge generation
    #prob = prob if prob * (qubits**2) > 1 else 2.0/qubits**2
    # ensure that there is at least one edge
    n_edges = 0
    s = seed
    while n_edges == 0:
        if type(s) is int:
            G = nx.fast_gnp_random_graph(qubits, p=prob, seed=s, directed=False)
            s += 1
        else:
            G = nx.fast_gnp_random_graph(qubits, p=prob, directed=False)
        n_edges = G.number_of_edges()
    return G

def maxcut_qualities(G, wires):
    """Return a Pauli-string representation of the maxcut cost-function.

    Parameters
    ----------
    G : networkx graph
        graph for which the maxcut problem is to be solved
    wires : list or range
        number of wires (qubits), must cover the number of graph vertices

    Returns
    -------
    Hamiltonian
        Pauli-string representation of the maxcut cost-function.
    """
    wires = list(wires)
    C = 0
    for i, j in G.edges:
        C += qml.Identity(wires) - qml.PauliZ(wires=i) @ qml.PauliZ(wires=j)
    return -0.5 * C

def qaoa_hypercube_maxcut_evolution(device, depth, n_expvals, seed):
    """State-evolution benchmark function for the QAOA with a hypercube (transverse-field) mixing operator.

    State evolution based on Hamiltonian simulation.

    Parameters
    ----------
    device :
        an initialised Pennylane device
    depth : int
        ansatz circuit depth
    n_expvals : int
        number of times to compute the state evolution and return the
        expectation value with random variational parameters

    Returns
    -------
    (float, float)
        the last computed expectation value and the time taken to evaluate
        n_expvals repeats of the circuit
    """

    qubits = len(device.wires)

    G = gen_graph(qubits, seed)

    wires = range(qubits)
    qualities_H = maxcut_qualities(G, wires)

    @qml.qnode(device)
    def circuit(gammas_ts):
        for wire in wires:
            qml.Hadamard(wires=wire)
        for gamma, t in zip(*qml.numpy.split(gammas_ts, 2)):
            phase_shift(gamma, wires, qualities_H)
            hypercube_mixer(t, wires)
        return qml.expval(qualities_H)

    start = time()
    rng = qml.numpy.random.default_rng(seed)
    gammas_ts = rng.uniform(size=2 * depth, low=0, high=2 * qml.numpy.pi)
    for _ in range(n_expvals):
        expval = circuit(gammas_ts)
    specs = qml.specs(circuit)
    gate_sizes = specs(gammas_ts)['resources'].gate_sizes
    end = time()
    specs = qml.specs(circuit)
    gate_sizes = specs(gammas_ts)['resources'].gate_sizes
    circuit_depth = specs(gammas_ts)['resources'].depth
    return float(expval), end - start, circuit_depth, gate_sizes[1], gate_sizes[2]

def qaoa_complete_maxcut_evolution(device, depth, n_expvals, seed):
    """State-evolution benchmark function for the QAOA with a complete-graph mixing operator.

    State evolution based on the QFT.

    Parameters
    ----------
    device :
        an initialised Pennylane device
    depth : int
        ansatz circuit depth
    n_expvals : int
        number of times to compute the state evolution and return the
        expectation value with random variational parameters

    Returns
    -------
    (float, float)
        the last computed expectation value and the time taken to evaluate
        n_expvals repeats of the circuit
    """

    qubits = len(device.wires)

    G = gen_graph(qubits, seed)

    wires = range(qubits)
    qualities_H = maxcut_qualities(G, wires)

    eigen_decomp = diagonal_pauli_decompose(complete_eigenvalues(2**qubits))

    @qml.qnode(device)
    def circuit(gammas_ts):
        for wire in wires:
            qml.Hadamard(wires=wire)
        for gamma, t in zip(*qml.numpy.split(gammas_ts, 2)):
            phase_shift(gamma, wires, qualities_H)
            circulant_mixer(t, wires, eigen_decomp)
        return qml.expval(qualities_H)

    start = time()
    rng = qml.numpy.random.default_rng(seed)
    gammas_ts = rng.uniform(size=2 * depth, low=0, high=2 * qml.numpy.pi)
    for _ in range(n_expvals):
        expval = circuit(gammas_ts)
    specs = qml.specs(circuit)
    gate_sizes = specs(gammas_ts)['resources'].gate_sizes
    end = time()
    specs = qml.specs(circuit)
    gate_sizes = specs(gammas_ts)['resources'].gate_sizes
    circuit_depth = specs(gammas_ts)['resources'].depth
    return float(expval), end - start, circuit_depth, gate_sizes[1], gate_sizes[2]

def main_args():

    import argparse

    parser = argparse.ArgumentParser(description = "Run a test QAOA circuit with random variational parameters.", epilog = "Simulation output: last expectation value, qubits, depth, repeats, backend, graph sparsity, simulation time")
    parser.add_argument("-q", "--qubits", default=4, type=int, dest='qubits', nargs='?', help = 'number of qubits, default = 4')
    parser.add_argument("-d", "--depth", default=2, type=int, dest='depth', nargs='?', help = 'number of ansatz iterations, default = 2')
    parser.add_argument("-r", "--repeats", default=1, type=int, dest='repeats', nargs='?', help = 'number of expectation value evaluations, default = 1')
    parser.add_argument("-b", "--backend", default="lightning.qubit", type=str, dest='backend', nargs='?', help = 'simulation backend, default = lightning.qubit')
    parser.add_argument("-o", "--options", default=[],  dest='options', nargs = '*', help = 'backend-specific keyword options for device creation')
    parser.add_argument("-s", "--seed", default=None, dest='seed', type = int, nargs = '?', help = 'seed random number generation')
    parser.add_argument("-p", "--plot", default=False, dest='plot', action = 'store_true', help = 'plot the cicuit, do not simulate')
    parser.add_argument("-g", "--graph", default=0.1, dest='graph', type=float, help = 'graph sparsity (0,1], default = 0.1')
    parser.add_argument("-c", "--circuit", default=None, dest='circuit', type=str,  help = 'if present, save the circuit to this path as a QASM file')

    return parser.parse_args()

if __name__ == "__main__":

    import sys

    args = main_args()

    if len(args.options) > 0:
        device_code = f"qml.device('{args.backend}', wires = {args.qubits}, {' ,'.join(args.options)})"
        device = eval(device_code)
    else:
        device = qml.device(args.backend, wires = args.qubits)

    G = gen_graph(args.qubits, args.seed, args.graph)

    wires = range(args.qubits)
    qualities_H = maxcut_qualities(G, wires)

    if not args.seed is None:
        rng = qml.numpy.random.default_rng(args.seed)
    else:
        rng = qml.numpy.random.default_rng()

    gammas_ts = rng.uniform(size = 2*args.depth)

    @qml.qnode(device)
    def circuit(gammas_ts):
        for wire in wires:
            qml.Hadamard(wires=wire)
        for gamma, t in zip(*qml.numpy.split(gammas_ts, 2)):
            phase_shift(gamma, wires, qualities_H)
            hypercube_mixer(t, wires)
        return qml.expval(qualities_H)

    if args.plot:
        drawer = qml.draw(circuit)
        print(drawer(gammas_ts))
        sys.exit(0)

    start = time()
    for _ in range(args.repeats):
        expval = circuit(gammas_ts)
    end = time()

    if not args.circuit is None:
        with open(args.circuit, 'w') as f:
            f.write(circuit.qtape.to_openqasm())

    print(f"{expval},{args.qubits},{args.depth},{args.repeats},{args.backend},{args.graph},{end - start}")


from django.shortcuts import render
from trino.dbapi import connect
from trino.auth import BasicAuthentication
import pandas as pd
from core.models import Item
import numpy as np
# Create your views here.

conn = connect(host="tcp.cheerful-maggot.dataos.app",
               port="7432",
               auth=BasicAuthentication(
                   'balaji', "dG9rZW5fc2NhcmNlbHlfc2VyaW91c2x5X2ZyZXNoX2tpZC43YmJmMDIwZS0xMmJhLTRkNjEtYmFmZS0zNGQzNTcxZDZkOGQ="),
               http_scheme="https",
               http_headers={"cluster-name": "minervac"}  # eg:minervaa
               )

def create_prods(request):

    skus_df = pd.read_csv('./dbmigrate/skus/skus.csv')
    qr = "SELECT * FROM redshift.retail_accelerator.product WHERE sku_id IN ({0})".format(','.join(["'"+s+"'" for s in skus_df['sku_id']]))

    cat_qr = 'SELECT * FROM redshift.retail_accelerator.product_category'

    cat_df = pd.read_sql(cat_qr, conn)

    df = pd.read_sql(qr, conn)

    rename_dict = {'sku_id': 'id',
                   'product_name': 'title',
                   'list_price': 'price',
                   'sale_price': 'discount_price',
                   'product_category_id': 'category',
                   'product_subcategory_id': 'subcat_id',
                   'product_subcategory': 'subcat',
                   'product_description': 'description'
                   }

    df_out = df.rename(columns=rename_dict)
    df_out['slug'] = df_out['id'].copy()
    #df_out['discount_price'] = df_out['price'].apply(lambda x: float("{:.2f}".format(x*np.random.uniform(low = 0.6, high = 0.95))))

    df_out = df_out[list(rename_dict.values())+['slug']]

    df_out = df_out.merge(cat_df[['product_category', 'product_category_id']], left_on='category',
                          right_on='product_category_id', how='left')

    df_out.rename(columns={'product_category': 'image'}, inplace=True)
    df_out.drop(['product_category_id'], axis=1, inplace=True)

    df_out['image'] = df_out['image'].str.replace('mens', 'men')
    df_out['image'] = df_out['image'].str.replace('Mens', 'Men')

    df_out['image'] = df_out['image'].apply(lambda x: x+'.jpeg')
    df_out['label'] = ['P']*len(df_out)

    out_records = df_out.to_dict(orient='records')
    for r in out_records:
        Item.objects.create(id=r['id'], title=r['title'], price=r['price'],
                            discount_price=r['discount_price'], category=r['category'], slug=r['slug'], subcat_id = r['subcat_id'], subcat = r['subcat'], description=r['description'], image=r['image'], label=r['label'])

    return render(request, 'db_check.html')


double_list = []
my_list = [1, 2, 3]
# using normal operation
print("Using normal operataion")
for item in my_list:
    double_list.append(item * 2)
print(double_list)

# using list comprehensive
print("List comprenensive")
double_list = [item * 3 for item in my_list]
print(double_list)

# accessing elements of list using list comprehension
users = [{'name': 'Tilak', 'age': 23}, {'name': 'Hari', 'age': 21}]
user_name = [user['name'] for user in users]
print(user_name)

# flterdata user

filter_user_name = [user['name']
                    for user in users if user['age'] > 22 and user['name'] == 'Tilak']
print(filter_user_name)

# nested loop in list comprehension
user_groups = [
    [
        {'name': 'Harke', 'age': 35},
        {'name': 'Haribahadur', 'age': 25}
    ],
    [
        {'name': 'chameli', 'age': 33},
        {'name': 'mina', 'age': 21}
    ]
]
user_name = [person['name']
             for group in user_groups for person in group if person['age'] < 30]
print(user_name)


# Fatorial 1 forma 'while'
from math import factorial
n = int(input('Digite um número para\ncalcular sua fatorial: '))
f = factorial(n)
print('O fatorial de {} é {}'.format(n, f))

# Fatorial 2 forma 'while'
n = int(input('Digite um número para\ncalcular sua fatorial: '))
c = n
f = 1
print('Calculando {}! = '.format(n), end='')
while c > 0:
    print('{}'.format(c), end='')
    print(' x '  if c > 1 else ' = ', end='')
    f *= c
    c -= 1
print('{}'.format(f))

# Fatorial 3 forma 'for'
from math import factorial
n = int(input('Digite um número para\ncalcular sua factorial: '))
f = factorial(n)
print('Calculando {}! = '.format(n), end='')
for c in range(n, 0):
    print('{}'.format(c), end='')
print('{}'.format(f))

Python-Exercícios&Aulas/Ex060 - Cálculo do Fatorial.py


# -*- encoding: utf-8 -*-
import numpy as np

def resize_img(a,scale):
    new_a = np.zeros((np.array(a.shape)*scale))
    for i in xrange(scale):
        for j in xrange(scale):
            new_a[i::scale,j::scale]=a
    return new_a


from rest_framework import viewsets, decorators, status
from rest_framework.response import Response
from django.db import transaction

from geoplaces.models import Place
from geoplaces.serializers import PlaceSerializer, PlaceIncreaseRatingSerializer
from geoplaces.filters import GeoPlacesFilter

class PlaceViewSet(viewsets.ReadOnlyModelViewSet):
    """
    API endpoint that allows places to be viewed or searched.

    Include additional query parameters to perform filter on the objects:

     - text: str
     - location: geojson
     - distance: float, in meters
     - rating: int, in range 1..5
     - tags_titles: list of str
     - types_titles: list of str
     - priceranges_titles: list of str
    """

    queryset = (
        Place.objects.all()
        .prefetch_related("tags", "types", "priceranges")
        .order_by("-updated_at")
    )
    serializer_class = PlaceSerializer
    filter_backends = [GeoPlacesFilter]

    @decorators.action(
        detail=True,
        methods=["POST"],
        url_name="submit-rating",
        serializer_class=PlaceIncreaseRatingSerializer,
    )
    def submit_rating(self, request, pk=None):
        serializer = PlaceIncreaseRatingSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        place = self.get_object()

        # update the place rating with moving average over last ratings
        with transaction.atomic():
            serializer.save(place=place)
            place.update_rating().save()

        return Response(serializer.data, status=status.HTTP_201_CREATED)


"""
Distributor, Layout, Transform, and Transpose class definitions.
"""

import logging
from mpi4py import MPI
import numpy as np
import itertools
from collections import OrderedDict

from ..tools.cache import CachedMethod, CachedAttribute
from ..tools.config import config
from ..tools.array import prod
from ..tools.general import OrderedSet

logger = logging.getLogger(__name__.split('.')[-1])
GROUP_TRANSFORMS = config['transforms'].getboolean('GROUP_TRANSFORMS')
TRANSPOSE_LIBRARY = config['parallelism'].get('TRANSPOSE_LIBRARY')
GROUP_TRANSPOSES = config['parallelism'].getboolean('GROUP_TRANSPOSES')
SYNC_TRANSPOSES = config['parallelism'].getboolean('SYNC_TRANSPOSES')

if TRANSPOSE_LIBRARY.upper() == 'FFTW':
    from .transposes import FFTWTranspose as TransposePlanner
elif TRANSPOSE_LIBRARY.upper() == 'MPI':
    from .transposes import AlltoallvTranspose as TransposePlanner
from .transposes import RowDistributor, ColDistributor

# Public interface
__all__ = ['Distributor']

class Distributor:
    """
    Directs parallelized distribution and transformation of fields.

    Parameters
    ----------
    dim : int
        Dimension
    comm : MPI communicator, optional
        MPI communicator (default: comm world)
    mesh : tuple of ints, optional
        Process mesh for parallelization (default: 1-D mesh of available processes)

    Attributes
    ----------
    comm_cart : MPI communicator
        Cartesian MPI communicator over mesh
    coords : array of ints
        Coordinates in cartesian communicator
    layouts : list of layout objects
        Available layouts

    Notes
    -----
    Computations are parallelized by splitting D-dimensional data fields over
    an R-dimensional mesh of MPI processes, where R < D.  In coefficient space,
    we take the first R dimensions of the data to be distributed over the mesh,
    leaving the last (D-R) dimensions local.  To transform such a data cube to
    grid space, we loop backwards over the D dimensions, performing each
    transform if the corresponding dimension is local, and performing an MPI
    transpose with the next dimension otherwise.  This effectively bubbles the
    first local dimension up from the (D-R)-th to the first dimension,
    transforming to grid space along the way.  In grid space, then, the first
    dimensional is local, followed by R dimensions distributed over the mesh,
    and the last (D-R-1) dimensions local.

    The distributor object for a given dimension constructs layout objects
    describing each of the (D+R+1) layouts (sets of transform/distribution
    states) and the paths between them (D transforms and R transposes).
    """

    def __init__(self, coordsystems, comm=None, mesh=None, dtype=None):
        # Accept single coordsystem in place of tuple/list
        if not isinstance(coordsystems, (tuple, list)):
            coordsystems = (coordsystems,)
        # Note if only a single coordsystem for simplicity
        if len(coordsystems) == 1:
            self.single_coordsys = coordsystems[0]
        else:
            self.single_coordsys = False
        # Get coords
        self.coords = tuple([coord for coordsystem in coordsystems for coord in coordsystem.coords])
        for coordsystem in coordsystems:
            coordsystem.set_distributor(self)
        self.coordsystems = coordsystems
        # Defaults
        if comm is None:
            comm = MPI.COMM_WORLD
        if mesh is None:
            mesh = np.array([comm.size], dtype=int)
        else:
            if isinstance(mesh, list) or isinstance(mesh, tuple):
                mesh = np.array(mesh, dtype=int)
        # Trim trailing ones
        mesh = 1 + np.trim_zeros(mesh - 1, trim='b')
        self.dim = dim = len(self.coords)
#        self.dim = dim = sum(coordsystem.dim for coordsystem in coordsystems)
        self.comm = comm
        self.mesh = mesh = np.array(mesh)
        # Check mesh compatibility
        logger.debug('Mesh: %s' %str(mesh))
        if mesh.size >= dim:
            raise ValueError("Mesh (%s) must have lower dimension than distributor (%i)" %(mesh, dim))
        if np.prod(mesh) != comm.size:
            raise ValueError("Wrong number of processes (%i) for specified mesh (%s)" %(comm.size, mesh))
        self.dtype = dtype
        # Create cartesian communicator, ignoring axes with m=1
        reduced_mesh = [m for m in mesh if m > 1]
        self.comm_cart = comm.Create_cart(reduced_mesh)
        self.comm_coords = np.array(self.comm_cart.coords, dtype=int)
        # Build layout objects
        self._build_layouts()

    @CachedAttribute
    def cs_by_axis(self):
        cs_dict = {}
        for cs in self.coordsystems:
            for subaxis in range(cs.dim):
                cs_dict[cs.axis+subaxis] = cs
        return cs_dict

    def get_coordsystem(self, axis):
        return self.cs_by_axis[axis]

    def _build_layouts(self, dry_run=False):
        """Construct layout objects."""
        D = self.dim
        R = np.sum(self.mesh > 1)
        # First layout: full coefficient space
        local = np.array([True] * D)
        local[:self.mesh.size][self.mesh > 1] = False
        grid_space = [False] * D
        layout_0 = Layout(self, local, grid_space)
        layout_0.index = 0
        # Layout and path lists
        self.layouts = [layout_0]
        self.paths = []
        self.transforms = []
        # Subsequent layouts
        for i in range(1, R+D+1):
            # Iterate backwards over bases to last coefficient space basis
            for d in reversed(range(D)):
                if not grid_space[d]:
                    # Transform if local
                    if local[d]:
                        grid_space[d] = True
                        layout_i = Layout(self, local, grid_space)
                        if not dry_run:
                            path_i = Transform(self.layouts[-1], layout_i, d)
                            self.transforms.insert(0, path_i)
                        break
                    # Otherwise transpose
                    else:
                        local[d] = True
                        local[d+1] = False
                        layout_i = Layout(self, local, grid_space)
                        if not dry_run:
                            path_i = Transpose(self.layouts[-1], layout_i, d, self.comm_cart)
                        break
            layout_i.index = i
            self.layouts.append(layout_i)
            if not dry_run:
                self.paths.append(path_i)
        # Directly reference coefficient and grid space layouts
        self.coeff_layout = self.layouts[0]
        self.grid_layout = self.layouts[-1]
        # Allow string references to coefficient and grid space layouts
        self.layout_references = {'c': self.coeff_layout,
                                  'g': self.grid_layout}

    def get_layout_object(self, input):
        """Dereference layout identifiers."""
        if isinstance(input, Layout):
            return input
        else:
            return self.layout_references[input]

    def buffer_size(self, domain, scales, dtype):
        """Compute necessary buffer size (bytes) for all layouts."""
        return max(layout.buffer_size(domain, scales, dtype) for layout in self.layouts)

    def remedy_scales(self, scales):
        """Remedy different scale inputs."""
        if scales is None:
            scales = 1
        if not hasattr(scales, "__len__"):
            scales = [scales] * self.dim
        if 0 in scales:
            raise ValueError("Scales must be nonzero.")
        return tuple(scales)

    def get_transform_object(self, axis):
        return self.transforms[axis]

    def get_axis(self, coord):
        return self.coords.index(coord)

    def Field(self, *args, **kw):
        """Alternate constructor for fields."""
        from .field import Field
        return Field(self, *args, **kw)

    def ScalarField(self, *args, **kw):
        """Alternate constructor for scalar fields."""
        from .field import ScalarField
        return ScalarField(self, *args, **kw)

    def VectorField(self, *args, **kw):
        """Alternate constructor for vector fields."""
        from .field import VectorField
        return VectorField(self, *args, **kw)

    def TensorField(self, *args, **kw):
        """Alternate constructor for tensor fields."""
        from .field import TensorField
        return TensorField(self, *args, **kw)

    def IdentityTensor(self, coordsys):
        """Identity tensor field."""
        from .field import TensorField
        I = TensorField(self, (coordsys, coordsys))
        for i in range(coordsys.dim):
            I['g'][i, i] = 1
        return I

    def local_grid(self, basis, scale=None):
        # TODO: remove from bases and do it all here?
        if basis.dim == 1:
            return basis.local_grid(scale=scale)
        else:
            raise ValueError("Use `local_grids` for multidimensional bases.")

    def local_grids(self, *bases, scales=None):
        # TODO: remove from bases and do it all here?
        return sum((basis.local_grids(scales=scales) for basis in bases), ())

    def local_modes(self, basis):
        # TODO: remove from bases and do it all here?
        return basis.local_modes()

    @CachedAttribute
    def default_nonconst_groups(self):
        return sum((cs.default_nonconst_groups for cs in self.coordsystems), ())

class Layout:
    """
    Object describing the data distribution for a given transform and
    distribution state.

    Attributes
    ----------
    local : array of bools
        Axis locality flags (True/False for local/distributed)
    grid_space : array of bools
        Axis grid-space flags (True/False for grid/coeff space)

    """

    def __init__(self, dist, local, grid_space):
        self.dist = dist
        # Freeze local and grid_space lists into boolean arrays
        self.local = np.array(local)
        self.grid_space = np.array(grid_space)
        # Extend mesh and coordinates to distributor dimension
        self.ext_mesh = np.ones(dist.dim, dtype=int)
        reduced_mesh = [m for m in dist.mesh if m > 1]
        self.ext_mesh[~self.local] = reduced_mesh
        self.ext_coords = np.zeros(dist.dim, dtype=int)
        self.ext_coords[~self.local] = dist.comm_coords

    def global_shape(self, domain, scales):
        """Global data shape."""
        scales = self.dist.remedy_scales(scales)
        #global_shape = np.array(domain.coeff_shape).copy()
        #global_shape[self.grid_space] = np.array(domain.grid_shape(scales))[self.grid_space]
        global_shape = domain.global_shape(self, scales)
        return tuple(global_shape)

    def chunk_shape(self, domain):
        """Chunk shape."""
        #scales = self.dist.remedy_scales(scales)
        #chunk_shape = np.array(domain.coeff_group_shape).copy()
        #chunk_shape[self.grid_space] = 1
        chunk_shape = domain.chunk_shape(self)
        return tuple(chunk_shape)

    def group_shape(self, domain):
        """Chunk shape."""
        return tuple(domain.group_shape(self))

    def local_chunks(self, domain, scales, rank=None, broadcast=False):
        """Local chunk indices by axis."""
        global_shape = self.global_shape(domain, scales)
        chunk_shape = self.chunk_shape(domain)
        chunk_nums = -(-np.array(global_shape) // np.array(chunk_shape))  # ceil
        local_chunks = []
        # Get coordinates
        if rank is None:
            ext_coords = self.ext_coords
        else:
            ext_coords = np.zeros(self.dist.dim, dtype=int)
            ext_coords[~self.local] = self.dist.comm_cart.Get_coords(rank)
        # Get chunks axis by axis
        for axis, basis in enumerate(domain.full_bases):
            if self.local[axis]:
                # All chunks for local dimensions
                local_chunks.append(np.arange(chunk_nums[axis]))
            else:
                # Block distribution otherwise
                mesh = self.ext_mesh[axis]
                if broadcast and (basis is None):
                    coord = 0
                else:
                    coord = ext_coords[axis]
                block = -(-chunk_nums[axis] // mesh)
                start = min(chunk_nums[axis], block*coord)
                end = min(chunk_nums[axis], block*(coord+1))
                local_chunks.append(np.arange(start, end))
        return tuple(local_chunks)

    def global_elements(self, domain, scales):
        """Global element indices by axis."""
        global_shape = self.global_shape(domain, scales)
        indices = [np.arange(n) for n in global_shape]
        return tuple(indices)

    def local_elements(self, domain, scales, rank=None, broadcast=False):
        """Local element indices by axis."""
        chunk_shape = self.chunk_shape(domain)
        local_chunks = self.local_chunks(domain, scales, rank=rank, broadcast=broadcast)
        indices = []
        for chunk_size, chunks in zip(chunk_shape, local_chunks):
            ax_indices = chunk_size*np.repeat(chunks, chunk_size) + np.tile(np.arange(chunk_size), len(chunks))
            indices.append(ax_indices)
        return tuple(indices)

    @CachedMethod
    def valid_elements(self, tensorsig, domain, scales, rank=None, broadcast=False):
        """Make dense array of mode inclusion."""
        # Make dense array of local elements
        elements = self.local_elements(domain, scales, rank=rank, broadcast=broadcast)
        elements = np.array(np.meshgrid(*elements, indexing='ij'))
        # Check validity basis-by-basis
        grid_space = self.grid_space
        vshape = tuple(cs.dim for cs in tensorsig) + elements[0].shape
        valid = np.ones(shape=vshape, dtype=bool)
        for basis in domain.bases:
            basis_axes = slice(basis.first_axis, basis.last_axis+1)
            valid &= basis.valid_elements(tensorsig, grid_space[basis_axes], elements[basis_axes])
        return valid

    def _group_arrays(self, elements, domain):
        # Convert to groups basis-by-basis
        grid_space = self.grid_space
        groups = np.zeros_like(elements)
        groups = np.ma.masked_array(groups)
        for basis in domain.bases:
            basis_axes = slice(basis.first_axis, basis.last_axis+1)
            groups[basis_axes] = basis.elements_to_groups(grid_space[basis_axes], elements[basis_axes])
        return groups

    @CachedMethod
    def local_group_arrays(self, domain, scales, rank=None, broadcast=False):
        """Dense array of local groups (first axis)."""
        # Make dense array of local elements
        elements = self.local_elements(domain, scales, rank=rank, broadcast=broadcast)
        elements = np.array(np.meshgrid(*elements, indexing='ij'))
        return self._group_arrays(elements, domain)

    @CachedMethod
    def global_group_arrays(self, domain, scales):
        """Dense array of local groups (first axis)."""
        # Make dense array of local elements
        elements = self.global_elements(domain, scales)
        elements = np.array(np.meshgrid(*elements, indexing='ij'))
        return self._group_arrays(elements, domain)

    @CachedMethod
    def local_groupsets(self, group_coupling, domain, scales, rank=None, broadcast=False):
        local_groupsets = self.local_group_arrays(domain, scales, rank=rank, broadcast=broadcast).astype(object)
        # Replace non-enumerated axes with None
        for axis in range(local_groupsets.shape[0]):
            if group_coupling[axis]:
                local_groupsets[axis] = None
        # Flatten local groupsets
        local_groupsets = local_groupsets.reshape((local_groupsets.shape[0], -1))
        # Drop masked groups
        local_groupsets = np.ma.compress_cols(local_groupsets)
        # Return unique groupsets
        local_groupsets = tuple(map(tuple, local_groupsets.T))
        return OrderedSet(local_groupsets)

    @CachedMethod
    def local_groupset_slices(self, groupset, domain, scales, rank=None, broadcast=False):
        groups = self.local_group_arrays(domain, scales, rank=rank, broadcast=broadcast)
        dim = groups.shape[0]
        group_shape = self.group_shape(domain)
        # find all elements which match group
        selections = np.ones(groups[0].shape, dtype=int)
        for i, subgroup in enumerate(groupset):
            if subgroup is not None:
                selections *= (subgroup == groups[i])
                # Note: seems to exclude masked elements for ==, unlike other comparisons
        # determine which axes to loop over, which to find bounds for
        slices = []
        for i, subgroup in enumerate(groupset):
            if subgroup is None:
                subslices = [slice(None)]
            else:
                # loop over axis i but taking into account group_shape
                subslices = [slice(j, j+group_shape[i]) for j in range(0, groups.shape[i+1], group_shape[i])]
            slices.append(subslices)
        group_slices = []
        for s in itertools.product(*slices):
            sliced_selections = selections[tuple(s)]
            if np.any(sliced_selections): # some elements match group
                # assume selected groups are cartesian product, find left and right bounds
                lefts = list(map(np.min, np.where(sliced_selections)))
                rights = list(map(np.max, np.where(sliced_selections)))
                # build multidimensional group slice
                group_slice = []
                for i in range(dim):
                    if s[i] != slice(None):
                        group_slice.append(s[i])
                    else:
                        group_slice.append(slice(lefts[i], rights[i]+1))
                group_slices.append(tuple(group_slice))
        return group_slices

    def slices(self, domain, scales):
        """Local element slices by axis."""
        local_elements = self.local_elements(domain, scales)
        slices = []
        for LE in local_elements:
            if LE.size:
                slices.append(slice(LE.min(), LE.max()+1))
            else:
                slices.append(slice(0, 0))
        return tuple(slices)

    @CachedMethod
    def local_shape(self, domain, scales, rank = None):
        """Local data shape."""
        local_elements = self.local_elements(domain, scales, rank = rank)
        shape = tuple(LE.size for LE in local_elements)
        return shape

    def buffer_size(self, bases, scales, dtype):
        """Local buffer size (bytes)."""
        local_shape = self.local_shape(bases, scales)
        return prod(local_shape) * np.dtype(dtype).itemsize

    # def local_group_index(self, group, domain, scales):
    #     """Index of a group within local groups."""
    #     index = []
    #     for grp, local_grps in zip(group, self.local_groups(domain, scales)):
    #         if grp is None:
    #             index.append(None)
    #         else:
    #             index.append(local_grps.index(grp))
    #     return index

        # if distribution == 'block':
        #     index[~local] = (group - start)[~local]
        # elif distribution == 'cyclic':
        #     index[~local] = np.mod(group, mesh)[~local]

    # def group(self, local_index):
    #     pass
    #     # if distribution == 'block':
    #     #     group = start + index
    #     # elif distribution == 'cyclic':
    #     #     group = mesh *

    # @CachedMethod
    # def groups(self, domain, scales):
    #     """Comptue group sizes."""
    #     groups = []
    #     for axis, space in enumerate(domain.spaces):
    #         if space is None:
    #             groups.append(1)
    #         elif self.grid_space[axis]:
    #             groups.append(1)
    #         else:
    #             groups.append(space.group_size)
    #     return np.array(groups, dtype=int)

    # @CachedMethod
    # def blocks(self, domain, scales):
    #     """Compute block sizes for data distribution."""
    #     global_shape = self.global_shape(domain, scales)
    #     groups = self.groups(domain, scales)
    #     return groups * np.ceil(global_shape / groups / self.ext_mesh).astype(int)

    # @CachedMethod
    # def start(self, domain, scales):
    #     """Compute starting coordinates for local data."""
    #     blocks = self.blocks(domain, scales)
    #     start = self.ext_coords * blocks
    #     start[domain.constant] = 0
    #     return start

    # @CachedMethod
    # def local_shape(self, domain, scales):
    #     """Compute local data shape."""
    #     global_shape = self.global_shape(domain, scales)
    #     blocks = self.blocks(domain, scales)
    #     start = self.start(domain, scales)
    #     local_shape = np.minimum(blocks, global_shape-start)
    #     local_shape = np.maximum(0, local_shape)
    #     return local_shape

    # @CachedMethod
    # def slices(self, domain, scales):
    #     """Compute slices for selecting local portion of global data."""
    #     start = self.start(domain, scales)
    #     local_shape = self.local_shape(domain, scales)
    #     return tuple(slice(s, s+l) for (s, l) in zip(start, local_shape))

class Transform:
    """
    Directs spectral transforms between two layouts.

    TODO:
        - Implement grouped transforms
    """

    def __init__(self, layout0, layout1, axis):
        self.layout0 = layout0
        self.layout1 = layout1
        self.axis = axis

    def increment(self, fields):
        """Backward transform a list of fields."""
        if len(fields) == 1:
            self.increment_single(*fields)
        elif GROUP_TRANSFORMS:
            self.increment_group(fields)
        else:
            for field in fields:
                self.increment_single(field)

    def decrement(self, fields):
        """Forward transform a list of fields."""
        if len(fields) == 1:
            self.decrement_single(*fields)
        elif GROUP_TRANSFORMS:
            self.decrement_group(fields)
        else:
            for field in fields:
                self.decrement_single(field)

    def increment_single(self, field):
        """Backward transform a field."""
        axis = self.axis
        basis = field.domain.full_bases[axis]
        # Reference views from both layouts
        cdata = field.data
        field.preset_layout(self.layout1)
        gdata = field.data
        # Transform non-constant bases with local data
        if (basis is not None) and prod(cdata.shape):
            basis.backward_transform(field, axis, cdata, gdata)
            #basis.backward_transform(cdata, gdata, axis, field.scales[axis], field.tensorsig)
            #plan = basis.transform_plan(cdata.shape, self.axis, field.scales[self.axis], field.dtype)
            #plan.backward(cdata, gdata)

    def decrement_single(self, field):
        """Forward transform a field."""
        axis = self.axis
        basis = field.domain.full_bases[axis]
        # Reference views from both layouts
        gdata = field.data
        field.preset_layout(self.layout0)
        cdata = field.data
        # Transform non-constant bases with local data
        if (basis is not None) and prod(gdata.shape):
            basis.forward_transform(field, axis, gdata, cdata)
            #basis.forward_transform(gdata, cdata, axis, field.scales[axis], field.tensorsig)
            #plan = basis.transform_plan(cdata.shape, self.axis, field.scales[self.axis], field.dtype)
            #plan.forward(gdata, cdata)

    def increment_group(self, fields):
        """Backward transform multiple fields simultaneously."""
        #logger.warning("Group transforms not implemented.")
        for field in fields:
            self.increment_single(field)

    def decrement_group(self, fields):
        """Forward transform multiple fields simultaneously."""
        #logger.warning("Group transforms not implemented.")
        for field in fields:
            self.decrement_single(field)

    # @CachedMethod
    # def group_data(self, nfields, scales):
    #     local_shape0 = self.layout0.local_shape(scales)
    #     local_shape1 = self.layout1.local_shape(scales)
    #     group_shape0 = [nfields] + list(local_shape0)
    #     group_shape1 = [nfields] + list(local_shape1)
    #     group_cdata = fftw.create_array(group_shape0, self.layout0.dtype)
    #     group_gdata = fftw.create_array(group_shape1, self.layout1.dtype)
    #     return group_cdata, group_gdata

    # def increment_group(self, fields):
    #     fields = list(fields)
    #     scales = fields[0].meta[:]['scale']
    #     cdata, gdata = self.group_data(len(fields), scales)
    #     for i, field in enumerate(fields):
    #         np.copyto(cdata[i], field.data)
    #     self.basis.backward(cdata, gdata, self.axis+1, fields[0].meta[self.axis])
    #     for i, field in enumerate(fields):
    #         field.layout = self.layout1
    #         np.copyto(field.data, gdata[i])

    # def decrement_group(self, fields):
    #     fields = list(fields)
    #     scales = fields[0].meta[:]['scale']
    #     cdata, gdata = self.group_data(len(fields), scales)
    #     for i, field in enumerate(fields):
    #         np.copyto(gdata[i], field.data)
    #     self.basis.forward(gdata, cdata, self.axis+1, fields[0].meta[self.axis])
    #     for i, field in enumerate(fields):
    #         field.layout = self.layout0
    #         np.copyto(field.data, cdata[i])

class Transpose:
    """
    Directs distributed transposes between two layouts.

    TODO:
        - Implement grouped transposes
        - Transpose all components simultaneously
    """

    def __init__(self, layout0, layout1, axis, comm_cart):
        self.layout0 = layout0
        self.layout1 = layout1
        self.axis = axis
        self.comm_cart = comm_cart
        # Create subgrid communicator along the moving mesh axis
        remain_dims = [0] * comm_cart.dim
        # No comm cart across axes where mesh = 1
        mesh = layout0.dist.mesh
        comm_cart_axis = axis - np.sum(mesh[:axis]==1)
        remain_dims[comm_cart_axis] = 1
        self.comm_sub = comm_cart.Sub(remain_dims)

    @CachedMethod
    def _sub_shape(self, domain, scales):
        """Build global shape of data assigned to sub-communicator."""
        local_shape = self.layout0.local_shape(domain, scales)
        global_shape = self.layout0.global_shape(domain, scales)
        # Global shape along transposing axes, local shape along others
        sub_shape = np.array(local_shape)
        sub_shape[self.axis] = global_shape[self.axis]
        sub_shape[self.axis+1] = global_shape[self.axis+1]
        return tuple(sub_shape)

    @CachedMethod
    def _plan(self, ncomp, sub_shape, chunk_shape, dtype):
        axis = self.axis
        if prod(sub_shape) == 0:
            return None  # no data
        elif (sub_shape[axis] == chunk_shape[axis]) and (sub_shape[axis+1] == chunk_shape[axis+1]):
            return None  # no change
        else:
            # Add axis for components
            full_sub_shape = (ncomp,) + sub_shape
            full_chunk_shape = (ncomp,) + chunk_shape
            return TransposePlanner(full_sub_shape, full_chunk_shape, dtype, axis+1, self.comm_sub)

    def _single_plan(self, field):
        """Build single transpose plan."""
        ncomp = int(prod([cs.dim for cs in field.tensorsig]))
        sub_shape = self._sub_shape(field.domain, field.scales)
        chunk_shape = field.domain.chunk_shape(self.layout0)
        return self._plan(ncomp, sub_shape, chunk_shape, field.dtype)

    def _group_plans(self, fields):
        """Build group transpose plan."""
        # Segment fields by sub_shapes and chunk_shapes
        field_groups = OrderedDict()
        for field in fields:
            sub_shape = self._sub_shape(field.domain, field.scales)
            chunk_shape = field.domain.chunk_shape(self.layout0)
            if (sub_shape, chunk_shape) in field_groups:
                field_groups[(sub_shape, chunk_shape)].append(field)
            else:
                field_groups[(sub_shape, chunk_shape)] = [field]
        # Plan for each field group
        plans = []
        for (sub_shape, chunk_shape), fields in field_groups.items():
            ncomp = 0
            for field in fields:
                ncomp += int(prod([cs.dim for cs in field.tensorsig]))
            plan = self._plan(ncomp, sub_shape, chunk_shape, field.dtype) # Assumes last field's dtype is good for everybody
            plans.append((fields, plan))
        return plans

    def increment(self, fields):
        """Backward transpose a list of fields."""
        if SYNC_TRANSPOSES:
            self.comm_sub.Barrier()
        if len(fields) == 1:
            self.increment_single(*fields)
        elif GROUP_TRANSPOSES:
            self.increment_group(fields)
        else:
            for field in fields:
                self.increment_single(field)

    def decrement(self, fields):
        """Forward transpose a list of fields."""
        if SYNC_TRANSPOSES:
            self.comm_sub.Barrier()
        if len(fields) == 1:
            self.decrement_single(*fields)
        elif GROUP_TRANSPOSES:
            self.decrement_group(fields)
        else:
            for field in fields:
                self.decrement_single(field)

    def increment_single(self, field):
        """Backward transpose a field."""
        plan = self._single_plan(field)
        if plan:
            # Reference views from both layouts
            data0 = field.data
            field.preset_layout(self.layout1)
            data1 = field.data
            # Transpose between data views
            plan.localize_columns(data0, data1)
        else:
            # No communication: just update field layout
            field.preset_layout(self.layout1)

    def decrement_single(self, field):
        """Forward transpose a field."""
        plan = self._single_plan(field)
        if plan:
            # Reference views from both layouts
            data1 = field.data
            field.preset_layout(self.layout0)
            data0 = field.data
            # Transpose between data views
            plan.localize_rows(data1, data0)
        else:
            # No communication: just update field layout
            field.preset_layout(self.layout0)

    def increment_group(self, fields):
        """Backward transpose multiple fields simultaneously."""
        plans = self._group_plans(fields)
        for fields, plan in plans:
            if plan:
                if len(fields) == 1:
                    field = fields[0]
                    # Reference views from both layouts
                    data0 = field.data
                    field.preset_layout(self.layout1)
                    data1 = field.data
                    # Transpose between data views
                    plan.localize_columns(data0, data1)
                else:
                    # Gather data across fields
                    data0 = []
                    data1 = []
                    for field in fields:
                        rank = len(field.tensorsig)
                        # Reference views from both layouts
                        flat_comp_shape = (-1,) + field.data.shape[rank:]
                        if field.data.size:
                            data0.append(field.data.reshape(flat_comp_shape))
                        field.preset_layout(self.layout1)
                        flat_comp_shape = (-1,) + field.data.shape[rank:]
                        if field.data.size:
                            data1.append(field.data.reshape(flat_comp_shape))
                    if data0:
                        data0 = np.concatenate(data0)
                    else:
                        data0 = np.zeros(0, dtype=fields[0].dtype) # Assumes same dtypes
                    if data1:
                        data1 = np.concatenate(data1)
                    else:
                        data1 = np.zeros(0, dtype=fields[0].dtype) # Assumes same dtypes
                    # Transpose between data views
                    plan.localize_columns(data0, data1)
                    # Split up transposed data
                    i = 0
                    for field in fields:
                        ncomp = int(prod([cs.dim for cs in field.tensorsig]))
                        data = data1[i:i+ncomp]
                        field.data[:] = data.reshape(field.data.shape)
                        i += ncomp
            else:
                # No communication: just update field layouts
                for field in fields:
                    field.preset_layout(self.layout1)

    def decrement_group(self, fields):
        """Forward transpose multiple fields simultaneously."""
        plans = self._group_plans(fields)
        for fields, plan in plans:
            if plan:
                if len(fields) == 1:
                    field = fields[0]
                    # Reference views from both layouts
                    data1 = field.data
                    field.preset_layout(self.layout0)
                    data0 = field.data
                    # Transpose between data views
                    plan.localize_rows(data1, data0)
                else:
                    # Gather data across fields
                    data0 = []
                    data1 = []
                    for field in fields:
                        rank = len(field.tensorsig)
                        # Reference views from both layouts
                        flat_comp_shape = (-1,) + field.data.shape[rank:]
                        if field.data.size:
                            data1.append(field.data.reshape(flat_comp_shape))
                        field.preset_layout(self.layout0)
                        flat_comp_shape = (-1,) + field.data.shape[rank:]
                        if field.data.size:
                            data0.append(field.data.reshape(flat_comp_shape))
                    if data0:
                        data0 = np.concatenate(data0)
                    else:
                        data0 = np.zeros(0, dtype=fields[0].dtype) # Assumes same dtypes
                    if data1:
                        data1 = np.concatenate(data1)
                    else:
                        data1 = np.zeros(0, dtype=fields[0].dtype) # Assumes same dtypes
                    # Transpose between data views
                    plan.localize_rows(data1, data0)
                    # Split up transposed data
                    i = 0
                    for field in fields:
                        ncomp = int(prod([cs.dim for cs in field.tensorsig]))
                        data = data0[i:i+ncomp]
                        field.data[:] = data.reshape(field.data.shape)
                        i += ncomp
            else:
                # No communication: just update field layouts
                for field in fields:
                    field.preset_layout(self.layout1)

    # def increment_group(self, *fields):
    #     """Transpose group from layout0 to layout1."""
    #     scales = unify(field.scales for field in fields)
    #     plan, buffer0, buffer1 = self._group_plan(len(fields), scales)
    #     if plan:
    #         # Copy fields to group buffer
    #         for i, field in enumerate(fields):
    #             np.copyto(buffer0[i], field.data)
    #         # Transpose between group buffer views
    #         plan.localize_columns(buffer0, buffer1)
    #         # Copy from group buffer to fields in new layout
    #         for i, field in enumerate(fields):
    #             field.preset_layout(self.layout1)
    #             np.copyto(field.data, buffer1[i])
    #     else:
    #         # No data: just update field layouts
    #         for field in fields:
    #             field.preset_layout(self.layout1)

    # def decrement_group(self, *fields):
    #     """Transpose group from layout1 to layout0."""
    #     scales = unify(field.scales for field in fields)
    #     plan, buffer0, buffer1 = self._group_plan(len(fields), scales)
    #     if plan:
    #         # Copy fields to group buffer
    #         for i, field in enumerate(fields):
    #             np.copyto(buffer1[i], field.data)
    #         # Transpose between group buffer views
    #         plan.localize_rows(buffer1, buffer0)
    #         # Copy from group buffer to fields in new layout
    #         for i, field in enumerate(fields):
    #             field.preset_layout(self.layout0)
    #             np.copyto(field.data, buffer0[i])
    #     else:
    #         # No data: just update field layouts
    #         for field in fields:
    #             field.preset_layout(self.layout0)


from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    #?sessão de administração padrão do django
    path('admin/', admin.site.urls),
    #?rotas para os apps
    path('', include('Rest_app.urls')),
    #?rotas de autentificação do rest_framework
    path('api-auth/', include('rest_framework.urls')),
    path('dj-rest-auth/', include('dj_rest_auth.urls')),
]


#               Best        Worst
# Partioning    O(n)        O(n)
# # of times    O(log n)    O(n)    depends on the pivot
# Total         O(n log(n)) O(n^2)
# Space         O(log(n))   O(n)

def quick_sort(array, start, end):
    if start >= end: return

    boundary = partition(array, start, end)
    quick_sort(array, start, boundary - 1)
    quick_sort(array, boundary + 1, end)

def partition(array, start, end):
    pivot = array[end]
    boundary = start - 1
    for i in range(start, end + 1):
        if array[i] <= pivot:
            boundary += 1
            swap(array, i, boundary)
    return boundary

def swap(array, index1, index2):
    temp = array[index1]
    array[index1] = array[index2]
    array[index2] = temp

numbers = [15,6,3,1,22,10,13]
quick_sort(numbers, 0 , len(numbers) - 1)
print(numbers)