import numpy as np
import pandas as pd
import tensorflow as tf
import tensorflow.keras as keras
import cv2 as cv
from tensorflow.keras.optimizers import RMSprop, Adam
from tensorflow.keras.preprocessing.image import ImageDataGenerator

datagen = ImageDataGenerator(rescale=1./255)
train_datagen = datagen.flow_from_directory('../input/garbage-classification/Garbage classification/Garbage classification/',
                           target_size=(300, 300),
                           batch_size=128,
                           class_mode='categorical')

model = tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(64, (3,3), activation='relu', input_shape=(300, 300, 3)),
    tf.keras.layers.MaxPooling2D((2,2)),
    tf.keras.layers.Conv2D(32, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    tf.keras.layers.Conv2D(16, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(512, activation='relu'),
    tf.keras.layers.Dense(6, activation='softmax')
])

model.compile(loss='categorical_crossentropy',
              optimizer=Adam(learning_rate=0.003),
              metrics=['accuracy'])

history = model.fit(
      train_datagen,
      steps_per_epoch=8,
      epochs=40,
      verbose=1)

model.save('trash_module.h5')


# from django import forms
# from .models import Article

# # from account.mixins import FieldsMixin

# class ArticleAddForm(forms.ModelForm):
#    class Meta:
#        model = Article
#        fields = '__all__' # Include all fields from the model

from django import forms
from .models import Article

class ArticleAddForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        # Extract the 'fields' argument from kwargs
        fields_arg = kwargs.pop('fields', None)

        # Call the parent class's __init__ method
        super().__init__(*args, **kwargs)

        # Update the 'fields' attribute based on the 'fields' argument
        if fields_arg:
            self.fields = {field_name: self.fields[field_name] for field_name in fields_arg}

    class Meta:
        model = Article
        fields = '__all__'  # Default fields option, can be overridden dynamically


import unittest
import sys

DATA_STRUCTURE_DIR = '../..'
sys.path.append(DATA_STRUCTURE_DIR)

from find_intersection import find_intersection
from LinkedList import LinkedList

class FindIntersectionTest(unittest.TestCase):
    def setUp(self):
        self.lst1 = LinkedList()
        self.lst2 = LinkedList()
        self.common_lst = LinkedList()

        self.lst1.insert(4)
        self.lst1.insert(2)
        self.lst1.insert(5)
        self.lst1.insert(8)
        self.lst1.insert(6)

        self.lst2.insert(3)
        self.lst2.insert(10)
        self.lst2.insert(8)

        self.common_lst.insert(3)
        self.common_lst.insert(2)
        self.common_lst.insert(5)
        self.common_lst.insert(7)

        current = self.lst1.head
        while current.get_next():
            current = current.get_next()
        current.set_next(self.common_lst.head)

        current = self.lst2.head
        while current.get_next():
            current = current.get_next()
        current.set_next(self.common_lst.head)

    def test_find_intersection(self):
        lst = find_intersection(self.lst1, self.lst2)
        self.assertEqual(lst.size(), 4)
        self.assertEqual(lst.head.get_data(), 7)
        self.assertEqual(lst.head.get_next().get_data(), 5)

    def test_find_intersection_no_common(self):
        lst1 = LinkedList()
        lst2 = LinkedList()
        lst1.insert(4)
        lst1.insert(3)
        lst1.insert(2)
        lst1.insert(1)

        lst2.insert(4)
        lst2.insert(3)
        lst2.insert(2)

        lst = find_intersection(lst1, lst2)
        self.assertEqual(lst, None)


#ACRONYM HE
k = int(input())
dislikeWords =[]
for i in range(k):
    dislikeWords = dislikeWords + [str(input())]
#print(dislikeWords)
n = int(input())
sentence = str(input())
sentence = sentence.split()
for i in range(k):
    if sentence.count(dislikeWords[i])>=1:
        sentence.remove(dislikeWords[i])
#print(sentence)
acr = ""
for i in range(len(sentence)-1):
    #print(sentence[i][0].upper())
    acr = acr + sentence[i][0].upper() + '.'
    #print(acr)
acr = acr + sentence[len(sentence)-1][0].upper()
print(acr)


from flask import Flask, render_template, request, redirect, jsonify, json, abort,g
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from pixdb_setup import Photos, Events, User, Base

from flask_httpauth import HTTPBasicAuth
import json

#NEW IMPORTS
from oauth2client.client import flow_from_clientsecrets
from oauth2client.client import FlowExchangeError
import httplib2
from flask import make_response
import requests

auth = HTTPBasicAuth()

app = Flask(__name__)

engine = create_engine('postgresql+psycopg2://postgres:XxxAahSn@2*5@localhost/pixtest')
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
session = DBSession()

# Create anti-forgery state token
@app.route('/login')
def showLogin():
    state = ''.join(random.choice(string.ascii_uppercase + string.digits)
                    for x in range(32))
    login_session['state'] = state
    return "The current session state is %s" % login_session['state']

@auth.verify_password
def verify_password(emailid_or_token, username):
    #Try to see if it's a token first
    user_email_id = User.verify_auth_token(emailid_or_token)
    if user_email_id:
        user = session.query(User).filter_by(email_id = user_email_id).one()
    else:
        user = session.query(User).filter_by(email_id = emailid_or_token).first()
        if not user:
            return False
    g.user = user
    return True

@app.route('/token')
@auth.login_required
def get_auth_token():
    token = g.user.generate_auth_token()
    return jsonify({'token': token.decode('ascii')})

@app.route('/users/<username>/<email_id>', methods = ['POST'])
def new_user(username,email_id):
    #username = request.json.get('username')
    #email_id = request.json.get('email_id')
    if username is None or email_id is None:
        print ("missing arguments")
        abort(400)

    if session.query(User).filter_by(email_id = email_id).first() is not None:
        print ("existing user")
        user = session.query(User).filter_by(username=username).first()
        return jsonify({'message':'user already exists'}), 200#, {'Location': url_for('get_user', id = user.id, _external = True)}

    user = User(email_id = email_id,username = username)
    #user.hash_password(password)
    session.add(user)
    session.commit()
    return jsonify({ 'email_id': user.email_id }), 201#, {'Location': url_for('get_user', id = user.id, _external = True)}

@app.route('/api/users/<email_id>')
def get_user(email_id):
    user = session.query(User).filter_by(email_id=email_id).one()
    if not user:
        abort(400)
    return jsonify({'username': user.username})

@app.route('/api/resource')
@auth.login_required
def get_resource():
    return jsonify({ 'data': 'Hello, %s!' % g.user.username })

## To get the events associated witha particular user ##
@app.route('/pixget/<email_id>/elist')
def dataJSON_get(email_id):
	hosted_events = session.query(Events.code_id).filter_by(event_email_id =email_id).all()
	as_guest = session.query(User.guest_code_id).filter_by(email_id =email_id).all()
	#return jsonify({'event_email_id': hosted_events}) This works
	return jsonify({'guest_code_id': as_guest, 'hosted_events': hosted_events})

## To check if an event id guest entered exists##
@app.route('/pixget/<event_id>/event')
def dataJSON_getEventCheck(event_id):
	event_e = session.query(Events).filter_by(code_id=event_id)
	if event_e is not None:
		checked = 1
		return str(checked)
	else:
		return

@app.route('/pixpost/events/<email_id>', methods = ['GET', 'POST'])
def dataJSON_post(email_id):
	if request.method == 'GET':
    # RETURN ALL DATA IN DATABASE
		user_d = session.query(User).filter_by(email_id =email_id)
		items = session.query(Events).filter_by(event_email_id =email_id)
		return jsonify(Events=[i.serialize for i in items])

	elif request.method == 'POST':
    # MAKE A NEW DATA COLUMN AND STORE IT IN DATABASE
        #if request.headers['Content-Type'] == 'application/json':
		user_i = session.query(User).filter_by(email_id =email_id).one()
		tempo =request.json["code_id"]
		starr = []
		starr.append(tempo)
		if user_i.admin_code_id is not None:
			user_i.admin_code_id = starr + user_i.admin_code_id
		else:
			user_i.admin_code_id = starr
		#return ''.join(user_i.admin_code_id)
		session.commit()
		data_item = Events(code_id = request.json["code_id"], event_type = request.json["event_type"], album_name = request.json["album_name"],
        	event_date= request.json["event_date"], event_loc= request.json["event_loc"],bucket_link= request.json["bucket_link"],
        	event_email_id=user_i.email_id)
		session.add(data_item)
		session.commit()
		items = session.query(Events).all()
		return jsonify(Events=[i.serialize for i in items])

@app.route('/pixget/photos/<event_id>/count')
def dataJSON_getPhotoCount(event_id):
	#event = session.query(Events).filter_by(code_id=event_id).one()
	photos_e = session.query(Photos).filter_by(photo_code_id=event_id)
	tempo = photos_e.count()
	if tempo == 0:
		return
	else:
		return str(photos_e.count())
    #items = session.query(Photos).all()
    #return jsonify(Photos=[i.serialize for i in items])

@app.route('/pixpost/photos/<event_id>', methods = ['GET', 'POST'])
def dataJSON_postPhotos(event_id):
	if request.method == 'GET':
    # RETURN ALL DATA IN DATABASE
		event = session.query(Events).filter_by(code_id=event_id).one()
		photos_e = session.query(Photos).filter_by(photo_code_id=event.code_id)
		return jsonify(Photos=[i.serialize for i in photos_e])
		#return str(photos_e.count())

	elif request.method == 'POST':
    # MAKE A NEW DATA COLUMN AND STORE IT IN DATABASE
        #if request.headers['Content-Type'] == 'application/json':
		photo1 = Photos(photo_code_id = event_id, image_url = request.json["image_url"])
		session.add(photo1)
		session.commit()
		event = session.query(Events).filter_by(code_id=event_id).one()
		photos_e = session.query(Photos).filter_by(photo_code_id=event.code_id)
		return jsonify(Photos=[i.serialize for i in photos_e])
		#items = session.query(Photos).all()
    	#return jsonify(Photos=[i.serialize for i in items])

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


