from flask import request
from app import csrf, app, db
from flask import jsonify
from services.functions import *
from services.mail_functions import sendMail
from sqlalchemy.exc import SQLAlchemyError

# Show User by ID
# curl -i -H "Content-Type:application/json" -H "Accept: application/json" http://localhost:5000/api/user/id
@app.route('/api/user/<id>', methods=['GET'])
def apiGetUserById(id):
    user = get_user(id)
    return jsonify(user.to_json())

# Show all Users
# curl -H "Accept:application/json" http://localhost:5000/api/users
@app.route('/')
@app.route('/api/users', methods=['GET'])
def apiShowUsers():
    users_list = list_user()
    return jsonify({'users': [user.to_json() for user in users_list]})

# Delete User
# curl -i -X DELETE -H "Accept: application/json" http://localhost:5000/api/user/id
@app.route('/api/user/<id>', methods=['DELETE'])
@csrf.exempt
def deleteUser(id):
    user = get_user(id)
    db.session.delete(user)
    db.session.commit()
    return '', 204

# Show Event by ID
# curl -i -H "Content-Type:application/json" -H "Accept: application/json" http://localhost:5000/api/event/id
@app.route('/api/event/<id>', methods=['GET'])
def apiGetEventById(id):
    event = get_event(id)
    return jsonify(event.to_json())

# Show all Events
# curl -H "Accept:application/json" http://localhost:5000/api/events
@app.route('/')
@app.route('/api/events', methods=['GET'])
def apiShowEvents():
    event_list = show_events()
    return jsonify({'events': [event.to_json() for event in event_list]})

# Update Event
# curl -i -X PUT -H "Content-Type:application/json" -H "Accept:application/json" http://localhost:5000/api/event/id -d '{"title":"", "place":""}'
@app.route('/api/event/<id>', methods=['PUT'])
@csrf.exempt
def apiUpdateEvent(id):
    event = get_event(id)
    event.title = request.json.get('title', event.title)
    event.date = request.json.get('date', event.date)
    event.place = request.json.get('place', event.place)
    event.description = request.json.get('description', event.description)
    event.type = request.json.get('type', event.type)
    event.status = 0
    try:
        db.session.add(event)
        db.session.commit()
    except SQLAlchemyError as e:
        db.session.rollback()
        print(e)

    return jsonify(event.to_json()), 201

# Approve event
# curl -i -X PUT -H "Content-Type:application/json" -H
# "Accept:application/json" http://localhost:5000/api/event/id/approve
@app.route('/api/event/<id>/approve', methods=['PUT'])
@csrf.exempt
def apiApproveEvent(id):
    event = get_event(id)
    event.status = 1
    db.session.add(event)
    db.session.commit()

    sendMail(event.user.email, 'Evento aprobado', 'event_approved', event=event)
    return jsonify(event.to_json()), 201

# Delete Event
# curl -i -X DELETE -H "Accept: application/json" http://localhost:5000/api/event/id
@app.route('/api/event/<id>', methods=['DELETE'])
@csrf.exempt
def deleteEvent(id):
    event = get_event(id)
    db.session.delete(event)
    db.session.commit()
    return '', 204

# Show Comment by ID
# curl -i -H "Content-Type:application/json" -H "Accept: application/json" http://localhost:5000/api/comment/id
@app.route('/api/comment/<id>', methods=['GET'])
def apiGetCommentById(id):
    comment = get_comment(id)
    return jsonify(comment.to_json())

# Show Comments by Events
# curl -i -H "Content-Type:application/json" -H "Accept: application/json" http://localhost:5000/api/comments/id
@app.route('/api/comments/<event>', methods=['GET'])
def apiGetCommentByEvent(event):
    comment_list = show_comments(event)
    return jsonify({'Comments': [comment.to_json() for comment in comment_list]})

# Delete Comment
# curl -i -X DELETE -H "Accept: application/json" http://localhost:5000/api/comment/id
@app.route('/api/comment/<id>', methods=['DELETE'])
@csrf.exempt
def apiDeleteCommentById(id):
    comment = get_comment(id)
    db.session.delete(comment)
    db.session.commit()
    return '', 204


from __future__ import unicode_literals
import frappe
from frappe.model.document import Document

class WebshopOrder(Document):
    pass

def create_order_from_api(kwargs=None):
    if (kwargs):
        try:
            import json
            json_formatted_str = json.dumps(kwargs, indent=2)
            webshop_order = frappe.get_doc({
                "doctype": "Webshop Order",
                "request": json_formatted_str
            }).insert(ignore_permissions=True)
            return raise_200()
        except Exception as err:
            return raise_xxx(500, '', err, daten=kwargs)

# Success Return
def raise_200(answer='Success'):
    frappe.local.response.http_status_code = 200
    frappe.local.response.message = answer
    return ['200 Success', answer]

# Error Return
def raise_xxx(code, title, message, daten=None):
    frappe.log_error("{0}\n{1}\n{2}\n\n{3}\n\n{4}".format(code, title, message, frappe.utils.get_traceback(), daten or ''), 'SP API Error!')
    frappe.local.response.http_status_code = code
    frappe.local.response.message = message
    return ['{code} {title}'.format(code=code, title=title), {
        "error": {
            "code": code,
            "message": "{message}".format(message=message)
        }
    }]


# -*- coding: UTF-8 -*-
#Coders by Nikolasi
# v1.2
# code optimization (by Sirius)
# fix search Paths (by Sirius)
# py3 fix

from Components.Renderer.Renderer import Renderer
from Components.Converter.Poll import Poll
from Components.Pixmap import Pixmap
from Tools.LoadPixmap import LoadPixmap
from Tools.Directories import resolveFilename ,SCOPE_SKIN_IMAGE, SCOPE_CURRENT_SKIN
from enigma import eServiceCenter, ePixmap, ePicLoad, loadPic, eTimer
import os

class MovieCover(Renderer, Poll):
	__module__ = __name__
	searchPaths = ('/media/hdd/%s/', '/media/usb/%s/', '/media/sdb1/%s/', '/media/sdb2/%s/')

	def __init__(self):
		Poll.__init__(self)
		Renderer.__init__(self)
		self.path = 'covers'
		self.nameCache = {}
		self.size = []
		self.pics = []
		self.pixmaps = []
		self.pngname = ''
		self.png = ''
		self.picon = ePicLoad()
		self.pixdelay = 60

	def applySkin(self, desktop, parent):
		attribs = []
		for (attrib, value) in self.skinAttributes:
			if attrib == 'path':
				self.path = value
			elif attrib == 'size':
				self.size = value.split(',')
			elif attrib == 'pixdelay':
				self.pixdelay = int(value)
			attribs.append((attrib, value))
		self.skinAttributes = attribs
		return Renderer.applySkin(self, desktop, parent)

	GUI_WIDGET = ePixmap

	def changed(self, what):
		self.poll_interval = 2000
		self.poll_enabled = True
		if self.instance:
			pngname = ''
			if (what[0] != self.CHANGED_CLEAR):
				sname = self.source.text
				pngname = self.nameCache.get(sname, '')
				if (pngname == ''):
					pngname = self.findPicon(sname)
					if (pngname != ''):
						self.nameCache[sname] = pngname
			if (pngname == ''):
				pngname = self.nameCache.get('default', '')
				if (pngname == ''):
					pngname = self.findPicon('picon_default')
					if (pngname == ''):
						tmp = resolveFilename(SCOPE_CURRENT_SKIN, 'no_poster.png')
						if os.path.exists(tmp):
							pngname = tmp
						self.nameCache['default'] = pngname
			if (self.pngname != pngname):
				self.pngname = pngname
				self.instance.setScale(1)
			self.picon.setPara((int(self.size[0]), int(self.size[1]), 1, 1, False, 1, '#00000000'))
			self.picon.startDecode(self.pngname, 0, 0, False)
			self.png = self.picon.getData()
			self.instance.setPixmap(self.png)
			self.runAnim()

	def findPicon(self, serviceName):
		for path in self.searchPaths:
			try:
				name = ((path % self.path) + serviceName)
				pngname = name + '.jpg'
				if os.path.exists(pngname):
					return pngname
			except:
				return ''
		return ''

	def runAnim(self):
		txt=[]
		text = ""
		if len(self.pics) == 0:
			for x in self.pixmaps:
				self.pics.append(loadPic(resolveFilename(SCOPE_SKIN_IMAGE, x), int(self.size[0]), int(self.size[1]), 0, 0, 0, 1))
			self.slide = len(self.pics)
			self.timer = eTimer()
			self.timer.callback.append(self.timerEvent)
			self.timer.start(self.pixdelay, True)
		else:
			self.instance.setPixmap(self.png)

	def timerEvent(self):
		if self.slide > 0:
			self.timer.stop()
			self.instance.setPixmap(self.pics[len(self.pics) - self.slide])
			self.slide = self.slide - 1
			self.timer.start(self.pixdelay, True)
		else:
			self.timer.stop()
			self.instance.setPixmap(self.png)


import os, sys, subprocess

def test_fsl():
    # import shell environment variable

    # check if it is set to NIFTI_GZ
    try:
        TEST_FSL = os.environ["FSLOUTPUTTYPE"]
        if TEST_FSL == "NIFTI_GZ":
            print("FSL output type is set to NIFTI_GZ")
    except:
        print("FSL output type is not set to NIFTI_GZ")
        print("running FSL config file")

        os.system(" . $FSLDIR/etc/fslconf/fsl.sh")

        # fslConfig = subprocess.run(["chmod +wrx $FSLDIR/etc/fslconf/fsl.sh; . $FSLDIR/etc/fslconf/fsl.sh"], shell=True, capture_output=True, check=True)
        # print(fslConfig)
        # fslConfig

        subprocess.run(["echo $FSLOUTPUTTYPE"],
                            shell=True,
                            check=True)

        if os.system("echo $FSLOUTPUTTYPE") == "NIFTI_GZ":
            print("FSL output type is now set to NIFTI_GZ")
        else:
            print("FSL output type is still not set to NIFTI_GZ")
            print("Exiting...")
            sys.exit(1)


from threading import Condition, Lock
from time import monotonic as _time
import os

class CheckInSemaphore:
    """
    Thread synchronization object used to keep a thread waiting until
    all checked in threads have checked out.
    """

    def __init__(self):
        self.tokens = []  #: List of checked in tokens.
        self.condition = Condition()
        """
        Condition variable used internally.
        """

    def wait(self, timeout=None):
        """
        Wait for all checked in threads to check out.

        :param timeout: Time out.
        """
        with self.condition:
            self.condition.wait_for(lambda: len(self.tokens) == 0, timeout=timeout)

    def check_in(self, token=None):
        """
        Used to check in a thread.

        :param token: Optional unique token used to identify
           the thread checking in. This token must be unique,
           duplicate tokens will be ignored. If no token is given,
           one will be generated.
        :returns: The token.
        """

        if token is None:
            # No toke was passed, so we must generate one.
            token = os.urandom(32)

            # If the generated token is already in the token list.
            # generate a new one.
            while token in self.tokens:
                token = os.urandom(32)

        # Add the token if it's not in the list.
        if token not in self.tokens:
            self.tokens.append(token)

        return token

    def check_out(self, token):
        """
        Used to check out a thread.

        :param token: The token that was used to check in.
        """
        if token in self.tokens:
            self.tokens.remove(token)

        with self.condition:
            self.condition.notify_all()

