Пример #1
0
 def submenu_empty(self):
     """
     Truncate the selected table if possible
     :return:
     """
     # need the table to truncate
     table = self.cleaneddata[self.grid.edit_cell[0]][
         self.grid.edit_cell[1]]
     # determine if user wants to cascade or not
     cascadeval = npyscreen.notify_yes_no(
         'Would you like to cascade to tables having foreign-key references?',
         editw=1)
     if cascadeval:
         SQL = 'truncate \"{0}\" CASCADE;'.format(table)
     else:
         SQL = 'truncate \"{0}\";'.format(table)
     retval = npyscreen.notify_yes_no(
         'Are you sure you wish to empty this table?', editw=1)
     if retval:
         value = ()
         try:
             conn = Connection.Instance().getconnection()
             cursor = conn.cursor()
             cursor.execute(SQL, value)
             npyscreen.notify_confirm('Table {0} emptied'.format(table),
                                      editw=1)
         except Exception as e:
             npyscreen.notify_confirm(e.message)
Пример #2
0
 def submenu_drop(self):
     """
     Drop the selected table
     :return:
     """
     # need the table to drop
     table = self.cleaneddata[self.grid.edit_cell[0]][
         self.grid.edit_cell[1]]
     # determine if user wants to cascade or not
     cascadeval = npyscreen.notify_yes_no(
         'Would you like to cascade to tables having foreign-key references?',
         editw=1)
     if cascadeval:
         SQL = 'drop table \"{0}\" CASCADE;'.format(table)
     else:
         SQL = 'drop table \"{0}\";'.format(table)
     retval = npyscreen.notify_yes_no(
         'Are you sure you wish to drop this table?', editw=1)
     if retval:
         value = ()
         try:
             conn = Connection.Instance().getconnection()
             cursor = conn.cursor()
             cursor.execute(SQL, value)
             npyscreen.notify_confirm('Table {0} dropped'.format(table),
                                      editw=1)
         except Error as e:
             npyscreen.notify_confirm(e.message, editw=1)
         try:
             self.cell = [0, 0]
             self.updateresults()
         except Exception as e:
             self.submenucmd = None
             self.parentApp.setNextForm('MAIN')
             raise
Пример #3
0
 def while_editing(self,arg):
     if arg is self.Selection:
         if len(arg.value) == 0:
             self.messageBox.values = ["please select at least one",
                                       arg.value,
                                       len(arg.value)]
         else:
             self.messageBox.values = [repr(arg.value),
                                       arg.value,
                                       len(arg.value)]
         self.messageBox.display()
         npyscreen.notify_yes_no('Has this worked', editw=1)
Пример #4
0
 def while_editing(self, arg):
     if arg is self.Selection:
         if len(arg.value) == 0:
             self.messageBox.values = [
                 "please select at least one", arg.value,
                 len(arg.value)
             ]
         else:
             self.messageBox.values = [
                 repr(arg.value), arg.value,
                 len(arg.value)
             ]
         self.messageBox.display()
         npyscreen.notify_yes_no('Has this worked', editw=1)
Пример #5
0
	def on_ok(self):
		exiting = npyscreen.notify_yes_no("Are you sure you want to quit?","Cancel?", editw=1)
		if exiting:
			npyscreen.notify_confirm("Goodbye!", editw=1)
			self.parentApp.setNextForm(None)
		else:
			npyscreen.notify_confirm("Please enter login information.", "Back to it!", editw=1)
Пример #6
0
	def exit_form(self):
		exiting = npyscreen.notify_yes_no("Are you sure you want to quit?","Quit?", editw=1)
		if exiting:
			npyscreen.notify_confirm("Goodbye!", editw=1)
			exit()
		else:
			pass
Пример #7
0
 def del_entry(self):
     delete = npyscreen.notify_yes_no("Are you sure you want to delete this entry?",
                                      "Delete?", editw=1)
     if delete:
         db.remove(self.value)
         npyscreen.notify_confirm("Entry was deleted successfully!", editw=1)
         self.parentApp.switchForm("LISTENTRIES")
Пример #8
0
    def whenPressed(self):
        delete = npyscreen.notify_yes_no(
            'Are you sure you want to delete message?', title='Delete message')

        if delete:
            Service.delete(Store.current_message)
            self.parent.parentApp.switchForm('INBOX')
Пример #9
0
 def on_ok(self):
     """Ask a confirmation for exiting"""
     exiting = nps.notify_yes_no(words['ConfirmExit'], words['ExitText'], editw = 2)
     if (exiting):
         self.exit_application()
     else:
         pass #~ Do nothing
Пример #10
0
 def on_cancel(self):
     """Return to the main screen when the button cancel is pressed"""
     exiting = nps.notify_yes_no(words['ConfirmUserExit'], words['ExitText'], editw = 2)
     if (exiting):
         self.return_to_main_screen()
     else:
         pass #~ Do nothing
    def on_ok(self):
        if self.profile_name.value:
            if self.profile_name.value in sv.list_of_profile_names and not npyscreen.notify_yes_no(
                    f"Profile {self.profile_name.value} already exists, would you like to override?",
                    title="Already Exists",
                    editw=1):
                return

            if self.profile_password.hidden:
                self.create_profile(self.profile_name.value, force=True)

            elif not self.profile_password.value:
                npyscreen.notify_confirm("Please provide password",
                                         wide=True,
                                         editw=1)
                return
            else:
                self.create_profile(self.profile_name.value,
                                    password=self.profile_password.value,
                                    force=True)
                npyscreen.notify_confirm("Profile Saved successfully!",
                                         wide=True,
                                         editw=1)

            sv.load_profiles()
            sv.CHANGES_PENDING = False
            self.parentApp.switchFormPrevious()
        else:
            npyscreen.notify_confirm("Please specify profile name",
                                     wide=True,
                                     editw=1)
