import pytest

from abridger.extraction_model import Relation
from abridger.schema import SqliteSchema
from test.unit.extractor.base import TestExtractorBase

class TestExtractorStickyRelations(TestExtractorBase):
    @pytest.fixture()
    def schema_out(self):
        '''
            test1 -> sticky         -> test3 <- test2
                  -> non_sticky     -> test3 <- test2
        '''
        for stmt in [
            '''
                CREATE TABLE non_sticky (
                    id INTEGER PRIMARY KEY,
                    test3_id INTEGER REFERENCES test3
                );
            ''', '''
                CREATE TABLE sticky (
                    id INTEGER PRIMARY KEY,
                    test3_id INTEGER REFERENCES test3
                );
            ''', '''
                CREATE TABLE test1 (
                    id INTEGER PRIMARY KEY,
                    sticky INTEGER REFERENCES sticky,
                    non_sticky INTEGER REFERENCES non_sticky
                );
            ''', '''
                CREATE TABLE test2 (
                    id INTEGER PRIMARY KEY,
                    test3_id INTEGER REFERENCES test3
                );
            ''', '''
                CREATE TABLE test3 (
                    id INTEGER PRIMARY KEY
                );
            ''',
        ]:
            self.database.execute(stmt)
        return SqliteSchema.create_from_conn(self.database.connection)

    @pytest.fixture()
    def data_out(self, schema_out):
        non_sticky = schema_out.tables[0]
        sticky = schema_out.tables[1]
        table1 = schema_out.tables[2]
        table2 = schema_out.tables[3]
        table3 = schema_out.tables[4]

        rows = [
            (table3, (1,)),
            (table3, (2,)),
            (table2, (1, 1)),
            (table2, (2, 2)),
            (sticky, (1, 1)),
            (non_sticky, (1, 2)),
            (table1, (1, 1, None)),
            (table1, (2, None, 1)),
        ]
        self.database.insert_rows(rows)

        self.data_everything_except_table2 = (
            rows[0:2] +  # table 3
            rows[4:6] +  # sticky and non_sticky
            rows[6:8]    # table 1
        )

        self.data_everything_except_table2_non_sticky_row = (
            rows[0:2] +  # table 3
            rows[4:6] +  # sticky and non_sticky
            rows[6:8] +  # table 1
            rows[2:3]    # table 2, row 1
        )

        return rows

    def test1(self, schema_out, data_out):
        # Check fetch without any relations, which won't grab any rows in
        # table 2
        table = {'table': 'test1'}

        self.check_one_subject(schema_out, [table],
                               self.data_everything_except_table2)

    def test2(self, schema_out, data_out):
        # Check fetch without sticky relations, which grabs everything
        table = {'table': 'test1'}
        relation = {'table': 'test2', 'column': 'test3_id'}
        self.check_one_subject(schema_out, [table], data_out,
                               relations=[relation])

    def test3(self, schema_out, data_out):
        # Check fetch without sticky relations, but flag test2 as sticky
        # this should not fetch anything in test2 since there is no sticky
        # trail
        table = {'table': 'test1'}

        def outgoing_sticky_rel(table, col):
            return {'table': table, 'column': col, 'sticky': True,
                    'type': Relation.TYPE_OUTGOING}

        relations = [
            outgoing_sticky_rel('test1', 'sticky'),
            outgoing_sticky_rel('sticky', 'test3_id'),
            outgoing_sticky_rel('test2', 'test3_id'),
            {'table': 'test2', 'column': 'test3_id', 'sticky': True},
        ]

        self.check_one_subject(
            schema_out, [table],
            self.data_everything_except_table2_non_sticky_row,
            relations=relations)


import paho.mqtt.client as mqtt
import requests

def on_connect(client, userdata, flags, rc):
    print("Connected with result code {0}".format(str(rc)))
    client.subscribe("esp32/temp")
    client.subscribe("esp32/humidity")

def on_message(client, userdata, msg):
    value = int(msg.payload.decode('UTF-8'))
    print(value)
    if (msg.topic == "esp32/temp"):
        requests.post('http://localhost:5000/temperature', json = {"temperature": value})
    elif (msg.topic == "esp32/humidity"):
        requests.post('http://localhost:5000/humidity', json = {"humidity": value})

client = mqtt.Client("PythonSub")
client.on_connect = on_connect
client.on_message = on_message
client.connect('127.0.0.1', 1883)
client.loop_forever()


# Kumpulan fungsi pendamping.

from components import var
import platform
import os
import time

# agar dapat menggunakan ANSI code di Windows
os.system("")

# fungsi menangani error

def moduleError():
    print(f"Maaf tetapi anda memiliki 1 module yang belum terpasang\nDibutuhkan module yang lengkap agar program dapat berjalan dengan optimal.\n")

    persetujuan = input(f"Apakah anda ingin menginstall module yang dibutuhkan sekarang? (Module yang dibutuhkan = Tabulate) [{var.hijau}Y{var.reset}/{var.merah}n{var.reset}]: ").upper()

    while True:
        if persetujuan == "Y":
            # Akan execute command line pip3 install tabulate jika sistem operasi user adalah Linux
            if var.platform_OS() == "linux":
                commandBash = os.popen("pip3 install tabulate")
                print(commandBash.read())
                break
            # Akan execute command line cmd /k pip3 install tabulate jika sistem operasi user adalah windows
            else:
                os.system('cmd /k "pip3 install tabulate"')
                os.system('cmd /k "exit"')
                break
        elif persetujuan == "N":
            break
        else:
            print(f"Silahkan Pilih {var.hijau}Y{var.reset} atau {var.merah}n{var.reset}.")

            persetujuan = input(f"Apakah anda ingin menginstall module yang dibutuhkan sekarang? (Module yang dibutuhkan = Tabulate) [{var.hijau}Y{var.reset}/{var.merah}n{var.reset}]: ").upper()

try:
    from tabulate import tabulate

    # Fungsi ini untuk mengganti command clear screen sesuai OS masing-masing

    def clear():
        OS = platform.system().lower()

        if OS == "linux":
            linux = os.system("clear")
            return linux
        else:
            windows = os.system("cls")
            return windows

    # Fungsi yang memuat animasi loading (Biar Keren)

    def loading(char, jumlahUlang):
        clear()
        for i in range(jumlahUlang):
            print(char + " -")
            time.sleep(0.2)
            clear()
            print(char + " |")
            time.sleep(0.2)
            clear()
            print(char + " /")
            time.sleep(0.2)
            clear()

    # Jika data pasien kosong

    def dataKosong(char):
        # Diberi variabel kosong supaya bisa menampung data yg diberikan
        tableData = []
        if len(char) == 0:
            tableData.append(["Maaf Tetapi data saat ini masih kosong."])
            print(tabulate(tableData))
        else:
            pass

    def verifikasiUser(char):
        persetujuan = input(f"\nApakah anda yakin ingin {char} data Pasien ini? [{var.hijau}Y{var.reset}/{var.merah}n{var.reset}]: ").upper()
        return persetujuan

    # Ini untuk menampilkan Tabel

    def tampilkanTable(char):
        clear()
        tableData = []
        nama = var.dataPasien[char]["Nama"]
        gender = var.dataPasien[char]["Gender"]
        penyakit = var.dataPasien[char]["Penyakit"]
        ruangan = var.dataPasien[char]["Ruangan"]
        id = char
        lamaMenginap = var.dataPasien[char]["Lama menginap"]

        tableData.append([nama, gender, penyakit, ruangan, id, lamaMenginap + " Hari"])

        print(tabulate(tableData, headers=["Nama", "Gender", "Penyakit", "Ruangan", "ID", "Lama menginap"], tablefmt="presto"))

    def templatePencarian(char, color1, color2):
        nama = var.dataPasien[char]["Nama"]
        gender = var.dataPasien[char]["Gender"]
        penyakit = var.dataPasien[char]["Penyakit"]
        ruangan = var.dataPasien[char]["Ruangan"]
        id = char
        lamaMenginap = var.dataPasien[char]["Lama menginap"]

        # Memasukkan data-data di atas ke dalam variabel tableData
        var.container.append([f"{color1}{nama}{color2}", f"{gender}", f"{penyakit}", f"{ruangan}", f"{id}", f"{lamaMenginap} " + "Hari"])

    # Ini akan mengecek id ketika menyebutkan nama.

    def pencarian(char):
        clear()

        for i in var.dataPasien:
            if char == var.dataPasien[i]["Nama"]:
                var.container = []
                var.peringatan = ""
                templatePencarian(i, '', '')
                break

            else:
                if char[0] == var.dataPasien[i]["Nama"][0]:
                    templatePencarian(i, '', '')
                    var.peringatan = f"{char} tidak ditemukan.Tetapi ada yang mendekati."
                else:
                    pass

        loading("Mencari", 3)

        print(f"{var.peringatan}\n")
        print(tabulate(var.container, headers=["Nama", "Gender", "Penyakit", "Ruangan", "ID", "Lama menginap"], tablefmt="presto"))

        var.container = []
        var.peringatan = ""

    def mengambilIdPasien(char):
        for i in var.dataPasien:
            if char == var.dataPasien[i]["Nama"]:
                return i
            else:
                pass

except ModuleNotFoundError:
    moduleError()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import copy
from random import randint
from Descida import descida

def ILS(n, s, d, vezesnivel, ILSmax):
    fo, s = descida(n,copy.deepcopy(s),d)
    iteracao = 0
    MelhorIter = 0
    nivel = 1
    while (iteracao - MelhorIter < ILSmax):
        iteracao += 1
        s_2l = copy.deepcopy(s)
        vezes = 0
        while (vezes < vezesnivel):
            ntrocasmax = nivel + 1
            ntrocas = 0
            s_2l = copy.deepcopy(s)
            fo_2l = fo
            while (ntrocas < ntrocasmax):
                ntrocas += 1
                i = randint(0, n-1)
                j = randint(0, n-1)
                while(j == i):
                    j = randint(0, n-1)
                aux = s_2l[i]
                s_2l[i] = s_2l[j]
                s_2l[j] = aux

            fo_2l, s_2l = descida(n,copy.deepcopy(s_2l),d)
            if (fo_2l < fo):
                fo = fo_2l
                s = copy.deepcopy(s_2l)
                vezes = 0
                nivel = 1
                MelhorIter = iteracao
            vezes +=1
        nivel += 1
    return fo, s


import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import make_scorer
import config as cfg
from model import deepfm
from model.deepfm import gini_norm
# from memory_profiler import profile
import gc

logger = cfg.logger

# # 由于基尼系数越大越好，所以用到了make_scorer   greater_is_better=true时越大越好
# gini_scorer = make_scorer(gini_norm, greater_is_better=True, needs_proba=True)

# @profile()
def load_data():
    train_df = pd.read_csv(cfg.TRAIN_FILE)
    test_df = pd.read_csv(cfg.TEST_FILE)

    def preprocess(df):
        cols = [c for c in df.columns if c not in ['id', 'target']]
        # df['missing_feat'] = np.sum(df[df[cols]==-1].values,axis=1)
        df["missing_feat"] = np.sum((df[cols] == -1).values, axis=1)
        df['ps_car_13_x_ps_reg_03'] = df['ps_car_13'] * df['ps_reg_03']
        return df

    train_df = preprocess(train_df)
    test_df = preprocess(test_df)

    # x_train 需要排除 id，target列，y是target列
    cols = [i for i in train_df.columns if i not in ['id', 'target']]
    x_train = train_df[cols].values
    y_train = train_df['target'].values
    # 测试数据集没有target列，所以需要置为-1
    x_test = test_df[cols].values
    # y_test = test_df['target'].values
    # y_test = -1

    # 返回带列名的x，不带列名的x，和Y
    return train_df, test_df, x_train, x_test, y_train

    del train_df
    gc.collect()

