import h5py
import numpy as np
import matplotlib
matplotlib.use('TkAgg')

import sys
import pylab as plt
plt.ion()

from time import sleep

gamma = 5.0 / 3
pertA = 0.0004
pertA = pertA * gamma

ylim = (-pertA,pertA)
#ylim = (1.0 - pertA,1.0 + pertA)

def getDim(f):
	n = 0
	for ff in f:
		if  ff is None:
			n=n+1
	return n

def plotData(fig, ax, filename, dsetnames, fixed=[None,None,None], savePng = False):
	h5file = h5py.File(filename, 'r')

	i = 0
	for dsetname in dsetnames:
		dataset = h5file[dsetname]

		#print("MAX OF DATASET %e at %d" % (np.max(dataset),np.argmax(dataset)) )

		if fixed[0] is None:
			if fixed[1] is None:
				if fixed[2] is None:
					arr = dataset[()]
				else:
					#fixed0 = None , fixed1 = None, projection along fixed2
					arr = dataset[:,:,fixed[2]]
			else:
				#fixed0=None, fixed1 != None
				if fixed[2] is None:
				#fixed0=None, fixed1 != None, fixed2 = None
					arr = dataset[:,fixed[1],:]
				else:
				#fixed0=None, fixed1 != None, fixed2 != None
					arr = dataset[:,fixed[1],fixed[2]]
					#dx = dataset.attrs["dx"]

		else:
			#fixed0 !=None
			if fixed[1] is None:
				if fixed[2] is None:
					#fixed0!=None, fixed1=None, fixed2 = None
					arr = dataset[fixed[0],:,:]
				else:
					#fixed0 != None , fixed1 = None, projection along fixed2
					arr = dataset[fixed[0],:,fixed[2]]
			else:
				#fixed0!=None, fixed1 != None
				if fixed[2] is None:
				#fixed0!=None, fixed1 != None, fixed2 = None
					arr = dataset[fixed[0],fixed[1],:]
				else:
				#fixed0!=None, fixed1 != None, fixed2 != None
					arr = dataset[fixed[0],fixed[1],fixed[2]]

		#print("MAX OF arr %e at %d" % (np.max(arr),np.argmax(arr)) )

		if len(arr.shape) == 1:
			ax[i].cla()
			ax[i].grid(True)
			x = np.linspace(0,1,len(arr))
	#		ax.hlines(ylim, np.min(x), np.max(x))
	#		ax.set_ylim(ylim)
			ax[i].plot(x,arr,label=dsetname)
			ax[i].legend()
		elif (len(arr.shape) == 2):
			ax[i].cla()
			ax[i].set_title(dsetname)
			ax[i].imshow(arr, origin='lower')
		elif (len(arr.shape) == 3):
			print("NOT IMPLEMENTED")

		plt.suptitle("time %f"%h5file.attrs["time"] )
		i=i+1
		#save file
		if savePng:
			fn = filename[:-3]
			ind = fn.index("_")
			n = int(fn[ind+1:])
			newfn = "%s%05d.png" % (fn[:ind+1],n)
			plt.savefig(newfn)

		fig.canvas.draw()
		plt.draw()

		plt.show()

	h5file.close()
plt.show()

def plotDataSeq(basename,start,end,dset,fixed,step=1, savePng=False):
	n = getDim(fixed)
	if n == 1:
		if(True):
			fig = plt.figure(1,figsize=(10,10))
			ax1 = fig.add_subplot(111)
			ax = []
			for i in range(len(dset)):
				ax.append(ax1)
			else:
				fig, ax = plt.subplots(nrows=len(dset), ncols=1, figsize=(20,10))
	elif n == 2:
		#fig, ax = plt.subplots(nrows=len(dset), ncols=1, figsize=(20,10))
		fig, ax1 = plt.subplots(nrows=int(np.floor(len(dset)/3)), ncols=3, figsize=(20,10))
		ax = []
		for i in range(ax1.shape[0]):
			for j in range(ax1.shape[1]):
				ax.append(ax1[i,j])
	else:
		print("NOT IMPLEMENTED ")
		sys.exit(0)
	print("FIXED DIM = %d" % n)
	for i in np.arange(start,end+1,step):
		fn = "%s%d.h5" % (basename,i)
		plotData(fig, ax,fn,dset,fixed,savePng)
		#sleep(2)

#plt.ion()
#plotData("pmytestfile.h5", ["bx"], [0,None,None])
#sleep(100)
#plotData("recon_2.h5", ["vx_n"], [0,None,None])
#sleep(100)
#plt.show(block=False)
plotDataSeq("recon_",1,23000,["rho_c", "rho_n", "B2_t", "vx_n", "vx_c", "vy_n", "vy_c", "temp_c", "temp_n", "eint_c", "eint_n", "jz"],[0,None,None],1, savePng=False)
#plotDataSeq("pmytestfile",0,0,["rho"],[0,None,None],1, savePng=False)


__author__ = "Nikola"

from ComplexQuery.PolishNotation import isOperator
from Set.set import arrayToSet

class ComplexParser(object):
    """
        Parser used to parse a given complex query array, and turn it into a set-contained Polish notation array.
        Resulting polish-notation array is then used to calculate the resulting set, using the class
        PolishNotation.
        Correct format example is:
            python && java || ( clojure && ! sql )
                ~ Spaces between tokens are not necessary.
    """

    def __init__(self, loader):
        self.output = []
        self.stack = []
        self.loader = loader

    def parseQuery(self, query):
        """
            Parses the complex query. Word tokens are pushed to the self.output (later used by PolishNotation object)
            Operator tokens need to behave according to the algorithm rules, which are defined in the pushOperator()
            function. After the function, self.output contains an array-like expression in Reverse-Polish form.
        """
        self.output.clear()

        for token in query:
            if not isOperator(token):
                _list = self.loader.trie.findContainingPages(token)
                _set = arrayToSet(self.loader, _list)
                self.output.append(_set)
            else:
                self.pushOperator(token)

        for index in reversed(range(self.stack.__len__())):
            self.output.append(self.stack.pop(index))

    def pushOperator(self, operator):
        """
            Used to push ! && and || onto the operator-stack (self.stack[]). Rules being followed are taken from
            the Shunting-Yard algorithm.
        """
        if self.stack.__len__() == 0:
            self.stack.append(operator)
        elif operator == '(':
            self.stack.append(operator)
        elif operator == ')':
            while self.stack[-1] != '(':
                self.output.append(self.stack.pop())
            self.stack.pop()
        else:
            while operatorPrecedence(self.stack[-1]) > operatorPrecedence(operator):
                self.output.append(self.stack.pop())
                if self.stack.__len__() == 0:
                    break
            self.stack.append(operator)

def operatorPrecedence(operator):
    """
        In order to use the operator stack properly, we need to give different operators advantage/precedence over
        each other. In the way that '*' has precedence over '+', thus it has a greater integer value.
    """
    if operator == '!':
        return 3
    if operator == '&&':
        return 2
    if operator == '||':
        return 1

    return 0


from __future__ import print_function

__author__ = 'dboyko'

import os
import sys
from selenium import webdriver
from selenium.webdriver.common.by import By
from tms_objects_map import ui_map, ui_map_events_tab
from tms_objects_map import ui_map_buttons, ui_map_templates_tab
from tms_objects_map import event_filters, ui_map_user_tab, ui_map_images_tab, ui_map_deployments_tab
from tms_elements import my_credentials
import binascii
from report_path import path_report
from role_setup import roles
import datetime
# import HTMLTestRunner
from selenium.webdriver.support.ui      import WebDriverWait
from selenium.webdriver.support.select  import Select # use for drop down menu
from pyvirtualdisplay import Display
from selenium import webdriver

display = Display(visible=0, size=(1024, 768))
display.start()

def driver():
    selenium_driver = webdriver.Firefox()
    selenium_driver.set_page_load_timeout(30)
    selenium_driver.implicitly_wait(30)
    selenium_driver.delete_all_cookies()
    return selenium_driver

def main():
    d = driver()

    role = roles()
    role.logIn(d)

    event = create_event_testsuite()
    event.event_tab(d)

    newEvent = new_event()
    newEvent.new_event_create(d)

    verify = event_verifications()
    verify.verification_deployment_name(d)
    verify.verification_event_name(d)
    verify.verification_template_name(d)
    verify.verification_estimation_price(d)

    # newEvent.event_delete(d)

    sys.stdout.close()

    d.quit()

class event_main_out():

    def event_main(self):
        d = driver()

        role = roles()
        role.logIn(d)

        event = create_event_testsuite()
        event.event_tab(d)

        newEvent = new_event()
        newEvent.new_event_create(d)

        verify = event_verifications()
        verify.verification_deployment_name(d)
        verify.verification_event_name(d)
        verify.verification_template_name(d)
        verify.verification_estimation_price(d)

        newEvent.edit_event(d)

        verify.verification_DP_estimation_price(d)

        # newEvent.event_delete(d)

        sys.stdout.close()

        d.quit()

class create_event_testsuite():

    sys.stdout = open(os.path.join(path_report, "TMS_Test_Events.log"), 'w')

    def event_tab(self, selenium_driver):

        ui_m = ui_map(selenium_driver)
        ui_button = ui_map_buttons(selenium_driver)
        ui_filters = event_filters(selenium_driver)
        crdn = my_credentials()
        ui_user = ui_map_user_tab(selenium_driver)
        ui_images = ui_map_images_tab(selenium_driver)
        ui_deployments = ui_map_deployments_tab(selenium_driver)
        ui_templates = ui_map_templates_tab(selenium_driver)
        ui_events = ui_map_events_tab(selenium_driver)

        # Select "Templates" tab
        ui_events.tms_events_tab(selenium_driver).click()
        print("\nEvents tab selected")
        # Select "List" button
        ui_button.tms_list(selenium_driver).click()
        print('Select "List" button')

        dropDownElement = WebDriverWait(driver, 10).\
            until(lambda driver: selenium_driver.find_element(By.ID, "customerId"))
        Select(dropDownElement).select_by_visible_text("ReadyTech")

class new_event():

    def new_event_create(self, selenium_driver):
        # import os, binascii
        catalog_num = binascii.b2a_hex(os.urandom(3))
        ui_m = ui_map(selenium_driver)
        ui_button = ui_map_buttons(selenium_driver)
        ui_filters = event_filters(selenium_driver)
        # crdn = my_credentials(selenium_driver)
        ui_user = ui_map_user_tab(selenium_driver)
        ui_images = ui_map_images_tab(selenium_driver)
        ui_deployments = ui_map_deployments_tab(selenium_driver)
        ui_templates = ui_map_templates_tab(selenium_driver)
        ui_events = ui_map_events_tab(selenium_driver)

        # Select "New Event" button
        ui_events.tms_new_event_button(selenium_driver).click()

        dropDownElement = WebDriverWait(driver, 10).\
            until(lambda driver: selenium_driver.find_element(By.ID, "eventTypeId"))
        Select(dropDownElement).select_by_visible_text("ILT Classroom")

        dropDownElement = WebDriverWait(driver, 10).\
            until(lambda driver: selenium_driver.find_element(By.ID, "ownerId"))
        Select(dropDownElement).select_by_visible_text("Dmitry Boyko")

        ui_m.tms_event_eventName(selenium_driver).send_keys("Automation_Event_Test")

        # drop down Time Zone
        dropDownElement = WebDriverWait(driver, 10).\
            until(lambda driver: selenium_driver.find_element(By.ID, "timezone"))
        Select(dropDownElement).select_by_visible_text("GMT-08:00 Pacific Time")
        # print("GMT-08:00 Pacific Time selected")

        # Calendar: Start date
        td = datetime.datetime.now() + datetime.timedelta(days=2)
        selenium_driver.find_element(By.ID, "startDate").send_keys((td.strftime("%m/%d/%Y")))
        td = datetime.datetime.now() + datetime.timedelta(days=4)
        selenium_driver.find_element(By.ID, "endDate").send_keys((td.strftime("%m/%d/%Y")))

        # Template Materials
        dropDownElement = WebDriverWait(driver, 10).\
                until(lambda driver: selenium_driver.find_element(By.ID, "templateId"))
        Select(dropDownElement).select_by_visible_text("Automation_Test_Template")

        # Requested Users:
        ui_m.tms_event_requestUsers(selenium_driver).clear()
        ui_m.tms_event_requestUsers(selenium_driver).send_keys("3")

        # Asseigned Data Center
        dropDownElement = WebDriverWait(driver, 10).\
                until(lambda driver: selenium_driver.find_element(By.ID, "datacenterId"))
        Select(dropDownElement).select_by_visible_text("DC 3 - Development")

        ui_m.tms_event_deny_license_checkbox(selenium_driver).click()

        # Select "Save" button
        ui_m.tms_event_save_button(selenium_driver).click()

        try:
            alert = selenium_driver.switch_to.alert
            alert.accept()

            ui_images.tms_image_save_button(selenium_driver).click()
        except:
            pass

        # verification
            # price estimation

    def edit_event(self, selenium_driver):
        # Edit event > Change Deployment
        ui_m = ui_map(selenium_driver)
        edit_button = WebDriverWait(driver, 10).\
            until(lambda driver: selenium_driver.find_element(By.LINK_TEXT, "Edit"))
        edit_button.click()
        # Change Deployment Type
        dropDownElement = WebDriverWait(driver, 10).\
                until(lambda driver: selenium_driver.find_element(By.ID, "deployTypeKey"))
        Select(dropDownElement).select_by_visible_text("Deployment Plan")
        # Select Deployment Plan
        dropDownElement = WebDriverWait(driver, 10).\
                until(lambda driver: selenium_driver.find_element(By.ID, "deploymentPlanId"))
        Select(dropDownElement).select_by_visible_text("HW VLAN")
        # Select "Save" button
        ui_m.tms_event_save_button(selenium_driver).click()
        # Confirmation
        alert = selenium_driver.switch_to.alert
        alert.accept()

    def event_delete(self, selenium_driver):
        # Delete created Event
        ui_m = ui_map(selenium_driver)

        str_element = selenium_driver.find_elements(By.ID, "name")
        for elem in str_element:
            if elem.text == u"Automation_Event_Test":
                ui_m.tms_event_delete_button(selenium_driver).click()
                alert = selenium_driver.switch_to.alert
                alert.accept()
                print("Event Delete: Pass")
            else:
                print("Event Delete: Fail")

