import fractions
import numpy as np

def format_num(num, decimal_len=3):
    try:
        num_str = str(num)
        num_float = float(sum(fractions.Fraction(s) for s in num_str.split()))
        num_formatted = ("{:." + str(decimal_len) + "f}").format(num_float).rstrip('0').rstrip('.')
        return num_formatted
    except:
        return num

class ShapeProperties:

    def __init__(self, shape_df):
        self.shape_df = shape_df

    def select_shape_data(self, shape_label, label_column='EDI_Std_Nomenclature'):
        self.selected_shapes = self.shape_df[self.shape_df[label_column] == shape_label]
        self.shape_section = self.selected_shapes['Type'].values[0]

    def select_section_data(self, shape_sections):
        self.selected_rows = self.shape_df[self.shape_df['Type'].isin(shape_sections)]

    def filter_by_value(self, **kwargs):
        filtered_rows = self.selected_rows.copy()

        for shape_property, value_limits in kwargs.items():
            property_values = filtered_rows[shape_property].astype(float)
            min_value = value_limits[0]
            max_value = value_limits[1]

            if min_value and max_value:
                filtered_rows = filtered_rows[(property_values >= float(min_value)) & (property_values <= float(max_value))]
            elif min_value:
                filtered_rows = filtered_rows[property_values >= float(min_value)]
            elif max_value:
                filtered_rows = filtered_rows[property_values <= float(max_value)]
            else:
                pass

        self.selected_shapes = filtered_rows

    def format_shape_data(self, properties_to_output):
        selected_columns = self.selected_shapes.reindex(columns=properties_to_output)
        selected_columns.replace(to_replace='0', value='–', inplace=True)
        filtered_columns = selected_columns.replace(to_replace='–', value=np.nan).dropna(axis=1, how='all').fillna('–')
        self.headers = filtered_columns.columns
        self.output_data = filtered_columns.applymap(format_num)

    def output_shape_data(self, table_header_dict):
        output_dict = {}
        output_dict['selected_properties'] = self.output_data.values
        output_dict['property_headers'] = [table_header_dict[header][1] for header in self.headers]
        output_dict['unit_headers'] = [table_header_dict[header][2] for header in self.headers]
        return output_dict

    def export_properties(self, output_filepath):
        output_df = self.selected_shapes
        output_df.to_excel(output_filepath, index=False)

class HistoricShapeProperties(ShapeProperties):

    def __init__(self, shape_df, editions):
        self.shape_df = shape_df[shape_df['Edition'].isin(editions)]


# Runtime: 108 ms, faster than 7.10% of Python3 online submissions

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
import queue

class Solution:
    def addOneRow(self, root, v, d):
        """
        :type root: TreeNode
        :type v: int
        :type d: int
        :rtype: TreeNode
        """
        if d == 1:
            newNode = TreeNode(v)
            newNode.left = root
            return newNode
        # [<node>, <level>]
        q = queue.Queue()
        q.put([root, 2])
        while not q.empty():
            now = q.get()
            if now[1] < d:
                if now[0].left:
                    q.put([now[0].left, now[1] + 1])
                if now[0].right:
                    q.put([now[0].right, now[1] + 1])
            else:
                newNode = TreeNode(v)
                newNode.left = now[0].left
                now[0].left = newNode

                newNode = TreeNode(v)
                newNode.right = now[0].right
                now[0].right = newNode
        return root


__author__  = 'Paul Ross'
__date__    = '2012-01-05'
__version__ = '0.1.0'
__rights__  = 'Copyright (c) 2012 Paul Ross.'

from TotalDepth.util.plot import Coord

#: Default SVG plot units
DEFAULT_PLOT_UNITS = 'in'
assert(DEFAULT_PLOT_UNITS in Coord.UNIT_MAP)
#: Units that we can convert to in LIS terms
DEFAULT_PLOT_LIS_UNITS = b"IN  "

#: Number of pixels per standard plot unit
VIEW_BOX_UNITS_PER_PLOT_UNITS = 96.0

#: Definition of a quarter inch margin
MarginQtrInch = Coord.Margin(
    Coord.Dim(0.25, 'in'),
    Coord.Dim(0.25, 'in'),
    Coord.Dim(0.25, 'in'),
    Coord.Dim(0.25, 'in'),
)

# These are here so that other modules can use them
#: Standard wireline log fan paper width i.e. long side.
STANDARD_PAPER_WIDTH = Coord.Dim(8.5, 'in')
#: Standard wireline log fan paper depth i.e. short side.
STANDARD_PAPER_DEPTH = Coord.Dim(6.25, 'in')
#: Standard wireline log fan paper margin.
STANDARD_PAPER_MARGIN = MarginQtrInch


import argparse

from torch_geometric.datasets import TUDataset
from torch_geometric.datasets import Planetoid
from torch_geometric.transforms import NormalizeFeatures

from GNNModels.Models import *
from GNNModels.Train import *

parser = argparse.ArgumentParser(description='Training GNN Models and Saving checkpoints')
parser.add_argument('--model', required=True,
                    help='provide model name from GCN,GAT,GNNGraphConv,GCN_3L')
parser.add_argument('--dataset',required=True,
                    help='provide dataset name from PROTEINS, MUTAG, Cora, CiteSeer')
parser.add_argument('--checkpoints',required=False,default='',
                    help='location to store checkpoints')

args = parser.parse_args()

# obtain the arguments to the python file
dataset_name=args.dataset
model_name=args.model
checkpoint_path=args.checkpoints

dataset=None
data=None

print("NOTE : This will overwrite checkpoints in new_checkpoints/")

print(dataset_name)
print(model_name)
print(checkpoint_path)

if dataset_name in ['Cora','CiteSeer']:
    dataset = Planetoid(root='GNNModels/data/Planetoid', name=dataset_name, transform=NormalizeFeatures())
    data = dataset[0]  # Get the first graph object.
elif dataset_name in ['MUTAG','PROTEINS']:
    dataset = TUDataset(root='GNNModels/data/TUDataset', name='PROTEINS')
else:
    print("Not a valid dataset name")

if model_name=='GCN':
    model = GCN(hidden_channels=16,num_features=dataset.num_features,num_classes=dataset.num_classes)
    params={'lr':0.01,'weight_decay':5e-4,'epochs':300,'verbose':True,'save_wts':checkpoint_path}
    #new_checkpoints/{}_{}_epochs=300.pt
    TrainModel(model,data,params,'NC')
elif model_name=='GAT':
    model= GAT(hidden_channels=8, num_features=dataset.num_features,num_classes=dataset.num_classes,heads=8)
    params={'lr':0.005,'weight_decay':5e-4,'epochs':300,'verbose':True,'save_wts':checkpoint_path}
    # new_checkpoints/GAT_PubMed_epochs=300.pt
    TrainModel(model,data,params,'NC')
elif model_name=='GCN_3L':
    model = GCN_3L(hidden_channels=64,num_features=dataset.num_node_features,num_classes=dataset.num_classes)
    params={'lr':0.01,'epochs':150,'verbose':True,'save_wts':checkpoint_path}
    #new_checkpoints/GCN_3L_PROTEINS_epochs=300.pt
    TrainModel(model,dataset,params,type='GC')
elif model_name=='GNNGraphConv':
    model = GNNGraphConv(hidden_channels=64,num_features=dataset.num_node_features,num_classes=dataset.num_classes)
    params={'lr':0.01,'epochs':300,'verbose':True,'save_wts':checkpoint_path}
    # new_checkpoints/GNNGraphConv_PROTEINS_epochs=300.pt
    TrainModel(model,dataset,params,type='GC')
else :
    print("Not a valid model name")


from keras.models import Sequential
from keras.layers import Dense, LSTM, GRU, SimpleRNN, InputLayer, Masking
from keras.layers.wrappers import Bidirectional, TimeDistributed
from keras.callbacks import TensorBoard, EarlyStopping
from os.path import join

class RNN_Model():
    def __init__(self, config):
        self.batch_size = config.batch_size
        self.epoch = config.epoch
        self.layers = [int(l) for l in config.layers.split(',')]
        self.direction = config.direction
        self.cell_type = config.cell_type
        self.num_classes = 40
        self.model_dir = config.model_dir
        self.model_name = config.model_name

        if config.data_type == 'mfcc':
            self.input_dim = (config.padding_size, 39)
        else:
            self.input_dim = (config.padding_size, 69)

        self.model = self.build()

    def rnn_layer(self, dim):
        if self.cell_type == 'rnn':
            return SimpleRNN(dim, dropout=0.25, return_sequences=True, activation='relu')
        elif self.cell_type == 'lstm':
            return LSTM(dim, dropout=0.25, return_sequences=True, activation='tanh', implementation=2)
        elif self.cell_type == 'gru':
            return GRU(dim, dropout=0.25, return_sequences=True, activation='relu', implementation=2)

    def build(self):
        model = Sequential()
        model.add(InputLayer(input_shape=self.input_dim))
        model.add(Masking())
        for layer in self.layers:
            if self.direction == 'uni':
                model.add(self.rnn_layer(layer))
            elif self.direction == 'bi':
                model.add(Bidirectional(self.rnn_layer(int(layer / 2))))
        model.add(TimeDistributed(Dense(self.num_classes, activation='softmax')))
        model.compile(
            optimizer='adam',
            loss='categorical_crossentropy',
            metrics=['accuracy'])
        model.summary()
        return model

    def train(self, x, y):
        tensorboard = TensorBoard(log_dir=self.model_dir + '/logs', batch_size=self.batch_size, write_graph=True)
        early_stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=2, verbose=0, mode='auto')

        self.model.fit(x, y, self.batch_size, self.epoch, shuffle=True, callbacks=[tensorboard, early_stopping],
                       validation_split=0.2)

        self.model.save_weights(
            join(self.model_dir, self.model_name + '.h5'))

    def test(self, x):
        self.model.load_weights(
            join(self.model_dir, self.model_name + '.h5'))
        predictions = self.model.predict_classes(x)
        return predictions


student = input()

grade = 1
bad_grades = 0
average_grade = 0.0
sum_grades = 0.0

while grade <= 12:
    annual_grade = float(input())

    if annual_grade < 4.00:
        bad_grades += 1

        if bad_grades == 2:
            break
        continue
    sum_grades += annual_grade
    average_grade = sum_grades / grade

    grade += 1

if bad_grades == 2:
    print(f'{student} has been excluded at {grade} grade')
else:
    print(f'{student} graduated. Average grade: {average_grade:.2f}')


# Setup Python ----------------------------------------------- #
import math
import random
from maintenance import custom_mouse, load_image, show_fps
import pygame

from scenes.options import OptionsLoop
from classes.enemy import Enemy
from classes.player import Player

