def input_without_N(lst):
    x = lst
    v = Validation()
    y = LinkedList()
    first_iter = True
    while x.length() != y.length():
        if not first_iter:
            print("Both length must be equal!")
        print("Input Y(double ENTER to stop): ")
        while True:  # while user will not input "ENTER", he enters a list
            i = input()
            if i == "":
                break
            if not v.positive_check(i):
                print(i, "was skipped because it's not a number!")
            else:
                dot = False
                for z in i:
                    if z == ".":
                        dot = True
                        break
                if dot:
                    y.append(float(i))
                else:
                    y.append(int(i))
        first_iter = False
    result = create_z(
        x, y,
        x.length())  #call a function to create list "z" according to task
    return result
Exemple #2
0
    def __poRequest__(self,user_bean):
        id=valid.Validataion().__inputIdValidataion__(6)
        if int(id)==1:
            menu.InventoryModuleMenu().__poRequestListMenu__()
            id=valid.Validataion().__inputIdValidataion__(4)
            if int(id)==1:
                dao.InventoryDAO().__poRequestList__(1,1)
            elif int(id)==2:
                dao.InventoryDAO().__poRequestList__(1,2)             
            elif int(id)==3:
                dao.InventoryDAO().__poRequestList__(1,3)
            elif int(id)==4:
                InventoryModule().__menuMethod__(5,user_bean)

        elif int(id)==2:
            dao.InventoryDAO().__addPORequest__(user_bean)
        elif int(id)==3:
            dao.InventoryDAO().__poRequestList__(1,1)
            poRequestId=dao.InventoryDAO().__selectUpdatePORequestId__()            
            dao.InventoryDAO().__updatePORequest__(poRequestId,user_bean,1)
        elif int(id)==4:
            if user_bean[1]!=3:
                dao.InventoryDAO().__poRequestList__(1,1)
                poRequestId=dao.InventoryDAO().__selectUpdatePORequestId__()
                dao.InventoryDAO().__updatePORequest__(poRequestId,user_bean,2)
            else:
                print("Error : You can't able to delete.")

        elif int(id)==5:
            print("========")
        elif int(id)==6:
            InventoryModule().initCall(user_bean)
        menu.InventoryModuleMenu().__poMenuList__()
        InventoryModule().__poRequest__(user_bean)
    def validation(self):
        """checks validation is passed and calls a dialog box if it fails"""
        val_passed = True

        if Validation.string_empty(self.save_list()):
            val_passed = False
            return messagebox.showinfo("Booking Failed", "All fields are required to be filled in.", parent=self.master)

        elif dbHelper.date_conflict("weddingTable", self.display_date.get(), self.om_room_val):
            val_passed = False
            return messagebox.showinfo('Booking Failed',
                                       'Room is currently booked.\n'
                                       'Please select another room, or change the date of booking.', parent=self.master)
        elif Validation.min_number([self.EntNumberOfGuest.get()]):
            val_passed = False
            return messagebox.showinfo("Booking Failed", "Must have entered more than one guest.", parent=self.master)
        elif not Validation.contact_number_val(self.EntContactNumber.get(), self.EntContactNumber, self.master):
            val_passed = False
            return

        if val_passed:
            Events.Wedding.create_wedding(
                self.EntNumberOfGuest.get(),
                self.EntNameOfContact.get(),
                self.EntAddress.get(),
                self.EntContactNumber.get(),
                self.om_room_val.get(),
                self.CalDateOfEvent.get(),
                self.om_band_name.get(),
                self.EntBedroomReserved.get())

            DialogBoxes.saved(self.master)
            self.master.destroy()
