import pandas as pd

import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc

from Application.Simulation import Simulation
import os

import numpy as np
from dash.dependencies import Input, Output, State
from Application.DistributionFactory import *
import base64
import sys
import traceback

import  threading

import plotly.graph_objects as go
from plotly.subplots import make_subplots
import Application.config as config

pd.options.plotting.backend = "plotly"

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.SLATE, {
    'href': 'https://use.fontawesome.com/releases/v5.8.1/css/all.css',
    'rel': 'stylesheet',
    'integrity': 'sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf',
    'crossorigin': 'anonymous'
}])
sys.setrecursionlimit(10 ** 6)
dfs = dict()
graphs = []

schemaPath = os.path.join(os.path.dirname(__file__), "./Application/files/profile_schema.json")
serviceSchemaPath = os.path.join(os.path.dirname(__file__), "./Application/files/service_schema.json")

schema = DistributionFactory.getContentFromFile(schemaPath)
serviceSchema = DistributionFactory.getContentFromFile(serviceSchemaPath)

profile = None
services = None
mapping = {}

seed = None

lastDropDown = dict()

expectedFig = None
distRequest = None  # [(np.random.triangular(0, 10E9, 60E9, 1), 1)]

@app.callback(
    Output("errors", "children"),
    Input('input_go', 'n_clicks'))
def startSimulation(value):
    global profile
    global services
    global mapping
    global seed
    global distRequest

    np.random.seed(1)

    if value > 0:
        if profile is not None and services is not None and mapping is not None:
            try:
                sim = Simulation(schema, serviceSchema)

                mapping2 = DistributionFactory.genMapping(profile, mapping)
                sim.main(profile, mapping2, services, distRequest)
                tmp = readFromQueue(sim)
                saveSimResult(tmp)

                createLayout()

                return html.Div(["Simulation complete"])
            except Exception as e:
                traceback.print_exc()
                print(e)
                return html.Div(str(e)),
        else:
            return html.Div("One or more inputs missing!")
    return html.Div([""])

def saveSimResult(observationDict, savePath="SimResults.json"):
    savePath = os.path.join(os.path.dirname(__file__), savePath)
    print(savePath)
    with open(savePath, 'w') as fp:
        json.dump(observationDict, fp)

def readFromQueue(sim):
    global dfs
    dfs = dict()

    # TODO: auto update the dfs dict properly

    tmp = sim.observationQueueToDict()

    for value, df in tmp.items():#
        x = pd.DataFrame.from_dict(df)
        x["t"] = pd.to_datetime(x["t"], unit='ns')
        x.set_index("t", inplace=True)

        if value in dfs:
            dfs[value].append(x)
        else:
            dfs[value] = x

    return tmp

def createLayout():
    uploadStyle = {
        'width': '100%',
        'height': '60px',
        'lineHeight': '60px',
        'borderWidth': '1px',
        'borderStyle': 'dashed',
        'borderRadius': '5px',
        'textAlign': 'center',
        'margin': '10px'
    }
    global app
    app.layout = html.Div(
        [
            html.Div([
                dcc.Interval(
                    id='interval-component',
                    interval=int(config.refreshTime) * 1000,  # in milliseconds
                    n_intervals=0
                ),
                dcc.Interval(
                    id='interval2',
                    interval=int(config.refreshTime/2) * 1000,  # in milliseconds
                    n_intervals=0
                ),
                html.Div([
                    html.Div([
                        dcc.Upload(
                            id='input_profile',
                            children=html.Div([
                                'Select Application Profile'
                            ]),
                            style=uploadStyle,
                            multiple=False
                        )
                    ], className="col-2"),
                    html.Div([
                        dcc.Upload(
                            id='input_services',
                            children=html.Div([
                                'Select Service Definition'
                            ]),
                            style=uploadStyle,
                            multiple=False
                        )
                    ], className="col-2"),
                    html.Div([
                        dcc.Upload(
                            id='input_mapping',
                            children=html.Div([
                                'Select Service Mapping'
                            ]),
                            style=uploadStyle,
                            multiple=False
                        )
                    ], className="col-2"),
                    html.Div([
                        dcc.Upload(
                            id='input_dist',
                            children=html.Div([
                                'Select Distribution Request'
                            ]),
                            style=uploadStyle,
                            multiple=False
                        )
                    ], className="col-2"),
                    html.Div([
                        dcc.Input(id="input_seed", placeholder='seed', style=uploadStyle)
                    ], className="col-1"),
                    html.Div([
                        html.Button(children=html.I(className="far fa-play-circle fa-3x",
                                                    style={"display": "inline-block",
                                                           "margin": "-8px auto auto -8px", "padding": "0"}),
                                    id='input_go',
                                    className="btn btn-outline-success",
                                    style={'lineHeight': '60px', 'margin': '10px',
                                           'width': '60px', 'height': '60px', "display": "inline-block",
                                           },
                                    n_clicks=0
                                    )
                    ], className="col-1"),
                    html.Div([

                    ], className="col-2", id="errors")
                ], className="row g-2 pt-3")
            ]),
            html.Div(getPlots() , className="container-fluid px-2 overflow-hidden", id="plots"),

        ]
    , style={"overflow": "hidden"})

def getPlots():
    plots = [
        html.Div([
            html.Div([
                html.Div([
                    html.Div([
                        getDropdown("dones")
                    ],
                        id="dones-dropdown"
                    ),
                    html.Div([
                        ],
                        id="dones-plot"
                    )
                ], id="done", className="col-6"),
                html.Div([
                    html.Div([
                        getDropdown("service_util")
                    ],
                        id="service_util-dropdown"
                    ),
                    html.Div([
                        ],
                        id="service_util-plot"
                    )
                ], id="service_util", className="col-6")
            ], className="row g-2 pt-3"),
            html.Div([
                html.Div([
                    html.Div([
                        getDropdown("response_time")
                    ],
                        id="response_time-dropdown"
                    ),
                    html.Div([
                        ],
                        id="response_time-plot"
                    )
                ], id="response_time", className="col-6"),

                html.Div([
                    html.Div([
                        getDropdown("sim_events")
                    ],
                        id="sim_events-dropdown"
                    ),
                    html.Div([
                    ],
                        id="sim_events-plot"
                    )
                ], id="sim_events", className="col-6")

            ], className="row g-2 pt-3")
        ])
    ]

    return plots

@app.callback(Output('input_profile', 'children'),
              Input('input_profile', 'contents'))
def setProfileInput(content):
    global profile
    try:
        if content is None and profile is not None:
            return html.Div(['Application Profile ✔'])

        if content is not None:
            content_type, content_string = content.split(',')
            p = json.loads(base64.b64decode(content_string))
            suc, e = DistributionFactory.validateContentvsSchema(p, schema)
            if not suc:
                return html.Div([str(e)])

            profile = p
            return html.Div(['Application Profile ✔'])
        else:
            return html.Div(['Select Application Profile'])
    except Exception as e:
        print(e)
        return html.Div(['Application Profile ❌'])

@app.callback(Output('input_services', 'children'),
              Input('input_services', 'contents'))
def setServicesInput(content):
    try:
        global services
        if content is None and services is not None:
            return html.Div(['Service Definition ✔'])

        if content is not None:
            content_type, content_string = content.split(',')
            p = json.loads(base64.b64decode(content_string))
            suc, e = DistributionFactory.validateContentvsSchema(p, serviceSchema)
            if not suc:
                return html.Div([str(e)])

            services = copy.deepcopy(p)
            return html.Div(['Service Definition ✔'])
        else:
            return html.Div(['Select Service Definition'])
    except Exception as e:
        print(e)
        return html.Div(['Service Definition ❌'])

@app.callback(Output('input_mapping', 'children'),
              Input('input_mapping', 'contents'))
def setMappingInput(content):
    try:
        global mapping
        global profile
        if content is None and mapping is not None:
            return html.Div(['Service Mapping ✔'])

        if content is not None:
            content_type, content_string = content.split(',')
            p = json.loads(base64.b64decode(content_string))

            if profile is None:
                return html.Div(['Select Application Profile first'])

            mapping = copy.deepcopy(p)
            return html.Div(['Service Mapping ✔'])
        else:
            return html.Div(['Select Service Mapping'])

    except Exception as e:
        print(e)
        return html.Div(['Service Mapping ❌'])

@app.callback(Output('input_dist', 'children'),
              Input('input_dist', 'contents'))
def setDistInput(content):
    try:
        global distRequest

        if content is None and distRequest is not None:
            return html.Div(['Distributions ✔'])

        if content is not None:
            distRequest = []
            content_type, content_string = content.split(',')
            p = json.loads(base64.b64decode(content_string))

            # TODO: validate that requested scenarioids are present in profile
            for req in p:
                if req["kind"] == "triangle":
                    dist = (np.random.triangular(req["start"]*1E9, req["highpoint"]*1E9, req["end"]*1E9, req["volume"]), req["scenarioID"])
                    distRequest.append(dist)

            return html.Div(['Distributions ✔'])
        else:
            return html.Div(['Select Distribution Request'])

    except Exception as e:
        print(e)
        return html.Div(['Distributions ❌'])

@app.callback(Output('input_seed', 'value'),
              Input('input_seed', 'value'))
def setSeed(value):
    if value is not None:
        global seed
        seed = int(value)
        return value

def getDropdown(keyword):
    if keyword not in dfs:
        return dcc.Dropdown(
            id=keyword + '-dropdown-dd',
            options=[],
            value=[]
        )

    options = []
    for i in sorted(dfs[keyword].identifier.unique()):
        options.append({"label": i, "value": i})

    return dcc.Dropdown(
        id=keyword + '-dropdown-dd',
        options=options,
        value=dfs[keyword].identifier.unique()[0]
    )

@app.callback(
    Output(component_id='dones-dropdown', component_property='children'),
    Output(component_id='response_time-dropdown', component_property='children'),
    Output(component_id='service_util-dropdown', component_property='children'),
    Output(component_id='sim_events-dropdown', component_property='children'),
    Input('interval2', 'n_intervals'))
def getDropdown2(n_intervals):
    returns = []
    global lastDropDown
    titles = ["sim_events","dones", "response_time", "service_util"]

    if not dfs:
        for i in titles:
            returns.append(dcc.Dropdown(
                id=str(i) + '-dropdown-dd',
                options=[],
                value=[])
            )
        return returns

    else:
        for keyword in sorted(list(dfs.keys())):
            options = []
            for i in sorted(dfs[keyword].identifier.unique()):
                options.append({"label": i, "value": i})

            value = lastDropDown[keyword] if lastDropDown[keyword] != [] else dfs[keyword].identifier.unique()[0]

            returns.append( dcc.Dropdown(
                id=keyword + '-dropdown-dd',
                options=options,
                value=value)
                )

        return returns

@app.callback(
    Output(component_id='dones-plot', component_property='children'),
    Input(component_id='dones-dropdown-dd', component_property='value'),
    Input('interval-component', 'n_intervals')
)
def update_output_div(input_value, n_intervals):
    global lastDropDown
    if input_value is not None:
        lastDropDown["dones"] = input_value
    else:
        input_value = lastDropDown["dones"]

    return getPlot("dones", input_value)

@app.callback(
    Output(component_id='response_time-plot', component_property='children'),
    Input(component_id='response_time-dropdown-dd', component_property='value'),
    Input('interval-component', 'n_intervals')
)
def update_output_div(input_value, n_intervals):
    global lastDropDown
    if input_value is not None:
        lastDropDown["response_time"] = input_value
    else:
        input_value = lastDropDown["response_time"]
    return getPlot("response_time", input_value)