# Tutorial Loop ---------------------------------------------- #
def DebuggerLoop5(game_engine):

    # Get Context
    game_engine.discord.update_discord_status("Editing new 'room'")
    cursor_img, cursor_rect = custom_mouse()

    TILE_SIZE = 64
    checkers = load_image("./resources/images/debug/checkers.png").convert()

    player = Player(15 * TILE_SIZE, 7 * TILE_SIZE, 8)
    enemies = []
    for i in range (1, 5):
        enemies.append(Enemy(random.randint(1, 25)* TILE_SIZE, random.randint(1, 15)* TILE_SIZE, 3, './resources/debug/slime.png', 1, 100, random.randint(3, 6)* TILE_SIZE, False))

    base_font = pygame.font.Font("./resources/fonts/Thintel.ttf", 35)
    cooldown = 100
# Loop Start ------------------------------------------------- #
    running = True
    while running:

        # Call required updates
        game_engine.discord.tick()

        # Reset Frame
        game_engine.screen.fill((50, 50, 20))

        # Mouse
        mx, my = pygame.mouse.get_pos()
        cursor_rect.center = (mx, my)

# Events ----------------------------------------------------- #
        for event in pygame.event.get():
            game_engine.chatConsole.update(event)

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    if game_engine.chatConsole.active == True:
                        print("TRUE")
                        break
                    if game_engine.chatConsole.active == False:
                        print("FALSE")
                        game_engine.mixer.sound_play('resources/sounds/UI_click.mp3')
                        if OptionsLoop(game_engine) == "leave_state":
                            running = False
                            return

        keys = pygame.key.get_pressed()
        player.move(keys)

# Computing -------------------------------------------------- #

# Render ----------------------------------------------------- #
        game_engine.screen.fill((0, 0, 0))
        for i in range(30):
            for j in range(25):
                game_engine.screen.blit(checkers, (i*TILE_SIZE, j*TILE_SIZE))

        print(cooldown)
        if cooldown <= 10:
            pygame.draw.circle(game_engine.screen, (255, 0, 0), (player.get_center()[0], player.get_center()[1]), 2* TILE_SIZE, 5)
            pygame.draw.circle(game_engine.screen, (255, 0, 0), (player.get_center()[0], player.get_center()[1]), 1* TILE_SIZE, 5)

        if cooldown <= 0:
            cooldown = 20
            for enemy in enemies:
                distance = player.pos.distance_to(enemy.getPos())
                if distance <= 2 * TILE_SIZE:
                    enemy.reduceHealth(10)
        else:
            cooldown -= 1

        # Enemies
        for enemy in enemies:
            if enemy.getHealth() >= 1:
                enemy.draw(game_engine.screen)
                enemy.update([player], game_engine.screen)
            else:
                enemies.remove(enemy)
        # Player
        player.draw(game_engine.screen)

        # System
        game_engine.chatConsole.draw()
        game_engine.screen.blit(cursor_img, cursor_rect)
        game_engine.screen.blit(show_fps(game_engine.mainClock, base_font), (10,0))

# Update ----------------------------------------------------- #
        game_engine.update_display()


import pandas as pd
from bson.objectid import ObjectId

recipe_collection_name = "RecipeNew"
f_vec_collection_name = "feature_vector"
u_act_collection_name = "UserActivity"
sim_mat_collection_name = "similarity_matrix"

def get_database(db_conn, db_name):
    import pymongo
    CONNECTION_STRING = db_conn
    client = pymongo.MongoClient(CONNECTION_STRING)
    return client[db_name]

def get_feature_vector(dbname):
    feature_collection = dbname[f_vec_collection_name]
    cursor = feature_collection.find()
    list_vectors = list(cursor)[0]
    list_vectors.pop('_id')
    return pd.DataFrame.from_dict(list_vectors, orient="index")

def get_this_user_activity(dbname, userEmail):
    user_act_collection = dbname[u_act_collection_name]
    return user_act_collection.find({"userEmail": userEmail})[0]

def get_all_recipes(dbname):
    recipe_collection = dbname[recipe_collection_name]
    return recipe_collection.find()

def get_this_recipe(dbname, recipeId):
    recipe_collection = dbname[recipe_collection_name]
    return recipe_collection.find_one({"_id": ObjectId(recipeId)})

def get_similarity_matrix(dbname):
    sim_mat_collection = dbname[sim_mat_collection_name]
    cursor = sim_mat_collection.find()
    sim_mat = list(cursor)[0]
    sim_mat.pop('_id')
    return sim_mat


import torch
from utils import preprocess_word, pad_texts

from torch.utils import data as data_utils

import numpy as np
from config import pad_token, load_args
import pandas as pd

args = load_args()

class Batch:
	"Object for holding a batch of data with mask."
	def __init__(self, src, src_mask, trg, device='cuda'):
		## src : (B, D, T)
		self.src = src.transpose(1, 2).to(device) # (B, T, D)
		self.src_mask = src_mask.unsqueeze(-2).to(device) # (B, 1, T)
		self.src_lens = self.src_mask.long().sum((1, 2))
		self.trg = trg

		self.trg_lens = (self.trg != 0).long().sum(-1)

class Dataset:
	def __init__(self, args):
		with open(args.vocab_file) as f:
			self.chars = list(f.read().strip())

		blank_tokens = [pad_token]

		self.v = blank_tokens + self.chars
		self.v2i = {self.v[i]: i for i in range(len(self.v))}
		self.i2v = {i : v for v, i in self.v2i.items()}

		self.feat_root = args.feat_root

		test_df = pd.read_csv(args.test_csv, delimiter=',', dtype = str)
		self.fpaths = test_df["video_id"].tolist()
		if args.full_word_test:
			self.texts = test_df["corresponding_word"].tolist()
		else:
			self.texts = test_df["fingerspelled_letters"].tolist()
		self.starts = test_df["start"].tolist()
		self.ends = test_df["end"].tolist()

		self.upsampling = args.upsampling
		self.downsampling = args.downsampling
		self.frame_stride = args.frame_stride

	def __getitem__(self, idx):
		feat_path = self.fpaths[idx]
		start = int(float(self.starts[idx]) * 25./self.frame_stride)
		end = int(float(self.ends[idx]) * 25./self.frame_stride)
		text = self.texts[idx]

		feats = np.load(f"{args.feat_root}/{feat_path}.npy")
		feats = torch.FloatTensor(feats[start : end])

		ctc_target = torch.LongTensor(self.to_ids(text))

		if self.upsampling > 1:
			feats = feats.unsqueeze(1).repeat(1, self.upsampling, 1).reshape(-1, feats.size(-1))

		if self.downsampling > 1:
			feats = feats[::self.downsampling]

		return feats, ctc_target

	def collate_fn(self, batch):
		feats, ctc_targets = [], []

		for i in range(len(batch)):
			feats.append(batch[i][0])
			ctc_targets.append(batch[i][1])

		assert len(feats) != 0

		lens = np.array([len(f) for f in feats])
		max_len = max(lens)
		sorted_indices = np.argsort(-lens)
		feats = [feats[idx] for idx in sorted_indices]
		ctc_targets = [ctc_targets[idx] for idx in sorted_indices]

		padded_feats, src_mask = [], torch.zeros(len(feats), max_len)
		for i, f in enumerate(feats):
			if f.size(0) == max_len:
				padded_feats.append(f)
				src_mask[i] = 1
			else:
				padding = torch.zeros((max_len - f.size(0), f.size(1)))
				padded_feats.append(torch.cat([f, padding], dim=0))
				src_mask[i, :f.size(0)] = 1

		padded_ctc_targets, ctc_mask = pad_texts(ctc_targets)
		padded_feats = torch.stack(padded_feats, dim=0)
		if len(padded_feats.size()) == 3:
			padded_feats = padded_feats.transpose(1, 2) # (B, C, T)

		return padded_feats, src_mask, padded_ctc_targets.long()

	def __len__(self):
		return len(self.texts)

	def to_ids(self, word):
		return [self.v2i[c] for c in str(word)]

	def to_text(self, ids):
		try:
			return ''.join([self.i2v[i.item()] for i in ids if i != 0])
		except:
			return ''.join([self.i2v[i] for i in ids if i != 0])

def get_dataloader(args):
	dataset = Dataset(args)
	dataloader = data_utils.DataLoader(dataset, batch_size=args.bs, num_workers=args.num_workers,
							collate_fn=dataset.collate_fn,
							drop_last=False, shuffle=False)

	return dataloader


import matplotlib.pyplot as plt
import pandas as pd

"""
Read in and analyze the Oregon dam data.
"""

df = pd.read_csv("data/dam/oregondams.csv")
cfreqs = df["county"].value_counts() # frequency of each county
cindex = df["county"].value_counts().index # county name

plt.bar(cindex, cfreqs)
plt.xticks(range(len(cindex)), cindex, rotation="vertical")
plt.xlabel("County")
plt.ylabel("Number of dams")
plt.title("Dam frequency by county")
plt.savefig("output/dam/freq.png")


from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC, wait
from selenium.webdriver.common.by import By

from .Yad2EstatePost import Yad2EstatePost # pylint: disable=import-error
from .Yad2VehiclePost import Yad2VehiclePost # pylint: disable=import-error
from .TargetSecurityTriggeredError import TargetSecurityTriggeredError # pylint: disable=import-error
from .PostFactory import PostFactory

FIREFOX_BINARY="C:\\Program Files\\Mozilla Firefox\\firefox.exe"
USER_INTERACTION_DELAY = 200

class Yad2Page:
    url = None
    driver = None

    def __init__(self, url):
        self.url = url

    def load(self,user_interact):
        factory = (
            PostFactory()
            .register("/html/body/div[2]/div[2]/div/main/div/div[3]/div[5]/div/div[1]/div/div/div[2]/div[1]/span[1]", Yad2EstatePost)
            .register("/html/body/div[2]/div[2]/div/main/div/div[3]/div[5]/div/div[1]/div/div/div[3]/div[1]/p[1]", Yad2VehiclePost)
            )

        options = Options()
        options.headless = not user_interact
        options.binary = FIREFOX_BINARY
        options.add_argument("--window-size=1920,1200")

        driver = webdriver.Firefox(options=options)
        driver.get(self.url)

        show_up_timeout = USER_INTERACTION_DELAY if user_interact else 10
        try:
            WebDriverWait(driver, show_up_timeout).until(EC.presence_of_element_located((By.XPATH, "/html/body/div[2]/div[2]/div/main/div/div[3]/div[4]/div")))
        except:
            raise TargetSecurityTriggeredError()

        self.driver = driver
        post = factory.get_post(driver,self.url)
        return post

    def close(self):
            self.driver.quit()


