from http.server import BaseHTTPRequestHandler, HTTPServer
from multiprocessing import Process
from glob import glob
import json
import os

PATH_RESPONSE_FOLDER = "response"
PATH_CONFIG_FILE = os.path.join("config", "config.json")
PATH_HTML_FILE = os.path.join("ui", "index.html")
PATH_CSS_FILE = os.path.join("ui", "css", "index.css")
PATH_JS_FILE = os.path.join("ui", "js", "request.js")
PATH_IMG_FILE = os.path.join("ui", "img", "copy-icon.png")
HEADER_CONTENT_TYPE = "Content-Type"
HEADER_CONTENT_LENGTH = "Content-Length"
CONTENT_TYPE_JSON = "application/json"
CONTENT_TYPE_TEXT = "text/html"
CONTENT_TYPE_JS = "application/javascript"
CONTENT_TYPE_CSS = "text/css"
CONTENT_TYPE_PNG = "image/png"
STATUS_OK = 200
STATUS_ERROR = 404
JSON_INDENT = 2
ENCODING_TYPE = "UTF-8"
config = {}

class BasicServer(BaseHTTPRequestHandler):
    def handle_http(self, status, content_type, response):
        self.send_response(status)
        self.send_header(HEADER_CONTENT_TYPE, content_type)
        self.end_headers()
        self.wfile.write(bytes(response, ENCODING_TYPE))

    def do_GET(self):
        if ".css" in self.get_path():
            self.handle_http(STATUS_OK, CONTENT_TYPE_CSS, read_file(PATH_CSS_FILE))
        elif ".js" in self.get_path():
            self.handle_http(STATUS_OK, CONTENT_TYPE_JS, read_file(PATH_JS_FILE))
        elif ".png" in self.get_path():
            self.send_response(STATUS_OK)
            self.send_header(HEADER_CONTENT_TYPE, CONTENT_TYPE_PNG)
            self.end_headers()
            self.wfile.write(read_image(PATH_IMG_FILE))
        else:
            self.handle_path_request()

    def do_POST(self):
        if self.headers.get_content_type() == CONTENT_TYPE_JSON:
            length = int(self.headers.get(HEADER_CONTENT_LENGTH))
            body = self.rfile.read(length)
            if self.path == "/serviceNames":
                self.handle_http(STATUS_OK, CONTENT_TYPE_JSON, self.create_json_from_string(get_routes_as_json()))
            elif self.path == "/OPR_UPDATE":
                if self.is_data_json(body.decode(ENCODING_TYPE)):
                    name = json.loads(body.decode(ENCODING_TYPE))["serviceNameSelect"]
                    data = json.loads(body.decode(ENCODING_TYPE))["jsonTextArea"]
                    if self.is_data_json(data):
                        is_updated = update_file(os.path.join(PATH_RESPONSE_FOLDER, "{}.json".format(name)), data)
                        if is_updated:
                            self.handle_http(STATUS_OK, CONTENT_TYPE_TEXT, "JSON updated")
                        else:
                            self.handle_http(STATUS_ERROR, CONTENT_TYPE_TEXT, "JSON is NOT updated")
                    else:
                        self.handle_http(STATUS_ERROR, CONTENT_TYPE_TEXT, "Malformed JSON text")
                else:
                    self.handle_http(STATUS_ERROR, CONTENT_TYPE_TEXT, "Malformed JSON")
            elif self.path == "/OPR_INSERT":
                if self.is_data_json(body.decode(ENCODING_TYPE)):
                    name = json.loads(body.decode(ENCODING_TYPE))["serviceNameInput"]
                    requested_route = self.get_route_name(name, get_route_list())
                    if requested_route:
                        self.handle_http(STATUS_ERROR, CONTENT_TYPE_TEXT, "\"{}\" service already exists".format(name))
                    else:
                        data = json.loads(body.decode(ENCODING_TYPE))["jsonTextArea"]
                        if self.is_data_json(data):
                            is_added = write_file(os.path.join(PATH_RESPONSE_FOLDER, "{}.json".format(name)), data)
                            if is_added:
                                self.handle_http(STATUS_OK, CONTENT_TYPE_TEXT, "JSON added")
                            else:
                                self.handle_http(STATUS_ERROR, CONTENT_TYPE_TEXT, "JSON is NOT added")
                        else:
                            self.handle_http(STATUS_ERROR, CONTENT_TYPE_TEXT, "Malformed JSON text")
                else:
                    self.handle_http(STATUS_ERROR, CONTENT_TYPE_TEXT, "Malformed JSON")
            elif self.path == "/OPR_SELECT":
                if self.is_data_json(body.decode(ENCODING_TYPE)):
                    name = json.loads(body.decode(ENCODING_TYPE))["serviceNameSelect"]
                    requested_route = self.get_route_name(name, get_route_list())
                    if requested_route:
                        self.handle_http(STATUS_OK, CONTENT_TYPE_JSON, self.create_json_from_file(requested_route))
                    else:
                        self.handle_http(STATUS_ERROR, CONTENT_TYPE_TEXT, "\"{}\" service does not exist".format(name))
                else:
                    self.handle_http(STATUS_ERROR, CONTENT_TYPE_TEXT, "Malformed JSON")
            elif self.path == "/OPR_DELETE":
                if self.is_data_json(body.decode(ENCODING_TYPE)):
                    name = json.loads(body.decode(ENCODING_TYPE))["serviceNameSelect"]
                    requested_route = self.get_route_name(name, get_route_list())
                    if requested_route:
                        is_deleted = delete_file(requested_route)
                        if is_deleted:
                            self.handle_http(STATUS_OK, CONTENT_TYPE_TEXT, "\"{}\" service JSON deleted.".format(name))
                        else:
                            self.handle_http(STATUS_ERROR, CONTENT_TYPE_TEXT,
                                             "Cannot delete \"{}\" service JSON.".format(name))
                    else:
                        self.handle_http(STATUS_ERROR, CONTENT_TYPE_TEXT, "\"{}\" service does not exist".format(name))
                else:
                    self.handle_http(STATUS_ERROR, CONTENT_TYPE_TEXT, "Malformed JSON")
        else:
            self.handle_path_request()

    def handle_path_request(self):
        if self.path.count("/") == 1:
            if self.path.split("/")[1]:
                requested_route = self.get_route_name(self.get_path(), get_route_list())
                if requested_route:
                    self.handle_http(STATUS_OK, CONTENT_TYPE_JSON, self.create_json_from_file(requested_route))
                else:
                    self.handle_http(STATUS_ERROR, CONTENT_TYPE_TEXT,
                                     "\"{}\" service response does not exist".format(self.get_path()))
            else:
                self.handle_http(STATUS_OK, CONTENT_TYPE_TEXT, read_file(PATH_HTML_FILE))
        else:
            self.handle_http(STATUS_ERROR, CONTENT_TYPE_TEXT, "Wrong path")

    @staticmethod
    def get_route_name(requested_route, routes):
        for rt in routes:
            if os.path.basename(rt).split(".")[0] == requested_route:
                return rt
        return None

    def get_path(self):
        return os.path.basename(self.path)

    @staticmethod
    def is_data_json(data):
        try:
            json.loads(data)
        except ValueError:
            return False
        return True

    @staticmethod
    def create_json_from_file(filename):
        return json.dumps(json.loads(read_file(filename)), indent=JSON_INDENT, ensure_ascii=False)

    @staticmethod
    def create_json_from_string(text):
        return json.dumps(text, indent=JSON_INDENT, ensure_ascii=False)

def read_file(path):
    res_file = None
    try:
        res_file = open(path, 'r', encoding=ENCODING_TYPE)
        file_data = res_file.read()
        res_file.close()
        return file_data
    except Exception as ex:
        if ex:
            print("Error occurred while reading file, exception message: {}".format(ex))
    finally:
        if res_file:
            res_file.close()

def read_image(path):
    res_file = None
    try:
        res_file = open(path, 'rb')
        file_data = res_file.read()
        res_file.close()
        return file_data
    except Exception as ex:
        if ex:
            print("Error occurred while reading file, exception message: {}".format(ex))
    finally:
        if res_file:
            res_file.close()

def write_file(path, data):
    res_file = None
    try:
        res_file = open(path, 'w', encoding=ENCODING_TYPE)
        res_file.write(data)
        return True
    except Exception as ex:
        print("Error occurred while writing file, exception message: {}".format(ex))
    finally:
        if res_file:
            res_file.close()

def update_file(path, updated_content):
    res_file = None
    try:
        res_file = open(path, 'r+', encoding=ENCODING_TYPE)
        res_file.read()
        res_file.seek(0)
        res_file.write(updated_content)
        res_file.truncate()
        res_file.close()
        return True
    except Exception as ex:
        print("Error occurred while writing file, exception message: {}".format(ex))
    finally:
        if res_file:
            res_file.close()

def delete_file(path):
    try:
        os.remove(path)
        return True
    except Exception as ex:
        print("Error occurred while deleting file, exception message: {}".format(ex))

def init_config():
    global config
    config = json.loads(read_file(PATH_CONFIG_FILE))

def get_route_list():
    return glob(os.path.join(PATH_RESPONSE_FOLDER, "*"))

def get_routes_as_json():
    routes = []
    route_list = get_route_list()
    route_list.sort()
    for rt in route_list:
        routes.append({"serviceNameSelect": str(os.path.basename(rt).split(".")[0])})
    return routes

def run():
    print('Starting server...')
    init_config()
    if not os.path.exists(PATH_RESPONSE_FOLDER):
        os.mkdir(PATH_RESPONSE_FOLDER)
    server_address = (config['ip'], int(config['port']))
    httpd = HTTPServer(server_address, BasicServer)
    print("Server running on port: {}".format(config['port']))
    httpd.serve_forever()

if __name__ == '__main__':
    p = Process(target=run())
    p.start()
    p.join()


# Zadanie domowe
# Postaraj się w jakiejś formie zwizualizować położenia na planszy
"""
To jest plansza bez gracza
0000
0000
0000
0000

Plansza z grczem:
0000
00G0
0000
0000

wcisam s:
0000
0000
00G0
0000

ide w lewo i trafiam na skarb
0000
0000
0S00
0000

plansza = [[0,0,0,0],[0,0,0,0],[0,S,0,0],[0,0,0,0]]

"""

playerPositionX = int(input("podaj pozucję x gracza:")) - 1 #musimy przetransformować wartość inputową na wartość indeksową
playerPositionY = int(input("podaj pozucję y gracza:")) - 1

for i in range(5):
    print('')
    for j in range(5):
        if playerPositionX == j and playerPositionY == i:
            print("G", end=" ")
        else:
            print("0", end=" ")


import numpy as np
import pandas as pd
from flask import Flask,request,jsonify,render_template
import pickle

app=Flask(__name__)
model=pickle.load(open('model.pkl','rb'))
modelheart=pickle.load(open('model_heart.pkl','rb'))
modellung=pickle.load(open('model_lung.pkl','rb'))
diabetes=pickle.load(open('diabetes.pkl','rb'))
hepatitis=pickle.load(open('hepatitis.pkl','rb'))
disease=pickle.load(open('disease.pkl','rb'))