class BinarySemaphore:
    """This class implements binary semaphore objects.

    Semaphores manage a counter representing the number of release() calls minus
    the number of acquire() calls, plus an initial value. The acquire() method
    blocks if necessary until it can return without making the counter
    negative. If not given, value defaults to 1.

    """

    # After Tim Peters' semaphore class, but not quite the same (no maximum)

    def __init__(self, initial_value: bool=True):
        self._cond = Condition(Lock())
        self._value = initial_value

    def acquire(self, blocking=True, timeout=None):
        """Acquire a semaphore, decrementing the internal counter by one.

        When invoked without arguments: if the internal counter is larger than
        zero on entry, decrement it by one and return immediately. If it is zero
        on entry, block, waiting until some other thread has called release() to
        make it larger than zero. This is done with proper interlocking so that
        if multiple acquire() calls are blocked, release() will wake exactly one
        of them up. The implementation may pick one at random, so the order in
        which blocked threads are awakened should not be relied on. There is no
        return value in this case.

        When invoked with blocking set to true, do the same thing as when called
        without arguments, and return true.

        When invoked with blocking set to false, do not block. If a call without
        an argument would block, return false immediately; otherwise, do the
        same thing as when called without arguments, and return true.

        When invoked with a timeout other than None, it will block for at
        most timeout seconds.  If acquire does not complete successfully in
        that interval, return false.  Return true otherwise.

        """
        if not blocking and timeout is not None:
            raise ValueError("can't specify timeout for non-blocking acquire")

        with self._cond:
            if self._value:
                self._value = False
                return True
            else:
                if not blocking:
                    return False
                else:
                    if self._cond.wait(timeout):
                        self._value = False
                        return True
                    else:
                        return False

    __enter__ = acquire

    def release(self):
        """Release a semaphore, incrementing the internal counter by one.

        When the counter is zero on entry and another thread is waiting for it
        to become larger than zero again, wake up that thread.

        """
        if not self._value:
            with self._cond:
                self._value = True
                self._cond.notify()

    def __exit__(self, t, v, tb):
        self.release()


# -*- coding: utf-8 -*-
r"""
Template filter for rendering a string with syntax highlighting.
It relies on Pygments to accomplish this.

Some standard usage examples (from within Django templates).
Coloring a string with the Python lexer:

    {% load syntax_color %}
    {{ code_string|colorize:"python" }}

You may use any lexer in Pygments. The complete list of which
can be found [on the Pygments website][1].

[1]: https://pygments.org/docs/lexers/

You may also have Pygments attempt to guess the correct lexer for
a particular string. However, if may not be able to choose a lexer,
in which case it will simply return the string unmodified. This is
less efficient compared to specifying the lexer to use.

    {{ code_string|colorize }}

You may also render the syntax highlighted text with line numbers.

    {% load syntax_color %}
    {{ some_code|colorize_table:"html+django" }}
    {{ let_pygments_pick_for_this_code|colorize_table }}

Please note that before you can load the ``syntax_color`` template filters
you will need to add the ``django_extensions.utils`` application to the
``INSTALLED_APPS``setting in your project's ``settings.py`` file.
"""
import os

from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe

try:
    from pygments import highlight
    from pygments.formatters import HtmlFormatter
    from pygments.lexers import get_lexer_by_name, guess_lexer, ClassNotFound
    HAS_PYGMENTS = True
except ImportError:  # pragma: no cover
    HAS_PYGMENTS = False

__author__ = 'Will Larson <lethain@gmail.com>'

register = template.Library()

def pygments_required(func):
    """Raise ImportError if pygments is not installed."""
    def wrapper(*args, **kwargs):
        if not HAS_PYGMENTS:  # pragma: no cover
            raise ImportError(
                "Please install 'pygments' library to use syntax_color.")
        rv = func(*args, **kwargs)
        return rv
    return wrapper

@pygments_required
@register.simple_tag
def pygments_css():
    return HtmlFormatter().get_style_defs('.highlight')

def generate_pygments_css(path=None):
    path = os.path.join(path or os.getcwd(), 'pygments.css')
    f = open(path, 'w')
    f.write(pygments_css())
    f.close()

def get_lexer(value, arg):
    if arg is None:
        return guess_lexer(value)
    return get_lexer_by_name(arg)

@pygments_required
@register.filter(name='colorize')
@stringfilter
def colorize(value, arg=None):
    try:
        return mark_safe(highlight(value, get_lexer(value, arg), HtmlFormatter()))
    except ClassNotFound:
        return value

@pygments_required
@register.filter(name='colorize_table')
@stringfilter
def colorize_table(value, arg=None):
    try:
        return mark_safe(highlight(value, get_lexer(value, arg), HtmlFormatter(linenos='table')))
    except ClassNotFound:
        return value

@pygments_required
@register.filter(name='colorize_noclasses')
@stringfilter
def colorize_noclasses(value, arg=None):
    try:
        return mark_safe(highlight(value, get_lexer(value, arg), HtmlFormatter(noclasses=True)))
    except ClassNotFound:
        return value


import random

class Markov(object):

	def __init__(self, open_file):
		self.cache = {}
		self.open_file = open_file
		self.words = self.file_to_words()
		self.word_size = len(self.words)
		self.database()

	def file_to_words(self):
		self.open_file.seek(0)
		data = self.open_file.read()
		words = data.split()
		return words

	def triples(self):
		""" Generates triples from the given data string. So if our string were
				"What a lovely day", we'd generate (What, a, lovely) and then
				(a, lovely, day).
		"""

		if len(self.words) < 3:
			return

		for i in range(len(self.words) - 2):
			yield (self.words[i], self.words[i+1], self.words[i+2])

	def database(self):
		for w1, w2, w3 in self.triples():
			key = (w1, w2)
			if key in self.cache:
				self.cache[key].append(w3)
			else:
				self.cache[key] = [w3]

	def generate_markov_text(self, last_one, last_two, size=40):
		'''
		this will take 2 words and an optional size arg and from there, create a chain begining with those words, spaning at least
		'size' words and finishing with a period
		'''
		seed = random.randint(0, self.word_size-3)
		w1, w2 = last_one, last_two
		gen_words = []
		for i in xrange(size):
			gen_words.append(w1)
			w1, w2 = w2, random.choice(self.cache[(w1, w2)])
		while w2[len(w2)-1] != '.':
			gen_words.append(w1)
			w1, w2 = w2, random.choice(self.cache[(w1, w2)])
		gen_words.append(w2)
		return ' '.join(gen_words)


from django.urls import path

from . import views

app_name = 'my_apps'
urlpatterns = [
    path('admin/', views.calc, name='admin'),
    path('beer_calc/', views.calc, name='beer_calc'),
    path('', views.index, name='homepage'),
    path('meetings_calendar/', views.calendar_generate, name='meetings_calendar'),
    path('meetings_edit_event/<int:id>/', views.edit_event, name='meetings_edit_event'),
    path('meetings_new_event/', views.new_event, name='meetings_new_event'),
    path('users_friends/', views.friends, name='users_friends'),
    path('users_log_in/', views.log_in, name='users_log_in'),
    path('users_log_out/', views.log_out, name='users_log_out'),
    path('users_register/', views.register, name='users_register'),
    path('split_homepage/', views.add_expense_group, name='split_homepage'),
    path('split_group/<int:group_id>/', views.split_group, name='split_group'),
]


"""
------------------------------------------------------------------------------------------------
Creado por Victor Daniel Sanchez Navarro.
Fecha: 06/10/2022
------------------------------------------------------------------------------------------------
"""
import random
import os

#Clase para poner color
class ANSI():
    def background(code):
        return "\33[{code}m".format(code=code)

    def style_text(code):
        return "\33[{code}m".format(code=code)

    def color_text(code):
        return "\33[{code}m".format(code=code)

FILAS = 10
COLUMNAS = 10
MAR = " "
PORTAAVION = "P" # Ocupa 5 casillas horizontal
ACORAZADO = "A" # Ocupa 4 casillas horizontal
CRUCERO = "C" # Ocupa 3 casillas horizontal
SUBMARINO = "S" # Ocupa 3 casillas vertical
DESTRUCTOR = "D"  # Ocupa 2 celdas vertical
DISPARO_FALLADO = "-"
DISPARO_ACERTADO = "*"
DISPAROS_INICIALES = 20
CANTIDAD_BARCOS_INICIALES = 10
JUGADOR_1 = "J1"
JUGADOR_2 = "J2"

def obtener_matriz_inicial():
    matriz = []
    for y in range(FILAS):
        # Agregamos un arreglo a la matriz.
        matriz.append([])
        for x in range(COLUMNAS):
            # Y luego agregamos una celda a esa fila. Por defecto lleva "Mar"
            matriz[y].append(MAR)
    return matriz

def incrementar_letra(letra):
    return chr(ord(letra)+1)

def imprimir_separador_horizontal():
    # Imprimir un renglón dependiendo de las columnas
    for _ in range(COLUMNAS+1):
        print("+---", end="")
    print("+")

def imprimir_fila_de_numeros():
    print("|   ", end="")
    for x in range(COLUMNAS):
        print(f"| {x+1} ", end="")
    print("|")

# Indica si una coordenada de la matriz está vacía
def es_mar(x, y, matriz):
    return matriz[y][x] == MAR

def coordenada_en_rango(x, y):
    return x >= 0 and x <= COLUMNAS-1 and y >= 0 and y <= FILAS-1

def colocar_e_imprimir_barcos(matriz, cantidad_barcos, jugador):
    barcos_cinco_celdas = cantidad_barcos//4
    barcos_cuatro_celdas = cantidad_barcos//4
    barcos_tres_celdas = cantidad_barcos//4
    barcos_tres_celdas_vertical = cantidad_barcos//4
    barcos_dos_celdas = cantidad_barcos//4

    if jugador == JUGADOR_1:
        print("Imprimiendo barcos del jugador 1 ")
    else:
        print("Imprimiendo barcos del jugador 2 ")
    print(f"Portaaviones: {barcos_cinco_celdas}\nAcorazado: {barcos_cuatro_celdas}\nCrucero: {barcos_tres_celdas}\nSubmarino: {barcos_tres_celdas_vertical}\nDestructor: {barcos_dos_celdas}\nTotal: {barcos_cinco_celdas+barcos_cuatro_celdas+barcos_tres_celdas+barcos_tres_celdas_vertical+barcos_dos_celdas}")
    # Primero colocamos los que tienen mas celdas para que se acomoden bien
    matriz = colocar_barcos_de_cinco_celdas_horizontal(
        barcos_cinco_celdas, PORTAAVION, matriz)
    matriz = colocar_barcos_de_cuatro_celdas_horizontal(
        barcos_cuatro_celdas, ACORAZADO, matriz)
    matriz = colocar_barcos_de_tres_celdas_horizontal(
        barcos_tres_celdas, CRUCERO, matriz)
    matriz = colocar_barcos_de_tres_celdas_vertical(
        barcos_tres_celdas_vertical, SUBMARINO, matriz)
    matriz = colocar_barcos_de_dos_celdas_vertical(
        barcos_dos_celdas, DESTRUCTOR, matriz)
    return matriz

def obtener_x_aleatoria():
    return random.randint(0, COLUMNAS-1)

def obtener_y_aleatoria():
    return random.randint(0, FILAS-1)

def colocar_barcos_de_una_celda(cantidad, tipo_barco, matriz):
    barcos_colocados = 0
    while True:
        x = obtener_x_aleatoria()
        y = obtener_y_aleatoria()
        if es_mar(x, y, matriz):
            matriz[y][x] = tipo_barco
            barcos_colocados += 1
        if barcos_colocados >= cantidad:
            break
    return matriz

def colocar_barcos_de_cinco_celdas_horizontal(cantidad, tipo_barco, matriz):
    barcos_colocados = 0
    i = 1
    while True:
        x = obtener_x_aleatoria()
        y = obtener_y_aleatoria()
        #x2 = x+1
        if coordenada_en_rango(x, y) and coordenada_en_rango(x, y) and es_mar(x, y, matriz) and es_mar(x, y, matriz):
            for i in range(5):
                matriz[y][i] = tipo_barco
            barcos_colocados += 1
        if barcos_colocados >= cantidad:
            break
    return matriz

