def cargar_articulos(self,fecha_reserva,Funcionario,descripcion, codigo, fecha_ingreso,reservado,tipo):
     if ( codigo=='' or codigo == None):
         raise Exception('Codigo de la dependencia vacio')
     else:
         try:
             value=int(codigo)
         except ValueError:
             raise Exception('El código del articulo debe ser del tipo númerico')
         else:
             try:
                 strptime(fecha_ingreso, '%d/%m/%Y')
                 persistence = ControladorPersistence()
                 persistence.leer(codigo)
             except ValueError:
                 raise Exception('El formato no corresponde\nfavor ingresar de la siguiente manera dd/mm/yyyy')
             except:
                 if( tipo == 'Notebook'):
                     a= Notebook(fecha_reserva,Funcionario,descripcion, codigo, fecha_ingreso,reservado)
                 elif(tipo=='Proyector'):
                     a= Proyector(fecha_reserva,Funcionario,descripcion, codigo, fecha_ingreso,reservado)
                 elif(tipo=='Multiple Electrico'):
                     a= MultipleElectrico(fecha_reserva,Funcionario,descripcion, codigo, fecha_ingreso,reservado)
                 a.cargar_articulos()
             else:
                 raise Exception('El código del articulo ya existe')
class Menu(object):
    "Display a menu and respond to choices when run"
    def __init__(self):
        self.notebook = Notebook()
        self.choices = {
                        "1": self.show_notes,
                        "2": self.search_notes,
                        "3": self.add_note,
                        "4": self.modify_note,
                        "5": self.quit
                        }

    def display_menu(self):
        print "1: show notes, 2: search, 3: add, 4: modify, 5: quit"

    def run(self):
        "Display the menu and respond to choices"
        while True:
            self.display_menu()
            choice = raw_input("> ")
            action = self.choices.get(choice)
            if action:
                action()
            else:
                print "{0} is not a valid choice".format(choice)

    def show_notes(self, notes=None):
        if not notes:
            notes = self.notebook.notes
        for note in notes:
            print "{0}, {1}:\n{2}".format(
                note.id, note.tags, note.memo)

    def search_notes(self):
        pattern = raw_input("Search for: ")
        notes = self.notebook.search(pattern)
        self.show_notes(notes)

    def add_note(self):
        memo = raw_input("Enter a memo: ")
        self.notebook.new_note(memo)
        print "Your note has been added."

    def modify_note(self):
        note_id = int(raw_input("Enter a note id: "))
        if not self.notebook._find_note(note_id):
            return
        memo = raw_input("Enter a memo: ")
        tags = raw_input("Enter tags: ")
        if memo:
            self.notebook.modify_memo(note_id, memo)
        if tags:
            self.notebook.modify_tags(note_id, tags)

    def quit(self):
        print "Thanks for using your notebook today."
        sys.exit()
Exemple #3
0
 def __init__(self):
     self.notebook = Notebook()
     self.choices = {"1": self.show_notes,
                     "2": self.search_notes, 
                     "3": self.add_note,
                     "4": self.modify_note,
                     "5": self.quit
                     }
Exemple #4
0
class Menu:
    '''Display a menu and respond to choices when run.'''
    def __init__(self):
        self.notebook = Notebook()
        self.choices = {
            "1": self.show_notes,
            "2": self.search_notes,
            "3": self.add_note,
            "4": self.modify_note,
            "5": self.quit
            }
    def display_menu(self):
        print("""
Notebook Menu
1. Show all Notes
2. Search Notes
3. Add Note
4. Modify Note
5. Quit
""")
    def run(self):
        '''Display the menu and respond to choices.'''
        while True:
            self.display_menu()
            choice = input("Enter an option: ")
            action = self.choices.get(choice)
            if action:
                action()
            else:
                print("{0} is not a valid choice".format(choice))

    def show_notes(self, notes=None):
        if not notes:
            notes = self.notebook.notes
            for note in notes:
                print("{0}: {1}\n{2}".format(
                    note.id, note.tags, note.memo))

    def search_notes(self):
        filter = input("Search for: ")
        notes = self.notebook.search(filter)
        self.show_notes(notes)

    def add_note(self):
        memo = input("Enter a memo: ")
        self.notebook.new_note(memo)
        print("Your note has been added.")

    def modify_note(self):
        id = input("Enter a note id: ")
        memo = input("Enter a memo: ")
        tags = input("Enter tags: ")
        if memo:
            self.notebook.modify_memo(id, memo)
        if tags:
            self.notebook.modify_tags(id, tags)

    def quit(self):
        print("Thank you for using your notebook today.")
        sys.exit(0)
Exemple #5
0
class Menu:
    def __init__(self):
        self.notebook = Notebook()
        self.choices = {
                "1": self.show_notes,
                "2": self.search_notes,
                "3": self.add_note,
                "4": self.modify_note,
                "5": self.quit
                }

    def display_menu(self):
        print ("""
                 Notebook Menu 
                   1. Show all Notes
                   2. Search Notes
                   3. Add Note
                   4. Modify Note
                   5. Quit """)

    def run(self):
        while True:
            self.display_menu()
            choice = input("enter an option: ")
            action = self.choice.get(choice)
            if action:
                action()
            else:
                print ("{0} is not a not valid".format(choice))

    def show_notes(self, notes=None):
        if not notes:
            notes = self.notebook.notes
        for note in notes:
            print ("%d: %s\n%s", % (note.id, note.tags, note.memo))

    def search_notes(self):
        title = input("search for: ")
        notes = self.notebook.lookin(title)
        self.show_notes(notes)


    def add_notes(self):
        memo = input("Enter a memo: ")
        self.notebook.new_note(memo)
        print ("you note added. ")

    def modify_note(self):
        id = input("enter note id: ")
        memo = input("enter a memo: ")
        tags = input("enter tags: ")
        if memo:
            self.notebook.modify_memo(id, memo)
        if tags:
            self.notebook.modify_tags(id, tags)


    def quit(self):
        print ("thanks! ")
        sys.exit(0)
Exemple #6
0
	def __init__(self):
		self.notebook = Notebook()
		self.choices = {
			'1': self.show_notes,
			'2': self.search_notes,
			'3': self.add_notes,
			'4': self.modify_notes,
			'5': self.quit
		}
 def __init__(self):
     self.notebook = Notebook()
     # Map strings to functions
     self.choices = {
         "1": self.show_notes,
         "2": self.search_notes,
         "3": self.add_note,
         "4": self.modify_note,
         "5": self.quit}
Exemple #8
0
 def __init_ctrls(self, prnt):
     wx.Panel.__init__(self, id=-1, name=u'Panel', parent=prnt,
                       style=wx.TAB_TRAVERSAL)
     self.notebook = Notebook(self, main)
     self.insertToolsPanel = insertTools.Panel(self.notebook, main)
     self.notebook.init_pages(self.insertToolsPanel,
                              _(u"Insert settings"), u'insert.ico')
     self.numberingPanel = self.notebook.numbering
     self.dateTimePanel = self.notebook.dateTime
Exemple #9
0
 	def __init__(self):
 		self.notebook = Notebook()
 		self.choices = {

 			1: self.show_notes,
 			2: self.search_notes,
 			3: self.add_note,
 			4: self.modify_note,
 			5: self.quit
 		}
Exemple #10
0
	def handler(self, message):
		command = message.get('command')
		print 'Handling bibliography command %s %s'%(command, datetime.datetime.now().strftime("%H:%M:%S.%f"))
		if message.get('sub_type') in ('notebook'):
			nb = Notebook(self.resource, self.render)
			result = nb.handler(message)
				
		elif command in ('parse_bibstring'):
			result = Translator(None).string_reader(message.get('bibstring', ''), count=message.get('count', 10000))
			
		elif command in ('save_bibnote'):
			result = self.save_bibnote(message.get('file'), message)
			
		elif command in ('save_bibtex'):
			result = self.save_bibtex(message.get('file', '').replace('.bibnote', '.bib'), message)
		
		elif command in ('save_html'):
			result = self.save_html(message.get('file'), message)
					
		elif command in ('save_and_load'):
			try:
				nb = Notebook(self.resource, self.render)
				nb.save_notebook(message, message.get('file'))
				result = nb.render_docmain(message.get('new_notebook'))
				result['success'] = 'success'
			except:
				result = {'success' : 'failed to load file %s'%(message.get('file'))}
			
		else: 
			result = {'success': 'undefined command: %s'%(command)}
			
		print 'Returning from bibliography command %s %s'%(command, datetime.datetime.now().strftime("%H:%M:%S.%f"))
		return result
Exemple #11
0
	def __init__(self):
		self.notebook = Notebook()
		self.choices = OrderedDict.fromkeys('12345')
		self.choices['1'] = {'display': 'Show notes',
							 'handler': self.show_notes}
		self.choices['2'] = {'display': 'Search notes',
							 'handler': self.search_notes}
		self.choices['3'] = {'display': 'Add notes',
							 'handler': self.add_note}
		self.choices['4'] = {'display': 'Modify notes',
							 'handler': self.modify_note}
		self.choices['5'] = {'display': 'Quit',
							 'handler': self.quit}
Exemple #12
0
class Menu:
    '''
    Display menu and respond to choices
    when run
    '''
    def __init__(self):
        self.notebook = Notebook()
        self.choices = {
            "1": self.show_notes,
            "2": self.search_notes,
            "3": self.add_note,
            "4": self.modify_note,
            "5": self.quit
        }

    def display_menu(self):
        print("""
Notebook Menu

1. Show all Notes
2. Search Notes
3. Add Note
4. Modify Note
5. Quit
""")

    def run(self):
        '''
        Display menu and respond to choices
        '''
        while True:
            self.display_menu()
            choice = input("Enter an option: ")
            action = self.choices.get(choice)
            if action:
                action()
            else:
                print(f"{choice} is not a valid choice")

    def show_notes(self, notes=None):
        '''
        Parameters
        ----------
        notes : list
            list of notes
        '''
        if not notes:
            notes = self.notebook.notes

        for note in notes:
            print(f"\n3{note.id}: {note.tags}\n{note.memo}")

    def search_notes(self):
        '''
        Search for a note
        '''
        filter = input("Search for: ")
        notes = self.notebook.search(filter)

        self.show_notes(notes)

    def add_note(self):
        '''
        Add note to the notebook
        '''
        memo = input("Enter a memo: ")
        self.notebook.new_note(memo)

        print("Your note has been added.")

    def modify_note(self):
        '''
        Modify given note
        '''
        id = input("Enter a note id: ")
        memo = input("Enter a memo: ")
        tags = input("Enter tags: ")

        if memo:
            self.notebook.modify_memo(id, memo)
        if tags:
            self.notebook.modify_tags(id, tags)

    def quit(self):
        '''
        Quit program
        '''
        print("Thank you for using your notebook today.")

        sys.exit(0)
Exemple #13
0
class Menu(object):
    """
    Display a menu and respond to choices when run.
    """
    def __init__(self):
        self.notebook = Notebook()
        self.choices = {
            "1": self.show_notes,
            "2": self.search_notes,
            "3": self.add_note,
            "4": self.modify_note,
            "5": self.quit
        }

    def display_menu(self):
        print(
            "\nNotebook Menu\n1. Show all Notes\n2. Search Notes\n3. Add Note\n4. Modify Note\n5. Quit\n"
        )

    def run(self):
        """
        Display the menu and respond to choices.
        """
        while True:
            self.display_menu()
            choice = input("Enter an option: ")
            action = self.choices.get(choice)
            if action:
                action()
            else:
                print("{0} is not a valid choice".format(choice))

    def show_notes(self, notes=None):
        if not notes:
            notes = self.notebook.notes
        for note in notes:
            print("{0}: {1}\n{2}".format(note.id, note.tags, note.memo))

    def search_notes(self):
        filter = input("Search for: ")
        notes = self.notebook.search(filter)
        self.show_notes(notes)

    def add_note(self):
        memo = input("Enter a memo: ")
        self.notebook.new_note(memo)
        print("Your note has been added.")

    def modify_note(self):
        id = input("Enter a note id: ")
        memo = input("Enter a memo: ")
        tags = input("Enter tags: ")
        if memo:
            result = self.notebook.modify_memo(id, memo)
            if result:
                if tags:
                    self.notebook.modify_tags(id, tags)
            else:
                print("Error. Such note doesn't exist.")

    def quit(self):
        print("Thank you for using your notebook today.")
        sys.exit(0)
Exemple #14
0
class Menu:
    '''Display a menu and respond to choices when run.'''
    def __init__(self):
        """
        Takes one parameter: the menu.
        """
        self.notebook = Notebook()
        self.choices = {
            "1": self.show_notes,
            "2": self.search_notes,
            "3": self.add_note,
            "4": self.modify_note,
            "5": self.quit
        }

    def display_menu(self):
        """
        Displays the menu.
        """
        print("""
        Notebook Menu
        1. Show all Notes
        2. Search Notes
        3. Add Note
        4. Modify Note
        5. Quit
        """)

    def run(self):
        '''Display the menu and respond to choices.'''
        while True:
            self.display_menu()
            choice = input("Enter an option: ")
            action = self.choices.get(choice)
            if action:
                action()
            else:
                print("{0} is not a valid choice".format(choice))

    def show_notes(self, notes=None):
        """
        Function shows notes.
        """
        if not notes:
            notes = self.notebook.notes

        for note in notes:
            print("{0}: {1}\n{2}".format(note.id, note.tags, note.memo))

    def search_notes(self):
        """
        Function searches for notes.
        """

        filter = input("Search for: ")
        notes = self.notebook.search(filter)
        self.show_notes(notes)

    def add_note(self):
        """
        Function adds notes.
        """
        memo = input("Enter a memo: ")
        self.notebook.new_note(memo)
        print("Your note has been added.")

    def modify_note(self):
        """
        Function modifies notes.
        """
        id = input("Enter a note id: ")
        memo = input("Enter a memo: ")
        tags = input("Enter tags: ")
        if memo:
            self.notebook.modify_memo(id, memo)
        if tags:
            self.notebook.modify_tags(id, tags)

    def quit(self):
        """
        Function quits the program with a message.
        """
        print("Thank you for using your notebook today.")
        sys.exit(0)
Exemple #15
0
class Menu:
    """Display a menu and respond to choises when run."""

    def __init__(self):
        self.notebook = Notebook()
        self.choises = {
            "1": self.show_notes,
            "2": self.search_notes,
            "3": self.add_note,
            "4": self.modify_note,
            "5": self.quit
        }
    
    def display_menu(self):
        print(
            """
            Notebook Menu

            1. Show All Notes 
            2. Search Notes 
            3. Add Note 
            4. Modify Note 
            5. Quit

            """
        )
    
    def run(self):
        """Display the menu and respond to choises. """
        while True:
            self.display_menu()
            choise = input("Enter a choise: ")
            action = self.choises.get(choise)
            if action:
                action()
            else:
                print("{0} is not a valid choise.".format(choise))
    
    def show_notes(self, notes = None):
        if not notes:
            notes = self.notebook.notes
        for note in notes:
            print("{0}: {1}\n{2}".format(note.id, note.tags, note.memo))
    
    def search_notes(self):
        filter = input("Search For: ")
        notes = self.notebook.search(filter)
        self.show_notes(notes)
    
    def add_note(self):
        memo = input("Enter a memo: ")
        self.notebook.new_note(memo)
        print("Your note has been added")
    
    def modify_note(self):
        id = input("Enter a note id: ")
        memo = input("Enter a memo: ")
        tags = input("Enter tags: ")
        if memo: 
            self.notebook.modify_memo(id, memo)
        if tags:
            self.notebook.modify_tags(id, tags)
    
    def quit(self):
        print("Exiting")
        sys.exit(0)
Exemple #16
0
class Window(gtk.Window):
	__gsignals__ = { 'active_tab_changed' : (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (Tab,)) }

	def __init__(self):
		super(type(self), self).__init__()
		debug(DEBUG_WINDOW)

		self._active_tab = None
		self._num_tabs = 0
		self._removing_tabs = False
		self._state = WINDOW_STATE_NORMAL
		self._dispose_has_run = False
		self._fullscreen_controls = None
		self._fullscreen_animation_timeout_id = 0

		#TODO
		#self._message_bus = MessageBus()

		self._window_group = gtk.WindowGroup()
		self._window_group.add_window(self)

		main_box = gtk.VBox(False, 0)
		self.add(main_box)
		main_box.show()

		# Add menu bar and toolbar bar
		self.create_menu_bar_and_toolbar(main_box)

		# Add status bar
		self.create_statusbar(main_box)

		# Add the main area
		debug_message(DEBUG_WINDOW, "Add main area")
		self._hpaned = gtk.HPaned()
		main_box.pack_start(self._hpaned, True, True, 0)

		self._vpaned = gtk.VPaned()
		self._hpaned.pack2(self._vpaned, True, False)
		
		debug_message(DEBUG_WINDOW, "Create taluka notebook")
		self._notebook = Notebook()
		self.add_notebook(self._notebook)

		# side and bottom panels
	  	self.create_side_panel()
		self.create_bottom_panel()

		# panes' state must be restored after panels have been mapped,
		# since the bottom pane position depends on the size of the vpaned.
		self._side_panel_size = prefs_manager_get_side_panel_size()
		self._bottom_panel_size = prefs_manager_get_bottom_panel_size()

		self._hpaned.connect_after("map", self.hpaned_restore_position)
		self._vpaned.connect_after("map", self.vpaned_restore_position)

		self._hpaned.show()
		self._vpaned.show()

		# Drag and drop support, set targets to None because we add the
		# default uri_targets below
		self.drag_dest_set(gtk.DEST_DEFAULT_MOTION | gtk.DEST_DEFAULT_HIGHLIGHT | gtk.DEST_DEFAULT_DROP, (), gtk.gdk.ACTION_COPY)

		# Add uri targets
		tl = self.drag_dest_get_target_list()
	
		if tl == None:
			tl = ()
			self.drag_dest_set_target_list(tl)

		tl += (TARGET_URI_LIST,)

		# connect instead of override, so that we can
		# share the cb code with the view TODO