@app.route('/',methods=['POST','GET'])
def home():
    if request.method=='POST':
        init_features=[]
        all_features=['receiving_blood_transfusion', 'red_sore_around_nose',
       'abnormal_menstruation', 'continuous_sneezing', 'breathlessness',
       'blackheads', 'shivering', 'dizziness', 'back_pain', 'unsteadiness',
       'yellow_crust_ooze', 'muscle_weakness', 'loss_of_balance', 'chills',
       'ulcers_on_tongue', 'stomach_bleeding', 'lack_of_concentration', 'coma',
       'neck_pain', 'weakness_of_one_body_side', 'diarrhoea',
       'receiving_unsterile_injections', 'headache', 'family_history',
       'fast_heart_rate', 'pain_behind_the_eyes', 'sweating', 'mucoid_sputum',
       'spotting_ urination', 'sunken_eyes', 'dischromic _patches', 'nausea',
       'dehydration', 'loss_of_appetite', 'abdominal_pain', 'stomach_pain',
       'yellowish_skin', 'altered_sensorium', 'chest_pain', 'muscle_wasting',
       'vomiting', 'mild_fever', 'high_fever', 'red_spots_over_body',
       'dark_urine', 'itching', 'yellowing_of_eyes', 'fatigue', 'joint_pain',
       'muscle_pain']
        print(request.form)
        doctor=pd.read_csv('people.csv')
        arr=np.asarray(doctor)
        for y in all_features:
            if y not in request.form.keys():
                init_features.append(0)
            else:
                init_features.append(1)
        print(init_features)
        final_features = [np.array(init_features)]
        prediction = disease.predict(final_features)
        # if (prediction[0] == 0):
        #     output = "Patient doesnt have parkinsons!"
        # else:
        #     output = "Patient have parkinsons!"
        output=prediction[0]
        return render_template('index.html',doctor=arr,len=10,prediction_text='Predicted class:  {val}'.format(val=output))
    else:
        doctor=pd.read_csv('people.csv')
        arr=np.asarray(doctor)
        return render_template('index.html',doctor=arr,len=10)

@app.route('/predict',methods=['POST','GET'])
def predict():
    if request.method=='POST':
        int_features = [float(x) for x in request.form.values()]
        final_features = [np.array(int_features)]
        prediction = model.predict(final_features)
        if(prediction[0]==0):
            output="Patient doesnt have parkinsons!"
        else:
            output="Patient have parkinsons!"
        return render_template('parkinson.html', prediction_text=output)
    else:
        return render_template('parkinson.html')
@app.route('/predict2',methods=['POST','GET'])
def predict2():
    if(request.method=='POST'):
        int_features=[float(x) for x in request.form.values()]
        final_feature=[np.array(int_features)]
        prediction=modelheart.predict(final_feature)
        if(prediction[0]==0):
            output="Patient doesnt have heart disease!"
        else:
            output="Patient has heart disease!"
        return render_template('heart.html', prediction_text=output)
    else:
        return render_template('heart.html')

@app.route('/predict3',methods=['POST','GET'])
def predict3():
    if(request.method=='POST'):
        int_features=[float(x) for x in request.form.values()]
        final_feature=[np.array(int_features)]
        prediction=modellung.predict(final_feature)
        if(prediction[0]==0):
            output="Patient doesnt have lung cancer!"
        else:
            output="Patient has lung cancer!"
        return render_template('lung.html', prediction_text=output)
    else:
        return render_template('lung.html')

@app.route('/predict4',methods=['POST','GET'])
def predict4():
    if(request.method=='POST'):
        int_features=[float(x) for x in request.form.values()]
        final_feature=[np.array(int_features)]
        prediction=diabetes.predict(final_feature)
        print(prediction[0])
        if(prediction[0]==0):
            output="Patient doesnt have diabetes!"
        else:
            output="Patient has diabetes!"
        return render_template('diabetes.html', prediction_text=output)
    else:
        return render_template('diabetes.html')

@app.route('/predict5',methods=['POST','GET'])
def predict5():
    if(request.method=='POST'):
        int_features=[float(x) for x in request.form.values()]
        final_feature=[np.array(int_features)]
        prediction=hepatitis.predict(final_feature)
        print(prediction[0])
        if(prediction[0]==0):
            output="Patient doesnt have hepatitis!"
        else:
            output="Patient has disease! {val}".format(val=prediction[0])
        return render_template('hepatitis.html', prediction_text=output)
    else:
        return render_template('hepatitis.html')

if __name__ == "__main__":
    app.run(debug=True)


from app.line_item import LineItem

class BsaData(object):

    def __init__(self, json):
        self.line_items = []
        self.line_item_names = None
        self.data = json
        self.formatted_data = []

    def add_line_item_names(self):
        # sorting makes things easier to read in the spreadsheet
        self.line_item_names = sorted(set(x.get("lineitem_name") for x in self.data))
        return self

    def add_line_items(self):
        for li in self.line_item_names:
            relevant_stats = list(x for x in self.data if x.get("lineitem_name") == li)
            self.line_items.append(LineItem(relevant_stats).build())
        return self

    def format_data(self):
        self.formatted_data = list([li.get_name(), li.get_impressions(), li.get_clicks(), li.start_of_data, li.end_of_data] for li in self.line_items)
        return self

    def add_header_to_formatted_data(self):
        header = ["Name", "Impressions", "Clicks", "Data From", "Data To"]
        self.formatted_data.insert(0, header)
        return self

    def format_and_return_data(self):
        self.add_line_item_names()
        self.add_line_items()
        self.format_data()
        self.add_header_to_formatted_data()
        return self.formatted_data

if __name__ == '__main__':
    main()


#
#Version 0.2.0 Alpha
#
#By editing this code you accept any dammages to your installation of this progarm or your computer or data held within it. If you are just inrested in reading this code try the notepad sample code as the progarm
#does nothing with it as it is just there to allow for risk free reading of the sorce code
#
#MIT License
#
#Copyright (c) 2020 Epig-is-a-llama
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all
#copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
#SOFTWARE.
#
global current_version
current_version = '0.2.0.A'
global last_version
last_version = '0.1.1.A'
import random
#imports random for the random question and operation selectors
import sys
#imports sys for the 'exit()' command at the end to close the program when the user is done
#or to close the prograrm if a bypass of the lisense system is detected
#from Tkinter import *
global user_nickname
global old_nickmame
global use_old_nickname
global nickname_prompt
global difficlty
global nickname
global questions_in_bunch
global random_operation_selector
global system_operation
global user_operation_input
global validation_loop_variable
global random_number
#used to enshure no variables are left not declared and to make any futrure port to python 2 very easy
global number_1
global score_all_time
global total_questions_all_time
global number_2
global view_error
global score
global quit_yn
global see_credits
global see_bug_finders
global accept
global open_file_internaly
global read
global question_as_string
global user_answer
global computer_answer
global  internal_dependency_number
global see_changelog_latest
global credits_
global see_full_changelog
global version_last_ran
global score_this_bunch
global questions_in_bunch
global random_operation_number
global total_questions
global disclaimer_data
global new_version
global changelog_data
global latest_changelog_data
global bug_finder_data
global disclaimer_accept
global new_install
global disclaimer_read
global any_read_files
global credits_read
global bugfinders_read
global changelog_latest_read
global number_one_not_even
global number_two_not_even
internal_dependency_number = '3'
number_one_not_even = 'true'
number_two_not_even = 'true'
veiw_error = 'N'
score = 0
quit_yn = 'N'
questions_in_bunch = 0
total_questions = 0
random_operation = 'False'
#program = Tk()
#program.title('Maths Practice Game')
#label = Label(program, text='Welcome to my maths practice game!')
#label.grid(column=5,row=1)
#program.mainloop()
validation_loop_variable = 'Not Valid'
dependnency_file = open('dependency_number.txt','rt')
extenal_dependncy_number = dependnency_file.readline()
if internal_dependency_number != extenal_dependncy_number:
    print('Your dependency files are out of date or corrupted please try to contact a member of the dev team or re-download the prograrm as the zip file and fully re-install it.')
    dependencies_up_to_date = 'No'
elif  internal_dependency_number == extenal_dependncy_number:
    dependencies_up_to_date = 'Yes'
else:
    print('Non critical error message:\n the progarm can not verify if your dependencys are out of date please try to re-download and install the prograrm.')
    dependencies_up_to_date = 'IDK'
dependnency_file.close()
lisense_read = open('lisense_read.txt','rt')
read = lisense_read.readline()
lisense_read.close()
version_last_ran_file = open('version_last_ran.txt','rt')
version_last_ran = version_last_ran_file.readline()
version_last_ran_file.close()
disclaimer_read_file = open('disclaimer_read.txt','rt')
disclaimer_read = disclaimer_read_file.readline()
disclaimer_read_file.close()
changelog_latest_read_file = open('changelog_latest_read.txt','rt')
changelog_latest_read = changelog_latest_read_file.readline()
changelog_latest_read_file.close()
credits_read_file = open('credits_read.txt','rt')
credits_read = credits_read_file.readline()
credits_read_file.close()
bugfinders_read_file = open('bugfinders_read.txt','rt')
bugfinders_read = bugfinders_read_file.readline()
bugfinders_read_file.close
if disclaimer_read != 'Yes' or credits_read != 'Yes' or bugfinders_read != 'Yes' or changelog_latest_read != 'Yes' or new_account == 'No':
    any_read_files = 'No'
else:
    any_read_files= 'Yes'
if version_last_ran == '':
    print('Thank you for installing my maths quiz prograrm.\nPlease contact me if you encounter any bugs or issues but first we need to get some legal stuff out of the way\n.')
    read == 'no'
    new_version = 'Yes'
    new_install = 'Yes'
elif version_last_ran != current_version:
    print('Thank you for updating the software!\nWe now need to re varifiy the lisense as there may have been changes to it please enshure you re-read it!\nOnce that is done we will show all updated documentation for the program including the change log.')
    read = 'no'
    new_version = 'Yes'
    new_install = 'No'
elif version_last_ran == current_version:
    new_install = 'No'
    new_version = 'No'
else:
    print('\nNon crititcal error message: Version not verified as a precution please contact the dev team, automaticly reseting lisence verification.\n')
    read = 'no'
    any_read_files == 'No'
if read != 'Yes' or new_version == 'Yes' or new_install == 'Yes' or any_read_files == 'No' or new_account == 'Yes':
    open_file_internaly = input('Would you like to read the lisense file in program?\n(Y/N) :')
    if open_file_internaly == 'Y':
        lisense = open('lisense(.txt_version).txt','rt')
        print (lisense.readlines())
    elif open_file_internaly == 'N':
        print('Please find the file "copyright and lisense.txt" in the game install directory and read it or restart the progarm and have it display the lisense internaly.')
    else:
        print('Attempted bypass of lisense term accepting system detected, now closing prograrm!')
        input('Press enter to exit')
        exit()
    print('Do you accept the lisense terms?')
    accept = input('(Y/N)')
    if accept == 'N':
        print('You have denided the terms you have 24 hrs from the time that you downloaded the software to remove all traces of it from your computer (or any storage devices owned/managed by you) or accept!')
        input('Press enter to exit')
        exit()
    elif accept == 'Y':
        accept = 'Yes'
        print('Thank you for accepting the lisense terms!')
        lisense_read_write = open('lisense_read.txt','wt')
        lisense_read_write.write('Yes')
        lisense_read_write.close()
    else:
        print('Attempted bypass of lisense term accepting system detected, now closing prograrm!')
        input('Press enter to exit')
        exit()
elif read == 'no' or read == 'No' or read == 'NO':
    print('Attempted bypass of lisense system detected! Will now close the program!')
    input('Press enter to close')
    exit()
if disclaimer_read != 'Yes' or new_version == 'Yes' or new_install == 'Yes' or disclaimer_read == 'no' or disclaimer_read == 'No' or disclaimer_read == 'NO' or disclaimer_read == 'nO'or new_account == 'Yes':
    disclaimer_file = open('disclaimer.txt','rt')
    disclaimer_data = disclaimer_file.readlines()
    disclaimer_file.close()
    print(disclaimer_data)
    disclaimer_accept = input('Do you accept that you have read and understand this disclaimer? (Y/N) :')
    if disclaimer_accept == 'Y':
        print('Thank you for accepting the disclaimer')
        disclaimer_read_file_write = open('disclaimer_read.txt','wt')
        disclaimer_read_file_write.write('Yes')
        disclaimer_read_file_write.close()
    elif disclaimer_accept == 'N':
        print('You have declined the disclaimer policy you may not use this software until you accept it.\nNow closing program')
        disclaimer_read_file_write = open('disclaimer_read.txt','wt')
        disclaimer_read_file_write.write('no')
        disclaimer_read_file_write.close()
        input('Press enter to close')
        exit()
    else:
        print('Attempt to bypass disclaimer accepance system detected now closing prograrm!')
        input('Press enter to close')
        exit()
