import networkx as nx
import ndlib.models.ModelConfig as mc
import ndlib.models.epidemics as ep
import csv
import numpy as np
import math
from geneticalgorithm import geneticalgorithm as ga
from sklearn.metrics import mean_squared_error

days =113
n = 500
beta = 0.3
gamma = 0.3
g = nx.erdos_renyi_graph(n, 0.5)
a = int()

# Model selection
SIRModel = ep.SIRModel(g)
# Model Configuration
cfg = mc.Configuration()
cfg.add_model_parameter('beta', beta)
cfg.add_model_parameter('gamma', gamma)
cfg.add_model_parameter("fraction_infected", 0.3)
SIRModel.set_initial_status(cfg)

# Ready CSV
arq = open("casos_sj.csv")
sirSjCsv = csv.DictReader(arq,fieldnames = ["S","R","I"])

matriz_gerada = np.zeros((days,3), dtype = np.int)
sirSj = list()
sirS = list()
sirI = list()
sirR = list()
Igerado = list()
Rgerado = list()
i = 0

for row in sirSjCsv:
    sirSj.insert(i, { "S": int(row['S']), "I": int(row['I']), "R" : int(row['R'])})
    sirS.append(int(row['S']))
    sirI.append(int(row['I']))
    sirR.append(int(row['R']))
    i+=1

#print(sirSj)
data = sirSj

#print(data[0]['I'])

varbound=np.array([[0,1]]*2)

def fitness(x):
    SIRModel.reset()
    cfg.add_model_parameter('beta', x[0])
    cfg.add_model_parameter('gamma', x[1])
    SIRModel.set_initial_status(cfg)
    iterations = SIRModel.iteration_bunch(days)
    print(iterations)
    a = 0
    Igerado.clear()
    Rgerado.clear()
    for x in iterations:
        matriz_gerada[a][0] = x['node_count'][0]
        matriz_gerada[a][1] = x['node_count'][1]
        matriz_gerada[a][2] = x['node_count'][2]
        Igerado.append(x['node_count'][1])
        Rgerado.append(x['node_count'][2])
        a = a + 1

    print(matriz_gerada)
    print(Igerado)
    print(iterations)

    mseI = mean_squared_error(sirI, Igerado)
    mseR = mean_squared_error(sirR, Rgerado)
    rmseI = math.sqrt(mseI)
    rmseR = math.sqrt(mseR)
    f = (rmseI + rmseR) / 2
    return f

GaModel= ga(function= fitness,dimension=2,variable_type='real',variable_boundaries=varbound)

GaModel.run()


#!/usr/bin/env python3
__author__ == "Bo Feng"
__email__ == "bfeng18@lzu.edu.cn"
'''
This use subprocess to ouput a file's change history difference between commit bdfore and express in one line in kernel
'''
from subprocess import Popen, check_output

def gitFileDynamics(fileName, kernelRange, repo):
    cmd = ["git", "-stat", "--oneline", "--follow", kernelRange, fileName]
    result = check_output(cmd, cwd=repo).decode("utf-8")
    print(result)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 25 15:40:02 2019