#		self.connect("drag_data_received", drag_data_received_cb)

		# we can get the clipboard only after the widget
		# is realized TODO
#		self.connect("realize", window_realized)
#		self.connect("unrealize", window_unrealized)

		# Check if the window is active for fullscreen TODO
#		self.connect("notify::is-active", check_window_is_active)

		debug_message(DEBUG_WINDOW, "Update plugins ui")
	
#		plugins_engine_get_default().activate_plugins(self) TODO

		# set visibility of panes.
		# This needs to be done after plugins activatation TODO
#		self.init_panels_visibility()

#		self.update_sensitivity_according_to_open_tabs() TODO

		debug_message(DEBUG_WINDOW, "END")
		
#		self._action_group = gtk.ActionGroup("ExamplePyPluginActions")
#		self._action_group.add_actions(
#		                               [
#		                                ("File", None, "File", None, None, None),
#		                                ("FileNew", gtk.STOCK_NEW, None, None, None, commands._file_new),
#		                                ("FileOpen", gtk.STOCK_OPEN, None, None, None, commands._file_open),
#		                                ("FileSave", gtk.STOCK_SAVE, None, None, None, commands._file_save),
#		                                ("FileSaveAs", gtk.STOCK_SAVE_AS, None, "<shift><control>S",
#		                                 "Save the current file with a different name", commands._file_save_as),
#		                                ("FileClose", gtk.STOCK_CLOSE, None, None, None, commands._file_close),
#		                                ("FileQuit", gtk.STOCK_QUIT, None, None, None, commands._file_quit),
#		                                ("Edit", None, "Edit", None, None, None),
#		                                ("EditUndo", gtk.STOCK_UNDO, None, "<control>Z", None, commands._edit_undo),
#		                                ("EditRedo", gtk.STOCK_REDO, None, "<shift><control>Z", None, commands._edit_redo),
#		                                ("EditCut", gtk.STOCK_CUT, None, None, None, commands._edit_cut),
#		                                ("EditCopy", gtk.STOCK_COPY, None, None, None, commands._edit_copy),
#		                                ("EditPaste", gtk.STOCK_PASTE, None, None, None, commands._edit_paste),
#		                                ("EditSelectAll", gtk.STOCK_SELECT_ALL, None, None, None, commands._edit_select_all)
#		                               ],
#		                               self
#		                              )
#		
#		self._ui_manager = gtk.UIManager()
#		self._ui_manager.add_ui_from_file(os.path.join(reloc.DATADIR, 'taluka/taluka-ui.xml'))
#		self._ui_manager.insert_action_group(self._action_group, -1)
#		
#		vbox = gtk.VBox()
#		
#		self._menubar = self._ui_manager.get_widget("/MenuBar")
#		vbox.pack_start(self._menubar, expand=False)
#		
#		self._toolbar = self._ui_manager.get_widget("/ToolBar")
#		assert self._toolbar != None
#		vbox.pack_start(self._toolbar, expand=False)
#		
#		hpaned = gtk.HPaned()
#		
#		self._side_panel = Panel()
#		hpaned.pack1(self._side_panel, False, False)
#		
#		vpaned = gtk.VPaned()
#		self._notebook = Notebook()
#		vpaned.pack1(self._notebook, True, False)
#		
#		self._bottom_panel = Panel()
#		vpaned.pack2(self._bottom_panel, False, False)
#		
#		hpaned.pack2(vpaned, True, False)
#		
#		vbox.add(hpaned)
#		
#		self.add(vbox)
#		
#		self.connect("delete_event", self.on_delete_event)
#		self.connect("destroy", self.on_destroy)
#		self.show_all()
#		
#		#	static gboolean is_first = True;
#		#	GtkWidget *main_box;
#		#	GtkTargetList *tl;

#		debug(DEBUG_WINDOW)

#		#	window->priv = GEDIT_WINDOW_GET_PRIVATE (window);
#		
#		self._active_tab = None
#		
#		#	self._num_tabs = 0;
#		#	self._removing_tabs = FALSE;
#		self._state = WINDOW_STATE_NORMAL;
#		#	self._destroy_has_run = FALSE;

#		self._window_group = gtk.WindowGroup()
#		self._window_group.add_window(self)

#		#	main_box = gtk_vbox_new (FALSE, 0);
#		#	gtk_container_add (GTK_CONTAINER (window), main_box);
#		#	gtk_widget_show (main_box);

#		#	/* Add menu bar and toolbar bar */
#		#	create_menu_bar_and_toolbar (window, main_box);

#		#	/* Add status bar */
#		#	create_statusbar (window, main_box);

#		#	/* Add the main area */
#		#	gedit_debug_message (DEBUG_WINDOW, "Add main area");		
#		#	self._hpaned = gtk_hpaned_new ();
#		#  	gtk_box_pack_start (GTK_BOX (main_box), 
#		#  			    self._hpaned, 
#		#  			    True, 
#		#  			    True, 
#		#  			    0);

#		#	self._vpaned = gtk_vpaned_new ();
#		#  	gtk_paned_pack2 (GTK_PANED (self._hpaned), 
#		#  			 self._vpaned, 
#		#  			 True, 
#		#  			 FALSE);
#		#  	
#		#	gedit_debug_message (DEBUG_WINDOW, "Create gedit notebook");
#		#	self._notebook = gedit_notebook_new ();
#		#  	gtk_paned_pack1 (GTK_PANED (self._vpaned), 
#		#  			 self._notebook,
#		#  			 True, 
#		#  			 True);
#		#  	gtk_widget_show (self._notebook);  			 

#		#	/* side and bottom panels */
#		#  	create_side_panel (window);
#		#	create_bottom_panel (window);

#		#	/* restore paned positions as soon as we know the panes allocation.
#		#	 * This needs to be done only for the first window, the successive
#		#	 * windows are created by cloning the first one */
#		#	if (is_first)
#		#	{
#		#		is_first = FALSE;

#		#		self._side_panel_size = gedit_prefs_manager_get_side_panel_size ();
#		#		self._bottom_panel_size = gedit_prefs_manager_get_bottom_panel_size ();
#		#		g_signal_connect_after (self._hpaned,
#		#					"map",
#		#					G_CALLBACK (hpaned_restore_position),
#		#					window);
#		#		g_signal_connect_after (self._vpaned,
#		#					"map",
#		#					G_CALLBACK (vpaned_restore_position),
#		#					window);
#		#	}

#		#	gtk_widget_show (self._hpaned);
#		#	gtk_widget_show (self._vpaned);

#		#	/* Drag and drop support, set targets to NULL because we add the
#		#	   default uri_targets below */
#		#	gtk_drag_dest_set (GTK_WIDGET (window),
#		#			   GTK_DEST_DEFAULT_MOTION |
#		#			   GTK_DEST_DEFAULT_HIGHLIGHT |
#		#			   GTK_DEST_DEFAULT_DROP,
#		#			   NULL,
#		#			   0,
#		#			   GDK_ACTION_COPY);

#		#	/* Add uri targets */
#		#	tl = gtk_drag_dest_get_target_list (GTK_WIDGET (window));
#		#	
#		#	if (tl == NULL)
#		#	{
#		#		tl = gtk_target_list_new (NULL, 0);
#		#		gtk_drag_dest_set_target_list (GTK_WIDGET (window), tl);
#		#		gtk_target_list_unref (tl);
#		#	}
#		#	
#		#	gtk_target_list_add_uri_targets (tl, TARGET_URI_LIST);

#		# Connect signals
#		self._notebook.connect("switch_page", notebook_switch_page, self)
#		
#		#	g_signal_connect (self._notebook,
#		#			  "tab_added",
#		#			  G_CALLBACK (notebook_tab_added),
#		#			  window);
#		#	g_signal_connect (self._notebook,
#		#			  "tab_removed",
#		#			  G_CALLBACK (notebook_tab_removed),
#		#			  window);
#		#	g_signal_connect (self._notebook,
#		#			  "tabs_reordered",
#		#			  G_CALLBACK (notebook_tabs_reordered),
#		#			  window);			  
#		#	g_signal_connect (self._notebook,
#		#			  "tab_detached",
#		#			  G_CALLBACK (notebook_tab_detached),
#		#			  window);
#		#	g_signal_connect (self._notebook,
#		#			  "tab_close_request",
#		#			  G_CALLBACK (notebook_tab_close_request),
#		#			  window);
#		#	g_signal_connect (self._notebook,
#		#			  "button-press-event",
#		#			  G_CALLBACK (notebook_button_press_event),
#		#			  window);
#		#	g_signal_connect (self._notebook,
#		#			  "popup-menu",
#		#			  G_CALLBACK (notebook_popup_menu),
#		#			  window);

#		#	/* connect instead of override, so that we can
#		#	 * share the cb code with the view */
#		#	g_signal_connect (window,
#		#			  "drag_data_received",
#		#	                  G_CALLBACK (drag_data_received_cb), 
#		#	                  None)

#		#	/* we can get the clipboard only after the widget
#		#	 * is realized */
#		#	g_signal_connect (window,
#		#			  "realize",
#		#			  G_CALLBACK (window_realized),
#		#			  None)
#		#	g_signal_connect (window,
#		#			  "unrealize",
#		#			  G_CALLBACK (window_unrealized),
#		#			  None)

#		#	gedit_debug_message (DEBUG_WINDOW, "Update plugins ui");
#		#	gedit_plugins_engine_update_plugins_ui (gedit_plugins_engine_get_default (),
#		#						window, True);

#		#	/* set visibility of panes.
#		#	 * This needs to be done after plugins activatation */
#		#	init_panels_visibility (window);

#		#	gedit_debug_message (DEBUG_WINDOW, "END");
#		self.create_tab(True)

		self.show() # FIXME: Remove this file and use something like gedit-session.c instead.

	def add_notebook(self, notebook):
		self._vpaned.pack1(notebook, True, True)
		notebook.show()
		self.connect_notebook_signals(notebook)

	def	init_panels_visibility(self):
		debug(DEBUG_WINDOW)

		# side pane
		active_page = prefs_manager_get_side_panel_active_page()
		self._side_panel._set_active_item_by_id(active_page)

		if prefs_manager_get_side_pane_visible():
			self._side_panel.show()

#TODO:
#		/* bottom pane, it can be empty */
#		if (gedit_panel_get_n_items (GEDIT_PANEL (window->priv->bottom_panel)) > 0)
#		{
#			active_page = gedit_prefs_manager_get_bottom_panel_active_page ();
#			_gedit_panel_set_active_item_by_id (GEDIT_PANEL (window->priv->bottom_panel),
#								active_page);

#			if (gedit_prefs_manager_get_bottom_panel_visible ())
#			{
#				gtk_widget_show (window->priv->bottom_panel);
#			}
#		}
#		else
#		{
#			GtkAction *action;
#			action = gtk_action_group_get_action (window->priv->panes_action_group,
#								  "ViewBottomPane");
#			gtk_action_set_sensitive (action, FALSE);
#		}

#		/* start track sensitivity after the initial state is set */
#		window->priv->bottom_panel_item_removed_handler_id =
#			g_signal_connect (window->priv->bottom_panel,
#					  "item_removed",
#					  G_CALLBACK (bottom_panel_item_removed),
#					  window);