if new_version == 'Yes' or credits_read == 'No' or any_read_files == 'No' or new_account == 'Yes':
    print('\nWould you like to veiw the credits for the prograrm?')
    see_credits = input('(Y/N):')
    if see_credits == 'Y':
        credits_file = open('credits.txt','rt')
        credits_ = credits_file.readline()
        credits_file.close()
        print(credits_)
        credits_record_write = open('credits_read.txt','wt')
        credits_record_write.write('Yes')
        credits_record_write.close()
    elif see_credits == 'N':
        pass
    else:
        pass
    print('\nWould you like to see the bug finder list?')
    see_bug_finders = input('(Y/N):')
    if see_bug_finders == 'Y' or bugfinders_read != 'Yes':
        bug_finder_file = open('Bugfinders.txt','rt')
        bug_finder_data = bug_finder_file.readline()
        print(bug_finder_data)
        bug_finder_record_write = open('bugfinders_read.txt','wt')
        bug_finder_record_write.write('Yes')
        bug_finder_record_write.close()
    elif see_bug_finders == 'N':
        pass
    else:
        pass
    print('\nWould you like to see the full change log?')
    see_full_changelog = input('(Y/N):')
    if see_full_changelog == 'Y':
        latest_changelog_record_write = open('changelog_latest_read.txt','wt')
        latest_changelog_record_write.write('Yes')
        latest_changelog_record_write.close()
        changelog_file = open('changelog.txt','rt')
        changelog_data = changelog_file.readline()
        print(changelog_data)
    elif see_full_changelog == 'N' or changelog_latest_read != 'Yes':
        print('\nWould you like to see the changes in the latest version?')
        see_changelog_latest = input('(Y/N):')
        if see_changeglog_latest == 'Y':
            latest_changelog_file = open('changelog_latest','rt')
            latest_changelog_data = latest_changelog_file.readline()
            print(latest_changelog_data)
            latest_changelog_record_write = open('changelog_latest_read.txt','wt')
            latest_changelog_record_write.write('Yes')
            latest_changelog_record_write.close()
        elif see_changelog_latest == 'N':
            pass
        else:
            pass
    else:
        pass
if dependencies_up_to_date == 'No' and new_version == 'Yes' and new_install == 'No':
    print('Your dependencies seem to be older than the version of code you are running./nPlease always fully unzip all files in the zip folder for an update.')
elif dependencies_up_to_date == 'No' and new_install == 'Yes':
    print('It seems all the .txt files have not been fully un-ziped when you installed this prograrm please try and re-un-zip this prograrm of you are having issues please contact a member of the dev team')
version_file_write = open('version_last_ran.txt','wt')
version_file_write.write(current_version)
version_file_write.close()
nickname_file = open('user_nicknames.txt','rt')
#looks to see if the user has used the file before to be able to offer that their nickname is automaticly set to their most recent one
old_nickname = nickname_file.readline()
if old_nickname != '':
    #if the user has used the program before it will offer the user the option to use their old nickname or create a new one
    while validation_loop_variable == 'Not Valid':
        nickname_prompt = 'In the past you have used ',old_nickname,' as your nickname would you like to create a new nickname? (Y/N) :'
        print('In the past you have used ',old_nickname,' as your nickname would you like to create a new nickname?')
        use_old_nickname = input('(Y/N) :')
        if use_old_nickname == 'N' or use_old_nickname == 'n':
            validation_loop_variable = 'Valid'
            user_nickname = old_nickname
        elif use_old_nickname == 'Y' or use_old_nickname == 'y':
            validation_loop_variable = 'Valid'
            user_nickname = input('Create a new nickname. :\n')
            nickname_file.close()
            nickname_file = open('user_nicknames.txt','wt')
            nickname_file.write(user_nickname)
            #writes new nickname to the file for future use
            nickname_file.close()
        else:
            print('Please answer Y or N to the question')
            #enshures the user answers the question in a way that the computer can use the user's reponse
else:
    user_nickname = input('Create a nickname:\n')
    nickname_file.close()
    nickname_file = open('user_nicknames.txt','wt')
    #if no old nickname can be found it will ask the user to create a new nickname
    nickname_file.write(user_nickname)
    nickname_file.close()
print('\nWelcome to my maths quiz program ',user_nickname,'\n')
#the while loop is as once the intital setup has been run the main bluck of the code just has to be run in a cycle
while quit_yn == 'N':
    questions_in_bunch = 0
    score_this_bunch = 0
    validation_loop_variable = 'Not Valid'
    while validation_loop_variable == 'Not Valid':
        #lets the user chose to practice a specific mathmatical operation or to have the computer randomly chose one
        user_operation_input=input('Please enter a mathmatical operation symbol to select that to practice or you can enter: "?" to have one randomly selected each question:\n')
        if user_operation_input == '+':
            system_operation = '+'
            validation_loop_variable = 'Valid'
            #all this if-elif-else statement is to convert the user's input of the operation symbol into an interger from a string for the computer to use at a later point in the code
        elif user_operation_input == '-':
            system_operation = '-'
            validation_loop_variable = 'Valid'
        elif user_operation_input == '*' or user_operation_input == 'x' or user_operation_input == 'X':
            system_operation = '*'
            validation_loop_variable = 'Valid'
        elif user_operation_input == '/':
            system_operation = '/'
            validation_loop_variable = 'Valid'
        elif user_operation_input == '?':
            system_operation = 'Random'
            random_operation = 'True'
            validation_loop_variable = 'Valid'
        else:
            print('Invalid input!\nPlease re-read the question.')
            validation_loop_variable = 'Not Valid'
    validation_loop_variable = 'Not Valid'
    #preps the validation loop for next useage
    print('\nYou have selected :',system_operation,' as your mathmatcial operation of choice to practice')
    is_int = 'True'
    while validation_loop_variable == 'Not Valid':
        is_int = 'True'
        difficulty = input('\nPlease select a number between 1 and 10 to be a diffiulcty (1 being the easyest and 10 being the hardest):')
        #to avoid a crash the code will first test to see if the input is an interger before trying to convert therefore accomodating for user error or attempts to crash the program
        try:
           difficulty = int(difficulty)
        except Exception as e:
            print('Your did not input in the correct format leading to this error :',e)
            is_int = 'False'
        if is_int == 'True':
            if difficulty > 10 or difficulty < 0:
                print('\nInvalid input please only enter a number between 1 and 10 next time.\n')
                #enshures yet again that the user's input will be of use to the computer
                validation_loop_variable = 'Not Valid'
            else:
                print('\nYou have selected a difficulty of: ',difficulty,'\n')
                validation_loop_variable = 'Valid'
        else:
            #this runs if the input isn't an interger and therefore can't be converted
            print('\nPlease input only a number (so no letters puntuation etc)')
        #this loop will run 10 times to give the user a batch of 10 questions before letting them change their settings and see their score
    while questions_in_bunch < 10:
            random_number = random.randint(1,10)
            number_1 = random_number*difficulty
            random_number = random.randint(1,10)
            #gets 2 random numbers between 1 and 10 to be used to randomly form the mathmatical sum
            number_2 = random_number*difficulty
            if random_operation == 'True':
                #looks to see if the user has the computer set to pick a random operation
                random_number = random.randint(1,4)
                random_operation_number = random_number
                if random_operation_number == 1:
                    system_operation = '+'
                elif random_operation_number == 2:
                    #uses a randint command to make a random number between 1 and 4 each number coresponding to a math matical operation
                    system_operation = '-'
                elif random_operation_number == 3:
                    system_operation = '*'
                elif random_operation_number == 4:
                    system_operation = '/'
                else:
                    print('Invalid value for "random_operation_number"')
            elif random_operation == 'False':
                pass
            else:
                validation_loop_variable = 'Not Valid'
                while validation_loop_variable == 'Not Valid':
                    print('\n!!!\nError:\nvariable issue: "random_operation" variable has not been set to either True of False!\n!!!\nWould you like to try and veiw what the variable has been set to? (WARNING: This runs a risk of crashing the program)')
                    view_error = input('(Y/N): ')
                    if veiw_error == 'Y':
                        print('The variable "random_operation" is set to: ',random_operation)
                        input('Press any key to continute ...')
                        validation_loop_variable = 'Valid'
                    elif veiw_error == 'N':
                        validation_loop_variable = 'Valid'
                    else:
                        validation_loop_variable = 'Not Valid'
                        print('Please read the question carefuly this time!')
            validation_loop_variable = 'Not Valid'
            if system_operation == '+':
                number_1 = number_1 * 2
                number_2 = number_2 * 2
                question_as_string = number_1,' + ',number_2,' = '
                computer_answer = number_1 + number_2
            elif system_operation == '-':
                question_as_string = number_1,' - ',number_2,' = '
                computer_answer = number_1 - number_2
            elif system_operation == '*':
                number_1 = number_1 * 2
                number_2 = number_2 * 2
                question_as_string = number_1,' X ',number_2,' = '
                computer_answer = number_1 * number_2
            elif system_operation == '/':
                while number_one_not_even == 'true':
                    even_value = number_1 % 2
                    if even_value == 1:
                        number_1 = random.randint(1,10)
                    elif even_value == 0:
                        number_one_not_even = 'false'
                    else:
                        print('Minor error:\n Variable "number_1" could not be identifed as even or odd will now assume it is odd')
                while number_two_not_even == 'true':
                    even_value = number_2 % 2
                    if even_value == 1:
                        number_2 = random.randint(1,10)
                    elif even_value == 0:
                        number_two_not_even = 'false'
                    else:
                        print('Minor error:\n Variable "number_2" could not be identifed as even or odd will now assume it is odd')
                number_1 = number_1 / 2
                number_2 = number_2 / 2
                question_as_string = number_1,' / ',number_2,' = '
                computer_answer = number_1 / number_2
            else:
                print('Warning!: Invalid value assigned to the variable "system_operation" is is currently set to: ',system_operation,'\nThis may lead to a crash of the program if the program continutes to run')
                input('Press enter to continute . . .')
            print(question_as_string,' \n\nRemember if the answer is a decimal to round to the nearest whole number.')
            user_answer = input('Please input your answer here :')
            is_int = 'True'
            try:
                user_answer = int(user_answer)
            except Exception as e:
                is_int = 'False'
            computer_answer = (round(computer_answer))
            if is_int == 'True':
                user_answer = int(user_answer)
                if user_answer == computer_answer:
                    print('\nYour answer was correct! ',user_nickname,'+1 Point!\n')
                    score = score + 1
                    #adds score to both the session score and the question bunch score
                    score_this_bunch = score_this_bunch + 1
                    #bunch refers to a batch of 10 questions the computer generates for the user
                else:
                    print('\nYour answer was wroung the correct answer was: ',computer_answer,' Better luck next time',user_nickname)
                    total_quesions = total_questions + 1
                    #tells the user their answer was wroung and informs them of the corecct answer while nor adding or deducting...
                    #points from them but still stating the question has being wroung for the user to see at the end of that question bunch
            else:
                print('\nYou did not input an interger into the progarm (defulting to wroung answer)')
                print('\nYour answer was wroung the correct answer was: ',computer_answer,' Better luck next time',user_nickname)
                total_quesions = total_questions + 1
            total_questions = total_questions + 1
            questions_in_bunch = questions_in_bunch + 1
            percentage = score_this_bunch / 10
            precentage = percentage * 100
        #calulates the user's percentage for the last 10 questions and tells the user that as well as their score over the same 10 questions
    print('Weldone you have compleated 10 questions out of these 10 you got:\n',score_this_bunch,' correct\n That means a percentage of: ',percentage*100,'% correct')
    valdation_loop_variable = 'Not Valid'
    while validation_loop_variable == 'Not Valid':
            print('Would you like to quit now to see your results for this whole session?')
            quit_yn = input('Please answer in the format (Y/N): ')
            #asks the user if they whant to end their session of the program
            if quit_yn == 'Y':
                percentage = score / total_questions
                percentage = precentage
                #gives the user their percentage for this whole instance that the program has beem ran
                print('\nDuring this whole session you did a total of: ',total_questions,' questions.\nAnd a total of: ',score,' were correct.\nThat leaves you with a percentage of: ',percentage,'% correct.\n')
                total_questions_file_read = open('total_questions.txt','rt')
                total_questions_all_time =  total_questions_file_read.readline()
                total_questions_all_time = int(total_questions_all_time)
                total_questions = total_questions + total_questions_all_time
                #calculates then displays the total questions ever done using this program by fetching data from a .txt file in the game directory
                print('Out of all the time you have been using this program you have compeated:\nA total of: ',total_questions,' questions!\n')
                total_score_file_read = open('total_score.txt','rt')
                score_all_time = total_score_file_read.readline()
                score_all_time = int(score_all_time)
                score = score + score_all_time
                print('And a total of: ',score,' were correct.\n')
                #does the same as the last comment but this time fore score
                percentage = score / total_questions
                percentage = percentage * 100
                print('That makes for an all time percentage of: ',percentage,'% correct.\n')
                #uses the 2 above mentioned stats to make an all time percentage
                total_score_file_read.close()
                total_questions_file_read.close()
                score = str(score)
                total_questions = str(total_questions)
                total_score_file_write = open('total_score.txt','wt')
                #writes the new updated stats to the .txt file for future useage
                total_questions_file_write = open('total_questions.txt','wt')
                total_questions_file_write.write(total_questions)
                total_score_file_write.write(score)
                total_score_file_write.close()
                total_questions_file_write.close()
                print('Your score and questions done have been sucessfully saved!')
                #tells the user they have been saved then exits the loop
                validation_loop_variable = 'Valid'
            elif quit_yn == 'N':
                validation_loop_variable = 'Valid'
                print('Thank you for choosing to continute to play!\n')
            else:
                print('Please use the (Y/N) format for your answer')
                validation_loop_variable = 'Not Valid'
