# ***********************************************************************
# Import libraries
# ***********************************************************************

import sys
import os
import dill
import pickle as pk
import numpy as np
import pandas as pd
import scipy as sp

sys.path.append( os.path.abspath( '../' ) )

from mfd.ecoMfd import EcoMfdConst as EcoMfd

from utl.utils import getLogger

# ***********************************************************************
# Some definitions
# ***********************************************************************

DIAG_FLAG = True
SREL_FLAG = True

# ***********************************************************************
# Class MfdMod: Model object that builds a manifold based model
# ***********************************************************************

class MfdMod:

    def __init__(   self,
                    dfFile,
                    minTrnDate,
                    maxTrnDate,
                    maxOosDate,
                    velNames,
                    stepSize     = None,
                    optType      = 'SLSQP',
                    maxOptItrs   = 100,
                    optGTol      = 1.0e-4,
                    optFTol      = 1.0e-8,
                    factor       = 4.0e-5,
                    regCoef      = None,
                    minMerit     = 0.0,
                    minTrend     = 0.0,
                    maxBias      = 1.0,
                    varFiltFlag  = False,
                    validFlag    = False,
                    selParams    = None,
                    smoothCount  = None,
                    srcTerm      = None,
                    atnFct       = 1.0,
                    mode         = 'intraday',
                    logFileName  = None,
                    verbose      = 1          ):

        self.dfFile      = dfFile
        self.minTrnDate  = minTrnDate
        self.maxTrnDate  = maxTrnDate
        self.maxOosDate  = maxOosDate
        self.stepSize    = stepSize
        self.optType     = optType
        self.maxOptItrs  = maxOptItrs
        self.optGTol     = optGTol
        self.optFTol     = optFTol
        self.minMerit    = minMerit
        self.minTrend    = minTrend
        self.maxBias     = maxBias
        self.varFiltFlag = varFiltFlag
        self.validFlag   = validFlag
        self.srcTerm     = srcTerm
        self.mode        = mode
        self.ecoMfd      = None
        self.trmFuncDict = {}
        self.logFileName = logFileName
        self.verbose     = verbose
        self.logger      = getLogger( logFileName, verbose, 'mod' )
        self.converged   = False

        if regCoef is None:
            self.regCoef    = 0.0
            self.optRegFlag = True
        else:
            self.regCoef    = regCoef
            self.optRegFlag = False

        self.factor   = factor

        assert atnFct >= 0, 'atnFct should be positive!'
        assert atnFct <= 1.0, 'atnFct should be less than or equal to 1.0!'

        self.atnFct = atnFct

        if selParams is None:
            self.velNames = velNames
        else:
            self.velNames = self.selVels( velNames, selParams )

        self.varNames = self.getVarNames()

        if smoothCount is not None :
            for velName in self.velNames:
                self.trmFuncDict[ velName ] = lambda x : x.rolling( int( smoothCount ),
                                                                    win_type = 'blackman',
                                                                    center   = True ).mean()

    def getVarNames( self ):

        varNames = []

        for velName in self.velNames:

            tmpList = velName.split( '_' )

            if tmpList[-1] == 'Diff':
                varName = '_'.join( tmpList[:-1] )
            else:
                varName = velName + '_Cumul'

            varNames.append( varName )

        return varNames

    def selVels( self, candVelNames, selParams ):

        assert isinstance( selParams, dict ), \
            'selParams should be of dict type!'

        assert 'inVelNames' in selParams.keys(), \
            'inVarNames should be set in selParams!'

        assert 'maxNumVars' in selParams.keys(), \
            'maxNumVars should be set in selParams!'

        assert 'minImprov' in selParams.keys(), \
            'minImprov should be set in selParams!'

        assert 'strategy' in selParams.keys(), \
            'strategy should be set in selParams!'

        inVelNames = selParams[ 'inVelNames' ]
        maxNumVars = selParams[ 'maxNumVars' ]
        minImprov  = selParams[ 'minImprov' ]
        strategy   = selParams[ 'strategy' ]

        assert set( inVelNames ).issubset( set( candVelNames ) ),\
            'inVelNames should be a subset of candVelNames!'

        assert maxNumVars <= len( candVelNames ), \
            'maxNumVars should be less than or equal to number of candVelNames!'

        assert maxNumVars >= len( inVelNames ), \
            'maxNumVars should be greater than or equal to number of inVelNames!'

        if strategy == 'forward':
            velNames = self.selVelsFwd( candVelNames, selParams )
        else:
            assert False, 'Unknown strategy %s!' % strategy

        return velNames

    def selVelsFwd( self, candVelNames, selParams ):

        inVelNames = selParams[ 'inVelNames' ]
        maxNumVars = selParams[ 'maxNumVars' ]
        minImprov  = selParams[ 'minImprov' ]
        strategy   = selParams[ 'strategy' ]

        if maxNumVars == len( inVelNames ):
            return inVelNames

        sortDict   = {}
        for velName in candVelNames:

            if velName in inVelNames:
                continue

            self.velNames = inVelNames + [ velName ]
            self.varNames = self.getVarNames()

            sFlag  = self.setMfd()

            if not sFlag:
                continue

            sortDict[ velName ] = self.ecoMfd.getError()

        sVelNames = sortDict.keys()

        assert len( sVelNames ) > 0, 'Unsuccessful variable selection!'

        sVelNames = sorted( sVelNames, key = lambda y : sortDict[y] )
        velNames  = inVelNames.copy()
        error     = np.inf
        cnt       = 0

        for velName in sVelNames:

            self.velNames = velNames + [ velName ]
            self.varNames = self.getVarNames()

            sFlag  = self.setMfd()

            if not sFlag:
                continue

            newError = self.ecoMfd.getError()

            if error - newError >= minImprov:
                velNames.append( velName )
                error = newError
                cnt += 1
                self.logger.info( 'Added %s ; error = %0.4f', velName, error )
            else:
                self.logger.info( '%s was not added!', velName )

            if cnt == maxNumVars:
                break

        assert len( velNames ) > 0, 'Unsuccessful variable selection!'

        self.logger.info( 'Selected:', velNames )
        self.logger.info( list( set( velNames ) - set( inVelNames ) ), 'were added!' )

        return velNames

    def build( self ):

        self.logger.info( 'Building a manifold...' )

        sFlag  = self.setMfd()

        self.echoMod()

        if not sFlag:
            self.converged = sFlag
            return False

        if self.varFiltFlag:
            dropFlag = self.filtVars()
            if dropFlag:
                sFlag = self.setMfd()

                self.echoMod()

                if not sFlag:
                    self.converged = sFlag
                    return False

        if self.optRegFlag:
            self.regCoef = self.optReg()
            sFlag = self.setMfd()

            self.echoMod()

            if not sFlag:
                self.converged = sFlag
                return False

        if self.validFlag:
            sFlag = self.validate()

            if not sFlag:
                self.converged = sFlag
                return False

        ecoMfd = self.ecoMfd
        merit  = ecoMfd.getMerit()
        merit  = min( merit, ecoMfd.getOosMerit() )
        trend  = ecoMfd.getOosTrendCnt()
        nDims  = ecoMfd.nDims
        bias   = 0

        for varId in range( nDims ):
            bias = max( bias, ecoMfd.getRelBias( varId ) )

        if merit < self.minMerit:
            self.logger.warning( 'Merit does not meet criteria!' )
            sFlag = False

        if trend < self.minTrend:
            self.logger.warning( 'Trend does not need criteria!' )
            sFlag = False

        if bias > self.maxBias:
            self.logger.warning( 'Bias does not meet criteria' )
            sFlag = False

        if not sFlag:
            self.converged = sFlag
            return False

        self.converged = True

        return True

    def setMfd( self ):

        self.ecoMfd = EcoMfd( varNames     = self.varNames,
                              velNames     = self.velNames,
                              dateName     = 'Date',
                              dfFile       = self.dfFile,
                              minTrnDate   = self.minTrnDate,
                              maxTrnDate   = self.maxTrnDate,
                              maxOosDate   = self.maxOosDate,
                              trmFuncDict  = self.trmFuncDict,
                              optType      = self.optType,
                              maxOptItrs   = self.maxOptItrs,
                              optGTol      = self.optGTol,
                              optFTol      = self.optFTol,
                              stepSize     = self.stepSize,
                              factor       = self.factor,
                              regCoef      = self.regCoef,
                              regL1Wt      = 0.0,
                              nPca         = None,
                              diagFlag     = DIAG_FLAG,
                              srelFlag     = SREL_FLAG,
                              endBcFlag    = True,
                              srcTerm      = self.srcTerm,
                              atnFct       = self.atnFct,
                              mode         = self.mode,
                              logFileName  = self.logFileName,
                              verbose      = self.verbose        )

        sFlag = self.ecoMfd.setParams()

        if not sFlag:
            self.logger.warning( 'Did not converge!' )

        return sFlag

    def save( self, outModFile ):

        with open( outModFile, 'wb' ) as fHd:
            dill.dump( self, fHd, pk.HIGHEST_PROTOCOL )

    def echoMod( self ):

        ecoMfd  = self.ecoMfd
        nDims   = ecoMfd.nDims

        self.logger.info( 'Manifold Error    : %0.6f', ecoMfd.getError() )
        self.logger.info( 'Manifold oos Error: %0.6f', ecoMfd.getOosError() )
        self.logger.info( 'Manifold oos velocity trend match: %0.6f', ecoMfd.getOosTrendCnt( 'vel' ) )

        self.logger.info( '\n' + str( ecoMfd.getTimeDf() ) )

    def filtVars( self ):

        if not self.varFiltFlag:
            return

        ecoMfd      = self.ecoMfd
        varNames    = self.varNames
        velNames    = self.velNames
        newVarNames = []
        newVelNames = []
        dropFlag    = False
        for varId in range( ecoMfd.nDims ):

            varName = varNames[varId]
            velName = velNames[varId]
            merit   = ecoMfd.getMerit( [ varName ] )
            bias    = ecoMfd.getRelBias( varId )

            if merit < self.minMerit:
                dropFlag = True
                continue

            if bias > self.maxBias:
                dropFlag = True
                continue

            newVarNames.append( varName )
            newVelNames.append( velName )

        self.varNames = newVarNames
        self.velNames = newVelNames

        return dropFlag

    def crossVal( self,
                  minYrs,
                  incYrs,
                  regCoef = 0.0   ):

        minDt     = pd.to_datetime( self.minTrnDate )
        maxDt     = pd.to_datetime( self.maxTrnDate )
        maxOosDt  = pd.to_datetime( self.maxOosDate )

        if 2 * incYrs > ( maxDt.year - minDt.year ):
            self.logger.warning( 'Increment is too small! No cross validation done!' )
            return None

        if 3 * incYrs > ( maxOosDt.year - minDt.year ):
            self.logger.warning( 'Increment is too small! No cross validation done!' )
            return None

        maxDt    = minDt + pd.DateOffset( years = int( minYrs ) )

        maxMaxDt = pd.to_datetime( self.maxOosDate ) -\
                   pd.DateOffset( years = incYrs )
        maxMaxDt = min( maxMaxDt, pd.to_datetime( self.maxTrnDate ) )

        maxTrnDates = []
        while maxDt <= maxMaxDt:
            maxTrnDates.append( maxDt.strftime( '%Y-%m-%d' ) )
            maxDt = maxDt + pd.DateOffset( years = int( incYrs ) )

        ecoMfds = []
        for maxTrnDate in maxTrnDates:

            maxOosDt   = pd.to_datetime( maxTrnDate ) +\
                         pd.DateOffset( years = incYrs )

            maxOosDate = maxOosDt.strftime( '%Y-%m-%d' )

            ecoMfd     = EcoMfd( varNames     = self.varNames,
                                 velNames     = self.velNames,
                                 dateName     = 'Date',
                                 dfFile       = self.dfFile,
                                 minTrnDate   = self.minTrnDate,
                                 maxTrnDate   = maxTrnDate,
                                 maxOosDate   = maxOosDate,
                                 trmFuncDict  = self.trmFuncDict,
                                 optType      = self.optType,
                                 maxOptItrs   = self.maxOptItrs,
                                 optGTol      = self.optGTol,
                                 optFTol      = self.optFTol,
                                 stepSize     = self.stepSize,
                                 factor       = self.factor,
                                 regCoef      = regCoef,
                                 regL1Wt      = 0.0,
                                 nPca         = None,
                                 diagFlag     = DIAG_FLAG,
                                 srelFlag     = SREL_FLAG,
                                 endBcFlag    = True,
                                 srcTerm      = self.srcTerm,
                                 atnFct       = self.atnFct,
                                 mode         = self.mode,
                                 logFileName  = self.logFileName,
                                 verbose      = self.verbose        )

            ecoMfds.append( ecoMfd )

        return ecoMfds

    def optReg( self ):

        if not self.optRegFlag:
            return

        self.logger.info( 'Running optimization for regularization coefficient!' )

        options    = {    'disp'       : False,
                          'gtol'       : 1e-05,
                          'eps'        : 1e-03,
                          'return_all' : False,
                          'maxiter'    : 200,
                          'norm'       : np.inf         }

        res  = sp.optimize.minimize( self.optRegFunc,
                                     x0      = 0.0,
                                     method  = 'CG',
                                     options = options   )
        self.logger.info( res )
        self.logger.info( res[ 'x' ] )

        return res[ 'x' ]

    def optRegFunc( self, regCoef ):

        minDt   = pd.to_datetime( self.minTrnDate )
        maxDt   = pd.to_datetime( self.maxTrnDate )
        minYrs  = int( ( maxDt.year - minDt.year ) / 2.0 )
        incYrs  = 1.0
        val     = 0.0

        ecoMfds = self.crossVal( minYrs  = minYrs,
                                 incYrs  = incYrs,
                                 regCoef = regCoef )

        for ecoMfd in ecoMfds:
            val += ecoMfd.getOosMerit()

        fct = len( ecoMfds )
        if fct > 0:
            fct = 1.0 / fct

        val *= fct

        return val

    def validate( self ):

        validFlag = True

        oosMeritAvg = self.optRegFunc( self.regCoef )

        self.logger.info( 'Average OOS merit:', oosMeritAvg )

        validFlag = validFlag & (oosMeritAvg >= self.minMerit)

        return validFlag


