'''
######################
|Sweta Karlekar Pd 4 |
|Sudoku Lab          |
|10/04/14            |
######################
'''
MAX = 9
from copy import deepcopy
from collections import Counter
def main():
   board = createSudokuBoard()
   print("Original Board:")
   printMatrix(board)
   board = recursivelySolveTheSudoku(board)
   print("Solved Board:")
   printMatrix(board)
   if solutionIsCorrect(board):
      print("Board verified.")
   else:
      print("Wrong solution.")

def printMatrix(board):
   for row in range(MAX):
      for col in range(MAX):
         if col == 0:
            print("|", end = '')
         if len(board[row][col].value) == 1:
            print(board[row][col].value, end = ' ')
         else:
            print({0}, end = ' ')
         if (col+1)%3==0:
            print("|", end = "")
      if (row+1)%3==0:
         print("\n_________________________________________")
      print()

def makeAllPossibleSimpleChangesToMatrix(matrix):
   oldmatrix = deepcopy(matrix)
   changesMade = False

   matrix = solveSimpleSolutionsRow(matrix)

   for r in range(MAX):
      for c in range(MAX):
         if matrix[r][c].value != oldmatrix[r][c].value:
            changesMade = True
   if changesMade:
      matrix = makeAllPossibleSimpleChangesToMatrix(matrix)

   matrix = solveSimpleSolutionsCol(matrix)

   for r in range(MAX):
      for c in range(MAX):
         if matrix[r][c].value != oldmatrix[r][c].value:
            changesMade = True

   if changesMade:
      matrix = makeAllPossibleSimpleChangesToMatrix(matrix)

   matrix = solveSimpleSolutionsBlock(matrix)
   for r in range(MAX):
      for c in range(MAX):
         if matrix[r][c].value != oldmatrix[r][c].value:
            changesMade = True
   if changesMade:
      matrix = makeAllPossibleSimpleChangesToMatrix(matrix)

   matrix = trickTwoRows(matrix)
   for r in range(MAX):
      for c in range(MAX):
         if matrix[r][c].value != oldmatrix[r][c].value:
            changesMade = True
   if changesMade:
      matrix = makeAllPossibleSimpleChangesToMatrix(matrix)

   matrix = trickTwoCols(matrix)
   for r in range(MAX):
      for c in range(MAX):
         if matrix[r][c].value != oldmatrix[r][c].value:
            changesMade = True
   if changesMade:
      matrix = makeAllPossibleSimpleChangesToMatrix(matrix)

   matrix = trickTwoBlocks(matrix)
   for r in range(MAX):
      for c in range(MAX):
         if matrix[r][c].value != oldmatrix[r][c].value:
            changesMade = True
   if changesMade:
      matrix = makeAllPossibleSimpleChangesToMatrix(matrix)
   return matrix

def createBlocks(matrix):
   block	= [[], [], [],	[], [], [],	[], [], []]

   block[0]	= [matrix[0][0], matrix[0][1], matrix[0][2],
      		  matrix[1][0], matrix[1][1],	matrix[1][2],
      		  matrix[2][0], matrix[2][1],	matrix[2][2],]

   block[1]	= [matrix[0][3], matrix[0][4], matrix[0][5],
      		  matrix[1][3], matrix[1][4],	matrix[1][5],
      		  matrix[2][3], matrix[2][4],	matrix[2][5],]

   block[2]	= [matrix[0][6], matrix[0][7], matrix[0][8],
      		  matrix[1][6], matrix[1][7],	matrix[1][8],
      		  matrix[2][6], matrix[2][7],	matrix[2][8],]

   block[3]	= [matrix[3][0], matrix[3][1], matrix[3][2],
      		  matrix[4][0], matrix[4][1],	matrix[4][2],
      		  matrix[5][0], matrix[5][1],	matrix[5][2],]

   block[4]	= [matrix[3][3], matrix[3][4], matrix[3][5],
      		  matrix[4][3], matrix[4][4],	matrix[4][5],
      		  matrix[5][3], matrix[5][4],	matrix[5][5],]

   block[5]	= [matrix[3][6], matrix[3][7], matrix[3][8],
      		  matrix[4][6], matrix[4][7],	matrix[4][8],
      		  matrix[5][6], matrix[5][7],	matrix[5][8],]

   block[6]	= [matrix[6][0], matrix[6][1], matrix[6][2],
      		  matrix[7][0], matrix[7][1],	matrix[7][2],
      		  matrix[8][0], matrix[8][1],	matrix[8][2],]

   block[7]	= [matrix[6][3], matrix[6][4], matrix[6][5],
      		  matrix[7][3], matrix[7][4],	matrix[7][5],
      		  matrix[8][3], matrix[8][4],	matrix[8][5],]

   block[8]	= [matrix[6][6], matrix[6][7], matrix[6][8],
      		  matrix[7][6], matrix[7][7],	matrix[7][8],
      		  matrix[8][6], matrix[8][7],	matrix[8][8],]

   return block

def solveSimpleSolutionsBlock(matrix):
   block = createBlocks(matrix)
   for blockindex in range(MAX):
      st = set()
      for cell in range(MAX):
         if len(block[blockindex][cell].value) == 1:
            temp = st | block[blockindex][cell].value
            st = temp
      for cell in range(MAX):
         if len(block[blockindex][cell].value) > 1:
            block[blockindex][cell].value = block[blockindex][cell].value - st
   return matrix

def trickTwoRows(matrix):
   for row in range(MAX):
      guesses = []
      for col in range(MAX):
         if len(matrix[row][col].value) > 1:
            for values in matrix[row][col].value:
               guesses.append(values)
      for col in range(MAX):
         if len(matrix[row][col].value) > 1:
            for values in matrix[row][col].value:
               if countTimesInList(guesses, values) == 1:
                  matrix[row][col].value = {values}
   return matrix

def trickTwoCols(matrix):
   for col in range(MAX):
      guesses = []
      for row in range(MAX):
         if len(matrix[row][col].value) > 1:
            for values in matrix[row][col].value:
               guesses.append(values)
      for row in range(MAX):
         if len(matrix[row][col].value) > 1:
            for values in matrix[row][col].value:
               if countTimesInList(guesses, values) == 1:
                  matrix[row][col].value = {values}
   return matrix

def trickTwoBlocks(matrix):
   block = createBlocks(matrix)
   for blockindex in range(MAX):
      guesses = []
      for cell in range(MAX):
         if len(block[blockindex][cell].value) > 1:
            for values in block[blockindex][cell].value:
               guesses.append(values)
      for cell in range(MAX):
         if len(block[blockindex][cell].value) > 1:
            for values in block[blockindex][cell].value:
               if countTimesInList(guesses, values) == 1:
                  block[blockindex][cell].value = {values}
   return matrix

def countTimesInList(lst, values):
   count = 0
   for n in range(len(lst)):
      if lst[n] == values:
         count+=1
   return count

def solveSimpleSolutionsRow(matrix):
   for row in range(MAX):
      st = set()
      for col in range(MAX):
         if len(matrix[row][col].value) == 1:
            temp = st | matrix[row][col].value
            st = temp
      for col in range(MAX):
         if len(matrix[row][col].value) > 1:
            matrix[row][col].value = matrix[row][col].value - st
   return matrix

def solveSimpleSolutionsCol(matrix):
   for col in range(MAX):
      st = set()
      for row in range(MAX):
         if len(matrix[row][col].value) == 1:
            temp = st | matrix[row][col].value
            st = temp
      for row in range(MAX):
         if len(matrix[row][col].value) > 1:
            matrix[row][col].value = matrix[row][col].value - st
   return matrix

def createSudokuBoard():
   M = [	[8, 0, 0, 0, 0, 0, 0, 0, 0],
			[0, 0, 3, 6, 0, 0, 0, 0, 0],
			[0, 7, 0, 0, 9, 0, 2, 0, 0],
			[0, 5, 0, 0, 0, 7, 0, 0, 0],
			[0, 0, 0, 0, 4, 5, 7, 0, 0],
			[0, 0, 0, 1, 0, 0, 0, 3, 0],
			[0, 0, 1, 0, 0, 0, 0, 6, 8],
			[0, 0, 8, 5, 0, 0, 0, 1, 0],
			[0, 9, 0, 0, 0, 0, 4, 0, 0], ]
   '''
   M = [	[4, 8, 1, 5, 0, 9, 6, 7, 0],
			[3, 0, 0, 8, 1, 6, 0, 0, 2],
			[5, 0, 0, 7, 0, 3, 0, 0, 8],
			[2, 0, 0, 0, 0, 0, 0, 0, 9],
			[9, 0, 0, 0, 0, 0, 0, 0, 1],
			[8, 0, 0, 0, 0, 0, 0, 0, 4],
			[0, 3, 9, 2, 7, 5, 4, 8, 0],
			[6, 0, 0, 0, 0, 0, 9, 2, 7],
			[7, 0, 0, 0, 0, 0, 3, 1, 0], ]
   '''
   matrix =	[]
   for r	in	range(MAX):
      row =	[]
      for c	in	range(MAX):
         row.append(Cell(M[r][c], r, c, matrix))
      matrix.append(row)
   return matrix

def recursivelySolveTheSudoku(matrix):
   matrix =	makeAllPossibleSimpleChangesToMatrix(matrix)
   if	badMatrix(matrix)	or	solutionIsCorrect(matrix):
      return matrix
   oldMatrix =	deepcopy(matrix)
   r,	c = coordinatesofCellWithSmallestValueSet(matrix)
   for guess in matrix[r][c].value:
      matrix[r][c].value =	{guess,}
      matrix =	recursivelySolveTheSudoku(matrix)
      if	solutionIsCorrect(matrix):
         return matrix
      matrix =	restoreValues(matrix, oldMatrix)
   return matrix

def restoreValues(matrix, oldMatrix):
   for r	in	range(MAX):
      for c	in	range(MAX):
         matrix[r][c].value =	oldMatrix[r][c].value
   return matrix

def badMatrix(matrix):
   bool = solutionIsCorrect(matrix)
   count = 0
   for r	in	range(MAX):
      for c	in	range(MAX):
         if	matrix[r][c].value == set():
            return True
   for r in range(MAX):
      for c in range(MAX):
         if len(matrix[r][c].value) == 1 and not bool:
            count+=1
   if count == MAX*MAX:
      return True
   return False

def coordinatesofCellWithSmallestValueSet(matrix):
   min = 200
   row = 0
   col = 0
   for r in range(MAX):
      for c in range(MAX):
         if len(matrix[r][c].value) < min and len(matrix[r][c].value) >=2:
            min = len(matrix[r][c].value)
            row = r
            col = c
   return row, col