from django.urls import path, re_path
from django.conf.urls import url
from .views import CategoryList, CategoryImage, FetchProvidersByCategory, \
    FetchAvailableTimeSlot, UserAppVersion, UserNotifications
from django.views.generic import TemplateView

urlpatterns = [
    path('service_list/', CategoryList.as_view(), name='services'),
    path('available_time_slot/', FetchAvailableTimeSlot.as_view(), name='available_time_slot'),
    path('providers_by_categories/<int:category_id>/', FetchProvidersByCategory.as_view(),
         name='providers_by_categories'),
    re_path(r'^uploads/catagories/(?P<filename>[-\w_\\-\\.]+)$', CategoryImage.as_view(),
            name='category_image-download'),
    path('notification/', UserNotifications.as_view(), name='add_notification'),
    path('appversion/', UserAppVersion.as_view(), name='add_notification'),
    path('privacy_policy/',TemplateView.as_view(template_name='policy.html'))
]


from app.models import db, Cart, environment, SCHEMA
from sqlalchemy.sql import text

def seed_carts():

    cart1 = Cart(
        user_id = 1,
        total_price=4.95
    )

    cart2 = Cart(
        user_id=2,
        total_price=2.95
    )

    cart3 = Cart(
        user_id=3,
        total_price=5.59
    )

    cart4 = Cart(
        user_id=4,
        total_price=5.59
    )

    all_carts = [cart1, cart2, cart3, cart4]
    add_carts = [db.session.add(cart) for cart in all_carts]
    db.session.commit()

    return all_carts

def undo_carts():
    if environment == "production":
        db.session.execute(
            f"TRUNCATE table {SCHEMA}.carts RESTART IDENTITY CASCADE;")
    else:
        db.session.execute(text("DELETE FROM carts"))

    db.session.commit()


import pandas as pd
from sklearn.preprocessing import StandardScaler
import pickle
import random
import numpy as np
import pywt
import os

train_df = pd.read_csv('./data/train.csv')
print('done')

# def get_signal_features(df_segment, window_size):
#     df = pd.DataFrame(index=range(150000/window_size    ), dtype=np.float64)
#     fft = np.fft.fft(df_segment.acoustic_data)
#     realFFT = np.real(zc)
#     imagFFT = np.imag(zc)
#     df['Rmean'] = realFFT.mean()
#     X.loc[seg_id, 'Rstd'] = realFFT.std()
#     X.loc[seg_id, 'Rmax'] = realFFT.max()
#     X.loc[seg_id, 'Rmin'] = realFFT.min()
#     X.loc[seg_id, 'Imean'] = imagFFT.mean()
#     X.loc[seg_id, 'Istd'] = imagFFT.std()
#     X.loc[seg_id, 'Imax'] = imagFFT.max()
#     X.loc[seg_id, 'Imin'] = imagFFT.min()
# scaler = StandardScaler(copy=False)
# train_df['acoustic_data'] = scaler.fit_transform(train_df['acoustic_data'].values.reshape(-1, 1))

#eval_index = list(np.random.permutation([i for i in range(4194)]))[:838]

import matplotlib.pyplot as plt
train_labels = dict()
eval_labels = dict()
prev_is_eval = False
for i in range(4194*2 - 838*2):
    train_labels['signal_' + str(i) + '.csv'] = train_df['time_to_failure'].iloc[i*75000 + 150000]
    wave = train_df['acoustic_data'].iloc[i*75000: i*75000 + 150000]

    fft = np.fft.fft(df_segment.acoustic_data)

    realFFT = np.real(fft)
    imagFFT = np.imag(fft)
    for i in range(1000):
        x = wave.values[150*i: 150*i + 150]
        r = realFFT[150*i: 150*i + 150]
        i = imagFFT[150*i: 150*i + 150]
        df['mean'] = x.mean()
        df['max'] = x.max()
        df['min'] = x.min()
        df['std'] = x.std()
        df['Rmean'] = r.mean()
        df['Rstd'] = r.std()
        df['Rmax'] = r.max()
        df['Rmin'] = r.min()
        df['Imean'] = i.mean()
        df['Istd'] = i.std()
        df['Imax'] = i.max()
        df['Imin'] = i.min()

    #train_df['acoustic_data'].iloc[i*75000: i*75000 + 150000].to_csv('./data/15000_processed_data/train/signal_' + str(i) + '.csv', index=False, header=False)

for i in range(4194*2 - 838*2, 4194*2 - 1, 1):
    eval_labels['signal_' + str(i) + '.csv'] = train_df['time_to_failure'].iloc[i*75000 + 150000]
    train_df['acoustic_data'].iloc[i*75000: i*75000 + 150000].to_csv('./data/15000_processed_data/eval/signal_' + str(i) + '.csv', index=False, header=False)

with open('./data/15000_processed_data/eval_labels.pkl', 'wb') as f:
    pickle.dump(eval_labels, f, protocol=2)
# with open('./data/15000_processed_data/train_labels.pkl', 'wb') as f:
#     pickle.dump(train_labels, f, protocol=2)


import matplotlib.pyplot as plt
import numpy as np
import math
from matplotlib.ticker import FuncFormatter

w200 = np.load('data/da/rugosidade20.npy')

x = np.array(range(len(w200)))
y = w200

print(y);

titulo = 'Deposição Aleatória'
eixox ='Tempo (t)'
eixoy = 'Rugosidade w(L,t)'

plt.title(titulo)
plt.xlabel(eixox)
plt.ylabel(eixoy)

plt.plot(x,y,label='Substrato {0}'.format(200))
plt.legend()
plt.yscale('log')
plt.xscale('log')

plt.show()
# plt.savefig('data/da/' + titulo + '.png', dpi=300)


import sys
from os import system
from os.path import isfile
from time import sleep
red = '\033[1;31m'

print(" ")
print(" ")
sleep(2)

FILE = "face_cracker.py"
def protect():

    if not isfile(FILE):
        print(f'{red}[!] Somethings Error...!')
        sleep(2)
        sys.exit()

def is_banner():
    try:
        from face_cracker import Banner, banner
    except ImportError as f:
        print(" ")
        print(f'{red}[!] Somthings Error')
        sys.exit()
if __name__ == "__main__":
    protect()
    is_banner()


#!/usr/bin/env python3
"""
Author      : Madhu Babu Kencha
Created on  : 14-sept-2018

1) This program demonstrate how to specify short options
"""
import argparse

def main():
	parser = argparse.ArgumentParser()
	# This means that, if the option is specified, assign the value True to args.verbose
	parser.add_argument( "-v", "--verbosity", help = "Increases the verbosity of output", \
		                 action="store_true" )
	args = parser.parse_args()
	if args.verbosity:
		print( "Verbosity is on" )

if __name__ == '__main__':
	main()


import dataclasses
import io
import tempfile
import typing
import unittest

from arcaflow_plugin_sdk import plugin

@dataclasses.dataclass
class StdoutTestInput:
    pass

@dataclasses.dataclass
class StdoutTestOutput:
    pass

@plugin.step(
    "stdout-test",
    "Stdout test",
    "A test for writing to stdout.",
    {"success": StdoutTestOutput},
)
def stdout_test_step(
    input: StdoutTestInput,
) -> typing.Tuple[str, StdoutTestOutput]:
    print("Hello world!")
    return "success", StdoutTestOutput()

class StdoutTest(unittest.TestCase):
    def test_capture_stdout(self):
        s = plugin.build_schema(stdout_test_step)
        tmp = tempfile.NamedTemporaryFile(suffix=".json")

        def cleanup():
            tmp.close()

        self.addCleanup(cleanup)
        tmp.write(bytes("{}", "utf-8"))
        tmp.flush()

        i = io.StringIO()
        o = io.StringIO()
        e = io.StringIO()
        exit_code = plugin.run(
            s, ["test.py", "-f", tmp.name, "--debug"], i, o, e
        )
        self.assertEqual(0, exit_code)
        self.assertEqual("Hello world!\n", e.getvalue())

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


import os
import re
from collections import defaultdict

from pathlib import Path

def process_input(input_path):
    mapping = {}
    with open(input_path, "r") as input_file:
        for line in input_file:
            signal = line.strip()
            match = re.match(r"Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)", signal)
            if match:
                sx, sy, bx, by = map(int, match.groups())
                mapping[(sx, sy)] = (bx, by)
    return mapping

def calculate_distances(mapping):
    distances = {}
    for (sx, sy), (bx, by) in mapping.items():
        distances[(sx, sy)] = abs(sx - bx) + abs(sy - by)
    return distances

def apply_coverage(distances, beacons_map):
    min_i, min_j, max_i, max_j = 1000, 1000, -1000, -1000
    coverage_grid = defaultdict(lambda: defaultdict(lambda: "."))
    for (sj, si), distance in distances.items():
        for idx in range(-distance, distance + 1):
            for jdx in range(-distance, distance + 1):
                if abs(idx) + abs(jdx) > distance:
                    continue

                _i = si + idx
                _j = sj + jdx
                coverage_grid[_i][_j] = "#"

                min_i, min_j = min(min_i, _i), min(min_j, _j)
                max_i, max_j = max(max_i, _i), max(max_j, _j)

    for (sj, si), (bj, bi) in beacons_map.items():
        coverage_grid[si][sj] = "S"
        coverage_grid[bi][bj] = "B"

    return coverage_grid, min_i, min_j, max_i, max_j

def visualize(grid, coverage_grid, min_i, min_j, max_i, max_j):
    for idx in range(min_i, max_i + 1):
        print(f"{idx}:", end="")
        for jdx in range(min_j, max_j + 1):
            if (jdx, idx) in grid:
                print("S", end="")
            else:
                print(coverage_grid[idx][jdx], end="")
        print()

if __name__ == "__main__":
    input_path = os.path.join(Path(__file__).parent.absolute(), "input.txt")

    sensor_beacon_map = process_input(input_path)
    sensor_beacon_distance = calculate_distances(sensor_beacon_map)
    coverage_grid, min_i, min_j, max_i, max_j = apply_coverage(sensor_beacon_distance, sensor_beacon_map)

    query_row = 2000000
    count = 0
    row = coverage_grid[query_row]
    for value in row.values():
        if value == "#":
            count += 1
    # visualize(sensor_beacon_map, coverage_grid, min_i, min_j, max_i, max_j)
    print("1: ", count, min_j, max_j)