Exemple #4
0
def main():
    choice = "y"
    while choice.lower() == "y":
        # get input from the user
        monthly_investment = Valid.get_float()
        yearly_interest_rate = Valid.get_float2()
        years = Valid.get_int()

        monthly_interest_rate = yearly_interest_rate / 12 / 100
        months = years * 12

        # calculate future value
        future_value = 0.0
        for i in range(0, months):
            future_value += monthly_investment
            monthly_interest = future_value * monthly_interest_rate
            future_value += monthly_interest

        print("Future value:\t\t\t" + str(round(future_value, 2)))
        print()

        # see if the user wants to continue
        choice = input("Continue? (y/n): ")
        print()

    print("Bye!")
    def __init__(self):

        self.FirstName = input("Enter First Name :")
        self.LastName = input("Enter Last Name :")

        #Validation To Check Enrollment Number Is Valid Or Not...
        while (True):
            self.EnrollmentNumber = input("Enter Enrollment Number :")
            if (not Validation.DataValidationEnroll(self.EnrollmentNumber)):
                print(
                    "<<<<     Please Enter Valid Enrollment Number!...     >>>>"
                )
                continue
            break

        #Validation To Check Email Is Valid Or Not...
        while (True):
            self.Email = input("Enter Email :")
            if (not Validation.DataValidationEmail(self.Email)):
                print("<<<<     Please Enter Valid Email!...     >>>>")
                continue
            break

        self.City = input("Enter City Name:")
        Database.Curcer.execute(
            "Insert into StudentDetail (FirstName,LastName,EnrollmentNumber,Email,City) Values(?,?,?,?,?)",
            (self.FirstName, self.LastName, self.EnrollmentNumber, self.Email,
             self.City))
        Database.Connection.commit()
        print("Your Data Inserted Successfully")
Exemple #6
0
    def do_PUT(self):
        try:
            if 'Content-Type: application/json' not in str(self.headers):
                self.send_error(415, Strings.message_415,
                                Strings.message_explanation_415)

            if self.path == "/users":
                content_length = int(
                    content_length_regex.search(str(self.headers))[1])
                users = self.rfile.read(content_length).decode()

                validation = Validation.validate_json_users(users)

                if validation == "Invalid data":
                    self.send_error(422, Strings.message_422,
                                    Strings.message_explanation_422)
                elif validation == "Invalid JSON":
                    self.send_error(400, Strings.message_400,
                                    Strings.message_explanation_400)
                else:
                    database_response = Database.insert_users_overwrite(
                        json.loads(users))

                    if database_response is True:
                        self.send_error(204)
                    else:
                        self.send_error(409, Strings.message_409,
                                        Strings.message_explanation_409)

            elif self.path == "/tracks":
                content_length = int(
                    content_length_regex.search(str(self.headers))[1])
                tracks = self.rfile.read(content_length).decode()

                validation = Validation.validate_json_tracks(tracks)

                if validation == "Invalid data":
                    self.send_error(422, Strings.message_422,
                                    Strings.message_explanation_422)
                elif validation == "Invalid JSON":
                    self.send_error(400, Strings.message_400,
                                    Strings.message_explanation_400)
                else:
                    database_response = Database.insert_tracks_overwrite(
                        json.loads(tracks))

                    if database_response is True:
                        self.send_error(204)
                    else:
                        self.send_error(409, Strings.message_409,
                                        Strings.message_explanation_409)
            else:
                self.send_error(404, Strings.message_404,
                                Strings.message_explanation_404)

            return
        except:
            self.send_error(500, Strings.message_500,
                            Strings.message_explanation_500)
    def __init__(self, master, booking, view_booking_self):
        super().__init__(master, booking)

        # Creation of wedding form set title, size ect..
        master.title("Hotel Booking System - Update Selected Conference")
        master.resizable(0, 0)
        master.config(background="#70ABAF")

        self.view_booking_self = view_booking_self
        self.booking = booking

        # defines options for drop down boxes

        # Labels for Conference booking form
        self.lblSubheading.config(text="Please update any details that you want to change")

        self.lblCompanyName = Label(master, text="Company Name", font=("arial", 10, "bold"), bg="#70ABAF")
        self.lblCompanyName.grid(row=7, columnspan=2, pady=(25, 0), padx=(10, 10))

        self.lblNoOfDays = Label(master, text="Number of Days", font=("arial", 10, "bold"), bg="#70ABAF")
        self.lblNoOfDays.grid(row=8, columnspan=2, pady=(25, 0), padx=(10, 10))

        self.lblProjectorReq = Label(master, text="Projector Required", font=("arial", 10, "bold"), bg="#70ABAF")
        self.lblProjectorReq.grid(row=9, columnspan=2, pady=(25, 0), padx=(10, 10))

        # Entry boxes, drop downs and date picker for conference form
        self.EntCompanyName = Entry(master, font=("arial", 10), width=50)
        self.CompanyName_VCMD = (self.EntCompanyName.register(lambda p: Validation.max_character_length_150(p, master)))
        self.EntCompanyName.config(validate='key', validatecommand=(self.CompanyName_VCMD, '%P'))

        self.number_of_days = StringVar()
        self.EntNoOfDays = Entry(master, font=("arial", 10), width=50, textvariable=self.number_of_days)
        self.Days_VCMD = (self.EntNoOfDays.register(lambda p: Validation.max_size_31(p, master)))
        self.EntNoOfDays.config(validate='key', validatecommand=(self.Days_VCMD, '%P'))

        # checkbox
        self.CheckVar1 = IntVar()
        self.chxProjectorRequired = Checkbutton(master, text='', variable=self.CheckVar1, onvalue=True, offvalue=False,
                                                bg="#70ABAF")

        # Entry boxes, drop downs and date picker for conference form being placed using a grid layout
        self.EntCompanyName.grid(row=7, column=2, columnspan=2, pady=(25, 0), padx=(0, 25))
        self.EntNoOfDays.grid(row=8, column=2, columnspan=2, pady=(25, 0), padx=(0, 25))

        # checkbox
        self.chxProjectorRequired.grid(row=9, column=2, pady=(25, 0), padx=(0, 25))

        # Buttons for Add and Cancel on the conference form
        self.btnUpdateBooking.config(command=lambda: self.validation(booking))  # calls update ,destroy and message box

        self.populate_form_conference(self.booking)

        self.display_date.trace('w', lambda name, index, mode: self.conference_room_check())
        self.number_of_days.trace('w', lambda name, index, mode: self.conference_room_check())