@app.callback(
    Output(component_id='service_util-plot', component_property='children'),
    Input(component_id='service_util-dropdown-dd', component_property='value'),
    Input('interval-component', 'n_intervals')
)
def update_output_div(input_value, n_intervals):
    global lastDropDown
    if input_value is not None:
        lastDropDown["service_util"] = input_value
    else:
        input_value = lastDropDown["service_util"]
    return getPlot("service_util", input_value)

@app.callback(
    Output(component_id='sim_events-plot', component_property='children'),
    Input(component_id='sim_events-dropdown-dd', component_property='value'),
    Input('interval-component', 'n_intervals')
)
def update_output_div(input_value, n_intervals):
    global lastDropDown
    if input_value is not None:
        lastDropDown["sim_events"] = input_value
    else:
        input_value = lastDropDown["sim_events"]
    return getPlot("sim_events", input_value)

def loadSimResult(savePath="SimResults.json"):
    global dfs

    savePath = os.path.join(os.path.dirname(__file__), savePath)
    if not os.path.isfile(savePath):
        print(savePath)
        return dfs

    with open(savePath, "r") as fp:
        dfDicts = json.load(fp)

    for value, df in dfDicts.items():
        dfs[value] = pd.DataFrame.from_dict(df)
        dfs[value]["t"] = pd.to_datetime(dfs[value]["t"], unit='ns')
        dfs[value].set_index("t", inplace=True)

    return dfs

def getHistPlot(fig, title, changes):
    global distRequest
    fig2 = make_subplots()

    hist = pd.DataFrame()

    if distRequest is not None:
        dists = sorted([pd.to_datetime(y/1E9, unit="s") for x,_ in distRequest for y in x])
        integratedCurve =  [i for i in range(len(dists))]

        expectedFig =go.Scatter(
            x=dists,
            y=integratedCurve,
            mode="lines",
            line=go.scatter.Line(color="black"),
            name="expected"
            )
        fig2.add_trace(expectedFig)
        hist["t"] = dists
        hist["t2"] = integratedCurve
        hist.set_index("t", inplace=True)
        hist = hist.resample(rule=config.bucketSize).last().interpolate()
        fig2.add_trace(go.Bar(x=hist.index, y=hist["t2"].diff(), name="input"))

    fig2.add_trace(fig)

    #hist = go.Histogram(x=dists, name="input")

    changes = changes.resample(rule=config.bucketSize).last().interpolate()

    fig2.add_trace(go.Bar(x=changes.index, y=changes["completed"].diff(), name="output"))

    fig2.update_layout({"title": title})

    return fig2

def getPlot(keyword, identifier=None):
    global dfs
    if keyword not in dfs:
        return html.P(keyword + ' graph')

    titles = {
        "sim_events": "events in queue",
        "dones": "completed interactions",
        "response_time": "response time",
        "service_util": "service utilization",
    }

    df = dfs[keyword]

    if identifier is None:
        identifier = df.identifier.unique()[0]

    if keyword == "sim_events":
        fig = df.loc[df["identifier"] == identifier].resample(rule=config.average).sum().interpolate().plot(kind='bar', title=f"{titles[keyword]}: {identifier}")

        return dcc.Graph(id=f"{keyword} {identifier}",
                         figure=fig,
                         style={"height": "24rem"}, animate=True)
    else:

        if keyword == "dones":
            data = df.loc[df["identifier"] == identifier].resample(rule = config.average).last().interpolate("pad")
            fig = go.Scatter(
                x=data.index,
                y=data["completed"],
                mode="lines",
                line=go.scatter.Line(color="blue"),
                name="completed"
            )

            fig = getHistPlot(fig, f"{titles[keyword]}: {identifier}", data)

        else:
            data = df.loc[df["identifier"] == identifier].resample(rule=config.average).mean().interpolate("pad")
            fig = data.plot(kind='line', title=f"{titles[keyword]}: {identifier}")

        return dcc.Graph(id=f"{keyword} {identifier}",
                         figure=fig,
                         style={"height": "24rem"}, animate=True)

if __name__ == '__main__':
    dfs = loadSimResult()

    createLayout()
    app.run_server(debug=True)


from sys import argv
from .crypto import sign, verify
# Argumentos padrão:
operation   = None
xml_file    = None
cert_file   = None
key_file    = None
cacert_file = None
out_file    = "out.xml"

argv.pop(0) # Descarta primeiro argumento

while argv:
    arg = argv.pop(0)
    if arg == "-in":
        xml_file = argv.pop(0)
    elif arg == "-out":
        out_file = argv.pop(0)
    elif arg == "-cert":
        cert_file = argv.pop(0)
    elif arg == "-key":
        key_file = argv.pop(0)
    elif arg == "-cacert":
        cacert_file = argv.pop(0)
    else:
        operation = arg

if operation == "sign":
    sign(xml_file, cert_file, key_file, out_file)
elif operation == "verify":
    verify(xml_file, cacert_file)
else:
    print("Operação inválida.")


#!/usr/bin/env python

# Author: Tom Parker <palfrey@tevp.net>
# Description: Docs rebuild script
# Requires: Docutils (http://docutils.sourceforge.net/)
# Hacked together from rst2html.py by David Goodger <goodger@users.sourceforge.net>

import locale
try:
    locale.setlocale(locale.LC_ALL, '')
except:
    pass

try:
	from docutils.core import publish_file
except:
	print("You need docutils (http://docutils.sourceforge.net/)\n")
	raise
from .html import Writer

def rebuild(rst,php):
	read_txt = open(rst,'r')
	read_html = open(php,'w')
	html = Writer()
	publish_file(writer=html, source=read_txt, destination=read_html)

	read_html = open(php,'r')
	data = read_html.readlines()
	read_html.close()
	data.insert(0,"<script language=\"php\">$title=\"Comics Grabber\";$TOPDIR=\"../../\";include $TOPDIR.\"top.php3\";</script>")
	data.append("<script language=\"php\">include $TOPDIR.\"bottom.php3\";</script>")
	read_html = open(php,'w')
	read_html.writelines(data)
	read_html.close()

rebuild('readme.txt','index.php')
rebuild('strips.def.txt','strips.php')


# -*- coding: utf-8 -*-
"""JJCM Practica 3 LC.ipynb

1) Implementar,	usando NLTK	 y	 Python,	 el	 algoritmo	 de	 Lesk	 simplificado	 para
desambiguar	el	 sentido	 de	las	 palabras	 (WSD).	 La	 función	 recibirá	 una	 palabra	 y
una	 frase	que	la	contenga	y	decidirá	el	mejor	sentido	para	esa	palabra.	Las	 frases
serán	en	inglés	 y	 se	 deberá	eliminar	de	la	 frase, de	la	glosa	 y de	los ejemplos	 de
cada	sentido	las	‘stopwords’
"""

# Imports
#!pip install nltk
import nltk
from nltk.corpus import wordnet as wn
from nltk.corpus import stopwords as sw
nltk.download('omw')
nltk.download('punkt')
nltk.download('stopwords')
nltk.download('wordnet')

# Obtain English Stop Words
sw_english=sw.words('english')

def compute_overlap(contexto, sign):
  return len(contexto.intersection(sign))

def lematizacion(frase):
    sentence_lematized = []
    for w in frase:
      sentence_lematized.append(wn.morphy(w))
    return sentence_lematized

def simplified_lesk(word, sentence):

  overlap = 0
  max_overlap = 0

  # Senses
  senses=wn.synsets(word)
  best_sense = senses

  # Tokenizado
  sentence_tokenized = nltk.word_tokenize(sentence)

  # lematizacion
  sentence_tokenized_lematized = lematizacion(sentence_tokenized)
  context = set(sentence_tokenized_lematized)

  # Quitamos Stop Words
  context = context.difference(sw_english)

  for sense in senses[1:]:
    signature = set(lematizacion(nltk.word_tokenize(sense.definition().join(sense.examples()))))
    signature = signature.difference(sw_english)
    overlap = compute_overlap(context, signature)
    if overlap > max_overlap:
      max_overlap = overlap
      best_sense = sense

  return best_sense

#simplified_lesk('bank', 'Hi, mi name is Jose Javier and i want go to bank')
simplified_lesk('bank', 'Yesterday	I	went to	the	bank to withdraw the	money and the	credit	card did	not	work')

"""2)	Implementar un	algoritmo	similar	para	la	desambiguación	semántica	utilizando
Word Embeddings	y	una	distancia	de	similitud	semántica como	la	distancia	coseno
"""

#Imports
# Word embeddings
import gensim
from nltk.data import find
import nltk
import numpy as np

nltk.download('word2vec_sample')
word2vec_sample = str(find('models/word2vec_sample/pruned.word2vec.txt'))
model = gensim.models.KeyedVectors.load_word2vec_format(word2vec_sample, binary=False)

def lematizacion(frase):
    sentence_lematized = []
    for w in frase:
      sentence_lematized.append(wn.morphy(w))
    return sentence_lematized

def computeDistance(contexto, sentido):
  res = 0.0
  for token_c in contexto:
    for token_s in sentido:
      #print(token_c)
      #print(token_s)
      res += model.similarity(token_c,token_s)
  return res

def desambiguar(word, sentence):

  # Senses
  senses=wn.synsets(word)
  best_sense = []
  max_similitud = 0.0

  # Tokenizado
  sentence_tokenized_con_sw = set(nltk.word_tokenize(sentence))
  sentence_tokenized_sin_sw = sentence_tokenized_con_sw.difference(sw_english)

  # lematizacion
  sentence_tokenized_lematized = lematizacion(sentence_tokenized_sin_sw)
  context = set(sentence_tokenized_lematized)

  if len(context.intersection({None})) > 0:
    context.remove(None)

  for sense in senses[1:]:

    signature_con_sw = set(nltk.word_tokenize(sense.definition().join(sense.examples())))
    signature_sin_sw = signature_con_sw.difference(sw_english)
    signature = set(lematizacion(signature_sin_sw))

    if len(signature.intersection({None})) > 0:
      signature.remove(None)

    similitud = computeDistance(context, signature)
    if similitud > max_similitud:
      max_similitud = similitud
      best_sense = sense

  return best_sense

desambiguar('bank', 'Yesterday	I	went to	the	bank to withdraw the	money and the	credit	card did	not	work')


import random
import os

from player import Player
from lines import AscLine, DescLine