class event_verifications():

    def verification_event_name(self, selenium_driver):
        str_element = selenium_driver.find_elements(By.ID, "name")
        for elem in str_element:
            if elem.text == u"Automation_Event_Test":
                print("Event Create: Pass")
            else:
                print("Event Create: Fail")

    def verification_template_name(self, selenium_driver):
        str_element = selenium_driver.find_elements(By.LINK_TEXT, "Automation_Test_Template")
        for elem in str_element:
            if elem.text == u"Automation_Test_Template":
                print("Starting Template: Pass")
            else:
                print("Starting Template: Fail")

    def verification_deployment_name(self, selenium_driver):
        str_element = selenium_driver.find_elements(By.LINK_TEXT, "Automation_Test_Deployment")
        for elem in str_element:
            if elem.text == u"Automation_Test_Deployment":
                print("Deployment: Pass")
            else:
                print("Deployment: Fail")

    def verification_estimation_price(self, selenium_driver):
        str_element = selenium_driver.find_elements(By.ID, "estimated_price")
        for elem in str_element:
            # if elem.text == u"$108.00": # for 1 day
            if elem.text == u"$324.00": # for 2 days
                print("Estimation Price: Pass")
            else:
                print("Estimation Price: Fail")

    def verification_DP_estimation_price(self, selenium_driver):

        str_element = selenium_driver.find_elements(By.ID, "estimated_price")
        for elem in str_element:
            # if elem.text == u"$147.00": # for 1 day
            if elem.text == u"$441.00": # for 2 days
                print("Estimation Price: Pass")
            else:
                print("Estimation Price: Fail")
        '''
        str_element = selenium_driver.find_element(By.ID, "estimated_price")
        if str_element.text == "$147.00":
            print("Estimation Price: Pass")
        else:
            print("Estimation Price: Fail")
        '''

if __name__ == "__main__":
    main()


import os

#To find minimum of a list
def minimum(A):
	mini = A[0]
	for i in A:
		if i < mini:
			mini = i
	return mini;

#To find maximum of a list
def maximum(A):
	maxi = A[0]
	for i in A:
		if i > maxi:
			maxi = i
	return maxi

#to swap 2 values in a list
def swap(A, x, y):
  tmp = A[x]
  A[x] = A[y]
  A[y] = tmp

#to rename a lot of files
#(with key label at the beginning) into a directory
def renameFiles(label = "", dir_path = ""):
	number_of_char = len(label)
	if dir_path == "":
		dir_path = "."
	for filename in os.listdir(dir_path):
		if filename.startswith(label):
			os.rename(filename, filename[number_of_char:])


import tensorflow as tf
import json
import time

datos = json.load(open('static/datos/BannedCards.json', 'r'))

X = datos['inputs']
Y = datos['outs']

VENTANA = len(X[0])

x_ = tf.placeholder(tf.float32, shape=[len(X), VENTANA], name='X')
y_ = tf.placeholder(tf.float32, shape=[len(Y), 1], name='Y')

capa_0 = tf.Variable(tf.random_uniform([VENTANA, 10], -1, 1), name='capa0')
capa_1 = tf.Variable(tf.random_uniform([10, 5], -1, 1), name='capa1')
capa_2 = tf.Variable(tf.random_uniform([5, 1], -1, 1), name='capa2')

bias_0 = tf.Variable(tf.zeros([10]), name='bias0')
bias_1 = tf.Variable(tf.zeros([5]), name='bias1')
bias_2 = tf.Variable(tf.zeros([1]), name='bias2')

operacion = tf.sigmoid(tf.matmul(x_, capa_0) + bias_0)
operacion1 = tf.sigmoid(tf.matmul(operacion, capa_1) + bias_1)
hipotesis = tf.sigmoid(tf.matmul(operacion1, capa_2) + bias_2)

costo = tf.reduce_mean(((y_ * tf.log(hipotesis)) + ((1 - y_) * tf.log(1.0 - hipotesis))) * -1)

entrenamiento = tf.train.GradientDescentOptimizer(0.1).minimize(costo)

init = tf.global_variables_initializer()

sesion = tf.Session()
sesion.run(init)

for i in range(150000):
    sesion.run(entrenamiento, feed_dict={
        x_: X,
        y_: Y
    })

    if i % 1000 == 0:
        print('Hipotesis: {}'.format(sesion.run(hipotesis, feed_dict={
            x_: X,
            y_: Y
        })))

        print('Capa 0: {}'.format(sesion.run(capa_0)))
        print('Bias 0: {}'.format(sesion.run(bias_0)))
        print('Capa 1: {}'.format(sesion.run(capa_1)))
        print('Bias 1: {}'.format(sesion.run(bias_1)))

        print('Costo: {}'.format(sesion.run(costo, feed_dict={
            x_: X,
            y_: Y
        })))
        print('Epoca: {}'.format(i))
ws = list()
ws.append(sesion.run(capa_0).tolist())
ws.append(sesion.run(capa_1).tolist())
ws.append(sesion.run(capa_2).tolist())
bs = list()
bs.append(sesion.run(bias_0).tolist())
bs.append(sesion.run(bias_1).tolist())
bs.append(sesion.run(bias_2).tolist())
# print(ws)
# print(bs)

json.dump({
    'ws': ws,
    'bs': bs
}, open('datos/BannedCardsPesos.json', 'w'))


import csv
from collections import Counter
with open('height.csv',newline='') as f:
    reader=csv.reader(f)
    file_data=list(reader)
file_data.pop(0)
new_data=[]
for i in range(len(file_data)):
    num=file_data[i][1]
    new_data.append(float(num))
data=Counter(new_data)
data_range={
            '50-60':0,
            '60-70':0,
            '70-80':0
            }
for height,occurrence in data.items():
    if 50 < float(height)<60:
        data_range['50-60']+=occurrence
    elif 60 < float(height)<70:
        data_range['60-70']+=occurrence
    elif 70 < float(height)<80:
        data_range['70-80']+=occurrence
mode_range,mode_occurrence=0,0
for range,occurrence in data_range.items():
    if occurrence > mode_occurrence:
       mode_range, mode_occurrence = [int(range.split("-")[0]), int(range.split("-")[1])], occurrence
mode = float((mode_range[0] + mode_range[1]) / 2)
print(mode)


import os
import signal
import subprocess

from mininet_topology import MininetTopology
from mininet.net import Mininet
from mininet.node import RemoteController
from mininet.link import TCIntf

class MininetNetwork:

    def __init__(self, bandwidth, delay, error_rate):
        self.__publishers_switch = "s1"
        self.__subscribers_switch = "s2"
        self.__dummy_switch = "s254"
        self.__switch_protocols = "OpenFlow13"

        self.__bandwidth = bandwidth
        self.__delay = delay
        self.__error_rate = error_rate

        self.__hosts = []

        self.__network = Mininet()
        self.__host_processes = []

    def add_host(self, name, host):
        self.__hosts.append( { "name": name, "ip": host } )

    def host_by_name(self, name):
        for host in self.__network.hosts:
            if host.name == name:
                return host
        return None

    def start(self):
        topology = MininetTopology()

        topology.addSwitch(
            name = self.__publishers_switch,
            protocols = self.__switch_protocols
        )

        topology.addSwitch(
            name = self.__subscribers_switch,
            protocols = self.__switch_protocols
        )

        topology.addSwitch(
            name = self.__dummy_switch,
            protocols = self.__switch_protocols
        )

        topology.addLink(
            node1 = self.__publishers_switch,
            node2 = self.__dummy_switch
        )

        topology.addLink(
            node1 = self.__subscribers_switch,
            node2 = self.__dummy_switch
        )

        for host in self.__hosts:
            topology.addHost(
                name = host["name"],
                ip = host["ip"]
            )

            if host["name"] == "broker":
                topology.addLink(
                    node1 = host["name"],
                    node2 = self.__dummy_switch
                )
            elif host["name"].startswith("pub"):
                topology.addLink(
                    node1 = host["name"],
                    node2 = self.__publishers_switch
                )
            elif host["name"].startswith("sub"):
                topology.addLink(
                    node1 = host["name"],
                    node2 = self.__subscribers_switch,
                    # intf = TCIntf,
                    # params1 = {'delay': str(self.__latency) + "ms"},
                    # params2 = {'delay': str(0) + "ms"}
                )

        self.__network = Mininet(
            topo = topology,
            controller = RemoteController,
            waitConnected = True,
            autoSetMacs = True,
            autoStaticArp = True
        )

        self.__network.addNAT().configDefault()

        self.__network.start()

    def priority_queues(self, priorities):
        bandwidth = self.__bandwidth * 8

        command = "sudo ovs-vsctl"
        command += " -- set port %s-eth2 qos=@newqos -- " % self.__dummy_switch
        command += "--id=@newqos create qos type=linux-htb other-config:min-rate=%s other-config:max-rate=%s " % \
                   ( str(0), str(bandwidth) )
        command += "queues="
        for priority in range(1, priorities + 1):
            queue_name = str(priority)
            queue_identifier = "@q%s" % queue_name
            command += "%s=%s," % (queue_name, queue_identifier)
        command = command[:-1]
        command += " -- "
        for priority in range(1, priorities + 1):
            queue_name = str(priority)
            queue_identifier = "@q%s" % queue_name
            command += "--id=%s create queue other-config:priority=%s other-config:min-rate=%s other-config:max-rate=%s -- " % \
                       ( queue_identifier, str(priority), str(0), str(bandwidth) )

        process = subprocess.Popen(
            command,
            shell = True,
            stdin = open(os.devnull),
            stdout = open(os.devnull),
            stderr = open(os.devnull)
        )

        process.wait()

    def topology_discovery(self):
        self.__network.pingAll()

    def execute(self, name, command):
        host = self.host_by_name(name)
        process = host.popen(command, shell = True)
        self.__host_processes.append( (name, process) )

    def stop(self):
        for host_process in self.__host_processes:
            try:
                process = host_process[1]
                os.killpg(process.pid, signal.SIGTERM)
            except Exception:
                pass

        self.__host_processes = []
        self.__network.stop()


#!/usr/bin/env python

import gtk

class NotebookCloseButton:
    def __init__(self):
        window = gtk.Window()
        window.set_default_size(400, 300)

        self.notebook = gtk.Notebook()

        for page in range(5):
            self.construct_tab("Tab %s" % page)

        window.connect("destroy", lambda w: gtk.main_quit())

        window.add(self.notebook)
        window.show_all()

    def construct_tab(self, title):
        hbox = gtk.HBox(False, 2)
        tab_label = gtk.Label(title)
        hbox.pack_start(tab_label)

        image = gtk.Image()
        image.set_from_stock(gtk.STOCK_CLOSE, gtk.ICON_SIZE_MENU)

        button = gtk.Button()
        button.add(image)
        settings = gtk.Widget.get_settings(button)
        width, height = gtk.icon_size_lookup_for_settings(settings, gtk.ICON_SIZE_MENU)

        button.set_relief(gtk.RELIEF_NONE)
        button.set_focus_on_click(False)
        button.set_size_request(width + 2, height + 2)

        style = gtk.RcStyle()
        style.xthickness = 0
        style.ythickness = 0
        button.modify_style(style)

        hbox.pack_start(button, False, False, 0)
        hbox.show_all()

        page_label = gtk.Label(title)

        self.notebook.insert_page(page_label, hbox)

        button.connect("clicked", self.close_tab, page_label)

    def close_tab(self, object, widget):
        page = self.notebook.page_num(widget)
        self.notebook.remove_page(page)