@author: jacastillo8
"""
import pandas as pd
import json, random, os
from getmac import get_mac_address

os.chdir('/home/jacastillo8/Projects/emr_traffic_sim/organizer/tasks/')

class Tasks(object):
    def __init__(self):
        # Reading desired IP addressess
        with open("../../IP_Addresses.txt", 'r') as file:
            self.text = []
            for line in file:
                if not line.startswith("#"):
                   self.text.append(line.replace('\n', ''))
        self.devices = len(self.text) # Number of devices is directly related to number of tasks (one task per device)
        self.data = None
        self.beds = None

    def read_excel(self, path_to_file, sheet_name=None):
        if sheet_name is None:
            self.data = pd.read_excel(path_to_file, sheet_name='Sheet1')
        else:
            self.data = pd.read_excel(path_to_file, sheet_name=sheet_name)

    def generate(self):
        """ Generates a number of tasks to be distributed for traffic generation
            (default to 5 devices) """
        if self.data is None:
            raise Exception("Set dataframe 'Tasks.read_excel()' before continuing.")
        self.beds = self.data['Bed Label'].unique().tolist()
        try:
            self.beds.remove('Discharged')  # Removing element (not a bed)
        except:
            pass
        random.shuffle(self.beds)
        bed_distro = [self.beds[i * self.devices:(i + 1) * self.devices]\
                          for i in range((len(self.beds) + self.devices - 1) //\
                                         self.devices)]
        TASKS = {}
        task = {}
        # Time intervals in 24h format [x1, x2) - math notation to define inclusivity
        time_interval = [(8, 10), (10, 13), (13, 19), (19, 23.98), (24, 3), (3, 8)]
        for i in range(self.devices):
            """
             Dictionary below contains two elements per key.
             First, time range for patient data transmission
             Second, time interval for which data transmission works
               For example:
                 - Key 'a' sends data every 10-15 minutes (inclusive) from 8AM-10AM
                 - Key 'b' sends data every 15-20 minutes from 10AM-1PM
            """
            task["a"] = [(10, 15), time_interval[0][:]]
            task["b"] = [(15, 20), time_interval[1][:]]
            task["c"] = [(5, 10), time_interval[2][:]]
            task["d"] = [(5, 25), time_interval[3][:]]
            task["e"] = [(20, 35), time_interval[4][:]]
            task["f"] = [(15, 30), time_interval[5][:]]
            task["beds"] = bed_distro[i]
            TASKS[f"{i+1}"] = task.copy()   # Create shallow copy of dict object
            random.shuffle(time_interval) # Randomize time intervales
        # Dump TASKS into json file
        with open("../../emr/info/task_distribution.json", 'w+') as file:
            json.dump(TASKS, file)

    def distribute(self):
        """ Generates a dictionary object to distrubute tasks according to MAC
            Addresses """
        # Obtain MAC per IP (last 6 digits only)
        mac = []
        for ip in self.text:
            mac.append(get_mac_address(ip=ip).replace(":", "")[-6:])
        # Create randomized list of tasks
        task_list = [str(i) for i in range(1,len(self.text)+1)]
        random.shuffle(task_list)
        # Generate dictionary containing task and MAC
        task_distribution = {}
        for i in range(len(self.text)):
            task_distribution[mac[i]] = task_list[i]
        # Dump task distribution into json file
        with open("../../emr/info/list.json", 'w+') as file:
            json.dump(task_distribution, file)

if __name__ == '__main__':
    tasks = Tasks()
    tasks.read_excel("../../../icu/Dataset/ICU1_data.xlsx")
    tasks.generate()
    tasks.distribute()


"""
座右铭:如果现在的生活不是你想要的,那就是你自找的.
@project:yuke
@author:Si_jin_hui
@file:Spider.PY
@ide:PyCharm
@time:2018-08-17 10:46:15
"""
from bs4 import BeautifulSoup
import requests

import sqlite3

class DBManger(object):
    connect = None
    cursor = None
    @classmethod
    def create_connect_and_cursor(cls):
        cls.connect = sqlite3.connect('kanshu.db')
        cls.cursor = cls.connect.cursor()
    @classmethod
    def create_table(cls):
        cls.cursor.execute(
            "create table if not exists paihang(id integer primary key unique, paiming text, fenlei text, shuming text, lianjie text, zuozhe text, zongzishu text, gengxin text, souquan text, jincheng text, zongdianji text, benyuedianji text)")
    @classmethod
    def insert_data(cls,result):
        cls.cursor.execute("insert into paihang(paiming,fenlei,shuming,lianjie,zuozhe,zongzishu,gengxin,souquan,jincheng,zongdianji,benyuedianji)VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" % (result["paiming"], result["fenlei"], result["shuming"], result["lianjie"], result["zuozhe"], result["zongzishu"],result["gengxin"],result["souquan"],result["jincheng"],result["zongdianji"],result["benyuedianji"]))
    @classmethod
    def close(cls):
        cls.connect.commit()
        cls.cursor.close()
        cls.connect.close()

class Spider(object):
    def __init__(self):
        self.proxies = {"http":"http://175.155.24.17:808"}
        self.headers = {"User-Agent":"Mozilla/5.0(Macintosh;IntelMacOSX10_7_0)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11",}
        self.session = requests.session()
        self.result_list = []

    def get_book_name(self):
        base_url = "http://top.kanshu.com/list_7_1.html"
        # abs_url = "http://top.kanshu.com/more/list_7_1.html?is_ajax=1&page=3&timeType=week&big_id=7"

        for i in range(1,7):
            params = {
                "is_ajax": "1",
                "page": i,
                "timeType": "week",
                "big_id": "7"
            }
            try:
                response = requests.get(url=base_url,params=params,headers=self.headers).json()
            except Exception as e:
                print("连接失败,原因: ", e)
            else:
                html = response['result']['data']['html']
                bs_soup = BeautifulSoup(html,"lxml")

                paiming = bs_soup.select("li .sp_01")
                fenlei =  bs_soup.select("li .sp_02")
                shuming = bs_soup.select("li .sp_03 a ")
                zuozhe =  bs_soup.select("li .sp_04")
                # dianji =  bs_soup.select("li .sp_05")
                zongzishu = bs_soup.select("li .sp_06")
                gengxin = bs_soup.select("li .sp_07")
                for i in range(0,len(shuming)):
                    result = {"paiming":paiming[i].string,"fenlei":fenlei[i].string,"shuming":shuming[i].string,"lianjie":shuming[i]["href"],"zuozhe":zuozhe[i].string,"zongzishu":zongzishu[i].string,"gengxin":gengxin[i].string}
                    self.result_list.append(result)

    # 定义一个函数获取子链接的内容,并将数据添加到子字典当中
    def get_info(self):
        for result_num in range(0, len(self.result_list)):
            url = self.result_list[result_num]['lianjie']

            try:
                print("正在请求子网页,url = ",url)
                response = requests.get(url,headers=self.headers).content
            except Exception as e:
                print("子网页连接错误,原因: ", e)
            else:
                bs_soup = BeautifulSoup(response,'lxml')
                result_info = bs_soup.select("#main1 .xx_xinx li .org")
                print("result_num=====",result_num)
                try:
                    self.result_list[result_num].setdefault("souquan",result_info[1].string)
                    self.result_list[result_num].setdefault('jincheng',result_info[2].string)
                    self.result_list[result_num].setdefault('zongdianji',result_info[4].string)
                    self.result_list[result_num].setdefault('benyuedianji',result_info[5].string)
                except Exception as e:
                    print("错误原因:  ", e)
                else:
                    DBManger.create_connect_and_cursor()
                    DBManger.insert_data(self.result_list[result_num])
                    DBManger.close()
                # 数据保存成功

if __name__ == '__main__':
    spider = Spider()

    DBManger.create_connect_and_cursor()
    DBManger.create_table()

    spider.get_book_name()
    spider.get_info()

    # DBManger.close()
    # spider.save_data()


import sys, os
import xml.etree.ElementTree as ET

class gameBox:
    """An info container class"""
    name = ""
    filename = ""
    imgsrc = ""
    programID = 0
    PID = 0

    def __init__(self, filename):
        self.filename = filename
        self.parseXML()

    def parseXML(self):
        gamesDirectoryPresent = False
        for dirname, dirnames, filenames in os.walk('.'):
            for subdirname in dirnames:
                if subdirname == "games":
                    gamesDirectoryPresent = True

            if not gamesDirectoryPresent:
                raise Exception("No games directory")
        infoFilePresent = False
        for dirname, dirnames, filenames in os.walk("./games"):
            for filename in filenames:
                if filename == self.filename:
                    infoFilePresent = True
            if not infoFilePresent:
                raise Exception("No game info file")

        gameTree = ET.parse("./games/" + self.filename)
        gameRoot = gameTree.getroot()

        self.programID = gameRoot.find("PID").text
        self.PID = self.programID
        self.name = gameRoot.find("name").text
        self.imgsrc = gameRoot.find("imagesource").text


from pyld import jsonld
import json
import re
import requests
import grequests
from collections import defaultdict
from subprocess import Popen, PIPE, STDOUT
from joblib import Parallel, delayed
import multiprocessing
import logging

logger = logging.getLogger(__name__)

from .utils import readFile

class JSONLDHelper:
    def __init__(self):
        self.processor = jsonld.JsonLdProcessor()
        self.temp_attr_id = None

    def jsonld2nquads_helper(self, jsonld_doc):
        """
        Given a JSONLD document, return its nquads format

        Params
        ======
        jsonld_doc: jsonld document containing both JSON and the context file

        TODO
        ======
        Currently it relies on the JSONLD ruby client to convert to nquads
        When the JSONLD Python client is ready to adapt to 1.1,
        should switch to the Python client
        """
        """
        No longer need JSON-LD Ruby Client
        PyLD for 1.1 json-ld version is available
        # the following 6 lines use JSON-LD Ruby client to convert
        # JSON-LD document into NQuads format
        cmd = 'jsonld --validate --format nquads'
        p = Popen(cmd.split(), stdout=PIPE, stdin=PIPE, stderr=STDOUT)
        p.stdin.write(doc.encode('utf-8'))
        stdout_data = p.communicate()[0]
        p.stdin.close()
        _response = stdout_data.decode()
        """
        # convert from jsonld doc to nquads format
        nquads = jsonld.to_rdf(jsonld_doc, {'format': "application/nquads"})
        """
        No longer need to deal with ruby error message
        if _response.startswith(('Error', 'ERROR')):
            logger.error("An error occured when JSON-LD Ruby client tries to parse the JSON-LD. \
                         The first 100 chars of the JSON document is %s", jsonld_doc[:100])
            return None
        # deal with cases when JSON-LD Ruby client returns empty resutls
        elif _response.startswith('\nParsed 0 statements'):
            logger.warning("0 statements is found when JSON-LD Ruby client tries to parse the JSON-LD input.\
                           The first 100 chars of the JSON document is %s", jsonld_doc[:100])
        else:
        """
        try:
            return self.processor.parse_nquads(nquads)
        except Exception as e:
            logger.error("Something Unexpected happend when JSON-LD Python client tries to parse the JSON-LD. \
                         The first 100 chars of the JSON document is %s", json.dumps(jsonld_doc[:100]))
            logger.error(e, exc_info=True)
            return None

    def jsonld2nquads(self, jsonld_docs):
        """
        Given a JSON-LD annotated document,
        Fetch it's corresponding NQUADs file from JSON-LD playground
        'http://jsonld.biothings.io/?action=nquads'

        TODO: Currently, PyLD hasn't been updated to match JSON-LD v 1.1
        So we are using the JSON-LD playground API, which is built upon
        JSON-LD ruby client for 1.1 version. When PyLD has been updated to
        match 1.1, we should switch back to PyLD.

        Params
        ======
        jsonld_doc: (dict)
            JSON-LD annotated document
        """
        # handle cases where input is a list of JSON documents
        # in this case, the results will also be a list of NQuads parsing results
        if type(jsonld_docs) == list and type(jsonld_docs[0]) == dict:
            #results = Parallel(n_jobs=multiprocessing.cpu_count())(delayed(self.jsonld2nquads_helper)(_doc) for _doc in jsonld_docs)
            results = []
            for _doc in jsonld_docs:
                results.append(self.jsonld2nquads_helper(_doc))
            if len(results) == 1:
                return results[0]
            else:
                return results
        # handle cases where input is a single JSON object document
        # in this case, the results will be a single NQuads parsing result
        elif type(jsonld_docs) == dict:
            """
            jsonld_docs = [jsonld_docs]
            results = Parallel(n_jobs=multiprocessing.cpu_count())(delayed(self.jsonld2nquads_helper)(_doc) for _doc in jsonld_docs)
            return results[0]
            """
            return self.jsonld2nquads_helper(jsonld_docs)
        # if the input is neither list of json_docs nor single json_doc
        # log error message and return None
        else:
            logger.warning("The input of the jsonld2nquads function should be a list of JSON docs or a single JSON dictionary doc. \
                           You input is %s. The first 100 chars of the input is %s", type(jsonld_docs), jsonld_doc[:100])
            return None

    def json2jsonld(self, json_docs, jsonld_context_path):
        """
        Given a JSON document and the endpoint where the doc comes from
        Fetch the JSON-LD context file for the endpoint
        Apply the JSON-LD context to JSON file to construct the JSON-LD document

        Return
        ======
        JSON-LD document
        """
        jsonld_context = readFile(jsonld_context_path)
        if type(json_docs) == list and type(json_docs[0]) == dict:
            jsonld_docs = [json_doc.update(jsonld_context) for json_doc in json_docs]
            return json_docs
        elif type(json_docs) == dict:
            json_docs.update(jsonld_context)
            return json_docs
        else:
            logger.warning("The input of the json2jsonld function should be a list of JSON docs or a single JSON dictionary doc. \
                           You input is %s. The first 100 chars of the input is %s", type(jsonld_docs), jsonld_doc[:100])
            return None

    def json2nquads(self, json_docs, context_file_path):
        """
        Given a JSON document, perform the following actions
        1) Find the json-ld context file based on endpoint_name
        2) Add JSON-LD context file to JSON doc
        3) Convert the JSON-LD doc into N-quads format

        Params
        ======
        json_doc: (dict)
            JSON document fetched from API calls
        endpoint_name: (str)
            the endpoint which the JSON doc comes from
        output: (str)
            URI subject
        predicate:
            NQUADS predicate, default is None
        """
        jsonld_docs = self.json2jsonld(json_docs, context_file_path)
        nquads = self.jsonld2nquads(jsonld_docs)
        return nquads

    def find_object_properties_in_jsonld(self, _dict):
        """
        extract the @base field corresponding to "attr:id" in a nested JSON-LD context file
        """
        for k,v in _dict.items():
            # check if @id startswith "attr:" or "rel:"
            if isinstance(v, dict) and "@id" in v and v["@id"] == "attr:id":
                # @base should be in the child level of @context
                if "@base" in v["@context"]:
                    self.temp_attr_id = v["@context"]["@base"]
                else:
                    print('@base should be included here! Something wrong with the JSON-LD context file!!')
            # otherwise, recall this function to look into the child level
            elif isinstance(v, dict):
                self.find_object_properties_in_jsonld(v)

    def jsonld_parser_helper(self, _dict, relation=defaultdict(set)):
        """
        extract relationship information from "@id" which startsfrom "assoc:"
        extract output information from "@base"
        """
        for k, v in _dict.items():
            # First, looking for value of @id startswith "assoc"
            # this represents an association in the nested structure
            if isinstance(v, dict) and "@id" in v and v["@id"].startswith("assoc:"):
                # Next, looking for whether "@base" exists in the direct child level
                if "@context" in v and "@base" in v["@context"]:
                    relation[v["@context"]["@base"]].add(v["@id"])
                # If "@base" not exists in direct child level, look for levels deeper
                elif "@context" in v:
                    self.temp_attr_id = None
                    self.find_object_properties_in_jsonld(v["@context"])
                    if self.temp_attr_id:
                        relation[self.temp_attr_id].add(v["@id"])
                    else:
                        print("attr:id is missing in the object properties!")
            elif isinstance(v, dict):
                self.jsonld_parser_helper(v, relation=relation)
        return relation

    def jsonld_relation_parser(self, jsonld_context):
        """
        Given a JSON-LD context file, reorganize the file
        so that the key would be the attr id,
        the rest of the information would be wrapped in the value

        Example Outputs:

        >>> jsonld_helper = JSONLDHelper()
        >>> jsonld_context_file = {"hits": {"@id": "http://bt.d2g/", "@type": "@id", "@context": {"gene": {"@id": ""}}}
        }}

        """
        if type(jsonld_context) != dict or '@context' not in jsonld_context:
            logging.error("Invalid JSON-LD context file!")
            return
        return self.jsonld_parser_helper(jsonld_context, relation=defaultdict(set))

    def fetch_object_value_by_predicate_value_in_nquads(self, nquads, predicate_value):
        """
        Given a nquads parsing results and a predicate_value
        find the corresponding object value(s)
        """
        object_values = []
        if '@default' in nquads:
            nquads = nquads['@default']
        for _nquad in nquads:
            if _nquad['predicate']['value'] == predicate_value:
                object_values.append(_nquad['object']['value'])
        return object_values

    def fetch_object_and_predicate_value_by_subject_value_in_nquads(self, nquads, subject_value, results=None):
        """
        Given a nquads parsing results and a subject_value
        find the corresponding object and predicate value
        """
        if not results:
            results = defaultdict(list)
        if '@default' in nquads:
            nquads = nquads['@default']
        for _nquad in nquads:
            if _nquad['subject']['value'] == subject_value:
                current_predicate_value = _nquad['predicate']['value']
                current_object_value = _nquad['object']['value']
                if current_predicate_value != 'http://biothings.io/pass/':
                    results[current_predicate_value].append(_nquad['object']['value'])
                else:
                    results = self.fetch_object_and_predicate_value_by_subject_value_in_nquads(nquads, _nquad['object']['value'], results)
        return results

    def fetch_properties_by_association_in_nquads(self, nquads, association_list):
        results = {}
        for _association in association_list:
            results[_association] = []
            object_values = self.fetch_object_value_by_predicate_value_in_nquads(nquads, _association)
            for _object_value in object_values:
                if _object_value.startswith('_:'):
                    object_predicate_dict = self.fetch_object_and_predicate_value_by_subject_value_in_nquads(nquads, _object_value)
                    if object_predicate_dict:
                        results[_association].append(object_predicate_dict)
                    else:
                        print("Could not fetch any properties from the given association: {}".format(_object_value))
                else:
                    results[_association].append({'http://biothings.io/explorer/vocab/attributes/id': [_object_value]})
        return results

    def fetch_properties_by_association_and_prefix_in_nquads(self, nquads, association, prefix):
        association_results = self.fetch_properties_by_association_in_nquads(nquads, [association])
        association_and_prefix_results = [_doc for _doc in association_results[association] if _doc['http://biothings.io/explorer/vocab/attributes/id'][0].startswith(prefix)]
        return association_and_prefix_results

t = jsonld.JsonLdProcessor()

def process_jsonld(doc):
    # cmd = 'ruby jsonld_test_cli.rb -a compact'
    doc = json.dumps(doc)
    logger.debug('The JSONLD file after json.dumps is %s', doc)
    RUBY_JSONLD_CMD = 'jsonld'
    cmd = RUBY_JSONLD_CMD + ' '
    cmd += '--validate --format nquads'
    p = Popen(cmd.split(), stdout=PIPE, stdin=PIPE, stderr=STDOUT)
    p.stdin.write(doc.encode('utf-8'))
    # stdout_data = p.communicate(input=doc.encode('utf-8'))[0]
    stdout_data = p.communicate()[0]
    p.stdin.close()
    _response = stdout_data.decode()
    if 'Parsed' in _response:
        _nquad = re.sub('Parsed .*second.\n', '', _response)
        return t.parse_nquads(_nquad)
    else:
        return None

def json2jsonld(json_doc, jsonld_context_path):
    """

    """
    doc = json.dumps(doc).replace(' ', '')
    cmd = 'jsonld --validate --format nquads'
    p = Popen(cmd.split(), stdout=PIPE, stdin=PIPE, stderr=STDOUT)
    p.stdin.write(doc.encode('utf-8'))
    stdout_data = p.communicate()[0]
    p.stdin.close()
    _response = stdout_data.decode()
    # check if startswith 'ERROR'
    # check if return nquads
    # check if the nquads is empty
    # if parsing error
    if 'Parsed' in _response:
        _nquad = re.sub('Parsed .*second.\n', '', _response)
        return t.parse_nquads(_nquad)
    else:
        return None

'''
def jsonld2nquads(jsonld_doc, mode='batch'):
    """
    Given a JSON-LD annotated document,
    Fetch it's corresponding NQUADs file from JSON-LD playground
    'http://jsonld.biothings.io/?action=nquads'

    TODO: Currently, PyLD hasn't been updated to match JSON-LD v 1.1
    So we are using the JSON-LD playground API, which is built upon
    JSON-LD ruby client for 1.1 version. When PyLD has been updated to
    match 1.1, we should switch back to PyLD.

    Params
    ======
    jsonld_doc: (dict)
        JSON-LD annotated document
    """
    # need to skip html escapes
    if mode != 'batch':
        nquads = requests.post('http://jsonld.biothings.io/?action=nquads', data={'doc': json.dumps(jsonld_doc).replace('>', ">").replace(' ', '')})
        if nquads.status_code != 413:
            # remove the log line from the nquads
            nquads = re.sub('Parsed .*second.\n', '', nquads.json()['output'])
            return t.parse_nquads(nquads)
    elif mode == 'batch':
        responses = []
        for _jsonld_doc in jsonld_doc:
            responses.append(grequests.post('http://jsonld.biothings.io/?action=nquads', data={'doc': json.dumps(_jsonld_doc).replace('>', ">").replace(' ', '')}))
        responses = grequests.map(iter(responses))
        results = []
        for _response in responses:
            if _response.status_code != 413:
                nquads = re.sub('Parsed .*second.\n', '', _response.json()['output'])
                results.append(t.parse_nquads(nquads))
            else:
                results.append(None)
        return results
'''
def jsonld2nquads(jsonld_docs):
    """
    Given a JSON-LD annotated document,
    Fetch it's corresponding NQUADs file from JSON-LD playground
    'http://jsonld.biothings.io/?action=nquads'

    TODO: Currently, PyLD hasn't been updated to match JSON-LD v 1.1
    So we are using the JSON-LD playground API, which is built upon
    JSON-LD ruby client for 1.1 version. When PyLD has been updated to
    match 1.1, we should switch back to PyLD.

    Params
    ======
    jsonld_doc: (dict)
        JSON-LD annotated document
    """
    results = []
    """
    for _doc in jsonld_docs:
        _response = process_jsonld(_doc)
        if 'Parsed' in _response:
            _nquad = re.sub('Parsed .*second.\n', '', _response)
            results.append(t.parse_nquads(_nquad))
        else:
            results.append(None)
    """
    num_cores = multiprocessing.cpu_count()
    results = Parallel(n_jobs=num_cores)(delayed(process_jsonld)(_doc) for _doc in jsonld_docs)
    return results

def fetchvalue(nquads, object_uri, predicate=None):
    """
    Given a NQUADS together with (URI/subject, predicate) pair
    Extract the object value

    Params
    ======
    nquads: (list)
        NQUADS doc
    object_uri: (str)
        URI subject
    predicate:
        NQUADS predicate. If None is specified, return all objects matching the subject
    """
    results = []
    # check if it's a valid nquads
    if nquads and '@default' in nquads:
        for _nquad in nquads['@default']:
            if predicate and object_uri in _nquad['object']['value'] and _nquad['predicate']['value'].split('/')[-1] == predicate.split(':')[-1]:
                results.append((_nquad['object']['value'].split(object_uri)[1], _nquad['predicate']['value'].split('/')[-1]))
            elif not predicate and object_uri in _nquad['object']['value']:
                results.append((_nquad['object']['value'].split(object_uri)[1], _nquad['predicate']['value'].split('/')[-1]))
    elif nquads:
        print('This is a invalid nquads, missing "@default"!!!')
    else:
        print('The nquads is empty')
    # if results is empty, it could be either nquads is empty or object_uri could not be found in nuqads
    if results:
        return list(set(results))
    else:
        return

def find_base(d, relation=defaultdict(set)):
    """
    Iterative function
    Given a JSON-LD context file as Python Dictionary,
    return all bio-entity URIs in that context file
    together with the relationship(s) as a set
    e.g. {'http://identifiers.org/pdb/': {'ont:has3DStructure'}}

    Params
    ======
    d: (dict)
        JSON-LD context
    relation: (dict)
        temporarily store relation info
    """
    for k, v in d.items():
        if isinstance(v, dict) and "@context" in v and "@base" in v["@context"]:
            relation[v["@context"]["@base"]].add(v["@id"])
        # if v is a dict and doesnt have @base, then reiterative the process
        elif isinstance(v, dict):
            find_base(v, relation=relation)
    return relation

def json2nquads(json_doc, context_file_path, output_type, predicate=None):
    """
    Given a JSON document, perform the following actions
    1) Find the json-ld context file based on endpoint_name
    2) Add JSON-LD context file to JSON doc
    3) Convert the JSON-LD doc into N-quads format

    Params
    ======
    json_doc: (dict)
        JSON document fetched from API calls
    endpoint_name: (str)
        the endpoint which the JSON doc comes from
    output: (str)
        URI subject
    predicate:
        NQUADS predicate, default is None
    """
    context_file = readFile(context_file_path)
    for _json_doc in json_doc:
        _json_doc.update(context_file)
    nquads = jsonld2nquads(json_doc)
    results = []
    for _nquad in nquads:
        output = fetchvalue(_nquad, output_type, predicate=predicate)
        if output:
            outputs = list(set(output))
            results.append(outputs)
        else:
            results.append(None)
    return results


from os.path import splitext
from os import listdir
import numpy as np
from glob import glob
import torch
from torch.utils.data import Dataset
import logging
from skimage.transform import resize, rotate
from skimage.filters import gaussian
from skimage import io
import Augmentor
import cv2

class BasicDataset(Dataset):
    """
    imgs dir : 이미지 디렉토리 경로(path of image directory)
    masks_dir : 이미지에 대한 mask 디렉토리 경로(path of directory masks correspond to image )
    resize : 입력 이미지 크기 조절 사이즈(Unet paper based, 572)
    """
    def __init__(self, imgs_dir, masks_dir, resizing=572, is_transform=True, shuffle=True):
        self.imgs_dir = imgs_dir
        self.masks_dir = masks_dir
        self.resizing = resizing
        self.is_transform = is_transform
        self.shuffle=shuffle

        self.image_name_list = [splitext(file)[0] for file in listdir(imgs_dir) #이미지 파일 가져오고, 그중에서 이름만 가져오기 (img.jpg => extract img except for .jpg)
                    if not file.startswith('.')] # 폴더안에 존재하는 이미지들의 이름들의 리스트 (list of image names)
        logging.info(f'Creating dataset with {len(self.image_name_list)} examples') # 로그 기록

    """
    self.ids : 총 데이터셋의 크기를 나타낸다.(Size of total dataset)
    """
    def __len__(self):
        return len(self.image_name_list)

    """
    idx : range(0, len(self.ids)) 의 원소 중 하나. 0부터 차례대로 들어온다.
    (one of element in range(0, len(self.ids))). input numbers in sequence.
    """

    def __getitem__(self, idx):

        image_name = self.image_name_list[idx]
        #glob(searching criteria) : find files that meet searching criteria, output type : list.
        #glob(탐색 기준식) : 탐색 기준식을 만족하는 파일을 찾아, 그 항목들을 리스트로 반환.
        mask_file = glob(self.masks_dir + image_name + '.*') # (in the case of 'image name == mask name')
        img_file = glob(self.imgs_dir + image_name + '.*') #(in the case of 'image name == mask name')

        assert len(mask_file) == 1, \
            f'Either no mask or multiple masks found for the ID {image_name}: {mask_file}'
        assert len(img_file) == 1, \
            f'Either no image or multiple images found for the ID {image_name}: {img_file}'

        # print("img name : {}".format(img_file[0]))
        img = io.imread(img_file[0])
        mask_for_notf = io.imread(mask_file[0])
        mask = cv2.imread(mask_file[0]) # for augmenting, gray image: cv2.imread=(width, height, 3) , io.imread=(width, height)

        assert img.shape == mask.shape, \
            f'Image and mask {image_name} should be the same size, but are {img.size} and {mask.size}'

        if self.is_transform == False:
            img = self.preprocess(img, self.resizing)
            mask = self.preprocess(mask_for_notf, self.resizing)
            data = {'image': torch.from_numpy(img), 'mask': torch.from_numpy(mask)}
        else:
            if np.random.uniform(size=1)[0] >= 0.7:
                  sigma = np.random.uniform(0.1,1,size=1)[0]
                  img = (gaussian(img, sigma=sigma, multichannel=True)*255).astype(np.uint8)

            p = Augmentor.DataPipeline([[img, mask]])
            p.resize(probability=1.0, width=256, height=256)
            p.rotate_without_crop(probability=0.3, max_left_rotation=25, max_right_rotation=25)
            p.shear(probability=0.3, max_shear_left=0.5, max_shear_right=0.5)
            p.flip_random(probability=0.6)
#           p.skew_tilt(probability=0.3, magnitude=0.1)
#           p.random_distortion(probability=0.3, grid_height=10, grid_width=10, magnitude=1)
#           p.zoom(probability=1.0, min_factor=1.1, max_factor=1.3)

            sample_p = p.sample(1)
            sample_p = np.array(sample_p).squeeze()

            p_img = sample_p[0]
            p_mask = sample_p[1]
            augmented_mask = (p_mask//255)*255 #np.where(p_mask<=0, p_mask, 255)

            q = Augmentor.DataPipeline([[p_img]])
            q.random_contrast(probability=0.3, min_factor=0.2, max_factor=1.0)  # low to High
            q.random_brightness(probability=0.3, min_factor=0.2, max_factor=1.0)  # dark to bright

            sample_q = q.sample(1)
            sample_q = np.array(sample_q).squeeze()

            augmented_img = sample_q
            augmented_mask = augmented_mask[::,::,0]
            kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(3,3))
            augmented_mask = cv2.morphologyEx(augmented_mask, cv2.MORPH_CLOSE, kernel)

            result_img= self.preprocess_wo_resize(augmented_img)
            result_mask = self.preprocess_wo_resize(augmented_mask)

            data = {'image': torch.from_numpy(result_img), 'mask': torch.from_numpy(result_mask)}
        return data

    @classmethod
    def preprocess(cls, img, resizing):
        img = resize(img, (resizing, resizing), anti_aliasing=True) # skimage.transform.resize

        img_nd = np.array(img)

        if len(img_nd.shape) == 2:
            img_nd = np.expand_dims(img_nd, axis=2)

        # HWC to CHW
        # numpy image: H x W x C
        # torch image: C X H X W
        img_trans = img_nd.transpose((2, 0, 1))
        if img_trans.max() > 1:
            img_trans = img_trans / 255

        return img_trans

    @classmethod
    def preprocess_wo_resize(cls, img):
        img_nd = np.array(img)

        if len(img_nd.shape) == 2:
            img_nd = np.expand_dims(img_nd, axis=0) #(H, W) -> (H, W)
            return img_nd

        # HWC to CHW
        # numpy image: H x W x C
        # torch image: C X H X W
        img_trans = img_nd.transpose((2, 0, 1))
        if img_trans.max() > 1:
            img_trans = img_trans / 255

        return img_trans


# -*- coding: utf-8 -*-
from rdflib import OWL, RDF, RDFS
from rdflib.namespace import Namespace

SH = Namespace('http://www.w3.org/ns/shacl#')

# Classes
RDF_Property = RDF.term('Property')
RDF_List = RDF.term('List')
RDFS_Resource = RDFS.term('Resource')
RDFS_Class = RDFS.term('Class')
OWL_Ontology = OWL.term("Ontology")
OWL_Class = OWL.term("Class")
OWL_DatatypeProperty = OWL.term("DatatypeProperty")
SH_NodeShape = SH.term('NodeShape')
SH_PropertyShape = SH.term('PropertyShape')
SH_ValidationResult = SH.term('ValidationResult')
SH_ValidationReport = SH.term('ValidationReport')
SH_Violation = SH.term('Violation')
SH_Info = SH.term('Info')
SH_Warning = SH.term('Warning')
SH_IRI = SH.term('IRI')
SH_BlankNode = SH.term('BlankNode')
SH_Literal = SH.term('Literal')
SH_BlankNodeOrIRI = SH.term('BlankNodeOrIRI')
SH_BlankNodeORLiteral = SH.term('BlankNodeOrLiteral')
SH_IRIOrLiteral = SH.term('IRIOrLiteral')
SH_ConstraintComponent = SH.term('ConstraintComponent')
SH_SHACLFunction = SH.term('SHACLFunction')
SH_SPARQLFunction = SH.term('SPARQLFunction')
SH_SPARQLRule = SH.term('SPARQLRule')
SH_TripleRule = SH.term('TripleRule')
SH_SPARQLTarget = SH.term('SPARQLTarget')
SH_SPARQLTargetType = SH.term('SPARQLTargetType')
SH_JSTarget = SH.term('JSTarget')
SH_JSTargetType = SH.term('JSTargetType')
SH_JSFunction = SH.term('JSFunction')

# predicates
RDF_type = RDF.term('type')
RDF_first = RDF.term('first')
RDF_rest = RDF.term('rest')
RDF_object = RDF.term('object')
RDF_predicate = RDF.term('predicate')
RDF_subject = RDF.term('subject')
RDFS_subClassOf = RDFS.term('subClassOf')
RDFS_comment = RDFS.term('comment')
SH_path = SH.term('path')
SH_deactivated = SH.term('deactivated')
SH_message = SH.term('message')
SH_name = SH.term('name')
SH_description = SH.term('description')
SH_property = SH.term('property')
SH_node = SH.term('node')
SH_target = SH.term('target')  # from advanced spec
SH_targetClass = SH.term('targetClass')
SH_targetNode = SH.term('targetNode')
SH_targetObjectsOf = SH.term('targetObjectsOf')
SH_targetSubjectsOf = SH.term('targetSubjectsOf')
SH_focusNode = SH.term('focusNode')
SH_resultSeverity = SH.term('resultSeverity')
SH_resultPath = SH.term('resultPath')
SH_resultMessage = SH.term('resultMessage')
SH_sourceConstraint = SH.term('sourceConstraint')
SH_sourceConstraintComponent = SH.term('sourceConstraintComponent')
SH_sourceShape = SH.term('sourceShape')
SH_severity = SH.term('severity')
SH_value = SH.term('value')
SH_conforms = SH.term('conforms')
SH_result = SH.term('result')
SH_inversePath = SH.term('inversePath')
SH_alternativePath = SH.term('alternativePath')
SH_zeroOrMorePath = SH.term('zeroOrMorePath')
SH_oneOrMorePath = SH.term('oneOrMorePath')
SH_zeroOrOnePath = SH.term('zeroOrOnePath')
SH_prefixes = SH.term('prefixes')
SH_prefix = SH.term('prefix')
SH_namespace = SH.term('namespace')
SH_rule = SH.term('rule')
SH_condition = SH.term('condition')
SH_order = SH.term('order')
SH_construct = SH.term('construct')
SH_subject = SH.term('subject')
SH_predicate = SH.term('predicate')
SH_object = SH.term('object')
SH_parameter = SH.term('parameter')
SH_ask = SH.term('ask')
SH_select = SH.term('select')
SH_this = SH.term('this')
SH_filterShape = SH.term('filterShape')
SH_nodes = SH.term('nodes')
SH_union = SH.term('union')
SH_intersection = SH.term('intersection')
SH_datatype = SH.term('datatype')
SH_nodeKind = SH.term('nodeKind')
SH_optional = SH.term('optional')
SH_js = SH.term('js')
SH_jsFunctionName = SH.term('jsFunctionName')
SH_jsLibrary = SH.term('jsLibrary')


from app import db
from app.models import Jogador, Equipa, Jogo, Competicao
import time

jogador = Jogador.query.all()
equipa = Equipa.query.all()
jogo = Jogo.query.all()
competicao = Competicao.query.all()

#JOGADOR
"""
for x in competicao:
     print('ID: ', x.id, ' // NOME: ', x.nome)