from PyQt5.QtWidgets import QMainWindow
from PyQt5 import QtCore
from qt_designer.visual_interface import Ui_MainWindow
from cpf_app import CpfApp

class App(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()

        self.setupUi(self)

        self.cpf_app = CpfApp('')

        self.linedit_display.setReadOnly(True)

        self.btn_generate_cpf.clicked.connect(self.generate_cpf)

        self.btn_validate_cpf.clicked.connect(self.validate_cpf)

        self.btn_reset.clicked.connect(self.reset_app)

        self.linedit_display.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)

        self.linedit_cpf.setInputMask('999.999.999-99')

        self.DISPLAY_COLOR_NORMAL = '#888888'
        self.DISPLAY_COLOR_VALID_CPF = '#5bff5d'
        self.DISPLAY_COLOR_INVALID_CPF = '#ff5f5b'

        self.DISPLAY_TEXT_NORMAL = 'Enter the cpf...'
        self.DISPLAY_TEXT_VALID_CPF = 'Valid cpf.'
        self.DISPLAY_TEXT_INVALID_CPF = 'Invalid cpf.'

        self.reset_app()

    def generate_cpf(self):
        self.cpf_app.generate_cpf()
        self.linedit_cpf.setText(self.cpf_app.cpf)

    def validate_cpf(self):

        if len(self.linedit_cpf.text()) < 11:
            self.display_show('invalid', msg = 'Cpf must have 11 digits.')
            return

        validation = CpfApp.validate_cpf(self.linedit_cpf.text())

        if validation:
            self.display_show('valid')
        else:
            self.display_show('invalid')

    def display_show(self, result, msg = None):

        if result == 'valid':
            self.linedit_display.setStyleSheet(f'background-color: {self.DISPLAY_COLOR_VALID_CPF}')
            self.linedit_display.setText(self.DISPLAY_TEXT_VALID_CPF)
        elif result == 'invalid':
            self.linedit_display.setStyleSheet(f'background-color: {self.DISPLAY_COLOR_INVALID_CPF}')

            if msg:
                self.linedit_display.setText(msg)
            else:
                self.linedit_display.setText(self.DISPLAY_TEXT_INVALID_CPF)

        else:
            self.linedit_display.setStyleSheet(f'background-color: {self.DISPLAY_COLOR_NORMAL}')
            self.linedit_display.setText(self.DISPLAY_TEXT_NORMAL)

    def reset_app(self):
        self.linedit_cpf.setText('')
        self.display_show('normal')


import Tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self):
        # Instantiate GUI objects
        tk.Tk.__init__(self)
        self.v = tk.StringVar()
        self.entry = tk.Entry(self, textvariable=self.v)
        self.button = tk.Button(self, text="Get", command=self.on_button)
        self.text = tk.Text()

        # Configure text box
        self.text.config(width=100, height=30, state=tk.DISABLED)
        self.text.bind('<Button-1>', self.empty)

        # Bind the return key to submit whatever text is present
        self.bind('<Return>', self.on_button)

        # Pack GUI elements together
        self.button.pack(side=tk.BOTTOM)
        self.entry.pack(side=tk.BOTTOM)
        self.text.pack(side=tk.TOP)

    def on_button(self,*args):
        #print self.entry.get()
        self.text.config(state=tk.NORMAL)
        self.text.insert(tk.END,self.entry.get()+'\n')
        self.v.set('')
        self.text.config(state=tk.DISABLED)

    def empty(self, *args):
        return 'break'

app = SampleApp()
app.mainloop()


from payment_status import PaymentStatus

class Payment:
	def __init__(self, payment_status, payment_date, stripe_payment_id, amount):
		self.payment_status = PaymentStatus(payment_status)
		self.payment_date = payment_date
		self.stripe_payment_id = stripe_payment_id
		self.amount = amount

	def to_dict(self):
		return {
			'paymentStatus': self.payment_status.value,
			'paymentDateTimestamp': self.payment_date.timestamp() * 1000 if self.payment_date else None,
			'stripePaymentId': self.stripe_payment_id,
			'amount': self.amount
		}


# -*- coding: utf-8 -*-
"""
ICIAR2018 - Grand Challenge on Breast Cancer Histology Images
https://iciar2018-challenge.grand-challenge.org/home/
"""
import openslide

import xml.etree.ElementTree as ET
import numpy as np
from scipy.misc import imsave
import cv2
import os
import argparse
from multiprocessing import Pool
import multiprocessing
import itertools
import argparse
import glob
from PIL import Image

def get_connected_components(img):
    img = cv2.cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1]  # ensure binary
    num_labels, labels_im = cv2.connectedComponents(img)
    return num_labels,labels_im

def readXML(filename):

    tree = ET.parse(filename)

    root = tree.getroot()
    regions = root[0][1].findall('Region')

    pixel_spacing = float(root.get('MicronsPerPixel'))

    labels = []
    coords = []
    length = []
    area = []

    for r in regions:
        area += [float(r.get('AreaMicrons'))]
        length += [float(r.get('LengthMicrons'))]
        try:
            label = r[0][0].get('Value')
        except:
            label = r.get('Text')
        if 'benign' in label.lower():
            label = 1
        elif 'in situ' in label.lower():
            label = 2
        elif 'invasive' in label.lower():
            label = 3

        labels += [label]
        vertices = r[1]
        coord = []
        for v in vertices:
            x = int(v.get('X'))
            y = int(v.get('Y'))
            # print("(X,Y)",x,y)
            coord += [[x,y]]

        coords += [coord]

    return coords,labels,length,area,pixel_spacing

def get_masked_img(image_size,coordinates,labels):
    #red is 'benign', green is 'in situ' and blue is 'invasive'
    colors = [(0,0,0),(255,0,0),(0,255,0),(0,0,255)]

    img = np.zeros(image_size,dtype=np.uint8)

    for c,l in zip(coordinates,labels):
        img1 = fillImage(img,[np.int32(np.stack(c))],color=colors[l])
    return img1

def fillImage(image, coordinates,color=255):
    cv2.fillPoly(image, coordinates, color=color)
    return image

def save_labels_for_patch(patch_mask,patch,patch_np,file_name,r,c):
    label_wise_save_directory = args.save_path
    classes = ['Normal', 'Benign', 'InSitu', 'Invasive', 'Benign_InSitu', 'Benign_Invasive', 'InSitu_Invasive', 'Benign_InSitu_Invasive']
    reqd_path = {}
    for i,cl in enumerate(classes):
        reqd_path[cl] = os.path.join(label_wise_save_directory,cl,file_name)
        os.makedirs(reqd_path[cl],exist_ok=True)
        if i<4:
            reqd_path[cl+"_impure"] = os.path.join(label_wise_save_directory,cl+"_impure",file_name)
            os.makedirs(reqd_path[cl+"_impure"],exist_ok=True)
    stats = np.unique(patch_mask,return_counts=True)
    stats_R = np.unique(patch_mask[:,:,0],return_counts=True)
    stats_G = np.unique(patch_mask[:,:,1],return_counts=True)
    stats_B = np.unique(patch_mask[:,:,2],return_counts=True)
    if len(stats[0])==1 and stats[0] == 0 :
        fp = reqd_path['Normal']+'/{}_X_{}_Y.png'.format(r,c)
        patch.save(fp)
    else:
        if len(stats_R[0])==1 and  stats_R[0] == 255:
            fp = reqd_path['Benign']+'/{}_X_{}_Y.png'.format(r,c)
            patch.save(fp)
        elif len(stats_G[0])==1 and  stats_G[0] == 255:
            fp = reqd_path['InSitu']+'/{}_X_{}_Y.png'.format(r,c)
            patch.save(fp)
        elif len(stats_B[0])==1 and stats_B[0] == 255:
            fp = reqd_path["Invasive"]+'/{}_X_{}_Y.png'.format(r,c)
            patch.save(fp)
        else:
            if len(stats_R[0])>1 and len(stats_G[0])>1 and len(stats_B[0])>1 :
                fp = reqd_path['Benign_InSitu_Invasive']+'/{}_X_{}_Y.png'.format(r,c)
                patch.save(fp)
            elif len(stats_R[0])>1 and len(stats_G[0])>1 :
                fp = reqd_path['Benign_InSitu']+'/{}_X_{}_Y.png'.format(r,c)
                patch.save(fp)
            elif len(stats_R[0])>1 and len(stats_B[0])>1:
                fp = reqd_path['Benign_Invasive']+'/{}_X_{}_Y.png'.format(r,c)
                patch.save(fp)
            elif len(stats_G[0])>1 and len(stats_B[0])>1:
                fp = reqd_path['InSitu_Invasive']+'/{}_X_{}_Y.png'.format(r,c)
                patch.save(fp)
            elif len(stats_R[0])>1:
                purity = stats_R[1][1]/(256*256)
                if purity>=0.45:
                    fp = reqd_path['Benign']+'/{}_X_{}_Y.png'.format(r,c)
                    patch.save(fp)
                else:
                    fp = reqd_path['Benign_impure']+'/{}_X_{}_Y.png'.format(r,c)
                    patch.save(fp)

            elif len(stats_G[0])>1:
                purity = stats_G[1][1]/(256*256)
                if purity>=0.45:
                    fp = reqd_path['InSitu']+'/{}_X_{}_Y.png'.format(r,c)
                    patch.save(fp)
                else:
                    fp = reqd_path['InSitu_impure']+'/{}_X_{}_Y.png'.format(r,c)
                    patch.save(fp)
            elif len(stats_B[0])>1:
                purity = stats_B[1][1]/(256*256)
                if purity>=0.45:
                    fp = reqd_path['Invasive']+'/{}_X_{}_Y.png'.format(r,c)
                    patch.save(fp)
                else:
                    fp = reqd_path['Invasive_impure']+'/{}_X_{}_Y.png'.format(r,c)
                    patch.save(fp)

            else:
                print("total stats",stats)
                print("R stats",stats_R)
                print("G stats",stats_G)
                print("B stats",stats_B)