NotebookCloseButton()
gtk.main()


# uncompyle6 version 3.7.4
# Python bytecode 3.8 (3413)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: build/bdist.macosx-10.9-x86_64/egg/cloudinary_storage/helpers.py
# Compiled at: 2019-12-17 14:08:28
# Size of source mod 2**32: 1270 bytes
import cloudinary.api

def get_resources_by_path(resource_type, tag, path):
    resources = []
    next_cursor = None
    while True:
        options = {'type':'upload',  'prefix':path,
         'resource_type':resource_type,
         'max_results':500,
         'tags':True}
        if next_cursor is not None:
            options['next_cursor'] = next_cursor
        response = (cloudinary.api.resources)(**options)
        for resource in response['resources']:
            if tag in resource['tags']:
                resources.append(resource['public_id'])
            next_cursor = response.get('next_cursor')
            if next_cursor is None:
                break

    return resources

def get_resources(resource_type, tag):
    resources = []
    next_cursor = None
    while True:
        options = {'resource_type':resource_type,
         'max_results':500}
        if next_cursor is not None:
            options['next_cursor'] = next_cursor
        response = (cloudinary.api.resources_by_tag)(tag, **options)
        for resource in response['resources']:
            resources.append(resource['public_id'])
        else:
            next_cursor = response.get('next_cursor')

        if next_cursor is None:
            break

    return resources


import os

from .model import AddonDataverseUserSettings, AddonDataverseNodeSettings, \
    DataverseFile
from .routes import settings_routes, api_routes
import views

MODELS = [AddonDataverseNodeSettings, AddonDataverseUserSettings, DataverseFile]
USER_SETTINGS_MODEL = AddonDataverseUserSettings
NODE_SETTINGS_MODEL = AddonDataverseNodeSettings

ROUTES = [settings_routes, api_routes]

SHORT_NAME = 'dataverse'
FULL_NAME = 'Dataverse'

OWNERS = ['user', 'node']

ADDED_DEFAULT = []
ADDED_MANDATORY = []

VIEWS = ['widget']
CONFIGS = ['user', 'node']

CATEGORIES = ['storage']

INCLUDE_JS = {
    'widget': [],
    'page': [],
    'files': [],
}

INCLUDE_CSS = {
    'widget': ['dataverse.css'],
    'page': [],
}

HAS_HGRID_FILES = True
GET_HGRID_DATA = views.hgrid.dataverse_hgrid_root

HERE = os.path.dirname(os.path.abspath(__file__))
NODE_SETTINGS_TEMPLATE = os.path.join(HERE, 'templates', 'dataverse_node_settings.mako')
USER_SETTINGS_TEMPLATE = os.path.join(HERE, 'templates', 'dataverse_user_settings.mako')


import json
import yfinance as yf
import boto3
import datetime

#kinesis = boto3.client('kinesis', "us-east-2")

def lambda_handler(event,context):
    kinesis = boto3.client('kinesis', "us-east-2")
    #record_dump={}
    start_date = '2021-05-11'
    end_date = '2021-05-12'
    interval = '5m'
    stocks = ['FB', 'SHOP', 'BYND', 'NFLX', 'PINS', 'SQ', 'TTD', 'OKTA', 'SNAP', 'DDOG']

    for stock in stocks:
        stream = yf.Ticker(stock).history(start=start_date,end=end_date,interval=interval)

        for index, value in stream.iterrows():
            record_dump = json.dumps({'high':value['High'],'low':value['Low'],'ts':str(index),'name':stock},separators=(',',': '))+"\n"
            print(record_dump)
            kinesis.put_record(
                StreamName="sta9760s2021_stream1",
                Data=record_dump.encode('utf-8'),
                PartitionKey="partitionkey")

    return{
        'statusCode': 200,
        'body': record_dump
    }


import random
import logging
from uuid import UUID

from rest_framework import viewsets
from rest_framework.views import APIView
from rest_framework.response import Response
from django.core.serializers import serialize
from rest_framework import status
from rest_framework.permissions import IsAdminUser
from rest_framework import mixins
from django.core.exceptions import ObjectDoesNotExist
from django.db import connection
from django.contrib.auth import get_user_model

from .permissions import PlayerPermission

from .models import (
    CategoryQuestionModel, AnswerModel, CategoryModel, QuestionModel,
    RankingModel
)
from .serializers import (
    CategoryQuestionSerializer, AnswerSerializer, CategorySerializer,
    QuestionSerializer, QuizSerializer, RankingSerializer, UserSerializer
)

class UserViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    UserModel = get_user_model()
    queryset = UserModel.objects.all()
    serializer_class = UserSerializer

class CategoryViewSet(viewsets.ModelViewSet):
    queryset = CategoryModel.objects.all()
    serializer_class = CategorySerializer
    permission_classes = (
        PlayerPermission,
    )

class QuestionViewSet(viewsets.ModelViewSet):
    queryset = QuestionModel.objects.all()
    serializer_class = QuestionSerializer
    permission_classes = [IsAdminUser]

class AnswerViewSet(viewsets.ModelViewSet):
    queryset = AnswerModel.objects.all()
    serializer_class = AnswerSerializer
    permission_classes = [IsAdminUser]

class CategoryQuestionViewSet(viewsets.ModelViewSet):
    queryset = CategoryQuestionModel.objects.all()
    serializer_class = CategoryQuestionSerializer
    permission_classes = [IsAdminUser]

class RankingViewSet(
    mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet
):
    queryset = RankingModel.objects.all().order_by('-value')
    serializer_class = RankingSerializer
    permission_classes = [PlayerPermission]

    # Neste caso, pk eh o id da category.
    def retrieve(self, request, pk):
        ranking = (
            RankingModel.objects.filter(category_id__in=[pk]).order_by('-value')
        )
        serializer = RankingSerializer(ranking, many=True)
        return Response(serializer.data)

class QuizAPIView(APIView):
    permission_classes = [PlayerPermission]
    def get(self, requests, category_id):
        cursor = connection.cursor()
        query = f'SELECT B.id, B.question FROM  core_categoryquestionmodel as A INNER JOIN core_questionmodel as B ON B.id = A.question_id WHERE A.category_id="{category_id.replace("-","")}";'
        cursor.execute(query)
        questions_db = cursor.fetchall()
        questions = [
            {'id': UUID(x), 'question': y} for x, y in questions_db
        ]
        random.shuffle(questions)
        answers_db = AnswerModel.objects.all()
        answers = list(answers_db.values())
        list_quiz = []
        for question in questions:
            random.shuffle(answers)
            question_answers_true = list(
                filter(
                    lambda x: (
                        x['question_id'] == question['id']
                        and x['correct_answer'] is True
                    ),
                    answers
                )
            )[0:1]
            question_answers_false = list(
                filter(
                    lambda x: (
                        x['question_id'] == question['id']
                        and x['correct_answer'] is False
                    ),
                    answers
                )
            )[0:2]
            list_questions = question_answers_true + question_answers_false
            random.shuffle(list_questions)
            data = {
                'question': {
                    'id':question['id'],
                    'question': question['question']
                },
                'answers': [
                    {'id': x['id'], 'answer': x['answer']}
                    for x in list_questions
                ]
            }
            list_quiz.append(data)
        # Verifica se o quiz possui >= 10 perguntas.
        if len(list_quiz) >= 10:
            return Response(list_quiz[0:10], status.HTTP_200_OK)
        else:
            result = {
                'msg': 'Quiz ainda não possui perguntas sufucientes.'
            }
            return Response(result, status.HTTP_500_INTERNAL_SERVER_ERROR)

    def post(self, requests, category_id):
        user = requests.user
        result = {}
        serialize_quiz = QuizSerializer(data=requests.data, many=True)
        if serialize_quiz.is_valid(raise_exception=True):
            list_answers = list(
                {x['id_answer'] for x in serialize_quiz.validated_data}
            )
            list_answers_db = list(
                AnswerModel.objects.filter(id__in=list_answers).values()
            )
            list_correct_answers = list(filter(
                lambda x: x['correct_answer'] == True, list_answers_db
            ))
            category = CategoryModel.objects.get(id=category_id)
            data = {
                'user_id': user.id,
                'category_id': category.id,
                'value': len(list_correct_answers)
            }
            #Cria ou atualiza os dados do ranking
            try:
                ranking = RankingModel.objects.get(
                    category=category_id,
                    user=user.id
                )
                ranking.value = data['value']
                ranking.save()
            except ObjectDoesNotExist:
                RankingModel.objects.create(**data)
            global_ranking = list(
                RankingModel.objects.all().order_by('-value').values()
            )
            index_user = [
                i for i, _ in enumerate(global_ranking)
                if _['user_id'] == user.id
            ][0]
            result = {
                'punctuation': data['value'],
                'ranking_position': index_user + 1
            }
            return Response(
                result, status=status.HTTP_201_CREATED
            )
        else:
            logging.error(msg='Erro ao processar os dados')
            return Response({'Result': result}, status.HTTP_200_OK)


import os

DEBUG = False

SITE_NAME = "Ratchet.io Status"
SITE_AUTHOR = "Cory Virok"
SITE_URL = "http://ratchetstatus.appspot.com"
REPORT_URL = "mailto:help@ratchet.io"

# Twitter update settings
TWITTER_CONSUMER_KEY = ''
TWITTER_CONSUMER_SECRET = ''
TWITTER_ACCESS_TOKEN = ''
TWITTER_ACCESS_TOKEN_SECRET = ''
TWITTER_HANDLE = 'ratchetio'

# RSS Feed settings
RSS_NUM_EVENTS_TO_FETCH = 50

# OAuth Consumer Credentials
CONSUMER_KEY = 'anonymous'
CONSUMER_SECRET = 'anonymous'

TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(__file__), "templates"),
)


#!/usr/bin/python

# Kindle Transit-Weather Display
# Inspired by Matthew Petroff (http://www.mpetroff.net/)
# November 2013

import requests
import json
import codecs
import os.path, time, datetime
import privateVars
import xml.etree.ElementTree as ET

from zoneinfo import ZoneInfo

def iconMap(condition, daylight):
    # deal with other codes? https://github.com/hrbrmstr/weatherkit/blob/batman/R/enumerations.R
    map = {
        "Clear": "clear.svg",
        "Rain": "rain.svg",
        "Snow": "snow.svg",
        "Sleet": "sleet.svg",
        "Windy": "wind.svg",
        "Fog": "fog.svg",
        "Dust": "fog.svg",
        "Haze": "hazy.svg",
        "Cloudy": "cloudy.svg",
        "MostlyClear": "mostlysunny.svg",
        "MostlyCloudy": "mostlycloudy.svg",
        "PartlyCloudy": "partlycloudy.svg",
        "ScatteredThunderstorms": "tstorms.svg",
        "Smoke": "hazy.svg",
        "Breezy": "wind.svg",
        "Drizzle": "rain.svg",
        "HeavyRain": "rain.svg",
        "Showers": "rain.svg",
        "Flurries": "flurries.svg",
        "HeavySnow": "snow.svg",
        "MixedRainAndSleet": "sleet.svg",
        "MixedRainAndSnow": "snow.svg",
        "MixedRainfall": "rain.svg",
        "MixedSnowAndSleet": "sleet.svg",
        "ScatteredShowers": "rain.svg",
        "ScatteredSnowShowers": "snow.svg",
        "Sleet": "sleet.svg",
        "SnowShowers": "snow.svg",
        "Blizzard": "snow.svg",
        "BlowingSnow": "snow.svg",
        "FreezingDrizzle": "sleet.svg",
        "FreezingRain": "sleet.svg",
        "Frigid": "snow.svg",
        "Hail": "sleet.svg",
        "Hot": "sunny.svg",
        "Hurricane": "tstorms.svg",
        "IsolatedThunderstorms": "tstorms.svg",
        "SevereThunderstorm": "tstorms.svg",
        "Thunderstorm": "tstorms.svg",
        "Thunderstorms": "tstorms.svg",
        "Tornado": "tstorms.svg",
        "TropicalStorm": "tstorms.svg",
    }

    out = map[condition]

    # if it's night see if there's a night option, use that if so
    if daylight == False and os.path.isfile(f"weather-icons/night/{out}"):
        out = f"night/{out}"

    return f"weather-icons/{out}"