Exemple #8
0
 def __menuMethod__(self,id,user_bean): 
     if int(id)==1:    
         menu.InventoryModuleMenu().__itemListMenu__()
         id=valid.Validataion().__inputIdValidataion__(2)             
         if int(id)==1:
             dao.InventoryDAO().__allItemList__(1)
         else:
             dao.InventoryDAO().__isCount0ItemList__()
     elif int(id)==2:
         print("---------------------- New Item  ---------------------")
         dao.InventoryDAO().__addItem__(user_bean)
     elif int(id)==3:
         print("---------------------- Update Item -------------------")
         dao.InventoryDAO().__allItemList__(2)
         item_id=dao.InventoryDAO().__selectUpdateItemId__()
         dao.InventoryDAO().__updateItem__(item_id,user_bean,1)
     elif int(id)==4:
         if user_bean[1]!=3:
             print("----------------------- Delete Item -------------------")
             dao.InventoryDAO().__allItemList__(1)
             #we don't detete the itme. we just update the item_status =0 
             item_id=dao.InventoryDAO().__selectUpdateItemId__()
             dao.InventoryDAO().__updateItem__(item_id,user_bean,2)
         else:
             print("Error : You can't able to delete.")
     elif int(id)==5:
         print("-----------------------PO Request ---------------------------------")
         menu.InventoryModuleMenu().__poMenuList__()
         InventoryModule().__poRequest__(user_bean)
     elif int(id)==6:
         print("---------------------- Main Menu ----------------------------------")
         login.Login().initialCall(self.user)        
     
     self.initCall(self.user)
Exemple #9
0
def login():

    print("Login to your account")

    accountNumberfromuser = int(input("What is your account number? \n" ))

    is_valid_account_number = Validation.account_number_validation(accountNumberfromuser)

    if user:
        bankOperation(user)

    print('Invalid account or password')

    if is_valid_account_number:

        password = input("What is your password? \n")
        password = getpass("What is your password? \n")

        user = HoggardDatabase.allowedUsernames(accountNumberfromuser, password)

        #for accountnumber, userDetails in database.items():
                #if(accountnumber == accountNumberfromuser):
                    #if(userDetails[3] == password):
                        #bankOperation(user)

        print('Invalid account or Password')
        login()
    else:
        print("Account number invalid")
        init()
def optimise(model_config, experiment_id, dataset):
    epoch = 0
    best_loss = 10000
    model_path = None
    best_model_path = None
    for i in range(2):
        worse_epochs = 0
        if i==1:
            print("Finished first round of training, now entering fine-tuning stage")
            model_config["batch_size"] *= 2
            model_config["cache_size"] *= 2
            model_config["min_replacement_rate"] *= 2
            model_config["init_sup_sep_lr"] = 1e-5
        while worse_epochs < model_config["worse_epochs"]: # Early stopping on validation set after a few epochs
            print("EPOCH: " + str(epoch))
            model_path = train(sup_dataset=dataset["train"], load_model=model_path)
            curr_loss = Validation.test(model_config, model_folder=str(experiment_id), audio_list=dataset["valid"], load_model=model_path)
            epoch += 1
            if curr_loss < best_loss:
                worse_epochs = 0
                print("Performance on validation set improved from " + str(best_loss) + " to " + str(curr_loss))
                best_model_path = model_path
                best_loss = curr_loss
            else:
                worse_epochs += 1
                print("Performance on validation set worsened to " + str(curr_loss))
    print("TRAINING FINISHED - TESTING NOW AVAILABLE WITH BEST MODEL " + best_model_path)