def emb_feat(train_df, test_df, numeuic_cols, ignore_cols):
    """
    :param train_df:
    :param test_df:
    :param numeuic_cols:
    :param ignore_cols:
    :return:feat_dict(特征索引), total_count（所有的特征数量，含不同的离散变量）
    """
    feat_dict = {}
    total_count = 0
    df = pd.concat([train_df, test_df])
    for col in df.columns:
        if col in ignore_cols:
            continue
        elif col in numeuic_cols:
            feat_dict[col] = total_count
            total_count += 1
        else:
            us = df[col].unique()
            # 这个里面对应的仍然是一个字典 里面的字典  key为每一个唯一的离散的特征，value为唯一索引（自增）
            feat_dict[col] = dict(zip(us, range(total_count, total_count + len(us))))
            total_count += len(us)
    return feat_dict, total_count

def feat_parse(feat_dict, df, has_label=False):
    df_i = df.copy()
    if has_label:
        y = df_i['target'].values.tolist()
        df_i.drop(['id', 'target'], axis=1, inplace=True)
    else:  # 测试数据集没有target
        ids = df_i['id'].values.tolist()
        df_i.drop(['id'], axis=1, inplace=True)
    # df_i for feature index
    # df_v for featur value which can be either binary(1/0) or float(e.g., 0.8899)
    df_v = df_i.copy()

    for col in df_i.columns:
        if col in cfg.IGNORE_COLS:
            df_i.drop(col, axis=1, inplace=True)
            df_v.drop(col, axis=1, inplace=True)
            continue
        elif col in cfg.NUMERIC_COLS:
            df_i[col] = feat_dict[col]
            # 这个少一个df_v啊  因为dv_v本来就是copy的train_df 所以不需要做任何更改
        # 离散变量
        else:
            # 取到字典中对应的索引值
            df_i[col] = df_i[col].map(feat_dict[col])
            df_v[col] = 1
        x_i = df_i.values.tolist()
        x_v = df_v.values.tolist()
        if has_label:
            return x_i, x_v, y
        else:
            return x_i, x_v, ids

def _make_submission(ids, y_pred, filename="submission.csv"):
    pd.DataFrame({"id": ids, "target": y_pred.flatten()}).to_csv(
        os.path.join(cfg.SUB_DIR, filename), index=False, float_format="%.5f")

def _plot_fig(train_results, valid_results, model_name):
    colors = ["red", "blue", "green"]
    xs = np.arange(1, train_results.shape[1] + 1)
    plt.figure()
    legends = []
    for i in range(train_results.shape[0]):
        plt.plot(xs, train_results[i], linestyle="solid", marker="o")
        plt.plot(xs, valid_results[i], linestyle="dashed", marker="o")
        legends.append("train-%d" % (i + 1))
        legends.append("valid-%d" % (i + 1))
    plt.xlabel("Epoch")
    plt.ylabel("Normalized Gini")
    plt.title("%s" % model_name)
    plt.legend(legends)
    plt.savefig("fig/%s.png" % model_name)
    plt.close()

if __name__ == '__main__':
    train_df, test_df, x_train, x_test, y_train = load_data()

    # 交叉验证,[(x1,y1),(x2,y2).....]
    folds = list(
        StratifiedKFold(n_splits=cfg.NUM_SPLITS, shuffle=True, random_state=cfg.RANDOM_SEED).split(x_train, y_train))
    # 处理特征 变成embedding
    feat_dict, total_count = emb_feat(train_df, test_df, cfg.NUMERIC_COLS, cfg.IGNORE_COLS)
    xi_train, xv_train, y_train = feat_parse(feat_dict=feat_dict, df=train_df, has_label=True)
    xi_test, xv_test, ids_test = feat_parse(feat_dict=feat_dict, df=test_df)

    dfm_params = cfg.dfm_params

    # 包含离散特征的取值  一共有多少个 例如年龄分别有12,14,15  total_count=3
    dfm_params['feature_size'] = total_count
    # 感觉像样本数量   也可能是特征数 例如年龄，性别  这就是2个特征
    dfm_params['field_size'] = len(xi_train[0])

    _get = lambda x, l: [x[i] for i in l]  # 假如l传入的是df，那么i即是列名

    # len(folds) 应该是folds分了多少层 就是多少，不是就应该等于cfg.NUM_SPLITS？  这个不懂 是不是4*30
    y_train_meta = np.zeros((train_df.shape[0], 1), dtype=float)
    y_test_meta = np.zeros((test_df.shape[0], 1), dtype=float)
    gini_results_cv = np.zeros(len(folds), dtype=float)
    gini_results_epoch_train = np.zeros((len(folds), dfm_params['epoch']), dtype=float)
    gini_results_epoch_valid = np.zeros((len(folds), dfm_params['epoch']), dtype=float)

    # folds 返回的是行索引   所以_get 匿名函数即是取kfold中分出来的数据集而已
    for i, (train_idx, valid_idx) in enumerate(folds):
        Xi_train_, Xv_train_, y_train_ = _get(xi_train, train_idx), _get(xv_train, train_idx), _get(y_train, train_idx)
        Xi_valid_, Xv_valid_, y_valid_ = _get(xi_train, valid_idx), _get(xv_train, valid_idx), _get(y_train, valid_idx)

        # 就是每一批训练了   重中之重-------------------------------------------------------------------------
        dfm = deepfm.DeepFm(**dfm_params)

        # fit
        dfm.fit(Xi_train_, Xv_train_, y_train_, Xi_valid_, Xv_valid_, y_valid_)

        y_train_meta[valid_idx, 0] = dfm.predict(Xi_valid_, Xv_valid_)
        y_test_meta[:, 0] += dfm.predict(xi_test, xv_test)

        gini_results_cv[i] = gini_norm(y_valid_, y_train_meta[valid_idx])
        gini_results_epoch_train[i] = dfm.train_result
        gini_results_epoch_valid[i] = dfm.valid_result

    y_test_meta /= float(len(folds))
    # save result
    if dfm_params["use_fm"] and dfm_params["use_deep"]:
        clf_str = "DeepFM"
    elif dfm_params["use_fm"]:
        clf_str = "FM"
    elif dfm_params["use_deep"]:
        clf_str = "DNN"
    print("%s: %.5f (%.5f)" % (clf_str, gini_results_cv.mean(), gini_results_cv.std()))
    filename = "%s_Mean%.5f_Std%.5f.csv" % (clf_str, gini_results_cv.mean(), gini_results_cv.std())
    _make_submission(ids_test, y_test_meta, filename)

    _plot_fig(gini_results_epoch_train, gini_results_epoch_valid, clf_str)

    print(y_train_meta, y_test_meta)  # 其实是验证数据集和测试数据集


# MODULES
# Consider a Module to be the same as a Code Library
# A File containing a set of Functions you want to include.
# This file uses the Modules_Modulefile.py for the examples.

# Standard Module Import
import modules_modulefile

# Create Alias for Module
import modules_modulefile as mm

# When using a Function from a Module, use the syntax: module_name.function_name
modules_modulefile.greeting("Johnathan Joestar")

# Modules can also have Variables of all types
x = modules_modulefile.person1["stand"]
print(x)

# Use Module Alias
y = mm.person1["firstname"]
print(y)

# Python has built in Modues, you can import whenever you like.
import platform
z = platform.system()
print(z)

# You can list all the Function Names or Variable Names in a Module.
# With the dir() function
zz = dir(platform)
print(zz)

# You can choose to import only perts from a Module, using the from Keyword
from modules_modulefile import person2

# When importing using the from Keyword, do not use the Module name when
# referring to elements in the Module. Use it like regular.
print(person2["stand"])


from guizero import App, PushButton, Slider, Text
from pygame import mixer
from threading import Thread
import sys
import signal
import os
import time
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BOARD)

os.putenv('DISPLAY',':0.0') #voir si c'est bon quand on lance directement depuis de RPI

app = App(title="Example", layout="grid")
app.bg='blue'

def main():
	app.tk.attributes("-fullscreen",True)
	app.tk.config(cursor='none')
	app.display() #agit comme une boucle infinie

def signal_handler(signal, frame):
	global NotFinished
	print('You pressed Ctrl+C!')
	print('Au revoir')
	NotFinished = False
	time.sleep(1)
	sys.exit(0)

def set1():
	alarmset=1
	bouton_set1.toggle()
	heure_alarm1.value=''
	for v in boutons:
		v.toggle()
def acv1():
	pass
	if bouton_acv1.bg == 'green':
		bouton_acv1.bg='red'
		bouton_acv1.text='ON'
	else:
		bouton_acv1.bg='green'
		bouton_acv1.text='OFF'
def playmusic():
	mixer.load('police.mp3')
	mixer.play(-1)

def num(args):
	global numchar,boutons
	temp=int(args)
	#print(args)
	#heure_alarm1.append(args)
	if numchar == 0:
		if temp > 2:
			numchar = 2
			heure_alarm1.append('0')
			heure_alarm1.append(args)
			heure_alarm1.append(':')
		else:
			numchar = 1
			heure_alarm1.append(args)
	elif numchar == 1:
		numchar = 2
		heure_alarm1.append(args)
		heure_alarm1.append(':')
	elif numchar == 2:
		if temp < 6:
			heure_alarm1.append(args)
			numchar=3
	elif numchar == 3:
		heure_alarm1.append(args)
		numchar=0
		for v in boutons:
			v.toggle()
		bouton_set1.toggle()
def quit():
	global NotFinished
	NotFinished=False
	print('quit by HMI')
	time.sleep(1)
	sys.exit(0)

class TimeMgt(Thread):
	def __init__(self):
		Thread.__init__(self)
		print('init heure')
	def run(self):
		while NotFinished is True:
			self.heure=time.localtime()
			cur_time.value = str(self.heure.tm_hour) + ':'
			cur_time.append(str(self.heure.tm_min) + ':')
			cur_time.append(self.heure.tm_sec)
			print (self.heure.tm_sec)
			time.sleep(1)

numchar = 0 #nombre de caracteres ajouté
NotFinished = True
mixer.init()
#fond = Text(app,text=' ',grid=[0,0,12,8])
#toto = Text(app,text='08:10',height=20,grid=[0,0])
bouton_quit = PushButton(app,text='X',command=quit,grid=[0,0])
heure_alarm1 = Text(app,text='08:20',grid=[0,1])
heure_alarm1.text_size = 50
#heure_alarm2 = Text(app,text='10:30',text_size=20,grid=[0,3])
bouton_set1 = PushButton(app,text=' Set 1 ',width=6,grid=[0,2],command=set1)
bouton_set1.text_size=30
bouton_acv1 = PushButton(app,text=' OFF ',width=5,grid=[1,2],command=acv1)
#bouton_acv1.text_size=30
cur_time = Text(app,text='00:00:00',grid=[0,4])
cur_time.text_size = 30