def fileChecker(path, refreshInterval):
    # check if the file exists
    if os.path.isfile(path):
        # check the time and compare it to the refresh interval
        mTime = time.strptime(time.ctime(os.path.getmtime(path)))
        lTime = time.localtime()
        # difference between modified time and local time in seconds
        if time.mktime(lTime) - time.mktime(mTime) > refreshInterval:
            output = "create"
        else:
            output = "useOld"
    else:
        output = "create"
    return output

def celsius_to_fahrenheit(celsius):
    """
    Convert temperature from Celsius to Fahrenheit.

    Arguments:
    celsius -- a temperature value in Celsius (float or integer)

    Returns:
    fahrenheit -- the equivalent temperature value in Fahrenheit (float)
    """
    fahrenheit = (celsius * 9/5) + 32
    return fahrenheit

def weatherGrabber(
    type,
    path,
    source="weatherKit",
    apiKey=privateVars.weatherKitToken,
    zipCode=privateVars.zipCode,
    lat=privateVars.lat,
    lng=privateVars.lng,
):
    if source == "wunderground":
        f = requests.get(
            "http://api.wunderground.com/api/"
            + apiKey
            + "/geolookup/"
            + type
            + "/q/"
            + zipCode
            + ".json"
        )
    elif source == "weatherKit":
        f = requests.get(
            f"https://weatherkit.apple.com/api/v1/weather/en/{lat}/{lng}?"
            + f"dataSets=currentWeather,forecastDaily,forecastHourly,forecastNextHour"
            + f"&timezone={privateVars.local_tz}"
            + f"&hourlyStart={datetime.datetime.now().astimezone(tz=ZoneInfo('UTC')).isoformat().replace('+00:00', 'Z')}",
            headers={"Authorization": f"Bearer {apiKey}"},
        )
    currFile = open(path, "w")
    currFile.write(f.text)
    f.close()
    currFile.close()

def ctaPredGrabber(stopIDs, path, apiKey=privateVars.ctaAPIkey):
    if isinstance(stopIDs, str):
        stopIDs = [stopIDs]
    f = requests.get(
        "http://www.ctabustracker.com/bustime/api/v1/getpredictions?key="
        + apiKey
        + "&stpid="
        + ",".join(stopIDs)
    )
    currFile = open(path, "w")
    currFile.write(f.text)
    f.close()
    currFile.close()

def ctaTrainPredGrabber(stopIDs, path, apiKey=privateVars.ctaTrainAPIkey):
    if isinstance(stopIDs, str):
        stopIDs = [stopIDs]
    f = requests.get(
        "http://lapi.transitchicago.com/api/1.0/ttarrivals.aspx?key="
        + apiKey
        + "&stpid="
        + ",".join(stopIDs)
    )
    currFile = open(path, "w")
    currFile.write(f.text)
    f.close()
    currFile.close()

def addTransit(
    output, paths=["localData/busPredictions.xml", "localData/trainPredictions.xml"]
):
    ########## transit ###########
    # establish display variables:
    show = "inline"
    hide = "none"

    thingsToTrack = list(privateVars.busesToTrack.keys()) + list(
        privateVars.trainsToTrack.keys()
    )

    buses = {x: [] for x in thingsToTrack}
    arrivals = {x: [] for x in thingsToTrack}

    bounds = {
        "Northbound": "nb",
        "Southbound": "sb",
        "Eastbound": "eb",
        "Westbound": "wb",
        "NORTH": "nb",
        "SOUTH": "sb",
        "EAST": "eb",
        "WEST": "wb",
    }

    # this should be abstracted
    trainStopIDsToBounds = {"30274": "sb", "30273": "nb", "30071": "sb", "30070": "nb"}
    seenVIDs = []

    # parse the buses file
    parsed_xml = ET.parse(paths[0])
    root = parsed_xml.getroot()
    for child in root:
        if child.tag == "prd":
            dupCheck = "".join(
                [
                    bounds[child.findall("rtdir")[0].text],
                    child.findall("rt")[0].text,
                    child.findall("vid")[0].text,
                    child.findall("prdtm")[0].text,
                ]
            )
            if dupCheck not in seenVIDs:
                seenVIDs.append(dupCheck)

                route = "".join(
                    [
                        bounds[child.findall("rtdir")[0].text],
                        child.findall("rt")[0].text,
                    ]
                )
                try:
                    buses[route].append(child.findall("prdtm")[0].text)
                except KeyError:
                    pass

    # parse the trains file
    parsed_xml = ET.parse(paths[1])
    root = parsed_xml.getroot()
    for child in root:
        if child.tag == "eta":
            dupCheck = "".join(
                [
                    trainStopIDsToBounds[child.findall("stpId")[0].text],
                    child.findall("rt")[0].text,
                    child.findall("rn")[0].text,
                    child.findall("arrT")[0].text,
                ]
            )
            if dupCheck not in seenVIDs:
                seenVIDs.append(dupCheck)

                route = "".join(
                    [
                        trainStopIDsToBounds[child.findall("stpId")[0].text],
                        child.findall("rt")[0].text,
                    ]
                ).lower()
                try:
                    buses[route].append(child.findall("arrT")[0].text)
                except KeyError:
                    pass

    # make a dictionary of arrival times
    for bus in arrivals.keys():
        for indBus in buses[bus]:
            if len(indBus) == 14:  # for buses
                arrival = datetime.datetime.strptime(
                    indBus, "%Y%m%d %H:%M"
                ) - datetime.datetime.fromtimestamp(time.mktime(time.localtime()))
                # subtract a minute from the minutes until arrival
                arrival = arrival - datetime.timedelta(seconds=60)
            if len(indBus) == 17:  # for trains
                arrival = datetime.datetime.strptime(
                    indBus, "%Y%m%d %H:%M:%S"
                ) - datetime.datetime.fromtimestamp(time.mktime(time.localtime()))
                arrival = arrival - datetime.timedelta(seconds=00)
            # ensure that arrival times are longer than 1 minute
            if arrival > datetime.timedelta(seconds=60):
                # extract the minutes
                arrival = str(arrival).split(":")[1]
                arrivals[bus].append(arrival)

    for bus in buses.keys():
        # grab the place identifier
        busPlace = privateVars.busPlaces[bus[2:]]
        # add the up or down designation
        if bus[:2] == "nb" or bus[:2] == "wb":
            busPlace = busPlace + "_D"
        else:
            busPlace = busPlace + "_U"
        for n in range(3):
            try:
                arrival = arrivals[bus][n]
                # clean the arrival time
                if arrival == "00":
                    arrival = "0"  # due does not fit with the current setup.
                elif arrival[0] == "0":
                    arrival = arrival[1:]
                output = output.replace(busPlace + str(n + 1) + "_DISP", show)
                output = output.replace(busPlace + str(n + 1), arrival)
            except IndexError:
                output = output.replace(busPlace + str(n + 1) + "_DISP", hide)
                output = output.replace(busPlace + str(n + 1), "")
                pass

    # Insert icons and temperatures

    # get localtime, add a minute to align better after synchronization
    lTime = str(
        datetime.datetime.fromtimestamp(time.mktime(time.localtime()))
        + datetime.timedelta(seconds=60)
    ).split(" ")[1]
    hrs = lTime.split(":")[0]
    mins = lTime.split(":")[1]
    if len(mins) < 2:
        mins = "0" + mins
    lTimeF = hrs + ":" + mins
    output = output.replace("TIME", str(lTimeF))

    output = output.replace("DISP_TRANSIT", show)

    return output

# check the ctabusPredictions file to see if it's older than 5 seconds
if fileChecker("localData/busPredictions.xml", 5) == "create":
    ctaPredGrabber(
        stopIDs=privateVars.busesToTrack.values(), path="localData/busPredictions.xml"
    )

# check the cttrainPredictions file to see if it's older than 5 seconds
if fileChecker("localData/trainPredictions.xml", 5) == "create":
    ctaTrainPredGrabber(
        stopIDs=privateVars.trainsToTrack.values(),
        path="localData/trainPredictions.xml",
    )

########## current ###########
# Open SVG to process
output = codecs.open("weather-transit-preprocess.svg", "r", encoding="utf-8").read()

# establish display variables:
show = "inline"
hide = "none"

### Deal with the currentConditions file
# check the currenConditions file to see if it's older than 5 minutes
if fileChecker("localData/currentConditions.json", 300) == "create":
    weatherGrabber(type="conditions", path="localData/currentConditions.json")
fCurrCond = open("localData/currentConditions.json", "r")

# read the file
json_string = fCurrCond.read()
parsed_json = json.loads(json_string)
fCurrCond.close()

# parse out the dynamic variables for wunderground
# CURRTEMP = int(round(parsed_json['current_observation']['temp_f']))
# CURRFEELS = int(round(float(parsed_json['current_observation']['feelslike_f'])))
# CURRWIND = int(round(parsed_json['current_observation']['wind_mph']))
# WIND_DEGS = parsed_json['current_observation']['wind_degrees']
# CURRHUM = parsed_json['current_observation']['relative_humidity']
# CURR_COND_ICON = parsed_json['current_observation']['icon']
# # check if the icon url has nt_ at the beginning
# if parsed_json['current_observation']['icon_url'].split('/')[-1][:3] == "nt_":
#     pre = "night/"
# else:
#     pre = ""
# CURR_COND_ICON_url = 'weather-icons/' + pre + CURR_COND_ICON + '.svg'

# parse out the dynamic variables for forecast
CURRTEMP = int(round(celsius_to_fahrenheit(parsed_json["currentWeather"]["temperature"])))
CURRFEELS = int(round(celsius_to_fahrenheit(parsed_json["currentWeather"]["temperatureApparent"])))
CURRWIND = int(round(parsed_json["currentWeather"]["windSpeed"]))
WIND_DEGS = parsed_json["currentWeather"]["windDirection"]
CURRHUM = parsed_json["currentWeather"]["humidity"]
CURR_COND_ICON = parsed_json["currentWeather"]["conditionCode"]
CURR_DAYLIGHT = parsed_json["currentWeather"]["daylight"]
CURR_COND_ICON_url = iconMap(CURR_COND_ICON, CURR_DAYLIGHT)

# Insert icons and temperatures
output = output.replace("CURRTEMP", str(CURRTEMP))
output = output.replace("CURRFEELS", str(CURRFEELS))
output = output.replace("CURRWIND", str(CURRWIND))
output = output.replace("CURRHUM", str(int(CURRHUM * 100)))  # for forecast.io
output = output.replace("WIND_DEGS", str(WIND_DEGS))

# Grab the icon for the condition
if os.path.isfile(CURR_COND_ICON_url):
    fIcon = codecs.open(CURR_COND_ICON_url, "r", encoding="utf-8")
    fIcon.readline()
    icon = fIcon.readline()
    fIcon.close()
else:
    fIcon = codecs.open("weather-icons/unknown.svg", "r", encoding="utf-8")
    fIcon.readline()
    icon = fIcon.readline()
    fIcon.close()
output = output.replace("CURR_COND_ICON", icon)

# add transit information
output = addTransit(output)

output = output.replace("DISP_CURR", show)
output = output.replace("DISP5DAY", hide)
output = output.replace("DISP12HOUR", hide)

# Write output
codecs.open("weather-script-output-current.svg", "w", encoding="utf-8").write(output)

########## hourly ###########
# Open SVG to process
output = codecs.open("weather-transit-preprocess.svg", "r", encoding="utf-8").read()

# establish display variables:
show = "inline"
hide = "none"

### Deal with the hourly file
# check the currenConditions file to see if it's older than 5 minutes
# if fileChecker("localData/hourly.json", 3600) == "create":
#     weatherGrabber(type="hourly", path="localData/hourly.json")
# fCurrCond = open("localData/hourly.json",'r')
fCurrCond = open("localData/currentConditions.json", "r")

# read the file
json_string = fCurrCond.read()
parsed_json = json.loads(json_string)
fCurrCond.close()