# -*- coding: utf-8 -*-
"""
Created on Wed Dec  9 21:14:01 2020

@author: eden_
"""

# importing the libraries
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim as optim
import torch.utils.data
from torch.autograd import Variable
from Dataset import SetGenerator
from torch.utils import data
import matplotlib.patches as mpatches
import matplotlib.lines as mlines
import matplotlib.pyplot as plt

"""Find two attributes with the higest Variance """
def findTwoAttrWithHigestVariance(data):
    variances =[]
    for i in range(data.shape[1]):
        variances.append(np.var(data[:,i]))

    index_max=np.argmax(variances)
    variances[index_max]=-1
    index_submax=np.argmax(variances)

    return index_max,index_submax

    """"Print scatter train plot"""
def printScatterTrainPlot(X,Y):
    plt.plot()
    ax =plt.subplot()
    plt.title('training set')

    ### Calculate x_num and y_num by largest variance later
    x_num,y_num = findTwoAttrWithHigestVariance(X)

    ### From here, do not touch - it works
    x_min= min(np.min(X[:,x_num])*1.25 , 0.1)

    x_max=max(np.max(X[:,x_num])*1.25 , 0.2)
    y_min=min(np.min(X[:,y_num])*1.25  , 0.1)
    y_max=max(np.max(X[:,y_num])*1.25  , 0.2)
    plt.axis([x_min,x_max,y_min,y_max])

    plt.xlabel('hidden value {} '.format(x_num))
    plt.ylabel('hidden value {} '.format(y_num))
    scatter=plt.scatter(X[:,x_num] ,X[:,y_num] ,s=10, c=Y)

    plt.show()

def setGraphTitles(graphTitle,X_Axis_Title,Y_Axis_Title):
    names=[]
    names.insert(0, graphTitle)
    names.insert(1, X_Axis_Title)
    names.insert(2, Y_Axis_Title)
    return names
    """"adds test results to training scatter plot"""
def addToScatterTestPoints(Test_set,SVM_pred,real_names):
    colorss =np.zeros(len(real_names))
    test_colors=[]
    for i in range(len(real_names)):
        if real_names[i]==0:
            test_colors.insert(i, 'cyan')
        elif real_names[i]==1:
             test_colors.insert(i, 'green')
    plt.scatter(Test_set[:,2],Test_set[:,3], c=test_colors)
    blue_x = mlines.Line2D([], [], color='blue', marker='x',
                          markersize=15, label='0')
    red_circle=mlines.Line2D([], [], color='red', marker='o',markerfacecolor='none',
                          markersize=15, label='1')
    plt.legend(handles=[blue_x,red_circle])

    for i, point in enumerate(SVM_pred):
        if SVM_pred[i]==0:
            plt.scatter(Test_set[i][2] ,Test_set[i][3] , marker="x",s=80,c='blue')
        if SVM_pred[i]==1:
            plt.scatter(Test_set[i][2] ,Test_set[i][3] , marker="o",s=120,edgecolors='red',facecolors = 'none')
    plt.show()

torch.set_default_dtype(torch.double)

class RBM():

   def __init__(self,
        visible_size=100, hidden_size=120, weights_init=None, hidden_bias_init=None, visible_bias_init=None,
        learning_rate=1e-4, momentum=0.5, n_epoch=30, batch_size=100, visible_std_init=10.0,
        n_gibbs_sampling=1, use_cuda=False):

        self.visible_size = visible_size
        self.hidden_size = hidden_size
        self.weights_init = weights_init
        self.hidden_bias_init = hidden_bias_init
        self.visible_bias_init = visible_bias_init
        self.learning_rate = learning_rate
        self.momentum = momentum
        self.n_epoch = n_epoch
        self.batch_size = batch_size
        self.n_gibbs_sampling = n_gibbs_sampling
        self.visible_std = torch.full((1, visible_size), visible_std_init)

        self.weights = torch.empty(visible_size, hidden_size)
        if weights_init is None:
            self.weights.normal_(mean=0, std=0.01)
        else:
            self.weights = torch.from_numpy(weights_init)

        self.hidden_bias = torch.empty(hidden_size)
        if hidden_bias_init is None:
            #set bi
            #sets hidden biases at exponental distrubutions define lambda as 2
            self.hidden_bias.exponential_(lambd=2)
        else:
            self.hidden_bias = torch.from_numpy(hidden_bias_init)

        self.visible_bias = torch.empty(visible_size)
        if visible_bias_init is None:
            #sets visible biases to zeros
            self.visible_bias.zero_()
        else:
            self.visible_bias = torch.from_numpy(visible_bias_init)

        #momentum its how a change during the training will affect this value
        self.visible_bias_momentum = self.visible_bias.clone()
        self.hidden_bias_momentum = self.hidden_bias.clone()
        self.weights_momentum = self.weights.clone()
        self.visible_std_momentum = self.visible_std.clone()
# =============================================================================
#   function description:
#   step create
#
#
#
#
#   Params:
#   x: array of visable node
# =============================================================================

   def sample_hidden(self, visible_layer):

        wx = torch.mm(visible_layer, self.weights)

        activation = wx + self.hidden_bias.expand_as(wx)
        p_h_given_v = torch.sigmoid(activation)
        return p_h_given_v, torch.bernoulli(p_h_given_v)

   def sample_visible(self, hidden_layer):
# =============================================================================
#
#         Sample visible layer based on hidden layer
#         hidden_layer: (hidden_size) sized tensor
#             the hidden layer used to sample the visible layer
#
#         Returns
#             tensor containing sampled visible layer
#
# =============================================================================
       visible_normal_mean = torch.mul(torch.mm(hidden_layer, self.weights.transpose(0, 1)), torch.pow(self.visible_std, 2)) + self.visible_bias
       visible_layer = torch.normal(mean=visible_normal_mean, std=self.visible_std.expand(self.batch_size, -1))
       return visible_layer

   def contrastive_divergence(self, batch):
# =============================================================================
#             """
#         Perform one iteration of contrastive divergence on bias and weights using gibbs sampling with mini-batches
#         batch: (batch_size, visible_size) sized tensor
#             the batch used in gradient descent
#         """
#
#         ''' 1. set visable layer with batch input, 3-dim: [batch_size][number of visible nodes][data]
#             2. get array of activeted hidden layer before Forward Pass
#         '''
# =============================================================================
        visible_layer = batch.clone()

        _,hidden_layer = self.sample_hidden(visible_layer)

        ''' calculate batch of input with original values hidden layers multiplication, hidden association, and std
            (before Forward Pass )
                  '''
        positive_association = torch.bmm(visible_layer.unsqueeze(2), hidden_layer.unsqueeze(1))
        positive_hidden_association = hidden_layer
        positive_std_association = torch.pow(visible_layer - self.visible_bias, 2)

        ''' start Forward Pass '''
        for i in range(self.n_gibbs_sampling):
            visible_layer = self.sample_visible(hidden_layer)
            _,hidden_layer = self.sample_hidden(visible_layer)
# =============================================================================
#
#                 ''' calculate batch of input with learned values hidden layers multiplication
#             (after Forward Pass )
#                   '''
# =============================================================================
        negative_association = torch.bmm(visible_layer.unsqueeze(2), hidden_layer.unsqueeze(1))

        ''' calculate gradient decent after sampeling on weights and biases '''
        self.weights_momentum = self.weights_momentum * self.momentum + torch.sum(positive_association - negative_association, dim=0)
        self.visible_bias_momentum = self.visible_bias_momentum * self.momentum + torch.sum(batch - visible_layer, dim=0)
        self.hidden_bias_momentum = self.hidden_bias_momentum * self.momentum + torch.sum(positive_hidden_association - hidden_layer, dim=0)

        ''' update rbm's  weights and biases'''
        self.weights += self.weights_momentum * self.learning_rate / self.batch_size
        self.visible_bias += self.visible_bias_momentum * self.learning_rate / self.batch_size
        self.hidden_bias += self.hidden_bias_momentum * self.learning_rate / self.batch_size

        ''' update visable layer std momentum and  '''
        negative_std_association = torch.pow(visible_layer - self.visible_bias, 2)
        self.visible_std_momentum = self.visible_std_momentum * self.momentum + torch.div(torch.sum(negative_std_association - positive_std_association, dim=0), torch.pow(self.visible_std, 3))
        self.visible_std += self.visible_std_momentum * self.learning_rate / self.batch_size
        error = torch.sum((batch - visible_layer) ** 2) / (self.batch_size * self.visible_size)
        print("             Error: " + str(error.item()), end='')

   def train(self,setGenerator,validation_size):
# =============================================================================
#         """
#         Train RBM with input data
#         input_data: numpy array
#             numpy array containing the training data
#         """
#
# =============================================================================
        datasetG=setGenerator
        generator=setGenerator
        training_set = generator.get_training_set()
        testing_set = generator.get_test_set()
        num_batch_in_input = len(training_set)//self.batch_size

        #create an array holds all of the values of the free energy during the contrastive divergence
        free_energy_gaps = torch.empty(self.n_epoch * num_batch_in_input)
        training_generator= data.DataLoader(training_set, sampler=data.RandomSampler(training_set), batch_size=self.batch_size, drop_last=True, pin_memory=True)
        training_representative_generator = data.DataLoader(training_set, sampler=data.RandomSampler(training_set), batch_size=self.batch_size, drop_last=True, pin_memory=True)
        validation_generator = data.DataLoader(testing_set, sampler=data.RandomSampler(testing_set), batch_size=self.batch_size, drop_last=True, pin_memory=True)

        # save a random  sample from the training set to use to stop over fitting
        training_set_representative = next(iter(training_representative_generator))
        batch_num = 1
        for i in range(self.n_epoch):
            for batch,_ in training_generator:
                print("Batch #" + str(batch_num), end='')

                self.contrastive_divergence(batch)
                #compare the free energy of the pre sampled batch from the training with the free energy of a batch from the test set
                #to prevent overfitting if the free energy is grows very positive it's a sign for overfitting
                feg = self.free_energy(training_set_representative) - self.free_energy(next(iter(validation_generator)))
                free_energy_gaps[batch_num - 1] = feg
                print("             FEG: {:.7f}".format(feg.item()))
                batch_num += 1

        self.datasetG=generator
        self.training_set =generator.get_training_set()
        self.testing_set = generator.get_test_set()

   def free_energy(self, visible_layers):
        """
        Calculate average free energy of given visible layers
        visible_layer: (validation_set_size, visible_size) sized tensor
            visible layer used to calculate free energy
        Returns
            average free energy of the given input
        """

        return (-1 * torch.sum(torch.mv(visible_layers[0], self.visible_bias)) + torch.sum(torch.log1p(torch.exp(torch.matmul(visible_layers[0], self.weights) + self.hidden_bias))))/self.batch_size