class Game:

    def __init__(self, player_n=2):
        self.player_names = ['A', 'B', 'C', 'D', 'E']
        self.cards_used = 0
        self.cards = [x for x in range(2, 100)] * 2
        self.players_count = player_n
        self.set_holds()
        self.set_lines()
        self.turn = 0
        self.player_index = 0
        self.playing = False
        self.min_cards = 2

    def shuffle_cards(self):
        random.shuffle(self.cards)

    def set_holds(self):
        players_count = self.players_count
        if players_count == 1:
            holds = 8
        elif players_count == 2:
            holds = 7
        elif players_count > 2 and players_count <= 5:
            holds = 6
        else:
            print('**Check Players (max 5)**')
            holds = 0
        self.holds = holds

    def set_players(self):
        self.players = []
        for _ in range(self.players_count):
            self.players.append(Player(self.player_names.pop(0)))
        self.now_player = self.players[0]

    def handout(self):
        # Cards distribution
        for player in self.players:
            for _ in range(self.holds):
                player.hands.append(self.cards.pop())

    def show_players_hands(self):
        for player in self.players:
            print(f'{player.name} - {player.hands}')

    def set_lines(self):
        # Table setting
        self.asc1 = AscLine()
        self.asc2 = AscLine()
        self.desc1 = DescLine()
        self.desc2 = DescLine()
        self.lines = [self.asc1, self.asc2, self.desc1, self.desc2]

    def show_lines_top(self):
        print(f'1) asc1 >> {self.asc1.top}')
        print(f'2) asc2 >> {self.asc2.top}')
        print(f'3) desc1 >> {self.desc1.top}')
        print(f'4) desc2 >> {self.desc2.top}')

    def next_turn(self):
        self.turn += 1
        self.player_index = self.turn % self.players_count
        print(f'next turn >> {self.players[self.player_index]}')

    def game_start(self):
        self.playing = True

    def game_end(self):
        self.playing = False

    def check_deck_empty(self):
        if not self.cards:
            self.min_cards = 1
            return True
        return False

    def player_do(self, game, player_index):
        player = self.players[player_index]
        cards_used = 0
        os.system('clear')
        while self.playing:
            if not self.check_end(player_index):
                print(f'{player.name}\'s turn:')
                input('Enter to start your turn')
                self.show_lines_top()
                player.show_hands()
                # n = int(input(f'\rwhich card do you want to put on?'))
                n, line_index = (None, None)
                while not Game.get_card_index(n, len(player.hands)):
                    try:
                        n = int(
                            input(f"which 'card' do you want to put on? (1 ~ {len(player.hands)})"))
                    except:
                        print('Only Number available')
                while not Game.get_line_index(line_index):
                    try:
                        line_index = int(
                            input("which 'line' do you want to put on? (1 ~ 4)"))
                    except:
                        print('Only Number available')
                line = self.lines[line_index - 1]
                try:
                    player.put_card(line, n - 1)
                except:
                    print('You did wrong way')
                    continue
                cards_used += 1
                # when cards_used > min_cards and player want to stop
                if cards_used >= self.min_cards:
                    want_stop = input(
                        'Do you want to finish your turn? (1:YES, 2:NO)')
                    if want_stop == '1':
                        break

            else:
                print('finish')
                self.playing = False
        player.draw(game, cards_used)
        os.system('clear')
        self.show_lines_top()
        player.show_hands()
        input('Enter to finish your turn')

    def check_end(self, player_index):
        for card in self.players[player_index].hands:
            if (
                self.asc1.top < card or
                self.asc2.top < card or
                self.desc1.top > card or
                self.desc2. top > card
            ):
                return False
        return True

    @staticmethod
    def get_card_index(i, limit):
        if not i:
            return False
        elif i < 0 or i > limit:
            print('You took wrong number')
            return False
        return True

    @staticmethod
    def get_line_index(i):
        if not i:
            return False
        elif i < 0 or i > 4:
            print('You took wrong number')
            return False
        return True

    # def play(self):
    #     # End condition
    #     while not self.is_end():
    #         for id in range(len(self.players)):
    #             self.turn_do(id)
    #     print('Game Finished')

    # def is_end(self):
    #     if self.cards or self.cards_onHands:
    #         for onHand in self.cards_onHands:
    #             try:
    #                 for card in onHand:
    #                     if card < self.desc1 or card < self.desc2 or card > self.asc1 or card > self.asc2:
    #                         return False
    #             except:
    #                 continue

    #     return True

    # def turn_do(self, id):
    #     self.turn_message(id)
    #     while not self.end_player(id):
    #         print(self.cards_onHands[id])
    #         if self.cards_used < 2:
    #             self.selected = int(
    #                 input('Select a card(put the card number): '))
    #         else:
    #             msg = "Select a card(put the card number) or End turn with '0': "
    #             self.selected = int(input(msg))
    #         print('*'*50)
    #         if self.selected in self.cards_onHands[id]:
    #             self.card_index = self.cards_onHands[id].index(self.selected)
    #             self.now_card = self.cards_onHands[id].pop(self.card_index)
    #             while True:
    #                 self.card_at = self.card_dest()
    #                 if self.put_card_on(self.card_at):
    #                     break

    #         # End turn phase
    #         elif self.selected == 0 and self.cards_used >= 2:
    #             print('Turn finished')
    #             self.cards_used = 0
    #             self.draw_cards(id)
    #             break
    #         else:
    #             print('**Put the number correctly**')

    # def end_player(self, id):
    #     if len(self.cards_onHands[id]) > self.holds - 2:
    #         for card in self.cards_onHands[id]:
    #             if card > self.desc1 or card > self.desc2 or card < self.asc1 or card < self.asc2:
    #                 print(f'Player {self.players[id]} out')
    #                 return True
    #     return False

    # def turn_message(self, id):
    #     print('*'*50)
    #     print(f'Turn of Player {self.players[id]}')
    #     print('*'*50)
    #     print(self.cards_onHands[id])
    #     print()
    #     self.status_message()

    # def status_message(self):
    #     self.cards_left = len(self.cards)
    #     print(f'{self.cards_left} cards left ')
    #     self.table_status = f'(1)asc1:  {self.asc1:2} (2)asc2:  {self.asc2:2} \n(3)desc1: {self.desc1:2} (4)desc2: {self.desc2:2}'
    #     print(self.table_status)

    # def card_dest(self):
    #     while True:
    #         print(f'Where do you want to put {self.now_card} on?')
    #         print('*'*50)
    #         print(self.table_status)
    #         self.dest = int(input('Type the number: '))
    #         print('*'*50)
    #         if self.dest > 4 or self.dest < 1:
    #             print('**Type right line number(1 ~ 4)**')
    #             continue
    #         return self.dest

    # def put_card_on(self, dest):
    #     if dest == 1:
    #         if self.asc1 < self.now_card or self.asc1 - 10 == self.now_card:
    #             self.asc1 = self.now_card
    #         else:
    #             print('***Wrong way.. think again***')
    #             return False
    #     elif dest == 2:
    #         if self.asc2 < self.now_card or self.asc2 - 10 == self.now_card:
    #             self.asc2 = self.now_card
    #         else:
    #             print('Wrong way.. think again')
    #             return False
    #     elif dest == 3:
    #         if self.desc1 > self.now_card or self.desc1 + 10 == self.now_card:
    #             self.desc1 = self.now_card
    #         else:
    #             print('Wrong way.. think again')
    #             return False
    #     elif dest == 4:
    #         if self.desc2 > self.now_card or self.desc2 + 10 == self.now_card:
    #             self.desc2 = self.now_card
    #         else:
    #             print('Wrong way.. think again')
    #             return False

    #     self.now_card = 0
    #     self.cards_used += 1
    #     self.status_message()
    #     return True

    # def draw_cards(self, id):
    #     while len(self.cards_onHands[id]) < self.holds:
    #         self.cards_onHands[id].append(self.cards.pop())
    #     self.cards_onHands[id].sort()


import math, random, sys, pygame, os, time, argparse
from pygame.locals import *
from agent import Agent
from part import Part
from objects import Object
from network_collection import NetworkCollection
from tab import Tab
from options import Options
from log import Log
from random import *