print('The progarm has finsished running.')
input('Press enter to exit')
#uses an input so the program waits before closing to give the user time to acknowlege the messages that have been sent before closing
exit()


from Phonebook.Framework.command_generator import CommandGenerator
import Phonebook.Framework.command_instractions as cm_instruction
from .parser import Parser

class ConsoleParser(Parser):
    def __init__(self, command_generator):
        self.__commands = [cm_instruction.CREATE_USER,
                            cm_instruction.LOGIN_USER,]
        self.__command_generator = command_generator

    def parse(self, command_str):
        command_list = command_str.split(' ')
        instruction = command_list[0]
        if instruction not in self.__commands:
            raise ValueError("Wrong Commnad")
        command_index = self.__commands.index(instruction)
        return self.__create_command(command_index, command_list[1:])

    def __create_command(self, command_index, command_list):
        command_options = dict()
        for option in command_list:
            option_name, option_value = option.split('=')
            command_options[option_name] = option_value
        if (command_index == 0):
            return self.__command_generator.create_user(command_options)
        if (command_index == 1):
            return self.__command_generator.login_user(command_options)


'''Altere o programa anterior para que ele aceite apenas números entre 0 e 1000. '''

i = int(input("Digite quantos números deseja digitar: \n"))

cont = 1
maiorNum = int(input("Digite um número entre 0 e 1000: \n"))
while maiorNum < 0 or maiorNum > 1000 :
    maiorNum = int(input("Número inválido! Digite novamente.\n"))
else:
    menorNum = maiorNum
    soma = maiorNum
    while cont < i :
        num = int(input("Digite um número entre 0 e 1000: \n"))
        if maiorNum < num :
            maiorNum = num

        if menorNum > num :
            menorNum = num

        soma = soma + num

        cont += 1

print("O menor número lido é: {}\n".format(menorNum))
print("O maior número lido é: {}\n".format(maiorNum))
print("A soma de todos os números lidos é: {}\n".format(soma))

python.org/Lista de Estrutura de Repetição/questao19.py


import pywhatkit

print("Bienvenido")

print("Escribe el tema que quieres investigar")
tema = str(input())

print("En cuentas lineas quieres la invetigacion?:")

lineas = int(input())

pywhatkit.info(tema, lines = lineas)

"Nota: tiene error con las palabras (xbox, google, auronplay), pronto se solucionara"


from __future__ import annotations

from CollisionHandler import CollisionHandler
from Coord import Coord
from functions import change, set_world

class HeroFireHandler(CollisionHandler):
    def __init__(self, handler: CollisionHandler | None):
        super().__init__(handler)
        self.sprites = "H", "F"

    def check_sprite_condition(self, x1: Coord, x2: Coord) -> bool:
        return x1.sprite.name in self.sprites and x2.sprite.name in self.sprites and x1.sprite.name != x2.sprite.name

    def do_sprite_collision(self, world: list[Coord], x1: Coord, x2: Coord) -> list[Coord]:
        print(f"生命：{x1.sprite} {x2.sprite}發生碰撞～英雄單位扣10hp～")
        if x1.sprite.name == "H":
            x1.sprite.hp -= 10
            if x1.sprite.hp <= 0:
                print("英雄已死亡")
                x1.sprite = None
            else:
                print(f"生命{x1.sprite}已移動至{x2.x}")
            x2.sprite = None
            world = set_world(world, x1, x2)
            world = change(world, x1, x2)
        elif x2.sprite.name == "H":
            x2.sprite.hp -= 10
            if x2.sprite.hp <= 0:
                print("英雄已死亡")
                x2.sprite = None
            x1.sprite = None
            world = set_world(world, x1, x2)
        return world


import numpy as np
import random

TOP = 1; BOTTOM = 0; RIGHT = 2; LEFT = 3; END = 8;
FLOWDIRECTIONS = [[1,0],[-1,0],[0,1],[0,-1],[-1,-1],[-1,1],[1,1],[1,-1]]
OCEANLEVEL = 0.2; OCEANDRAIN = -50; ZERO = 0.004

def fillDrain(heightmap,drainsmap,drains,flowheatmap,di,exitss,
		volumes,H,lakes,rivers,ignore):
	if di in ignore:
		return
	drain = drains[di]
	ye,xe = drain[0][1]
	drain.sort()
	s = 0
	drainid = di+2 #begins at 2
	exits = exitss[di]
	for i,(h,(y,x),filled) in enumerate(drain):
		if filled:
			continue #reloop to next
		lakes[di].append((h,(y,x)))
		drain[i] = (h,(y,x),True)
		for yt,xt in [(y+1,x),(y-1,x),(y,x+1),(y,x-1)]: #test overflow
			if drainsmap[yt][xt] != drainid:
				exits.append((heightmap[yt][xt],(yt,xt)))
				exits.sort() #put the lowest exit first
		if len(exits) > 0 and exits[0][0] <= h: #overflow
			ye,xe = exits[0][1] #exit position
			flowedzoneid = drainsmap[ye][xe] #new flowing zone
			fdi = flowedzoneid-2
			if flowedzoneid == 1: #to the ocean
				#print("flow into ocean at", (ye, xe))
				rivers.append((ye,xe))
				volumes[di] = 0 #set remaining volume for this zone to 0
			elif H[di] > H[fdi] and H[di] - H[fdi] < 0.001: #same level (== prob not correct)
				#need to fuse and run algo on fused zone
				volumes[di] += volumes[fdi]
				for hf,(yf,xf),f in drains[fdi]:
					drainsmap[yf][xf] = drainid #fuse drainmaps
				for hl,(yl,xl) in lakes[fdi]:
					lakes[di].append((hl,(yl,xl)))
				lakes[fdi] = []
				drains[di] += drains[fdi]
				print(len(drains[di]))
				exitss[di] += exitss[fdi]
				nexits = []
				for hne,(yne,xne) in exitss[di]:
					if (drainsmap[yne][xne] != drainid and
							drainsmap[yne][xne] != flowedzoneid):
						nexits.append((hne,(yne,xne)))
				exitss[di] = nexits
				ignore.append(fdi) #for when the fdi lake has not been made already
				print("level/fuse", drainid, "with", flowedzoneid, "at", (ye, xe), exits[0], H[di],H[fdi])
				fillDrain(heightmap,drainsmap,drains,flowheatmap,
					di,exitss,volumes,H,lakes,rivers,ignore)
				return
			elif H[di] > H[fdi]: #lower level: flow into
				volumes[fdi] += volumes[di]
				volumes[di] = 0 #set remaining volume for this zone to 0
				#print("flow into", flowedzoneid, "at", (ye, xe), exits[0])
				fillDrain(heightmap,drainsmap,drains,flowheatmap,
					fdi,exitss,volumes,H,lakes,rivers,ignore)
				if di in ignore: #filled drain has level and removed current drain
					return
				else: #a river goes into the filled drain
					rivers.append((ye,xe))
			else: #higher level: continue to fill itself
				pass
		hdif = drain[i+1][0] - h #prob is zone not big enough (too much flow for the minima sizes)
		H[di] += hdif
		s += 1
		volumes[di] -= s * hdif
		if volumes[di] <= 0:
			H[di] -= -volumes[di]/s
			break
		lakes[di][0] = (H[di],lakes[di][0][1])
	#rc = random.choice(lake)
	#print(rc, heightmap[rc[1][0]][rc[1][1]])
	#lakes.append(lake)
	#print((ye,xe), volumes[di], s, H[di])

def lakesMap(heightmap,drainsmap,drains,flowheatmap,flowmap):
	lakes, rivers = [], []
	volumes, drainids, H, exitss = [], [], [], []
	for drain in drains:
		for i,(h,(x,y)) in enumerate(drain):
			drain[i] = (h,(x,y),False)
		ye,xe = drain[0][1]
		surface = flowheatmap[ye][xe]
		volume = surface*1000
		volumes.append(volume)
		H.append(drain[0][0]) #lake height begins at lowest point
		exitss.append([])
		lakes.append([])
	ignore = [] #drains to be ignored
	for di,drain in enumerate(drains):
		fillDrain(heightmap,drainsmap,drains,
			flowheatmap,di,exitss,volumes,H,lakes,rivers,ignore)
	height, width = len(heightmap), len(heightmap[0])
	lakesmap = [[0]*width for _ in range(height)]
	waterhmap = [[0]*width for _ in range(height)]
	lakeid = 1
	for lake in lakes:
		for h,(y,x) in lake:
			waterhmap[y][x] = lake[0][0]
			lakesmap[y][x] = lakeid
		lakeid += 1
	riverid = lakeid
	print(len(rivers), "rivers")
	for yr,xr in rivers:
		while lakesmap[yr][xr] == 0 and drainsmap[yr][xr] != 0 and flowmap[yr][xr] != END:
			lakesmap[yr][xr] = riverid
			heightmap[yr][xr] -= 0.001
			yd, xd = FLOWDIRECTIONS[flowmap[yr][xr]]
			yr += yd
			xr += xd
	oceanid = riverid+10
	# for y,x in np.ndindex((height,width)):
	# 	if drainsmap[y][x] == 0:
	# 		lakesmap[y][x] = oceanid
	return lakesmap,waterhmap

def flowHeatMap(flowmap):
	height, width = len(flowmap), len(flowmap[0])
	flowheatmap = [[0]*width for _ in range(height)]
	for y,x in np.ndindex((height,width)):
		while flowmap[y][x] != -1 and flowmap[y][x] != END:
			yxd = FLOWDIRECTIONS[flowmap[y][x]]
			y += yxd[0]
			x += yxd[1]
			flowheatmap[y][x] += 1
	return flowheatmap