Exemple #11
0
def update_books(isbn):
    if isbn is False:
        error_help = {
            "error": "ISBN is missing",
            "help": "Check the ISBN which is passed"
        }
        response = Response(json.dumps(error_help),
                            status=415,
                            mimetype='application/json')
        return response
    else:
        data = request.get_json()
        result = Validation.validate_update_model(data)
        if result is True:
            datahandler.update_data_using_isbn(isbn, data)
            response = Response(json.dumps("Added"),
                                201,
                                mimetype='application/json')
            response.headers['Location'] = f'/books/' + str(isbn)
            return response
        else:
            error_help = {
                "error": "Invalid data passed",
                "help": "Check the model which is passed"
            }
            response = Response(json.dumps(error_help),
                                status=415,
                                mimetype='application/json')
            return response
Exemple #12
0
def add_book():
    data = request.get_json()
    result = Validation.validate_model(data)
    if result is True:
        duplicate = datahandler.validate_isbn_exist(data["Isbn"])
        if duplicate is False:
            datahandler.insert_data(data)
            response = Response(json.dumps("Added"),
                                201,
                                mimetype='application/json')
            response.headers['Location'] = f'/books/' + str(data['Isbn'])
            return response
        else:
            error_help = {
                "error": "Invalid data passed",
                "help": "ISBN already exist"
            }
        response = Response(json.dumps(error_help),
                            status=415,
                            mimetype='application/json')
        return response
    else:
        error_help = {
            "error": "Invalid data passed",
            "help": "Check the model which is passed"
        }
        response = Response(json.dumps(error_help),
                            status=415,
                            mimetype='application/json')
        return response
Exemple #13
0
def login():
    print("********* Login ********** ")

    accountNumberFromUser = (input("Enter your account number: \n"))

    is_valid_account_number = Validation.accountNumberValidation(
        accountNumberFromUser)

    if is_valid_account_number:

        #password = (input("Enter your password \n"))
        password = getpass("Enter your password \n")

        user = database.authenticated_user(accountNumberFromUser, password)

        if user:
            bankOperation(user)

        # for accountNumber,userDetails in database.read(accountNumberFromUser):
        #    if(accountNumber == int(accountNumberFromUser)):
        #       if(userDetails[3] == password):

        print('Invalid account or password')
        login()

    else:
        print(
            "Account Number Invalid: Check that you have up to 10 digits and only integer"
        )
        init()
Exemple #14
0
def insert_matrix():
    str_range = input('Please insert the range of a square matrix: ')
    Validation.is_valid_range(str_range)
    while not Validation.is_valid_range(str_range):
        str_range = input('Please insert a valid positive number, higher than 1: ')
    mat_range = int(str_range)
    matrix = []
    for i in range(mat_range):
        string_row = input('Insert row ' + str(i + 1) + ', with ' + str(mat_range) + ' numbers separated by comma: ')
        float_row = get_row(string_row, mat_range)
        while float_row is None:
            string_row = input('Insert row ' + str(i + 1) + ', with ' + str(mat_range) +
                               ' valid numbers separated by comma: ')
            float_row = get_row(string_row, mat_range)
        matrix.append(float_row)
    return matrix
    def validation(self):
        """checks validation is passed and calls a dialog box if it fails"""
        val_passed = True

        if Validation.string_empty(self.save_list()):
            val_passed = False
            return messagebox.showinfo(
                "Booking Failed",
                "All fields are required to be filled in.",
                parent=self.master)

        elif dbHelper.con_date_conflict("conferenceTable",
                                        self.display_date.get(),
                                        self.EntNoOfDays.get(),
                                        self.om_room_val.get()):
            val_passed = False
            return messagebox.showinfo(
                'Booking Failed', 'Room is currently booked.\n'
                'Please select another room, or change the date of booking.',
                parent=self.master)
        elif Validation.min_number(
            [self.EntNumberOfGuest.get(),
             self.EntNoOfDays.get()]):
            val_passed = False
            return messagebox.showinfo(
                "Booking Failed", "Must have more than one guest.\n"
                "The duration of the event must be at least one day.",
                parent=self.master)
        elif not Validation.contact_number_val(self.EntContactNumber.get(),
                                               self.EntContactNumber,
                                               self.master):
            val_passed = False
            return

        if val_passed:
            Events.Conference.create_conference(self.EntNumberOfGuest.get(),
                                                self.EntNameOfContact.get(),
                                                self.EntAddress.get(),
                                                self.EntContactNumber.get(),
                                                self.om_room_val.get(),
                                                self.display_date.get(),
                                                self.EntCompanyName.get(),
                                                self.EntNoOfDays.get(),
                                                self.CheckVar1.get())

            DialogBoxes.saved(self.master)
            self.master.destroy()
