# Name: Jeffery Ho
# Section: 201 - 11

import random

# list of ints -> int
# takes in a list, sorts it, and returns the # of comparisions needed to sort the list
def insert_sort(alist):
   counter = 0
   for idx in range(1, len(alist)):
       cur = alist[idx]
       pos = idx
       counter += 1
       while (pos > 0 and alist[pos - 1] > cur):
           alist[pos] = alist[pos - 1]
           pos -= 1
           counter += 2
       counter += 1
       alist[pos] = cur
   counter += 1
   return counter  # selection sort

# list of ints -> int
# implements selection sort on a list of ints and returns the number of comparisons
def select_sort(alist):
   count = 0
   for i in range(len(alist) - 1, 0, -1):
       max_pos = 0
       count += 1
       for j in range(1, i + 1):
           count += 1
           if alist[j] > alist[max_pos]:
               count+=1
               max_pos = j
       count += 1
       temp = alist[i]
       alist[i] = alist[max_pos]
       alist[max_pos] = temp
   count+=1
   return count

# Merge Sort
# list of int -> int
# Given a list of number, sorts the list and returns the number of comparisons
def merge_Sort(alist, count = 0, left = 0, right = 0):

    if len(alist)>1:
        mid = len(alist)//2
        lefthalf = alist[:mid]
        righthalf = alist[mid:]

        merge_Sort(lefthalf, count, left, right)
        merge_Sort(righthalf, count, left, right)

        i=0
        j=0
        k=0
        while i < len(lefthalf) and j < len(righthalf):
            count += 2
            if lefthalf[i] < righthalf[j]:
                count += 1
                alist[k]=lefthalf[i]
                i=i+1
            else:
                count += 1
                alist[k]=righthalf[j]
                j=j+1
            k=k+1
        count += 1
        while i < len(lefthalf):
            count += 1
            alist[k]=lefthalf[i]
            i=i+1
            k=k+1
        count += 1
        while j < len(righthalf):
            count += 1
            alist[k]=righthalf[j]
            j=j+1
            k=k+1
        count += 1
    return count

alist = []

for i in range(1000):
    n=random.randint(0,100)
    alist.append(n)

print('merge:',merge_Sort(alist))
print('selection:', select_sort(alist))
print('insertion:', insert_sort(alist))


import tensorflow as tf

class Attention_RNN(object):
    def __init__(self, num_classes, embedding_size, vocab_size, sequence_length, num_layers=1):
        self.input_x = tf.placeholder(tf.int32, [None, sequence_length], name='input_x')
        self.input_y = tf.placeholder(tf.float32, [None, num_classes], name='input_y')
        self.dropout_keep_prob = tf.placeholder(tf.float32, name='dropout')

        with tf.device('/cpu:0'), tf.name_scope('embedding'):
            W = tf.Variable(tf.constant(0., shape=[vocab_size, embedding_size]), name="W")  # ,trainable=False)
            self.embedding_placeholder = tf.placeholder(tf.float32, [vocab_size, embedding_size],
                                                        name='embedding_placeholder')
            embeding_init = W.assign(self.embedding_placeholder)
            embedded_inputs = tf.nn.embedding_lookup(embeding_init, self.input_x)

        with tf.name_scope('rnn'):
            # multi rnn
            cells = []
            for _ in range(num_layers):
                cell = tf.contrib.rnn.GRUCell(embedding_size)
                wraped_cell = tf.contrib.rnn.DropoutWrapper(cell, output_keep_prob=self.dropout_keep_prob)
                cells.append(wraped_cell)

            rnn_cell = tf.contrib.rnn.MultiRNNCell(cells, state_is_tuple=True)
            _outputs, _ = tf.nn.dynamic_rnn(cell=rnn_cell, inputs=embedded_inputs, dtype=tf.float32)
            last = _outputs[:, -1, :]

        # Final (unnormalized scores and predictions)
        with tf.name_scope("output"):
            self.scores = tf.layers.dense(last, num_classes, name='num_classes')
            self.sigmoidprob = tf.sigmoid(self.scores, name='sigmoidprob')
            self.predictions = self.sigmoidprob >= 0.5

        # Calculate mean cross-entropy loss
        with tf.name_scope('loss'):
            # beta=0.795542572957783
            # pos_weight=beta/(1-beta)
            # self.loss_per=tf.nn.weighted_cross_entropy_with_logits(logits=self.scores,targets=self.input_y,pos_weight=pos_weight)
            self.loss_per = tf.nn.sigmoid_cross_entropy_with_logits(logits=self.scores, labels=self.input_y)
            self.loss = tf.reduce_mean(self.loss_per)  # *(1-beta))

        # Accuracy
        with tf.name_scope('accuracy'):
            correct_predictions = tf.equal(self.predictions, tf.cast(self.input_y, "bool"))
            self.accuracy = tf.reduce_mean(
                tf.cast(correct_predictions, "float"), name="accuracy")


"""
Tests covering Pytelliot rpc connection  utils.
"""
import pytest
import requests
from brownie import chain

from telliot_core.model.endpoints import EndpointList
from telliot_core.model.endpoints import RPCEndpoint

network = "mainnet"
provider = "pokt"

def test_rpc_endpoint():
    """RPCEndpoint connects to the blockchain"""
    url = "http://127.0.0.1:8545"  # local Ganache node
    endpt = RPCEndpoint(network=network, provider=provider, url=url)
    endpt.connect()
    chain.mine(10)
    assert endpt.web3.eth.block_number > 1

    print(endpt.get_state())

def test_very_bad_rpc_url():
    """an invalid url will raise an exception in RPCEndpoint"""
    url = "this is not a valid rpc url"
    endpt = RPCEndpoint(network=network, provider=provider, url=url)
    with pytest.raises(ValueError):
        _ = endpt.connect()

@pytest.mark.skip()
def test_incomplete_rpc_url():
    """an incomplete url will raise an exception in RPCEndpoint"""
    url = "https://eth-rinkeby.gateway.pokt.network/v1/lb/"
    endpt = RPCEndpoint(network=network, provider=provider, url=url)
    # expect bad url error from requests library
    with pytest.raises(requests.exceptions.HTTPError):
        _ = endpt.connect()

@pytest.mark.skip("Only Pulsechain available in endpoint list")
def test_endpoint_list():
    sl = EndpointList()
    # print(json.dumps(sl.get_state(), indent=2))
    ep4 = sl.find(chain_id=4)[0]
    assert ep4.network == "rinkeby"

    ep3 = sl.find(chain_id=3)[0]
    assert ep3.network == "ropsten"


#probability

def BellmanFord():
	prob[1] = 1.0

	for i in range(n - 1):
		for edge in graph:
			u, v, w = edge

			if prob[v] != -1:					#!!! For undirected graph only		but, you can also do:
				prob[u] = max(prob[u], prob[v] * w)		#					prob[u] = max(prob[u], prob[v] * w)
			if prob[u] != -1:					#					prob[u] = max(prob[u], prob[v] * w)
				prob[v] = max(prob[v], prob[u] * w)		# 		-> because: "there is at least one path between intersection 1 and n."

while True:
	line = list(map(int, input().split()))
	if len(line) == 1:
		break

	graph = []
	n, m = line[0], line[1]

	for _ in range(m):
		u, v, c = map(int, input().split())
		graph.append((u, v, c / 100))

	prob = [-1.0] * (n + 1)
	BellmanFord()

	print("{:.6f} percent".format(prob[n] * 100))

9. Bellman-Ford/106 Miles To Chicago (URI Online Judge).py


from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
import tensorflow as tf
from sklearn.preprocessing import OneHotEncoder, MinMaxScaler
from sklearn.metrics import accuracy_score
import numpy as np

datasets = load_wine()
print(datasets.DESCR)
print(datasets.feature_names)

x_data = datasets.data
y_data = datasets.target
y_data = y_data.reshape(-1, 1)
print(x_data.shape, y_data.shape)  # (178, 13) (178, 1)

one_hot_Encoder = OneHotEncoder()
one_hot_Encoder.fit(y_data)
y_data = one_hot_Encoder.transform(y_data).toarray()

print(x_data.shape, y_data.shape)  # (178, 13) (178, 3)

x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, train_size=0.8, random_state=9, shuffle=True)

x = tf.placeholder(tf.float32, shape=[None, 13])
y = tf.placeholder(tf.float32, shape=[None, 3])

w = tf.Variable(tf.random_normal([13, 3]), dtype=tf.float32) # x X w = N, 3 (y)의 값이 되어야 한다
b = tf.Variable(tf.random_normal([1, 3]), dtype=tf.float32)

hypothesis = tf.nn.softmax(tf.matmul(x, w) + b)

loss = tf.reduce_mean(-tf.reduce_sum(y * tf.log(hypothesis), axis=1)) # categorical crossentropy

optimizer = tf.train.GradientDescentOptimizer(learning_rate=5e-1).minimize(loss)

sess = tf.compat.v1.Session()
sess.run(tf.global_variables_initializer())

for epochs in range(1001):
    cost_val, hy_val, _ = sess.run([loss, hypothesis, optimizer],
                    feed_dict={x:x_data, y:y_data})
    if epochs % 10 == 0:
        print(epochs, 'cost: ', cost_val, "predict: ", hy_val)

pred = sess.run(hypothesis, feed_dict={x:x_test}) # x_test에 대한 기울기 다시 도출
print('전:', pred[:5])
pred = np.argmax(pred, axis=1)
print('후:', pred[:5])
print('전 1:', y_test[:5])
y_test = np.argmax(y_test, axis=1)
print('후 1:', y_test[:5])
print('acc: ', accuracy_score(y_test, pred))

# acc:  0.4722222222222222


# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/cousins-in-binary-tree/solution/