"""

#EQUIPA
"""
for e in equipa:
     print('ID: ', e.id, '// NOME: ', e.nome, '// LOCAL: ', e.local)
"""

#print(jogador)
#print(equipa)
#print(jogo)
#print(competicao)

"""
c = Competicao(id=1, nome='Placard')
db.session.add(c)
db.session.commit()

c = Competicao(id=2, nome='TaçaPlacard')
db.session.add(c)
db.session.commit()
"""

"""
c = Competicao.query.get(1)
db.session.delete(c)
db.session.commit()
"""
"""
for x in jogo:
     print('ID: ', x.id, ' // EQUIPA_CASA: ', x.equipa_casa,
     ' // EQUIPA_FORA: ', x.equipa_fora, ' // LOCAL: ', x.local,
     ' // HORA ', x.hora, ' // DATA ', x.data, '// COMPETIÇÃO ', x.competicao)
"""

c = db.engine.execute('select id from competicao')
for i in c:
     i


from tkinter import *
from tkinter import ttk
from datetime import date
import csv
import time
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure

date = date.today() #Get today's date
date = str(date) #Convert to string
month = date[5:7] #Get the month
year = date[0:4] #Get the year
day = date[8:10]
currentBGDS = True
currentLGDS = False
currentBGMI = False
currentBGPS = False
currentBGSI = False

#Convert numerical month to letterical month
Months = {"01":"January",
          "02":"February",
          "03":"March",
          "04":"April",
          "05":"May",
          "06":"June",
          "07":"July",
          "08":"August",
          "09":"September",
          "10":"October",
          "11":"November",
          "12":"December"}

MonthsReverse =  {"January":"01",
                  "February":"02",
                  "March":"03",
                  "April":"04",
                  "May":"05",
                  "June":"06",
                  "July":"07",
                  "August":"08",
                  "September":"09",
                  "October":"10",
                  "November":"11",
                  "December":"12"}

dayInMonths ={"01":31,
              "02":{0:28,
                 1:29},
              "03":31,
              "04":30,
              "05":31,
              "06":30,
              "07":31,
              "08":31,
              "09":30,
              "10":31,
              "11":30,
              "12":31}

DateOfCurrentExpenses = "MonthlyExpense" + month + year + ".txt"
UsedExpensesFile = "UsedExpenses" + month + year + ".txt"
MonthlyItemsFile = "Items" + month + year + ".csv"
TotalDailyExpenditureFile = "DailyExpenditure" + month + year + ".csv"
Title = "Finance Tracker: " + Months[month] + " " + year
CurrentCurrency = "Currency" + month + year + ".txt"

def ReadMonthlyExpense(fileName):
    with open(fileName,"r") as file:
        monthlyExpense = file.read()
        file.close()
    return monthlyExpense

def ReadUsedExpenses(fileName):
    with open(fileName,"r") as file:
        usedExpenses = file.read()
        file.close()
    return usedExpenses

def ReadTDEF(fileName):
    with open(fileName, "r") as TDEF:
        a = csv.reader(TDEF)
        TDEFlist = list(a)
        TDEF.close()
    return TDEFlist

def WriteTDEF(List):
    with open (TotalDailyExpenditureFile, "w", newline='') as TDEF:
        Save = csv.writer(TDEF)
        Save.writerows(List)
        TDEF.close()

def ReadMonthlyItems(fileName):
    with open (fileName, "r") as MIF:
        a = csv.reader(MIF)
        MIFlist = list(a)
        MIF.close()
    return MIFlist

def WriteMonthlyItems(List):
    with open (MonthlyItemsFile, "w", newline='') as MIF:
        Save = csv.writer(MIF)
        Save.writerows(List)
        MIF.close()

def UpperFirsts(s):
    ProperVal = ""
    Skip = True
    ProperVal += s[0].upper()
    Length = len(s)
    for x in range(Length):
        if not Skip:
            ProperVal += s[x]
            if s[x] == " " or s[x] == "/" or s[x] == "-" or s[x] == "_":
                Skip = True
                ProperVal += s[x+1].upper()
        else:
            Skip = False
    return ProperVal

def StringToFloat(List):
    for x in range(len(List)):
        List[x] = float(List[x])
    return List

def maxMessage(List, day):
    print(List[1])
    List[1] = StringToFloat(List[1])
    expensivestIndex = List[1].index(max(List[1]))
    expensivest = List[0][expensivestIndex]
    if day == True:
        expensivestMessage = "The most expensive day \n this month is: "+ "Day " + expensivest +"!"
    else:
        expensivest = UpperFirsts(expensivest)
        expensivestMessage = "The most expensive item you \n bought this month is: "+ expensivest +"!"
    return expensivestMessage

def plotGraph(List, plots, xtitle, ytitle, mainTitle, BGDS, LGDS, BGMI, BGPS, BGSI, barTrue, lineTrue):
    global currentBGDS
    global currentLGDS
    global currentBGMI
    global currentBGPS
    global currentBGSI
    print("behairi")
    print(List[1])
    maxCost = int(max(List[1]))
    remainder = maxCost % 20
    highestYTick = maxCost + (20-remainder)
    increments = int(highestYTick / 20)
    if barTrue == True:
        plots.bar(range(len(List[0])), List[1])
    else:
        plots.plot(range(len(List[0])), List[1])
    plots.set_xticks(range(len(List[0])), minor=False)
    plots.set_xticklabels(List[0], fontdict=None, minor=False)
    if maxCost > 20:
        plots.set_yticks(range(0,highestYTick+1,increments))
    plots.set_xlabel(xtitle)
    plots.set_ylabel(ytitle)
    plots.set_title(mainTitle)
    currentBGDS = BGDS
    currentLGDS = LGDS
    currentBGMI = BGMI
    currentBGPS = BGPS
    currentBGSI = BGSI

def makeGraph(self, BGDS, LGDS, BGMI, BGPS, BGSI, col, rw, rowsp, colsp, TDEfileName, MIfileName, chosenStore):
    graphFigure = Figure(figsize=(10,5), dpi=100)
    dataPlots = graphFigure.add_subplot(111)
    canvas = FigureCanvasTkAgg(graphFigure, self)
##    toolbar = NavigationToolbar2TkAgg(canvas, self)
##    toolbar.update()
##    toolbar.pack()
    canvas.show()
    canvas.get_tk_widget().grid(column=col,row=rw, rowspan=rowsp, columnspan=colsp)

    dataPlots.clear()
    if BGDS == True:
        TDEFlist = ReadTDEF(TDEfileName)
        TDEFlist[1] = StringToFloat(TDEFlist[1])
        plotGraph(TDEFlist, dataPlots, "Day", "Expenditure", "Daily Spendings", True, False, False, False, False, True, False)
        return canvas

    elif LGDS == True:
        TDEFlist = ReadTDEF(TDEfileName)
        TDEFlist[1] = StringToFloat(TDEFlist[1])
        plotGraph(TDEFlist, dataPlots, "Day", "Expenditure", "Daily Spendings", False, True, False, False, False, False, True)
        return canvas

    elif BGMI == True:
        MIFlist = ReadMonthlyItems(MIfileName)
        itemsList = []
        for x in range(len(MIFlist[0])):
            item = UpperFirsts(MIFlist[0][x])
            itemsList.append(item)
        MIFlist[0] = itemsList
        MIFlist[1] = StringToFloat(MIFlist[1])
        plotGraph(MIFlist, dataPlots, "Items", "Expenditure", "Monthly Spendings per Item", False, False, True, False, False, True, False)
        return canvas

    elif BGPS == True:
        MIFlist = ReadMonthlyItems(MIfileName)
        storeList = [[],[]]
        for x in range(2, len(MIFlist)):
            store = UpperFirsts(MIFlist[x][0])
            storeTotalPrice = MIFlist[x][1]
            storeList[0].append(store)
            storeList[1].append(storeTotalPrice)
        storeList[1] = StringToFloat(storeList[1])
        print(storeList)
        plotGraph(storeList, dataPlots, "Stores", "Expenditure", "Monthly Spendings per Store", False, False, False, True, False, True, False)
        return canvas

    elif BGSI == True:
        MIFlist = ReadMonthlyItems(MIfileName)
        itemsList = [[],[]]
        for x in range(2,len(MIFlist)):
            if MIFlist[x][0] == chosenStore:
                for y in range(2, len(MIFlist[x]), 2):
                    itemsList[0].append(MIFlist[x][y])
                    itemsList[1].append(MIFlist[x][y+1])
                break
        itemsList[1] = StringToFloat(itemsList[1])
        xtitle = "Items From " + chosenStore
        plotGraph(itemsList, dataPlots, xtitle, "Expenditure", "Monthly Spendings per Store Item", False, False, False, False, True, True, False)
        return canvas

def NewData(itemEntry, storeEntry, costEntry, passController, RElabel, UElabel, EDlabel, EIlabel, self, BGDS, LGDS, BGMI, BGPS, BGSI):
    item = itemEntry.get()
    store = storeEntry.get()
    totalCost = costEntry.get()

    item = item.lower()
    store = store.lower()

    textfile = open(CurrentCurrency, "r")
    currence = textfile.read()

    try:
        totalCost = float(totalCost)
        try:
            MIFlist = ReadMonthlyItems(MonthlyItemsFile)
            rows = len(MIFlist)
            if item not in MIFlist[0]:
                MIFlist[0].append(item)
                MIFlist[1].append(totalCost)
                for x in range(rows):
                    if store == MIFlist[x][0]:
                        if item not in MIFlist[x]:
                            MIFlist[x].append(item)
                            MIFlist[x].append(totalCost)
                            MIFlist[x][1] = float(MIFlist[x][1]) + totalCost

                        break
                    else:
                        if x == rows-1:
                            MIFlist.append([store, totalCost, item, totalCost])

            else:
                itemIndex = MIFlist[0].index(item)
                for x in range(rows):
                    if store == MIFlist[x][0]:
                        if item not in MIFlist[x]:
                            MIFlist[x].append(item)
                            MIFlist[x].append(totalCost)
                            MIFlist[x][1] = float(MIFlist[x][1]) + totalCost
                        break
                    else:
                        if x == rows-1:
                            MIFlist.append([store, totalCost, item, totalCost])
                MIFlist[1][itemIndex] = float(MIFlist[1][itemIndex]) + totalCost

            WriteMonthlyItems(MIFlist)

            ######

            TDEFlist = ReadTDEF(TotalDailyExpenditureFile)
            dayIndex = TDEFlist[0].index(str(int(day)))
            TDEFlist[1][dayIndex] = float(TDEFlist[1][dayIndex]) + totalCost
            WriteTDEF(TDEFlist)

            #######

            usedExpense = float(ReadUsedExpenses(UsedExpensesFile))
            newUsedExpense = usedExpense + totalCost
            with open(UsedExpensesFile, "w") as UEF:
                UEF.write(str(newUsedExpense))
                UEF.close()

            remainingExpenses = str(float(ReadMonthlyExpense(DateOfCurrentExpenses)) - newUsedExpense)
            remainingExpensesMessage = "You have: " + currence + remainingExpenses + "\n remaining this month!"
            usedExpensesMessage = "You have spent: " + currence + str(newUsedExpense) + "\n this month!"
            TDEFlist = ReadTDEF(TotalDailyExpenditureFile)
            expensivestDayMessage = maxMessage(TDEFlist, True)
            MIFlist = ReadMonthlyItems(MonthlyItemsFile)
            expensivestItemMessage = maxMessage(MIFlist, False)

            #Resets the Entry fields and also updates the info labels at bottom of graph
            itemEntry.delete(0,END)
            storeEntry.delete(0,END)
            costEntry.delete(0,END)

            UpdateItems = []
            for x in range(len(MIFlist[0])):
                UpdateItems.append(UpperFirsts(MIFlist[0][x]))
            itemEntry['values'] = UpdateItems
            UpdateStores = []
            for x in range(2, len(MIFlist)):
                UpdateStores.append(UpperFirsts(MIFlist[x][0]))
            storeEntry['values'] = UpdateStores

            RElabel.config(text=str(remainingExpensesMessage))
            UElabel.config(text=usedExpensesMessage)
            EDlabel.config(text=expensivestDayMessage)
            EIlabel.config(text=expensivestItemMessage)

            makeGraph(self, BGDS, LGDS, BGMI, BGPS, BGSI, 2, 0, 17, 10, TotalDailyExpenditureFile, MonthlyItemsFile, "Kappa")

        except:
            newList = [[item], [totalCost], [store, totalCost, item, totalCost]]
            WriteMonthlyItems(newList)

            newList2 = [[],[]]
            if month == "02":
                isItLeapYear = int(year) % 4
                if isItLeapYear == 0:
                    numberOfDays = dayInMonths[month][1]
                else:
                    numberOfDays = dayInMonths[month][0]
            else:
                numberOfDays = dayInMonths[month]
            for x in range(1, (numberOfDays + 1)):
                newList2[0].append(x)
                newList2[1].append(0)
            dayIndex = newList2[0].index(int(day))
            newList2[1][dayIndex] = float(newList2[1][dayIndex]) + totalCost
            WriteTDEF(newList2)

            ###

            remainingExpensesMessage = "You have: " + currence + str(float(ReadMonthlyExpense(DateOfCurrentExpenses)) - totalCost) + "\n remaining this month!"
            usedExpensesMessage = "You have spent: " + currence + str(totalCost) + "\n this month!"
            TDEFlist = ReadTDEF(TotalDailyExpenditureFile)
            expensivestDayMessage = maxMessage(TDEFlist, True)
            MIFlist = ReadMonthlyItems(MonthlyItemsFile)
            expensivestItemMessage = maxMessage(MIFlist, False)

            with open (UsedExpensesFile, "w") as UEF:
                UEF.write(str(totalCost))
                UEF.close()

            #Resets the Entry fields and also updates the info labels at bottom of graph
            itemEntry.delete(0,END)
            storeEntry.delete(0,END)
            costEntry.delete(0,END)

            UpdateItems = []
            for x in range(len(MIFlist[0])):
                UpdateItems.append(UpperFirsts(MIFlist[0][x]))
            itemEntry['values'] = UpdateItems
            UpdateStores = []
            for x in range(2, len(MIFlist)):
                UpdateStores.append(UpperFirsts(MIFlist[x][0]))
            storeEntry['values'] = UpdateStores

            RElabel.config(text=remainingExpensesMessage)
            UElabel.config(text=usedExpensesMessage)
            EDlabel.config(text=expensivestDayMessage)
            EIlabel.config(text=expensivestItemMessage)

            makeGraph(self, BGDS, LGDS, BGMI, BGPS, BGSI, 2, 0, 17, 10, TotalDailyExpenditureFile, MonthlyItemsFile, "Kappa")

    except:
        messagebox.showerror(title="Input Error!",message="Please input correctly!")

class MainFrame(Tk):

    def __init__(self):
        Tk.__init__(self)

        Tk.title(self, Title)
        Tk.iconbitmap(self, default="fticon2.ico")

        window = Frame(self)
        window.pack(side="top",fill="both",expand=True)
        window.grid_rowconfigure(0, weight=1)
        window.grid_columnconfigure(0, weight=1)

        self.frames = {}

        for x in (NewMonth, Standard, LoadOldDataPage):
            frame = x(window, self)
            self.frames[x] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        try:
            monthlyExpense = ReadMonthlyExpense(DateOfCurrentExpenses)
            self.show_frame(Standard)
        except:
            self.show_frame(NewMonth)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

class NewMonth(Frame): #Completed 100%, perhaps make it look nice

    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        standardCurrency = ["$","$", "£", "€", "₹", "¥", "₩", "IDR", "OMR", "AED"]
        currency2 = StringVar()
        currency2.set(standardCurrency[0])
        self.currencyOption = ttk.OptionMenu(self, currency2, *standardCurrency)

        self.label = ttk.Label(self, text="What is your monthly expenses?").pack()
        self.entry = ttk.Entry(self)
        self.label2 = ttk.Label(self, text="Please enter your currency:")

        self.button = ttk.Button(self, text="ENTER",command=lambda: self.GET(controller, currency2))
        self.entry.pack()
        self.label2.pack()
        self.currencyOption.pack()
        self.button.pack()

    def GET(self,controller, currency2):
        monthlyExpense = self.entry.get()
        standardCurrency = ["$", "£", "€", "IDR", "OMR"]
        currency = currency2.get()
        with open(DateOfCurrentExpenses,"w") as file:
            file.write(monthlyExpense)
            file.close()
        if monthlyExpense == "" and currency == "":
            Pass = False
        else:
            Pass = True
        if Pass:
            try:
                monthlyExpenseINT = int(monthlyExpense)
                if monthlyExpenseINT <= 0:
                    messagebox.showerror(title="Input Error!",message="You can't have minus or zero monthly expenses!")
                else:
                    with open(DateOfCurrentExpenses,"w") as file:
                        file.write(monthlyExpense)
                        file.close()
                    controller.show_frame(Standard)
                    textfile = open(CurrentCurrency, "w")
                    textfile.write(currency)
                    textfile.close()
                    changeInitialLabels()
                    controller.show_frame(Standard)

            except:
                messagebox.showerror(title="Input Error!",message="That is not a number!")
        else:
            messagebox.showerror(title="Input Error!",message="You have left a field blank!")

def changeInitialLabels():
    textfile = open(CurrentCurrency, "r")
    currence = textfile.read()
    monthlyExpense = ReadMonthlyExpense(DateOfCurrentExpenses)
    monthlyExpense = "This month's expenses: " + currence + monthlyExpense
    label2.config(text=monthlyExpense)
    originalMoneys = ReadMonthlyExpense(DateOfCurrentExpenses)
    expenditureLeft = "The expenses you have remaining this month:\n" + currence + originalMoneys +"!"
    RElabel.config(text=expenditureLeft)
    aaa = "The expenses you have used this month:\n" + currence + "0" +"!"
    UElabel.config(text=aaa)

class Standard(ttk.Frame):
    def __init__(self, parent, controller):
        global label2
        global RElabel
        global UElabel
        ttk.Frame.__init__(self, parent)

        try:
            textfile = open(CurrentCurrency, "r")
            currence = textfile.read()
        except:
            currence = "tr"

        #Label texts
        try:
            monthlyExpense = ReadMonthlyExpense(DateOfCurrentExpenses)
            monthlyExpense = "This month's expenses: " + currence + monthlyExpense
        except:
            monthlyExpense="dsa"

        todayDate = "Today is: " + day + "/" + month + "/" + year

        empty = 40*"_"
        #value = StringVar()

        label = ttk.Label(self, text=todayDate)
        label.grid(column=0,row=1, columnspan=2)

        label2 = ttk.Label(self, text=monthlyExpense)
        label2.grid(column=0,row=2, columnspan=2)

        itemLabel = ttk.Label(self, text="Item Name")
        itemLabel.grid(column=0,row=3, columnspan=2)

        StoreLabel = ttk.Label(self, text="Store Name")
        StoreLabel.grid(column=0,row=5, columnspan=2)

        try:
            MIFlist = ReadMonthlyItems(MonthlyItemsFile)
            NewVal = []
            itemEntry = ttk.Combobox(self, textvariable=StringVar())
            for x in range(len(MIFlist[0])):
                NewVal.append(UpperFirsts(MIFlist[0][x]))
            itemEntry['values'] = NewVal
            itemEntry.grid(column=0,row=4, columnspan=2)
            NewVal = []
            storeEntry = ttk.Combobox(self, textvariable=StringVar())
            for x in range(2, len(MIFlist)):
                NewVal.append(UpperFirsts(MIFlist[x][0]))
            storeEntry['values'] = NewVal
            storeEntry.grid(column=0, row=6, columnspan=2)

        except:
            itemEntry = ttk.Combobox(self, textvariable=StringVar())
            itemEntry.grid(column=0,row=4, columnspan=2)
            print("gay fucker")

            storeEntry = ttk.Combobox(self, textvariable=StringVar())
            storeEntry.grid(column=0, row=6, columnspan=2)

        costLabel = ttk.Label(self, text="Total Cost")
        costLabel.grid(column=0,row=7, columnspan=2)

        costEntry = ttk.Entry(self)
        costEntry.grid(column=0,row=8, columnspan=2)

        enterButton = ttk.Button(self, text="ENTER", command=lambda: NewData(itemEntry, storeEntry, costEntry, controller, RElabel, UElabel, EDlabel, EIlabel, self, currentBGDS, currentLGDS, currentBGMI, currentBGPS, currentBGSI))
        enterButton.grid(column=0,row=9, columnspan=2)

        ####bottom left corner
        label12 = ttk.Label(self, text=empty)
        label12.grid(column=0,row=10, columnspan=2)

        GraphControlsLabel = ttk.Label(self, text="Graph Controls")
        GraphControlsLabel.grid(column=0,row=11, columnspan=2)

        GSBbutton = ttk.Button(self, text="Show General Spendings (BG)", command=lambda: self.GraphWork(True, False, False, False, False, 2, 0, 17, 10, TotalDailyExpenditureFile, MonthlyItemsFile, "Kappa"))
        GSBbutton.grid(column=0,row=12, columnspan=2)

        GSLbutton = ttk.Button(self, text="Show General Spendings (LG)", command=lambda: self.GraphWork(False, True, False, False, False, 2, 0, 17, 10, TotalDailyExpenditureFile, MonthlyItemsFile, "Kappa"))
        GSLbutton.grid(column=0,row=13, columnspan=2)

        SPIbutton = ttk.Button(self, text="Show Spendings per Item", command=lambda: self.GraphWork(False, False, True, False, False, 2, 0, 17, 10, TotalDailyExpenditureFile, MonthlyItemsFile, "Kappa"))
        SPIbutton.grid(column=0,row=14, columnspan=2)

        SPSbutton = ttk.Button(self, text="Show Spendings per Store",command=lambda: self.GraphWork(False, False, False, True, False, 2, 0, 17, 10, TotalDailyExpenditureFile, MonthlyItemsFile, "Kappa"))
        SPSbutton.grid(column=0,row=15,columnspan=2)

        SSISbutton = ttk.Button(self, text="Show Spendings per Store Item",command=lambda: self.StorePerItem())
        SSISbutton.grid(column=0,row=16,columnspan=2)

        LPSbutton = ttk.Button(self, text="Load Past Spendings", command=lambda: controller.show_frame(LoadOldDataPage))
        LPSbutton.grid(column=0,row=17, columnspan=2)

        #### end blc

        ####bottom most row

        dash = ttk.Label(self, text=5*"|\n")
        dash.grid(column=2, row=17, rowspan=2, sticky="w")

        try:
            remainingExpenses = str(float(ReadMonthlyExpense(DateOfCurrentExpenses)) - float(ReadUsedExpenses(UsedExpensesFile)))
            remainingExpensesMessage = "You have: " + currence + remainingExpenses + "\n remaining this month!"
            RElabel = Label(self, text=remainingExpensesMessage, borderwidth=2, relief="solid", bg="yellow")
            RElabel.grid(column=3, row=17, rowspan=2)
        except:
            try:
                remainingExpenses = str(float(ReadMonthlyExpense(DateOfCurrentExpenses)))
                remainingExpensesMessage = "You have: " + currence + remainingExpenses + "\n remaining this month!"
                RElabel = Label(self, text=remainingExpensesMessage, borderwidth=2, relief="solid", bg="yellow")
                RElabel.grid(column=3, row=17, rowspan=2)
            except:
                originalMoneys = "32"
                expenditureLeft = "You have: " + currence + originalMoneys + "\n remaining this month!"
                RElabel = Label(self, text=expenditureLeft, borderwidth=2, relief="solid", bg="yellow")
                RElabel.grid(column=3, row=17, rowspan=2)

        try:
            usedExpenses = ReadUsedExpenses(UsedExpensesFile)
            usedExpensesMessage = "You have spent: " + currence + str(usedExpenses) + "\n this month!"
            UElabel = Label(self, text=usedExpensesMessage, borderwidth=2, relief="solid", bg="yellow")
            UElabel.grid(column=5, row=17, rowspan=2)
        except:
            usedExpenses = "0"
            usedExpensesMessage = "You have spent: " + currence + str(usedExpenses) + "\n this month!"
            UElabel = Label(self, text=usedExpensesMessage, borderwidth=2, relief="solid", bg="yellow")
            UElabel.grid(column=5, row=17, rowspan=2)

        try:
            TDEFlist = ReadTDEF(TotalDailyExpenditureFile)
            expensivestDayMessage = maxMessage(TDEFlist, True)
            EDlabel = Label(self, text=expensivestDayMessage, borderwidth=2, relief="solid", bg="yellow")
            EDlabel.grid(column=7, row=17, rowspan=2)
        except:
            expensivestDayMessage = "You haven't spent anything this month!"
            EDlabel = Label(self, text=expensivestDayMessage, borderwidth=2, relief="solid", bg="yellow")
            EDlabel.grid(column=7, row=17, rowspan=2)

        try:
            MIFlist = ReadMonthlyItems(MonthlyItemsFile)
            expensivestItemMessage = maxMessage(MIFlist, False)
            EIlabel = Label(self, text=expensivestItemMessage, borderwidth=2, relief="solid", bg="yellow")
            EIlabel.grid(column=9, row=17, rowspan=2)
        except:
            expensivestItemMessage = "You haven't bought anything this month!"
            EIlabel = Label(self, text=expensivestItemMessage, borderwidth=2, relief="solid", bg="yellow")
            EIlabel.grid(column=9, row=17, rowspan=2)

        ######Canvas and graph time!
        try:
            self.canvas = makeGraph(self, True, False, False, False, False, 2, 0, 17, 14, TotalDailyExpenditureFile, MonthlyItemsFile, "Kappa")
        except:
            self.canvas = Canvas(self, height=500,width=1000,bg="white")
            self.canvas.grid(column=2,row=0, rowspan=17, columnspan=14)

    def GraphWork(self, BGDS, LGDS, BGMI, BGPS, BGSI, col, rw, rowsp, colsp, TDEfileName, MIfileName, lolz):
        self.canvas.get_tk_widget().destroy()
        self.canvas = makeGraph(self, BGDS, LGDS, BGMI, BGPS, BGSI, 2, 0, 17, 14, TotalDailyExpenditureFile, MonthlyItemsFile, lolz)

    def StorePerItem(self):
        self.canvas.get_tk_widget().destroy()

        self.SPIlabel = Label(self, text="Select Store to View")
        MIFlist = ReadMonthlyItems(MonthlyItemsFile)
        storeList = [MIFlist[2][0]]
        for x in range(2, len(MIFlist)):
            storeList.append(MIFlist[x][0])
        print(storeList)
        ShowingStore = StringVar()
        ShowingStore.set(storeList[0])
        self.StoreMenu = ttk.OptionMenu(self, ShowingStore, *storeList)
        self.SPIlabel.grid(column=7, row=6, rowspan=2)
        self.StoreMenu.grid(column=7, row=8, rowspan=2)
        self.SPIbutton = ttk.Button(self, text="ENTER", command=lambda: self.GetStoreAndProceed(ShowingStore))
        self.SPIbutton.grid(column=7, row=10, rowspan=2)

    def GetStoreAndProceed(self, ShowingStore):
        chosenStore = ShowingStore.get()
        self.SPIlabel.destroy()
        self.StoreMenu.destroy()
        self.SPIbutton.destroy()
        self.GraphWork(False, False, False, False, True, 2, 0, 17, 10, TotalDailyExpenditureFile, MonthlyItemsFile, chosenStore)

class LoadOldDataPage(Frame):
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.Options(controller)

    def Options(self, controller):
        MonthsPure = ["January","January","February","March","April","May", "June", "July", "August",
                      "September", "October", "November", "December"]
        YearsPure = ["2013"]
        Years = 2013
        yearINT = int(year)
        for x in range(yearINT - Years + 1):
            YearsPure.append(str(Years))
            Years += 1
        ShowingMonth = StringVar()
        ShowingMonth.set(MonthsPure[0])
        ShowingYear = StringVar()
        ShowingYear.set(YearsPure[0])
        self.label = Label(self, text="Which data would you like to see from?")
        self.MonthMenu = ttk.OptionMenu(self, ShowingMonth, *MonthsPure)
        self.YearMenu = ttk.OptionMenu(self, ShowingYear, *YearsPure)
        self.button = ttk.Button(self, text="ENTER", command=lambda: self.loadGraph(ShowingMonth, ShowingYear, controller))
        self.backButton = ttk.Button(self, text="BACK",command=lambda: controller.show_frame(Standard))
        self.label.pack()
        self.MonthMenu.pack()
        self.YearMenu.pack()
        self.button.pack()
        self.backButton.pack()

    def loadGraph(self,ShowingMonth, ShowingYear,controller):
        selectedMonth = ShowingMonth.get()
        selectedYear = ShowingYear.get()

        selectedMonthN = MonthsReverse[selectedMonth]

        DateOfOldExpenses = "MonthlyExpense" + selectedMonthN + selectedYear + ".txt"
        OldUsedExpensesFile = "UsedExpenses" + selectedMonthN + selectedYear + ".txt"
        self.OldMonthlyItemsFile = "Items" + selectedMonthN + selectedYear + ".csv"
        OldTotalDailyExpenditureFile = "DailyExpenditure" + selectedMonthN + selectedYear + ".csv"
        OldCurrency = "Currency" + selectedMonthN + selectedYear + ".txt"

        try:
            MI2file = ReadMonthlyItems(self.OldMonthlyItemsFile)
            oldExpense = ReadMonthlyExpense(DateOfOldExpenses)
            oldUsedExpense = ReadUsedExpenses(OldUsedExpensesFile)
            TDE2file = ReadTDEF(OldTotalDailyExpenditureFile)

            textfile = open(OldCurrency, "r")
            currence = textfile.read()

            self.label.destroy()
            self.MonthMenu.destroy()
            self.YearMenu.destroy()
            self.button.destroy()
            self.backButton.destroy()

            self.returnButton = ttk.Button(self, text="Return", command=lambda: self.Graph2Options(controller))
            self.DSBG = ttk.Button(self, text="Show General Spendings (BG)", command=lambda: self.InitiateGraph(0, OldTotalDailyExpenditureFile,  self.OldMonthlyItemsFile))
            self.DSLG = ttk.Button(self, text="Show General Spendings (LG)", command=lambda: self.InitiateGraph(1, OldTotalDailyExpenditureFile,  self.OldMonthlyItemsFile))
            self.SIBG = ttk.Button(self, text="Show Spendings per Item", command=lambda: self.InitiateGraph(2, OldTotalDailyExpenditureFile,  self.OldMonthlyItemsFile))
            self.SpS = ttk.Button(self, text="Show Spendings per Store", command=lambda: self.InitiateGraph(3, OldTotalDailyExpenditureFile,  self.OldMonthlyItemsFile))
            self.SpSI = ttk.Button(self, text="Show Spendings per Store Item", command=lambda: self.InitiateGraph(4, OldTotalDailyExpenditureFile,  self.OldMonthlyItemsFile))
            self.returnButton.grid(column=0,row=0, columnspan=2)
            self.graphL = Label(self, text="Graph Controls")
            self.graphL.grid(column=0,row=2, columnspan=2)
            self.DSBG.grid(column=0,row=3, columnspan=2)
            self.DSLG.grid(column=0,row=4, columnspan=2)
            self.SIBG.grid(column=0,row=5, columnspan=2)
            self.SpS.grid(column=0,row=6, columnspan=2)
            self.SpSI.grid(column=0,row=7, columnspan=2)

            print("n")
            self.canvas = makeGraph(self, True, False, False, False, False, 2, 0, 17, 14, OldTotalDailyExpenditureFile,  self.OldMonthlyItemsFile, "Kappa")
            print("n")
            oldRemainingExpenses = str(float(oldExpense) - float(oldUsedExpense))
            print("n")
            saved = "You saved " + currence + oldRemainingExpenses + " this month!"
            print("n")
            spent = "You spent " + currence + str(oldUsedExpense) + " this month!"
            print("n")
            expensivestDay = maxMessage(TDE2file, True)
            print("n")
            expensivestItem = maxMessage(MI2file, False)

            self.ODlabel = Label(self, text=saved, borderwidth=2, relief="solid", bg="yellow")
            self.ODlabel2 = Label(self, text=spent, borderwidth=2, relief="solid", bg="yellow")
            self.ODlabel3 = Label(self, text=expensivestDay, borderwidth=2, relief="solid", bg="yellow")
            self.ODlabel4 = Label(self, text=expensivestItem, borderwidth=2, relief="solid", bg="yellow")
            self.ODlabel.grid(column=0, row=9, columnspan=2)
            self.ODlabel2.grid(column=0, row=11, columnspan=2)
            self.ODlabel3.grid(column=0, row=13, columnspan=2)
            self.ODlabel4.grid(column=0, row=15, columnspan=2)

        except:
            messagebox.showerror(title="Files not found!",message="You do not have any data in this time period!")

    def InitiateGraph(self, a, fileA, fileB):
        self.canvas.get_tk_widget().destroy()
        if a == 0:
            self.canvas = makeGraph(self, True, False, False, False, False, 2, 0, 17, 14, fileA,  fileB, "Kappa")
        elif a == 1:
            self.canvas = makeGraph(self, False, True, False, False, False, 2, 0, 17, 14, fileA,  fileB, "Kappa")
        elif a == 2:
            self.canvas = makeGraph(self, False, False, True, False, False, 2, 0, 17, 14, fileA,  fileB, "Kappa")
        elif a == 3:
            self.canvas = makeGraph(self, False, False, False, True, False, 2, 0, 17, 14, fileA,  fileB, "Kappa")
        else:
            self.StorePerItem(fileA)

    def Graph2Options(self, controller):
        self.returnButton.destroy()
        self.graphL.destroy()
        self.DSBG.destroy()
        self.DSLG.destroy()
        self.SIBG.destroy()
        self.SpS.destroy()
        self.SpSI.destroy()
        self.canvas.get_tk_widget().destroy()
        self.ODlabel.destroy()
        self.ODlabel2.destroy()
        self.ODlabel3.destroy()
        self.ODlabel4.destroy()
        self.Options(controller)

    def StorePerItem(self, TotalDailyExpenditureFile):
        self.canvas.get_tk_widget().destroy()

        self.SPIlabel = Label(self, text="Select Store to View")
        MIFlist = ReadMonthlyItems(self.OldMonthlyItemsFile)
        storeList = [MIFlist[2][0]]
        for x in range(2, len(MIFlist)):
            storeList.append(MIFlist[x][0])
        print(storeList)
        ShowingStore = StringVar()
        ShowingStore.set(storeList[0])
        self.StoreMenu = ttk.OptionMenu(self, ShowingStore, *storeList)
        self.SPIlabel.grid(column=7, row=6, rowspan=2)
        self.StoreMenu.grid(column=7, row=8, rowspan=2)
        self.SPIbutton = ttk.Button(self, text="ENTER", command=lambda: self.GetStoreAndProceed(ShowingStore, TotalDailyExpenditureFile))
        self.SPIbutton.grid(column=7, row=10, rowspan=2)

    def GetStoreAndProceed(self, ShowingStore, TotalDailyExpenditureFile):
        chosenStore = ShowingStore.get()
        self.SPIlabel.destroy()
        self.StoreMenu.destroy()
        self.SPIbutton.destroy()
        self.canvas = makeGraph(self, False, False, False, False, True, 2, 0, 17, 10, TotalDailyExpenditureFile, self.OldMonthlyItemsFile, chosenStore)

app = MainFrame()
app.mainloop()

raise SystemExit(0)


#!/usr/bin/env python3
from __future__ import print_function
from math import trunc
from time import sleep
import sys
import codecs

from periphery import I2C

TCA9548_U93_ADDR = 0x70 #1110_000X  0XE0
SENSOR_IIC_BUS   = 0x01

def set_i2c_mux(dev_addr,channel):
  i2c = I2C("/dev/i2c-1")
  i2c.transfer(dev_addr, [I2C.Message([channel])])
  i2c.close()

def ad7414_reg_write(dev_addr,reg_addr,reg_value):
  i2c = I2C("/dev/i2c-1")
  i2c.transfer(dev_addr, [I2C.Message([reg_addr, reg_value])]) # SENSOR_IIC_BUS is selected
  i2c.close()

def ad7414_reg_read(dev_addr,reg_addr,nbits):
  i2c = I2C("/dev/i2c-1")
  read = I2C.Message([0x0]*nbits, read=True)
  i2c.transfer(dev_addr, [I2C.Message([reg_addr]), read]) # reg for read
  i2c.close()
  return codecs.encode(bytes(bytearray(read.data)), 'hex')

def ad7414_mon(dev_addr):
  #set the I2C Mux to SENSOR_IIC_BUS 0x01
  set_i2c_mux(TCA9548_U93_ADDR,SENSOR_IIC_BUS)

  ad7414_reg_write(dev_addr,0x1,0x48) #alert active low
  ad7414_reg_write(dev_addr,0x2,0x3F) #up limit is 63 Degree
  ad7414_reg_write(dev_addr,0x3,0x80) #low limit is 0 degree
  temperature=ad7414_reg_read(dev_addr,0x0,1)#read the temperature value
  return int(temperature,16)

def ltc2499_temp_mon(dev_addr,reg_addr0,reg_addr1):
  #set the I2C Mux to SENSOR_IIC_BUS 0x01 PUT INSIDE METHOD
  set_i2c_mux(TCA9548_U93_ADDR,SENSOR_IIC_BUS)

  # two delays as the chip is slow
  sleep(0.5)
  i2c = I2C("/dev/i2c-1")
  i2c.transfer(dev_addr, [I2C.Message([reg_addr1,reg_addr0])])# Reg for read
  sleep(0.5)

  read = I2C.Message([0x0]*4, read=True)
  i2c.transfer(dev_addr, [read])
  i2c.close()
  adc_code=int(codecs.encode(bytes(bytearray(read.data)),'hex'), 16)

  resolution=2500./0x80000000
  amplitude=(adc_code-0x40000000)*resolution
  if(adc_code==0x3FFFFFFF): amplitude=-1

  temperature= 326-0.5*amplitude
  return temperature


from Bio import SeqIO
import sys

# Author: Charlotte Capitanchik
# adds ptms to tRNA file

fasta = sys.argv[1]
fasta_sequences = SeqIO.parse(open(fasta), 'fasta')
new_file = sys.argv[2]
f_file = open(new_file,"w")

# Read the fasta file as a dictionary

for f in fasta_sequences:
    name, sequence = f.id, f.seq
    sequence = str(sequence).upper()
    if sequence[-3:] != "CCA":
        sequence = sequence + "CCA"
    if name.find("His") != -1:
        sequence = "G" + sequence
    f_file.write(">"+name+"\n"+sequence+"\n")

f_file.close()


class Solution(object):
    def kSmallestPairs(self, nums1, nums2, k):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :type k: int
        :rtype: List[List[int]]
        """
        if k == 0 or len(nums1) == 0 or len(nums2) == 0:
            return []
        import heapq
        h = []
        for i in nums1:
            for j in nums2:
                heapq.heappush(h, (i + j, [i, j]))
        res = []
        for _ in range(min(k, len(nums1) * len(nums2))):
            res.append(heapq.heappop(h)[1])
        return res