b1 = PushButton(app,text=' 1 ',grid=[2,1],command=num,args='1')
b2 = PushButton(app,text=' 2 ',grid=[3,1],command=num,args='2')
b3 = PushButton(app,text=' 3 ',grid=[4,1],command=num,args='3')
b4 = PushButton(app,text=' 4 ',grid=[2,2],command=num,args='4')
b5 = PushButton(app,text=' 5 ',grid=[3,2],command=num,args='5')
b6 = PushButton(app,text=' 6 ',grid=[4,2],command=num,args='6')
b7 = PushButton(app,text=' 7 ',grid=[2,3],command=num,args='7')
b8 = PushButton(app,text=' 8 ',grid=[3,3],command=num,args='8')
b9 = PushButton(app,text=' 9 ',grid=[4,3],command=num,args='9')
bv = PushButton(app,text='   ',grid=[2,4])
b0 = PushButton(app,text=' 0 ',grid=[3,4],command=num,args='0')
bV = PushButton(app,text='   ',grid=[4,4])
boutons=[b1,b2,b3,b4,b5,b6,b7,b8,b9,b0,bv,bV]
#boutons=[b2,b3,b5,b6,b8,b9,b0,bV]
for v in boutons:
	#print(v)
	v.text_size = 50
	v.toggle()

signal.signal(signal.SIGINT, signal_handler)

if __name__ == '__main__':
	timemgt = TimeMgt()
	timemgt.start()
	main()
	print('voila')


import logging
import signal
from unittest.mock import call, Mock, patch

import pytest
import zmq

from nemo_nowcast import log_aggregator

@patch("nemo_nowcast.log_aggregator.CommandLineInterface")
@patch("nemo_nowcast.log_aggregator.Config")
@patch("nemo_nowcast.log_aggregator._configure_logging")
@patch("nemo_nowcast.log_aggregator.logging")
@patch("nemo_nowcast.log_aggregator.run")
class TestMain:
    """Unit tests for log_aggregator.main function.
    """

    def test_commandline_interface(
        self, m_run, m_logging, m_config_logging, m_config, m_cli
    ):
        log_aggregator.main()
        args, kwargs = m_cli.call_args_list[0]
        assert args[0] == "log_aggregator"
        assert "package" in kwargs
        assert "description" in kwargs
        m_cli.build_parser.asser_called_once_with()

    def test_cli_parser(self, m_run, m_logging, m_config_logging, m_config, m_cli):
        log_aggregator.main()
        m_cli().parser.parse_args.assert_called_once_with()

    def test_config_load(self, m_run, m_logging, m_config_logging, m_config, m_cli):
        m_cli().parser.parse_args.return_value = Mock(config_file="nowcast.yaml")
        log_aggregator.main()
        m_config().load.assert_called_once_with("nowcast.yaml")

    def test_logging_config(self, m_run, m_logging, m_config_logging, m_config, m_cli):
        log_aggregator.main()
        m_config_logging.assert_called_once_with(m_config())

    @patch("nemo_nowcast.log_aggregator.logger")
    def test_logging_info(
        self, m_logger, m_run, m_logging, m_config_logging, m_config, m_cli
    ):
        log_aggregator.main()
        assert m_logger.info.call_count == 2

    def test_run(self, m_run, m_logging, m_config_logging, m_config, m_cli):
        log_aggregator.main()
        m_run.assert_called_once_with(m_config())

@patch("nemo_nowcast.log_aggregator.logging.config")
class TestConfigureLogging:
    """Unit tests for log_aggregator._configure_logging function.
    """

    config = {
        "logging": {
            "aggregator": {
                "handlers": {
                    "info_text": {
                        "class": "logging.handlers.RotatingFileHandler",
                        "backupCount": 7,
                    }
                }
            }
        }
    }

    def test_change_rotating_logger_handler_to_watched(self, m_logging_config):
        log_aggregator._configure_logging(self.config)
        handler = self.config["logging"]["aggregator"]["handlers"]["info_text"]
        assert handler["class"] == "logging.handlers.WatchedFileHandler"
        assert "backupCount" not in handler

    def test_logging_configure_dictConfig(self, m_logging_config):
        log_aggregator._configure_logging(self.config)
        m_logging_config.dictConfig.assert_called_once_with(
            self.config["logging"]["aggregator"]
        )

@patch("nemo_nowcast.log_aggregator.context")
@patch("nemo_nowcast.log_aggregator._install_signal_handlers")
@patch("nemo_nowcast.log_aggregator._process_messages")
class TestRun:
    """Unit tests for log_aggregator.run function.
    """

    def test_manager_port(self, m_proc_msgs, m_ish, m_context):
        config = {"zmq": {"host": "localhost", "ports": {"logging": {"manager": 4343}}}}
        log_aggregator.run(config)
        m_context.socket(zmq.SUB).connect.assert_called_once_with(
            "tcp://localhost:4343"
        )

    def test_local_worker_ports_list(self, m_proc_msgs, m_ish, m_context):
        config = {
            "zmq": {
                "host": "localhost",
                "ports": {"logging": {"workers": [4345, 4346]}},
            }
        }
        log_aggregator.run(config)
        assert m_context.socket(zmq.SUB).connect.call_args_list == [
            call("tcp://localhost:4345"),
            call("tcp://localhost:4346"),
        ]

    def test_remote_worker(self, m_proc_msgs, m_ish, m_context):
        config = {
            "zmq": {
                "host": "localhost",
                "ports": {"logging": {"manager": "salish:4348"}},
            }
        }
        log_aggregator.run(config)
        m_context.socket(zmq.SUB).connect.assert_called_once_with("tcp://salish:4348")

    def test_install_signal_handlers(self, m_proc_msgs, m_ish, m_context):
        config = {"zmq": {"host": "localhost", "ports": {"logging": {"worker": 4343}}}}
        log_aggregator.run(config)
        m_ish.assert_called_once_with(m_context.socket())

    def test_process_messages(self, m_proc_msgs, m_ish, m_context):
        config = {"zmq": {"host": "localhost", "ports": {"logging": {"worker": 4343}}}}
        log_aggregator.run(config)
        m_proc_msgs.assert_called_once_with(m_context.socket())

@patch("nemo_nowcast.log_aggregator.zmq.Socket", spec=zmq.Socket)
@patch("nemo_nowcast.log_aggregator.logger")
class TestLogMessages:
    """Unit test for log_aggregator._log_messages function.
    """

    def test_log_messages(self, m_logger, m_socket):
        m_socket.recv_multipart.return_value = [b"worker_name.INFO", b"message"]
        log_aggregator._log_messages(m_socket)
        m_logger.log.assert_called_once_with(
            logging.INFO, "message", extra={"logger_name": "worker_name"}
        )

@pytest.mark.parametrize(
    "i, sig", [(0, signal.SIGHUP), (1, signal.SIGINT), (2, signal.SIGTERM)]
)
class TestInstallSignalHandlers:
    """Unit tests for log_aggregator._install_signal_handlers function.
    """

    def test_signal_handlers(self, i, sig):
        with patch("nemo_nowcast.log_aggregator.signal.signal") as m_signal:
            log_aggregator._install_signal_handlers(Mock(name="socket"))
        args, kwargs = m_signal.call_args_list[i]
        assert args[0] == sig


#hrs = input("Enter Hours : ")
try:
    hrs = input("Enter Hours : ")
    #hr = int(hrs)
except:
    hr = "Error, please enter numeric input"
    print(hr)
#rate = input("Enter Rate per hour : ")
try:
    rate = input("Enter Rate per hour : ")
    #rt = int(rate)
except:
    rt = "Error, please enter numeric input"
    print(rt)

if hr>40:
    pay = 40 * rt + (hr - 40) * rt * 1.5
else:
	pay = hr * rt
print(pay)


import os, math, random, argparse, time
import torch
import numpy as np
import scipy.io as sio
import scipy.sparse as ssp
from tqdm import tqdm
from dgcnn.models import *
from utils.train_utils import *
from utils.io_utils import save_checkpoint
from tqdm import tqdm

def args_parse():
    parser = argparse.ArgumentParser(description='Link Prediction with SEAL')
    # general settings
    parser.add_argument('--data-name', help='network name')
    parser.add_argument('--train-name', help='train name')
    parser.add_argument('--test-name', help='test name')
    parser.add_argument('--no-cuda', action='store_true', default=False, help='disables CUDA training')
    parser.add_argument('--seed', type=int, metavar='S', help='random seed')
    parser.add_argument('--name-suffix', dest='name_suffix', help='suffix added to the output filename')
    parser.add_argument('--logdir', dest='logdir', help='Tensorboard log directory')
    parser.add_argument('--ckptdir', dest='ckptdir', help='Model checkpoint directory')
    # settings for stage 1 and 2
    parser.add_argument('--symmetric', action='store_true', default=False, help='whether to check net symmetry (for small nets only)')
    parser.add_argument('--max-train-num', type=int, help='set maximum number of train links (to fit into memory)')
    parser.add_argument('--test-ratio', type=float, help='ratio of test links')
    parser.add_argument('--hop', metavar='S', help='enclosing subgraph hop number, options: 1, 2,..., "auto"')
    parser.add_argument('--max-nodes-per-hop', help='if > 0, upper bound the # nodes per hop by subsampling')
    parser.add_argument('--use-embedding', help='how to use embeddings, option: None, "node2vec", "word2vec"')
    parser.add_argument('--no-attribute', action='store_true', default=False, help='whether not to use node attributes')
    parser.add_argument('--parallel', action='store_true', default=False, help='whether to extract subgraphs in parallel')
    # DGCNN configurations (primary)
    cmd_args = parser.add_argument_group(description='Arguments for DGCNN')
    cmd_args.add_argument('--mode', help='cpu/gpu')
    cmd_args.add_argument('--gm', help='gnn model to use')
    cmd_args.add_argument('--feat-dim', type=int, help='dimension of discrete node feature (maximum node tag)')
    cmd_args.add_argument('--edge-feat-dim', type=int, help='dimension of edge features')
    cmd_args.add_argument('--embed-dim', type=int, help='dimension of node embeddings')
    cmd_args.add_argument('--attr-dim', type=int, help='dimension of node attributes')
    cmd_args.add_argument('--num-class', type=int, help='#classes')
    cmd_args.add_argument('--num-epochs', type=int, help='number of epochs')
    cmd_args.add_argument('--batch-size', type=int, help='minibatch size')
    cmd_args.add_argument('--latent-dim', help='dimension(s) of latent layers')
    cmd_args.add_argument('--sortpooling-k', type=float, help='number of nodes kept after SortPooling')
    cmd_args.add_argument('--conv1d-activation', type=str, help='which nn activation layer to use')
    cmd_args.add_argument('--output-dim', type=int, help='graph embedding output size')
    cmd_args.add_argument('--hidden-dim', type=int, help='dimension of mlp hidden layer')
    cmd_args.add_argument('--dropout', type=bool, help='whether add dropout after dense layer')
    cmd_args.add_argument('--printAUC', type=bool, help='whether to print AUC (for binary classification only)')
    # optimization
    opt_parser = parser.add_argument_group()
    opt_parser.add_argument('--opt', dest='opt', type=str, help='Type of optimizer')
    opt_parser.add_argument('--opt-scheduler', dest='opt_scheduler', type=str, help='Type of optimizer scheduler (by default none)')
    opt_parser.add_argument('--opt-decay-step', dest='opt_decay_step', type=int, help='Number of epochs before decay')
    opt_parser.add_argument('--opt-decay-rate', dest='opt_decay_rate', type=float, help='Learning rate decay ratio')
    opt_parser.add_argument('--opt-restart', dest='opt_restart', type=int, help='Number of epochs before restart (by default set to 0 which means no restart)')
    opt_parser.add_argument('--lr', dest='lr', type=float, help='Learning rate')
    # defaults
    parser.set_defaults(data_name='dbyoA',  # general settings
                        train_name=None,
                        test_name=None,
                        seed=1,
                        name_suffix='',
                        logdir='test/log',
                        ckptdir='test/ckpt',
                        max_train_num=100000,  # settings for stage 1 and 2
                        test_ratio=0.1,
                        hop=1,
                        max_nodes_per_hop=None,
                        use_embedding = "word2vec",
                        mode='cpu',  # DGCNN configurations (primary)
                        gm='DGCNN',
                        feat_dim=0,
                        edge_feat_dim=0,
                        embed_dim = 0,
                        attr_dim = 0,
                        num_class=2,
                        num_epochs=50,
                        batch_size=50,
                        latent_dim=[32,32,32,1],
                        sortpooling_k=0.6,
                        conv1d_activation='ReLU',
                        output_dim=0,
                        hidden_dim=128,
                        dropout=True,
                        printAUC=True,
                        opt='adam',  # optimization
                        opt_scheduler='none',
                        lr=1e-4
                       )
    return parser.parse_args()