def solutionIsCorrect(matrix):
   rows = [[],	[], [], [],	[], [], [],	[], []]
   cols = [[],	[], [], [],	[], [], [],	[], []]
   for r	in	range(MAX):
      for c	in	range(MAX):
         rows[r].append(matrix[r][c].value)
         cols[c].append(matrix[r][c].value)
   block	= [[], [], [],	[], [], [],	[], [], []]

   block[0]	= [matrix[0][0].value, matrix[0][1].value, matrix[0][2].value,
      		  matrix[1][0].value, matrix[1][1].value,	matrix[1][2].value,
      		  matrix[2][0].value, matrix[2][1].value,	matrix[2][2].value,]

   block[1]	= [matrix[0][3].value, matrix[0][4].value, matrix[0][5].value,
      		  matrix[1][3].value, matrix[1][4].value,	matrix[1][5].value,
      		  matrix[2][3].value, matrix[2][4].value,	matrix[2][5].value,]

   block[2]	= [matrix[0][6].value, matrix[0][7].value, matrix[0][8].value,
      		  matrix[1][6].value, matrix[1][7].value,	matrix[1][8].value,
      		  matrix[2][6].value, matrix[2][7].value,	matrix[2][8].value,]

   block[3]	= [matrix[3][0].value, matrix[3][1].value, matrix[3][2].value,
      		  matrix[4][0].value, matrix[4][1].value,	matrix[4][2].value,
      		  matrix[5][0].value, matrix[5][1].value,	matrix[5][2].value,]

   block[4]	= [matrix[3][3].value, matrix[3][4].value, matrix[3][5].value,
      		  matrix[4][3].value, matrix[4][4].value,	matrix[4][5].value,
      		  matrix[5][3].value, matrix[5][4].value,	matrix[5][5].value,]

   block[5]	= [matrix[3][6].value, matrix[3][7].value, matrix[3][8].value,
      		  matrix[4][6].value, matrix[4][7].value,	matrix[4][8].value,
      		  matrix[5][6].value, matrix[5][7].value,	matrix[5][8].value,]

   block[6]	= [matrix[6][0].value, matrix[6][1].value, matrix[6][2].value,
      		  matrix[7][0].value, matrix[7][1].value,	matrix[7][2].value,
      		  matrix[8][0].value, matrix[8][1].value,	matrix[8][2].value,]

   block[7]	= [matrix[6][3].value, matrix[6][4].value, matrix[6][5].value,
      		  matrix[7][3].value, matrix[7][4].value,	matrix[7][5].value,
      		  matrix[8][3].value, matrix[8][4].value,	matrix[8][5].value,]

   block[8]	= [matrix[6][6].value, matrix[6][7].value, matrix[6][8].value,
      		  matrix[7][6].value, matrix[7][7].value,	matrix[7][8].value,
      		  matrix[8][6].value, matrix[8][7].value,	matrix[8][8].value,]

   for r	in	rows:
      for n	in	range(1,	MAX+1):
         if	{n} not in r:
            return False
   for c	in	cols:
      for n	in	range(1,	MAX+1):
         if	{n} not in c:
            return False
   for b	in	block:
      for n	in	range(1,	MAX+1):
         if	{n} not in b:
            return False
   return True

class	Cell(object):
   matrix =	None
   def __init__(self, val,	r,	c,	matrix):
      if	val != 0:
         self.value = {val,}
      else:
         self.value = {1,2,3,4,5,6,7,8,9}
      self.row	= r
      self.col	= c
      self.block = self.blockNumber(r,c)
      Cell.matrix	= matrix
   def blockNumber(self, row,	col):
      if			(self.row <	3)	and		(self.col <	3): return 0
      if			(self.row <	3)	and	(2	< self.col < 6): return	1
      if			(self.row <	3)	and	(5	< self.col):	return 2
      if		(2	< self.row < 6) and		(self.col <	3): return 3
      if		(2	< self.row < 6) and	(2	< self.col < 6): return	4
      if		(2	< self.row < 6) and	(5	< self.col):	return 5
      if			(self.row >	5)	and		(self.col <	3): return 6
      if			(self.row >	5)	and	(2	< self.col < 6): return	7
      if			(self.row >	5)	and	(5	< self.col):	return 8

from time import clock; START_TIME = clock(); main();
print (' | %5.2f seconds |' %(clock()-START_TIME))


'''

All the software  contained in this library  is protected by copyright.
Permission  to use, copy, modify, and  distribute this software for any
purpose without fee is hereby granted, provided that this entire notice
is included  in all copies  of any software which is or includes a copy
or modification  of this software  and in all copies  of the supporting
documentation for such software.

THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
WARRANTY. IN NO EVENT, NEITHER  THE AUTHORS, NOR THE PUBLISHER, NOR ANY
MEMBER  OF THE EDITORIAL BOARD OF  THE JOURNAL  "NUMERICAL ALGORITHMS",
NOR ITS EDITOR-IN-CHIEF, BE  LIABLE FOR ANY ERROR  IN THE SOFTWARE, ANY
MISUSE  OF IT  OR ANY DAMAGE ARISING OUT OF ITS USE. THE ENTIRE RISK OF
USING THE SOFTWARE LIES WITH THE PARTY DOING SO.

ANY USE OF THE SOFTWARE  CONSTITUTES  ACCEPTANCE  OF THE TERMS  OF THE
ABOVE STATEMENT.

AUTHORS:
Per A Brodtkorb
Python code Based on matlab code written by:

Marco Caliari
University of Verona, Italy
E-mail: marco.caliari@univr.it

Stefano de Marchi, Alvise Sommariva, Marco Vianello
University of Padua, Italy
E-mail: demarchi@math.unipd.it, alvise@math.unipd.it,
        marcov@math.unipd.it

Reference
---------
Padua2DM: fast interpolation and cubature at the Padua points in Matlab/Octave
NUMERICAL ALGORITHMS, 56 (2011), PP. 45-60

Padua module
------------
In polynomial interpolation of two variables, the Padua points are the first
known example (and up to now the only one) of a unisolvent point set
(that is, the interpolating polynomial is unique) with minimal growth of their
Lebesgue constant, proven to be O(log2 n).
This module provides all the functions needed to perform interpolation and
cubature at the Padua points, together with the functions and the demos used
in the paper.

pdint.m                 : main function for interpolation at the Padua points
pdcub.m                 : main function for cubature at the Padua points
pdpts.m                 : function for the computation of the Padua points
padua_fit.m              : function for the computation of the interpolation
                          coefficients by FFT (recommended)
pdcfsMM.m               : function for the computation of the interpolation
                          coefficients by matrix multiplications
pdval.m                 : function for the evaluation of the interpolation
                          polynomial
pdwtsFFT.m              : function for the computation of the cubature
                          weights by FFT
pdwtsMM.m               : function for the computation of the cubature
                          weights by matrix multiplications (recommended)
funct.m                 : function containing some test functions
demo_pdint.m            : demo script for pdint
demo_cputime_pdint.m    : demo script for the computation of CPU time for
                          interpolation
demo_errors_pdint.m     : demo script for the comparison of interpolation with
                          coefficients computed by FFT or by matrix
                          multiplications
demo_pdcub              : demo script for pdcub
demo_cputime_pdcub.m    : demo script for the computation of CPU time for
                          cubature
demo_errors_pdcub.m     : demo script for the comparison of cubature with
                          weights computed by FFT or by matrix multiplications
demo_errors_pdcub_gl.m  : demo script for the comparison of different cubature
                          formulas
cubature_square.m       : function for the computation of some cubature
                          formulas for the square
omelyan_solovyan_rule.m : function for the computation of Omelyan-Solovyan
                          cubature points and weights
Contents.m              : Contents file for Matlab

'''
from __future__ import division
import numpy as np
from numpy.fft import fft

class TestFunctions(object):
    '''
    Computes test function in the points (x, y)

    Parameters
    ----------
    x,y : array-like
        evaluate the function in the points (x,y)
    id : scalar int (default 0)
        id defining which test function to use. Options are
        0: franke
        1: half_sphere
        2: poly_degree20
        3: exp_fun1
        4: exp_fun100
        5: cos30
        6: constant
        7: exp_xy
        8: runge
        9: abs_cubed
        10: gauss
        11: exp_inv

    Returns
    -------
    z : array-like
        value of the function in the points (x,y)
    '''
    @staticmethod
    def franke(x, y):
        '''Franke function.

        The value of the definite integral on the square [-1,1] x [-1,1],
        obtained using a Padua Points cubature formula of degree 500, is
        2.1547794245591083e+000 with an estimated absolute error of 8.88e-016.

        The value of the definite integral on the square [0,1] x [0,1],
        obtained using a Padua Points cubature formula of degree 500, is
        4.06969589491556e-01 with an estimated absolute error of 8.88e-016.

        Maple: 0.40696958949155611906
        '''
        exp = np.exp
        return (3. / 4 * exp(-((9. * x - 2)**2 + (9. * y - 2)**2) / 4) +
                3. / 4 * exp(-(9. * x + 1)**2 / 49 - (9. * y + 1) / 10) +
                1. / 2 * exp(-((9. * x - 7)**2 + (9. * y - 3)**2) / 4) -
                1. / 5 * exp(-(9. * x - 4)**2 - (9. * y - 7)**2))

    @staticmethod
    def half_sphere(x, y):
        '''The value of the definite integral on the square [-1,1] x [-1,1],
        obtained using a Padua Points cubature formula of degree 2000, is
        3.9129044444568244e+000 with an estimated absolute error of 3.22e-010.
        '''
        return ((x - 0.5)**2 + (y - 0.5)**2)**(1. / 2)

    @staticmethod
    def poly_degree20(x, y):
        ''''Bivariate polynomial having moderate degree.
        The value of the definite integral on the square [-1,1] x
        [-1,1], up to machine precision, is 18157.16017316017 (see ref. 6).
        The value of the definite integral on the square [-1,1] x [-1,1],
        obtained using a Padua Points cubature formula of degree 500,
        is 1.8157160173160162e+004.

        2D modification of an example by L.N.Trefethen (see ref. 7), f(x)=x^20.
        '''
        return (x + y)**20

    @staticmethod
    def exp_fun1(x, y):
        ''' The value of the definite integral on the square [-1,1] x [-1,1],
        obtained using a Padua Points cubature formula of degree 2000,
        is 2.1234596326670683e+001 with an estimated absolute error of 7.11e-015.
        '''
        return np.exp((x - 0.5)**2 + (y - 0.5)**2)

    @staticmethod
    def exp_fun100(x, y):
        '''The value of the definite integral on the square [-1,1] x [-1,1],
        obtained using a Padua Points cubature formula of degree 2000,
        is 3.1415926535849605e-002 with an estimated absolute error of 3.47e-017.
        '''
        return np.exp(-100 * ((x - 0.5)**2 + (y - 0.5)**2))

    @staticmethod
    def cos30(x, y):
        ''' The value of the definite integral on the square [-1,1] x [-1,1],
        obtained using a Padua Points cubature formula of degree 500,
        is 4.3386955120336568e-003 with an estimated absolute error of 2.95e-017.
        '''
        return np.cos(30 * (x + y))

    @staticmethod
    def constant(x, y):
        '''Constant.
        To test interpolation and cubature at degree 0.
        The value of the definite integral on the square [-1,1] x [-1,1]
        is 4.
        '''
        return np.ones(np.shape(x))

    @staticmethod
    def exp_xy(x, y):
        '''The value of the definite integral on the square [-1,1] x [-1,1]
        is up to machine precision is 5.524391382167263 (see ref. 6).
        2. The value of the definite integral on the square [-1,1] x [-1,1],
        obtained using a Padua Points cubature formula of degree 500,
        is 5.5243913821672628e+000 with an estimated absolute error of 0.00e+000.
        2D modification of an example by L.N.Trefethen (see ref. 7),
        f(x)=exp(x).
        '''
        return np.exp(x + y)

    @staticmethod
    def runge(x, y):
        ''' Bivariate Runge function: as 1D complex function is analytic
        in a neighborhood of [-1; 1] but not throughout the complex plane.

        The value of the definite integral on the square [-1,1] x [-1,1],
        up to machine precision, is 0.597388947274307 (see ref. 6).
        The value of the definite integral on the square [-1,1] x [-1,1],
        obtained using a Padua Points cubature formula of degree 500,
        is 5.9738894727430725e-001 with an estimated absolute error of 0.00e+000.

        2D modification of an example by L.N.Trefethen (see ref. 7),
        f(x)=1/(1+16*x^2).
        '''
        return 1. / (1 + 16 * (x**2 + y**2))

    @staticmethod
    def abs_cubed(x, y):
        '''Low regular function.
        The value of the definite integral on the square [-1,1] x [-1,1],
        up to machine precision, is 2.508723139534059 (see ref. 6).
        The value of the definite integral on the square [-1,1] x [-1,1],
        obtained using a Padua Points cubature formula of degree 500,
        is 2.5087231395340579e+000 with an estimated absolute error of 0.00e+000.

        2D modification of an example by L.N.Trefethen (see ref. 7),
        f(x)=abs(x)^3.
        '''
        return (x**2 + y**2)**(3 / 2)

    @staticmethod
    def gauss(x, y):
        '''Bivariate gaussian: smooth function.
        The value of the definite integral on the square [-1,1] x [-1,1],
        up to machine precision, is 2.230985141404135 (see ref. 6).
        The value of the definite integral on the square [-1,1] x [-1,1],
        obtained using a Padua Points cubature formula of degree 500,
        is 2.2309851414041333e+000 with an estimated absolute error of 2.66e-015.

        2D modification of an example by L.N.Trefethen (see ref. 7),
        f(x)=exp(-x^2).
        '''
        return np.exp(-x**2 - y**2)

    @staticmethod
    def exp_inv(x, y):
        '''Bivariate example stemming from a 1D C-infinity function.
        The value of the definite integral on the square [-1,1] x [-1,1],
        up to machine precision, is 0.853358758654305 (see ref. 6).
        The value of the definite integral on the square [-1,1] x [-1,1],
        obtained using a Padua Points cubature formula of degree 2000,
        is 8.5335875865430544e-001 with an estimated absolute error of 3.11e-015.

        2D modification of an example by L.N.Trefethen (see ref. 7),
        f(x)=exp(-1/x^2).
        '''
        arg_z = (x**2 + y**2)
        # Avoid cases in which "arg_z=0", setting only in those instances
        # "arg_z=eps".
        arg_z = arg_z + (1 - np.abs(np.sign(arg_z))) * 1.e-100
        arg_z = 1. / arg_z
        return np.exp(-arg_z)

    def __call__(self, x, y, id=0):
        s = self
        test_function = [s.franke, s.half_sphere, s.poly_degree20, s.exp_fun1,
                         s.exp_fun100, s.cos30, s.constant, s.exp_xy, s.runge,
                         s.abs_cubed, s.gauss, s.exp_inv]
        return test_function[id](x, y)