from cs50 import get_string

input = get_string("Text: ")

ltrs = 0
wrds = len(input.split())
sntns = 0
len = len(input)
strtWrd = False

for i in range(len):
    if input[i].isalpha():
        ltrs += 1
        strtWrd = True
    if input[i] == "!" or input[i] == "?" or input[i] == ".":
        sntns += 1

index = 0.0588 * (ltrs / wrds * 100) - 0.296 * (sntns / wrds * 100) - 15.8;

if index > 16:
    print("Grade 16+")
elif index < 1:
    print("Before Grade 1")
else:
    print(f"Grade {round(index)}")


import os
import glob
from pyspark import SparkConf, SparkContext

import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class DataRDD:

	def get_data(self):
		# rdd_array = []
		# for fn in glob.glob(file_path):
		# 	if os.path.isfile(fn):
		# 		print "file://"+fn
		# 		rdd_array.append(self.sc.textFile("file://"+fn))
		# 		#self.data =  self.sc.union(self.sc.textFile("file://"+fn))
		# #file_path = "/data/*.geo"
		# #self.data = self.sc.textFile("file://"+file_path)# self.sc.union([self.sc.textFile("file://"+f) for f in file_path])
		# self.data =  self.sc.union(rdd_array);

		result = self.data.map(lambda line:(line.split(';')[:10]))#.map(lambda line: (line.split(';')[1],line.split(';')[2],line.split(';')[8]))#==str("292")))#.filter(lambda line: (line.split(';')[col]==str(id)))
		#print result.collect()
		#result.cache()
		return result

	def __init__(self, sc, dataset_path):
		#Init the recommendation engine given a Spark context and a dataset path

		logger.info("Starting up the data engine: "+dataset_path)
		file_path = dataset_path #os.path.join(dataset_path)
		self.sc = sc
		raw_RDD = sc.textFile(file_path);
		# for fn in os.listdir(file_path):
		# 	if os.path.isfile(fn):
		#         #print (fn)
		# 		self.data = self.sc.textFile(','.join("file:///"+fn))#sc.textFile(file_path)

		self.data = raw_RDD
		#self.data.filter(lambda line: (line.split(';')[9]==str('292')))
		#self.data.collect()
		#self.data.cache()


""" Settings for tests running. """

from .production import *

ENVIRONMENT_NAME = "test"

# Databases
DATABASES['default']['ENGINE'] = 'django.db.backends.sqlite3'
DATABASES['default']['NAME'] = ':memory:'

# Caches
CACHES['default']['BACKEND'] = 'django.core.cache.backends.locmem.LocMemCache'

SESSION_ENGINE = 'django.contrib.sessions.backends.cache'

# Disable south migrations on db creation in tests
SOUTH_TESTS_MIGRATE = False

# Celery
CELERY_ALWAYS_EAGER = True

logging.info("Test settings are loaded.")

# pylama:ignore=W0401,W0614


import socket

# local host IP address
local_host = '127.0.0.1'

# used port 5000
port = 5000

data = b"HTTP/1.1 200 OK\r\n" \
       b"Content-Type: text/html; charset=UTF-8\r\n\r\n" \
       b"<html>Congratulations! You've downloaded the first Wireshark lab file!</html>\r\n"

# create the socket object with IPv4 and TCP
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# bound the socket to the localhost IP and port 5000
s.bind(('localhost', port))

# listening for connection with a queue of 0
s.listen(0)

# wait for a connection, when there is one, it returns the socket object and an array that has the IP address
# and the port address of the process that is connecting to this server
connection, address = s.accept()

# just prints the IP and port that the new socket is connected to
print('# connected to ' + address[0] + ':' + str(address[1]))

print('Received:\n')
# receives 5000 bytes of data from the client which is the get request
con_data = connection.recv(5000)

# prints the data but uses decoded to transform bytes to string
print(con_data.decode())

print('Sending>>>>>>>>\n')

# prints the data but uses decoded to transform bytes to string
print(data.decode())

# sends the client the byte data from the variable data above which is some html with header information
connection.send(data)
print('<<<<<<<<\n')

# closes the new socket connection
connection.close()

s.close()


__author__ = 'Bohdan Mushkevych'

from db.model.single_session import SingleSession
from synergy.db.dao.base_dao import BaseDao
from constants import COLLECTION_SINGLE_SESSION

SESSION_ID = SingleSession.session_id.name
DOMAIN_NAME = SingleSession.domain_name.name

class SingleSessionDao(BaseDao):
    """ Thread-safe Data Access Object for single_session table/collection """

    def __init__(self, logger):
        super(SingleSessionDao, self).__init__(logger=logger,
                                               collection_name=COLLECTION_SINGLE_SESSION,
                                               model_class=SingleSession)

    def find_by_session_id(self, domain_name, session_id):
        query = {DOMAIN_NAME: domain_name, SESSION_ID: session_id}
        sessions = self.run_query(query)
        return sessions[0]


from flask import Flask, redirect, render_template, request, url_for
import utils.contact as contact_helper_fn
import utils.mailing_list as mailing_helper_fn
import utils.ip as ip_helper_fn

app = Flask(__name__)

notes = []

@app.route('/')
def index():
    return render_template('index.html', notes=notes)

@app.route('/add', methods=['POST'])
def add_note():
    note = request.form['note']
    if note:
        notes.append(note)

    # store access details to a table
    browser_details = request.user_agent.string
    ip_address = request.remote_addr
    ip_helper_fn.save_to_ip_list(ip_address, browser_details)

    return redirect(url_for('index'))

@app.route('/send_message', methods=['POST'])
def send_message():
    name = request.form['name']
    email = request.form['email']
    message = request.form['message']
    subscribe = request.form.get('subscribe')

    if subscribe:
        """
            Add this email to a email list being maintained on dynamodb
        """
        mailing_helper_fn.save_to_mailing_list(name, email)

    contact_helper_fn.contact_us(name, email, message)

    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(debug=True, host="0.0.0.0", port=5001)


import pandas as pd
import numpy as np
import joblib
import os

basedir = os.path.abspath(os.path.dirname(__file__))
MODEL_FILE_PATH = basedir + '/ModelFiles/'

def rrcf(t_sum_raw):
    path = MODEL_FILE_PATH + 'rrcf147.model'

    with open(path, "rb") as file:
        model = joblib.load(file)

    data = pd.DataFrame(t_sum_raw)
    rrcf_result = model.predict(data)
    rrcf_score = - model.score_samples(data)
    print(rrcf_score)
    print(rrcf_result)
    return rrcf_result, rrcf_score

def lof(t_sum_raw):
    data = np.array(t_sum_raw, dtype='complex_').astype(float)
    path = MODEL_FILE_PATH + 'lof2.model'
    print(data)
    with open(path, "rb") as file:
        model = joblib.load(file)

    lof_result = model.predict(data)
    lof_score = - model.score_samples(data)

    print(lof_result)
    print(lof_score)
    return lof_result, lof_score


import os
import re
import argparse
import xml.etree.ElementTree as ET

parser = argparse.ArgumentParser('takes as input xml file, writes a filtered xml file containing just the ReferenceClinVarAssertion nodes relating to cancer')
parser.add_argument('-f', '--filename', dest='filename', help='input file path')
args = parser.parse_args()

args_filename = args.filename
if args_filename[-3:] == '.gz':
    args_filename = args_filename[:-3]

data_dir = '/media/ani/DATA/Columbia/BINFG4003/BINF-G4003/data/'
filtered_dir = os.path.join(data_dir, 'filtered_xml_cancer')
# filtered_dir = os.path.join(data_dir, 'filtered_xml_breast_cancer')

def filter_xml(filepath, year, month):
    filtered_year_dir = os.path.join(filtered_dir, year)
    if not os.path.isdir(filtered_year_dir):
        os.mkdir(filtered_year_dir)
    out_filename = os.path.join(filtered_year_dir, 'filtered_' + os.path.basename(filepath))

    with open(out_filename, 'w') as f:
        f.write('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<dummy_root>\n')

    # https://stackoverflow.com/questions/324214/what-is-the-fastest-way-to-parse-large-xml-docs-in-python
    # get an iterable
    context = ET.iterparse(filepath, events=("start", "end"))

    # turn it into an iterator
    context = iter(context)

    # get the root element
    event, root = next(context)

    i = 0
    cnt = 0
    for event, elem in context:
        # cnt += 1
        # print(cnt)
        if event == "end" and elem.tag == "ReferenceClinVarAssertion":
            elem_traitset = elem.find('TraitSet')
            if elem_traitset is None or elem_traitset.attrib['Type'] != "Disease":
                continue
            traitset_text = re.sub(r"\s+", ' ', ' '.join(elem_traitset.itertext())).strip()
            if 'cancer' in traitset_text:
                i += 1
                print('cancer record found #', i, sep='')
                with open(out_filename, 'a') as f:
                    f.write(ET.tostring(elem).decode('utf-8'))
            root.clear()

    with open(out_filename, 'a') as f:
        f.write('</dummy_root>')
    # print('done')
    print(year+'-'+month+':', i, 'cancer records found')

def main():
    # os.chdir(filtered_dir)
    filename = os.path.basename(args_filename)
    year, month = filename.split('_')[1].split('.')[0].split('-')
    filter_xml(args_filename, year, month)

if __name__ == '__main__':
    main()


from fastapi import FastAPI
from fastapi.testclient import TestClient
from .gaze_estimation_api import app
import json
import os
import cv2
from random import shuffle
from .heat_map_api import get_gaze_heat_map
url = "/gaze/"

client = TestClient(app)

def test_read_main():
    dataset = {"P2achJNX001":"data/scenario1/s1_1_avijson/json",
     "P2ACHJNX002":"",
     "P2ACHJNX003":"",
     "p2achjnx004":"data/air_space_001",
     "P2ACHJNX005":"",
     "P2ACHJNX006":"",
     "P2ACHJNX007":"",
     "P2ACHJNX008":""}
    dummy_data = []
    for key, value in dataset.items():

        if value == "":
            continue
        [dummy_data.append((key, os.path.join(value, fname))) for fname in os.listdir(value)]

    shuffle(dummy_data)
    for id, fpath in dummy_data:
        payload = json.load(open(fpath, 'r'))
        response = client.put(
            f"/gaze/{id}/",
            # headers={"X-Token": "coneofsilence"},
            json=payload,
        )
        assert response.status_code == 200
        gaze_est_res = response.json()
        id = gaze_est_res['device_id']
        for gaze_info in gaze_est_res['gaze_info']:
            heat_map = get_gaze_heat_map(id, gaze_info['gaze'], gaze_info['gaze_cov'])
            if heat_map is not None:
                face_id = gaze_info['face_id']
                # cv2.imshow(f'{id}_{face_id}', heat_map)
                # cv2.waitKey(0)