def loop_dataset(g_list, classifier, sample_idxes, bsize, optimizer=None, scheduler=None):
    total_loss = []
    total_iters = (len(sample_idxes) + (bsize - 1) * (optimizer is None)) // bsize
    pbar = tqdm(range(total_iters), unit='batch')
    all_targets = []
    all_scores = []

    n_samples = 0
    for pos in pbar:
        selected_idx = sample_idxes[pos * bsize : (pos + 1) * bsize]

        batch_graph = [g_list[idx] for idx in selected_idx]
        targets = [g_list[idx].label for idx in selected_idx]
        all_targets += targets
        if classifier.regression:
            pred, mae, loss = classifier(batch_graph)
            all_scores.append(pred.cpu().detach())  # for binary classification
        else:
            # logits, loss, acc, p, r, f1 = classifier(batch_graph)
            logits, loss, acc = classifier(batch_graph)
            all_scores.append(logits[:, 1].cpu().detach())  # for binary classification

        if optimizer is not None:
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            if scheduler is not None:
                    scheduler.step()

        loss = loss.data.cpu().detach().numpy()
        if classifier.regression:
            pbar.set_description('MSE_loss: %0.5f MAE_loss: %0.5f' % (loss, mae) )
            total_loss.append( np.array([loss, mae]) * len(selected_idx))
        else:
            pbar.set_description('loss: %0.5f acc: %0.5f' % (loss, acc) )
            total_loss.append( np.array([loss, acc]) * len(selected_idx))

        n_samples += len(selected_idx)
    if optimizer is None:
        assert n_samples == len(sample_idxes)
    total_loss = np.array(total_loss)
    avg_loss = np.sum(total_loss, 0) / n_samples
    all_scores = torch.cat(all_scores).cpu().numpy()

    # np.savetxt('test_scores.txt', all_scores)  # output test predictions

    if not classifier.regression:
        all_targets = np.array(all_targets)
        fpr, tpr, _ = metrics.roc_curve(all_targets, all_scores, pos_label=1)
        auc = metrics.auc(fpr, tpr)
        # avg_loss = np.concatenate((avg_loss, [auc, p, r, f1]))
        avg_loss = np.concatenate((avg_loss, [auc]))

    return avg_loss

def main():
    start = time.time()

    '''argument settings'''
    args = args_parse()
    args.cuda = not args.no_cuda and torch.cuda.is_available()
    args.file_dir = os.path.dirname(os.path.realpath('__file__'))
    if args.hop != 'auto':
        args.hop = int(args.hop)
    if args.max_nodes_per_hop is not None:
        args.max_nodes_per_hop = int(args.max_nodes_per_hop)

    random.seed(args.seed)
    np.random.seed(args.seed)
    torch.manual_seed(args.seed)
    if args.cuda:
        torch.cuda.manual_seed(args.seed)

    ''' stage 1 and 2: enclosing subgraph extraction, node information matrix construction'''
    # load net and sample train_pos, train_neg, test_pos, test_neg links
    if args.train_name is None:
        args.data_dir = os.path.join(args.file_dir, 'data', args.data_name, '{}.mat'.format(args.data_name))
        data = sio.loadmat(args.data_dir)
        net = data['net']

        if 'match' in data.keys():
        # load same_as links
            match = data['match']
        if 'iden' in data.keys():
        # load vid_entity mapping
            iden = data['iden']
        if args.symmetric:
        # check whether net is symmetric (for small nets only)
            net_ = net.toarray()
            #net_[idx_list, :] = 0
            #net_[:, idx_list] = 0
            assert(np.allclose(net_, net_.T, atol=1e-8))
        train_pos, train_neg, test_pos, test_neg = sample_neg(mat=match, test_ratio=args.test_ratio, max_train_num=args.max_train_num)
        train_pos, train_neg, test_pos, test_neg = entity2vid(train_pos, iden), entity2vid(train_neg, iden), entity2vid(test_pos, iden), entity2vid(test_neg, iden)
        verify_sample(net, train_pos, train_neg, test_pos, test_neg)
    else:
        args.train_dir = os.path.join(args.file_dir, 'data/{}'.format(args.train_name))
        args.test_dir = os.path.join(args.file_dir, 'data/{}'.format(args.test_name))
        train_idx = np.loadtxt(args.train_dir, dtype=int)
        test_idx = np.loadtxt(args.test_dir, dtype=int)
        max_idx = max(np.max(train_idx), np.max(test_idx))
        net = ssp.csc_matrix((np.ones(len(train_idx)),(train_idx[:,0],train_idx[:,1])), shape=(max_idx+1, max_idx+1))
        net[train_idx[:, 1], train_idx[:, 0]] = 1  # add symmetric edges
        net[np.arange(max_idx+1), np.arange(max_idx+1)] = 0  # remove self-loops
        # sample negative links (resp. for train and test)
        train_pos = (train_idx[:, 0], train_idx[:, 1])
        test_pos = (test_idx[:, 0], test_idx[:, 1])
        train_pos, train_neg, test_pos, test_neg = sample_neg(net, train_pos=train_pos, test_pos=test_pos, max_train_num=args.max_train_num)

    A = net.copy()  # the observed network

    A[test_pos[0], test_pos[1]] = 0  # mask test links
    A[test_pos[1], test_pos[0]] = 0  # mask test links

    # node information matrix construction: load node embeddings and node attributes (here a.k.a. node classes)
    if args.use_embedding == 'node2vec':
        embeddings = generate_node2vec_embeddings(A, 128, True, train_neg)
    elif args.use_embedding == 'word2vec' and 'w2v' in data.keys():
        embeddings = data['w2v']
    else:
        embeddings = None
    if (not args.no_attribute) and ('group' in data.keys()):
        attributes = data['group']
    else:
        attributes = None

    # enclosing subgraph extraction
    train_graphs, test_graphs, max_n_label = links2subgraphs(A, train_pos, train_neg, test_pos, test_neg, args.hop, args.max_nodes_per_hop, embeddings, attributes, args.parallel)
    print('#train: %d, #test: %d' % (len(train_graphs), len(test_graphs)))

    '''stage 3: GNN Learning'''
    # DGCNN configurations
    args.mode = 'gpu' if args.cuda else 'cpu'
    args.feat_dim = max_n_label + 1
    if embeddings is not None:
        args.embed_dim = embeddings.shape[1]
    if attributes is not None:
        args.attr_dim = attributes.shape[1]
    if args.sortpooling_k <= 1:
        num_nodes_list = sorted([g.num_nodes for g in train_graphs+test_graphs])
        args.sortpooling_k = num_nodes_list[int(math.ceil(args.sortpooling_k*len(num_nodes_list)))-1]
        args.sortpooling_k = max(10, args.sortpooling_k)
        print('k used in SortPooling is: ' + str(args.sortpooling_k))

    # model and optimizer
    classifier = Classifier(args)
    if args.mode == 'gpu':
        classifier = classifier.cuda()
    scheduler, optimizer = build_optimizer(args, classifier.parameters())

    # train and test
    train_idx = list(range(len(train_graphs)))
    best_loss = None
    for epoch in range(args.num_epochs):
        random.shuffle(train_idx)
        classifier.train()
        avg_loss = loop_dataset(train_graphs, classifier, train_idx, args.batch_size, optimizer=optimizer, scheduler=scheduler)
        if not args.printAUC:
            avg_loss[2] = 0.0
        # print('\033[92maverage training of epoch %d: loss %.3f acc %.3f auc %.3f p %.3f r %.3f f1 %.3f\033[0m' % (epoch, avg_loss[0], avg_loss[1], avg_loss[2], avg_loss[3], avg_loss[4], avg_loss[5]))
        print('\033[92maverage training of epoch %d: loss %.5f acc %.5f auc %.5f\033[0m' % (epoch, avg_loss[0], avg_loss[1], avg_loss[2]))

        classifier.eval()
        test_loss = loop_dataset(test_graphs, classifier, list(range(len(test_graphs))), args.batch_size)
        if not args.printAUC:
            test_loss[2] = 0.0
        # print('\033[93maverage test of epoch %d: loss %.3f acc %.3f auc %.3f p %.3f r %.3f f1 %.3f\033[0m' % (epoch, test_loss[0], test_loss[1], test_loss[2], test_loss[3], test_loss[4], test_loss[5]))
        print('\033[93maverage test of epoch %d: loss %.5f acc %.5f auc %.5f\033[0m' % (epoch, test_loss[0], test_loss[1], test_loss[2]))

    # save evaluation results
    os.makedirs(args.logdir+'/SEAL', exist_ok=True)
    with open(args.logdir+'/SEAL/test_results.txt', 'a+') as f:
        f.write(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())+'\t'+args.data_name+'\t'+str(test_loss[0])+'\t'+str(test_loss[1])+'\t'+str(test_loss[2])+'\t'+args.name_suffix+'\n')

    # save checkpoint
    graphs = train_graphs + test_graphs
    cg_dict = { 'graph': graphs,
                'adj': np.array([graph.adj for graph in graphs]),
                'feat': np.array([graph.node_attrs for graph in graphs]),
                'label': np.array([graph.label for graph in graphs])}
    #print(cg_dict['feat'])
    print(cg_dict['feat'].shape)
    #exit(0)
    save_checkpoint(args, classifier, cg_dict)

    # print total time
    end = time.time()
    print('All finished in {}s.'.format(end - start))

if __name__ == "__main__":
    main()


from typing import List

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        if not nums:
            return 0
        # 参考：https://leetcode-cn.com/problems/lian-xu-zi-shu-zu-de-zui-da-he-lcof/solution/mian-shi-ti-42-lian-xu-zi-shu-zu-de-zui-da-he-do-2/
        for i in range(1, len(nums)):
            nums[i] = max(nums[i - 1] + nums[i], nums[i], 0)
        # print(nums)
        return max(nums)

numbers = [1, -2, 3, 5, -2, 6, -1]
# numbers = [-2, 1]
print(Solution().maxSubArray(numbers))

牛客网/剑指offer/子数组最大累计和.py