Пример #12
0
 def when_finish(self, *args, **kwargs):
     if npyscreen.notify_yes_no(
             "Are you sure you want to finish task '{}'".format(
                 self.value)):
         self.parentApp.taskGraph.update_task_stat(self.value, 'finished',
                                                   self.dt.value)
         self.parentApp.switchFormPrevious()
Пример #13
0
 def exit_program(self):
     exit = npyscreen.notify_yes_no("Do you want to exit the program?", "Exit?", editw=1)
     if exit:
         npyscreen.notify_wait("Ok,\n Bye then :(")
         self.parentApp.switchForm(None)
     else:
         self.parentApp.switchForm("MAIN")
Пример #14
0
	def confirm_delete(self):
		# http://npyscreen.readthedocs.org/messages.html?highlight=yes_no#selectFile
		isDelete = npyscreen.notify_yes_no("Confirm to delete the row?", title="Confirm Deletion", form_color='STANDOUT', wrap=True, editw = 0)
		if isDelete:
			# dict for where clause of SQL statement (contains primary key:value pairs)
			where_dict = {} 
			row_num = self.myGrid.edit_cell[0]
			for col, col_value in zip(self.parentApp.myGridSet.columns_list, self.myGrid.values[row_num]):
				if  col.primary_key:
					where_dict[col.name] = col_value
			# delete row
			if self.parentApp.myGridSet.db_type == 'PostgreSQL':
				del_row_data, isSuccess = self.parentApp.postgreDb.delete_record(self.parentApp.myGridSet.table, where_dict)
			else:
				del_row_data, isSuccess = self.parentApp.mySQLDb.delete_record(self.parentApp.myGridSet.table, where_dict)
			# give feedback
			if isSuccess:
				del_data_dict = {}
				for col, col_value in zip(self.parentApp.myGridSet.columns_list, del_row_data):
					del_data_dict[col.name] = col_value
				self.feedback.value  = "Deleted succesfully. " + str(del_data_dict).strip("{}'\0")
				self.feedback.color = 'SAFE'
				# update myGrid and screen
				self.update_grid()
			else:
				self.feedback.value  = str(del_row_data)
				self.feedback.color = 'ERROR'
			# make feedback visible
			self.feedback.hidden = False
			self.display()
			# set times to hide the feedback
			self.timer = Timer(FEEDBACK_TIMEOUT, self.hideFeedback)
			self.timer.start()
Пример #15
0
 def quit(self, command_line, widget_proxy, live):
     if self.parent.pending_edits:
         msg = 'You have edits pending on this encounter, do you want to exit without saving?'
         exit_anyway = npyscreen.notify_yes_no(msg, title="Pending Edits")
         if not exit_anyway:
             return
     self.parent.parentApp.switchFormPrevious()
Пример #16
0
 def on_cancel(self):
     exit = npyscreen.notify_yes_no("Are you sure you want to cancel")
     if exit:
         npyscreen.notify_confirm("Thank you for using PyMp3. GoodBye!", "Cancel!")
         self.parentApp.setNextForm(None)
     else:
         npyscreen.notify_confirm("You may continue listening", "Okay")
Пример #17
0
 def endOrContinue(self):
     option = npyscreen.notify_yes_no("Czy zakonczyc prace?", "Koniec")
     if option:
         exit()
     else:
         self.parent.parentApp.switchForm("MAIN")
         npyscreen.blank_terminal()
Пример #18
0
 def on_ok(self):
     v = self.chose.get_selected_objects()[0]
     filename = self.filename.value
     if v == "Download":
         self.parentApp.getForm("Download").filename.value = \
             self.filename.value
         self.parentApp.switchForm("Download")
     elif v == "Delete":
         # DELETE FROM DB
         confirm = npyscreen.notify_yes_no(
             "Are you sure you want to delete file %s?" % filename,
             title="Confimation", form_color='STANDOUT',
             wrap=True, editw=1)
         if confirm:
             global LogUser
             client.removeFile(LogUser, filename)
             self.parentApp.getForm("List").update_list()
             self.parentApp.switchForm("List")
     elif v == "Share":
         global LogUser
         if client.getPermission(LogUser, filename):
             self.parentApp.getForm("WhoIsShared").filename.value = \
                 self.filename.value
             self.parentApp.switchForm("WhoIsShared")
         else:
             npyscreen.notify_wait("You have no Permission to Share the File", title='Failure',
                               form_color='CRITICAL')
     elif v == "Diff":
         self.parentApp.getForm("Get").filename.value = \
             self.filename.value
         self.parentApp.switchForm("Get")
Пример #19
0
    def on_cancel(self):
        discard = npyscreen.notify_yes_no(
            'Are you sure you want to discard message?',
            title='Discard message')

        if discard:
            self.back()
Пример #20
0
    def deactivate_client(self, keypress=None):
        """Ask to deactivate the client and do it if yes."""
        # cancel if there are no clients
        if len(self.values) < 1:
            return False

        # get selected client
        self.parent.parentApp.tmpClient = self.values[self.cursor_line].copy()

        client_str = '"{}: {}"'.format(
            self.parent.parentApp.tmpClient.client_id,
            self.parent.parentApp.tmpClient.fullname())
        really = npyscreen.notify_yes_no(
            'Really deactivate the client {} and all its projects?'.format(
                client_str),
            form_color='WARNING')

        # yepp, deactivate it
        if really:
            worked = self.parent.parentApp.L.deactivate_client(
                client=self.parent.parentApp.tmpClient,
                inactive_dir=self.parent.parentApp.S.inactive_dir,
                settings=self.parent.parentApp.S)

            # something went wrong
            if not worked:
                npyscreen.notify_confirm(
                    'Client not properly deactivated, woops!',
                    form_color='WARNING')

            # ouhkaaaay
            else:
                self.update_values()
                self.refresh_project_list()