JSON_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
SIMPLE_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S%z"
SIMPLE_DATE_FORMAT = "%Y-%m-%d"

# Event names for the UserActivityData table
UMR_OPEN_ARTICLE_ACTION = "UMR - OPEN ARTICLE"
UMR_OPEN_STARRED_ARTICLE_ACTION = "UMR - OPEN STARRED ARTICLE"
UMR_ARTICLE_FOCUSED_ACTION = "UMR - ARTICLE FOCUSED"
UMR_ARTICLE_CLOSED_ACTION = "UMR - ARTICLE CLOSED"

UMR_TRANSLATE_TEXT_ACTION = "UMR - TRANSLATE TEXT"
UMR_SPEAK_TEXT_ACTION = "UMR - SPEAK TEXT"
UMR_OPEN_ALTERMENU_ACTION = "UMR - OPEN ALTERMENU"
UMR_CLOSE_ALTERMENU_ACTION = "UMR - CLOSE ALTERMENU"
UMR_UNDO_TEXT_TRANSLATION_ACTION = "UMR - UNDO TEXT TRANSLATION"
UMR_SEND_SUGGESTION_ACTION = "UMR - SEND SUGGESTION"
UMR_CHANGE_ORIENTATION_ACTION = "UMR - CHANGE ORIENTATION"
UMR_STAR_ARTICLE_ACTION = "UMR - STAR ARTICLE"
UMR_LIKE_ARTICLE_ACTION = "UMR - LIKE ARTICLE"