Exemple #16
0
 def initCall(self, user):
     user_bean=[]
     self.user=user
     user_bean.insert(0,user['user_id'][0])
     user_bean.insert(1,user['role_id'][0])
     menu.InventoryModuleMenu().__mainMuen__() 
     id=valid.Validataion().__inputIdValidataion__(6)               
     self.__menuMethod__(id,user_bean)
Exemple #17
0
 def init(self):
     self.__linkDict = dict()
     self.__sentenceDict = dict()
     self.__keywordDict = dict()
     self.__distanceDict = dict()
     self.__validation = Validation.Validation()
     self.__validation.init_dic()
     self.__validation.init_base_normalized()
     self.__sentenceTokenizer = TextRank.SentenceTokenizer()
Exemple #18
0
def create_analyze_calculate_error_dbscan(fromDate, toDate, a, b, c, x, y, n):
    analyze_with_different_dbscan_params(a, b, c, x, y, n)
    rides_over_time_dbscan(fromDate, toDate, a, b, c, x, y)
    v.calculate_mse_for_all_dbscan(a, b, c, x, y, fromDate, toDate)

    errors = ['R2', 'MSE', 'MAE']
    attrTypes = ['ENTRIES', 'EXITS']

    for e in errors:
        for a in attrTypes:
            v.graph_errors(startEPS=a,
                           stopEPS=b,
                           stepEPS=c,
                           startSample=x,
                           stopSample=y,
                           fromDate=fromDate,
                           toDate=toDate,
                           whatToGraph='{} {}'.format(e, a))
Exemple #19
0
    def get(self, phone, email):

        # strip strings and convert to lower-case
        phone = phone.strip()
        email = email.strip().lower()

        # check phone
        isPhoneValid = Validation.validatePhone(phone)
        if isPhoneValid == 'True':

            # check email
            isEmailValid = Validation.validateEmail(email)
            if isEmailValid == 'True':
                isSent = DatabaseHandling.sendEmailVerification(phone, email)
                return toJson(isSent)
            else:
                return toJson(isEmailValid)
        else:
            return toJson(isPhoneValid)
Exemple #20
0
    def get(self, userName, address, city, pinCode, phone, email, password,
            confirmPassword):
        print('received user info')

        # strip strings and convert to lower-case
        userName = userName.strip().lower()
        address = address.strip().lower()
        city = city.strip().lower()
        pinCode = pinCode.strip()
        phone = phone.strip()
        email = email.strip().lower()

        # match passwords
        isPasswordMatched = Validation.matchPasswords(password,
                                                      confirmPassword)
        if isPasswordMatched != 'True':
            return toJson(isPasswordMatched)

        if userName == '' or address == '' or city == '' or pinCode == '' or phone == '' or email == '' or password == '':
            return toJson('field(s) found empty')

        # check pin
        isPinValid = Validation.validatePinCode(pinCode)
        if isPinValid == 'True':

            # check phone
            isPhoneValid = Validation.validatePhone(phone)
            if isPhoneValid == 'True':

                # check email
                isEmailValid = Validation.validateEmail(email)
                if isEmailValid == 'True':
                    isInserted = DatabaseHandling.insertUserDataIntoDB(
                        userName, address, city, pinCode, phone, email,
                        password)
                    return toJson(isInserted)
                else:
                    return toJson(isEmailValid)
            else:
                return toJson(isPhoneValid)
        else:
            return toJson(isPinValid)
Exemple #21
0
    def post(self, of, email, otp, password, confirmPassword):
        # strip strings and convert to lower-case
        of = of.strip().lower()
        email = email.strip().lower()
        otp = otp.strip()

        # match passwords
        isPasswordMatched = Validation.matchPasswords(password,
                                                      confirmPassword)
        if isPasswordMatched != 'True':
            return toJson(isPasswordMatched)

        # check email
        isEmailValid = Validation.validateEmail(email)
        if isEmailValid == 'True':
            isPasswordChanged = DatabaseHandling.changePassword(
                of, otp, email, password)
            return toJson(isPasswordChanged)
        else:
            return toJson(isEmailValid)