Пример #21
0
    def on_login(self):
        client_controller: Clients = self.parentApp.client_controller
        username = self.__username.value
        if not Clients.validate_username(username):
            npyscreen.notify_confirm("Username is not valid: use only `a-zA-Z0-9_`, "
                                     "minimal length is 4", title='Error')
            return

        result = client_controller.login_client(username)
        if result is None:
            message_to_display = "Such client with username `%s` hasn't been registered yet. " \
                                 "We will register you with such username. If you want to be a " \
                                 "regular user, proceed with `No`, if you want to be admin - " \
                                 "choose `Yes`" % username
            register_as_admin = npyscreen.notify_yes_no(message_to_display, title='Registration')
            try:
                client_controller.register_client(username, register_as_admin)
            except Exception as e:
                npyscreen.notify_confirm('Error occurred: %s' % str(e), title='Error')
                return
            npyscreen.notify_confirm('Successfully registered %s with username `%s`' %
                                     ('admin' if register_as_admin else 'user', username), title='Result')
            result = client_controller.login_client(username)

        if result is True:
            self.parentApp.switchForm("ADMIN")
        else:
            self.parentApp.current_username = username
            self.parentApp.getForm('USER').username_was_set_hook(username)
            self.parentApp.switchForm("USER")
Пример #22
0
 def c_delete_feed(self, *args, **keywords):
     if npyscreen.notify_yes_no(
             'Are you sure you want to remove this feed?',
             title='Confirm Delete'):
         with session_scope() as session:
             md.delete_feed(session, self.parent.value[1]['feed_id'])
         self.parent.parentApp.switchFormPrevious()
Пример #23
0
    def create(self):
 
        desc_wrap = textwrap.wrap(msg.decription, self.columns - 6)
        
        self.description_label = self.add(npyscreen.MultiLineEdit, value='\n'.join(desc_wrap), max_height=6, rely=2, editable=False)
        self.description_label.autowrap = True

        self.os_type = self.add(npyscreen.TitleFixedText, name=msg.os_type_label, begin_entry_at=18, value=msg.os_type + ' ' + msg.os_version, editable=False)
        self.init_type = self.add(npyscreen.TitleFixedText, name=msg.init_type_label, begin_entry_at=18, value=msg.os_initdaemon, editable=False)
        self.httpd_type = self.add(npyscreen.TitleFixedText, name=msg.httpd_type_label, begin_entry_at=18, value=msg.apache_version, field_width=40, editable=False)
        self.license_confirm = self.add(npyscreen.Checkbox, scroll_exit=True, name=msg.acknowledge_lisence)  
        self.warning_text = self.add(npyscreen.MultiLineEdit, value=msg.setup_properties_warning, max_height=4, editable=False)

        for sys_req in ('file_max', 'mem_size', 'number_of_cpu', 'free_disk_space'):
            cur_val = getattr(msg, 'current_' + sys_req)
            req_val = getattr(msg, 'suggested_' + sys_req)
            if cur_val < req_val:
                warning_text = getattr(msg, 'insufficient_' + sys_req).format(cur_val, req_val)
                
                if sys_req == 'file_max':
                    self.parentApp.exit_reason = warning_text
                    self.parentApp.onCleanExit()
                    time.sleep(3.5)
                    sys.exit(False)
                
                warning_text += '. Do you want to continue?'
                result = npyscreen.notify_yes_no(warning_text, title="Warning")
                if not result:
                    self.parentApp.exit_reason = msg.not_to_continue
                    self.parentApp.onCleanExit()
                    sys.exit(False)
Пример #24
0
 def submenu_delete(self):
     # get current row's value to form query with headers
     curvalues = self.grid.selected_row()
     # prompt user to be sure, then just execute delete query from here
     retval = npyscreen.notify_yes_no(
         'Are you sure you wish to delete this row?', editw=1)
     if retval:
         # do the delete
         wheretext = ''
         for idx, i in enumerate(self.headers):
             wheretext += '\"' + i + '\" = (%s) AND '
         # trim that last and and 2 spaces
         wheretext = wheretext[:-5]
         SQL = 'delete from \"{0}\" where {1};'.format(
             self.table, wheretext)
         try:
             value = tuple(curvalues)
             conn = Connection.Instance().getconnection()
             cursor = conn.cursor()
             cursor.execute(SQL, value)
             npyscreen.notify_confirm('{0} rows affected'.format(
                 cursor.rowcount),
                                      editw=1)
             self.cell = [0, 0]
         except Exception as e:
             npyscreen.notify_confirm(e.message, editw=1)
         # reflect the change immediately
         try:
             self.updateresults()
         except Exception as e:
             npyscreen.notify_confirm(e.message, editw=1)
             self.backonequery()
Пример #25
0
    def h_remove_block(self):
        """
        The "Remove block" button is pushed.
        Ask for confirmation and delete if ok.
        """
        # Ask for confirmation
        if not npyscreen.notify_yes_no(
                "Are you sure you want to delete the block: %s" %
                self.block['name'],
                "Confirm deletion",
                form_color='DANGER'):
            return

        # Actually delete the block
        delete_block(self.block['name'], self.block['location'] == "LOCAL")

        # Notify
        npyscreen.notify_wait(
            "The block %s has been removed from the %s ini file." %
            (self.block['name'], self.block['location']))

        # Add to specify this edit_return_value to prevent failure
        self.__class__.edit_return_value = None

        # Returns to the MainMenu
        self.parentApp.switchFormPrevious()
Пример #26
0
 def on_ok(self, direct=False):
     if direct:
         self.parentApp.switchForm(None)
     ans = npyscreen.notify_yes_no('Are you sure, you want to quit?')
     if ans:
         self.TG.receiver.stop()
         self.parentApp.switchForm(None)
Пример #27
0
	def on_ok(self):
		exiting = npyscreen.notify_yes_no("Are you sure you want to quit?","Quit?", editw=1)
		if exiting:
			npyscreen.notify_confirm("Goodbye!", editw=1)
			self.parentApp.switchForm(None)
		else:
			pass