import requests
import json
import logging
import time

logging.basicConfig(
    filename="server.log",
    filemode='a',
    level=logging.INFO,
    format='{levelname} {asctime} {name} : {message}',
    style='{'
)
log = logging.getLogger(__name__)

def main(url):
    while True:
        try:
            r = requests.get(url)
            data = json.loads(r.content)
            for key in data.keys():
                logging.info("Ключ: %s, Значення: %s", key, data[key])
        except requests.exceptions.ConnectionError as err:
            logging.error("Server is not available (" + str(err) + ")")
        if '--once' in sys.argv:
            break
        time.sleep(60)

if __name__ == '__main__':
    main("http://localhost:8000/health")


__author__ = "ResearchInMotion"

class Node:
    def __init__(self,data):
        self.data = data
        self.next = None

class LinkedList:

    def __init__(self):
        self.head = None

    def insert(self,newNode):
        if self.head is None:
            self.head = newNode
        else:
            lastNode = self.head
            while True:
                if lastNode.next is None:
                    break
                lastNode = lastNode.next
            lastNode.next = newNode

    def printList(self):
        if self.head is None:
            print("List is Empty")
            return

        currentNode = self.head
        while True:
            if currentNode is None:
                break
            print(currentNode.data)
            currentNode = currentNode.next

firstNode = Node("Sahil")
linkedList = LinkedList()
linkedList.insert(firstNode)
secondNode = Node("Nikki")
linkedList.insert(secondNode)
thirdNode = Node("Manju")
linkedList.insert(thirdNode)
fourthNode = Node("Vimal")
linkedList.insert(fourthNode)
linkedList.printList()


# for figure 3 in the paper: binary classification
import numpy as np
import matplotlib.pyplot as plt
import sys
sys.path.append("/home/fwq/PycharmProjects/my_code_cpu/invgp")
from kernels.image_transforms import rotate_img_angles, rotate_img_angles_stn
import tensorflow as tf
import gpflow
np.random.seed(1234)
tf.random.set_seed(1234)

def all_data(path="/home/fwq/PycharmProjects/my_code/RMT4ML-master/datasets/mnist.npz"):
	# prepare the data
	mnist_data = np.load(path, allow_pickle=True)
	train_X = mnist_data['x_train']   # (60000, 28, 28)
	train_Y = mnist_data['y_train']   # (60000, )
	test_X = mnist_data['x_test']     # (10000, 28, 28)
	test_Y = mnist_data['y_test']
	# a, b = train_X.max(), test_X.max()
	# print(a, b)
	# train_X = train_X/a
	# test_X = test_X/b
	N = np.shape(train_X)[0]
	# print("before permutation: ", train_X[:1], train_Y[:10])
	index = np.random.permutation(N)
	train_X = train_X[index]
	train_Y = train_Y[index]
	# print("after permutation: ", train_X[:1], train_Y[:10])
	return train_X, train_Y.reshape((-1, 1)), test_X, test_Y.reshape((-1, 1))

def transform_data(X, Y):
	row, _, _ = np.shape(X)
	after_transform = np.ones((row, 784))  # (60000, 784)
	alpha = 90.0 # or 180
	for i in range(row):
		angle = - alpha + 2*alpha*np.random.random()
		# angle = [alpha, -alpha][np.random.randint(0, 2)]
		after_transform[i] = rotate_img_angles(tf.expand_dims(X[i], axis=0), np.array([angle]),
		                                   "nearest").numpy().reshape(-1, 784)
	mean = np.mean(after_transform, axis=0)
	std = np.std(after_transform, axis=0)
	std[std == 0] = 1.0
	after_transform = (after_transform - mean)/std
	return after_transform, Y

def filter_01(X, Y, c1, c2):
	lbls01 = np.logical_or(Y == c1, Y == c2).flatten()
	return X[lbls01, :], Y[lbls01]

def odd_vs_even(X, Y, c1, c2):
	lbls01 = np.logical_or(Y % 2 == c1, Y % 2 == c2).flatten()
	return X[lbls01, :], Y[lbls01]

# print("====================before transform======================")
# train_X, train_Y, test_X, test_Y = all_data()
# print(np.shape(train_X), np.shape(train_Y))
# print(np.shape(test_X), np.shape(test_Y))
# print(np.unique(train_Y), np.unique(test_Y))
# print(train_Y[0], test_Y[0])
# plt.figure(1)
# plt.imshow(train_X[0], cmap='gray')
# plt.figure(2)
# plt.imshow(test_X[0], cmap='gray')
# # plt.show()
#
#
# print("===================after transform====================")
# train_X, train_Y = transform_data(train_X, train_Y)
# test_X, test_Y = transform_data(test_X, test_Y)
# print(np.shape(train_X), np.shape(train_Y))
# print(np.shape(test_X), np.shape(test_Y))
# print(np.unique(train_Y), np.unique(test_Y))
# print(train_Y[0], test_Y[0])
# plt.figure(3)
# plt.imshow(train_X[0].reshape((28, 28)), cmap='gray')
# plt.figure(4)
# plt.imshow(test_X[0].reshape((28, 28)), cmap='gray')
# # plt.show()
#
# print("===================after filter====================")
# c1 = 1; c2 = 0
# train_X, train_Y = filter_01(train_X, train_Y, c1, c2)
# test_X, test_Y = filter_01(test_X, test_Y,  c1, c2)
# train_Y = tf.cast(train_Y == c1, dtype=gpflow.config.default_float())
# test_Y = tf.cast(test_Y == c1, dtype=gpflow.config.default_float())
# print(np.shape(train_X), np.shape(train_Y))
# print(np.shape(test_X), np.shape(test_Y))
# print(np.unique(train_Y), np.unique(test_Y))
# print(train_Y[0], test_Y[0])
# plt.figure(5)
# plt.imshow(train_X[0].reshape((28, 28)), cmap='gray')
# plt.figure(6)
# plt.imshow(test_X[0].reshape((28, 28)), cmap='gray')
# plt.show()


import pandas as pd
from ortools.linear_solver import pywraplp

from main.models import Rule