def colocar_barcos_de_cuatro_celdas_horizontal(cantidad, tipo_barco, matriz):
    barcos_colocados = 0
    i = 1
    while True:
        x = obtener_x_aleatoria()
        y = obtener_y_aleatoria()
        x2 = x+1
        if coordenada_en_rango(x, y) and coordenada_en_rango(x2, y) and es_mar(x, y, matriz) and es_mar(x2, y, matriz):
            for i in range(4):
                matriz[y][i] = tipo_barco
            barcos_colocados += 1
        if barcos_colocados >= cantidad:
            break
    return matriz

def colocar_barcos_de_tres_celdas_horizontal(cantidad, tipo_barco, matriz):
    barcos_colocados = 0
    i = 1
    while True:
        x = obtener_x_aleatoria()
        y = obtener_y_aleatoria()
        x2 = x+1
        if coordenada_en_rango(x, y) and coordenada_en_rango(x2, y) and es_mar(x, y, matriz) and es_mar(x2, y, matriz):
            for i in range(3):
                #matriz[y][x] = tipo_barco
                matriz[y][i] = tipo_barco
            barcos_colocados += 1
        if barcos_colocados >= cantidad:
            break
    return matriz

def colocar_barcos_de_tres_celdas_vertical(cantidad, tipo_barco, matriz):
    barcos_colocados = 0
    i = 1
    while True:
        x = obtener_x_aleatoria()
        y = obtener_y_aleatoria()
        y2 = y+1
        if coordenada_en_rango(x, y) and coordenada_en_rango(x, y2) and es_mar(x, y, matriz) and es_mar(x, y2, matriz):
            for i in range(3):
                #matriz[y][x] = tipo_barco
                matriz[i][x] = tipo_barco
            barcos_colocados += 1
        if barcos_colocados >= cantidad:
            break
    return matriz

def colocar_barcos_de_dos_celdas_horizontal(cantidad, tipo_barco, matriz):
    barcos_colocados = 0
    while True:
        x = obtener_x_aleatoria()
        y = obtener_y_aleatoria()
        x2 = x+1
        if coordenada_en_rango(x, y) and coordenada_en_rango(x2, y) and es_mar(x, y, matriz) and es_mar(x2, y, matriz):
            matriz[y][x] = tipo_barco
            matriz[y][x2] = tipo_barco
            barcos_colocados += 1
        if barcos_colocados >= cantidad:
            break
    return matriz

def colocar_barcos_de_dos_celdas_vertical(cantidad, tipo_barco, matriz):
    barcos_colocados = 0
    while True:
        x = obtener_x_aleatoria()
        y = obtener_y_aleatoria()
        y2 = y+1
        if coordenada_en_rango(x, y) and coordenada_en_rango(x, y2) and es_mar(x, y, matriz) and es_mar(x, y2, matriz):
            matriz[y][x] = tipo_barco
            matriz[y2][x] = tipo_barco
            barcos_colocados += 1
        if barcos_colocados >= cantidad:
            break
    return matriz

def imprimir_disparos_restantes(disparos_restantes, jugador):
    print(f"Disparos restantes de {jugador}: {disparos_restantes}")

def imprimir_matriz(matriz, deberia_mostrar_barcos, jugador):
    print(f"Este es el mar del jugador {jugador}: ")
    letra = "A"
    for y in range(FILAS):
        imprimir_separador_horizontal()
        print(f"| {letra} ", end="")
        for x in range(COLUMNAS):
            celda = matriz[y][x]
            valor_real = celda
            if not deberia_mostrar_barcos and valor_real != MAR and valor_real != DISPARO_FALLADO and valor_real != DISPARO_ACERTADO:
                valor_real = " "
            print(f"| {valor_real} ", end="")
        letra = incrementar_letra(letra)
        print("|",)  # Salto de línea
    imprimir_separador_horizontal()
    imprimir_fila_de_numeros()
    imprimir_separador_horizontal()

def solicitar_coordenadas(jugador):
    print(f"Solicitando coordenadas de disparo al jugador {jugador}")
    # Ciclo infinito. Se rompe cuando ingresan una fila correcta
    y = None
    x = None
    while True:
        letra_fila = input(
            "Ingrese una letra de la A a la J en mayuscula: ")
        # Necesitamos una letra de 1 carácter. Si no es de 1 carácter usamos continue para repetir este ciclo
        if len(letra_fila) != 1:
            print("Debes ingresar únicamente una letra")
            continue
        # Convertir la letra a un índice para acceder a la matriz
        # La A equivale al ASCII 65, la B al 66. Para convertir la letra a índice
        # convertimos la letra a su ASCII y le restamos 65 (el 65 es el ASCII de la A, por lo que A es 0)
        y = ord(letra_fila) - 65
        # Verificar si es válida. En caso de que sí, rompemos el ciclo
        if coordenada_en_rango(0, y):
            break
        else:
            print("Fila inválida")
    # Hacemos lo mismo pero para la columna
    while True:
        try:
            x = int(input("Ingresa el número de columna: "))
            if coordenada_en_rango(x-1, 0):
                x = x-1  # Para hallar el indice restamos un 1
                break
            else:
                print("Columna inválida")
        except:
            print("Ingresa un número válido")

    return x, y

def disparar(x, y, matriz) -> bool:
    if es_mar(x, y, matriz):
        matriz[y][x] = DISPARO_FALLADO
        return False
    # Si ya había disparado antes, se le cuenta como falla igualmente
    elif matriz[y][x] == DISPARO_FALLADO or matriz[y][x] == DISPARO_ACERTADO:
        return False
    else:
        matriz[y][x] = DISPARO_ACERTADO
        return True

def oponente_de_jugador(jugador):
    if jugador == JUGADOR_1:
        return JUGADOR_2
    else:
        return JUGADOR_1

def todos_los_barcos_hundidos(matriz):
    for y in range(FILAS):
        for x in range(COLUMNAS):
            celda = matriz[y][x]
            # Si no es mar o un disparo, significa que todavía hay un barco por ahí
            if celda != MAR and celda != DISPARO_ACERTADO and celda != DISPARO_FALLADO:
                return False
    # Acabamos de recorrer toda la matriz y no regresamos en la línea anterior. Entonces todos los barcos han sido hundidos
    return True

def indicar_victoria(jugador):
    print(f"Fin del juego\nEl jugador {jugador} es el ganador")

def indicar_fracaso(jugador):
    print(
        f"Fin del juego\nEl jugador {jugador} pierde. Se han acabado sus disparos")

def imprimir_matrices_con_barcos(matriz_j1, matriz_j2):
    print("Mostrando ubicación de los barcos de ambos jugadores:")
    imprimir_matriz(matriz_j1, True, JUGADOR_1)
    imprimir_matriz(matriz_j2, True, JUGADOR_2)

def jugar():
    disparos_restantes_j1 = DISPAROS_INICIALES
    disparos_restantes_j2 = DISPAROS_INICIALES
    cantidad_barcos = 5
    matriz_j1, matriz_j2 = obtener_matriz_inicial(), obtener_matriz_inicial()
    matriz_j1 = colocar_e_imprimir_barcos(
        matriz_j1, cantidad_barcos, JUGADOR_1)
    matriz_j2 = colocar_e_imprimir_barcos(
        matriz_j2, cantidad_barcos, JUGADOR_2)
    turno_actual = JUGADOR_1
    print("===============")
    while True:
        print(f"Turno de {turno_actual}")
        disparos_restantes = disparos_restantes_j2
        if turno_actual == JUGADOR_1:
            disparos_restantes = disparos_restantes_j1
        imprimir_disparos_restantes(disparos_restantes, turno_actual)
        matriz_oponente = matriz_j1
        if turno_actual == JUGADOR_1:
            matriz_oponente = matriz_j2
        imprimir_matriz(matriz_oponente, False,
                        oponente_de_jugador(turno_actual))
        x, y = solicitar_coordenadas(turno_actual)
        acertado = disparar(x, y, matriz_oponente)
        if turno_actual == JUGADOR_1:
            disparos_restantes_j1 -= 1
        else:
            disparos_restantes_j2 -= 1

        imprimir_matriz(matriz_oponente, False,
                        oponente_de_jugador(turno_actual))
        if acertado:
            print("Disparo acertado")
            if todos_los_barcos_hundidos(matriz_oponente):
                indicar_victoria(turno_actual)
                imprimir_matrices_con_barcos(matriz_j1, matriz_j2)
                break
        else:
            print("Disparo fallado")
            if disparos_restantes-1 <= 0:
                indicar_fracaso(turno_actual)
                imprimir_matrices_con_barcos(matriz_j1, matriz_j2)
                break
            turno_actual = oponente_de_jugador(turno_actual)

def acerca_de():
    print("Realizado por Victor Daniel Sanchez Navarro")

def mostrar_menu():
    eleccion = ""
    while eleccion != "3":
        menu = """Batalla Naval
1. Jugar
2. Acerca de
3. Salir
Selecciona una opción: """
        eleccion = input(menu)
        if eleccion == "1":
            jugar()
        elif eleccion == "2":
            acerca_de()

mostrar_menu()


from music21 import*
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import LSTM
from keras.layers import Activation
from keras.utils import np_utils
from keras.callbacks import ModelCheckpoint
from keras.layers import Flatten

import utildata as ud
import numpy as np

dataset = ud.loadobj('./Files/BachChords')
num_timesteps = 16

#Create input sequences and corresponding output sequences(one_hot categorical)
def get_sequences(dataset):
    input_sequences = []
    output_sequences = []
    #Traverse each song
    for song in dataset:
        for i in range(0,len(song)-(num_timesteps+1),1):
            timestep_set = song[i:i+num_timesteps]
            temp_in = []
            for something in timestep_set:
                note = something[0]
                time = something[len(something)-1]
                temp_in.append([note,time])
            input_sequences.append(temp_in)
            note_out = song[i+num_timesteps][0]
            time_out = song[i+num_timesteps][len(song[i+num_timesteps])-1]
            output_sequences.append([note_out,time_out])
    return input_sequences,output_sequences

#One-hot encode output
def one_hot(output_sequences):
    return np_utils.to_categorical(output_sequences)

#Standerdize input sequences for neural net
def normalize(input_sequences,output_size):
    num = len(input_sequences)
    input_sequences = np.reshape(input_sequences,(num,num_timesteps,2))
    normalized_input = input_sequences/float(output_size)
    return normalized_input

def train_network():
    input_sequences,output_sequences = get_sequences(dataset)
    output_sequences = one_hot(output_sequences)
    print(output_sequences)
    input_sequences = normalize(input_sequences,output_sequences.shape[1])

    model = create_network(input_sequences,output_sequences.shape[1])
    train(model,input_sequences,output_sequences)

def create_network(network_input,output_size):
    model = Sequential()

    model.add(LSTM(
    512,
    input_shape=(network_input.shape[1],network_input.shape[2]),
    return_sequences=True
    ))
    model.add(Dropout(0.5))
    model.add(LSTM(1024,return_sequences=True))
    model.add(Dropout(0.5))
    model.add(LSTM(1024,return_sequences=True))
    model.add(Dropout(0.5))
    model.add(LSTM(512))
    model.add(Dense(512))
    model.add(Dropout(0.5))
    model.add(Dense(output_size))
    model.add(Activation('softmax'))
    model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['categorical_accuracy'])

    return model

def train(model,network_input,network_output):
    filepath = "./TrainingData/KERAS-LSTM/weights-{epoch:02d}-{loss:.4f}.hdf5"
    checkpoint = ModelCheckpoint(
    filepath,
    monitor='loss',
    verbose=1,
    save_best_only=True,
    mode='min'
    )
    callbacks_list = [checkpoint]

    model.fit(network_input,network_output,epochs=1000,batch_size=50,callbacks=callbacks_list)