Пример #28
0
 def on_ok(self):
     if self.group_name.value and self.multi_host_select.get_selected_objects(
     ):
         for host in self.multi_host_select.get_selected_objects():
             if sv.HOSTS_CONFIG[host]['method'] != sv.HOSTS_CONFIG[
                     self.multi_host_select.get_selected_objects()
                 [0]]['method']:
                 npyscreen.notify_confirm(
                     "Hosts do not share common remoting method",
                     wide=True,
                     editw=1)
                 return
         if self.group_name.value in sv.GROUPS_CONFIG.keys():
             if not npyscreen.notify_yes_no(
                     f"Group {self.group_name.value} already exists, would you like to override?",
                     title="Already Exists",
                     editw=1):
                 return
         sv.CHANGES_PENDING = True
         sv.GROUPS_CONFIG[self.group_name.value] = []
         for host in self.multi_host_select.get_selected_objects():
             sv.GROUPS_CONFIG[self.group_name.value].append(host)
         self.parentApp.getForm('MAIN').reload_screen()
         self.parentApp.switchFormPrevious()
     else:
         npyscreen.notify_confirm(
             "Please Make sure you select at least one host and give your group a name.",
             wide=True,
             editw=1)
Пример #29
0
 def on_cancel(self):
     exiting = npyscreen.notify_yes_no("Are you sure you want to cancel?"+
                                       " This session will be lost.",
                                       "Quit?", editw=1)
     if exiting:
         self.clearvalues()
         self.parentApp.switchFormPrevious()
Пример #30
0
    def on_ok(self):
        # ok btn press
        def want_to_save_log():
            data = {
                'userName': self.fname.value,
                'todayDone': self.todayDone.value,
                'saveTime': self.logTime.value,
                'todayProblem': self.problem.value
            }
            if not os.path.exists('./logs/'):
                os.mkdir('./logs')
            with open('./logs/' + self.logTime.value + '.json', 'w') as f:
                json.dump(data, f)
                npyscreen.notify_confirm(
                    'Good!' + self.fname.value +
                    '\n\nYour log has been saved!\nNow click "Cancel" to leave! '
                )
                self.saved.value = 'Saved! at ' + datetime.now().strftime(
                    "%Y-%m-%d.%H:%M")

        savedNewFileName = datetime.now().strftime("%Y-%m-%d") + ".json"
        if os.path.exists('./logs/' + savedNewFileName):
            postive_rewrite = npyscreen.notify_yes_no(
                'You had saved a log today, Do you want to rewrite?',
                'Rewrite?',
                editw=1)
            if postive_rewrite: want_to_save_log()
            else:
                npyscreen.notify_confirm('bye bye!', 'Not Rewrite!')
                self.parentApp.setNextForm(None)
        else:
            want_to_save_log()
Пример #31
0
    def delete(self, keypress=None):
        """Ask and delete entry."""
        # cancel if there are no values
        if len(self.values) < 1:
            return False

        entry = self.values[self.cursor_line]['item']
        name = self.values[self.cursor_line]['name']

        really = npyscreen.notify_yes_no(
            'Really delete the entry "{}"?'.format(entry.title),
            form_color='CRITICAL')

        if really:
            if self.is_offer(entry):
                deleted = self.parent.parentApp.P.remove_offer(name=name)
            elif self.is_invoice(entry):
                deleted = self.parent.parentApp.P.remove_invoice(name=name)
            elif self.is_entry(entry):
                if self.parent.parentApp.tmpEntry_offer_invoice == 'offer':
                    deleted = self.parent.parentApp.P.remove_offer_entry(
                        name=name)
                else:
                    deleted = self.parent.parentApp.P.remove_invoice_entry(
                        name=name)
            else:
                deleted = False

            if not deleted:
                npyscreen.notify_confirm('Could not delete the entry!',
                                         form_color='WARNING')
            else:
                self.update_values()
Пример #32
0
 def on_cancel(self):
     exiting = npyscreen.notify_yes_no("Are you sure you want to cancel?" +
                                       " This session will be lost.",
                                       "Quit?",
                                       editw=1)
     if exiting:
         self.parentApp.switchFormPrevious()
Пример #33
0
    def on_ok(self):
        send = npyscreen.notify_yes_no(
            'Are you sure you want to send message?', title='Send message')

        if send:
            self.sendMessage()
            self.back()
Пример #34
0
 def on_cancel(self):
     exiting = npyscreen.notify_yes_no("Are you sure you want to cancel", "Positive?", editw=2)
     if exiting:
         npyscreen.notify_confirm("Form has not been saved", 'bye bye', editw=1)
         self.parentApp.setNextForm(None)
     else:
         npyscreen.notify_confirm("You can continue working", 'okay', editw=1)
Пример #35
0
    def on_ok(self):
        # Check fields validity
        if (self.ldap.value == ""):
            nps.notify_confirm(words['LdapPassword'], words['Warning'])
            return
        if (self.uname.value == ""):
            nps.notify_confim(words['InsertUsername'], words['Warning'])
            return

        # Check if this user exists
        if(ldap.userexists(self.uname.value)):
            pass
        else:
            errormsg = words['User']+self.uname.value+words['UserNotExist']
            nps.notify_confirm(errormsg, words['Warning'], editw = 1)
            return

        # Try to connect to LDAP database
        try:
            db = ldap.lcmldap("ldaps://xx8.xx1.mi.infn.it/",
                              "cn=Manager","dc=xx8,dc=xx1", self.ldap.value)
        except:
            nps.notify_confirm(words['DBConnFail'], words['Warning'])
            self.ldap.value = None
            return

        # Ask to confirm you really want to delete this user
        dele = nps.notify_yes_no(words['ConfirmDel']+self.uname.value+"?",
                                 words['DeleteUser'], editw = 2)
        if (dele):
            dele2 = nps.notify_yes_no(words['AreYouSure']+self.uname.value+"?\n"+
            words['ItCannotBeUndo'], words['DeleteUser'], editw = 2)
            if (dele2):
                pass
            else:
                return
        else:
            return

        delusercmd="userdel -r "+self.uname.value
        system(delusercmd)

        db.deluser(self.uname.value)

        nps.notify_confirm(words['UserDeleted'], words['Warning'])

        self.return_to_main_screen()