UMR_ARTICLE_LOST_FOCUS_ACTION = "UMR - ARTICLE LOST FOCUS"
UMR_USER_FEEDBACK_ACTION = "UMR - USER FEEDBACK"
UMR_WORDS_REVIEW = "UMR - WORDS REVIEW"

UMR_UNFOLLOW_FEED = "UMR - UNFOLLOW FEED"

# Event types for word_knowledge/WordInteractionHistory
WIH_READ_CLICKED = 0
WIH_READ_NOT_CLICKED_IN_SENTENCE = 1
WIH_READ_NOT_CLICKED_OUT_SENTENCE = 2
WIH_CORRECT_EX_RECOGNIZE = 3
WIH_CORRECT_EX_TRANSLATE = 4
WIH_CORRECT_EX_CHOICE = 5
WIH_CORRECT_EX_MATCH = 6
WIH_WRONG_EX_RECOGNIZE = 7
WIH_WRONG_EX_TRANSLATE = 8
WIH_WRONG_EX_CHOICE = 9
WIH_WRONG_EX_MATCH = 10

# time delta in which consecutive bookmarks are merged together
TIMEDELTA = 120

UMR_ARTICLES_REQUESTED_FROM_ZEEGUU = "UMR - ARTICLES REQUESTED FROM ZEEGUU"
UMR_USER_SCROLL_ACTION = "UMR - SCROLL"