if __name__=='__main__':
    train_network()


import os
import os.path
max_offset = 26
result = ""

def getString():
        print('Please enter the name of the source file. ')
        file = input()
        if os.path.isfile(file):
            textFile = open(file, 'r')
            string = textFile.read()
            return string
        else:
            print('File name incorrect.')
            exit(1)
def getOutputFile():
    print ('Please enter the name of the output file. ')
    file = input()
    try:
        outputFile = open(file, 'w')
        return outputFile
    except:
        print('Output file cannot be accessed.')
        exit(1)

def getOffset():
    offset = 0
    while True:
        print('Enter the offset (1-%s)' % (max_offset))
        offset = int(input())
        if (offset >= 1 and offset <= max_offset):
            return offset
        else:
            print('Incorrect offset entered.')

def caesar(string, offset):
    offset = -offset
    result = ""

    if symbol.isalpha():
            num = ord(symbol)
            num += offset

            if symbol.isupper():
                if num > ord('Z'):
                    num -= 26
                elif num < ord('A'):
                    num += 26
            elif symbol.islower():
                if num > ord('z'):
                    num -= 26
                elif num < ord('a'):
                    num += 26
            result += chr(num)
    else:
        result += symbol
    return result

def writeOutput(outputFile, result):
    outputFile.write(result)
    outputFile.close()

string = getString()
outputFile = getOutputFile()
offset = getOffset()
for symbol in string:
    result += caesar(string, offset)
writeOutput(outputFile, result)


answer = 0
N = int(input()) # 분해합.

for i in range(0, N+1):
    str_num = str(i)
    temp_num = i
    for s in str_num:
        temp_num += int(s)
    if temp_num == N:
        answer = i
        break
print(answer)


FILE_PATH = "src/data/employee_retention.csv"
TEST_SIZE = 0.3
TARGET = "left"
TEST_DATA_FILE = "src/data/test_data.csv"

ALL_MODELS_OUTPUT_DIR = "src/output/performance"
ALL_MODELS_PERFORMANCE_IMAGE_NAME = "performance_metrics"

VISUALIZATION_OUTPUT_DIR = "src/output/visualization"
COR_MATRIX_FILE_NAME = "colorbar_visualization"
HEATMAP_FILE_NAME = "heatmap_visualization"
PAIR_PLOT_FILE_NAME = "pair_plots_visualization"


'''
---------------
Assignment 4.6

Write a program to prompt the user for hours
and rate per hour using input to compute gross pay.
Pay should be the normal rate for hours up to 40 and
time-and-a-half for the hourly rate for all hours worked above
40 hours.

Put the logic to do the computation of pay in a function
called computepay() and use the function to do the computation.
The function should return a value.

Use 45 hours and a rate of 10.50 per hour to test the program
(the pay should be 498.75). You should use input to read a
string and float() to convert the string to a number.
Do not worry about error checking the user input unless
you want to - you can assume the user types numbers properly.

Do not name your variable sum or use the sum() function.
---------------
'''

# Verify and set hours worked
shours = (input("How many hours did you work? "))

try :
    ihours = float(shours)
except :
    print("Invalid entry, please enter a numerical value")
    quit()

# Verify and set hourly wage
swage = (input("What is your hourly wage? "))

try :
    iwage  = float(swage)
except :
    print("Invalid entry, please enter a numerical value")
    quit()

# Calculate pay function
def computepay(hours, wage) :

    otHours = 0
    otWage = 0

    if (hours > 40.0) :
        otHours = (hours - 40)
        otWage = (wage * 1.5)
        hours = 40

    pay = (hours * wage) + (otHours * otWage)
    return pay

# Run function and print pay
paycheckAmount = computepay(ihours, iwage)
print(paycheckAmount)

# Caclulate Gross Pay
def computeGrossPay(hours, wage) :
    otHours = 0
    otWage = 0

    if (hours > 40.0) :
        otHours = (hours - 40)
        otWage = (wage * 1.5)
        hours = 40

    pay = (hours * wage) + (otHours * otWage)

    grossPay = (pay * .7)
    return grossPay

grossPaycheckAmount = computeGrossPay(ihours, iwage)
print("Gross Pay:", grossPaycheckAmount)


#tkinter touchpad binds
import tkinter

window = tkinter.Tk()
canvas = tkinter.Canvas()
canvas.pack()

def circle(coordinates):
    #print(coordinates)
    x = coordinates.x
    y = coordinates.y
    canvas.create_oval(x-5, y-5, x+5, y+5)

def house(coordinates):
    x = coordinates.x
    y = coordinates.y
    canvas.create_rectangle(x-5, y-5, x+5, y+5)
    canvas.create_line(x-5, y-5, x, y-10, x+5, y-5)

def bored(coordinates):
    x = coordinates.x
    y = coordinates.y
    canvas.create_oval(x-5, y-10, x+5, y+10)

canvas.bind('<Button-1>',circle)
canvas.bind('<Button-3>', house)
canvas.bind('<B1-Motion>', bored)
window.mainloop()


SCREEN_SIZE = (1440, 1000)
SQUARE_SIZE = 100
L_SQUARE_COLOR = (195,165,113)
D_SQUARE_COLOR = (137,93,58)
BACKRGOUND_COLOR = (55, 55, 55)

import pygame as pg
screen = pg.display.set_mode((SCREEN_SIZE), pg.RESIZABLE)

def draw():
    draw_board()

def draw_board():
    pg.draw.rect(screen, (BACKRGOUND_COLOR), ((0, 0), SCREEN_SIZE))
    draw_squares()

def draw_squares():
    for i in range(8):
        start_pos = ((SCREEN_SIZE[0] - SQUARE_SIZE * 8) / 2, ((SCREEN_SIZE[1] - SQUARE_SIZE * 8) /2) + SQUARE_SIZE * i)
        draw_rank(start_pos, i%2)

def draw_rank(start_pos, start_color):
    for i in range(8):
        if (start_color + i) % 2 == 0:
            color = L_SQUARE_COLOR
        else:
            color = D_SQUARE_COLOR
        pg.draw.rect(screen, color, ((start_pos[0] + i * SQUARE_SIZE, start_pos[1]), (SQUARE_SIZE, SQUARE_SIZE)))

draw_board()

pg.display.update()

while True:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            pg.quit()

        if event.type == pg.VIDEORESIZE:
            SCREEN_SIZE = screen.get_size()
            draw()
            pg.display.update()


"""Helpers to label files.
For any data file, i.e., ``image.png``, the corresponding label files has the
same base, but the extension ``.label``, i.e., ``image.label``.
IPython widgtes for annotating data sets:
* :class:`ImageAnnotator`
* :class:`AudioAnnotator`
* :class:`Annotator`
Distributed as part of ``https://github.com/chmp/misc-exp`` under the MIT
license, (c) 2017 Christopher Prohm.
"""
import base64
import collections.abc
import datetime
import glob
import html
import json
import logging
import os.path

from ipywidgets import DOMWidget, Button, Text, HBox, VBox, jslink, register
from IPython.display import display_javascript, Javascript
from traitlets import Unicode, Float

from astropy.coordinates import Angle, SkyCoord
from astropy import units as u

_logger = logging.getLogger(__name__)

def get_source_name(s):
    source_coord = SkyCoord(
            s['wavg_ra'],
            s['wavg_dec'],
            unit=(u.deg, u.deg)
        )
    source_name = "VAST {}".format(
            source_coord.to_string(
                "hmsdms", sep='', precision=1
            ).replace(
                " ", ""
            )[:15]
        )
    return source_name

def annotate(
    items, sources, *, classes, history_length=5, display_value=None, cls=None, kwargs=None
):
    """Annotate data inside the ipython notebook.
    This function constructs an IPython widget and displays it to the user. The
    returned list will be filled with the labels as the user interacts with the
    widget.
    :param Sequence[Any] items:
        the collection of items to label. The interpretation of the items
        depends on the :class:`Annotator` chosen by the ``cls`` argument.  For
        image and audio, each item should be a filename. For text, the items
        should be the lines of the text. For custom ``display_value`` each item
        is passed as is.
    :param Sequence[str] classes:
        the classes to choose from.
    :param int history_length:
        the number of previously labeled items to show for changes in case of
        errors.
    :param Optional[Callable[str,Any]] display_value:
        if given, a callable that accepts an item and returns a HTML
        representation to show to the user.
    :param Optional[Union[str,class]] cls:
        the type of annotator to use. Can be either a class directly or one
        of ``'image'``, ``'audio'``. If not given, but ``display_value`` is
        given, it will be used to display the result to the user. If neither
        one is given, the ``repr`` will be shown to the user.
    :param Optional[Mapping[Str,Any]] kwargs:
        if given, additional keyword arguments passed on constucting the
        annotator object. Note, ``history_length`` and ``display_value``
        are set by the parameters of this function.
    :returns:
        a list that is filled with feedback supplied by the user. In case of
        corrections both the old and the new label will be returned. With the
        new label having a higher index. To only retain the latest labels, use
        the additional ``get_latest`` method on the returned object.
    """
    from IPython.core.display import display

    kwargs = {} if kwargs is None else dict(kwargs)

    kwargs.update(history_length=history_length)
    if display_value is not None:
        kwargs.update(display_value=display_value)

    annotator = SourceAnnotator(classes, **kwargs)

    annotator.annotate(items)
    display(annotator)

    return annotator.annotations

def listdata(pattern, valid_lables=None):
    fnames = glob.glob(pattern)
    result = []

    for fname in fnames:
        if has_label(fname):
            d = dict(get_label(fname), file=os.path.abspath(fname))

        else:
            d = dict(label="<unlabeled>", file=os.path.abspath(fname))

        if valid_lables is None or d["label"] in valid_lables:
            result.append(d)

    return result

def get_label(fname):
    fname = get_label_fname(fname)
    with open(fname, "rt") as fobj:
        return json.load(fobj)

def find_labeled(pattern, recursive=False):
    return _find_predicate(pattern, recursive, lambda fname: has_label(fname))

def find_unlabeled(pattern, recursive=False):
    return _find_predicate(pattern, recursive, lambda fname: not has_label(fname))

def _find_predicate(pattern, recursive, predicate):
    return [
        fname for fname in glob.iglob(pattern, recursive=recursive) if predicate(fname)
    ]

def has_label(fname):
    return os.path.exists(get_label_fname(fname))