from typing import List

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        if len(nums) == 0:
            return 0
        # two pointers
        counter = 0
        for i in range(len(nums)):
            if nums[i] != val:
                nums[counter] = nums[i] # nums[i] is different with val, we both increase counter and i
                counter += 1
            else:
                continue # wihe nums[i] equals to val, we only increase i. counter is the last index for processed value
        return counter

if __name__ == '__main__':
    test = [0,1,2,2,3,0,4,2]
    ans = Solution()
    print(ans.removeElement(test, val=2))


from TMQ.TMDataRepository.DR_MysqlTool import CheckTradeDateMysqlTool
import TMQ.TMDataRepository.DR_TushareTool as tst

start = '20181220'
end = '20181221'
ts_code = '000001.SZ'

tdf = tst.ts_get_trade_date(start,end)
pdf = tst.ts_get_oms_price(ts_code, start, end)

pdf.fillna(None)

# pdf.iloc[239]

tdf['ts_code'] = ts_code
tdf['has_data'] = 0

checkTradeDate = CheckTradeDateMysqlTool()

checkTradeDate.insert_data(tdf)

checkTradeDate.disconnect_db()

# ['ts_code', 'exchange', 'cal_date', 'is_open', 'has_data']
tdf = tst.ts_get_trade_date(start,end)
tdf['ts_code'] = ts_code
tdf['has_data'] = 0

df = checkTradeDate.get_data_from_db(ts_code, start, end)

checkTradeDate.disconnect_db()


import json
from pymongo import MongoClient
from flask import Flask, request, jsonify
app = Flask(__name__)

client = MongoClient()

db = client.git_orgs

orgs = db.orgs

@app.route('/<org_id>', methods=['GET'])
def find_org(org_id):
    res = orgs.find_one({'org_id': org_id})
    print(res)
    if res is None:
        return {'repos': None}
    else:
        return {'repos': res['repos']}

@app.route('/<org_id>', methods=['POST'])
def insert_org(org_id):
    repos = json.loads(request.data)['repos']
    orgs.insert_one({'org_id': org_id, 'repos': repos})
    return jsonify(success=True)

if __name__ == "__main__":
    app.run(port=5002, debug=True)


"""Illustrate increment operation."""
from math import pi
from qiskit import QuantumCircuit, QuantumRegister, transpile
from qiskit.circuit.library.standard_gates import XGate
from qiskit_aer import AerSimulator

register1 = QuantumRegister(4)
register2 = QuantumRegister(4)
circuit = QuantumCircuit(register1, register2)

#  Create inital sate
circuit.x(register1[0])
circuit.x(register2[2])

# Do addition
def increment_register(circuit, register):
    for i in range(0, len(register))[::-1]:
        gate = XGate()
        if i != 0:
            gate = gate.control(i)

        circuit.append(gate, register[:i] + [register[i]], [])

def decrement_register(circuit, register):
    for i in range(0, len(register)):
        gate = XGate()
        if i != 0:
            gate = gate.control(i)

        circuit.append(gate, register[:i] + [register[i]], [])

increment_register(circuit, register1)
decrement_register(circuit, register2)

circuit.measure_all()

circuit.draw('mpl', filename='increment.png')

simulator = AerSimulator()

compiled_circuit = transpile(circuit, simulator)

job = simulator.run(compiled_circuit, shots=1000)

result = job.result()
counts = result.get_counts(compiled_circuit)

print(counts)


import unittest
from drones import Drone, DroneStore

class DroneTest(unittest.TestCase):
    def test_add_success(self):
        # Arrange
        dr = Drone("Test drone")
        store = DroneStore()

        # Act
        store.add(dr)

        # Assert
        self.assertEqual(store.get(1), dr)

    def test_add_fail(self):
        # Arrange
        dr = Drone("Test drone")
        store = DroneStore()
        errorText = 'Drone already exists in store'

        # Act
        try:
            store.add(dr)
            store.add(dr)

        # Assert
        except Exception as ex:
            self.assertEqual(str(ex), errorText)

    def test_remove_success(self):
        # Arrange
        dr = Drone("Test drone")
        store = DroneStore()
        store.add(dr)

        # Act
        store.remove(dr)

        # Assert
        self.assertEqual(store.get(1), None)

    def test_remove_fail(self):
        # Arrange
        dr = Drone("Test drone")
        store = DroneStore()
        errorText = 'Drone does not exist in store'

        # Act
        try:
            store.remove(dr)

        # Assert
        except Exception as ex:
            self.assertEqual(str(ex), errorText)

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


# -*- coding: utf-8 -*-
"""
Created on Mon Mar 25 19:58:28 2019

@author: timothy.whalen
"""
def remove_duplicates(df, training = True):
    import os
    import pandas as pd
    _thisFile = os.path.dirname(os.path.abspath('__file__'))
    if training:
        _dupFile = r'%s/duplicate_article_ids_train.csv' % _thisFile
    else:
        _dupFile = r'%s/duplicate_article_ids_test.csv' % _thisFile
    _dups = pd.read_csv(_dupFile, names=['first_id', 'dup_id'], skiprows=1)
    df = df[~df.id.isin(_dups.dup_id.tolist())]
    return(df)

#import sqlite3
#_dbfile = r'%s/articles_zenodo.db' % _thisFile.replace("EDA", "Article Collection")
#_db = sqlite3.connect(_dbfile)
#query = "SELECT * FROM test_content;"
#df = pd.read_sql_query(query, _db)
#df = remove_duplicates(df, training=False)


import json
import matplotlib.pyplot as plt
import numpy as np

# Define the connections between the keypoints to form the skeleton
# connections = [    [0, 1], [1, 2], [2, 3], [3, 4],  # Right arm
#     [0, 5], [5, 6], [6, 7], [7, 8],  # Left arm
#     [0, 9], [9, 10], [10, 11], [11, 12],  # Right leg
#     [0, 13], [13, 14], [14, 15], [15, 16],  # Left leg
#     [0, 17],  # Body
# ]
connections= [  # assume it used openpose 18 keypoint model
    [0, 1], [0, 14], [0, 15],
    [1, 2], [1, 5], [1, 8],[1,11],
    [2, 3],
    [3, 4],
    [5, 6],
    [6, 7],
    [8, 9],
    [9, 10],
    [11,12],
    [12,13],
    [14, 16],
    # [15, 17],
]
# Load the keypoints from a JSON file
with open("DSC_0808_000000000000_keypoints.json") as f:
    data = json.load(f)

# Extract the x and y coordinates of each keypoint
keypoints = np.array(data["people"][0]["pose_keypoints"]).reshape(-1, 3)[:, :2]
keypoints[:,1]=-keypoints[:,1]
x=keypoints[10,0]
y=keypoints[10,1]
# keypoints[:,0]=keypoints[:,0]-x
# keypoints[:,1]=keypoints[:,1]-y
# Plot the skeleton
fig, ax = plt.subplots()
ax.set_aspect("equal")
ax.set_xlim(-1000, 1000)
ax.set_ylim(-1000, 1000)
# ax.invert_yaxis()  # Flip the y-axis to match the OpenPose coordinate system)
for connection in connections:
    start = keypoints[connection[0]]
    end = keypoints[connection[1]]
    ax.plot([start[0], end[0]], [start[1], end[1]], color="blue")
plt.show()


from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64

key = base64.b64decode(b'VGhlX09wZXJhdG9yczIxMQ==')
iv = b'kRsKfm6P4mmp6CXS'

with open('2.dat', 'r') as f:
    data = f.read()
bytes_string = bytes.fromhex(data)
cipher = AES.new(key, AES.MODE_CFB, iv)
plaintext = cipher.decrypt(bytes_string)
#plaintext = unpad(plaintext, AES.block_size)

for i in plaintext:
    print(i, end = " ")


import numpy as np
import keras

from keras.layers import Input, Dense, Reshape, Flatten, Dropout, multiply, GaussianNoise
from keras.layers import BatchNormalization, Activation, Embedding, ZeroPadding2D
from keras.layers import MaxPooling2D, Lambda
from keras.layers.convolutional import UpSampling2D, Conv2D, Conv2DTranspose, Cropping2D
from keras.models import Sequential, Model
from keras.layers import MaxPooling2D, concatenate, Add
import keras.backend as K

import keras.utils
from keras.engine.topology import Layer
class Bias(Layer):
    def build(self, input_shape):
        self.bias = self.add_weight(shape=(input_shape[-1],),
                                        initializer="zeros",
                                        name='bias',
                                        regularizer=None,
                                        constraint=None)
        super(Bias, self).build(input_shape)

    def call(self, inputs):
        outputs = K.bias_add(
                inputs,
                self.bias)
        return outputs

    def compute_output_shape(self, input_shape):
        return input_shape

keras.layers.Bias = Bias

def partial_convolution(input_, mask, filters, shape, stride, activation):
    convolution_layer = Conv2D(filters, shape, strides=stride, use_bias=False,
                               padding="same")

    mask_sum_layer = Conv2D(filters, shape, strides=stride,
                                  padding="same",
                                  weights=[np.ones((shape[0], shape[1], input_.shape[-1], filters)),
                                           np.zeros((filters,))])

    mask_sum_layer.trainable = False

    mask_sum = mask_sum_layer(mask)

    new_mask = Lambda(lambda x: K.clip(x, 0, 1))(mask_sum)

    output = convolution_layer(keras.layers.multiply([mask, input_]))

    inv_sum = Lambda(lambda x: filters * shape[0] * shape[1] / (.0001 + x))(mask_sum)

    output = keras.layers.multiply([output, inv_sum])

    output = Bias()(output)

    output = activation(output)

    return output, new_mask

def nvidia_unet(patch_size=256):
    input_ = Input((patch_size, patch_size, 3))
    input_mask = Input((patch_size, patch_size, 3))
    skips = []
    output = input_
    mask = input_mask
    for shape, filters in zip([7, 5, 5, 3, 3, 3, 3, 3], [64, 128, 256, 512, 512, 512, 512, 512]):
        skips.append((output, mask))
        print(output.shape)
        output, mask = partial_convolution(output, mask, filters, (shape, shape), 2,
                                           Activation("relu"))
        if shape != 7:
            output = BatchNormalization()(output)
    for shape, filters in zip([4, 4, 4, 4, 4, 4, 4, 4], [512, 512, 512, 512, 256, 128, 64, 3]):
        output = keras.layers.UpSampling2D()(output)
        mask = keras.layers.UpSampling2D()(mask)
        skip_output, skip_mask = skips.pop()
        output = concatenate([output, skip_output], axis=3)
        mask = concatenate([mask, skip_mask], axis=3)

        if filters != 3:
            activation = keras.layers.LeakyReLU(.2)
        else:
            activation = Activation("linear")
        output, mask = partial_convolution(output, mask, filters, (shape, shape), 1, activation)
        if filters != 3:
            output = BatchNormalization()(output)
    assert len(skips) == 0
    return Model([input_, input_mask], [output])