testfunct = TestFunctions()

def _find_m(n):
    ix = np.r_[1:(n + 1) * (n + 2):2]
    if np.mod(n, 2) == 0:
        n2 = n // 2
        offset = np.array([[0, 1] * n2 + [0, ]] * (n2 + 1))
        ix = ix - offset.ravel(order='F')
    return ix

def padua_points(n, domain=(-1, 1, -1, 1)):
    ''' Return Padua points

    Parameters
    ----------
    n : scalar integer
         interpolation degree
    domain : vector [a,b,c,d]
        defining the rectangle [a,b] x [c,d]. (default domain = (-1,1,-1,1))

    Returns
    -------
    pad : array of shape (2 x (n+1)*(n+2)/2) such that
        (pad[0,:], pad[1,: ]) defines the Padua points in the domain
        rectangle [a,b] x [c,d].
    or
     X1,Y1,X2,Y2 : arrays
         Two subgrids X1,Y1 and X2,Y2 defining the Padua points
    -------------------------------------------------------------------------------
    '''
    a, b, c, d = domain
    t0 = [np.pi] if n == 0 else np.linspace(0, np.pi, n + 1)
    t1 = np.linspace(0, np.pi, n + 2)
    zn = (a + b + (b - a) * np.cos(t0)) / 2
    zn1 = (c + d + (d - c) * np.cos(t1)) / 2

    Pad1, Pad2 = np.meshgrid(zn, zn1)
    ix = _find_m(n)
    return np.vstack((Pad1.ravel(order='F')[ix],
                      Pad2.ravel(order='F')[ix]))

def error_estimate(C0f):
    ''' Return interpolation error estimate from Padua coefficients
    '''
    n = C0f.shape[1]
    C0f2 = np.fliplr(C0f)
    errest = sum(np.abs(np.diag(C0f2)))
    if (n >= 1):
        errest = errest + sum(np.abs(np.diag(C0f2, -1)))
        if (n >= 2):
            errest = errest + sum(np.abs(np.diag(C0f2, -2)))
    return 2 * errest

def padua_fit(Pad, fun, *args):
    '''
    Computes the Chebyshevs coefficients

    so that f(x, y) can be approximated by:

           f(x, y) = sum cjk*Tjk(x, y)

    Parameters
    ----------
    Pad : array-like
        Padua points, as computed  with padua_points function.
    fun : function to be interpolated in the form
        fun(x, y, *args), where *args are optional arguments for fun.

    Returns
    -------
    coefficents: coefficient matrix
    abs_err   : interpolation error estimate

    '''

    N = np.shape(Pad)[1]
    # recover the degree n from N = (n+1)(n+2)/2
    n = int(round(-3 + np.sqrt(1 + 8 * N)) / 2)
    C0f = fun(Pad[0], Pad[1], *args)
    if (n > 0):
        ix = _find_m(n)
        GfT = np.zeros((n + 2) * (n + 1))
        GfT[ix] = C0f * 2 / (n * (n + 1))
        GfT = GfT.reshape(n + 1, n + 2)
        GfT = GfT.T
        GfT[0] = GfT[0] / 2
        GfT[n + 1] = GfT[n + 1] / 2
        GfT[:, 0] = GfT[:, 0] / 2
        GfT[:, n] = GfT[:, n] / 2
        Gf = GfT.T
        # compute the interpolation coefficient matrix C0f by FFT
        Gfhat = np.real(fft(Gf, 2 * n, axis=0))
        Gfhathat = np.real(fft(Gfhat[:n + 1, :], 2 * (n + 1), axis=1))
        C0f = 2 * Gfhathat[:, 0:n + 1]
        C0f[0] = C0f[0, :] / np.sqrt(2)
        C0f[:, 0] = C0f[:, 0] / np.sqrt(2)
        C0f = np.fliplr(np.triu(np.fliplr(C0f)))
        C0f[n] = C0f[n] / 2

    return C0f, error_estimate(C0f)

def paduavals2coefs(f):
    useFFTwhenNisMoreThan=100
    m = len(f)
    n = int(round(-1.5 + np.sqrt(.25+2*m)))
    x = padua_points(n)
    idx = _find_m(n)
    w = 0*x[0] + 1./(n*(n+1))
    idx1 = np.all(np.abs(x) == 1, axis=0)
    w[idx1] = .5*w[idx1]
    idx2 = np.all(np.abs(x) != 1, axis=0)
    w[idx2] = 2*w[idx2]

    G = np.zeros(idx.max()+1)
    G[idx] = 4*w*f

    if ( n < useFFTwhenNisMoreThan ):
        t1 = np.r_[0:n+1].reshape(-1, 1)
        Tn1 = np.cos(t1*t1.T*np.pi/n)
        t2 = np.r_[0:n+2].reshape(-1, 1)
        Tn2 = np.cos(t2*t2.T*np.pi/(n+1));
        C = np.dot(Tn2, np.dot(G,Tn1))
    else:

        # dct = @(c) chebtech2.coeffs2vals(c);
        C = np.rot90(dct(dct(G.T).T), axis=1)

    C[0] = .5*C[0]
    C[:,1] = .5*C[:, 1]
    C[0,-1] = .5*C[0, -1]
    del C[-1]

    # Take upper-left triangular part:
    return np.fliplr(np.triu(np.fliplr(C)))
    #C = triu(C(:,end:-1:1));
    #C = C(:,end:-1:1);

def padua_fit2(Pad, fun, *args):
    N = np.shape(Pad)[1]
    # recover the degree n from N = (n+1)(n+2)/2
    n = int(round(-3 + np.sqrt(1 + 8 * N)) / 2)
    C0f = fun(Pad[0], Pad[1], *args)
    return paduavals2coefs(C0f)

def _compute_moments(n):
    k = np.r_[0:n:2]
    mom = 2 * np.sqrt(2) / (1 - k ** 2)
    mom[0] = 2
    return mom

def padua_cubature(coefficients, domain=(-1, 1, -1, 1)):
    '''
    Compute the integral through the coefficient matrix.
    '''
    n = coefficients.shape[1]
    mom = _compute_moments(n)
    M1, M2 = np.meshgrid(mom, mom)
    M = M1 * M2
    C0fM = coefficients[0:n:2, 0:n:2] * M
    a, b, c, d = domain
    integral = (b - a) * (d - c) * C0fM.sum() / 4
    return integral

def padua_val(X, Y, coefficients, domain=(-1, 1, -1, 1), use_meshgrid=False):
    '''
    Evaluate polynomial in padua form at X, Y.

     Evaluate the interpolation polynomial defined through its coefficient
     matrix coefficients at the target points X(:,1),X(:,2) or at the meshgrid(X1,X2)

    Parameters
    ----------
    X, Y: array-like
        evaluation points.
    coefficients : array-like
         coefficient matrix
    domain : a vector [a,b,c,d]
         defining the rectangle [a,b] x [c,d]
    use_meshgrid: bool
        If True interpolate at the points meshgrid(X, Y)

    Returns
    -------
     fxy : array-like
         evaluation of the interpolation polynomial at the target points
    '''
    X, Y = np.atleast_1d(X, Y)
    original_shape = X.shape
    min, max = np.minimum, np.maximum
    a, b, c, d = domain
    n = np.shape(coefficients)[1]

    X1 = min(max(2 * (X.ravel() - a) / (b - a) - 1, -1), 1).reshape(1, -1)
    X2 = min(max(2 * (Y.ravel() - c) / (d - c) - 1, -1), 1).reshape(1, -1)
    tn = np.r_[0:n][:, None]
    TX1 = np.cos(tn * np.arccos(X1))
    TX2 = np.cos(tn * np.arccos(X2))
    TX1[1:n + 1] = TX1[1:n + 1] * np.sqrt(2)
    TX2[1:n + 1] = TX2[1:n + 1] * np.sqrt(2)
    if use_meshgrid:
        return np.dot(TX1.T, np.dot(coefficients, TX2)).T  # eval on meshgrid points
    val = np.sum(np.dot(TX1.T, coefficients) * TX2.T, axis=1)  # scattered points
    return val.reshape(original_shape)


from django.urls import reverse
from django.contrib.auth import get_user_model

from rest_framework.test import APITestCase
from rest_framework import status

from mixer.backend.django import mixer

from courses.models import Course

class CourseViewSetTestsForGetListRequest(APITestCase):
    def setUp(self) -> None:
        self.teacher = mixer.blend(get_user_model(), role='Teacher')
        self.client.force_authenticate(self.teacher)
        self.url = reverse('course-list')

    def test_get_list_returning_all_courses_relate_to_user(self):
        mixer.cycle(5).blend(Course, teachers=self.teacher.pk)
        user = mixer.blend(get_user_model())
        mixer.cycle(5).blend(Course, teachers=user.pk)
        res = self.client.get(self.url)
        assert status.HTTP_200_OK == res.status_code
        assert 5 == len(res.data)

    def test_get_list_not_working_without_login(self):
        self.client.logout()
        res = self.client.get(self.url)
        assert status.HTTP_401_UNAUTHORIZED == res.status_code


from flask import Flask, render_template, request
from Determinant import determinant
from MatrixMultiply import matmul
from Inverse import inverse
from Eigenspace import eigenspace
from Rref import rref