def save_patches_256(slide_file,xml_file):
    label_wise_save_directory = args.save_path
    whiteness_limit = 210
    blackness_limit = 5
    max_faulty_pixels = 0.8
    min_conn_comp = 10
    scan = openslide.OpenSlide(slide_file)
    orig_w,orig_h = scan.level_dimensions[0]
    file_name = slide_file.split('/')[-1].split('.')[0]
    patch_size = 256
    dims = scan.dimensions
    img_size = (dims[1],dims[0],3)

    coords,labels,length,area,pixel_spacing = readXML(xml_file)
    masked_img = get_masked_img(img_size,coords,labels)
    os.makedirs("/ssd_scratch/cvit/ashishmenon/ICIAR2018_reconstructed_slides/",exist_ok=True)

    # slide_img_to_be_saved = np.ones((orig_w,orig_h,3),dtype=np.uint8)*240
    # masked_img_to_be_saved = np.zeros(masked_img.shape,dtype=np.uint8)
    # for r in range(0,orig_w,patch_size):
    #     for c in range(0, orig_h,patch_size):
    #         if c+patch_size > orig_h and r+patch_size<= orig_w:
    #             p = orig_h-c
    #             pp = patch_size

    #         elif c+patch_size <= orig_h and r+patch_size > orig_w:
    #             p = patch_size
    #             pp = orig_w-r

    #         elif  c+patch_size > orig_h and r+patch_size > orig_w:
    #             p = orig_h-c
    #             pp = orig_w-r

    #         else:
    #             p = patch_size
    #             pp = patch_size
    #         patch_to_be_saved = np.swapaxes(np.array(scan.read_region((r,c),0,(p,pp)),dtype=np.uint8)[...,0:3],1,0)
    #         patch_mask = masked_img[c:c+p,r:r+pp]
    #         is_white = np.all([patch_to_be_saved[:,:,i]>whiteness_limit for i in range(3)], axis=0)
    #         is_black = np.all([patch_to_be_saved[:,:,i]<blackness_limit for i in range(3)], axis=0)
    #         num_labels, labels_im = get_connected_components(patch_to_be_saved)
    #         if np.sum(is_white+is_black)>patch_size*patch_size*max_faulty_pixels and num_labels<min_conn_comp:
    #             continue
    #         else:
    #             masked_img_to_be_saved[c:c+p,r:r+pp] = patch_mask
    #             slide_img_to_be_saved[r:r+pp,c:c+p] = patch_to_be_saved
    #             save_labels_for_patch(patch_mask,patch_to_be_saved,file_name,r,c)

    upscale_factor = 1
    patch_size_upscaled = upscale_factor*patch_size
    W,H = orig_w-orig_w%patch_size_upscaled,orig_h-orig_h%patch_size_upscaled
    # slide_img_to_be_saved = np.zeros((W//upscale_factor,H//upscale_factor,3),dtype=np.uint8)
    # masked_img_to_be_saved = np.zeros((H//upscale_factor,W//upscale_factor,3),dtype=np.uint8)
    for r in range(0,W//upscale_factor,patch_size):
        for c in range(0, H//upscale_factor,patch_size):
            print(r,c)
            patch = scan.read_region(location=(upscale_factor*r,upscale_factor*c), level=0, \
                        size=(patch_size_upscaled,patch_size_upscaled)).convert('RGB')
            patch = patch.resize((patch_size,patch_size))
            patch_np = np.swapaxes(np.array(patch),1,0)

            patch_mask_upscaled = masked_img[upscale_factor*c:(upscale_factor*c)+patch_size_upscaled,upscale_factor*r:(upscale_factor*r)+patch_size_upscaled]
            try:
                patch_mask = cv2.resize(patch_mask_upscaled, (patch_size, patch_size), interpolation=cv2.INTER_CUBIC)
            except:
                print("Exception",patch_mask_upscaled.shape)
            is_white = np.all([patch_np[:,:,i]>whiteness_limit for i in range(3)], axis=0)
            is_black = np.all([patch_np[:,:,i]<blackness_limit for i in range(3)], axis=0)
            num_labels, labels_im = get_connected_components(patch_np)
            if np.sum(is_white+is_black)>patch_size*patch_size*max_faulty_pixels and num_labels<min_conn_comp:
                continue
            else:
                save_labels_for_patch(patch_mask,patch,patch_np,file_name,r,c)
                # slide_img_to_be_saved[r:r+patch_size,c:c+patch_size] = patch_np
                # masked_img_to_be_saved[c:c+patch_size,r:r+patch_size] = patch_mask

    print("Done completely")
    # Image.fromarray(slide_img_to_be_saved[::8,::8]).save("/ssd_scratch/cvit/ashishmenon/ICIAR2018_reconstructed_slides/"+"{}_resized_8.png".format(file_name))
    # Image.fromarray(masked_img_to_be_saved[::8,::8]).save("/ssd_scratch/cvit/ashishmenon/ICIAR2018_reconstructed_slides/"+"{}_mask_resized_8.png".format(file_name))
    # Image.fromarray(np.swapaxes(slide_img_to_be_saved,1,0)[::8,::8]).save("/ssd_scratch/cvit/ashishmenon/ICIAR2018_reconstructed_slides/"+"{}_resized_8_swapped.png".format(file_name))
    # Image.fromarray(np.swapaxes(masked_img_to_be_saved,1,0)[::8,::8]).save("/ssd_scratch/cvit/ashishmenon/ICIAR2018_reconstructed_slides/"+"{}_mask_resized_8_swapped.png".format(file_name))

if __name__=='__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--dataroot', type=str, default="./")
    parser.add_argument('--save_path', type=str, default='./')

    args = parser.parse_args()

    reqd_patients = ['A01','A02','A03','A04','A05','A06','A07','A08','A09','A10']
    # reqd_patients= [x.split('/')[-1].split('.')[0] for x in slides_list]

    slides_list = glob.glob(args.dataroot+'/*.svs')

    ann_list = glob.glob(args.dataroot+ '/*.xml')

    reqd_ann = [x for x in ann_list if x.split('/')[-1].split('.')[0] in reqd_patients]
    reqd_slides = [x for x in slides_list if x.split('/')[-1].split('.')[0] in reqd_patients]

    reqd_ann.sort()
    reqd_slides.sort()

    print(len(reqd_ann),len(reqd_slides))
    for i in zip(reqd_slides,reqd_ann):
        print(i[0].split('/')[-1],i[1].split('/')[-1])
    pool = Pool(multiprocessing.cpu_count())
    pool.starmap(save_patches_256, zip(reqd_slides,reqd_ann))


import cv2
import cv2.aruco as aruco
import numpy as np

def findArucoMarkers(img, markerSize=6, totalMarkers=250, draw=True):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    key = getattr(aruco, f'DICT_5X5_250')
    arucoDict = aruco.Dictionary_get(key)
    arucoParam = aruco.DetectorParameters_create()
    corners, ids, rejected = aruco.detectMarkers(gray, arucoDict, parameters=arucoParam)

    if len(corners) > 0:
        ids = ids.flatten()

        for (markerCounter, markerID) in zip(corners, ids):
            corners = markerCounter.reshape((4,2))
            (tl, tr, br, bl) = corners

            tr = (int(tr[0]), int(tr[1]))
            tl = (int(tl[0]), int(tl[1]))
            bl = (int(bl[0]), int(bl[1]))
            br = (int(br[0]), int(br[1]))

            cv2.putText(img, str(markerID), tl,cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), 2, cv2.LINE_AA)

cap = cv2.VideoCapture(0)

while True:
    check, frame = cap.read()

    if check:
        findArucoMarkers(frame)
        cv2.imshow("image", frame)

    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break
cap.release()
cv2.destroyAllWindows()


from ctypes import Array, c_char_p, c_void_p
from dataclasses import dataclass
from enum import IntEnum
from typing import Any, Dict, Mapping, Optional, Union

import numpy as np

from power_grid_model.core.error_handling import VALIDATOR_MSG
from power_grid_model.core.index_integer import IdxC, IdxNp
from power_grid_model.core.power_grid_core import AttributePtr, ComponentPtr, DatasetPtr, IdxPtr
from power_grid_model.core.power_grid_core import power_grid_core as pgc

# constant enum for ctype
# pylint: disable=invalid-name
class PGMCType(IntEnum):
    """enumeration for ctype"""

    int32 = 0
    int8 = 1
    double = 2
    double3 = 3

_CTYPE_NUMPY_MAP = {PGMCType.double: "f8", PGMCType.int32: "i4", PGMCType.int8: "i1", PGMCType.double3: "(3,)f8"}
_ENDIANNESS = "<" if pgc.is_little_endian() == 1 else ">"
_NAN_VALUE_MAP = {
    f"{_ENDIANNESS}f8": np.nan,
    f"{_ENDIANNESS}(3,)f8": np.nan,
    f"{_ENDIANNESS}i4": np.iinfo(f"{_ENDIANNESS}i4").min,
    f"{_ENDIANNESS}i1": np.iinfo(f"{_ENDIANNESS}i1").min,
}

@dataclass
class ComponentMetaData:
    """
    Data class for component metadata
    """

    dtype: np.dtype
    dtype_dict: Dict[str, Any]
    nans: Dict[str, Union[float, int]]
    nan_scalar: np.ndarray

    def __getitem__(self, item):
        """
        Get item of dataclass

        Args:
            item: item name

        Returns:

        """
        return getattr(self, item)

DatasetMetaData = Dict[str, ComponentMetaData]
PowerGridMetaData = Dict[str, DatasetMetaData]

def _generate_meta_data() -> PowerGridMetaData:
    """

    Returns: meta data for all dataset

    """
    py_meta_data = {}
    n_datasets = pgc.meta_n_datasets()
    for i in range(n_datasets):
        dataset = pgc.meta_get_dataset_by_idx(i)
        py_meta_data[pgc.meta_dataset_name(dataset)] = _generate_meta_dataset(dataset)
    return py_meta_data