class NBO:

    def __init__(self, ids, limits, phone_cost, sms_cost, email_cost,
                 phone_percent, sms_percent, email_percent,
                 calls_limit, budget, cheque_up, min, sale):

        flag = False
        while not flag:
            try:
                f = open(r'C:\Users\li.iskhakova\PycharmProjects\ClientAnalytics\media\СводнаяТаблица.csv')
                flag = True
                f.close()
            except IOError:
                print("File not accessible")

        pivot = pd.read_csv(r'C:\Users\li.iskhakova\PycharmProjects\ClientAnalytics\media\СводнаяТаблица.csv',
                            index_col=0)
        rules = Rule.objects.filter(id__in=ids)

        clusters = rules.values('cluster_class').distinct()
        clusters = list(clusters.values_list('cluster_class', flat=True))

        print(clusters)

        df_result = pd.DataFrame(index=pivot.index)

        # для каждого правила необходимо составить рейтинг
        for cluster in clusters:

            for rule_name in rules.filter(cluster_class=cluster):
                left = rule_name.left
                right = rule_name.right
                confidence = rule_name.confidence

                df_result[rule_name.__str__()] = pivot[pivot.columns[2]] * pivot[left] * confidence \
                                                 * pivot[right].apply(
                    lambda x: 0 if x > 0 else 1) * pivot[pivot.columns[0]].apply(
                    lambda x: 1 if str(x) == cluster else 0)

        mean_cluster_cheque = pivot[pivot.columns[:2]].groupby(pivot.columns[0]).mean()
        mean_cluster_cheque.columns = ['cheque']

        df_result.to_excel(r'./media/Ratings.xlsx', index=True)
        dict_rule_customers = self.analyse(df_result, limits, rules, pivot)

        # определяем вид коммуникации

        max_calls_per_rule = int(int(calls_limit) / len(rules))

        rules_final = []

        for rule in rules:
            r_final = Rule_Final(name=rule.__str__(),
                                 cluster=rule.cluster_class,
                                 left=rule.left,
                                 right=rule.right,
                                 confidence=rule.confidence,
                                 phone_cost=phone_cost,
                                 sms_cost=sms_cost,
                                 email_cost=email_cost,
                                 phone_percent=phone_percent,
                                 sms_percent=float(sms_percent) * 0.01,
                                 email_percent=float(email_percent) * 0.01,
                                 max_calls=max_calls_per_rule,
                                 budget=float(budget) / len(rules),
                                 cheque=mean_cluster_cheque.loc[int(rule.cluster_class)]['cheque'],
                                 cheque_up=cheque_up,
                                 min=min,
                                 sale=sale,
                                 customers=dict_rule_customers[rule.__str__()])
            rules_final.append(r_final)

        self.save(rules_final)

        total_costs = sum([rule.total_cost for rule in rules_final])
        total_revenue = sum([rule.total_revenue for rule in rules_final])

        self.rules_final = rules_final
        self.clusters = clusters
        self.total_cost = round(total_costs, 2)
        self.revenue = round(total_revenue, 2)

    def analyse(self, df, limits, rules, pivot):
        costs = df.to_numpy()
        print(len(costs))
        print(len(costs[0]))
        num_workers = len(costs)
        num_tasks = len(costs[0])

        # Solver
        # Create the mip solver with the SCIP backend.
        solver = pywraplp.Solver.CreateSolver('SCIP')

        dict_result = {}
        for rule in rules:
            dict_result[rule.__str__()] = []

        x = {}
        for i in range(num_workers):
            for j in range(num_tasks):
                x[i, j] = solver.IntVar(0, 1, '')

        # Ограничение на кол-во акций на человека
        for i in range(num_workers):
            solver.Add(solver.Sum([x[i, j] for j in range(num_tasks)]) <= 1)

        for j in range(num_tasks):
            solver.Add(solver.Sum([x[i, j] for i in range(num_workers)]) <= int(limits[j]))

        # Objective
        objective_terms = []
        for i in range(num_workers):
            for j in range(num_tasks):
                objective_terms.append(costs[i][j] * x[i, j])

        solver.Maximize(solver.Sum(objective_terms))

        # Solve
        status = solver.Solve()

        # Print solution.
        if status == pywraplp.Solver.OPTIMAL or status == pywraplp.Solver.FEASIBLE:
            print('Total cost = ', solver.Objective().Value(), '\n')
            for i in range(num_workers):
                for j in range(num_tasks):
                    # Test if x[i,j] is 1 (with tolerance for floating point arithmetic).
                    if x[i, j].solution_value() > 0.5:
                        # print('Customer %d assigned to offer %d.  Rating = %f' %
                        #       (i, j + 1, costs[i][j]))
                        contacts = dict_result[rules[j].__str__()]
                        contacts.append(Customer(pivot.index[i], costs[i][j], rules[j].__str__()))
                        dict_result[rules[j].__str__()] = contacts

        for k, v in dict_result.items():
            dict_result[k] = sorted(v, key=lambda customer: customer.rating, reverse=True)

        for k, v in dict_result.items():
            for customer in v:
                print(customer)

        return dict_result
        # pd.DataFrame(dict([(k, pd.Series(v)) for k, v in dict_result.items()])) \
        #     .to_excel('./media/Контакты.xlsx')

    def save(self, rules):
        rule = rules[0]
        print(rule)
        df = pd.DataFrame.from_records([c.to_dict() for c in rule.customers])
        print(rule.__str__()[:30])
        i = 1
        df.to_excel('media/Контакты.xlsx', sheet_name=f'правило{i}', index=False)

        for rule in rules[1:]:
            i = i +1
            print(rule)
            df = pd.DataFrame.from_records([c.to_dict() for c in rule.customers])

            with pd.ExcelWriter('media/Контакты.xlsx', engine='openpyxl', mode='a') as writer:
                df.to_excel(writer, sheet_name=f'{rule.__str__()[:30]}', index=False)

def calculate_numbers(phone_max, phone_cost, sms_cost, email_cost, budget, people, email_percent,
                      sms_percent):
    solver = pywraplp.Solver.CreateSolver('SCIP')

    infinity = solver.infinity()
    # x and y are integer non-negative variables.
    phone_number = solver.IntVar(0.0, infinity, 'phone_number')
    sms_number = solver.IntVar(0.0, infinity, 'sms_number')
    email_number = solver.IntVar(0.0, infinity, 'email_number')

    solver.Add(phone_number <= phone_max)
    solver.Add(phone_cost * phone_number + sms_cost * sms_number + email_cost * email_number <= budget)
    solver.Add(phone_number + sms_number + email_number == people)
    solver.Add(email_number >= people * email_percent)
    solver.Add(sms_number >= (sms_percent / email_percent) * email_number)

    print('Number of constraints =', solver.NumConstraints())

    solver.Maximize(phone_number)
    status = solver.Solve()

    x, y, z = 0, 0, 0

    if status == pywraplp.Solver.OPTIMAL:
        print('Solution:')
        print('Objective value =', solver.Objective().Value())
        print('x =', phone_number.solution_value())
        print('y =', sms_number.solution_value())
        print('z =', email_number.solution_value())
        print(
            phone_cost * phone_number.solution_value() + sms_cost * sms_number.solution_value() + email_cost * email_number.solution_value())

        x = phone_number.solution_value()
        y = sms_number.solution_value()
        z = email_number.solution_value()
    else:

        print('The problem does not have an optimal solution.')

    return x, y, z

class Customer(object):
    def __init__(self, id_param, rating, rule):
        self.id = id_param
        self.rating = rating
        self.rule = rule
        self.contact_type = None

    def set_contact_type(self, contact_type):
        self.contact_type = contact_type

    def __str__(self):
        return f"{self.id} {self.rating}"

    def __hash__(self):
        return self.id

    def to_dict(self):
        return {
            'id': self.id,
            'rating': self.rating,
            'rule': self.rule,
            'contact_type': self.contact_type
        }

class Rule_Final(object):
    def __init__(self, name, cluster, left, right, confidence, phone_cost, sms_cost, email_cost,
                 phone_percent, sms_percent, email_percent,
                 max_calls, budget, cheque, cheque_up, min, sale, customers):
        self.cluster = cluster
        self.name = name
        self.left = left
        self.right = right
        self.confidence = float(confidence)
        self.phone_cost = float(phone_cost)
        self.sms_cost = float(sms_cost)
        self.email_cost = float(email_cost)
        self.phone_percent = float(phone_percent)
        self.sms_percent = float(sms_percent)
        self.email_percent = float(email_percent)
        self.budget = float(budget)
        self.cheque_up = float(cheque_up)
        self.min = float(min)
        self.sale = int(sale)
        self.cheque = float(cheque)
        self.customers = customers

        self.phone_total_cost = None
        self.sms_total_cost = None
        self.email_total_cost = None
        self.total_cost = None
        self.total_revenue = None

        self.set_contact_type_to_customers(max_calls)

    def __str__(self):

        return f"{self.cluster} {self.left} -> {self.right} " \
               f"чек: {self.cheque} cost: {self.total_cost} revenue:{self.total_revenue} "

    def calls_limit(self, max_calls):
        temp = int(len(self.customers) * self.phone_percent)
        return min(max_calls, temp)

    def set_contact_type_to_customers(self, max_calls):
        total_customers_number = len(self.customers)

        phone_number = self.calls_limit(max_calls)

        x, y, z = calculate_numbers(phone_max=phone_number,
                                    phone_cost=self.phone_cost,
                                    sms_cost=self.sms_cost,
                                    email_cost=self.email_cost,
                                    budget=self.budget,
                                    people=len(self.customers),
                                    email_percent=self.email_percent,
                                    sms_percent=self.sms_percent)

        self.phone_number = int(x)
        self.sms_number = int(y)
        self.email_number = int(z)

        self.phone_total_cost = round(phone_number * self.phone_cost,2)
        self.sms_total_cost = round(self.sms_number * self.sms_cost,2)
        self.email_total_cost = round(self.email_number * self.email_cost,2)

        self.total_cost = self.phone_total_cost + self.sms_total_cost + self.email_total_cost

        self.new_cheque = int(round((self.cheque + self.cheque_up + self.total_cost / len(
            self.customers)) / (1 - self.sale * 0.01), -2))

        self.cheque = round(self.cheque, 2)

        self.total_revenue = round(total_customers_number * self.cheque * self.min * 0.01 - self.total_cost,2)

        for c in range(0, self.phone_number):
            self.customers[c].set_contact_type('phone')

        for c in range(self.phone_number, self.phone_number + self.sms_number):
            self.customers[c].set_contact_type('sms')

        if (not (self.phone_number == 0 and self.sms_number == 0 and self.email_number == 0)):
            for c in range(self.phone_number + self.sms_number, total_customers_number):
                self.customers[c].set_contact_type('email')


#!/usr/bin/python
import os

#variavel que recebe texto digitado
texto=""
#nome do arquivo que vai receber o conteudo
nomearq=""
#var que indica a acao a ser tomada em relacao ao nomearq
gravarsn=""

#inicio do editor
os.system('clear')
print('###############################################')
os.system('figlet Che Editor')
os.system('\n')
print('###############################################')
os.system('\n')
os.system('\n')
nomearq = input("Nome do arquivo: ")
os.system('clear')
texto=""
gravarsn=""

while True:
	linha = input(" > ")
	if linha == ":q":
		break
	texto = texto + linha + "\n"
#ao sair do primeiro loop, exibe o que foi digitado

while True:
	gravarsn=input("(w) substituir arquivo atual || (a) adicionar atual\n (q) sair sem gravar\n: ")
	if gravarsn == "q":
		print("Saindo sem gravar")
		break
	if gravarsn == "w":
		#abre o arquivo e sobreescreve o conteudo
		arq = open(nomearq, "w")
		arq.write(texto)
		arq.close()
		print("Texto substituido")
		break
	if gravarsn == "a":
		#adiciona ao final do arquivo
		arq = open(nomearq, "a")
		arq.write(texto)
		arq.close()
		print("Linhas adicionadas")
		break


import math
ver = "2.1"

def prime(num):
    is_prime = True

    if num > 1:
        for i in range(2, int(math.sqrt(num))+1):
            if num % i == 0:
                is_prime = False

    if num == 2:
        return True
    else:
        return is_prime

def find():
    i = int(input("Input starting number: "))

    max_num = input('Input limit (leave empty for removing the limit): ')

    if max_num == "":
        max_num = False
    else:
        max_num = int(max_num)
    set_number = i

    print("---------------------------")

    log = open("log.txt", "a")
    log.write(f"Prime Finder - Results\nMode = Find\nSet number = {set_number}\nStarting number = {i}\nLimit = {max_num}\nVersion = {ver}\n---------------------------\n")
    count = 1

    while True:
        if i >= max_num and max_num != False:
            break
        if prime(i) == True:
            print(f"{i} - is prime - T - attempts: {count}")
            log.write(f"{i} - is prime - T - attempts: {count}\n")
        else:
            log.write(f"{i} - faild - F - attempts: {count}\n")
        i += 1
        count += 1

    log.write("\n\n")
    log.close()
    print("\nDone!")
    print('log file is located in the same folder as this app "log.txt"\n')