application = Flask(__name__)
application.register_blueprint(determinant)
application.register_blueprint(matmul)
application.register_blueprint(inverse)
application.register_blueprint(eigenspace)
application.register_blueprint(rref)

@application.route("/")
def index():

    selected = -1
    return render_template("index.html", selected=selected)

@application.route("/dimensions", methods=['POST', 'GET'])
def dimensions():
    if request.method == 'POST':
        res = str(request.form.get('choice'))

        selected = -1

        if res == 'det':
            selected = 0

        elif res == 'matmul':
            selected = 1

        elif res == 'rref':
            selected = 2

        elif res == 'inv':
            selected = 3

        elif res == 'eig':
            selected = 4

        return render_template("index.html", res=res, selected=selected)

@application.after_request
def clear_cache(req):

    req.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    req.headers["Pragma"] = "no-cache"
    req.headers["Expires"] = "0"
    req.headers["Cache-Control"] = "public, max-age=0"
    return req

if __name__ == '__main__':
    application.run()


import unittest

class TestLocalRolesAuthorizationPolicy(unittest.TestCase):
    def _getTargetClass(self):
        from .. import LocalRolesAuthorizationPolicy
        return LocalRolesAuthorizationPolicy

    def _makeOne(self):
        return self._getTargetClass()()

    def _makeResources(self):
        from pyramid.security import Allow
        from pyramid.security import ALL_PERMISSIONS
        from pyramid.security import DENY_ALL
        root = DummyContext()
        community = DummyContext(__name__='community', __parent__=root)
        blog = DummyContext(__name__='blog', __parent__=community)
        root.__acl__ = [
            (Allow, 'role.member', VIEW),
            ]
        root.__ac_local_roles__ = {
            'someguy': ['role.member'],
            }
        community.__acl__ = [
            (Allow, 'role.admin', ALL_PERMISSIONS),
            (Allow, 'role.member', MEMBER_PERMS),
            (Allow, 'role.reader', VIEW),
            DENY_ALL,
            ]
        community.__ac_local_roles_block__ = True
        community.__ac_local_roles__ = {
            'fred': ['role.admin'],
            'wilma': ['role.reader'],
            }
        blog.__ac_local_roles__ = {
            'barney': ['role.member'],
            'wilma': ['role.reader'],
            }

        return root, community, blog

    def test_class_implements_IAuthorizationPolicy(self):
        from zope.interface.verify import verifyClass
        from pyramid.interfaces import IAuthorizationPolicy
        verifyClass(IAuthorizationPolicy, self._getTargetClass())

    def test_instance_implements_IAuthorizationPolicy(self):
        from zope.interface.verify import verifyObject
        from pyramid.interfaces import IAuthorizationPolicy
        verifyObject(IAuthorizationPolicy, self._makeOne())

    def test_permits(self):
        from pyramid.security import Deny
        from pyramid.security import Allow
        from pyramid.security import Everyone
        from pyramid.security import Authenticated
        from pyramid.security import ALL_PERMISSIONS

        root, community, blog = self._makeResources()
        policy = self._makeOne()

        result = policy.permits(blog, [Everyone, Authenticated, 'wilma'],
                                'view')
        self.assertEqual(result, True)
        self.assertEqual(result.context, community)
        self.assertEqual(result.ace, (Allow, 'role.reader', VIEW))
        self.assertEqual(result.acl, community.__acl__)

        result = policy.permits(blog, [Everyone, Authenticated, 'wilma'],
                                'delete')
        self.assertEqual(result, False)
        self.assertEqual(result.context, community)
        self.assertEqual(result.ace, (Deny, Everyone, ALL_PERMISSIONS))
        self.assertEqual(result.acl, community.__acl__)

        result = policy.permits(blog, [Everyone, Authenticated, 'fred'], 'view')
        self.assertEqual(result, True)
        self.assertEqual(result.context, community)
        self.assertEqual(result.ace, (Allow, 'role.admin', ALL_PERMISSIONS))
        result = policy.permits(blog, [Everyone, Authenticated, 'fred'],
                                'doesntevenexistyet')
        self.assertEqual(result, True)
        self.assertEqual(result.context, community)
        self.assertEqual(result.ace, (Allow, 'role.admin', ALL_PERMISSIONS))
        self.assertEqual(result.acl, community.__acl__)

        result = policy.permits(blog, [Everyone, Authenticated, 'barney'],
                                'view')
        self.assertEqual(result, True)
        self.assertEqual(result.context, community)
        self.assertEqual(result.ace, (Allow, 'role.member', MEMBER_PERMS))
        result = policy.permits(blog, [Everyone, Authenticated, 'barney'],
                                'administer')
        self.assertEqual(result, False)
        self.assertEqual(result.context, community)
        self.assertEqual(result.ace, (Deny, Everyone, ALL_PERMISSIONS))
        self.assertEqual(result.acl, community.__acl__)

        result = policy.permits(root, [Everyone, Authenticated, 'someguy'],
                                'view')
        self.assertEqual(result, True)
        self.assertEqual(result.context, root)
        self.assertEqual(result.ace, (Allow, 'role.member', VIEW))
        result = policy.permits(blog,
                                [Everyone, Authenticated, 'someguy'], 'view')
        self.assertEqual(result, False)
        self.assertEqual(result.context, community)
        self.assertEqual(result.ace, (Deny, Everyone, ALL_PERMISSIONS))
        self.assertEqual(result.acl, community.__acl__)

    def test_principals_allowed_by_permission(self):
        root, community, blog = self._makeResources()
        policy = self._makeOne()

        result = sorted(policy.principals_allowed_by_permission(blog, VIEW))
        self.assertEqual(result, ['barney', 'fred', 'role.admin', 'role.member', 'role.reader', 'wilma'])
        result = sorted(policy.principals_allowed_by_permission(community, VIEW))
        self.assertEqual(result, ['fred', 'role.admin', 'role.member', 'role.reader', 'wilma'])
        result = sorted(policy.principals_allowed_by_permission(community, VIEW))
        result = sorted(policy.principals_allowed_by_permission(root, VIEW))
        self.assertEqual(result, ['role.member', 'someguy'])

    def test_callable_ac_local_roles(self):
        from pyramid.security import Allow
        context = DummyContext()
        context.__acl__ = [(Allow, 'role.reader', 'read')]
        fn = lambda self: {'bob': ['role.reader']}
        context.__ac_local_roles__ = fn.__get__(context, context.__class__)
        policy = self._makeOne()
        result = policy.permits(context, ['bob'], 'read')
        self.assertTrue(result)

    def test_string_ac_local_roles(self):
        from pyramid.security import Allow
        context = DummyContext()
        context.__acl__ = [(Allow, 'role.reader', 'read')]
        context.__ac_local_roles__ = {'bob': 'role.reader'}
        policy = self._makeOne()
        result = policy.permits(context, ['bob'], 'read')
        self.assertTrue(result)

class DummyContext:
    def __init__(self, *arg, **kw):
        self.__dict__.update(kw)

VIEW = 'view'
EDIT = 'edit'
CREATE = 'create'
DELETE = 'delete'
MODERATE = 'moderate'
ADMINISTER = 'administer'
COMMENT = 'comment'

GUEST_PERMS = (VIEW, COMMENT)
MEMBER_PERMS = GUEST_PERMS + (EDIT, CREATE, DELETE)
MODERATOR_PERMS = MEMBER_PERMS + (MODERATE,)
ADMINISTRATOR_PERMS = MODERATOR_PERMS + (ADMINISTER,)


import numpy as np
import xarray
import matplotlib.pyplot as plt
import pandas as pd
import os
import cartopy.crs as ccrs
import gsw as TEOS_10

file_name_stem = 'CO_DMQCGL01_'
data_type_dict = {'XBT': ['PR_XB','PR_BA','PR_TE','PR_OC','PR_SH','PR_GL'],
                  'CTD': ['PR_OC','PR_TE','PR_BA','PR_CT','PR_IC','PR_ME','PR_SD','PR_OS','PR_SH'],
                  'Seal': ['PR_OC','PR_TE','PR_BA','PR_CT','PR_IC','PR_ME','PR_SD','PR_OS'],
                  'Float': ['PR_PF','PR_TE'],
                  'All' : ['PR_PF','PR_XB','PR_BA','PR_TE','PR_OC','PR_SH','PR_GL','PR_CT','PR_IC','PR_ME','PR_SD','PR_OS','PR_SH']}

data_type_string  = ['PR_XB','PR_BA','PR_TE','PR_OC','PR_SH','PR_GL']

#data_type_string  = ['PR_OC','PR_TE','PR_BA','PR_CT','PR_IC','PR_ME','PR_SD','PR_OS','PR_GL']

WMO_code_dict = {'XBT'  : ['001','002','009','011','019','021','022','031','032','039','041','042','049',
                           '051','052','059','060','061','069','071','079','081','201','202','211','212',
                           '221','222','229','231','241','251','252','401','411','421','431','451','460',
                           '461','462','481','491','501','700','710','720','730','741','742','743','751'],
                 'CTD'  : ['800','810','820','830','1017'],
                 'Seal' : ['995'],
                 'Float': ['831','840','841','842','843','844','845','846','847','850','851','852','853','856',
                           '856','858','860','861'],
                 'All' : ['001','002','009','011','019','021','022','031','032','039','041','042','049',
                           '051','052','059','060','061','069','071','079','081','201','202','211','212',
                           '221','222','229','231','241','251','252','401','411','421','431','451','460',
                           '461','462','481','491','501','700','710','720','730','741','742','743','751',
                           '800','810','820','830','1017',
                           '831','840','841','842','843','844','845','846','847','850','851','852','853','856',
                           '856','858','860','861',
                           '995',
                           '999']}

#data_type_string  = ['PR_CT','PR_OC','PR_TE']
def get_duplicate_depth_index(depths):

    unique_vals, inverse, count = np.unique(depths, return_inverse=True,return_counts=True)
    idx_vals_repeated = np.where(count > 1)[0]
    if 0==len(idx_vals_repeated):

        return []

    else:
        vals_repeated = unique_vals[idx_vals_repeated]
        idx_repeated  = []
        for i_rep_val in vals_repeated:
            idx_repeated.append(np.nonzero(depths==i_rep_val)[0])
    return idx_repeated

def compound_logical(data,condition):
    data = data.tolist()
    n_conditions = len(condition)
    matching_indicies  = []
    found_data = False

    for i_cond in range(0,n_conditions):
        condition_indicies = [i for i,n in enumerate(data) if n.strip() == condition[i_cond]]
        if len(condition_indicies) != 0:
            for idx in condition_indicies:
               matching_indicies.append(idx)

    return sorted(matching_indicies)

if __name__ == '__main__':

    #base_file_path  = '/OSM/CBR/OA_DCFP/data3/observations/CORA/legacy/CORA_50/unpacked/home/cercache/users/mirror/home/oo9/oo/CORA4.3/Final_patched'
    base_file_path  = '/OSM/CBR/OA_DCFP/data2/observations/CORA/CORA_50/unpacked/home/cercache/users/mirror/home/oo9/oo/CORA4.3/Final_patched/'