# Main Class. This runs the application and updates the UI
class Main():

	def __init__(self):
		# Initialise variables and randomly generate ane nvironment
		self.initialize_variables()
		self.generate_world()
		# Update display
		self.update_display = True

		# main loop
		while True:
			# Check for inputs
			self.check_inputs()
			# If not paused
			if not self.paused:
				# If a run is ongoing
				if self.running:
					# Different modes
					if self.training:
						self.training_mode()
					else:
						self.free_mode()
				# Update environment objects positions
				self.move_environment()
				# Update the display if the user chooses too
				# Program runs faster when it is off
				if self.update_display:
					self.draw_sprites()

	def initialize_variables(self):
		# define display surface
		self.dimensions = (1080, 600)
		# Initial parameters
		self.subsumption = True
		self.episode_num = 0
		self.extra = False
		self.agent_num = 0
		self.placing_object = False
		self.rotate_unplaced = 0
		self.continuous = True
		self.draw_goal = False
		self.wolf = True
		self.randomness = 5
		self.reference = 20
		self.draw_scaleable = False
		self.display = [False, False, False]
		self.training = False
		self.running = False
		self.custom_build = False
		self.paused = False
		self.agents_to_be_added = []

		# Backgrounds colour
		self.background = (0, 153, 255, 221)

		# Keeps track of the winrate across training stages
		self.win_counter = 0
		self.network_collection = NetworkCollection()
		# Place window in the center of the screen
		os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (150,80)
		# initialise display
		pygame.init()
		self.clock = pygame.time.Clock()
		self.canvas = pygame.display.set_mode(self.dimensions)
		pygame.display.set_caption("Intelligent Agent Structures")
		# Create a font used to write on the screen
		pygame.font.init()
		self.font = pygame.font.SysFont('arial', 12)
		self.font.set_bold(True)

		# Get the image resources for the world
		self.pointers = [None, None]
		self.pointers[0] = pygame.image.load("image_resources/pointer_alt.png").convert_alpha()
		self.pointers[1] = pygame.image.load("image_resources/pointer.png").convert_alpha()

		# array containing the environments current blocks and agents
		self.blocks, self.agents = [],[]
		# Adds agents into the world
		self.floor = Object(0, (0, 400))
		self.floor.load_image("image_resources/flat_floor.png")

		# File paths for the block images
		self.block_images = ["300x200","200x600","400x400","200x200","goal","goal_flipped"]

		# UI Tabs for environment modification, output log and controls
		self.tabs = []
		self.tabs.append(Options(0, self))
		self.tabs.append(Log(1, self.font, self))
		self.tabs.append(Tab(2))

		# Static agents used in the final training stage
		self.scaleable_agents = []
		preset_rotations = [44,0,270,90,90,90,0,0,0,90,90,90,0,0,0]
		self.scaleable_agents.append(Agent((582,339), self.network_collection, 0, None, 25, False, self.randomness, self.subsumption))
		self.scaleable_agents.append(Agent((667,339), self.network_collection, 0, None, 25, False, self.randomness, self.subsumption))
		self.scaleable_agents.append(Agent((667,304), self.network_collection, 0, None, 25, False, self.randomness, self.subsumption))
		for i in range(3):
			self.scaleable_agents[i].parts.set_rotations(preset_rotations)
		# Rounds won/lost
		self.won = 0
		self.lost = 0

	# Check computer inputs
	def check_inputs(self):
		# Event Listener
		for event in pygame.event.get():
			# On quit event quit game
			if event.type == QUIT:
				pygame.quit()
				sys.exit()
			elif event.type == KEYDOWN:
				# Start run
				if event.key == K_RETURN:
					self.running = True
				# End run / Reset environment
				elif event.key == K_ESCAPE:
					self.reset_environment()
				# Rotate block clockwise and anti clockwise
				elif event.key == K_q:
					self.rotate_unplaced += 1
				elif event.key == K_e:
					self.rotate_unplaced += -1
				# Update display
				elif event.key == K_u:
					self.update_display = not self.update_display
				# Play / Pause
				elif event.key == K_p:
					self.paused = not self.paused
			elif event.type == KEYUP:
				# Stop rotating block
				if event.key == K_e:
					self.rotate_unplaced += 1
				elif event.key == K_q:
					self.rotate_unplaced += -1
			# On mouse click check which button was pressed
			elif event.type == pygame.MOUSEBUTTONDOWN and not self.paused:
				self.pos = pygame.mouse.get_pos()
				# If an object is being held by the user place it
				if self.placing_object:
					self.place_object()
				# Check buttons
				for i in range(3):
					self.tabs[i].click(self.pos)

	# Draw sprites
	def draw_sprites(self):
		# Draw background
		self.canvas.fill(self.background)
		# Draw the goal if there is one
		if self.draw_goal:
			self.canvas.blit(self.goal.get_image(), self.goal.get_position())
		# Draw sensors if user chooses
		if self.display[1]:
			for i in range(len(self.agents)):
				self.agents[i].sensors.run(self.canvas)
		# Draw any blocks within the environment including any the user is holding
		if self.placing_object:
			self.canvas.blit(self.unplaced.get_image(), self.unplaced.get_position())
		for i in range(len(self.blocks)):
			self.canvas.blit(self.blocks[i].get_image(), self.blocks[i].get_position())
		# Draw the agents used in the final training stage
		if self.draw_scaleable:
			for i in range(len(self.scaleable_agents)):
				self.scaleable_agents[i].parts.run(self.canvas)
		# Draw the agents
		for i in range(len(self.agents)):
			self.agents[i].parts.run(self.canvas)
		# Draw the floor
		self.canvas.blit(self.floor.get_image(), self.floor.get_position())
		# Draw the agents collision points with the environment if the request it
		if self.display[0]:
			for i in range(len(self.agents)):
				markers = self.agents[i].get_box()
				for j in range(len(markers)):
					self.canvas.blit(self.pointers[1], (int(markers[j][0]), int(markers[j][1])))
		# Draw the agents center of gravity if the request it
		if self.display[2]:
			for i in range(len(self.agents)):
				cog = self.agents[i].cog
				self.canvas.blit(self.pointers[0], (int(cog[0]), int(cog[1])))
		# Draw tabs
		for i in range(3):
			self.tabs[i].run(self.canvas)
		pygame.display.update()
		# Max FPS
		self.clock.tick(120)

	# Place an object the user is holding
	def place_object(self):
		# It must overlap with the environment (No freefloating structures)
		if (self.check_environmental_overlap()):
			# Place new goal
			if self.unplaced_goal:
					self.goal = self.unplaced
					self.draw_goal = True
			# Place block
			else:
				self.blocks.append(self.unplaced)
		self.placing_object = False

	# Check if a block is overlapping with the environment (No free floating structures)
	def check_environmental_overlap(self, goal=False):
		# Compare either the goal or the block the user is currently holding
		checking = self.unplaced
		if goal:
			checking = self.goal
		# Compare against every block including the floor
		for k in range(len(self.blocks) + 1):
			comparison = None
			if k == len(self.blocks):
				comparison = [self.floor.get_position(), self.floor.get_mask()]
			else:
				comparison = [self.blocks[k].get_position(), self.blocks[k].get_mask()]

			# Find the position difference between the agent part and the external object
			offset = (int(comparison[0][0] - checking.get_position()[0]), int(comparison[0][1] - checking.get_position()[1]))
			result = checking.get_mask().overlap(comparison[1], offset)
			# If there was a collision return the collision position
			if result:
				return result[1]
		# Else return false
		return False

	# Randomly generate a new environment
	def generate_world(self):
		# Reset environment
		self.blocks = []
		self.agents = []
		self.agent_num = 0
		# Randomly place 3 blocks.
		while len(self.blocks) < 3:
			self.unplaced = Object(0, (randint(500,800), randint(0,200)))
			self.unplaced.load_image("image_resources/"+self.block_images[randint(0,3)]+".png")
			self.unplaced.rotate(randint(0,180))
			# Only keep the block if it touches the environment
			if self.check_environmental_overlap():
				self.blocks.append(self.unplaced)
		# Place goal
		self.set_goal()

	# Move an item in the environment. Either what the user it holding or a tab
	def move_environment(self):
		# User holding item
		if self.placing_object:
			self.pos = pygame.mouse.get_pos()
			if self.unplaced_goal:
				self.unplaced.set_position((self.pos[0] - 25, self.pos[1] - 25))
			else:
				self.unplaced.set_position((self.pos[0] - 200, self.pos[1] - 200))
				self.unplaced.rotate(self.rotate_unplaced)
		# Update tabs
		for i in range(3):
			self.tabs[i].move()

	# Automatically place goal in the environment
	def set_goal(self):
		# Goal is shapped like a flag. Keep trying to place goal until the attaches to the ground by the flag pole
		for i in range(10):
			# Randomly position
			x_pos = randint(850,900)
			self.goal = Object(0, (x_pos, 0))
			# Pick a direction for the goal to face. When placing on a slope means it can attach to the ground by the pole
			flipped = False
			if randint(0, 100) > 50:
				self.goal.load_image("image_resources/goal.png")
			else:
				self.goal.load_image("image_resources/goal_flipped.png")
				flipped = True
			counter = 0
			# Start the goal in the air. Keep lowering until it touches the ground
			while(not self.check_environmental_overlap(True)):
				counter += 1
				self.goal.set_position((x_pos,counter))
			# Lower the goal by 2 pixels to plant it firmly in the ground
			self.goal.set_position((x_pos,counter + 2))
			# If planted by the flag pole break otherwise try a maximum of 10 times
			if self.check_environmental_overlap(True) > 40:
				break
		self.draw_goal = True

	# Reset environment
	def reset_environment(self,  clear_world=False):
		# Reset variables
		self.running = False
		self.placing_object = False
		self.network_collection.reset_training()
		# Clear blocks and agents
		self.agents = []
		self.agent_num = 0
		self.episode_num = 0
		self.draw_scaleable = False
		if not clear_world:
			self.blocks = []
			self.draw_goal = False
		# If not custom built environments generate a new one
		if not self.custom_build:
			self.generate_world()
		self.tabs[1].write_message("Environment Reset")

	# When the user requests a block give them one
	def world_building(self, object_num):
		if not self.running and (object_num < 4 or self.draw_goal == False):
			if self.custom_build or object_num > 3:
				self.placing_object = True
				# Centered so cursor is in the middle of the image
				self.unplaced = Object(0, (self.pos[0] - 200, self.pos[1] - 200))
				self.unplaced.load_image("image_resources/"+self.block_images[object_num]+".png")
				self.unplaced_goal = (object_num > 3)

	# Training mode. Here the user performs several subtasks to train the neural network
	def training_mode(self):
		# If no agents exist create one
		if len(self.agents) == 0:
			if self.reference > 0:
				self.create_agent(290, True, True)
			else:
				self.create_agent(290, True, False)

		# Get agent
		agent = self.agents[0]
		# Get collection of neural networks
		network_collection = self.network_collection
		# Move agent
		agent.move()

		# If the agent finishes its run reset environment
		if agent.restart:
			# Did the agent win
			if agent.won:
				self.won += 1
				if self.extra:
					self.tabs[1].write_message("WON")
			else:
				self.lost += 1
				if self.extra:
					self.tabs[1].write_message("LOST")

			# Run the first 2 training stages until the networks have 20000 pieces of data.
			# Run the last 2 training stages until the networks have 50000 pieces of data.
			comparator = 50000
			if network_collection.get_turn() < 2:
				comparator = 20000

			difference = (network_collection.get_length() - (comparator * self.reference / 100))

			# If the network has enough data
			if network_collection.get_length() > comparator:
				# Move to the next step
				self.tabs[1].write_message("Training Stage " + str(network_collection.get_turn() + 1) + "/4 Complete")
				network_collection.increment_turn()
				# Generate new environment
				self.generate_world()
				# Average of the averages from each stage of training
				self.win_counter += (self.won/(self.won + self.lost))/4
				# Finish episode
				if network_collection.get_turn() == 0:
					self.tabs[1].write_message("Episode " + str(self.episode_num + 1) + " Finished")
					self.tabs[1].write_message("Training, This may take a while")
					self.draw_scaleable = False
					self.draw_sprites()
					# If using Win or Learn Fast update the learning rate
					learn_rate = network_collection.get_learn_rate()
					if self.wolf:
						learn_rate = 0.1 - (self.win_counter * 0.099)
						network_collection.update_learn_rate(learn_rate)
					# Finish episode and save network
					network_collection.finish_episode()
					network_collection.save_checkpoint()
					self.tabs[1].write_message("Network Trained With LR: " + str("%.3f" % learn_rate))

					# Reset variables
					self.episode_num += 1
					self.win_counter = 0
					preset = False

					# End run
					self.run_ended()

				# Empty environment except on the 3rd stage
				elif network_collection.get_turn() == 3:
					self.blocks = []
					self.draw_goal = False
				# Reset win/loss count
				self.won = 0
				self.lost = 0
			elif self.extra:
				self.tabs[1].write_message(str(network_collection.get_length()) + " / " + str(comparator))

			# Reset agent
			self.agents = []
			self.create_agent(290, True, (network_collection.get_length() < (comparator * self.reference / 100)))

			# On the 3rd training step spawn static training agents
			if network_collection.get_turn() == 3:
				for j in range(len(self.scaleable_agents)):
					self.agents[self.agent_num].add_other_agent(self.scaleable_agents[j])
				self.draw_scaleable = True

	# Free mode. Environment are built and agents attempt to work together to scale them
	def free_mode(self):
		# If no agents currently exist create one
		if len(self.agents) == 0:
			# If there is no goal make one
			if not self.draw_goal:
				self.set_goal()
			self.create_agent(390, False)

		# Move all the agents
		for i in range(self.agent_num + 1):
			self.agents[i].move()
			# Once an agent is confirmed to be finished add its mask to the next agent
			if self.agents[i].finished_completely:
				self.agents[i].finished_completely = False
				self.agents[self.agent_num].add_other_agent(self.agents[i])
		# If an agent requests another then spawn another agent
		if self.agents[self.agent_num].finished == 1:
			self.agents_to_be_added = [self.agent_num]
			self.agent_num += 1
			self.create_agent(100, False)
		# If the agent declares a run finished, end run
		elif self.agents[self.agent_num].finished == -1:
			if self.agents[self.agent_num].won:
				self.tabs[1].write_message("Run Finished Successfully")
			else:
				self.tabs[1].write_message("Run Failed")
			self.run_ended()

	# Run ended.
	def run_ended(self):
		# If it's in continuous create a new run otherwise reset environment and wait for user input
		if self.continuous:
			self.agents = []
			# If the environment is custom keep it otherwise reset the environment
			if self.custom_build:
				self.agent_num = 0
			else:
				self.reset_environment()
				self.running = True
		else:
			self.reset_environment(self.custom_build)

	# Create a new agent
	def create_agent(self, x_pos, training, reference=False):
		# Append to agent array
		if self.training:
			# Choose if the run is a reference of the neural network
			if self.extra:
				if reference:
					self.tabs[1].write_message("Reference")
				else:
					self.tabs[1].write_message("Neural Network")
			self.agents.append(Agent((x_pos,200), self.network_collection, 0, None, 25, True, self.randomness, reference))
		else:
			self.agents.append(Agent((x_pos,200), self.network_collection, 0, self.goal, 25, False, self.randomness, self.subsumption))
		if self.extra:
			self.tabs[1].write_message("New Agent Created")
		# Inform agent of the other agents positions
		for j in range(len(self.agents) - 2):
			self.agents[self.agent_num].add_other_agent(self.agents[j])
		self.agents[self.agent_num].add_object((self.floor.get_mask(), self.floor.get_position()[0], self.floor.get_position()[1]))
		# Inform agent of the environmental objects positions
		for j in range(len(self.blocks)):
			self.agents[self.agent_num].add_object((self.blocks[j].get_mask(), self.blocks[j].get_position()[0], self.blocks[j].get_position()[1]))

Main()


from django.contrib import admin
from django import forms

from .models import *

# Register your models here.

# class PersonForm(forms.ModelForm):
#     some_field = forms.ModelMultipleChoiceField(Person.objects.all(), widget=FilteredSelectMultiple("Person", False, attrs={'rows':'2'}))
#     class Meta:
#         model = CategoriaNoticia

class NoticiaForm(forms.ModelForm):
    class Meta:
        model = Noticia
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        forms.ModelForm.__init__(self, *args, **kwargs)
        self.fields['categoria'].queryset = CategoriaNoticia.objects.filter(estado=True)
        self.fields['empresa'].queryset = Empresa.objects.filter(estado=True,categoria__nombre='periodico')