def pad_to_patch_size(image, mask, patch_size=256):
    #Network only accepts square images with size as a multiple of 256.
    #Use the mask to make sure that the output only depends on the valid rectangle.
    network_input = np.zeros((1, patch_size, patch_size, 3))
    network_mask = np.zeros((1, patch_size, patch_size, 3))

    network_input[:, :image.shape[1], :image.shape[2]] = image
    network_mask[:, :mask.shape[1], :mask.shape[2]] = mask

    return network_input, network_mask

def compute_patch_size_to_fit(z):
    num_patches = (max(z.shape[1], z.shape[2]) - 1) // 256 + 1
    return 256 * num_patches


from flask_restplus import Namespace, Resource, fields, reqparse
import core as dbfn
import json
#NOTE: reqparse will be removed eventually, so a different parser might need to be implemented later
#no authentication right now, just string confirmation
api = Namespace('Users', description='User related operations')

names = api.model('Names', {
    'first_name': fields.String(required=True, description='User first name'),
    'last_name' : fields.String(required=True, description='User last name')
})

user = api.model('User', {
    'user_id': fields.Integer(readonly=True, description='User unique ID'),
    'first_name': fields.String(required=True, description='User first name'),
    'last_name' : fields.String(required=True, description='User last name'),
    'email' : fields.String(required=True, description='User Email address'),
    'pass_word' : fields.String(required=True, description='User\'s password'),
    'attending': fields.Boolean(description='If User attending next event'),
    'vote_id' : fields.Integer(default=0, description='What movie User has voted on')
})

email = api.model('Email', {'email' : fields.String(required=True, description= 'the user email address')})

@api.route('/')
class UserList(Resource):
    '''Shows a list of all users and create new users'''
    @api.doc('list_users')
    @api.marshal_list_with(user, envelope="User_list")
    def get(self):
        '''List all users'''
        tuples = dbfn.queryDB('select * from users')
        return tuples

    @api.doc('create_user')
    @api.expect(user)
    @api.marshal_with(user, code=201)
    def post(self):
        '''Create a new User'''
        #need pass down values
        print(((api.payload['first_name'])))
        insert_str = '\'' + api.payload['first_name'] + '\', \'' + api.payload['last_name'] + '\', \'' + api.payload['email'] +'\', \'' + api.payload['pass_word'] + '\', false, 0'
        dbfn.commitDB('insert into users (first_name, last_name, email, pass_word, attending, vote_id) values ('+ insert_str +')')
        return { 'message' : 'user create success' }, 201

@api.route('/<int:id>')
@api.param('id', 'The users unique identifier')
@api.response(404, 'User not found')
class User(Resource):
    '''Show a single user and can update/delete users'''
    @api.doc('get_user')
    @api.marshal_with(user)
    def get(self, id):
        '''Fetch a user given its identifier'''
        return dbfn.queryDB('select * from users where user_id = ' + id), 200

    @api.doc('delete_user')
    @api.response(204, 'User deleted')
    def delete(self, id):
        '''Delete a user given its identifier'''
        dbfn.commitDB('delete from users where user_id = '+id)
        return {"message": "user " + id + " deleted"}, 204
        # api.abort(404)
    @api.doc('update_user')
    @api.marshal_with(user)
    def put(self,id): #maybe should be patch?
        #add check if exist else return no user
        #need help on what to be updating...? shouldn't need an update
        '''Update user data'''
        #query =
        #dbfn.commitDB('update users set '+ query +'where user_id = '+id)
        return {'message':'user ' +id+' updated'}

@api.route('/attendee')
class Attending(Resource):
    @api.doc('get_list_of_attending_users')
    @api.marshal_list_with(names)
    def get(self):
        '''List all users attending'''
        tuples = dbfn.queryDB('select first_name, last_name from users where attending = true')
        print(tuples)
        return tuples

@api.route('/attendee/<int:id>/<string:attend>')
class userAttending(Resource):
    @api.doc('Update attendance of specific user')
    def patch(self, id, attend):
        # usr = USERS.get(id)
        dbfn.commitDB('update users set attending = '+ attend +' where user_id = '+str(id))
        return {"message": "attendance updated to "+ attend}, 204

@api.route('/email')
class emailAccess(Resource):
    @api.doc('search via email')
    @api.marshal_with(user)
    def get(self):
        return dbfn.queryDB('select * from users where email = \''+api.payload['email']+'\'')


from node import Node
from enums import *
import config

class SplitNode(Node):
    """Node of the tree

    Contains two children, which can be nodes or children.
    PlaneType defines whether the node is split horizontally or vertically
    """

    def __init__(self, **kwargs):
        Node.__init__(self, 2)

        self.plane_type = kwargs.get('plane_type', PLANE.HORIZONTAL)
        self.split_ratio = kwargs.get('split_ratio', 0.5)

    # --------------------------------------------------------------------------
    # Getters
    # --------------------------------------------------------------------------

    def get_plane_type(self):
        return self.plane_type

    def get_split_coordinate(self):
        ((_, _), (x_size, y_size)) = self.parent.get_viewport(self)

        if self.get_plane_type() == PLANE.HORIZONTAL:
            split_coordinate = int(y_size * self.get_split_ratio())
        elif self.get_plane_type() == PLANE.VERTICAL:
            split_coordinate = int(x_size * self.get_split_ratio())
        else:
            raise Exception("Invalid plane")

        return split_coordinate

    def get_split_ratio_from_split_coordinate(self, split_coordinate):
        ((_, _), (x_size, y_size)) = self.parent.get_viewport(self)

        if self.get_plane_type() == PLANE.HORIZONTAL:
            split_ratio = float(split_coordinate) / float(y_size)
        elif self.get_plane_type() == PLANE.VERTICAL:
            split_ratio = float(split_coordinate) / float(x_size)
        else:
            raise Exception("Invalid plane")

        return split_ratio

    def get_split_ratio(self):
        return self.split_ratio

    # --------------------------------------------------------------------------
    # Setters
    # --------------------------------------------------------------------------

    def set_plane_type(self, new_plane_type):
        self.plane_type = new_plane_type

    def set_split_ratio(self, new_split_ratio):
        self.split_ratio = new_split_ratio

    def alter_split_coordinate(self, increment):
        new_split_coordinate = self.get_split_coordinate() + increment
        new_split_ratio = self.get_split_ratio_from_split_coordinate(
            new_split_coordinate)
        self.set_split_ratio(new_split_ratio)

    # --------------------------------------------------------------------------
    # Trickle downs
    # --------------------------------------------------------------------------

    def to_json(self):
        json = Node.to_json(self)
        json['type'] = 'split_node'
        json['plane_type'] = self.get_plane_type()
        json['split_ratio'] = self.get_split_ratio()

        return json

    def get_layout_json(self):
        json = Node.get_layout_json(self)
        json['type'] = 'split_node'
        json['plane_type'] = self.get_plane_type()
        json['split_ratio'] = self.get_split_ratio()

        return json

    def restore_splits(self):
        self.set_split_ratio(self.get_split_ratio())
        [c.restore_splits() for c in self.get_children()]

    def set_regular_state(self, state=WINDOW_STATE.NORMAL):
        [win.set_regular_state(state) for win in self.get_children()]

    # --------------------------------------------------------------------------
    # Bubble ups
    # --------------------------------------------------------------------------

    def get_split_node(self):
        return self

    def get_smallest_immutable_subtree(self, calling_child):
        return calling_child

    # --------------------------------------------------------------------------
    # Child Requests
    # --------------------------------------------------------------------------

    def get_viewports(self):
        """
        Horizontal Split

                 x size
               |-----------|

        (x, y) +-----------+  -        -
               |           |  |        |
               |           |  | y      | split
               +-----------+  | size   -
               |           |  |
               |           |  |
               +-----------+  -

        Vertical Split

                 x size
               |-----------|

        (x, y) +-----+-----+  -
               |     |     |  |
               |     |     |  | y
               |     |     |  | size
               |     |     |  |
               |     |     |  |
               +-----+-----+  -

               |-----|
                split
        """
        (x_pos, y_pos), (x_size, y_size) = self.parent.get_viewport(self)
        split = self.get_split_coordinate()

        if self.get_plane_type() == PLANE.HORIZONTAL:
            x_pos_1 = x_pos
            y_pos_1 = y_pos
            x_size_1 = x_size
            y_size_1 = split

            x_pos_2 = x_pos
            y_pos_2 = y_pos + split
            x_size_2 = x_size
            y_size_2 = y_size - split

            # Gap correction
            y_size_1 -= config.get_config('gap') / 2

            y_pos_2 += config.get_config('gap') / 2
            y_size_2 -= config.get_config('gap') / 2

        elif self.get_plane_type() == PLANE.VERTICAL:
            x_pos_1 = x_pos
            y_pos_1 = y_pos
            x_size_1 = split
            y_size_1 = y_size

            x_pos_2 = x_pos + split
            y_pos_2 = y_pos
            x_size_2 = x_size - split
            y_size_2 = y_size

            # Gap correction
            x_size_1 -= config.get_config('gap') / 2

            x_pos_2 += config.get_config('gap') / 2
            x_size_2 -= config.get_config('gap') / 2
        else:
            raise Exception("Invalid plane")

        viewport_1 = ((x_pos_1, y_pos_1), (x_size_1, y_size_1))
        viewport_2 = ((x_pos_2, y_pos_2), (x_size_2, y_size_2))
        return [viewport_1, viewport_2]

    def get_viewport(self, calling_child):
        index = self.get_child_index(calling_child)
        return self.get_viewports()[index]

    def change_plane(self):
        if self.get_plane_type() == PLANE.HORIZONTAL:
            self.set_plane_type(PLANE.VERTICAL)
        else:
            self.set_plane_type(PLANE.HORIZONTAL)

        self.set_split_ratio(0.5)
        self.restore_splits()
        self.redraw()

    # --------------------------------------------------------------------------
    # Other
    # --------------------------------------------------------------------------

    def resize(self, child, plane_type, increment):
        if self.get_plane_type() != plane_type:
            self.parent.resize(self, plane_type, increment)
            return

        if self.get_child_index(child) == 1:
            increment *= -1
        self.alter_split_coordinate(increment)
        self.redraw()

    # TODO: Refactor name
    def all_are_bees(self, caller_child):
        """If the calling child is 'ChildB', ripple the call up to check if THIS
        caller is also 'ChildB'
        Returns True if the entire call stack up to the screen are all
        'ChildB's.

        Returns False if any along the call stack are 'ChildA'
        """
        if self.get_child_index(caller_child) == 1:
            return self.parent.all_are_bees(self)
        return False

    # TODO: Refactor name
    def find_earliest_a_but_not_me(self, caller_child):
        """Returns the earliest (deepest in the tree, but above the caller)
        'ChildA' that is not part of the call stack
        """
        if self.get_child_index(caller_child) == 0:
            return self.parent.find_earliest_a_but_not_me(self)
        return self.get_child(0)