# parse out the dynamic variables weatherKit
hours = [
    datetime.datetime.fromisoformat(
        parsed_json["forecastHourly"]["hours"][x]["forecastStart"].replace(
            "Z", "+00:00"
        )
    ).astimezone(tz=ZoneInfo(privateVars.local_tz)).hour
    for x in range(1, 13)
]
temps = [
    int(round(celsius_to_fahrenheit(parsed_json["forecastHourly"]["hours"][x]["temperature"])))
    for x in range(1, 13)
]
winds = [
    int(round(parsed_json["forecastHourly"]["hours"][x]["windSpeed"]))
    for x in range(1, 13)
]
winds_degs = [
    int(parsed_json["forecastHourly"]["hours"][x]["windDirection"]) for x in range(1, 13)
]
humids = [
    int(parsed_json["forecastHourly"]["hours"][x]["humidity"] * 100)
    for x in range(1, 13)
]
percips = [
    int(parsed_json["forecastHourly"]["hours"][x]["precipitationChance"] * 100)
    for x in range(1, 13)
]
cond_icons = [(parsed_json["forecastHourly"]["hours"][x]["conditionCode"]) for x in range(1, 13)]

# Insert icons and temperatures
h = 1
for v in hours:
    output = output.replace("H_" + str(h) + "_", str(v))
    h += 1
h = 1
for v in temps:
    output = output.replace("TEMP_" + str(h) + "_", str(v))
    h += 1
h = 1
for v in winds:
    output = output.replace("WINDSPEED_" + str(h) + "_", str(v))
    h += 1
h = 1
for v in winds_degs:
    output = output.replace("HOUR_" + str(h) + "_WIND_DEGS", str(v))
    h += 1
h = 1
for v in humids:
    output = output.replace("HUMID_" + str(h) + "_", str(v))
    h += 1
h = 1
for v in percips:
    output = output.replace("PERC_" + str(h) + "_", str(v))
    h += 1

# Grab the icon for the condition
h = 1
for v in cond_icons:
    CURR_COND_ICON_url = iconMap(v, True)
    if os.path.isfile(CURR_COND_ICON_url):
        fIcon = codecs.open(CURR_COND_ICON_url, "r", encoding="utf-8")
        fIcon.readline()
        icon = fIcon.readline()
        fIcon.close()
    else:
        fIcon = codecs.open("weather-icons/unknown.svg", "r", encoding="utf-8")
        fIcon.readline()
        icon = fIcon.readline()
        fIcon.close()
    output = output.replace("HOUR_" + str(h) + "_COND_ICON", icon)
    h += 1

# Add transit information
output = addTransit(output)

output = output.replace("DISP_CURR", hide)
output = output.replace("DISP5DAY", hide)
output = output.replace("DISP12HOUR", show)

# Write output
codecs.open("weather-script-output-hourly.svg", "w", encoding="utf-8").write(output)

########## daily ###########
# Open SVG to process
output = codecs.open("weather-transit-preprocess.svg", "r", encoding="utf-8").read()

# establish display variables:
show = "inline"
hide = "none"

### Deal with the hourly file
# check the currenConditions file to see if it's older than 5 minutes
# if fileChecker("localData/hourly.json", 3600) == "create":
#     weatherGrabber(type="hourly", path="localData/hourly.json")
# fCurrCond = open("localData/hourly.json",'r')
fCurrCond = open("localData/currentConditions.json", "r")

# read the file
json_string = fCurrCond.read()
parsed_json = json.loads(json_string)
fCurrCond.close()

# parse out the dynamic variables weatherKit

days = [
    datetime.datetime.fromisoformat(
        parsed_json["forecastDaily"]["days"][x]["forecastStart"].replace(
            "Z", "+00:00"
        )
    ).astimezone(tz=ZoneInfo(privateVars.local_tz)).strftime('%A')
    for x in range(0, 5)
]
hitemps = [
    int(round(celsius_to_fahrenheit(parsed_json["forecastDaily"]["days"][x]["temperatureMax"])))
    for x in range(0, 5)
]
lotemps = [
    int(round(celsius_to_fahrenheit(parsed_json["forecastDaily"]["days"][x]["temperatureMin"])))
    for x in range(0, 5)
]
cond_icons = [(parsed_json["forecastDaily"]["days"][x]["conditionCode"]) for x in range(0, 5)]

# Insert icons and temperatures
h = 1
for v in days:
    output = output.replace("DAY_" + str(h) + "_", str(v))
    h += 1
h = 1
for v in hitemps:
    output = output.replace("TEMP_HI_" + str(h) + "_", str(v))
    h += 1
h = 1
for v in lotemps:
    output = output.replace("TEMP_LO_" + str(h) + "_", str(v))
    h += 1

# Grab the icon for the condition
h = 1
for v in cond_icons:
    CURR_COND_ICON_url = iconMap(v, True)
    if os.path.isfile(CURR_COND_ICON_url):
        fIcon = codecs.open(CURR_COND_ICON_url, "r", encoding="utf-8")
        fIcon.readline()
        icon = fIcon.readline()
        fIcon.close()
    else:
        fIcon = codecs.open("weather-icons/unknown.svg", "r", encoding="utf-8")
        fIcon.readline()
        icon = fIcon.readline()
        fIcon.close()
    output = output.replace("DAY_COND_ICON_" + str(h), icon)
    h += 1

# Add transit information
output = addTransit(output)

output = output.replace("DISP_CURR", hide)
output = output.replace("DISP5DAY", show)
output = output.replace("DISP12HOUR", hide)

# Write output
codecs.open("weather-script-output-daily.svg", "w", encoding="utf-8").write(output)


def fib_loop(n: int) -> int:
    if n == 1 or n == 2:
        return 1
    temp1: int = 1
    temp2: int = 1
    cnt: int = 2
    while cnt < n:
        temp: int = temp2
        temp2 = temp1 + temp2
        temp1 = temp
        cnt += 1
    return temp2

def fib_rec(n: int) -> int:
    if n == 1:
        return 1
    if n == 0:
        return 0
    return fib_rec(n - 1) + fib_rec(n - 2)

print(fib_loop(10))
print(fib_rec(10))


import cv2
import json
from PIL import Image

ICDAR_FOLDER = './icdar_formatted'
UNITY_FOLDER = 'C:/Users/Supremus/Documents/GitHub/HDRP_Test2/output_dataset'

with open(UNITY_FOLDER + '/bounding_boxes.json') as f:

    for line in f:

        data = json.loads(line)

        print(data)

        img = cv2.imread(UNITY_FOLDER + '/' + data['picName'])
        height, width, channels = img.shape

        polygon_x1, polygon_y1 = data['polygon_x1'], height - data['polygon_y1']
        polygon_x2, polygon_y2 = data['polygon_x2'], height - data['polygon_y2']
        polygon_x3, polygon_y3 = data['polygon_x3'], height - data['polygon_y3']
        polygon_x4, polygon_y4 = data['polygon_x4'], height - data['polygon_y4']

        correct_str = data['groundTruth'].replace('s', ' ').replace('l', '/').replace('m', '-').replace('p', '.')

        im = Image.open(UNITY_FOLDER + '/' + data['picName'])
        rgb_im = im.convert('RGB')
        rgb_im.save(ICDAR_FOLDER + '/' + data['picName'].split('.')[0] + '.jpg')

        with open(ICDAR_FOLDER + '/' + data['picName'].split('.')[0] + '.txt', 'w', encoding='utf-8-sig') as out_csv:
            out_csv.write(str(polygon_x1) + ',' + str(polygon_y1) + ',' +
                          str(polygon_x2) + ',' + str(polygon_y2) + ',' +
                          str(polygon_x3) + ',' + str(polygon_y3) + ',' +
                          str(polygon_x4) + ',' + str(polygon_y4) + ',' +
                          correct_str)


import re

class pde():

    def __init__(self, f_var, vrs, eq_str):
        """
        Initializes a PDE object with given variables and string rep of equation
        :param f_var : character of the solution function        | f_var  = 'U'
        :param vars  : list of variables as characters           | vars   = ['x','t']
        :param eq_str: string representing the equation to solve | eq_str = "U_xx - U_tt = 0"
        """

        # Check parameter types before initializing
        assert type(f_var)  is str
        assert type(vrs)    is list
        assert type(eq_str) is str

        self.f_var   = f_var
        self.vrs     = vrs
        self.eq_str  = eq_str
        self.allvars = vrs.copy()
        self.allvars.append(f_var)

        print(self.allvars)

        # Verify that the eq_str is valid
        chset = sorted(set(eq_str))
        print("chset for pde: {}".format(chset))
        sep = [x.strip() for x in re.split("=",eq_str)]
        print(sep)


import pygame
import time

import random
from libs.animation import Animation
from textures.buttons import TexButtons as txbuttons
import libs.vector as vec
from collections import OrderedDict
from abc import ABCMeta, abstractmethod
from engine import Engine

class Buttons:
    def __init__(self, surface):
        self.BLUE = surface.read(0)
        self.CYAN = surface.read(1)
        self.GREEN = surface.read(2)
        self.RED = surface.read(3)
        self.YELLOW = surface.read(4)

class Structure(pygame.sprite.Sprite):
    __metaclass__ = ABCMeta

    width = 96
    height = 96

    def __init__(self, position):
        super(Structure, self).__init__()
        self.engine = Engine
        self.position = position
        self.rect = pygame.Rect(self.position[0], self.position[1], self.width, self.height)
        self.text = pygame.font.SysFont('Arial', 14, bold=True)
        self.buttons = Buttons(Animation(txbuttons.BUTTONS, txbuttons.SCALED))
        self.position_offset = vec.new_add(self.position, (self.width/2, self.height/2))
        self.actions = []

        self.name = 'Unknown'
        self.max_health = 0
        self.current_health = 0
        self.armor = 0
        self.area = 30
        self.level = 1
        self.dead = False
        self.remove = False
        self.last_selected = None
        self.selector = None
        self.image = None

        self.time = time.time()

    def deal_damage(self, damage):
        if self.armor >= 0:
            dm = 100.0 / (100.0 + self.armor)
        else:
            dm = 2.0 - (100.0/(100.0-self.armor))

        self.current_health -= int(damage * dm)
        if self.current_health <= 0:
            self.dead = True

    @abstractmethod
    def update(self):
        pass

    @abstractmethod
    def render(self, screen, camera):
        pass

    @abstractmethod
    def menu_info(self):
        pass

    def render_health_bar(self, im, screen, camera):
        health_bar = pygame.Rect((self.rect.x, self.rect.y - (im.get_height() / 10)), (self.rect.width, 2))
        pygame.draw.rect(screen, (255, 255, 255), camera.apply(health_bar))

        percent = self.current_health * 1.0 / self.max_health
        hp = self.rect.width * percent
        if hp > 0:
            pygame.draw.rect(screen, (255, 0, 0), camera.apply(pygame.Rect(health_bar.topleft, (hp, 2))))

    def draw_selector(self, rect, screen, camera):
        ex, ey, ew, eh = (rect.x, rect.y + 22, rect.width * 1.4, rect.height / 2)
        selector = pygame.Surface((ew, eh), pygame.SRCALPHA)
        pygame.draw.ellipse(selector, (255, 255, 0, 196), (0, 0, ew, eh))
        screen.blit(selector, camera.apply((ex, ey)))

    def draw_on(self, main, *args):
        """draw surfaces on main surface. Centered."""
        for arg in args:
            tx = main.get_width() / 2 - arg.get_width() / 2
            ty = main.get_height() / 2 - arg.get_height() / 2
            main.blit(arg, (tx, ty))

    def draw_button(self, screen, camera, text_on=None):
        button = self.buttons.BLUE.copy()
        if text_on:
            text = self.text.render(str(text_on), False, (0, 0, 0))
        else:
            text = self.text.render(str(self.level), False, (0, 0, 0))
        self.draw_on(button, text)

        bx = self.rect.x + self.rect.width - 15
        by = self.rect.y + self.rect.height - 15
        screen.blit(button, camera.apply((bx, by)))

    def get_point_around_shape(self, unit_width, unit_height):
        points = [(self.rect.x + x*unit_width, self.rect.y + self.height) for x in range(self.width / unit_width)]
        # spawn_x, spawn_y = random.choice(points)
        return points


#!usr/bin/python3
import os
import re

# Program Catch
prog_pat = re.compile('\s*program\s*=(.+)\\n')
programs_set = set()

for subdir, dirs, files in os.walk('dataset-large'):
    for file in files:
        # Catch User file
        if file == 'user.txt':
        	with open(os.path.join(subdir, file)) as f:
        		for line in f:
        			if prog_pat.findall(line):
        				programs_set.add(prog_pat.findall(line)[0])

        	f.close()

for prog in sorted(programs_set):
	print(prog)


#!/usr/bin/env python3
import numpy as np
import pandas as pd
import sys
from sklearn.model_selection import KFold
from sklearn.metrics.pairwise import cosine_similarity

N = 30

VERBOSE = False

if '-v' in sys.argv:
  VERBOSE = True

def log(message):
  if VERBOSE:
    print(message)

"""
Importing data from different Folders
"""
folder = "ml-latest-small/"