class FotoNoticiaInline(admin.StackedInline):
    model = FotoNoticia
    # form = HorarioForm
    fields = ('foto', 'descripcion','autor','localidad')
    can_delete = False
    extra = 1

class NoticiaAdmin(admin.ModelAdmin):
    model = Noticia
    form = NoticiaForm
    # list_display = ('id','titulo', 'sub_titulo', 'descripcion', 'link_fuente', 'estado', 'creado', 'empresa','categoria')
    # list_filter = ('username', 'is_staff', 'is_active', 'groups')
    # fieldsets = (
    #     ('Informacion Personal', {'fields': ('username', 'password', 'nombres', 'apellidos','email','foto','ciudad')}),
    #     ('Permisos', {'fields': ('is_staff', 'is_active','groups', 'user_permissions')}),
    # )
    # add_fieldsets =(
    #     (None, {
    #         'classes': ('wide',),
    #         'fields': ('username', 'password1', 'password2', 'nombres',  'apellidos', 'foto','email', 'is_staff', 'is_active')}
    #     ),
    # )
    inlines = (FotoNoticiaInline,)
    filter_horizontal = ('categoria',)
    # search_fields = ('username',)
    ordering = ('creado',)
    actions = ["activar_noticia"]

    def get_actions(self, request):#eliminar la accion de eliminar
        actions = super().get_actions(request)
        if 'delete_selected' in actions:
            del actions['delete_selected']
        return actions

    def activar_noticia(self, request, queryset):#acciones masivas
        queryset.update(is_active=True)

admin.site.register(CategoriaNoticia)
admin.site.register(Noticia,NoticiaAdmin)
# admin.site.register(FotoNoticia)


import json
import requests
from collections import Counter

def numberOfDates(data):
	counter = 0
	for key in data:
		counter += 1
	return counter

def findTop5Highest(data):
	num = numberOfDates(data)
	k = Counter(data)
	printCounter = num

	if num < 5:
		high = k.most_common(num)
	else:
		high = k.most_common(5)
		printCounter = 5

	highDict = {}

	for i in high:
		highDict[i[0]] = i[1]

	return highDict

def feelingNumber(feeling):

	if feeling == 'Fantastic':
		return 100

	elif feeling == 'Ok':
		return 50

	elif feeling == 'Frustrated':
		return 0

def getFinalValues(feelingsCompare, dataDict):

	num = numberOfDates(feelingsCompare)
	tempAverage = 0
	noiseAverage = 0
	humiAverage = 0
	brightAverage = 0

	for key in feelingsCompare:
		tempAverage += dataDict[key]['tempAverage']
		noiseAverage += dataDict[key]['noiseAverage']
		humiAverage += dataDict[key]['humiAverage']
		brightAverage += dataDict[key]['brightAverage']

	tempAverage /= num
	noiseAverage /= num
	humiAverage /= num
	brightAverage /= num

	tempAverage = round(tempAverage, 2)
	noiseAverage = round(noiseAverage, 2)
	humiAverage = round(humiAverage, 2)
	brightAverage = round(brightAverage, 2)

	finalDict = {
		"tempAverage": tempAverage,
		"humiAverage": humiAverage,
		"noiseAverage": noiseAverage,
		"brightAverage":brightAverage
	}

	return finalDict

def calculate_function(feelings, data):

	feelingsDict = {}
	feelingsTop = {}
	dataDict = {}

	for line in feelings:
		jsonTemp = line
		keyTemp = jsonTemp['time']['date']
		if keyTemp in feelingsDict.keys():
			feelingsDict[keyTemp]['value'] += feelingNumber(jsonTemp['feeling'])
			feelingsDict[keyTemp]['people'] += 1
		else:
			feelingsDict[keyTemp] = {}
			feelingsDict[keyTemp]['value'] = feelingNumber(jsonTemp['feeling'])
			feelingsDict[keyTemp]['people'] = 1

	for key in feelingsDict:
		feelingsTop[key] = feelingsDict[key]['value']/feelingsDict[key]['people']

	for line in data:
		jsonTemp = line
		keyTemp = jsonTemp['time']['date']
		if keyTemp in dataDict.keys():
			dataDict[keyTemp]['counter'] += 1
			dataDict[keyTemp]['temperature'] += jsonTemp['temperature']
			dataDict[keyTemp]['humidity'] += jsonTemp['humidity']
			dataDict[keyTemp]['noise'] += jsonTemp['noise']
			dataDict[keyTemp]['brightness'] += jsonTemp['brightness']
		else:
			dataDict[keyTemp] = {}
			dataDict[keyTemp]['counter'] = 1
			dataDict[keyTemp]['temperature'] = jsonTemp['temperature']
			dataDict[keyTemp]['humidity'] = jsonTemp['humidity']
			dataDict[keyTemp]['noise'] = jsonTemp['noise']
			dataDict[keyTemp]['brightness'] = jsonTemp['brightness']

	for key in dataDict:
		dataDict[key]['tempAverage'] = dataDict[key]['temperature']/dataDict[key]['counter']
		dataDict[key]['humiAverage'] = dataDict[key]['humidity']/dataDict[key]['counter']
		dataDict[key]['noiseAverage'] = dataDict[key]['noise']/dataDict[key]['counter']
		dataDict[key]['brightAverage'] = dataDict[key]['brightness']/dataDict[keyTemp]['counter']

	feelingsCompare = findTop5Highest(feelingsTop)

	print(json.dumps(getFinalValues(feelingsCompare, dataDict)))

feelings = requests.post('http://192.168.1.27:3000/feeling/getAll')
feelingsJSON = feelings.json()

data = requests.post('http://192.168.1.27:3000/data/getData')
dataJSON = data.json()

calculate_function(feelingsJSON, dataJSON)


from django.urls import path
from core import views as v

urlpatterns = [
    path('', v.home, name='core_home'),
    path('pessoas/', v.lista_pessoas, name='core_lista_pessoas'),
    path('pessoas/criar', v.criar_pessoas, name='core_criar_pessoas'),
    path('pessoas/update/<int:id>', v.update_pessoa, name='core_update_pessoa'),
    path('pessoas/delete/<int:id>', v.delete_pessoa, name='core_delete_pessoa'),

    path('veiculos/', v.lista_veiculos, name='core_lista_veiculos'),
    path('veiculos/criar', v.criar_veiculos, name='core_criar_veiculos'),
    path('veiculos/update/<int:id>', v.update_veiculo, name='core_update_veiculo'),
    path('veiculos/delete/<int:id>', v.delete_veiculo, name='core_delete_veiculo'),

    path('mov-rot/', v.lista_movrotativo, name='core_lista_movrotativo'),
    path('mov-rot/criar', v.criar_movrotativo, name='core_criar_movrotativo'),
    path('mov-rot/update/<int:id>', v.update_movrotativo, name='core_update_movrotativo'),
    path('mov-rot/delete/<int:id>', v.delete_movrotativo, name='core_delete_movrotativo'),

    path('mensalistas/', v.lista_mensalista, name='core_lista_mensalista'),
    path('mensalistas/criar', v.criar_mensalista, name='core_criar_mensalista'),
    path('mensalistas/update/<int:id>', v.update_mensalista, name='core_update_mensalista'),
    path('mensalistas/delete/<int:id>', v.delete_mensalista, name='core_delete_mensalista'),

    path('mov-mens/', v.lista_movmensalista, name='core_lista_movmensalista'),
    path('mov-mens/criar', v.criar_movmensalista, name='core_criar_movmensalista'),
    path('mov-mens/update/<int:id>', v.update_movmensalista, name='core_update_movmensalista'),
    path('mov-mens/delete/<int:id>', v.delete_movmensalista, name='core_delete_movmensalista')
]


import sqlite3

from app.core.pathutils import get_database_root
from app.database.tables import users_table, shopping_list_table

class DatabaseCreator:
    def __init__(self) -> None:
        self._database_path = get_database_root()
        self._connector = sqlite3.connect(self._database_path)

    def create_tables(self) -> None:
        cursor = self._connector.cursor()
        cursor.execute(shopping_list_table)
        cursor.execute(users_table)
        self._connector.commit()

if __name__ == "__main__":
    DatabaseCreator().create_tables()


from utils import *

import random

class Board:

    def __init__(self,p1,p2):
        self.map = [[0,0,0],[0,0,0],[0,0,0]]
        self.is_playing = 0
        self.winner = 0
        self.nb_turn = 1
        self.player1 = p1
        self.player2 = p2

    def display_map(self):
        d_map = "Turn : "+str(self.nb_turn)+"\n\n+-----+\n"
        for i in range(3):
            for j in range(3):
                d_map += "|"
                if self.map[i][j] == 0:
                    d_map += " "
                if self.map[i][j] == 1:
                    d_map += "o"
                if self.map[i][j] == -1:
                    d_map += "*"
            d_map += "|\n+-----+\n"

        print(d_map)

    def restart(self):
        self.map = [[0,0,0],[0,0,0],[0,0,0]]
        self.is_playing = 0
        self.winner = 0
        self.nb_turn = 1

    def end_turn(self):
        self.is_playing *= -1
        self.nb_turn += 1

    def declare_winner(self,winner):
        self.winner = winner

    def get_winner(self):
        return self.winner


import os
import sys

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

try:
    from distutils.command.build_py import build_py_2to3 as build_py
except ImportError:
    from distutils.command.build_py import build_py

path, script = os.path.split(sys.argv[0])
os.chdir(os.path.abspath(path))

# Don't import rjmetrics module here, since deps may not be installed
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'rjmetrics'))
from version import VERSION

install_requires = ['requests >= 0.8.8']

# Get simplejson if we don't already have json
if sys.version_info < (3, 0):
    try:
        from util import json
    except ImportError:
        install_requires.append('simplejson')

setup(
    name='rjmetrics',
    cmdclass={'build_py': build_py},
    version=VERSION,
    description='Python client for RJMetrics APIs',
    author='RJMetrics',
    author_email='support@rjmetrics.com',
    url='https://rjmetrics.com/',
    packages=['rjmetrics', 'rjmetrics.test'],
    package_data={'rjmetrics': ['../VERSION']},
    install_requires=install_requires,
    test_suite='rjmetrics.test.all',
    use_2to3=True,
    classifiers=[
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: Apache Software License",
        "Operating System :: OS Independent",
        "Programming Language :: Python",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.4",
        "Programming Language :: Python :: Implementation :: PyPy",
        "Topic :: Software Development :: Libraries :: Python Modules",
    ])


"""Adds edges between family members at the same address."""

import six

from . import entity_tools
from . import graph_tools
from . import utils

# Edges between neighbours are added only if the number of entities
# at a particular address is at most `MAX_NEIGHBOUR_GROUP_SIZE`:
MAX_NEIGHBOUR_GROUP_SIZE = 2

# String to prefix log messages with:
LOG_PREFIX = '[post_process_neighbours] '

def _are_surnames_similar(surname1, surname2):
    """Decides if two surnames are similar enough to be family."""

    if (not surname1) or (not surname2):
        return False

    # TODO(matejbalog): Consider normalising by removing accents and
    # capitalisation.

    if surname1 == surname2:
        return True

    # Decide based on the length of the longest common prefix:
    lcp = utils.longest_common_prefix(surname1, surname2)
    if (lcp >= 3 and lcp >= len(surname1) - 3 and
            lcp >= len(surname2) - 1 and surname1[-1] in ['a', '\xe1']):
        return True
    if (lcp >= 3 and lcp >= len(surname1) - 1 and
            lcp >= len(surname2) - 3 and surname2[-1] in ['a', '\xe1']):
        return True

    return False