def write_label(*args, keep_existing=True, **kwargs):
    if len(args) == 1:
        fname, = args
        d = {}

    elif len(args) == 2:
        fname, d = args
        d = dict(d)

    else:
        raise ValueError("invalid number of position arguments: {}".format(len(args)))

    d.update(kwargs)
    label_fname = get_label_fname(fname)

    if keep_existing:
        if os.path.exists(label_fname):
            _logger.info("found existing label file %s", label_fname)
            with open(label_fname, "rt") as fobj:
                old_label = json.load(fobj)

            d["old_label"] = old_label

    if "timestamp" not in d:
        d["timestamp"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    _logger.info("write file %s", label_fname)
    with open(label_fname, "w") as fobj:
        json.dump(d, fobj, indent=2, sort_keys=True)

def get_label_fname(fname):
    label_fname, _ = os.path.splitext(fname)
    label_fname = label_fname + ".label"

    return label_fname

def write_latest_labels(
    annotator, skip_class="skip", label_key="label", fname_key="item"
):
    """Write the latest labels added to an annotator.
    """

    def unpack(*dict_and_keys):
        d, *keys = dict_and_keys
        return tuple(d[k] for k in keys)

    for item in annotator.get_latest():
        fname = item[fname_key]
        label = item[label_key]

        if label == skip_class:
            continue

        kwargs = dict(item, fname=os.path.basename(fname), label=label)
        write_label(fname, **kwargs)

class BaseAnnotator:
    """Abstract annotator without ties to IPython.
    """

    def __init__(self):
        self.data = None
        self.annotations = None
        self.current_item = None

    def get_latest(self):
        if self.annotations is None:
            return []

        return self.annotations.get_latest()

    def update_display(self):
        """Hook that is called, when new information should be shown.
        The default does nothing, to add custom behavior overwrite it in a
        subclass.
        """
        pass

    def clear(self):
        self.annotations = None
        self.data = None
        self.current_item = None

    def annotate(self, data):
        if self.annotations is not None:
            raise RuntimeError("call clear before annotating again")

        self.annotations = Annotations()
        self.data = [("order", idx, item) for idx, item in enumerate(data)]
        self.next()

    def next(self, item=None):
        if item is not None:
            self.current_item = item

        elif self.data:
            self.current_item = self.data.pop(0)

        else:
            self.current_item = None
            self.update_display()
            return

        self.update_display()

    def annotate_current(self, label):
        if self.annotations is None or self.current_item is None:
            return

        reason, index, item = self.current_item
        self.annotations.append(
            dict(index=index, reason=reason, item=item, label=label)
        )
        self.next()

    def repeat(self, idx):
        if idx < 0 or idx >= len(self.annotations):
            return

        if self.current_item is not None:
            self.data.insert(0, self.current_item)

        index, item = self.annotations[idx]["index"], self.annotations[idx]["item"]
        item = "repeat", index, item

        self.next(item)

class Annotator(BaseAnnotator):
    """IPython widget to quickly annotate data sets.
    """

    def __init__(self, classes, history_length=10):
        super().__init__()
        self.history_length = int(history_length)
        self.last_repeat = 0
        self._build(classes)

    def build_display_value(self, item):
        """Build the display of the item being annotated.
        This class has to be overwritten in subclasses.
        :returns:
            an HTML reprensetation of the item to display.
        """
        return html.escape(repr(item))

    def clear(self):
        super().clear()
        self.last_repeat = 0

    def update_display(self):
        if self.current_item is None:
            self._html.value = "No data to annotate"
            self._info.value = " "

        else:
            reason, index, item = self.current_item
            self._html.value = self.build_display_value(item)
            self._info.value = html.escape(
                "index: {}, reason: {}".format(index, reason)
            )

        if len(self.annotations) > self.last_repeat:
            from ipywidgets import Button, Layout

            repeats = list(self._history.children)

            for idx in range(self.last_repeat, len(self.annotations)):
                annotation = self.annotations[idx]

                repeat_button = Button(
                    description=f'{annotation["label"]} - {annotation["item"]!r}',
                    layout=Layout(width="50%"),
                )
                repeat_button.on_click(lambda b: self.repeat(idx))

                repeats = [repeat_button] + repeats

            self.last_repeat = len(self.annotations)

            repeats = repeats[: self.history_length]
            self._history.children = repeats

    def _build(self, classes):
        from ipywidgets import HTML, VBox, Layout, Box

        self._html = HTML(value="No data to annotate")
        self._info = HTML(value=" ")
        self._history = VBox(layout=Layout(margin="1em 0em 0em 0em"))

        self._widget = VBox(
            [
                self._html,
                self._info,
                Box(
                    [self._build_label_button(label) for label in classes],
                    layout=Layout(flex_flow="row wrap"),
                ),
                self._history,
            ]
        )

    def _build_label_button(self, label):
        from ipywidgets import Button

        if not isinstance(label, collections.abc.Mapping):
            label = {"label": label, "style": ""}

        else:
            label = dict(label)
            label.setdefault("style", "")

        b = Button(description=label["label"], button_style=label["style"])
        b.on_click(lambda b: self.annotate_current(label["label"]))
        return b

    def _ipython_display_(self, **kwargs):
        return self._widget._ipython_display_(**kwargs)

class ImageAnnotator(Annotator):
    """IPython widget to annotate image files.
    The widget expects a list of filenames.
    """

    def build_display_value(self, item):
        return ''.format(url=build_data_url(item))

class Annotations(list):
    def get_latest(self):
        result = []
        added = set()

        for item in reversed(self):
            if item["index"] in added:
                continue

            added.add(item["index"])
            result.append(item)

        return result

def build_data_url(fname, mime_type=None):
    """Helper to build a data-url with data read from a file.
    :param str fname:
        the file to load the content from
    :param Optional[str] mime_type:
        if given the mime type to use, otherwise it's auto-detected from the
        file extension.
    :returns:
        the data url.
    """
    _, ext = os.path.splitext(fname)
    ext = ext.lower()

    if mime_type is None:
        try:
            mime_type = _mime_types[ext]

        except AttributeError:
            raise ValueError("unknown file extension {}".format(ext))

    with open(fname, "rb") as fobj:
        data = fobj.read()

    data = base64.b64encode(data)
    data = data.decode("ascii")

    return "data:{mime_type};base64,{data}".format(mime_type=mime_type, data=data)

_mime_types = {
    ".gif": "image.gif",
    ".jpg": "image/jpeg",
    ".mp3": "audio/mpeg",
    ".ogg": "audio/ogg",
    ".png": "image/png",
    ".wav": "audio/wav",
}

class SourceAnnotator(Annotator):
    """IPython widget to annotate Sources.
    The widget expects a list of filenames.
    """
    def __init__(self, sources, classes, folder=None, **kwargs):
        if folder is None:
            self.folder = '.'
        else:
            self.folder = folder

        self.sources = sources
        super(SourceAnnotator, self).__init__(classes, **kwargs)

    def build_display_value(self, item):
        source_info = self.sources.loc[item]
        source_name = get_source_name(source_info).replace(' ','_')
        lc_file = os.path.join(self.folder,'{}_lc.png'.format(source_name))
        cutout_file = os.path.join(self.folder,'{}_cutouts.png'.format(source_name))
        zoomed_cutout_file = os.path.join(self.folder,'{}_cutouts_zoom.png'.format(source_name))

        if os.path.isfile(lc_file):
            lc_html_str = '<img src="{}"'.format(build_data_url(lc_file))
        else:
            lc_html_str = ''

        if os.path.isfile(cutout_file):
            cutout_html_str = '<img src="{}"'.format(build_data_url(cutout_file))
        else:
            cutout_html_str = ''

        if os.path.isfile(zoomed_cutout_file):
            zoomed_cutout_html_str = '<img src="{}"'.format(build_data_url(zoomed_cutout_file))
        else:
            zoomed_cutout_html_str = ''

        url_str = 'V_peak={:.3f}, Eta_peak={:.3f}, SNR: {:.1f}-{:.1f}
'.format(item,source_info.v_peak, source_info.eta_peak, source_info.min_snr, source_info.max_snr)
        return lc_html_str+url_str+cutout_html_str+zoomed_cutout_html_str

    def _get_stats(source_info):
        return

def annotate_sources(
    sources, classes, folder=None, history_length=5, display_value=None, cls=None, kwargs=None, annotations=None
):
    from IPython.core.display import display

    kwargs = {} if kwargs is None else dict(kwargs)

    kwargs.update(history_length=history_length)
    if display_value is not None:
        kwargs.update(display_value=display_value)

    if annotations is not None:
        last_index = annotations[-1]['index']
        sources = sources[last_index+1:]

    annotator = SourceAnnotator(sources, classes, folder=folder, **kwargs)

    source_ids = list(sources.index)
    annotator.annotate(source_ids)
    display(annotator)
    return annotator.annotations, annotator

    #if annotations is None:
    #    return annotator.annotations
    #else:
    #    annotations.extend(annotator.annotations)
    #    return annotations


import sys
read = sys.stdin.readline

#상 하 좌 우 좌상 좌하 우상 우하
d = [[-1, 0], [1, 0], [0, -1], [0, 1], [-1, -1], [1, -1], [-1, 1], [1, 1]]

def getScore(length):
    if length <= 2:
        return 0
    elif length <= 4:
        return 1
    elif length <= 5:
        return 2
    elif length <= 6:
        return 3
    elif length <= 7:
        return 5
    elif length <= 8:
        return 11

def solve(board, nowR, nowC, word, idx, wordIdx):
    global maxString
    global maxScore
    global cnt
    global check

    #이미 찾은적이 있다면 return
    if check[wordIdx]:
        return

    #마지막까지 왔고 마지막 알파벳까지 같다면, 찾은것
    if idx == len(word)-1 and board[nowR][nowC] == word[idx]:
        #찾은 개수 증가
        cnt += 1
        #점수 증가
        maxScore += getScore(len(word))
        #string길이 최대로 바꿈
        if len(word) > len(maxString):
            maxString = word
        elif len(word) == len(maxString):
            tempAlp = [maxString, word]
            tempAlp.sort()
            maxString = tempAlp[0]

        #찾았으니 check True로 바꿈
        check[wordIdx] = True
        return

    #idx번째 알파벳이 다르다면 return
    if board[nowR][nowC] != word[idx]:
        return

    #한 word에서 같은 board 두번 방문 못함
    boardCheck[nowR][nowC] = 1
    #모든 방향 탐색
    for i in range(8):
        nextR, nextC = nowR + d[i][0], nowC + d[i][1]
        #범위 이내이고, board가 방문한적이 없어야함
        if 0<=nextR<4 and 0<=nextC<4:
            if boardCheck[nextR][nextC] == 0:
                solve(board, nextR, nextC, word, idx+1, wordIdx)

    #solve로 넘어가지 않았을때 다시 탐색이 올 수 있기때문에 방문안한것으로 처리해줌
    #(solve로 넘어갔을때만 현재 nowR, nowC board를 못쓰는거지, 다른 R,C에서 현재 nowR, nowC로
    # 넘어 오는 경우에는 방문을 하지 않은 상태여야 하므로)
    boardCheck[nowR][nowC] = 0

W = int(read())
words = [read().replace('\n', '') for _ in range(W)]
#빈줄 입력
_ = read()

#혹시나 같은 단어가 두번 주어지나 싶어서 해봄
words = list(set(words))
W = len(words)

B = int(read())
boards = []
for cnt in range(B):
    temp = [read().replace('\n', '') for _ in range(4)]
    boards.append(temp)
    if cnt == B-1:
        break
    _ = read()

for i in range(B):
    board = boards[i]
    maxScore = 0
    maxString = ''
    cnt = 0
    check = [False for _ in range(W)]
    for w in range(W):
        boardCheck = [[0, 0, 0, 0] for _ in range(4)]
        for n in range(16):
            r, c = n // 4, n % 4
            solve(board, r, c, words[w], 0, w)
    print(maxScore, maxString, cnt)


import pathlib

from django.conf import settings

METAJSONS_PATH = pathlib.Path(settings.BASE_DIR) / settings.JSONFORMS_SCHEMA_DIR
META_VERSIONS = {
    metapath.name[-8:-5]: metapath
    for metapath in METAJSONS_PATH.iterdir() if metapath.suffix == ".json"
}
LATEST_META_VERSION = max(list(META_VERSIONS.keys()))


from typing import List

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        top = 0
        bottom = len(matrix) - 1

        while top <= bottom:
            mid = top + (bottom - top) // 2

            if target < matrix[mid][0]:
                bottom = mid - 1
            elif target > matrix[mid][-1]:
                top = mid + 1
            else:
                break

        if not (top <= bottom):
            return False

        row = top + (bottom - top) // 2

        l = 0
        r = len(matrix[row]) - 1

        while l <= r:
            mid = l + (r - l) // 2

            if matrix[row][mid] < target:
                l = mid + 1

            elif matrix[row][mid] > target:
                r = mid - 1

            else:
                return True

        return False


from flask import Flask,jsonify,request
from dankcli import *
from meme_gen import *
from firebase_upload_download import *
import os
import imageio
import matplotlib.pyplot as plt
from ImageClub import *
from random_no import *

dir_path = os.path.dirname(os.path.realpath(__file__))

app=Flask(__name__)

@app.route('/dankcli-meme',methods=['GET','POST'])
def dankcli():
	n = random_no()
	format_ = '.png'
	name = "Heading_on_image"+n+format_

	url = request.json['URL']
	text = request.json['Text']
	c = request.json['COLOR']

	img = imageio.imread(url)

	plt.imsave(name,meme(img,text,c))

	link = upload("/.Generated/"+name,name)
	return link

@app.route('/meme-gen',methods=['GET','POST'])
def mem_gen():
	n = random_no()
	format_ = '.jpg'
	name = "Heading_on_image"+n+format_

	url = request.json['URL']
	top_text = request.json['TOP']
	bottom_text = request.json['BOTTOM']
	c = request.json['COLOR']

	img = imageio.imread(url)

	plt.imsave(name,generate_meme(c,img,top_text,bottom_text))

	link = upload("/.Generated/"+name,name)

	return link

@app.route('/hconcat',methods=['GET','POST'])
def hconcat():
	n = random_no()
	format_='.jpg'
	name = "Hconcat_"+n+format_

	urls = request.json['URL']
	imgs = [imageio.imread(url) for url in urls]

	plt.imsave(name,hconcat_resize_min(imgs))

	link = upload("/.Generated/"+name,name)

	return link

#completed
@app.route('/vconcat',methods=['GET','POST'])
def vconcat():
	n = random_no()
	format_='.jpg'
	name = "Vconcat_"+n+format_

	urls = request.json['URL']
	imgs = [imageio.imread(url) for url in urls]

	plt.imsave(name,vconcat_resize_min(imgs))

	link = upload("/.Generated/"+name,name)

	return link

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


#!/usr/bin/env python

import pygame
from math import sqrt

class Grid(pygame.sprite.Sprite):
    _cmap = None
    fgcolor = (255,255,255)
    bgcolor = (0,0,0)
    def __init__(self,x,y,width,gridType):
        super(Grid,self).__init__()
        self.rect = pygame.rect.Rect((x*width,y*width),(width,width))
        self.bounds = pygame.rect.Rect((0,0),(width,width))
        self.x = x
        self.y = y
        self.type = gridType

    def __str__(self):
        s = super(Grid,self).__str__()
        return "%s @ type %s %d,%d\n\trect: %s\n\tbounds: %s" % (s,
                                                                 self.type,
                                                                 self.x,self.y,
                                                                 self.rect,
                                                                 self.bounds)

    def distance(self,grid):
        '''
        Grid distance between two grid squares.
        '''
        x = self.x + grid.x
        y = self.y + grid.y
        return int(sqrt((x*x)+(y*y)))

    def heading(self,grid):
        '''
        Unit vector Rect between self and other grid.
        '''

        d = self.distance(grid)

        x = self.x + grid.x
        y = self.y + grid.y

        return pygame.rect.Rect((x/d,y/d),(0,0))


from .accessors import get_check_shapes
from .base_types import Dimension, Shape
from .checker import ShapeChecker
from .checker_context import check_shape, get_shape_checker
from .config import (
    DocstringFormat,
    ShapeCheckingState,
    disable_check_shapes,
    get_drop_frames,
    get_enable_check_shapes,
    get_enable_function_call_precompute,
    get_rewrite_docstrings,
    set_drop_frames,
    set_enable_check_shapes,
    set_enable_function_call_precompute,
    set_rewrite_docstrings,
)
from .decorator import check_shapes
from .error_contexts import ErrorContext
from .inheritance import inherit_check_shapes
from .integration.tf import install_tf_integration
from .integration.tfp import install_tfp_integration
from .integration.torch import install_torch_integration
from .shapes import get_shape, register_get_shape

install_tf_integration()
install_tfp_integration()
install_torch_integration()

__version__ = "1.1.1"

__all__ = [
    "Dimension",
    "DocstringFormat",
    "ErrorContext",
    "Shape",
    "ShapeChecker",
    "ShapeCheckingState",
    "accessors",
    "argument_ref",
    "base_types",
    "bool_specs",
    "check_shape",
    "check_shapes",
    "checker",
    "checker_context",
    "config",
    "decorator",
    "disable_check_shapes",
    "error_contexts",
    "exceptions",
    "get_check_shapes",
    "get_drop_frames",
    "get_enable_check_shapes",
    "get_enable_function_call_precompute",
    "get_rewrite_docstrings",
    "get_shape",
    "get_shape_checker",
    "inherit_check_shapes",
    "inheritance",
    "parser",
    "register_get_shape",
    "set_drop_frames",
    "set_enable_check_shapes",
    "set_enable_function_call_precompute",
    "set_rewrite_docstrings",
    "shapes",
    "specs",
]


#
#
# Author: Aniruddha Gokhale
# CS4287-5287: Principles of Cloud Computing, Vanderbilt University
#
# Created: Sept 6, 2020
#
# Purpose:
#
#    Demonstrate the use of Kafka Python streaming APIs.
#    In this example, we use the "top" command and use it as producer of events for
#    Kafka. The consumer can be another Python program that reads and dumps the
#    information into a database OR just keeps displaying the incoming events on the
#    command line consumer (or consumers)
#

import os   # need this for popen
import time # for sleep
from kafka import KafkaProducer  # producer of events

# We can make this more sophisticated/elegant but for now it is just
# hardcoded to the setup I have on my local VMs

# acquire the producer
# (you will need to change this to your bootstrap server's IP addr)
producer = KafkaProducer (bootstrap_servers="129.114.25.80:9092",
                                          acks=1)  # wait for leader to write to log

# say we send the contents 100 times after a sleep of 1 sec in between
for i in range (100):

    # get the output of the top command
    process = os.popen ("top -n 1 -b")

    # read the contents that we wish to send as topic content
    contents = process.read ()

    # send the contents under topic utilizations. Note that it expects
    # the contents in bytes so we convert it to bytes.
    #
    # Note that here I am not serializing the contents into JSON or anything
    # as such but just taking the output as received and sending it as bytes
    # You will need to modify it to send a JSON structure, say something
    # like <timestamp, contents of top>
    #
    producer.send ("utilizations", value=bytes (contents, 'ascii'))
    producer.flush ()   # try to empty the sending buffer

    # sleep a second
    time.sleep (1)

# we are done
producer.close ()


import math
import random
from torch.nn import MultiLabelSoftMarginLoss
from sklearn.metrics import classification_report
from data_loader import Data
import torch.optim as optim
from models import *
import torch
import time

if __name__=='__main__':
    n_class = 6
    six_field = ['Machine learning',
                'Distributed computing',
                'Real-time computing',
                'Data mining',
                'Computer network',
                'Pattern recognition']

    data = Data('../dataset/6field/', n_class)

    with open('data.pkl', 'wb') as f:
        pickle.dump(data, f)

    criterion = MultiLabelSoftMarginLoss()

    model = GCN(nfeat = data.features.shape[1], nhid=160, nclass=n_class, dropout=0.5)
    optimizer = optim.Adam(model.parameters(), lr=0.0001)
    lab = torch.LongTensor(data.label_list)

    for epoch in range(0, 10001):
        start = time.time()
        model.train()
        optimizer.zero_grad()
        output = model(data.features, data.nfadj)
        loss_train = criterion(output[data.idx_train], lab[data.idx_train])

        loss_train.backward()
        optimizer.step()
        if epoch % 1000 == 0:
            torch.save({
                'epoch': epoch,
                'model_state_dict': model.state_dict(),
                'optimzier_state_dict': optimizer.state_dict(),
                'loss': loss_train,
                }, './noSigmoid.pt')
            print('{:2d} {:.4f} {:.2f}s\n'.format(epoch, loss_train.item(), time.time() - start), end='\t')

            with torch.no_grad():
                model.eval()
                output = model(data.features, data.nfadj)

                outputs = nn.Sigmoid()(output) > 0.5  # uses sigmoid function in test case instead of train case
                kk = classification_report(outputs[data.idx_test].tolist(), lab[data.idx_test].tolist())
                print(kk)


import os
import re
import shutil
import subprocess  # nosec
import sys
import time

os.chdir(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))