def check():
    ch_num = int(input("Input number: "))
    log = open("log.txt", "a")
    log.write(f"Prime Finder - Results\nMode = Check\nSet number = {ch_num}\nVersion = {ver}\n---------------------------\n")

    print("---------------------------")
    if prime(ch_num):
        print(f"{ch_num} is prime - T\n")
        log.write(f"{ch_num} is prime - T\n")
    else:
        print(f"{ch_num} is not prime- F\n")
        log.write(f"{ch_num} is not prime - F\n")

    log.write("\n\n")
    log.close()
    print("Done!")
    print('log file is located in the same folder as this app "log.txt"\n')

print(f'Prime finder {ver} - By Jan "Daxicek" Gruner')
print("---------------------------")

del_log = input("Do you want to clear the log file? (y, yes, n, no): ")
del_log.lower()
if del_log == "y" or del_log == "yes":
    log = open("log.txt", "w")
    log.write("")
    log.close()
else:
    pass

mode = input("Mode (f, find, c, check, e, exit): ")
mode.lower()
while True:
    if mode == "f" or mode == "find":
        find()
    if mode == "c" or mode == "check":
        check()
    if mode == "e" or mode == "exit":
        break

    del_log = input("Do you want to clear the log file? (y, yes, n, no): ")
    del_log.lower()
    if del_log == "y" or del_log == "yes":
        log = open("log.txt", "w")
        log.write("")
        log.close()
    else:
        pass

    mode = input("Mode (f, find, c, check, e, exit): ")
    mode.lower()


# 14503 로봇 청소기
from collections import deque
import sys
input = sys.stdin.readline

def bfs(r,c,d):
    ans = 0
    visited = [[False]*m for _ in range(n)]
    q = deque()
    q.append((r,c))

    while q:
        x,y = q.popleft()
        if not visited[x][y]:
            ans+=1
        visited[x][y] = True   # 현재 위치 청소
        cnt = 0   # 네방향 이동 가능 여부
        for i in range(4):
            d = (d-1) % 4
            nx, ny = dx[d]+x, dy[d]+y
            if not visited[nx][ny] and arr[nx][ny] == 0:
                q.append((nx,ny))
                break
            else:
                cnt += 1
            # 네 방향 모두 청소되어 있는 경우
            if cnt == 4:
                # 뒤쪽 방향이 벽인 경우
                if arr[x+dx[(d-2)%4]][y+dy[(d-2)%4]] == 1:
                    return print(ans)
                q.append((x+dx[(d-2)%4],y+dy[(d-2)%4]))
    return print(ans)

n,m = map(int,input().split())
r,c,d = map(int, input().split())
arr = [list(map(int,input().split())) for _ in range(n)]
dx,dy = (-1,0,1,0), (0,1,0,-1)   # 북:0 동:1 남:2 서:3   cnt = (cnt-1) % 4

bfs(r,c,d)


import a1
import unittest

class TestStockPriceSummary(unittest.TestCase):
    """ Test class for function a1.stock_price_summary. """

    # Add your test methods for a1.stock_price_summary here.
    def test_stock_example_1(self):
        """Test price_changes with mixed list of changes including zeros."""

        actual = stock_price_summary([0.01, 0.03, -0.02, -0.14, 0, 0, 0.10, -0.01])
        expected = (0.14, -0.17)
        self.assertEqual(expected, actual)

    def test_stock_example_2(self):
        """Test price_changes with an empty list."""

        actual = stock_price_summary([])
        expected = (0.0, 0.0)
        self.assertEqual(expected, actual)

    def test_stock_example_3(self):
        """Test price_changes with only negative numbers."""

        actual = stock_price_summary([-2])
        expected = (0.0, -2.0)
        self.assertEqual(expected, actual)

    def test_stock_example_4(self):
        """Test price_changes with only positive numbers."""

        actual = stock_price_summary([2])
        expected = (2.0, 0.0)
        self.assertEqual(expected, actual)

    def test_stock_example_5(self):
        """Test price_changes with 1 zero number."""

        actual = stock_price_summary([0])
        expected = (0.0, 0.0)
        self.assertEqual(expected, actual)

if __name__ == '__main__':
    unittest.main(exit=False)


from flask import Flask,request
from flask_cors import CORS
import json
import helperFunctionsAPI as hp

app = Flask(__name__)
CORS(app)

@app.route('/search', methods=['GET'])
def searchResult():
    song_input = request.args.get('song_name')
    artist_input = request.args.get('artist_name')
    album_input = request.args.get('album_name')

    response = hp.getDataFromQuery(song_input, artist_input, album_input)
    return json.dumps(response)

@app.route('/recommend', methods=['GET'])
def generateRecommend():
    featureVector = json.loads(request.args.get("query"))["featureVector"]
    recommendations = hp.getRecommendations(featureVector,"fromProfile",50,"")
    return json.dumps(recommendations)

@app.route('/getmp3url', methods=['GET'])
def getMP3URL():
    response = {}
    artist = request.args.get('artist')
    songInput = request.args.get('input')
    songId = request.args.get('songid')

    response["url"] = hp.getMP3URL(songInput, artist)
    response["data"] = hp.getInformationFromID(songId)

    return json.dumps(response)

@app.route('/recommendByTrack', methods=['GET'])
def recommendByTrack():
    songId = request.args.get("input")
    response = hp.getRecommendations([], "fromTrackID", 15, songId)
    return json.dumps(response)

if __name__ == "__main__":
    app.run(host='0.0.0.0')


import unittest
from datetime import datetime

import sys
sys.path.append('/Users/hungwanping/Documents/GitHub/forage-lyft-project')

from battery.spindler_battery import SplindlerBattery

class TestSpindlerBattery(unittest.TestCase):
    def test_needs_serviced(self):
        current_date = datetime.today().date()
        last_service_date = current_date.replace(
            year = current_date.year - 4)
        battery = SplindlerBattery(current_date, last_service_date)
        self.assertTrue(battery.needs_service())

    def test_no_need_serviced(self):
        current_date = datetime.today().date()
        last_service_date = current_date.replace(
            year = current_date.year - 2)
        battery = SplindlerBattery(current_date, last_service_date)
        self.assertFalse(battery.needs_service())

if __name__ == '__main__':
    unittest.main()


from num2words import num2words
from .name_patterns import number_patterns
import random

def digits(num):
    return len(str(num))

def reverse(num):
    return str(num)[::-1]

def even(num):
    return 'Yes' if num % 2 == 0 else 'No'

def odd(num):
    return 'Yes' if num % 2 != 0 else 'No'

def prime(num):
    c = 0
    for i in range(1,num+1):
        if num % i == 0:
            c+=1
    return 'Yes' if c == 2 else 'No'

def armstrong(num):
    num_str = str(num)
    num_digits = len(num_str)
    sum_of_powers = sum(int(digit) ** num_digits for digit in num_str)
    return 'Yes' if num == sum_of_powers else 'No'

# print(armstrong(100))

def magic(num):
    # Convert the number to a string
    num_str = str(num)

    # Calculate the sum of digits
    digit_sum = sum(int(digit) for digit in num_str)

    # Check if the digit sum is equal to the product of digits
    return 'Yes' if digit_sum * digit_sum == num else 'No'

def perfect(num):
    if num <= 0:
        return False
    divisors = [divisor for divisor in range(1, num) if num % divisor == 0]
    divisors_sum = sum(divisors)
    return 'Yes' if num == divisors_sum else 'No'

# def sum(num):
#     return sum(divisor for divisor in range(1, num) if num % divisor == 0)

def collatz(num):
    sequence = [num]
    while num != 1:
        if num % 2 == 0:
            num = numr // 2
        else:
            num = num * 3 + 1
        sequence.append(num)
    return sequence

def binary(num):
    return bin(num)[2:]

def octal(num):
    return oct(num)[2:]

def hexadecimal(num):
    return hex(numr)[2:]

def word(num):
    word = num2words(num)
    return word.replace('-',' ').title()

def factorial(num):
    if num == 0:
        return 1
    else:
        return num * factorial(num - 1)

def palindrome(num):
    return 'Yes' if str(num) == str(num)[::-1] else 'No'

def fibonacci(num):
    if num < 0:
        return False

    a, b = 0, 1
    while b < num:
        a, b = b, a + b

    return 'Yes' if b == num else 'No'

def prime_factorization(num):
    factors = []
    for i in range(2,num+1):
        if num % i == 0:
            factors.append(i)
    factors.remove(num)
    return factors

def table(num):
    try:
        table_string = ''
        table_patterns = (
        f"Here is the {num}th math table:",
        f"I have the {num}th math table for you:",
        f"Let's look at the {num}th math table:",
        f"The {num}th math table is as follows:",
        f"Here's the table for {num}:",
        f"Behold the {num}th math table:",
        f"Prepare to witness the {num}th math table:",
        f"Unlocking the secrets of the {num}th math table:",
        f"The {num}th math table holds valuable information:",
        f"Exploring the depths of the {num}th math table:",
        f"Unveiling the mysteries of the {num}th math table:",
        f"Discovering the patterns in the {num}th math table:",
        f"Behold, the majestic {num}th math table:",
        f"Embark on a journey through the {num}th math table:",
        f"Prepare to be amazed by the {num}th math table:",
        f"Let's delve into the {num}th math table:",
        f"The {num}th math table awaits your attention:",
        f"Unlocking the power of the {num}th math table:",
        f"Behold the beauty of the {num}th math table:",
        f"Delving into the wonders of the {num}th math table:"    )
        for i in range(1,11):
            table_string+= f"
{num} X {i} = {num*i}

"
        return random.choice(table_patterns)+'

'+table_string
    except:
        return 'Please provide number to generate math table'

def even_numbers(from_,to_):
    even_numbers_list = []
    for i in range(from_,to_+1):
        if i % 2 == 0:
            even_numbers_list.append(str(i))
    return random.choice(number_patterns).replace('{number_category}', 'Even').replace('{start}', str(from_)).replace('{end}', str(to_)) +'
    '+', '.join(even_numbers_list)+''

def odd_numbers(from_,to_):
    even_numbers_list = []
    for i in range(from_,to_+1):
        if i % 2 != 0:
            even_numbers_list.append(str(i))
    return random.choice(number_patterns).replace('{number_category}', 'Odd').replace('{start}', str(from_)).replace('{end}', str(to_)) +'
    '+', '.join(even_numbers_list)+''

def prime_numbers(from_,to_):
    prime_numbers_list = []
    for num in range(from_,to_+1):
        c = 0
        for i in range(1,num+1):
            if num % i == 0 :
                c += 1
        prime_numbers_list.append(str(num)) if c == 2 else 0
    return random.choice(number_patterns).replace('{number_category}', 'Prime').replace('{start}', str(from_)).replace('{end}', str(to_)) +'
    '+', '.join(prime_numbers_list)+''