"""
Berezhnyi Oleksii
Homework 16. Iterators and Generators
"""

# Task 1

def with_index(iterable, start=0):
    for i in iterable:
        yield start, i
        start += 1

s = {1, "string", 4, True}
print(list(with_index(s, 10)))

# Task 2

def in_range(start, end, step=1):
    if start < end:
        while start < end:
            start += abs(step)
            yield start - abs(step)
    else:
        while start > end:
            start -= abs(step)
            yield start + abs(step)

r = in_range(1, -10, -2)
for i in r:
    print(i)
print("*" * 80)
for i in range(1, -10, -2):  #
    print(i)

# Task 3

class Iterable:

    def __init__(self, iterable):
        self._iterable = iterable
        self._index = len(iterable)
        self._i = -1

    # def __getitem__(self, item):
    #     self._i += 1
    #     return self._iterable[self._i]

    def __iter__(self):
        return (self)

    def __next__(self):
        self._i += 1
        if self._i == self._index:
            raise StopIteration
        return self._iterable[self._i]

iter = Iterable("asdlaksdlajhs")
for i in iter:
    print(i)

16_Iterators_and_Generators/homework16 Iterators and Generators.py


from decimal import Decimal, getcontext
from vector import Vector

getcontext().prec = 30

class Plane(object):
    '''Vector representation of a Plane in three dimension'''

    NO_NONZERO_ELTS_FOUND_MSG = 'No nonzero elements found'

    def __init__(self, normal_vector=None, constant_term=None):
        '''Create a Plane Object

        Ax + By + Cz = k
        Vector([A, B, C]) represents a normal Vector'''
        self.dimension = 3

        if not normal_vector:
            all_zeros = ['0'] * self.dimension
            normal_vector = Vector(all_zeros)
        self.normal_vector = normal_vector

        if not constant_term:
            constant_term = Decimal('0')
        self.constant_term = Decimal(constant_term)

        self.set_basepoint()

    def __getitem__(self, i):
        return self.normal_vector[i]

    def set_basepoint(self):
        '''find the first non zero coordinate, either (0, k/B) or (k/A, 0)'''
        try:
            n = self.normal_vector
            c = self.constant_term
            basepoint_coords = ['0'] * self.dimension

            initial_index = Plane.first_nonzero_index(n)
            initial_coefficient = n[initial_index]

            basepoint_coords[initial_index] = c / initial_coefficient
            self.basepoint = Vector(basepoint_coords)

        except Exception as e:
            if str(e) == Plane.NO_NONZERO_ELTS_FOUND_MSG:
                self.basepoint = None
            else:
                raise e

    def __str__(self):

        num_decimal_places = 3

        def write_coefficient(coefficient, is_initial_term=False):
            coefficient = round(coefficient, num_decimal_places)
            if coefficient % 1 == 0:
                coefficient = int(coefficient)

            output = ''

            if coefficient < 0:
                output += '-'
            if coefficient > 0 and not is_initial_term:
                output += '+'

            if not is_initial_term:
                output += ' '

            if abs(coefficient) != 1:
                output += '{}'.format(abs(coefficient))

            return output

        n = self.normal_vector

        try:
            initial_index = Plane.first_nonzero_index(n)
            terms = []
            for i in range(self.dimension):
                if round(n[i], num_decimal_places) != 0:
                    terms.append(write_coefficient(
                        n[i],
                        is_initial_term=(i == initial_index)) +
                        'x_{}'.format(i + 1))
            output = ' '.join(terms)

        except Exception as e:
            if str(e) == self.NO_NONZERO_ELTS_FOUND_MSG:
                output = '0'
            else:
                raise e

        constant = round(self.constant_term, num_decimal_places)
        if constant % 1 == 0:
            constant = int(constant)
        output += ' = {}'.format(constant)

        return output

    @staticmethod
    def first_nonzero_index(iterable):
        for k, item in enumerate(iterable):
            if not MyDecimal(item).is_near_zero():
                return k
        raise Exception(Plane.NO_NONZERO_ELTS_FOUND_MSG)

    def is_parallel_to(self, plane2):
        '''two planes are parallel if their normal vectors are parallel'''
        return self.normal_vector.is_parallel_to(plane2.normal_vector)

    def __eq__(self, plane2):
        '''two planes are equal, if the vector connecting one point on each
        plane is orthogonal to the planes normal vectors'''
        # normal vector have to be parallel in order to be equal
        # if not self.is_parallel_to(plane2):
        #     return False

        # v_connect = self.basepoint.minus(plane2.basepoint)
        # return v_connect.is_orthogonal_to(self.normal_vector)
        if self.normal_vector.is_zero():
            if not plane2.normal_vector.is_zero():
                return False

            diff = self.constant_term - plane2.constant_term
            return MyDecimal(diff).is_near_zero()

        elif plane2.normal_vector.is_zero():
            return False

        if not self.is_parallel_to(plane2):
            return False

        basepoint_difference = self.basepoint.minus(plane2.basepoint)
        return basepoint_difference.is_orthogonal_to(self.normal_vector)

class MyDecimal(Decimal):
    def is_near_zero(self, eps=1e-10):
        return abs(self) < eps

if __name__ == '__main__':

    print('################################')
    print('Quiz: Planes in 3 Dimensions - 2')

    p1 = Plane(Vector([-0.412, 3.806, 0.728]), -3.46)
    p2 = Plane(Vector([1.03, -9.515, -1.82]), 8.65)
    print('equal: {0}'.format(p1 == p2))
    print('parallel but unequal: {0}'.format(p1.is_parallel_to(p2)))

    p3 = Plane(Vector([2.611, 5.528, 0.283]), 4.6)
    p4 = Plane(Vector([7.715, 8.306, 5.342]), 3.76)
    print('equal: {0}'.format(p3 == p4))
    print('parallel but unequal: {0}'.format(p3.is_parallel_to(p4)))

    p5 = Plane(Vector([-7.926, 8.625, -7.212]), -7.952)
    p6 = Plane(Vector([-2.642, 2.875, -2.404]), -2.443)
    print('equal: {0}'.format(p5 == p6))
    print('parallel but unequal: {0}'.format(p5.is_parallel_to(p6)))


# This is a simple program for finding the sum of digits in python

def getAns(n):
    sum = 0
    while (n != 0):
        sum += int(n % 10)
        #Gets the digit
        n = n // 10
        # You can also do "n = int(n/10)"
    return sum

# Call Function
num = int(input("Enter a poitive integer:".rstrip()))
print(f"The sum of the digits of the number {num} is: {getAns(num)}")

#Excal-rs Github


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

urlpatterns = [
    url(r'^login/', login, name='login'),
    url(r'^logout/', logout, name='logout'),
    path(r'view/', view_movie, name='view'),
    path(r'add/', add_movie, name='add'),
    path(r'update/<data>', update_movie, name='update'),
    path(r'delete/<str:movie_name>', delete_movie, name='delete'),
    path(r'', search_movie, name='search'),
]


# Day 28 - Type Hinting

# The benefits of type hinting:
# 1.It makes it easier to understand our code, because our helpful variable names are now accompanied by a description
# of the sort of data we expect to be assigned to them.
# 2.Most modern editors are able to make good use of our type annotations to provide more meaningful hints when we do
# things like calling functions.
# 3. We can use tools like mypy to check that our type annotations are being honoured, helping us catch bugs caused by
# passing around incorrect types.

# Installing mypy : python -m pip install mypy

# from typing import Union
#
# name: str = "Phil"
# age: int = 29
# height_metres: Union[int, float] = 1.87

# from typing import Any
#
# name: str = "Phil"
# age: int = 29
# height_metres: Any = 1.87

# from typing import List

# names: List[str]  =  ["Rick", "Morty", "Summer", "Beth", "Jerry"]

# from typing import List, Union
#
# random_values: List[Union[str, int]] =  ["x", 13, "camel", 0]

# from typing import Tuple
#
# movie: Tuple[str, str, int] = ("Toy Story 3", "Lee Unkrich", 2010)

# In Python 3.9 we won't have to import things like Tuple, List, and Dict from the typing module.
# Instead, we'll be able to use the standard tuple, list, and dict types for annotation.

# from typing import List, Tuple
#
# movies: List[Tuple[str, str, int]] = [
#     ("Finding Nemo", "Andrew Stanton", 2005),
#     ("Inside Out", "Pete Docter", 2015),
#     ("Toy Story 3", "Lee Unkrich", 2010)
# ]

# from typing import List, Tuple
#
# Movie = Tuple[str, str, int]
#
# movies: List[Movie] = [
#     ("Finding Nemo", "Andrew Stanton", 2005),
#     ("Inside Out", "Pete Docter", 2015),
#     ("Toy Story 3", "Lee Unkrich", 2010)
# ]

from typing import List, Tuple, Union

Movie = Tuple[str, str, int]

def find_movie(search_term: str, movies: List[Movie]):
    for title, director, year in movies:
        if title == search_term:
            return (title, director, year)

def show_movies(movies: List[Movie]):
    for movie in movies:
        print_movie(movie)

def print_movie(movie: Movie):
    title, director, year = movie
    print(f"{title} ({year}), by {director}")

movies: List[Movie] = [
    ("Finding Nemo", "Andrew Stanton", 2005),
    ("Inside Out", "Pete Docter", 2015),
    ("Toy Story 3", "Lee Unkrich", 2010)
]

show_movies(movies)

search_result: Union[Movie, None] = find_movie("Finding Nemo", movies)

if search_result:
    print_movie(search_result)
else:
    print("Couldn't find movie.")

"""Exercises
There's only one exercise today, because it's a big one. Take your final solution to the day 14 project
(easy or hard version) and implement type hinting for your code.

If you're unsure of how to do something, remember that you can always look at the typing module documentation."""


from strategy.base_ccp import BaseCaptain
from gosling.utils import *
from physics.math import Vec3
from strategy.drone import Drone
from strategy.players import *
import numpy as np