version = subprocess.check_output([sys.executable,  # nosec
                                   os.path.join('scripts', 'find_version.py')],
                                  universal_newlines=True).strip()

man_page_src_file = os.path.join('share', 'walrus.rst')
man_page_dst_file = os.path.join('share', 'walrus.1')

with open(man_page_src_file, 'r', encoding='utf-8') as f:
    man_page_content = f.read()

man_page_content = re.sub(
    r'(?m)^:Version: (?:.*?)$',
    ':Version: v{}'.format(version).replace('\\', r'\\'),
    man_page_content, count=1
)
man_page_content = re.sub(
    r'(?m)^:Date: (?:.*?)$',
    ':Date: {}'.format(time.strftime('%B %d, %Y')).replace('\\', r'\\'),
    man_page_content, count=1
)

with open(man_page_src_file, 'w', encoding='utf-8') as f:
    f.write(man_page_content)

rst2man = shutil.which('rst2man.py')
if rst2man is None:
    raise RuntimeError('rst2man.py not found')
subprocess.check_call([sys.executable, rst2man, man_page_src_file, man_page_dst_file])  # nosec


import random

async def main(message, client, args):
  # defaults
  CODE_LEN = 4
  TURNS = 10

  async def play():
    # make code & start game
    digits = [str(n+1) for n in range(6)]
    code = ""
    for x in range(CODE_LEN):
      rd = random.choice(digits)
      code += str(rd)
      digits.remove(rd)
    digits = [str(n+1) for n in range(6)]  # reset digits
    await message.channel.send("The " + str(CODE_LEN) + "-digit code has been made!\nThe options for digits are 1, 2, 3, 4, 5, and 6.\n'x' represents a correct number and location; 'o' represents a correct number; '-' represents an incorrect number.\nYou get " + str(TURNS) + " guesses.")

    # run through 10 trials
    record = "{.author.display_name}'s mastermind game\n".format(message)
    trialnum = 1
    correct = False
    while trialnum <= TURNS and correct is False:
      def onlyNums(msg):
        if msg.channel == message.channel and msg.author == message.author:
          try:
            int(msg.content.replace(" ", ""))  # remove spaces, then check if msg only contains numbers
          except:
            return False
          return True

      await message.channel.send("{.author.mention} Input guess #".format(message) + str(trialnum) + ": ")
      resp = await client.wait_for('message', check=onlyNums)
      guess = resp.content.replace(" ", "")  # remove spaces

      def hasInvalidNums():
        for i in range(CODE_LEN):
          if guess[i] not in digits:
            return True
        return False

      # check string for length and numbers out of range, before grading
      if len(guess) != CODE_LEN:
        await message.channel.send("Your guess should be " + str(CODE_LEN) + " digits long.")
      elif hasInvalidNums():
        await message.channel.send("Your guess should only consist of numbers 1-6.")
      else:  # grade the guess and output appropriate marks
        grade = ""
        digitsAlreadyChecked = set()
        numMarksPlaced = 0

        if guess == code:
          correct = True
          await message.channel.send("Correct!")
        else:
          for h in range(CODE_LEN):  # check for correct number & location
            if guess[h] == code[h]:
              grade += "x"
              numMarksPlaced += 1
              digitsAlreadyChecked.add(guess[h])
          for i in range(CODE_LEN):  # check for correct number
            if guess[i] not in digitsAlreadyChecked:
              for j in range(CODE_LEN):
                if guess[i] == code[j]:
                  grade += "o"
                  numMarksPlaced += 1
            digitsAlreadyChecked.add(guess[i])
          grade += "-" * (CODE_LEN - numMarksPlaced)
          await message.channel.send(grade)
          record += str(trialnum) + ".\t" + guess + "\t" + grade + "\n"
          await message.channel.send("```\n" + record + "```")

        trialnum += 1

    await message.channel.send("The code was: " + code + "\nThanks for playing!")

  # process arguments
  if len(args) > 0:
    if len(args) > 1:
      TURNS = int(args[1])

    CODE_LEN = int(args[0])
    if CODE_LEN > 6:
      await message.channel.send("The code length should be no greater than 6.")
      CODE_LEN = 4
    else:
      await play()
  else:
    await play()