Exemple #22
0
    def post(self, of, email):
        # strip strings and convert to lower-case
        of = of.strip().lower()
        email = email.strip().lower()

        # check email
        isEmailValid = Validation.validateEmail(email)
        if isEmailValid == 'True':
            isDeleted = DatabaseHandling.deleteAccount(of, email)
            return toJson(isDeleted)
        else:
            return toJson(isEmailValid)
Exemple #23
0
    def get(self, of, phone, email):
        # strip strings and convert to lower-case
        of = of.strip().lower()
        phone = phone.strip()
        email = email.strip().lower()

        # check phone
        isPhoneValid = Validation.validatePhone(phone)
        if isPhoneValid == 'True':

            # check email
            isEmailValid = Validation.validateEmail(email)
            if isEmailValid == 'True':
                isSent = DatabaseHandling.findAccount(of, phone, email)

                # OTP sent. Display message: OTP has been sent. If not received then press findAccount button again
                DatabaseHandling.sendEmailVerification(phone, email)
                return toJson(isSent)
            else:
                return toJson(isEmailValid)
        else:
            return toJson(isPhoneValid)
Exemple #24
0
    def get(self, of, email, otp):
        # strip strings and convert to lower-case
        of = of.strip().lower()
        email = email.strip().lower()
        otp = otp.strip()

        # check email
        isEmailValid = Validation.validateEmail(email)
        if isEmailValid == 'True':
            isVerified = DatabaseHandling.verifyOTP(of, email, otp)
            return toJson(isVerified)
        else:
            return toJson(isEmailValid)
 def __addItem__(self,user_bean):        
     try:
         item= vaild.Validataion().__addItemValidation__()   
         insert_query = 'insert into inv_item(item_name,item_description,item_status,created_by,created_on) values("'+str(item[0])+'","'+str(item[1])+'",2,"'+str(user_bean[0])+'",now())'             
         cursor = connection.cursor()
         result  = cursor.execute(insert_query)
         connection.commit()
         print ("\nRecord inserted successfully into inventory table")
     except Exception as error :
         print("Failed inserting record into inventory table ",error)
         connection.rollback() #rollback if any exception occured    
     finally:
         #closing database connection.
         if(connection.is_connected()):
             cursor.close()
Exemple #26
0
    def post(self, userName, address, city, pinCode, phone, email):
        # strip strings and convert to lower-case
        userName = userName.strip().lower()
        address = address.strip().lower()
        city = city.strip().lower()
        pinCode = pinCode.strip().lower()
        phone = phone.strip().lower()

        # check pinCode
        isPinValid = Validation.validatePinCode(pinCode)
        if isPinValid == 'True':

            # check phone
            isPhoneValid = Validation.validatePhone(phone)
            if isPhoneValid == 'True':

                # now, update data to the database
                isUpdated = DatabaseHandling.updateUserInfo(
                    userName, address, city, pinCode, phone, email)
                return toJson(isUpdated)
            else:
                return toJson(isPhoneValid)
        else:
            return toJson(isPinValid)