#1 BFS, record the parent and depth
#2 DFS, record the parent and depth
"""
import collections
class Solution:
    def isCousins_bfs(self, root: 'TreeNode', x: 'int', y: 'int') -> 'bool':
        parents, depths = {}, {}
        queue = collections.deque((root, 0))
        while queue:
            node, d = queue.popleft()
            if node.left:
                queue.append((node.left, d + 1))
                if node.left.val in (x, y):
                    parents[node.left.val] = node.val
                    depths[node.left.val] = d + 1
            if node.right:
                queue.append((node.right, d + 1))
                if node.right.val in (x, y):
                    parents[node.right.val] = node.val
                    depths[node.right.val] = d + 1
            if len(parents) == 2:
                break
        if len(parents) != 2:
            return False
        if parents[x] != parents[y] and depths[x] == depths[y]:
            return True
        return False

    def isCousins_dfs(self, root: 'TreeNode', x: 'int', y: 'int') -> 'bool':
        parent, depth = {}, {}
        def dfs(node, par = None):
            if node:
                depth[node.val] = 1 + depth[par.val] if par else 0
                parent[node.val] = par
                dfs(node.left, node)
                dfs(node.right, node)
        dfs(root)
        return depth[x] == depth[y] and parent[x] != parent[y]


def solve(n:int, numArrays:list) -> int:
    count = 0
    for i in range(n):
        if numArrays[i] % 2 != 0:
            count += 1
    return count

t = int(input())

for i in range(t):
    n = int(input())
    a = list(map(int, input().split()))
    total = solve(n, a)
    print(total)


'''
Created on May 2, 2014

@author: A. Rupam Mahmood

'''

import numpy as np
import pylab as pl
import random
import matplotlib as mpl

class MDP(object):
  '''
  It creates a generic MDP object.
  Requires Pssa, Rssa and other structures to be specified.
  '''
  def __init__(self, params):
    '''
    Create all the necessary structure for the MDP
    '''
    self.ns         = params['ns']
    self.na         = params['na']
    self.ftype      = params['ftype'] # feature type
    if self.ftype=='tabular':   self.nf = self.ns
    elif self.ftype=='binary':  self.nf = int(np.ceil(np.log(self.ns+1)/np.log(2)))
    else: self.nf = params['nf']

    self.Rstd       = params['Rstd'] # std dev. for generating random rewards
    self.initsdist  = params['initsdist'] # initial state distribution
    self.Gamma      = params['Gamma'] # diagonal matrix of state-dependent gammas
    self.mdpseed    = params['mdpseed'] # seed to generate mdps
    self.rdmdp      = np.random.RandomState(self.mdpseed)

    if type(self.initsdist)==str:
      self.initsdistname = self.initsdist
      if self.initsdistname=='statemiddle':
        self.initsdist= np.zeros(self.ns)
        self.initsdist[(self.ns-1)/2] = 1.
    else:
      self.initsdistname = None

    self.Pssa       = self.getPssa()
    self.Rssa       = self.getRssa()
    self.bpol       = self.getBPolicy()
    (self.Pssb, self.exprb) = getPolInducedModel(self.Pssa, self.Rssa, self.bpol)
    if 'offpolicy' in params and params['offpolicy']==True:
      self.offpolicy  = True
      self.tpol       = self.getTPolicy()
      (self.Psst, self.exprt) = getPolInducedModel(self.Pssa, self.Rssa, self.tpol)
    else:
      self.offpolicy  = False
      self.tpol       = self.bpol
      (self.Psst, self.exprt) = (self.Pssb, self.exprb)

    self.Phi                = self.getPhi(self.ftype, self.ns, self.nf, rndobj=self.rdmdp)
    self.dsb                = self.steadystateprob(self.Pssb)
    if self.initsdist=='steadystate': self.initsdist = self.dsb

  def getPssa(self, params):
    raise NotImplementedError

  def getRssa(self, params):
    raise NotImplementedError

  def getBPolicy(self):
    raise NotImplementedError

  def getTPolicy(self):
    raise NotImplementedError

  def initTrajectory(self, runseed):
    self.rdrun    = np.random.RandomState(runseed)
    if self.initsdistname=='statezero':
      self.s  = 0
    elif self.initsdistname=='statemiddle':
      self.s  = (self.ns-1)/2
    else:
      self.s  = sampleFrom(self.initsdist, self.rdrun)

  def step(self):
    a = 0 if self.na==1 else self.getAction(self.bpol, self.s, self.rdrun)
    snext   = self.getNextState(self.Pssa, self.s, a, self.rdrun)
    noise   = self.rdrun.normal(0, self.Rstd) if self.Rstd>0 else 0.
    R       = self.getReward(self.Rssa, self.s, snext, a) + noise
    phi     = self.Phi[self.s]
    phinext = self.Phi[snext]
    g       = self.Gamma[self.s, self.s]
    gnext   = self.Gamma[snext, snext]
    stemp   = self.s
    self.s  = snext
    return {'s':stemp, 'phi':phi, 'act':a, \
            'R':R, 'snext':snext, 'phinext':phinext, \
            'g':g, 'gnext':gnext}

  def getRho(self, s, a):
    return self.tpol[s,a]/self.bpol[s,a]

  def isTerminal(self):
    return self.Gamma[self.s, self.s] == 0.0

  def getPhi(self, ftype, ns, nf=None, rndobj=None):
    Phi = 0.0
    if ftype=='tabular':
      Phi = np.eye(ns)
    elif ftype=='binary':
      nf = int(np.ceil(np.log(ns+1)/np.log(2)))
      Phi = np.zeros((ns, nf))
      for i in range(ns):
        for j in range(nf):
          Phi[i, nf-j-1] = ((i+1)>>j) & 1
        a = sum(Phi[i,]*Phi[i,])
        Phi[i,] = Phi[i,]/np.sqrt(a)
    elif ftype=='normal':
      Phi = np.zeros((ns, nf))
      for i in range(ns):
        for j in range(nf):
          Phi[i, j] = rndobj.normal(0, 1)
        a = sum(Phi[i,]*Phi[i,])
        Phi[i,] = Phi[i,]/np.sqrt(a)
    return Phi

  def getAction(self, pol, s, rndobj):
    rndnum = rndobj.uniform(0, 1)
    return mpl.mlab.find(rndnum<np.cumsum(pol[s,:]))[0]

  def getNextState(self, Pssa, s, a, rndobj):
    rndnum = rndobj.uniform(0, 1)
    return mpl.mlab.find(rndnum<np.cumsum(Pssa[s,:,a]))[0]

  def getReward(self, Rssa, s, snext, a):
    return Rssa[s,snext,a]

  @staticmethod
  def getFixedPoint(Pss, ExpR, Phi, ds, Gamma, Lmbda):
    (ns, ns) = np.shape(Pss)
    D = np.diag(ds)
    ImPGLinv = pl.inv(np.eye(ns)- np.dot(Pss, np.dot(Gamma, Lmbda)))
    PhiTD = np.dot(Phi.T, D)
    ImPG = np.eye(ns) - np.dot(Pss, Gamma)
    A = np.dot(np.dot(PhiTD, ImPGLinv), np.dot(ImPG, Phi))
    b = np.dot(PhiTD, np.dot(ImPGLinv, ExpR))
    thstar = np.dot(pl.inv(A), b)
    return thstar

  def steadystateprob(self, Pss):
    (eigvals, eigvecs) = pl.eig(Pss.T)
    eigi = np.argmax(eigvals)
    diotas = eigvecs[:,eigi]/sum(eigvecs[:,eigi])
    return np.real(diotas)

## general ergodic MDP, general gamma
## Pssa is of s X s' X a form

def getRandomMDP(ns, na, rndobj, rtype='uniform', rparam=1):
  Pssa = np.reshape(rndobj.uniform(0, 1, ns*ns*na) + 10**-10 , \
                                (ns, ns, na))

  rsums = np.sum(Pssa, 1)
  Pssa = Pssa / rsums[:, None]
  if rtype=='uniform':
    Rssa = np.reshape(rndobj.uniform(0, rparam, ns*ns*na),
                                (ns, ns, na))
  if rtype=='normal':
    Rssa = np.reshape(rndobj.normal(0, rparam, ns*ns*na),
                                (ns, ns, na))
  return (Pssa, Rssa)

def getPolInducedModel(Pssa, Rssa, pol):
    Pss = getPss(Pssa, pol)
    Rsa = getRsa(Rssa, Pssa)
    ExpR = getExpR(Rsa, pol)

    return (Pss, ExpR)

def followon(Pss, startstatedist):
  (ns, ns) = np.shape(Pss)
  return np.dot(pl.inv(np.eye(ns) - Pss.T), startstatedist)

def getPss(Pssa, pol):
  (ns, t1, nacts) = np.shape(Pssa)
  Pss = np.zeros((ns, ns))
  for i in range(ns):
    for j in range(ns):
      Pss[i, j] = np.dot(Pssa[i, j, ], pol[i, ])
  return Pss

def getRsa(Rssa, Pssa):
  (ns, t1, nacts) = np.shape(Rssa)
  Rsa = np.zeros((ns, nacts))
  for i in range(ns):
    for j in range(nacts):
        Rsa[i, j] = np.dot(Pssa[i,:,j], Rssa[i,:,j])
  return Rsa

def getExpR(Rsa, pol):
  (ns, t1) = np.shape(Rsa)
  ExpR = np.zeros(ns)
  for i in range(ns): ExpR[i] = np.dot(pol[i,], Rsa[i,])
  return ExpR

def getRandomlySampledPolicy(ns, na, rndobj, coverage=True):
  pol = np.reshape(np.array([rndobj.uniform(0, 1) + coverage*10**-15 for i in range(ns*na)]), (ns, na) )
  pol = np.array([ pol[i]/sum(pol[i]) for i in range(ns) ])
  return pol

def getUniformRandomPolicy(ns, na):
  pol = np.ones((ns, na))/na
  return pol

def getSkewedPolicy1(ns, na, rndobj):
  pol = np.zeros((ns, na))
  for i in range(ns):
    a = rndobj.randint(0, na)
    if na>1: pol[i,:] = 0.01/(na-1)
    pol[i, a] = 0.99
  return pol

def sampleFrom(dist, rndobj):
  rndnum = rndobj.uniform(0, 1)
  return mpl.mlab.find(rndnum<np.cumsum(dist))[0]

def getPhiIndices(Phi):
  (ns, nf) = np.shape(Phi)
  PhiIndices = [[]]*ns
  for s in range(ns):
    PhiIndices[s] = mpl.mlab.find(Phi[s]!=0)
  return PhiIndices

class PerformanceMeasure(object):
  '''
  This class takes the responsibility of measuring performance of an estimate.
  Only for on-policy case at this point.
  '''

  def __init__(self, params, prob):
    self.T            = params['T'] # number of total steps
    self.N            = params['N'] # number of data points to store
    self.Phi          = prob.Phi
    self.prob         = prob
    if 'offpolicy' in params and params['offpolicy']==True:
      self.Pss             = prob.Psst
      self.expr            = prob.exprt
    else:
      self.Pss             = prob.Pssb
      self.expr            = prob.exprb
    self.thstar       = prob.getFixedPoint(self.Pss, self.expr, prob.Phi, prob.dsb, prob.Gamma, 1.)
    self.VTrueProj    = np.dot(prob.Phi, self.thstar)
    self.D            = np.diag(prob.dsb)
    self.normFactor   = np.dot(self.VTrueProj, np.dot(self.D, self.VTrueProj))
    self.MSPVE          = np.zeros(self.N)

  def getThstarMSPBE(self, Lmbda):
    return self.prob.getFixedPoint(self.Pss, self.expr, self.Phi, self.prob.dsb, self.prob.Gamma, Lmbda)

  def calcMSPVE(self, alg, t): # t is the number of the current step
    index               = t*self.N/self.T
    msediff             = np.dot(self.Phi, alg.estimate()) - self.VTrueProj
    self.MSPVE[index]  += np.dot( np.dot(msediff, self.D), msediff)
    if np.mod(t+1, self.T/self.N)==0:
      self.MSPVE[index]  /= self.T/self.N

  def getNormMSPVE(self):
    return self.MSPVE/self.normFactor


# Submitter: ggabrich(Gabricht, George)

import re
from goody import irange
from collections import defaultdict

# Before running the driver on the bsc.txt file, ensure you have put a regular
#   expression pattern in the files repattern1a.txt, repattern1b.txt, and
#   repattern2a.txt. The patterns must be all on the first line

def pages (page_spec : str, unique :  bool) -> [int]: #result in ascending order
    page_struct = (set() if unique else [])
    page_comp = re.compile(open('repattern2a.txt', 'r').read())
    for spec in page_spec.split(','):
        g1, g2, g3, g4 = page_comp.match(spec).groups()
        assert page_comp.match(spec), f'pages: in page specification {spec}, No Match Found!'
        if not g2:
            if unique: page_struct.add(int(g1))
            else: page_struct.append(int(g1))
        if g2 == '-':
            assert (int(g1) <= int(g3)), f'pages: in page specification {spec}, {g1} > {g3}.'
            if unique:
                if not g4: page_struct.update({pg for pg in irange(int(g1), int(g3))})
                else: page_struct.update({pg for pg in irange(int(g1), int(g3), int(g4))})
            else:
                if not g4: page_struct.extend([pg for pg in irange(int(g1), int(g3))])
                else: page_struct.extend([pg for pg in irange(int(g1), int(g3), int(g4))])
        elif g2 == ':':
            if unique:
                if not g4: page_struct.update({pg for pg in range(int(g1), int(g1)+int(g3))})
                else: page_struct.update({pg for pg in range(int(g1), int(g1)+int(g3), int(g4))})
            else:
                if not g4: page_struct.extend([pg for pg in range(int(g1), int(g1)+int(g3))])
                else: page_struct.extend([pg for pg in range(int(g1), int(g1)+int(g3), int(g4))])
    return sorted(page_struct)

def expand_re(pat_dict:{str:str}):
        for rule in sorted(pat_dict, key=(lambda x: len(pat_dict[x]))):
            rule_comp = re.compile(f'#{rule}#')
            for rule2 in sorted(pat_dict, key=(lambda y: len(pat_dict[y]))): pat_dict[rule2] = rule_comp.sub(f'(?:{pat_dict[rule]})', pat_dict[rule2])

if __name__ == '__main__':

    p1a = open('repattern1a.txt').read().rstrip() # Read pattern on first line
    print('Testing the pattern p1a: ',p1a)
    for text in open('bm1.txt'):
        text = text.rstrip()
        print('Matching against:',text)
        m = re.match(p1a,text)
        print(' ','Matched' if m != None else "Not matched")

    p1b = open('repattern1b.txt').read().rstrip() # Read pattern on first line
    print('\nTesting the pattern p1b: ',p1b)
    for text in open('bm1.txt'):
        text = text.rstrip()
        print('Matching against:',text)
        m = re.match(p1b,text)
        print('  ','Matched with groups ='+ str(m.groups()) if m != None else 'Not matched' )

    p2 = open('repattern2a.txt').read().rstrip() # Read pattern on first line
    print('\nTesting the pattern p2: ',p2)
    for text in open('bm2a.txt'):
        text = text.rstrip()
        print('Matching against:',text)
        m = re.match(p2,text)
        print('  ','Matched with groups ='+ str(m.groups()) if m != None else 'Not matched' )

    print('\nTesting pages function')
    for text in open('bm2b.txt'):
        text = text.rstrip().split(';')
        text,unique = text[0], text[1]=='True'
        try:
            p = pages(text,unique)
            print('  ','pages('+text+','+str(unique)+') = ',p)
        except:
            print('  ','pages('+text+','+str(unique)+') = raised exception')

    print('\nTesting expand_re')
    pd = dict(digit = r'[0-9]', integer = r'[+-]?#digit##digit#*')
    print('  Expanding ',pd)
    expand_re(pd)
    print('  result =',pd)
    # produces/prints the dictionary
    # {'digit': '[0-9]', 'integer': '[+-]?(?:[0-9])(?:[0-9])*'}

    pd = dict(integer       = r'[+-]?[0-9]+',
              integer_range = r'#integer#(..#integer#)?',
              integer_list  = r'#integer_range#(?,#integer_range#)*',
              integer_set   = r'{#integer_list#?}')
    print('\n  Expanding ',pd)
    expand_re(pd)
    print('  result =',pd)
    # produces/prints the dictionary
    # {'integer': '[+-]?[0-9]+',
    #  'integer_range': '(?:[+-]?[0-9]+)(..(?:[+-]?[0-9]+))?',
    #  'integer_list': '(?:(?:[+-]?[0-9]+)(..(?:[+-]?[0-9]+))?)(?,(?:(?:[+-]?[0-9]+)(..(?:[+-]?[0-9]+))?))*',
    #  'integer_set': '{(?:(?:(?:[+-]?[0-9]+)(..(?:[+-]?[0-9]+))?)(?,(?:(?:[+-]?[0-9]+)(..(?:[+-]?[0-9]+))?))*)?}'
    # }

    pd = dict(a='correct',b='#a#',c='#b#',d='#c#',e='#d#',f='#e#',g='#f#')
    print('\n  Expanding ',pd)
    expand_re(pd)
    print('  result =',pd)
    # produces/prints the dictionary
    # {'a': 'correct',
    #  'b': '(?:correct)',
    #  'c': '(?:(?:correct))',
    #  'd': '(?:(?:(?:correct)))',
    #  'e': '(?:(?:(?:(?:correct))))',
    #  'f': '(?:(?:(?:(?:(?:correct)))))',
    #  'g': '(?:(?:(?:(?:(?:(?:correct))))))'
    # }

    print()
    print()
    import driver
    driver.default_file_name = "bscq2F18.txt"
#     driver.default_show_traceback = True
#     driver.default_show_exception = True
#     driver.default_show_exception_message = True
    driver.driver()


def is_armstrong(number):
    in_val = number
    numbers = []
    while in_val > 0:
        numbers.append(in_val % 10)
        in_val = in_val // 10

    total = sum(i ** len(numbers) for i in numbers)

    return total == number


import os

from PostCardModel import PostCardListModel
from RecipientModel import RecipientListModel

class Database:
    """Class handling the loading/storage of the card/recipient databases."""

    CARDS_FILE = "cards.csv"
    SENT_CARDS_FILE = "sent.csv"
    RECIPIENTS_FILE = "recipients.csv"

    def __init__(self, rootFolder, folder):
        self.rootFolder = rootFolder
        self.storageFolder = os.path.join(rootFolder, folder)
        self.cardsPath = os.path.join(self.storageFolder, self.CARDS_FILE)
        self.sentCardsPath = os.path.join(self.storageFolder, self.SENT_CARDS_FILE)
        self.recipientsPath = os.path.join(self.storageFolder, self.RECIPIENTS_FILE)

        os.makedirs(self.storageFolder, exist_ok=True)

        # Load or create recipient list
        if os.path.isfile(self.recipientsPath):
            self.recipientListModel = RecipientListModel.fromFile(self.recipientsPath)
        else:
            self.recipientListModel = RecipientListModel()
            self.recipientListModel.toCsvFile(self.recipientsPath)

        # Load or create card list
        if os.path.isfile(self.cardsPath):
            self.postCardListModel = PostCardListModel.fromFile(self.cardsPath)
        else:
            self.postCardListModel = PostCardListModel()
            self.postCardListModel.toCsvFile(self.cardsPath)

        # Load or create sent cards list
        if os.path.isfile(self.sentCardsPath):
            self.sentCardsListModel = PostCardListModel.fromFile(self.sentCardsPath)
        else:
            self.sentCardsListModel = PostCardListModel()
            self.sentCardsListModel.toCsvFile(self.sentCardsPath)

        self.postCardListModel.setSentCardsListModel(self.sentCardsListModel)

    def getPostCardListModel(self):
        """Get the list of postcards."""
        return self.postCardListModel

    def getSentCardsListModel(self):
        """Get the list of sent postcards."""
        return self.sentCardsListModel

    def getRecipientListModel(self):
        """Get the list of recipients"""
        return self.recipientListModel

    def saveDatabase(self):
        """Save the modifications to the database into files."""
        self.recipientListModel.toCsvFile(self.recipientsPath)
        self.postCardListModel.toCsvFile(self.cardsPath)
        self.sentCardsListModel.toCsvFile(self.sentCardsPath)


# Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser.

import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output, State
import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
import json
import numpy as np
import pandas as pd
import io
import requests

########################################################################################
## Download the data
########################################################################################
def get_data_from_url(url):
    content = requests.get(url).content
    return pd.read_csv(io.StringIO(content.decode('utf-8')))

# COVID-19 Cases Data
phu_data_rolling = get_data_from_url('https://data.ontario.ca/dataset/1115d5fe-dd84-4c69-b5ed-05bf0c0a0ff9/resource/d1bfe1ad-6575-4352-8302-09ca81f7ddfc/download/cases_by_status_and_phu.csv')
ontario_daily = get_data_from_url('https://data.ontario.ca/dataset/f4f86e54-872d-43f8-8a86-3892fd3cb5e6/resource/ed270bb8-340b-41f9-a7c6-e8ef587e6d11/download/covidtesting.csv')
# COVID-19 Testing Data
df_test = get_data_from_url('https://data.ontario.ca/dataset/a2dfa674-a173-45b3-9964-1e3d2130b40f/resource/07bc0e21-26b5-4152-b609-c1958cb7b227/download/testing_metrics_by_phu.csv')
# COVID-19 Ontario ICU Data
df_ICU = get_data_from_url('https://data.ontario.ca/dataset/8f3a449b-bde5-4631-ada6-8bd94dbc7d15/resource/e760480e-1f95-4634-a923-98161cfb02fa/download/region_hospital_icu_covid_data.csv')
# COVID-19 Ontario Vaccine Data
df_Vaccine = get_data_from_url('https://raw.githubusercontent.com/ccodwg/Covid19Canada/master/timeseries_prov/vaccine_administration_timeseries_prov.csv')
# COVID-19 Ontario Age and Gender Data
df_age_gender = get_data_from_url('https://data.ontario.ca/dataset/f4112442-bdc8-45d2-be3c-12efae72fb27/resource/455fd63b-603d-4608-8216-7d8647f43350/download/conposcovidloc.csv')
# COVID-19 Testing Centers
df_testing_centre = get_data_from_url('https://data.ontario.ca/dataset/covid-19-assessment-centre-locations/resource/c60993bb-3988-4648-9be9-398dee480514/download/assessment_centre_locations.csv')

########################################################################################
## Modify the Data and Make Plot
########################################################################################

########################################################################################
# COVID-19 Statistics

# necessary global variables
ontario_daily.loc[:,'new_positive'] = ontario_daily['Confirmed Positive'].diff()
ontario_daily.loc[:,'new_cases']= ontario_daily['Total Cases'].diff()
ontario_daily.loc[:,'new_resolved']= ontario_daily['Resolved'].diff()
ontario_daily.loc[:,'new_death']= ontario_daily['Deaths'].diff()

today = ontario_daily.loc[ontario_daily['Reported Date']==ontario_daily['Reported Date'].max(),:]
active_cases = int(today['Confirmed Positive'])
total_cases = int(today['Total Cases'])
total_deaths = int(today['Deaths'])
total_recoveries = int(today['Resolved'])
total_tests = int(ontario_daily['Total tests completed in the last day'].sum())

new_positive_today = int(today['new_cases'])
new_recovered_today = int(today['new_resolved'])
new_deaths_today = int(today['new_death'])
tests_today = int(today['Total tests completed in the last day'])

if(new_positive_today < 0):
    new_positive_today = 0

########################################################################################
# Map Plot

# COVID-19 Cases Data for map plot
df = phu_data_rolling.groupby('PHU_NAME')['FILE_DATE'].max().reset_index()
df = df.merge(phu_data_rolling, on = ['PHU_NAME', 'FILE_DATE'])
df.reset_index(inplace=True, drop=True)

# modify testing centres to only contain currently active testing centres
df_testing_centre = df_testing_centre.loc[df_testing_centre['active']=='Yes']
df_testing_centre = df_testing_centre.loc[(df_testing_centre['latitude'].isna()==False)&(df_testing_centre['longitude'].isna()==False)]
df_testing_centre['longitude'] = pd.to_numeric(df_testing_centre['longitude'].str.strip())
df_testing_centre.loc[df_testing_centre['phone'].isna(),'phone'] = 'N/A'
df_testing_centre = df_testing_centre.loc[df_testing_centre['longitude'] != 0]

with open("Ministry_of_Health_Public_Health_Unit_Boundary Simplified.json") as f:
    boundary_data = json.load(f)

fig = px.choropleth_mapbox(df, geojson=boundary_data, featureidkey='properties.PHU_ID',
                           locations='PHU_NUM', color='ACTIVE_CASES',
                           color_continuous_scale="purpor",
                           #color_continuous_scale="agsunset",
                           range_color=(0, 4000),
                           mapbox_style="carto-positron",
                           zoom=4, center = {"lat": 48.31, "lon": -84.73},
                           opacity=0.5,
                           labels={'PHU_NUM': 'PHU Number'},
                           hover_data = ['PHU_NAME']
                          )

fig2 = px.scatter_mapbox(df_testing_centre,lat='latitude',lon='longitude',
                         hover_name='location_name',hover_data=['phone','website'],
                         mapbox_style="carto-positron",zoom=4, center = {"lat": 48.31, "lon": -84.73})

fig.add_trace(fig2.data[0])
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0}, dragmode=False)

########################################################################################
# PHU Bar Plot

# Needed for plotting phu bars
phu_dict_list = [{'label':name, 'value':name} for name in phu_data_rolling['PHU_NAME'].unique() if name is not np.nan]
phu_dict_list.append({'label':'ONTARIO','value':'ONTARIO'})

# Bar plot for phu data
colors = ['#d9534f','#5cb85c','#7289da']

phu_bar = go.Figure(data=[go.Bar(
    x=['Active', 'Recovered', 'Deaths'],
    y=[active_cases, total_recoveries, total_deaths],
    marker_color=colors # marker color can be a single color value or an iterable
)])
phu_bar.update_layout(
    yaxis_title="Number of Cases")

########################################################################################
# ICU Line Plot

## compute the ICU cases by different region
df_ICU_ONTARIO = df_ICU.groupby('date')['date', 'ICU'].agg('sum')
df_ICU_ONTARIO.reset_index(inplace = True)

# get icu dropdown list
icu_dict_list = [{'label':name + ' ONTARIO', 'value':name + ' ONTARIO'} for name in df_ICU['oh_region'].unique()]
icu_dict_list.append({'label':'ONTARIO','value':'ONTARIO'})

fig_ICU = go.Figure(data=[go.Scatter(
    x=df_ICU_ONTARIO.date,
    y=df_ICU_ONTARIO.ICU,
    name="ONTARIO",
    line=dict(color="#7289da"))])
fig_ICU.update_layout(
    xaxis_title="Date",
    yaxis_title="Number of ICU Cases")

########################################################################################
# Age and Gender Bar Plot

# modify gender feature to only contain female, male and other
df_age_gender.Client_Gender = df_age_gender.Client_Gender.replace(
    {'FEMALE': 'FEMALE', 'MALE': 'MALE',
    'UNSPECIFIED': 'OTHER',
    'GENDER DIVERSE': 'OTHER'})

# drop the missing age group and
df_age_gender = df_age_gender.loc[df_age_gender.Age_Group != 'UNKNOWN']
df_age_gender.Age_Group.dropna(inplace = True)
# change age group names
df_age_gender.Age_Group = df_age_gender.Age_Group.replace(
    {'<20': '0-19', '20s': '20-29', '30s': '30-39',
    '40s': '40-49', '50s': '50-59', '60s': '60-69',
    '70s': '70-79', '80s': '80-89', '90s': '90-99'})

# only keep case report date, gender and age
df_age_gender = df_age_gender[['Case_Reported_Date', 'Age_Group', 'Client_Gender']]
df_age_only = df_age_gender[['Case_Reported_Date', 'Age_Group']]

# create bar plots of total cases, cases by age groups, cases by exposure:
df_age_gender_date = df_age_gender[['Case_Reported_Date', 'Age_Group', 'Client_Gender']]
bar_df = df_age_gender_date.groupby('Case_Reported_Date')['Client_Gender'].agg(['count'])
bar_df.reset_index(inplace = True)

fig_bar1 = px.bar(x= pd.to_datetime(bar_df.iloc[:, 0]), y= bar_df.iloc[:, 1])
fig_bar1.update_layout(
    title="",
    xaxis_title="Case Reported Date",
    yaxis_title="Number of Reported Cases")
fig_bar1.update_traces(hovertemplate='Date: %{x}
Count: %{y}', selector=dict(type='bar'))

age_bar_df = df_age_gender_date.groupby(['Case_Reported_Date', 'Age_Group'])['Client_Gender'].agg(['count'])
age_bar_df.reset_index(inplace = True)
age_bar_df['Age_Group'] = age_bar_df['Age_Group'].astype(object)
fig_bar2 = px.bar(x= pd.to_datetime(age_bar_df['Case_Reported_Date']), y= age_bar_df['count'], color = age_bar_df['Age_Group'])
fig_bar2.update_layout(
    title="",
    xaxis_title="Case Reported Date",
    yaxis_title="Number of Reported Cases",
    legend_title_text='Age Group')
fig_bar2.update_traces(hovertemplate='Date: %{x}
Count: %{y}', selector=dict(type='bar'))

gender_bar_df = df_age_gender_date.groupby(['Case_Reported_Date', 'Client_Gender'])['Client_Gender'].agg(['count'])
gender_bar_df.reset_index(inplace = True)

fig_bar3 = px.bar(x= pd.to_datetime(gender_bar_df['Case_Reported_Date']), y= gender_bar_df['count'], color = gender_bar_df['Client_Gender'])
fig_bar3.update_layout(
    title="",
    xaxis_title="Case Reported Date",
    yaxis_title="Number of Reported Cases",
    legend_title_text='Gender')

fig_bar3.update_traces(hovertemplate='Date: %{x}
Count: %{y}', selector=dict(type='bar'))

# compute total count groupby age and gender
df_age_gender = df_age_gender.groupby(by=['Age_Group', 'Client_Gender']).count()
df_age_gender = df_age_gender.groupby(level = 0).apply(lambda x: 100 * x / float(x.sum()))
df_age_gender.reset_index(inplace = True)

# compute total count groupby age
df_age_only = df_age_only.groupby(by=['Age_Group']).count()
df_age_only = df_age_only.apply(lambda x: 100 * x / float(x.sum()))
df_age_only.reset_index(inplace = True)
# merge the df_age_gender and df_age_only
df_age_gender = df_age_gender.merge(df_age_only, on = 'Age_Group')
# compute the distribution of age and gender
df_age_gender['percent'] = df_age_gender['Case_Reported_Date_x'] * df_age_gender['Case_Reported_Date_y']/100

fig_age_gender = px.bar(df_age_gender, x="percent", y="Age_Group", color="Client_Gender",
             labels={'percent':'Proportion (%)', 'Age_Group': 'Age Group (Years)',
                    'Client_Gender': 'Gender'})

########################################################################################
# COVID-19 Positive Rate Bar Plot

## compute the population in each Public Health Unit
# convert string to integer
df_test['test_volumes_7d_avg'] = df_test['test_volumes_7d_avg'].apply(lambda x: int(x.replace(',', '')))
df_test['DATE']= pd.to_datetime(df_test['DATE'], dayfirst = True)

current_date = max(df_test['DATE'].unique())
df_test_current = df_test.loc[df_test['DATE'] == current_date]
df_test_current.reset_index(inplace=True, drop=True)

# compute the population for each PHU
df_test_current['pop'] = (df_test_current['test_volumes_7d_avg'] / df_test_current['tests_per_1000_7d_avg']) * 1000

## compute the COVID-19 positive rate by Public Health Unit and generate bar plot
df = df.merge(df_test_current, left_on='PHU_NUM', right_on='PHU_num')
df['positive_rate'] = (df['ACTIVE_CASES']/df['pop']) * 100
df = df.sort_values(by = 'positive_rate')
fig_positive_rate = px.bar(df, x='positive_rate', y='PHU_NAME', height=700,
                           # color='positive_rate',
                           #color_continuous_scale="purpor",
                           labels={'positive_rate': 'COVID-19 Active Cases Rate %',
                                   'PHU_NAME': 'Public Health Unit'})
fig_positive_rate.update_layout(margin=dict(l=4,r=4))
fig_positive_rate.update_traces(marker_color="#7289da")

########################################################################################
# Vaccine Administration Line Plot

# compute Ontario Vaccine Administration
df_Vaccine = df_Vaccine.loc[df_Vaccine['province'] == 'Ontario']
df_Vaccine['date_vaccine_administered']= pd.to_datetime(df_Vaccine['date_vaccine_administered'], dayfirst = True)
df_Vaccine.reset_index(inplace = True, drop = True)
fig_Vaccine = px.line(df_Vaccine, x = 'date_vaccine_administered', y = 'avaccine',
              labels={
                  'date_vaccine_administered': 'Date',
                  'avaccine': 'Vaccine Administered'
              })
fig_Vaccine.update_layout(margin=dict(r=8))

########################################################################################
# HTML Components

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])

# HTML components go here, control the heights using h classes with percent of screen height ##########
app.layout = dbc.Container(
    [
        #### Header
        dbc.Row([dbc.Col(html.H1("Ontario COVID-19 Dashboard")),
                dbc.Col(dbc.Button(
                            "Reference Data",
                            id="link-centered",
                            className="ml-auto",
                            href='https://data.ontario.ca/dataset/'
                            ), md=2, width=6)]),
        html.Hr(),

        #### COVID-19 Statistics
        dbc.Row(
            [
                dbc.Col(dbc.Card(
                    dbc.CardBody(
                        [dbc.Row([dbc.Col([html.H4("New Cases Today", className="card-title"),
                            html.H1('{:,}'.format(new_positive_today)),
                            ], width=6),
                            dbc.Col([html.H4("Total Cases", className="card-title"),
                            html.H1('{:,}'.format(total_cases)),
                            ], width=6)
                        ])

                        ]
                    ),
                    style={'text-align':'center',
                           'margin-top': '10px',
                           'margin-bottom': '5px',
                           'margin-left': '15px'},outline=True),md=6, width=6),
                dbc.Col(dbc.Card(
                    dbc.CardBody(
                        [dbc.Row([dbc.Col([html.H4("Deaths Today", className="card-title"),
                            html.H1('{:,}'.format(new_deaths_today)),
                            ], width=6),
                            dbc.Col([html.H4("Total Deaths", className="card-title"),
                            html.H1('{:,}'.format(total_deaths)),
                            ], width=6)
                        ])

                        ]
                    ),
                    style={'text-align':'center',
                           'margin-top': '10px',
                           'margin-bottom': '5px',
                           'margin-right': '15px'},outline=True),md=6, width=6),
            ]),
        dbc.Row(
            [
                dbc.Col(dbc.Card(
                    dbc.CardBody(
                        [dbc.Row([dbc.Col([html.H4("Recovered Today", className="card-title"),
                            html.H1('{:,}'.format(new_recovered_today)),
                            ], width=6),
                            dbc.Col([html.H4("Total Recovered", className="card-title"),
                            html.H1('{:,}'.format(total_recoveries)),
                            ], width=6)
                        ])

                        ]
                    ),
                    style={'text-align':'center',
                           'margin-top': '10px',
                           'margin-bottom': '5px',
                           'margin-left': '15px'},outline=True),md=6, width=6),
                dbc.Col(dbc.Card(
                    dbc.CardBody(
                        [dbc.Row([dbc.Col([html.H4("Tests Completed Today", className="card-title"),
                            html.H1('{:,}'.format(tests_today)),
                            ], width=6),
                            dbc.Col([html.H4("Total Tests Completed", className="card-title"),
                            html.H1('{:,}'.format(total_tests)),
                            ], width=6)
                        ])

                        ]
                    ),
                    style={'text-align':'center',
                           'margin-top': '10px',
                           'margin-bottom': '5px',
                           'margin-right': '15px'}, outline=True),md=6, width=6),
            ]),

        # main choropleth map
        dbc.Row(html.H3("Ontario COVID-19 Active Cases and Test Locations"),
               style={'margin-left': '15px'}),
        dbc.Row(
            dbc.Col(dcc.Graph(id='ontario-map',figure=fig),id="map-box"),
            style={'text-align':'center',
                           'margin-top': '10px',
                           'margin-bottom': '10px',
                           'margin-left': '20px',
                           'margin-right': '10px'}),

        # COVID-19 Cases and ICU plots
        dbc.Row(
            [
                dbc.Col(dbc.Card(
                    dbc.CardBody(
                        [dbc.Row([dbc.Col(html.H5('Number of Cases in'),md=4,width=3),
                                  dbc.Col(dcc.Dropdown(
                    options=phu_dict_list,
                    value='ONTARIO',
                    clearable=False,
                id="phu_dropdown"),md=8,width=9, align = "start")], align="start", form=True),
                         dbc.Row([dbc.Col(dcc.Graph(id='phu-bar',figure=phu_bar),id="phu-zone")])
                         ]
                    ),
                    style={'text-align': 'start',
                           'margin-top': '20px',
                           'margin-bottom': '5px',
                           'margin-left': '15px'}, outline=True), md=6, width=6),
                dbc.Col(dbc.Card(
                    dbc.CardBody(
                        [dbc.Row([dbc.Col(dcc.Dropdown(
                    options=icu_dict_list,
                    value='ONTARIO',
                    clearable=False,
                id="icu_dropdown"),md=4,width=4, align = "start"),
                            dbc.Col(html.H5('COVID-19 ICU Cases'),md=6,width=8)], align="start", form=True),
                         dbc.Row([dbc.Col(dcc.Graph(id='covid19-icu',figure=fig_ICU),id="line-box")])
                         ]
                    ),
                    style={'text-align': 'start',
                           'margin-top': '20px',
                           'margin-bottom': '5px',
                           'margin-right': '15px'}, outline=True), md=6, width=6),
            ]),

        # Age and Gender plots
        dbc.Row(
            [
                dbc.Col(dbc.Card(
                    dbc.CardBody(
                        [dbc.Row([dbc.Col(html.H5('COVID-19 Cases in Ontario by Reporting Date'))], align="start"),
                         dbc.Row([dbc.Col(dcc.Dropdown(
                                      options=[
                                          {'label': 'Total Cases', 'value': 'all'},
                                          {'label': 'by Age Group', 'value': 'age'},
                                          {'label': 'by Gender', 'value': 'gender'}
                                      ],
                                      value='all',
                                      clearable=False,
                                      id="dropdown"), md=4, width=4, align = "start")

                         ], align="start"),
                         dbc.Row([dbc.Col(dcc.Graph(id='covid19-casebar',figure=fig_bar1),id="ovid19-casebar")])
                         ]
                    ),
                    style={'text-align': 'start',
                           'margin-top': '20px',
                           'margin-bottom': '5px',
                           'margin-left': '15px'}, outline=True), md=6, width=6),
                dbc.Col(dbc.Card(
                    dbc.CardBody(
                        [dbc.Row([dbc.Col(html.H5('Age and Gender Distribution of COVID-19 Cases in Ontario'))]),
                         dbc.Row([dbc.Col(dcc.Graph(id='covid19-ageGender',figure=fig_age_gender),id="ageGender-box")])
                         ]
                    ),
                    style={'text-align': 'start',
                           'margin-top': '20px',
                           'margin-bottom': '5px',
                           'margin-right': '15px',
                           'height': '35rem'}, outline=True), md=6, width=6),
            ]),

        # COVID-19 Positive Rate and Vaccine plots
        dbc.Row(
            [
                dbc.Col(dbc.Card(
                    dbc.CardBody(
                        [dbc.Row([dbc.Col(html.H5('PHU Ranked by COVID-19 Positive Rate'))]),
                         dbc.Row([dbc.Col(dcc.Graph(id='covid19-positive',figure=fig_positive_rate),id="bar-box")]),
                        ]
                    ),
                    style={'text-align': 'start',
                           'margin-top': '20px',
                           'margin-bottom': '5px',
                           'margin-left': '15px'}, outline=True), md=7, width=8),
                dbc.Col(dbc.Card(
                    dbc.CardBody(
                        [dbc.Row([dbc.Col(html.H5('Ontario Daily Vaccine Administration'))], align="start"),
                         dbc.Row([dbc.Col(dcc.Graph(id='covid19-vaccine',figure=fig_Vaccine),id="vaccine-box")])
                        ]
                    ),
                    style={'text-align': 'center',
                           'margin-top': '20px',
                           'margin-bottom': '5px',
                           'margin-right': '15px'}, outline=True), md=5, width=4),
            ]),
    ],
    fluid=True,
    style={"height":"100vh"}
)

@app.callback(
    Output('phu-bar', 'figure'),
    [Input('phu_dropdown', 'value')])
def update_phu_bar(value):
    #too many plots to precompute. Compute plot dynamically
    if value is not None:
        if value=='ONTARIO':
            phu_bar.update_layout(
                margin=dict(t=50))
            return phu_bar
        else:
            #compute new plot
            phu_df = phu_data_rolling.loc[phu_data_rolling['PHU_NAME']==value]
            phu_df = phu_df.loc[phu_df['FILE_DATE'] == phu_df['FILE_DATE'].max()]
            phu_bar2 = go.Figure(data=[go.Bar(
                x=['Active', 'Recovered', 'Deaths'],
                y=[int(phu_df['ACTIVE_CASES']), int(phu_df['RESOLVED_CASES']), int(phu_df['DEATHS'])],
                marker_color=colors
            )])
            phu_bar2.update_layout(
                margin=dict(t=50), yaxis_range=[0,100000])
            phu_bar.update_layout(
                yaxis_title="Number of Cases")
            return phu_bar2
    return phu_bar

# ICU Scatter Plot
@app.callback(
    Output('covid19-icu', 'figure'),
    [Input('icu_dropdown', 'value')])
def update_icu_scatter(value):
    color_dict = {'CENTRAL ONTARIO': "#7f8bf5", 'TORONTO ONTARIO': "#445bab",
                 'WEST ONTARIO': "#0fba7c", 'EAST ONTARIO': "#4b9cfc", 'NORTH ONTARIO': "#d461f2"}

    #too many plots to precompute. Compute plot dynamically
    if value is not None:
        if value=='ONTARIO':
            fig_ICU.update_layout(
                margin=dict(t=50))
            return fig_ICU
        else:
            #compute new plot
            df_ICU_temp= df_ICU.loc[df_ICU.oh_region == value.split()[0]]
            icu_temp = go.Figure(data=[go.Scatter(
                x=df_ICU_temp.date,
                y=df_ICU_temp.ICU,
                name=value,
                line=dict(color=color_dict[value]))])

            icu_temp.update_layout(
                margin=dict(t=50), yaxis_range=[0,450])
            icu_temp.update_layout(
                xaxis_title="Date",
                yaxis_title="Number of ICU Cases")
            return icu_temp
    return icu_temp

@app.callback(
    Output('covid19-casebar', 'figure'),
    [Input('dropdown', 'value')])
def update_figure(value):
    if value is not None:
        if value=='all':
            fig_bar1.update_layout(
                margin=dict(t=20))
            return fig_bar1
        elif value=='age':
            fig_bar2.update_layout(
                margin=dict(t=20))
            return fig_bar2
        else:
            fig_bar3.update_layout(
                margin=dict(t=20))
            return fig_bar3
    return fig_bar1

if __name__ == '__main__':
    # port=8000, host='127.0.0.1'
    # debug=True
    app.run_server(debug=True)


from http.client import ACCEPTED
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework.serializers import Serializer
from .models import UserModel, Meep
from .serializers import FollowerSerializer, UserSerializer, MeepSerializer, MeepFeedSerializer
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from rest_framework.authtoken.models import Token
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework import status
import json

from meepit import serializers

# Create your views here.
@api_view(['POST',])
@permission_classes((AllowAny,))
def SignUp(request):
    if request.method == 'POST':
        serializer = UserSerializer(data = request.data)
        data = {}
        if serializer.is_valid():
            user = serializer.save()
            data['response'] = "User registration successful"
            data['email'] = user.email
            data['uname'] = user.uname
            token = Token.objects.get(user=user).key
            data['token'] = token
            return JsonResponse(data, status=status.HTTP_200_OK)
        else:
            return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['POST'])
@permission_classes((IsAuthenticated,))
def CreateMeep(request):

    if request.method == 'POST':
        user = request.user
        serializer = MeepSerializer(data = request.data,context={'userid': user.id})
        data = {}
        if serializer.is_valid():
            meep = serializer.save()
            data['response'] = "Meep successfully created"
            data['meeptext'] = meep.meeptext
            data['user'] = str(user)
            return JsonResponse(data, status=status.HTTP_200_OK)
        else:
            return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['POST'])
@permission_classes((IsAuthenticated,))
def FollowPerson(request,uname):

    if request.method == 'POST':
        user = request.user
        serializer = FollowerSerializer(data = request.data,context={'userid':user.id,'person':uname})
        data = {}
        if serializer.is_valid():
            follower = serializer.save()
            data['response'] = "Follow successful"
            data['Follower'] = str(follower.follower)
            data['Followed Person'] = str(follower.person)
            return JsonResponse(data, status=status.HTTP_200_OK)
        else:
            return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET'])
@permission_classes((IsAuthenticated,))
def LoadMeeps(request):
    if request.method == 'GET':
        user = request.user
        meeps = MeepFeedSerializer(data=request.data,context={'userid':user.id})
        meepit = meeps.save()
        l = []
        if meeps.is_valid():
            for i in meepit:
                l.append(str(i.userid)+": "+str(i.meeptext))
            return JsonResponse(l,safe=False, status=status.HTTP_200_OK)
        else:
            return JsonResponse(meeps.errors, status=status.HTTP_400_BAD_REQUEST)


#Arithmetic Operators
# print("5 + 6 is ", 5 + 6)
# print("5 - 6 is ", 5 - 6)
# print("5 * 6 is ", 5 * 6)
# print("5 / 6 is ", 5 / 6)
# print("5 ** 6 is ", 5 ** 6)
# print("5 // 6 is ", 5 // 6)

#Assignment Operators
a=5
print(a)
b=1
b +=1
print(b)
c=2
c -=1
print(c)
d=3
d *=1
print(d)
e=5
e /=3
print(e)
f=5
f %= 2
print(f)
g=5
g //= 3
print(g)
h=5
h **= 2
print(h)
i=5
i &= 1  # & ->bitwise and operator
print(i)
j=5
j |= 1  # | ->bitwise or operator
print(j)
k=5
k ^= 3  # ^ ->bitwise xor operator
print(k)
l=5
l >>= 2  # >>= ->bitwise right shift
print(l)
m=5
m <<= 2  # <<= ->bitwise left shift
print(m)

#Comparison Operators
# i=5
# print(i==10)
# print(i!=10)
# print(i<10)
# print(i>10)
# print(i<=10)
# print(i>=10)

#Logical Operators
# a=True
# b=False
# print(a and b)  #and->and operator if both are true then return true otherwise false
# print(a or b)   #or->or operator if one of them are true then return true otherwise false
# print(not b)   #not->if true return false if false then return true

#Identity Operators
# a=5
# b=6
# print(a is b)
# print(a is not b)

#Membership Operators
# list=[1,2,3,4,5,6,7]
# print(7 in list)
# print(8 in list)
# print(7 not in list)
# print(8 not in list)

#Bitwise Operators
#Bitwise and Operator
# print(0 & 0)
# print(0 & 1)
# print(1 & 0)
# print(1 & 1)
# print(2 & 3)

#Bitwise or operator
# print(0 | 0)
# print(0 | 1)
# print(1 | 0)
# print(1 | 1)
# print(2 | 3)

#Bitwise xor operator
# print(0 ^ 0)
# print(0 ^ 1)
# print(1 ^ 0)
# print(1 ^ 1)

# Bitwise not operator
# a=10
# print(~a) #not operator->first increement by one and place negative sign

# Bitwise zero fill left shift operator
# a=5
# print(a << 2) #first convert 5 into binary and left shift the digits 2 times(one by one) and in blank spaces place 0

# Bitwise signed right shift operator
# a=6
# print(a >> 2) #first convert 6 into binary and right shift the digits 2 times(one by one) and in blank spaces place 0


from celda import Celda

class ColaEncadenada:
    __cant = 0
    __primer = None
    __ultimo = None

    def __init__(self, cant=0):
        self.__cant = cant

    def vacia(self):
        return self.__cant == 0

    def insertar(self, dato):
        aux = Celda(dato)
        aux.setSiguiente(None)
        if self.__ultimo is None:
            self.__primer = aux
            self.__ultimo = aux
            self.__cant += 1
        else:
            self.__ultimo.setSiguiente(aux)
            self.__ultimo = aux
            self.__cant += 1
        return self.__ultimo.getDato()

    def suprimir(self):
        if self.vacia():
            print('Cola vacía.')
            x = -1
        else:
            aux = self.__primer
            x = aux.getDato()
            self.__primer = self.__primer.getSiguiente()
            self.__cant -= 1
            print(type(self.__primer))
            if self.__primer is None:
                self.__ultimo = None
            del aux
        return x

    def recorrer(self):
        aux = self.__primer
        while aux is not None:
            dato = aux.getDato()
            print(dato)
            aux = aux.getSiguiente()


import os

from flask import Flask

from flask import request

import requests, json

app = Flask(__name__)

@app.route('/')
def hello():
    default_t = 10
    degree = request.args.get('apparent_t')
    if degree is not None and len(degree) != 0:
        try:
            default_t = float(degree)
        except:
            print("degree is not float, ignore")
    createErrorResponse = request.args.get('createErrorResponse')
    url = "http://www.bom.gov.au/fwo/IDN60801/IDN60801.95765.json"
    if (createErrorResponse == "True"):
        url += ".error"
    user_agent = {'User-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'}
    response_obj = requests.get(url, headers = user_agent)
    if response_obj.status_code != 200:
        rsp = {
                'error': "Error Connecting to BOM. Reason: " + response_obj.reason
            }
        rsp_code = 503
    else:
        response_text = response_obj.text
        response = json.loads(response_text)
        station_list = []
        item = {}
        for station in response['observations']['data']:
            if station['apparent_t'] > default_t:
                item = {
                        'name': station['name'],
                        'apparent_t': station['apparent_t'],
                        'lat': station['lat'],
                        'lon': station['lon']
                    }
                station_list.append(item)
                station_list.sort(key=lambda x: x.get('apparent_t'))
        print(station_list)
        rsp = {
                'response': station_list
            }
        rsp_code = 200
    return json.dumps(rsp), rsp_code

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


#!/usr/bin/env python3

import re

def findName(str):
    regex = re.compile(r'[A-Z][a-z]+\s[A-Z][a-z]+')
    ans = regex.search(str)

    if ans is not None:
        print(ans.group())

findName("Zeng Runquan")


import unittest
import Tkinter

from ropeide.uihelpers import EnhancedList, EnhancedListHandle
from ropeide.uihelpers import TreeView, TreeViewHandle

class SampleListHandle(EnhancedListHandle):

    def __init__(self):
        pass

    def entry_to_string(self, integer_obj):
        return 'element ' + str(integer_obj)

class SampleTreeHandle(TreeViewHandle):

    def __init__(self):
        pass

    def entry_to_string(self, string_obj):
        return 'element ' + str(string_obj)

    def get_children(self, string_obj):
        if len(string_obj) > 2:
            return []
        return [string_obj + str(i) for i in range(3)]

class UIHelpersTest(unittest.TestCase):

    def setUp(self):
        super(UIHelpersTest, self).setUp()
        self.parent = Tkinter.Frame()

    def tearDown(self):
        self.parent.destroy()
        super(UIHelpersTest, self).tearDown()

    def test_enhanced_inserting_clearing(self):
        handle = SampleListHandle()
        enhanced_list = EnhancedList(self.parent, handle)
        enhanced_list.add_entry(1)
        enhanced_list.add_entry(2)
        self.assertEquals(2, enhanced_list.list.size())
        enhanced_list.clear()
        self.assertEquals(0, enhanced_list.list.size())

    def test_enhanced_list_to_string(self):
        handle = SampleListHandle()
        enhanced_list = EnhancedList(self.parent, handle)
        enhanced_list.add_entry(1)
        self.assertEquals('element 1', enhanced_list.list.get(0))

    def test_tree_view(self):
        handle = SampleTreeHandle()
        tree_viewer = TreeView(self.parent, handle)
        tree_viewer.add_entry('a')
        self.assertTrue(tree_viewer.get(0).endswith('element a'))

    def test_tree_view_expanding(self):
        handle = SampleTreeHandle()
        tree_viewer = TreeView(self.parent, handle)
        tree_viewer.add_entry('a')
        tree_viewer.expand(0)
        self.assertEquals(4, tree_viewer.size())
        self.assertTrue(tree_viewer.get(0).endswith('element a'))
        self.assertTrue(tree_viewer.get(1).endswith('element a0'))
        self.assertTrue(tree_viewer.get(2).endswith('element a1'))
        self.assertTrue(tree_viewer.get(3).endswith('element a2'))

    def test_tree_view_multi_expanding(self):
        handle = SampleTreeHandle()
        tree_viewer = TreeView(self.parent, handle)
        tree_viewer.add_entry('a')
        tree_viewer.expand(0)
        tree_viewer.expand(0)
        self.assertEquals(4, tree_viewer.size())

    def test_tree_view_shrinking(self):
        handle = SampleTreeHandle()
        tree_viewer = TreeView(self.parent, handle)
        tree_viewer.add_entry('a')
        tree_viewer.expand(0)
        self.assertEquals(4, tree_viewer.size())
        tree_viewer.collapse(0)
        self.assertEquals(1, tree_viewer.size())
        self.assertTrue(tree_viewer.get(0).endswith('element a'))

    def test_expansion_signs(self):
        handle = SampleTreeHandle()
        tree_viewer = TreeView(self.parent, handle)
        tree_viewer.add_entry('a')
        self.assertEquals('+ element a', tree_viewer.get(0))
        tree_viewer.expand(0)
        self.assertEquals('- element a', tree_viewer.get(0))
        tree_viewer.collapse(0)
        self.assertEquals('+ element a', tree_viewer.get(0))

    def test_expansion_signs_for_leaves(self):
        handle = SampleTreeHandle()
        tree_viewer = TreeView(self.parent, handle)
        tree_viewer.add_entry('a00')
        self.assertEquals('  element a00', tree_viewer.get(0))
        tree_viewer.expand(0)
        self.assertEquals('  element a00', tree_viewer.get(0))

    def test_expansion_signs(self):
        handle = SampleTreeHandle()
        tree_viewer = TreeView(self.parent, handle)
        tree_viewer.add_entry('a')
        self.assertEquals('+ element a', tree_viewer.get(0))
        tree_viewer.toggle(0)
        self.assertEquals('- element a', tree_viewer.get(0))
        tree_viewer.toggle(0)
        self.assertEquals('+ element a', tree_viewer.get(0))

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


# -*- coding: utf-8 -*-
"""
Created on Thu Feb 14 22:44:36 2019