#    base_file_path  = '/OSM/CBR/OA_DCFP/work/cha674/CORA_interrogation/test_files/'
    platform_type   = 'All'
    CORA_VERSION    = 50
    variable_to_get = 'salinity'

    MAX_DEPTH_TO_COMPUTE_STATS = 2000
    START_YEAR  = 2014
    END_YEAR    = 2016

    file_to_read = {str(START_YEAR) : []}
    total_num_profiles_for_year = {str(START_YEAR) : 0}
    for i_year in range(START_YEAR,END_YEAR):
        file_to_read[str(i_year)] = []
        total_num_profiles_for_year[str(i_year)] = 0

    total_num_profiles  = 0
    n_days_in_database  = 0
    n_files  = 0

    for i_year in range(START_YEAR,END_YEAR):
        data_path_for_current_year = os.path.join(base_file_path,str(i_year))
        dir_contents = os.listdir(data_path_for_current_year)
        dir_contents.sort()
        first_pass = True
        total_num_profiles_current_year = 0

        for entry in dir_contents:
            for i_file_type in data_type_dict[platform_type]:
                if os.path.isfile(os.path.join(data_path_for_current_year,entry)) and entry.endswith(i_file_type + ".nc"):
                    #print(entry)
                    file_handle  = xarray.open_dataset(os.path.join(data_path_for_current_year,entry), decode_times=True)
                    WMO_inst_type = file_handle['WMO_INST_TYPE'].values.astype('str')
                    WMO_type = WMO_inst_type.dtype
                    if platform_type == 'All':
                        idx_to_get = file_handle['N_PROF'].values

                    else:
                        idx_to_get = compound_logical(WMO_inst_type,WMO_code_dict[platform_type])
                    if first_pass:
                        dates  = pd.to_datetime(file_handle['JULD'][idx_to_get].values).date
                        first_pass=False
                    else:
                        dates = np.concatenate([dates,pd.to_datetime(file_handle['JULD'][idx_to_get].values).date])

                    variable_list = file_handle.data_vars

                    if ((variable_to_get.lower() == 'temperature') or (variable_to_get.lower() == 'temp')) and 'TEMP' in variable_list:

                        var     = file_handle['TEMP'][idx_to_get,:]
                        n_profiles_current_file = np.logical_not(np.all(np.isnan(var),axis=1)).values.sum()

                    elif ((variable_to_get == 'salinity') or (variable_to_get.lower() == 'salt')) and 'PSAL' in variable_list:

                        var     = file_handle['PSAL'][idx_to_get,:]
                        n_profiles_current_file = np.logical_not(np.all(np.isnan(var),axis=1)).values.sum()

                    else:
                        n_profiles_current_file = 0

                    total_num_profiles_current_year = total_num_profiles_current_year + n_profiles_current_file

                    #END if n_profiles !=0
                    file_handle.close()
                    if n_profiles_current_file !=0:
                        file_to_read[str(i_year)].append(os.path.join(data_path_for_current_year,entry))
                #END if os.path
            #END for i_file_type in data_type_string
        #END for entry in dir_contents
        file_to_read[str(i_year)].sort()

        if i_year == START_YEAR:
            unique_dates = {str(i_year) : np.sort(np.unique(dates))}
        else:
            unique_dates[str(i_year)] = np.sort(np.unique(dates))

        n_days_in_database = n_days_in_database + len(unique_dates[str(i_year)])

        n_files = n_files + len(file_to_read[str(i_year)])
        total_num_profiles_for_year[str(i_year)] = total_num_profiles_current_year
        total_num_profiles = total_num_profiles + total_num_profiles_current_year
    #END for i_year
    #print(file_to_read)
    print('==============================================================')
    print('Total number of files: ', n_files)
    print('Total number of profiles: ', total_num_profiles)
    print('Total number of unique dates in database:', n_days_in_database)
    print('==============================================================')
#    file_of_type_to_get.sort()
#    n_points_at_depth
#    for i_year in range(START_YEAR,END_YEAR):
#        print(total_num_profiles_for_year[str(i_year)])

    print(total_num_profiles_for_year)

    for i_year in range(START_YEAR,END_YEAR):

        #data_path_for_current_year = os.path.join(base_file_path,str(i_year))
        #dir_contents = os.listdir(data_path_for_current_year)
        first_pass = True
        total_num_profiles_current_year = 0

        print('============================')
        print('Year: ', i_year)
        print('Total number of profiles for year: ', total_num_profiles_for_year[str(i_year)])
        profile_counter = 0
        latitude  = np.nan * np.zeros(total_num_profiles_for_year[str(i_year)],dtype=np.float32)
        longitude = np.nan * np.zeros(total_num_profiles_for_year[str(i_year)],dtype=np.float32)
        time      = np.zeros(total_num_profiles_for_year[str(i_year)],dtype='datetime64[ns]')

        WMO_inst_code  = np.zeros(total_num_profiles_for_year[str(i_year)],dtype=WMO_type)
        max_depth      = np.zeros(total_num_profiles_for_year[str(i_year)],dtype=np.float32)

        files_for_current_year = file_to_read[str(i_year)]
        for i_file in files_for_current_year:

            file_handle  = xarray.open_dataset(i_file, decode_times=True)
            n_levels            = file_handle['N_LEVELS'].size
            n_profiles_for_file = file_handle['N_PROF'].size
            WMO_inst_type = file_handle['WMO_INST_TYPE'].values.astype('str')

            if platform_type == 'All':
                idx_to_get = file_handle['N_PROF'].values
            else:
                idx_to_get = compound_logical(WMO_inst_type,WMO_code_dict[platform_type])

            WMO_inst_type = WMO_inst_type[idx_to_get]

            variable_list = file_handle.data_vars
            if ((variable_to_get.lower() == 'temperature') or (variable_to_get.lower() == 'temp')) and 'TEMP' in variable_list:
                var  = file_handle['TEMP'][idx_to_get,:]
            elif ((variable_to_get == 'salinity') or (variable_to_get.lower() == 'salt')) and 'PSAL' in variable_list:
                var  = file_handle['PSAL'][idx_to_get,:]

            good_profile_idx = np.nonzero(np.logical_not(np.all(np.isnan(var),axis=1)).values)[0]
            n_good_profiles = good_profile_idx.size

            current_latitudes = file_handle['LATITUDE'][idx_to_get][good_profile_idx].values
            current_longitudes = file_handle['LONGITUDE'][idx_to_get][good_profile_idx].values

            if 'DEPH' in variable_list:
                depth    = file_handle['DEPH'][idx_to_get,:][good_profile_idx,:].values
                vertical_coord_QC = file_handle['DEPH_QC'][idx_to_get,:][good_profile_idx,:].values

            if 'PRES' in variable_list:
                pressure          = file_handle['PRES'][idx_to_get,:][good_profile_idx,:].values
                vertical_coord_QC = file_handle['PRES_QC'][idx_to_get,:][good_profile_idx,:].values

                lat_broadcast = np.tile(current_latitudes,[1,n_levels]).reshape([n_good_profiles,n_levels])
                depth_from_pressure = -TEOS_10.z_from_p(pressure, lat_broadcast)

            if ('DEPH' in variable_list) and ('PRES' in variable_list):

                bad_profile_depth_idx = np.nonzero(np.all(np.isnan(depth),axis=1))[0]
                bad_profile_press_idx = np.nonzero(np.all(np.isnan(pressure),axis=1))[0]

                for i_bad_depth_profile in bad_profile_depth_idx:
                    if i_bad_depth_profile not in bad_profile_press_idx:
                        depth[i_bad_depth_profile,:] = depth_from_pressure[i_bad_depth_profile,:]
            if ('DEPH' not in variable_list) and ('PRES' in variable_list):
               depth = depth_from_pressure

            bad_profile_depth_idx = np.nonzero(np.all(np.isnan(depth),axis=1))[0]
            #print(np.nanmax(depth,axis=1))
            max_depth[profile_counter:profile_counter+n_good_profiles] = np.nanmax(depth,axis=1)

            current_latitudes[bad_profile_depth_idx] = np.nan
            current_longitudes[bad_profile_depth_idx] =np.nan
            latitude[profile_counter:profile_counter+n_good_profiles]  = current_latitudes
            longitude[profile_counter:profile_counter+n_good_profiles] = current_longitudes
            time[profile_counter:profile_counter+n_good_profiles]           =   file_handle['JULD'][good_profile_idx]
            WMO_inst_code[profile_counter:profile_counter+n_good_profiles]  = WMO_inst_type[good_profile_idx]

            profile_counter = profile_counter + n_good_profiles
        #END for entry in dir_contents

        output_file_path = '/OSM/CBR/OA_DCFP/work/cha674/CORA_interrogation/Stat_files_v' + str(CORA_VERSION) + '/V2_after_bug_fix/'
        output_file_name = 'CORA_v' + str(CORA_VERSION) + '_' + variable_to_get + '_' + str(i_year) + '_stats_' + platform_type + 'QC012.fix2.nc'

        print('Writing file: ', output_file_name, ' to ', output_file_path)

        output_dataset = xarray.DataArray(latitude,dims=('N_PROF'),coords={'N_PROF':np.arange(0,latitude.size)}).to_dataset(name='latitudes')
        output_dataset['longitudes'] = xarray.DataArray(longitude,dims=('N_PROF'),coords={'N_PROF':np.arange(0,latitude.size)})
        output_dataset['JULD']       = xarray.DataArray(time,dims=('N_PROF'),coords={'N_PROF':np.arange(0,latitude.size)})
        output_dataset['max_depth']  = xarray.DataArray(max_depth,dims=('N_PROF'),coords={'N_PROF':np.arange(0,latitude.size)})
        output_dataset['WMO_instrument_code']  = xarray.DataArray(WMO_inst_code,dims=('N_PROF'),coords={'N_PROF':np.arange(0,latitude.size)})

        output_dataset.to_netcdf(os.path.join(output_file_path,output_file_name))

    #END for i_year

    dsa
    for i_year in range(START_YEAR,END_YEAR):
        print('============================')
        print('Year: ', i_year)
        print('Total number of profiles for year: ', total_num_profiles_for_year[str(i_year)])
        profile_counter = 0
        latitude  = np.nan * np.zeros(total_num_profiles_for_year[str(i_year)],dtype=np.float32)
        longitude = np.nan * np.zeros(total_num_profiles_for_year[str(i_year)],dtype=np.float32)
        time      = np.zeros(total_num_profiles_for_year[str(i_year)],dtype=np.float64)

        WMO_inst_code  = np.zeros(total_num_profiles_for_year[str(i_year)],dtype=np.int32)
        max_depth      = np.zeros(total_num_profiles_for_year[str(i_year)],dtype=np.float32)

        n_points_on_level = np.zeros([len(unique_dates[str(i_year)]),interp_levels.size],dtype=np.int32)

        n_files_for_year = len(file_of_type_to_get[str(i_year)])

        data_path_for_current_year = os.path.join(base_file_path,str(i_year))
        for i_file in range(0,n_files_for_year):

            print("Opening file: ", i_file, ' of ', n_files_for_year,': ', file_of_type_to_get[str(i_year)][i_file])

            file_handle  = xarray.open_dataset(os.path.join(data_path_for_current_year, file_of_type_to_get[str(i_year)][i_file]), decode_times=True)
            n_levels     = file_handle['N_LEVELS'].size
            WMO_inst_type = file_handle['WMO_INST_TYPE'].values.astype('str')

            idx_to_get = compound_logical(WMO_inst_type,WMO_code_dict[platform_type])
            n_profiles = len(idx_to_get)

            if n_profiles==0:
                continue

            current_latitude                                          = file_handle['LATITUDE'][idx_to_get].values
            current_longitude                                         = file_handle['LONGITUDE'][idx_to_get].values
            time_current_file                                         = file_handle['JULD'][idx_to_get].values
            time [profile_counter:profile_counter+n_profiles]         = time_current_file
            WMO_inst_code[profile_counter:profile_counter+n_profiles] = WMO_inst_type[idx_to_get].astype(int)

            latitude[profile_counter:profile_counter+n_profiles]      = file_handle['LATITUDE'][idx_to_get].values
            longitude[profile_counter:profile_counter+n_profiles]     = file_handle['LONGITUDE'][idx_to_get].values
            current_dates                                             = pd.to_datetime(time_current_file).date

            variable_list = file_handle.data_vars
            if 'DEPH' in variable_list:
                depth    = file_handle['DEPH'][idx_to_get,:].values
                vertical_coord_QC = file_handle['DEPH_QC'][idx_to_get,:]

            elif 'PRES' in variable_list:
                pressure          = file_handle['PRES'][idx_to_get,:].values
                vertical_coord_QC = file_handle['PRES_QC'][idx_to_get,:]

                lat_broadcast = np.tile(latitude[profile_counter:profile_counter+n_profiles],[1,n_levels]).reshape([n_profiles,n_levels])
                depth = -TEOS_10.z_from_p(pressure, lat_broadcast)
            #END if 'DEPH' in variable_list
            max_depth[profile_counter:profile_counter+n_profiles] = np.nanmax(depth,axis=1)

            if (variable_to_get.lower() == 'temperature') or (variable_to_get.lower() == 'temp'):
                if 'TEMP' in variable_list:

                    var     = file_handle['TEMP'][idx_to_get,:]
                    var_QC  = file_handle['TEMP_QC'][idx_to_get,:]
                else:
                    continue
            elif (variable_to_get == 'salinity') or (variable_to_get.lower() == 'salt'):
                if 'PSAL' in variable_list:
                    var     = file_handle['PSAL'][idx_to_get,:]
                    var_QC  = file_handle['PSAL_QC'][idx_to_get,:]
                else:
                    continue

            for i_profile in range(0,n_profiles):