class DefenderState:
    """"
    In shadowing, the keeper goes to the goal and focuses on strategic positioning.
    Once the correct position is reached we wait for a shot at goal
    In keeping, the keeper attempts to prevent a goal
    """
    GET_BOOST = 0
    COVER = 1
    COVER_NEAR = 2
    SHOOT = 3
    INACTIVE = 4

class AttackerState:
    """
    Gets boost in the mid area, then shoots the ball if it is on the enemy side.
    If not on the enemy side -> Call prepare first to ensure positioning is correct.
    After the optional Prepare step it shoots.
    """
    PREPARE = 1
    SHOOT = 2
    COVER = 3

class Attack(BaseCaptain):
    """"
    Assign the roles (tactics) to the bots in the current team when defending.
    We have one bot who is the assigned keeper and two other bots who fetch boost.
    """
    LENGTH_MAP_ONE_SIDE = 5250
    BOOST_THRESHOLD = 30
    SHOOT_RANGE = 3000

    ATTACKER_COVER_DIST_RATIO = 0.70  # Ratio at which the attacking drones cover
    ATTACKER_CANCEL_CHECK_RANGE = 1500  # Range at which we consider to cancel our shot
    ATTACKER_PREPARE_OFFSETS = [1500, 2500]  # Prepare offest range

    DEFENDER_COVER_DIST_RATIO = 0.40  # Ratio at which the defending drone covers
    DEFENDER_COVER_PREP_RATIO = 0.75
    DEFENDER_DRONE_PREPARE_X_WINDOW = 2400  # Max distance from y-centerline to consider preparing
    DEFENDER_DRONE_SHOOT_X_WINDOW = 1400  # Max distance from y-centerline to consider shooting

    FACTOR_SCORE_HIGH_PENALTY = 1000  # The factor by which we multiply score (higher score is bad)

    def __init__(self):
        self.team = self.drones[0].team
        self.own_goal_location = Vec3(0, self.LENGTH_MAP_ONE_SIDE * side(self.team), 0)
        self.other_goal_location = Vec3(0, self.LENGTH_MAP_ONE_SIDE * side(self.team) * -1, 0)

        # Clear the stacks
        for drone in self.drones:
            drone.flush_actions()

        drone_closest_to_ball = self._get_teammate_closest_to_ball(prefer_friendly_side=True)
        self.attacker_drones = [drone_closest_to_ball]
        self.attacker_states = {drone_closest_to_ball: AttackerState.PREPARE}
        drone_closest_to_ball.assign(Prepare())

        # Select keeper from remaining drones
        remaining_drones = [drone for drone in self.drones if (drone != drone_closest_to_ball)]
        if len(remaining_drones) > 0:
            goal_dist = {(Vec3.from_other_vec(drone.car.physics.location) - self.own_goal_location).magnitude(): drone
                         for drone in remaining_drones}
            self.defender_drone = goal_dist[min(goal_dist.keys())]
            self.defender_state = DefenderState.COVER
            self.defender_drone.assign(Cover(distance_ratio=self.DEFENDER_COVER_DIST_RATIO))
        else:
            self.defender_drone = None
            self.defender_state = DefenderState.INACTIVE

        # All other drones
        remaining_drones = [drone for drone in remaining_drones if (drone != self.defender_drone)]
        for idx, drone in enumerate(remaining_drones):
            self.attacker_states[drone] = AttackerState.COVER
            self.attacker_drones.append(drone)
            drone.assign(Cover(distance_ratio=self.ATTACKER_COVER_DIST_RATIO))

        offsets = np.linspace(*self.ATTACKER_PREPARE_OFFSETS, num=len(self.attacker_drones))
        self.attacker_offsets = {drone: offset for drone, offset in zip(self.attacker_drones, offsets)}

    def step(self):
        """
        Return whether this captain is done or not
        Assigns bots, to get boost and then go to the ball or shadow.
        Assigns one bot to keeper which, intercept the ball if there is a predicted goal

        :return: Done flag, true if finished
        :rtype: bool
        """
        if self.defender_drone is not None:
            self._control_defender()
        self._control_attacker_drones()

    def _control_defender(self):
        """Sets the control for the keeper drone"""
        # Controlling the keeper
        done = self.defender_drone.step()

        centerline_dist = abs(self.world.ball.physics.location.x)

        # done and COVER -> SHOOT if opportunity else COVER
        if done and self.defender_state == DefenderState.COVER:
            self._defender_act_ball_near_center(centerline_dist)

        elif done and self.defender_state == DefenderState.COVER_NEAR:
            # print("CPT ATTACK: DEFENDER - INTERCEPT")
            self.defender_drone.assign(Intercept())
            self.defender_state = DefenderState.SHOOT

        elif self.defender_state == DefenderState.COVER_NEAR:

            if centerline_dist > self.DEFENDER_DRONE_PREPARE_X_WINDOW:
                # print("CPT ATTACK: DEFENDER - Too far from center - Back to Cover")
                self.defender_drone.flush_actions()
                self.defender_drone.assign(Cover(distance_ratio=self.DEFENDER_COVER_DIST_RATIO))
                self.defender_state = DefenderState.COVER

            elif centerline_dist < self.DEFENDER_DRONE_SHOOT_X_WINDOW:
                # print("CPT ATTACK: DEFENDER - Right in center -> Skip prepare! SHOOT!")
                self.defender_drone.flush_actions()
                self.defender_drone.assign(Intercept())
                self.defender_state = DefenderState.SHOOT

        # done and SHOOT -> COVER
        elif self.defender_state == DefenderState.SHOOT:
            if done:
                # print("CPT ATTACK: DEFENDER - SHOT DONE - Returning")
                self.defender_drone.assign(Cover(distance_ratio=self.DEFENDER_COVER_DIST_RATIO))
                self.defender_state = DefenderState.COVER
            elif centerline_dist > self.DEFENDER_DRONE_PREPARE_X_WINDOW:
                # print("CPT ATTACK: DEFENDER - Shot out of window")
                self.defender_drone.flush_actions()
                self.defender_drone.assign(Cover(distance_ratio=self.DEFENDER_COVER_DIST_RATIO))
                self.defender_state = DefenderState.COVER

    def _defender_act_ball_near_center(self, centerline_dist: float):
        """ Controls the defender drone depending on how far the ball is from the center Y-axis """
        if centerline_dist < self.DEFENDER_DRONE_SHOOT_X_WINDOW:
            # print("CPT ATTACK: DEFENDER - Right in center - COVER -> INTERCEPT")
            self.defender_drone.assign(Intercept())
            self.defender_state = DefenderState.SHOOT

        elif centerline_dist < self.DEFENDER_DRONE_PREPARE_X_WINDOW:
            # print("CPT ATTACK: DEFENDER - NEAR CENTER - START PREPARING")
            self.defender_drone.assign(Cover(distance_ratio=self.DEFENDER_COVER_PREP_RATIO))
            self.defender_state = DefenderState.COVER_NEAR
        else:
            self.defender_drone.assign(Cover(distance_ratio=self.DEFENDER_COVER_DIST_RATIO))

    def _control_attacker_drones(self):
        """Sets the controls for all other drones"""
        # All other drones get boost and try to intercept
        for drone in self.attacker_drones:
            drone_state = self.attacker_states[drone]
            done = drone.step()

            if done:
                self._select_state_attacker_drone(drone, drone_state)
            else:
                self._check_and_adjust_current_state_attacker_drone(drone, drone_state)

    def _select_state_attacker_drone(self, drone: Drone, drone_state: int):
        """Switch to different state upon completion. Assumes that the current state is done"""
        if drone_state == AttackerState.PREPARE:
            if self._allow_shoot_state():
                self.attacker_states[drone] = AttackerState.SHOOT
                drone.assign(Intercept())
            else:
                self.attacker_states[drone] = AttackerState.PREPARE
                drone.assign(Prepare(offset_in_ball_direction=self.attacker_offsets[drone]))

        elif drone_state == AttackerState.SHOOT:
            self.attacker_states[drone] = AttackerState.COVER
            drone.assign(Cover(distance_ratio=self.ATTACKER_COVER_DIST_RATIO))

        elif drone_state == AttackerState.COVER:
            self.attacker_states[drone] = AttackerState.PREPARE
            drone.assign(Prepare(offset_in_ball_direction=self.attacker_offsets[drone]))

    def _check_and_adjust_current_state_attacker_drone(self, drone: Drone, drone_state: int):
        """Switch to different state before completion of the task when particular conditions are met"""
        if drone_state == AttackerState.SHOOT:
            if self._detect_bad_shot(drone):
                self.attacker_states[drone] = AttackerState.COVER
                drone.flush_actions()
                drone.assign(Cover(distance_ratio=self.ATTACKER_COVER_DIST_RATIO))

    def _allow_shoot_state(self) -> bool:
        """"Only allows shoot state when no other drone is shooting."""
        for d, state in self.attacker_states.items():
            if AttackerState.SHOOT == state:
                return False
        return True

    def _get_teammate_closest_to_ball(self, prefer_friendly_side: bool = False) -> Drone:
        """ Select the drone closest to the ball to attack first drones on correct side have a higher preference """
        if prefer_friendly_side:
            penalty_points = {}
            for drone in self.drones:
                ball_dist = self.world.calc_dist_to_ball(drone.car)
                if drone.car.physics.location.y * side(self.team) > self.world.ball.physics.location.y * \
                        side(self.team):
                    penalty_points[ball_dist * self.FACTOR_SCORE_HIGH_PENALTY] = drone
                else:
                    penalty_points[ball_dist] = drone
            drone_closest_to_ball = penalty_points[min(penalty_points.keys())]
        else:
            ball_dist = {self.world.calc_dist_to_ball(drone.car): drone for drone in
                         self.drones}
            drone_closest_to_ball = ball_dist[min(ball_dist.keys())]
        return drone_closest_to_ball

    def _detect_bad_shot(self, drone: Drone) -> bool:
        """"Check if our shot is bad"""
        # Can only be False when we are close to the ball
        if (Vec3.from_other_vec(self.world.ball.physics.location) -
            Vec3.from_other_vec(drone.car.physics.location)).magnitude() < self.ATTACKER_CANCEL_CHECK_RANGE:

            # Cancel if we expect to fire to our own goal
            if (self.world.ball.physics.location.y - drone.car.physics.location.y) * side(self.team) > 0:
                # print(f"Bad shot detected. Ball: {self.world.ball.physics.location.y} "
                #       f"Drone: {drone.car.physics.location.y}")
                return True

        return False


n = int(input())
p = list(map(int, input().split()))
ans = 0
for i in range(n-2):
    p1 = p[i]
    p2 = p[i+1]
    p3 = p[i+2]
    np = [p1, p2, p3]
    np.sort()
    if np[1] == p2:
        ans += 1
print(ans)