"""\
A pure Python package providing the core RDF constructs.

The packages is intended to provide the core RDF types and interfaces
for working with RDF. The package defines a plugin interface for
parsers, stores, and serializers that other packages can use to
implement parsers, stores, and serializers that will plug into the
rdflib package.

The primary interface `rdflib` exposes to work with RDF is
`rdflib.graph.Graph`.

A tiny example:

    >>> import rdflib

    >>> g = rdflib.Graph()
    >>> result = g.parse("http://www.w3.org/2000/10/swap/test/meet/white.rdf")

    >>> print("graph has %s statements." % len(g))
    graph has 19 statements.
    >>>
    >>> for s, p, o in g:
    ...     if (s, p, o) not in g:
    ...         raise Exception("It better be!")

    >>> s = g.serialize(format='n3')

"""
__docformat__ = "restructuredtext en"

# The format of the __version__ line is matched by a regex in setup.py
__version__ = "4.0.1"
__date__ = "2013/05/22"

__all__ = [
    'URIRef',
    'BNode',
    'Literal',
    'Variable',

    'Namespace',

    'Dataset',
    'Graph',
    'ConjunctiveGraph',

    'RDF',
    'RDFS',
    'OWL',
    'XSD',

    'util',
]

import sys
assert sys.version_info >= (2, 5, 0), "rdflib requires Python 2.5 or higher"
del sys

import logging
_LOGGER = logging.getLogger("rdflib")
_LOGGER.info("RDFLib Version: %s" % __version__)

NORMALIZE_LITERALS = True
"""
If True - Literals lexical forms are normalized when created.
I.e. the lexical forms is parsed according to data-type, then the
stored lexical form is the re-serialized value that was parsed.

Illegal values for a datatype are simply kept.  The normalized keyword
for Literal.__new__ can override this.

For example:

>>> from rdflib import Literal,XSD
>>> Literal("01", datatype=XSD.int)
rdflib.term.Literal(u'1', datatype=rdflib.term.URIRef(u'http://www.w3.org/2001/XMLSchema#integer'))

This flag may be changed at any time, but will only affect literals
created after that time, previously created literals will remain
(un)normalized.

"""

DAWG_LITERAL_COLLATION = False
"""
DAWG_LITERAL_COLLATION determines how literals are ordered or compared
to each other.

In SPARQL, applying the >,<,>=,<= operators to literals of
incompatible data-types is an error, i.e:

Literal(2)>Literal('cake') is neither true nor false, but an error.

This is a problem in PY3, where lists of Literals of incompatible
types can no longer be sorted.

Setting this flag to True gives you strict DAWG/SPARQL compliance,
setting it to False will order Literals with incompatible datatypes by
datatype URI

In particular, this determines how the rich comparison operators for
Literal work, eq, __neq__, __lt__, etc.
"""

from rdflib.term import (
    URIRef, BNode, Literal, Variable)

from rdflib.namespace import Namespace

from rdflib.graph import Dataset, Graph, ConjunctiveGraph

from rdflib.namespace import RDF, RDFS, OWL, XSD

from rdflib import plugin
from rdflib import query
# tedious sop to flake8
assert plugin
assert query

from rdflib import util


import pygame as pg
from enum import Enum
from sys import exit
import os

#Set working directory
proj_folder = str(os.path.dirname((os.path.dirname(os.path.realpath(__file__)))))
os.chdir(proj_folder+"\include")

#define game states
class GameState(Enum):

    CHARACTERSELECT = 0

    #TO-DO: Implement remaining game states

class GameStateManager:
    def __init__(self):
        self.current_state = None

    def change_state(self, new_state):
        self.current_state = new_state

    def run_state(self):
        # if self.current_state == GameState.TITLESCREEN:
        #     titlescreen()
        # elif self.current_state == GameState.LOGINSCREEN:
        #     loginscreen()
        # elif self.current_state == GameState.PLAYERCONNECT:
        #     playerconnect()
        if self.current_state == GameState.CHARACTERSELECT:
            characterselect()
        # elif self.current_state == GameState.MAINGAME:
        #     maingame()