if __name__ == "__main__":
  main()


#!/usr/bin/python
# -*- coding: utf-8 -*-
"""This hook checks Munki pkginfo files to ensure they are valid."""

import argparse
import os
import plistlib
from xml.parsers.expat import ExpatError

from pre_commit_hooks.util import (
    validate_pkginfo_key_types,
    validate_required_keys,
    validate_restart_action_key,
)

def build_argument_parser():
    """Build and return the argument parser."""

    parser = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument("--categories", nargs="+", help="List of approved categories.")
    parser.add_argument("--catalogs", nargs="+", help="List of approved catalogs.")
    parser.add_argument(
        "--required-keys",
        nargs="+",
        default=["description", "name"],
        help="List of required top-level keys.",
    )
    parser.add_argument(
        "--require-pkg-blocking-apps",
        action="store_true",
        help="Require a blocking_applications array for pkg installers.",
    )
    parser.add_argument("filenames", nargs="*", help="Filenames to check.")
    return parser

def main(argv=None):
    """Main process."""

    # Typical extensions for installer packages.
    pkg_exts = ("pkg", "dmg")
    dupe_suffixes = ["__{}.{}".format(i, ext) for ext in pkg_exts for i in range(1, 9)]

    # RestartAction values that obviate the need to check blocking applications.
    blocking_actions = ("RequireRestart", "RequireShutdown", "RequireLogout")

    # Parse command line arguments.
    argparser = build_argument_parser()
    args = argparser.parse_args(argv)

    retval = 0
    for filename in args.filenames:
        try:
            with open(filename, "rb") as openfile:
                pkginfo = plistlib.load(openfile)
        except (ExpatError, ValueError) as err:
            print("{}: plist parsing error: {}".format(filename, err))
            retval = 1

        # Check for presence of required pkginfo keys.
        if args.required_keys:
            if not validate_required_keys(pkginfo, filename, args.required_keys):
                retval = 1
                break  # No need to continue checking this file

        # Ensure pkginfo keys have expected types.
        if not validate_pkginfo_key_types(pkginfo, filename):
            retval = 1

        # Validate RestartAction key.
        if not validate_restart_action_key(pkginfo, filename):
            retval = 1

        # Check for common mistakes in min/max OS version keys.
        os_vers_corrections = {
            "min_os": "minimum_os_version",
            "max_os": "maximum_os_version",
            "min_os_vers": "minimum_os_version",
            "max_os_vers": "maximum_os_version",
            "minimum_os": "minimum_os_version",
            "maximum_os": "maximum_os_version",
            "minimum_os_vers": "minimum_os_version",
            "maximum_os_vers": "maximum_os_version",
        }
        for os_vers_key in os_vers_corrections:
            if os_vers_key in pkginfo:
                print(
                    "{}: You used {} when you probably meant {}.".format(
                        filename, os_vers_key, os_vers_corrections[os_vers_key]
                    )
                )
                retval = 1

        # Check for rogue categories.
        if args.categories and pkginfo.get("category") not in args.categories:
            print(
                '{}: category "{}" is not in list of approved categories'.format(
                    filename, pkginfo.get("category")
                )
            )
            retval = 1

        # Check for rogue catalogs.
        if args.catalogs:
            for catalog in pkginfo.get("catalogs"):
                if catalog not in args.catalogs:
                    print(
                        '{}: catalog "{}" is not in approved list'.format(
                            filename, catalog
                        )
                    )
                    retval = 1

        # Check for pkg filenames showing signs of duplicate imports.
        if pkginfo.get("installer_item_location", "").endswith(tuple(dupe_suffixes)):
            print(
                '{}: installer item "{}" may be a duplicate import'.format(
                    filename, pkginfo.get("installer_item_location")
                )
            )
            retval = 1

        # Checking for the absence of blocking_applications for pkg installers.
        # If a pkg doesn't require blocking_applications, use empty "<array/>" in pkginfo.
        if args.require_pkg_blocking_apps and all(
            (
                "blocking_applications" not in pkginfo,
                pkginfo.get("installer_item_location", "").endswith(".pkg"),
                pkginfo.get("RestartAction") not in blocking_actions,
                not pkginfo["name"].startswith("munkitools"),
            )
        ):
            print(
                "{}: contains a pkg installer but missing a blocking applications array".format(
                    filename
                )
            )
            retval = 1

        # Ensure an icon exists for the item.
        if not any(
            (
                pkginfo.get("icon_name"),
                os.path.isfile("icons/{}.png".format(pkginfo["name"])),
                pkginfo.get("installer_type") == "apple_update_metadata",
            )
        ):
            print("{}: missing icon".format(filename))
            retval = 1

        # Ensure uninstall method is set correctly if uninstall_script exists.
        if "uninstall_script" in pkginfo:
            if pkginfo.get("uninstall_method") != "uninstall_script":
                print(
                    '{}: has uninstall script, but the uninstall method is set to "{}"'.format(
                        filename, pkginfo.get("uninstall_method")
                    )
                )
                retval = 1

        # Ensure all pkginfo scripts have a proper shebang.
        shebangs = (
            "#!/bin/bash",
            "#!/bin/sh",
            "#!/bin/zsh",
            "#!/usr/bin/osascript",
            "#!/usr/bin/perl",
            "#!/usr/bin/python",
            "#!/usr/bin/ruby",
            "#!/usr/local/munki/munki-python",
            "#!/usr/local/munki/Python.framework/Versions/Current/bin/python3",
        )
        script_types = (
            "installcheck_script",
            "uninstallcheck_script",
            "postinstall_script",
            "postuninstall_script",
            "preinstall_script",
            "preuninstall_script",
            "uninstall_script",
        )
        for script_type in script_types:
            if script_type in pkginfo:
                if all(not pkginfo[script_type].startswith(x + "\n") for x in shebangs):
                    print(
                        "{}: Has a {} that does not start with a valid shebang.".format(
                            filename, script_type
                        )
                    )
                    retval = 1

        # Ensure the items_to_copy list does not include trailing slashes.
        # Credit to @bruienne for this idea.
        # https://gist.github.com/bruienne/9baa958ec6dbe8f09d94#file-munki_fuzzinator-py-L211-L219
        if "items_to_copy" in pkginfo:
            for item_to_copy in pkginfo.get("items_to_copy"):
                if item_to_copy.get("destination_path").endswith("/"):
                    print(
                        '{}: has an items_to_copy with a trailing slash: "{}"'.format(
                            filename, item_to_copy["destination_path"]
                        )
                    )
                    retval = 1

    return retval

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


from ..util.logger import logged

class GroupManager:

        def __init__(self, arg):
            try:
                self.list = arg["groups"]
            except KeyError:
                self.list = {}

        def __check(self, group_name):
            for group in self.list:
                if group["name"] == group_name:
                    return group
            return None

        @logged(__qualname__)
        def create(self, group_name):
            group={}
            group["name"]=group_name
            group["commands"]=[]
            self.list.append(group)
            return group

        @logged(__qualname__)
        def delete(self, group_name):
            group = self.get(group_name)
            if group:
                self.list.remove(group)
                return True
            return False

        @logged(__qualname__)
        def add(self, group_name, command):
            group = self.get(group_name)
            for cmd in group["commands"]:
                if cmd == command:
                    return False
            group["commands"].append(command)
            return group

        @logged(__qualname__)
        def remove(self, group_name, command):
            group = self.get(group_name)
            try:
                group["commands"].remove(command)
                return group
            except Exception as e:
                return False

        @logged(__qualname__)
        def get(self, group_name):
            group = self.__check(group_name)
            return group

        @logged(__qualname__)
        def get_all(self):
            group_list = self.list
            return group_list


from db import db