linksdf = pd.read_csv(folder + "links.csv")
moviesdf = pd.read_csv(folder + "movies.csv")
tagsdf = pd.read_csv(folder + "tags.csv")
ratingsdf = pd.read_csv(folder + "ratings.csv")

"""
Logging headers from the different DataFrames
"""
log("Links headers are : " + str(list(linksdf)))
log("Tags headers are : " + str(list(tagsdf)))
log("Movies headers are : " + str(list(moviesdf)))
log("Ratings headers are : " + str(list(ratingsdf)))

"""Merge movies and ratings table"""

"""
Below are the lines to subtract the mean user rating from movie ratings.
This is done to get rid of the Rating bias introduced by the diifferent user.
"""
mean_user_rating = ratingsdf.groupby(['userId'], as_index = False, sort = False).mean().rename(columns = {'rating' : 'rating_mean'})[['userId', 'rating_mean']]
RatingsDF  = pd.merge(ratingsdf, mean_user_rating, on = 'userId', how = 'left', sort = False)
RatingsDF['adjusted'] = RatingsDF['rating'] - RatingsDF['rating_mean']
CFDF = pd.DataFrame({'userId' : RatingsDF['userId'], 'movieId' : RatingsDF['movieId'], "rating" : RatingsDF["adjusted"]})

"""
Loggin results of New DataFrame
"""
log("New CFDF  headers are : " + str(list(CFDF)))
log(CFDF)

result = CFDF.pivot_table(index = 'userId', columns = "movieId", values = "rating").fillna(0)
log(result)

""" What do I want to do????
For the whole dataset
-Calculate The Cosine Similarity

"""

def split_data(df):
    kf = KFold(n_splits=5, shuffle = True)
    errors = [pred_acc(df.ix[train_idx], df.ix[test_idx]) for train_idx, test_idx in kf.split(df)]
    print(errors)

def make_predictions(train_data):
  log("work in progress")
  print(train_data.shape)
  mean_user_rating = train_data.groupby(['userId'], as_index = False, sort = False).mean().rename(
  columns = {'rating' : 'rating_mean'})[['userId', 'rating_mean']]
  RatingsDF  = pd.merge(train_data, mean_user_rating, on = 'userId', how = 'left', sort = False)
  RatingsDF['adjusted'] = RatingsDF['rating'] - RatingsDF['rating_mean']
  CFDF = pd.DataFrame({'userId' : RatingsDF['userId'], 'movieId' : RatingsDF['movieId'], "rating" : RatingsDF["adjusted"]})
  result = CFDF.pivot_table(index = 'userId', columns = "movieId", values = "rating").fillna(0)
  correlation_matrix = similarity(result)
  weight_matrix = np.flip(np.sort(correlation_matrix), axis = 1)
  index_matrix = np.flip(np.argsort(correlation_matrix), axis = 1)
  user_ids = list(result.index)
  dictionary = {}
  print(train_data.shape)
  for idx in range(correlation_matrix.shape[0]):
    p1  = [user_ids[i] for i in index_matrix[idx, 1:N+1]]
    p2 = weight_matrix[idx, 1:N + 1]
    key = user_ids[idx]
    dictionary[key] = (p1, p2)
  return (CFDF, dictionary)
  """
  np.flip(sims[40, -(N + 1):610]))
  userIds =
  """
def mean_id(data):
  mean_user_rating = train_data.groupby(['userId'], as_index = False, sort = False).mean().rename(
  columns = {'rating' : 'rating_mean'})[['userId', 'rating_mean']]
  return mean_user_rating

def similarity(pivot_table):
  return cosine_similarity(pivot_table)

def get_ranking(movie_id, user_id, dic, CFDF):
  (indices, weights) = dic[user_id]
  total = 0
  rank = 0
  for i in range(len(indices)):
    rat = CFDF.loc[(CFDF["userId"] == [indices[i]]) & (CFDF["movieId"] == movie_id)]["rating"].values
    if len(rat) == 1:
      rank += rat[0] * weights[i]
      total += np.abs(weights[i])
  val = 0 if total == 0 else rank / total
  return val

def pred_acc(train_data, test_data):
  """
  Calculates the prediction error
  """
  print("getting prediction accuracy")
  print(train_data.shape)
  mean_user_rating = train_data.groupby(['userId'], as_index = False, sort = False).mean().rename(
  columns = {'rating' : 'rating_mean'})[['userId', 'rating_mean']]
  (CFDF, dictionary) = make_predictions(train_data)
  count = 0
  total = 0
  print("yo")
  print(train_data.shape)
  print(train_data.size)
  print(test_data.shape)
  for index, row in test_data.iterrows():
    uid = row["userId"]
    mid = row["movieId"]
    real_rank = row["rating"]
    pred_rank = get_ranking(mid, uid, dictionary, CFDF)
    mean = list(mean_user_rating.loc[mean_user_rating["userId"] == 610]["rating_mean"])[0]
    count += 1
    total += ((pred_rank + mean) - real_rank) ** 2
    if (count == 1000):
      print("we have proccessed " + str(count) + " rows")
  t = np.sqrt(total / count)
  print(t)
  return(t)

  """ For each value in test_data
  Get the mean rating for the user
  Get their rating
  subrtract the two
  call get_ranking()
  calculate the difference"""

make_predictions(ratingsdf)
print("starting the task")
val = split_data(ratingsdf)
print(val)

"""
mergedDF = pd.merge(, RatingsDF, on = 'movieId', how = 'left', sort = False)
result = mergedDF.pivot_table(index = 'userId', columns = 'movieId', values = 'rating')
result1 = mergedDF.pivot_table(index = 'userId', columns = 'movieId', aggfunc = 'mean')
log("Merged headers are : " + str(list(mergedDF)))
log(result)
log(result1)
df = pd.read_csv("crowd.tsv", encoding = "iso-8859-1", sep = '\t')
df = df[['id', 'question', 'opinion']]
mean = df.groupby(['id'], as_index = False, sort = False).mean().rename(columns = {'opinion' : 'opinion_mean'})[['id', 'opinion_mean']]
Opinions = pd.merge(df, mean, on = 'id', how = 'left', sort = False)
Opinions['adjusted'] = Opinions['opinion'] - Opinions['opinion_mean']
result = pd.DataFrame({'id':Opinions['id'], "question": Opinions['question'], "opinion" : Opinions['adjusted']})
result1 = result.pivot_table(index = 'id', columns = 'question', values = 'opinion').fillna(0)
from sklearn.metrics.pairwise import cosine_similarity
cosine_similarity(result1)
resulty = np.argsort(cosine_similarity(result1))
user = int(input("What is your ID? : "))
k = int(input("Value for K cut off? : "))
print(np.flip(resulty[user, -(k+1): 37]))
"""


#Python的循环有两种:
#第一种是for...in循环，依次把list或tuple中的每个元素迭代出来，看例子：
names = ['Michael','Bob','Tracy']
for name in names:
	print(name)

#所以for x in ...循环就是把每个元素代入变量x，然后执行缩进块的语句。再比如我们想计算1-10的整数之和，可以用一个sum变量做累加：
sum = 0
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
    sum = sum + x
print(sum)
#如果要计算1-100的整数之和，从1写到100有点困难，幸好Python提供一个range()函数，可以生成一个整数序列，
#再通过list()函数可以转换为list。比如range(5)生成的序列是从0开始小于5的整数：
print(list(range(5)))

#第二种循环是while循环，只要条件满足，就不断循环，条件不满足时退出循环。比如我们要计算100以内所有奇数之和，可以用while循环实现：
sum = 0
n = 99
while n > 0:
	sum += n
	n -= 2
print(sum)

#在循环中，break语句可以提前退出循环。
n = 0
while n <= 100:
	if n > 10:
		break
	n += 1
	print(n)
print('end')
#在循环过程中，也可以通过continue语句，跳过当前的这次循环，直接开始下一次循环。
n = 0
while n <= 10:
	n += 1
	if n % 2 == 0:
		continue
	print(n)
print('end')


import torch.nn as nn
import torch.nn.functional as F
import torch
from model.backbone import resnet, mobilenet, drn, vgg, xception
from model.backbone.layer_factory import ASPP_V2
from utils.net_util import weight_initialization, set_require_grad
from model.sync_batchnorm import SynchronizedBatchNorm1d, SynchronizedBatchNorm2d, SynchronizedBatchNorm3d

dilation_rates = [6, 12, 18, 24]
padding_series = [6, 12, 18, 24]
norm_instance = (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d,
                 SynchronizedBatchNorm1d, SynchronizedBatchNorm2d, SynchronizedBatchNorm3d)

class DeebLab(nn.Module):

    def __init__(self, num_classes, initial='kaiming', backbone='resnet'):
        super(DeebLab, self).__init__()
        support_backbone = ['resnet', 'mobilenet', 'drn', 'vgg', 'xception']
        assert support_backbone.__contains__(backbone), 'unsupported backbone'

        if backbone == 'resnet':
            self.backbone = resnet.resnet_101(pre_trained=True)
        elif backbone == 'mobilenet':
            self.backbone = mobilenet.mobilenet_v2(pre_trained=True)
        elif backbone == 'drn':
            self.backbone = drn.drn_d_105(pre_trained=True)
        elif backbone == 'vgg':
            self.backbone = vgg.vgg_16(pre_trained=True)
        elif backbone == 'xception':
            self.backbone = xception.modified_xception(pre_trained=True)

        for m in self.backbone.modules():
            if isinstance(m, nn.Conv2d):
                self.in_dim = m.weight.data.size()[0]

        self.dilation_rates = dilation_rates
        self.padding_series = padding_series
        self.classifier = weight_initialization(
            ASPP_V2(in_dim=self.in_dim, dilation_rates=dilation_rates, padding_rates=padding_series,
                    num_classes=num_classes), init_type=initial)
        self.classifier_aux = weight_initialization(
            ASPP_V2(in_dim=1024, dilation_rates=dilation_rates, padding_rates=padding_series,
                    num_classes=num_classes), init_type=initial)

        # freeze bn layers
        self.freeze_bn()

    def forward(self, x):
        h, w = x.size()[2:]
        feature_1, feature_2 = self.backbone(x)
        out1 = self.classifier_aux(feature_1)
        out2 = self.classifier(feature_2)
        out1 = F.interpolate(out1, size=(h, w), mode='bilinear', align_corners=True)
        out2 = F.interpolate(out2, size=(h, w), mode='bilinear', align_corners=True)
        return out1, out2

    def freeze_bn(self):
        """
        freeze the batch normalization layers
        """
        for module in self.modules():
            if isinstance(module, norm_instance):
                set_require_grad(module, False)

    def get_1x_lr_params(self):
        modules = []
        modules.append(self.backbone)

        for i in range(len(modules)):
            for j in modules[i].modules():
                if isinstance(j, nn.Conv2d) or isinstance(j, norm_instance):
                    for k in j.parameters():
                        if k.requires_grad:
                            yield k

    def get_10x_lr_params(self):
        modules = []
        modules.append(self.classifier)
        modules.append(self.classifier_aux)

        for i in range(len(modules)):
            for j in modules[i].modules():
                if isinstance(j, nn.Conv2d) or isinstance(j, norm_instance):
                    for k in j.parameters():
                        if k.requires_grad:
                            yield k

    def get_optim_params(self, parser):
        return [{'params': self.get_1x_lr_params(), 'lr': parser.learning_rate},
                {'params': self.get_10x_lr_params(), 'lr': 10 * parser.learning_rate}]

if __name__ == '__main__':
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    deeplab = DeebLab(num_classes=19, backbone='resnet')
    deeplab = deeplab.to(device)
    image = torch.ones(1, 3, 720, 1280)
    image = image.to(device)
    _, output = deeplab(image)
    print(output)
    print(output.size())


import pytest
from django.shortcuts import reverse
from django.test import TestCase

from dino.synczones.models import Zone

@pytest.mark.django_db()
def test_zonelistview(client_admin, mock_pdns_get_zones):
    response = client_admin.get(reverse('zoneeditor:zone_list'))
    content = response.content.decode()
    assert response.status_code == 200
    assert 'example.com.' in content
    assert 'example.org.' in content
    assert 'example11.org' in content
    assert 'example400.org' not in content

@pytest.mark.django_db()
def test_zonelistview_sync(client_admin, mock_pdns_get_zones):
    assert Zone.objects.all().count() == 0
    client_admin.get(reverse('zoneeditor:zone_list'))
    assert Zone.objects.all().count() > 2
    assert Zone.objects.filter(name='example.com.').exists()

@pytest.mark.django_db()
def test_zonelistview_filter(client_admin, mock_pdns_get_zones):
    response = client_admin.get(reverse('zoneeditor:zone_list') + '?q=xample.org.')
    response.content.decode()
    assert response.status_code == 200
    assert len(response.context['object_list']) == 1
    assert response.context['object_list'][0].name == 'example.org.'