@author: sathvik
"""

import cv2
import numpy as np
img=cv2.imread('C:\\Users\\sathvik\\Desktop\\opencv\\butterfly.jpeg',1)

img=cv2.GaussianBlur(img,(5,5),0)
cv2.imshow("image",img)
cv2.waitKey(0)

cv2.imwrite("GaussianBlur.jpeg",img)
cv2.destroyAllWindows()


import pandas as pd
from .velocity import velocity_mean

def throughput(velocity_df: pd.DataFrame, start_step: int = 0, end_step: int = None, road_length: int = 100):
    if end_step is None:
        end_step = len(velocity_df)

    df = velocity_df.iloc[start_step:end_step, :]
    vehicle_number = len(df.columns)

    mean = velocity_mean(velocity_df, start_step, end_step)
    return vehicle_number * mean / road_length


import requests
from time import sleep

bot_token = "BOT_TOKEN"
channel_id = "@channel_name"

def telegram_bot_send_text(bot_message):
    """Отправляем сообщение в канал через телеграм бота"""
    send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + channel_id + '&parse_mode=Markdown&text=' + bot_message
    response = requests.get(send_text).json()
    sleep(0.1)
    return response

if __name__ == "__main__":
    telegram_bot_send_text("IMPORT TELEGRAM")


"""#529. Minesweeper