def flowMap(heightmap):
	height, width = len(heightmap), len(heightmap[0])
	flowmap = [[[None]*width for _ in range(height)] for __ in range(3)]
	flowgraph = []
	for y,x in np.ndindex((height,width)):
		if heightmap[y][x] > OCEANLEVEL:
			h = heightmap[y][x]
			d = []
			for D in FLOWDIRECTIONS:
				d.append(heightmap[y+D[0]][x+D[1]] - h)
			sqrt2 = 2**0.5
			for i in range(3,8): #divide by hori/diago ratio
				d[i] /= sqrt2
			steepest = d.index(min(d))
			if d[steepest] < 0:
				flowmap[0][y][x] = steepest
				# D = FLOWDIRECTIONS[steepest]
				# flowmap[2][y][x] = (d[steepest], (y+D[0], x+D[1]))
			else:
				flowmap[0][y][x] = END
			if abs(d[steepest]) < ZERO:
				d[steepest] = 0
			flowmap[1][y][x] = d[steepest]
		else:
			flowmap[0][y][x] = -1
			flowmap[1][y][x] = -1
	return flowmap

def drainageBasins(heightmap,flowmap):
	drainid = 2;
	height, width = len(heightmap), len(heightmap[0])
	drainmap = [[0]*width for _ in range(height)]
	drains = []
	ends = []
	nends = 0
	for y,x in np.ndindex((height,width)):
		path = []
		while flowmap[0][y][x] != -1 and flowmap[0][y][x] != END and drainmap[y][x] == 0:
			direction = flowmap[0][y][x]
			path.append((y,x))
			y += FLOWDIRECTIONS[direction][0] #follow the flow
			x += FLOWDIRECTIONS[direction][1]
		if drainmap[y][x] == 0: #unexplored tile
			if flowmap[0][y][x] == END: #new minima
				nends += 1
				di = drainid
				for ye,xe in ends:
					if abs(ye-y) <= 1 and abs(xe-x) <= 1:
						di = drainmap[ye][xe] #fuse with close drain
						nends -= 1
						break
				if di == drainid: #new drain
					drainid += 1
					drains.append([])
				drainmap[y][x] = di
				drains[di-2].append(((heightmap[y][x]),(y,x)))
				ends.append((y,x))
			elif flowmap[0][y][x] == -1: #sea
				di = 1
			else:
				di = -100
		else: #already assigned minima
			di = drainmap[y][x]
			if di != 1:
				drains[di-2].append(((heightmap[y][x]),(y,x)))
		for yf,xf in path: #set the id of the path
			drainmap[yf][xf] = di
			if di != 1:
				drains[di-2].append((heightmap[yf][xf],(yf,xf)))
	print(len(ends), nends, "ends")
	for ye,xe in ends:
		pass
		#drainmap[ye][xe] = 0
	print(drains[0][0:1])
	return drainmap,drains

def exploreFlat(basinsmap, flowmap, yi, xi, bid):
	pile = []
	pile.append((yi,xi))
	while len(pile) > 0:
		y, x = pile.pop()
		if basinsmap[y][x] == 0 and abs(flowmap[1][y][x]) < ZERO and flowmap[0][y][x] != 0:
			basinsmap[y][x] = bid
			pile.append((y+1, x))
			pile.append((y-1, x))
			pile.append((y, x+1))
			pile.append((y, x-1))

def flatMap(flowmap):
	height, width = len(flowmap[0]), len(flowmap[0][0])
	basinsmap = [[0]*width for _ in range(height)]
	bid = 1
	for y,x in np.ndindex((height,width)):
		if flowmap[0][y][x] != 0: #not ocean
			exploreFlat(basinsmap, flowmap, y, x, bid)
			if basinsmap[y][x] == bid: #used the id
				bid += 1
	return basinsmap


class User():

    def __init__(self, first_name, last_name , age, location, username, email ):

        self.first_name = first_name
        self.last_name = last_name
        self.age = age
        self.location = location
        self.username = username
        self.email = email
        self.login_attempts = 0

    def describe_user(self):
        print("\nFirst name: " + self.first_name.title()
        +"\nLast name: " + self.last_name.title()
        +"\nAge: " + str(self.age)
        +"\nLocation: " + self.location.title()
              +"\nUsername: " + self.username.title()
              +"\nEmail: " + self.email)

    def greet_user(self):
        print("Hello " + self.first_name.title() + " " +self.last_name.title())

    def increment_login_attempts(self):
        self.login_attempts += 1

    def reset_login_attempts(self):
        self.login_attempts = 0

user_a = User('tashan','wright-mckenzie',26,'london','tashwri93', 'tash93@gmail.com')

print("User details:")
user_a.describe_user()

print("\nAttempted Logins:")
user_a.increment_login_attempts()
user_a.increment_login_attempts()
user_a.increment_login_attempts()
print("Attempted logins: " + str(user_a.login_attempts))

print("\nResetting Logins...")

user_a.reset_login_attempts()
print("Attempted logins: " + str(user_a.login_attempts))


def sum_csv(file_name):
    somma=0
    my_file=open(file_name, 'r') # r=read

    for line in my_file:
        elements=line.strip('\n').split(',')
        if elements[0]!='Date':
            items=float(elements[1])
            somma+=items

    if somma==0:
        return None
    return somma
    #if elements[0]==None:
        #return None
    #else:
        #return somma

#../directory/ quando il file a cui fai riferimento è in una directory differente rispetto a quella del file che stai editando
#print(sum_csv('../files/vuoto.csv'))


'''

In a file called fuel.py, implement a program that

prompts the user for a fraction, formatted as X/Y,
    wherein each of X and Y is an integer, and then
    outputs, as a percentage rounded to the nearest integer, how much fuel is in the tank.
        If 0 - 1%, output E
        If 99% - 100%, output F
        and "Z%" otherwise, wherein Z is that same int.

'''

def main():
    while True:
        try:
            response = input('Fraction: ')
            percentage = convert(response)
            print(gauge(percentage))
            break
        except (ValueError, TypeError, ZeroDivisionError):
            continue #re-prompt for input

def convert(fraction):
    x, y = fraction.strip().split('/')
    try:
        if int(x)/int(y) > 1:
            raise ValueError

        elif int(y) == 0:
            raise ZeroDivisionError

        else:
            return int(x)/int(y)*100

    except :
        return #re-prompt for input in main()

def gauge(percentage):

        if 1 < percentage < 99:
            return f'{percentage:.0f}%'
        elif 99 <= percentage <= 100:
            return 'F'
        elif 0 <= percentage <= 1:
            return 'E'
        else:
            return

if __name__ == '__main__':
    main()

# check50 cs50/problems/2022/python/fuel
# submit50 cs50/problems/2022/python/fuel


from flask_app import app, render_template, request, redirect, session
from flask_app.models.model_survey import Survey

@app.route('/')
def index():
    return render_template("index.html")

@app.route('/process', methods=['POST'])
def create_survey():
    data = {
        "name" : request.form['name'],
        "location" : request.form['location'],
        "language" : request.form['language'],
        "comments" : request.form['comments']
    }

    if not Survey.validate_survey(request.form):
        return redirect('/')

    id= Survey.save(data)
    return redirect(f"/result/{id}")

@app.route("/result/<int:id>")
def show_survey(id):
    print("Showing the User Info From the Form")
    data = {
        "id":id
        }
    survey=Survey.get_one(data)
    print(survey)
    return render_template("result.html", survey=survey )


from rest_framework import viewsets
from . import serializers
from .models import *
from datetime import datetime, timedelta
from django.db.models import Sum, Q, Count
from rest_framework.response import Response
from rest_framework.renderers import JSONRenderer
from rest_framework.views import APIView

from rest_framework.decorators import action

class InvernaderoViewset(viewsets.ModelViewSet):
    queryset = Invernadero.objects.all()
    serializer_class = serializers.InvernaderoSerializer

class ZonaViewset(viewsets.ModelViewSet):
    queryset = Zona.objects.all()
    serializer_class = serializers.ZonaSerializer
    def get_queryset(self):
        i = self.request.GET.get('invernadero', None)
        if i :
            zonas_invernadero = Zona.objects.filter(invernadero_id=i)
            print(i)
            return zonas_invernadero
        else:
            queryset = Zona.objects.all()
            return queryset

class TratamientoViewset(viewsets.ModelViewSet):
    queryset = Tratamiento.objects.all()
    serializer_class = serializers.TratamientoSerializer

class HorarioViewset(viewsets.ModelViewSet):
    queryset = Horario.objects.all()
    serializer_class = serializers.HorarioSerializer

class SolucionViewset(viewsets.ModelViewSet):
    queryset = Solucion.objects.all()
    serializer_class = serializers.SolucionSerializer

class NutrienteViewset(viewsets.ModelViewSet):
    queryset = Nutriente.objects.all()
    serializer_class = serializers.NutrienteSerializer

class PlantaViewset(viewsets.ModelViewSet):
    queryset = Planta.objects.all()
    serializer_class = serializers.PlantaSerializer

class TanqueViewset(viewsets.ModelViewSet):
    queryset = Tanque.objects.all()
    serializer_class = serializers.TanqueSerializer
    def get_queryset(self):
        i = self.request.GET.get('zona', None)
        if i :
            tanque_zona = Tanque.objects.filter(zona_id=i)
            print(i)
            return tanque_zona
        else:
            queryset = Tanque.objects.all()
            return queryset

class SensorViewset(viewsets.ModelViewSet):
    queryset = Sensor.objects.all()
    serializer_class = serializers.SensorSerializer
    def get_queryset(self):
        i = self.request.GET.get('tanque', None)
        if i :
            sensor_tanque = Sensor.objects.filter(tanque_id=i)
            print(i)
            return sensor_tanque
        else:
            queryset = Sensor.objects.all()
            return queryset


from typing import List
class Solution:
    def maxHeight(self, cuboids: List[List[int]]) -> int:
        # rotate cube so that width<=length<=height
        for item in cuboids:
            item.sort()
        # sort by width, then length, then height
        cuboids = sorted(cuboids, key=lambda x: (x[0], x[1], x[2]))

        n = len(cuboids)
        dp = [0] * n
        # dp[i] to hold accumated height at each i
        for i, cube in enumerate(cuboids):
            dp[i] = cube[2]
            for j in range(i):
                if cube[1] >= cuboids[j][1] and cube[2] >= cuboids[j][2]:
                    dp[i] = max(dp[i], dp[j] + cube[2])

        return max(dp)


"""This module processes and shows geospatial data to maps.
It is part of the od-dash application.
Example:

TODO example here
"""

import osrm
import pickle
import polyline
import pandas as pd
import plotly.graph_objects as go
import numpy as np
import network_operations as net_ops
from from_to_pair import FromToPair
import graphs.graph_ops as gops
import networkx as nx
import copy
import pdb

css_cols = ['aliceblue','aqua','aquamarine','azure','beige','bisque','black','blanchedalmond','blue','blueviolet','brown','burlywood','cadetblue','chartreuse','chocolate','coral','cornflowerblue','cornsilk','crimson','cyan','darkblue','darkcyan','darkgoldenrod','darkgray','darkgrey','darkgreen','darkkhaki','darkmagenta','darkolivegreen','darkorange','darkorchid','darkred','darksalmon','darkseagreen','darkslateblue']

def create_all_min_path_pairs(centroids_csv):
    """Method to get a file with regional units centres and coordinates and to
    return a list of minimum paths between all points with every other point.

    Args:
        centroids_csv (str): csv file containing all geo information regarding
        regional units.

    Returns:
        [MinPath]: class with path_between points A and B and their geometry.
        should follow the given od matrix
    """
    # read the csv file to dataframe
    df = load_matrix(centroids_csv)
    # create a list of all pairs
    pairs_list = _create_pairs_from_df(df)
    # for each pair, compute the minimum path
    for pair in pairs_list:
        pair.compute_geometry()
    return pairs_list