#                print(i_profile)
                date_of_profile = current_dates[i_profile]
                idx_date = np.nonzero(unique_dates[str(i_year)]==date_of_profile)[0][0]

                profile_current = var[i_profile,:]
                QC_profile_current = var_QC[i_profile,:]
                vertical_coord_QC_profile_current = vertical_coord_QC[i_profile,:]

                profile_current = profile_current.where((QC_profile_current.astype(float)==0) | (QC_profile_current.astype(float)==1) | (QC_profile_current.astype(float)==2))
                profile_current = profile_current.where((vertical_coord_QC_profile_current.astype(float)==0) | (vertical_coord_QC_profile_current.astype(float)==1) | (vertical_coord_QC_profile_current.astype(float)==2))

                idx_duplicate_depths = get_duplicate_depth_index(depth[i_profile,:])
                if len(idx_duplicate_depths) != 0:
                    for i_duplicate_index in idx_duplicate_depths:
                        for i_index in range(1,len(i_duplicate_index)):

                            depth[i_profile,i_duplicate_index[i_index]]   = depth[i_profile,i_duplicate_index[i_index]] + 0.01*float(i_index)
                    #END for i_duplicate_index
                #END if len(idx_duplicate_depths) !=0

                n_good_points = (1*profile_current.notnull().values).sum()

                if n_good_points<5:
                    continue
                else:

                    profile_current['N_LEVELS'] = np.sort(depth[i_profile,:])
                    first_good_depth_var   = profile_current.to_series().first_valid_index()
                    last_good_depth_var    = profile_current.to_series().last_valid_index()
                    first_good_depth_depth = profile_current['N_LEVELS'].to_series().first_valid_index()
                    last_good_depth_depth  = profile_current['N_LEVELS'].to_series().last_valid_index()

                    first_good_depth = max(first_good_depth_var,first_good_depth_depth)
                    last_good_depth  = max(last_good_depth_var,last_good_depth_depth)

                    first_good_idx   = np.nonzero(profile_current['N_LEVELS'].values==first_good_depth)[0][0]
                    last_good_idx    = np.nonzero(profile_current['N_LEVELS'].values==last_good_depth )[0][0]

                    if np.any(profile_current['N_LEVELS'][first_good_idx:last_good_idx+1].isnull()):
#                        print('Hello')
                        depth_tmp = depth[i_profile,:]

                        depth_tmp[first_good_idx:last_good_idx] = pd.Series(depth_tmp[first_good_idx:last_good_idx+1]).interpolate().values
                        profile_current['N_LEVELS'] = depth_tmp
#                    print(last_good_depth)
#                    print(first_good_depth)
#                    print('======')
                    if first_good_depth>MAX_DEPTH_TO_COMPUTE_STATS:
                        first_standard_level =interp_levels.size
                    else:
                        first_standard_level = np.nonzero(interp_levels>=first_good_depth)[0][0]

                    if last_good_depth > MAX_DEPTH_TO_COMPUTE_STATS:
                        last_standard_level = interp_levels.size
                    else:
                        last_standard_level  = np.nonzero(interp_levels>=last_good_depth)[0][0]
                    good_levels = np.ones([last_standard_level-first_standard_level])
                    #print(first_good_depth)
                    #print(last_good_depth)
                    #print(first_standard_level)
                    #print(last_standard_level)
                    n_points_on_level[idx_date,first_standard_level:last_standard_level] = n_points_on_level[idx_date,first_standard_level:last_standard_level] + good_levels

                    #try:
                    #    profile_current = profile_current[first_good_idx:last_good_idx].interp(N_LEVELS=interp_levels,method='nearest')
                    #except:
                    #    profile_curren = np.nan * interp_levels

                    #n_points_on_level[idx_date,:] = n_points_on_level[idx_date,:] +  1*profile_current.notnull().values

                 #END if n_good_points<5:
            #END for i_profile
            profile_counter = profile_counter + n_profiles
            file_handle.close()
        #END for i_file

        n_points_on_level[:,0] = n_points_on_level[:,1]
        #output_file_path = '/OSM/CBR/OA_DCFP/work/cha674/CORA_interrogation/Stat_files_v51/'
        #output_file_name = 'CORA_v51_' + variable_to_get + '_' + str(i_year) + '_stats_' + platform_type + 'QC012.npz'

        output_file_path = '/OSM/CBR/OA_DCFP/work/cha674/CORA_interrogation/Stat_files_v' + str(CORA_VERSION) + '/Simple_Counts/'
        output_file_name = 'CORA_v' + str(CORA_VERSION) + '_' + variable_to_get + '_' + str(i_year) + '_stats_' + platform_type + 'QC012.simple_count_new.npz'

        print("Saving file: ", output_file_path + output_file_name)
        np.savez(output_file_path + output_file_name, n_points_on_level=n_points_on_level, time=time,longitude=longitude,latitude=latitude,unique_dates=unique_dates[str(i_year)],WMO_inst_code=WMO_inst_code,max_depth=max_depth)

    #END for i_year


# 10001st prime
#
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
# What is the 10 001st prime number?

def primes(max_num):
  if max_num >= 2:
    prime_bitmap = [True for i in xrange(max_num)]
    prime_bitmap[0] = False
    prime_bitmap[1] = False
    for i in xrange(max_num):
      if prime_bitmap[i]:
        yield i
        for j in xrange(i**2, max_num, i):
          prime_bitmap[j] = False

def nth_prime(n):
  # Use iterative-deepening approach to find primes.
  iteration = 0
  while True:
    iteration += 1
    count = 0
    for prime in primes(2**iteration):
      count += 1
      if count == n:
        return prime

print(nth_prime(10001))
# 104743

# iteration: 17


import pygame
import random
import math
from pygame import mixer
# Iniciar Pygame
pygame.init()

# Crear pantalla
pantalla = pygame.display.set_mode((800, 600))

# Titulo e Icono
pygame.display.set_caption("Invasion especial")
icono = pygame.image.load("tierra.png")
pygame.display.set_icon(icono)

# Fondo
cuadros = [pygame.image.load(f'Start{i + 1}.png') for i in range(5)]
indice_cuadro_actual = 0
retraso = 150
contador = 0

# Agregar musica

mixer.music.load("musica_fondo.mp3")
mixer.music.set_volume(0.1)
mixer.music.play(-1)

# Jugador
img_jugador = pygame.image.load("nave.png")
jugador_x = 364
jugador_x_cambio = 0
jugador_y = 536
jugador_y_cambio = 50

# balas
balas = []
img_bala = pygame.image.load("bala.png")
bala_x = 0
bala_x_cambio = 0
bala_y = 536
bala_y_cambio = 0.7
bala_visible = False

# Enemigo
img_enemigo = []
enemigo_x = []
enemigo_x_cambio = []
enemigo_y = []
enemigo_y_cambio = []
cantidad_enemigos = 20

# Texto Puntaje
puntaje = 0
fuente = pygame.font.Font("Pixel NES.otf", 32)
texto_x = 10
texto_y = 10

# Texto Final
juego_terminado = False

def texto_final():
    texto_final_juego = fuente.render("Juego Terminado", True, (255, 255, 255))
    pantalla.blit(texto_final_juego, (60, 200))

# funcion enseñar puntaje
def mostrar_puntaje(x, y):
    texto = fuente.render(f"Puntaje: {puntaje}", True, (255, 255, 255))
    pantalla.blit(texto, (x, y))

for e in range(cantidad_enemigos):
    img_enemigo.append(pygame.image.load("enemigos.png"))
    enemigo_x.append(random.randint(0, 736))
    enemigo_x_cambio.append(0.7)
    enemigo_y.append(random.randint(50, 200))
    enemigo_y_cambio.append(55)

def jugador(x, y):
    pantalla.blit(img_jugador, (x, y))

def enemigo(x, y, enemigo):
    pantalla.blit(img_enemigo[enemigo], (x, y))

def disparar(x, y):
    global bala_visible
    bala_visible = True
    pantalla.blit(img_bala, (x + 16, y + 10))

def colision(x_1, y_1, x_2, y_2):
    distancia = math.sqrt( math.pow(x_1 - x_2, 2) + math.pow(y_2 - y_1, 2) )
    if distancia < 64:
        return True
    else: False