https://leetcode.com/problems/minesweeper/
"""

''' SOlution1  DFS'''
class Solution(object):

    def check_range(self,i,j):
        if i >=0 and i < len(self.board) and j >=0 and j < len(self.board[0]):
            return True
        else:
            return False

    def check_adjacent_mines(self,i,j):
        num_of_mines= 0
        # COUNT NUMBER OF MINES
        for dir in self.dirs:
            pi,pj = i+dir[0],j+ dir[1]
            if self.check_range(pi,pj) :
                if self.board[pi][pj] == "M":
                    num_of_mines+=1

        return num_of_mines

    def updateBoard(self, board, click):
        """
        :type board: List[List[str]]
        :type click: List[int]
        :rtype: List[List[str]]
        """
        self.board=board
        self.dirs = [ [-1,1],[0,1],[1,1],[-1,0],[1,0],[-1,-1],[0,-1],[1,-1]]
        stop_tag= False

        if stop_tag is False:
            if self.check_range(click[0],click[1]):
            #If a mine ('M') is revealed, then the game is over - change it to 'X'.
                if board[click[0]][click[1]]=="M":
                    board[click[0]][click[1]]="X"
                    stop_tag = True
                    return board

                elif  board[click[0]][click[1]]=="E" :
                    numofmines_adj = self.check_adjacent_mines(click[0],click[1])

                    if    numofmines_adj==0 :
                        board[click[0]][click[1]]="B"
                        for dir in self.dirs:
                            pi,pj = click[0]+dir[0],click[1]+ dir[1]
                            self.updateBoard( board, [pi,pj])

                    else:#numofmines_adj>0 ):
                        board[click[0]][click[1]]= str(numofmines_adj)

                    stop_tag= True

        return board


#记忆化搜索(自顶向下的解决问题)
MAXSIZE = 1000
memo = [-1 for i in range(MAXSIZE)]
def fib3(n,memo):
    if n <= 0:
        return n
    if memo[n] == -1:
        memo[n] = fib3(n-1,memo) + fib3(n-2,memo)
    return memo[n]
print(fib3(6,memo))

#动态规划(自底向上的解决问题)
def fib2(n):
    memo = [-1 for x in range(n+1)]
    memo[0] = 0
    memo[1] = 1
    for i in range(2, n+1):
        memo[i] = memo[i-1]+memo[i-2]
    return memo[n]

print(fib2(6))


from aiogram import Dispatcher, types
from aiogram.dispatcher.filters import Text
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.state import State, StatesGroup
from data_base.sqlite_db import sql_add_command
from keyboards import admin_kb

class FSMAdmin(StatesGroup):
    photo = State()
    name = State()
    description = State()
    price = State()

async def cm_open_keyboard(message: types.Message):
    if (message.from_user.username == "Imitater"):
        await message.answer("Клавиатура админа открыта!",
                             reply_markup=admin_kb.edit_kb)
    else:
        await message.answer("ТЫ НЕ АДМИН!")

# dp.message_handler(commands='Загрузить', state=None)
async def cm_start(message: types.Message):
    await FSMAdmin.photo.set()
    await message.reply('Загрузи фото')

# dp.message_handler(content_types=['photo'], state=FSMAdmin.photo)
async def load_photo(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['photo'] = message.photo[0].file_id
    await FSMAdmin.next()
    await message.reply("Теперь введи название")

# dp.message_handler(state=FSMAdmin.name)
async def load_name(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['name'] = message.text
    await FSMAdmin.next()
    await message.reply("Введи описание")

# dp.message_handler(state=FSMAdmin.description)
async def load_description(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['description'] = message.text
    await FSMAdmin.next()
    await message.reply("Введи цену")

# dp.message_handler(state=FSMAdmin.price)
async def load_price(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['price'] = float(message.text)
    await sql_add_command(state=state)
    # после этой команды полностью очищается словарь с данными, введеными во время состояния
    await state.finish()

async def cansel_handler(message: types.Message, state: FSMContext):
    current_state = await state.get_state()
    if current_state is None:
        return
    await state.finish()
    await message.reply("ОК")

def register_handlers_admin(dp: Dispatcher):
    dp.register_message_handler(
        cm_open_keyboard, Text(equals="Открыть клавиатуру"))
    dp.register_message_handler(cm_start, commands=["Загрузить"], state=None)
    dp.register_message_handler(cansel_handler, state="*", commands='отмена')
    dp.register_message_handler(cansel_handler, Text(
        equals='отмена', ignore_case=True), state="*")
    dp.register_message_handler(load_photo, content_types=[
                                'photo'], state=FSMAdmin.photo)
    dp.register_message_handler(load_name, state=FSMAdmin.name)
    dp.register_message_handler(load_description, state=FSMAdmin.description)
    dp.register_message_handler(load_price, state=FSMAdmin.price)


"""
    Victor Chimenti
    CPSC 5510 FQ18
    http_cli.py
    v2.0
    Created           10/19/2018
    Last Modified     11/15/2018
    Simple Web Client in Python3
    /usr/local/python3/bin/python3