Exemple #27
0
    def get(self, loginAs, email, password):

        # strip strings and convert to lower-case
        email = email.strip().lower()

        # check email
        isEmailValid = Validation.validateEmail(email)
        if isEmailValid == 'True':
            isCorrect = DatabaseHandling.login(loginAs, email, password)
            if isCorrect == True:
                print('You are logged in ')
                return toJson(True)
            else:
                return toJson('Check validity, password, email and try again')
        else:
            return toJson(isEmailValid)
    def run(self, excelPathInputValue, errbox):
        try:

            targetExcel = load_workbook(excelPathInputValue,
                                        data_only=True)  # 엑셀 연다.

            bioProjectSheetName = ''
            bioSampleSheetName = []
            sampleTypeSheetName = []
            experimentSheetName = []

            sheets = targetExcel.sheetnames
            #시트 이름들을 가져와서 포함되는 단어에 따라서 각각의 배열에 추가
            for sheet in sheets:
                if 'BioProject' in str(sheet):
                    bioProjectSheetName += str(sheet)
                elif 'BioSample' in str(sheet):
                    bioSampleSheetName.append(str(sheet))
                elif 'Sample type' in str(sheet):
                    sampleTypeSheetName.append(str(sheet))
                elif 'Experiment' in str(sheet):
                    experimentSheetName.append(str(sheet))

            #biosample,sampletype,experiment 쌍의 개수만큼 반복한다.
            rotation = len(bioSampleSheetName)

            bioProject = targetExcel[bioProjectSheetName]
            Validation.bioProject_Validation(
                bioProject, bioProjectSheetName,
                errbox)  #BioProject는 1개뿐이므로 그냥 validation 실행

            #나머지 시트들은 존재하는 개수만큼 실행한다.
            #bioSample_SampleName = []

            i = 0
            while i < rotation:
                bioSample = targetExcel[bioSampleSheetName[i]]
                sampleType = targetExcel[sampleTypeSheetName[i]]
                experiment = targetExcel[experimentSheetName[i]]

                Validation.bioSample_Validation(bioSample, sampleType,
                                                bioSampleSheetName[i], errbox)
                bioSample_SampleName = Validation.sampleType_Validation(
                    sampleType, sampleTypeSheetName[i], errbox)
                Validation.Experiment_Validation(experiment,
                                                 experimentSheetName[i],
                                                 errbox, bioSample_SampleName)
                i += 1

        except IOError as err:
            errbox.insertPlainText("IO Error : " + str(err))
Exemple #29
0
def registration():
    request_model = request.get_json()
    result = Validation.validate_registraton_model(request_model)
    if result:
        status = auth_check.registration_check(request_model)
        if status is True:
            return Response(
                json.dumps('User already exist try another username'),
                status=403,
                mimetype='application/json')
        else:
            user_status = auth_check.add_user(request_model)
            return Response(json.dumps(user_status),
                            status=201,
                            mimetype='application/json')
    else:
        return Response(json.dumps('Request model is wrong'),
                        status=403,
                        mimetype='application/json')
    def UpdateStudentDetails(Enrollment):
        print("Enter Details where you have to Update it.")
        FirstName = input("Enter First Name :")
        LastName = input("Enter Last Name :")

        #Validation To Check Email Is Valid Or Not...
        while (True):
            Email = input("Enter Email :")
            if (not Validation.DataValidationEmail(Email)):
                print("<<<<     Please Enter Valid Email!...     >>>>")
                continue
            break

        City = input("Enter City Name:")
        Database.Curcer.execute(
            "update StudentDetail set FirstName=?,LastName=?,Email=?,City=? where EnrollmentNumber=?",
            (FirstName, LastName, Email, City, Enrollment))
        Database.Connection.commit()
        print("Your Data Updated Successfully")
def login():

    print("Login to your account")

    accountNumberfromuser = int(input("What is your account number? \n" ))

    is_valid_account_number = Validation.account_number_validation(accountNumberfromuser)

    if is_valid_account_number:

        password = input("What is your password? \n")

        for accountnumber, userDetails in database.items():
                if(accountnumber == accountNumberfromuser):
                    if(userDetails[3] == password):
                        bankOperation(user)

    print('Invalid account or Password')
    login()
Exemple #32
0
def get_row(row, range):
    numbers = row.replace(' ', '').split(',')
    length = len(numbers)
    float_row = []
    valid = True
    i = 0
    if length == range:
        while i < length and valid:
            num = numbers[i]
            float_num = Validation.is_number(num)
            if float_num is not None:
                float_row.append(float_num)
            else:
                valid = False
            i += 1
        if valid:
            return float_row
        else:
            return None
    else:
        return None
 def testDiscontinueTRoute002b(self):
     event = {"Origin": 5,"Destination": 6, "Priority": 3, "Company": "Air Balloon Rides", "TransportType": "Sea"}
     errorMessages = Validation.validate(event)
     assert(len(errorMessages) == 1),errorMessages
 def testUpdateCustomerPrice001(self):
     event = {"Origin": 4,"Destination": 9, "Priority": 1,"PricePerGram": 10.50,"PricePerCC": 12.60}
     errorMessages = Validation.validate(event)
     assert(len(errorMessages) == 0),errorMessages          
    def testUpdateCustomerPrice002a(self):
        event = {"Origin": 'z',"Destination": 'a', "Priority": "a","PricePerGram": "abc","PricePerCC": "def"}

        errorMessages = Validation.validate(event)
        assert(len(errorMessages) == 5), errorMessages   