"""
Mango Python Library Client
"""
import json

import requests
from requests.exceptions import ConnectionError

from .error import UnableToConnect, AuthenticationError, NotFound, \
    InputValidationError, InputValidationGenericError, \
    UnhandledError, MethodNotAllowed

BASE_URL = "https://api.getmango.com"
HEADERS = {"content-type": "application/json"}

def req(api_key, method, endpoint, data=None, params=None):
    """
    Make request and return a Python object from the JSON response. If
    HTTP method is DELETE return True for 204 response, false otherwise.

    :param api_key: String with the API key
    :param method: String with the HTTP method
    :param endpoint: String with the URL
    :param data: Dictionary with data that will be sent
    :param params: Dictionary with query strings
    :return: Native python object resulting of the JSON deserialization of the API response
    """
    if data:
        data = json.dumps(data)

    try:
        response = requests.request(
            method,
            build_url(endpoint),
            data=data,
            params=params,
            auth=(api_key, ""),
            headers=HEADERS
        )
    except ConnectionError:
        raise UnableToConnect

    # Success
    if 200 <= response.status_code <= 206:
        if response.request.method == "DELETE":
            return response.status_code == 204 or response.status_code == 200

        return response.json()

    # Error handling
    if response.status_code == 400:
        try:
            input_validation_error = response.json()
            errors = input_validation_error.get("errors")[0]
            error_code, error_message = errors.items()[0]
        except:
            raise InputValidationGenericError("{status_code}: {text}".format(
                status_code=response.status_code,
                text=response.text
            ))
        raise InputValidationError(error_code, error_message)
    elif response.status_code == 401:
        raise AuthenticationError
    elif response.status_code == 404:
        raise NotFound
    elif response.status_code == 405:
        raise MethodNotAllowed

    raise UnhandledError("{status_code}: {text}".format(
        status_code=response.status_code,
        text=response.text
    ))