def add_family_and_neighbour_edges(db, test_mode):
    """Adds edges between family members and close neighbours.

    Creates two new edge types and adds the corresponding edges:
    (1) "family": Links any two entities at the same address with
        "sufficiently" similar surnames (as determined by the function
        `_are_surnames_similar` above).
    (2) "neighbours": Links any two entities at the same address, as
        long as there are at most MAX_NEIGHBOUR_GROUP_SIZE entities at
        that address.
    """

    # Load surnames and academic titles:
    surnames = entity_tools.get_surnames()
    titles_parser = entity_tools.get_academic_titles_parser()

    # Compute mapping from eids to parsed entity names:
    parsed_name = {}
    suffix = ' LIMIT 50000;' if test_mode else ';'
    query = 'SELECT id, name FROM entities' + suffix
    with db.get_server_side_cursor(query) as cur:
        for eid, name in cur:
            parsed = entity_tools.parse_entity_name(
                name, titles_parser, surnames, verbose=False)
            if parsed:
                parsed_name[eid] = parsed

    # Initialise edges:
    edges_family = []
    edges_neighbours = []

    # Iterate through entity groups sharing the same Address:
    suffix = " LIMIT 50000;" if test_mode else ";"
    cur = db.get_server_side_cursor("""
        SELECT array_agg(id) as eids
        FROM entities
        GROUP BY address_id
        """ + suffix, buffer_size=10000)

    # Iterate through entity groups sharing the same Address:
    for row in cur:
        eids = row[0]

        # Iterate through distinct pairs of entities in this group:
        group_size = len(eids)
        for i in six.moves.range(group_size):
            # Add family edges:
            if eids[i] in parsed_name:
                for j in six.moves.range(i + 1, group_size):
                    if eids[j] in parsed_name:
                        if _are_surnames_similar(
                                parsed_name[eids[i]].surname,
                                parsed_name[eids[j]].surname):
                            edges_family.append((eids[i], eids[j]))
                            edges_family.append((eids[j], eids[i]))

            # Add neighbour edges:
            if group_size <= MAX_NEIGHBOUR_GROUP_SIZE:
                for j in range(i + 1, group_size):
                    edges_neighbours.append((eids[i], eids[j]))
                    edges_neighbours.append((eids[j], eids[i]))

    cur.close()
    print('%sAccumulated %d family edges and %d neighbour edges' % (LOG_PREFIX, len(edges_family), len(edges_neighbours)))

    # Get edge type indices for the new edge types:
    edge_type_family = graph_tools.add_or_get_edge_type(
        db, "Zhoda v priezvisku a adrese", LOG_PREFIX)
    edge_type_neighbour = graph_tools.add_or_get_edge_type(
        db, "Susedia", LOG_PREFIX)

    # Remove any existing edges of these edge types:
    q_data = [edge_type_family, edge_type_neighbour]
    db.execute("""
        DELETE FROM related
        WHERE stakeholder_type_id=%s OR stakeholder_type_id=%s;
        """, q_data)
    print("%sRemoved any existing edges of types %s" % (LOG_PREFIX, q_data))

    # Insert the new edges:
    with db.cursor() as cur:
        q = """
        INSERT INTO related(eid, eid_relation, stakeholder_type_id)
        VALUES (%s, %s, %s);
        """
        q_data = [(source, target, edge_type_family)
                  for source, target in edges_family]
        cur.executemany(q, q_data)
        q_data = [(source, target, edge_type_neighbour)
                  for source, target in edges_neighbours]
        cur.executemany(q, q_data)


from django.conf import settings
from django.contrib import messages
from django.core.exceptions import PermissionDenied, SuspiciousOperation
from django.db.models.query import QuerySet
from django.http import FileResponse, HttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.utils.translation import gettext as _
from django.views.decorators.http import require_GET, require_POST
from django.views.generic import DetailView, TemplateView

from evap.evaluation.auth import (
    grade_downloader_required,
    grade_publisher_or_manager_required,
    grade_publisher_required,
)
from evap.evaluation.models import Course, EmailTemplate, Evaluation, Semester
from evap.evaluation.tools import get_object_from_dict_pk_entry_or_logged_40x, ilen
from evap.grades.forms import GradeDocumentForm
from evap.grades.models import GradeDocument

@grade_publisher_required
class IndexView(TemplateView):
    template_name = "grades_index.html"

    def get_context_data(self, **kwargs):
        return super().get_context_data(**kwargs) | {
            "semesters": Semester.objects.filter(grade_documents_are_deleted=False),
            "disable_breadcrumb_grades": True,
        }

def course_grade_document_count_tuples(courses: QuerySet[Course]) -> list[tuple[Course, int, int]]:
    courses = courses.prefetch_related("degrees", "responsibles", "evaluations", "grade_documents")

    return [
        (
            course,
            ilen(gd for gd in course.grade_documents.all() if gd.type == GradeDocument.Type.MIDTERM_GRADES),
            ilen(gd for gd in course.grade_documents.all() if gd.type == GradeDocument.Type.FINAL_GRADES),
        )
        for course in courses
    ]

@grade_publisher_required
class SemesterView(DetailView):
    template_name = "grades_semester_view.html"
    model = Semester
    pk_url_kwarg = "semester_id"

    object: Semester

    def get_object(self, *args, **kwargs):
        semester = super().get_object(*args, **kwargs)
        if semester.grade_documents_are_deleted:
            raise PermissionDenied
        return semester

    def get_context_data(self, **kwargs):
        courses = (
            self.object.courses.filter(evaluations__wait_for_grade_upload_before_publishing=True)
            .exclude(evaluations__state=Evaluation.State.NEW)
            .distinct()
        )
        courses = course_grade_document_count_tuples(courses)

        return super().get_context_data(**kwargs) | {
            "courses": courses,
            "disable_breadcrumb_semester": True,
        }

@grade_publisher_or_manager_required
class CourseView(DetailView):
    template_name = "grades_course_view.html"
    model = Course
    pk_url_kwarg = "course_id"

    def get_object(self, *args, **kwargs):
        course = super().get_object(*args, **kwargs)
        if course.semester.grade_documents_are_deleted:
            raise PermissionDenied
        return course

    def get_context_data(self, **kwargs):
        return super().get_context_data(**kwargs) | {
            "semester": self.object.semester,
            "grade_documents": self.object.grade_documents.all(),
            "disable_breadcrumb_course": True,
        }

def on_grading_process_finished(course):
    evaluations = course.evaluations.all()
    if all(evaluation.state == Evaluation.State.REVIEWED for evaluation in evaluations):
        for evaluation in evaluations:
            assert evaluation.grading_process_is_finished
        for evaluation in evaluations:
            evaluation.publish()
            evaluation.save()

        EmailTemplate.send_participant_publish_notifications(evaluations)
        EmailTemplate.send_contributor_publish_notifications(evaluations)

@grade_publisher_required
def upload_grades(request, course_id):
    course = get_object_or_404(Course, id=course_id)
    semester = course.semester
    if semester.grade_documents_are_deleted:
        raise PermissionDenied

    final_grades = request.GET.get("final") == "true"  # if parameter is not given, assume midterm grades

    grade_document = GradeDocument(course=course)
    if final_grades:
        grade_document.type = GradeDocument.Type.FINAL_GRADES
        grade_document.description_en = settings.DEFAULT_FINAL_GRADES_DESCRIPTION_EN
        grade_document.description_de = settings.DEFAULT_FINAL_GRADES_DESCRIPTION_DE
    else:
        grade_document.type = GradeDocument.Type.MIDTERM_GRADES
        grade_document.description_en = settings.DEFAULT_MIDTERM_GRADES_DESCRIPTION_EN
        grade_document.description_de = settings.DEFAULT_MIDTERM_GRADES_DESCRIPTION_DE

    form = GradeDocumentForm(request.POST or None, request.FILES or None, instance=grade_document)

    if form.is_valid():
        form.save(modifying_user=request.user)

        if final_grades:
            on_grading_process_finished(course)

        messages.success(request, _("Successfully uploaded grades."))
        return redirect("grades:course_view", course.id)

    template_data = {
        "semester": semester,
        "course": course,
        "form": form,
        "final_grades": final_grades,
        "show_automated_publishing_info": final_grades,
    }
    return render(request, "grades_upload_form.html", template_data)

@require_POST
@grade_publisher_required
def set_no_grades(request):
    course = get_object_from_dict_pk_entry_or_logged_40x(Course, request.POST, "course_id")

    try:
        status = bool(int(request.POST["status"]))
    except (KeyError, TypeError, ValueError) as e:
        raise SuspiciousOperation from e

    if course.semester.grade_documents_are_deleted:
        raise PermissionDenied

    course.gets_no_grade_documents = status
    course.save()

    if course.gets_no_grade_documents:
        on_grading_process_finished(course)

    return HttpResponse()  # 200 OK

@require_GET
@grade_downloader_required
def download_grades(request, grade_document_id):
    grade_document = get_object_or_404(GradeDocument, id=grade_document_id)
    if grade_document.course.semester.grade_documents_are_deleted:
        raise PermissionDenied

    return FileResponse(grade_document.file.open(), filename=grade_document.filename(), as_attachment=True)

@grade_publisher_required
def edit_grades(request, grade_document_id):
    grade_document = get_object_or_404(GradeDocument, id=grade_document_id)
    course = grade_document.course
    semester = course.semester
    if semester.grade_documents_are_deleted:
        raise PermissionDenied

    form = GradeDocumentForm(request.POST or None, request.FILES or None, instance=grade_document)

    final_grades = (
        grade_document.type == GradeDocument.Type.FINAL_GRADES
    )  # if parameter is not given, assume midterm grades

    if form.is_valid():
        form.save(modifying_user=request.user)
        messages.success(request, _("Successfully updated grades."))
        return redirect("grades:course_view", course.id)

    template_data = {
        "semester": semester,
        "course": course,
        "form": form,
        "show_automated_publishing_info": False,
        "final_grades": final_grades,
    }
    return render(request, "grades_upload_form.html", template_data)

@require_POST
@grade_publisher_required
def delete_grades(request):
    grade_document = get_object_from_dict_pk_entry_or_logged_40x(GradeDocument, request.POST, "grade_document_id")
    grade_document.delete()
    return HttpResponse()  # 200 OK


from django_project.search_engine.http.resolver import HttpRequestResolver, ParameterError, ResponseCodeError
import unittest
from unittest.mock import Mock, patch

class TestHttpRequestResolver(unittest.TestCase):
    @patch('requests.Session')
    def setUp(self, session_mock):
        self.actual_session_mock = Mock()
        session_mock.return_value = self.actual_session_mock

        self.url = "http://dummy.url"
        self.headers = "dummy_header"
        self.params = "dummy_prarams"
        self.response_OK = 200
        self.response_NOK = 400
        self.json_data = "dummy_data"
        self.uut = HttpRequestResolver(url=self.url, headers=self.headers)
        self.actual_session_mock.mount.assert_called_once()

    def test_resolve_succeeded(self):
        response_mock = Mock()
        response_mock.status_code = self.response_OK
        response_mock.json.return_value = self.json_data
        self.actual_session_mock.get.return_value = response_mock

        self.uut.set_params(self.params)

        result_json = self.uut.resolve()
        self.actual_session_mock.get.assert_called_with(self.url, params=self.params, headers=self.headers)
        response_mock.json.assert_called_once()

        self.assertEqual(result_json, self.json_data)

    def test_resolve_throw_when_params_not_set(self):
        self.assertRaisesRegex(ParameterError, '.*', self.uut.resolve)

    def test_response_not_valid(self):
        response_mock = Mock()
        response_mock.status_code = self.response_NOK
        self.actual_session_mock.get.return_value = response_mock

        self.uut.set_params(self.params)

        self.assertRaisesRegex(ResponseCodeError, '.*', self.uut.resolve)
        self.actual_session_mock.get.assert_called_with(self.url, params=self.params, headers=self.headers)