@pytest.mark.parametrize('q', [
    'example.org',
    'example.org.',
])
@pytest.mark.django_db()
def test_zonelistview_jump(client_admin, mock_pdns_get_zones, q):
    response = client_admin.get(reverse('zoneeditor:zone_list') + f'?q={q}')
    TestCase().assertRedirects(response, f'/zones/example.org.', fetch_redirect_response=False)

@pytest.mark.django_db()
def test_zonelistview_unauthenicated(client):
    url = reverse('zoneeditor:zone_list')
    response = client.get(url)
    TestCase().assertRedirects(response, f'/accounts/login/?next={url}', fetch_redirect_response=False)

@pytest.mark.django_db()
def test_zonelistview_user_tenant_admin(client_user_tenant_admin, mock_pdns_get_zones):
    response = client_user_tenant_admin.get(reverse('zoneeditor:zone_list'))
    content = response.content.decode()
    assert response.status_code == 200
    assert 'example.com.' in content
    assert 'example.org.' not in content
    assert 'example16.org' not in content

@pytest.mark.django_db()
def test_zonelistview_user_no_tenant(client_user_no_tenant, mock_pdns_get_zones):
    response = client_user_no_tenant.get(reverse('zoneeditor:zone_list'))
    content = response.content.decode()
    assert response.status_code == 200
    assert 'example.com.' not in content
    assert 'example.org.' not in content
    assert 'example16.org' not in content


#definiton of alerts: plot histogram for requested cities, and show outliers
# plot global map of outliers threshold

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import netCDF4
import sys
import time
from datetime import datetime
import matplotlib.patheffects as PathEffects
colors=[ '#434348', '#7cb5ec', '#90ed7d', '#f7a35c', '#8085e9', '#D8D8D8', '#f15c80', '#e4d354', '#8085e8', '#8d4653', '#91e8e1','#F3F781'];
plt.close('all')

cities=['Lille','Dakar','Beijing','Toronto']

#figure sizes
#square
fsc=4
#time serie
fsr=[12,4]

obspath='/lustre/storeB/project/aerocom/aerocom1/AEROCOM_OBSDATA/Export/AERONETSun2.0_20161029/'
modpath='/lustre/storeB/project/aerocom/aerocom1/ECMWF_OSUITE_NRT.old/renamed/'

thralert=0.0

# function to find index to nearest point
def near(array,value):
    idx=(np.abs(array-value)).argmin()
    return idx

#alert definition
def aeralert(od, odclim, thr):
    levalert=0
    if od>thr:
        if od/odclim>5:
            levalert=3
        elif od/odclim>3:
            levalert=2
        elif od/odclim>2:
            levalert=1
    if np.isnan(od):
        levalert=np.nan
    return levalert

#list of observation sites
from os import listdir
from os.path import isfile, join
import glob
fdir=obspath+'/'
onlyfiles = glob.glob(fdir+'od550aer_daily*')

selecfiles=[]
for f in onlyfiles:
    for city in cities:
        if city+'.txt' in f:
            selecfiles.append(f)

#read observation files to get coordinates
import csv
stat={'name':[],'lat':[],'lon':[]}
for f in selecfiles:
    after_under=f.split("_")[4]
    station=after_under.split(".txt")[0]
    readCSV = csv.reader(open(f), delimiter=':')
    for i, row in enumerate(readCSV):
        if i==1:
            lat=float(row[1])
        if i==2:
            lon=float(row[1])
            stat['name'].append(station)
            stat['lat'].append(lat)
            stat['lon'].append(lon)
            break

# - - - - - - - - - - - - - - - - - - -
#    read clim for calculation alerts

yrs=['2013','2014','2015']

ods={'2013':[],'2014':[],'2015':[]}
clims=ods
for iy, yr in enumerate(yrs):

    print('read',yr)
    #clim reading (NetCDF)
    pathclim='/lustre/storeB/project/aerocom/aerocom1/ECMWF_OSUITE_NRT.old/renamed/'
    climurl=pathclim+'aerocom.ECMWF_OSUITE_NRT.daily.alertaer.'+yr+'.nc'
    varclim='od550aerclim'
    varod='od550aer'
    nc = netCDF4.Dataset(climurl)
    lat = nc.variables['lat'][:]
    lon = nc.variables['lon'][:]
    times = nc.variables['time']
    clims[yr] = nc.variables[varclim][:,:,:]
    ods[yr] = nc.variables[varod][:,:,:]
    lon180=lon

#conversion 0|360 to -180|180
for il,l in enumerate(lon180):
    if l>180:
        lon180[il]=lon180[il]-360
lon=lon180

print(np.shape(ods['2013']))

seasons=['JFM','AMJ','JAS','OND']
i0s=[0,92,183,275]
i1s=[91,182,217,365]

#for each citie, plot histogram
for j, station in enumerate(stat['name']):
    for i, season in enumerate(seasons):
        print(station,season)
        tsod=[]

        #check index of lat lon for clim aod
        ix = near(lon, stat['lon'][j])
        iy = near(lat, stat['lat'][j])

        tsod=np.array([ods['2013'][i0s[i]:i1s[i],iy,ix],ods['2014'][i0s[i]:i1s[i],iy,ix],ods['2015'][i0s[i]:i1s[i],iy,ix]])
        tsod=tsod.flatten()
        tsodok=[]
        for tso in tsod:
            if tso>0:
                tsodok.append(tso)

        q75, q25 = np.percentile(tsodok, [75 ,25])
        iqr = np.subtract(*np.percentile(tsodok, [75, 25]))
        outlthr = q75 + 1.5 * iqr

        fig = plt.figure(i+j*10,figsize=(fsc,fsc))
        ax=plt.gca()
        ax.set_zorder(100)
        bins = np.arange(0,2,0.05)
        n, bins, patches = plt.hist(tsodok, bins, normed=1, facecolor='0.7', alpha=1,zorder=10,lw=1.5,edgecolor='white')
        #plt.title(stat['name'][j]+' ('+str(lon[ix])+';'+str(lat[iy])+')')
        plt.title(stat['name'][j]+' - '+season)
        plt.xlabel('AOD at 550 nm')
        plt.ylabel('Frequency')
        from matplotlib.ticker import FormatStrFormatter
        ax.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
        ax.locator_params(nbins=8, axis='x')

        #plot thr
        (ymin,ymax)=ax.get_ylim()
        plt.plot([outlthr,outlthr],[0,ymax*1.2],linewidth='2', color='red',zorder=20)
        plt.plot([q25,q25],[0,ymax*1.2],linestyle=':',linewidth='1', color='blue',zorder=1)
        plt.plot([q75,q75],[0,ymax*1.2],linestyle=':',linewidth='1', color='blue',zorder=1)
        plt.ylim((ymin,ymax*1.2))

        #
        (ymin,ymax)=ax.get_ylim()
        (xmin,xmax)=ax.get_xlim()
        xtxt=xmin+0.8*(xmax-xmin)
        ytxt=ymin+0.85*(ymax-ymin)
        dy=0.1*(ymax-ymin)
        #plt.text(xtxt,ytxt,season,color='k')
        plt.text(xtxt,ytxt,str(round(outlthr,2)),color='red',zorder=30,bbox=dict(boxstyle='square,pad=0', fc='white', alpha=1, ec='none'))

        plt.subplots_adjust(left=0.17, right=0.90, top=0.9, bottom=0.14)
        #plt.show()
        fig.savefig('./defalert/'+station+'-'+season+'-distrib.png', dpi=300)
        #print time serie: if large seasonality, cannot apply one threshold


###########################################
### JOGO DA VELHA COM INTERFACE GRAFICA ###
###                                     ###
### João Carlos                15/11/16 ###
###########################################

from tkinter import *

#criando a janela
instancia_Tk = Tk()

#Titulo
instancia_Tk.title("Jogo da Velha")

#especificando o tamanho da janela
instancia_Tk.geometry('550x400')

#deixando a tela em tamanho fixo
instancia_Tk.resizable(width=False, height=False)

class Game:
	def __init__(self, instancia):

		self.sub_frames = {}
		self.buttons = {}

		self.gameFrame = Frame(instancia)
		self.victory = Frame(instancia)

		self.gameFrame.grid(row=0, column=0, sticky='news')
		self.victory.grid(row=0, column=0, sticky='news')

		self.test = True

		x = 0

		self.sub_frames['f%i'%(x)] = Frame(self.gameFrame)
		self.sub_frames['f%i'%(x+1)] = Frame(self.gameFrame)
		self.sub_frames['f%i'%(x+2)] = Frame(self.gameFrame)

		self.sub_frames['f%i'%(x)].pack()
		self.sub_frames['f%i'%(x+1)].pack()
		self.sub_frames['f%i'%(x+2)].pack()

		x = 0

		self.labelVictory = Label(self.victory, text = "VITÓRIAA!!!!").pack()

		self.label = Label(self.sub_frames['f0'], text = "", font = ("Verdana", '27')).pack()

		self.b1 = Button(self.sub_frames['f%i'%(x)], text = "  ", font = ("Verdana", '50', "bold"), padx = "35",  fg = 'blue', command = self.click_b1)
		self.b2 = Button(self.sub_frames['f%i'%(x)], text = "  ", font = ("Verdana", '50', "bold"), padx = "35",  fg = 'blue', command = self.click_b2)
		self.b3 = Button(self.sub_frames['f%i'%(x)], text = "  ", font = ("Verdana", '50', "bold"), padx = "35",  fg = 'blue', command = self.click_b3)
		self.b4 = Button(self.sub_frames['f%i'%(x+1)], text = "  ", font = ("Verdana", '50', "bold"), padx = "35",  fg = 'blue', command = self.click_b4)
		self.b5 = Button(self.sub_frames['f%i'%(x+1)], text = "  ", font = ("Verdana", '50', "bold"), padx = "35",  fg = 'blue', command = self.click_b5)
		self.b6 = Button(self.sub_frames['f%i'%(x+1)], text = "  ", font = ("Verdana", '50', "bold"), padx = "35",  fg = 'blue', command = self.click_b6)
		self.b7 = Button(self.sub_frames['f%i'%(x+2)], text = "  ", font = ("Verdana", '50', "bold"), padx = "35",  fg = 'blue', command = self.click_b7)
		self.b8 = Button(self.sub_frames['f%i'%(x+2)], text = "  ", font = ("Verdana", '50', "bold"), padx = "35",  fg = 'blue', command = self.click_b8)
		self.b9 = Button(self.sub_frames['f%i'%(x+2)], text = "  ", font = ("Verdana", '50', "bold"), padx = "35",  fg = 'blue', command = self.click_b9)

		self.b1.pack(side = 'left')
		self.b2.pack(side = 'left')
		self.b3.pack(side = 'left')
		self.b4.pack(side = 'left')
		self.b5.pack(side = 'left')
		self.b6.pack(side = 'left')
		self.b7.pack(side = 'left')
		self.b8.pack(side = 'left')
		self.b9.pack(side = 'left')

		self.show_frame(self.gameFrame)

	def click_b1(self):
		if self.test:
			self.b1['text'] = 'X'
			self.test = False
		else:
			self.b1['text'] = 'O'
			self.test = True
		self.test_victory()

	def click_b2(self):
		if self.test:
			self.b2['text'] = 'X'
			self.test = False
		else:
			self.b2['text'] = 'O'
			self.test = True
		self.test_victory()

	def click_b3(self):
		if self.test:
			self.b3['text'] = 'X'
			self.test = False
		else:
			self.b3['text'] = 'O'
			self.test = True

	def click_b4(self):
		if self.test:
			self.b4['text'] = 'X'
			self.test = False
		else:
			self.b4['text'] = 'O'
			self.test = True
		self.test_victory()

	def click_b5(self):
		if self.test:
			self.b5['text'] = 'X'
			self.test = False
		else:
			self.b5['text'] = 'O'
			self.test = True
		self.test_victory()

	def click_b6(self):
		if self.test:
			self.b6['text'] = 'X'
			self.test = False
		else:
			self.b6['text'] = 'O'
			self.test = True
		self.test_victory()

	def click_b7(self):
		if self.test:
			self.b7['text'] = 'X'
			self.test = False
		else:
			self.b7['text'] = 'O'
			self.test = True
		self.test_victory()

	def click_b8(self):
		if self.test:
			self.b8['text'] = 'X'
			self.test = False
		else:
			self.b8['text'] = 'O'
			self.test = True
		self.test_victory()

	def click_b9(self):
		if self.test:
			self.b9['text'] = 'X'
			self.test = False
		else:
			self.b9['text'] = 'O'
			self.test = True
		self.test_victory()

	def show_frame(self, frame):
		frame.tkraise()

	def test_victory(self):
		if (self.b1['text'] == self.b2['text'] == self.b3['text']) and (self.b1['text'] != "  "):
			self.show_frame(self.victory)