def fibonacci_numbers(from_,to_):
    fibonacci_numbers = [0, 1]
    while fibonacci_numbers[-1] < to_:
        next_number = fibonacci_numbers[-1] + fibonacci_numbers[-2]
        fibonacci_numbers.append(next_number)
    fibonacci_numbers = [str(num) for num in fibonacci_numbers if from_ <= num <= to_]
    return random.choice(number_patterns).replace('{number_category}', 'Fibonacci').replace('{start}', str(from_)).replace('{end}', str(to_)) +'
    '+', '.join(fibonacci_numbers)+''

def explain_number(num):
    num = int(num)
    value = f"""

{num}

        {' '*4}The given number is {num}({word(num)}). It is {'an Even' if even(num) == 'Yes' else 'not an Even'} number. It is {'an Odd' if odd(num) == 'Yes' else 'not an Odd'} number. It is {'a Prime' if prime(num) == 'Yes' else 'not a Prime'} number. It is {'a Perfect' if perfect(num) == 'Yes' else 'not a Perfect'} number. It is {'Armstrong' if armstrong(num) == 'Yes' else 'not an Armstrong'} number. It is {'a Magic' if magic(num) == 'Yes' else 'not a Magic'} number. It is {'a Fibonacci' if fibonacci(num) == 'Yes' else 'not a'} Fibonacci number.

        No of digits : {digits(num)}

        Even Number : {even(int(num))}

        Odd Number : {odd(int(num))}

        Prime Number : {prime(int(num))}

        Perfect Number : {perfect(int(num))}

        Armstrong Number : {armstrong(int(num))}

        Magic Number : {magic(int(num))}

        Fibonacci Number : {fibonacci(int(num))}

"""
    return value


import time
import random
import requests
import pandas as pd
from requests_oauthlib import OAuth1
key_words=["Object Detection","YOLO","Machine Learning"]
auth = OAuth1("R3HqOpqIo6AcKjDYKD1tpsBzQ", "hw1X2Hv7IlND6eKewSFbFa7SgQ70OpEHKKr7wzvtFDPlFuffVe",f"AAAAAAAAAAAAAAAAAAAAAPnOhgEAAAAAtGmcPuNuqE%2FTStZkA1wcHCmpY%2Bw%3Dn9KHHdFYQJEyBy5sDYNchbCDqiFV5JBRNTtKPPNWpAE9aJ8uyY")
def bearer_oauth(r):
    r.headers["Authorization"]="Bearer {}".format(f"AAAAAAAAAAAAAAAAAAAAAPnOhgEAAAAAtGmcPuNuqE%2FTStZkA1wcHCmpY%2Bw%3Dn9KHHdFYQJEyBy5sDYNchbCDqiFV5JBRNTtKPPNWpAE9aJ8uyY")
    r.headers["User-Agent"]="Mozilla/5.0"

    return r
query_params={'query': 'Python',
             'tweet.fields': 'author_id',
             'expansions':'author_id',
             'max_results': '100',
             'user.fields':'created_at,entities,description,id,location,name,pinned_tweet_id,profile_image_url,protected,public_metrics,url,username,verified,withheld'
             }
url = "https://api.twitter.com/2/tweets/search/recent"#API url
query_params_two=query_params.copy() # next page header
id_had_lst=[]# looped user
user_info_lst=[]# result
key_word_num=0
next=False # flip page
pageNum=0
while key_word_num<len(key_words):

    query_params['query']= key_words[key_word_num]
    query_params_two['query']= key_words[key_word_num]
    print("now we are in",query_params['query'])
    time.sleep(random.random()*10)
    if next:# the second page of now searching key word
        r = requests.get(url,auth=bearer_oauth,params=query_params_two)
    else:# the first page of the now searching key word

        r = requests.get(url,auth=bearer_oauth,params=query_params)
    js = r.json()
    print(js)
    for one_user in js["includes"]["users"]:
        if one_user["id"] in id_had_lst: #pass the already looped users
            continue
        id_had_lst.append(one_user["id"])
        user_info_lst.append(one_user)
    print("Done one page!")
    if "next_token" not in js["meta"]: #if we have data in next page
        key_word_num+=1
        next=False
        print("finish the {} key word".format(key_word_num))
        continue
    else:
        pageNum+=1
        if pageNum>9:
            key_word_num+=1
            pageNum=0
            next=False
            print("finish the {} key word".format(key_word_num))
            continue
        query_params_two["next_token"] = js["meta"]["next_token"]
        next=True
        continue
pd.DataFrame(user_info_lst).to_csv(r"twitter.csv")


# -*- coding: utf-8 -*-

import vtk

#Genera la imagen en un archivo.
def plotToFile(fName, renWin, renderer, width, height,fileFormat):
  w2i = vtk.vtkWindowToImageFilter()
  writer = vtk.vtkJPEGWriter()
  w2i.SetInput(renWin)
  w2i.Update()
  writer.SetInputConnection(w2i.GetOutputPort())
  writer.SetFileName(fName)
  renWin.Render()
  w2i.Update()
  writer.Write()


from django.shortcuts import render, reverse, HttpResponse, redirect
from django.contrib import messages
from django.conf import settings

# Create your views here.
import stripe

def donate(request):
    return render(request, 'payment_donate.html')

def charge(request):
    get_amount = request.GET['amount']
    if get_amount == '':
        # messages.error(request, 'Please insert a value.')
        return redirect(reverse('donate'))
    else:
        amount = int(get_amount) * 100
        if amount == 0:
            messages.error(request, 'Please insert a value more than 0.')
            # return redirect(reverse('donate'), error_message='Please insert a value more than 0.')
            return redirect(reverse('donate'))

    stripe.api_key = settings.STRIPE_SECRET_KEY

    session = stripe.checkout.Session.create(payment_method_types=['card'],
        line_items=[
            {
                'name' : 'Donation',
                'description' : 'A simple donation to support BuggyReporter',
                'amount' : amount ,
                'currency' : 'sgd',
                'quantity' : 1
            }
        ],
        success_url= request.build_absolute_uri(reverse('success')),
        cancel_url=request.build_absolute_uri(reverse('cancel'))
    )
    return render(request, 'payment_charge_donate.html', {
        'CHECKOUT_SESSION_ID': session.id,
        'publishable_key': settings.STRIPE_PUBLISHABLE_KEY
    })

def success(request):
    messages.success(request, "You have successfully made a donation.")
    return redirect(reverse('index'))
    # return HttpResponse("
We have gotten your money
")

def cancel(request):
    messages.error(request, "You have cancelled a donation.")
    return redirect(reverse('donate'))

    # return HttpResponse("
No, don't go!
")


import datetime

DEFAULT_DATE_FORMAT = '%d/%m/%Y'
KNOWN_DATE_FORMATS = [DEFAULT_DATE_FORMAT, '%d-%b-%Y', '%Y-%b-%d', '%b-%d-%Y', '%Y/%m/%d', '%m/%d/%Y']

def string_to_date(string):
    for date_format in KNOWN_DATE_FORMATS:
        try:
            return datetime.datetime.strptime(string, date_format)
        except:
            pass
    return None

def date_to_string(date, date_format = DEFAULT_DATE_FORMAT):
    return date.strftime(date_format) if date else date

def previous_business_date(date = None, count_back = 1):
    if date is None:
        date = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)

    delta = datetime.timedelta(days = 1)
    count_down = count_back
    while count_down > 0:
        new_date = date - delta

        if new_date.weekday() >= 5: #If Saturday or Sunday
            date = new_date
            continue

        count_down -= 1
        if count_down == 0:
            return new_date

    return date

def get_today():
    time_now = datetime.datetime.now()
    hour_now = time_now.hour
    time_now = time_now.replace(hour=0, minute=0, second=0, microsecond=0)

    #If weekend (i.e. Sat or Sun)
    if time_now.weekday() > 4:
        while time_now.weekday() > 4:
            time_now -= datetime.timedelta(days = 1)
        return time_now

    #The daily paper import finishes at 2AM UTC of that day. Therefore,
    #if hour < 2AM then we have to show the previous date.
    #There could be a minor difference if daylight saving is present, but it does not
    #really affect result that much (user may have incorrect result for one hour at most).
    if hour_now < 2:
        time_now = time_now.replace(hour=0, minute=0, second=0, microsecond=0)
        return previous_business_date(time_now, count_back = 1)
    else: #Otherwise, we show paper of the current date
        return previous_business_date(count_back = 0)


#!/usr/bin/env python3
import iterm2, sys

# main command to be executed (NOTE: it will run in fresh iterm session, i.e. - home directory)
main_command = "./monitor_app.sh"

# The commands to run
commands = [main_command + " "  + x for x in sys.argv[1:]]
# dummy_commands = ["one", "two", "three", "four", "five", "six", "seven", "eight"]

async def main(connection):
    app = await iterm2.async_get_app(connection)
    window = app.current_terminal_window

    if window is not None:
        all_panes = []
        # Start a new tab
        tab = await window.async_create_tab()
        left = tab.current_session
        # Split into half
        right = await left.async_split_pane(vertical=True, before=False)
        all_panes.append(left)
        all_panes.append(right)

        # Start splitting on the left side
        pane_to_split = left
        for cmd in commands[2:]:
            newTab = await pane_to_split.async_split_pane(vertical=False, before=False)
            # Next to split is the last pane that was appended to all_panes
            pane_to_split = all_panes[-1]
            all_panes.append(newTab)

        for pane, cmd in zip(all_panes, commands):
            await pane.async_send_text(cmd)

    else:
        print("No current window, please open iterm2 and enable python API in settings")

iterm2.run_until_complete(main)


from typing import Optional, List

import instructions

class Argument:
    label: str = None
    immediate: int = None
    offset: int = None

    @classmethod
    def from_label(cls, label: str, offset: int = 0):
        argument = Argument()
        argument.label = label
        argument.offset = offset
        return argument

    @classmethod
    def from_immediate(cls, immediate: int):
        argument = Argument()
        argument.immediate = immediate
        return argument

    def is_label(self) -> bool:
        return self.label is not None

    def __repr__(self) -> str:
        if self.is_label():
            suffix = ''
            if self.offset != 0:
                sign = '+' if self.offset > 0 else '-'
                suffix = f'{sign}{self.offset}'
            return f'{self.label}{suffix}'
        else:
            return str(self.immediate)

    def __eq__(self, other):
        return self.label == other.label and self.immediate == other.immediate and self.offset == other.offset