def _generate_meta_dataset(dataset: DatasetPtr) -> DatasetMetaData:
    """

    Args:
        dataset: dataset

    Returns: meta data for one dataset

    """
    py_meta_dataset = {}
    n_components = pgc.meta_n_components(dataset)
    for i in range(n_components):
        component = pgc.meta_get_component_by_idx(dataset, i)
        py_meta_dataset[pgc.meta_component_name(component)] = _generate_meta_component(component)
    return py_meta_dataset

def _generate_meta_component(component: ComponentPtr) -> ComponentMetaData:
    """

    Args:
        component: component

    Returns: meta data for one component

    """

    dtype_dict = _generate_meta_attributes(component)
    dtype = np.dtype({k: v for k, v in dtype_dict.items() if k != "nans"})  # type: ignore
    nans = dict(zip(dtype_dict["names"], dtype_dict["nans"]))
    if dtype.alignment != pgc.meta_component_alignment(component):
        raise TypeError(f'Aligment mismatch for component type: "{pgc.meta_component_name(component)}" !')
    # get single nan scalar
    nan_scalar = np.empty(1, dtype=dtype)
    for key, value in nans.items():
        nan_scalar[key] = value
    # return component
    return ComponentMetaData(dtype=dtype, dtype_dict=dtype_dict, nans=nans, nan_scalar=nan_scalar)

def _generate_meta_attributes(component: ComponentPtr) -> dict:
    """

    Args:
        component: component

    Returns: meta data for all attributes

    """
    names = []
    formats = []
    offsets = []
    nans = []
    n_attrs = pgc.meta_n_attributes(component)
    for i in range(n_attrs):
        attribute: AttributePtr = pgc.meta_get_attribute_by_idx(component, i)
        attr_name: str = pgc.meta_attribute_name(attribute)
        attr_ctype: int = pgc.meta_attribute_ctype(attribute)
        attr_offset: int = pgc.meta_attribute_offset(attribute)
        attr_np_type = f"{_ENDIANNESS}{_CTYPE_NUMPY_MAP[PGMCType(attr_ctype)]}"
        attr_nan = _NAN_VALUE_MAP[attr_np_type]
        names.append(attr_name)
        formats.append(attr_np_type)
        offsets.append(attr_offset)
        nans.append(attr_nan)
    return {
        "names": names,
        "formats": formats,
        "offsets": offsets,
        "itemsize": pgc.meta_component_size(component),
        "aligned": True,
        "nans": nans,
    }

# store meta data
power_grid_meta_data = _generate_meta_data()

def initialize_array(data_type: str, component_type: str, shape: Union[tuple, int], empty: bool = False):
    """
    Initializes an array for use in Power Grid Model calculations

    Args:
        data_type: input, update, sym_output, or asym_output
        component_type: one component type, e.g. node
        shape: shape of initialization
            integer, it is a 1-dimensional array
            tuple, it is an N-dimensional (tuple.shape) array
        empty: if leave the memory block un-initialized

    Returns:
        np structured array with all entries as null value
    """
    if not isinstance(shape, tuple):
        shape = (shape,)
    if empty:
        return np.empty(shape=shape, dtype=power_grid_meta_data[data_type][component_type].dtype, order="C")
    return np.full(
        shape=shape,
        fill_value=power_grid_meta_data[data_type][component_type].nan_scalar,
        dtype=power_grid_meta_data[data_type][component_type].dtype,
        order="C",
    )

# prepared data for c api
@dataclass
class CBuffer:
    """
    Buffer for a single component
    """

    data: c_void_p
    indptr: Optional[IdxPtr]  # type: ignore
    n_elements_per_scenario: int
    batch_size: int

@dataclass
class CDataset:
    """
    Dataset definition
    """

    dataset: Dict[str, CBuffer]
    batch_size: int
    n_components: int
    components: Array
    n_component_elements_per_scenario: Array
    indptrs_per_component: Array
    data_ptrs_per_component: Array

# pylint: disable=R0912
def prepare_cpp_array(
    data_type: str, array_dict: Mapping[str, Union[np.ndarray, Mapping[str, np.ndarray]]]
) -> CDataset:
    """
    prepare array for cpp pointers
    Args:
        data_type: input, update, or symmetric/asymmetric output
        array_dict:
            key: component type
            value:
                data array: can be 1D or 2D (in batches)
                or
                dict with
                    key:
                        data -> data array in flat for batches
                        indptr -> index pointer for variable length input
    Returns:
        instance of CDataset ready to be fed into C API
    """
    # process
    schema = power_grid_meta_data[data_type]
    dataset_dict = {}
    for component_name, entry in array_dict.items():
        if component_name not in schema:
            continue
        # homogeneous
        if isinstance(entry, np.ndarray):
            data = entry
            ndim = entry.ndim
            indptr_c = IdxPtr()
            if ndim == 1:
                batch_size = 1
                n_elements_per_scenario = entry.shape[0]
            elif ndim == 2:  # (n_batch, n_component)
                batch_size = entry.shape[0]
                n_elements_per_scenario = entry.shape[1]
            else:
                raise ValueError(f"Array can only be 1D or 2D. {VALIDATOR_MSG}")
        # with indptr
        else:
            data = entry["data"]
            indptr: np.ndarray = entry["indptr"]
            batch_size = indptr.size - 1
            n_elements_per_scenario = -1
            if data.ndim != 1:
                raise ValueError(f"Data array can only be 1D. {VALIDATOR_MSG}")
            if indptr.ndim != 1:
                raise ValueError(f"indptr can only be 1D. {VALIDATOR_MSG}")
            if indptr[0] != 0 or indptr[-1] != data.size:
                raise ValueError(f"indptr should start from zero and end at size of data array. {VALIDATOR_MSG}")
            if np.any(np.diff(indptr) < 0):
                raise ValueError(f"indptr should be increasing. {VALIDATOR_MSG}")
            indptr_c = np.ascontiguousarray(indptr, dtype=IdxNp).ctypes.data_as(IdxPtr)
        # convert data array
        data_c = np.ascontiguousarray(data, dtype=schema[component_name].dtype).ctypes.data_as(c_void_p)
        dataset_dict[component_name] = CBuffer(
            data=data_c, indptr=indptr_c, n_elements_per_scenario=n_elements_per_scenario, batch_size=batch_size
        )
    # total set
    n_components = len(dataset_dict)
    if n_components == 0:
        batch_size = 1
    else:
        batch_sizes = np.array([x.batch_size for x in dataset_dict.values()])
        if np.unique(batch_sizes).size > 1:
            raise ValueError(f"Batch sizes across all the types should be the same! {VALIDATOR_MSG}")
        batch_size = batch_sizes[0]
    return CDataset(
        dataset=dataset_dict,
        batch_size=batch_size,
        n_components=n_components,
        components=(c_char_p * n_components)(*(x.encode() for x in dataset_dict)),
        n_component_elements_per_scenario=(IdxC * n_components)(
            *(x.n_elements_per_scenario for x in dataset_dict.values())
        ),
        indptrs_per_component=(IdxPtr * n_components)(*(x.indptr for x in dataset_dict.values())),  # type: ignore
        data_ptrs_per_component=(c_void_p * n_components)(*(x.data for x in dataset_dict.values())),
    )


# -*- coding: utf-8 -*-
import os

from pymongo import MongoClient

class DBManager(object):
    db = None
    connection = None

    @classmethod
    def get_db(cls):
        if not cls.db:
            if not cls.connection:
                cls.connection = MongoClient(os.environ['CRAWLER_MONGO_URL'])

            if os.environ['PYTHON_ENV'] in ['development', 'staging', 'production']:
                cls.db = cls.connection.appbee
                print('Use appbee db for', os.environ['PYTHON_ENV'], 'environment')
            elif os.environ['PYTHON_ENV'] in ['test']:
                cls.db = cls.connection.test
                print('Use test db for', os.environ['PYTHON_ENV'], 'environment')
            else:
                print('Wrong environment:', os.environ['PYTHON_ENV'])

        return cls.db

    @classmethod
    def close(cls):
        if cls.connection:
            cls.connection.close()

    @classmethod
    def get_uncrawled_package_names_without_error_code(cls):
        db = cls.get_db()
        uncrawled_package_names = db['uncrawled-apps'].distinct('packageName', {'errCode': {'$exists': False}})
        other_apps_package_names = db['other-apps'].distinct('packageName')

        return list(filter(lambda package_name: package_name not in other_apps_package_names, uncrawled_package_names))

    @classmethod
    def update_error_code_of_uncrawled_app(cls, package_name, error_code):
        print('### Update errCode:' + str(error_code) + ' of ' + str(package_name) + 'in Uncrawled Apps ###')
        db = cls.get_db()

        db['uncrawled-apps'].update_one({'packageName': package_name}, {"$set": {'errCode': error_code}}, upsert=False)

    @classmethod
    def delete_uncrawled_app(cls, package_name):
        print('### Delete ' + str(package_name) + ' from Uncrawled Apps ###')
        db = cls.get_db()
        db['uncrawled-apps'].delete_one({'packageName': package_name})

    @classmethod
    def update_app_usages(cls, item):
        app_info = {
            'appName': item['appName'],
            'categoryId': item['categoryId1'],
            'categoryName': item['categoryName1'],
            'developer': item['developer'],
            'iconUrl': item['iconUrl'],
        }

        DBManager.get_db()['app-usages'].update_many({'packageName': item['packageName']}, {'$set': app_info})

    @classmethod
    def upsert_app(cls, item):
        print('### Upsert ' + str(item['packageName']) + ' to Apps ###')
        db = cls.get_db()
        db['apps'].update_one({'packageName': item['packageName']}, {'$set': dict(item)}, upsert=True)
        cls.update_app_usages(item)

    @classmethod
    def upsert_category(cls, item):
        print('### Upsert ' + str(item['id']) + ' to Categories ###')
        db = cls.get_db()
        db['categories'].update_one({'id': item['id']}, {'$set': dict(item)}, upsert=True)

    @classmethod
    def upsert_other_app(cls, item):
        print('### Upsert ' + str(item['packageName']) + ' to Other App ###')
        db = cls.get_db()
        db['other-apps'].update_one({'packageName': item['packageName']}, {'$set': dict(item)}, upsert=True)

    @classmethod
    def get_package_names_to_update_info(cls):
        db = cls.get_db()
        package_names = db['app-usages'].distinct('packageName')
        return package_names