def load_matrix(selected_matrix, delim='\t', pre_path='data/geodata_names/'):
    """Method to load a matrix of data as table.

    Args:
        selected_matrix (str): name of the file in disk to be loaded.
        delim (str, optional): delimiter for the file to be read. Defaults to
            '\t'.
        pre_path (str, optional): path leading to file. Defaults to
            'data/geodata_names'.

    Returns:
        dataframe: dataframe containing the file contents.
    """
    matrix_filepath = pre_path + selected_matrix
    sample_df = pd.read_csv(matrix_filepath, delimiter=delim)
    sample_df = sample_df.fillna(0)
    print("full loaded matrix path is ", matrix_filepath)
    return sample_df

def _create_pairs_from_df(df):
    # strip df of excess information. hold on to just name and coords
    new_df = df.drop(['ΠΕΡΙΦΕΡΕΙΑ', 'ΚΕΝΤΡΟΕΙΔΕΣ'], axis=1)
    # create a list of tuples containing <name, lon, lat>
    tuples = list(new_df.itertuples(index=False, name=None))
    # iterate tuples and create a list with all vs all
    pairs_list = []
    for curr_node in tuples:
        for next_node in tuples:
            pair = FromToPair('','')
            # assign the tuples to the from and to nodes respectively
            pair.from_node.init_node(*(curr_node))
            pair.to_node.init_node(*(next_node))
            pairs_list.append(pair)
    return pairs_list

def plot_routes_to_map(pairs):
    """Method to plot min paths of pairs to map.

    Args:
        pairs (FromToPair): Minimum path between two nodes and geometry.
        FromToPair class describes the structure of this.
    """
    fig = ''
    graph_filepath = 'data/geodata_names/greece-athens.graphml'
    graph = net_ops.load_graph_from_disk(graph_filepath)
    colorscales = css_cols
    # initialize figure
    fig = go.Figure()
    lat_lines_list = []
    lon_lines_list = []
    lat_nodes_list = []
    lon_nodes_list = []
    skat = 0
    for pair in pairs:
        print(skat)
        skat += 1
        if pair.from_node.name != pair.to_node.name and skat>70:
            has_geometry_set = set_geometry_between_two_points(pair, lat_lines_list, lon_lines_list, skat)
            set_coords_of_two_points(pair, lat_nodes_list, lon_nodes_list, has_geometry_set)
            paint_data_to_figure(fig, lat_nodes_list, lon_nodes_list,
                        lat_lines_list, lon_lines_list, colorscales[-1])
            lat_lines_list = []
            lon_lines_list = []
            lat_nodes_list = []
            lon_nodes_list = []
            if skat> 100:
                break
    #paint_data_to_figure(fig, lat_nodes_list, lon_nodes_list,
    #                     lat_lines_list, lon_lines_list, colorscales)
    return fig

def set_geometry_between_two_points(pair, lat_list, lon_list, skat):
    try:
        route_lines = polyline.decode(pair.geometry)
    except:
        print("error in pair ", skat)
        return False
    for line in route_lines:
        lat, lon = line
        lat_list.append(lat)
        lon_list.append(lon)
    return True

def set_coords_of_two_points(pair, lat_list, lon_list, has_geometry_set):
    if not has_geometry_set:
        return False
    #print("from node is ", pair.from_node.name, " while to node is ", pair.to_node.name)
    lat_list.append(pair.from_node.lat)
    lon_list.append(pair.from_node.lon)
    lat_list.append(pair.to_node.lat)
    lon_list.append(pair.to_node.lon)
    return True

def paint_data_to_figure(fig, lat_nodes_list, lon_nodes_list,
                         lat_lines_list, lon_lines_list, color, weight=4.5,
                         node_title="Κέντρα Περιφερειακών Ενοτήτων", edge_title="Ροές Φορτίων"):
        fig.add_trace(go.Scattermapbox(
            name = edge_title,
            mode = "lines",
            lon = lon_lines_list,
            lat = lat_lines_list,
            marker = {'size': 10},
            line = dict(width = weight, color = color)))
        # adding source marker
        fig.add_trace(go.Scattermapbox(
            name = node_title,
            mode = "markers",
            lon = lon_nodes_list,
            lat = lat_nodes_list,
            marker = {'size': 15, 'color':color, 'opacity':0.8},
            ))

        # getting center for plots:
        lat_center = np.mean(lat_lines_list)
        long_center = np.mean(lon_lines_list)
        # defining the layout using mapbox_style
        fig.update_layout(mapbox_style="open-street-map", #"stamen-terrain",
            mapbox_center_lat = 30, mapbox_center_lon=-80)
        fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0},
                        mapbox = {
                            'center': {'lat': lat_center,
                            'lon': long_center},
                            'zoom': 8})

def scenario_print_traffic(traffic_fname):
    open_file = open(traffic_fname, 'rb')
    loaded_list = pickle.load(open_file)
    open_file.close()
    fig = plot_routes_to_map(loaded_list)

def simple_scenario(traffic_fname):
    centr_csv = 'centroids.csv'
    mp_pairs = create_all_min_path_pairs(centr_csv)
    open_file = open(traffic_fname, 'wb')
    pickle.dump(mp_pairs, open_file)
    open_file.close()
    print("file has been created")

def print_flows(products_file, nodes_list, edges_list, nx_graph):
    """Method to print in a map the total flows in the network.

    Args:
        products_file (str): csv file that contains all flows towards all.
        centroids_list_file (str): csv file that contains all centroids.
    """
    _get_flows_between_nodes(products_file, edges_list, nodes_list, nx_graph)
    # prepare each edge geometry and coordinates for printing
    colorscales = css_cols
    old_range, min_val = _compute_old_range(edges_list)
    # sort edges list by usage weight (in order for the heavier edges to be last)
    edges_list.sort(key=lambda x: x.usage_weight, reverse=False)
    fig = go.Figure()
    for edge in edges_list:
        lat_nodes_list = [edge.from_node.lat, edge.to_node.lat]
        lon_nodes_list = [edge.from_node.lon, edge.to_node.lon]
        lat_lines_list, lon_lines_list = edge.get_geometry_lats_lons_lists()
        scaled_weight = _get_scaled_weight(edge, old_range, min_val)
        scaled_color = _set_scaled_color(scaled_weight)
        route_title_name, route_name_weight = _get_route_details(edge)
        if edge.print_enabled and edge.usage_weight > 0:
            paint_data_to_figure(fig, lat_nodes_list, lon_nodes_list,
                            lat_lines_list, lon_lines_list, scaled_color, scaled_weight,
                            route_title_name, route_name_weight)
    return fig, edges_list, nodes_list

def get_network_as_graph(centroids_list_file):
    centroids_csv = centroids_list_file #'/home/blaxeep/workspace/od-dash/data/geodata_names/centroids-list.csv'
    centroids_df = pd.read_csv(centroids_csv, sep='\t')
    nodes_list, edges_list, net_graph = gops.read_adjacency_list_from_file(centroids_df)
    return nodes_list, edges_list, net_graph

def _get_flows_between_nodes(products_file, edges_list, nodes_list, net_graph):
    pdf = pd.read_csv(products_file, sep='\t')
    # drop first two columns as they contain redundant data.
    pdf = pdf.iloc[:,2:]
    # get all columns to a list (regional units)
    regional_units = pdf.columns.tolist()
    # iterate over all regional units adding the weight.
    for unit in regional_units:
        values = pdf[unit].tolist()
        _add_weight_to_edges_participating_to_min_path(unit, regional_units, values, edges_list, nodes_list, net_graph)

def _add_weight_to_edges_participating_to_min_path(unit, regional_units, values, edges_list, nodes_list, net_graph):
    """method to add weight to edges consisting the minimum path of a flow.
    Algorithm:
    For each <from, to> pair:
        find the min path (dijkstra) from networkx graph
        correspond each edge to edges list
        add the weight to those edges.

    Args:
        unit ([type]): [description]
        values ([type]): [description]
        edges_list ([type]): [description]
        net_graph ([type]): [description]
    """
    # find the min path between the edges
    for reg_unit, weight in zip(regional_units, values):
        try:
            dijkstra_path_nodes = nx.dijkstra_path(net_graph, unit, reg_unit)
            _assign_weight_type_to_node(nodes_list, copy.deepcopy(dijkstra_path_nodes), weight)
            # assign to each edge the weight corresponding to it
            for from_idx in range(len(dijkstra_path_nodes)-1):
                to_idx = from_idx+1
                for edge in edges_list:
                    if edge.are_both_nodes_in_edge(dijkstra_path_nodes[from_idx], dijkstra_path_nodes[to_idx]):
                    #if edge.is_node_in_edge(dijkstra_path_nodes[from_idx]) or\
                    #    edge.is_node_in_edge(dijkstra_path_nodes[to_idx]):
                        edge.add_to_usage_weight(weight)
        except nx.NetworkXNoPath:
            print("No path between ", unit, " and ", reg_unit)

def _compute_old_range(edges_list):
    min_val = 1000000
    max_val = 0
    # find minimum and maximum weights from total edges
    for edge in edges_list:
        if min_val > edge.usage_weight:
            min_val = edge.usage_weight
        if max_val < edge.usage_weight:
            max_val = edge.usage_weight
    # compute old_range and return it
    old_range = max_val - min_val
    print("max range is ", max_val, " and min val is ", min_val)
    return old_range, min_val

def _get_scaled_weight(edge, old_range, min_val, new_range=12):
    """scaling takes place according to this:
    NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin

    https://stackoverflow.com/questions/929103/convert-a-number-range-to-another-range-maintaining-ratio

    Args:
        edge ([type]): [description]
        old_range ([type]): [description]
        min_range ([type]): [description]
    """
    if old_range == 0:
        print("no range, it is 0. cannot be.")
        return -1
    new_min = 3
    old_weight = edge.usage_weight
    weight = ((old_weight - min_val) * new_range) / old_range +new_min
    return weight

def _set_scaled_color(weight, max_threshold=12):
    if weight < max_threshold/4 + 3:
        return 'rgb(0, 255, 0)'
    elif weight < 2*max_threshold/4 + 3:
        return 'rgb(255, 255, 0)'
    elif weight < 3*max_threshold/4 + 3:
        return 'rgb(255, 165, 0)'
    else:
        return 'rgb(255, 0, 0)'

def _get_route_details(edge):
    """ method to get route name and weight."""
    route_name = "Κέντρο Περιφερειακής Ενότητας"
    #route_flow = "Κίνηση: " + str(round(edge.usage_weight, 2))
    if np.isnan(edge.usage_weight):
        edge.usage_weight = 0
    route_flow = str(edge.edge_name) + ":" + str(int(edge.usage_weight)) + " κιλά"
    return route_name, route_flow

def _assign_weight_type_to_node(nodes_list, dijkstra_path_list, weight):
    """
    Method to assign weight to nodes depending on the type of the node.
    If it is a "from" node (meaning weight is starting from there),
    a "to" node (meaning weight is ending there) or
    a "passing" node (meaning this is a node where the weight is transferred through).

    Networkx dijkstra method returns a list of nodes for a certain path, including
    from and to nodes. For instance, in a route A -> B -> C -> D the dijkstra method
    return a list of [A, B, C, D].

    nodes_list is a list containing all available nodes.
    dijkstra path is a path of nodes in a certain route.
    weight is the weight to be added to each node.
    """
    if len(dijkstra_path_list) < 2:
        single_node = dijkstra_path_list.pop()
        #print("number of elements of list dijksta is ", len(dijkstra_path_list), " and it is ", str(single_node))
        #_assign_weight_to_node(single_node, nodes_list, weight, weight_type='from')
        #_assign_weight_to_node(single_node, nodes_list, weight, weight_type='to')
    else:
        _assign_from_to_nodes(dijkstra_path_list, nodes_list, weight)
        if len(dijkstra_path_list) > 0:
            for dijkstra_node in dijkstra_path_list:
                # assign the weight to the right value in the node and continue.
                _assign_weight_to_node(dijkstra_node, nodes_list, weight, weight_type='passing')

def _assign_from_to_nodes(dijkstra_path_list, nodes_list, weight):
        last_node = dijkstra_path_list.pop()
        _assign_weight_to_node(last_node, nodes_list, weight, weight_type='to')
        first_node = dijkstra_path_list.pop(0)
        _assign_weight_to_node(first_node, nodes_list, weight, weight_type='from')