Exemple #36
0
 def testAddMail001(self):
     event = {"Origin": 3,"Destination": 2, "Weight": 1.00,"Volume": 2.00,"Priority": 2}
     errorMessages = Validation.validate(event)
     assert(len(errorMessages) == 0),errorMessages          
Exemple #37
0
 def testAddMail002a(self):
     event = {"Origin": 'za',"Destination": 'az', "Weight": "_ab_","Volume": "1a2b3c","Priority": 'x'}
     errorMessages = Validation.validate(event)
     assert(len(errorMessages) == 5), errorMessages   
maxVal = max(target)
# we still need to implement validation so 0% is used for validation
# 70% of the data is used for training and 30% for testing here
segmented_input = parser.segmentation(data, 0.8, 0.0, 0.2)
segmented_target = parser.segmentation(target, 0.8, 0.0, 0.2)
train_input = segmented_input[0]
train_target = segmented_target[0]

train_size = len(train_input)

train_input = np.array(train_input)
train_target = np.array(train_target)
train_target = train_target.reshape(train_size, 1)

## Find Optimal NN setup ##
validation.k_folds(3, train_input, train_target, feature_value_range, minVal, maxVal)


# test_input = segmented_input[2]
# test_target = segmented_target[2]

# train_size = len(train_input)
# test_size = len(test_input)
# # we need to convert the format of the data to be
# # compliant with the neurolab API, print out the
# # values of inp and tar to see format
# train_input = np.array(train_input)
# train_target = np.array(train_target)
# train_target = train_target.reshape(train_size, 1)

# # Create network with 3 layers with 5, 5, and 1 neruon(s) in each layer 
 def testDiscontinueTRoute001(self):
     event = {"Origin": 10,"Destination": 5, "Priority": 2, "Company": "Patrick Mumford Railways", "TransportType": "Air"}
     errorMessages = Validation.validate(event)
     assert(len(errorMessages) == 0),errorMessages     
    def testTransportCostUpdate002a(self):
        event = {"Origin":"abc","Destination": "def", "Priority": "ghi","PricePerGram": "jkl","PricePerCC": "mno", "Company": 7,
                 "TransportType": 1,"DayOfWeek": "pqr", "Frequency": "stu","Duration": "vwx"}

        errorMessages = Validation.validate(event)
        assert(len(errorMessages) == 10), errorMessages   
    def testTransportCostUpdate002c(self):
        event = {"Origin": 5,"Destination": 5, "Priority": 2,"PricePerGram": 5,"PricePerCC": 4, "Company": "Nick McNeil Airways",
                 "TransportType": "Air","DayOfWeek": 6, "Frequency": 54,"Duration": 3}

        errorMessages = Validation.validate(event)
        assert(len(errorMessages) == 1), errorMessages  
 def testDiscontinueTRoute002a(self):
     event = {"Origin": 9,"Destination": 9, "Priority": "Team A", "Company": 7, "TransportType": 'z'}
     errorMessages = Validation.validate(event)
     assert(len(errorMessages) == 4),errorMessages    
    def testUpdateCustomerPrice002c(self):
        event = {"Origin": 10,"Destination": 10, "Priority": 1,"PricePerGram": 6.25,"PricePerCC": 4.23}

        errorMessages = Validation.validate(event)
        assert(len(errorMessages) == 1), errorMessages  
def insertTransportCost(cUD): # Cost Update Data
    errorMessages = Validation.validate(cUD)
    if len(errorMessages) > 0:
        return errorMessages
    RH.updateTransportRoute(cUD)
    return errorMessages  
def updateCustomerPrice(pUD):
    errorMessages = Validation.validate(pUD)
    if len(errorMessages) > 0:
        return errorMessages
    RH.updateCustomerRoute(pUD)
    return errorMessages  
 def testUpdateCustomerPrice002c(self):
     event = {"Origin": 45,"Destination": 45, "Priority": 1, "Company": "Submarine Services", "TransportType": "Land"}
     errorMessages = Validation.validate(event)
     assert(len(errorMessages) == 1), errorMessages
def discontinueTransport(dtT):
    errorMessages = Validation.validate(dtT)   
    if len(errorMessages) > 0:
        return errorMessages
    RH.discontinueRoute(dtT)
    return errorMessages    
 def testUpdateCustomerPrice002b(self):
     event = {"Origin": 12,"Destination": 56, "Priority": 0,"PricePerGram": -2.50,"PricePerCC": -1.00}
     
     errorMessages = Validation.validate(event)
     assert(len(errorMessages) == 3), errorMessages