"""

"""
# v2 includes updates for web server assignment including:
    # fixed Command Line parameters feedback -2 points
    # fixed URL Handling feedback -2 points
    # fixed HTTP Request feedback -2 points
    # fixed Error Handling feedback -4 points
    # fixed Discretionary feedback -3 points
    # Sends & Receives HTTP Messages feedback -5 points
"""

import socket           # network sockets
import sys              # io and error handling

# set defaults
port = 80                               # default port is 80 web server standard
path = ""                               # declare path with empty string
min_URL = 5                             # minimum length of an acceptable URL
buffer_length = 0                       # default buffer length
charset = "UTF-8"                       # default encoding protocol

# set constants
DOUBLE_SLASH = "//"                     # delimiter for parsing URLs
SINGLE_SLASH = "/"                      # delimiter for parsing URL paths
COLON = ":"                             # delimiter for parsing port from URL
SEMI_COLON = ";"                        # delimiter for parsing data from header
NEW_LINE = "\r\n"                       # delimiter for new line return
END_HEADER = "\r\n\r\n"                 # delimiter for parsing header and body
MATCH_ALL = "0.0.0.0"                   # for IP validity checking

# get user input from command line
try:
    user_input = sys.argv[1]
except IndexError:
    sys.stderr.write("ERROR No Valid Command Line Input : ")
    sys.exit("Exiting Program")
except KeyError:
    sys.stderr.write("ERROR Invalid Charcter Entered : ")
    sys.exit("Exiting Program")
except Exception:
    sys.stderr.write("ERROR Invalid Command Line Entry : ")
    sys.exit("Exiting Program")

# parse user_input to expose full URL
try:
    x = user_input.find(DOUBLE_SLASH)
    # if no http:// protocol was entered by the user
    if x == -1 : full_URL = user_input
    # if an http:// protocol was entered with the URL
    else : protocol, full_URL = (user_input.split(DOUBLE_SLASH, 2))
except Exception:
    sys.stderr.write("ERROR Parsing User Input : ")
    sys.exit("Exiting Program")

# validate full_URL
x = len(full_URL)
if x < 5:
    sys.stderr.write("ERROR Invalid URL Format : ")
    sys.exit("Exiting Program")

# parse full URL for domain, path and port number
x = full_URL.find(COLON)
# if there is a COLON in the user input
if x != -1:
    try:
        # parse the host domain from the full URL
        host, portPathway = (full_URL.split(COLON, 2))
    except Exception:
        sys.stderr.write("ERROR Parsing Host input : ")
        sys.exit("Exiting Program")

    # search for a path after the port number
    y = portPathway.find(SINGLE_SLASH)
    try:
        # if there is a path after the port number
        if y != -1:
            portstr = portPathway[:y]
            path = portPathway[y:]
            port = int(portstr)
        else:
            port = int(portPathway)
    except Exception:
        sys.stderr.write("ERROR Parsing Port Number : ")
        sys.exit("Exiting Program")

# if there is no COLON in the user input, then use default port
else:
    try:
        # parse domain from path with new delimiter
        x = full_URL.find(SINGLE_SLASH)
        if x != -1:
            host = full_URL[:x]
            path = full_URL[x:]
        else:
            host = full_URL
            path = SINGLE_SLASH
    except Exception:
        sys.stderr.write("ERROR Parsing Path : ")
        sys.exit("Exiting Program")

# confirm that the path contains any value after first slash
x = len(path)
if x <= 1:
    path = SINGLE_SLASH

# validate URL entered and assign host IP number
try:
    host_ip = socket.gethostbyname(host)
except socket.gaierror:
    sys.stderr.write("ERROR Invalid URL Entered : ")
    sys.exit("Exiting Program")

# convert host IP number to integer
host_ip_str = str(host_ip)
if host_ip_str == MATCH_ALL:
        sys.stderr.write("ERROR Invalid IP Number : ")
        sys.exit("Exiting Program")

# Set up a TCP/IP socket
try:
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except OSError:
    sys.stderr.write("ERROR Creating Socket : ")
    sys.exit("Exiting Program")

# Connect to the server as a client
sock.settimeout(10)
try:
    sock.connect((host, port))
except OSError:
    sys.stderr.write("ERROR Connecting : ")
    sys.exit("Exiting Program")

# prepare message for server with delimiter included
message = "GET " + path \
                 + " HTTP/1.1\r\nConnection: close\r\nHost: " \
                 + host \
                 + END_HEADER

# display GET Request
try:
    sys.stderr.write(message)
except Exception:
    sys.stderr.write("ERROR Standard Error Write : ")
    sys.exit("Exiting Program")

# send message to the web server
try:
    sock.sendall(message.encode(charset))
    # tell server I am sending only 1 message
    sock.shutdown(1)
except UnicodeError:
    sys.stderr.write("Error Encoding Message : ")
    sys.exit("Exiting Program")
except OSError:
    sys.stderr.write("ERROR Sending Data : ")
    sys.exit("Exiting Program")

# encode the Header delimiter to binary
try:
    delim_in_bytes = END_HEADER.encode(charset)
except UnicodeError:
    sys.stderr.write("ERROR Encoding Delimiter : ")
    sys.exit("Exiting Program")

# receive message back from server in byte stream
binary_header = bytearray()
binary_body = bytearray()

# receive only the header first one byte at a time
try:
    while True:
        response = sock.recv (1)
        binary_header += response
        x = binary_header.find(delim_in_bytes)
        if x != -1: break
except OSError:
    sys.stderr.write("ERROR Receiving Header : ")
    sys.exit("Exiting Program")

# decode the header
try:
    response_header = binary_header.decode(charset)
except OSError:
    sys.stderr.write("ERROR Decoding Image Header : ")
    sys.exit("Exiting Program")

# print the Header
try:
    sys.stderr.write(response_header)
except Exception:
    sys.stderr.write("ERROR Writing Response Header : ")
    sys.exit("Exiting Program")

# initialize variables for to parse header content
LENGTH_FIELD = "Content-Length:"
TYPE_FIELD = "Content-Type:"
CHARSET_FIELD = "charset="
TEXT = "text"
IMAGE = "image"
message_type = ""
char_field = ""
msg_length = 0

# check for status code
STATUS_CODE = "200 OK"
sc = response_header.find(STATUS_CODE)

# if the status code is 200 OK
if sc != -1:

    # parse header for content type
    x = response_header.find(TYPE_FIELD)
    # parse content type for character set
    y = response_header.find(CHARSET_FIELD)
    # parse header for content size
    z = response_header.find(LENGTH_FIELD)
    # parse response header for content type field
    if x != -1:
        try:
            ignore_field, ignore_type, message_type  = \
                response_header.partition(TYPE_FIELD)
            # parse content type field for the type
            message_type, ignore_SEMI_COLON, char_field = \
                message_type.partition(SEMI_COLON)
        except Exception :
            sys.stderr.write("ERROR Partitioning Content-Type: ")
            sys.exit("Exiting Program")

    # or else it's an invalid header
    else:
        sys.stderr.write("ERROR Parsing Header : ")
        sys.exit("Exiting Program")

    # parse the remainder for the charset field if present
    if y != -1:
        try:
            ignore_field, char_field, charset = \
                char_field.partition(CHARSET_FIELD)
            # parse the charset field for the value
            charset, ignore, ignore_field = \
                charset.partition(NEW_LINE)
        except Exception:
            sys.stderr.write("ERROR Parsing for charset= : ")
            sys.exit("Exiting Program")
    # else use the default charset assignment

    # parse response_header for the message length
    if z != -1:
        # find the field containing the length
        try:
            ignore_field, target_field, size_field = \
                response_header.partition(LENGTH_FIELD)
        except Exception:
            sys.stderr.write("ERROR Parsing for Content-Length : ")
            sys.exit("Exiting Program")

        # slice the length from the header
        try:
            buf_str, ignore_nl, ignore_field = size_field.partition('\r\n')
        except Exception:
            sys.stderr.write("ERROR Assigning Length to String : ")
            sys.exit("Exiting Program")

        # convert length to an int
        try:
            msg_length = int(buf_str)
        except Exception:
            sys.stderr.write("ERROR Assigning the Message Length : ")
            sys.exit("Exiting Program")

    # or else there is no length in the header
    else:
        sys.stderr.write("ERROR Invalid Header : Length Not Given : ")
        sys.exit("Exiting Program")

    # receive message body from server in byte stream
    recv_buffer = 0

    # receive body one byte at a time until all of message received
    try:
        while True:
            body = sock.recv(1)
            binary_body += body
            recv_buffer += 1
            if recv_buffer >= msg_length: break
    except OSError:
        sys.stderr.write("ERROR Receiving Body : ")
        sys.exit("Exiting Program")

    # add delimiter for formatting output
    binary_body += delim_in_bytes

    # determine content type and print the message body
    x = message_type.find(TEXT)
    y = message_type.find(IMAGE)

    # decode and print text/html message body
    if x != -1:
        try:
            response_body = binary_body.decode(charset)
            sys.stdout.write(response_body)
        except Exception:
            sys.stderr.write("ERROR Writing Text Response Body : ")
            sys.exit("Exiting Program")

    # print image message body
    elif y != -1:
        try:
            sys.stdout.buffer.write(binary_body)
        except Exception:
            sys.stderr.write("ERROR Writing Image Response Body : ")
            sys.exit("Exiting Program")

    # or else it is not a valid content-type
    else:
        sys.stderr.write("ERROR Invalid Content-Type : ")
        sys.exit("Exiting Program")

# or else the Status Code is not 200 OK
else:
    try:
        response_body = binary_body.decode(charset)
        sys.stdout.write(response_body)
    except Exception:
        sys.stderr.write("ERROR Writing Response Body : Status Code not 200 OK : ")
        sys.exit("Exiting Program")

# Close the Socket
sock.close()
# Close the program
sys.exit()
# eof


import numpy as np
from numpy import loadtxt
from numpy.linalg import norm as de

file1 = './DATA_DTW/FC1_1.txt'
file2 = './DATA_DTW/FC2_2.txt'

def loadmat(f1, f2):
    sig1 = loadtxt(f1)
    sig2 = loadtxt(f2)
    return np.zeros(len(sig1) * len(sig2)).reshape((len(sig1), len(sig2))), sig1, sig2

def distance_euclidienne(f1, f2):
    M, sig1, sig2 = loadmat(f1, f2)
    for i in range(len(sig1)):
        for j in range(len(sig2)):
            M[i,j] = de(sig1[i] - sig2[j])
    return M

def distance_elastique(f1, f2):
    M, sig1, sig2 = loadmat(f1, f2)
    M = distance_euclidienne(f1, f2)
    for i in range(1, len(sig1)):
        for j in range(1, len(sig2)):
            M[i,j] += min(M[i-1, j-1], M[i-1, j], M[i, j-1])
    return M

def distance_total(M):
    return sum(sum(M)) / (M.shape[0] * M.shape[1])

print(distance_total(distance_euclidienne(file1, file2)))
print(distance_total(distance_elastique(file1, file2)))

def pcc(m):
    ret = []
    for sm in m:
        ret.append(np.argmin(sm[1:]))
    return ret

print(pcc(distance_euclidienne(file1, file2)))
print(pcc(distance_elastique(file1, file2)))


def welcome_message():
    print("""
    This program calculates the power of numbers.
    You can choose the exponent value and ...
    You can chose the limit of the calculations
    """)

welcome_message()

def input_values():
    # print(welcome_message())
    # base_number = int(input("Please, enter the base value: "))
    exponent_number = int(input("Enter the exponent value:"))
    print(" ")
    limit_number = int(input("Enter the limit value of the calculations: "))

    # base value
    base_number = 0

    # loop
    while base_number < limit_number:
        # base_number = base_number + 1
        base_number += 1
        power_of = base_number ** exponent_number
        print("The power " + str(exponent_number) + " of " + str(base_number) + " is: " + str(power_of))

if __name__ == "__main__":
    input_values()


"""
Utils specific to T5 network.
"""

# torch
import torch

# numpy
import numpy as np

# numpy
from transformers.generation_stopping_criteria import (
    MaxLengthCriteria,
    StoppingCriteriaList,
)

# TRT-HuggingFace
from NNDF.general_utils import measure_python_inference_code
from NNDF.torch_utils import use_cuda

@use_cuda
def decoder_inference(
    t5_decoder, input_ids, encoder_last_hidden_state, timing_profile, use_cuda=True
):
    decoder_stmt = lambda: t5_decoder(
        input_ids=input_ids, encoder_hidden_states=encoder_last_hidden_state
    )
    decoder_e2e_median_time = measure_python_inference_code(
        decoder_stmt, number=timing_profile.number, iterations=timing_profile.iterations
    )

    return (decoder_stmt(), decoder_e2e_median_time)

@use_cuda
def encoder_inference(t5_encoder, input_ids, timing_profile, use_cuda=True):
    encoder_stmt = lambda: t5_encoder(input_ids=input_ids)
    encoder_e2e_median_time = measure_python_inference_code(
        encoder_stmt, number=timing_profile.number, iterations=timing_profile.iterations
    )

    return (encoder_stmt(), encoder_e2e_median_time)

# Code specifically for Pythonic inference measurement used across all T5 related scripts
@use_cuda
def full_inference_greedy(
    t5_encoder,
    t5_decoder,
    input_ids,
    tokenizer,
    timing_profile,
    max_length,
    use_cuda=True,
):
    stopping_criteria = StoppingCriteriaList([MaxLengthCriteria(max_length)])
    decoder_input_ids = torch.full(
        (1, 1), tokenizer.convert_tokens_to_ids(tokenizer.pad_token), dtype=torch.int32
    )

    if use_cuda:
        decoder_input_ids = decoder_input_ids.to("cuda")

    def _e2e():
        encoder_last_hidden_state = t5_encoder(input_ids=input_ids)

        return t5_decoder.greedy_search(
            input_ids=decoder_input_ids,
            encoder_hidden_states=encoder_last_hidden_state,
            stopping_criteria=stopping_criteria,
        )

    full_e2e_median_time = measure_python_inference_code(
        _e2e,
        number=timing_profile.number,
        iterations=timing_profile.iterations,
    )

    return (_e2e(), full_e2e_median_time)


import os
import sys
from pydantic_settings import BaseSettings, SettingsConfigDict

class Settings(BaseSettings):
    app_name: str = "gogame"
    workers: int = 1

    reinit_db_tables: bool = True
    clear_db_tables: bool = True

    # Filled by `.env` file
    db_driver: str = ""
    db_user: str = ""
    db_password: str = ""
    db_host: str = ""
    db_port: str = ""
    db_name: str = ""

    cache_host: str = "localhost"
    cache_port: int = 6379

    cors_allow_origins: list = [
        "http://localhost",
        "http://localhost:8080",
        "http://localhost:5173",
    ]
    cors_allow_credentials: bool = True
    cors_allow_methods: list = ["*"]
    cors_allow_headers: list = ["*"]

    default_limit: int = 18

    model_config = SettingsConfigDict(
        env_file=(
            ".dev.env"
            if (
                ("--dev" in sys.argv or "--debug" in sys.argv)
                and os.path.isfile(".dev.env")
            )
            else ".env"
        )
    )

settings = Settings()