Пример #36
0
    def nextButtonPressed(self):
        for service in self.services:
            cb_val = getattr(self, service).value
            setattr(self.parentApp.installObject, service, cb_val)

        if self.installOxd.value:
            self.parentApp.installObject.oxd_server_https = 'https://{}:8443'.format(
                self.parentApp.installObject.hostname)

        if self.installCasa.value:
            if not self.installOxd.value and not self.oxd_url.value:
                npyscreen.notify_confirm(msg.install_oxd_or_url_warning,
                                         title="Warning")
                return

            if not self.installOxd.value:

                oxd_server_https = self.oxd_url.value

                oxd_connection_result = self.parentApp.installObject.check_oxd_server(
                    oxd_server_https)

                if oxd_connection_result != True:
                    npyscreen.notify_confirm(msg.oxd_connection_error.format(
                        oxd_server_https, oxd_connection_result),
                                             title="Warning")
                    return

                oxd_hostname, oxd_port = self.parentApp.installObject.parse_url(
                    oxd_server_https)
                oxd_ssl_result = self.parentApp.installObject.check_oxd_ssl_cert(
                    oxd_hostname, oxd_port)
                if oxd_ssl_result:

                    npyscreen.notify_confirm(msg.oxd_ssl_cert_error.format(
                        oxd_ssl_result['CN'], oxd_hostname),
                                             title="Warning")
                    return

                self.parentApp.installObject.oxd_server_https = oxd_server_https

        oxd_hostname, oxd_port = self.parentApp.installObject.parse_url(
            self.parentApp.installObject.oxd_server_https)
        if not oxd_port:
            oxd_port = 8443

        self.parentApp.installObject.templateRenderingDict[
            'oxd_hostname'] = oxd_hostname
        self.parentApp.installObject.templateRenderingDict['oxd_port'] = str(
            oxd_port)

        if self.installOxd.value:
            result = npyscreen.notify_yes_no(
                msg.ask_use_gluu_storage_oxd,
                title=msg.ask_use_gluu_storage_oxd_title)
            if result:
                self.parentApp.installObject.oxd_use_gluu_storage = True

        self.parentApp.switchForm('DBBackendForm')
Пример #37
0
 def del_entry(self):
     delete = npyscreen.notify_yes_no(
         "Are you sure you want to delete this entry?", "Delete?", editw=1)
     if delete:
         db.remove(self.value)
         npyscreen.notify_confirm("Entry was deleted successfully!",
                                  editw=1)
         self.parentApp.switchForm("LISTENTRIES")
Пример #38
0
 def spawn_notify_popup(self, entity):
     message_to_display = f'{entity} is empty. \n\t Do you wanna create some?'
     notify_result = npyscreen.notify_yes_no(message_to_display, title='Info box')
     if notify_result:
         self.parent.parentApp.getForm('MUSICIANEDIT').value = None
         self.parent.parentApp.switchForm(f"{entity.upper()[:-1]}EDIT")
     else:
         self.parent.parentApp.switchForm("MAIN")
Пример #39
0
 def on_cancel(self):
     exiting = nps.notify_yes_no("Vuoi veramente uscire?",
                                 "Close Application",
                                 editw=2)
     if (exiting):
         self.exit_application()
     else:
         pass
Пример #40
0
 def accept(self, x):
     app = self.parent.parentApp
     state = app.process_state.state
     if self.value not in state.all_accounts:
         if not npyscreen.notify_yes_no("Account %s does not exist.  Add it?" % self.value, editw=2):
             return
     app.current_matches[-1] = app.make_new_candidate(self.value)
     self.cancel(x)
Пример #41
0
def show_quit_popup(key=None):
    """Display popup asking whether to quit application"""
    result = npyscreen.notify_yes_no(
        message='Do you really want to quit?',
        title='Quit',
        editw=1,  # select No button by default
    )
    if result:
        quit()
Пример #42
0
 def on_cancel(self):
     ok_cancel = npyscreen.notify_yes_no("Are you sure you want to exit?",
                                         "Warning",
                                         editw=2)
     if ok_cancel:
         if ok_cancel:
             self.parentApp.setNextForm(None)
     else:
         self.parentApp.setNextFormPrevious
Пример #43
0
 def on_tweet(self):
     post = self.tweet.value
     if len(post) == 0:
         notify_confirm('You can\'t post an empty tweet')
     elif len(post) > 140:
         notify_confirm('Your tweet is too long!', title='Error')
     elif notify_yes_no('Are you sure you want to post:\n' + post, title='Post'):
         self.post_tweet(post)
         self.tweet.value = ''
Пример #44
0
    def on_cancel(self):
        confirm = npyscreen.notify_yes_no(
            "Are you sure you want to exit?", title="Confimation",
            form_color='STANDOUT', wrap=True, editw=1)

        if confirm:
            self.parentApp.switchForm(None)
        else:
            self.parentApp.switchFormPrevious()
Пример #45
0
 def actionHighlighted(self, act_on_this, key_press):
     if act_on_this == "📜Add entry":
         self.parent.parentApp.switchForm("NEWENTRY")
     if act_on_this == "📚View previous entries":
         self.parent.parentApp.switchForm("LISTENTRIES")
     if act_on_this == "❎Exit":
         exiting = npyscreen.notify_yes_no("Are you sure you want to quit?", "Quit?", editw=1)
         if exiting:
             npyscreen.notify_confirm("Goodbye!", editw=1)
             exit()
         else:
             pass
