from OpenGL.GLUT import *
from OpenGL.GLU import *
from OpenGL.GL import *
import numpy as np

x0 = -1
xn = 1

y0 = -1
yn = 1

n = 50
dx = (xn - x0)/n
dy = (yn - y0)/n

def f2(x,y):
    # Paraboloide Circular
    return x**2+y**2 # para cima

def f(x,y):
    # Paraboloide Circular
    return x**2-y**2 # para baixo

# cores de verde para azul
def cor (t, c1 = np.array([0,1,0]), c2 = np.array([0,0,1])):
    return c1 + t*(c2 - c1)

def desenhaSuperficie():

    y = y0 # posicao inicial de y, que vai andar conforme dy na vertical

    for i in range(n):
        x = x0 # posicao inicial de x, anda conforme dx
        glBegin(GL_TRIANGLE_STRIP) # tipo primitivo
        for j in range(n):
            # indica a cor para o ponto
            glColor3fv(cor(j/(n-1)))

            z = f(x, y)
            z2 = f(x,y + dy)

            glVertex3f(x, y, z) # desenha primeiro vertice
            glVertex3f(x, y + dy, z2) # desenha segundo vertice
            x += dx
        y += dy

        glEnd()

a = 0

def desenhaSuperficie2():

    y = y0

    for i in range(n):
        glBegin(GL_TRIANGLE_STRIP)
        x = x0
        for j in range(n):
            z = f2(x, y)
            z2 = f2(x,y + dy)
            glColor3fv(cor(j/(n-1)))

            glVertex3f(x, y, z)
            glVertex3f(x, y + dy, z2)
            x += dx
        y += dy

        glEnd()

def desenha():
    global a
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
    glPushMatrix()

    glTranslate(-3, 3, 0)
    glRotatef(-a,1,0,0)
    desenhaSuperficie()

    glPopMatrix()
    glPushMatrix()

    glTranslate(3, -3, 0)
    glRotatef(-a,1,0,0)
    desenhaSuperficie2()

    glPopMatrix()
    glutSwapBuffers()
    a += 1

def timer(i):
    glutPostRedisplay()
    glutTimerFunc(50,timer,1)

# PROGRAMA PRINCIPAL
glutInit(sys.argv)
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_MULTISAMPLE)
glutInitWindowSize(800,600)
glutCreateWindow("Superficie")
glutDisplayFunc(desenha)
glEnable(GL_MULTISAMPLE)
glEnable(GL_DEPTH_TEST)
glClearColor(0.,0.,0.,1.)
gluPerspective(45,800.0/600.0,0.1,100.0)
glTranslatef(0.0,0.0,-15)
glutTimerFunc(50,timer,1)
glutMainLoop()


import h5py
import cv2
import numpy as np
import os
import random

def get_images_list():
    list = []
    add_images("../images/", list)
    return list

def add_images(dir, list):
    for entry in os.scandir(dir):
        if entry.is_file():
            list.append(entry.path)
        elif entry.is_dir():
            add_images(entry.path, list)

def read_image(path):
    raw_image = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
    image = np.reshape(raw_image, (32 * 32))
    return image

def create_dataset(filelist, name):
    f = h5py.File(f"../dataset/{name}.h5", "w")
    # Create train dataset
    n = len(filelist)
    f.create_dataset(f"{name}_images", (n, 32*32), np.uint8)
    f.create_dataset(f"{name}_tags", (n, 1), np.uint8)
    f.create_dataset(f"{name}_files", (n, 1), dtype=h5py.string_dtype())

    print(f"Adding {n} images to {name} dataset")
    for i in range(n):
        path = filelist[i]
        img = read_image(path)
        f[f"{name}_images"][i] = img
        f[f"{name}_tags"][i] = 1 if "/a/" in path else 0
        f[f"{name}_files"][i] = path

    f.close()

def create_datasets(training_set, test_set):
    create_dataset(training_set, "train")
    create_dataset(test_set, "test")

def split_sets(images, split):
    n = len(images)
    training_size = int(n * split / 100)
    training_set = []
    for i in range(training_size):
        image = random.choice(images)
        training_set.append(image)
        images.remove(image)

    return training_set, images

if __name__ == '__main__':
    images = get_images_list()
    training_set, test_set = split_sets(images, 80)
    # print(len(training_set))
    # print(len(test_set))
    create_datasets(training_set, test_set)


import argparse
import struct
import time

from common.Control import Control
from common.Protocol.AutoIp import AutoIp

def activate_dhcp(deviceControl):
    # open connection to device
    deviceControl.open()
    deviceControl.login(Control.USERLEVEL_SERVICE, 'CUST_SERV')
    # setup ethernet mode to DHCP
    deviceControl.writeVariable(b'EIAddrMode', struct.pack('B', 1))
    time.sleep(1)
    deviceControl.invokeMethod(b'mEthUpdt')
    deviceControl.logout()

    deviceControl.login(Control.USERLEVEL_SERVICE, 'CUST_SERV')
    deviceControl.writeVariable(b'EIAddrMode', struct.pack('B', 1))
    deviceControl.logout()

    deviceControl.close()

def activate_static_ip(deviceControl, ip):
    # open connection to device
    deviceControl.open()
    deviceControl.login(Control.USERLEVEL_SERVICE, 'CUST_SERV')
    # setup ethernet mode to static IP
    deviceControl.writeVariable(b'EIIpAddr', struct.pack('>4B', *[int(x) for x in ip.split(".")]))
    deviceControl.writeVariable(b'EIAddrMode', struct.pack('B', 0))
    time.sleep(1)
    deviceControl.invokeMethod(b'mEthUpdt')
    deviceControl.logout()

    deviceControl.login(Control.USERLEVEL_SERVICE, 'CUST_SERV')
    deviceControl.writeVariable(b'EIAddrMode', struct.pack('B', 0))
    deviceControl.logout()

    deviceControl.close()

def find_device_ip(deviceType, interfaceIPAddress, interfaceNetMask):
    autoIp = AutoIp(interfaceIPAddress, interfaceNetMask)
    print('Scanning for device ...')
    devices = autoIp.scan()
    for dev in devices:
        if dev.items["DeviceType"][0] == deviceType:
            return dev.items['IPAddress'][0]

# === Device specific protocol & control_port mapping ===
# Visionary-T Mini CX      => CoLa2 / Port 2122
# handle argument parsing from cmd arguments
parser = argparse.ArgumentParser(description="Exemplary DHCP activation for SICK Visionary devices.")
parser.add_argument('-i', '--interfaceIPAddress', required=False, type=str,
                    default="192.168.1.2", help="The ip address of the network interface where device is connected to.")
parser.add_argument('-n', '--interfaceNetMask', required=False, type=str,
                    default="255.255.255.0", help="The subnet mask of the network interface where device is connected to.")
parser.add_argument('-si', '--staticIPAddress', required=False, type=str,
                    default="192.168.1.10", help="The static ip address of the device.")
parser.add_argument('-p', '--protocol', required=False, choices=['ColaB', 'Cola2'],
                    default="Cola2", help="The SICK CoLa protocol version.")
parser.add_argument('-c', '--control-port', required=False, type=int,
                    default=2122, help="The control port to change settings.")
parser.add_argument('-s', '--setback_static', required=False, type=bool,
                    default=False, help="The option to setback ethernet mode to static ip.")
args = parser.parse_args()

if __name__ == '__main__':
    deviceType = 'Visionary-T Mini CX V3S105-1x'
    deviceIP = find_device_ip(deviceType, args.interfaceIPAddress, args.interfaceNetMask)
    print("Initial IP Address of the device {}".format(deviceIP))

    # Obtain IP address from DHCP server
    print("Activating DHCP ethernet addressing mode ...")
    deviceControl = Control(ipAddress=deviceIP, protocol=args.protocol, control_port=args.control_port)
    activate_dhcp(deviceControl)
    print("Wait till IP address is obtained from DHCP server ...")
    time.sleep(30) # Default DHCP Server timeout
    deviceIP = find_device_ip(deviceType, args.interfaceIPAddress, args.interfaceNetMask)
    print("IP Address of the device obtained from DHCP Server {}".format(deviceIP))

    if args.setback_static:
        print("Revert ethernet addressing mode to static IP {}".format(args.staticIPAddress))
        del deviceControl
        deviceControl = Control(ipAddress=deviceIP, protocol=args.protocol, control_port=args.control_port)
        activate_static_ip(deviceControl, args.staticIPAddress)
        time.sleep(5)
        deviceIP = find_device_ip(deviceType, args.interfaceIPAddress, args.interfaceNetMask)
        print("IP Address of the device after setting static IP {}".format(deviceIP))


# !/usr/bin/python3
# coding: utf8
import os
import json
import tornado.web
import tornado.websocket
import tornado.ioloop
from algo_src.a_star import astar_launch
from algo_src.utils import spiral, validate_random_puzzle
from algo_src.heuristique import check_gaschnig, check_manhattan, check_hamming

uri = os.getenv("WS_HOST", "127.0.0.1")
port = os.getenv("WS_PORT", "8082")
address = "ws://" + uri + ":" + port
root = os.path.dirname(__file__)

class WebSocketHandler(tornado.websocket.WebSocketHandler):
	connections = set()

	def check_origin(self, origin):
		""" Is not important for this local project"""
		return True

	def open(self):
		self.connections.add(self)
		print("New client connected")

	def on_message(self, message):
		print("Transmitting message: %s" % message)

		front_msg = json.loads(message)
		message_send = {}

		print("DEBUG", front_msg)

		if ('algo' in front_msg.keys()):
			puzzle = front_msg['algo']['puzzle']
			if front_msg['algo']['heuristics'] == "manhattan":
				heuristics = check_manhattan
			elif front_msg['algo']['heuristics'] == "gaschnig":
				heuristics = check_gaschnig
			elif front_msg['algo']['heuristics'] == "hamming":
				heuristics = check_hamming
			factor = int(front_msg['algo']['factor'])
			size_puzzle = int(front_msg['algo']['size_puzzle'])
			message_send['algo'] = astar_launch(heuristics, puzzle, size_puzzle, factor)
		elif('random_puzzle' in front_msg.keys()):
			size_puzzle = front_msg['random_puzzle']
			message_send['random_puzzle'] = {}
			message_send['random_puzzle']['puzzle'] = validate_random_puzzle(int(size_puzzle))
			message_send['random_puzzle']['size_puzzle'] = size_puzzle

		elif('logs' in front_msg.keys()):
			print("Client send logs: %s" % front_msg['logs'])
			return

		if bool(message_send) == False:
			message_send['logs'] = "Error Message Socket invalid"

		print("Message send to a client: %s" % str(message_send))
		self.write_message(json.dumps(message_send))

	def on_close(self):
		self.connections.remove(self)
		print("Client disconnected")

print("URI ws://%s:%s is now open for web communication" % (uri, port))
application = tornado.web.Application([(r"/", WebSocketHandler)], debug=False)

if __name__ == "__main__":
	application.listen(8082)
	tornado.ioloop.IOLoop.instance().start()


#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""TOM Toolkit broker to listen to a Pitt-Google Pub/Sub stream via the REST API.

Relies on `ConsumerStreamRest` to manage the connections and work with data.

See especially:

.. autosummary::
   :nosignatures:

   BrokerStreamRest.request_alerts
   BrokerStreamRest.user_filter