# Loop del juego
se_ejecuta = True
while se_ejecuta:
    # Primero se pinta la pantalla
    pantalla.fill((0, 0, 4))

    pantalla.blit(cuadros[indice_cuadro_actual], (0, 0))

    contador += 1
    if contador >= retraso:
        contador = 0
        indice_cuadro_actual += 1
        if indice_cuadro_actual >= len(cuadros):
            indice_cuadro_actual = 0

    # Eventos
    for e in pygame.event.get():
        # Evento cerrar
        if e.type == pygame.QUIT:
            se_ejecuta = False

        # Evento Presionar
        if e.type == pygame.KEYDOWN:
            if e.key == pygame.K_LEFT:
                jugador_x_cambio = -0.6
            if e.key == pygame.K_RIGHT:
                jugador_x_cambio = 0.6
            if e.key == pygame.K_UP:
                jugador_y_cambio = -0.6
            if e.key == pygame.K_DOWN:
                jugador_y_cambio = 0.6
            if e.key == pygame.K_SPACE:
                sonido_bala = mixer.Sound("disparo.mp3")
                sonido_bala.set_volume(0.3)
                sonido_bala.play()
                nueva_bala = {
                "x": jugador_x,
                "y": jugador_y,
                "velocidad": -5
                }
                balas.append(nueva_bala)
        # Evento Soltar
        if e.type == pygame.KEYUP:
            if e.key == pygame.K_LEFT or e.key == pygame.K_RIGHT:
                jugador_x_cambio = 0
            if e.key == pygame.K_UP or e.key == pygame.K_DOWN:
                jugador_y_cambio = 0

    # Coloca al jugador
    jugador_x += jugador_x_cambio

    jugador_y += jugador_y_cambio

    # Mantiene al jugador en sus bordes
    if jugador_x <= 0:
        jugador_x = 0

    elif jugador_x >= 736:
        jugador_x = 736

    if jugador_y <= 0:
        jugador_y = 0

    elif jugador_y >= 536:
        jugador_y = 536

    # Modificar la posicion de los enemigos
    for e in range(cantidad_enemigos):

        hay_colision_jugador = colision(enemigo_x[e], enemigo_y[e], jugador_x, jugador_y)
        if hay_colision_jugador:
            for k in range(cantidad_enemigos):
                enemigo_y[k] = 1000
            juego_terminado = True
            break

        enemigo_x[e] += enemigo_x_cambio[e]

        if enemigo_x[e] <= 0:
            enemigo_x_cambio[e] = 0.4
            enemigo_y[e] += enemigo_y_cambio[e]

        elif enemigo_x[e] >= 736:
            enemigo_x_cambio[e] = -0.4
            enemigo_y[e] += enemigo_y_cambio[e]

    # colision
        for bala in balas:
            colision_bala_enemigo = colision(enemigo_x[e], enemigo_y[e], bala["x"], bala["y"])
            if colision_bala_enemigo:
                sonido_colision = mixer.Sound("Golpe.mp3")
                sonido_colision.set_volume(0.4)
                sonido_colision.play()
                balas.remove(bala)
                puntaje += 1
                if puntaje > 20:
                    cantidad_enemigos = 20
                enemigo_x[e] = random.randint(0, 736)
                enemigo_y[e] = random.randint(20, 200)
                break

        enemigo(enemigo_x[e], enemigo_y[e], e)

    if bala_y <= -64:
        bala_y = 500
        bala_visible = False

    # Movimiento bala
    for bala in balas:
        bala["y"] += bala["velocidad"]
        pantalla.blit(img_bala, (bala["x"] + 16, bala["y"] + 10))
        if bala["y"] < 0:
            balas.remove(bala)
    for bala in balas:
        bala["y"] += bala["velocidad"]
        pantalla.blit(img_bala, (bala["x"] + 16, bala["y"] + 10))
        if bala["y"] < 0:
            balas.remove(bala)

    # Coloca a las entidades
    jugador(jugador_x, jugador_y)
    mostrar_puntaje(texto_x, texto_y)
    if juego_terminado:
        texto_final()

    pygame.display.update()


#!/usr/bin/env python3
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QTextBlock
from PyQt5.QtWidgets import QHBoxLayout, QLabel, QPushButton, QTextEdit, QWidget

class Right_Widget(QWidget):
    def __init__(self):
        super(Right_Widget, self).__init__()
        self.layout = QHBoxLayout()
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(0)
        self.setLayout(self.layout)
        #
        temp_button = QPushButton('aa')
        self.text_edit = QTextEdit()
        self.text_edit.setVisible(False)
        self.image_label = QLabel()
        self.image_label.setAlignment(Qt.AlignCenter)
        self.image_label.setVisible(False)
        self.layout.addWidget(self.image_label)
        self.layout.addWidget(self.text_edit)


from git import Repo, GitCommandError

from floxcore.context import Flox
from floxcore.exceptions import PluginException

from loguru import logger

def create_branch(flox: Flox, out, flow_id, **kwargs):
    """Create branch"""
    repo = Repo(flox.working_dir)

    try:
        repo.git.checkout(flow_id)
        out.info(f"Switched to existing branch '{flow_id}'")
    except GitCommandError:
        branch = repo.create_head(flow_id)
        branch.checkout()
        out.success(f"Created and switched to new branch '{flow_id}'")

def add_files(flox: Flox, out, message, **kwargs):
    """Add current state to git repository"""
    repo = Repo(flox.working_dir)

    try:
        repo.git.add("-A")
        repo.git.commit("-m", message)
        out.success("Committed current state of work")
    except GitCommandError:
        pass

def pull_changes(flox: Flox, out, branch, **kwargs):
    """Pull changes from remote"""
    repo = Repo(flox.working_dir)
    try:
        logger.debug("pull")
        repo.git.branch(f"--set-upstream-to=origin/{branch}", branch)
        repo.git.pull()
        out.success(f"Pulled from remote origin")
    except GitCommandError as e:
        raise PluginException(f"Failed to pull")

def push_changes(flox: Flox, out, **kwargs):
    """Push changes to remote"""
    repo = Repo(flox.working_dir)
    origin = repo.remote("origin")
    try:
        repo.git.push("--set-upstream", origin, repo.head.ref)
        out.success(f"Pushed to remote origin")
    except GitCommandError as e:
        raise PluginException(f"Failed to push to origin. {e.stderr}")

def workflow_finish(flox: Flox, out, **kwargs):
    """Switch back to default branch"""
    repo = Repo(flox.working_dir)
    repo.git.checkout("master")

    out.success(f"Switched back to default branch")


import os
import numpy as np
from nltk import edit_distance, jaccard_distance, word_tokenize
import argparse
import sys
import re

def define_paths(root_dir):

	vocabs = {'genre': os.path.join(
				root_dir, 'knowledge_base', 'genre.txt')
			}

	return vocabs

def get_vocab(label):

	root_dir = os.path.dirname(__file__)

	vocabs = define_paths(root_dir)
	with open(vocabs[label]) as f:
		vocab = f.read().split('\n')
	return vocab

def get_candidate(word, vocab, jaccard_thresh=0.4):
	min_d = 10
	candidate = word
	if word.isdigit():
		return word
	for w in vocab:
		d = edit_distance(w, word.lower())
		if d < min_d:
			if d > 2 and len(word)>5:
				continue
			if d > 1 and len(word)<=5:
				continue
			j_distance = jaccard_distance(set(candidate), set(word.lower()))
			if j_distance < jaccard_thresh:
				min_d = d
				candidate = w

	return candidate

def fix_sentence(sentence, label):
	vocab = get_vocab(label)
	sentence = clean_str(sentence)
	sentence = remove_junk(sentence)
	if ' ' in sentence:
		tokens = sentence.split(' ')
	else:
		tokens = [sentence]
	tokens = [x for x in tokens if len(x) != 0]
	result = []

	for t in tokens:
		if t.lower() in vocab:
			result.append(t)
			continue
		result.append(get_candidate(t, vocab))
	return ' '.join(result)

def remove_junk(string):
	junk = '%^*\'|/?"():'
	for ch in junk:
		string = string.replace(ch, '')
	return string

def clean_str(text):
	"""Method dedicated to remove extra spaces
	and unwanted characters in the string.

	@param: string - string to be cleaned

	@return: string - the same string with extra
			spaces removed
	"""

	text = re.sub(r'(\n|\r|\t)', ' ', text)
	text = ''.join([x for x in text if x.isprintable()])
	text = re.sub(r' +', ' ', text)

	if text.startswith(' '):
		text = text[1:]
	if text.endswith(' '):
		text = text[:-1]
	return text


from abc import ABC
import pandas as pd
from itertools import combinations

'''
Classe che una volta caricato un CSV mette a disposizione dei metodi per la divisione in gruppi
'''
class group_divider(ABC):

    __partecipanti = [] # conterrà tutti i partecipanti
    __matrice = [] # contiene la matrice

    '''
    Carica il file CSV per l'utilizzo nella classe, modificando lo stato interno

    @param file -> path del file da aprire
    @modify partecipanti e matrice, definendo i loro valori in base al file caricato
    '''
    def carica_csv(self, file):
        df = pd.read_csv(file,index_col=0)
        self.__partecipanti = list(df.columns)
        self.__matrice = df

    '''
    Stampa la matrice
    '''
    def stampa_matrice(self):
        print(self.__matrice)

    '''
    Genera le combinazioni e ricerca in brute-force la combinazione che ha la media più alta.

    @return team_a
    @return team_b
    @return media_migliore -> la media più alta trovata
    '''
    def dividi_in_due_gruppi_media(self):
        if(self.__partecipanti): # Truth value testing
            combinazioni = self.__gen_combinazioni(int(len(self.__partecipanti)/2))

            # calcola i due valori
            media_migliore = 0
            team_a = []
            team_b = []
            for a in combinazioni:
                punteggio_a = self.__punti_gruppo(a)
                b = [x for x in self.__partecipanti if x not in a]
                punteggio_b = self.__punti_gruppo(b)

                med_a = punteggio_a / len(a)
                med_b = punteggio_b / len(b)

                media = (med_a + med_b) / 2

                if media > media_migliore:
                    media_migliore = media
                    team_a = a
                    team_b = b

            return team_a, team_b, media_migliore

        else:
            print("Inserire csv prima di eseguire le funzioni")
            return None, None, None

    '''
    Genera tutte le combinazioni di gruppi possibili di N partecipanti e li ritorna come una lista.

    @param num_membrs -> numero di persone per gruppo
    @return lista -> una lista di liste, dove le liste interne rappresentano i gruppi
    '''
    def __gen_combinazioni(self,num_mebers) -> list:
        return [list(c) for c in combinations(self.__partecipanti,num_mebers)]

    '''
    Somma tutte le celle della matrice generata dai partecipanti del gruppo e ne ritorna il risultato. Non modifica lo stato interno

    @param gruppo -> lista dei partecipanti che formano un gruppo
    @return sum -> somma dei valori della matrice
    '''
    def __punti_gruppo(self,gruppo) -> int:
        # creazione della matrice
        offerte = self.__matrice.loc[gruppo]
        offerte_gruppo = offerte[gruppo]

        sum = 0
        for i in range(len(offerte_gruppo.axes[1])):
            for j in range(len(offerte_gruppo.axes[1])):
                tmp = offerte_gruppo.iloc[i,j]
                if isinstance(tmp, str) and tmp.isnumeric(): # in pandas NaN = float
                    sum = sum + int(tmp)
        return sum


def flatten(dictionary):
    def look_inside(d, result, k=None):
        for key in d.keys():
            value = d[key] if d[key] else ''

            if not isinstance(value, dict):
                if not k:
                    result[key] = value
                else:
                    result[k + "/" + key] = value
            else:
                if not k:
                    look_inside(value, result, key)
                else:
                    look_inside(value, result, k + "/" + key)

    result = {}
    look_inside(dictionary, result)
    return result

if __name__ == '__main__':
    test_input = {"key": {"deeper": {"more": {"enough": "value"}}}}
    print(' Input: {}'.format(test_input))
    print('Output: {}'.format(flatten(test_input)))

    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert flatten({"key": "value"}) == {"key": "value"}, "Simple"
    assert flatten(
        {"key": {"deeper": {"more": {"enough": "value"}}}}
    ) == {"key/deeper/more/enough": "value"}, "Nested"
    assert flatten({"empty": {}}) == {"empty": ""}, "Empty value"
    assert flatten({"name": {
                        "first": "One",
                        "last": "Drone"},
                    "job": "scout",
                    "recent": {},
                    "additional": {
                        "place": {
                            "zone": "1",
                            "cell": "2"}}}
    ) == {"name/first": "One",
          "name/last": "Drone",
          "job": "scout",
          "recent": "",
          "additional/place/zone": "1",
          "additional/place/cell": "2"}
    print('You all set. Click "Check" now!')


#!/usr/bin/env python
import os
from setuptools import setup, find_packages

with open(
    os.path.join(os.path.dirname(os.path.realpath(__file__)), "README.md")
) as file:  # noqa
    long_description = file.read()