Пример #46
0
    def on_element_selected(self, selected_show, keypress):
        #selected_show.popTicket()
        if selected_show.isEmptyTickets():
            if selected_show.freeplaces < selected_show.theater.places and npyscreen.notify_yes_no("The show can start!\n\nDelete this show?"):
                    # delete show
                    self.parentApp.cinema.shows.delete(selected_show.ID)
        else:
            #npyscreen.notify_confirm("We still need "+str(selected_show.tickets.length)+" people "\
                #+ "for the film \n   '" + selected_show.film.title+ "'.")
            self.parentApp.getForm("CHOOSEAMOUNTOFPEOPLE").selected_show = selected_show
            self.parentApp.switchForm("CHOOSEAMOUNTOFPEOPLE")

        self.update_list()
Пример #47
0
	def deleteRow(self):
		if self.SQL_display.value:
			self.yesOrNo = npyscreen.notify_yes_no("You are about to delete a row. This action cannot be undone. Proceed?", editw=1)
			if self.yesOrNo:
				# fix bug where always select index of first page result
				self.SQL_display.value[0] += (self.page * self.parentApp.rows_per_page)
				# This passes the table name, column names, column values to the function that deletes the row.
				self.parentApp.sql.delete_row(self.value, self.colnames, self.results[self.SQL_display.value[0]]) 
				self.parentApp.switchForm('BROWSE')
			else:
				npyscreen.notify_confirm("Aborted. Your row was NOT deleted.", editw=1)
		else:
			npyscreen.notify_confirm("Please select a row to delete.", editw=1)
Пример #48
0
	def deleteField(self):
		if self.SQL_display.value:
			self.yesOrNo = npyscreen.notify_yes_no("You are about to delete a field. This action cannot be undone. Proceed?", editw=1)
			if self.yesOrNo:
				# fix bug where always select index of first page result
				self.SQL_display.value[0] += (self.page * self.parentApp.rows_per_page)
				# This passes the table name and column name to the column delete function
				column_values = self.results[self.SQL_display.value[0]]
				self.parentApp.sql.delete_column(self.value, column_values) 
				self.parentApp.switchForm('STRUCTURE')
			else:
				npyscreen.notify_confirm("Aborted. Your field was NOT deleted.", editw=1)
		else:
			npyscreen.notify_confirm("Please select a field to delete.", editw=1)
Пример #49
0
 def on_ok(self):
     amount = 0
     try:
         amount = int(self.Amount.value)
         if not 0 < amount <= self.selected_show.tickets.length:
             raise Exception()
         
         for _ in range(amount):
             self.selected_show.popTicket()
         
         if self.selected_show.isEmptyTickets() and self.selected_show.freeplaces < self.selected_show.theater.places:
             if npyscreen.notify_yes_no("The show can start!\n\nDelete this show?"):
                 # delete show
                 self.parentApp.cinema.shows.delete(self.selected_show.ID)
             
         self.parentApp.switchForm("PICKSHOWTOENTER")
             
     except:
         npyscreen.notify_confirm("Not a valid amount, try again!")
Пример #50
0
 def on_ok(self):
     ans = npyscreen.notify_yes_no('Are you sure, you want to quit?')
     if ans:
         TG.receiver.stop()
         self.parentApp.switchForm(None)