class RefraccionVisionModel(db.Model):
    __tablename__ = "opt_refraccion_vision"

    id = db.Column(db.Integer, primary_key=True)

    examen_id = db.Column(db.Integer, db.ForeignKey('examen.id'))
    examen = db.relationship('ExamenModel', lazy=True, viewonly=True)

    vlOjoDerechoSC = db.Column(db.String(250))
    vlOjoIzquierdoSC = db.Column(db.String(250))
    vlOjoDerechoCC = db.Column(db.String(250))
    vlOjoIzquierdoCC = db.Column(db.String(250))
    vpOjoDerechoSC = db.Column(db.String(250))
    vpOjoIzquierdoSC = db.Column(db.String(250))
    vpOjoDerechoCC = db.Column(db.String(250))
    vpOjoIzquierdoCC = db.Column(db.String(250))
    rxOjoDerecho = db.Column(db.String(250))
    rxOjoIzquierdo = db.Column(db.String(250))
    qtOjoDerecho = db.Column(db.String(250))
    qtOjoIzquierdo = db.Column(db.String(250))
    atrOjoDerecho = db.Column(db.String(250))
    atrOjoIzquierdo = db.Column(db.String(250))
    estOD = db.Column(db.String(50))
    cylOD = db.Column(db.String(50))
    ejeOD = db.Column(db.String(50))
    addOD = db.Column(db.String(50))
    estOI = db.Column(db.String(50))
    cylOI = db.Column(db.String(50))
    ejeOI = db.Column(db.String(50))
    addOI = db.Column(db.String(50))

    def __init__(self, examen_id, vlOjoDerechoSC, vlOjoIzquierdoSC, vlOjoDerechoCC, vlOjoIzquierdoCC, vpOjoDerechoSC,
                 vpOjoIzquierdoSC,
                 vpOjoDerechoCC, vpOjoIzquierdoCC, rxOjoDerecho, rxOjoIzquierdo, qtOjoDerecho, qtOjoIzquierdo,
                 atrOjoDerecho,
                 atrOjoIzquierdo, estOD, cylOD, ejeOD, addOD, estOI, cylOI, ejeOI, addOI):
        self.examen_id = examen_id
        self.vlOjoDerechoSC = vlOjoDerechoSC
        self.vlOjoIzquierdoSC = vlOjoIzquierdoSC
        self.vlOjoDerechoCC = vlOjoDerechoCC
        self.vlOjoIzquierdoCC = vlOjoIzquierdoCC
        self.vpOjoDerechoSC = vpOjoDerechoSC
        self.vpOjoIzquierdoSC = vpOjoIzquierdoSC
        self.vpOjoDerechoCC = vpOjoDerechoCC
        self.vpOjoIzquierdoCC = vpOjoIzquierdoCC
        self.rxOjoDerecho = rxOjoDerecho
        self.rxOjoIzquierdo = rxOjoIzquierdo
        self.qtOjoDerecho = qtOjoDerecho
        self.qtOjoIzquierdo = qtOjoIzquierdo
        self.atrOjoDerecho = atrOjoDerecho
        self.atrOjoIzquierdo = atrOjoIzquierdo
        self.estOD = estOD
        self.cylOD = cylOD
        self.ejeOD = ejeOD
        self.addOD = addOD
        self.estOI = estOI
        self.cylOI = cylOI
        self.ejeOI = ejeOI
        self.addOI = addOI

    def __str__(self):
        return f"id: {self.id}: examen_id: {self.examen_id} vlOjoDerechoSC: {self.vlOjoDerechoSC} " \
               f"vlOjoIzquierdoSC: {self.vlOjoIzquierdoSC} vlOjoDerechoCC: {self.vlOjoDerechoCC} " \
               f"vlOjoIzquierdoCC: {self.vlOjoDerechoCC} vpOjoDerechoSC: {self.vpOjoDerechoSC} " \
               f"vpOjoIzquierdoSC: {self.vpOjoIzquierdoSC} rxOjoDerecho: {self.rxOjoDerecho} " \
               f"rxOjoIzquierdo: {self.rxOjoIzquierdo} qtOjoDerecho: {self.qtOjoDerecho} " \
               f"qtOjoIzquierdo:{self.qtOjoIzquierdo} atrOjoDerecho: {self.atrOjoDerecho} " \
               f"atrOjoIzquierdo:{self.atrOjoIzquierdo} estOD: {self.estOD} cylOD: {self.cylOD} " \
               f"ejeOD:{self.ejeOD} addOD: {self.addOD} estOI: {self.estOI} cylOI: {self.cylOI} " \
               f"ejeOI: {self.ejeOI} addOI: {self.addOI}"

    def json(self):
        return {
            "id": self.id,
            "examen": {
                "id": self.examen_id,
                "id_transaccion": self.examen.id_transaccion,
                "fecha": self.examen.fecha,
                "paciente_id": self.examen.paciente_id,
                "estado": self.examen.estado,
                "medico": {
                    "id": self.examen.medico_id,
                    "codigo": self.examen.medico_.codigo,
                    "cedula": self.examen.medico_.cedula,
                    "nombre": self.examen.medico_.nombre,
                    "apellidos": self.examen.medico_.apellidos,
                    "telefono": self.examen.medico_.sexe,
                    "specialidad": {
                        "id": self.examen.medico_.admspecialidad_id,
                        "nombre": self.examen.medico_.admspecialidad.nombre,
                        "descripcion": self.examen.medico_.admspecialidad.descripcion,
                        "estado": self.examen.medico_.admspecialidad.estado
                    },
                },
            },
            "vlOjoDerechoSC": self.vlOjoDerechoSC,
            "vlOjoIzquierdoSC": self.vlOjoIzquierdoSC,
            "vlOjoDerechoCC": self.vlOjoDerechoCC,
            "vlOjoIzquierdoCC": self.vlOjoIzquierdoCC,
            "vpOjoDerechoSC": self.vpOjoDerechoSC,
            "vpOjoIzquierdoSC": self.vpOjoIzquierdoSC,
            "qtOjoDerecho": self.qtOjoDerecho,
            "qtOjoIzquierdo": self.qtOjoIzquierdo,
            "atrOjoDerecho": self.atrOjoDerecho,
            "atrOjoIzquierdo": self.atrOjoIzquierdo,
            "estOD": self.estOD,
            "cylOD": self.cylOD,
            "ejeOD": self.ejeOD,
            "addOD": self.addOD,
            "estOI": self.estOI,
            "cylOI": self.cylOI,
            "ejeOI": self.ejeOI,
            "addOI": self.addOI,
        }

    @classmethod
    def find_by_id(cls, id):
        return cls.query.filter_by(id=id).first()

    @classmethod
    def find_by_examen_id(cls, examen_id):
        return cls.query.filter_by(examen_id=examen_id).first()

    def save_to_db(self):
        db.session.add(self)
        db.session.commit()

    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()


import json
from datetime import timedelta

from django.http import JsonResponse

from dateutil import parser

from workoutentry.training_data import TrainingDataManager
from workoutentry.views.json.response import TrainingDiaryResponse
from workoutentry.views.training_diary_resource import TrainingDiaryResource
from workoutentry.views.utilities.utilities import BaseJSONForm

class NextDiaryDate(TrainingDiaryResource):

    URL = '/data/next_diary_date/'

    def call_resource(self, request):
        response = TrainingDiaryResponse()
        last_date = TrainingDataManager().latest_date()
        d = parser.parse(last_date).date()
        next_date = d + timedelta(1)
        response.add_data('next_date', next_date)

        return JsonResponse(data=response.as_dict())

class DataForDate(TrainingDiaryResource):

    URL = '/data/for_dates/'

    def required_post_fields(self):
        return ['from_date', 'to_date', 'data_type']

    def call_resource(self, request):
        response = TrainingDiaryResponse()
        tdm = TrainingDataManager()
        instances = []
        if request.POST['data_type'] == 'Day':
            instances = tdm.days_between(request.POST['from_date'], request.POST['to_date'])
        elif request.POST['data_type'] == 'Reading':
            instances = tdm.readings_between(request.POST['from_date'], request.POST['to_date'])
        elif request.POST['data_type'] == 'Workout':
            instances = tdm.workouts_between(request.POST['from_date'], request.POST['to_date'])

        response.add_data('instances', [i.data_dictionary() for i in instances])

        return JsonResponse(data=response.as_dict())

class ReadingsLeftForDay(TrainingDiaryResource):

    URL = '/readings/left_for_date/'

    def required_post_fields(self):
        return ['date']

    def call_resource(self, request):
        readings = TrainingDataManager().reading_types_unused_for_date(request.POST['date'])

        response = TrainingDiaryResponse()
        response.add_data('readings', readings)

        return JsonResponse(data=response.as_dict())

class SaveDay(TrainingDiaryResource):

    URL = '/save/day/'

    def required_post_fields(self):
        return ['date', 'day_type', 'comments']

    def call_resource(self, request):
        target_date = request.POST['date']
        response = TrainingDiaryResponse()
        tdm = TrainingDataManager()

        if tdm.day_exists(target_date):
            tdm.update_day(target_date, request.POST['day_type'], request.POST['comments'])
            response.add_message(response.MSG_INFO, f"Day updated for {target_date}")
        else:
            tdm.save_day(target_date, request.POST['day_type'], request.POST['comments'])
            response.add_message(response.MSG_INFO, f"New day added for {target_date}")

        response.add_data('day', tdm.day_for_date(target_date).data_dictionary())

        return JsonResponse(data=response.as_dict())

class SaveNewReadings(TrainingDiaryResource):

    URL = '/readings/new/save/'

    def required_post_fields(self):
        return ['json', 'date']

    def call_resource(self, request):
        date = request.POST['date']
        readings = list()
        tdm = TrainingDataManager()
        for reading in json.loads(request.POST['json']):
            tdm.save_reading(date, reading['reading'], reading['value'])
            readings.append(reading['reading'])

        readings_saved = list()
        for r in readings:
            readings_saved.append(tdm.reading_for_date_and_type(date, r)[0].data_dictionary())

        response = TrainingDiaryResponse()
        response.add_message(response.MSG_INFO, f"{len(readings)} saved: {', '.join(readings)}")
        response.add_data('readings', readings_saved)
        return JsonResponse(data=response.as_dict())

class SaveWorkout(BaseJSONForm):

    URL = '/workout/save/'

    COMMON_FIELDS = {'activity', 'activity_type', 'equipment', 'seconds', 'rpe', 'tss', 'tss_method', 'km', 'kj', 'ascent_metres',
                  'reps', 'is_race', 'cadence', 'watts', 'watts_estimated', 'heart_rate', 'is_brick', 'keywords', 'comments'}
    UPDATE_FIELDS = {'primary_key'} | COMMON_FIELDS
    NEW_FIELDS = {'date'} | COMMON_FIELDS

    def required_post_fields(self):
        return ['json']

    def call_resource(self, request):
        response = TrainingDiaryResponse()
        dd, errors = self._process_data(request.POST['json'])
        [response.add_message(response.MSG_ERROR, e) for e in errors]

        tdm = TrainingDataManager()
        primary_key = tdm.workout_primary_key(dd['date'], dd['workout_number'])
        try:
            if 'primary_key' not in dd or dd['primary_key'] == "":
                # new workout
                lastrowid = tdm.save_workout(**self._filtered_dict(dd, self.NEW_FIELDS))
                response.add_message(response.MSG_INFO, f"New workout saved")
                response.add_data('workout', tdm.workout_for_rowid(lastrowid)[0].data_dictionary())
            elif primary_key == dd['primary_key']:
                # update workout
                tdm.update_workout(**self._filtered_dict(dd, self.UPDATE_FIELDS))
                response.add_message(response.MSG_INFO, f"Workout updated")
                response.add_data('workout', tdm.workout_for_primary_key(primary_key)[0].data_dictionary())
            else:
                # changed the date. Need a new workout to get primary_keys right
                old_key = dd['primary_key']
                tdm.delete_workout_for_primary_key(old_key)
                response.add_data('removed_primary_key', old_key)
                lastrowid = tdm.save_workout(**self._filtered_dict(dd, self.NEW_FIELDS))
                workout = tdm.workout_for_rowid(lastrowid)[0]
                response.add_message(response.MSG_INFO, f"Workout date changed so old workout deleted and new one added. Remove {old_key} and added {workout.primary_key}")
                response.add_data('workout', workout.data_dictionary())
        except TypeError as e:
            response.set_status(response.ERROR)
            response.add_message(response.MSG_ERROR, str(e))

        return JsonResponse(data=response.as_dict())

    def _filtered_dict(self, dd, filter) -> (dict, set):
        new_dd = dict()
        errors = set()
        for k in filter:
            if k in {'is_race', 'is_brick', 'watts_estimated'}:
                new_dd[k] = 1 if k in dd else 0
            elif k == 'seconds':
                parts = dd[k].split(":")
                if len(parts) != 3:
                    errors.add(f"Invalid time format. Expecting three parts hh:mm:ss but got {len(parts)}")
                try:
                    new_dd[k] = int(parts[0]) * 3600 + int(parts[1]) * 60 + int(parts[2])
                except Exception:
                    errors.add(f"Invalid time format: {dd[k]}")
            elif k not in dd:
                errors.add(f"Missing field: {k}")
            else:
                new_dd[k] = dd[k]

        return new_dd

    def _int_fields(self) -> set:
        return {}

    def _float_fields(self) -> set:
        return {}

    def _yes_no_boolean_fields(self) -> set:
        return {"can_record_for_day", "can_record_in_workout"}

    def _extra_processing(self, data) -> bool:
        return False

class DeleteWorkout(TrainingDiaryResource):

    URL = '/workout/delete/'

    def required_post_fields(self):
        return ['primary_key']

    def call_resource(self, request):
        response = TrainingDiaryResponse()
        try:
            tdm = TrainingDataManager()
            tdm.delete_workout_for_primary_key(request.POST['primary_key'])
            response.set_status(response.SUCCESS)
            response.add_data('primary_key', request.POST['primary_key'])
            response.add_message(response.MSG_INFO, f"Workout Deleted: {request.POST['primary_key']}")
        except Exception as e:
            response.set_status(response.ERROR)
            response.add_message(response.MSG_ERROR, f"Delete failed: {str(e)}")

        return JsonResponse(data=response.as_dict())

class DeleteReading(TrainingDiaryResource):

    URL = '/reading/delete/'

    def required_post_fields(self):
        return ['primary_key']

    def call_resource(self, request):
        response = TrainingDiaryResponse()
        try:
            tdm = TrainingDataManager()
            tdm.delete_reading_for_primary_key(request.POST['primary_key'])
            response.set_status(response.SUCCESS)
            response.add_data('primary_key', request.POST['primary_key'])
            response.add_message(response.MSG_INFO, f"Reading Deleted: {request.POST['primary_key']}")
        except Exception as e:
            response.set_status(response.ERROR)
            response.add_message(response.MSG_ERROR, f"Delete failed: {str(e)}")

        return JsonResponse(data=response.as_dict())