def _assign_weight_to_node(dijkstra_node, nodes_list, weight, weight_type):
    for node in nodes_list:
        if node.name == dijkstra_node:
            if weight_type == 'from':
                node.from_weight += weight
                break
            elif weight_type == 'to':
                node.to_weight += weight
                break
            else:
                node.passing_weight += weight
                break

def main():
    #simple_scenario("/home/blaxeep/Downloads/geolist.pkl")
    fig = scenario_print_traffic("/home/blaxeep/Downloads/geolist.pkl")
    products_f = '/home/blaxeep/workspace/od-dash/results/output-1.csv' #mydf.csv'
    centroids_f = '/home/blaxeep/workspace/od-dash/data/geodata_names/perif_centroids_abal.csv'
    nodes_list, edges_list, nx_graph = get_network_as_graph(centroids_f)
    fig, edges_list, nodes_list = print_flows(products_f, nodes_list, edges_list, nx_graph)
    pdb.set_trace()

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt

#スペクトルをテキストファイルから読み込み
def load_spectrum_txt(file_name):
	spectrum=np.loadtxt(file_name,skiprows=1)

	return spectrum

#スペクトルの合計値を計算
def calc_spectrum_sum(spectrum):
	sum_spectrum=np.sum(spectrum[:,2])

	return sum_spectrum

#正規化したスペクトルを返す
def specturm_normalization(spectrum,sum_spectrum):
	spectrum[:,2]=spectrum[:,2]/sum_spectrum

	return spectrum

#正規化したスペクトルをファイルに書き込み
def write_spectrum(file_name,spectrum_norm):
	with open(file_name,'w') as f:
		f.write("1\n")
		for j in range(len(spectrum_norm)):
			f.write("{:.3f} {:.3f} {:.6f}\n".format(spectrum_norm[j][0],spectrum_norm[j][1],spectrum_norm[j][2]))

def main():
	for i in range(100):
		i=i+1

		input_name='./Spectrum/spectrum%d.text' % i

		spectrum=load_spectrum_txt(input_name)

		sum_spectrum=calc_spectrum_sum(spectrum)

		spectrum_norm=specturm_normalization(spectrum,sum_spectrum)

		output_name='./Spectrum_norm/spectrum_norm%d.txt' % i

		write_spectrum(output_name,spectrum_norm)

if __name__=="__main__":
	main()


#!/usr/bin/env python
# -- coding: utf-8 --#
# @Time : 2019/12/25 16:06
# @Author : Aries
# @Site :
# @File : cal_num.py
# @Software: PyCharm

import re

def cal_num(cal_str):
    '''
    简单四则运算
    :param cal_str:
    :return:
    '''
    cal_list = []
    print(cal_str)
    cal_str = cal_str.replace('[', '(').replace('{', '(').replace(']', ')').replace('}', ')').replace(' ', '')
    print(cal_str)
    num = ''
    for i in cal_str:
        if re.match('[0-9]', i):
            num += i
        elif i == '':
            continue
        else:
            if i == '-' and num == '' and cal_list[-1] == '(':
                num += i
            else:
                if len(num) > 0:
                    cal_list.append(num)
                    num = ''
                cal_list.append(i)

        print(cal_list)
    if len(num) > 0:
        cal_list.append(num)
    print(cal_list)

    num_list = []
    stack = []
    for val in cal_list:
        if val == '(':
            stack.append(val)
        elif val == ')':
            tmp = stack.pop()
            while not (tmp == '('):
                num_list.append(tmp)
                tmp = stack.pop()
        elif val == '*' or val == '/':
            while len(stack) > 0:
                tmp = stack[-1]
                if tmp == '*' or tmp == '/':
                    stack.pop()
                    num_list.append(tmp)
                else:
                    break
            stack.append(val)
        elif val == '+' or val == '-':

            while len(stack) > 0:
                tmp = stack[-1]
                if tmp != '(':
                    stack.pop()
                    num_list.append(tmp)
                else:
                    break
            stack.append(val)
        else:
            num_list.append(val)
    while len(stack) > 0:
        num_list.append(stack.pop())

    new_stack = []
    for val in num_list:
        print(new_stack, val)
        if val in ['+', '-', '*', '/']:
            num2 = new_stack.pop()
            num1 = new_stack.pop()
            if val == '+':
                new_stack.append(num1 + num2)
            elif val == '-':
                new_stack.append(num1 - num2)
            elif val == '*':
                new_stack.append(num1 * num2)
            elif val == '/':
                new_stack.append(num1 / num2)
        else:
            new_stack.append(int(val))
        print(num_list)

    print(new_stack[0])

if __name__ == '__main__':
    '''
    [‘0’-‘9’],‘+’,‘-’, ‘*’,‘/’ ,‘(’， ‘)’,‘[’, ‘]’,‘{’ ,‘}’。
    3+2*{1+2*[-4/(8-6)+7]}
    '''
    cal = '(7+5*4*3+6)'
    cal_num(cal)


import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *

clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.GeometryConversion)

clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager

doc = DocumentManager.Instance.CurrentDBDocument
slabs = UnwrapElement(IN[0])
success = []

TransactionManager.Instance.EnsureInTransaction(doc)
for slab in slabs:
	objtype = slab.GetType().ToString()
	if objtype == "Autodesk.Revit.DB.FootPrintRoof" or objtype == "Autodesk.Revit.DB.Floor":
		try:
			slab.SlabShapeEditor.ResetSlabShape()
			success.append(True)
		except: success.append(False)
	else: success.append(False)
TransactionManager.Instance.TransactionTaskDone()

OUT = (slabs, success)


# -*- encoding: utf-8 -*-
# Given a binary tree
#
#     struct TreeLinkNode {
#       TreeLinkNode *left;
#       TreeLinkNode *right;
#       TreeLinkNode *next;
#     }
# Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
#
# Initially, all next pointers are set to NULL.
#
# Note:
#
# You may only use constant extra space.
# You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
# For example,
# Given the following perfect binary tree,
#          1
#        /  \
#       2    3
#      / \  / \
#     4  5  6  7
# After calling your function, the tree should look like:
#          1 -> NULL
#        /  \
#       2 -> 3 -> NULL
#      / \  / \
#     4->5->6->7 -> NULL
# 用stack每次往里存一排的，然后连上
class TreeLinkNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
        self.next = None
from collections import deque
class Solution:
    # @param root, a tree link node
    # @return nothing
    def connect(self, root):
        #corner case
        if root is None:
            return root

        q =  deque()
        q.append(root)
        while q:
            le = len(q)
            temp = None
            for i in range(le):
                item = q.pop()
                if item.right:
                    q.appendleft(item.right)
                if item.left:
                    q.appendleft(item.left)
                if i == 0:
                    item.next = None
                else:
                    item.next = temp
                temp = item

mycode/leetcode2017/Tree/116. Populating Next Right Pointers in Each Node.py


# -*- coding: utf-8 -*-
# 2次元プロットデータ（3クラス）のデータを読み込んで，k-means法でクラスタリングする
import numpy as np

# 2点間距離を測る関数
def distance(a, b):
    dist = 0.0
    for i in range(len(a)):
        dist += (a[i] - b[i])**2
    dist = np.sqrt(dist)

    return dist

# データを読み込む
data = np.loadtxt("data.csv", delimiter=",")

# データの次元
dim = 2

# クラスターサイズを決定する
NUM = 3

# 各データに対してランダムに各クラスタを割り振る
cluster = []
for i in range(len(data)):
    cluster.append(np.random.randint(NUM))

for time in range(100):
    # 重心を初期化
    center = []
    for i in range(NUM):
        center.append(np.zeros(dim))

    # クラスターの重心を計算する
    for i in range(len(data)):
        center[cluster[i]] += data[i]
    for i in range(NUM):
        center[i] /= cluster.count(i)

    # 各データと各クラスタとの距離を求め，最も近いクラスタに割り当て直す
    for i in range(len(data)):
        dist = distance(center[0], data[i])
        minvalue = dist
        index = 0
        for j in range(1, NUM):
            dist = distance(center[j], data[i])
            if dist<minvalue:
                minvalue = dist
                index = j
        cluster[i] = index

# プロットする
import matplotlib.pyplot as plt

for i in range(len(data)):
    if cluster[i]==0:
        plt.scatter(data[i,0], data[i,1], color='r', marker='o', s=20)
    elif cluster[i]==1:
        plt.scatter(data[i,0], data[i,1], color='g', marker='o', s=20)
    else:
        plt.scatter(data[i,0], data[i,1], color='b', marker='o', s=20)

# グリッド表示
plt.grid(True)

# 表示
plt.show()


'''
Given a binary string S. The task is to count the number of substrings that starts and end with 1. For example, if the input string is
“00100101”, then there are three substrings “1001”, “100101” and “101”.
'''
if __name__ == '__main__':

    t = int(input())
    while t>0:
        s = input()

        x = s.count('1')
        res = (x * (x-1))//2
        print(res)
        '''
        res = 0
        for i in range(len(s)):
            if s[i] == '1':
                for j in range(i+1,len(s)):
                    if s[j] == '1':
                        res += 1
        print(res)
        '''
        t -= 1


"""
Given a list of integers, find the length of the longest range of consecutive integers that are contained in the sorted version of the list.

Here's an illustrative example. Consider the list:

[4, 9, 10, 5, 17, 3, 8, 11, 1, 12, 18, 20]
... which, after sorting, becomes:

[1, 3, 4, 5, 8, 9, 10, 11, 12, 17, 18, 20]
The longest consecutive subsequence is now clearly [8, 9, 10, 11, 12], which has length 5.

Examples
max_consec([4, 9, 10, 5, 17, 3, 8, 11, 1, 12, 18, 20]) ➞ 5
# After sorting list becomes [1, 2, 4, 5, 8, 9, 10, 11, 12, 17, 18, 20]
# Longest consecutive subsequence is [8, 9, 10, 11, 12], which has length 5

max_consec([14, 13, 7, 1, 4, 12, 3, 7, 7, 12, 11, 5, 7]) ➞ 4
# After sorting get [1, 3, 4, 5, 7, 7, 7, 7, 11, 12, 12, 13, 14]
# Longest consecutive subsequence is [11, 12, 13, 14], which has length 4

max_consec([13, 3, 8, 5, 5, 2, 13, 6, 14, 2, 11, 4, 10, 8, 1, 9]) ➞ 6
# After sorting get [1, 2, 2, 3, 4, 5, 5, 6, 8, 8, 9, 10, 11, 13, 13, 14]
# Longest consecutive subsequence is [1, 2, 3, 4, 5, 6], which has length 6
Notes
As in the 2nd and 3rd examples, the given list is allowed to include repeated elements,
but such repetitions are ignored when finding the longest range of consecutive elements.
"""

def max_consec(arr):

    s = set()
    ans = 0

    for ele in arr:
        s.add(ele)

    for i in range(len(arr)):
        if (arr[i] - 1) not in s:

            j = arr[i]
            while (j in s):
                j += 1

            ans = max(ans, j - arr[i])
    return ans

print(max_consec([4, 9, 10, 5, 17, 3, 8, 11, 1, 12, 18, 20]))

Longest Range in the List (Casual Version).py


'''
Perfect Sum Problem (Print all subsets with given sum)
Difficulty Level : Hard
Last Updated : 02 Mar, 2021
Given an array of integers and a sum, the task is to print all subsets of the given array with a sum equal to a given sum.
Examples:

Input : arr[] = {2, 3, 5, 6, 8, 10}
        sum = 10
Output : 5 2 3
         2 8
         10

Input : arr[] = {1, 2, 3, 4, 5}
        sum = 10
Output : 4 3 2 1
         5 3 2
         5 4 1

Algorithm (recursion in Dynamic Programming)
1. Consider that ele and call recursion
2. Don't consider that ele and call recustion
3. If sum == currSum then Count+=1
'''