Пример #51
0
    def on_ok(self):
        """ Save changes made to vent.template """
        # ensure user didn't have any syntactical errors
        input_is_good, trimmed_input = self.valid_input(self.edit_space.value)
        if not input_is_good:
            return
        self.edit_space.value = trimmed_input

        # get the number of instances and ensure user didn't malform that
        if re.search(r'instances\ *=', self.edit_space.value):
            try:
                # split out spaces
                instances_val = re.split(r'instances\ *=\ *',
                                         self.edit_space.value)[1]
                instances_val = instances_val.split('\n')[0]
                new_instances = int(re.match(r'\d+$', instances_val).group())
            except AttributeError:
                npyscreen.notify_confirm("You didn't specify a valid number"
                                         ' for instances.', title='Invalid'
                                         ' instance number')
                return
            # user can't change instances when configuring new instnaces
            if (self.instance_cfg and
                    self.settings['new_instances'] != new_instances):
                npyscreen.notify_confirm("You can't change the number of"
                                         ' instnaces while configuring new'
                                         ' instances!', title='Illegal change')
                return
            # get old number of instances
            try:
                if 'old_instances' in self.settings:
                    old_instances = self.settings['old_instances']
                else:
                    settings_dict = json.loads(
                        self.manifest.option(self.section,
                                             'settings')[1])
                    old_instances = int(settings_dict['instances'])
            except Exception:
                old_instances = 1
        else:
            new_instances = 1
            old_instances = 1

        # save changes and update manifest we're looking at with changes
        if self.vent_cfg:
            save_args = {'main_cfg': True,
                         'config_val': self.edit_space.value}
            self.manifest = self.settings['save_configure'](**save_args)[1]
        else:
            save_args = copy.deepcopy(self.tool_identifier)
            save_args.update({'config_val': self.edit_space.value})
            if self.registry_tool:
                save_args.update({'from_registry': True})
            if self.instance_cfg:
                save_args.update({'instances': new_instances})
            self.manifest = self.settings['save_configure'](**save_args)[1]

        # restart tools, if necessary
        if not self.just_downloaded and not self.instance_cfg:
            restart_kargs = {'main_cfg': self.vent_cfg,
                             'old_val': self.config_val,
                             'new_val': self.edit_space.value}
            if self.vent_cfg:
                wait_str = 'Restarting tools affected by changes...'
            else:
                wait_str = 'Restarting this tool with new settings...'
                restart_kargs.update(self.tool_identifier)
            npyscreen.notify_wait(wait_str,
                                  title='Restarting with changes')
            self.settings['restart_tools'](**restart_kargs)

        # start new instances if user wanted to
        if self.instance_cfg and self.settings['start_new']:
            npyscreen.notify_wait('Starting new instances...',
                                  title='Start')
            tool_d = {}
            for i in range(self.settings['old_instances'] + 1,
                           self.settings['new_instances'] + 1):
                # create section by scrubbing instance number out of names
                # and adding new instance number
                i_section = self.section.rsplit(':', 2)
                i_section[0] = re.sub(r'[0-9]', '', i_section[0]) + str(i)
                i_section = ':'.join(i_section)
                t_name = self.manifest.option(i_section, 'name')[1]
                t_id = {'name': t_name}
                tool_d.update(self.settings['prep_start'](**t_id)[1])
            if tool_d:
                self.settings['start_tools'](tool_d)

        # prompt user for instance changes, as necessary
        if not self.instance_cfg and not self.vent_cfg:
            if new_instances > old_instances:
                try:
                    diff = str(new_instances - old_instances)
                    res = npyscreen.notify_yes_no('You will be creating ' +
                                                  diff + ' additional'
                                                  ' instance(s) is that okay?',
                                                  title='Confirm new'
                                                  ' instance(s)')
                    if res:
                        if self.manifest.option(self.section,
                                                'built')[1] == 'yes':
                            run = npyscreen.notify_yes_no('Do you want to'
                                                          ' start these new'
                                                          ' tools upon'
                                                          ' creation?',
                                                          title='Run new'
                                                          ' instance(s)')
                        else:
                            run = False
                        # get clean name (no instance numbers in it)
                        new_name = self.settings['tool_name']
                        new_name = re.sub(r'[0-9]+$', '', new_name)
                        self.settings['tool_name'] = new_name
                        npyscreen.notify_wait('Pulling up default settings'
                                              ' for ' +
                                              self.settings['tool_name'] +
                                              '...',
                                              title='Gathering settings')
                        Repository(System().manifest)._clone(
                            self.settings['repo'])
                        self.settings['new_instances'] = new_instances
                        self.settings['old_instances'] = old_instances
                        self.settings['start_new'] = run
                        self.settings['new_instance'] = True
                        self.settings['name'] = 'Configure new instance(s)' + \
                            ' for ' + self.settings['tool_name']
                        self.parentApp.addForm('INSTANCEEDITOR' +
                                               self.settings['tool_name'],
                                               EditorForm, **self.settings)
                        self.parentApp.change_form('INSTANCEEDITOR' +
                                                   self.settings['tool_name'])
                    else:
                        return
                except Exception:
                    npyscreen.notify_confirm('Trouble finding tools to add,'
                                             ' exiting', title='Error')
                    self.on_cancel()
            elif new_instances < old_instances:
                try:
                    diff = str(old_instances - new_instances)
                    res = npyscreen.notify_yes_no('You will be deleting ' +
                                                  diff + ' instance(s), is'
                                                  ' that okay?',
                                                  title='Confirm delete'
                                                  ' instance(s)')
                    if res:
                        form_name = 'Delete instances for ' + \
                            re.sub(r'\d+$', '',
                                   self.settings['tool_name']) + '\t'*8 + \
                            '^E to exit configuration process'
                        clean_section = self.section.rsplit(':', 2)
                        clean_section[0] = re.sub(r'\d+$', '',
                                                  clean_section[0])
                        clean_section = ':'.join(clean_section)
                        d_args = {'name': form_name,
                                  'new_instances': new_instances,
                                  'old_instances': old_instances,
                                  'next_tool': self.settings['next_tool'],
                                  'manifest': self.manifest,
                                  'section': clean_section,
                                  'clean': self.settings['clean'],
                                  'prep_start': self.settings['prep_start'],
                                  'start_tools': self.settings['start_tools']}
                        self.parentApp.addForm('DELETER' +
                                               self.settings['tool_name'],
                                               DeleteForm, **d_args)
                        self.parentApp.change_form('DELETER' +
                                                   self.settings['tool_name'])
                except Exception:
                    npyscreen.notify_confirm('Trouble finding instances to'
                                             ' delete, exiting', title='Error')
                    self.on_cancel()

        if (new_instances == old_instances or
                self.instance_cfg or self.vent_cfg):
            npyscreen.notify_confirm('Done configuring ' +
                                     self.settings['tool_name'],
                                     title='Configurations saved')
            self.change_screens()