if __name__ == '__main__':
    unittest.main()


import folium

def map_creation(df_static,geo_json_data):
    #json file with the coordinates of each commune in France imported as dataframe
    #capitalized everything because it is case sensitive
    geo_json_data['libgeo'] = geo_json_data['libgeo'].str.upper()

    commune_avg = df_static.groupby('Nom de la commune', as_index=False)['Consommation annuelle moyenne de la commune (MWh)'].mean()
    commune_avg['Nom de la commune'] = commune_avg['Nom de la commune'].str.upper()

    #creating the dataframe that only contains the communes in both dataframes with their coordinates and consumption rates
    geo_json_data=geo_json_data.loc[:,('libgeo','geometry')]
    df_final = geo_json_data.merge(commune_avg, left_on='libgeo', right_on='Nom de la commune',how='outer')
    df_final = df_final.dropna()

    #adding our data to the map
    mymap = folium.Map(location=[46.2276,2.2137], zoom_start=5.5)
    mymap.choropleth(
        geo_data=geo_json_data,
        name='Communes',
        data=commune_avg,
        columns=['Nom de la commune','Consommation annuelle moyenne de la commune (MWh)'],
        key_on="feature.properties.libgeo",
        fill_color='YlGnBu', nan_fill_color="#FF000000",
        fill_opacity=1,
        line_opacity=0.2,
        legend_name='Consommation moyenne des 4 dernières années (MWh)',
        smooth_factor=0
        )

    #designing our interactive map
    style_function = lambda x: {'fillColor': '#ffffff',
                            'color':'#000000',
                            'fillOpacity': 0.1,
                            'weight': 0.1}
    highlight_function = lambda x: {'fillColor': '#000000',
                                'color':'#000000',
                                'fillOpacity': 0.50,
                                'weight': 0.1}

    #adding our interactive features
    folium.features.GeoJson(
        data=df_final,
        style_function=style_function,
        control=False,
        highlight_function=highlight_function,
        tooltip=folium.features.GeoJsonTooltip(
            fields=['Nom de la commune','Consommation annuelle moyenne de la commune (MWh)'],
            aliases=['Neighborhood: ','Resident foreign population in %: '],
            style=("background-color: white; color: #333333; font-family: arial; font-size: 12px; padding: 10px;"),
            localize=True,
            sticky=True,
            labels=True,
            )
        ).add_to(mymap)
    folium.LayerControl().add_to(mymap)
    return(mymap)


# the amount of stuff purchased.

ans1 = input("Did you buy something?(Yea or No only): ")

if ans1 == str("Yes"):
    n = int(input("How many extra items did you buy: "))
    total = 10.95 + (2.95*n)
    total2 = n + 1
    print("You bought " + str(total2) + " items.")
    print("Your total shipping fee is $" + str(total) +".")
elif ans1 == str("No"):
    print("Have a good day.")
else:
    print("Answer Yes or No.")


class Sample:
    num1 = 0
    num2 = 0

    def display(ref, value1, value2):
        ref.num1 = value1
        ref.num2 = value2
        print(" Num : ", ref.num1)
        print(" Num : ", ref.num2)

obj = Sample()
del obj             # object has been deleted
obj.display(20, 30)


t = int(input())

for _ in range(t):
    n = int(input())
    arr = list(map(int, input().split()))
    steps = []
    for i in range(n):
        l = len("{:b}".format(arr[i]))
        old = arr[i]
        if (1 << l) >= arr[i]:
            arr[i] = 1 << l
        else:
            arr[i] = 1 << l + 1
        if arr[i] > old:
            steps.append((i + 1, arr[i] - old))
    print(len(steps))
    for i, x in steps:
        print(i, x)


from neuro_sdk import PluginManager

from .main import main  # noqa
from .version import __version__  # noqa

NEURO_EXTRAS_UPGRADE = """\
You are using Neuro Extras tool {old_ver}, however {new_ver} is available.
You should consider upgrading via the following command:
    python -m pip install --upgrade neuro-extras
"""

def get_neuro_extras_txt(old: str, new: str) -> str:
    return NEURO_EXTRAS_UPGRADE.format(old_ver=old, new_ver=new)

def setup_plugin(manager: PluginManager) -> None:
    manager.version_checker.register("neuro-extras", get_neuro_extras_txt)


# 스택
# https://www.acmicpc.net/problem/10828

import sys

class stack:
	def __init__(self):
		self.li = list()
		self.cnt = 0

	def push(self,x):
		self.cnt = self.cnt + 1
		self.li.append(x)
		return

	def pop(self):
		if self.cnt == 0:
			print(-1)
			return -1
		print(self.li[self.cnt-1])
		self.cnt = self.cnt-1
		return self.li.pop()

	def top(self):
		if self.cnt == 0:
			print(-1)
			return -1
		else:
			print(self.li[self.cnt-1])
			return self.li[self.cnt-1]

	def empty(self):
		if self.cnt == 0:
			print(1)
			return 1
		else:
			print(0)
			return 0

	def size(self):
		print(self.cnt)
		return self.cnt

stack = stack()

leng1 = int(sys.stdin.readline().strip())
for i in range(leng1):
	leng2 = sys.stdin.readline().strip()
	if "push" in leng2:
		push_input = int(leng2.split(' ')[1])
		stack.push(push_input)
	elif "pop" in leng2:
		stack.pop()
	elif "top" in leng2:
		stack.top()
	elif "empty" in leng2:
		stack.empty()
	elif "size" in leng2:
		stack.size()

# if __name__ == "__main__":
# 	stack = stack()
# 	stack.push(1)
# 	stack.top()


#User function Template for python3

class Solution:
    def dfs(self, i, j, n, m, mat, vis):
        vis[i][j] = 1

        mat[i][j] = 'A'

        directions = [[0, 1], [1, 0], [-1, 0], [0, -1]]

        for di, dj in directions:
            ni, nj = i + di, j + dj

            if ni < 0 or ni >= n or nj < 0 or nj >= m or vis[ni][nj] or mat[ni][nj] == 'X':
                continue

            self.dfs(ni, nj, n, m, mat, vis)

    def fill(self, n, m, mat):
        # code here

        vis = [[0] * m for _ in range(n)]

        for i in range(n):
            for j in range(m):
                if (i == 0 or i == n - 1 or j == 0 or j == m - 1) and mat[i][j] == 'O':
                    self.dfs(i, j, n, m, mat, vis)

        for i in range(n):
            for j in range(m):
                if mat[i][j] == 'O':
                    mat[i][j] = 'X'

                if mat[i][j] == 'A':
                    mat[i][j] = 'O'

        return mat

#{
 # Driver Code Starts
#Initial Template for Python 3

if __name__ == '__main__':
    t = int(input())
    for _ in range(t):
        n, m = [int(x) for x in input().split()]
        mat = []
        for i in range(n):
            s = list(map(str,input().split()))
            mat.append(s)

        ob = Solution()
        ans = ob.fill(n, m, mat)
        for i in range(n):
            for j in range(m):
                print(ans[i][j], end = " ")
            print()
# } Driver Code Ends

Replace O's with X's - GFG/replace-os-with-xs.py


from Proyecto_final_archivos import listados, graficos, graf_prov_afc
'''He querido hacer un programa que integre los tres ejercicios. Desde este menú nos dirije a a listados.py para ver
    los informes de estadísticas, a graf_prov_afec.py que nos da las provincias con más casos y graficos.py para los gráficos 2D
    de los datos.'''

def estadisticas():
    listados.menu_listados()
    return True

def graficas():
    graficos.menu_graf()
    return True

def prov_mas_afec():
    graf_prov_afc.menu_graf_prov_max_afec()
    return True

def menu_principal():
    try:
        continuar = True

        while(continuar):
            print("MENU VISUALIZACION ESTADISTICAS COVID-19")
            print("==========================================")

            eleccion =int(input("""Elija una opción de visualización:
                1) Consulta de datos.
                2) Gráficas.
                3) Provincias más afectadas.
                4) Salir \n"""))
            if eleccion == 1:
                estadisticas()
            elif eleccion == 2:
                graficas()
            elif eleccion == 3:
                prov_mas_afec()
            elif eleccion == 4:
                continuar = False
            else:
                print("Debe elegir una opción del menú")

    except ValueError as val_error:
        print("Debe de eligir una opción del menú")
        menu_principal()
    except Exception as ex:
        print(ex)

menu_principal()


from service import *
from repository import *

class UI:
    def __init__(self, driverServ, orderServ):
        self._driverService = driverServ
        self._orderService = orderServ

    def read_command(self):
        command = input("your command: ")
        idx = command.find(" ")
        if idx == -1:
            return (command,[])
        else:
            cmd = command[:idx]
            params = command[idx+1:].split(",")
        return (cmd, params)

    def start(self):
        while True:
            command = self.read_command()
            cmd = command[0]
            params = command[1]
            if cmd == "exit":
                return
            elif cmd == "add":
                self.add_order(params)
            elif cmd == "display":
                self.display_orders()
            elif cmd == "income":
                self.income_driver(params)

    def display_orders(self):
        for i in self._orderService.get_orders():
            print(i)

    def add_order(self, params):
        try:
            self._orderService.add_order(int(params[0]), int(params[1]))
        except ValueError as ve:
            print(ve)

    def income_driver(self, params):
        print(self._orderService.income_driver(int(params[0])))

driverRepo = DriverRepository("drivers.txt")
orderRepo = OrderRepository("orders.txt", driverRepo)
driverServ = DriverService(driverRepo)
orderServ = OrderService(orderRepo)
ui = UI(driverServ, orderServ)
ui.start()


import argparse
import os
import sys

from . import client, message_variables

DEFAULT_RUN_MESSAGE = "Run triggered by `tfc` command line tool"

class MessageVariableMapping:
    """
    Wrapper for the tfc.message_variables module

    Wraps the tfc.message_variables module in a mapping (dictionary like) interface. The name of
    each function in tfc.message_variables becomes a key in the mapping and the value is the result
    of running that function with no arguments.

    This wrapper effectively allows us to lazily pass all of the results from the functions in
    tfc.message_variables into str.format() (i.e. without running functions which are not used by
    the format string)
    """

    def __getitem__(self, key):
        func = getattr(message_variables, key)
        if getattr(func, "is_message_variable", False):
            return func()
        else:
            raise KeyError(key)

def trigger_run_with_variables(organization, workspace, message, assignments):
    token = os.environ["TERRAFORM_CLOUD_TOKEN"]
    terraform = client.TerraformClient(token, organization, workspace)
    vars = terraform.get_variables()

    for (variable_name, new_value) in assignments.items():
        variable = vars[variable_name]
        terraform.update_variable(variable.id, new_value)
        old_value = variable.value
        print(f"Updated {variable_name!r} from {old_value!r} to {new_value!r}")

    run = terraform.create_run(message)
    print(f"Created run {run.id} - check status at: {run.url}")

def variable_assignment(value):
    if "=" not in value:
        raise argparse.ArgumentTypeError(
            f"Expected an assignment with an equals sign, got {value!r}"
        )
    return value

def get_command_line_arguments(argv):
    parser = argparse.ArgumentParser(
        description="Trigger a Terraform Cloud run",
        epilog="Put your API token in the TERRAFORM_CLOUD_TOKEN environment variable",
    )
    parser.add_argument("organization", help="The name of your organization in Terraform Cloud")
    parser.add_argument("workspace", help="The name of your workspace in Terraform Cloud")
    parser.add_argument(
        "variables",
        metavar="name=value",
        type=variable_assignment,
        nargs="*",
        help="Set terraform variable NAME to VALUE before creating the run",
    )
    parser.add_argument(
        "--message",
        "-m",
        help="The message to be associated with this run",
        default=DEFAULT_RUN_MESSAGE,
    )

    args = parser.parse_args(argv[1:])
    args.variables = dict([v.split("=", 1) for v in args.variables])
    return args