class AsmLine:
    is_data: bool = False
    mnemonic: str = None
    argument: Argument = None
    address: int = None
    label: str = None

    def is_relative_branch(self) -> bool:
        return self.mnemonic in ['BR', 'BRZ', 'BRN']

    def is_non_relative_branch(self) -> bool:
        return self.mnemonic in [
            'LDAM',
            'LDBM',
            'STAM',
            'LDAC',
            'LDBC',
            'LDAP',
            'LDAI',
            'LDBI',
            'STAI',
            'BRB',
        ]

    @classmethod
    def from_instruction(cls, mnemonic: str, argument: Argument):
        asm_line = AsmLine()
        asm_line.mnemonic = mnemonic
        asm_line.argument = argument
        return asm_line

    @classmethod
    def from_data(cls, argument: Argument):
        asm_line = AsmLine()
        asm_line.argument = argument
        asm_line.is_data = True
        return asm_line

    def __repr__(self) -> str:
        prefix = ''

        if self.label is not None:
            prefix = f'{self.label} '

        if self.is_data:
            asm_line_str = f'DATA {self.argument}'
        else:
            asm_line_str = f'{self.mnemonic} {self.argument}'

        return f'{prefix}{asm_line_str}'

    def __eq__(self, other):
        return self.is_data == other.is_data and \
               self.mnemonic == other.mnemonic and \
               self.argument == other.argument and \
               self.address == other.address and \
               self.label == other.label

    def __copy__(self):
        result = Argument()
        result.is_data = self.is_data
        result.mnemonic = self.mnemonic
        result.argument = self.argument
        result.address = self.address
        result.label = self.label

        return result

    def to_int(self) -> int:
        if self.is_data:
            return self.argument.immediate
        else:
            opcode = instructions.MNEMONICS.index(self.mnemonic)
            argument = 0 if self.argument is None else self.argument.immediate
            instruction = (opcode << 4) + argument
            return instruction

    def is_prefix(self) -> bool:
        return self.mnemonic == 'PFIX'

def asm_lines_to_machine_code(asm_lines: List[AsmLine]) -> List[int]:
    return [asm_line.to_int() for asm_line in asm_lines]


from collections import Counter

class Database:
    def insert(self, movies_data_list, movies_kw_data):
        self.MOVIES_DATA = movies_data_list
        self.MOVIES_KW_DATA = movies_kw_data

    def get_data(self, query):

        for operator in ["AND", "OR", "NOT"]:
            if operator in query:
                query1, query2 = query.split(operator)
                res1, res2 = self.__fetch(query1), self.__fetch(query2)
                break

        if "AND" in query:
            res_indices = list(set(res1) & set(res2))
            res_indices.sort(key=Counter(res1 + res2).get, reverse=True)
        elif "OR" in query:
            res_indices = list(set(res1 + res2))
            res_indices.sort(key=Counter(res1 + res2).get, reverse=True)
        elif "NOT" in query:
            res_indices = list(set(res1) - set(res2))
            res_indices.sort(key=Counter(res1).get, reverse=True)
        else:
            temp = self.__fetch(query)
            res_indices = list(set(temp))
            res_indices.sort(key=Counter(temp).get, reverse=True)

        res = []
        for index in res_indices:
            res.append(self.MOVIES_DATA[index])
        return res

    def __fetch(self, query):
        query = query.split()
        res_indices = []

        for word in query:
            if word in self.MOVIES_KW_DATA:
                res_indices += self.MOVIES_KW_DATA[word]

        return res_indices


from manager_settings import *

import os
import pygit2
import time
import subprocess
import shutil
import multiprocessing

class BuildManager(object):
    def __init__(self, build_dir):
        if not os.path.exists(build_dir):
            os.mkdir(build_dir)

        try:
            self.repo = pygit2.Repository(TUNGSTEN_CLONE_DIR)
        except Exception:
            self.repo = pygit2.clone_repository(TUNGSTEN_REPO, TUNGSTEN_CLONE_DIR)

        self.builds = {}
        for path in os.listdir(build_dir):
            success_dir = os.path.join(build_dir, path, "build.success")
            tungsten = os.path.join(build_dir, path, "build", "release", "tungsten")
            if os.path.exists(success_dir):
                # confirm this is a commit
                if self.repo.get(path) is None:
                    continue

                self.builds[path] = {"exec": tungsten, "success": True}

    def get_latest_commits(self, num):
        latest = self.repo.lookup_branch("origin/master", pygit2.GIT_BRANCH_REMOTE).target
        count = 1
        for commit in self.repo.walk(latest, pygit2.GIT_SORT_TOPOLOGICAL):
            yield commit.oid.hex
            count += 1
            if count > num:
                return

    def get_latest_commit(self):
        self.fetch()
        return self.repo.lookup_branch("origin/master", pygit2.GIT_BRANCH_REMOTE).target.hex

    def get_latest_built_commit(self):
        for commit in self.get_latest_commits(10):
            ex = self.get_exec(commit)
            if ex:
                return ex

    def get_exec(self, commit):
        if commit not in self.builds:
            return None
        if not self.builds[commit].get('success'):
            return None
        return self.builds[commit]['exec']

    def fetch(self):
        t = self.repo.remotes['origin'].fetch()
        while (t.received_objects < t.total_objects):
            time.sleep(1)

    def build(self, commit=None, force=False):
        self.fetch()

        if commit is None: # build latest
            commit = self.get_latest_commit()

        git_commit = self.repo.get(commit)
        if git_commit is None:
            raise ValueError("Not a valid commit")
        if git_commit.type != pygit2.GIT_OBJ_COMMIT:
            raise ValueError("Object is not a commit!")

        self.repo.reset(commit, pygit2.GIT_RESET_HARD)

        build_root = os.path.join(TUNGSTEN_BUILD_DIR, commit)
        lock_dir = os.path.join(build_root, "build.lock")
        success_dir = os.path.join(build_root, "build.success")
        fail_dir = os.path.join(build_root, "build.fail")

        if os.path.exists(fail_dir):
            if not force:
                raise Exception("Build failed already, will not build again")
        if os.path.exists(success_dir):
            if not force:
                return

        if os.path.exists(build_root):
            shutil.rmtree(build_root)

        os.mkdir(build_root)
        os.mkdir(lock_dir)

        if not os.path.exists(build_root):
            raise Exception("Failed to make build_root %r" % build_root)

        print(build_root)
        p = subprocess.Popen([os.path.join(TUNGSTEN_CLONE_DIR, "setup_builds.sh")], shell=True, cwd=build_root)
        if p.wait() != 0:
            os.mkdir(fail_dir)
            os.rmdir(lock_dir)
            self.builds[commit] = {"success": False}
            raise Exception("Failed to setup_builds")

        p = subprocess.Popen(["make", "-j", str(multiprocessing.cpu_count())], cwd=os.path.join(build_root, "build", "release"))
        if p.wait() != 0:
            os.mkdir(fail_dir)
            os.rmdir(lock_dir)
            self.builds[commit] = {"success": False}
            raise Exception("Failed to build")

        if not os.path.exists(os.path.join(build_root, "build", "release", "tungsten")):
            os.mkdir(fail_dir)
            os.rmdir(lock_dir)
            self.builds[commit] = {"success": False}
            raise Exception("Failed to build")

        self.builds[commit] = {"exec": os.path.join(build_root, "build", "release", "tungsten"),
                "success": True}

        os.mkdir(success_dir)
        os.rmdir(lock_dir)


import csv
from datetime import date
import sys
import ctypes
import pprint
import shutil

kernel32 = ctypes.windll.kernel32
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)

'''
Colors!
Write a module and import in future.
'''
red_text = '\033[31m'
green_text = '\033[32m'
yellow_text = '\033[33m'
blue_text = '\033[34m'
white_text_on_blue = '\033[37m\033[44m'
marked_text = '\033[43m'
end_text = '\033[0m'
numbers = white_text_on_blue

def main():
    '''
    Main function.
    Base structure.
    '''
    base_file = "base_pd.csv"
    base_structure = [
        'Фамилия Имя Отчество (с учетом РЕГИСТРА)',
        'Дата рождения dd.mm.yyyy',
        'Место рождения',
        'Паспорт (Номер, Кем выдан, Дата выдачи, Код подразделения)',
        'СНИЛС (только цифры)',
        'ИНН',
        'Адрес (Индекс, Регион, Город, Улица, Дом, Квартира)',
        'Телефон (+7********** несколько через запятую)',
        'e-mail (несколько через запятую)',
        'Дата актуальности'
        ]
    menu_choise = menu()
    menu_handling(menu_choise, base_file, base_structure)

def menu():
    '''
    Menu function
    '''
    menu_choise = 'выбор не сделан'
    print("\033[4m{}\033[0m".format("\nМЕНЮ"))
    print(numbers + " " + "1" + " " + end_text + " - Найти запись")
    print(numbers + " " + "2" + " " + end_text + " - Внести записи")
    print(numbers + " " + "3" + " " + end_text + " - Изменить запись")
    print(numbers + " " + "4" + " " + end_text + " - Напечатать все записи")
    print(numbers + " " + "0" + " " + end_text + " - Выход \n")
    menu_choise = input("Выберите " + numbers + "пункт" + end_text + " меню - " + blue_text).strip()
    print(end_text, end='')
    while menu_choise not in ['0', '1', '2', '3', '4']:
        menu_choise = input(red_text + "Неправильный выбор\n" + end_text + "Выберите " + numbers + "пункт" + end_text + " меню - " + blue_text).strip()
    return menu_choise

def menu_handling(menu_choise, base_file, base_structure):
    if menu_choise == '1':
        rec_find(base_file)
    elif menu_choise == '2':
        rec_new(base_file, base_structure)
    elif menu_choise == '3':
        change_data(base_file, base_structure)
    elif menu_choise == '4':
        print_all_data(base_file)
    elif menu_choise == '0':
        print(green_text + "ВЫХОД из программы" + end_text)
        sys.exit()
    else:
        pass

def rec_find(base_file):
    '''Func that recieved basefile name and printed list of finded records'''
    record = input("Введите ФИО для поиска: (с учетом РЕГИСТРА) ").strip()
    base_list = base_file_read(base_file)
    find_list = get_find_list(base_list, record)
    print_find_list(find_list, record)
    return find_list

def get_find_list(base_list, record):
    '''Func recieved list of records and returned list of finded records and theyes indexes'''
    find_list = []
    for rec in range(len(base_list)):
        if record in base_list[rec][0]:
            finded_record = rec, base_list[rec]
            find_list.append(finded_record)
        elif base_list[rec] == []:
            continue
        else:
            continue
    return find_list

def print_find_list(find_list, record):
    '''Func recieved list of finded records and record that need to find.
    Printed heads.
    For rec in base printed index of finded record and finded record.
    if record not in base, print notice.
    '''
    if len(find_list) > 0:
        print()
        print(numbers + ' № ' + end_text + '     Запись' + '\n')
        for rec in range(len(find_list)):
            print(numbers + ' ' + str(find_list[rec][0]) + ' ' + end_text, ' ', end='')
            pprint.pprint(find_list[rec][1], indent=4, width=160)
            print()
    else:
        print('\nЗапись', marked_text + record + end_text, red_text + 'НЕ НАЙДЕНА' + end_text)
        print(green_text + 'Работа программы ЗАВЕРШЕНА' + end_text)
        sys.exit()

def rec_new(base_file, base_structure):
    '''Make error handling of non-numerical inputs
    Make input handling 0'''
    n = int(input("Введите количество записей для ввода - ").strip())
    for i in range(n):
        data = []
        for y in range(len(base_structure) - 1):
            data_input = input("Введите данные: " + base_structure[y] + " - ").strip()
            if y == 0:
                if check_name(data_input, base_file) is True:
                    print("Такая запись уже внесена.\nОСТАНОВКА программы\n")
                    break
                else:
                    data.append(data_input)
            else:
                data.append(data_input)
        if len(data) > 1:
            date = date_today()
            data.append(date)
            base_file_write(base_file, data)