Пример #52
0
    def valid_input(val):
        """ Ensure the input the user gave is of a valid format """
        # looks for 3 nums followed by a dot 3 times and then ending with
        # 3 nums, can be proceeded by any number of spaces
        ip_value = re.compile(r'(\d{1,3}\.){3}\d{1,3}$')
        # looks for only numbers and commas (because priorities can have commas
        # between them), can be proceeded by any number of spaces
        all_num = re.compile(r'(\d,?\ *)+$')
        sections_comments = re.compile(r"""
        \ *\#.*             # comments (any number of whitespace, then #
                            # followed by anything)

        | \[[\w-]+\]$       # section headers (any combination of chars, nums,
                            # underscores, and dashes between brackets)
        """, re.VERBOSE)
        # can't can be a comment on option side and value side can't have
        # [, ], {, or } otherwise it is turned over to literal_eval for
        # checkout
        options_values = re.compile(r'[^# ]+\ *=[^[\]{}]*$')
        line_num = 0
        warning_str = ''
        error_str = ''
        trimmed_val = []
        for entry in val.split('\n'):
            line_num += 1
            # get rid of any extraneous commas at the end of a dict and remove
            # extra whitespace from input
            trimmed_val.append(re.sub(r',\ *}', '}', entry).strip())
            # empty line
            if entry.strip() == '':
                continue
            # look at regular (non dictionary or list) option-value pairs
            if options_values.match(entry):
                value = entry.split('=', 1)[1]
                # deal with potentially more equals signs
                for val in value.split('='):
                    val = val.strip()
                    # empty val means malformed equals signs
                    if val == '':
                        error_str += '-You have a misplaced equals sign on' \
                            ' line ' + str(line_num) + '\n'
                    # starts with a num; look for bad ip input or warn user
                    # about having extraneous characters in number input
                    if re.match('\ *\d', val):
                        # bad ip syntax
                        if val.find('.') >= 0 and not ip_value.match(val):
                            error_str += '-You have an incorrectly' \
                                ' formatted ip address (bad syntax) at' \
                                ' line ' + str(line_num) + '\n'
                        # possibly malformed numbers
                        elif val.find('.') < 0 and not all_num.match(val):
                            warning_str += '-Line starting with a number has' \
                                ' characters mixed in at line ' + \
                                str(line_num) + '\n'
                        # bad ip values
                        elif val.find('.') >= 0:
                            for num in val.strip().split('.'):
                                num = int(num)
                                if num > 255 or num < 0:
                                    error_str += '-You have an incorrectly' \
                                        ' formatted ip address (values' \
                                        ' exceeding 255 or below 0) at' \
                                        ' line ' + str(line_num) + '\n'
                    # ensure no lines end with a comma (most likely extraneous
                    # commas from groups or priorities)
                    if re.search(',$', val):
                        error_str += '-You have an incorrect comma at the' \
                            ' end of line ' + str(line_num) + '\n'
            # see if input is a header or comment, otherwise try to
            # literal_eval it to ensure correct structure
            elif not sections_comments.match(entry):
                lit_val = ''
                try:
                    opt_val = entry.split('=', 1)
                    if opt_val[0].strip() == '':
                        error_str += '-You have nothing preceeding an' \
                            ' equals sign at line ' + str(line_num) + '\n'
                    else:
                        lit_val = opt_val[1].strip()
                except IndexError:
                    lit_val = ''
                    error_str += '-You have an incorrectly formatted' \
                        ' section header at line ' + str(line_num) + '\n'
                if lit_val:
                    try:
                        ast.literal_eval(lit_val)
                    except SyntaxError:
                        error_str += '-You have an incorrectly formatted' \
                            ' list/dictionary at line ' + str(line_num) + \
                            '\n'

        if error_str:
            npyscreen.notify_confirm('You have the following error(s) and'
                                     " can't proceed until they are fixed:" +
                                     '\n' + '-'*50 + '\n' + error_str,
                                     title='Error in input')
            return (False, '')
        elif warning_str:
            res = npyscreen.notify_yes_no('You have may have some error(s)'
                                          ' that you want to check before'
                                          ' proceeding:' + '\n' + '-'*50 +
                                          '\n' + warning_str + '\n' + '-'*50 +
                                          '\n' + 'Do you want to continue?',
                                          title='Double check')
            return (res, '\n'.join(trimmed_val))
        return (True, '\n'.join(trimmed_val))
Пример #53
0
 def whenPressed(self):
     if npyscreen.notify_yes_no("doit?", title="doit?"):
         self.parent.printThread.stop()
         return self.parent.prepareStopMove()
Пример #54
0
 def handle_del(self, *args, **kwargs):
     record_name = self.get_selection(cursor=True)
     if npyscreen.notify_yes_no("Really delete %s?" % (record_name)):
         self.delete_record(record_name)
         self.refresh_values()
Пример #55
0
 def on_quit(self):
     if notify_yes_no('Are you sure you wanna quit?', title='Quit'):
         exit()
Пример #56
0
    def on_ok(self):
        # Check fields validity
        if (self.ldap.value == ""):
            nps.notify_confirm(words['LdapPassword'], words['Warning'])
            return
        if (self.uname.value == ""):
            nps.notify_confirm(words['InsertUsername'], words['Warning'])
            return
        if (search(r'[^A-Za-z0-9_]', self.uname.value)):
            nps.notify_confirm(words['BadChar'], words['Warning'])
            return

        # Check if this user exists
        if(ldap.userexists(self.uname.value)):
            pass
        else:
            errormsg = words['User']+self.uname.value+words['UserNotExist']
            nps.notify_confirm(errormsg, words['Warning'], editw = 1)
            return

        # Try to connect to LDAP database
        try:
            db = ldap.lcmldap("ldaps://xx8.xx1.mi.infn.it/",
                              "cn=Manager","dc=xx8,dc=xx1", self.ldap.value)
        except:
            nps.notify_confirm(words['DBConnFail'], words['Warning'])
            self.ldap.value = None
            return

        newday = time.gmtime(time.time()+3*86400*365)
        newdaystr = time.strftime("%d/%m/%Y", newday)
        # Convert in the right format for chage command
        newshadow = time.strftime("%m/%d/%Y", newday)

        text = words['RenewUser1'] + self.uname.value + words['RenewUser2']
        text = text + newdaystr + "?"

        ren = nps.notify_yes_no(text, words['RenewUser'], editw = 2)
        if (not ren):
            self.return_to_main_screen()
            return

        cmd = "chage " + self.uname.value + " -E " + newshadow
        expDate=str( (int(time.time())+3*86400*365) / 86400 )

        db.changeshadowexpire(self.uname.value, expDate)
        system(cmd)


        # Ask to send mail to user
        sm = nps.notify_yes_no(words['SendMailToUser'], editw = 2)
        if (sm):
            sender    = '*****@*****.**'
            usermail  = self.uname.value + "@lcm.mi.infn.it"
            receivers = [ usermail, '*****@*****.**' ]

            message = """From: <*****@*****.**>
To: """ + usermail + """
Subject: Rinnovo account LCM
Reply-to: <*****@*****.**>

Ciao,

abbiamo rinnovato il tuo account.
Nuova data di scadenza: """ + newdaystr + """

A presto,
LCM Staff
"""

            try:
                smtpObj = smtplib.SMTP('localhost')
                smtpObj.sendmail(sender, receivers, message)
                nps.notify_confirm(words['MailSent'], words['Warning'])
            except smtplib.SMTPException:
                nps.notify_confirm(words['MailNotSent'], words['Warning'])

        nps.notify_confirm(words['UserRenewed'], words['Warning'])
        self.return_to_main_screen()
Пример #57
0
 def c_delete_feed(self, *args, **keywords):
     if npyscreen.notify_yes_no('Are you sure you want to remove this feed?', title='Confirm Delete'):
         with session_scope() as session:
             md.delete_feed(session, self.parent.value[1]['feed_id'])
         self.parent.parentApp.switchFormPrevious()