def build_url(endpoint):
    """
    Build complete URL from API endpoint

    :param endpoint: String with the endpoint, ex: /v1/charges/
    :return: String with complete URL, ex: https://api.getmango.com/v1/charges/
    """
    return "{base_url}/{endpoint}".format(
        base_url=BASE_URL,
        endpoint=endpoint
    )


from PyQt5.QtCore import QRectF
from enum import Enum
import re

class Tile(Enum):
    grass = 0
    wall = 1
    stone = 2
    sand = 3
    dark_sand = 4
    sand_stone = 5
    snow = 6
    ice = 7
    stonewall = 8
    fire = 9

    def walkable(self):
        return self in [Tile.grass, Tile.sand, Tile.dark_sand, Tile.snow, Tile.stone]
    def shootable(self):
        return self in [Tile.grass, Tile.sand, Tile.dark_sand, Tile.snow, Tile.stone, Tile.ice]

class LevelLoader:

    LEVEL_SIZE = 100
    TILE_SIZE = 10

    META_DATA_TAGS = ['single_spawn', 'duel_spawns', 'chaser_spawns']
    META_DATA_DEFAULT_VALUES = {'single_spawn' : (50,50), 'duel_spawns' : [(10,50),(90,50)], 'chaser_spawns' : [(50,20),(20,50),(70,50)]}

    # Reads a txt file and creates an 2 dimensional array representing a level
    # A '0' represents free space, a '1' represents a wall
    @classmethod
    def loadLevel(self, filePath):
        levelMatrix = []
        rects = []
        metadata = {}

        # construct regex pattern
        pattern = '(?P<name>'
        for tag in self.META_DATA_TAGS:
            pattern += tag + '|'
        pattern = pattern[:-1] # remove last '|'
        pattern += ')'
        pattern += ':\s*(?P<data>.*)'

        with open(filePath, "r") as fileObject:
            for line in fileObject:
                if line.startswith('\n'):
                    continue

                match = re.match(pattern, line)
                if match:
                    # if it matches, the line contains metadata
                    tag = match.group('name')
                    if tag in self.META_DATA_TAGS:
                        metadata[tag] = eval(match.group('data'))
                    else:
                        raise Exception('Unknown tag name: "' + tag + '" in level "' + filePath + '"')
                else:
                    # else it contains level data
                    row = []
                    for c in line:
                        if c == '\n':
                            continue
                        try:
                            tileNum = int(c)
                            row.append(Tile(tileNum))
                        except:
                            raise Exception('Unknown symbol: "' + c + '" in level "' + filePath + '"')
                    levelMatrix.append(row)

        # construct obstacle list
        for i in range(self.LEVEL_SIZE):
            for j in range(self.LEVEL_SIZE):
                if levelMatrix[i][j] == Tile.wall:
                    new_rect = QRectF(j * self.TILE_SIZE, i * self.TILE_SIZE,
                                          self.TILE_SIZE, self.TILE_SIZE)

                    # Check if the rect would already be covered by one of our rects
                    if any(rect.contains(new_rect) for rect in rects):
                        continue

                    # Explore right and down to cover more walls in one square
                    n=0
                    while all(all(x == Tile.wall for x in column[j:j+n]) for column in levelMatrix[i:i+n]):
                        n += 1

                    rects.append(QRectF(j * self.TILE_SIZE, i * self.TILE_SIZE,
                                        (n-1) * self.TILE_SIZE, (n-1) * self.TILE_SIZE))

        # fill in missing metadata with default values
        for tag in self.META_DATA_TAGS:
            if tag not in metadata:
                metadata[tag] = self.META_DATA_DEFAULT_VALUES[tag]

        return levelMatrix, rects, metadata