# Criando objeto de Game
Game(instancia_Tk)

# Loop do game
instancia_Tk.mainloop()


from __future__ import division
import numpy as np
import matplotlib.pyplot as plt

alpha = 1

def getTemp(alpha, L=1, tMax=0.1):
    dt = 0.00005
    dx = 0.01
    Nx = int(L / dx)
    dx = L / Nx
    Nt = int(tMax / dt)
    dt = tMax / Nt

    dx = L / Nx
    dt = tMax / Nt

    assert dt * alpha / dx ** 2 <= 0.5, 'Parameters are not numerically stable'

    temp = np.zeros(Nx)
    temp[0] = 1

    for i in range(Nt):
        temp[1:-1] += dt * alpha / dx ** 2 * (temp[0:-2] - 2 * temp[1:-1] + temp[2:])
    return temp, np.linspace(0, L, Nx)

T, x = getTemp(alpha)
plt.plot(x, T)
plt.show()


#! /usr/bin/python
"""
 Usage: test with -->
    cat books_inverted_index/part-00000 | python query_mapper.py | sort -k1,1 -k2,1 | python query_reducer.py
"""

from sys import stdin
import os
import ast
import math

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

#finds total number of books in books directory
#for rel_rank system to work
path = './books'

#count = number of books
total_docs = len([f for f in os.listdir(path)
                if os.path.isfile(os.path.join(path, f))])
#subtract 1 because there is a .DS_STORE file on when testing on macs
total_docs = (float)(total_docs - 1)

# both programs need to reference the same keys
#keys = ['yours', 'you', 'yield', 'king', 'shield', 'young', 'yawned', 'yards', 'xfas']

keywords_file =os.path.dirname(os.path.realpath(__file__))+'/search_keywords.txt'
with open(keywords_file) as f:
    keywords = f.read()
    keys = ast.literal_eval(keywords)

###########
# RANKING #
###########
reducer_index = {}
rel_index = {}
for line in stdin:
    # guard against blank lines
    if len(line.split('\t')) < 3:
        continue

    word, count_and_book, listing = line.split('\t')
    count, book = count_and_book.split(':')

    if word not in reducer_index:
        reducer_index[word] = []
        rel_index[word] = []

    reducer_index[word].append([int(count), book, listing])
    rel_index[word].append([int(count), book])

# sort when we're done, DESC --> so highest frequency is first
for word in reducer_index:
    reducer_index[word].sort(reverse=True)

# use algorithm to calculate the weight of a word in a doc
# w(key, doc) = (1 + log2 freq(key,doc)) * log2 (N / n(doc))
# w(key, doc) is the weight of a word(key) in some doc
# freq(key, doc) is just the frequency of a word in some doc
# (N/n(doc)) where N = number of total docs, and n(doc) = number of docs the word appears in
# for more info : https://en.wikipedia.org/wiki/Tf%E2%80%93idf
def calc_weight(freq, doc_freq):

    #this is part calculation of idf which is inverse document frequency
    part_idf = total_docs/doc_freq
    idf = math.log(part_idf, 2)

    #this is calculation of term frequency
    tf = 1 + math.log(freq, 2)
    weight = idf*tf
    weight = round(weight, 6)

    #returns the weight of some word in given doc
    return weight

weights_per_doc = {}
total_weights = {}
##########################
#RELEVENCE RANKING SYSTEM#
##########################
def rel_rank(word):
    #number of docs the word appears in
    doc_freq = len(rel_index[word])

    for temp_book in rel_index[word]:
        #number of times the term appears in given doc
        freq = temp_book[0]

        #doc name -> book name
        doc = temp_book[1]

        #The weight of the word in given doc based on the number of docs
        #it appears in and total number of docs.
        weight = calc_weight(freq, doc_freq)

        if doc not in weights_per_doc:
            weights_per_doc[doc] = [word, weight]
            total_weights[doc] = weight
        else:
            weights_per_doc[doc].append([word, weight])
            total_weights[doc] = total_weights[doc] + weight

#search term string
search_term = " "
#do all the calculations using rel_rank
for key in keys:
    if key in reducer_index:
        rel_rank(key)
search_term = search_term.join(keys)

#sort the weights in decending order for ease of access
sort_weights = sorted(total_weights.items(), key=lambda value: value[1], reverse=True)

###############################
# RELEVANCE RANKING RETRIEVAL #
###############################
print('================================================================================')
print('     BUSQUEDA: --> "%s"' % search_term)
print('================================================================================')

# split the term, to go through
search_list = search_term.split()

save_line_num = {}
#find if any words appear in the same context, in other words a phrase
for x in range(0, 3):

    #go through each word
    for some_word in search_list:
         #if there are an words at all
         if sort_weights:
             #find the word in index
             if some_word in reducer_index:
                 #get infor about the word
                 for target_data in reducer_index[some_word]:

                     #if it's the word from the book we are looking for
                     if target_data[1] == sort_weights[x][0]:

                         # get the first line number
                         line_data = ast.literal_eval(target_data[2])

                         #sort line data so, if it's a phrase the line numbers will be the same
                         line_data.sort()

                         #pick the first available line_num
                         #AKA the first place it appears at
                         line_num = line_data[0]  # could slice to :n, to get the first `n` numbers

                         #record the doc we are in
                         doc = target_data[1]

                         #create a tuple with line number and doc
                         target = (line_num, doc)

                         #if it's already not in our dictionary, add it to the dictionarry
                         #with prev tuple as the key
                         if target not in save_line_num:
                             #put the word at given tuple
                             save_line_num[(line_num, doc)] = [some_word]
                         else:
                             #if it line_num and doc tuple is alread there, it means the word is
                             #probably part of a phrase
                             save_line_num[(line_num, doc)].append(some_word)
         else:
             print("No se encontraron palabras!")

print_term = " "
#print the top 3 results from the weights_per_doc
for x in range(0, 3):
    print("\n")
    if sort_weights:
        #the total weight per doc, which is search_term[0]_weight + search_term[1]_weigth +..search_term[n]_weight
        #added some boldness to weight for aesthetics
        print_weight = ("Peso = %f"%(sort_weights[x][1]))
        print_weight = bcolors.BOLD + print_weight + bcolors.ENDC
        print("Resultado %d --> %s"%(x+1,print_weight))
        #print title
        cur_title = bcolors.OKBLUE+ bcolors.BOLD +  sort_weights[x][0] + bcolors.ENDC
        print("TITULO : %s\n" %(cur_title))

    for some_line in save_line_num:
        if some_line[1]==sort_weights[x][0]:

            #display what key words the context is for
            word_list = save_line_num[some_line]
            print_term = ", ".join(word_list)
            print("Ultimas entradas para los terminos : %s"%(print_term))
            print("---------------------------------------------------------------------------------------------------------")
            print("---------------------------------------------------------------------------------------------------------")

            #get line number
            line_num = some_line[0]

            # get the filename
            fname = some_line[1]

            # get the directory
            dir_path = os.path.dirname(os.path.realpath(__file__))

            # concat full path for our file
            fpath = dir_path + '/books/' + fname

            # only the grab the context for lines right our around our target
            context = ""
            with open(fpath) as f:
                for i, line in enumerate(f):
                    if i == line_num - 2:
                        context += '\t' + line
                    if i == line_num - 1:
                        context += '\t' + bcolors.OKGREEN + line + bcolors.ENDC #added color for aesthetics
                    if i == line_num:
                        context += '\t' + line
                    if i == line_num + 1:
                        context += '\t' + line
                    if i == line_num + 2:
                        context += '\t' + line
            #print the context around the words in the search term
            print(context)
            print("---------------------------------------------------------------------------------------------------------")
            print("---------------------------------------------------------------------------------------------------------")

#############
# RETRIEVAL #
#############
# and finally ---> go find the results in the associated files
# iterate through each search term
for key in keys:

    print('======================================')
    print('     BUSQUEDA: --> "%s"' % key)
    print('======================================')

    # check if we have the key, at all
    if key in reducer_index:

        # get top 3 documents
        for idx in range(0, 3):

            # guard against out of bounds
            if idx > len(reducer_index[key]) - 1:
                break

            # otherwise, we can retrieve data!
            else:
                # index into the target file
                target_data = reducer_index[key][idx]

                # get the first line number
                line_data = ast.literal_eval(target_data[2])
                line_num = line_data[0]  # could slice to :n, to get the first `n` numbers

                # get word occurrences
                count = reducer_index[key][idx][0]

                # get the filename
                fname = target_data[1]

                # get the directory
                dir_path = os.path.dirname(os.path.realpath(__file__))

                # concat full path for our file
                fpath = dir_path + '/books/' + fname

                # only the grab the context for lines right our around our target
                context = ""
                with open(fpath) as f:
                    for i, line in enumerate(f):
                        if i == line_num - 2:
                            context += '\t' + line
                        if i == line_num -1:
                            context += '\t' + bcolors.OKGREEN + line + bcolors.ENDC
                        if i == line_num:
                            context += '\t' + line
                        if i == line_num + 1:
                            context += '\t' + line
                        if i == line_num + 2:
                            context += '\t' + line

                # and print our result!

                #bold count for aesthetics
                occur = bcolors.BOLD + str(count) + bcolors.ENDC

                #color book title for aesthetics
                fname = bcolors.OKBLUE + bcolors.BOLD + fname + bcolors.ENDC

                print('Resultado  %d para la busqueda de la palabra ---> `%s`:\nTITULO: %s\t >> Repeticiones de la palabra: %s << \n%s' %
                      ((idx + 1), key, fname, occur, context))

    # if we don't have the word, display this result for user
    else:
        print('------------------------------------')
        print('No se encontraron resultados para la palabra: "%s"' % key)
        print('------------------------------------')


from Persistence.Repositories import PacienteRepository

def get_all():
    return PacienteRepository.get_all()

def get_by_id(ide):
    if isinstance(ide, int):
        return PacienteRepository.get_by_id(ide)
    else:
        raise TypeError("El dato debe ser int")

def get_by_name(name):
    if isinstance(name, str):
        return PacienteRepository.get_by_name(name)
    else:
        raise TypeError("El dato debe ser str")

def get_by_numerohistorial(numerohistorial):
    if isinstance(numerohistorial, str):
        return PacienteRepository.get_by_numerohistorial(numerohistorial)
    else:
        raise TypeError("El dato debe ser str")

def create(paciente):
    if paciente.nombre == "":
        raise TypeError("Nombre paciente erroneo")
    if paciente.numerohistorial == "":
        raise TypeError("Numero de historial paciente erroneo")
    if paciente.fechanacimiento == "":
        raise TypeError("fecha nacimiento paciente erroneo")
    if paciente.sexo == "":
        raise TypeError("sexo paciente erroneo")
    if paciente.enfermedadesconocidas == "":
        raise TypeError("enfermedades conocidas paciente erroneo")
    if not isinstance(paciente.edad, int):
        raise TypeError("edad paciente erroneo")
    if not isinstance(paciente.edadconsulta, int):
        raise TypeError("edad consulta")
    PacienteRepository.create(paciente)

def update(paciente):
    if paciente.nombre == "" or paciente.numerohistorial == "" or paciente.fechanacimiento or paciente.sexo == "" \
            or paciente.enfermedadesconocidas == "" or not isinstance(paciente.edad, int) \
            or not isinstance(paciente.edadconsulta, int) or not isinstance(paciente.id, int):
        raise TypeError("La entidad no esta bien construida")
    PacienteRepository.update(paciente)

def delete(paciente):
    raise NotImplementedError("Esta opcion no se implementa")

def get_factores(paciente):
    if paciente.nombre == "" or paciente.numerohistorial == "" or paciente.fechanacimiento or paciente.sexo == "" \
            or paciente.enfermedadesconocidas == "" or not isinstance(paciente.edad, int) \
            or not isinstance(paciente.edadconsulta, int):
        raise TypeError("La entidad tiene campos en blanco")
    return PacienteRepository.get_factores(paciente)

def get_episodios(paciente):
    if paciente.nombre == "" or paciente.numerohistorial == "" or paciente.fechanacimiento or paciente.sexo == "" \
            or paciente.enfermedadesconocidas == "" or not isinstance(paciente.edad, int) \
            or not isinstance(paciente.edadconsulta, int):
        raise TypeError("La entidad tiene campos en blanco")
    return PacienteRepository.get_episodios(paciente)