CONFIGS = {
# Initial diversification params
    'nstruct_div': 10, #per job
    'njobs_div'  : 100, # NSTRUCT*NJOBS = NTOTAL per option (aggr/cons)

## All below are for iterative process
#Basic run opt
    'niter'                  : 30,
    'debug'                  : False,
    'simple'                 : False,
    'nproc'                  : 60,           #Ncores to use
    'max_min_terminate'      : 240.0,        #kill if each iter last longer than this
    'npool'                  : 50,           #N members in the pool

# Scoring params
    'cstweight'              : 0.2,
    'cst_fa_weight'          : 1.0,
    #'cencst'                 : '',
    #'facst'                  : '',
    'pool_update'            : 'Q',   # [standard/Q/Qlocal/...]

# Sampling params
    'mulfactor_phase0'       : 1.0,
    'ntempl_per_job'         : 5,            #how may templates per each hybrid run
    'cross2_autocst'         : True,
    'reconstruct_every_iter' : True,
    'xml_cross1_suffix'      : 'cross.xml',  #use faster hybrid
    'xml_cross2_suffix'      : 'cross2.xml',
    'xml_mut_suffix'         : 'mut.xml',

# GA/CSA params
    'nseed'                  : 10,
    'nperseed'               : 4,            # 4-n for cross / n for mut
    'ngen_per_job'           : 3,            #total jobs: NSEED*NPERSEED*NGEN_PER_JOB : 120
    'nmutperseed'            : {0:2},        # key: phase value: nmut
    'dcut0'                  : 0.4,          #max dcut
    'dcut_min_scale'         : 0.5,          #DCUTMIN:DCUT0*DCUT_MIN_SCALE
    'n0_to_reset'            : 3,            #
    'simlimit_base'          : 0.05,
    'recomb'                 : "random",
    'recomb_iter'            : 5, #unused if <0

# Deformation factor params
    'penalize_wrt_init'      : 1,
    'iha'                    : 25.0,

# Extra options
    'e2cst_args'             : '-pcore 0.8 0.8 0.9',
    'native'                 : '',
    'symmetric'              :  0,
    'symmdef'                : ''
}


# See other file for comments
class Seg_Tree:

    def __init__(self, n):
        self.n = n
        self.tree = [0] * (n*2)

    def find_max(self, low, high): # Inclusive
        low += self.n
        high += self.n

        max_val = 0
        while low < high:
            if low % 2 == 1: # low & 1 also works
                max_val = max(max_val, self.tree[low])
                low += 1
            if high % 2 == 0:
                max_val = max(max_val, self.tree[high])
                high -= 1

            low = low >> 1
            high = high >> 1

        if low == high:
            max_val = max(max_val, self.tree[low])

        return max_val

    def update(self, index, value):
        index += self.n
        self.tree[index] = value
        while index >> 1 > 0:
            index = index >> 1
            self.tree[index] = max(self.tree[index << 1], self.tree[(index << 1) + 1])

class Solution:

    def forward_with_segtree(self, nums, k):
        solution_tree = Seg_Tree(max(nums) + 1)

        for x in nums:
            max_subseq = 1 + solution_tree.find_max(max(0, x - k), x - 1)
            solution_tree.update(x, max_subseq)

        return solution_tree.find_max(0, max(nums))

    def lengthOfLIS(self, nums: list[int], k: int) -> int:
        return self.forward_with_segtree(nums, k)

test = Solution()
input = [7,4,5,1,8,12,4,7]
# input = list(range(1, 100000))
k = 5
result = test.lengthOfLIS(input, k)
print(result)


from flask import Flask, request, jsonify, render_template
from flask_cors import CORS
import requests
import os

app = Flask(__name__)
CORS(app)

# search_query = input('Enter search query')
# numberOfImages  = int(input('Number of Images'))

from google_images_download import google_images_download

@app.route('/', methods=['GET'])
def index():
    return render_template('index.html')

@app.route('/google', methods=['GET'])
def google():
    return render_template('google.html')

@app.route('/instagram', methods=['GET'])
def instagram():
    return render_template('instagram.html')

@app.route('/website', methods=['GET'])
def website():
    return render_template('website.html')

@app.route('/classes', methods=['GET'])
def classes():
    return render_template('classes.html')