def check_name(data_input, base_file):
    record = False
    data = base_file_read(base_file)
    for rec in data:
        if rec[0] == data_input:
            record = True
            return record
        else:
            continue
    return record

def date_today():
    '''Func that returned today date'''
    today = date.today()
    return today

def base_file_read(base_file):
    '''Func that reads csv file (delimiter is ';') and returns a list of lists of strings'''
    with open(file=base_file, mode='r', encoding='utf-8') as base:
        lines = csv.reader(base, delimiter=';')
        base_list = list(lines)
    return base_list

def base_file_write(base_file, data):
    with open(file=base_file, mode="a", encoding="UTF-8", newline='') as base:
        writer = csv.writer(base, delimiter=';')
        writer.writerow(data)
        print(green_text + "Внесена запись" + end_text)
        print(data)

def print_all_data(base_file):
    '''Func print all data from basefile'''
    base = base_file_read(base_file)
    for rec in base:
        print(( ';').join(rec) + '\n')

def change_data(base_file, base_structure):
    '''Func finds records on request.
    '''
    find_list = rec_find(base_file)
    rec_for_change = input('Введите ' + numbers + ' № ' + end_text + ' записи для изменения - ' + blue_text).strip()
    print(end_text, end='')
    print()
    for rec in find_list:
        if rec_for_change == str(rec[0]):
            print(end_text, end='')
            print(red_text + 'Изменить запись???' + end_text, yellow_text + str(rec) + end_text)
            choise = input('Напишите ' + red_text + 'ДА' + end_text + ' или ' + green_text + 'НЕТ' + end_text + ' - ' + yellow_text).strip()
            print(end_text, end='')
            print()
            if choise.lower() == 'да':
                base_list = base_file_read(base_file)
                change_record(rec, base_structure, base_list, base_file)
            else:
                print('Не меняем записи')
        else:
            continue

def change_record(record_for_change, base_structure, base_list, base_file):
    '''Func recieve tuple.
    Save position 0 in new record.
    And check all data in position 1'''
    #print(record_for_change)
    new_record = record_for_change[1]
    if len(new_record) < len(base_structure):
        for n in range(len(base_structure) - len(new_record)):
            new_record.append(' ')
    for y in range(len(base_structure) - 1):
        print("ПРОВЕРЬТЕ данные: " + base_structure[y])
        print(yellow_text + new_record[y] + end_text)
        print()
        choise = input("Изменить данные? Введите " + red_text + "ДА" + end_text + " или " + green_text + "НЕТ" + end_text + " - " + yellow_text).strip()
        print(end_text, end='')
        print()
        if choise.lower() == 'да':
            new_data = input('Введите данные: '+ base_structure[y] + ' - ').strip()
            new_record[y] = new_data
        else:
            continue
    if new_record[-1] != date_today():
        date = date_today()
        new_record[-1] = date
        print(red_text + 'Запись ИЗМЕНЕНА' + end_text, date)
    record_for_write = (record_for_change[0], new_record)
    base_list = preper_base_list(base_list, record_for_write)
    write_change_base_file(base_file, base_list)

def preper_base_list(base_list, record_for_write):
    '''Insert a new record in place of the old one'''
    index, line = record_for_write
    base_list[index] = line
    return base_list

def write_change_base_file(base_file, base_list):
    '''Func recieved name base file and new base list.
    Then write base file from list.'''
    with open(file=base_file, mode="w", encoding="UTF-8", newline='') as base:
        writer = csv.writer(base, delimiter=';')
        for line in base_list:
            writer.writerow(line)
    print(red_text + "Файл базы данных ЗАПИСАН" + end_text + "\n")

def auto_backup():
    date = date_today().strftime('%Y-%m-%d')
    filename = date + '-backup.csv'
    shutil.copy2('base_pd.csv', filename)

if __name__ == "__main__":
    main()
    auto_backup()
    print(green_text + 'Работа программы ЗАВЕРШЕНА' + end_text)


import pytest
from flask import Flask, json
from extensions import flask_app
from helpers import get_model_from_pickle

@pytest.fixture
def client():
    flask_app.config['TESTING'] = True
    with flask_app.test_client() as client:
        yield client

def test_get_movies_mocked_one(client, mocker):
    mocker.patch('helpers.get_model_from_pickle', return_value = None)
    mocker.patch('app.recommend_top_20_movies_for_user', return_value = "harry+potter,star+wars")
    response = client.get('/recommend/2')
    assert(response.status == '200 OK')
    assert(response.text == "harry+potter,star+wars")

def test_get_movies_mocked_two(client, mocker):
    mocker.patch('helpers.get_model_from_pickle', return_value = None)
    mocker.patch('app.recommend_top_20_movies_for_user', return_value = "harry+potter,star+wars")
    response = client.get('/recommend/-2')
    assert(response.status == '400 BAD REQUEST')

def test_get_movies_mocked_three(client, mocker):
    mocker.patch('helpers.get_model_from_pickle', return_value = None)
    mocker.patch('app.recommend_top_20_movies_for_user', return_value = "harry+potter,star+wars")
    response = client.get('/recommend/badinput')
    assert(response.status == '400 BAD REQUEST')

def test_get_movies_bad_unmocked_one(client, mocker):
    mocker.patch('helpers.get_model_from_pickle', return_value = get_model_from_pickle("svd_model"))
    response = client.get('/recommend/-2')
    assert(response.status == '400 BAD REQUEST')

def test_get_movies_unmocked(client, mocker):
    mocker.patch('app.get_model', return_value = get_model_from_pickle("svd_model"))
    response = client.get('/recommend/2')
    assert(response.status == '200 OK')
    res = "thrill+ride+the+science+of+fun+1997,vincent+1982,chaotic+ana+2007,for+the+birds+2000,a+very+social+secretary+2005,keeping+the+promise+1997,sweepers+1999,the+madagascar+penguins+in+a+christmas+caper+2005,the+true+meaning+of+christmas+specials+2002,asfalto+2000,the+bleeding+2009,mascara+1999,the+manzanar+fishing+club+2012,paths+of+hate+2011,season+for+assassins+1975,children+2006,so+much+so+fast+2006,home+alone+2+lost+in+new+york+1992"
    assert(response.text == res)

def test_get_movies_bad_two_unmocked(client, mocker):
    mocker.patch('app.get_model', return_value = get_model_from_pickle("svd_model"))
    response = client.get('/recommend/invalid')
    assert(response.status == '400 BAD REQUEST')


from tkinter import *
from tkinter import filedialog
import webbrowser
root = Tk()
root.geometry("600x600")
root.columnconfigure(0, weight=2)  # sets the co-ordinates in center
root.config(bg='#BEBEBE')

def openweb():
    webbrowser.open(url, new=new)

def file_open():
    global file1
    file1 = filedialog.askopenfile(
        mode="r", filetype=[('jpg file', '*.jpg'), ('png file', '*.png'), ('jpeg file', '*.jpeg')])  # gets the file from device
    filename.delete('1.0', 'end')
    filename.insert(END, file1.name)

def click(event):
    entry1.config(state=NORMAL)
    entry1.delete(0, END)

def encrypt_image():
    if file1 is not None:

        file_name = file1.name
        print(file_name)
        # getting the unique key entered by user
        key = entry1.get()
        print(file_name, key)

        file = open(file_name, 'rb')
        image = file.read()
        file.close()

        image = bytearray(image)    # byte of image in array
        for index, values in enumerate(image):
            # interchanging the key with array using XOR operator
            image[index] = values ^ int(key)
        fle = open(file_name, 'wb')
        fle.write(image)
        fle.close()

        successfull.config(text="Image Have SuccessFully Encrypted 👌 ",
                           fg="Red", font=("verdana", 15, "bold"))
        successfull.place(x=90 , y=380)
        remember.config(text=("Remember the key for Decryption Is : "+key))
        remember.place(x=140 , y=450)

def decrypt_image():
    if file1 is not None:

        file_name = file1.name
        print(file_name)
        key = entry1.get()  # getting the unique key entered by user
        print(file_name, key)

        file = open(file_name, 'rb')
        image = file.read()
        file.close()

        image = bytearray(image)    # byte of image in array
        for index, values in enumerate(image):
            # interchanging the key with array using XOR operator
            image[index] = values ^ int(key)
        fle = open(file_name, 'wb')
        fle.write(image)
        fle.close()
        successfull.config(text="Successfully Decrypted the image ",
                           fg="green", font=("Verdana", 15, "bold"))
        successfull.place(x=90 , y=380)

# for encryption process

welcome_label = Label(root, text="🔥Image Encryption & Decryption System 🔥",
                      font=("panton rust", 18, "bold"), fg='#303030' , bg='#BEBEBE')
welcome_label.grid()

Btn1 = Button(root, text="Choose the image 🎞", command=file_open, font=(
    "Verdana", 15, "bold"), fg="white", bg='#505050', border=8 , activeforeground="Orange",
activebackground="green")

Btn1.grid(pady=10 , padx=100)

support = Label(root, text='🙌'+"Supports only Jpg, jpeg,and png format" + '🙌',
                fg='red',  bg='#BEBEBE' , font=("Verdana", 12 , 'bold'))
support.place(x=100, y=100)

filename = Text(root, height=4, width=45)
filename.insert(END, "File Has Not Choosen!" + '💀💀💀💀💀')

filename.grid(pady=20)

entry1 = Entry(root,width=40)
entry1.insert(0, "Enter an integer key between 0 and 255")  # placeholder
entry1.config(state=NORMAL)
entry1.bind("<Button-1>", click)
entry1.grid(pady=20)
entry1.place(x=160 , y=220)

support1 = Label(root, text="✨Same Key should be used for encryption and decryption✨",
                 fg='red', bg='#BEBEBE' , font=("jost", 12 , 'bold'))
support1.place(x=80, y=240)

encrypt = Button(root, text="Encrypt", command=encrypt_image, font=(
    "jost", 15, "bold"), fg="white", bg='red')
encrypt.place(x=130, y=280)

decrypt = Button(root, text="Decrypt", command=decrypt_image, font=(
    "jost", 15, "bold"), fg="white", bg='#00ffc3')
decrypt.place(x=360, y=280)

successfull = Label(root, text=" " , fg="red",bg='#BEBEBE')
successfull.grid(pady=70)

remember = Label(root, text="", fg="red",bg='#BEBEBE',  font=("jost", 10))
remember.place(x=140, y=320)

root.mainloop()


# Series sum = 1 + 1/2! + 1/3! + ... + 1/n!

n = int(input("Enter The Value of n : "))

fact = 1
i = 1
sum = 0

while(i <= n):
    fact *= i
    sum += 1/fact
    i += 1

print(sum)


import datetime
import uuid

from pony import orm