setup(
    name="statuses",
    author="chrisdotcode",
    author_email="pypi+chris@code.sc",
    url="https://github.com/chrisdotcode/statuses",
    description="The `Status` class represents the status of some event.",
    long_description_content_type="text/markdown",
    long_description=long_description,
    license="BSD 3-Clause License",
    packages=find_packages(exclude=["tests"]),
    package_data={"statuses": ["py.typed"]},
    zip_safe=False,
    install_requires=[],
    setup_requires=["setuptools_scm"],
    use_scm_version=True,
    test_suite="tests",
)


from tkinter import *
from time import *
import webbrowser

def update():
    time_string = strftime("%I:%M:%S %p")
    time_label.config(text=time_string)

    time_label.after(1000,update)
def click():
    handle = webbrowser.get()
    handle.open('https://www.youtube.com/watch?v=dQw4w9WgXcQ')

window = Tk()

time_label = Label(window,font=("Arial",16),fg="#b59cb3",bg="#23282e")
time_label.pack()

day_label = Label(window,font=("Arial",25,"bold"))
day_label.pack()

date_label = Label(window,font=("Arial",30))
date_label.pack()

window.geometry("420x420")
window.title("Free Robux Now!")

icon = PhotoImage(file='icon.png')
window.iconphoto(True,icon)
window.config()

image = PhotoImage('file=robux.png')

button = Button(window,
                text="Generate robux",
                command=click,
                font=("Segoe UI",35),
                fg="#6557ff",
                bg="gray",
                activeforeground="#6557ff",
                activebackground="gray",
                state=ACTIVE,)

button.pack()

update()

window.mainloop()


"""
Read file into texts and calls.
It's ok if you don't understand how to read files
"""
import csv
with open('texts.csv', 'r') as f:
    reader = csv.reader(f)
    texts = list(reader)

with open('calls.csv', 'r') as f:
    reader = csv.reader(f)
    calls = list(reader)

"""
TASK 2: Which telephone number spent the longest time on the phone
during the period? Don't forget that time spent answering a call is
also time spent on the phone.
Print a message:
"<telephone number> spent the longest time, <total time> seconds, on the phone during
September 2016.".
"""

"""
1- make a alist for all different numbers in calls list.
2- loop in diffNumbers list and iterate in the calls list if the number is found add call duration in the total duration for the number
3- iterate in the new list to pick the greatest duration.
"""
# function to collect all the caller and the called numbers in one list.
# O(2n) complexity as the executed instructions increments two unit per 1 unit increse in the input legnth
def makeNumersList(records):
    list=[]
    # gather the frist two columns on calls data in one list
    for i in records:
        list.append(i[0])
        list.append(i[1])
    return list

# Function to the number with the longest call duration in the month
# O(n^2+2n+2n+n) = O(n^2+5n) ~ O(n^2)
def searchForTheLongestDuration(calls_):
    # O(2n) complexity
    list_ = makeNumersList(calls_)
    count = 1
    durationDict = {list_[0]:0}
    # construct a dictionary for all numbers in the calls data
    # we have to iterate on the legnth of the input twice to identify if each element is counted and added to the dictionary before or not.
    # O(n^2) complexity
    for i in range (1,len(list_)):
        for j in range(0,i+1):
            if (list_[i]==list_[j]):
                break;
        if (i == j ):
            count +=1
            durationDict[list_[i]] = 0
    # iterate ont the constructed dictionary to fill the duration for each number
    # considering the worst case the complexity would be up to the total legnth of the input(n) :
    # O(n) complexity
    for key in durationDict:
        for i in calls :
            if i[0] == key or i[1] == key :
                durationDict[key] += int(i[3])
    # get The longest duration
    # O(2n) ~ O (n) complexity
    longestDuration = durationDict[list_[0]]
    longestKey = list_[0]
    for key in durationDict:
        if durationDict[key] > longestDuration:
            longestDuration = durationDict[key]
            longestKey = key
    return longestKey , durationDict[longestKey]

# Function to get the longest duration number and print it in the required format .
def printTheLongestDuration(calls_):
    key , duration = searchForTheLongestDuration(calls_)
    print (key , " spent the longest time, ",duration, "seconds, on the phone during September 2016.")

printTheLongestDuration(calls)


from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, IntegerField, SelectField
from wtforms.validators import ValidationError, DataRequired, Email, EqualTo, InputRequired
from app.model.seed import Seed
# this is for the admin to use in which we add to the database
class SeedForm(FlaskForm):
    seedname = StringField('Seed Name', validators=[DataRequired()])
    seed_type = StringField('Seed Type', validators=[DataRequired()])
    price = IntegerField('Price', validators=[DataRequired()])
    quantity = IntegerField('Quantity', validators=[DataRequired()])
    submit = SubmitField('Register')

    def validate_seedname(self, seedname):
        seed = Seed.query.filter_by(name=seedname.data).first()
        if seed is not None:
            raise ValidationError('Please use a different seed name.')

class SeedUpdate(FlaskForm):
    seedname = SelectField('Seed Name', coerce=int, validators=[DataRequired()])
    quantity = IntegerField('Quantity', validators=[DataRequired()])
    submit = SubmitField('Update')

class SeedDelete(FlaskForm):
    seedname = SelectField('Seed Name', coerce=int, validators=[DataRequired()])
    submit = SubmitField('Delete')


import matplotlib.pyplot as plt
import numpy as np
from collections import deque

class Plotter(object):
    def __init__(self, fig_num=0, capacity=20000, save_path='./figure/v1',
                 show_figure=False, interval=100, episodes=100):
        self.fig_num = fig_num
        self.x = deque(iterable=[], maxlen=capacity)
        self.t = deque(iterable=[], maxlen=capacity)
        self.show_figure = show_figure
        self.t_now = 0
        self.interval = interval
        self.episodes = episodes
        self.title_text = 'Average Reward on {interval} Steps'.format(interval=self.episodes)
        self.save_path = save_path
        return

    def plot(self, x):
        plt.figure(self.fig_num)
        self.x.append(x)
        self.t.append(self.t_now)
        self.t_now += self.interval
        line_1, = plt.plot(self.t, self.x, label='line_0')
        plt.legend(handles=[line_1])
        plt.xlabel('Step')
        plt.ylabel('Reward')
        plt.title(self.title_text)
        plt.savefig(self.save_path)
        plt.close(self.fig_num)
        return


from typing import List
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from fastapi import FastAPI ,Depends , status , HTTPException, APIRouter, Body
from server.model.main import UnitBase, Unit, User, UnitCreate, UnitUpdate, PropositionBase, Proposition, PropositionCreate, Uservote, Propositioncomment, PropositioncommentCreate
from server.db import init_db, get_session
from server.auth.token import get_current_servicenumber, get_current_user

router = APIRouter()

@router.post("/{proposal_id}")
async def add_proposition_comment(proposal_id: int, prop: PropositioncommentCreate, session: AsyncSession = Depends(get_session), service_number: str = Depends(get_current_user)):
    # Check proposal writer's unit == commenter's unit
    query_proposal = select(Proposition).where(Proposition.proposal_id == proposal_id)
    exc_proposal = await session.execute(query_proposal)
    result_proposal = exc_proposal.scalars().one()
    proposal_writer = result_proposal.writer
    query_writer = select(User).where(User.service_number == proposal_writer)
    exc_writer = await session.execute(query_writer)
    result_writer = exc_writer.scalars().one()
    writer_unit = result_writer.unit_id
    commenter = await session.get(User, service_number)
    commenter_unit = commenter.unit_id
    if writer_unit != commenter_unit:
        raise HTTPException(
            status_code=404,
            detail="Logic_Error : Current user can't add comment to this proposal. Please contact Backend Developer !"
        )
    else:
        comment = Propositioncomment(commenter = service_number, proposal_id = proposal_id, contents = prop.contents)
        session.add(comment)
        await session.commit()
        await session.refresh(comment)

    return comment

@router.get("/{proposal_id}")
async def get_all_proposal_comment(proposal_id: int, session: AsyncSession = Depends(get_session)):
    result = []
    dp = {}
    query_comment = select(Propositioncomment).where(Propositioncomment.proposal_id == proposal_id)
    exc_comment = await session.execute(query_comment)
    result_query = exc_comment.scalars().all()
    if not result_query:
        raise HTTPException(
            status_code=404,
            detail="There is No exist comment in this proposal"
        )

    # mapping result
    for i in range(len(result_query)):
        service_number = result_query[i].commenter
        check_exist = service_number in dp
        if check_exist == False:
            commenter = await session.get(User, service_number)
            commenter_name = commenter.name
            dp[service_number] = commenter_name
            result.append(
                {
                    "commenter_service_number": service_number,
                    "commenter_name": commenter_name,
                    "contents": result_query[i].contents,
                    "proposal_id": result_query[i].proposal_id,
                    "comment_date": result_query[i].comment_date
                }
            )
        else:
            commenter_name = dp[service_number]
            result.append(
                {
                    "commenter_service_number": service_number,
                    "commenter_name": commenter_name,
                    "contents": result_query[i].contents,
                    "proposal_id": result_query[i].proposal_id,
                    "comment_date": result_query[i].comment_date
                }
            )

    return result


# -*- coding: utf-8 -*-
"""
Created on Mon Dec 16 20:29:06 2019

@author: shubham
"""

fact_no = input('Enter the no:')
fact=int(fact_no)
no=fact
if (no==0):
    print('1')
else:
    for i in range(fact-1):
        no=no-1
        fact=fact*no
    print(fact)

Basic Python case study/case/case_m3_1_7.py


#!/usr/bin/env python

"""
Abstract Region Query -- Implementation Agnostic

Binds together multiple implementations and algorithms into
common single, abstracted interface.

Classes:
- RQEnum
"""

from abc import ABCMeta, abstractmethod
from typing import Any, Type, Union

from sources.core import RegionSet

class RQEnum(metaclass=ABCMeta):
  """
  Abstract Static Class

  Binds together multiple implementations and algorithms into
  common single, abstracted interface.

  Class Attributes:
    algorithms:
      The mapping of algorithm names to
      algorithm implementation classes.
  """
  algorithms = {}

  @classmethod
  def get(cls, alg: str, *args, **kwargs):
    """
    Retrieves and returns the specified algorithm with given name.
    Returns the algorithm's implementation class.
    If additional arguments are given, passes the arguments to the prepare
    class method of the algorithm's implementation class, and returns the
    evaluator function for evaluating the query instead.

    Args:
      alg:
        The name of the algorithm to retrieve.
      args, kwargs:
        Additional arguments to be passed to the
        'prepare' class method of the algorithm's
        implementation class.

    Returns:
      The algorithm's implementation class, or
      a function to evaluate the algorithm and
      compute the resulting value.
    """
    assert alg in cls.algorithms
    algorithm = cls.algorithms[alg]
    assert callable(getattr(algorithm, 'prepare'))

    return algorithm if len(args) + len(kwargs) == 0 \
                     else algorithm.prepare(*args, **kwargs)

  @classmethod
  def results(cls, alg: str, ctx: Any, *args, **kwargs) -> RegionSet:
    """
    Compute and return the results of the query with the specified
    algorithm with the given context object (must have the 'dimension'
    attribute).

    Args:
      alg:
        The name of the algorithm to retrieve.
      ctx:
        The context object.
      args, kwargs:
        Additional arguments to be passed to the
        'prepare' class method of the algorithm's
        implementation class.

    Returns:
      The resulting values for the query evaluation.
    """
    assert alg in cls.algorithms
    assert ctx is not None and hasattr(ctx, 'dimension')

    results = RegionSet(dimension=ctx.dimension)
    enumerator = cls.get(alg, ctx, *args, **kwargs)
    for region, _ in enumerator():
      results.add(region)

    return results