@app.route('/search', methods=['GET','POST'])
def main():

    search_query=request.json['search']
    numberOfImages=request.json['number']

    response = google_images_download.googleimagesdownload()

    # print(os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop'))

    # def downloadimages(query):

    arguments = {"keywords": search_query,
                "format": "jpg",
                "limit":numberOfImages,
                "print_urls":True,
                "size": "medium",
                "aspect_ratio":"panoramic",
                "output_directory": os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')}
                # "output_directory": os.path.join(os.path.join(os.environ['HOME']), 'Desktop')}
    # try:
    response.download(arguments)
    return render_template('google.html')

        # # Handling File NotFound Error
        # except FileNotFoundError:
        #     arguments = {"keywords": query,
        #                 "format": "jpg",
        #                 "limit":4,
        #                 "print_urls":True,
        #                 "size": "medium"}

        #     # Providing arguments for the searched query
        #     try:
        #         # Downloading the photos based
        #         # on the given arguments
        #         response.download(arguments)
        #         return 200
        #     except:
        #         pass
        #         return 500

    # Driver Code

    # downloadimages(search_query)
    # print()

@app.route('/bsearch', methods=['POST'])
def bsearch():
    search_query=request.json['search']
    numberOfImages=request.json['number']

#     print(os.path.join(os.path.join(os.environ['HOME']), 'Desktop'))

    import pathlib

    desktop = pathlib.Path.home() / 'Desktop'

    from bing_image_downloader import downloader

    downloader.download(search_query, limit=int(numberOfImages),  output_dir=desktop, adult_filter_off=True, force_replace=False, timeout=60, verbose=True)

    return jsonify({ 'msg': 'Successful' })

@app.route('/instaprofile', methods=['GET', 'POST'])
def instasearch():
    profile = request.json['profile']

    import instaloader

    instaloader.Instaloader().download_profile(profile, profile_pic_only=False)

    return jsonify({ 'msg': 'Successful' })

if __name__ == '__main__':
    app.run(debug=False)


import logging
import argparse
import sys
import os
import time
# Package imports
from dbsync import UpDown

# Create logger for jplotlib
logger = logging.getLogger(__name__)

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

def main():
    """Main program.

    Parse command line, then iterate over files and directories under
    rootdir and upload all files.  Skips some temporary files and
    directories, and avoids duplicate uploads by comparing size and
    mtime with the server.
    """

    parser = argparse.ArgumentParser(description='Sync ~/dropbox to Dropbox')
    parser.add_argument('--rootdir',
                        default=os.environ['DROPBOX_ROOTDIR'] if "DROPBOX_ROOTDIR" in os.environ else "~/Downloads",
                        help='Local directory to upload')
    parser.add_argument('--folder', '-f',
                        default=os.environ['DROPBOX_FOLDER'] if "DROPBOX_FOLDER" in os.environ else "",
                        help='Folder name in your Dropbox')
    parser.add_argument('--appKey', default=os.environ['DROPBOX_APP_KEY'] if "DROPBOX_APP_KEY" in os.environ else "",
                        help='Application key')
    parser.add_argument('--appSecret',
                        default=os.environ['DROPBOX_APP_SECRET'] if "DROPBOX_APP_SECRET" in os.environ else "",
                        help='Application secret')
    parser.add_argument('--refreshToken',
                        default=os.environ['DROPBOX_REFRESH_TOKEN'] if "DROPBOX_REFRESH_TOKEN" in os.environ else "",
                        help='Refresh token')
    parser.add_argument('--interval', '-i',
                        default=int(os.environ['DROPBOX_INTERVAL']) if "DROPBOX_INTERVAL" in os.environ else 10,
                        help='Interval to sync from dropbox')
    parser.add_argument('--fromDropbox', action='store_true',
                        help='Direction to synchronize Dropbox')
    parser.add_argument('--fromLocal', action='store_true',
                        help='Direction to synchronize Dropbox')
    parser.add_argument('--verbose', '-v', action='store_true',
                        help='Show all Take default answer on all questions')
    # Parser arguments
    args = parser.parse_args()
    # Initialize loggger
    level = logging.DEBUG if args.verbose else logging.INFO
    logging.basicConfig(level=level, format='%(name)s - %(levelname)s - %(message)s')
    # Check token
    if not (args.appKey and args.appSecret):
        print(f"{bcolors.FAIL}app key and app secret must be set{bcolors.ENDC}")
        sys.exit(2)

    # Check folders
    folder = args.folder
    rootdir = os.path.expanduser(args.rootdir)
    if not os.path.exists(rootdir):
        print(f"{bcolors.FAIL}{rootdir} does not exist on your filesystem{bcolors.ENDC}")
        sys.exit(1)
    elif not os.path.isdir(rootdir):
        print(f"{bcolors.FAIL}{rootdir} is not a folder on your filesystem{bcolors.ENDC}")
        sys.exit(1)
    # Configure type of overwrite
    if args.fromDropbox:
        overwrite = "dropbox"
    elif args.fromLocal:
        overwrite = "host"
    else:
        overwrite = ""

    # Start updown sync with refresh token, designed for long living
    updown = UpDown(args.appKey, args.appSecret, args.refreshToken, folder, rootdir, interval=args.interval,
                    overwrite=overwrite)

    # Run observer
    logger.info("Server started")
    updown.start()
    # Run loop
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        logger.debug("Keyboard interrupt")
    # Stop server
    updown.stop()

if __name__ == '__main__':
    main()
# EOF


from app import app,paystack
from flask import request,render_template, redirect,session,flash
from random import randint
bal = 0
@app.route('/')
def index():
    global bal
    return render_template("index.html",bal=bal)

@app.post('/payment/initializePaymentGateway')
def PaystackInit():
    data = request.form
    email = data.get('email')
    amount = data.get('amount')
    reference = str(randint(1000000,99999999))
    try:
        init = paystack.InitializeTransaction(email,amount,reference,callback_url=f'http://localhost:5000/verify_transaction')
        if init[1]:
            return redirect(init[0]['data']['authorization_url'])
        else:
            return init[0]
    except:
        return "Err something went wrong with tour connection"
@app.route('/verify_transaction')
def verify():
    global bal
    data = request.args.get
    reference = data('reference')

    init = paystack.VerifyTransaction(reference)
    if init[0]['status']:
        bal += (init[0]['data']['amount']/100)
        flash('success')
        return redirect('/')
    else:
        flash('failed')
        return redirect('/')
# @app.route('/successful')
# def success():


from distance import Distance
from engine import Engine
from time import sleep, sleep_us, sleep_ms
from light import Light
import utime
import time
from machine import Pin, PWM
import network
import socket
import urequests

LDRFront = Pin(16, Pin.IN)
LDRRight = Pin(17, Pin.IN)
LDRLeft = Pin(4, Pin.IN)

engine = Engine()
distance = Distance()
light = Light()

threshold = 20
freq = 1

NO = 0
LEFT = 1
RIGHT = 2
turn = NO
turnOld = NO
countFront = 0
countRight = 0
countLeft = 0
countLight = ""
receive = 0

greenLightFront = False
greenLightRight = False
greenLightLeft = False
blueLightFront = False
blueLightRight = False
blueLightLeft = False
redLightFront = False
redLightRight = False
redLightLeft = False

def do_connect():
    import network
    sta_if = network.WLAN(network.STA_IF)
    if not sta_if.isconnected():
        print('connecting to network...')
        sta_if.active(True)
        sta_if.connect('WieHeistEuerWlan', 'Unser12PW34geht56so78')
        while not sta_if.isconnected():
            pass
    print('network config:', sta_if.ifconfig())

do_connect()

addr_info = socket.getaddrinfo("192.168.2.143", 42042)
addr = addr_info[0][-1]
s = socket.socket()
s.connect(addr)
s.send(b"CONNECTED")
print("Maybe sended")
#a = 0
try:
    engine.both()
    start = utime.ticks_us()
    t_last = time.time()
    timeE = 0
    while True:
        #print("Loops: " + str(a))
        #a += 1
        stop = utime.ticks_us()
        t = (stop-start)/1000000
        start = stop
        timeE += t

        if receive == 0:
            countLight = ""
            countLight = s.recv(1024)
            print("received: " + str(countLight))
            if countLight == b'0' or countLight == b'1' or countLight == b'2':
                receive = 1
                print("RECEIVED SOMETIHNG!!" + " Receive = "+ str(receive))
        tLED = time.time()
        if tLED-t_last > freq and countFront+countRight+countLeft < 3:
            print(LDRFront.value())
            if LDRFront.value() == 1 or countFront == 1:
                if redLightFront == False:
                    light.redLightFront()
                    greenLightFront = False
                    blueLightFront = False
                    redLightFront = True
                countFront = 1
                if countLight == b'0' and LDRFront.value() == 1:
                    countRight = 1
                    countLeft = 1
                    light.redLightRight()
                    light.redLightLeft()
                    receive = 0
            elif countLight == b'0' and countFront == 0:
                if blueLightFront == False:
                    light.blueLightFront()
                    blueLightFront = True
                    greenLightFront = False
                    redLightFront = False
            else:
                if greenLightFront == False:
                    light.greenLightFront()
                    blueLightFront = False
                    greenLightFront = True
                    redLightFront = False

            if LDRRight.value() == 1 or countRight == 1:
                if redLightRight == False:
                    light.redLightRight()
                    greenLightRight = False
                    blueLightRight = False
                    redLightRight = True
                countRight = 1
                if countLight == b'2' and LDRRight.value() == 1:
                    countFront = 1
                    countLeft = 1
                    light.redLightFront()
                    light.redLightLeft()
                    receive = 0
            elif countLight == b'2' and countRight == 0:
                if blueLightRight == False:
                    light.blueLightRight()
                    blueLightRight = True
                    greenLightRight = False
                    redLightRight = False
            else:
                if greenLightRight == False:
                    light.greenLightRight()
                    blueLightRight = False
                    greenLightRight = True
                    redLightRight = False

            if LDRLeft.value() == 1 or countLeft == 1:
                if redLightLeft == False:
                    light.redLightLeft()
                    redLightLeft = True
                    greenLightLeft = False
                    blueLightLeft = False
                countLeft = 1
                if countLight == b'1' and LDRLeft.value() == 1:
                    countFront = 1
                    countRight = 1
                    light.redLightFront()
                    light.redLightRight()
                    receive = 0
            elif countLight == b'1' and countLeft == 0:
                if blueLightLeft == False:
                    light.blueLightLeft()
                    redLightLeft = False
                    greenLightLeft = False
                    blueLightLeft = True
            else:
                if greenLightLeft == False:
                    light.greenLightLeft()
                    redLightLeft = False
                    greenLightLeft = True
                    blueLightLeft = False
            t_last = tLED
        elif countFront + countRight + countLeft == 3:
            light.bounce()
            engine.off()
            if tLED-t_last > 5*freq:
                countFront = 0
                countRight = 0
                countLeft = 0
                t_last = tLED

        try:
            left  = distance.get_left()
            right = distance.get_right()
        except OSError as exc:
            print(exc)

        # braun 4, gelb 5
        if timeE > .5:
            timeE = 0
            print("Left", "%6.2f" % left, "Right", "%6.2f" % right)

        turnOld = turn
        if turn == NO:
            if left > threshold:
                # links kante erkannt -> rechts drehen = links fahren
                #print("Turn right")
                turn = RIGHT
                #engine.left()
            elif right > threshold:
                # rechts kante erkannt -> links drehen = rechts fahren
                #print("Turn left")
                turn = LEFT
                #engine.right()
            else:
                # laufe bis kante
                #print("pass")
                pass
                #engine.both()
        elif turn == LEFT:
            if right <= threshold:
                # stop
                #print("Walk")
                turn = NO
                #engine.both()
        elif turn == RIGHT:
            if left <= threshold:
                # stop
                #print("Walk")
                turn = NO
                #engine.both()
        sleep(0.5)

        if turn != turnOld:
            if turn == LEFT:
                engine.right()
            if turn == RIGHT:
                engine.left()
            if turn == NO:
                engine.both()

except KeyboardInterrupt as e:
    print("off")
    engine.off()


# This is the Exercise 11.9.2 for Book 'Python for Everybody: Exploring Data
# in Python 3'

# Write a program to look for lines of the form
# "New Revision: 39772"
# and extract the number from each of the lines using a regular expression and
# the findall() method. Compute the average of the numbers and print out the average.

# Enter file: mbox.txt
# 38549.7949721

# Enter file: mbox-short.txt
# 39756.9259259

import re
name=input("Enter file:")
if len(name)<1:
    name="mbox.txt"
# Guardian
try:
    handle=open(name)
except:
    print("File cannot be opened:",name)
    exit()

count=0
sum=0
for line in handle:
    line=line.strip()
    x=re.findall('^New Revision: ([0-9]+)',line)
    if len(x)<1:   # Remember that if there is a blank line, just continue the loop until we find a number
        continue
    for number in x:
        count=count+1
        intnumber=int(number)
        sum=sum+intnumber

print("Average:",sum/count)


# Q2349m, runtime 14.29%
class NumberContainers:

    def __init__(self):
        self.n2i = {}
        self.i2n = {}

    def change(self, index: int, number: int) -> None:
        if index not in self.i2n:
            self.i2n[index] = number
        else:
            prevn = self.i2n[index]
            self.i2n[index] = number

            i = bisect.bisect_left(self.n2i[prevn], index)
            del self.n2i[prevn][i]

        if number not in self.n2i:
            self.n2i[number] = []

        i = bisect.bisect_left(self.n2i[number], index)
        if i == len(self.n2i[number]):
            self.n2i[number].append(index)
        elif self.n2i[number][i] != index:
            self.n2i[number].insert(i, index)

    def find(self, number: int) -> int:
        if number not in self.n2i or len(self.n2i[number]) <= 0:
            return -1
        return self.n2i[number][0]

# TLE
'''
    def __init__(self):
        self.n2i = {}
        self.i2n = {}

    def change(self, index: int, number: int) -> None:
        if index not in self.i2n:
            self.i2n[index] = number
        else:
            prevn = self.i2n[index]
            self.i2n[index] = number
            self.n2i[prevn].remove(index)
            heapq.heapify(self.n2i[prevn])
        if number not in self.n2i:
            self.n2i[number] = []
            heapq.heapify(self.n2i[number])
        heapq.heappush(self.n2i[number], index)

    def find(self, number: int) -> int:
        if number not in self.n2i or len(self.n2i[number]) <= 0:
            return -1
        return self.n2i[number][0]
'''

# Your NumberContainers object will be instantiated and called as such:
# obj = NumberContainers()
# obj.change(index,number)
# param_2 = obj.find(number)


'''
13-Crear una lista con los nombres de tres colores y agregar dos colores más al
final de la lista. Mostrar la lista resultante.

'''

colores=[]
for i in range(3):
    color=input('Ingresa nombre del color: ')
    colores.append(color)
else:
    print('Lista de los colores:')
    for color in colores:
        print (color)
    for i in range(2):
        color=input('Agregar un color mas: ')
        colores.append(color)
    print('Lista de colores agregando los 2 ultimos colores:')
    for color in colores:
        print (color)


import os

import yaml
from transformers import (
    Trainer,
    set_seed)
from transformers.integrations import MLflowCallback

import mlflow
from nlp_sa.ModelBuilder import ModelBuilder
from nlp_sa.data_loader import DataLoader
from nlp_sa.utils.callbacks import CustomMLflowCallback
from nlp_sa.utils.logger_utils import get_logger
from nlp_sa.utils.train_utils import apply_preprocessing, detect_checkpoint, get_metric_callable, get_check_point, \
    combine_training_args, log_conf_as_yaml
from nlp_sa.workload import Workload

logger = get_logger()

yaml.SafeDumper.yaml_representers[None] = lambda self, data: \
    yaml.representer.SafeRepresenter.represent_str(
        self,
        str(data),
    )

class ModelTrainJob(Workload):

    def launch(self):
        logger.info('ModelTrainJob job started!')
        log_level = self.conf.training_args.log_level
        logger.setLevel(log_level)

        set_seed(self.conf.training_args.seed)
        data_loader = DataLoader(self.conf, self.spark)
        model_builder = ModelBuilder(self.conf, data_loader)

        apply_preprocessing(self.conf, data_loader, model_builder)
        last_checkpoint = detect_checkpoint(self.conf)

        # combine the arguements for trainig
        combine_training_args(self.conf, data_loader)

        # log the conf as conf.yaml

        log_conf_as_yaml(self.conf)

        mlflow.set_tracking_uri(os.getenv("MLFLOW_TRACKING_URI"))

        with mlflow.start_run():
            trainer = Trainer(
                model=model_builder.model,
                args=self.conf.training_args,
                train_dataset=data_loader.train if self.conf.training_args.do_train else None,
                eval_dataset=data_loader.test if self.conf.training_args.do_eval else None,
                compute_metrics=get_metric_callable(self.conf, data_loader),
                tokenizer=model_builder.tokenizer
            )

            trainer.remove_callback(MLflowCallback)
            trainer.add_callback(CustomMLflowCallback)

            checkpoint = get_check_point(self.conf, last_checkpoint)
            trainer.train(resume_from_checkpoint=checkpoint)

            logger.info('ModelTrainJob job finished!')

            # Evaluation
            if self.conf.training_args.do_eval:
                logger.info("*** Evaluate ***")
                trainer.evaluate(eval_dataset=data_loader.test)

if __name__ == '__main__':
    job = ModelTrainJob()
    job.launch()


from __future__ import unicode_literals
import dataent
from dataent.utils import sanitize_html

def execute():
	for product_bundle in dataent.get_all('Product Bundle'):
		doc = dataent.get_doc('Product Bundle', product_bundle.name)
		for item in doc.items:
			if item.description:
				description = sanitize_html(item.description)
				item.db_set('description', description, update_modified=False)


class Solution:
    def countGoodSubstrings(self, s: str) -> int:
        if len(s) < 3: return 0
        cur = collections.defaultdict(int)
        cur[s[0]] += 1
        cur[s[1]] += 1
        ans = 0
        for i in range(2, len(s)):
            cur[s[i]] += 1
            if len(cur) == 3:
                ans += 1
            cur[s[i-2]] -= 1
            if cur[s[i-2]] == 0:
                del cur[s[i-2]]
        return ans


from kavenegar import *

# sms message sender
#-----------------------------------------------------
def send_sms(mobile_number,message):
    try:
        api = KavenegarAPI('586C572B4E73445A5964732B504B72503258486446527949484637473134566946387373614D35797871493D')
        params = {
            'sender': '',   #optional (the number you buy from kavenegar (it is not neccesary))
            'receptor': mobile_number ,   #multiple mobile number, split by comma
            'message': message,
        }
        response = api.sms_send(params)
        print(response)
    except APIException as e:
        print(e)
    except HTTPException as e:
        print(e)


from unidecode import unidecode
import re

NONALPHA_RE = re.compile(r'[^a-z]')
NONALPHANUM_RE = re.compile(r'[^a-z0-9]')
DIGIT_RE = re.compile(r'[0-9]')
PUNCTUATION_RE = re.compile(r"[^A-Za-z0-9' ]")
PARENTHESIS_RE = re.compile(r'[_ ]\(.*\)')
SPACES_RE = re.compile(r'  +')

def slugify(text):
    """
    Return a text as a sequence of letters. No spaces, digits, hyphens,
    or apostrophes. This kind of reduced form of text is sometimes called a
    "slug", and that's the term we use for it throughout solvertools.
    """
    return NONALPHA_RE.sub('', text.lower())

def alphanumeric(text):
    return NONALPHANUM_RE.sub('', text.lower())

def sanitize(text):
    """
    Return a text as a sequence of letters, digits, apostrophes, and spaces.
    """
    return SPACES_RE.sub(' ', PUNCTUATION_RE.sub(' ', text))

def unspaced_lower(text):
    """
    Remove spaces and apostrophes from text. This is a gentler form of
    `slugify` that preserves regex operators, for example.
    """
    return text.replace(' ', '').replace("'", '').lower()

# We don't want to translate every number, just the ones that have single words.
NUMERALS = {
    '0': 'zero', '1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': 'six',
    '7': 'seven', '8': 'eight', '9': 'nine', '10': 'ten', '11': 'eleven', '12': 'twelve',
    '13': 'thirteen', '14': 'fourteen', '15': 'fifteen', '16': 'sixteen', '17': 'seventeen',
    '18': 'eighteen', '19': 'nineteen', '20': 'twenty', '30': 'thirty', '40': 'forty',
    '50': 'fifty', '60': 'sixty', '70': 'seventy', '80': 'eighty', '90': 'ninety',
    '1st': 'first', '2nd': 'second', '3rd': 'third', '4th': 'fourth', '5th': 'fifth',
    '6th': 'sixth', '7th': 'seventh', '8th': 'eighth', '9th': 'ninth', '10th': 'tenth',
    '11th': 'eleventh', '12th': 'twelfth', '13th': 'thirteenth', '14th': 'fourteenth',
    '15th': 'fifteenth', '16th': 'sixteenth', '17th': 'seventeenth', '18th': 'eighteenth',
    '19th': 'nineteenth', '20th': 'twentieth'
}

def transform_simple_numbers(word):
    if word in NUMERALS:
        return NUMERALS[word]
    else:
        if DIGIT_RE.search(word):
            return '###'
        else:
            return word

def fix_entities(text):
    return text.replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"')

def normalize_wp_link(text):
    text = text.split('#')[0]
    text = PARENTHESIS_RE.sub('', text)
    text = unidecode(text)
    text = fix_entities(text)
    text = text.replace("\\'", "'").replace('-', ' ').replace('_', ' ').replace('&', ' AND ').replace('/', ' ').replace('List of ', '').replace('History of ', '')
    text = PUNCTUATION_RE.sub('', text)
    words = [transform_simple_numbers(word).upper() for word in text.split()]
    return SPACES_RE.sub(' ', ' '.join(words)).strip()


import csv
import matplotlib.pyplot as plt

def loadCountriesPie():
  with open("./data.csv", 'r') as file:
    next(file)
    csvreaded = csv.reader(file)
    countries = dict()
    for row in csvreaded:
      country = {
        row[2]: int(float(row[16]) * 100)
      }
      countries.update(country)
    return countries

def loadCountries():
  with open("./data.csv", 'r') as file:
    next(file)
    csvreaded = csv.reader(file)
    countries = dict()
    for row in csvreaded:
      country = {
        row[2]: {
          "2022": int(row[5]),
          "2020": int(row[6]),
          "2015": int(row[7]),
          "2010": int(row[8]),
          "2000": int(row[9]),
          "1990": int(row[10]),
          "1980": int(row[11])
        }
      }
      countries.update(country)
    return countries

def getCountry():
  countrySelected = input('Please, type a country ').capitalize()
  return countrySelected

def generate_pie_chart(labels, values):
  print(labels)
  print(values)
  fig, ax = plt.subplots()
  ax.pie(values, labels=labels)
  plt.show()

def generate_bar_chart(labels, values):
  fig, ax = plt.subplots()
  ax.bar(labels, values)
  plt.show()

def runChart(countrySelected, countries):
  if countrySelected in countries:
    countryDict = countries[countrySelected]
    generate_bar_chart(countryDict.keys(), countryDict.values())
  else:
    print('This country does not exist')
    getCountry()

if __name__ == '__main__':
  countries = loadCountriesPie()
  generate_pie_chart(countries.keys(), countries.values())
  # countries = loadCountries()
  # countrySelected = getCountry()
  # runChart(countrySelected, countries)


def gerarProtocolo(): #Função para gerar um número de protocolo
    import datetime
    from random import randint

    dia = datetime.date.today().day
    mes = datetime.date.today().month
    ano = datetime.date.today().year

    while True:
        numero = randint(1000, 9999)
        protocol = f'{dia}{mes}{ano}{numero}'
        if not verificarProt(protocol):
            return protocol

def verificarProt(protocolo, nomeArq = 'registro.txt'): #Função que verifica se o protocolo já existe
    if arquivo_existe():
        a = open(nomeArq, 'r')
        nProtocol = a.readlines()
        a.close()
        for i in range(len(nProtocol)):
            if protocolo in nProtocol[i].split(';'):
                return True
        return False

def confirmacao(tipoAtendimento, protocolo): #Função que mostra o aviso do registro do atendimento
    print(f'Sua {tipoAtendimento} foi registrada!\nO número do protocolo é {protocolo}.\nPara consultar, clique em Status no Menu Principal!')

def arquivo_existe(nome='registro.txt'): # Função para verificar se o arquivo já existe
    try:
        a = open(nome, 'r')
        a.close()
    except FileNotFoundError:
        return False
    else:
        return True

def criar_arquivo(nome='registro.txt'): #Função para criar o arquivo
    a = open(nome, 'w')
    a.close()

def salvarRegistro(protocolo, tipoAtendimento, setor, hotel, apto, descricao, nomeArquivo = 'registro.txt'): #Função que salva o atendimento no bloco de notas
    from time import sleep

    if not arquivo_existe():
        criar_arquivo()

    arquivo = open(nomeArquivo, 'a')
    arquivo.write(f'{protocolo}; {tipoAtendimento}; {setor}; {hotel}; {apto}; {descricao}\n')
    arquivo.close()

    confirmacao(tipoAtendimento, protocolo)
    sleep(4)
    return 0


#Integers: Integers are whole numbers it can be positive, negative, or zero and there should be no decimal part.
a=10
b=-10
c=0

#Floats: Floats are numbers with decimal
d=12,3
e=-12,9

#Booleans: Booleans are values that can be either True or False but you have to start with capital letter.
f=True
g=False

#Strings: Strings are sequences of characters.It must be surrounded by single or double quotes.
h="Kodlama.io"
j='Kodlama.io'

#Lists: They are used to store multiple items in a single variable.
list = ["python", "java", "c#"]

#Tuples: It is the same as the list, but with parentheses outside
tuple = ("sunny", "rainy", "foggy")

#Sets: Unlike tuples and lists, set items are unordered.
set = {"red", "black", "white"}

#Dictionaries: Dictionaries are used to store data values as key:value format.
dictionary = {
  "name": "Gizem",
  "surname": "Poyraz",
  "birthYear": 1999
}

'''Kodlama.io if we start from the examples on the site, we will
    whether the course has been completed as a boolean,
    the percentage of completion of the course as int,
    as a list of the section where the courses take place,
    we can evaluate the headings as strings.
'''


import time
import math
from easygopigo3 import EasyGoPiGo3,Servo,DistanceSensor,MotionSensor
import picamera
from io import BytesIO
from PIL import Image
from di_sensors import distance_sensor as ds_sensor
from di_sensors import  inertial_measurement_unit as imu

class Robot2I013(object):
    """
    Classe d'encapsulation du robot et des senseurs.
    Constantes disponibles :
    LED (controle des LEDs) :  LED_LEFT_EYE, LED_RIGHT_EYE, LED_LEFT_BLINKER, LED_RIGHT_BLINKER, LED_WIFI
    MOTEURS (gauche et droit) : MOTOR_LEFT, MOTOR_RIGHT
    et les constantes ci-dessous qui definissent les elements physiques du robot
    """

    WHEEL_BASE_WIDTH         = 117  # distance (mm) de la roue gauche a la roue droite.
    WHEEL_DIAMETER           = 66.5 #  diametre de la roue (mm)
    WHEEL_BASE_CIRCUMFERENCE = WHEEL_BASE_WIDTH * math.pi # perimetre du cercle de rotation (mm)
    WHEEL_CIRCUMFERENCE      = WHEEL_DIAMETER   * math.pi # perimetre de la roue (mm)

    def __init__(self,resolution=None,servoPort = "SERVO1",motionPort="AD1"):
        """
            Initialise le robot

            :controler: le controler du robot, muni d'une fonction update et d'une fonction stop qui
                        rend in booleen (vrai a la fin du controle, faux sinon)
            :fps: nombre d'appel a controler.update() par seconde (approximatif!)
            :resolution: resolution de la camera
            :servoPort: port du servo (SERVO1 ou SERVO2)
            :motionPort: port pour l'accelerometre (AD1 ou AD2)
        """

        self._gpg= EasyGoPiGo3()
        self.LED_LEFT_EYE = self._gpg.LED_LEFT_EYE
        self.LED_RIGHT_EYE = self._gpg.LED_RIGHT_EYE
        self.LED_LEFT_BLINKER = self._gpg.LED_LEFT_BLINKER
        self.LED_RIGHT_BLINKER = self._gpg.LED_RIGHT_BLINKER
        self.LED_WIFI = self._gpg.LED_WIFI
        self.MOTOR_LEFT= self._gpg.MOTOR_LEFT
        self.MOTOR_RIGHT = self._gpg.MOTOR_RIGHT

        try:
            self.camera = picamera.PiCamera()
            if resolution:
                self.camera.resolution = resolution
        except Exception as e:
            print("Camera not found",e)
        try:
            self.servo = Servo(servoPort,self._gpg)
        except Exception as e:
            print("Servo not found",e)
        try:
            self.distanceSensor = ds_sensor.DistanceSensor()
        except Exception as e:
            print("Distance Sensor not found",e)
        try:
            self.imu = imu.inertial_measurement_unit()
        except Exception as e:
            print("IMU sensor not found",e)
        self._gpg.set_motor_limits(self._gpg.MOTOR_LEFT+self._gpg.MOTOR_RIGHT,0)

    def set_led(self, led, red = 0, green = 0, blue = 0):
        """
        Allume une led.

        :led: une des constantes LEDs (ou plusieurs combines avec +) : LED_LEFT_EYE, LED_RIGHT_EYE, LED_LEFT_BLINKER, LED_RIGHT_BLINKER, LED_WIFI.
        :red: composante rouge (0-255)
        :green:  composante verte (0-255)
        :blue: composante bleu (0-255)
        """
        self._gpg.set_led(led,red,green,blue)

    def get_voltage(self):
        """ get the battery voltage """
        return self._gpg.get_voltage_battery()

    def set_motor_dps(self, port, dps):
        """
        Fixe la vitesse d'un moteur en nombre de degres par seconde

        :port: une constante moteur,  MOTOR_LEFT ou MOTOR_RIGHT (ou les deux MOTOR_LEFT+MOTOR_RIGHT).
        :dps: la vitesse cible en nombre de degres par seconde
        """
        self._gpg.set_motor_dps(port,dps)

    def get_motor_position(self):
        """
        Lit les etats des moteurs en degre.
        :return: couple du  degre de rotation des moteurs
        """
        return self._gpg.read_encoders()

    def offset_motor_encoder(self, port, offset):
        """
        Fixe l'offset des moteurs (en degres) (permet par exemple de reinitialiser a 0 l'etat
        du moteur gauche avec offset_motor_encode(self.MOTOR_LEFT,self.get_motor_position()[0])

        :port: un des deux moteurs MOTOR_LEFT ou MOTOR_RIGHT (ou les deux avec +)
        :offset: l'offset de decalage en degre.

        Zero the encoder by offsetting it by the current position
        """
        self._gpg.offset_motor_encoder(port,offset)

    def get_distance(self):
        """
        Lit le capteur de distance (en mm).
        :returns: entier distance en millimetre.
            1. L'intervalle est de **5-8,000** millimeters.
            2. Lorsque la valeur est en dehors de l'intervalle, le retour est **8190**.
        """
        return self.distanceSensor.read_range_single(False)

    def servo_rotate(self,position):
        """
        Tourne le servo a l'angle en parametre.
        :param int position: Angle de rotation, de **0** a **180** degres, 90 pour le milieu.
        """
        self.servo.rotate_servo(position)
    def stop(self):
        """ Arrete le robot """
        self.set_motor_dps(self.MOTOR_LEFT+self.MOTOR_RIGHT,0)
        self.set_led(self.LED_LEFT_BLINKER+self.LED_LEFT_EYE+self.LED_LEFT_BLINKER+self.LED_RIGHT_EYE+self.LED_WIFI,0,0,0)

    def get_image(self):
        stream = BytesIO()
        self.camera.capture(stream,format="jpeg")
        stream.seek(0)
        img= Image.open(stream).copy()
        stream.close()
        return img


'''
Proyecto Final del Módulo 2.

Conversiones con SET y LIST
'''

def ordenar_sin_repetidos(lista):
    conjunto = set(lista)
    return conjunto

print("\n*Ordenaremos y devolveremos tu lista de números sin repetidos*")

bandera = True
lista = []

while bandera:
    numero = int(input("\nEscribe un número: "))
    lista.append(numero)

    bandera2 = True

    while bandera2:
        respuesta = input("¿Deseas escribir otro número? (Sí o No): ")
        if respuesta == "Sí" or respuesta == "Si" or respuesta == "si" or respuesta == "sí":
            bandera2 = False
        elif respuesta == "No" or respuesta == "no":
            bandera = False
            bandera2 = False
        else:
            print("Escribe bien tu respuesta.\n")

print("\nTu lista original ")

for numero in lista:
    print("Número: {}".format(numero))

print("\nTu lista ordenada y sin repetidos ")

lista = list(ordenar_sin_repetidos(lista))
for numero in lista:
    print("Número: {}".format(numero))

print("\nFin.")


import sys
import socket
from urllib.parse import urlparse
from pathlib import Path

"""
Project 1: Project #1: Web Proxy

*   A proxy server is created to handle GET request from clients.
*   Proxy server will run indefinitely until admin user terminates it manually.
*   Proxy server can only handle GET request at http/1.1 standard.
*   Proxy server will only store/cache requests with status code of 200.
*   If the response status code from origin server is not 200 or 404, proxy server will
    override the status code from response to 500 and send it to clients (for example,
    http://google.com will respond with 301 status code, which will be overwritten to 500).
*   If client request is invalid, proxy will send 500 status code to client.
*   Proxy server will terminate client connection if: (a) client request is malformed, (b) if
    url provided by client is invalid or/and inaccessible (which will raise exception), and (c)
    if client request is longer than 4096 bytes.
*   User request url must start with 'http://'
*   User request method must be 'GET'
*   User request http version must be 'HTTP/1.1'

Authors: Sizhe Liu
Version: April 19, 2023
"""

# function to validate client request/input
def validateClientRequest(client_msg):
    """
        function to validate client request/input

        :param client_msg: client request in string format
        :return: False if client request is invalid. True otherwise
    """
    split_msg = client_msg.split()
    if len(split_msg) != 3:
        return False
    if split_msg[0] != 'GET':
        return False
    if split_msg[1][0:7].lower() != 'http://':
        return False
    if split_msg[2] != 'HTTP/1.1':
        return False
    return True

# function to turn url into filename
def turnUrlToFilename(url):
    """
        function to turn url into filename

        :param url: client request url
        :return: filename in string format
    """
    fileName = ''
    for ele in url:
        if ele == '/' or ele == ':' or ele == '.':
            ele = '-'
        fileName += ele
    return fileName

# function to create cache main folder
def createMainFolder(folderName):
    """
        function to create cache folder

        :param folderName: desired folder name
    """
    if Path(folderName).exists() == False:
        Path(folderName).mkdir()
        print(f'main folder: {folderName} is created.')
    else:
        print(f'main folder: {folderName} already exists.')

# function to create cache sub folder
def createSubFolder(mainfolderName, subfolderName):
    """
        function to create cache sub folder

        :param mainfolderName: the main folder name defined by admin user
        :param subfolderName: the subfolder name, use lower case host name here
    """
    sub_path = f'{mainfolderName}/{subfolderName}'
    if Path(sub_path).exists() == False:
        Path(sub_path).mkdir()
        print(f'sub folder: {sub_path} is created.')
    else:
        print(f'sub folder: {mainfolderName}/{subfolderName} already exists.')

# function to create cache file
def createCacheFile(path_to_file, origin_resp):
    """
        function to create cache file, write content to file

        :param path_to_file: relative file path
        :param origin_resp: raw response from origin server
    """
    # handle file checking and creating
    if (not Path(path_to_file).is_file()):
        body = origin_resp.split(b'\r\n\r\n', 1)[1]
        # write payload to file in bytes
        with open(path_to_file, "wb") as file:
            file.write(body)
        print(path_to_file + ' created...')
    else:
        print(path_to_file + ' already exists...')

# function to check the status code from origin server response
def checkStatusCode(lines):
    """
        function to check status code from origin server response

        :param lines: list of lines from origin server response
        :return: status code in int format
    """
    code = lines[0].split()[1]
    if code == b'200':
        return 200
    elif code == b'404':
        return 404
    return 500

# functions to create the request to origin server
def createReqToOrigin(method, path, http_version, host):
    """
        function to create request to origin server

        :param method: 'GET'
        :param path: absolute path in url
        :param http_version: 'HTTP/1.1'
        :param host: host of url
        :return: request itself
    """
    # contracting request
    request = f'{method} {path} {http_version}\r\n'
    request += f'Host: {host}\r\n'
    request += 'Connection: close\r\n'
    request += '\r\n'
    return request

# function to modify response from origin server (cache hit & status code)
def modifyResponse(response):
    """
        function to modified origin server response before replaying it to client

        :param response: raw response from origin server
        :return: the modified response
    """
    cache_header = b'\r\ncache hit: 0\r\n'
    res_list = response.split(b'\r\n', 1)
    code = res_list[0].split()[1]
    if code != b'200' and code != b'404' and code != b'500':
        # modify header
        res_list[0] = b'HTTP/1.1 500 Internal Server Error'
    return res_list[0] + cache_header + res_list[1]

# validate grader input - only one argument - port/socket number is allowed when
# the proxy.py is invoked in command line
if len(sys.argv) != 2:
    print('invalid commandline argument! program terminated.')
    exit(1)
if not sys.argv[1].isnumeric():
    print('invalid port number! program terminated.')
    exit(1)
if int(sys.argv[1]) > 65535 or int(sys.argv[1]) < 1:
    print('invalid port number! program terminated.')
    exit(1)

# create/check main cache folder
fileExtension = '.txt'
mainfolderName = 'cache'
createMainFolder(mainfolderName)

# extract port number from command line argument
portNum = int(sys.argv[1])
# create socket to listen
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# bind the socket/port number to local host
server.bind(('', portNum))
# turn server on - listening any request
server.listen(1)

# when client establish connection with the proxy server
while True:
    print('********************** proxy is ready ****************************')
    print(f'proxy listening at port: {portNum}')

    # create a socket to talk to the client, store client socket address and ip address
    socClient, address = server.accept()
    print('Received a client connection from', address)

    # receive request from client (bytestream)
    # be CAREFUL here... may get infinite loop
    clientRequest = socClient.recv(4096)
    print('Received a message from this client:', clientRequest)
    clientRequest = str(clientRequest, 'utf-8')

    # validate client request, make sure it is not gibberish
    if validateClientRequest(clientRequest) == False:
        errorMsg = f'HTTP/1.1 500 Internal Server Error\ninvalid client request\n'
        socClient.sendall(bytes(errorMsg, 'utf-8'))
        socClient.close()
        print('invalid client request... connection is closed')
    else:
        # if client request is valid - lets handle the request
        # split client request
        split_client_request = clientRequest.split()
        url = split_client_request[1]

        # create & check if subfolder already exists
        subfolderName = urlparse(url).netloc.split(':')[0].lower()  # get rid of potential port#
        createSubFolder(mainfolderName, subfolderName)

        # convert url to file name and create path to file
        fileName = turnUrlToFilename(url)
        path_to_file = f'{mainfolderName}/{subfolderName}/{fileName}{fileExtension}'

        # check if the file exists in cache
        # case: file is not in cache
        if Path(path_to_file).is_file() == False:
            # file does not exist, need to fetch from original server
            print('the file requested is NOT in cache... fetching from the origin server...')

            # prepare request to origin server - need url, host name, and connection header
            # parse url to get useful info
            parseUrlObj = urlparse(url)
            method = split_client_request[0]
            path = ''
            if len(parseUrlObj.path) == 0:
                path = '/'
            else:
                path = parseUrlObj.path
            http_version = split_client_request[2]
            host = parseUrlObj.netloc.split(':', 1)[0]  # strip port number from url if needed

            # prepare request to origin server - string form
            request_to_origin = createReqToOrigin(method, path, http_version, host)

            # request is ready, lets establish connection with the origin server
            socOriginServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            port = 80
            try:
                socOriginServer.connect((host, port))
            except:
                # handle exception - unable to connect to url provided by client
                errorMsg = f'HTTP/1.1 500 Internal Server Error\n' \
                           f'failed to connect to: {url}! url may be invalid!\n' \
                           f'socket.gaierror: [Errno 11001] getaddrinfo failed\n'
                socClient.sendall(bytes(errorMsg, 'utf-8'))
                socClient.close()
                print('exception encounter... unable to connect to client URL...'
                      ' closing socket...')
                continue

            # & forward client request to the origin server
            print('Sending the following message to proxy to server:')
            print(request_to_origin)
            socOriginServer.sendall(bytes(request_to_origin, 'utf-8'))

            # let's receive the data from the origin server
            response = b''
            while True:
                packet = socOriginServer.recv(4096)
                response += packet
                if len(packet) == 0:
                    # data xfer is done
                    break
            socOriginServer.close()

            # split response into a list of lines (in bytes)
            lines = response.splitlines()

            # check the response code - only 200 will be saved to cache
            code = checkStatusCode(lines)
            if code == 200:
                print('response received from server, and status code is 200! writing to cache...')
                createCacheFile(path_to_file, response)
            else:
                print('response received from server, but status code is not 200! No cache writing...')
                print('relaying response to client...')

            # modify response from origin server (add 'cache hit' header & modify status code if needed)
            # before replaying it back to client
            modified_resp = modifyResponse(response)

            # send the modified response back to client
            socClient.sendall(modified_resp)
            print("job done... closing socket...")
            socClient.close()
        else:
            # file in cache, send it over to the client
            # read content of cache file
            print('the file requested is in the cache! sending it over now...')
            file = open(path_to_file, "rb")
            data = file.read()
            file_len = len(data)

            # prepare custom header
            header = f'HTTP/1.1 200 OK\r\nContent-Length: {file_len}\r\nConnection: close\r\n' \
                     f'Cache-Hit: 1\r\n\r\n'

            # send header, file data, ending msg to client
            socClient.sendall(bytes(header, 'utf-8'))
            socClient.sendall(data)
            file.close()
            socClient.close()
            print("job done...closing socket...")