from managed_system.managing_system.state_machine import StockStateMachine
from managed_system.model import Stock

class StockActioner:
    def __init__(self, stock_name, account, controller):
        self.account = account
        self.stock_name = stock_name
        self.controller = controller

    def perform_action(self, stock_price, state):
        stock = Stock(name=self.stock_name, price=stock_price)
        if state == StockStateMachine.STATUS_BUY:
            self.controller.buy_stock(stock, self.account)
            print(self.account.get_portfolio())
        elif state == StockStateMachine.STATUS_SELL:
            self.controller.sell_stock(stock, self.account)
            print(self.account.get_portfolio())


import random
from deap import algorithms as alg, base, creator, tools

class KnapsackProblem:

  def __init__(self, max_weight, length_items, max_weight_items, max_price_items, lenght_population, lenght_generations):
    self.max_weight = max_weight
    self.length_items = length_items
    self.max_weight_items = max_weight_items
    self.max_price_items = max_price_items
    self.lenght_population = lenght_population
    self.lenght_generations = lenght_generations
    self.items = []
    self.population = []
    self.toolbox = base.Toolbox()
    self.best_option = 0

  @property
  def createItems(self):
    for i in range(self.length_items):
      self.items.append({"weight": random.randint(1, self.max_weight_items),
                         "value": random.randint(1, self.max_price_items)})
    return self.items

  def setFitness(self, individual):
    weight = 0
    value = 0
    for index, item in enumerate(individual):
        if item == 1:
            weight += self.items[index]['weight']
            value += self.items[index]['value']
    if weight > self.max_weight:
        return 0,
    return value,

  @property
  def setToolbox(self):
    creator.create("Fitness", base.Fitness, weights=(1.0,))
    creator.create("Individual", list, fitness=creator.Fitness)
    self.toolbox.register("attr_bool", random.randint, 0, 1)
    self.toolbox.register("individual", tools.initRepeat, creator.Individual, self.toolbox.attr_bool, n=self.length_items)
    self.toolbox.register("population", tools.initRepeat, list, self.toolbox.individual, n=self.lenght_generations)

    self.population = self.toolbox.population()

    self.toolbox.register("evaluate", self.setFitness)
    self.toolbox.register("mate", tools.cxTwoPoint)
    self.toolbox.register("mutate", tools.mutFlipBit, indpb=0.05)
    self.toolbox.register("select", tools.selTournament, tournsize=3)

  @property
  def setGenerations(self):
    for gen in range(self.lenght_generations):
      offspring = alg.varAnd(self.population, self.toolbox, cxpb=0.5, mutpb=0.1)
      fits = self.toolbox.map(self.toolbox.evaluate, offspring)
      for fit, ind in zip(fits, offspring):
          ind.fitness.values = fit
      self.population = self.toolbox.select(offspring, k=len(self.population))

  @property
  def bestOption(self):
    bests = tools.selBest(self.population, k=10)
    self.best_option = bests[0]
    return self.best_option

  @property
  def showItems(self):
    print("\n------------ Items ------------")
    for item in self.items:
      print(item)

  @property
  def getKnapsackMaxWeight(self):
    print("\nMax Capacity of this Knapsack: {}kg".format(self.max_weight))

  @property
  def show(self):
    print("\n------------ Result ------------")
    weight = 0
    value = 0
    for index, item in enumerate(self.best_option):
        if item == 1:
            print(self.items[index])
            weight += self.items[index]['weight']
            value += self.items[index]['value']

    print('\nTotal Weight: {}kg'.format(weight))
    print('Total Value: ${}'.format(value))

  @property
  def solveProblem(self):
    self.getKnapsackMaxWeight
    self.createItems
    self.showItems
    self.setToolbox
    self.setGenerations
    self.bestOption
    self.show


#!/usr/bin/env python

from donor_models import Donor, DonorCollection
from operator import itemgetter

############################
# DONOR MANAGEMENT FUNCTIONS
############################

def add_donation():  # Tested
    """
    Adds a donation to the specified donor.  Prints a thank you letter to stdout.
    :return: None
    """
    donor = find_donor()
    while True:
        donation_input = input("Input {}'s donation amount in dollars\n".format(donor.name))
        try:
            donor.add_donation(donation_input)
            print(donor.thank_you_letter)
            return
        except ValueError:
            print("{} is not a valid donation amount.".format(donation_input))
            continue

def add_donor():  # Tested
    """
    Adds a donor to the donor collection
    :return: None
    """
    donor_valid = False
    while not donor_valid:
        try:
            user_input = str(input("Provide the name to add to the donor list\n"))
        except TypeError:
            continue
        try:
            donor_collection.add_donor(user_input)
            donor_valid = True
        except ValueError:
            print("Donor {} already exists.  Please provide a different donor name to add".format(user_input))
            continue

def list_donors():  # Tested
    """
    Prints a list of donor names to stdout.
    :return: None
    """
    print(donor_collection.donor_list)

def print_thank_you():  # Tested
    """
    Prompts for the name of a donor.  Prints a thank you letter for the donor's mmost recent donation.
    :return: None
    """
    print(find_donor().thank_you_letter)

def write_letters_to_disk():  # Tested
    """
    Writes a text file to disk for each donor in the donor collection.
    Each file contains a thank you letter for the donor's most recent donation.
    :return: None
    """
    for donor in donor_collection.donors:
        with open('thank_you_letter_{}'.format(donor.name), 'w') as thank_you_file:
            thank_you_file.write(donor.thank_you_letter)

######################
# NAVIGATION FUNCTIONS
######################

def donor_management():  # Tested
    """
    Calls a function based on the user's input in the program's donor menu.
    :return: None
    """
    donor_menu_options = {'l': list_donors, 'a': add_donor, '$': add_donation, 't': print_thank_you,
                          'g': write_letters_to_disk}
    user_input = menu_donor()
    donor_menu_options.get(user_input)()

def find_donor():  # Tested
    """
    Prompts user for a donor name.  Locates the corresponding Donor object in the DonorCollection
    :return: Donor object
    """
    while True:
        user_input = str(input("Provide the name of the donor.\n"))
        for donor in donor_collection.donors:
            if donor.name == user_input:
                return donor
        print("Donor {} not found.".format(user_input))

def menu_donor():  # Tested
    """
    Presents user with the donor sub-menu's options.  Validates user input.
    :return: str with one of the following values: l, a, $, t, g
    """
    while True:
        user_input = input("l to list donors\na to add donor\n$ to add donation\nt to print thank you message\n"
                           "g to generate thank you letters for all donors\n \n").lower()
        if user_input == 'l' or user_input == 'a' or user_input == '$' or user_input == 't' or user_input == 'g':
            return user_input

def menu_main():  # Tested
    """
    Prompts user with the program's main menu options.  Validates user input.
    :return: str with one of the following values: q, r, d, p
    """
    while True:
        user_input = input("\nq to quit\nr to generate a report\nd to manage donors\n \n").lower()
        if user_input == 'q' or user_input == 'r' or user_input == 'd' or user_input == 'p':
            return user_input

#####################
# MAIN MENU FUNCTIONS
#####################

def main():  # Tested
    """
    Calls a function based on the user's input in the program's main menu.
    :return: None
    """
    main_menu_options = {'r': report, 'd': donor_management, 'p': populate_default_data, 'q': exit}
    user_input = ''
    while 'q' not in user_input:
        user_input = menu_main()
        main_menu_options.get(user_input)()

def populate_default_data():  # Tested
    """
    Populates donor_collection with various donor objects.  Not listed in menu options.
    :return: None
    """
    # Hard coded data, ewwww...
    donors = [
        {'Name': 'Alice', 'Donations': ('$10000.00',)},
        {'Name': 'Bob', 'Donations': (200, 1000.00)},
        {'Name': 'Christine', 'Donations': (0,)},
        {'Name': 'Dave', 'Donations': ()},
        {'Name': 'Kim', 'Donations': (50.25, 50.00, 50)}
    ]
    for donor in donors:
        donor_collection.add_donor(donor['Name'], donor['Donations'])

def report():  # Tested
    """
    Prints a table to stdout containing donor statistics.
    :return: None
    """
    sorted_donor_data = sorted(donor_collection.donor_report, key=itemgetter(1), reverse=True)
    print("Donor Name{}| Total Given | Num Gifts | Average Gift".format(' ' * 20))
    print('-' * 70)
    for donor in sorted_donor_data:
        total_str = '{:,.2f}'.format(donor[1])
        average_str = '{:,.2f}'.format(donor[3])
        print("{name}{w1}${w2}{t}{w3}{num}  ${w4}{a}".format(
            name=donor[0],
            w1=' ' * (31 - len(str(donor[0]))),
            w2=' ' * (12 - len(total_str)),
            t=total_str,
            w3=' ' * (12 - len(str(donor[2]))),
            num=donor[2],
            w4=' ' * (11 - len(average_str)),
            a=average_str
        ))

donor_collection = DonorCollection()
if __name__ == '__main__':
    main()


from pyspark.sql import SparkSession, SQLContext
from pyspark import SparkConf, SparkContext
from pyspark.sql.types import *
from pyspark.sql.functions import array, udf, col, explode, concat_ws, collect_list, sort_array, count, size, coalesce, expr, regexp_replace, array_contains
spark= SparkSession.builder.config('spark.ui.port','4040').getOrCreate()

spark.conf.set('spark.sql.caseSensitive', 'True')

WoS3 = spark.read.format("parquet").load("/WoSraw_2020_all/parquet/part*")

WoS = WoS3.filter(WoS3.static_data.summary.pub_info._pubyear.contains('2020'))