#Define player class
class Player:
    def __init__(self, name, character, hasBomb, isAlive, playernum):
        self.name = name
        self.character = character
        self.hasBomb = hasBomb
        self.isAlive = isAlive
        self.img = pg.image.load("img/"+character+".png").convert_alpha()
        if playernum == 1:
            playerpos = (screenWidth//2, screenHeight//2+200)
        if playernum == 2:
            playerpos = (screenWidth//2 - 200, screenHeight//2-100)
        if playernum == 3:
            playerpos = (screenWidth//2+200, screenHeight//2-100)
        self.img = pg.transform.scale(self.img, (150, 150))
        self.player_rect = self.img.get_rect(center = playerpos)

    def throwBomb(self, direction):
        print ("Bomb thrown to " + str(direction))

#Define Screen Functions
def characterselect():
    #  #load character images
    # characters = ["sarim", "bouganis", "naylor"]
    # player1 = Player("noor", characters[0], hasBomb = True, isAlive = True, playernum = 1)
    # player2 = Player("shaheer", characters[1], hasBomb = False, isAlive = True, playernum =  2)
    # player3 = Player("jim", characters[2], hasBomb = False, isAlive = True, playernum = 3)
    # player1 = pg.image.load("img/sarim.png").convert_alpha()
    # player2 = pg.image.load("img/sarim.png").convert_alpha()
    # player3 = pg.image.load("img/sarim.png").convert_alpha()
    # players = [player1, player2, player3]
    characters_1 = pg.image.load("img/sarim.png").convert_alpha()
    characters_2 = pg.image.load("img/bouganis.png").convert_alpha()
    characters_3 = pg.image.load("img/naylor.png").convert_alpha()

    characters_1 = pg.transform.scale(characters_1, (300, 150))
    characters_1_trans = characters_1.copy()
    characters_1_trans.set_alpha(120)#Pass 0 for invisible and 255 for fully opaque.
    characters_1rect = characters_1.get_rect(center=((screenWidth // 3)-250,(screenHeight // 3)-70))

    characters_2 = pg.transform.scale(characters_2, (300, 150))
    characters_2_trans = characters_2.copy()
    characters_2_trans.set_alpha(240)
    characters_2rect = characters_2.get_rect(center=((screenWidth // 2), (screenHeight // 3)-70))

    characters_3 = pg.transform.scale(characters_3, (300, 150))
    characters_3_trans = characters_3.copy()
    characters_3_trans.set_alpha(120)
    characters_3rect = characters_3.get_rect(center=((screenWidth // 1.5)+250,(screenHeight // 3)-70))

    # for player in players:
    #     player = pg.transform.scale(player, (300, 150))
    play=["jim","noor", "shaheer"]
    numPlayers = 3

    cc=0
    ccc1=0
    ccc2=0
    ccc3=0
    pg.display.flip()
    characters_rects=[characters_1rect,characters_2rect, characters_3rect]
    #characters_rects=[]

    while True:
        for event in pg.event.get():
            state = "Waiting"
            if cc < numPlayers:
               plays = play[cc]
            if event.type == pg.QUIT:
                pg.quit()
                exit()
            elif event.type == pg.MOUSEBUTTONUP:
                if cc <numPlayers:
                    print(cc)
                    #plays = play[cc]
                    state = "0"
                    Plays_msg = font1.render(' please connect to a character'+plays, True, black)
                    Plays_msgrect = Plays_msg.get_rect(center=((screenWidth // 2) , (screenHeight //2) +150))
                    #screen.blit(Plays_msg,Plays_msgrect)
                    print (plays)
                    if (characters_1rect.collidepoint(pg.mouse.get_pos())) and ccc1<1:
                     #       playersss.append(player)
                        state ="1"
                        #characters_rects.append(characters_1rect)
                        success_msg1 = font1.render(plays+' connected to Character1', True, black)
                        success_msg1rect = success_msg1.get_rect(center= ((screenWidth // 2) , (screenHeight //2) +150))
                        ccc1 = ccc1+1
                        cc+=1
                        #print("successfully selected")

                    elif (characters_2rect.collidepoint(pg.mouse.get_pos())) and ccc2<1:
                     #       playersss.append(player)
                        state ="2"
                        #characters_rects.append(characters_2rect)
                        success_msg2 = font1.render(plays+' connected to Character2', True, black)
                        success_msg2rect = success_msg2.get_rect(center= ((screenWidth // 2) , (screenHeight //2) +200))
                        ccc2 = ccc2+1
                        cc+=1
                       # print("successfully selected")

                    elif (characters_3rect.collidepoint(pg.mouse.get_pos())) and ccc3<1:
                     #       playersss.append(player)
                        state ="3"
                       # characters_rects.append(characters_3rect)
                        success_msg3 = font1.render(plays+' connected to Character3', True, black)
                        success_msg3rect = success_msg3.get_rect(center= ((screenWidth // 2) , (screenHeight //2) +250))
                        ccc3 = ccc3+1
                        cc+=1
                    elif  ((characters_3rect.collidepoint(pg.mouse.get_pos())) and ccc3!=0) or  ((characters_2rect.collidepoint(pg.mouse.get_pos())) and ccc2!=0) or ((characters_1rect.collidepoint(pg.mouse.get_pos())) and ccc1!=0):
                        state ="error"
                        print("error")
            elif ccc3 <1 or ccc2 <1 or ccc1 <1:
                 state = "0"
                 Plays_msg = font1.render(plays+' please connect to a character', True, black)
                 Plays_msgrect = Plays_msg.get_rect(center=((screenWidth // 2) , (screenHeight //2) +150))

            elif ccc3>0 and ccc2 >0 and ccc1>0:
                state = "All_Characters_Connected"

            if event.type == pg.KEYDOWN and state == "All_Characters_Connected":
                game_state_manager.change_state(GameState.LOGINSCREEN)
               # game_state_manager.run_state(MAINGAME)
                #print("game")

            screen.fill(light_grey)
            unsuccess_msg = font1.render("Character selected, please select another one", True, black)
            unsuccess_msgrect = unsuccess_msg.get_rect(center= ((screenWidth // 2) , (screenHeight //2) +150))
            start_msg = font1.render('Start game', True, black)
            start_msg_rect = start_msg.get_rect()
            start_msg_rect.center = ((screenWidth / 2 - start_msg.get_width() / 2), (screenHeight - 45))
            waiting_msg2 = font1.render("No Character selected yet. Press any key to start character select", True, black)
            waiting_msg2rect =  waiting_msg2.get_rect(center= ((screenWidth // 2) , (screenHeight //3) -200))

            if state == "Waiting":
               screen.blit(waiting_msg2,waiting_msg2rect)
            elif state == "All_Characters_Connected" :
               screen.blit(success_msg1,success_msg1rect)
               screen.blit(success_msg2,success_msg2rect)
               screen.blit(success_msg3,success_msg3rect)
               pg.draw.rect(screen, green, (screenWidth / 2 - 75, (screenHeight //2) +40, 150, 50), border_radius=10)
               screen.blit(start_msg, (screenWidth / 2 - start_msg.get_width() / 2, (screenHeight//2) +50))
               print("state_all")
            elif state=="0":
                screen.blit(Plays_msg,Plays_msgrect)
            elif state =="1" :
                screen.blit(success_msg1,success_msg1rect)
            elif state =="2":
               screen.blit(success_msg2,success_msg2rect)
            elif state =="3":
               screen.blit(success_msg3,success_msg3rect)
            elif state =="error":
               screen.blit(unsuccess_msg,unsuccess_msgrect)

        screen.blit(characters_1,characters_1rect)
        screen.blit(characters_2,characters_2rect)
        screen.blit(characters_3,characters_3rect)
        screen.blit(waiting_msg2,waiting_msg2rect)
        pg.display.flip()

pg.init()

#Initialize game state manager and set state = TitleScreen
game_state_manager = GameStateManager()
game_state_manager.change_state(GameState.CHARACTERSELECT)

#Setup display
screenWidth = 1280
screenHeight = 720
screen = pg.display.set_mode((screenWidth, screenHeight))
pg.display.set_caption("FoodGame")

#Define Colours:
black = (0, 0, 0)
white = (255, 255, 255)
light_grey = (200, 200, 200)
blue = (0, 0, 255)
green = (0, 255, 0)
red = (255, 0, 0)

#Set Fonts
font1 = pg.font.Font(r"fonts\retro.ttf", 20)

#Setup clock
clock = pg.time.Clock()

#Load Media
titleLogo = pg.image.load(r"img\title.png").convert_alpha()

def main():
    game_state_manager.run_state()

main()


# -*- coding: utf-8 -*-
"""
Created on Mon Aug  6 13:18:04 2018

@author: Jack
"""
from keras.models import Sequential
from keras.layers import Dense
import numpy as np
import sklearn.preprocessing
from sklearn.decomposition import PCA
import pandas as pd
from matplotlib import pyplot as plt

df = pd.read_csv('data.csv')

#deleting unneeded rows
del df["Unnamed: 32"]
del df["id"]
df["diagnosis"].replace("M",1,inplace=True)
df["diagnosis"].replace("B",0,inplace=True)
df["Diagnosis"] = df["diagnosis"]
del df["diagnosis"]

#separating data into training, dev, and test sets
training_df = df.values[0:500]
dev_df = df.values[500:535]
test_df = df.values[535:]

train_x, train_y, test_x, test_y, dev_x, dev_y = [], [], [], [], [], []

#inserting data into training, dev, and test sets
for row in training_df:
    row = row.tolist()
    train_x.append(row[0:29])
    train_y.append(int(row[30]))

for row in dev_df:
    row = row.tolist()
    dev_x.append(row[0:29])
    dev_y.append(int(row[30]))

for row in test_df:
    row = row.tolist()
    test_x.append(row[0:29])
    test_y.append(int(row[30]))

#normalizing data
train_x, train_y = sklearn.preprocessing.normalize(np.array(train_x)), np.array(train_y)
dev_x, dev_y = sklearn.preprocessing.normalize(np.array(dev_x)), np.array(dev_y)
test_x, test_y = sklearn.preprocessing.normalize(np.array(test_x)), np.array(test_y)

#creating the model structure
model = Sequential()
model.add(Dense(units=64, activation='relu', input_dim=29))
model.add(Dense(units=48, activation='relu'))
model.add(Dense(units=32, activation='relu'))
model.add(Dense(units=16, activation='relu'))
model.add(Dense(units=1, activation='sigmoid'))
model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

#training the model
model.fit(train_x, train_y, epochs=5, batch_size=1, shuffle=True)
print("\n")

#using model to predict dev set
score = model.evaluate(dev_x, dev_y)
print("----Dev Set----\nLoss: " + str(score[0]) + "\nAccuracy: " + str(round(score[1]*100, 3))+"%\n")

#using model to predict test set
score = model.evaluate(test_x, test_y)
print("----Test Set----\nLoss: " + str(score[0]) + "\nAccuracy: " + str(round(score[1]*100, 3))+"%")

#separating data labels for graphing
malignant = sklearn.preprocessing.normalize(df[df["Diagnosis"]==1].values)
benign = sklearn.preprocessing.normalize(df[df["Diagnosis"]==0].values)

#using PCA to reduce dimensionality of the data to 2 features for graphing purposes
pca = PCA(n_components=2)
malignant = pca.fit_transform(malignant)
benign = pca.fit_transform(benign)

#using pyplot to graph data
for t in range(2):
    if t == 0:
        plt.scatter([pair[0] for pair in benign], [pair[1] for pair in benign], color='r', s=10, label="Benign")
    else:
        plt.scatter([pair[0] for pair in malignant], [pair[1] for pair in malignant], color='g', s=10, label="Malignant")
plt.legend()


import pygame
pygame.init()
import colorama
colorama.init()
import sys
import os
import abc
import random
import time
import math
import threading
import ast
from itertools import cycle
from pathlib import Path
import matplotlib.pyplot as plt

class bcolors:
	RED = '\033[31m'
	GREEN = '\033[32m'
	YELLOW = '\033[33m'
	BLUE = '\033[34m'
	MAGENTA = '\033[35m'
	MAGENTA = '\033[35m'
	BRIGHT_BLACK = '\033[90m'
	NORMAL = '\033[0m'

class Person(abc.ABC):

	people = [] # type: List[Person]
	actual_people = {} # type: Dict[Person, List[Person]]
	radius = 10
	speed = 5
	screen = None
	score_matrix = [[0, 3], [-1, 2]]

	#colors
	c_red = (179, 27, 0)
	c_green = (0, 179, 18)
	c_black = (0, 0, 0)
	c_pink = (227, 0, 227)
	c_blue = (0, 181, 217)
	c_brown = (176, 123, 0)
	# change when adding new person

	def __init__(self, pos, dir) -> None:
		self.pos = pos
		self.dir = dir
		self.collide = False
		self.last_collided = None
		Person.people.append(self)

	def draw(self, color) -> None:
		pygame.draw.circle(Person.screen, color, (self.pos[0], self.pos[1]), Person.radius)

	def new_dir(self) -> None:
		# only able to go in 3 ways to make it more realistic
		new_dir = random.randrange(0, 3)
		# right turn
		if new_dir == 0:
			self.dir[0], self.dir[1] = -self.dir[1], self.dir[0]
		# left turn
		elif new_dir == 1:
			self.dir[0], self.dir[1] = self.dir[1], -self.dir[0]
		# else go forward the same way -> no change
		del new_dir

	def move(self) -> None:
		self.out_of_map()
		self.pos[0] += self.dir[0] * Person.speed
		self.pos[1] += self.dir[1] * Person.speed

	def out_of_map(self) -> None:
		x, y = Person.screen.get_size()
		# left
		if self.pos[0] + self.dir[0] * Person.speed + Person.radius > x:
			self.dir[0], self.dir[1] = -self.dir[0], -self.dir[1]
		# right
		elif self.pos[0] + self.dir[0] * Person.speed - Person.radius < 0:
			self.dir[0], self.dir[1] = -self.dir[0], -self.dir[1]
		# top
		if self.pos[1] + self.dir[1] * Person.speed + Person.radius > y:
			self.dir[0], self.dir[1] = -self.dir[0], -self.dir[1]
		# bottom
		elif self.pos[1] + self.dir[1] * Person.speed - Person.radius < 0:
			self.dir[0], self.dir[1] = -self.dir[0], -self.dir[1]

		del x, y

	def move_in_one(self) -> None:
		if not self.collide:
			self.new_dir()
			self.move()
			self.draw(self.__class__.color)
			t1 = threading.Thread(target=self.collision, args=[3])
			t1.start()
		else:
			self.draw(self.__class__.color)

	def collision(self, num: int) -> None:
		for x in Person.people:
			if x != self and self.last_collided != x and not x.collide:
				if math.sqrt((self.pos[0] - x.pos[0]) ** 2 + (self.pos[1] - x.pos[1]) ** 2) < Person.radius * 2:
					self.last_collided = x
					self.collide = True
					x.last_collided = self
					x.collide = True
					self.check_points(x, 10)
					x.check_points(self, 10)

					time.sleep(num)
					self.collide = False
					x.collide = False
					self.dir[0], self.dir[1] = -self.dir[0], -self.dir[1]
					x.dir[0], x.dir[1] = -x.dir[0], -x.dir[1]

	@abc.abstractmethod
	def check_points(self, x, num):
		"""implement in child"""

	@staticmethod
	def check_evolution(time_v: int) -> None:
		time.sleep(time_v)
		while len(Person.people) > 0:
			num = round(len(Person.people)/10)
			best_num = sorted(Person.people, key=lambda x: x.points, reverse=True)[:num]
			worst_num = sorted(Person.people, key=lambda x: x.points, reverse=False)[:num]

			for x in best_num:
				x.__class__([random.randrange(50,450), random.randrange(50,450)])
			for x in worst_num:
				Person.people.remove(x)
				x.__class__.people.remove(x)

			# get data for chart
			Person.get_actual_people()

			for x in Person.people:
				x.points = 0

			Black.points = 0
			Pink.points = 0
			Blue.points = 0
			Brown.points = 0
			Green.points = 0
			# change when adding new person
			time.sleep(time_v)

	@staticmethod
	def show_chart(dic) -> None:
		fig = plt.figure()
		x = range(0, len(next(iter(dic.values()))) * 30, 30)

		temp_list = []
		for key, value in dic.items():
			temp_list.append(key.__name__.lower())
		colors = cycle(temp_list)

		for key, value in dic.items():
			plt.scatter(x, value, color=next(colors))
		plt.show()
		del colors, fig, x, temp_list

	@staticmethod
	def write_stats(dic, path: str) -> None:
		with open(path, 'r') as f:
			lines = f.readlines()
		with open(path, 'a+') as f:
			if len(lines) != 0:
				last_line = lines[-1]
				for key, value in dic.items():
					f.write(f"{key.__name__}\t{value}\n")
				f.write(f"{int(last_line) + 1}\n")
			else:
				f.write(f"1\n")
				for key, value in dic.items():
					f.write(f"{key.__name__}\t{value}\n")
				f.write(f"2\n")

	@staticmethod
	def fill_actual_people() -> None:
		Person.actual_people = {}
		for person in Person.people:
			if person.__class__.__name__ not in Person.actual_people:
				Person.actual_people[person.__class__] = []

	@staticmethod
	def get_actual_people() -> None:
		for a_class in Person.actual_people:
			Person.actual_people[a_class].append(len(a_class.people))

	@staticmethod
	def in_map(pos) -> None:
		x, y = Person.screen.get_size()
		if pos[0] + Person.radius < x and pos[0] - Person.radius > 0 and pos[1] + Person.radius < y and pos[1] - Person.radius > 0:
			return True
		return False

	@staticmethod
	def del_people() -> None:
		Person.people = []
		Black.people = []
		Pink.people = []
		Blue.people = []
		Brown.people = []
		Green.people = []
		# change when adding new person

class Black(Person):

	people = []
	points = 0
	color = Person.c_black

	def __init__(self, pos = [10, 10], dir = [0, 1], points = 0) -> None:
		super(Black, self).__init__(list(pos), dir)
		self.points = points
		Black.people.append(self)

	def __str__(self) -> str:
		return f"Black; {self.points}p"

	def __repr__(self) -> str:
		return f"Black; {self.points}p"

	def check_points(self, x: Person, num: int) -> None:
		if x.__class__.__name__ == "Black":
			self.points += Person.score_matrix[0][0] * num
			Black.points += Person.score_matrix[0][0] * num
		elif x.__class__.__name__ == "Pink":
			self.points += Person.score_matrix[0][1] * num
			Black.points += Person.score_matrix[0][1] * num
		elif x.__class__.__name__ == "Blue":
			self.points += Person.score_matrix[0][1] + Person.score_matrix[0][0] * (num - 1)
			Black.points += Person.score_matrix[0][1] + Person.score_matrix[0][0] * (num - 1)
		elif x.__class__.__name__ == "Brown":
			self.points += Person.score_matrix[0][0] * num
			Black.points += Person.score_matrix[0][0] * num
		elif x.__class__.__name__ == "Green":
			self.points += Person.score_matrix[0][0] * num
			Black.points += Person.score_matrix[0][0] * num

class Pink(Person):

	people = []
	points = 0
	color = Person.c_pink

	def __init__(self, pos = [10, 10], dir = [0, 1], points = 0) -> None:
		super(Pink, self).__init__(list(pos), dir)
		self.points = points
		Pink.people.append(self)

	def __str__(self) -> str:
		return f"Pink; {self.points}p"

	def __repr__(self) -> str:
		return f"Pink; {self.points}p"

	def check_points(self, x: Person, num: int) -> None:
		if x.__class__.__name__ == "Black":
			self.points += Person.score_matrix[1][0] * num
			Pink.points += Person.score_matrix[1][0] * num
		elif x.__class__.__name__ == "Pink":
			self.points += Person.score_matrix[1][1] * num
			Pink.points += Person.score_matrix[1][1] * num
		elif x.__class__.__name__ == "Blue":
			self.points += Person.score_matrix[1][1] * num
			Pink.points += Person.score_matrix[1][1] * num
		elif x.__class__.__name__ == "Brown":
			self.points += Person.score_matrix[1][0] * num
			Pink.points += Person.score_matrix[1][0] * num
		elif x.__class__.__name__ == "Green":
			self.points += Person.score_matrix[1][0] + Person.score_matrix[1][1] * num
			Pink.points += Person.score_matrix[1][0] + Person.score_matrix[1][1] * num

class Blue(Person):

	people = []
	points = 0
	color = Person.c_blue

	def __init__(self, pos = [10, 10], dir = [0, 1], points = 0) -> None:
		super(Blue, self).__init__(list(pos), dir)
		self.points = points
		Blue.people.append(self)

	def __str__(self) -> str:
		return f"Blue; {self.points}p"

	def __repr__(self) -> str:
		return f"Blue; {self.points}p"

	def check_points(self, x: Person, num: int) -> None:
		if x.__class__.__name__ == "Black":
			self.points += Person.score_matrix[1][0] + Person.score_matrix[0][0] * (num - 1)
			Blue.points += Person.score_matrix[1][0] + Person.score_matrix[0][0] * (num - 1)
		elif x.__class__.__name__ == "Pink":
			self.points += Person.score_matrix[1][1] * num
			Blue.points += Person.score_matrix[1][1] * num
		elif x.__class__.__name__ == "Blue":
			self.points += Person.score_matrix[1][1] * num
			Blue.points += Person.score_matrix[1][1] * num
		elif x.__class__.__name__ == "Brown":
			self.points += Person.score_matrix[1][0] + Person.score_matrix[0][0] * (num - 1)
			Blue.points += Person.score_matrix[1][0] + Person.score_matrix[0][0] * (num - 1)
		elif x.__class__.__name__ == "Green":
			self.points += Person.score_matrix[1][0] * math.ceil(num / 2) + Person.score_matrix[0][1] * int(num / 2)
			Blue.points += Person.score_matrix[1][0] * math.ceil(num / 2) + Person.score_matrix[0][1] * int(num / 2)

class Brown(Person):

	people = []
	points = 0
	color = Person.c_brown

	def __init__(self, pos = [10, 10], dir = [0, 1], points = 0) -> None:
		super(Brown, self).__init__(list(pos), dir)
		self.points = points
		Brown.people.append(self)

	def __str__(self) -> str:
		return f"Brown; {self.points}p"

	def __repr__(self) -> str:
		return f"Brown; {self.points}p"

	def check_points(self, x: Person, num: int) -> None:
		if x.__class__.__name__ == "Black":
			self.points += Person.score_matrix[0][0] * num
			Brown.points += Person.score_matrix[0][0] * num
		elif x.__class__.__name__ == "Pink":
			self.points += Person.score_matrix[0][1] * num
			Brown.points += Person.score_matrix[0][1] * num
		elif x.__class__.__name__ == "Blue":
			self.points += Person.score_matrix[0][1] + Person.score_matrix[0][0] * (num - 1)
			Brown.points += Person.score_matrix[0][1] + Person.score_matrix[0][0] * (num - 1)
		elif x.__class__.__name__ == "Brown":
			self.points += Person.score_matrix[1][1] * num
			Brown.points += Person.score_matrix[1][1] * num
		elif x.__class__.__name__ == "Green":
			self.points += Person.score_matrix[0][0] * num
			Brown.points += Person.score_matrix[0][0] * num

class Green(Person):

	people = []
	points = 0
	color = Person.c_green

	def __init__(self, pos = [10, 10], dir = [0, 1], points = 0) -> None:
		super(Green, self).__init__(list(pos), dir)
		self.points = points
		Green.people.append(self)

	def __str__(self) -> str:
		return f"Green; {self.points}p"

	def __repr__(self) -> str:
		return f"Green; {self.points}p"

	def check_points(self, x: Person, num: int) -> None:
		if x.__class__.__name__ == "Black":
			self.points += Person.score_matrix[0][0] * num
			Green.points += Person.score_matrix[0][0] * num
		elif x.__class__.__name__ == "Pink":
			self.points += Person.score_matrix[0][1] + Person.score_matrix[1][1] * (num - 1)
			Green.points += Person.score_matrix[0][1] + Person.score_matrix[1][1] * (num - 1)
		elif x.__class__.__name__ == "Blue":
			self.points += Person.score_matrix[0][1] * math.ceil(num / 2) + Person.score_matrix[1][0] * int(num / 2)
			Green.points += Person.score_matrix[0][1] * math.ceil(num / 2) + Person.score_matrix[1][0] * int(num / 2)
		elif x.__class__.__name__ == "Brown":
			self.points += Person.score_matrix[0][0] * num
			Green.points += Person.score_matrix[0][0] * num
		elif x.__class__.__name__ == "Green":
			self.points += Person.score_matrix[0][0] * num
			Green.points += Person.score_matrix[0][0] * num

def represent_int(s):
	try:
		int(s)
		return True
	except ValueError:
		return False

if __name__ == "__main__":
	# console
	console = True
	while console:
		print()
		msg = input(f"What do you want to do? (you can use help to see all commands): ").strip().lower()
		print()

		if msg == "help" or msg == "h":
			print(f"help(h) - Show all commands.")
			print(f"exit(e) - Exit from the program.")
			print(f"show(s) - Show the outcomes. Read from a file.")
			print(f"description(d) - Show a detailed description of the game.")
			print(f"basic(b) - Start Evolution of Trust and place some people.")
			print(f"test(t) - Simulate some examples with random number of people.")
			print(f"find(f) - Find a starting position for a color to win.")
			print(f"guess(g) - Make a starting position and let the AI guess the outcome.")
		elif msg == "description" or msg == "d":
			print(f"Evolution of Trust interactive game.\nThere are 5 different personalities:\n{bcolors.BRIGHT_BLACK}Black{bcolors.NORMAL} who always cheats.\n{bcolors.MAGENTA}Pink{bcolors.NORMAL} who always cooperates.\n{bcolors.BLUE}Blue{bcolors.NORMAL} who first cooperates then plays the as the his opponent played the last round.\n{bcolors.YELLOW}Brown{bcolors.NORMAL} who only cooperates with other browns.\n{bcolors.GREEN}Green{bcolors.NORMAL} who is similar to blue but cheats the first time.\nThere are 4 different functions:\nShow where you can see the result of past simulations on graphs.\nBasic where you can place the people any way you want and start the simulation.\nTest where you can run tests and save them to a file for reading later.\nFind where you can read a start from a file where a specific person won.")
			print(f"Have fun!")
		elif msg == "exit" or msg == "e":
			print(f"Exiting from program")
			pygame.quit()
			sys.exit()
		elif msg == "show" or msg == "s":
			path = input(f"Give the file path to show (Base is 'stats.txt'): ")
			file = Path(path)
			if path.strip().lower() == "base":
				file = Path("stats.txt")
			if file.is_file():
				with open(file, 'r') as f:
					lines = f.readlines()
					fig = plt.figure()
					last_line = lines[-1]

					count = int(lines[0]) + 1
					del lines[0]
					dic = {}
					for line in lines:
						if represent_int(line) and int(line) == count:
							x = range(0, len(next(iter(dic.values()))) * 30, 30)

							temp_list = []
							for key, value in dic.items():
								temp_list.append(key.lower())
							colors = cycle(temp_list)

							size = math.sqrt(int(last_line) - 1)
							if size - int(size) < 0.5:
								ax = fig.add_subplot(math.ceil(size), int(size), count - 1)
							else:
								ax = fig.add_subplot(math.ceil(size), math.ceil(size), count - 1)

							for key, value in dic.items():
								plt.scatter(x, value, color=next(colors))

							# reset
							dic = {}
							count += 1
						else:
							(key, val) = line.split('\t')
							dic[key] = ast.literal_eval(val)
					plt.show()
			elif file.is_dir():
				print(f"Path is a directory, not a file.")
			elif not file.exists():
				print(f"Path doesn't exist.")
			else:
				print(f"Unknow error.")
		elif msg == "basic" or msg == "b":
			path = input(f"Do you want to save to file (Base is 'stats.txt'): ")

			# prepare
			pygame.display.init()
			screen = pygame.display.set_mode((500,500), pygame.RESIZABLE)
			pygame.display.set_caption("Evolution of Trust Simulation (basic)")
			pygame.font.init()
			font = pygame.font.SysFont("Times New Roman", 18)
			Person.screen = screen

			actual_person = None
			prepare = True
			while prepare:
				for event in pygame.event.get():
					if event.type == pygame.QUIT:
						prepare = False
					if event.type == pygame.KEYDOWN:
						if event.key == pygame.K_a:
							actual_person = Black
						if event.key == pygame.K_s:
							actual_person = Pink
						if event.key == pygame.K_d:
							actual_person = Blue
						if event.key == pygame.K_f:
							actual_person = Brown
						if event.key == pygame.K_g:
							actual_person = Green
						# change when adding new person
						if event.key == pygame.K_c:
							Person.del_people()
						if event.key == pygame.K_r:
							prepare = False
					if event.type == pygame.MOUSEBUTTONUP and actual_person != None:
						pos = list(pygame.mouse.get_pos())
						if event.button == 1:
							actual_person(pos)
						elif event.button == 3:
							for x in range(10):
								temp_pos = list(pos)
								temp_pos[0] += random.randint(-96, 96)
								temp_pos[1] += random.randint(-54, 54)
								# try till get a position inside screen
								while not Person.in_map(temp_pos):
									temp_pos = list(pos)
									temp_pos[0] += random.randint(-96, 96)
									temp_pos[1] += random.randint(-54, 54)

								actual_person(temp_pos)
								del temp_pos
					if event.type == pygame.VIDEORESIZE:
						scr_size = event.size
						screen = pygame.display.set_mode(scr_size, pygame.RESIZABLE)
						del scr_size

				if not prepare:
					break

				screen.fill((255,255,255))
				text_surface = font.render(f"Press 'A-G' for person", False, Person.c_black)
				screen.blit(text_surface, (5, 0))
				text_surface = font.render(f"Left click to place person", False, Person.c_black)
				screen.blit(text_surface, (5, 20))
				text_surface = font.render(f"Right click to place 10 person", False, Person.c_black)
				screen.blit(text_surface, (5, 40))
				# display selected person count
				if actual_person != None:
					text_surface = font.render(f"{actual_person.__name__}: {len(actual_person.people)}", False, Person.c_black)
					screen.blit(text_surface, (5, 70))
				else:
					text_surface = font.render(f"No person selected", False, Person.c_black)
					screen.blit(text_surface, (5, 70))
				# change when adding new person

				for person in Person.people:
					person.draw(person.color)

				pygame.display.flip()

			del prepare

			if len(Person.people) == 0:
				print(f"No people present. Can't start simulation.")
				pygame.display.quit()

			# simulation
			if len(Person.people) > 0:
				t1 = threading.Thread(target=Person.people[0].check_evolution, args=[5])
				t1.daemon = True
				t1.start()
				Person.fill_actual_people()
				Person.get_actual_people()

				running = True
				while running:
					for event in pygame.event.get():
						if event.type == pygame.QUIT:
							running = False

					# points
					screen.fill((255,255,255))
					text_surface = font.render(f"{Black.points} points for 'Black'", False, Person.c_black)
					screen.blit(text_surface, (5, 0))
					text_surface = font.render(f"{Pink.points} points for 'Pink'", False, Person.c_black)
					screen.blit(text_surface, (5, 20))
					text_surface = font.render(f"{Blue.points} points for 'Blue'", False, Person.c_black)
					screen.blit(text_surface, (5, 40))
					text_surface = font.render(f"{Brown.points} points for 'Brown'", False, Person.c_black)
					screen.blit(text_surface, (5, 60))
					text_surface = font.render(f"{Green.points} points for 'Green'", False, Person.c_black)
					screen.blit(text_surface, (5, 80))
					# counts
					w, h = screen.get_size()
					text_surface = font.render(f"{len(Black.people)} 'Black' person", False, Person.c_black)
					screen.blit(text_surface, (w - text_surface.get_rect().width, 0))
					text_surface = font.render(f"{len(Pink.people)} 'Pink' person", False, Person.c_black)
					screen.blit(text_surface, (w - text_surface.get_rect().width, 20))
					text_surface = font.render(f"{len(Blue.people)} 'Blue' person", False, Person.c_black)
					screen.blit(text_surface, (w - text_surface.get_rect().width, 40))
					text_surface = font.render(f"{len(Brown.people)} 'Brown' person", False, Person.c_black)
					screen.blit(text_surface, (w - text_surface.get_rect().width, 60))
					text_surface = font.render(f"{len(Green.people)} 'Green' person", False, Person.c_black)
					screen.blit(text_surface, (w - text_surface.get_rect().width, 80))
					# change when adding new person

					for person in Person.people:
						person.move_in_one()

					pygame.display.flip()

				del running
				pygame.display.quit()
				Person.del_people()
				Person.show_chart(Person.actual_people)
				t1.join()
				file = Path(path)
				if path.strip().lower() == "no":
					pass
				elif path.strip().lower() == "yes" or path.strip().lower() == "base":
					file = Path(f"{os.getcwd()}/stats.txt")
					Person.write_stats(Person.actual_people, file)
					print(f"Saved to stats.txt")
				elif file.is_file():
					print(f"Saved to {file}")
					Person.write_stats(Person.actual_people, file)
				elif file.is_dir():
					print(f"Path is directory, not file.")
				elif not file.exists():
					print(f"File doesn't exist.")
				else:
					print(f"Unknow error.")
		elif msg == "test" or msg == "t":
			path = input(f"Do you want to save to file? (if yes give path. Base is 'stats.txt'): ")
			count = input(f"How many simulations do you want to run? ")
			grouped = input(f"Do you want to spawn people in groups of 10? ")
			exclude = input(f"Do you want to exclude brown? ")

			# init
			pygame.display.init()
			screen = pygame.display.set_mode((1920,1020), pygame.RESIZABLE)
			pygame.display.set_caption("Evolution of Trust Simulation (test)")
			pygame.font.init()
			font = pygame.font.SysFont('Times New Roman', 18)
			Person.screen = screen

			for _ in range(int(count)):
				# prepare
				w, h = screen.get_size()
				if exclude.strip().lower() == "yes":
					for person in Person.__subclasses__():
						if person.__name__ != "Brown":
							if grouped.strip().lower() == "yes":
								for _ in range(random.randrange(10)):
									pos = [random.randrange(50, w - 50), random.randrange(50, h - 50)]
									for x in range(10):
										temp_pos = list(pos)
										temp_pos[0] += random.randint(-96, 96)
										temp_pos[1] += random.randint(-54, 54)
										# try till get a position inside screen
										while not Person.in_map(temp_pos):
											temp_pos = list(pos)
											temp_pos[0] += random.randint(-96, 96)
											temp_pos[1] += random.randint(-54, 54)

										person(temp_pos)
										del temp_pos
							else:
								for _ in range(random.randrange(100)):
									person([random.randrange(50, w - 50), random.randrange(50, h - 50)])
				else:
					for person in Person.__subclasses__():
						if grouped.strip().lower() == "yes":
							for _ in range(random.randrange(10)):
								pos = [random.randrange(50, w - 50), random.randrange(50, h - 50)]
								for x in range(10):
									temp_pos = list(pos)
									temp_pos[0] += random.randint(-96, 96)
									temp_pos[1] += random.randint(-54, 54)
									# try till get a position inside screen
									while not Person.in_map(temp_pos):
										temp_pos = list(pos)
										temp_pos[0] += random.randint(-96, 96)
										temp_pos[1] += random.randint(-54, 54)

									person(temp_pos)
									del temp_pos
						else:
							for _ in range(random.randrange(100)):
								person([random.randrange(50, w - 50), random.randrange(50, h - 50)])

				# simulation
				t1 = threading.Thread(target=Person.people[0].check_evolution, args=[5])
				t1.daemon = True
				t1.start()
				Person.fill_actual_people()
				Person.get_actual_people()

				running = True
				while running:
					if len(Person.people) == len(Black.people) or len(Person.people) == len(Pink.people) or len(Person.people) == len(Blue.people) or len(Person.people) == len(Brown.people) or len(Person.people) == len(Green.people) or len(next(iter(Person.actual_people.values()))) >= 50:
						running = False

					for event in pygame.event.get():
						if event.type == pygame.QUIT:
							running = False

					if not running:
						break

					# counts
					screen.fill((255,255,255))
					text_surface = font.render(f"{len(Black.people)} 'Black' person", False, Person.c_black)
					screen.blit(text_surface, (5, 0))
					text_surface = font.render(f"{len(Pink.people)} 'Pink' person", False, Person.c_black)
					screen.blit(text_surface, (5, 20))
					text_surface = font.render(f"{len(Blue.people)} 'Blue' person", False, Person.c_black)
					screen.blit(text_surface, (5, 40))
					text_surface = font.render(f"{len(Brown.people)} 'Brown' person", False, Person.c_black)
					screen.blit(text_surface, (5, 60))
					text_surface = font.render(f"{len(Green.people)} 'Green' person", False, Person.c_black)
					screen.blit(text_surface, (5, 80))
					# change when adding new person

					for person in Person.people:
						person.move_in_one()

					pygame.display.flip()

				del running
				Person.del_people()
				t1.join()
				file = Path(path)
				if path.strip().lower() == "no":
					pass
				elif path.strip().lower() == "yes" or path.strip().lower() == "base":
					file = Path(f"{os.getcwd()}/stats.txt")
					Person.write_stats(Person.actual_people, file)
					print(f"Saved to stats.txt")
				elif file.is_file():
					print(f"Saved to {path}")
					Person.write_stats(Person.actual_people, path)
					print("saved to file")
				elif file.is_dir():
					print(f"Path is directory, not file.")
				elif not file.exists():
					print(f"File doesn't exist.")
				else:
					print(f"Unknow error.")

			pygame.display.quit()
		elif msg == "find" or msg == "f":
			path = input(f"Give the file path to search in. (Base is 'stats.txt'): ")
			winner = input(f"Which person do you want to win? (Give color): ")
			file = Path(path)
			if path.strip().lower() == "base":
				file = Path("stats.txt")
			if file.is_file():
				with open(file, 'r') as f:
					lines = f.readlines()
					del lines[0]
					dic = {}
					for line in lines:
						if represent_int(line):
							if max(dic, key=lambda x: dic[x][-1]).lower() == winner.strip().lower():
								# init
								pygame.display.init()
								screen = pygame.display.set_mode((1920,1020), pygame.RESIZABLE)
								pygame.display.set_caption("Evolution of Trust Simulation (find)")
								pygame.font.init()
								font = pygame.font.SysFont('Times New Roman', 18)
								Person.screen = screen

								for key, val in dic.items():
									w, h = screen.get_size()
									if val[0] % 10 == 0:
										for _ in range(int(val[0] / 10)):
											pos = [random.randrange(50, w - 50), random.randrange(50, h - 50)]
											for x in range(10):
												temp_pos = list(pos)
												temp_pos[0] += random.randint(-96, 96)
												temp_pos[1] += random.randint(-54, 54)
												# try till get a position inside screen
												while not Person.in_map(temp_pos):
													temp_pos = list(pos)
													temp_pos[0] += random.randint(-96, 96)
													temp_pos[1] += random.randint(-54, 54)

												eval(key)(temp_pos)
												del temp_pos
									else:
										for _ in val[0]:
											eval(key)([random.randrange(50, w - 50), random.randrange(50, h - 50)])

								# simulation
								t1 = threading.Thread(target=Person.people[0].check_evolution, args=[5])
								t1.daemon = True
								t1.start()
								Person.fill_actual_people()
								Person.get_actual_people()

								running = True
								while running:
									if len(Person.people) == len(Black.people) or len(Person.people) == len(Pink.people) or len(Person.people) == len(Blue.people) or len(Person.people) == len(Brown.people) or len(Person.people) == len(Green.people) or len(next(iter(Person.actual_people.values()))) >= 50:
										running = False

									for event in pygame.event.get():
										if event.type == pygame.QUIT:
											running = False

									if not running:
										break

									# counts
									screen.fill((255,255,255))
									text_surface = font.render(f"{len(Black.people)} 'Black' person", False, Person.c_black)
									screen.blit(text_surface, (5, 0))
									text_surface = font.render(f"{len(Pink.people)} 'Pink' person", False, Person.c_black)
									screen.blit(text_surface, (5, 20))
									text_surface = font.render(f"{len(Blue.people)} 'Blue' person", False, Person.c_black)
									screen.blit(text_surface, (5, 40))
									text_surface = font.render(f"{len(Brown.people)} 'Brown' person", False, Person.c_black)
									screen.blit(text_surface, (5, 60))
									text_surface = font.render(f"{len(Green.people)} 'Green' person", False, Person.c_black)
									screen.blit(text_surface, (5, 80))
									# change when adding new person

									for person in Person.people:
										person.move_in_one()

									pygame.display.flip()

								del running
								Person.del_people()
								t1.join()
								pygame.display.quit()
								break
							dic = {}
						else:
							(key, val) = line.split('\t')
							dic[key] = ast.literal_eval(val)
					plt.show()
			elif file.is_dir():
				print(f"Path is a directory, not a file.")
			elif not file.exists():
				print(f"Path doesn't exist.")
			else:
				print(f"Unknow error.")
		else:
			print(f"Command not recognised.\n")


import requests

# Get data from API. More info: https://gorest.co.in/
response = requests.get('https://gorest.co.in/public/v1/users')
# Get JSON from response
json_response = response.json()
# This JSON has two parts 'meta' and 'data'. Take just the data portion
json_data = json_response.get('data')
# Create a dictionary
gender_count = {'male': 0, 'female': 0}
# Go through the data, each user object is a JSON
for user in json_data:
    gender = user.get('gender')
    if gender == 'male':
        gender_count['male'] = gender_count['male'] + 1
    if gender == 'female':
        gender_count['female'] = gender_count['female'] + 1
# Final data
print(gender_count)


import csv
from matplotlib import pyplot as plt
import matplotlib
import random

class ResultReader():
    def __init__(self):

        with open('Results.csv') as csvfile:
            readCSV = csv.reader(csvfile, delimiter=',')
            rows_list = []

            count = 0
            for row in readCSV:
                for index, item in enumerate(row):
                    if count < 1:
                        rows_list.append([item, []])
                    else:
                        rows_list[index][1].append(row[index])
                #print(count)
                count += 1
            print("Rows list: ", rows_list)

            self.dates= []
            self.example_prices_all = []
            self.output_dict = {}
            for index, item in enumerate(rows_list):
                if index > 1:
                    example_prices = []
                    for i in rows_list[index][1]:
                        if len(i) > 2:
                            string = i[1:-1]
                            num = int(string)
                        else: num = 0
                        example_prices.append(num)
                    # print(example_prices)
                    self.example_prices_all.append([rows_list[index][0],example_prices])
                    self.dates.append(rows_list[index][0])

            print("Actual Dates", self.dates)

            example_dates = []
            for i in rows_list[0][1]:
                if i[4] == '/':
                    string = i[2:4]
                elif i[6] == '/':
                    #print("1st: ",i[2:6])
                    string = i[2:6]
                    #print("2nd: ",string)
                num = float(string)
                example_dates.append(num)
            print("Example Prices All: ", self.example_prices_all)
            print("Example Dates: ", example_dates)

            font = {'family': 'normal',
                    'weight': 'bold',
                    'size': 5}

            matplotlib.rc('font', **font)

            print("Dates: {}".format(example_dates))
            self.dates_dict = {}

            for index,item in enumerate(example_dates):
                self.dates_dict[index] = item
            print("Dates dictionary: {}".format(self.dates_dict))
            # self.plotting()
            self.output()

    def output(self):
        # Initialise the output
        for index, item in enumerate(self.example_prices_all):
            self.output_dict[index] = [[],[]]

        # Populate the output
        for index, item in enumerate(self.example_prices_all):
            # print("index: ", index)
            tempDates = []
            tempPrices = []
            # print(item[1])

            emptyflag = 1
            for ind, ite in enumerate(item[1]):
                if ite != 0:
                    tempDates.append(self.dates_dict[ind])
                    tempPrices.append(ite)
                    emptyflag = 0

            if emptyflag == 1:
                break
                # raise Exception("Sorry there is an empty to date to be removed: {}".format(self.dates_dict[index]))
            self.output_dict[index] = [tempDates, tempPrices]
        print("Output Dictionary", self.output_dict)
        return self.output_dict

    def plotting(self):
        for i in self.example_prices_all:
            tempDates = []
            tempPrices = []
            for ind, ite in enumerate(i[1]):
                if ite != 0:
                    tempDates.append(self.dates_dict[ind])
                    tempPrices.append(ite)

            plt.plot(tempDates, tempPrices, label = i[0])

        #     for x, y in zip(example_dates, i[1]):
        #         label = i[0]
        #
        #         plt.annotate(label,  # this is the text
        #                      (x, y),  # this is the point to label
        #                      textcoords="offset points",  # how to position the text
        #                      xytext=(random.randrange(0,20,10), 0),  # distance from text to points (x,y)
        #                      ha='center')  # horizontal alignment can be left, right or center
        #
        # plt.plot(example_dates, example_prices)
        # plt.legend()
        plt.show()

if __name__ == "__main__":
    Reader = ResultReader()
    Reader.plotting()
    output = Reader.output()


import numpy
import matplotlib.pyplot as my_plot
import matplotlib.tri as tri
import math

from fenics import *
from mshr import *

T = 1
steps = 50
dt = T / steps
filenames = []
R = 1
Error = 1E-16
domain = Circle(Point(0, 0), R)
mesh = generate_mesh(domain, 64)
V = FunctionSpace(mesh, 'P', 2)

bounds = MeshFunction("size_t", mesh, 1)

# du/dn|y>0 = g(x,y)
class boundary1(SubDomain):
    def inside(self, x, on_boundary):
        return on_boundary or (x[1] >= 0)

b1 = boundary1()
b1.mark(bounds, 0)

# u|(y<0) = h(x,y), on boundary and y<0
class boundary2(SubDomain):
    def inside(self, x, on_boundary):
        return on_boundary or (x[1] < 0)

b2 = boundary2()
b2.mark(bounds, 1)

alpha = 2
beta = 3
t = 0

#gamma = -1 #main formula
#h = Expression('0.1 * x[0] * cos(x[1])*t', degree = 2, t = t)
#f = Expression('(1 + t) * 0.1 * x[0] * cos(x[1])', degree = 2, t = t)
#g = Expression('-0.1 * x[0] * sin(x[1]) * x[1] * t / R - 0.1 * cos(x[1]) * x[0] * t / R', degree = 2, R = R, t = t)

#gamma = -1 #main formula
#h = Expression('0.5 * x[0] + 0.3 * x[1] + 0.7 * t',degree = 2, t = 0)
#f = Expression('0.7 + 0.5 * x[0] + 0.3 * x[1] + 0.7 * t', degree=2, t = t)
#g = Expression('0.5 * x[0]/R + 0.3 * x[1]/R', degree=2, R = R)

gamma = -10 #main formula
h = Expression('-10 * x[1] * x[0] * x[0] * t', degree = 2, t = t) # == h
f = Expression('-10 * x[1] * x[0] + 20', degree = 2, t = t)
g = Expression('-10 * x[0] * x[1] * x[0] * t / R - 10 * x[0] * x[0] * x[1] * t / R', degree = 2, R = R, t = t)

bc = DirichletBC(V, h, bounds, 1)
u_i = interpolate(h,V)

u = TrialFunction(V)
v = TestFunction(V)

a = gamma*dt * dot(grad(u),grad(v))*dx + u*v*dx
L = (u_i + dt*f)*v*dx + gamma * dt * g * v *ds(0, subdomain_data = bounds)

n = mesh.num_vertices()
d = mesh.geometry().dim()
mesh_coordinates = mesh.coordinates().reshape((n,d))
triangles = numpy.asarray([cell.entities(0) for cell in cells(mesh)])
triangulation = tri.Triangulation(mesh_coordinates[:,0],mesh_coordinates[:,1],triangles)

errL2 = []
errC = []
tt = []
u = Function(V)

for n in range(steps):

    t += dt
    tt.append(t)
    h.t = t

    solve(a==L, u, bc)

    u_e = interpolate(h,V)

    vertex_values_u_e = u_e.compute_vertex_values(mesh)
    vertex_values_u   = u.compute_vertex_values(mesh)

    error_L2 = errornorm(u_e, u, 'L2')
    error_C = numpy.max(numpy.abs(vertex_values_u - vertex_values_u_e))

    print('t = ', t, ', error_L2 = ', error_L2,'\n', '        error_C = ', error_C)
    errL2.append(error_L2)
    errC.append(error_C)

    my_plot.figure()
    zfaces = numpy.asarray([u(cell.midpoint()) for cell in cells(mesh)])
    my_plot.tripcolor(triangulation, facecolors=zfaces, edgecolors='k')
    #plt.clim(4.1,5.2)
    #plt.clim(-1.5, 1.5)
    my_plot.clim(-0.5, 0.5)
    my_plot.colorbar()
    my_plot.title(('Sol: t = '+"{:.1f}".format(t)+', error_L2 = '+"{:.5f}".format(error_L2)+', error_C = '+ "{:.5f}".format(error_C)))
    my_plot.savefig('heat3_s_'+"{:.1f}".format(t)+'.png')

    my_plot.figure()
    zfaces = numpy.asarray([u_e(cell.midpoint()) for cell in cells(mesh)])
    my_plot.tripcolor(triangulation, facecolors=zfaces, edgecolors='k')
    my_plot.title(('An: t = '+"{:.1f}".format(t)+', error_L2 = '+"{:.5f}".format(error_L2)+', error_C = '+ "{:.5f}".format(error_C)))
    #plt.clim(4.1,5.2)
    #plt.clim(-1.5, 1.5)
    my_plot.clim(-0.5, 0.5)
    my_plot.colorbar()
    my_plot.savefig('heat3_a_'+"{:.1f}".format(t)+'.png')
    u_i.assign(u)

my_plot.figure()
my_plot.title("Errors")
my_plot.plot(tt, errL2, 'r-', label= 'L2')
my_plot.plot(tt, errC, 'g-', label = 'C')
my_plot.legend()
my_plot.grid()
my_plot.savefig('errors.png')


import random
import redis

pool = redis.ConnectionPool(host='localhost', port=6379, db=2)
redis_cli = redis.Redis(connection_pool=pool)

pipe = redis_cli.pipeline()

def create_data():
    user_id = 100000
    while user_id:
        redis_cli.setbit('article1:today', user_id, random.choice([1, 1, 1, 0]))
        redis_cli.setbit('article2:today', user_id, random.choice([1, 1, 1, 0, 0]))
        redis_cli.setbit('article3:today', user_id, random.choice([1, 1, 1, 0, 0, 0, 0]))
        user_id = user_id - 1

def print_users_read_article():
    print('So luong nguoi dung da xem bai bao 1: ', redis_cli.bitcount('article1:today'))

def print_users_read_a_article():
    pipe.bitcount('article1:today')
    pipe.bitcount('article2:today')
    pipe.bitcount('article3:today')
    print('Tong so nguoi da xem moi bai bao la: ', pipe.execute())

def print_num_article_123user_read():
    pipe.getbit('article1:today', 123)
    pipe.getbit('article2:today', 123)
    pipe.getbit('article3:today', 123)
    print('So bai bao nguoi dung 123 da xem ngay hom nay: ', sum(pipe.execute()))

def print_user123_read_2_article():
    # pipe.setbit('user123', 123, 1)
    # pipe.bitop('AND', '123:sawboth', 'user123', 'article1:today', 'article3:today')
    pipe.bitop('AND', '123:sawboth', 'article1:today', 'article3:today')
    pipe.getbit('123:sawboth', 123)
    # pipe.delete('123:sawboth', 'user123')
    # print('Nguoi dung 123 da xem 2 bai bao ngay hom nay? ', bool(pipe.execute()[2]))
    print('Nguoi dung 123 da xem 2 bai bao ngay hom nay? ', bool(pipe.execute()[1]))

def print_users_read_atleast_one():
    pipe.bitop('OR', 'atleastonearticle', 'article1:today', 'article2:today', 'article3:today')
    pipe.bitcount('atleastonearticle')
    pipe.delete('atleastonearticle')
    print('So nguoi xem it nhat mot bai bao hom nay: ', pipe.execute()[1])

def print_recommendation():
    pipe.bitop('XOR', 'recommendother', 'article1:today', 'article2:today')
    pipe.bitop('AND', 'recommend:article1', 'recommendother', 'article2:today')
    pipe.bitop('AND', 'recommend:article2', 'recommendother', 'article1:today')
    pipe.bitcount('recommendother')
    pipe.bitcount('recommend:article1')
    pipe.bitcount('recommend:article2')
    pipe.delete('recommendother', 'recommend:article1', 'recommend:article2')
    result = pipe.execute()
    print('So nguoi chua doc ca 2 bai bao: ', result[3])
    print('So nguoi da doc bai 2, va se gioi thieu bai 1: ', result[4])
    print('So nguoi da doc bai 1, va se gioi thieu bai 2: ', result[5])

if __name__ == '__main__':
    # create_data()
    # print_users_read_article()
    # print_users_read_a_article()
    # print_num_article_123user_read()
    print_user123_read_2_article()
    # print_users_read_atleast_one()
    # print_recommendation()


import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np

def add_or_new(d, k, v):
    try:
        d[k] += v
    except KeyError:
        d[k] = v.copy()

def find_bin(val, ar):
    # Find the first bin which has left index geq the query.
    # The query belongs in the bin to the left of this one.
    # Assumes the bins are right-inclusive.
    try:
        return np.argmin(ar < val)
    except TypeError:
        return np.argmin([a == val for a in ar])
    raise NotImplementedError  # comparison between bins of objects that aren't exact is not supported

def only_finite(ar):
    return ar[np.isfinite(ar)]

def get_feat_vals(ebm_global, feat_id):
    good_vals = ebm_global.data(feat_id)["names"]
    return good_vals

def calc_density(
    use_density, feat_vals1, feat_vals2, feat_id1, feat_id2, X_train, laplace=0
):
    if use_density:
        density = np.zeros((len(feat_vals1), len(feat_vals2))) + laplace
        for x in X_train:
            idx1 = find_bin(x[feat_id1], feat_vals1)
            idx2 = find_bin(x[feat_id2], feat_vals2)
            density[idx1, idx2] += 1
        return density
    else:
        return None

def overlap(bounds1, bounds2):
    assert bounds1[0] < bounds1[1]
    assert bounds2[0] < bounds2[1]
    if bounds1[0] == bounds2[0] or bounds1[1] == bounds2[1]:
        return True
    if bounds1[0] > bounds2[0]:
        return bounds1[1] < bounds2[1]
    else:  # bounds1[0] < bounds2[0]
        return bounds2[1] < bounds1[1]

def merge_arrs(ar1_names, ar2_names, ar2_values):
    # Preserves the bins of ar1.
    ar_mapped = np.zeros((len(ar1_names) - 1))
    for i, val in enumerate(ar2_values):
        raw_left_boundary = ar2_names[i]
        try:
            raw_right_boundary = ar2_names[i + 1]
        except:
            raw_right_boundary = np.inf

        for j, left_boundary in enumerate(ar1_names):
            mapped_left_boundary = left_boundary
            try:
                mapped_right_boundary = ar1_names[j + 1]
            except:
                mapped_right_boundary = np.inf
            if raw_right_boundary < raw_left_boundary:
                temp = raw_right_boundary
                raw_right_boundary = raw_left_boundary
                raw_left_boundary = temp
            if overlap(
                (raw_left_boundary, raw_right_boundary),
                (mapped_left_boundary, mapped_right_boundary),
            ):
                ar_mapped[j] += val
                break
    return ar_mapped

def plot_interaction(
    val_names1,
    val_names2,
    before,
    after,
    dataset_name,
    feat_name1,
    feat_name2,
    model_name,
    move_name,
):
    # Plots an interaction effect before and after purification.
    # Set up figure and image grid
    fig = plt.figure(figsize=(9.75, 3))
    grid = ImageGrid(
        fig,
        111,  # as in plt.subplot(111)
        nrows_ncols=(1, 2),
        axes_pad=0.15,
        share_all=True,
        cbar_location="right",
        cbar_mode="single",
        cbar_size="7%",
        cbar_pad=0.15,
    )

    # Add data to image grid
    extent = (val_names2[0], val_names2[-1], val_names1[0], val_names1[-1])

    aspect = float(extent[3] - extent[2]) / float(extent[1] - extent[0])
    aspect = 1 / aspect

    im = grid[0].imshow(
        before, aspect=aspect, origin="lower", interpolation="none", extent=extent
    )
    im = grid[1].imshow(
        after, aspect=aspect, origin="lower", interpolation="none", extent=extent
    )

    # Colorbar
    ax = grid[-1]
    ax.cax.colorbar(im)
    ax.cax.toggle_label(True)

    grid[0].set_ylabel(feat_name1, fontsize=22)
    grid[0].set_xlabel(feat_name2, fontsize=22)
    grid[1].set_xlabel(feat_name2, fontsize=22)
    grid[0].tick_params(axis="both", which="major", labelsize=16)
    grid[0].tick_params(axis="both", which="minor", labelsize=12)
    grid[1].tick_params(axis="both", which="major", labelsize=16)
    grid[1].tick_params(axis="both", which="minor", labelsize=12)
    ax.cax.tick_params(axis="both", which="major", labelsize=16)
    ax.cax.tick_params(axis="both", which="minor", labelsize=12)

    plt.savefig(
        "figs/{}/interactions/{}_{}_{}".format(
            dataset_name, feat_name1, feat_name2, model_name, move_name
        )
    )


from django.core.management.base import BaseCommand
import csv
from Kick.models import Kickstarter_camp

class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('path', help='Path to CSV')

    def handle(self, *args, **kwargs):
        path = kwargs['path']
        with open(path, encoding="utf8") as csv_file:
            info = csv.reader(csv_file, delimiter=',')
            line = 0
            for row in info:
                if line != 0:
                    data = Kickstarter_camp.objects.create(
                        backers_count = int(row[0]),
                        blurb = row[1],
                        goal = row[11],
                        pledged = row[17])
                line += 1


# vim:set fileencoding=utf-8:
from django.db import models
from .. import settings

class RusManager(models.Manager):
    use_for_related_fields = True

    def get_queryset(self):
        return super(RusManager, self).get_queryset().select_related('profile', 'rusclass', 'initial_rusclass', 'profile__user')

class TutorProfileManager(models.Manager):
    use_for_related_fields = True

    def get_queryset(self):
        return super(TutorProfileManager, self).get_queryset()

class TutorManager(models.Manager):
    use_for_related_fields = True

    def get_queryset(self):
        return super(TutorManager, self).get_queryset().select_related('profile', 'profile__user')

class VisibleTutorGroups(models.Manager):
    def get_queryset(self):
        qs = super(VisibleTutorGroups, self).get_queryset()
        return qs.filter(visible=True, tutor__year__in=[settings.YEAR]).distinct()

class RusClassManager(models.Manager):
    def create_from_official(self, year, official_name):
        """Translate (2015, "MA1") into a fresh RusClass object."""
        official_study = official_name[:2]
        number = official_name[2:]
        handle, internal_name = next(
            (handle, internal)
            for official, handle, internal in settings.RUSCLASS_BASE
            if official == official_study
        )
        handle = '%s%s' % (handle, number)
        internal_name = '%s %s' % (internal_name, number)
        return self.model(year=year, official_name=official_name,
                          handle=handle, internal_name=internal_name)

    def create_from_handle(self, year, handle):
        """Translate (2015, "mat1") into a fresh RusClass object."""
        study = handle.rstrip('0123456789')
        number = handle[len(study):]
        try:
            official_name, internal_name = next(
                (official, internal)
                for official, handle_, internal in settings.RUSCLASS_BASE
                if handle_ == study
            )
        except StopIteration:
            raise ValueError("Invalid study %r" % study)
        official = '%s%s' % (official_name, number)
        internal = '%s %s' % (internal_name, number)
        return self.model(year=year, official_name=official,
                          handle=handle, internal_name=internal)


import sys, os, subprocess, re, argparse, logging

# check whether azure_operations.py exist
module_path = os.path.realpath(__file__)
module_dir = os.path.dirname(module_path)
azure_module_path = '{}/azure_operations.py'.format(module_dir)
if not os.path.exists(azure_module_path):
    raise SystemError('No azure_operations.py found')

from azure_operations import *

vm_whitelist = []
container_whitelist = ['ddvevhds', 'templates', 'ddveimgs']
#container_whitelist = []
vhd_whitelist = ['AVE-7.4.0.242-disk1.vhd', 'AVE-7.5.0.183-disk1.vhd', 'AVE-7.4.1.56-disk1.vhd']

# set logging level
logger = logging.getLogger('Logging')
logger.setLevel(logging.INFO)
# stream handler
# sh = logging.StreamHandler(stream = sys.stdout)
# sh.setFormatter(logging.Formatter(fmt = '%(message)s'))
# logger.addHandler(sh)

class delete_op:
    def __init__(self):
        self.azure_ops = azure_operations(client_id = os.environ['AZURE_CLIENT_ID'],
                secret_key = os.environ['AZURE_SECRET_KEY'],
                tenant_id = os.environ['AZURE_TENANT_ID'])

    # delete unused nics
    def delete_unused_nics(self, resource_group, delete = False):

        for nic in self.azure_ops.network_client.network_interfaces.list(resource_group):
            name = nic.name
            attached_vm = nic.virtual_machine
            if not attached_vm:
                if not delete:
                    logger.info('Unused NIC: {}'.format(name))
                else:
                    self.azure_ops.delete_nic(resource_group, name)
                    logger.info('NIC {} successfully deleted.'.format(name))

    def delete_unused_vms(self, resource_group, delete = False):

        for vm_ref in self.azure_ops.compute_client.virtual_machines.list(resource_group):
            vm = self.azure_ops.get_vm(resource_group, vm_ref.name)

            state = vm.instance_view.statuses[0].display_status
            # VM may not be successfully deployed in below case
            if state == 'Provisioning succeeded':
                state = vm.instance_view.statuses[1].display_status

            if 'running' in state:
                continue
            if '-lr' in vm.name or '-longrun' in vm.name:
                continue
            if vm.name in vm_whitelist:
                continue

            if not delete:
                logger.info('Unused VM: {}'.format(vm.name))
            else:
                self.azure_ops.delete_vm(resource_group, vm.name)
                logger.info('VM {} successfully deleted.'.format(vm.name))

    def delete_unused_vhds(self, resource_group, delete = False):

        # managed disks
        for managed_disk_ref in self.azure_ops.compute_client.disks.list_by_resource_group(resource_group):
            disk_name = managed_disk_ref.name
            logger.debug(disk_name)
            if managed_disk_ref.managed_by:
                continue
            if not delete:
                logger.info('Unused Disk: {}'.format(disk_name))
            else:
                self.azure_ops.compute_client.disks.delete(resource_group, disk_name)
                logger.info('Managed disk {} successfully deleted.'.format(disk_name))

        # unmanaged disks
        # hierarchy: storage account/container/vhd
        storage_accounts = self.azure_ops.storage_client.storage_accounts.list_by_resource_group(resource_group)
        for storage_account in storage_accounts:
            if storage_account.kind == Kind.blob_storage:
                logger.debug('Listing VHD operations will neglect Blob storage account {}.'.format(storage_account.name))
                continue

            # get storage account keys
            storage_account_keys = self.azure_ops.storage_client.storage_accounts.list_keys(resource_group, storage_account.name)
            storage_account_keys_map = {v.key_name: v.value for v in storage_account_keys.keys}
            storage_account_primary_key = storage_account_keys_map['key1']

            blob_service = BaseBlobService(account_name = storage_account.name ,account_key = storage_account_primary_key)
            for container_ref in blob_service.list_containers():
                container = container_ref.name
                if container in container_whitelist:
                    continue
                elif re.search('[0-9a-z]{16}-[0-9a-z]{16}-[cdm]0', container):
                    if delete:
                        blob_service.delete_container(container_name = container)
                        logger.info('Storage container {} successfully deleted.'.format(container))
                    else:
                        logger.error('Wrong Usage: {}/{}'.format(storage_account.name, container))
                elif 'bootdiagnostics-' in container:
                    if delete:
                        blob_service.delete_container(container_name = container)
                        logger.info('Storage container {} successfully deleted.'.format(container))
                    else:
                        logger.info('Unused Container: {}/{}'.format(storage_account.name, container))
                else:
                    blobs = blob_service.list_blobs(container_name = container)
                    for blob in blobs:
                        if re.search(r'\.vhd', blob.name):
                            if blob.properties.lease.status == 'unlocked' and blob.properties.lease.state == 'available':
                                if blob.name in vhd_whitelist:
                                    continue
                                if delete:
                                    delete_ops.azure_ops.delete_blob(resource_group, storage_account.name, container, blob.name)
                                    logger.info('Unmanaged disk {} successfully deleted.'.format(disk_name))
                                else:
                                    logger.info('Unused VHD: {}/{}/{}'.format(storage_account.name, container, blob.name))

    def delete_unused_public_ips(self, resource_group, delete = False):

        for public_ip in self.azure_ops.network_client.public_ip_addresses.list(resource_group):
            public_ip_name = public_ip.id.split('/')[-1]
            public_ip_addr = public_ip.ip_address
            if public_ip_addr:
                continue
            if not delete:
                logger.info('Unused public ip: {}'.format(public_ip_name))
            else:
                self.azure_ops.delete_public_ip(resource_group, public_ip_name)
                logger.info('Public ip {} successfully deleted.'.format(public_ip_name))

    def delete_unused_resources(self, resource_group = None, delete = False):
        if not resource_group:
            for resource_group in self.azure_ops.resource_client.resource_groups.list():
                rg_name = resource_group.name

                # list unused vms
                self.delete_unused_vms(rg_name, delete)
                # list unused vhds
                self.delete_unused_vhds(rg_name, delete)
                # list unused nics
                self.delete_unused_nics(rg_name, delete)
                # list unused public ips
                self.delete_unused_public_ips(rg_name, delete)

                logger.info('')
        else:
            # list unused vms
            self.delete_unused_vms(resource_group, delete)
            # list unused vhds
            self.delete_unused_vhds(resource_group, delete)
            # list unused nics
            self.delete_unused_nics(resource_group, delete)
            # list unused public ips
            self.delete_unused_public_ips(resource_group, delete)

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument('-S', '--subscription', help='delete resources from this subscription')
    parser.add_argument('-r', '--resource_group', help='delete resources from this group')
    parser.add_argument('--delete', action='store_true', help='delete resources from this group')
    parsed_args = parser.parse_args()

    # First check whether environmental variables are set
    try:
        os.environ['AZURE_CLIENT_ID']
        os.environ['AZURE_SECRET_KEY']
        os.environ['AZURE_TENANT_ID']
    except:
        raise SystemError("Please set environmental variables for Service Principal first.")

    delete_ops = delete_op()
    # Get all subscriptions
    subscription_map = {}
    for subscription in delete_ops.azure_ops.subscription_client.subscriptions.list():
        subscription_map[subscription.subscription_id] = subscription.display_name

    if not parsed_args.subscription:
        for (sub_id, sub_name) in subscription_map.items():
            # Subscription for Azure Marketplace
            if str(sub_id) == '1919bdd0-d66c-4699-8c08-a134883a985a':
                continue
            os.environ['AZURE_SUBSCRIPTION_ID'] = str(sub_id)
            logger.info('')
            logger.info('Subscription: {} - {}'.format(sub_id, sub_name))
            delete_ops.azure_ops.init_clients(str(sub_id))
            delete_ops.delete_unused_resources(parsed_args.resource_group, parsed_args.delete)
    else:
        os.environ['AZURE_SUBSCRIPTION_ID'] = parsed_args.subscription
        logger.info('Subscription: {} - {}'.format(parsed_args.subscription, subscription_map[parsed_args.subscription]))
        delete_ops.azure_ops.init_clients(parsed_args.subscription)
        delete_ops.delete_unused_resources(parsed_args.resource_group, parsed_args.delete)


import re
from typing import List, Tuple

def part1(inp: List[str]) -> int:
    x, y = 0, 0
    orientation = "E"
    directions = ["N", "E", "S", "W"]
    for n, line in enumerate(inp, 1):
        instruction, magnitude = line[0], int(line[1:])
        if instruction == "N":
            y += magnitude
        elif instruction == "S":
            y -= magnitude
        elif instruction == "E":
            x += magnitude
        elif instruction == "W":
            x -= magnitude
        elif instruction == "F":
            delta = {
                "N": [0, 1],
                "E": [1, 0],
                "S": [0, -1],
                "W": [-1, 0],
            }[orientation]
            x += delta[0] * magnitude
            y += delta[1] * magnitude
        elif instruction == "L":
            assert magnitude in (90, 180, 270), f"Unknown value for turn: {line}"
            orientation = directions[int(directions.index(orientation) - (magnitude / 90))]
        elif instruction == "R":
            assert magnitude in (90, 180, 270), f"Unknown value for turn: {line}"
            orientation = directions[(int(directions.index(orientation) + (magnitude / 90))) % 4]
    return abs(x) + abs(y)

def load_input_file(filename: str):
    with open(filename, "r") as inp:
        return [line.strip() for line in inp.readlines()]

def test_part1():
    inp1 = load_input_file("sample.txt")
    assert part1(inp1) == 25

    inp = load_input_file("input.txt")
    assert part1(inp) == 562

def part2(inp: List[str]) -> int:
    w_x, w_y = 10, 1
    x, y = 0, 0
    for n, line in enumerate(inp, 1):
        instruction, magnitude = line[0], int(line[1:])
        if instruction == "N":
            w_y += magnitude
        elif instruction == "S":
            w_y -= magnitude
        elif instruction == "E":
            w_x += magnitude
        elif instruction == "W":
            w_x -= magnitude
        elif instruction == "F":
            x += w_x * magnitude
            y += w_y * magnitude
        elif instruction == "L":
            assert magnitude in (90, 180, 270), f"Unknown value for turn: {line}"
            turns = int(magnitude / 90)
            if turns == 1:
                w_x, w_y = -w_y, w_x
            elif turns == 2:
                w_x, w_y = -w_x, -w_y
            elif turns == 3:
                w_x, w_y = w_y, -w_x
        elif instruction == "R":
            assert magnitude in (90, 180, 270), f"Unknown value for turn: {line}"
            turns = int(magnitude / 90)
            if turns == 1:
                w_x, w_y = w_y, -w_x
            elif turns == 2:
                w_x, w_y = -w_x, -w_y
            elif turns == 3:
                w_x, w_y = -w_y, w_x
    return abs(x) + abs(y)

def test_part2():
    inp1 = load_input_file("sample.txt")
    assert part2(inp1) == 286

    inp = load_input_file("input.txt")
    assert part2(inp) == 101860


import torch
from torch import nn
import torch.nn.functional as F
#from torchsummary import summary
from torch.utils.model_zoo import load_url as load_state_dict_from_url
import re

class BasicConv2d(nn.Module):
    """Some Information about BasicConv2d"""
    def __init__(self, in_filters, out_filters, kernel_size=(1,1), stride=(1,1), padding=(0,0), bias=False):
        super(BasicConv2d, self).__init__()
        self.conv = nn.Conv2d(in_filters, out_filters, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias)
        self.bn = nn.BatchNorm2d(out_filters, eps=0.001, momentum=0.1, affine=True, track_running_stats=True)

    def forward(self, x):
        x = self.conv(x)
        return F.relu(self.bn(x))

class Inception(nn.Module):
    """Some Information about Inception"""
    def __init__(self, st_bconv_in_filters,b1_bconv_out_filters, b2_bconv1_out_filters,b2_bconv2_out_filters,b3_bconv1_out_filters,b3_bconv2_out_filters,b4_bconv_out_filters):
        super(Inception, self).__init__()
        self.branch1 = BasicConv2d(in_filters=st_bconv_in_filters,out_filters=b1_bconv_out_filters, kernel_size=(1,1), stride=(1,1), bias=False)
        self.branch2 = nn.Sequential(
            BasicConv2d(in_filters=st_bconv_in_filters,out_filters=b2_bconv1_out_filters, kernel_size=(1,1), stride=(1,1), bias=False),
            BasicConv2d(in_filters=b2_bconv1_out_filters,out_filters=b2_bconv2_out_filters, kernel_size=(3,3), stride=(1,1),padding=(1,1),bias=False)
        )
        self.branch3 = nn.Sequential(
            BasicConv2d(in_filters=st_bconv_in_filters,out_filters=b3_bconv1_out_filters, kernel_size=(1,1), stride=(1,1), bias=False),
            BasicConv2d(in_filters=b3_bconv1_out_filters,out_filters=b3_bconv2_out_filters, kernel_size=(3,3), stride=(1,1),padding=(1,1),bias=False)
        )
        self.branch4 = nn.Sequential(
            nn.MaxPool2d(kernel_size=3, stride=1, padding=1, dilation=1, ceil_mode=True),
            BasicConv2d(in_filters=st_bconv_in_filters,out_filters=b4_bconv_out_filters, kernel_size=(1,1), stride=(1,1), bias=False)
        )

    def forward(self, x):
        return torch.cat((self.branch1(x), self.branch2(x),self.branch3(x), self.branch4(x)),1)

class GoogLeNet(nn.Module):
    def __init__(self):
        super(GoogLeNet, self).__init__()

        self.conv1 = BasicConv2d(in_filters=3,out_filters=64, kernel_size=(7,7), stride=(2,2), padding=(3,3), bias=False)
        self.maxpool1 = nn.MaxPool2d(kernel_size=3, stride=2, padding=0,dilation=1,ceil_mode=True)

        self.conv2 = BasicConv2d(in_filters=64,out_filters=64, kernel_size=(1,1), stride=(1,1), bias=False)
        self.conv3 = BasicConv2d(in_filters=64,out_filters=192, kernel_size=(3,3), stride=(1,1),padding=(1,1), bias=False)
        self.maxpool2 = nn.MaxPool2d(kernel_size=3, stride=2, padding=0,dilation=1,ceil_mode=True)

        self.inception3a = Inception(st_bconv_in_filters=192,b1_bconv_out_filters=64,b2_bconv1_out_filters=96,b2_bconv2_out_filters=128,b3_bconv1_out_filters=16,b3_bconv2_out_filters=32,b4_bconv_out_filters=32)
        self.inception3b = Inception(st_bconv_in_filters=256,b1_bconv_out_filters=128,b2_bconv1_out_filters=128,b2_bconv2_out_filters=192,b3_bconv1_out_filters=32,b3_bconv2_out_filters=96,b4_bconv_out_filters=64)
        self.maxpool3 = nn.MaxPool2d(kernel_size=3, stride=2, padding=0, dilation=1, ceil_mode=True)

        self.inception4a = Inception(st_bconv_in_filters=480,b1_bconv_out_filters=192,b2_bconv1_out_filters=96,b2_bconv2_out_filters=208,b3_bconv1_out_filters=16,b3_bconv2_out_filters=48,b4_bconv_out_filters=64)
        self.inception4b = Inception(st_bconv_in_filters=512,b1_bconv_out_filters=160,b2_bconv1_out_filters=112,b2_bconv2_out_filters=224,b3_bconv1_out_filters=24,b3_bconv2_out_filters=64,b4_bconv_out_filters=64)
        self.inception4c = Inception(st_bconv_in_filters=512,b1_bconv_out_filters=128,b2_bconv1_out_filters=128,b2_bconv2_out_filters=256,b3_bconv1_out_filters=24,b3_bconv2_out_filters=64,b4_bconv_out_filters=64)
        self.inception4d = Inception(st_bconv_in_filters=512,b1_bconv_out_filters=112,b2_bconv1_out_filters=144,b2_bconv2_out_filters=288,b3_bconv1_out_filters=32,b3_bconv2_out_filters=64,b4_bconv_out_filters=64)
        self.inception4e = Inception(st_bconv_in_filters=528,b1_bconv_out_filters=256,b2_bconv1_out_filters=160,b2_bconv2_out_filters=320,b3_bconv1_out_filters=32,b3_bconv2_out_filters=128,b4_bconv_out_filters=128)
        self.maxpool4 = nn.MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)

        self.inception5a = Inception(st_bconv_in_filters=832,b1_bconv_out_filters=256,b2_bconv1_out_filters=160,b2_bconv2_out_filters=320,b3_bconv1_out_filters=32,b3_bconv2_out_filters=128,b4_bconv_out_filters=128)
        self.inception5b = Inception(st_bconv_in_filters=832,b1_bconv_out_filters=384,b2_bconv1_out_filters=192,b2_bconv2_out_filters=384,b3_bconv1_out_filters=48,b3_bconv2_out_filters=128,b4_bconv_out_filters=128)

        self.avgpool = nn.AdaptiveAvgPool2d((1,1))
        self.dropout = nn.Dropout(p=0.2,inplace=False)
        self.fc = nn.Linear(in_features=1024, out_features=1000, bias=True)

    def forward(self, x):
        x = self.conv1(x)
        x = self.maxpool1(x)

        x = self.conv2(x)
        x = self.conv3(x)
        x = self.maxpool2(x)

        x = self.inception3a(x)
        x = self.inception3b(x)
        x = self.maxpool3(x)

        x = self.inception4a(x)
        x = self.inception4b(x)
        x = self.inception4c(x)
        x = self.inception4d(x)
        x = self.inception4e(x)
        x = self.maxpool4(x)

        x = self.inception5a(x)
        x = self.inception5b(x)

        x = self.avgpool(x)
        x = torch.flatten(x,1)
        x = self.dropout(x)
        return self.fc(x)

model_urls = {
    # GoogLeNet ported from TensorFlow
    'googlenet': 'https://download.pytorch.org/models/googlenet-1378be20.pth',
}

def googlenet(pretrained=False, progress=True, **kwargs):
    r"""GoogLeNet (Inception v1) model architecture from
    `"Going Deeper with Convolutions" <http://arxiv.org/abs/1409.4842>`_.
    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
    """
    model = GoogLeNet()

    if pretrained:
        state_dict = load_state_dict_from_url(model_urls['googlenet'],
                                              progress=progress)
        helper_state_dict = state_dict.copy()
        for key in helper_state_dict.keys():
            if re.match(r"aux*",key):
                del state_dict[key]

        #state_dict["conv1.conv.weight"]=state_dict["conv1.conv.weight"][:,:2,:,:]
        state_dict["fc.weight"] = _initialize_weights(model.fc.weight)
        state_dict["fc.bias"] = _initialize_weights(model.fc.bias)
        model.load_state_dict(state_dict)

    return model

def _initialize_weights(layer):
    import scipy.stats as stats
    X = stats.truncnorm(-2, 2, scale=0.01)
    values = torch.as_tensor(X.rvs(layer.numel()), dtype=layer.dtype)
    values = values.view(layer.size())
    with torch.no_grad():
        layer.copy_(values)
    return values

# def main():
#     model=googlenet(pretrained=True).cuda()
#     #summary(model,(3,224,224))

# if __name__=="__main__":
#     main()


from flask import Flask, request, json, render_template, send_file
from pymongo import MongoClient
from decouple import config
from bson import json_util
from bson.objectid import ObjectId
from datetime import datetime
from reportlab.lib.pagesizes import letter
from reportlab.lib import colors
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.graphics.barcode import code39, code128, code93
from reportlab.graphics.barcode import eanbc, qr, usps
from reportlab.graphics.shapes import Drawing
from reportlab.lib.pagesizes import letter
from reportlab.lib.units import mm
from reportlab.pdfgen import canvas
from reportlab.graphics import renderPDF
import os

app = Flask(__name__)

# Read the mongo_uri from the .env file
mongo_uri = config('MONGODB_URI')
db_name = config('DBNAME')

def parse_json(data):
    return json.loads(json_util.dumps(data))

@app.route('/', methods=['GET'])
def home():
    return render_template('home.html')

@app.route('/enter_doctors', methods=['GET'])
def enter_doctors():
    return render_template('enter-doctor.html')

@app.route('/enter_patients', methods=['GET'])
def enter_patients():
    return render_template('enter-patient.html')

@app.route('/get_doctors', methods=['GET'])
def get_doctors():
    client = MongoClient(mongo_uri)
    try:
        client.server_info()  # Check if connected to MongoDB
        db = client.get_database(db_name)
        doctors_collection = db.get_collection('doctors_collection')

        doctors_list = list(doctors_collection.find({}))
        return render_template("get-doctor.html", doctors_list = doctors_list)
    except Exception as e:
        print(f'Error getting doctors data: {e}')
        return parse_json({'message': 'An error occurred'}), 500
    finally:
        client.close()

@app.route('/enter_prescription', methods=['GET'])
def enter_prescription():
    client = MongoClient(mongo_uri)
    try:
        client.server_info()  # Check if connected to MongoDB
        db = client.get_database(db_name)
        medications_collection = db.get_collection('medications_collection')
        patient_collection = db.get_collection('patient_collection')
        doctors_collection = db.get_collection('doctors_collection')

        doctors_list = list(doctors_collection.find({}))
        patients_list = list(patient_collection.find({}))
        medications_list = list(medications_collection.find({}))
        return render_template('enter-prescription.html', medications_list = medications_list, doctors_list=doctors_list, patients_list=patients_list)
    except Exception as e:
        print(f'Error getting prescription data: {e}')
        return parse_json({'message': 'An error occurred'}), 500
    finally:
        client.close()

@app.route('/get_patients', methods=['GET'])
def get_patients():
    client = MongoClient(mongo_uri)
    try:
        client.server_info()  # Check if connected to MongoDB
        db = client.get_database(db_name)
        patient_collection = db.get_collection('patient_collection')

        patients_list = list(patient_collection.find({}))
        return render_template("get-patient.html", patients_list = patients_list)
    except Exception as e:
        print(f'Error getting patient data: {e}')
        return parse_json({'message': 'An error occurred'}), 500
    finally:
        client.close()

@app.route('/insert_doctor', methods=['POST'])
def insert_doctor():
    data = json.loads(request.get_data())
    client = MongoClient(mongo_uri)
    try:
        client.server_info()  # Check if connected to MongoDB
        db = client.get_database(db_name)
        doctors_collection = db.get_collection('doctors_collection')

        insert_result = doctors_collection.insert_one(data)
        return parse_json({'message': 'Doctor data inserted successfully', 'inserted_id': str(insert_result.inserted_id)})
    except Exception as e:
        print(f'Error inserting doctor data: {e}')
        return parse_json({'message': 'An error occurred'}), 500
    finally:
        client.close()

@app.route('/insert_patient', methods=['POST'])
def insert_patient():
    data = json.loads(request.get_data())
    client = MongoClient(mongo_uri)
    try:
        client.server_info()  # Check if connected to MongoDB
        db = client.get_database(db_name)
        patient_collection = db.get_collection('patient_collection')

        insert_result = patient_collection.insert_one(data)
        return parse_json({'message': 'Patient data inserted successfully', 'inserted_id': str(insert_result.inserted_id)})
    except Exception as e:
        print(f'Error inserting patient data: {e}')
        return parse_json({'message': 'An error occurred'}), 500
    finally:
        client.close()

@app.route('/insert_prescription', methods=['POST'])
def insert_prescription():
    data = json.loads(request.get_data())
    client = MongoClient(mongo_uri)
    print(data)
    try:
        client.server_info()  # Check if connected to MongoDB
        db = client.get_database(db_name)
        prescription_collection = db.get_collection('prescription_collection')
        medications_collection = db.get_collection('medications_collection')
        patient_collection = db.get_collection('patient_collection')
        doctors_collection = db.get_collection('doctors_collection')

        selected_doctor = list(doctors_collection.find({"_id":ObjectId(data['doctor_name'])}))[0]
        selected_patient = list(patient_collection.find({"_id":ObjectId(data['patient_name'])}))[0]
        selected_medication = list(medications_collection.find({"_id":ObjectId(data['prescription_name'])}))[0]

        print(selected_doctor)
        print(selected_patient)
        print(selected_medication)

        prescription_object = {
            "prescription_date": "{:%B %d, %Y}".format(datetime.now()),
            "patient_name" : "{} {}".format(selected_patient['firstName'], selected_patient['lastName']),
            "patient_age": selected_patient['age'],
            "patient_phone": selected_patient['phoneNumber'],
            "patient_dob": selected_patient['dob'],
            "patient_email": selected_patient.get('email'),
            "patient_gender": selected_patient.get('gender'),
            "patient_address": selected_patient.get('address'),
            "patient_allergies": selected_patient.get('allergies'),
            "patient_health_condition": selected_patient.get('healthCondition'),

            "selected_medication": selected_medication.get('name'),
            "purpose": data.get('purpose'),
            "dosage": data.get('dosage') ,
            "route": data.get('route'),
            "frequency": data.get('frequency'),

            "doctor_name": "{} {}".format(selected_doctor['firstName'], selected_doctor['lastName']),
            "doctor_phone": selected_doctor.get('phoneNumber'),
            "doctor_email": selected_doctor.get('email'),
        }

        insert_result = prescription_collection.insert_one(prescription_object).inserted_id
        inserted_prescription = list(prescription_collection.find({"_id":ObjectId(insert_result)}))[0]

        barcode_value = insert_result
        # barcode128 = code128.Code128(barcode_value)
        # x = 1 * mm
        # y = 285 * mm
        # x1 = 6.4 * mm

        # Load JSON data
        data = inserted_prescription

        # Create a PDF
        if not os.path.exists('cached'):
            os.makedirs('cached')
        prescription_pdf_path = "cached/prescription.pdf"
        doc = SimpleDocTemplate(prescription_pdf_path, pagesize=letter)

        elements = []

        # Styles
        styles = getSampleStyleSheet()
        style = styles["BodyText"]

        # Create a table to display the data
        data = [
            ["Prescription Date:", data["prescription_date"]],
            ["Patient Name:", data["patient_name"]],
            ["Patient Age:", data["patient_age"]],
            ["Patient Phone:", data["patient_phone"]],
            ["Patient Date of Birth:", data["patient_dob"]],
            ["Patient Email:", data["patient_email"]],
            ["Patient Gender:", data["patient_gender"]],
            ["Patient Address:", data["patient_address"]],
            ["Patient Allergies:", data["patient_allergies"]],
            ["Patient Health Condition:", data["patient_health_condition"]],
            ["Selected Medication:", data["selected_medication"]],
            ["Purpose:", data["purpose"]],
            ["Dosage:", data["dosage"]],
            ["Route:", data["route"]],
            ["Frequency:", data["frequency"]],
            ["Doctor Name:", data["doctor_name"]],
            ["Doctor Phone:", data["doctor_phone"]],
            ["Doctor Email:", data["doctor_email"]],
        ]

        table = Table(data, colWidths=120, rowHeights=20)
        table.setStyle(TableStyle([
            ('BACKGROUND', (0, 0), (-1, 0), colors.grey),
            ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
            ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
            ('BACKGROUND', (0, 1), (-1, -1), colors.whitesmoke),
            ('GRID', (0, 0), (-1, -1), 1, colors.black)
        ]))

        elements.append(Paragraph("Prescription Details", style))
        elements.append(table)

        # Generate a Code128 barcode
        # barcode = code128.Code128("123456789", writer=renderPDF)
        # barcode.drawOn(doc, 50, 50)  # Adjust the coordinates as needed

        # Build the PDF
        doc.build(elements)

        print("Prescription PDF created: prescription.pdf")
        return send_file(os.getcwd() + "/" + prescription_pdf_path, as_attachment=True)

        # return parse_json({'message': 'Prescription data inserted successfully', 'inserted_id': str(insert_result.inserted_id)})
    except Exception as e:
        print(f'Error inserting prescription data: {e}')
        return parse_json({'message': 'An error occurred'}), 500
    finally:
        client.close()

if __name__ == '__main__':
    app.run(debug=True)


import re
import requests as req
import bs4
from bs4 import BeautifulSoup as bs

def HtmlGet(url,code='utf-8'):
    try:
        request=req.get(url)
        request.raise_for_status()
        request.encoding=code
        return request.text
    except:
        return ""

def HtmlAss(li,url):
    html=HtmlGet(url,'GB2312')
    soup=bs4.BeautifulSoup(html,"html.parser")
    l=soup.find_all('a')
    for i in l:
        try:
            href=i.attrs['href']
            st=re.findall(r"[s][hz]\d{6}",href)[0]
            li.append(st)
        except:
            continue
    return li

def HtmlPri(li,fileurl,url):
    count=0
    for i in li:
        url2=url+i+".html"
        html=HtmlGet(url2)
        try:
            if html=="":
                continue
            dic = {}
            list=[]
            soup=bs4.BeautifulSoup(html,"html.parser")
            info=soup.find('div',attrs={'class':'stock-bets'})
            name=info.find_all(attrs={'class':'bets-name'})[0]
            price=info.find_all('strong',attrs={'class':'_close'})[0]
            list.append(name.text.strip().split()[0])
            list.append(price.text)
            dic.update({'股票名称：':str(list)})
            with open(fileurl,'a') as f:
                f.write(str(dic)+'\n')
                count=count+1
                print('\r当前进度：{:.2f}%'.format(count/len(li)),end='')
                f.close()
        except:
            f.close()
            #traceback.print_exc()
def main():
    li=[]
    url="http://quote.eastmoney.com/stocklist.html"
    url2="https://gupiao.baidu.com/stock/"
    fileurl="F:\\t.txt"
    #url2=""
    li=HtmlAss(li,url)
    HtmlPri(li,fileurl,url2)

main()


import pytz
from django.http import HttpResponse
from django.utils.datetime_safe import datetime
from django.views.decorators.csrf import ensure_csrf_cookie
from gatherer.models import Log
from model_builder.bought_together_builder import recalculate_bought_together_db
from model_builder.user_ratings_builder import update_ratings_for_user

@ensure_csrf_cookie
def log_event(request):
    if request.method == 'POST':
        date = datetime.now(pytz.utc)
        event_type = request.POST['event_type']
        content_id = request.POST['content_id']
        session_id = request.POST['session_id']

        log = Log(
            created=date,
            event_type=event_type,
            content_id=content_id,
            session_id=session_id,
            user_id=request.user.id)\
            .save()

        if request.user.id is not None:
            update_ratings_for_user(request.user.id)

        if event_type == "purchase_event":
            recalculate_bought_together_db()

    else:
        return HttpResponse('Log only possible with a POST request!')

    return HttpResponse('ok')