def main(argv=sys.argv):
    """The entry point when running `tfc` as a script"""
    args = get_command_line_arguments(argv)
    message = args.message.format_map(MessageVariableMapping())
    trigger_run_with_variables(args.organization, args.workspace, message, args.variables)
    return 0


# Given an array of intervals where intervals[i] = [starti, endi],
# merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

def merge(intervals):
        if intervals==[]:
            return []
        result=[]
        intervals.sort()
        for interval in intervals:
            if result==[] or result[-1][1]<interval[0]:
                result.append(interval)
            else:
                result[-1][1]=max(result[-1][1],interval[1])
        return result

if __name__ == "__main__":
    intervals=[[1,3],[2,5]]
    print(merge(intervals))


# 1) Time Module
# Write a program that:
# . Prompts you for a word.
# . Once you have entered the word, the programs displays the amount of seconds it took you
# (approx.) to type the word. (Display seconds up to one decimal place, as in 1.5 secs, hint
# remember your format notes from course I)
# Hint: You have to use the time.time() function to capture the time in seconds just before and
# just after you type your word.

import time;

timeStart = time.time();

input('Please type "hello": ');

timeEnd = round(time.time() - timeStart, 2);

print(timeEnd)


import pandas as pd

from components.constants import class_categories

def load_data_and_clean_data():

# Load Data

    top_x = 100

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

    # Drop null values
    df = df.dropna()

    # Drop irrelevant columns
    df = df.drop(['nametype', 'GeoLocation'], axis=1)

    # Rename columns
    df = df.rename(columns={'mass (g)': 'mass', 'recclass':'class', 'reclat': 'latitude', 'reclong': 'longitude'})

    # Convert data types
    df['year'] = df['year'].astype(int)

    # Convert mass from grams to kilograms
    df['mass'] = df['mass'] / 1000
    df['mass'] = df['mass'].astype(int)

    # Sort by mass descending
    df = df.sort_values(by='mass', ascending=False)

    # Choose top x values
    df = df.iloc[:top_x]

    # Apply the class categories to the class column and create a new column called class_cat
    df['class_cat'] = df['class'].apply(lambda x: [k for k, v in class_categories.items() if x in v][0])

    # print(df.columns)
    # print(df.head())
    # print(len(df))
    # print(df.dtypes)
    # print(df.describe())

    return df

# %%


#! /usr/bin/env python
# -*- coding: UTF-8 -*-

#----------------------------------------------------------------------------------------------------------------------*

import sys, time, os, json
import makefile, default_build_options
import generic_galgas_makefile

#----------------------------------------------------------------------------------------------------------------------*

def buildForUnix (dictionary, jsonFilePath, EXECUTABLE, GOAL, maxParallelJobs, displayCommands) :
  gmf = generic_galgas_makefile.GenericGalgasMakefile ()
  gmf.mJSONfilePath = jsonFilePath
  gmf.mDictionary = dictionary
  gmf.mExecutable = EXECUTABLE
  gmf.mGoal = GOAL
  gmf.mMaxParallelJobs = maxParallelJobs
  gmf.mDisplayCommands = displayCommands
  gmf.mTargetName = "unix"
#---
  gmf.mCompilerTool = ["gcc"]
  gmf.mLinkerTool   = ["g++"]
  gmf.mStripTool    = ["strip"]
  gmf.mSudoTool     = ["sudo"]

#   gmf.mCompilerTool = ["/usr/local/Cellar/gcc/10.2.0/bin/gcc-10"]
#   gmf.mLinkerTool   = ["/usr/local/Cellar/gcc/10.2.0/bin/g++-10"]
#   gmf.mStripTool    = ["strip"]
#   gmf.mSudoTool     = ["sudo"]

  gmf.mCompilationMessage = "Compiling for Unix"
  gmf.mLinkingMessage = "Linking for Unix"
  gmf.mInstallationgMessage = "Installing"
  gmf.mStripMessage = "Stripping"
#--- Options for all compilers
  gmf.mAllCompilerOptions = default_build_options.allCompilerOptions (["-Wconversion"])
#--- Options for release mode
  gmf.mCompilerReleaseOptions = default_build_options.compilerReleaseOptions (["-O2"])
#--- Options for debug mode
  gmf.mCompilerDebugOptions = default_build_options.compilerDebugOptions ([])
#--- Options for C compiling (.c extension)
  gmf.m_C_CompilerOptions = default_build_options.C_CompilerOptions ([])
#--- Options for C++ compiling (.cpp extension)
  gmf.m_Cpp_CompilerOptions = default_build_options.Cpp_CompilerOptions (["-Weffc++", "-Wsign-promo"])
#--- Options for Objective-C compiling (.m extension)
  gmf.m_ObjectiveC_CompilerOptions = default_build_options.ObjectiveC_CompilerOptions ([])
#--- Options for Objective-C++ compiling (.mm extension)
  gmf.m_ObjectiveCpp_CompilerOptions = default_build_options.ObjectiveCpp_CompilerOptions ([])
#--- Run makefile
  gmf.run ()

#----------------------------------------------------------------------------------------------------------------------*


import os
import glob
import torch.utils.data
import numpy as np

class RGBImageSet(torch.utils.data.Dataset):
    def __init__(self, path, centered=False):
        super().__init__()
        self.centered = centered
        self.add_string = lambda a, b: a + b

        assert os.path.exists(path)
        self.base_path = path

        self.mean_image = self.get_mean_image()

        cur_file_paths = glob.glob(self.base_path + '/*.npy')
        cur_file_paths.sort()
        self.file_paths = cur_file_paths

    def __len__(self):
        return len(self.file_paths)

    def __getitem__(self, item):
        data = np.load(self.file_paths[item])
        data = np.transpose(data, (2, 0, 1))
        # (h w c) => (c h w)

        if data.dtype.name == 'uint8':
            data = data.astype(float)

        if self.centered:
            data = torch.FloatTensor(data)
        else:
            data = torch.FloatTensor(data)
            data = data - self.mean_image
            data.div_(255)
        return data

    def get_decenterd_data(self, centered_data):
        result = centered_data.mul_(255) + self.mean_image
        result = result.byte()
        return result

    def get_mean_image(self):
        mean_image = np.load(os.path.join(os.path.dirname(self.base_path), "mean_image.npy"))
        mean_image = np.transpose(mean_image, (2, 0, 1))
        mean_image = torch.from_numpy(mean_image).float()
        return mean_image


# @author: Gautam Patel
# Problem Description URL: https://www.hackerrank.com/challenges/bot-saves-princess---2/problem
#

def findPrincessPos(n, grid):
    for i in range(n):
        for j in range(n):
            if grid[i][j] == 'p':
                return (i, j)
    return (0, 0)

def nextMove(n,r,c,grid):
    pr, pc = findPrincessPos(n, grid)
    dr, dc = r-pr, c-pc
    if dc > 0:
        return ("LEFT" if dc > abs(dr) else "UP" if dr > 0 else "DOWN")
    return ("RIGHT" if abs(dc) > abs(dr) else "UP" if dr > 0 else "DOWN")

n = int(input())
r,c = [int(i) for i in input().strip().split()]
grid = []
for i in range(0, n):
    grid.append(input())

print(nextMove(n,r,c,grid))


from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAdminUser, IsAuthenticated

from core.models import ShoppingCart, ShoppingCartItem, Book
from .serializers import ShoppingCartSerializer, ShoppingCartItemSerializer
from utils.model_tools import get_instance

@api_view(["GET"])
@permission_classes([IsAdminUser, IsAuthenticated])
def list_shopping_carts(request):
    """
    Get all shoppingcarts in dabatabe
    """

    queryset = ShoppingCart.objects.all()
    serializer = ShoppingCartSerializer(queryset, many=True)
    return Response(serializer.data, status=status.HTTP_200_OK)

@api_view(["POST"])
def add_item_to_cart(request):
    """
    Add a book in the user cart
    """

    try:
        book_id = int(request.data.get("book_id", ''))
        quantity = request.data.get("quantity", '')
    except ValueError:
        return Response({
            "error": "The 'book_id' and 'quantity' must be intengers values."
        }, status=status.HTTP_400_BAD_REQUEST)

    exist, result = get_instance(Book, pk=book_id)
    if not exist:
        return result

    cart = ShoppingCart.objects.get(user=request.user)

    if cart.items.filter(book=result).exists():
        existent_item = cart.items.get(book=result)
        existent_item.quantity = quantity
        existent_item.save()
    else:
        item = ShoppingCartItem.objects.create(book=result, quantity=quantity)
        cart.items.add(item)

    serializer = ShoppingCartSerializer(cart)
    return Response(serializer.data, status=status.HTTP_200_OK)

@api_view(["DELETE"])
def remove_item_from_cart(request, item_id):
    """
    Remove specified item from user cart
    """

    cart = ShoppingCart.objects.get(user=request.user)
    if not cart.items.filter(pk=item_id).exists():
        return Response({
            "error": "The item '{0}' is not in the cart.".format(item_id)
        }, status=status.HTTP_404_NOT_FOUND)

    item = cart.items.get(pk=item_id)
    item.delete()
    serializer = ShoppingCartSerializer(cart)
    return Response(serializer.data, status=status.HTTP_200_OK)

@api_view(["GET"])
def get_shopping_cart(request):
    """
    Get shopping cart of the current user
    """

    cart = ShoppingCart.objects.get(user=request.user)
    serializer = ShoppingCartSerializer(cart)
    return Response(serializer.data, status=status.HTTP_200_OK)

@api_view(["GET"])
def get_user_cart_items(request):
    """
    Get all user shoppingcart items in database
    """

    cart = ShoppingCart.objects.get(user=request.user)
    serializer = ShoppingCartItemSerializer(cart.items, many=True)
    return Response(serializer.data, status=status.HTTP_200_OK)

@api_view(["PUT"])
def update_cart_item(request):
    """
    Update a shoppingcart item
    """

    try:
        item_id = int(request.data.get("item_id", ''))
        quantity = int(request.data.get("quantity", ''))
    except ValueError:
        return Response({
            "error": "The 'item_id' and 'quantity' must be intengers values."
        }, status=status.HTTP_400_BAD_REQUEST)

    cart = ShoppingCart.objects.get(user=request.user)
    item = cart.items.filter(id=item_id)
    if not item.exists():
        return Response({
            "error": "This item does not exists in the cart."
        }, status=status.HTTP_400_BAD_REQUEST)

    item.update(quantity=quantity)
    serializer = ShoppingCartSerializer(cart)

    return Response(serializer.data, status=status.HTTP_200_OK)


'''
@Author: grehex
@Date: 2020-03-29 16:42:13
@LastEditTime: 2020-03-30 15:33:26
'''

import socket
import time
import struct

addr = ("", 8888)
server = socket.create_server(addr)

print(f'[*] server is listening on {addr[1]}')
while True:
    client, client_addr = server.accept()
    print(client_addr)
    rev_msg = str(client.recv(1024), encoding='utf8')
    print(rev_msg)
    # header = b'\x40\x00\x00\x00hello'
    header = struct.pack('<Is', 0x40, b'A' * 64)
    client.send(header)
    time.sleep(10)
    send_msg = 'AAA'
    while True:
        client.send(bytes(send_msg, encoding='utf8'))
        time.sleep(1)
        print('send success!')
client.close()