wos = WoS.select(WoS.UID.alias("wosID"),
                 WoS.static_data.summary.pub_info._pubyear.alias("Year"),
                 WoS.static_data.summary.pub_info._pubtype.alias("publicationType"),
                 WoS.static_data.summary.doctypes.doctype[0].alias("documentType"),
                 WoS.static_data.summary.publishers.publisher.names["name"]["full_name"].alias("publisher"),
                 WoS.static_data.summary.publishers.publisher.names["name"].full_name.alias("publicationName"),
                 WoS.static_data.summary.pub_info.page._page_count.alias("pageCount"),
                 concat_ws(', ', WoS.static_data.fullrecord_metadata.fund_ack.fund_text.p).alias("fundingText"),
                 concat_ws(', ', WoS.static_data.fullrecord_metadata.addresses.address_name.names["name"][0].full_name).alias("reprintAuthor"),
                 WoS.static_data.fullrecord_metadata.reprint_addresses.address_name.address_spec.full_address[0].alias("reprintAuthorAddress"),
                 WoS.static_data.fullrecord_metadata.addresses.address_name.address_spec['full_address'].alias('full_address')
                            )

wos = wos.withColumn("full_address", concat_ws(", ",  col("full_address")))

###################################################################
wos_test =  WoS.select(WoS.UID.alias("wosID"),
                       WoS.static_data.fullrecord_metadata.addresses.address_name.address_spec.organizations.organization[1].alias("org"))

wos_test2 = wos_test.withColumn("org1", wos_test["org"].getItem(0))

wos_test2 = wos_test2.withColumn("org2", wos_test["org"].getItem(1))

wos_test2 = wos_test2.withColumn("org3", wos_test["org"].getItem(2))

wos_test2 = wos_test2.withColumn("org4", wos_test["org"].getItem(3))

wosEorg = wos_test2.withColumn("org1", explode(array("org1"))).select("*", col("org1")["_VALUE"].alias("Eorg1"))
wosEorg = wosEorg.withColumn("org2", explode(array("org2"))).select("*", col("org2")["_VALUE"].alias("Eorg2"))
wosEorg = wosEorg.withColumn("org3", explode(array("org3"))).select("*", col("org3")["_VALUE"].alias("Eorg3"))
wosEorg = wosEorg.withColumn("org4", explode(array("org4"))).select("*", col("org4")["_VALUE"].alias("Eorg4"))

wosEorg = wosEorg.select('wosID', 'Eorg1', 'Eorg2', 'Eorg3', 'Eorg4')

#wosEorg = wosEorg.filter(col("Eorg").like('Indiana%'))

#wosEorg.show(50, truncate = True)

###################################################################
#BUILD ISSN/EISSN/DOI TABLE

wosIdPlus = WoS.select(WoS.UID.alias("wosID"),
                       WoS.dynamic_data.cluster_related.identifiers.identifier.alias('ids'))

wosIdPlus2 = wosIdPlus.withColumn("ids", explode("ids")).select("*", col("ids")["_type"].alias("altID"))

wosIdDf = wosIdPlus.select(wosIdPlus.wosID.alias("wosID"))

wosIdPlus3 = wosIdPlus2.select('wosID', 'ids.*')

issn   = wosIdPlus3.filter(wosIdPlus3._type == "issn")
issn2  = issn.groupBy("wosID").agg(sort_array(collect_list("_value")).alias("_value"))
issn3  = issn2.withColumn("_value", concat_ws("| ", issn2._value))
issn4  = issn3.select(col('wosID').alias("wosID"), col('_value').alias('issn'))

doi   = wosIdPlus3.filter(wosIdPlus3._type == "doi")
doi2  = doi.groupBy("wosID").agg(sort_array(collect_list("_value")).alias("_value"))
doi3  = doi2.withColumn("_value", concat_ws("| ", doi2._value))
doi4   = doi3.select(col('wosID').alias('wosID'), col('_value').alias('doi'))

eissn   = wosIdPlus3.filter(wosIdPlus3._type == "eissn")
eissn2  = eissn.groupBy("wosID").agg(sort_array(collect_list("_value")).alias("_value"))
eissn3  = eissn2.withColumn("_value", concat_ws("| ", eissn2._value))
eissn4  = eissn3.select(col('wosID').alias('wosID'), col('_value').alias('eissn'))

isbn   = wosIdPlus3.filter(wosIdPlus3._type == "isbn")
isbn2  = isbn.groupBy("wosID").agg(sort_array(collect_list("_value")).alias("_value"))
isbn3  = isbn2.withColumn("_value", concat_ws("| ", isbn2._value))
isbn4  = isbn3.select(col('wosID').alias('wosID'), col('_value').alias('isbn'))

pmid   = wosIdPlus3.filter(wosIdPlus3._type == "pmid")
pmid2  = pmid.groupBy("wosID").agg(sort_array(collect_list("_value")).alias("_value"))
pmid4  = pmid2.select(col('wosID').alias('wosID'), concat_ws("| ", pmid2._value).alias('pmid'))

wosIdPlus4 = wosIdDf.join(doi4,   wosIdDf['wosID'] == doi4['wosID'],   how='left') \
                    .join(eissn4, wosIdDf['wosID'] == eissn4['wosID'], how='left') \
                    .join(isbn4,  wosIdDf['wosID'] == isbn4['wosID'],  how='left') \
                    .join(pmid4,  wosIdDf['wosID'] == pmid4['wosID'],  how='left') \
                    .join(issn4,  wosIdDf['wosID'] == issn4['wosID'],  how='left') \
                 .select(coalesce(wosIdDf.wosID, issn4.wosID, doi4.wosID, eissn4.wosID, isbn4.wosID, pmid4.wosID).alias('wosID'),
                        issn4.issn, doi4.doi, eissn4.eissn, isbn4.isbn, pmid4.pmid)

####################################################################################################
#BUILD AUTHOR ARRAY
wos5 = WoS.select(WoS.UID.alias("wosID"), WoS.static_data.summary.names['name'].alias("author"))

wos6 = wos5.withColumn("author", explode("author")).select("*", col("author")["_seq_no"].alias("seq_no"),
                                                                col("author")["display_name"].alias("standardNames")
                                                          )

wos_author = wos6.select("wosID", concat_ws(" ", wos6.standardNames, wos6.seq_no).alias("standardNames")
                        )

wos_auth2 = wos_author.groupBy("wosID").agg(sort_array(collect_list("standardNames")).alias("standardNames")
                                           )
wos_auth2 = wos_auth2.select(
   col('wosID'),
   concat_ws("| ", col('standardNames')).alias('standardNames'),
   size('standardNames').alias('count')
)

wos_auth2 = wos_auth2.drop('count')

################################################################################################

wtOutput = wos.join(wosIdPlus4, wos['wosID'] == wosIdPlus4['wosID'], how='full') \
              .join(wosEorg,    wos['wosID'] == wosEorg['wosID'],    how='full') \
              .join(wos_auth2,  wos['wosID'] == wos_auth2['wosID'],  how='full') \
            .select(coalesce(wos.wosID,
                             wosIdPlus4.wosID,
                             wosEorg.wosID,
                             wos_auth2.wosID).alias('wosId'),
                   wos.Year,
                   wos.publicationType,
                   wos.documentType,
                   wos.publisher,
                   wos.publicationName,
                   wos.pageCount,
                   wos.fundingText,
                   wos.reprintAuthor,
                   wos.reprintAuthorAddress,
                   wos.full_address,
                    wos_auth2.standardNames,
                       wosIdPlus4.issn,
                       wosIdPlus4.doi,
                       wosIdPlus4.eissn,
                       wosIdPlus4.isbn,
                       wosIdPlus4.pmid,
                        wosEorg.Eorg1,
                        wosEorg.Eorg2,
                        wosEorg.Eorg3,
                        wosEorg.Eorg4)

#################################################
#wtOutput2 = wtOutput.filter(wtOutput.Eorg.like('Indiana University System'))

wtOutput2 = wtOutput.filter(col("Eorg3").like('Indiana University Bloomington'))

#################################################

wtOutput2.coalesce(100).write.option("header","True") \
                               .option("sep","\t") \
                               .option("quoteAll", True) \
                               .mode("overwrite") \
                               .csv('/wtQuery')


from funciones import *
from funciones import verificar_tablas_existen, insertar_datos_SUMMARY
import pyodbc
import pandas as pd
import csv
import os