"""

from django import forms
from tom_alerts.alerts import GenericQueryForm, GenericAlert, GenericBroker

from .consumer_stream_rest import ConsumerStreamRest
from .utils.templatetags.utility_tags import jd_to_readable_date

class FilterAlertsForm(GenericQueryForm):
    """Basic form for filtering alerts.

    Fields:

        subscription_name (``CharField``)

        classtar_threshold (``FloatField``)

        classtar_gt_lt (``ChoiceField``)

        max_results (``IntegerField``)
    """

    subscription_name = forms.CharField(
        required=True,
        initial='ztf-loop',
        help_text=(
            "The subscription will be created if it doesn't already exist "
            "in the user's project. The ztf-loop stream is recommended for testing. "
            "It is a 'heartbeat' stream with ~1 alert/sec."
        )
    )
    classtar_threshold = forms.FloatField(
        required=False,
        min_value=0,
        max_value=1,
        help_text="Star/Galaxy score threshold",
    )
    classtar_gt_lt = forms.ChoiceField(
        required=True,
        choices=[("lt", "less than"), ("gt", "greater than or equal")],
        initial="lt",
        widget=forms.RadioSelect,
        label="",
    )
    max_results = forms.IntegerField(
        required=False,
        initial=100,
        min_value=1,
    )

class BrokerStreamRest(GenericBroker):
    """Pitt-Google broker class to pull alerts from a stream via the REST API.

    Base class: ``tom_alerts.alerts.GenericBroker``
    """

    name = "Pitt-Google StreamRest"
    form = FilterAlertsForm

    def fetch_alerts(self, parameters):
        """Entry point to pull and filter alerts."""
        clean_params = self._clean_parameters(parameters)

        self.consumer = ConsumerStreamRest(clean_params['subscription_name'])

        alerts, i, max_tries = [], 0, 5  # avoid trying forever
        while (len(alerts) < parameters['max_results']) & (i < max_tries):
            i += 1
            clean_params['max_results'] = parameters['max_results'] - len(alerts)
            alerts += self.request_alerts(clean_params)  # List[dict]

        return iter(alerts)

    def request_alerts(self, parameters):
        """Pull alerts using a POST request with OAuth2, unpack, apply user filter.

        Returns:
            alerts (List[dict])
        """
        response = self.consumer.oauth2.post(
            f"{self.consumer.subscription_url}:pull",
            data={"maxMessages": parameters["max_results"]},
        )
        response.raise_for_status()
        alerts = self.consumer.unpack_and_ack_messages(
            response,
            lighten_alerts=True,
            callback=self.user_filter,
            parameters=parameters,
        )  # List[dict]
        return alerts

    @staticmethod
    def user_filter(alert_dict, parameters):
        """Apply the filter indicated by the form's parameters.

        Used as the `callback` to `BrokerStreamRest.unpack_and_ack_messages`.

        Args:
            `alert_dict`: Single alert, ZTF packet data as a dictionary.
                          The schema depends on the value of `lighten_alerts` passed to
                          `BrokerStreamRest.unpack_and_ack_messages`.
                          If `lighten_alerts=False` it is the original ZTF alert schema
                          (https://zwickytransientfacility.github.io/ztf-avro-alert/schema.html).
                          If `lighten_alerts=True` the dict is flattened and extra
                          fields are dropped.

            `parameters`: parameters submitted by the user through the form.

        Returns:
            `alert_dict` if it passes the filter, else `None`
        """
        if parameters["classtar_threshold"] is None:
            # no filter requested. all alerts pass
            return alert_dict

        # run the filter
        lt_threshold = alert_dict["classtar"] < parameters["classtar_threshold"]
        if ((parameters["classtar_gt_lt"] == "lt") & lt_threshold) or (
            (parameters["classtar_gt_lt"] == "gt") & ~lt_threshold
        ):
            return alert_dict
        else:
            return None

    def _clean_parameters(self, parameters):
        clean_params = dict(parameters)
        return clean_params

    def to_generic_alert(self, alert):
        """Map the Pitt-Google alert to a TOM `GenericAlert`."""
        return GenericAlert(
            timestamp=jd_to_readable_date(alert["jd"]),
            url=self.consumer.subscription_url,
            id=alert["candid"],
            name=alert["objectId"],
            ra=alert["ra"],
            dec=alert["dec"],
            mag=alert["magpsf"],
            score=alert["classtar"],
        )


"""Convert root into pandas dataframe
"""
from root_numpy import root2array
import pandas as pd
import numpy as np
import os
from textwrap import dedent
from pymongo import MongoClient
from tqdm import tqdm

def load_dataframe(filename, amplifier=10):
    """convert ROOT file into dataframe format.

    :param filename: file name including the path
    :return data: data in pandas dataframe format
    """
    data_1 = pd.DataFrame(root2array(filename, 'T1'))

    array_branches = []
    scalar_branches = ['BaseLineChannel', 'BaseLineChannelSigma', 'S2sPMT']  # these two are not scalar
    # columns that we want two peaks from them
    column_two = ['S2sPeak', 'S1sPeak', 'S1sTot', 'S2sTot', 'S2sPosX', 'S2sPosY']
    for name in data_1.columns.values:
        if name in scalar_branches:
            continue
        if hasattr(data_1[name][0], '__len__'):
            if name in column_two:
                continue
            array_branches.append((name, np.nan))
            # TODO add length to different array
        else:
            scalar_branches.append(name)

    data_2 = pd.DataFrame(root2array(filename, branches=array_branches))

    data = pd.concat([data_1[scalar_branches], data_2], axis=1)

    # Add S1 S2 info including second s1 and s2
    info = {
        'S1sTot': {
            'array_branches': ('S1sTot', np.nan, 2),
            'column_name': ['s1', 'largest_other_s1']
        },
        'S2sTot': {
            'array_branches': ('S2sTot', np.nan, 2),
            'column_name': ['s2', 'largest_other_s2']
        },
        'S1sPeak': {
            'array_branches': ('S1sPeak', np.nan, 2),
            'column_name': ['s1_time', 'alt_s1_time']
        },
        'S2sPeak': {
            'array_branches': ('S2sPeak', np.nan, 2),
            'column_name': ['s2_time', 'alt_s2_time']
        },
        'S2sPosX': {
            'array_branches': ('S2sPosX', np.nan, 2),
            'column_name': ['x', 'alt_s2_x']
        },
        'S2sPosY': {
            'array_branches': ('S2sPosY', np.nan, 2),
            'column_name': ['y', 'alt_s2_y']
        }
    }
    for name, content in info.items():
        data_tmp = pd.DataFrame(data=root2array(filename, branches=content['array_branches']),
                                columns=content['column_name'])
        data = pd.concat([data, data_tmp], axis=1)

    # convert time from sample to us
    sample_to_us = 4 / 1e3
    time_columns = ['s1_time', 'alt_s1_time', 's2_time', 'alt_s2_time', 'S1sWidth', 'S1sLowWidth',
                    'S2sLowWidth', 'S2sWidth', 'S1sRiseTime', 'S1sDropTime', 'S2sRiseTime', 'S2sDropTime']
    for column in time_columns:
        data.loc[:, column] *= sample_to_us

    # divide signal by 10
    # TODO: just for temporal purpose. put this in processor in the future and remove these lines
    if amplifier:
        signal_columns = ['s1', 'largest_other_s1', 's2', 'largest_other_s2']
        for column in signal_columns:
            data.loc[:, column] /= amplifier

    # add alias
    data['drift_time'] = data['s2_time'] - data['s1_time']  # us
    data['r'] = np.sqrt(data['x'] ** 2 + data['y'] ** 2)

    return data

def load_path(path, amplifier=10):
    """Load all root files from specific path
    """
    assert isinstance(path, (str, list)), "path should be either string or list type"

    if isinstance(path, str):
        files = os.listdir(path)
        full_file_path_s = [os.path.join(path, file) for file in files if '.root' in file]

        data = load_dataframe(full_file_path_s, amplifier)
    else:
        data = pd.DataFrame()
        for path_ in path:
            data_tmp = load_path(path_)
            data = pd.concat([data, data_tmp], ignore_index=True)
    return data

def get_coll():
    """get data collection info from mongodb"""
    client = MongoClient('mongodb://sandix:%s@132.239.186.12:27017' % os.environ['MONGO_PASSWORD'])
    db = client['run']
    coll = db['data']
    return coll

def get_datasets():
    """get run info as pd dataframe"""
    coll = get_coll()
    doc_s = list(coll.find())
    datasets = pd.DataFrame(doc_s)
    return datasets.drop(['_id', 'processed_data_location'], axis=1)

def get_processor_version_name(processor):
    """get processor name from processor name.
    You may find it stupid, but '.' is not supported in BSON for mongodb..
    Plus we would like to send a reminder if name goes wrong... limited choices!"""
    if processor == 'sandix_v1.1':
        name = 'sandix_v1p1'
    elif processor == 'sandp_test':
        name = 'sandp_test'
    elif processor == 'sandp_test_nrd':
        name = 'sandp_test_nrd'
    else:
        raise ValueError("processor is either 'sandix_v1.1', 'sandp_test' or 'sandp_test_nrd', wanna try again?")

    return name

def run_number_to_file_s(run_numbers, processor):
    """find file path(s) and amplifier condition based on run numbers"""
    if not isinstance(run_numbers, list):
        run_numbers = run_numbers.tolist()
    coll = get_coll()
    doc_s = list(coll.find({'run_number': {'$in': run_numbers}}))

    version_name = get_processor_version_name(processor)

    run_info = doc_s_to_run_info(doc_s, version_name)

    return run_info

def doc_s_to_run_info(doc_s, version_name):
    """get info of run (file location, amplifier_on, run_number) based on doc after selection
    and processor version name"""
    run_info = []
    for doc in doc_s:
        if not os.path.exists(doc['processed_data_location'][version_name]):
            print('run: %d is not found, will be skipped' % doc['run_number'])
            continue

        run_info.append({'file_location': doc['processed_data_location'][version_name],
                         'amplifier_on': doc['amplifier_on'],
                         'run_number': doc['run_number']})

    return run_info

def get_file_from_path(path):
    """get absolute path for files under certain path(s)"""
    if isinstance(path, str):
        if not os.path.exists(path):
            return []

        files = os.listdir(path)
        full_path_s = [os.path.join(path, file) for file in files if '.root' in file]
    else:
        assert hasattr(path, '__len__'), "if 'path' is not a string, then it should be an array or list!"
        full_path_s_tmp = []
        for path_ in path:
            full_path_s_tmp.append(get_file_from_path(path_))

        full_path_s = [element for sub_path in full_path_s_tmp for element in sub_path]

    return full_path_s

def folders_to_path(folder, processor):
    """find absolute path of each folder based on name of folder and processor version"""
    version_name = get_processor_version_name(processor)

    if version_name == 'sandix_v1p1':  # TODO: put this into ini
        base_path = '/home/nilab/10T_Two/Processed/Run21/sandp_v1.1/Co57'

    elif version_name == 'sandp_test':
        base_path = '/home/nilab/10T_Two/Processed/Run21/sandp_test/SE_update_s1_width_10/Co57/'
    else:
        base_path = '/home/nilab/10T_Two/Processed/Run21/sandp_test/SE_update_s1_width_10_nrd/Co57/'

    if isinstance(folder, str):
        path = os.path.join(base_path, folder)

    else:
        assert hasattr(folder, '__len__'), "if 'folder' is not a string, then it should be an array or list!"
        path = [folders_to_path(folder_, processor) for folder_ in folder]

    return path

def folders_to_file_s(folder, processor):
    """find files and amplifier conditions based on folder name(s).
    Return dictionary with keys of file_location and amplifier_on"""
    path = folders_to_path(folder, processor)
    full_file_path = get_file_from_path(path)
    coll = get_coll()
    version_name = get_processor_version_name(processor)
    doc_s = list(coll.find({'processed_data_location.%s' %version_name: {'$in': full_file_path}}))

    run_info = doc_s_to_run_info(doc_s, version_name)

    return run_info

def judge_str(input):
    if isinstance(input, str):
        return True
    else:
        if hasattr(input, '__len__'):
            if isinstance(input[0], str):
                return True
            else:
                return False

def load(input, processor='sandix_v1.1'):
    """load data into pd dataframe by run numbers, or folder name"""
    # hardcode for now
    is_string = judge_str(input)

    if is_string:
        run_info = folders_to_file_s(input, processor)

    else:
        run_info = run_number_to_file_s(input, processor)

    data = pd.DataFrame()
    for run in tqdm(run_info, desc='load data'):
        if run['amplifier_on']:
            amplifier = 10
        else:
            amplifier = 1
        data_tmp = load_dataframe(run['file_location'], amplifier=amplifier)
        data_tmp['run_number'] = run['run_number']
        data = pd.concat([data, data_tmp], ignore_index=True)

    return data

def code_hider():
    """Stolen from hax
    Make a button in the jupyter notebook to hide all code
    """
    # Stolen from stackoverflow... forget which question
    # I would really like these buttons for every individual cell.. but I don't know how
    from IPython.display import HTML  # Please keep here, don't want hax to depend on ipython!
    return HTML(dedent('''
                       <script>
                       code_show=true
                       function code_toggle() {
                        if (code_show){
                        $('div.input').hide();
                          } else {
                        $('div.input').show();
                        }
                        code_show = !code_show
                       }
                       $( document ).ready(code_toggle);
                       </script>
                       <form action="javascript:code_toggle()"><input type="submit"
                       value="Show/hide  all code in this notebook"></form>'''))


import seaborn as sns
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import config
import torch
import numpy as np

def accuracy(predictions, labels):
    pred = torch.max(predictions, 1)[1]
    rights = pred.eq(labels.data.view_as(pred)).sum()
    return rights, len(labels)

def evaluate_data(net,data,device):
    net.eval()
    val_rights = []
    outputs = []
    targets = []
    with torch.no_grad():

        for (data, target) in data:
            data = data.to(device)
            target = target.to(device)
            targets.append(target.cpu().numpy())

            output = net(data)
            pred = torch.max(output, 1)[1]

            outputs.append(pred.cpu().numpy())

            right = accuracy(output, target)
            val_rights.append(right)

    val_r = (sum([tup[0] for tup in val_rights]), sum([tup[1] for tup in val_rights]))
    label = config.labels

    list_targets = [y for x in targets for y in x]
    list_outputs = [y for x in outputs for y in x]

    sns.set()
    f, ax = plt.subplots()

    C2 = confusion_matrix(np.array(list_targets), np.array(list_outputs))
    for i in range(len(label)):
        print(label[i], '{:.2f}%'.format(C2[i][i] / np.sum(C2[i]) * 100))
    print('Average accuracy{:.2f}%'.format(100 * val_r[0].cpu().numpy() / val_r[1]))
    print(C2)
    sns.heatmap(C2, annot=True, ax=ax, fmt='.20g')

    ax.set_title('Confusion matrix')  #
    ax.set_xlabel('Predict\nIndoor, Outdoor, Transport')
    ax.set_ylabel('True\nIndoor, Outdoor, Transport')
    plt.savefig('confusion matrix.pdf')


import sys
from xml.dom import minidom
import ruamel.yaml

sys.setrecursionlimit(10**9)
yaml = ruamel.yaml.YAML()

final_graph = str
with open('simulazione_esame/esercizio_3/modo_browser/dp_mst.yaml') as fp:
     data = yaml.load(fp)
     final_graph = data['graphml']

xmldoc = minidom.parse(final_graph)

edge_list = xmldoc.getElementsByTagName('edge')
node_list = xmldoc.getElementsByTagName('node')
numero_nodi = len(node_list)
numero_archi = len(edge_list)

def node_edges():
     nodi_grafo = []
     for node_id in range(numero_nodi):
          nodi_grafo.append(node_list[node_id].attributes['id'].value)
     return nodi_grafo

def numero_node_edges():
     numero_nodi = len(node_list)
     numero_archi = len(edge_list)
     return numero_nodi, numero_archi

def node_position():
     coordinate_nodi = []
     node_x_y = xmldoc.getElementsByTagName('y:Geometry')

     for node_id in range(numero_nodi):
          x = node_x_y[node_id].attributes['x'].value
          y = node_x_y[node_id].attributes['y'].value
          coordinate_nodi.append([int(int(float(x))/13), int(int(float(y))/8)])
     return coordinate_nodi

def node_tag():
    node_tag = []
    tmp_node_tag = xmldoc.getElementsByTagName('y:NodeLabel')

    for node_id in range(len(tmp_node_tag)):
        if tmp_node_tag[node_id].getAttribute('tag') != "":
            node_tag.append(tmp_node_tag[node_id].getAttribute('tag'))

    # print(node_tag)

    return node_tag

def node_color():
    colori_nodi = []
    node_color = xmldoc.getElementsByTagName('y:Fill')

    for node_id in range(numero_nodi):
        color = node_color[node_id].attributes['color'].value
        colori_nodi.append(color)
    return colori_nodi

def node_arrow():
     archi_grafo_arrow = []
     arrow_list = xmldoc.getElementsByTagName('y:Arrows')
     arch_weight = xmldoc.getElementsByTagName('y:EdgeLabel')

     for count in range(numero_archi):
         weight = arch_weight[count].firstChild.data
         if weight == " ":
             weight = -13234214325

        #  if arrow_list[count].attributes['type'].value == 'curve':
        #      archi_grafo_arrow.append(
        #          [edge_list[count].attributes['source'].value, edge_list[count].attributes['target'].value, 'curve', weight, arrow_list[count].attributes['type'].value])
        # else:
         if arrow_list[count].attributes['target'].value == 'none' and arrow_list[count].attributes['source'].value == 'none':
             archi_grafo_arrow.append(
                 [edge_list[count].attributes['source'].value, edge_list[count].attributes['target'].value, 'line', weight, arrow_list[count].attributes['type'].value])

         elif arrow_list[count].attributes['target'].value == 'standard' and arrow_list[count].attributes['source'].value == 'none':
             archi_grafo_arrow.append(
                 [edge_list[count].attributes['source'].value, edge_list[count].attributes['target'].value, 'arrow', weight, arrow_list[count].attributes['type'].value])

         elif arrow_list[count].attributes['target'].value == 'standard' and arrow_list[count].attributes['source'].value == 'standard':
             archi_grafo_arrow.append(
                 [edge_list[count].attributes['source'].value, edge_list[count].attributes['target'].value, 'bidirectional', weight, arrow_list[count].attributes['type'].value])
     return archi_grafo_arrow

def edge_string():
     edge_to_string = '['

     for count in range(numero_archi):
          edge_to_string += '('
          edge_to_string += edge_list[count].attributes['source'].value + ',' + edge_list[count].attributes['target'].value
          edge_to_string += ')'
     return edge_to_string + ']'


import sys

file = open(sys.argv[1])
buffer = file.read()
buffer = buffer.split('\n')

wire1 = buffer[0].split(',')
wire2 = buffer[1].split(',')

intersections = [] #List of intersections
wirepoints = {} #Every point on the grid the first wire covers
coord = (0, 0) #Current X and Y coordinate

for lines in wire1:
    if lines[0] == 'U':
        for _ in range(int(lines[1:])):
            coord = (coord[0], coord[1] + 1)
            wirepoints[coord] = 1
    elif lines[0] == 'D':
        for _ in range(int(lines[1:])):
            coord = (coord[0], coord[1] - 1)
            wirepoints[coord] = 1
    elif lines[0] == 'L':
        for _ in range(int(lines[1:])):
            coord = (coord[0] - 1, coord[1])
            wirepoints[coord] = 1
    elif lines[0] == 'R':
        for _ in range(int(lines[1:])):
            coord = (coord[0] + 1, coord[1])
            wirepoints[coord] = 1

coord = [0, 0] #Reset at central port
for lines in wire2:
    if lines[0] == 'U':
        for _ in range(int(lines[1:])):
            coord = (coord[0], coord[1] + 1)
            if coord in wirepoints:
                intersections += [coord]
    elif lines[0] == 'D':
        for _ in range(int(lines[1:])):
            coord = (coord[0], coord[1] - 1)
            if coord in wirepoints:
                intersections += [coord]
    elif lines[0] == 'L':
        for _ in range(int(lines[1:])):
            coord = (coord[0] - 1, coord[1])
            if coord in wirepoints:
                intersections += [coord]
    elif lines[0] == 'R':
        for _ in range(int(lines[1:])):
            coord = (coord[0] + 1, coord[1])
            if coord in wirepoints:
                intersections += [coord]

shortest = abs(intersections[0][0]) + abs(intersections[0][1])
for cross in intersections:
    distance = abs(cross[0]) + abs(cross[1])
    if distance < shortest:
        shortest = distance

print("SHORTEST MANHATTEN DISTANCE: ")
print(shortest) #870


import os
import testinfra.utils.ansible_runner

testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
    os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')

def test_virtualenv(host):
    venv = '/opt/test/python3-virtualenv'
    host.check_output(venv + '/bin/python --version').startswith('Python 3.')
    host.check_output(venv + '/bin/pip --version').startswith('Python 3.')
    assert host.file(venv + '/bin/python').is_file
    assert host.file(venv + '/bin/python3').is_file
    assert host.file(venv + '/bin/pip').is_file
    assert host.file(venv + '/bin/pip3').is_file
    packages = host.check_output(venv + '/bin/pip freeze')
    assert 'omego==' in packages
    assert 'scc==' in packages


import matplotlib.pyplot as plt

fig, axs = plt.subplots(2,2)

weekdays = ['H', 'K', 'Sz', 'Cs', 'P']

# Hallgatok
axs[0][0].plot(weekdays, [6,5,2,1,1], label="Erik", marker='o', linewidth = 7, color='#ff00ff')
axs[0][0].plot(weekdays, [4,3,2,2,1], label="Balazs", marker='v', linestyle = '--')
axs[0][0].plot(weekdays, [4,3,0,2,1], label="Gergo", marker='d', linestyle='')
axs[0][0].set_title('Hallgatok oraterhelese')
axs[0][0].set_ylabel('Oraszam (db)')
axs[0][0].set_ybound(1,4)

# Mate
axs[0][0].legend()
axs[0][1].bar(weekdays,[7,4,0,2,0])
axs[0][1].set_title('Mate oraterhelese')

# ???
axs[1][0].scatter([0,10,50],[0,20,-10],[10,140,50],color=['red','blue','red'])

plt.show()


import argparse
import inspect
import math
import os
import tempfile
from pathlib import Path
from typing import Optional

import onnx
import torch
import transformers
from torch import nn

def disable_huggingface_init():
    """do not init model twice as it slow initialization"""

    torch.nn.init.kaiming_uniform_ = lambda x, *args, **kwargs: x
    torch.nn.init.uniform_ = lambda x, *args, **kwargs: x
    torch.nn.init.normal_ = lambda x, *args, **kwargs: x
    torch.nn.init.constant_ = lambda x, *args, **kwargs: x
    torch.nn.init.xavier_uniform_ = lambda x, *args, **kwargs: x
    torch.nn.init.xavier_normal_ = lambda x, *args, **kwargs: x
    torch.nn.init.kaiming_normal_ = lambda x, *args, **kwargs: x
    torch.nn.init.orthogonal_ = lambda x, *args, **kwargs: x

def get_model_parameter_size(model: nn.Module):
    """to calculate how much memory this model needs"""
    param_size = 0
    param_sum = 0
    for param in model.parameters():
        param_size += param.nelement() * param.element_size()
        param_sum += param.nelement()
    buffer_size = 0
    buffer_sum = 0
    for buffer in model.buffers():
        buffer_size += buffer.nelement() * buffer.element_size()
        buffer_sum += buffer.nelement()
    all_size = (param_size + buffer_size) / 1024 / 1024
    return all_size

def initialize_model_and_sample_inputs(hf_model: str, cache_dir: Optional[str], tokenizer=None):
    """
    get the pretrained torch model from hugginface,
    and sample model-inputs
    """

    disable_huggingface_init()

    model = transformers.AutoModelForCausalLM.from_pretrained(  # type: ignore
        hf_model, torch_dtype=torch.float16, cache_dir=cache_dir, trust_remote_code=True
    )
    if tokenizer is None:
        tokenizer = hf_model
    tokenizer = transformers.AutoTokenizer.from_pretrained(tokenizer)  # type: ignore

    sample_inputs = tuple(tokenizer("Hello, my dog is cute", return_tensors="pt").values())
    return model, sample_inputs

def auto_pipeline_parallel(model: nn.Module, gpulist: list, sample_inputs: tuple):
    """Make the model executable across multiple GPUs."""

    def input_gpu_device_hook(mod, inputs, kwargs):
        modifyed_inputs = []
        first_dev = None
        for layer_input in inputs:
            if type(layer_input) is not torch.Tensor:
                modifyed_inputs.append(layer_input)
            elif hasattr(mod, "weight"):
                modifyed_inputs.append(layer_input.to(mod.weight.device))
            elif hasattr(mod, "parameters"):
                device = next(mod.parameters(), layer_input).device
                modifyed_inputs.append(layer_input.to(device))
            elif hasattr(next(mod.children(), None), "weight"):
                modifyed_inputs.append(layer_input.to(next(mod.children()).weight.device))
            elif first_dev is not None and layer_input.device != first_dev:
                modifyed_inputs.append(layer_input.to(first_dev))
            else:
                modifyed_inputs.append(layer_input)
            if first_dev is None:
                first_dev = modifyed_inputs[0].device
        for key, value in kwargs.items():
            if type(value) is torch.Tensor:
                kwargs[key] = value.to(first_dev)

        return (tuple(modifyed_inputs), kwargs)

    def move_layer_to_device_rurc(mod, dev):
        mod.to(dev)
        for layer in mod.named_children():
            move_layer_to_device_rurc(layer[1], dev)

    model = model.half()
    all_hooks = []
    all_hooks.append(model.register_forward_pre_hook(input_gpu_device_hook, with_kwargs=True))
    pre_fix = next(iter(model.named_children()))[0]
    for top_name, top_module in model.named_children():
        for name, module in top_module.named_children():
            all_hooks.append(module.register_forward_pre_hook(input_gpu_device_hook, with_kwargs=True))
            if type(module) in [torch.nn.ModuleList]:
                num_layers_on_each_gpu = math.floor(len(module) / len(gpulist))
                for idx, attn_layer in enumerate(module):
                    all_hooks.append(attn_layer.register_forward_pre_hook(input_gpu_device_hook, with_kwargs=True))

                    to_dev = gpulist[min(idx // num_layers_on_each_gpu, len(gpulist))]
                    attn_layer.to(to_dev)
                    move_layer_to_device_rurc(attn_layer, to_dev)
                    print(f"move {pre_fix}.{name}.{idx} to {to_dev}")
            else:
                module.to(gpulist[0])
                print(f"move {pre_fix}.{name} to {gpulist[0]}")
        if len(list(top_module.named_children())) == 0:
            top_module.to(gpulist[0])
            print(f"move {top_name} to {gpulist[0]}")

    with torch.no_grad():
        model(sample_inputs[0], attention_mask=sample_inputs[1])
    return model

def retrieve_onnx_inputs(model: nn.Module, sample_inputs: tuple, with_past: bool):
    """
    auto retrieve onnx inputs from torch model as we can't enumlate all possibilities
    for all models
    """
    user_inputs = []

    def hook_for_inputs(_, inputs, kwargs):
        user_inputs.append((inputs, kwargs))
        return user_inputs[0]

    hook_handle = model.register_forward_pre_hook(hook_for_inputs, with_kwargs=True)

    forward_params = inspect.signature(model.forward).parameters
    input_keys = list(forward_params.keys())
    default_values = [forward_params.get(key).default for key in input_keys]
    out = model(sample_inputs[0], attention_mask=sample_inputs[1])
    hook_handle.remove()
    user_inputs = user_inputs[0]
    onnx_inputs = default_values
    for idx, _val in enumerate(user_inputs[0]):
        onnx_inputs[idx] = user_inputs[0][idx]
    for key, value in user_inputs[1].items():
        idx = input_keys.index(key)
        onnx_inputs[idx] = value
    for idx, (key, value) in enumerate(zip(input_keys, onnx_inputs)):
        if type(value) is torch.Tensor:
            value.to(model.device)
        # Didn't touch past_key_value now, please change it if you want
        if "use_cache" in key:
            onnx_inputs[idx] = with_past

    return input_keys, onnx_inputs, out.past_key_values

def move_to_approprate_device(model: nn.Module, sample_inputs_tp: tuple) -> nn.Module:
    """
    According to the model size, we will upload it to
    CPU if has no GPU or enough GPU memory,
    Single GPU if has only one GPU in local or model size is enough to fit one GPU
    Multiple GPU if there is more than one gpu in local and model is too large
    """
    total_mem_per_cpu = torch.cuda.get_device_properties(0).total_memory / 1024 / 1024

    print(f"Model_Size = {get_model_parameter_size(model)/1024} GB")
    print(f"total_mem_per_cpu = {total_mem_per_cpu/1024} GB")
    if get_model_parameter_size(model) > total_mem_per_cpu * 0.45:
        device_collection = [torch.device(i) for i in range(torch.cuda.device_count())]
        if len(device_collection) > 1:
            print(
                f"{len(device_collection)} GPUs are used to export onnx, \
                   Please set CUDA_VISIBLE_DEVICES to use specific GPU group"
            )
            model = auto_pipeline_parallel(model, device_collection, sample_inputs_tp)
        else:
            print("!!!! convert model to float and export onnx using CPU")
            model = model.cpu().float()
    else:
        print("Export model on a single GPU")
        model = model.cuda().half()
    return model

def adapt_inputs_to_device(sample_inputs: tuple, device: torch.device) -> tuple:
    """move inputs to device"""
    sample_inputs_ = []
    for sample_int in sample_inputs:
        if isinstance(sample_int, torch.Tensor):
            sample_inputs_.append(sample_int.to(device))
        else:
            sample_inputs_.append(sample_int)
    return tuple(sample_inputs_)

def fetch_onnx_inputs_outputs_name(
    model: nn.Module,
    onnx_inputs: list,
    torch_input_names: tuple,
    past_key_values: tuple,
    with_past: bool,
    input_with_past: bool,
):
    """fetch onnx inputs and outputs name"""
    num_of_past_key = 0
    kv_cache_axis = {0: "batch_size"}
    # try get num_of_past_key and shape of past_key_value
    if past_key_values is not None:
        num_of_past_key = len(past_key_values)
        seq_index = (torch.tensor(past_key_values[0][0].shape) == onnx_inputs[0].shape[-1]).nonzero().view(-1)
        assert seq_index.numel() == 1
        kv_cache_axis = {0: "batch_size", seq_index.item(): "seq_len"}

    if not num_of_past_key:
        num_of_past_key = model.config.num_hidden_layers

    onnx_inp_names = ("input_ids", "attention_mask")
    onnx_out_names = ("logits",)
    onnx_dynamic_axes = {
        "input_ids": {0: "batch_size", 1: "seq_len"},
        "attention_mask": {0: "batch_size", 1: "seq_len"},
    }
    if input_with_past:
        for i in range(num_of_past_key):
            onnx_inp_names += (f"present_key.{i}",)
            onnx_inp_names += (f"present_values.{i}",)

            onnx_dynamic_axes[onnx_inp_names[-1]] = kv_cache_axis
            onnx_dynamic_axes[onnx_inp_names[-2]] = kv_cache_axis

    if with_past or input_with_past:
        for i in range(num_of_past_key):
            onnx_out_names += (f"past_key.{i}",)
            onnx_out_names += (f"past_values.{i}",)
            onnx_dynamic_axes[onnx_out_names[-1]] = kv_cache_axis
            onnx_dynamic_axes[onnx_out_names[-2]] = kv_cache_axis

    for idx, name in enumerate(torch_input_names):
        if input_with_past:
            if name == "past_key_values":
                onnx_inputs[idx] = past_key_values
            elif name == "attention_mask":
                attn_mask = onnx_inputs[idx]
                onnx_inputs[idx] = torch.cat(
                    (attn_mask, torch.ones((attn_mask.shape[0], 1), device=attn_mask.device)), dim=1
                )
            elif name == "input_ids":
                input_ids = onnx_inputs[idx]
                onnx_inputs[idx] = input_ids[:, -1:]

    return onnx_inp_names, onnx_out_names, onnx_dynamic_axes

def do_export_internal(model: nn.Module, onnx_io_tuple: tuple, onnx_inputs: tuple, onnx_path: Path, opset: int):
    """do export with torch.onnx.export"""
    onnx_model_name = onnx_path.name
    onnx_inp_names, onnx_out_names, onnx_dynamic_axes = onnx_io_tuple
    # two step to export onnx
    # 1. export onnx with lots of pieces of weights
    # 2. save all weights to external data
    with tempfile.TemporaryDirectory() as tmpdirname:
        tmp_onnx = os.path.join(tmpdirname, "tmp.onnx")

        torch.onnx.export(
            model=model,
            args=tuple(onnx_inputs),
            f=tmp_onnx,
            verbose=False,
            opset_version=opset,
            input_names=onnx_inp_names,
            output_names=onnx_out_names,
            dynamic_axes=onnx_dynamic_axes,
        )

        onnx_path.unlink(missing_ok=True)
        (onnx_path.parent / f"{onnx_model_name}_ext.data").unlink(missing_ok=True)

        onnx_model = onnx.load(str(tmp_onnx))
        onnx.save_model(
            onnx_model,
            str(onnx_path),
            save_as_external_data=(len(os.listdir(tmpdirname)) > 1),
            all_tensors_to_one_file=True,
            location=f"{onnx_model_name}_ext.data",
            size_threshold=1024,
            convert_attribute=False,
        )

@torch.no_grad()
def export_onnx(hf_model: str, cache_dir: Optional[str], onnx_path_str: str, with_past: bool, opset: int):
    """
    do export
    model: torch model
    onnx_path: where the onnx model saved to
    sample_inputs_tp: inputs for torch model
    """
    model, sample_inputs_tp = initialize_model_and_sample_inputs(hf_model, cache_dir)

    model = move_to_approprate_device(model, sample_inputs_tp)

    sample_inputs = adapt_inputs_to_device(sample_inputs_tp, next(model.parameters()).device)

    # input_keys would be usesful if the model has some special inputs
    input_keys, onnx_inputs, past_key_value = retrieve_onnx_inputs(model, sample_inputs, with_past)

    onnx_io_tuple = fetch_onnx_inputs_outputs_name(model, onnx_inputs, input_keys, past_key_value, with_past, False)

    onnx_model_name = "model.onnx"
    onnx_path: Path = Path(onnx_path_str).absolute()
    if onnx_path.suffix != ".onnx":
        onnx_path = onnx_path / onnx_model_name

    do_export_internal(model, onnx_io_tuple, onnx_inputs, onnx_path, opset)
    if not with_past:
        return

    onnx_io_tuple = fetch_onnx_inputs_outputs_name(model, onnx_inputs, input_keys, past_key_value, with_past, True)

    onnx_model_name = "model_with_past.onnx"
    onnx_path = onnx_path.parent / onnx_model_name

    do_export_internal(model, onnx_io_tuple, onnx_inputs, onnx_path, opset)

def parse_arguments():
    """arguments parsing."""
    parser = argparse.ArgumentParser()

    parser.add_argument(
        "-m",
        "--model",
        required=True,
        type=str,
        default=["meta-llama/Llama-2-70b-hf"],
        help="Pre-trained models in huggingface model hub",
    )
    parser.add_argument(
        "-s",
        "--saved_path",
        required=False,
        type=str,
        default="./onnx_models/",
        help="where the onnx model will be saved",
    )
    parser.add_argument(
        "--cache_dir",
        required=False,
        type=str,
        default=None,
        help=("cache directy of huggingface, by setting this to avoid useless downloading if you have one"),
    )
    parser.add_argument(
        "--with_past",
        action="store_true",
        default=False,
        help=("The tool will export onnx without past-key-value by default"),
    )
    parser.add_argument(
        "--opset",
        required=False,
        type=int,
        default=17,
        help=(
            "the opset to save onnx model, \
              try to increase it if this opset doens't have new features you want"
        ),
    )
    return parser.parse_args()

if __name__ == "__main__":
    args = parse_arguments()

    export_onnx(args.model, args.cache_dir, args.saved_path, args.with_past, args.opset)


import os, ssl
import re
import numpy as np
import pandas as pd
import requests
import urllib.request
from bs4 import BeautifulSoup
from lxml import html

# Scrape with not valid SSL certificate
if (not os.environ.get('PYTHONHTTPSVERIFY', '') and
    getattr(ssl, '_create_unverified_context', None)):
    ssl._create_default_https_context = ssl._create_unverified_context

def data_from_given_city(URL, city_code, colnames, len_items):

    '''
    Returns a pandas dataframe with data extracted from SIOPE Website
    for a given IBGE city code.

    Parameters:

    URL: URL to extract tables
    city_code: city code from IBGE
    colnames: colnames to be passed to dataframe
    len_items: n# of columns with data
    '''
    URL = '{0}{1}'.format(URL, city_code)
    PAGE = urllib.request.urlopen(URL).read()
    soup = BeautifulSoup(PAGE)

    tables = soup.find_all('table', {'class': 'table'})
    list_of_tables = []

    for i in tables:
        storeTable = i.find_all('tr')
        tabledata = []
        finaldata = []

        for row in storeTable:
            cols = row.find_all('td')
            cols = [ele.text.strip() for ele in cols]
            tabledata.append([ele for ele in cols if ele])

        for item in tabledata:
            if len(item) > len_items:
                for row in range(len(item)):
                    item[row] = re.sub('\xa0%','', item[row])
                    item[row] = re.sub(',','.', item[row])
                finaldata.append(item)

        list_of_tables.append(finaldata)

    data = pd.DataFrame([item for sublist in list_of_tables for item in sublist],
                        columns=colnames)

    data['city_code'] = str(city_code)

    return(data)

# Get data from Years 2008 and 2016
data_slice_01 = data_from_given_city(
        URL='https://www.fnde.gov.br/siope/indicadoresFinanceirosEEducacionais.do?acao=PESQUISAR&anoPaginacao=2011&paginacao=-&pag=result&cod_uf=31&municipios=',
        city_code=317130,
        colnames=['id', 'var_name', 'y2008', 'y2009','y2010', 'y2011', 'y2012', 'y2013'], len_items=7)

data_slice_02 = data_from_given_city(URL='https://www.fnde.gov.br/siope/indicadoresFinanceirosEEducacionais.do?acao=PESQUISAR&anoPaginacao=2013&paginacao=%2B&pag=result&cod_uf=31&municipios=',
        city_code=317130,
        colnames=['id', 'var_name', 'y2014', 'y2015','y2016'],
        len_items=4)

data = data_slice_01.merge(data_slice_02, on=['id', 'var_name', 'city_code'])
data = data[ ['city_code'] + [ col for col in data.columns if col != 'city_code' ] ]

data.to_csv('~/Downloads/SIOPE.csv')


# uzytkownik podaje wielkosc listy, n > 0
# elementy listy losowane z przedzialu (x, y) podanego przez uzytkownika
# wyswietlenie listy uporzadkowanej rosnaco
# podanie szukanej liczby
# wyswietlenie czy taka jest lub jej nie ma a jesli jest to podac index
import random

def quicksort(l, r, list):
    if l >= r:
        return

    v = list[r]
    p = l

    for j in range(l, r):
        if list[j] < v:
            list[p], list[j] = list[j], list[p]
            p += 1

    list[p], list[r] = list[r], list[p]

    quicksort(l, p - 1, list)
    quicksort(p + 1, r, list)
    return list

def binarysearch(lista, left, right, szukana):
    left = 0
    right = n - 1
    srodek = (left + right) // 2
    while left <= right:
        srodek = (left + right) // 2
        if lista[srodek] == szukana:
            return srodek
        elif lista[srodek] > szukana:
            right = srodek - 1
        else:
            left = srodek + 1

    return -1

while True:
    n = int(input('podaj wielkosc tabeli: '))
    if n > 0:
        print('okej')
        break
    else:
        print('podaj n wiekrze od 0')

while True:
    x = int(input('podaj x: '))
    y = int(input('podaj y: '))
    if x <= y:
        print('jest ok')
        break
    else:
        print('x powinno byc mniejsze od y')

lista = [random.randint(x, y) for i in range(n)]
print(f'wygenerowana lista: {lista}')
quicksort(0, n - 1, lista)
print(f'posortowana lista: {lista}')
z = int(input('Jakiej liczby szukasz? '))
print(f'szukana liczba znajduje sie na indeksie: {binarysearch(lista,0,n,z)}')


import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time

Client = discord.Client()
client = commands.Bot(command_prefix = "!")

@client.event
async def on_ready():
    print("Učitavam Discord API")
    print("Povezivanje na servere....")
    print("Provjera tokena----")
    print("'Snješko bot' je spreman!")

@client.event
async def on_message(message):
    if message.content.upper() == "SULJO":
        await client.send_message(message.channel, ":pig: @Mifke, gdje si?")
    if message.content.upper().startswith('!ZULA'):
        userID = message.author.id
        await client.send_message(message.channel, "<@%s>, najbolji igrač je 'mitric[51]' " % (userID))
    if message.content.upper().startswith('!KOMANDE'):
        await client.send_message(message.channel, "Komande su : \n !zula - Prikaz najboljeg igrača (level) \n !napisi - Poruka u ime bota \n !sajt - Link sajta \n !sajt - Lista igrica \n ADMIN komande: \n !broadcast - Boldirana poruka na ekranu \n !ban - Banuj \n !unban - Unban \n !kick - Kickuj \n !mute - Muteuj ")
    if message.content.upper().startswith('!NAPISI'):
        args = message.content.split(" ")
        await client.send_message(message.channel, "%s" % (" ".join(args[1:])))
    if message.content.upper().startswith('!SAJT'):
        userID = message.author.id
        await client.send_message(message.channel, "<@%s>, posjeti link 'https://www.snjesko.ga/' " % (userID))
    if message.content.upper().startswith('!IGRICE'):
        await client.send_message(message.channel, "Zula Europe \n Counter-Strike: Global Offensive \n Grand Theft Auto V \n Fortnite \n Far Cry 5 \n Subnautica \n Kerbal Space Program")
@client.command(pass_context=True)
async def obrisi(ctx, amount=100):
    channel = ctx.message.channel
    messages = []
    async for message in client.logs_from(channel, limit=int(amount)):
        messages.append(message)
    await client.delete_message(messages)
    await client.say('Poruke obrisane.')

 #Sistem moderacije
@client.command()
@commands.has_permissions(administrator=True)
async def kick(ctx, member:discord.Member = None):
    if not member:
        await ctx.send("Molim izaberi korisnika")
        return
    await member.kick()
    await ctx.send(f"{member.mention} je kikovan")
@kick.error
async def kick_error(ctx, error):
    if isinstance(error, commands.CheckFailure):
        await ctx.send("Nemaš dozovlu da kickuješ korisnike!")

@client.command()
@commands.has_permissions(administrator=True)
async def ban(ctx, member:discord.Member = None):
    if not member:
        await ctx.send("Molim izaberi korisnika")
        return
    await member.ban()
    await ctx.send(f"{member.mention} je banovan")
@ban.error
async def kick_error(ctx, error):
    if isinstance(error, commands.CheckFailure):
        await ctx.send("Nemaš dozvolu da banuješ korisnike!")

@client.command()
@commands.has_permissions(administrator=True)
async def mute(ctx, member: discord.Member=None):
    if not member:
        await ctx.send("Molim izaberi korisnika")
        return
    role = discord.utils.get(ctx.guild.roles, name="muted")
    await member.add_roles(role)
@mute.error
async def mute_error(ctx, error):
    if isinstance(error, commands.CheckFailure):
        await ctx.send("Nemaš dozvolu da mutuješ korisnike!")

@client.command()
@commands.has_permissions(administrator=True)
async def unmute(ctx, member: discord.Member=None):
    if not member:
        await ctx.send("Molim izaberi korisnika")
        return
    role = discord.utils.get(ctx.guild.roles, name="muted")
    await member.remove_roles(role)
@mute.error
async def unmute_error(ctx, error):
    if isinstance(error, commands.CheckFailure):
        await ctx.send("Nemaš dozvolu da unmutuješ korisnike!")

client.run("NTI2MTc4MjM3MzQxMTA2MTc3.DwDyLg.v2YmHAvkgrOdKnlrkz3rRywopsE")


import collections

import utils

def play(last_round):
    numbers = utils.get_input()[0]

    occurrences = collections.defaultdict(list, {number: [i] for i, number in enumerate(numbers)})
    last_number = numbers[-1]

    i = len(numbers)

    while i < last_round:
        if len(occurrences[last_number]) == 1:
            last_number = 0
        else:
            last_two_occurrences = occurrences[last_number][-2:]
            last_number = last_two_occurrences[1] - last_two_occurrences[0]

        occurrences[last_number].append(i)
        i += 1

    print(last_number)

@utils.part
def part_1():
    play(2020)

@utils.part
def part_2():
    play(30000000)


from os import stat
from time import localtime
from locale import setlocale,format,LC_NUMERIC
from math import ceil
def MGgetFileDateInt (eachFile):
    statInfo =stat(eachFile)
    return int (statInfo.st_mtime)

def MGgetFileSizeInt (eachFile):
    statInfo =stat(eachFile)
    sizeRaw = ceil (statInfo.st_size/1024.0)
    return sizeRaw

def MGgetFileDateSize (fileString):
    fileList = fileString.split (';')
    result=''
    for eachFile in fileList:
        statInfo =stat(eachFile)
        sizeRaw = ceil (statInfo.st_size/1024.0)
        setlocale (LC_NUMERIC,'')
        sizeString =format ('%.*f',(0,sizeRaw),True)+'KB;'
        result+=sizeString;

        dateTopRow = int (statInfo.st_mtime)
        dateRaw =localtime (dateTopRow )
        dateString = str (dateRaw.tm_mon)+'/'+str (dateRaw.tm_mday)+'/'+str (dateRaw.tm_year)+' '+str (dateRaw.tm_hour)+':'+str (dateRaw.tm_min)+':'+str (dateRaw.tm_sec)#+';'
        result+=dateString;
        #result+=(str(sizeRaw)+";");
        #result+=(str(dateTopRow));

    return result

#if __name__ == '__main__':
#    MGgetFileDateSize ('E:/Data/Char/Conch_v1.5.ma;E:/Data/Char/Z-Mouse_v1.35.ma')


# runFittingAnalysis.py
#
# Bryan Daniels
# 2021/9/24
#
# Branched from runLandauTestAnalysis.py
#
# Run data fitting (Landau and/or Gaussian mixture model) and save the results.
#

from criticalDynamics import simpleCollectiveDynamics,allToAllNetworkAdjacency
from landauAnalysis import landauAnalysis,gaussianMixtureAnalysis,principalComponents
import time
import sys
import numpy as np
import pandas as pd
import subprocess # for getGitHash
from toolbox import load,save

def loadBeeData(log=True,skipDays=[4,]):
    """
    Returns dictionary keyed by age in days
    """
    xlFile = pd.ExcelFile("../../Data/170614/nanostring data with VG protein data.xlsx")
    rawData = xlFile.parse('Sheet1')
    speciesNames = [name for name in rawData.keys()][4:-1]
    ages = np.unique(rawData['Age'])
    #print("Number of species = {}".format(len(speciesNames)))
    dataFull = rawData.set_index('Age')
    dataFull.drop(['Unnamed: 2','Unnamed: 3','Gene','Sample ID'],axis=1,inplace=True)

    if log:
        data = np.log(dataFull)
    else:
        data = dataFull

    return dict([ (age,data.loc[age]) for age in ages if age not in skipDays ])

def loadBeeDataDict(log=True):
    """
    Returns dictionary of dictionaries of form for use in runFitting
    """

    beeData = loadBeeData(log=log)

    dataDictDict = {}
    for age,data in beeData.items():
        dataDictDict[age] = {'age':age,
                             'log':log,
                             'finalStates':data,
                            }
    return dataDictDict

def loadSimulationData(datafile,numSamples,samplesOffset):
    """
    Loads existing simulation data created using runLandauTestSimulations.py

    Returns dictionary keyed by mu
    """
    # load data from file created using runLandauTestSimulations.py
    samplesDataDict = load(datafile)

    for mu,data in samplesDataDict.items():
        # remove any existing fitting analysis to avoid confusion
        analysisKeys = ['runLandauAnalysis','landauTimeMinutes','numNuMax',
                        'sampleMean','valList','vecList','llList','cList','dList',
                        'simTimeMinutes']
        for k in analysisKeys:
            data.pop(k,None)
        # save simulation gitHash with new name to avoid confusion
        simulationGitHash = data.pop('gitHash',None)
        data['simulationGitHash'] = simulationGitHash

        # take desired slice of data
        assert(len(data['finalStates']) >= samplesOffset+numSamples) # enough data?
        data['finalStates'] = data['finalStates'][samplesOffset:samplesOffset+numSamples]
        data['Nsamples'] = numSamples

    return samplesDataDict

def runFitting(dataType='bee',numNuMax=10,ndimsGaussianList=[None,1],
    datafile=None,numSamples=None,samplesOffset=None,outputfilename=None,
    runLandauAnalysis=True,runGaussianMixtureAnalysis=True,
    verbose=True):
    """
    dataType ('bee')        : One of ['bee','simulation']
    """

    # load data
    if dataType == 'bee':
        dataVariable = 'age'
        dataDictDict = loadBeeDataDict()
    elif dataType == 'simulation':
        dataVariable = 'mu'
        dataDictDict = loadSimulationData(datafile,numSamples,samplesOffset)
    else:
        raise(Exception,'Unrecognized dataType')

    for key,dataDict in dataDictDict.items():

        finalStates = dataDict['finalStates']

        if runLandauAnalysis:
            # do dimensionality reduction first if we only want to fit to
            # the first principal component (it's equivalent and makes the
            # mathematica code run much faster)
            if numNuMax == 1:
                vals,vecs = principalComponents(finalStates)
                sampleMean = np.mean(finalStates,axis=0)
                transformedData = np.dot(finalStates-sampleMean,
                                         np.transpose(vecs))[:,:numNuMax]
                transformedData = np.real_if_close(transformedData)
                finalStatesLandau = transformedData
                # For some reason mathematica chokes when the mean is zero
                # (by definition here).  Add 1 to everything to avoid this
                # (doesn't affect anything except the sample mean mu, which
                # we fix below).
                dataOffset = 1.
            else:
                finalStatesLandau = finalStates
                dataOffset = 0.

            # run Landau analysis on final states
            startTime = time.time()
            landauOutput = landauAnalysis(finalStatesLandau + dataOffset,
                                          numNuMax=numNuMax)
            sampleMean = landauOutput.pop('mu') - dataOffset
            landauTimeMinutes = (time.time() - startTime)/60.

            landauOutput.update(
                       {'landauTimeMinutes': landauTimeMinutes,
                        'numNuMax': numNuMax,
                        'sampleMean': sampleMean,
                        'gitHash': getGitHash(),
                       } )
            dataDict['landauAnalysis'] = landauOutput

        if runGaussianMixtureAnalysis:
            # run Gaussian Mixture analysis on final states
            for ndims in ndimsGaussianList:
                startTime = time.time()
                gaussianOutput = gaussianMixtureAnalysis(finalStates,ndims=ndims)
                gaussianTimeMinutes = (time.time() - startTime)/60.

                gaussianOutput.update(
                            {'gaussianTimeMinutes': gaussianTimeMinutes,
                             'ndims': ndims,
                             'gitHash': getGitHash(),
                            } )
                dataDict['gaussianMixtureAnalysis{}'.format(ndims)] = gaussianOutput

        if verbose:
            print("runFitting: Done with fitting {} = {}".format(dataVariable,key))

        if outputfilename:
            # save data
            save(dataDictDict,outputfilename)
            if verbose:
                print("runFitting: Saved fitting data to {}".format(outputfilename))

    return dataDictDict

def getGitHash(dir='./'):
    """
    Get the hash code for the current HEAD state of the git repository
    in directory 'dir'.
    """
    hashVal = subprocess.check_output(['git','rev-parse','HEAD'],cwd=dir)
    return hashVal.strip().decode()

if __name__ == '__main__':

    # set up parameters of run
    runLandauAnalysis = True
    runGaussianMixtureAnalysis = True
    dataType = 'simulation' # bee'
    numNuMax = 1
    ndimsGaussianList = [None,1]
    # parameters for use in sampling from simulation data
    networkName = 'allToAll'
    Ncomponents = 10 #1000 #10 #91
    Nsamples = 16 #100 # number of samples to fit to
    NsamplesOriginal = 1000 #16 #1000 # number of samples in original simulation datafiles
    samplesOffset = 0 #500 # index of first sample used for fitting
    Nmus = 51 #31 #51

    # if command line argument is given, use it to set runIndex
    if len(sys.argv) == 2:
        runIndex = int(sys.argv[1])
    elif len(sys.argv) > 2:
        print("Usage: python runFittingAnalysis.py [runIndex]")
        exit()
    else:
        runIndex = 0

    # set up output data dictionary and filenames
    if dataType == 'bee':
        filename = 'FittingData_{}.dat'.format(dataType)
        samplesKwargs = {} # (only used for simulation data samples)
    elif dataType == 'simulation':
        filename = 'FittingData_{}_Ncomponents{}_Nsamples{}_offset{}_Nmus{}_run{}.dat'.format(
                networkName,Ncomponents,Nsamples,samplesOffset,Nmus,runIndex)
        datafile = 'LandauTestData_{}_Ncomponents{}_Nsamples{}_Nmus{}_run{}.dat'.format(
                networkName,Ncomponents,NsamplesOriginal,Nmus,runIndex)
        samplesKwargs = {'datafile': datafile,
                         'numSamples': Nsamples,
                         'samplesOffset': samplesOffset,
                        }
    else:
        raise(Exception,"Unrecognized dataType")

    # run the analysis
    dataDictDict = runFitting(dataType,
                          numNuMax=numNuMax,
                          ndimsGaussianList=ndimsGaussianList,
                          runLandauAnalysis=runLandauAnalysis,
                          runGaussianMixtureAnalysis=runGaussianMixtureAnalysis,
                          outputfilename=filename,
                          **samplesKwargs)

    # save data
    save(dataDictDict,filename)
    print("runFittingAnalysis: Saved data to {}".format(filename))


import pytest
from unittest.mock import patch, MagicMock
from datetime import datetime
from datetime import timedelta

import session
from models.user import User
from models.booking import Booking
from models.space import Space

# Returns a test user
@pytest.fixture
def curr_user():
    user = User(userId=123, isLibrarian=False, firstName="first name", lastName="last name")
    return user

# Returns a test session object
@pytest.fixture
def session_object(curr_user):
    # mock bookings dictionary in Session object
    mock_data_bookings = MagicMock(return_value = {
        0: Booking(0, 2, "cdong49@uwo.ca", datetime.strptime("2022-11-21 14:00:00",'%Y-%m-%d %H:%M:%S'), datetime.strptime("2022-11-21 16:00:00",'%Y-%m-%d %H:%M:%S')),
        1: Booking(1, 0, "eliu72@uwo.ca", datetime.strptime("2022-11-21 11:00:00",'%Y-%m-%d %H:%M:%S'), datetime.strptime("2022-11-21 13:00:00",'%Y-%m-%d %H:%M:%S'))
    })
    patch_loadBookings = patch("session.Session.loadBookings", mock_data_bookings)

    # mock spaces dictionary in Session object
    mock_data_spaces = MagicMock(return_value = {
        0: Space(0, 4, {"outlets": True,"accessible": True,"quiet": False,"private": True,"media": True}, "Taylor - Room 155"),
        1: Space(1, 1, {"outlets": True,"accessible": True,"quiet": False,"private": True,"media": True}, "Taylor - Room 55")
    })
    patch_loadSpaces = patch("session.Session.loadSpaces", mock_data_spaces)

    # return a session object
    with patch_loadBookings as p1:
        with patch_loadSpaces as p2:
            return session.Session(curr_user)

# test loadBookings function to check that it correctly parses the json data
def test_loadBookings(session_object):
    # patch open since we don't want to actually open the file
    patch_open = patch("builtins.open", MagicMock())

    # bookings are made for future dates since load bookings removes past bookings
    mock_data = MagicMock(return_value = [
        {
            "bookingId": 0,
            "spaceId": 2,
            "userEmail": "cdong49@uwo.ca",
            "startTime": "2100-11-21 14:00:00",
            "endTime": "2100-11-21 16:00:00"
        },
        {
            "bookingId": 1,
            "spaceId": 0,
            "userEmail": "eliu72@uwo.ca",
            "startTime": "2100-11-21 11:00:00",
            "endTime": "2100-11-21 13:00:00"
        }])
    patch_json_load = patch("json.load", mock_data)

    # the expected return value after parsing the json data
    expected_data = {
        0: Booking(0, 2, "cdong49@uwo.ca", datetime.strptime("2100-11-21 14:00:00",'%Y-%m-%d %H:%M:%S'), datetime.strptime("2100-11-21 16:00:00",'%Y-%m-%d %H:%M:%S')),
        1: Booking(1, 0, "eliu72@uwo.ca", datetime.strptime("2100-11-21 11:00:00",'%Y-%m-%d %H:%M:%S'), datetime.strptime("2100-11-21 13:00:00",'%Y-%m-%d %H:%M:%S'))
    }

    # using the mocks, test loadBookings function
    with patch_open as p_open:
        with patch_json_load as p_json_load:
            loaded_bookings = session_object.loadBookings()
            # check that the actual and expected have the same num of bookings
            assert len(loaded_bookings) == len(expected_data)
            # check that their values are the same
            for key in loaded_bookings.keys():
                assert loaded_bookings[key].userId == expected_data[key].userId
                assert loaded_bookings[key].start == expected_data[key].start
                assert loaded_bookings[key].end == expected_data[key].end
                assert loaded_bookings[key].spaceId == expected_data[key].spaceId

# # test loadSpaces function to check that it correctly parses the json data
def test_loadSpaces(session_object):
    # patch open since we don't want to actually open the file
    patch_open = patch("builtins.open", MagicMock())

    # provide mock data for tests
    mock_data = MagicMock(return_value = [
        {
            "spaceId": 0,
            "location": "Taylor - Room 155",
            "seats": 4,
            "filters": {
                "outlets": True,
                "accessible": True,
                "quiet": False,
                "private": True,
                "media": True
            }
        },
        {
            "spaceId": 1,
            "location": "Taylor - Floor G",
            "seats": 1,
            "filters": {
                "outlets": True,
                "accessible": True,
                "quiet": True,
                "private": False,
                "media": False
            }
        }])
    patch_json_load = patch("json.load", mock_data)

    # the expected return value after parsing the json data
    expected_data = {
        0: Space(0, 4, {"outlets": True,"accessible": True,"quiet": False,"private": True,"media": True}, "Taylor - Room 155"),
        1: Space(1, 1, {"outlets": True,"accessible": True,"quiet": True,"private": False,"media": False}, "Taylor - Floor G")
    }

    # using the mocks, test loadBookings function
    with patch_open as p_open:
        with patch_json_load as p_json_load:
            loaded_spaces = session_object.loadSpaces()
            # check that the actual and expected have the same num of bookings
            assert len(loaded_spaces) == len(expected_data)
            # check that their values are the same
            for key in loaded_spaces.keys():
                assert loaded_spaces[key].filters == expected_data[key].filters
                assert loaded_spaces[key].location == expected_data[key].location
                assert loaded_spaces[key].seats == expected_data[key].seats

# test add booking function to make sure that we update the dict and json data
def test_addBooking(session_object):
    # we don't want to actually write to the file so we mock this funciton
    patch_open = patch("builtins.open", MagicMock())
    with patch_open as p_open:
        newBooking = session_object.addBooking("12", '2023-11-28 09:00:00', '2023-11-28 10:00:00')

        # check that new booking is in the bookings dict
        assert newBooking == session_object.allBookings[newBooking.bookingId]

        # check that we tried to add to database
        p_open.assert_called_once()

# test cancelBooking function to make sure that we update the dict and json data
def test_cancelBooking(session_object):
    # we don't want to actually write to the file so we mock this funciton
    patch_open = patch("builtins.open", MagicMock())
    with patch_open as p_open:
        # add a fake booking and try to remove it
        newBooking = session_object.addBooking("13", '2023-11-28 11:00:00', '2023-11-28 12:00:00')
        newBookingId = newBooking.bookingId

        # remove the new booking
        session_object.cancelBooking(newBookingId)

        # check that the booking is no longer in the dict
        assert newBookingId not in session_object.allBookings

        # check that changes are saved to db
        assert p_open.call_count == 2 # 1 call for addBooking, 1 call for removeBooking

# function to make sure that adding a space updates in memory dict and database
def test_addSpace(session_object):
    # we don't want to actually write to the file so we mock this funciton
    patch_open = patch("builtins.open", MagicMock())
    with patch_open as p_open:
        newSpace = session_object.addSpace("Fake location", 10)

        # check that new space is in the spaces dict
        assert newSpace == session_object.allSpaces[newSpace.spaceId]

        # check that we tried to add to database
        p_open.assert_called_once()

# function to make sure that removing a space updates in memory dict and database
def test_removeSpace(session_object):
    # we don't want to actually write to the file so we mock this funciton
    patch_open = patch("builtins.open", MagicMock())
    patch_cancelBooking = patch("session.Session.cancelBooking")
    with patch_open as p_open:
        with patch_cancelBooking:
            # remove a space
            spaceId = 0
            session_object.removeSpace(spaceId)

            # check that the space is no longer in the dict
            assert spaceId not in session_object.allSpaces

            # check that changes are saved to db
            p_open.assert_called_once()


import tkinter as tk
from tkinter import ttk
import subprocess

def abrir_resumen_ventas():
    # Lógica para abrir la ventana de Resumen de Ventas
    subprocess.run(["python", "abrir_resumen_de_ventas.py"])

def abrir_gestionar_productos():
    # Abrir el archivo productos.py
    subprocess.run(["python", "productos.py"])

def abrir_registro_ventas():
    # Lógica para abrir la ventana de Registro de Ventas
    subprocess.run(["python", "registro_de_ventas.py"])

def abrir_gestionar_clientes():
    # Abrir el archivo clientes.py
    subprocess.run(["python", "clientes.py"])

def cerrar_sesion():
    ventana.destroy()

# Crear la ventana principal
ventana = tk.Tk()
ventana.title("División en tres secciones")
ventana.geometry("800x600")

# Colores de fondo para cada sección
color_negro = "#0D1117"
color_blanco = "#FFFFFF"
color_celeste_claro = "#B2EBF2"

# Estilo personalizado para los botones
style = ttk.Style()
style.configure("Custom.TButton", background=color_celeste_claro, foreground="black", font=("Arial", 12), relief=tk.FLAT)

# Barra de navegación vertical (sección izquierda)
barra_navegacion = tk.Frame(ventana, bg=color_negro, width=200)
barra_navegacion.pack(side=tk.LEFT, fill=tk.Y)

# Calcular el espacio entre los botones
espacio_botones = 30

# Espacio en blanco para separar los botones
espacio_blanco = tk.Frame(barra_navegacion, bg=color_negro, height=20)
espacio_blanco.pack()

# Contenedor de los botones
contenedor_botones = tk.Frame(barra_navegacion, bg=color_negro)
contenedor_botones.pack(pady=(150, espacio_botones))

# Botón Resumen de Ventas
boton_resumen_ventas = ttk.Button(contenedor_botones, text="Resumen de Ventas", style="Custom.TButton", command=abrir_resumen_ventas)
boton_resumen_ventas.pack(pady=espacio_botones)

# Botón Gestionar productos
boton_gestionar_productos = ttk.Button(contenedor_botones, text="Gestionar productos", style="Custom.TButton", command=abrir_gestionar_productos)
boton_gestionar_productos.pack(pady=espacio_botones)

# Botón Registro de Ventas
boton_registro_ventas = ttk.Button(contenedor_botones, text="Registro de Ventas", style="Custom.TButton", command=abrir_registro_ventas)
boton_registro_ventas.pack(pady=espacio_botones)

# Botón Gestionar Clientes
boton_gestionar_clientes = ttk.Button(contenedor_botones, text="Gestionar Clientes", style="Custom.TButton", command=abrir_gestionar_clientes)
boton_gestionar_clientes.pack(pady=espacio_botones)

# Área de contenido principal (sección central)
contenido_principal = tk.Frame(ventana, bg=color_blanco)
contenido_principal.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

# Barra de navegación horizontal (sección superior dentro del contenido principal)
barra_navegacion_horizontal = tk.Frame(contenido_principal, bg=color_celeste_claro, height=80)
barra_navegacion_horizontal.pack(fill=tk.X)

# Botón Cerrar Sesión
boton_cerrar_sesion = ttk.Button(barra_navegacion_horizontal, text="Cerrar Sesión", style="Custom.TButton", command=cerrar_sesion)
boton_cerrar_sesion.pack(side=tk.RIGHT, padx=10, pady=10)

# Resto del contenido principal (sección inferior dentro del contenido principal)
contenido_principal_resto = tk.Frame(contenido_principal, bg=color_blanco)
contenido_principal_resto.pack(fill=tk.BOTH, expand=True)

# Agrega el resto del contenido aquí

# Ejecutar el bucle principal de la ventana
ventana.mainloop()


from random import randint

class Die():
    """这是一个模拟骰子的类"""
    def __init__(self,sides):
        self.sides = sides

    def roll_die(self):
        x = randint(1,self.sides)
        print(x)

test_1 = Die(6)
for i in range(1,11):
    test_1.roll_die()

print('\n')

test_2 = Die(10)
for j in range(1,11):
    test_2.roll_die()

print('\n')

test_3 = Die(20)
for k in range(1,11):
    test_3.roll_die()


"""
This dot-py file defines a CLI for reading a given time period's worth of GTFS-R records on disc into a SQLite database
containing only complete trips. It assumes that the data has already been localized onto disc using the
`push-stops.py` script (or an equivalent).

E.g. how I've been using it:

> python compile-logbooks-to-db.py ~/Desktop/subway-explorer-datastore/ '2018-01-18T00:00' '2018-01-18T12:00' .
"""

import click
import os
from datetime import datetime, timedelta
import gtfs_tripify as gt
from tqdm import tqdm
import sqlite3

# FEED_IDENTIFIERS = [16]
FEED_IDENTIFIERS = [1, 2, 11, 16, 21, 26, 31, 36]
LOG_CUT_HEURISTIC_EXCEPTIONS = ['GS']
TERMINUS_TIME = 3

def daily_transform(logbook, start_datetime):
    """Helper function for cropping the data to fit the complete single-day format."""
    for trip_id in list(logbook.keys()):
        if len(logbook[trip_id]) > 0 and logbook[trip_id].iloc[0].route_id not in LOG_CUT_HEURISTIC_EXCEPTIONS:
            logbook[trip_id] = gt.utils.cut_cancellations(logbook[trip_id])

    logbook = gt.utils.discard_partial_logs(logbook)

    for trip_id in list(logbook.keys()):
        if len(logbook[trip_id]) <= 1:
            del logbook[trip_id]
        else:
            start_ts = logbook[trip_id].iloc[0]['latest_information_time']
            if datetime.fromtimestamp(int(start_ts)).day != start_datetime.day:
                del logbook[trip_id]

    return logbook

@click.command()
@click.argument('root')
@click.argument('start_time')
@click.argument('end_time')
@click.argument('out')
def run(root, start_time, end_time, out):
    """
    Specify a date (in %Y-%m-%dT%H:%M format, e.g. "2018-01-17T21:00".
    """
    conn = sqlite3.connect("{0}/logbooks.sqlite".format(out))

    for feed_id in tqdm(FEED_IDENTIFIERS):

        # Date format munging.
        feed_root = "{0}/mta-gtfs-{1}".format(root, feed_id)
        start_datetime = datetime.strptime(start_time, "%Y-%m-%dT%H:%M")
        end_datetime = datetime.strptime(end_time, "%Y-%m-%dT%H:%M")
        read_in_terminus = end_datetime + timedelta(hours=TERMINUS_TIME)
        day_of_root = "{0}/{1}".format(feed_root, start_datetime.strftime("%Y-%m-%d"))
        day_after_root = "{0}/{1}".format(feed_root, (start_datetime + timedelta(days=1)).strftime('%Y-%m-%d'))

        # TODO: Raise an error if there is not enough follow-up data to complete trips that extend past the end time.
        # if not os.path.isdir(day_after_root):
        #     raise IOError("In order to account for trips that transition through day's end, please provide "
        #                   "six hour's of data from the day following the chosen time span.")

        # Get the relevant feeds.
        #
        # In order to convert all of the GTFS-R messages into a unified trip log we need to read the overall GTFS-R
        # stream in chunks. The maximum size of the chunks that we use will be restricted by how much memory the
        # machine doing the processing has: a single day of data on a busy feed can very nearly max out 16 GB of RAM
        # (dictity in particular suffers from extremely regressive memory profile performance; this was definitely
        # not true when I initially wrote it, and definitely something I need to investigate in great detail
        # eventually).
        #
        # OK, so we need to read the data in chunks. How big should the chunks be? Our end goal is to create a
        # database with complete stop records for every trip. Trips that fall exactly inside of our desired stop and
        # end time are easy: we have all the information we need. But trips that intersect on the edges are hard. We
        # don't want to include partial trip information in our database, only complete trip information. How do we
        # deal with it?
        #
        # To run this script we define a `start_time` and a `stop_time`. The result that gets written to the database
        # will be this: every trip that *starts* in between `start_time` and `stop_time`. This includes trips that
        # actually do not finish until (potentially well) past the `stop_time` we've specified.
        #
        # We achieve this by defining a timedelta of additional records we'll read in that extends past the
        # `stop_time`. In this script I've arbitrarily chosen three hours as that value, on the hypothesis that no
        # train trip could possible take more than three hours to complete.
        #
        # At runtime, this script calculates a stop time three hours after the specified `stop_time`. It figures out
        # what logs correspond with that additional information, and appends them to the logs to be read.
        #
        # Then, after we've done all of the heavy lifting with `gtfs-tripify`, including cutting out partial trips,
        # we'll have a logbook with two kinds of trips: trips that started in between `start_time` and `stop_time`,
        # and trips that started after `stop_time`, but finished before `stop_time` + 3 hours. The last thing we'll
        # need to do will be removing the latter category of things. This is easy to do: check the individual logs
        # and make sure that the trip timestamps start in between `start_time` and `stop_time`. Any trips whose first
        # timestamp is post-`stop time` is undesirable and we'll throw it out.
        #
        # The end result is that the data we write to the database is neatly contiguous: it's every trip that started
        # in between `start_time` and `stop_time`. We can pick whatever chunk size we want: six hours, half a day,
        # or a full day, whatever, and execute this script on each chunk of time to push those trips to the database.
        # Obviously though, because of the fixed costs, bigger is better.
        stream = []
        possibly_relevant_feeds = sorted(os.listdir(day_of_root))
        for fp in possibly_relevant_feeds:
            dt = datetime.strptime(":".join(fp.split(":")[:2]), "%Y-%m-%d_%H:%M")
            if (dt < read_in_terminus) and (dt > start_datetime):
                stream.append('{0}/{1}'.format(day_of_root, fp))

        more_possibly_relevant_feeds = sorted(os.listdir(day_after_root))
        for fp in more_possibly_relevant_feeds:
            dt = datetime.strptime(":".join(fp.split(":")[:2]), "%Y-%m-%d_%H:%M")
            if (dt < read_in_terminus) and (dt > start_datetime):
                stream.append('{0}/{1}'.format(day_after_root, fp))

        # Built the logbook.
        gt.io.stream_to_sql(stream, conn, transform=lambda logbook: daily_transform(logbook, start_datetime))

if __name__ == '__main__':
    run()


from django.urls import path

from . import views

app_name = 'blog'
urlpatterns = [
    path('', views.home, name='home'),
    path('<int:article_id>/', views.detail, name='detail'),
    path('newArticle/', views.newArticle, name='newArticle'),
    path('save/', views.saveArticle, name='saveArticle'),
    path('<int:article_id>/update/', views.updateArticle, name="updateArticle"),
    path('<int:article_id>/delete/', views.deleteArticle, name="deleteArticle"),
    path('<int:article_id>/writeComment/', views.writeComment, name="writeComment"),
    path('uploadImage/', views.uploadImage, name="uploadImage"),
    path('deleteComment/', views.deleteComment, name="deleteComment"),
    path('search/',views.searchArticle, name="search"),
    ]


import matplotlib.pyplot as plt
import numpy as np
import skimage.draw as draw
import torch
import torchvision.transforms as transforms
from PIL import Image
from scipy import ndimage
from scipy.ndimage.measurements import center_of_mass, label
from skimage.feature import peak_local_max
from pathlib import Path

def compute_gradient(image):
    # we compute the gradient of the image
    '''kx = np.array([[1, 0, -1], [2, 0, -2], [1, 0, -1]])
        ky = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]])
        sx = ndimage.convolve(depth[0][0], kx)
        sy = ndimage.convolve(depth[0][0], ky)'''
    sx = ndimage.sobel(image, axis=0, mode='nearest')
    sy = ndimage.sobel(image, axis=1, mode='nearest')
    gradient = transforms.ToTensor()(np.hypot(sx, sy))

    return gradient[0]

def local_max(image):
    max_out = peak_local_max(image, min_distance=19, threshold_rel=0.5, exclude_border=False, indices=False)
    labels_out = label(max_out)[0]
    max_out = np.array(center_of_mass(max_out, labels_out, range(1, np.max(labels_out) + 1))).astype(np.int)
    max_values = []

    for index in max_out:
        max_values.append(image[index[0]][index[1]])

    max_out = np.array([x for _, x in sorted(zip(max_values, max_out), reverse=True, key=lambda x: x[0])])

    return max_out

def corner_mask(output):
    max_coord = local_max(output)
    corners = torch.zeros(3, output.shape[0], output.shape[1])
    for idx, (i, j) in enumerate(max_coord):
        cx, cy = draw.circle_perimeter(i, j, 9, shape=output.shape)
        if idx < 4:
            corners[0, cx, cy] = 1.

    return corners, max_coord

def save_img(rgb, output, depth, name):
    corners, max_coord = corner_mask(output)
    rgb, corners = transforms.ToPILImage()(rgb), transforms.ToPILImage()(corners)
    image = Image.blend(rgb, corners, 0.3)
    plt.ioff()
    fig, ax = plt.subplots(1, 3)
    fig.set_size_inches((15, 6))
    ax[2].axis('off')
    ax[2].set_title('RGB image')
    ax[1].axis('off')
    ax[1].set_title('Network\'s output')
    ax[0].axis('off')
    ax[0].set_title('Depth image')
    ax[0].imshow(depth, cmap='gray', vmin=0.5, vmax=depth.max())
    ax[1].imshow(output, cmap='afmhot', vmin=0, vmax=1)
    ax[2].imshow(image)
    Path('output/').mkdir(parents=True, exist_ok=True)
    plt.savefig('output/{image}.png'.format(image=name))
    plt.close('all')

def show_corners(image, corners):
    """Show image with landmarks"""
    plt.imshow(image, cmap='gray')
    plt.scatter(corners[:, 1], corners[:, 0], s=10, marker='.', c='r')
    plt.pause(0.005)  # pause a bit so that plots are updated


from django.http import HttpResponse
import paydunya
from paydunya import InvoiceItem, Store, Invoice

from django.shortcuts import get_object_or_404, redirect, render
from django.conf import settings
from orders.models import Order
from send_mail.views import payment_successful_email

paydunya.debug = True

paydunya.api_keys = settings.PAYDUNYA_ACCESS_TOKENS

store = Store(name='Magasin Chez Jaba')

def payment_process(request):
    order_id = request.session.get("order_id")
    order = get_object_or_404(Order, pk=order_id)
    order_items = order.items.all()
    items = [InvoiceItem(
        name=item.product.name,
        quantity=item.quantity,
        unit_price=str(item.price),
        total_price=str(item.price * item.quantity),
        description=item.product.name
    ) for item in order_items
    ]
    invoice = paydunya.Invoice(store)
    host = request.get_host()
    invoice.callback_url = f"http://{host}/payment-done/"
    invoice.cancel_url = f"http://{host}/payment-canceled/"
    invoice.return_url = f"http://{host}/payment-done/"
    invoice.add_items(items)
    successful, response = invoice.create()
    if successful:
        return redirect(response.get("response_text"))

def payment_done(request):
    token = request.GET.get("token")
    invoice = Invoice(store)
    successful, response = invoice.confirm(token)
    if successful:
        return HttpResponse("
Merci pour le paiement
")

def payment_canceled(request):
    return HttpResponse("
Vous avez annulé le paiement
")


import fileinput

lines = list(fileinput.input())

def get():
    ops = list()
    for line in lines:
        line = line.strip()
        line = line.split(',')
        for item in line:
            ops.append(int(item))
    return ops
def solve(commands,a,b):
    x = commands
    x[1] = a
    x[2] = b
    for i in range(0,len(x)-1,4):
        posx = x[i+1]
        posy = x[i+2]
        posz = x[i+3]

        if x[i] == 1:
            x[posz] = x[posx] + x[posy]
        elif x[i] == 2:
            x[posz] = x[posx] * x[posy]
        elif x[i] == 99:
            break
        else:
             print("oh no")
    return x

for i in range(0, 99):
    for j in range(0, 99):
        ops = get()
        s = solve(ops,i,j)
        if s[0] == 19690720:
            print(s)
            print(100*i*j)
            break