#		g_signal_connect (window->priv->bottom_panel,
#				  "item_added",
#				  G_CALLBACK (bottom_panel_item_added),
#				  window);
#	}

	def on_delete_event(self, widget, event, data=None):
		return False

	def create_tab(self, jump_to):
		tab = Tab()
		tab.show()
		self._notebook.add_tab(tab, -1, jump_to)
		return tab

	def create_tab_from_uri(self, uri, encoding, line_pos, create, jump_to):
		if uri == None:
			return None
		
		tab = tab_new_from_uri(uri, encoding, line_pos, create)
		if tab == None:
			return None

		tab.show()

		self._notebook.add_tab(tab, -1, jump_to)
		
		return tab
	
	def close_tab(self, tab):
		if tab.get_state() == TAB_STATE_SAVING or tab.get_state() == TAB_STATE_SHOWING_PRINT_PREVIEW:
			return
		self._notebook.remove_tab(tab)

	def close_all_tabs(self):
		if self._state & WINDOW_STATE_SAVING or self._state & WINDOW_STATE_SAVING_SESSION:
			return
		self._removing_tabs = True
		self._notebook.remove_all_tabs()
		self._removing_tabs = False

	def get_active_tab(self):
		return self._active_tab

	def get_documents(self):
		documents = []
		for i in range(self._notebook.get_n_pages()):
			documents.append(self._notebook.get_nth_page(i))
		return documents
	
	def get_unsaved_documents(self):
		unsaved_docs = []
		tabs = self._notebook.get_children()
		for tab in tabs:
			if not tab._can_close():
				unsaved_docs.append(tab.get_document())
		return unsaved_docs
	
	def get_views(self):
		return None
	
	def get_group(self):
		return self._window_group
	
	def get_side_panel(self):
		return self._side_panel
	
	def get_bottom_panel(self):
		return self._bottom_panel
	
	def get_statusbar(self):
		return self._statusbar
	
	def get_ui_manager(self):
		return self._ui_manager
	
	def get_state(self):
		return self._state
	
	def get_tab_from_uri(self, uri):
		return None
		
	def on_destroy(self, widget):
		gtk.main_quit()
	
	def on_about(self, data):
		self.abt.show_all()
		self.abt.run()
		self.abt.hide_all()
	
	def on_build_activate(self, data):
		pass
		
	def on_file_open(self, data):
		filechooser = gtk.FileChooserDialog(title="Choose File", action=gtk.FILE_CHOOSER_ACTION_OPEN, buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
		filechooser.set_transient_for(self)
		response = filechooser.run()
		if response == gtk.RESPONSE_OK:
			file = filechooser.get_filename()
		else:
			file = None
		filechooser.destroy()
		
		if file != None:
			self.create_tab_from_uri(urllib.unquote(file), None, 0, False, True)

	def on_new_project(self, widget):
		self.newproject = NewProject(self)
	
	def on_open_project(self, widget):
		filechooser = gtk.FileChooserDialog(title="Choose Project File", action=gtk.FILE_CHOOSER_ACTION_OPEN, buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
		filter = gtk.FileFilter()
		filter.set_name("Taluka Project Files")
		filter.add_pattern("*.taluka")
		filechooser.add_filter(filter)
		filter = gtk.FileFilter()
		filter.set_name("All Files")
		filter.add_pattern("*")
		filechooser.add_filter(filter)

		filechooser.set_current_folder(os.environ["HOME"])

		filechooser.set_transient_for(self.window)
		
		response = filechooser.run()
		if response == gtk.RESPONSE_OK:
			file = filechooser.get_filename()
		else:
			file = None
		filechooser.destroy()
		
		if file != None:
			p = project.Project(self)
			p.filename = urllib.unquote(file)
			p.open()
	
	def on_save_project(self, widget):
		self.active_project.save()
	
	def on_save_file(self, data):
		self.get_current_file().save()

	def on_close_file(self, data):
		if self.get_current_file().can_close():
			self.get_current_file().close()
	
	def get_current_file(self):
		return self._notebook.get_nth_page(self._notebook.get_current_page())

	def get_current_scrolledwindow(self):
		return self.get_current_file()
		
	def get_bottom_notebook(self):
		return self.glade.get_widget('notebook3')
	
	def get_active_document(self):
		self._notebook.get_current_page()
	
	def get_bottom_panel(self):
		return self._bottom_panel

	def on_cut(self, widget):
		buffer = self.get_current_scrolledwindow().get_child().get_buffer()
		if buffer != None:
			buffer.cut_clipboard(gtk.Clipboard(), True)

	def on_copy(self, widget):
		buffer = self.get_current_scrolledwindow().get_child().get_buffer()
		if buffer != None:
			buffer.copy_clipboard(gtk.Clipboard())

	def on_paste(self, widget):
		buffer = self.get_current_scrolledwindow().get_child().get_buffer()
		if buffer != None:
			buffer.paste_clipboard(gtk.Clipboard(), None, True)
	
	def get_default_path(self):
		return "/home/jhasse" # FIXME: Don't use this path!
	
	def file_save(self, tab, window):
		assert tab != None
		assert window != None

		doc = tab.get_document()
		assert doc != None

		if doc.is_untitled() or doc.get_readonly():
			self.file_save_as(tab, window)
			return
		
		uri_for_display = doc.get_uri_for_display()
		
		self._statusbar.flash_message(self._generic_message_cid, "Saving file '%s'\342\200\246" % uri_for_display)
		
		tab.save()
			

# 		gtk.window_set_default_icon_from_file(os.path.join(reloc.DATADIR, 'pixmaps/taluka.png'))
# 		self.glade = gtk.glade.XML(os.path.join(reloc.DATADIR, 'taluka/main.glade'))
# 		self.glade.signal_autoconnect(self)
# 		self.window = self.glade.get_widget('window1')
# 		self._notebook = self.glade.get_widget('notebook_files')
# 		assert self._notebook != None
# 		
# 		self.abt = gtk.AboutDialog()

# 		self.abt.set_name(PROGRAM_NAME)
# 		self.abt.set_version(PROGRAM_VERSION)
# 		self.abt.set_comments("Taluka is a simple C/C++/Python IDE written in PyGTK.")
# 		self.abt.set_authors(["Jan Niklas Hasse <*****@*****.**>", "Jannes Meyer <*****@*****.**>", "Fabian Franzen <*****@*****.**>"])
# 		self.abt.set_copyright("Copyright © 2007 watteimdocht.de")
# 		gtk.about_dialog_set_url_hook(lambda dialog, url: url_show(url))
# 		gtk.about_dialog_set_email_hook(lambda dialog, email: url_show('mailto:'+email))
# 		self.abt.set_website("http://www.watteimdocht.de/index_Taluka.php")
# 		self.abt.set_website_label("Taluka Homepage")
# 		
# 		self.manager = project.Manager(self)
# 		
# 		self.active_project = None
# 		
# 		start_here = self.glade.get_widget("start_tab_event") # TODO: Don't use a EventBox
# 		# geht nicht: start_here.set_events(gtk.gdk.BUTTON_PRESS_MASK)
# 		start_here.connect("button-press-event", self.on_tab_click, 0)
# 		
# 		self._bottom_panel = Panel(self)
# 	
# 	def on_tab_click(self, widget, event, tab_index):
# 		if event.button == 2:
# 			self._notebook.remove_page(tab_index)
# 		elif event.button == 3:
# 			print "Kontextmenü"
	def set_title(self):
		# TODO: This function may be improved. Should display project name
		
		if self._active_tab == None:
			super(type(self), self).set_title("Taluka IDE")
			return
			
		doc = self._active_tab.get_document()
		
		name = doc.get_short_name_for_display()
		
		super(type(self), self).set_title("%s - Taluka IDE" % name)

	def get_active_view(self):
		if self._active_tab == None:
			return None
		return self._active_tab.get_view()

	def set_active_tab(self, tab):
		page_num = self._notebook.page_num(tab)
		if page_num == -1:
			return
		self._notebook.set_current_page(page_num)
	
	def update_recent_files_menu(self): # TODO
		pass

	def set_sensitivity_according_to_tab(self, tab):
		# TODO: Implement all of this
		
		debug(DEBUG_WINDOW)

		lockdown = app_get_default().get_lockdown()

#		state = gedit_tab_get_state (tab);
#		state_normal = (state == GEDIT_TAB_STATE_NORMAL);

#		view = gedit_tab_get_view (tab);
#		editable = gtk_text_view_get_editable (GTK_TEXT_VIEW (view));

#		doc = GEDIT_DOCUMENT (gtk_text_view_get_buffer (GTK_TEXT_VIEW (view)));

#		clipboard = gtk_widget_get_clipboard (GTK_WIDGET (window),
#							  GDK_SELECTION_CLIPBOARD);

#		action = gtk_action_group_get_action (self._action_group,
#							  "FileSave");
#		gtk_action_set_sensitive (action,
#					  (state_normal ||
#					   (state == GEDIT_TAB_STATE_EXTERNALLY_MODIFIED_NOTIFICATION) ||
#					   (state == GEDIT_TAB_STATE_SHOWING_PRINT_PREVIEW)) &&
#					  !gedit_document_get_readonly (doc) &&
#					  !(lockdown & GEDIT_LOCKDOWN_SAVE_TO_DISK));

#		action = gtk_action_group_get_action (self._action_group,
#							  "FileSaveAs");
#		gtk_action_set_sensitive (action,
#					  (state_normal ||
#					   (state == GEDIT_TAB_STATE_EXTERNALLY_MODIFIED_NOTIFICATION) ||
#					   (state == GEDIT_TAB_STATE_SHOWING_PRINT_PREVIEW)) &&
#					  !(lockdown & GEDIT_LOCKDOWN_SAVE_TO_DISK));

#		action = gtk_action_group_get_action (self._action_group,
#							  "FileRevert");
#		gtk_action_set_sensitive (action,
#					  (state_normal ||
#					   (state == GEDIT_TAB_STATE_EXTERNALLY_MODIFIED_NOTIFICATION)) &&
#					  !gedit_document_is_untitled (doc));

#		action = gtk_action_group_get_action (self._action_group,
#							  "FilePrintPreview");
#		gtk_action_set_sensitive (action,
#					  state_normal &&
#					  !(lockdown & GEDIT_LOCKDOWN_PRINTING));

#		action = gtk_action_group_get_action (self._action_group,
#							  "FilePrint");
#		gtk_action_set_sensitive (action,
#					  (state_normal ||
#					  (state == GEDIT_TAB_STATE_SHOWING_PRINT_PREVIEW)) &&
#					  !(lockdown & GEDIT_LOCKDOWN_PRINTING));
#					  
#		action = gtk_action_group_get_action (self._action_group,
#							  "FileClose");

#		gtk_action_set_sensitive (action,
#					  (state != GEDIT_TAB_STATE_CLOSING) &&
#					  (state != GEDIT_TAB_STATE_SAVING) &&
#					  (state != GEDIT_TAB_STATE_SHOWING_PRINT_PREVIEW) &&
#					  (state != GEDIT_TAB_STATE_PRINTING) &&
#					  (state != GEDIT_TAB_STATE_PRINT_PREVIEWING) &&
#					  (state != GEDIT_TAB_STATE_SAVING_ERROR));

#		action = gtk_action_group_get_action (self._action_group,
#							  "EditUndo");
#		gtk_action_set_sensitive (action, 
#					  state_normal &&
#					  gtk_source_buffer_can_undo (GTK_SOURCE_BUFFER (doc)));

#		action = gtk_action_group_get_action (self._action_group,
#							  "EditRedo");
#		gtk_action_set_sensitive (action, 
#					  state_normal &&
#					  gtk_source_buffer_can_redo (GTK_SOURCE_BUFFER (doc)));

#		action = gtk_action_group_get_action (self._action_group,
#							  "EditCut");
#		gtk_action_set_sensitive (action,
#					  state_normal &&
#					  editable &&
#					  gtk_text_buffer_get_has_selection (GTK_TEXT_BUFFER (doc)));

#		action = gtk_action_group_get_action (self._action_group,
#							  "EditCopy");
#		gtk_action_set_sensitive (action,
#					  (state_normal ||
#					   state == GEDIT_TAB_STATE_EXTERNALLY_MODIFIED_NOTIFICATION) &&
#					  gtk_text_buffer_get_has_selection (GTK_TEXT_BUFFER (doc)));
#					  
#		action = gtk_action_group_get_action (self._action_group,
#							  "EditPaste");
#		if (state_normal && editable)
#		{
#			set_paste_sensitivity_according_to_clipboard (window,
#									  clipboard);
#		}
#		else
#		{
#			gtk_action_set_sensitive (action, FALSE);
#		}

#		action = gtk_action_group_get_action (self._action_group,
#							  "EditDelete");
#		gtk_action_set_sensitive (action,
#					  state_normal &&
#					  editable &&
#					  gtk_text_buffer_get_has_selection (GTK_TEXT_BUFFER (doc)));

#		action = gtk_action_group_get_action (self._action_group,
#							  "SearchFind");
#		gtk_action_set_sensitive (action,
#					  (state_normal ||
#					   state == GEDIT_TAB_STATE_EXTERNALLY_MODIFIED_NOTIFICATION));

#		action = gtk_action_group_get_action (self._action_group,
#							  "SearchIncrementalSearch");
#		gtk_action_set_sensitive (action,
#					  (state_normal ||
#					   state == GEDIT_TAB_STATE_EXTERNALLY_MODIFIED_NOTIFICATION));

#		action = gtk_action_group_get_action (self._action_group,
#							  "SearchReplace");
#		gtk_action_set_sensitive (action,
#					  state_normal &&
#					  editable);

#		b = gedit_document_get_can_search_again (doc);
#		action = gtk_action_group_get_action (self._action_group,
#							  "SearchFindNext");
#		gtk_action_set_sensitive (action,
#					  (state_normal ||
#					   state == GEDIT_TAB_STATE_EXTERNALLY_MODIFIED_NOTIFICATION) && b);

#		action = gtk_action_group_get_action (self._action_group,
#							  "SearchFindPrevious");
#		gtk_action_set_sensitive (action,
#					  (state_normal ||
#					   state == GEDIT_TAB_STATE_EXTERNALLY_MODIFIED_NOTIFICATION) && b);

#		action = gtk_action_group_get_action (self._action_group,
#							  "SearchClearHighlight");
#		gtk_action_set_sensitive (action,
#					  (state_normal ||
#					   state == GEDIT_TAB_STATE_EXTERNALLY_MODIFIED_NOTIFICATION) && b);

#		action = gtk_action_group_get_action (self._action_group,
#							  "SearchGoToLine");
#		gtk_action_set_sensitive (action,
#					  (state_normal ||
#					   state == GEDIT_TAB_STATE_EXTERNALLY_MODIFIED_NOTIFICATION));
#	
#		action = gtk_action_group_get_action (self._action_group,
#							  "ViewHighlightMode");
#		gtk_action_set_sensitive (action, 
#					  (state != GEDIT_TAB_STATE_CLOSING) &&
#					  gedit_prefs_manager_get_enable_syntax_highlighting ());

#		update_next_prev_doc_sensitivity (window, tab);

#		gedit_plugins_engine_update_plugins_ui (gedit_plugins_engine_get_default (),
#							window, FALSE);
#	}

	def create_languages_menu(self): # TODO
		pass
	
	def set_toolbar_style(self, x):
		pass # TODO: Implement this
	
	def setup_toolbar_open_button(self, toolbar):
		pass # TODO: Implement this
	
	def toolbar_visibility_changed(self):
		pass # TODO: Implement this
	
	def create_statusbar(self, main_box):
		pass # TODO: Implement this
	
	def hpaned_restore_position(self):
		pass # TODO: Implement this
	
	def vpaned_restore_position(self):
		pass # TODO: Implement this

	def create_menu_bar_and_toolbar(self, main_box):
		debug(DEBUG_WINDOW)

		manager = gtk.UIManager()
		self._manager = manager

		self.add_accel_group(manager.get_accel_group())

		action_group = gtk.ActionGroup("TalukaWindowAlwaysSensitiveActions")
		action_group.set_translation_domain("") # TODO: Should it be NULL instead of ""?
		action_group.add_actions(always_sensitive_menu_entries, self)
		action_group.add_toggle_actions(always_sensitive_toggle_menu_entries, self)

		manager.insert_action_group(action_group, 0)
		#g_object_unref (action_group); FIXME: Do i need this?
		self._always_sensitive_action_group = action_group

		action_group = gtk.ActionGroup("TalukaWindowActions")
		action_group.set_translation_domain("") # TODO: Should it be NULL instead of ""?
		action_group.add_actions(menu_entries, self)
		manager.insert_action_group(action_group, 0)
		#g_object_unref (action_group); FIXME see above
		self._action_group = action_group

		# set short labels to use in the toolbar
		action = action_group.get_action("FileSave")
		action.set_property("short_label", _("Save"))
#		action = action_group.get_action("FilePrint") TODO Don't forget to uncomment these lines
#		action.set_property("short_label", _("Print"))
#		action = action_group.get_action("SearchFind")
#		action.set_property("short_label", _("Find"))
#		action = action_group.get_action("SearchReplace")
#		action.set_property("short_label", _("Replace"))

		# set which actions should have priority on the toolbar
		action = action_group.get_action("FileSave")
		action.set_property("is_important", True)
		action = action_group.get_action("EditUndo")
		action.set_property("is_important", True)

		action_group = gtk.ActionGroup("TalukaQuitWindowActions")
		action_group.set_translation_domain("") # TODO: Should it be NULL instead of ""?
		action_group.add_actions(quit_menu_entries, self)

		manager.insert_action_group(action_group, 0)
		#g_object_unref (action_group); FIXME: see above
		self._quit_action_group = action_group

		action_group = gtk.ActionGroup("TalukaCloseWindowActions")
		action_group.set_translation_domain("") # TODO: Should it be NULL instead of ""?
		action_group.add_actions(close_menu_entries, self)

		manager.insert_action_group(action_group, 0)
		#g_object_unref (action_group); FIXME
		self._close_action_group = action_group

		action_group = gtk.ActionGroup("TalukaWindowPanesActions")
		action_group.set_translation_domain("") # TODO: Should it be NULL instead of ""?
		action_group.add_toggle_actions(panes_toggle_menu_entries, self)

		manager.insert_action_group(action_group, 0)
		#g_object_unref (action_group); FIXME
		self._panes_action_group = action_group

		# now load the UI definition
		ui_file = os.path.join(reloc.DATADIR, 'taluka/taluka-ui.xml')
		manager.add_ui_from_file(ui_file)

		# show tooltips in the statusbar
		manager.connect("connect_proxy", connect_proxy_cb, self)
		manager.connect("disconnect_proxy", disconnect_proxy_cb, self)

		# recent files menu
		action_group = gtk.ActionGroup("RecentFilesActions")
		action_group.set_translation_domain("") # TODO: Should it be NULL instead of ""?
		self._recents_action_group = action_group
		manager.insert_action_group(action_group, 0)
		#g_object_unref (action_group); FIXME see above

		recent_manager = gtk.recent_manager_get_default()
		self._recents_handler_id = recent_manager.connect("changed", recent_manager_changed, self)
		self.update_recent_files_menu()

		# languages menu
		action_group = gtk.ActionGroup("LanguagesActions")
		action_group.set_translation_domain("") # TODO: Should it be NULL instead of ""?
		self._languages_action_group = action_group
		manager.insert_action_group(action_group, 0)
		self.create_languages_menu()

		# list of open documents menu
		action_group = gtk.ActionGroup("DocumentsListActions")
		action_group.set_translation_domain("") # TODO: Should it be NULL instead of ""?
		self._documents_list_action_group = action_group
		manager.insert_action_group(action_group, 0)

		self._menubar = manager.get_widget("/MenuBar")
		main_box.pack_start(self._menubar, False, False, 0)

		self._toolbar = manager.get_widget("/ToolBar")
		main_box.pack_start(self._toolbar, False, False, 0)

		self.set_toolbar_style(None)
	
		self._toolbar_recent_menu = self.setup_toolbar_open_button(self._toolbar)

		self._toolbar.foreach(set_non_homogeneus)

		self._toolbar.connect_after("show", self.toolbar_visibility_changed)
		self._toolbar.connect_after("hide", self.toolbar_visibility_changed)
	
	def create_side_panel(self):
		pass # TODO: Implement this
	
	def create_bottom_panel(self):
		pass # TODO: Implement this

	def connect_notebook_signals(self, notebook):
		notebook.connect("switch_page", notebook_switch_page, self)
Exemple #17
0
def convert_file(arg):
    nb = Notebook(arg['input_file'])
    nb.export(arg['output_file'], img_to=arg['media_folder'])
Exemple #18
0
                    os.rmdir(os.path.join(root, name))

            os.rmdir(absolute)
        else:
            os.remove(absolute)

    try:
        make_folder("subdir")

        make_file("worksheet_a.rws")
        make_file("subdir/worksheet_c.rws")

        make_file("library_a.py")
        make_file("subdir/library_b.py")

        notebook = Notebook(notebook_folder)
        file_list = FileList(notebook)

        def expect(*expected_items):
            items = []
            model = file_list.get_model()
            iter = model.get_iter_first()
            while iter:
                depth = len(model.get_path(iter)) - 1
                items.append((">" * depth) + model.get_value(iter, 0).get_text())
                iter = _next_row_depthfirst(model, iter)

            if items != list(expected_items):
                raise AssertionError("Got %s expected %s" % (items, expected_items))

        expect("Worksheets",
Exemple #19
0
class Menu:
    """
    Display a menu and respond to choices when run.
    """
    def __init__(self):
        """
        Initiate a dictionary that maps s strings to functions 
        on the menu object itself.
        """
        self.notebook = Notebook()
        self.choices = {
            "1": self.show_notes,
            "2": self.search_notes,
            "3": self.add_note,
            "4": self.modify_note,
            "5": self.quit
        }

    def display_menu(self):
        """
        Prints Notebook menu
        """
        print("""
Notebook Menu

1. Show all Notes
2. Search Notes
3. Add Note
4. Modify Note
5. Quit
""")

    def run(self):
        """
        Display the menu and respond to choices.
        """
        while True:
            self.display_menu()
            choice = input("Enter an option: ")
            action = self.choices.get(choice)
            if action:
                action()
            else:
                print("{0} is not a valid choice".format(choice))

    def show_notes(self, notes=None):
        """
        Respond to user choise and shows list of notes.
        """
        if not notes:
            notes = self.notebook.notes
        for note in notes:
            print("{0}: {1}\n{2}".format(note.id, note.tags, note.memo))

    def search_notes(self):
        """
        Search for note by id and returns it.
        """
        filter = input("Search for: ")
        notes = self.notebook.search(filter)
        self.show_notes(notes)

    def add_note(self):
        """
        Add a new note to curent list.
        """
        memo = input("Enter a memo: ")
        self.notebook.new_note(memo)
        print("Your note has been added.")

    def modify_note(self):
        """
        Modify chossen by id note.
        """
        id = input("Enter a note id: ")
        memo = input("Enter a memo: ")
        tags = input("Enter tags: ")
        if memo:
            self.notebook.modify_memo(id, memo)
        if tags:
            self.notebook.modify_tags(id, tags)

    def quit(self):
        """
        Finish progarm.
        """
        print("Thank you for using your notebook today.")
        sys.exit(0)
class Menu:
    '''
    Display a menu and respond to choices when run.
    '''
    def __init__(self):
        '''
        Initialize a menu with an empty notebook and available choices.
        '''
        self.notebook = Notebook()
        self.choices = {
            '1': self.show_notes,
            '2': self.search_notes,
            '3': self.add_note,
            '4': self.modify_note,
            '5': self.quit
        }

    def display_menu(self):
        '''
        Display the menu.
        '''
        print('''
Notebook Menu
1. Show all Notes
2. Search Notes
3. Add Note
4. Modify Note
5. Quit''')

    def run(self):
        '''
        Display the menu and respond to choices.
        '''
        while True:
            self.display_menu()
            choice = input('Enter an option: ')
            action = self.choices.get(choice)

            if action:
                action()
            else:
                print('{0} is not a valid choice'.format(choice))

    def show_notes(self, notes=None):
        '''
        Show all notes in a formatted way.
        '''
        if not notes:
            notes = self.notebook.notes

        for note in notes:
            print(f'{note.id}: {note.tags}\n{note.memo}')

    def search_notes(self):
        '''
        Search for notes by filter query.
        '''
        filter_str = input('Search for: ')
        notes = self.notebook.search(filter_str)
        self.show_notes(notes)

    def add_note(self):
        '''
        Add a note to the notebook.
        '''
        memo = input('Enter a memo: ')
        self.notebook.new_note(memo)
        print('Your note has been added.')

    def modify_note(self):
        '''
        Modify note by id if it exists.
        '''
        note_id = input('Enter a note id: ')
        memo = input('Enter a memo: ')
        tags = input('Enter tags: ')

        if memo:
            self.notebook.modify_memo(note_id, memo)

        if tags:
            self.notebook.modify_tags(note_id, tags)

    def quit(self):
        '''
        Stop the script.
        '''
        print('Thank you for using your notebook today.')
        sys.exit(0)
Exemple #21
0
auth.authorizor.add_permission("Show user's Notes")
auth.authorizor.add_permission("Search Notes")
auth.authorizor.add_permission("Add Note")
auth.authorizor.add_permission("Modify Note")

# set admin user
auth.authenticator.add_user("Admin", "qwerty123")

# set all possible rights of admin
auth.authorizor.permit_user("Show all Notes", "Admin")
auth.authorizor.permit_user("Show user's Notes", "Admin")
auth.authorizor.permit_user("Search Notes", "Admin")
auth.authorizor.permit_user("Add Note", "Admin")
auth.authorizor.permit_user("Modify Note", "Admin")

admin_notebook = Notebook()

# set an instance of default user
auth.authenticator.add_user("usual_user", "password123")

# set permission of default user
auth.authorizor.permit_user("Add Note", "usual_user")
auth.authorizor.permit_user("Show user's Notes", "usual_user")
auth.authorizor.permit_user("Search Notes", "usual_user")
auth.authorizor.permit_user("Modify Note", "usual_user")

default_user_notebook = Notebook()

notebooks_dict = {"Admin": admin_notebook, "user": default_user_notebook}

Exemple #22
0
from notebook import Notebook

border = "--------------------"
note = Notebook()

while True:
    print(border)
    print("数字を入力し操作したい項目を選択して下さい")
    choice = int(
        input(border + "\n1: 単語を登録する\n2: 登録した単語をキーワードで検索する\n0: 操作を終了する\n"))
    if choice == 1:
        note.regist()
    elif choice == 2:
        if not note.word_dict:
            print(border)
            print("まだ登録がありません")
        else:
            print(border)
            note.search()
    elif choice == 0:
        print("プログラムを終了します")
        break
    else:
        print("無効な値が入力されました")
        print("最初からやり直してください")
Exemple #23
0
class Menu(object):
    """
	display a menu and respond to user choiced to interact 
	with the Note and Notebook when run
	"""
    def __init__(self):
        self.notebook = Notebook()
        self.choices = {
            '1': self.show_notes,
            '2': self.search_notes,
            '3': self.add_notes,
            '4': self.modify_notes,
            '5': self.quit
        }

    def display_menu(self):
        # use triple quotes for managing multiple lines of long printing
        print("""
			Notebook Menu

			1.Show All Notes
			2.Search Notes
			3.Add Notes
			4.Modify Notes
			5.Quit
			""")

    def run(self):
        """display the menu and respond to choices"""

        while True:
            self.display_menu()
            choice = input('Enter an option: ')
            # .get() allows you to provide a value as the second parameter
            # and return that value if the key is missing, instead of
            # throwing KeyError
            action = self.choices.get(choice)
            if action:
                action()
            else:
                print('{0} is not a valid choice'.format(choice))

    def show_notes(self, notes=None):
        """
		optional notes parameter. If it's supplied,
		it displays only the filtered notes, but if it's not, it displays all notes
		"""
        if not notes:
            notes = self.notebook.notes

        for note in notes:
            print('{0}: {1}\n{2}'.format(note.id, note.tags, note.memo))

    def search_notes(self):
        filter_string = input('Search For: ')
        notes = self.notebook.search(filter_string)
        self.show_notes(notes)

    def add_note(self):
        memo = input('Enter a memo: ')
        self.notebook.new_note(memo)
        print('Your note has been added.')

    def modify_notes(self):
        id = input('Enter a note id: ')
        memo = input('Enter a memo: ')
        tags = input('Enter tags: ')

        if memo:
            self.notebook.modify_memo(id, memo)
        if tags:
            self.notebook.modify_tags(id, tags)

    def quit(self):
        print('Thank you for using your notebook today.')
        # Exit the interpreter by raising SystemExit(status)
        sys.exit(0)
Exemple #24
0
class Menu:
    """CLI для блокнота"""
    def __init__(self):
        self.notebook = Notebook()
        self.choices = {
            "1": self.show_notes,
            "2": self.search_notes,
            "3": self.add_note,
            "4": self.modify_note,
            "5": self.quit
        }

    def display_menu(self):
        print("""Notebook Menu
            1. Show all Notes
            2. Search Notes
            3. Add Note
            4. Modify Note
            5. Quit
            """)

    def run(self):
        """Показывает меню и ответ при выборе"""
        while True:
            self.display_menu()
            choice = input("Enter an option: ")
            action = self.choices.get(choice)
            if action:
                action()
            else:
                print("{0} is not a valid choice".format(choice))

    def show_notes(self, notes=None):
        if not notes:
            notes = self.notebook.notes

        for note in notes:
            # print("{0}: {1}\n{2}".format(note.id, note.tags, note.memo))
            print("{0}: {1}\n{2}".format(note.id, note.tags, note.memo))

    def search_notes(self):
        filter = input("Search for: ")
        notes = self.notebook.search(filter)
        self.show_notes(notes)

    def add_note(self):
        """Cюда бы добавить ещё тэги"""
        memo = input("Enter a memo: ")
        self.notebook.new_note(memo)
        print(self.notebook.notes)
        print("Your note has been added.")

    def modify_note(self):
        id = input("Enter a note id: ")
        memo = input("Enter a memo: ")
        tags = input("Enter tags: ")
        if memo:
            self.notebook.modify_memo(id, memo)
        if tags:
            self.notebook.modify_tags(id, tags)

    def quit(self):
        print("Thank you for using your notebook today")
        sys.exit()
Exemple #25
0
class OpPanel(Operation):
    """Panel in charge of replacing matches with text or operations."""

    def __init_sizer(self, parent):
        #smallestSize = parent.rightSizer.GetSize() - parent.rightTopSizer.GetSize() - (10,10)
        mainSizer = wx.BoxSizer(wx.VERTICAL)
        #mainSizer.SetMinSize(smallestSize)
        mainSizer.Add(self.notebook, 0, wx.EXPAND)
        self.SetSizerAndFit(mainSizer)

    def __init_ctrls(self, prnt):
        wx.Panel.__init__(self, id=-1, name=u'Panel', parent=prnt,
                          style=wx.TAB_TRAVERSAL)
        self.notebook = Notebook(self, main)
        self.replaceToolsPanel = replaceTools.Panel(self.notebook, main)
        self.notebook.init_pages(self.replaceToolsPanel,
                                 _(u"Replace settings"), u'replace.ico')
        self.numberingPanel = self.notebook.numbering
        self.dateTimePanel = self.notebook.dateTime


    def __init__(self, parent, main_window, params={}):
        Operation.__init__(self, params)
        global main
        main = main_window
        self.__init_ctrls(parent)
        self.__init_sizer(parent)

    def on_config_load(self):
        """Update GUI elements, settings after config load."""
        self.replaceToolsPanel.on_load()
        self.numberingPanel.on_config_load()
        self.dateTimePanel.get_from_item_checkbox(False)

    def reset_counter(self, c):
        """Reset the numbering counter for the operation."""
        utils.reset_counter(self, self.replaceToolsPanel, c)

    def rename_item(self, path, name, ext, original):
        operations = self.replaceToolsPanel.opButtonsPanel
        newName = self.join_ext(name, ext)
        if not newName:
            return path, name, ext

        # basic settings
        search = self.replaceToolsPanel.search
        searchValues = search.searchValues
        text = self.replaceToolsPanel.repl_txt.GetValue()

        #- do nothing
        if searchValues[0] == u"text" and not searchValues[2] and not text:
            return path, name, ext

        #- search and replace when field not blank:
        elif searchValues[0] == u"text" and searchValues[2]:
            find = searchValues[2]
            parsedText = operations.parse_input(text, original, self)
            #case insensitive
            if not searchValues[1]:
                found = search.case_insensitive(newName)
                for match in found:
                    newName = newName.replace(match, parsedText)
            #case sensitive:
            else:
                newName = newName.replace(find, parsedText)
        
        #- replace everything if text field is blank:
        elif searchValues[0] == u"text":
            newName = operations.parse_input(text, original, self)

        #- replace using regular expression:
        elif searchValues[0] == u"reg-exp" and searchValues[1]:
            # need to first substiute, then parse for backreference support
            try:
                replaced = searchValues[2].sub(text, newName)
            except (sre_constants.error, AttributeError) as err:
                main.set_status_msg(_(u"Regular-Expression: %s") % err, u'warn')
                # so we know not to change status text after RE error msg:
                app.REmsg = True
                pass
            else:
                newName = operations.parse_input(replaced, original, self)

            # show RE error message from search, if any
            if search.REmsg:
                main.set_status_msg(search.REmsg, u'warn')
                app.REmsg = True

        #- replace in between
        elif searchValues[0] == u"between":
            positions = search.get_between_to_from(newName)
            if positions:
                frm = positions[0]
                to = positions[1]
                parsedText = operations.parse_input(text, original, self)
                newName = newName[:frm] + parsedText + newName[to:]

        #- replace by position:
        elif searchValues[0] == u"position":
            ss = search.repl_from.GetValue()
            sl = search.repl_len.GetValue()
            frm, to, tail = search.get_start_end_pos(ss, sl, newName)
            parsedText = operations.parse_input(text, original, self)
            newName = newName[:frm] + parsedText + tail

        name, ext = self.split_ext(newName, name, ext)
        return path, name, ext
Exemple #26
0
from notebook import Notebook
from note import Note
import argparse


def load_args():
    parser = argparse.ArgumentParser(description='Python Note Logger')
    parser.add_argument()


if __name__ == '__main__':
    load_args()
    notebook = Notebook()
    test_note = Note('Books I have read', '2019 Books', 'Books',
                     ['read', 'books', '2019'])
    notebook.add_note(test_note)
    notebook.save_to_file('test.dat')

    notebook2 = Notebook()
    notebook2.load_from_file('test.dat')
    for note in notebook2:
        note.print()
Exemple #27
0
class Menu:
    '''Display a menu and respond to choices when run.'''
    def __init__(self):
        self.notebook = Notebook()
        self.choices = {
                "1": self.show_notes,
                "2": self.search_notes,
                "3": self.add_note,
                "4": self.modify_note,
                "5": self.quit
                }

    def display_menu(self):
        print("""
Notebook Menu

1. Show all Notes
2. Search Notes
3. Add Note
4. Modify Note
5. Quit
""")

    def run(self):
        '''Display the menu and respond to choices.'''
        while True:
            self.display_menu()
            choice = input("Enter an option: ")
	    #choice = sys.argv
            action = self.choices.get(choice)
	    #print "value of self.choices.get(choice) is %s  ==" %  self.choices.get("1")
            print("value of choice  is ==", choice)
            print("value of action is ==", action)
            if action:
                action()
            else:
                print("{0} is not a valid choice".format(choice))

    def show_notes(self, notes=None):
        if not notes:
            notes = self.notebook.notes
        for note in notes:
            print("{0}: {1}\n{2}".format(
                note.id, note.tags, note.memo))

    def search_notes(self):
        filter = input("Search for: ")
        notes = self.notebook.search(filter)
        self.show_notes(notes)

    def add_note(self):
        memo = input("Enter a memo: ")
        self.notebook.new_note(memo)
        print("Your note has been added.")

    def modify_note(self):
        id = input("Enter a note id: ")
        memo = input("Enter a memo: ")
        tags = input("Enter tags: ")
        if memo:
            self.notebook.modify_memo(id, memo)
        if tags:
            self.notebook.modify_tags(id, tags)

    def quit(self):
        print("Thank you for using your notebook today.")
        sys.exit(0)
Exemple #28
0
class Menu:
    '''Display a menu and respond to choices when run.'''
    def __init__(self):
        self.notebook = Notebook()
        self.choices = {
            "1": self.show_notes,
            "2": self.search_notes,
            "3": self.add_note,
            "4": self.modify_note,
            "5": self.quit
        }

    def display_menu(self):
        print("""
        Notebook Menu
        1. Show all Notes
        2. Search Notes
        3. Add Note
        4. Modify Note
        5. Quit
        """)

    def run(self):
        '''Display the menu and respond to choices.'''
        while True:
            self.display_menu()
            choice = input("Enter an option: ")
            action = self.choices.get(choice)
            if action:
                action()
            else:
                print("{0} is not a valid choice".format(choice))

            if choice == '5':
                break

    def show_notes(self, notes=None):
        if not notes:
            notes = self.notebook.notes
        for note in notes:
            print("{0}: {1}\n{2}".format(note.id, note.tags, note.memo))

    def search_notes(self):
        filter = input("Search for: ")
        notes = self.notebook.search(filter)
        self.show_notes(notes)

    def add_note(self):
        memo = input("Enter a memo: ")
        self.notebook.new_note(memo)
        print("Your note has been added.")

    def modify_note(self):
        id = input("Enter a note id: ")
        memo = input("Enter a memo: ")
        tags = input("Enter tags: ")
        if memo: self.notebook.modify_memo(id, memo)
        if tags: self.notebook.modify_tags(id, tags)

    def quit(self):
        print("Thank you for using your notebook today.")
        proceed = input(
            "Do you want to know more about object oriented programming? [Y/N]"
        )
        if proceed.lower() == "n":
            sys.exit(0)
        else:
            train()

        sys.exit(0)
Exemple #29
0
class Menu(object):
	"""
	display a menu and respond to user choiced to interact 
	with the Note and Notebook when run
	"""

	def __init__(self):
		self.notebook = Notebook()
		self.choices = {
			'1': self.show_notes,
			'2': self.search_notes,
			'3': self.add_notes,
			'4': self.modify_notes,
			'5': self.quit
		}

	def display_menu(self):
		# use triple quotes for managing multiple lines of long printing
		print(
			"""
			Notebook Menu

			1.Show All Notes
			2.Search Notes
			3.Add Notes
			4.Modify Notes
			5.Quit
			"""
		)

	def run(self):
		"""display the menu and respond to choices"""

		while True:
			self.display_menu()
			choice = input('Enter an option: ')
			# .get() allows you to provide a value as the second parameter
			# and return that value if the key is missing, instead of 
			# throwing KeyError
			action = self.choices.get(choice)
			if action:
				action()
			else:
				print( '{0} is not a valid choice'.format(choice) )
	
	def show_notes( self, notes = None ):
		"""
		optional notes parameter. If it's supplied,
		it displays only the filtered notes, but if it's not, it displays all notes
		"""
		if not notes:
			notes = self.notebook.notes

		for note in notes:
			print( '{0}: {1}\n{2}'.format( note.id, note.tags, note.memo ) )

	def search_notes(self):
		filter_string = input('Search For: ')
		notes = self.notebook.search(filter_string)
		self.show_notes(notes)

	def add_note(self):
		memo = input('Enter a memo: ')
		self.notebook.new_note(memo)
		print('Your note has been added.')

	def modify_notes(self):
		id   = input('Enter a note id: ')
		memo = input('Enter a memo: ')
		tags = input('Enter tags: ')
		
		if memo:
			self.notebook.modify_memo( id, memo )
		if tags:
			self.notebook.modify_tags( id, tags )

	def quit(self):
		print('Thank you for using your notebook today.')
		# Exit the interpreter by raising SystemExit(status)
		sys.exit(0)
def pytest_funcarg__notebook_with_one_note(request):
    notebook = Notebook()
    notebook.new_note("hello world")
    return notebook
Exemple #31
0
class Menu:
    """Display a menu and responds to choices by calling functions on the Notebook"""
    def __init__(self):
        self.notebook = Notebook()
        self.choices = {
            "1": self.show_notes,
            "2": self.search_notes,
            "3": self.add_note,
            "4": self.modify_note,
            "5": self.quit,
        }

    def display_menu(self):
        print("""
Notebook Menu

1. Show all Notes
2. Search Notes
3. Add Note
4. Modify Note
5. Quit
            """)

    def run(self):
        """Display the menu and respond to choices"""
        while True:
            self.display_menu()
            choice = input("Enter an option: ")
            action = self.choices.get(choice)
            if action:
                action()
            else:
                print("{0} is not a valid choice".format(choice))

    def show_notes(self, notes=None):
        if not notes:
            notes = self.notebook.notes
        for note in notes:
            print("{0}: {1}\n{2}".format(note.id, note.tags, note.memo))

    def search_notes(self):
        filter = input("Search for: ")
        notes = self.notebook.search(filter)
        self.show_notes(notes)

    def add_note(self):
        memo = input("Enter a memo: ")
        self.notebook.new_note(memo)
        print("Noted added successfully!")

    def modify_note(self):
        id = input("Enter a note id: ")
        memo = input("Enter a memo: ")
        tags = input("Enter tags: ")
        if memo:
            self.notebook.modify_memo(id, memo)
        if tags:
            self.notebook.modify_tags(id, tags)

    def quit(self):
        print("Thank you for using the notebook")
        sys.exit(0)
Exemple #32
0
class Menu:
    def __init__(self):
        """
        An initiaton of class attributes.
        """
        self.notebook = Notebook()
        self.choices = {
            '1': self.show_notes,
            '2': self.search_notes,
            '3': self.add_note,
            '4': self.modify_note,
            '5': self.remove_note,
            '6': self.backup,
            '7': self.restore,
            '8': self.quit
        }

    def display_menu(self):
        """
        Displays the menu.
        """
        print("""
        Notebook menu:
        1. Show notes
        2. Search notes
        3. Add a note
        4. Modify a note
        5. Remove a note
        6. Save notes localy
        7. Load local saved notes
        8. Quit
        """)

    def run(self):
        """
        Runs a program.
        """
        while True:
            self.display_menu()
            choice = input('Enter an option: ')
            action = self.choices.get(choice)
            if action:
                action()
            else:
                print(f'{choice} is not valid.')

    def show_notes(self, notes=None):
        """
        (list) -> None
        Shows all created notes.
        """
        if not notes:
            notes = self.notebook.note_list
        for note in notes:
            print(note.last_id, note.tags, note.memo, '\n' + '-' * 30)

    def search_notes(self):
        """
        Searches note by inserted value.
        """
        filter = input('Search for: ')
        notes = self.notebook.search(filter)
        self.show_notes(notes)

    def add_note(self):
        """
        Creates a Note object in Notebook
        """
        memo = input("Enter a memo: ")
        self.notebook.add_note(memo)
        print('Your note has benn added.')

    def modify_note(self):
        """
        Modifies existing Note object with inserted values.
        """
        id = input('Enter a note id: ')
        memo = input('Enter a memo: ')
        tags = input('Eneter a tags: ')
        if memo:
            self.notebook.modify_memo(id, memo)
        if tags:
            self.notebook.modify_tags(id, tags)

    def remove_note(self):
        """
        Removes the Note object from Notebook, by inserted id.
        """
        id = input('Enter a note id: ')
        self.notebook.remove_note(id)
        print('Your note has been deleted.')

    def restore(self):
        """
        Restores a localy saved notes (if they exist).
        """
        if not os.path.isdir('notes'):
            print('No backups found.')
        else:
            local_files = glob.glob('notes/*_note.json')
            for each in local_files:
                with open(each, 'r') as file:
                    note = json.load(file)
                    self.notebook.recover_note(note)

    def backup(self):
        """
        Backups all notes locally.
        """
        if not os.path.isdir('notes'):
            os.makedirs('notes')
        notes = self.notebook.note_list
        for each in notes:
            with open(f'notes/{each.last_id}_{each.date}_note.json',
                      'w') as file:
                print(vars(each))
                json.dump(vars(each), file)

    def quit(self):
        """
        Stops the program.
        """
        print('Thanks for using notebook')
        sys.exit(0)
Exemple #33
0
def write_example(src_name, src_dir, rst_dir, cfg):
    """Write rst file from a given python example.

    Parameters
    ----------
    src_name : str
        Name of example file.
    src_dir : 'str'
        Source directory for python examples.
    rst_dir : 'str'
        Destination directory for rst files generated from python examples.
    cfg : config object
        Sphinx config object created by Sphinx.
    """
    last_dir = src_dir.psplit()[-1]
    # to avoid leading . in file names, and wrong names in links
    if last_dir == '.' or last_dir == 'examples':
        last_dir = Path('')
    else:
        last_dir += '_'

    src_path = src_dir.pjoin(src_name)
    example_file = rst_dir.pjoin(src_name)
    shutil.copyfile(src_path, example_file)

    image_dir = rst_dir.pjoin('images')
    thumb_dir = image_dir.pjoin('thumb')
    notebook_dir = rst_dir.pjoin('notebook')
    image_dir.makedirs()
    thumb_dir.makedirs()
    notebook_dir.makedirs()

    base_image_name = os.path.splitext(src_name)[0]
    image_path = image_dir.pjoin(base_image_name + '_{0}.png')

    basename, py_ext = os.path.splitext(src_name)
    rst_path = rst_dir.pjoin(basename + cfg.source_suffix)
    notebook_path = notebook_dir.pjoin(basename + '.ipynb')

    if _plots_are_current(src_path, image_path) and rst_path.exists and \
        notebook_path.exists:
        return

    blocks = split_code_and_text_blocks(example_file)
    if blocks[0][2].startswith('#!'):
        blocks.pop(0)  # don't add shebang line to rst file.

    rst_link = '.. _example_%s:\n\n' % (last_dir + src_name)
    figure_list, rst = process_blocks(blocks, src_path, image_path, cfg)

    has_inline_plots = any(cfg.plot2rst_plot_tag in b[2] for b in blocks)
    if has_inline_plots:
        example_rst = ''.join([rst_link, rst])
    else:
        # print first block of text, display all plots, then display code.
        first_text_block = [b for b in blocks if b[0] == 'text'][0]
        label, (start, end), content = first_text_block
        figure_list = save_all_figures(image_path)
        rst_blocks = [IMAGE_TEMPLATE % f.lstrip('/') for f in figure_list]

        example_rst = rst_link
        example_rst += eval(content)
        example_rst += ''.join(rst_blocks)
        code_info = dict(src_name=src_name, code_start=end)
        example_rst += LITERALINCLUDE.format(**code_info)

    example_rst += CODE_LINK.format(src_name)
    ipnotebook_name = src_name.replace('.py', '.ipynb')
    ipnotebook_name = './notebook/' + ipnotebook_name
    example_rst += NOTEBOOK_LINK.format(ipnotebook_name)

    f = open(rst_path, 'w')
    f.write(example_rst)
    f.flush()

    thumb_path = thumb_dir.pjoin(src_name[:-3] + '.png')
    first_image_file = image_dir.pjoin(figure_list[0].lstrip('/'))
    if first_image_file.exists:
        first_image = io.imread(first_image_file)
        save_thumbnail(first_image, thumb_path, cfg.plot2rst_thumb_shape)

    if not thumb_path.exists:
        if cfg.plot2rst_default_thumb is None:
            print("WARNING: No plots found and default thumbnail not defined.")
            print("Specify 'plot2rst_default_thumb' in Sphinx config file.")
        else:
            shutil.copy(cfg.plot2rst_default_thumb, thumb_path)

    # Export example to IPython notebook
    nb = Notebook()

    for (cell_type, _, content) in blocks:
        content = content.rstrip('\n')

        if cell_type == 'code':
            nb.add_cell(content, cell_type='code')
        else:
            content = content.replace('"""', '')
            content = '\n'.join([
                line for line in content.split('\n')
                if not line.startswith('.. image')
            ])
            html = publish_parts(content, writer_name='html')['html_body']
            nb.add_cell(html, cell_type='markdown')

    with open(notebook_path, 'w') as f:
        f.write(nb.json())
Exemple #34
0
from pprint import pprint
from shutil import Error
import sys
import time
import uuid

import requests
from websocket import ABNF, WebSocket, WebSocketApp, create_connection

from notebook import Notebook

#base_url = 'http://localhost:8888'
#notebook_password = '******'
notebook_path = '/work/BatchAPIExample.ipynb'

nb = Notebook(notebook_path)
nb.start_session()

if (nb.login()):
    nb.start_kernel()
    nb.build_notebook()

messages = []
session = uuid.uuid1().hex

def send_execute_request(code):
    msg_type = 'execute_request'
    content = { 
        'code' : code, 
        'silent' : False 
        }
Exemple #35
0
class Menu:
    """Display menu and respond with choices"""
    def __init__(self):
        self.notebook = Notebook()
        self.choices = {
            "1": self.show_notes,
            "2": self.search_notes,
            "3": self.add_note,
            "4": self.modify_note,
            "5": self.quit
        }

    def display_menu(self):
        print("""
Notebook Menu 

1. Show all Notes
2. Search Notes
3. Add Note
4. Modify Note
5. Quit
        """)

    def run(self):
        """Display the menu and respond to chocies"""
        while True:
            self.display_menu()
            choice = input("Enter an option: ")
            action = self.choices.get(choice)
            if action:
                action()
            else:
                print(f"{choice} is not a valid choice")

    def show_notes(self, notes=None):
        if not notes:
            notes = self.notebook.notes
            for note in notes:
                print(f"{note.id}:{note.tags}\{note.memo}")

    def search_notes(self):
        filter = input("Search for: ")
        notes = self.notebook.search(filter)
        self.show_notes(notes)

    def add_note(self):
        memo = input("Enter a memo")
        self.notebook.new_note(memo)
        print("Your note has been added")

    def modify_note(self):
        id = input("Enter a note id ")
        memo = input("Enter a new memo")
        tags = input("Enter tags")
        if memo:
            self.notebook.modify_memo(id, memo)
            if tags:
                self.notebook.modify_tags(id, tags)

    def quit(self):
        print("Thank you for using notebook today")
        sys.exit(0)
Exemple #36
0
class Menu:
    """
    Menu class. Contains __init__ , display_menu, run, show_notes,
    search_notes, add_note, modify_note, quit methods
    """
    def __init__(self):
        """

        main method to create object. It is called when
        the new object is being created

        >>> menu = Menu()

        """
        self.notebook = Notebook()
        self.choices = {
            "1": self.show_notes,
            "2": self.search_notes,
            "3": self.add_note,
            "4": self.modify_note,
            "5": self.quit
        }

    def display_menu(self):
        """
        dispays the menu

        >>> menu = Menu()
        >>> menu.display_menu()
        <BLANKLINE>
        <BLANKLINE>
                Notebook Menu
        <BLANKLINE>
                1. Show all Notes
                2. Search Notes
                3. Add Note
                4. Modify Note
                5. Quit
        """
        print("""
        
        Notebook Menu

        1. Show all Notes
        2. Search Notes
        3. Add Note
        4. Modify Note
        5. Quit""")

    def run(self):
        '''Display the menu and respond to choices.'''
        while True:
            self.display_menu()
            choice = input("Enter an option: ")
            action = self.choices.get(choice)
            if action:
                action()
            else:
                print("{0} is not a valid choice".format(choice))

    def show_notes(self, notes=None):
        """
        displays the notes
        """
        if not notes:
            notes = self.notebook.notes
        for note in notes:
            print(f"{note.id}: {note.tags},\n{note.memo}")

    def search_notes(self):
        """
        searches fot the notes using the keyword

        """
        key_word = input("Search for:")
        notes = self.notebook.search(key_word)
        self.show_notes(notes)

    def add_note(self):
        """
        adds a note
        """
        memo = input("Enter a memo:")
        self.notebook.new_note(memo)
        print("Your note has been added")

    def modify_note(self):
        """
        modifies the note
        """
        id = input("enter a note id:")
        memo = input("Enter a memo:")
        tags = input("Enter tags:")
        if memo:
            self.notebook.modify_memo(id, memo)
        if tags:
            self.notebook.modify_tags(id, tags)

    def quit(self):
        """
        ends the program
        """
        print("Thank you")
        sys.exit(0)
Exemple #37
0
def write_example(src_name, src_dir, rst_dir, cfg):
    """Write rst file from a given python example.

    Parameters
    ----------
    src_name : str
        Name of example file.
    src_dir : 'str'
        Source directory for python examples.
    rst_dir : 'str'
        Destination directory for rst files generated from python examples.
    cfg : config object
        Sphinx config object created by Sphinx.
    """
    last_dir = src_dir.psplit()[-1]
    # to avoid leading . in file names, and wrong names in links
    if last_dir == '.' or last_dir == 'examples':
        last_dir = Path('')
    else:
        last_dir += '_'

    src_path = src_dir.pjoin(src_name)
    example_file = rst_dir.pjoin(src_name)
    shutil.copyfile(src_path, example_file)

    image_dir = rst_dir.pjoin('images')
    thumb_dir = image_dir.pjoin('thumb')
    notebook_dir = rst_dir.pjoin('notebook')
    image_dir.makedirs()
    thumb_dir.makedirs()
    notebook_dir.makedirs()

    base_image_name = os.path.splitext(src_name)[0]
    image_path = image_dir.pjoin(base_image_name + '_{0}.png')

    basename, py_ext = os.path.splitext(src_name)
    rst_path = rst_dir.pjoin(basename + cfg.source_suffix)
    notebook_path = notebook_dir.pjoin(basename + '.ipynb')

    if _plots_are_current(src_path, image_path) and rst_path.exists and \
        notebook_path.exists:
        return

    print('plot2rst: %s' % basename)

    blocks = split_code_and_text_blocks(example_file)
    if blocks[0][2].startswith('#!'):
        blocks.pop(0)  # don't add shebang line to rst file.

    rst_link = '.. _example_%s:\n\n' % (last_dir + src_name)
    figure_list, rst = process_blocks(blocks, src_path, image_path, cfg)

    has_inline_plots = any(cfg.plot2rst_plot_tag in b[2] for b in blocks)
    if has_inline_plots:
        example_rst = ''.join([rst_link, rst])
    else:
        # print first block of text, display all plots, then display code.
        first_text_block = [b for b in blocks if b[0] == 'text'][0]
        label, (start, end), content = first_text_block
        figure_list = save_all_figures(image_path)
        rst_blocks = [IMAGE_TEMPLATE % f.lstrip('/') for f in figure_list]

        example_rst = rst_link
        example_rst += eval(content)
        example_rst += ''.join(rst_blocks)
        code_info = dict(src_name=src_name, code_start=end)
        example_rst += LITERALINCLUDE.format(**code_info)

    example_rst += CODE_LINK.format(src_name)
    ipnotebook_name = src_name.replace('.py', '.ipynb')
    ipnotebook_name = './notebook/' + ipnotebook_name
    example_rst += NOTEBOOK_LINK.format(ipnotebook_name)

    f = open(rst_path, 'w')
    f.write(example_rst)
    f.flush()

    thumb_path = thumb_dir.pjoin(src_name[:-3] + '.png')
    first_image_file = image_dir.pjoin(figure_list[0].lstrip('/'))
    if first_image_file.exists:
        first_image = io.imread(first_image_file)
        save_thumbnail(first_image, thumb_path, cfg.plot2rst_thumb_shape)

    if not thumb_path.exists:
        if cfg.plot2rst_default_thumb is None:
            print("WARNING: No plots found and default thumbnail not defined.")
            print("Specify 'plot2rst_default_thumb' in Sphinx config file.")
        else:
            shutil.copy(cfg.plot2rst_default_thumb, thumb_path)

    # Export example to IPython notebook
    nb = Notebook()

    # Add sphinx roles to the examples, otherwise docutils
    # cannot compile the ReST for the notebook
    sphinx_roles = PythonDomain.roles.keys()
    preamble = '\n'.join('.. role:: py:{0}(literal)\n'.format(role)
                         for role in sphinx_roles)

    # Grab all references to inject them in cells where needed
    ref_regexp = re.compile('\n(\.\. \[(\d+)\].*(?:\n[ ]{7,8}.*)+)')
    math_role_regexp = re.compile(':math:`(.*?)`')

    text = '\n'.join(
        (content for (cell_type, _, content) in blocks if cell_type != 'code'))

    references = re.findall(ref_regexp, text)

    for (cell_type, _, content) in blocks:
        if cell_type == 'code':
            nb.add_cell(content, cell_type='code')
        else:
            if content.startswith('r'):
                content = content.replace('r"""', '')
                escaped = False
            else:
                content = content.replace('"""', '')
                escaped = True

            if not escaped:
                content = content.replace("\\", "\\\\")

            content = content.replace('.. seealso::', '**See also:**')
            content = re.sub(math_role_regexp, r'$\1$', content)

            # Remove math directive when rendering notebooks
            # until we implement a smarter way of capturing and replacing
            # its content
            content = content.replace('.. math::', '')

            if not content.strip():
                continue

            content = (preamble + content).rstrip('\n')
            content = '\n'.join([
                line for line in content.split('\n')
                if not line.startswith('.. image')
            ])

            # Remove reference links until we can figure out a better way to
            # preserve them
            for (reference, ref_id) in references:
                ref_tag = '[{0}]_'.format(ref_id)
                if ref_tag in content:
                    content = content.replace(ref_tag, ref_tag[:-1])

            html = publish_parts(content, writer_name='html')['html_body']
            nb.add_cell(html, cell_type='markdown')

    with open(notebook_path, 'w') as f:
        f.write(nb.json())
Exemple #38
0
def write_example(src_name, src_dir, rst_dir, cfg):
    """Write rst file from a given python example.

    Parameters
    ----------
    src_name : str
        Name of example file.
    src_dir : 'str'
        Source directory for python examples.
    rst_dir : 'str'
        Destination directory for rst files generated from python examples.
    cfg : config object
        Sphinx config object created by Sphinx.
    """
    last_dir = src_dir.psplit()[-1]
    # to avoid leading . in file names, and wrong names in links
    if last_dir == '.' or last_dir == 'examples':
        last_dir = Path('')
    else:
        last_dir += '_'

    src_path = src_dir.pjoin(src_name)
    example_file = rst_dir.pjoin(src_name)
    shutil.copyfile(src_path, example_file)

    image_dir = rst_dir.pjoin('images')
    thumb_dir = image_dir.pjoin('thumb')
    notebook_dir = rst_dir.pjoin('notebook')
    image_dir.makedirs()
    thumb_dir.makedirs()
    notebook_dir.makedirs()

    base_image_name = os.path.splitext(src_name)[0]
    image_path = image_dir.pjoin(base_image_name + '_{0}.png')

    basename, py_ext = os.path.splitext(src_name)
    rst_path = rst_dir.pjoin(basename + cfg.source_suffix)
    notebook_path = notebook_dir.pjoin(basename + '.ipynb')

    if _plots_are_current(src_path, image_path) and rst_path.exists and \
        notebook_path.exists:
        return

    blocks = split_code_and_text_blocks(example_file)
    if blocks[0][2].startswith('#!'):
        blocks.pop(0) # don't add shebang line to rst file.

    rst_link = '.. _example_%s:\n\n' % (last_dir + src_name)
    figure_list, rst = process_blocks(blocks, src_path, image_path, cfg)

    has_inline_plots = any(cfg.plot2rst_plot_tag in b[2] for b in blocks)
    if has_inline_plots:
        example_rst = ''.join([rst_link, rst])
    else:
        # print first block of text, display all plots, then display code.
        first_text_block = [b for b in blocks if b[0] == 'text'][0]
        label, (start, end), content = first_text_block
        figure_list = save_all_figures(image_path)
        rst_blocks = [IMAGE_TEMPLATE % f.lstrip('/') for f in figure_list]

        example_rst = rst_link
        example_rst += eval(content)
        example_rst += ''.join(rst_blocks)
        code_info = dict(src_name=src_name, code_start=end)
        example_rst += LITERALINCLUDE.format(**code_info)

    example_rst += CODE_LINK.format(src_name)
    ipnotebook_name = src_name.replace('.py', '.ipynb')
    ipnotebook_name = './notebook/' + ipnotebook_name
    example_rst += NOTEBOOK_LINK.format(ipnotebook_name)

    f = open(rst_path, 'w')
    f.write(example_rst)
    f.flush()

    thumb_path = thumb_dir.pjoin(src_name[:-3] + '.png')
    first_image_file = image_dir.pjoin(figure_list[0].lstrip('/'))
    if first_image_file.exists:
        first_image = io.imread(first_image_file)
        save_thumbnail(first_image, thumb_path, cfg.plot2rst_thumb_shape)

    if not thumb_path.exists:
        if cfg.plot2rst_default_thumb is None:
            print("WARNING: No plots found and default thumbnail not defined.")
            print("Specify 'plot2rst_default_thumb' in Sphinx config file.")
        else:
            shutil.copy(cfg.plot2rst_default_thumb, thumb_path)

    # Export example to IPython notebook
    nb = Notebook()

    for (cell_type, _, content) in blocks:
        content = content.rstrip('\n')

        if cell_type == 'code':
            nb.add_cell(content, cell_type='code')
        else:
            content = content.replace('"""', '')
            content = '\n'.join([line for line in content.split('\n') if
                                 not line.startswith('.. image')])
            html = publish_parts(content, writer_name='html')['html_body']
            nb.add_cell(html, cell_type='markdown')

    with open(notebook_path, 'w') as f:
        f.write(nb.json())
Exemple #39
0
class DeepAugment:
    """Initiliazes commponents of DeepAugment (e.g. Controller, Child-model, Notebook) and optimizes image augmentation hyperparameters

    """
    @logger(logfile_dir=EXPERIMENT_FOLDER_PATH)
    def __init__(self, images="cifar10", labels=None, config=None):
        """Initializes DeepAugment object

        Does following steps:
            1. load and preprocess data
            2. create child model
            3. create controller
            4. create notebook (for recording trainings)
            5. do initial training
            6. create objective function
            7. evaluate objective function without augmentation

        Args:
            images (numpy.array/str): array with shape (n_images, dim1, dim2 , channel_size), or a string with name of keras-dataset (cifar10, fashion_mnsit)
            labels (numpy.array): labels of images, array with shape (n_images) where each element is an integer from 0 to number of classes
            config (dict): dictionary of configurations, for updating the default config which is:
                {
                    "model": "basiccnn",
                    "method": "bayesian_optimization",
                    "train_set_size": 2000,
                    "opt_samples": 3,
                    "opt_last_n_epochs": 3,
                    "opt_initial_points": 10,
                    "child_epochs": 50,
                    "child_first_train_epochs": 0,
                    "child_batch_size": 64,
                    "pre_aug_weights_path": "pre_aug_weights.h5",
                    "logging": logging,
                    "notebook_path": f"{EXPERIMENT_FOLDER_PATH}/notebook.csv"
                }
        """
        self.config = DEFAULT_CONFIG
        self.config.update(config)
        self.iterated = 0  # keep tracks how many times optimizer iterated

        self.load_and_preprocess_data(images, labels)

        # define main objects
        self.child_model = ChildCNN(self.input_shape, self.num_classes,
                                    self.config)
        self.controller = Controller(self.config)
        self.notebook = Notebook(self.config)
        if self.config["child_first_train_epochs"] > 0:
            self.do_initial_training()
        self.child_model.save_pre_aug_weights()
        self.objective_func = Objective(self.data, self.child_model,
                                        self.notebook, self.config)

        self.evaluate_objective_func_without_augmentation()

    def optimize(self, iterations=300):
        """Optimize objective function hyperparameters using controller and child model

        Args:
            iterations (int): number of optimization iterations, which the child model will be run

        Returns:
            pandas.DataFrame: top policies (with highest expected accuracy increase)
        """
        # iteratate optimizer
        for trial_no in range(self.iterated + 1,
                              self.iterated + iterations + 1):
            trial_hyperparams = self.controller.ask()
            print("trial:", trial_no, "\n", trial_hyperparams)
            f_val = self.objective_func.evaluate(trial_no, trial_hyperparams)
            self.controller.tell(trial_hyperparams, f_val)

        self.iterated += iterations  # update number of previous iterations

        top_policies = self.notebook.get_top_policies(20)
        self.notebook.output_top_policies()
        print("\ntop policies are:\n", top_policies)
        return top_policies

    def load_and_preprocess_data(self, images, labels):
        """Loads and preprocesses data

        Records `input_shape`, `data`, and `num_classes` into `self

        Args:
            images (numpy.array/str): array with shape (n_images, dim1, dim2 , channel_size), or a string with name of keras-dataset (cifar10, fashion_mnsit)
            labels (numpy.array): labels of images, array with shape (n_images) where each element is an integer from 0 to number of classes
        """
        if isinstance(images, str):
            X, y, self.input_shape = DataOp.load(images)
        else:
            X, y = images, labels
        self.input_shape = X.shape[1:]
        self.data = DataOp.preprocess(X, y, self.config["train_set_size"])
        self.num_classes = DataOp.find_num_classes(self.data)

    def do_initial_training(self):
        """Do the first training without augmentations

        Training weights will be used as based to further child model trainings
        """
        history = self.child_model.fit(
            self.data, epochs=self.config["child_first_train_epochs"])
        self.notebook.record(-1,
                             ["first", 0.0, "first", 0.0, "first", 0.0, 0.0],
                             1, None, history)

    def evaluate_objective_func_without_augmentation(self):
        """Find out what would be the accuracy if augmentation are not applied
        """
        no_aug_hyperparams = ["crop", 0.0, "crop", 0.0, 0.0]
        f_val = self.objective_func.evaluate(0, no_aug_hyperparams)
        self.controller.tell(no_aug_hyperparams, f_val)
Exemple #40
0
class OpPanel(Operation):
    """This panel controls inserts."""
    
    def __init_sizer(self, parent):
        #smallestSize = parent.rightSizer.GetSize() - parent.rightTopSizer.GetSize() - (10,10)
        mainSizer = wx.BoxSizer(wx.VERTICAL)
        #mainSizer.SetMinSize(smallestSize)
        mainSizer.Add(self.notebook, 0, wx.EXPAND)
        self.SetSizerAndFit(mainSizer)

    def __init_ctrls(self, prnt):
        wx.Panel.__init__(self, id=-1, name=u'Panel', parent=prnt,
                          style=wx.TAB_TRAVERSAL)
        self.notebook = Notebook(self, main)
        self.insertToolsPanel = insertTools.Panel(self.notebook, main)
        self.notebook.init_pages(self.insertToolsPanel,
                                 _(u"Insert settings"), u'insert.ico')
        self.numberingPanel = self.notebook.numbering
        self.dateTimePanel = self.notebook.dateTime


    def __init__(self, parent, main_window, params={}):
        Operation.__init__(self, params)
        global main
        main = main_window
        self.__init_ctrls(parent)
        self.__init_sizer(parent)

    def on_config_load(self):
        """Update GUI elements, settings after config load."""
        self.insertToolsPanel.activate_options(False)
        self.numberingPanel.on_config_load()
        self.dateTimePanel.get_from_item_checkbox(False)

    def reset_counter(self, c):
        """Reset the numbering counter for the operation."""
        utils.reset_counter(self, self.insertToolsPanel, c)

    def rename_item(self, path, name, ext, original):
        """Insert into name."""
        newName = self.join_ext(name, ext)
        if not newName:
            return path, name, ext

        insert = self.insertToolsPanel
        operations = insert.opButtonsPanel
        parsedText = operations.parse_input(insert.Text.GetValue(), original, self)
        # prefix
        if insert.prefix.GetValue():
            newName = parsedText + name
        # suffix
        elif insert.suffix.GetValue():
            newName = name + parsedText
        # exact position
        elif insert.position.GetValue():
            pos = insert.positionPos.GetValue()
            if pos == -1:
                newName += parsedText
            elif pos < -1:
                newName = newName[:pos + 1] + parsedText + newName[pos + 1:]
            else:
                newName = newName[:pos] + parsedText + newName[pos:]

        # insert before/after a character:
        elif insert.after.GetValue() or insert.before.GetValue():
            good2go = False
            textMatch = insert.BAtextMatch.GetValue()
            # text search
            if not insert.regExpPanel.regExpr.GetValue():
                try:
                    insertAt = newName.index(textMatch)
                except ValueError:
                    pass
                else:
                    if insert.after.GetValue():
                        insertAt += len(textMatch)
                    good2go = True
            # regular expression search
            else:
                insertRE = insert.regExpPanel.create_regex(textMatch)
                try:
                    insertAt = insertRE.search(newName).end()
                except AttributeError:
                    pass
                else:
                    if insert.before.GetValue():
                        insertAt -= len(textMatch)
                    good2go = True

            if good2go:
                newName = newName[:insertAt] + parsedText + newName[insertAt:]

        # insert in between 2 characters:
        # (copy of search.py function)
        elif insert.between.GetValue():
            good2go = False
            if insert.regExpPanel.regExpr.GetValue():
                mod1 = insert.regExpPanel.create_regex(insert.BTWtextMatch1.GetValue())
                mod2 = insert.regExpPanel.create_regex(insert.BTWtextMatch2.GetValue())
                try:
                    frm = mod1.search(newName).end()
                    to = mod2.search(newName, frm).start()
                except AttributeError:
                    pass
                else:
                    good2go = True
            else:
                match1 = insert.BTWtextMatch1.GetValue()
                match2 = insert.BTWtextMatch2.GetValue()
                try:
                    frm = newName.index(match1) + len(match1)
                    to = newName.index(match2, frm)
                except ValueError:
                    pass
                else:
                    good2go = True
            if good2go:
                newName = newName[:frm] + parsedText + newName[to:]

        name, ext = self.split_ext(newName, name, ext)

        return path, name, ext
Exemple #41
0
from notebook import Note, Notebook
from menu import Menu

n1 = Note("hello first")
n2 = Note("hello again")
print(n1.id)
print(n2.id)
n1.match('hello')
n2.match('second')

notb = Notebook()
notb.new_note("hello world")
notb.new_note("hello again")
print(notb.notes)

print(notb.notes[0].id)
print(notb.notes[1].id)

notb.notes[0]
notb.search("hello")
notb.search("world")

notb.modify_memo(1, "hi world")
print(notb.notes[0].memo)

print(dir(notb))
print(dir(n2))

print(isinstance(n1, Note))
print(isinstance(notb, Notebook))
 def listar_articulos(self):
     a=Notebook(None,None,None, None, None,None)
     return a.listar_articulos()
Exemple #43
0
class Menu:
    '''Display the menu and respond to choices'''
    def __init__(self):
        self.notebook = Notebook()
        self.choices = {
            "1" : self.show_notes,
            "2" : self.search_notes,
            "3" : self.add_note,
            "4" : self.modify_note,
            "5" : self.quit
        }

    def display_menu(self):
        print("""
        Notebook Menu
        1. Show all Notes
        2. Search Notes
        3. Add Note
        4. Modify Note
        5. Quit
        """)
    
    def run(self):
        '''Display the menu and response to choices'''
        while True:
            self.display_menu()
            choice = int(input("Enter an Opinion: "))
            if choice <= 0 and choice > 5:
                print(f"{choice} is Invalid choice")
            elif choice == 1:
                self.show_notes()
            elif choice == 2:
                self.search_notes()
            elif choice == 3:
                self.add_note()
            elif choice == 4:
                self.modify_note()
            elif choice == 5:
                self.quit()

    def show_notes(self, notes = None):
        if not notes:
            notes = self.notebook.notes
        for note in notes:
            print(f"{note.id} : {note.tags} \n {note.memo}")
    
    def search_notes(self):
        filter = input("Search for:")
        notes = self.notebook.search(filter)
        self.show_notes(notes)
    
    def add_note(self):
        memo = input("Enter a memo: ")
        self.notebook.new_note(memo)
        print("Your note has been added")

    def modify_note(self):
        id = input("Enter a note id: ")
        memo = input("Enter a memo: ")
        tags = input("Enter tags: ")
        if memo:
            self.notebook.modify_memo(id,memo)
        if tags:
            self.notebook.modify_tags(id, tags)

    def quit(self):
        print("Thank you for using your notebook today")
        sys.exit(0)
Exemple #44
0
	def __init__(self):
		super(type(self), self).__init__()
		debug(DEBUG_WINDOW)

		self._active_tab = None
		self._num_tabs = 0
		self._removing_tabs = False
		self._state = WINDOW_STATE_NORMAL
		self._dispose_has_run = False
		self._fullscreen_controls = None
		self._fullscreen_animation_timeout_id = 0

		#TODO
		#self._message_bus = MessageBus()

		self._window_group = gtk.WindowGroup()
		self._window_group.add_window(self)

		main_box = gtk.VBox(False, 0)
		self.add(main_box)
		main_box.show()

		# Add menu bar and toolbar bar
		self.create_menu_bar_and_toolbar(main_box)

		# Add status bar
		self.create_statusbar(main_box)

		# Add the main area
		debug_message(DEBUG_WINDOW, "Add main area")
		self._hpaned = gtk.HPaned()
		main_box.pack_start(self._hpaned, True, True, 0)

		self._vpaned = gtk.VPaned()
		self._hpaned.pack2(self._vpaned, True, False)
		
		debug_message(DEBUG_WINDOW, "Create taluka notebook")
		self._notebook = Notebook()
		self.add_notebook(self._notebook)

		# side and bottom panels
	  	self.create_side_panel()
		self.create_bottom_panel()

		# panes' state must be restored after panels have been mapped,
		# since the bottom pane position depends on the size of the vpaned.
		self._side_panel_size = prefs_manager_get_side_panel_size()
		self._bottom_panel_size = prefs_manager_get_bottom_panel_size()

		self._hpaned.connect_after("map", self.hpaned_restore_position)
		self._vpaned.connect_after("map", self.vpaned_restore_position)

		self._hpaned.show()
		self._vpaned.show()

		# Drag and drop support, set targets to None because we add the
		# default uri_targets below
		self.drag_dest_set(gtk.DEST_DEFAULT_MOTION | gtk.DEST_DEFAULT_HIGHLIGHT | gtk.DEST_DEFAULT_DROP, (), gtk.gdk.ACTION_COPY)

		# Add uri targets
		tl = self.drag_dest_get_target_list()
	
		if tl == None:
			tl = ()
			self.drag_dest_set_target_list(tl)

		tl += (TARGET_URI_LIST,)

		# connect instead of override, so that we can
		# share the cb code with the view TODO
#		self.connect("drag_data_received", drag_data_received_cb)

		# we can get the clipboard only after the widget
		# is realized TODO
#		self.connect("realize", window_realized)
#		self.connect("unrealize", window_unrealized)

		# Check if the window is active for fullscreen TODO
#		self.connect("notify::is-active", check_window_is_active)

		debug_message(DEBUG_WINDOW, "Update plugins ui")
	
#		plugins_engine_get_default().activate_plugins(self) TODO

		# set visibility of panes.
		# This needs to be done after plugins activatation TODO
#		self.init_panels_visibility()

#		self.update_sensitivity_according_to_open_tabs() TODO

		debug_message(DEBUG_WINDOW, "END")
		
#		self._action_group = gtk.ActionGroup("ExamplePyPluginActions")
#		self._action_group.add_actions(
#		                               [
#		                                ("File", None, "File", None, None, None),
#		                                ("FileNew", gtk.STOCK_NEW, None, None, None, commands._file_new),
#		                                ("FileOpen", gtk.STOCK_OPEN, None, None, None, commands._file_open),
#		                                ("FileSave", gtk.STOCK_SAVE, None, None, None, commands._file_save),
#		                                ("FileSaveAs", gtk.STOCK_SAVE_AS, None, "<shift><control>S",
#		                                 "Save the current file with a different name", commands._file_save_as),
#		                                ("FileClose", gtk.STOCK_CLOSE, None, None, None, commands._file_close),
#		                                ("FileQuit", gtk.STOCK_QUIT, None, None, None, commands._file_quit),
#		                                ("Edit", None, "Edit", None, None, None),
#		                                ("EditUndo", gtk.STOCK_UNDO, None, "<control>Z", None, commands._edit_undo),
#		                                ("EditRedo", gtk.STOCK_REDO, None, "<shift><control>Z", None, commands._edit_redo),
#		                                ("EditCut", gtk.STOCK_CUT, None, None, None, commands._edit_cut),
#		                                ("EditCopy", gtk.STOCK_COPY, None, None, None, commands._edit_copy),
#		                                ("EditPaste", gtk.STOCK_PASTE, None, None, None, commands._edit_paste),
#		                                ("EditSelectAll", gtk.STOCK_SELECT_ALL, None, None, None, commands._edit_select_all)
#		                               ],
#		                               self
#		                              )
#		
#		self._ui_manager = gtk.UIManager()
#		self._ui_manager.add_ui_from_file(os.path.join(reloc.DATADIR, 'taluka/taluka-ui.xml'))
#		self._ui_manager.insert_action_group(self._action_group, -1)
#		
#		vbox = gtk.VBox()
#		
#		self._menubar = self._ui_manager.get_widget("/MenuBar")
#		vbox.pack_start(self._menubar, expand=False)
#		
#		self._toolbar = self._ui_manager.get_widget("/ToolBar")
#		assert self._toolbar != None
#		vbox.pack_start(self._toolbar, expand=False)
#		
#		hpaned = gtk.HPaned()
#		
#		self._side_panel = Panel()
#		hpaned.pack1(self._side_panel, False, False)
#		
#		vpaned = gtk.VPaned()
#		self._notebook = Notebook()
#		vpaned.pack1(self._notebook, True, False)
#		
#		self._bottom_panel = Panel()
#		vpaned.pack2(self._bottom_panel, False, False)
#		
#		hpaned.pack2(vpaned, True, False)
#		
#		vbox.add(hpaned)
#		
#		self.add(vbox)
#		
#		self.connect("delete_event", self.on_delete_event)
#		self.connect("destroy", self.on_destroy)
#		self.show_all()
#		
#		#	static gboolean is_first = True;
#		#	GtkWidget *main_box;
#		#	GtkTargetList *tl;

#		debug(DEBUG_WINDOW)

#		#	window->priv = GEDIT_WINDOW_GET_PRIVATE (window);
#		
#		self._active_tab = None
#		
#		#	self._num_tabs = 0;
#		#	self._removing_tabs = FALSE;
#		self._state = WINDOW_STATE_NORMAL;
#		#	self._destroy_has_run = FALSE;

#		self._window_group = gtk.WindowGroup()
#		self._window_group.add_window(self)

#		#	main_box = gtk_vbox_new (FALSE, 0);
#		#	gtk_container_add (GTK_CONTAINER (window), main_box);
#		#	gtk_widget_show (main_box);

#		#	/* Add menu bar and toolbar bar */
#		#	create_menu_bar_and_toolbar (window, main_box);

#		#	/* Add status bar */
#		#	create_statusbar (window, main_box);

#		#	/* Add the main area */
#		#	gedit_debug_message (DEBUG_WINDOW, "Add main area");		
#		#	self._hpaned = gtk_hpaned_new ();
#		#  	gtk_box_pack_start (GTK_BOX (main_box), 
#		#  			    self._hpaned, 
#		#  			    True, 
#		#  			    True, 
#		#  			    0);

#		#	self._vpaned = gtk_vpaned_new ();
#		#  	gtk_paned_pack2 (GTK_PANED (self._hpaned), 
#		#  			 self._vpaned, 
#		#  			 True, 
#		#  			 FALSE);
#		#  	
#		#	gedit_debug_message (DEBUG_WINDOW, "Create gedit notebook");
#		#	self._notebook = gedit_notebook_new ();
#		#  	gtk_paned_pack1 (GTK_PANED (self._vpaned), 
#		#  			 self._notebook,
#		#  			 True, 
#		#  			 True);
#		#  	gtk_widget_show (self._notebook);  			 

#		#	/* side and bottom panels */
#		#  	create_side_panel (window);
#		#	create_bottom_panel (window);

#		#	/* restore paned positions as soon as we know the panes allocation.
#		#	 * This needs to be done only for the first window, the successive
#		#	 * windows are created by cloning the first one */
#		#	if (is_first)
#		#	{
#		#		is_first = FALSE;

#		#		self._side_panel_size = gedit_prefs_manager_get_side_panel_size ();
#		#		self._bottom_panel_size = gedit_prefs_manager_get_bottom_panel_size ();
#		#		g_signal_connect_after (self._hpaned,
#		#					"map",
#		#					G_CALLBACK (hpaned_restore_position),
#		#					window);
#		#		g_signal_connect_after (self._vpaned,
#		#					"map",
#		#					G_CALLBACK (vpaned_restore_position),
#		#					window);
#		#	}

#		#	gtk_widget_show (self._hpaned);
#		#	gtk_widget_show (self._vpaned);

#		#	/* Drag and drop support, set targets to NULL because we add the
#		#	   default uri_targets below */
#		#	gtk_drag_dest_set (GTK_WIDGET (window),
#		#			   GTK_DEST_DEFAULT_MOTION |
#		#			   GTK_DEST_DEFAULT_HIGHLIGHT |
#		#			   GTK_DEST_DEFAULT_DROP,
#		#			   NULL,
#		#			   0,
#		#			   GDK_ACTION_COPY);

#		#	/* Add uri targets */
#		#	tl = gtk_drag_dest_get_target_list (GTK_WIDGET (window));
#		#	
#		#	if (tl == NULL)
#		#	{
#		#		tl = gtk_target_list_new (NULL, 0);
#		#		gtk_drag_dest_set_target_list (GTK_WIDGET (window), tl);
#		#		gtk_target_list_unref (tl);
#		#	}
#		#	
#		#	gtk_target_list_add_uri_targets (tl, TARGET_URI_LIST);

#		# Connect signals
#		self._notebook.connect("switch_page", notebook_switch_page, self)
#		
#		#	g_signal_connect (self._notebook,
#		#			  "tab_added",
#		#			  G_CALLBACK (notebook_tab_added),
#		#			  window);
#		#	g_signal_connect (self._notebook,
#		#			  "tab_removed",
#		#			  G_CALLBACK (notebook_tab_removed),
#		#			  window);
#		#	g_signal_connect (self._notebook,
#		#			  "tabs_reordered",
#		#			  G_CALLBACK (notebook_tabs_reordered),
#		#			  window);			  
#		#	g_signal_connect (self._notebook,
#		#			  "tab_detached",
#		#			  G_CALLBACK (notebook_tab_detached),
#		#			  window);
#		#	g_signal_connect (self._notebook,
#		#			  "tab_close_request",
#		#			  G_CALLBACK (notebook_tab_close_request),
#		#			  window);
#		#	g_signal_connect (self._notebook,
#		#			  "button-press-event",
#		#			  G_CALLBACK (notebook_button_press_event),
#		#			  window);
#		#	g_signal_connect (self._notebook,
#		#			  "popup-menu",
#		#			  G_CALLBACK (notebook_popup_menu),
#		#			  window);

#		#	/* connect instead of override, so that we can
#		#	 * share the cb code with the view */
#		#	g_signal_connect (window,
#		#			  "drag_data_received",
#		#	                  G_CALLBACK (drag_data_received_cb), 
#		#	                  None)

#		#	/* we can get the clipboard only after the widget
#		#	 * is realized */
#		#	g_signal_connect (window,
#		#			  "realize",
#		#			  G_CALLBACK (window_realized),
#		#			  None)
#		#	g_signal_connect (window,
#		#			  "unrealize",
#		#			  G_CALLBACK (window_unrealized),
#		#			  None)

#		#	gedit_debug_message (DEBUG_WINDOW, "Update plugins ui");
#		#	gedit_plugins_engine_update_plugins_ui (gedit_plugins_engine_get_default (),
#		#						window, True);

#		#	/* set visibility of panes.
#		#	 * This needs to be done after plugins activatation */
#		#	init_panels_visibility (window);

#		#	gedit_debug_message (DEBUG_WINDOW, "END");
#		self.create_tab(True)

		self.show() # FIXME: Remove this file and use something like gedit-session.c instead.
Exemple #45
0
class Menu:
    def __init__(self):
        self.notebook = Notebook()
        self.choices = {
                        "1": self.make_new_entry,
                        "2": self.edit_entry,
                        "3": self.delete_entry,
                        "4": self.list_all_entries,
                        "5": self.list_books_for_author,
                        "6": self.quit,
                       }

    def run(self):
        while True:
            menu = ("Hi, please choose from one of the options below:\n\n" 
                    "1: Make a new entry for an author \n"
                    "2: Edit an entry \n"
                    "3: Delete an entry \n"
                    "4: List all entries.\n"
                    "5: List entries for an author\n"
                    "6: quit")
            print(menu)
            option = input("Option: ")
            action = self.choices.get(option)
            if action:
                action()

    def make_new_entry(self):
        author_name = input("Please enter the name of the author for which you would like to make a new entry: ")
        if not author_name:
            print("No name entered.")
        else:
            added = self.notebook.add_entry(author_name)
            if not added:
                print("An entry already exists for {}.\n".format(author_name))
            else:
                print("Entry for {} successfully created.\n".format(author_name))

    def show_edit_book_menu(self, entry):
        print("Would you like to add a new book, remove a book, or edit a book name? \n" 
               "1: Add a new book \n" 
               "2: Remove a book \n" 
               "3: Edit a book's name \n")
        option = input("Option: ")
        if not option:
            print("No option chosen.")
        else:
            if option == "1":
                book_name = input("Please enter the name of the book to be added: ")
                entry.add_book(book_name)
            elif option == "2":
                book_name = input("Please enter the name of the book to be removed: ")
                entry.remove_book(book_name)
            elif option == "3":
                old_book_name = input("Please enter the name of the book to be changed: ")
                new_book_name = input("Please enter the new name of the book: ")
                entry.edit_book(old_book_name, new_book_name)
            else:
                print("Invalid option.")

    def edit_entry(self):
        author_name = input("Please enter the name of the author whose entry you would like to edit: ")
        if not author_name:
            print("No name entered.")
        else:
            entry = self.notebook.get_entry_for_author(author_name)
            if not entry:
                print("No entry exists for {}".format(author_name))
            else:
                self.show_edit_book_menu(entry)

    def list_all_entries(self):
        self.notebook.list_authors()

    def list_books_for_author(self):
        author_name = input("Please enter the name of the author whose books you would like to see.")
        self.notebook.list_books_for_author(author_name)

    def delete_entry(self):
        author_name = input("Please enter the name of the author whose entry you want to delete.")
        if not author_name:
            print("No name entered.\n")
        else:
            deleted = self.notebook.delete_entry(author_name)
            if deleted:
                print("Entry for {} successfully deleted.\n".format(author_name))
            else:
                print("No entry for {}.\n".format(author_name))

    def quit(self):
        sys.exit(0)
Exemple #46
0
class Menu:
    def __init__(self):
        self.notebook = Notebook()
        self.choices = {
            '1': self.show_notes,
            '2': self.search_notes,
            '3': self.add_note,
            '4': self.modify_note,
            '5': self.quit
        }

    def display_menu(self):
        print("""
Notebook menu

1. Show all notes
2. Search notes
3. Add note
4. Modify note
5. QUit
""")

    def run(self):
        while True:
            self.display_menu()
            choice = input('Enter an option: ')
            action = self.choices.get(choice)
            if action:
                action()
            else:
                print("{} is not a valid choice".format(choice))

    def show_notes(self, notes=None):
        if not notes:
            notes = self.notebook.notes
        for note in notes:
            print("{}: {}\n{}".format(note.id, note.tags, note.memo))

    def search_notes(self):
        filter = input("Search for: ")
        notes = self.notebook.search(filter)
        self.show_notes(notes)

    def add_note(self):
        memo = input("Enter a memo: ")
        self.notebook.new_note(memo)
        print("Your note has been added")

    def modify_note(self):
        id = input("Enter a note id: ")
        memo = input("Enter a memo: ")
        tags = input("Enter tags: ")
        if memo:
            mem_mod = self.notebook.modify_memo(id, memo)
            if not mem_mod:
                print('memo {} does not exist'.format(id))
        if tags:
            tags_mod = self.notebook.modify_tags(id, tags)
            if not tags_mod:
                print('memo {} does not exist'.format(id))

    def quit(self):
        print("Thank you for using notebook today")
        sys.exit(0)
Exemple #47
0
class OpPanel(Operation):
    """This panel controls inserts."""
    def __init_sizer(self, parent):
        #smallestSize = parent.rightSizer.GetSize() - parent.rightTopSizer.GetSize() - (10,10)
        mainSizer = wx.BoxSizer(wx.VERTICAL)
        #mainSizer.SetMinSize(smallestSize)
        mainSizer.Add(self.notebook, 0, wx.EXPAND)
        self.SetSizerAndFit(mainSizer)

    def __init_ctrls(self, prnt):
        wx.Panel.__init__(self,
                          id=-1,
                          name=u'Panel',
                          parent=prnt,
                          style=wx.TAB_TRAVERSAL)
        self.notebook = Notebook(self, main)
        self.insertToolsPanel = insertTools.Panel(self.notebook, main)
        self.notebook.init_pages(self.insertToolsPanel, _(u"Insert settings"),
                                 u'insert.ico')
        self.numberingPanel = self.notebook.numbering
        self.dateTimePanel = self.notebook.dateTime

    def __init__(self, parent, main_window, params={}):
        Operation.__init__(self, params)
        global main
        main = main_window
        self.__init_ctrls(parent)
        self.__init_sizer(parent)

    def on_config_load(self):
        """Update GUI elements, settings after config load."""
        self.insertToolsPanel.activate_options(False)
        self.numberingPanel.on_config_load()
        self.dateTimePanel.get_from_item_checkbox(False)

    def reset_counter(self, c):
        """Reset the numbering counter for the operation."""
        utils.reset_counter(self, self.insertToolsPanel, c)

    def rename_item(self, path, name, ext, original):
        """Insert into name."""
        newName = self.join_ext(name, ext)
        if not newName:
            return path, name, ext

        insert = self.insertToolsPanel
        operations = insert.opButtonsPanel
        parsedText = operations.parse_input(insert.Text.GetValue(), original,
                                            self)
        # prefix
        if insert.prefix.GetValue():
            newName = parsedText + name
        # suffix
        elif insert.suffix.GetValue():
            newName = name + parsedText
        # exact position
        elif insert.position.GetValue():
            pos = insert.positionPos.GetValue()
            if pos == -1:
                newName += parsedText
            elif pos < -1:
                newName = newName[:pos + 1] + parsedText + newName[pos + 1:]
            else:
                newName = newName[:pos] + parsedText + newName[pos:]

        # insert before/after a character:
        elif insert.after.GetValue() or insert.before.GetValue():
            good2go = False
            textMatch = insert.BAtextMatch.GetValue()
            # text search
            if not insert.regExpPanel.regExpr.GetValue():
                try:
                    insertAt = newName.index(textMatch)
                except ValueError:
                    pass
                else:
                    if insert.after.GetValue():
                        insertAt += len(textMatch)
                    good2go = True
            # regular expression search
            else:
                insertRE = insert.regExpPanel.create_regex(textMatch)
                try:
                    insertAt = insertRE.search(newName).end()
                except AttributeError:
                    pass
                else:
                    if insert.before.GetValue():
                        insertAt -= len(textMatch)
                    good2go = True

            if good2go:
                newName = newName[:insertAt] + parsedText + newName[insertAt:]

        # insert in between 2 characters:
        # (copy of search.py function)
        elif insert.between.GetValue():
            good2go = False
            if insert.regExpPanel.regExpr.GetValue():
                mod1 = insert.regExpPanel.create_regex(
                    insert.BTWtextMatch1.GetValue())
                mod2 = insert.regExpPanel.create_regex(
                    insert.BTWtextMatch2.GetValue())
                try:
                    frm = mod1.search(newName).end()
                    to = mod2.search(newName, frm).start()
                except AttributeError:
                    pass
                else:
                    good2go = True
            else:
                match1 = insert.BTWtextMatch1.GetValue()
                match2 = insert.BTWtextMatch2.GetValue()
                try:
                    frm = newName.index(match1) + len(match1)
                    to = newName.index(match2, frm)
                except ValueError:
                    pass
                else:
                    good2go = True
            if good2go:
                newName = newName[:frm] + parsedText + newName[to:]

        name, ext = self.split_ext(newName, name, ext)

        return path, name, ext
def pytest_funcarg__notebook_with_two_notes(request):
    notebook = Notebook()
    notebook.new_note("hello world")
    notebook.new_note("hello again")
    return notebook
Exemple #49
0
class OpPanel(Operation):
    """This is the main panel for directory manipulations.

    It holds the notebook holding all directory panels.
    """

    def __init_sizer(self, parent):
        #smallestSize = parent.rightSizer.GetSize() - parent.rightTopSizer.GetSize() - (10,10)
        superSizer = wx.BoxSizer(wx.VERTICAL)
        #superSizer.SetMinSize(smallestSize)
        superSizer.Add(self.notebook, 0, wx.EXPAND)
        self.SetSizerAndFit(superSizer)

    def __init_ctrls(self, prnt):
        wx.Panel.__init__(self, id=-1, name=u'Panel', parent=prnt,
                          style=wx.TAB_TRAVERSAL)
        self.notebook = Notebook(self, main)
        self.directoryToolsPanel = directoryTools.Panel(self.notebook, main)
        self.notebook.init_pages(self.directoryToolsPanel,
                                 _(u"Directory settings"), u'directory.ico')
        self.numberingPanel = self.notebook.numbering
        self.dateTimePanel = self.notebook.dateTime


    def __init__(self, parent, main_window, params={}):
        Operation.__init__(self, params)
        global main
        main = main_window
        self.set_as_path_only()
        self.__init_ctrls(parent)
        self.__init_sizer(parent)
        self.update_parameters(self.directoryToolsPanel.params)

    def on_config_load(self):
        """Update GUI elements, settings after config load."""
        self.numberingPanel.on_config_load()
        self.dateTimePanel.get_from_item_checkbox(False)

    def __add_path(self, newPath, path):
        """Extra operation for absolute paths."""
        recurPath = ''
        recur = self.directoryToolsPanel.pathRecur.GetValue()
        path = path.split(os.sep)
        # remove drive letter
        if wx.Platform == '__WXMSW__':
            path = path[1:]

        # inverse the selection or not
        if not self.directoryToolsPanel.inverse.GetValue():
            if recur <= 0:
                recur -= 1
            path = path[-recur:]
        else:
            path = path[:-recur]

        # reassemble path
        for segment in path:
            recurPath = os.path.join(recurPath, segment)
        newPath = newPath.replace(self.params['pathStructTxt'], recurPath)
        return newPath

    def __add_file_name(self, newPath, name, ext):
        if self.directoryToolsPanel.useFileExt.GetValue() and self.directoryToolsPanel.useFileName.GetValue():
            if ext:
                ext = '.' + ext
            parsedName = name + ext
        elif self.directoryToolsPanel.useFileName.GetValue():
            parsedName = name
        elif self.directoryToolsPanel.useFileExt.GetValue():
            parsedName = ext
        else:
            parsedName = ''

        newPath = newPath.replace(self.params['nameTxt'], parsedName)
        return newPath

    def reset_counter(self, c):
        """Reset the numbering counter for the operation."""
        utils.reset_counter(self, self.directoryToolsPanel, c)

    def rename_item(self, path, name, ext, original):
        """Create the new path."""
        rejoin = False
        operations = self.directoryToolsPanel.opButtonsPanel
        newPath = self.directoryToolsPanel.directoryText.GetValue()
        params = self.params

        # absolute path
        if os.path.isabs(newPath):
            split = os.path.splitdrive(newPath)
            newPath = split[1]
            rejoin = True

        # add path structure
        if params['pathStructTxt'] in newPath:
            newPath = self.__add_path(newPath, path)

        # add filename
        if params['nameTxt'] in newPath:
            newPath = self.__add_file_name(newPath, name, ext)

        newPath = operations.parse_input(newPath, original, self)

        if rejoin:
            newPath = os.path.join(split[0], newPath)
        else:
            newPath = os.path.join(path, newPath)

        return (newPath, name, ext)
Exemple #50
0
		def __init__(self):
		self.notebook = Notebook()
		self.choices = {
		"1":self.show_notes,
		"2":self.search_notes,
		"3":self.add_note,
		"4":self.modify_note.
		"5":self.quit
		}
		
		def display(self):
			print ('''
			Notebook Menu
			1.show all Notes
			2.Search Notes
			3.Add Note
			4.Modify Note
			5.Quit
			''')
		def run(self):
			while True:
				self.display_menu():
				choice = input('enter an option')
				action = sef.choice.get(choice)
				if action:
					action()
				else:
				print ("{0}is not a valid choice".format(choice))
			
		def show_notes(self,note = None):
			if not notes:
				notes = self.notebook.notes
			for note in notes:
			print('{0}:{1}\n{2}".format(
				note.id,note.tags,note.memo))
		def search_notes(self):
			filter = input('search for:')
			notes = self.notebook.search(filter)
			self.show_notes(notes)
		def add_note(self):
			memo = input('enter a memo:')
			self.notebook.new_note(memo)
			print ('your note has been added.')
		def modify_note(self):
			id = input('enter a note id:')
			memo = input('enter a memo:')
			tags = input('enter  tags:')
			if memo:
				self.notebook.modift_memo(id,memo)
			if tags:
				self.motebookl.modify_tags(id,tags)
		def quit(self):
			print ('sdf')
			sys.exit(0)
	if __name__ ==" __main__":
		Menu().run()
		'''#这段代码首先通过一个绝对导入语句导入笔记本对象,
		不能使用相对导入,因为我们还没有把我们的代码放到一个包里。
		menu 的run方法会重复地现实菜单选项(dict),用户输入一个choice,就从dict里检索这个对象
		action实际上是调用一个特定方法的接口,通过action()来调用这个方法。
		当用户输入不存在的选项时,返回错误提示语句,所以action里面需要一个判断检查。'''
		
class Contact:
#类的继承
	all_contacts = []
	def __init__(self,name,email):
		self.name = name
		self.email = email 
		Contact.all_contacts.append(self)		
class Supplier(Contact):
	def order(self,order):
		print ('the order of {} is {}'.format(order,self.name))
c = Contact('a','email')
s = Supplier('v','emails')
s.order('your order')

'''创建一个新的类来扩展list,然后实例化这个子类(Contactlist)作为列表(all_contacts = Contactlist()),
和上面不同(上面是实例化一个list作为一个类)'''
class Contactlist(list):#list这个内置语法,我们创建一个空的列表,[] == list()(相同的语法),然后这个就可以扩展,
	def search(self,name):#拓展内置类最典型的就是给它增加功能。扩展一个search方法,通过名字来搜索联系人
		matching_contacts = []
		for contact in self:
			if name in Contact.name:
				maching_contacts.append(contact)
			return matching_contacts
class Contact:
	all_contacts = Contactlist()#联系上面的class Contactlist(list),list可以扩展,()里也可以用dict,但是dict语法很繁琐。
	def __init__(self,name,email):
	self.name = name
	self.email = email 
	self.all_contacts.append(self)
a1 = Contact('sdf','aw')
a2 = Contact('asdf','f*g')
a.name for a in Contact.all_contacts.search('df')

class fx(dict):#dict的扩展
	def f2(self):
		longest = None
		for key in self:
			if not longest or len(key) > len(longest):
				longest = key
			return longest

		
>>> longkeys = fx()
>>> longkeys['hello'] = 1
>>> longkeys['longest yet'] = 5
>>> longkeys['hello2'] = 'world'
>>> longkeys.f2()
'longest yet'
>>> longkeys['wefadsgsfds'] = 2
>>> longkeys.f2()
'wefadsgsfds'

#重写和super:就是在子类里想要添加新方法或者改变或者覆盖父类(超类)里的方法,使得整个父类都可以用这个功能
class Friend(Contact):
	def __init__(self,name,email,phone):
		super().__init__(name,email)
		self.phone = phone
		#上面的super().__init__(name,email) 相当于复制父类里面的属性的简写 :
		''' self.name = name
			self.email = email'''
		#然后再加上自己的属性,self.phone = phone
		
#super的使用,super表示调用下一个(index),父类总是排在派生类之后,所以object最后被调用。
class Baseclass:
	num_base_calls = 0
	def call_me(self):
		print 'calling method on the base class'
		self.num_base_calls +=1
Exemple #51
0
class Menu:
    """To work with menu"""
    def __init__(self):
        """Init func"""
        self.notebook = Notebook()
        self.choices = {
            "1": self.show_notes,
            "2": self.search_notes,
            "3": self.add_note,
            "4": self.modify_note,
            "5": self.quit
        }

    def display_menu(self):
        """To show menu"""
        print("""
        Notebook Menu
        1. Show all Notes
        2. Search Notes
        3. Add Note
        4. Modify Note
        5. Quit
        """)

    def run(self):
        """To run this file as long as user uses it"""
        while True:
            self.display_menu()
            choice = input("Enter an option: ")
            action = self.choices.get(choice)
            if action:
                action()
            else:
                print("{0} is not a valid choice".format(choice))

    def show_notes(self, notes=None):
        """To check which notes you already have"""
        if not notes:
            notes = self.notebook.notes
        for note in notes:
            print("{0}: {1}\n{2}".format(note.id, note.tags, note.memo))

    def search_notes(self):
        """To search for key words in all your notes"""
        filter = input("Search for: ")
        notes = self.notebook.search(filter)
        self.show_notes(notes)

    def add_note(self):
        """To add new note"""
        memo = input("Enter a memo: ")
        self.notebook.new_note(memo)
        print("Your note has been added.")

    def modify_note(self):
        """To mdify notes"""
        id = input("Enter a note id: ")
        memo = input("Enter a memo: ")
        tags = input("Enter tags: ")
        if memo:
            self.notebook.modify_memo(id, memo)
        if tags:
            self.notebook.modify_tags(id, tags)

    def quit(self):
        """To stop runing this project"""
        print("Thank you for using your notebook today.")
        sys.exit(0)
class Menu:
    '''
    Display a menu and respond to choices when run
    '''

    def __init__(self):
        self.notebook = Notebook()
        # Map strings to functions
        self.choices = {
            "1": self.show_notes,
            "2": self.search_notes,
            "3": self.add_note,
            "4": self.modify_note,
            "5": self.quit}

    def display_menu(self):
        print("""
        Notebook menu

        1. Show all Notes
        2. Search Notes
        3. Add Note
        4. Modify Note
        5. Quit

        """)

    def run(self):
        '''
        Repeatedly display the menu and respond to choices
        Calls functions on the notebook
        :return:
        '''

        while True:
            self.display_menu()
            choice = input("Enter an option: ")
            action = self.choices.get(choice)
            if action:
                action()
            else:
                print("{0} is not a valid choice".format(choice))

    def show_notes(self, notes=None):
        if not notes:
            notes = self.notebook.notes
        for note in notes:
            print("{0}: {1}\n{2}".format(note.id, note.tags, note.memo))

    def search_notes(self):
        filter = input("Search for: ")
        notes = self.notebook.search(filter)
        # Serves double duty
        # if notes supplied, displays only filtered notes
        # if none supplied, displays all notes
        self.show_notes(notes)

    def add_note(self):
        memo = input("Enter a memo: ")
        self.notebook.new_note(memo)
        print("Your note has been added.")

    def modify_note(self):
        id = input("Enter a note id: ")
        memo = input ("Enter a memo")
        tags = input ("Enter tags: ")
        if memo:
            self.notebook.modify_memo(id, memo)
        if tags:
            self.notebook.modify_tags(id,tags)

    def quit(self):
        print("Thank you for using your notebook today.")
        sys.exit(0)
Exemple #53
0
def write_example(src_name, src_dir, rst_dir, cfg):
    """Write rst file from a given python example.

    Parameters
    ----------
    src_name : str
        Name of example file.
    src_dir : 'str'
        Source directory for python examples.
    rst_dir : 'str'
        Destination directory for rst files generated from python examples.
    cfg : config object
        Sphinx config object created by Sphinx.
    """
    last_dir = src_dir.psplit()[-1]
    # to avoid leading . in file names, and wrong names in links
    if last_dir == '.' or last_dir == 'examples':
        last_dir = Path('')
    else:
        last_dir += '_'

    src_path = src_dir.pjoin(src_name)
    example_file = rst_dir.pjoin(src_name)
    shutil.copyfile(src_path, example_file)

    image_dir = rst_dir.pjoin('images')
    thumb_dir = image_dir.pjoin('thumb')
    notebook_dir = rst_dir.pjoin('notebook')
    image_dir.makedirs()
    thumb_dir.makedirs()
    notebook_dir.makedirs()

    base_image_name = os.path.splitext(src_name)[0]
    image_path = image_dir.pjoin(base_image_name + '_{0}.png')

    basename, py_ext = os.path.splitext(src_name)
    rst_path = rst_dir.pjoin(basename + cfg.source_suffix)
    notebook_path = notebook_dir.pjoin(basename + '.ipynb')

    if _plots_are_current(src_path, image_path) and rst_path.exists and \
        notebook_path.exists:
        return

    print('plot2rst: %s' % basename)

    blocks = split_code_and_text_blocks(example_file)
    if blocks[0][2].startswith('#!'):
        blocks.pop(0) # don't add shebang line to rst file.

    rst_link = '.. _example_%s:\n\n' % (last_dir + src_name)
    figure_list, rst = process_blocks(blocks, src_path, image_path, cfg)

    has_inline_plots = any(cfg.plot2rst_plot_tag in b[2] for b in blocks)
    if has_inline_plots:
        example_rst = ''.join([rst_link, rst])
    else:
        # print first block of text, display all plots, then display code.
        first_text_block = [b for b in blocks if b[0] == 'text'][0]
        label, (start, end), content = first_text_block
        figure_list = save_all_figures(image_path)
        rst_blocks = [IMAGE_TEMPLATE % f.lstrip('/') for f in figure_list]

        example_rst = rst_link
        example_rst += eval(content)
        example_rst += ''.join(rst_blocks)
        code_info = dict(src_name=src_name, code_start=end)
        example_rst += LITERALINCLUDE.format(**code_info)

    example_rst += CODE_LINK.format(src_name)
    ipnotebook_name = src_name.replace('.py', '.ipynb')
    ipnotebook_name = './notebook/' + ipnotebook_name
    example_rst += NOTEBOOK_LINK.format(ipnotebook_name)

    f = open(rst_path, 'w')
    f.write(example_rst)
    f.flush()

    thumb_path = thumb_dir.pjoin(src_name[:-3] + '.png')
    first_image_file = image_dir.pjoin(figure_list[0].lstrip('/'))
    if first_image_file.exists:
        first_image = io.imread(first_image_file)
        save_thumbnail(first_image, thumb_path, cfg.plot2rst_thumb_shape)

    if not thumb_path.exists:
        if cfg.plot2rst_default_thumb is None:
            print("WARNING: No plots found and default thumbnail not defined.")
            print("Specify 'plot2rst_default_thumb' in Sphinx config file.")
        else:
            shutil.copy(cfg.plot2rst_default_thumb, thumb_path)

    # Export example to IPython notebook
    nb = Notebook()

    # Add sphinx roles to the examples, otherwise docutils
    # cannot compile the ReST for the notebook
    sphinx_roles = PythonDomain.roles.keys()
    preamble = '\n'.join('.. role:: py:{0}(literal)\n'.format(role)
                         for role in sphinx_roles)

    # Grab all references to inject them in cells where needed
    ref_regexp = re.compile('\n(\.\. \[(\d+)\].*(?:\n[ ]{7,8}.*)+)')
    math_role_regexp = re.compile(':math:`(.*?)`')

    text = '\n'.join((content for (cell_type, _, content) in blocks
                     if cell_type != 'code'))

    references = re.findall(ref_regexp, text)

    for (cell_type, _, content) in blocks:
        if cell_type == 'code':
            nb.add_cell(content, cell_type='code')
        else:
            if content.startswith('r'):
                content = content.replace('r"""', '')
                escaped = False
            else:
                content = content.replace('"""', '')
                escaped = True

            if not escaped:
                content = content.replace("\\", "\\\\")

            content = content.replace('.. seealso::', '**See also:**')
            content = re.sub(math_role_regexp, r'$\1$', content)

            # Remove math directive when rendering notebooks
            # until we implement a smarter way of capturing and replacing
            # its content
            content = content.replace('.. math::', '')

            if not content.strip():
                continue

            content = (preamble + content).rstrip('\n')
            content = '\n'.join([line for line in content.split('\n') if
                                 not line.startswith('.. image')])

            # Remove reference links until we can figure out a better way to
            # preserve them
            for (reference, ref_id) in references:
                ref_tag = '[{0}]_'.format(ref_id)
                if ref_tag in content:
                    content = content.replace(ref_tag, ref_tag[:-1])

            html = publish_parts(content, writer_name='html')['html_body']
            nb.add_cell(html, cell_type='markdown')

    with open(notebook_path, 'w') as f:
        f.write(nb.json())
Exemple #54
0
class Menu:
	"""
	Represent a command-line user interface for Notebook application.
	"""

	def __init__(self):
		self.notebook = Notebook()
		self.choices = OrderedDict.fromkeys('12345')
		self.choices['1'] = {'display': 'Show notes',
							 'handler': self.show_notes}
		self.choices['2'] = {'display': 'Search notes',
							 'handler': self.search_notes}
		self.choices['3'] = {'display': 'Add notes',
							 'handler': self.add_note}
		self.choices['4'] = {'display': 'Modify notes',
							 'handler': self.modify_note}
		self.choices['5'] = {'display': 'Quit',
							 'handler': self.quit}

	def display_menu(self):
		"""
		Display the Notebook application's menu.
		"""
		print('==================')
		for k, v in self.choices.items():
			print(k, v.get('display'))

		choice = input('What do you want to do? ')
		action = self.choices.get(choice)

		if action:
			handler = action.get('handler')
			handler()
		else:
			print(choice, 'is not a valid choice')

	def run(self):
		"""
		Run the application: display the menu and respond to user's choice.
		"""
		while True:
			self.display_menu()
			pass

	def show_notes(self, notes=None):
		"""
		Display all notes in the notebook.
		"""

		if notes is None:
			notes = self.notebook.notes

		if len(notes) > 0:
			for note in notes:
				print(note, '\r\n')
		else:
			print("No note matches.")

	def search_notes(self):
		"""
		Search for a note in the notebook (by its content and tags).
		"""
		search_string = input('You want to search for ...? ')
		filtered_notes = self.notebook.search(search_string)
		self.show_notes(filtered_notes)

	def add_note(self):
		"""
		Add a new note to the notebook.
		"""
		memo = input('Enter the memo: ')
		tags = input('Enter the tags (separated by commas): ')
		self.notebook.create_note(memo, tags)
		print('Your note has been created.')

	def modify_note(self):
		"""
		Modify a note in the notebook.
		"""
		note_id = input('Enter the note id: ')
		note = self.notebook.find_note_by_id(note_id)

		if note is None:
			print('No note matches.')
		else:
			memo = input('Enter the new memo: ')
			tags = input('Enter the new tags (separated by commas): ')

			if memo:
				note.memo = memo

			if tags:
				note.tags = tags

	def quit(self):
		"""
		Exit the application.
		"""
		print("Thank you for using Notebook application.")
		sys.exit(0)