try:
    conexion = pyodbc.connect('DRIVER={SQL Server};SERVER=DESKTOP-3H6HKSS\SQLEXPRESS;DATABASE=fut_usm;Trusted_Connection=yes;')
    cursor = conexion.cursor()

    tablas_a_crear = ["SUMMARY", "FIFA"]
    if not verificar_tablas_existen(conexion, tablas_a_crear):
        crear_tablas(conexion)

        # Obtiene una lista de todos los archivos .csv
        directorio_csv = os.path.abspath('./archivos_csv')
        archivos_csv = [archivo for archivo in os.listdir(directorio_csv) if archivo.endswith('.csv')]

        # Insertar datos a la tabla SUMMARY
        ruta = os.path.join(directorio_csv, archivos_csv[-1])
        insertar_datos_SUMMARY(conexion,ruta)

        i = 1 # Contador para ID (primary key)
        for archivo in archivos_csv:
            if "Summary" not in archivo:
                ruta = os.path.join(directorio_csv, archivo)
                year = int(archivo[7:11])
                i = insertar_datos_FIFA(conexion,ruta,year,i)

    # Menu y opciones
    while True:
        print("Menu Fut-USM: ")
        print("1. Mostrar Campeones")
        print("2. Mostrar goleadores")
        print("3. Mostrar Tercer Lugar más veces")
        print("4. Mostrar Pais mas goles recibidos")
        print("5. Buscar un pais")
        print("6. Top 3 paises en el mundial")
        print("7. Mayor cantidad ganados")
        print("8. Paises ganando en casa")
        print("9. Mas veces en el podio")
        print("10. Mayores rivales")
        print("0. Salir")
        print()
        respuesta = input("Seleccione una opcion: ")
        print()

        if respuesta == "1":

            cursor.execute("""
            CREATE VIEW CampeonesView AS
            SELECT
                Year AS Año,
                Champion AS Campeon
            FROM
                SUMMARY
            """)

            cursor.execute("SELECT * FROM CampeonesView")
            data = cursor.fetchall()
            campeones_resultados = pd.DataFrame.from_records(data, columns=["Año","Campeon"])
            print(campeones_resultados.to_string(index=False))
            print('\n')

        elif respuesta == "2":

            cursor.execute("""
            SELECT TOP 5
                Team AS Equipo,
                SUM(Goals_For) AS Total_Goles
            FROM
                FIFA
            GROUP BY
                Team
            ORDER BY
                SUM(Goals_for) DESC;
            """)

            data = cursor.fetchall()
            goleadores = pd.DataFrame.from_records(data, columns=["Equipo","Goles_marcados"])
            print(goleadores.to_string(index=False))
            print('\n')

        elif respuesta == "3":

            cursor.execute("""
            SELECT TOP 5
                Third_place AS Tercer_lugar,
                COUNT(Third_place) AS cantidad_tercer_lugar
            FROM
                SUMMARY
            GROUP BY
                Third_place
            ORDER BY
                COUNT(Third_place) DESC;
            """)

            data = cursor.fetchall()
            tercer_lugar = pd.DataFrame.from_records(data, columns=["Equipo","Cantidad"])
            print("Top 5 equipos con mayor tercer lugar: \n")
            print(tercer_lugar.to_string(index=False))
            print('\n')

        elif respuesta == "4":

            cursor.execute("""
            SELECT TOP 5
                Team AS Equipo,
                SUM(Goals_Against) AS Goles_en_contra
            FROM
                FIFA
            GROUP BY
                Team
            ORDER BY
                SUM(Goals_Against) DESC;
            """)

            data = cursor.fetchall()
            goles_en_contra = pd.DataFrame.from_records(data, columns=["Equipo","Goles_recibidos"])
            print(goles_en_contra.to_string(index=False))
            print('\n')

        elif respuesta == "5":

            salir = True
            while salir:
                respuesta = mostrar_menu_equipos(conexion)

                if respuesta == 's':
                    salir = False
                else:
                    mostrar_info_equipo(conexion,respuesta)

        elif respuesta == "6":

            cursor.execute("""
            SELECT TOP 3
                Team AS Equipo,
                COUNT(Team) AS Cantidad_mundiales_jugados
            FROM
                FIFA
            GROUP BY
                Team
            ORDER BY
                COUNT(Team) DESC;
            """)

            data = cursor.fetchall()
            cantidad_mundiales = pd.DataFrame.from_records(data, columns=["Equipo","Mundiales_jugados"])
            print(cantidad_mundiales.to_string(index=False))
            print('\n')

        elif respuesta == "7":

            cursor.execute("""
            SELECT TOP 1
                Team AS Equipo,
                CONCAT(CAST(dbo.calcularTasa(SUM(Win),SUM(Games_Played)) AS DECIMAL(10,2) ), '%') AS Tasa_partidos_ganados
            FROM
                FIFA
            GROUP BY
                Team
            ORDER BY
                Tasa_partidos_ganados DESC;
            """
            )

            data = cursor.fetchall()
            promedio_partidos_ganados = pd.DataFrame.from_records(data, columns=["Equipo", "Tasa_partidos_ganados"])
            print(promedio_partidos_ganados.to_string(index=False))
            print('\n')

        elif respuesta == "8":

            cursor.execute("""
            SELECT
                Year AS Año,
                Host AS Anfitrion,
                Champion AS Campeon
            FROM
                SUMMARY
            WHERE
                Host = Champion;
            """)

            data = cursor.fetchall()
            paises_ganando_en_casa_resultado = pd.DataFrame.from_records(data, columns=["Año","Anfitrion","Campeon"])
            print("Paises ganando en casa: ")
            print(paises_ganando_en_casa_resultado.to_string(index=False))
            print('\n')

        elif respuesta == "9":

            cursor.execute("""
            SELECT TOP 1 Team, COUNT(*) AS Veces_podio
            FROM (
                SELECT Champion AS Team FROM SUMMARY
                UNION ALL
                SELECT Runner_up AS Team FROM SUMMARY
                UNION ALL
                SELECT Third_Place AS Team FROM SUMMARY
            ) AS Podio
            GROUP BY Team
            ORDER BY Veces_podio DESC;
            """)

            data = cursor.fetchall()
            podio = pd.DataFrame.from_records(data, columns=["Pais","Veces_en_el_podio"])
            print(podio.to_string(index=False))
            print('\n')

        elif respuesta == "10":

            cursor.execute("""
            WITH Parejas AS(
                SELECT
                    CASE WHEN Champion < Runner_up THEN Champion ELSE Runner_up END AS Equipo1,
                    CASE WHEN Champion < Runner_up THEN Runner_up ELSE Champion END AS Equipo2
                FROM
                    SUMMARY
            )
            SELECT TOP 1
                Equipo1,
                Equipo2,
                COUNT(*) AS Veces_Repetidos
            FROM
                Parejas
            GROUP BY
                Equipo1,
                Equipo2
            ORDER BY
                Veces_Repetidos DESC;
            """)

            data = cursor.fetchall()
            mayores_rivales = pd.DataFrame.from_records(data,columns=["Pais1","Pais2","Veces_Rivales"])
            mayores_rivales['Rivales'] = mayores_rivales["Pais1"] + '-' + mayores_rivales["Pais2"]  # Se juntan los paises en una sola tabla
            mayores_rivales.drop(['Pais1', 'Pais2'], axis=1, inplace=True)
            mayores_rivales = mayores_rivales[['Rivales', 'Veces_Rivales']] # Cambiar el orden de las columnas
            print("Paises que han sido los mayores rivales: \n")
            print(mayores_rivales.to_string(index=False))
            print('\n')

        elif respuesta == "0":
            print("¡Hasta pronto!")
            break

        else:
            print("Opcion no valida, ingresa una nueva opcion")

    cursor.close()
    conexion.close()

except Exception as e:
    print("Ocurrio un error al conectar a SQL Server: ", e)


import sys
from os.path import dirname, join
from textx import metamodel_from_file

class StateMachine(object):
    """
    StateMachine model interpreter.
    """
    def __init__(self, model):
        self.model = model

        self.current_state = None

        # First state is initial
        self.initial_state = model.states[0]

        # We are in the initial state at the beginning
        self.set_state(self.initial_state)

    def set_state(self, state):
        if self.current_state is None or state is not self.current_state:
            # Trigger state actions
            for action in state.actions:
                print("Executing action ", action.name)
            print("Transition to state ", state.name)
            self.current_state = state

    def event(self, event):
        # Check if this is some of reset events
        if event in self.model.resetEvents:
            self.set_state(self.initial_state)
        else:
            for transition in self.current_state.transitions:
                if transition.event is event:
                    self.set_state(transition.to_state)
                    return

    def print_menu(self):
        print("Current state: ", self.current_state.name)
        print("Choose event:")
        for idx, event in enumerate(self.model.events):
            print(idx + 1, '-', event.name, event.code)
        print('q - quit')

    def interpret(self):
        """
        Main interpreter loop.
        """
        self.print_menu()
        while True:
            try:
                event = input()
                if event == 'q':
                    return
                event = int(event)
                event = self.model.events[event - 1]
            except Exception:
                print('Invalid input')

            self.event(event)
            self.print_menu()

if __name__ == '__main__':
    this_folder = dirname(__file__)
    if len(sys.argv) != 2:
        print("Usage: python {} <model>".format(sys.argv[0]))
    else:
        meta_model = metamodel_from_file(join(this_folder, 'state_machine.tx'))
        model = meta_model.model_from_file(sys.argv[1])
        state_machine = StateMachine(model)
        state_machine.interpret()


from tkinter import *
from math import *
#importation de la bibliotheque Tkinter et math
fenetre = Tk()
fenetre.geometry("400x500") #definis la taille de la fenetre
fenetre.title ('Calculatrice') #Nom de la fenetre

entree = Entry(fenetre)
entree.grid(row=0 , column=0)
entree.bind("<Return>", egale)#fait en sorte qu'un evenement se produit lorsque l'on appuye sur enter
chaine = Label(fenetre)#Modifie l'attribut "texte" lors de l'evenement

entree.grid(row=0, column=1)
chaine.grid()
def ajouter():
    nb1 = entree.get()
    global nb2,math
    math = "addition"
    nb2 = int(nb1)
    entree.delete(0,END)
def soustraction():
    nb1 = entree.get()
    global nb2,math
    math = "soustraction"
    nb2 = int(nb1)
    entree.delete(0,END)
def multiplication():
    nb1 = entree.get()
    global nb2,math
    math = "multiplication"
    nb2 = int(nb1)
    entree.delete(0,END)
def division():
    nb1 = entree.get()
    global nb2,math
    math = "division"
    nb2 = int(nb1)
    entree.delete(0,END)
def reset():
    entree.delete(0 , END)
    chaine.configure(text = " ")
def egale():
    nb3 = entree.get()
    entree.delete(0 , END)
    if math == "addition" :
        entree.insert(0, nb2 + int(nb3))
        chaine.configure(text = "resultat=" + str(eval(entree.get())))
    elif math == "soustraction" :
        entree.insert(0, nb2 - int(nb3))
        chaine.configure(text = "resultat=" + str(eval(entree.get())))
    elif math == "multiplication" :
        entree.insert(0, nb2 * int(nb3))
        chaine.configure(text = "resultat=" + str(eval(entree.get())))
    elif math == "division" :
        entree.insert(0, nb2 / int(nb3))
        chaine.configure(text = "resultat=" + str(eval(entree.get())))
    entree.delete(0 , END)
#def egale():

	#chaine.configure(text = "resultat=" + str(eval(entree.get())))

boudiv = Button(fenetre, text='/', width =6 , command=division).grid(row =3, column =1)
bouegale = Button(fenetre, text='=', width =6 , command=egale).grid(row =4, column =1)
bouplus = Button(fenetre, text='+', width =6 , command=ajouter).grid(row =2, column =0)
boumoins = Button(fenetre, text='-', width =6 , command=soustraction).grid(row =2, column =1)
boufois = Button(fenetre, text='x', width =6 , command=multiplication).grid(row =3, column =0)
boureset = Button(fenetre, text=' reset', width =6 , command=reset).grid(row =4, column =0)

#Placement des boutons
fenetre.mainloop()