def define_discordserver(db):
    class DiscordServer(db.Entity):
        id = orm.PrimaryKey(uuid.UUID, default=uuid.uuid4)
        state = orm.Required(int, min=1,
                             max=4)  # 1 = waiting for approval, 2 = public, 3 = expired, 4 = requeued (eg channel change)
        invite_code = orm.Required(str, unique=True)
        server_id = orm.Required(int, unique=True, size=64)
        name = orm.Required(str, max_len=32)
        description = orm.Optional(str, max_len=100)
        invitee_id = orm.Required(int, size=64)
        submitted_at = orm.Required(datetime.datetime)
        category_channel_name = orm.Required(str)
        genre_category_name = orm.Optional(str)
        last_checked = orm.Required(datetime.datetime)
        # deprecated
        index_message_id = orm.Optional(int, size=64)


"""core functions."""

from pathlib import Path
from random import choices

import numpy as np
import pandas as pd

from wt.io import glob_str, yamlr, yamlw

def __batch_prepare_card_uuids_and_versions(path):
    import uuid
    cards = []
    p = Path(path)
    files = p.glob(glob_str)
    for file in files:
        with open(file, 'r+') as fid:
            doc = yamlr.load(fid)
            doc['version'] = 1
            doc['uuid'] = str(uuid.uuid4())
            cards.append(doc.copy())
            fid.seek(0)
            fid.truncate()
            yamlw.dump(doc, fid)
    return cards

def prep_cards(database, classes, types=None):
    """Prepares the set of valid cards for a search on classes and types.

    Parameters
    ----------
    database: `pd.DataFrame`
        card database
    classes : iterable
        iterable of class(es) to draw valid cards for
    types : iterable, optional
        types to further filter by; card can be any of the specified types

    Returns
    -------
    `pandas.DataFrame`
        filtered dataframe of valid cards

    """
    # begin all valid sets with all generic cards
    class_masks = [database['class'] == 'generic']

    # for each class specified, create a mask on the database of cards which have that class
    for class_ in classes:
        class_masks.append(database['class'] == class_)

    # concatonate the masks and accept values where any mask passes
    class_mask = pd.concat(class_masks, axis=1).any(axis=1)
    total_mask = class_mask

    # if some card types are specified, repeat class masking for types
    if types:
        types_masks = []
        for type_ in types:
            types_masks.append(database[database['types'].apply(lambda x: type_ in x)])
        type_mask = pd.concat(types_masks, axis=1).any(axis=1)

        # finally, find the mask which satisfies both the class and type masks simultaneously
        total_mask = pd.concat((class_mask, type_mask), axis=1)
        total_mask = total_mask.replace(np.NaN, False).all(axis=1)

    return database[total_mask]  # return cards satisfying this mask

def draw_cards(valid_cards, n=1):
    """Draw card(s).

    Parameters
    ----------
    valid_cards: `pd.DataFrame`
        card database
    n: `int`
        number of cards to draw

    Returns
    -------
    iterable of `dict`s
        iterable containing a dict for each card

    """
    uuids = valid_cards.uuid.values
    weights = valid_cards.draw_chance.values
    id_ = choices(uuids, weights, k=n)
    outmask = valid_cards.uuid.isin(id_)
    chosen_cards = valid_cards[outmask]
    dictionaries = chosen_cards.to_dict(orient='records')
    return dictionaries

def prep_and_draw_cards(database, classes, types=None, n=1):
    """Prepares valid cards and draws a card for the user.

    This is a macro that calls the preparation and draw functions, it is a convenience function
    for when the valid cards for a particular case are not already cached.

    Parameters
    ----------
    valid_cards: `pd.DataFrame`
        card database
    classes : iterable
        iterable of class(es) to draw valid cards for
    types : iterable, optional
        types to further filter by; card can be any of the specified types
    n: `int`
        number of cards to draw

    Returns
    -------
    iterable of `dict`s
        iterable containing a dict for each card

    """
    valid_cards = prep_cards(database, classes, types)
    return draw_cards(valid_cards, n)


import json
from . import configutil
import os
import errno

def openJSON(filepath):
    """ open a json file and return a JSON object """
    with open(filepath) as data_file:
        data = json.load(data_file)
    return data

def save(data):
    """ save some data into the output file """
    with open(configutil.getOutputFilePath(),"w") as file:
        file.write(data)

def mkdir(path):
    try:
        os.makedirs(path)
    except OSError as exception:
        if exception.errno != errno.EEXIST:
            raise


import sys
input = sys.stdin.readline

def size(a):
        return len(a)
def empty(a):
        if len(a) == 0: return 1
        else: return 0
def top(a):
        if len(a) == 0: return -1
        else: return a[-1]
def pop(a):
        if len(a) == 0: return -1
        else: return a.pop(-1)
def push(a, n):
        a.append(n)

stack = []
for i in range(int(input())):
    a = input().split()
    if a[0] == 'size':
        print(size(stack))
    elif a[0] == 'empty':
        print(empty(stack))
    elif a[0] == 'top':
        print(top(stack))
    elif a[0] == 'pop':
        print(pop(stack))
    elif a[0] == 'push':
        push(stack, a[1])


import csv

from pymotifs import core
from pymotifs import models as mod
from sqlalchemy import desc

class Loader(core.SimpleLoader):

    merge_data = True
    allow_no_data = True

    """
    @property
    def table(self):
        return mod.LoopAnnotations
    """

    def to_process(self, pdbs, **kwrags):
        """ return the different loop types to process
        """
        return ["IL","HL"]

    """
    def remove(self, *args, **kwargs):
        Does not actually remove from the DB. We always want the loop ids to
        be consistent so we do not automatically remove loops.
        """

    """Added has_data because it should force the stage to recompute "IL". This is not a permenant solution."""

    def has_data(self, args, **kwargs):
        return False

    def query(self, session, pdb):
        return session.query(mod.LoopAnnotations)

    def _get_loop_annotations(self,loop_type):
        """ Gets access to the spreadsheet, reads values, and saves data in DB friendly format.
        Create dictionary for loop_annotations 1 and 2 and motif_annotations 1 and 2 with loop_id and motif_id
        as their respective keys and with values consisting of a 2-element set: annotation and author.
        """

        loop_annotation1 = {}
        loop_annotation2 = {}
        motif_annotation1 = {}
        motif_annotation2 = {}

        #Read data from csv file and save each row as a list of strings

        loop_data = []

        self.logger.info("Reading %s annotations from CSV file" % loop_type)
        print("annotations.py reading %s loop annotations" % loop_type)

        with open("/usr/local/pipeline/hub-core/%s_annotations.csv" % loop_type, "r") as annotations:
            entries = csv.reader(annotations, delimiter = ',')
            for rawrow in entries:
                #If a loop_id is indicated, then check for and save loop annotation 1
                #and/or loop annotation 2

                # trim leading and trailing white space
                row = [r.strip() for r in rawrow]

                # record loop-specific annotations
                if isinstance(row[1], str) and row[1]:
                    for row1 in row[1].replace(" ","").replace(";",",").split(","):
                        print(row1)
                        if isinstance(row[2], str) and row[2]:
                            loop_annotation1[row1] = [row[2], row[4]]     # save annotation and author
                            if isinstance(row[3], str) and row[3]:
                                loop_annotation2[row1] = [row[3], row[4]] # save annotation and author
                            else:
                                loop_annotation2[row1] = [row[2], row[4]] # repeat column C annotation

                    # Listing a loop id with two blank annotations means
                    # not to annotate that loop, even using the motif annotation
                    if len(row[2]) == 0 and len(row[3]) == 0:
                        loop_annotation1[row1] = ["NULL", row[4]]
                        loop_annotation2[row1] = ["NULL", row[4]]

                #Otherwise check for motif group and save motif annotation 1 and/or motif annotation 2
                elif isinstance(row[0],str) and row[0]:
                    if isinstance(row[2], str) and row[2]:
                        motif_annotation1[row[0]] = [row[2], row[4]]   # save annotation and author
                    if isinstance(row[3], str) and row[3]:
                        motif_annotation2[row[0]] = [row[3], row[4]]  # save annotation and author

        #Save each loop annnotation to loop_data in DB-friendly format

        #if a loop instance has either annotation1 and annotation 2 indicated,
        #then do not check for motif annotations
        annotated_loops = list(set(loop_annotation1.keys()) | set(loop_annotation2.keys()))

        for loop in annotated_loops:
            if loop in loop_annotation1:
                ann1 = loop_annotation1[loop][0]
                author = loop_annotation1[loop][1]
            else:
                ann1 = "NULL"
            if loop in loop_annotation2:
                ann2 = loop_annotation2[loop][0]
                author = loop_annotation1[loop][1]
            else:
                ann2 = "NULL"

            if not ann1 == "NULL" and not ann2 == "NULL":
                loop_data.append(mod.LoopAnnotations(
                    loop_id = loop,
                    annotation_1 = ann1,
                    annotation_2 = ann2,
                    author = author))

        #The rest of the LoopAnnotations entries need to be checked for motif_annotations

        #Get current motif release
        with self.session() as session:
            current_ml_release = session.query(mod.MlReleases.ml_release_id).\
                order_by(desc(mod.MlReleases.index)).\
                limit(1)

#            self.logger.info("Current motif atlas release %s" % current_ml_release)

        # collect together all annotated motif groups
        all_motifs = set(motif_annotation1.keys()) | set(motif_annotation2.keys())
        for motif in all_motifs:
            # For each motif, get the associated loop_ids
            with self.session() as session:
                query = session.query(mod.MlLoops.loop_id).\
                     filter(mod.MlLoops.motif_id == motif)
                loop_ids = [r.loop_id for r in query]

            loop_ids = list(set(loop_ids))     # remove any duplicates
            print("Unique loop ids in motif group %s" % motif)
            print(loop_ids)

            # For each loop in this motif, check for loop instance annotations, otherwise use the motif annotation (if it exists)
            # This code should handle the cases that the loop has either annotation1, annotation2, or neither
            for loop in loop_ids:
                # If a loop in this motif does not have a loop instance annotation1, then use motif_annotation1 given that motif_annotation1 exists
                if loop not in annotated_loops:
                    if motif in motif_annotation1:
                        loop_annotation1[loop] = motif_annotation1[motif]
                    else:
                        loop_annotation1[loop] = ["NULL", "NULL"]
                    if motif in motif_annotation2:
                        loop_annotation2[loop] = motif_annotation2[motif]
                    else:
                        loop_annotation2[loop] = ["NULL", "NULL"]

                    #Add completed loop_entry to loop_data
                    loop_data.append(mod.LoopAnnotations(
                        loop_id = loop,
                        annotation_1 = loop_annotation1[loop][0],
                        annotation_2 = loop_annotation2[loop][0],
                        author = loop_annotation1[loop][1]))

        return loop_data

    def data(self, loop_type, **kwargs):
        """ Get the loop annotations from the spreadsheet.
        Return a list of all loop annotations. """

        print("annotations.py running data method")

        #Get loop annotations
        data = []
        data = self._get_loop_annotations(loop_type)

        #Return data to be written to the database.
        if not data:
            self.logger.error("No loop annotations found.")
        else:
            return data