#!/usr/bin/python -tt
# -*- coding: utf-8 -*-

import flask, json

app = flask.Flask(__name__)

posts = [
			{
				u"userId": 1,
				u"id": 1,
				u"title": u"Título 1",
				u"body": u"Mensaje 1"
			},
			{
				u"userId": 1,
				u"id": 2,
				u"title": u"Título 2",
				u"body": u"Mensaje 2"
			},
			{
				u"userId": 1,
				u"id": 3,
				u"title": u"Título 3",
				u"body": u"Mensaje 3"
			},
			{
				u"userId": 1,
				u"id": 4,
				u"title": u"Título 4",
				u"body": u"Mensaje 4"
			},
			{
				u"userId": 1,
				u"id": 5,
				u"title": u"Título 5",
				u"body": u"Mensaje 5"
			},
			{
				u"userId": 2,
				u"id": 6,
				u"title": u"Título 6",
				u"body": u"Mensaje 6"
			},
			{
				u"userId": 2,
				u"id": 7,
				u"title": u"Título 7",
				u"body": u"Mensaje 7"
			},
			{
				u"userId": 2,
				u"id": 8,
				u"title": u"Título 8",
				u"body": u"Mensaje 8"
			},
			{
				u"userId": 2,
				u"id": 9,
				u"title": u"Título 9",
				u"body": u"Mensaje 9"
			},
			{
				u"userId": 2,
				u"id": 10,
				u"title": u"Título 10",
				u"body": u"Mensaje 10"
			},
			{
				u"userId": 3,
				u"id": 11,
				u"title": u"Título 11",
				u"body": u"Mensaje 11"
			},
			{
				u"userId": 3,
				u"id": 12,
				u"title": u"Título 12",
				u"body": u"Mensaje 12"
			},
			{
				u"userId": 3,
				u"id": 13,
				u"title": u"Título 13",
				u"body": u"Mensaje 13"
			},
			{
				u"userId": 3,
				u"id": 14,
				u"title": u"Título 14",
				u"body": u"Mensaje 14"
			},
			{
				u"userId": 3,
				u"id": 15,
				u"title": u"Título 15",
				u"body": u"Mensaje 15"
			}
		]

users = [
			{
				u"id": 1,
				u"name": u"Leanne Graham",
				u"username": u"Bret"
			},
			{
				u"id": 2,
				u"title": u"Ervin Howell",
				u"username": u"Antonette"
			},
			{
				u"id": 3,
				u"name": u"Clementine Bauch",
				u"username": u"Samantha"
			}
		]

def getPostsUserId(userId):
	postsUser = []
	try:
		id = int(userId)
		for post in posts:
			if post["userId"] == id:
				postsUser.append(post)
		return json.dumps(postsUser)
	except:
		return json.dumps(postsUser), 404

@app.route("/")
def index():
	return u"Bienvenido a mi servidor REST"

@app.route("/posts")
def getPosts():
	query_string = flask.request.args
	if "userId" in query_string:
		return getPostsUserId(query_string["userId"])
	else:
		return json.dumps(posts)

@app.route("/posts/<id>")
def getPostsId(id):
	try:
		if (int(id) > len(posts)) or (int(id) < 1):
			return json.dumps({}), 404
		else:
			return json.dumps(posts[int(id) - 1])
	except:
		return json.dumps({}), 404

@app.route("/users")
def getUsers():
	return json.dumps(users)

@app.route("/users/<id>")
def getUsersId(id):
	try:
		if (int(id) > len(users)) or (int(id) < 1):
			return json.dumps({}), 404
		else:
			return json.dumps(users[int(id) - 1])
	except:
		return json.dumps({}), 404

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


import argparse
import cmath
import logging
import math
import pathlib
import random
import shutil

import h5py
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.cuda as cuda
import torch.nn as nn
from skimage.measure import compare_ssim as ssim
from tensorboardX import SummaryWriter
from torch.autograd import Variable
from torch.nn import functional as F
from torch.utils.data import Dataset

import utils
from data import transforms
from anet_model import AnetModel
from args import get_args

args = get_args()
train_loader, dev_loader = utils.create_data_loaders(args)

# ### Custom dataset class

def build_model(args):
    model = AnetModel(
        in_chans=2,
        out_chans=2,
        chans=args.num_chans,
        num_pool_layers=args.num_pools,
        drop_prob=args.drop_prob
    ).to(args.device)
    return model

# def build_optim(args, params):
#     optimizer = torch.optim.RMSprop(params, args.learning_rate, weight_decay=args.weight_decay)
#     return optimizer

# def load_model(checkpoint_file):
#     checkpoint = torch.load(checkpoint_file)
#     args = checkpoint['args']
#     model = build_model(args)
#     model.load_state_dict(checkpoint['model'])

#     optimizer = build_optim(args, model.parameters())
#     optimizer.load_state_dict(checkpoint['optimizer'])
#     return checkpoint, model, optimizer

# ### Image normalized

loss_func = nn.MSELoss()
best_val_loss = 1e9
writer = SummaryWriter(log_dir=args.exp_dir+'/summary')
valid_loss=[]
train_loss=[]
print('Total number of epochs:', args.epoch)
print('Total number of training iterations: ',len(train_loader))
print('Total number of validation iterations: ',len(dev_loader))

if args.resume:
    checkpoint, model, optimizer = utils.load_model(args.exp_dir + "/best_model.pt", build_model(args))
    best_dev_loss = checkpoint['best_dev_loss']
    start_epoch = checkpoint['epoch']
    if checkpoint['state']=='train':
        train = False
    del checkpoint
else:
    model = build_model(args)
    # if args.data_parallel:
        # model = torch.nn.DataParallel(model)
    optimizer = utils.build_optim(args, model.parameters())
    best_dev_loss = 1e9
    start_epoch = 0
    train = True

print(model)

# if args.resume:
#     checkpoint, model optimizer = load_model(args.checkpoint)
#     #best_val_loss = checkpoint['best_val_loss']
#     start_epoch = checkpoint['epoch']
#     if checkpoint['state']=='train':
#         train = False
#     del checkpoint
# else:
#     encoder = Encoder().cuda()
#     decoder = Decoder().cuda()
#     parameters = list(encoder.parameters())+ list(decoder.parameters())
#     optimizer = torch.optim.Adam(parameters, lr=args.learning_rate)
#     start_epoch = 0
#     train = True

for i in range(start_epoch, args.epoch):
    print("Epoch: ",i)
    global_step = i * len(train_loader)
    ##########################################TRAINING PHASE######################################################
    if train:
        print("Training Phase")
        total_loss_kspace = total_loss_image = 0.0
        model.train()
        for j, data in enumerate(train_loader):
            original_kspace, masked_kspace, mask, target, fname, slice_index = data

            # preprocessing the kspace (input)
            if args.preprocess == "unitize":
                nmasked_kspace, divisor = utils.unitize(masked_kspace)
                noriginal_kspace, divisor = utils.unitize(original_kspace, divisor)
            elif args.preprocess == "standardize":
                nmasked_kspace, mean, std = utils.standardize(masked_kspace)
                noriginal_kspace, mean, std = utils.standardize(original_kspace, mean, std)

            # transforming the input according to dimension and type
            noriginal_kspace, nmasked_kspace = utils.transformshape(noriginal_kspace), utils.transformshape(nmasked_kspace)

            nmasked_kspace = Variable(nmasked_kspace).to(args.device)
            noriginal_kspace = Variable(noriginal_kspace).to(args.device)

            # forward pass
            outputkspace = model(nmasked_kspace)

            # finding the kspace loss
            loss_kspace = loss_func(outputkspace, noriginal_kspace)
            loss_image = loss_func(utils.kspaceto2dimage(utils.transformback(outputkspace), args.polar), utils.kspaceto2dimage(utils.transformback(noriginal_kspace), args.polar))

            # setting up all the gradients to zero
            optimizer.zero_grad()

            #backward pass
            (loss_kspace + 3.0*loss_image).backward()
            optimizer.step()

            total_loss_kspace += loss_kspace.data.item()
            total_loss_image += loss_image.data.item()
            if j % 100 == 0:
                avg_loss_kspace, avg_loss_image = total_loss_kspace/(j + 1), total_loss_image/(j + 1)
                print(j+1, ': AVG TRAINING LOSS: Kspace:', avg_loss_kspace, 'Image', avg_loss_image, 'ITR LOSS: Kspace', loss_kspace.data.item(), 'Image', loss_image.data.item())

                if j % 500 == 0:
                    utils.compareimageoutput(original_kspace, masked_kspace, outputkspace, mask, writer, global_step + j + 1, 0, args.polar)
            writer.add_scalar('TrainKspaceLoss', loss_kspace.data.item(), global_step + j+1)
            writer.add_scalar('TrainImageLoss', loss_image.data.item(), global_step + j+1)
        utils.save_model(args, args.exp_dir, i+1 , model, optimizer, best_val_loss, False, 'train')
        # train_loss.append(total_loss_kspace/len(train_loader))
    train = True

    ################################VALIDATION#######################################################
    print("Validation Phase")
    # validation loss
    total_val_loss = 0.0
    model.eval()
    for j,data in enumerate(dev_loader):
        original_kspace, masked_kspace, mask, target, fname, slice_index = data

        # preprocessing the kspace (input)
        if args.preprocess == "unitize":
            nmasked_kspace, divisor = utils.unitize(masked_kspace)
            noriginal_kspace, divisor = utils.unitize(original_kspace, divisor)
        elif args.preprocess == "standardize":
            nmasked_kspace, mean, std = utils.standardize(masked_kspace)
            noriginal_kspace, mean, std = utils.standardize(original_kspace, mean, std)

        # transforming the input according to dimension and type
        noriginal_kspace, nmasked_kspace = utils.transformshape(noriginal_kspace), utils.transformshape(nmasked_kspace)

        nmasked_kspace = Variable(nmasked_kspace).to(args.device)
        noriginal_kspace = Variable(noriginal_kspace).to(args.device)

        # forward pass
        outputkspace = model(nmasked_kspace)

        # finding the kspace loss
        loss_kspace = loss_func(outputkspace, noriginal_kspace)
        loss_image = loss_func(utils.kspaceto2dimage(utils.transformback(outputkspace), args.polar), utils.kspaceto2dimage(utils.transformback(noriginal_kspace), args.polar))

        loss_itr = loss_kspace.data.item() + loss_image.data.item()

        total_val_loss += loss_itr

        if j % 100 == 0:
            avg_loss = total_val_loss/(j+1)
            print(j+1, ': AVG VALIDATION LOSS:', avg_loss, 'ITR LOSS:', loss_itr)
            if j % 200 == 0:
                utils.compareimageoutput(original_kspace,masked_kspace,outputkspace,mask,writer,global_step + j+1, 0, args.polar)

        writer.add_scalar('ValidationLoss', loss_itr, global_step + j+1)

    valid_loss.append(total_val_loss / len(dev_loader))

    print('saving')
    is_new_best = valid_loss[-1] < best_val_loss
    best_val_loss = min(best_val_loss, valid_loss[-1])
    print("best val loss :",best_val_loss)
    utils.save_model(args, args.exp_dir, i+1, model, optimizer, best_val_loss, is_new_best, 'valid')
writer.close()