class PerfectSum:
    count = 0
    def printPossibleSubSets(self, arr, sum, i, curSum):
        if(curSum == sum):
            self.count+=1
            return self.count
        if(curSum < sum  and i<len(arr)):
            self.printPossibleSubSets(arr, sum, i+1, curSum+arr[i])
            self.printPossibleSubSets(arr, sum, i+1, curSum)

if __name__ == '__main__':
    arr = [2, 3, 5, 6, 8, 10]
    sum = 10
    obj = PerfectSum()
    obj.printPossibleSubSets(arr, sum, 0, 0)
    print(obj.count)


from __future__ import unicode_literals
import frappe

from frappe.utils import cstr

__all__ = ["execute"]

def execute(filters={}):
	return get_columns(filters), \
		get_data(filters)

def get_conditions(filters):
	"""
	Return sql conditions ready to use in query

	NOTE: Value is mandatory if condition_type == value
	"""
	company = frappe.get_value("User Permission", {
		"user":frappe.session.user,
		"allow":"Company",
	}, "for_value")

	conditions = (
		("Item", "company", "=", company),
	)

	sql_conditions = []

	for doctype, fieldname, compare, value in conditions:

		if not value:
			continue

		sql_condition = "`tab{doctype}`.`{fieldname}` {compare} '{value}'" \
			.format(doctype=doctype, fieldname=fieldname, compare=compare,
				value=value)

		sql_conditions.append(sql_condition)

	return " And ".join(sql_conditions)

def get_formatted_field(label, width=100, fieldtype=None):
	"""
	Returns formatted string
		[Label]:[Field Type]/[Options]:[Width]
	"""
	from frappe import _

	parts = (
		_(label).title(),
		fieldtype if fieldtype else "Data",
		cstr(width),
	)
	return ":".join(parts)

def get_data(filters):
	"""
	Return the data that needs to be rendered
	"""
	fields = get_fields(filters)
	conditions = get_conditions(filters)

	if filters.get("report_type") == "Stock Report":
		result = frappe.db.sql("""
			Select
				{fields},
				(Select Sum(actual_qty) from `tabStock Ledger Entry` where item_code = `tabPurchase Invoice Item`.item_code) as qty
			From
				`tabPurchase Invoice`
			Inner Join
				`tabPurchase Invoice Item`
				On
					`tabPurchase Invoice`.name = `tabPurchase Invoice Item`.parent
				And
					`tabPurchase Invoice`.docstatus = 1
			Inner Join
					`tabItem`
				On
					`tabItem`.item_code = `tabPurchase Invoice Item`.item_code
				And
					`tabItem`.item_type = 'Containers'
			Inner Join
				`tabItem Description`
			On
				`tabItem Description`.parent = `tabItem`.item_code
			Where
				{conditions}
			Having
				qty > 0

		""".format(fields=fields, conditions=conditions or "1 = 1"),
		filters, debug=True)

	if filters.get("report_type") == "Sold Report":
		result = frappe.db.sql("""
			Select
				{fields}
			From
				`tabSales Invoice`
			Inner Join
				`tabSales Invoice Item`
			On
				`tabSales Invoice`.name = `tabSales Invoice Item`.parent
			And
				`tabSales Invoice`.docstatus = 1
			Inner Join
				`tabItem Description`
			On
				`tabItem Description`.vim_number = SUBSTRING_INDEX(`tabSales Invoice Item`.vim_number,'-', 1)
			Inner Join
				`tabItem`
			On
				`tabItem`.item_code = `tabSales Invoice Item`.item_code
			And
				`tabItem`.item_type = 'Containers'
			Where
				{conditions}
			Group By
				`tabItem Description`.item_code

			""".format(fields=fields, conditions=conditions or "1 = 1"),
		filters, debug=False)

	return result
# SUBSTRING_INDEX(`tabSales Invoice Item`.vim_number, '-', 1)
def get_columns(filters):
	"""
	Return Frappe columns ready to be used on report
	"""
	cols_obj = {
		"Stock Report":(
			("Company", "company", "Data", 120),
			("ETA", "eta", "Date", 90),
			("Due Date", "d_date", "Date", 90),
			("Purchase Date", "p_date", "Date", 90),
			("Supplier", "supplier", "Link/Supplier", 150),
			("Vim Number", "vim_number", "Data", 150),
			("Model", "model", "Data", 80),
			("Year", "year", "Data", 80),
			("Item Code", "item_code", "Link/Item", 110),
			("Booking No.", "booking", "Data", 120),
			("Container", "container", "Data", 110),
			("Purchased Qty", "conversion_factor", "Int", 100),
			("Price", "rate", "Currency", 90),
			("LCV", "landed_cost_voucher_amount", "Currency", 90),
			("Purchase Inv.", "purchase_name", "Link/Purchase Invoice", 110),
			("Shipping Line", "shipping_line", "Data", 110),
		),
		"Sold Report":(
			("Company", "company", "Data", 120),
			("ETA", "eta", "Date", 90),
			("Due Date", "d_date", "Date", 90),
			("Sold Date", "p_date", "Date", 90),
			("Customer", "customer", "Link/Customer", 150),
			("Vim Number", "vim_number", "Data", 150),
			("Make", "make", "Data", 80),
			("Year", "year", "Data", 80),
			("Item Code", "item_code", "Link/Item", 110),
			("Booking No.", "booking", "Data", 120),
			("Container", "container", "Data", 110),
			("Price", "price", "Currency", 90),
			("Cost CAD", "cost", "Float", 90),
			("Cost USD", "cost", "Float", 90),
			("LCV", "lcv", "Float", 90),
			("Purchased Qty", "qty", "Int", 100),
			("Sales Inv.", "purchase_name", "Link/Sales Invoice", 110),
			("Shipping Line", "shipping_line", "Data", 110),
		)
	}

	columns = cols_obj.get(filters.get("report_type"))
	formatted_columns = []

	for label, fieldname, fieldtype, width in columns:
		formatted_column = get_formatted_field(label=label,
			fieldtype=fieldtype, width=width)

		formatted_columns.append(formatted_column)

	return formatted_columns

def get_fields(filters):
	"""
	Return sql fields ready to be used on query
	"""
	fields_obj = {
		"Stock Report":  (
			("Purchase Invoice", "company"),
			("Item", "eta"),
			("Purchase Invoice", "due_date"),
			("Purchase Invoice", "posting_date"),
			("Purchase Invoice", "supplier"),
			("Item Description", "vim_number"),
			("Item Description", "model", "model"),
			("Item Description", "year", "year"),
			("Item", "item_code"),
			("Item", "booking_no"),
			("Item", "container_no"),
			("Purchase Invoice Item", "conversion_factor"),
			("Purchase Invoice Item", "rate"),
			("Purchase Invoice Item", "landed_cost_voucher_amount"),
			("Purchase Invoice", "name"),
			("Item", "shipping_line"),
		),
		"Sold Report":(
			("Sales Invoice", "company"),
			("Item", "eta"),
			("Sales Invoice", "due_date"),
			("Sales Invoice", "posting_date"),
			("Sales Invoice", "customer"),
			("Item Description", "vim_number"),
			("Item Description", "model", "model"),
			("Item Description", "year", "year"),
			("Item", "item_code"),
			("Item", "booking_no"),
			("Item", "container_no"),
			("Sales Invoice Item", "amount"),
			("(SELECT pinv_base_amount from `viewItem Pricing` where item_code = `tabItem`.item_code) as cost"),
			("(SELECT pinv_amount from `viewItem Pricing` where item_code = `tabItem`.item_code) as cost"),
			("(SELECT lcv from `viewItem Pricing` where item_code = `tabItem`.item_code) as lcv"),
			("Sales Invoice Item", "qty"),
			("Sales Invoice", "name"),
			("Item", "shipping_line"),
		)
	}

	fields = fields_obj.get(filters.get("report_type"))

	sql_fields = []

	for args in fields:
		sql_field = get_field(args)

		sql_fields.append(sql_field)

	return ", ".join(sql_fields)

def get_field(args):

	if len(args) == 2:
		doctype, fieldname = args
		alias = fieldname
	elif len(args) == 3:
		doctype, fieldname, alias = args
	else:
		return args if isinstance(args, basestring) \
			else " ".join(args)

	sql_field = "`tab{doctype}`.`{fieldname}` as {alias}" \
		.format(doctype=doctype, fieldname=fieldname, alias=alias)

	return sql_field


import psycopg2
import psycopg2.extras
import pprint as pp
import logging
import pandas

logger = logging.getLogger()

conn = connections['Default Warehouse']['client']
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)

# build command to create a new table
# use CREATE OR REPLACE VIEW name AS in order to avoid conflicts when trying to replace data
# https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_VIEW.html

create_table = '''
create or replace view build_summary_table as (

with a as (
select
cid as primary_key
from schema_a.table_a
limit 100
)
,

b as (
select
client_id as foreign_key,
count(*) as total
from schema_b.table_b
group by 1
order by 2 desc
)
,

c as (
select
a.*,
nvl(b.total,0) as total
from a
left join b
on a.primary_key = b.foreign_key
)

select
total,
count(*)
from c
group by 1

);
'''

# execute command to create a new table

try:
    cur.execute(create_table)
    logger.info('Successfully executed CREATE TABLE AS command')

# make the changes to the database persistent
    conn.commit()
    logger.info('Successfully committed changes to the database')

finally:
    cur.close()
    conn.close()


import json
from repository import models
from utils.page import Pagination
from .base import BaseService
from ..table_config import server as server_conf

class ServerService(BaseService):
    def __init__(self, request):
        super(ServerService, self).__init__(request)
        self.table_config = server_conf.table_config
        self.search_config = server_conf.search_config

    def fetch(self):
        """获取数据列表"""
        current_page = self.request.GET.get('pageNum')
        # 获取需要渲染的字段
        values = self.values()
        # 构造 组合查询的Q条件
        condition = self.condition()
        try:
            total_item_count = models.Server.objects.filter(condition).count()
            page_obj = Pagination(current_page, total_item_count, '/web/server')
            server_list = models.Server.objects.filter(condition).values(*values)[page_obj.start:page_obj.end]
        except Exception as e:
            total_item_count = 0
            page_obj = Pagination(current_page, total_item_count, '/web/server')
            server_list = []

        response = {
            'status': True,
            'data_list': list(server_list),
            'table_config': self.table_config,
            'search_config': self.search_config,
            'global_choices_dict': {
                'status_choices': models.Server.server_status_choices
            },
            'pager_html': page_obj.page_html_js()
        }
        return response

    def delete(self):
        """删除数据"""
        response = {'status':True, 'msg':''}
        id_list = json.loads(self.request.body.decode('utf-8'))
        # models.Server.objects.filter(id__in=id_list).delete()
        for nid in id_list:
            try:
                print('delete: ', nid)
                models.Server.objects.filter(id=nid).delete()
            except Exception as e:
                response['status'] = False
                response['msg'] += 'delete server failed(id=%s)：%s|'%(nid,str(e))
        return response

    def save(self):
        """保存(更新)数据"""
        response = {'status':True, 'msg':''}
        update_items = json.loads(self.request.body.decode('utf-8'))
        for item in update_items:
            nid = item.get('id')
            try:
                print('update: ', item)
                item.pop('id')
                models.Server.objects.filter(id=nid).update(**item)
            except Exception as e:
                response['status'] = False
                response['msg'] += 'update server failed(id=%s)：%s|'%(nid,str(e))
        return response


from django.urls import path
from .views import AddToCart, RemoveFromCart, ListCart, ClearCart

urlpatterns = [
    path('add_to_cart/', AddToCart.as_view(), name='add_to_cart'),
    path('list_cart/', ListCart.as_view(), name='list_cart'),
    path('remove_from_cart/', RemoveFromCart.as_view(), name='remove_from_cart'),
    path('clear_cart/', ClearCart.as_view(), name='clear_cart')
]