Exemplo n.º 1
0
  def __init__(self, A_f, numLevels, theta=0.25, verb=0, graph=False):
    timer = Timer('AMG setup')
    self.seqA = [None]*numLevels
    self.updates = [None]*numLevels
    self.downdates = [None]*numLevels
    self.seqA[numLevels-1] = A_f

    tab1 = Tab()
    tab2 = Tab()
    for i in reversed(range(numLevels-1)):
      Debug.msg1(verb, '-------------------------------------------------------------')
      Debug.msg1(verb, tab1, 'coarsening level %d to level %d' % (i+1,i))
      np.set_printoptions(threshold=np.inf)
      Debug.msg4(verb, tab2, 'operator is A[%d]\n' % i, self.seqA[i+1].tolil())
      C = coarsen(self.seqA[i+1], theta = theta, verb=verb)
      Debug.msg2(verb, tab2, '#vertices: %d' % len(C))
      if graph:
        matrixGraph(self.seqA[i+1], C, name='graph-%d.gv' % i)
      Debug.msg1(verb, tab1, 'making update operator: level %d to level %d' % (i+1,i))
      I_up = smoothUpdate(self.seqA[i+1], C, verb)
      Debug.msg1(verb, tab1, 'making downdate operator: level %d to level %d' % (i,i+1))
      I_down = makeDowndate(I_up, verb)
      self.updates[i] = I_up
      self.downdates[i] = I_down
      self.seqA[i] = self.downdates[i]*(self.seqA[i+1]*self.updates[i])
Exemplo n.º 2
0
    def setUpClass(self):

        username = os.getenv(constants.USERNAME, "")
        password = os.getenv(constants.PASSWORD, "")
        """Start web browser"""
        self._browser = Tab()
        self._browser.login_on_page(constants.DERA_SCM_URL, username, password)
Exemplo n.º 3
0
    def __init__(self, nb):
        Tab.__init__(self, nb)
        self.project_list = wx.ListCtrl(self, -1, style=wx.LC_REPORT, size=(700, 400))
        self.project_list.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self._load_project)
        
        self._il = wx.ImageList(16,16)
        self._il.Add(bitmaps.fetch_icon_bitmap("actions", "agt_action_success", scale=(16,16)))
        self.project_list.SetImageList(self._il, wx.IMAGE_LIST_SMALL)        

        titles = ['', 'Title', '# Jobs', 'Last Action']
        sizes = [20,400, 100,140]
        for i,t in enumerate(titles):
            self.project_list.InsertColumn(i, t)
            self.project_list.SetColumnWidth(i, sizes[i])
        
        self.sidebar = wx.BoxSizer(wx.VERTICAL)
        
        new = metallicbutton.MetallicButton(self, -1, 'New', '', bitmaps.fetch_icon_bitmap("actions", "folder_new"), size=(120,40))
        delete = metallicbutton.MetallicButton(self, -1, 'Delete', '', bitmaps.fetch_icon_bitmap("actions", "fileclose"), size=(120,40))
        load = metallicbutton.MetallicButton(self, -1, 'Load', '', bitmaps.fetch_icon_bitmap("actions", "folder"), size=(120,40))
         
        self.Bind(wx.EVT_BUTTON, self._new_project, new)
        self.Bind(wx.EVT_BUTTON, self._load_project, load)
        self.Bind(wx.EVT_BUTTON, self._delete_project, delete)
                
        self.sidebar.Add(new, 0, wx.EXPAND|wx.ALL, 5)
        self.sidebar.Add(load, 0, wx.EXPAND|wx.ALL, 5)
        self.sidebar.Add(delete, 0, wx.EXPAND|wx.ALL, 5)
        
        self.sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.sizer.Add(self.project_list, 0, wx.EXPAND | wx.ALL, 5)
        self.sizer.Add(self.sidebar, 0, wx.EXPAND | wx.ALL, 5)
        
        self.SetSizer(self.sizer)
Exemplo n.º 4
0
    def render_graphs(self):
        # If MDF loaded iterate through tabs and render each plot onto their graphs.
        if self.mdf_extracted != None:
            # Delete old tab wigets. Redraw leads to ugly behavior.
            for i in reversed(range(self.tabs.count())):
                self.tabs.removeTab(i)
            new_tabs = []
            # Create new tab widgets, add to new tab list.
            for tab_obj in self.tab_list:
                newTab = Tab(tab_obj.get_title(), self.play_slider)
                for plot in tab_obj.get_plots():
                    group = plot[0]
                    signal = plot[1]
                    try:
                        mdf_obj = self.channel_dict[group][signal]
                        if mdf_obj is not None:
                            newTab.add_plot(group, signal, mdf_obj.timestamps,
                                            mdf_obj.samples, mdf_obj.unit)
                    except Exception:
                        newTab.add_plot(group, signal)
                self.tabs.addTab(newTab.get_tab_widget(), newTab.get_title())
                new_tabs.append(newTab)
                newTab.render_multiplot()

            # Replace old tab list with new and redraw features.
            self.tab_list.clear()
            self.tab_list = new_tabs
            self.redraw_slider()
Exemplo n.º 5
0
 def __init__(self, nb):
     Tab.__init__(self, nb)
     
     Refinement.set_proot(self.s.proot)
     
     # plot
     self.dpi = 100
     self.fig = Figure((5.0, 4.0), dpi=self.dpi)
     col = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BACKGROUND)
     self.fig.patch.set_facecolor((col[0]/255.0, col[1]/255.0, col[2]/255.0))
     self.canvas = FigCanvas(self, -1, self.fig)
     self.ax1 = self.fig.add_subplot(111)
     self.ax1.set_position([0.115,0.17,0.80,0.79])
     [i.set_linewidth(0.5) for i in self.ax1.spines.itervalues()]
     self.ax2 = self.ax1.twinx()
     self.ax2.set_position([0.115,0.17,0.80,0.79])
     self._clear_figure()
             
     # stats
     self.stats_sizer = wx.FlexGridSizer(cols=2, rows=9, hgap=5, vgap=5)
     self._labels = [
         wx.StaticText(self, -1, 'Title'),
         wx.StaticText(self, -1, 'Status'),
         wx.StaticText(self, -1, 'Cycle'),
         wx.StaticText(self, -1, 'Resolution (A)'),
         wx.StaticText(self, -1, 'R-work (%)'),
         wx.StaticText(self, -1, 'R-free (%)'),
         wx.StaticText(self, -1, '# of Reflections'),
         wx.StaticText(self, -1, 'Parameters'),
         wx.StaticText(self, -1, 'Data:Parameter')
     ]
     
     self._labels[0].Wrap(200)
     self._values = [ wx.StaticText(self, -1, '') for x in range(len(self._labels)) ]
     
     rows = [1,2,3,4,6]
     for i in range(len(self._labels)):
         self.stats_sizer.Add(self._labels[i], 0, wx.EXPAND|wx.TOP, i in rows and 15 or 5)
         self.stats_sizer.Add(self._values[i], 0, wx.EXPAND|wx.TOP, i in rows and 15 or 5)
     
     self.vbox = wx.BoxSizer(wx.VERTICAL)
     self.vbox.Add(self.stats_sizer, 0, wx.ALL, 10)
             
     self.button_sizer = wx.BoxSizer(wx.HORIZONTAL)
     self.vbox.Add(self.button_sizer, 0, wx.EXPAND|wx.CENTER, 10)
             
     self.hbox = wx.BoxSizer(wx.HORIZONTAL)
     self.hbox.Add(self.vbox, 1, wx.EXPAND|wx.ALL, 10)
     self.hbox.Add(self.canvas, 4, wx.EXPAND|wx.ALL, 10)
 
     self.SetSizer(self.hbox)
     self.hbox.Fit(self)
     
     self._refinement = None
Exemplo n.º 6
0
    def populate(self, categories_list):
        self.favorites_tab = FavoriteTab(self.notebook, self,
                                         self.favorites_image)
        self.expired_tab = ExpiredTab(self.notebook, self, self.expired_image,
                                      self.favorites_tab)
        self.favorites_tab.set_expired_tab(self.expired_tab)
        for i in range(len(categories_list)):

            new_tab = Tab(self.notebook, categories_list[i], self,
                          self.favorites_tab, self.expired_tab)
            new_tab.populate_tab()
            self.tabs_list.append(new_tab)
Exemplo n.º 7
0
    def __init__(self, window):
        self.databaseWindow = window

        store = Gtk.TreeStore(str)
        Tab.__init__(self, store)

        renderer = Gtk.CellRendererText()

        column = Gtk.TreeViewColumn("Name", renderer, text=0)
        column.set_resizable(True)
        column.set_expand(True)
        self.tree.append_column(column)
Exemplo n.º 8
0
    def generateTab(self):
        self.error_window = QtWidgets.QErrorMessage()
        error_count = 0
        message = ""
        tab_idx = -1

        # Check empty fields.
        if self.title.text() == "":
            error_count += 1
            message += "ERROR {}: You must enter a title.".format(error_count)
        if len(self.added_dict) == 0:
            error_count += 1
            message += "ERROR {}: You must apply at least one signal.".format(
                error_count)

        # Check if tab name unique. If no check if intent is to edit,
        if self.title.text() in [
                tab.get_title() for tab in self.main.tab_list
        ]:
            if self.edit == True:
                tab_idx = [
                    idx if self.title.text() == tab.get_title() else -1
                    for idx, tab in enumerate(self.main.tab_list)
                ]
                tab_idx = tab_idx[0]
            else:
                error_count += 1
                message += "ERROR {}: Tab title \"{}\" is already taken.".format(
                    error_count, self.title.text())

        # If errors then present else add tab to main window and close.
        if error_count > 0:
            self.error_window.showMessage(message)
        else:
            newTab = Tab(self.title.text(), self.main.play_slider)
            newTab.add_plots(self.added_dict)
            newTab.render_multiplot()

            # If editing delete old tab and replace with new at same index. Else append.
            if tab_idx != -1:
                self.main.tabs.removeTab(tab_idx)
                self.main.tabs.insertTab(tab_idx, newTab.get_tab_widget(),
                                         newTab.get_title())
                self.main.tab_list.pop(tab_idx)
                self.main.tab_list.insert(tab_idx, newTab)
            else:
                self.main.tabs.addTab(newTab.get_tab_widget(),
                                      newTab.get_title())
                self.main.tab_list.append(newTab)

            self.main.render_graphs()
            self.close()
Exemplo n.º 9
0
    def LoadWorkspace(self):
        # On "Import Workspace" load JSON and generate tab objects in tab_list.
        file_path = QtWidgets.QFileDialog.getOpenFileName(
            self, 'Import Workspace',
            os.getcwd() + "/" + self.workspace_file, "JSON (*.json)")

        try:
            with open(file_path[0]) as fd:

                # Remove any old tabs. Clean slate.
                for i in reversed(range(self.tabs.count())):
                    self.tabs.removeTab(i)
                self.tab_list.clear()

                # Generate new tabs.
                tab_data = json.load(fd)
                for tab, groups in tab_data.items():
                    new_tab = Tab(tab, self.play_slider)
                    new_tab.add_plots(groups)
                    new_tab.render_multiplot()

                    self.tabs.addTab(new_tab.get_tab_widget(),
                                     new_tab.get_title())
                    self.tab_list.append(new_tab)
            self.workspace_file = os.path.split(file_path[0])[1]
        except Exception:
            pass

        # Display data immediately upon upload if MDF already uploaded.
        self.render_graphs()
Exemplo n.º 10
0
 def addNewTab(self, modus, tabData=None):
     """adds new tab"""
     if (tabData is None):
         tab = Tab(
             modus,
             QtCore.QCoreApplication.translate("MainWindow", "Neuer Tab"))
         self.tabWidget.insertTab(
             self.tabWidget.count() - 1, tab,
             QtCore.QCoreApplication.translate("MainWindow", "Neuer Tab"))
     else:
         tab = Tab(modus, tabData.name, tabData)
         self.tabWidget.insertTab(
             self.tabWidget.count() - 1, tab,
             QtCore.QCoreApplication.translate("MainWindow", tabData.name))
     self.tabWidget.setCurrentIndex(self.tabWidget.count() - 2)
Exemplo n.º 11
0
    def __init__(self, nb):
        Tab.__init__(self, nb)
        
        Holder.set_finished_callback(self._job_finished)
                
        self._tabs = wx.aui.AuiNotebook(self, -1, size=(700,750))
        
        self.main = wx.BoxSizer(wx.HORIZONTAL)
        self.main.Add(self._tabs, 1 , wx.EXPAND)
        self.SetSizer(self.main)

        self._auto_manager = AutoProcessManager()
        AutoProcess.set_start_refinement(self.start_new_refinement)
        
        self._running = 0
Exemplo n.º 12
0
    def __init__(self, windowDatabase):
        self.windowDatabase = windowDatabase
        store = Gtk.ListStore(int, str, str)
        Tab.__init__(self, store)

        for i, value in enumerate(itemModel):
            renderer = Gtk.CellRendererText()
            if value != "ID":
                renderer.set_property("editable", True)
            renderer.connect("edited", self.editRenderer, value)
            column = Gtk.TreeViewColumn(value, renderer, text=i)
            column.set_resizable(True)
            column.set_expand(True)
            self.tree.append_column(column)

        self.itemCapacities = list()
Exemplo n.º 13
0
    def __init__(self, nb):
        Tab.__init__(self, nb)

        self._tabs = wx.aui.AuiNotebook(self, -1, style=wx.NB_TOP, size=(850,750))
        self.sheet1 = Projects(self._tabs)
        
                
        self.sheet2 = Jobs(self._tabs)

        self._tabs.AddPage(self.sheet1, "Projects")
        self._tabs.AddPage(self.sheet2, "Job List")
            
        self.main = wx.BoxSizer(wx.HORIZONTAL)
        self.main.Add(self._tabs, 1, wx.EXPAND)
        
        self.SetSizer(self.main)
Exemplo n.º 14
0
    def __init__(self, nb):
        Tab.__init__(self, nb)

        #Process.set_finished_callback(self.refinement_finished)
        
        self._tabs = wx.aui.AuiNotebook(self, -1, style=wx.NB_TOP, size=(850,750))
        self._tab_list = []
        
        self._stats = Process(self)
        self._stats.set_finished_callback(self.refinement_finished)
        self._tabs.AddPage(self._stats, 'Refinement')

        self.sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.sizer.Add(self._tabs, 1, wx.EXPAND)
            
        self.SetSizer(self.sizer)
Exemplo n.º 15
0
Arquivo: App.py Projeto: balu/fm
 def dup_tab(self):
     t = Tab.create(self, self.gettab().path())
     if t:
         self.tablist.append(t)
         self.curtab = len(self.tablist) - 1
         self.UI.draw()
     return True
Exemplo n.º 16
0
    def __init__(self, nb):
        Tab.__init__(self, nb)
        
        self.job_list = wx.ListCtrl(self, -1, style=wx.LC_REPORT|wx.LC_SINGLE_SEL, size=(700, 400))
        self.job_list.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self._load_job)
        
        titles = ['ID', 'Date', 'Title', 'Type', 'Status', 'R']
        sizes = [65,135,225,130,80,60]
        for i,t in enumerate(titles):
            self.job_list.InsertColumn(i, t, width=sizes[i])

        new = metallicbutton.MetallicButton(self, -1, 'New', '', bitmaps.fetch_icon_bitmap("actions", "window_new"), size=(120,40))
        load = metallicbutton.MetallicButton(self, -1, 'Load', '', bitmaps.fetch_icon_bitmap("actions", "fileopen"), size=(120,40))
        delete = metallicbutton.MetallicButton(self, -1, 'Delete', '', bitmaps.fetch_icon_bitmap("actions", "fileclose"), size=(120,40))
        sum = metallicbutton.MetallicButton(self, -1, 'Summary', '', bitmaps.fetch_icon_bitmap("actions", "info"), size=(120,40))
                
        self.Bind(wx.EVT_BUTTON, self._new_job, new)
        self.Bind(wx.EVT_BUTTON, self._load_job, load)
        self.Bind(wx.EVT_BUTTON, self._delete_job, delete)
        self.Bind(wx.EVT_BUTTON, self._show_summary, sum)
                
        import_cif = metallicbutton.MetallicButton(self, -1, 'Import HKL', '', icons.hkl_file.GetBitmap(), size=(120,40))
        import_pdb = metallicbutton.MetallicButton(self, -1, 'Import PDB', '', icons.pdb_file.GetBitmap(), size=(120,40))
        rcsb_dl = metallicbutton.MetallicButton(self, -1, 'RCSB PDB', '', bitmaps.fetch_icon_bitmap("actions", "down"), size=(120,40))
        self.Bind(wx.EVT_BUTTON, self._import_pbd, import_pdb)
        self.Bind(wx.EVT_BUTTON, self._import_cif, import_cif)
        self.Bind(wx.EVT_BUTTON, self._download_files, rcsb_dl)
        
        self.sidebar = wx.BoxSizer(wx.VERTICAL)
        self.sidebar.Add(new, 0, wx.EXPAND | wx.ALL, 5)
        self.sidebar.Add(load, 0, wx.EXPAND | wx.ALL, 5)
        self.sidebar.Add(sum, 0, wx.EXPAND | wx.ALL, 5)
        self.sidebar.Add(delete, 0, wx.EXPAND | wx.ALL, 5)
        self.sidebar.AddSpacer(20)
                
        self.sidebar.Add(import_cif, 0, wx.EXPAND | wx.ALL, 5)
        self.sidebar.Add(import_pdb, 0, wx.EXPAND | wx.ALL, 5)
        self.sidebar.AddSpacer(10)
        self.sidebar.Add(rcsb_dl, 0, wx.EXPAND | wx.ALL, 5)
                
        self.main = wx.BoxSizer(wx.HORIZONTAL)
        self.main.Add(self.job_list, 0, wx.EXPAND|wx.ALL, 5)
        self.main.Add(self.sidebar, 0, wx.EXPAND|wx.ALL, 5)
        
        self.SetSizer(self.main)
Exemplo n.º 17
0
 def describe(self):
     tab0 = Tab()
     tab1 = Tab()
     print(tab0, '=' * 60)
     print(tab0, 'Newton-Krylov solver')
     print(tab1, 'Max iters: ', self.maxIters)
     print(
         tab1,
         'Tolerance: tau_r=%12.5g, tau_a=%12.5g' % (self.tau_r, self.tau_a))
     print(tab1, 'Verbosity: ', self.verb)
     print(
         tab1, 'Newton-Krylov tolerance multiplier=%12.5g, min tol=%12.5g' %
         (self.tolFudge, self.minLinTol))
     print(tab1, 'use tolerance adjustment: ', not self.fixLinTol)
     print(tab1, 'Linear solver: GMRES, maxIters=', self.maxLinIters)
     print(
         tab1, 'Preconditioner: ILU(drop=%12.5g, fill=%d)' %
         (self.iluDrop, self.iluFill))
     print(tab1, 'Recycle initial preconditioner ', self.reusePrecond)
Exemplo n.º 18
0
    def __init__(self, shell, plugin):
        GObject.Object.__init__(self)
        self.shell = shell
        self.sp = shell.get_property('shell-player')
        self.db = shell.get_property('db')
        self.plugin = plugin

        self.settings = Gio.Settings("org.gnome.rhythmbox.plugins.tabsearch")
        self.sites = self.get_sites()
        self.nr_sites = len(self.sites)
        self.tab_list = []
        self.info_tab = Tab('Info', 'Infos\n=====')
        self.stock = self.get_stock_icon(ICON_FILENAME)

        self.visible = True

        self.init_gui()
        self.connect_signals()

        self.action_toggle = (
            'ToggleTabSearch', self.stock, _('TabSearch'), None,
            _('Change the visibility of the tab search pane'),
            self.toggle_visibility, True)

        self.action_group = Gtk.ActionGroup('TabSearchActions')
        self.action_group.add_toggle_actions([self.action_toggle])

        # since the visibility toggle is per default set to TRUE,
        # click it once, if visibility in gconf is set to false!
        if self.settings.get_boolean('visible') == False:
            action = self.action_group.get_action('ToggleTabSearch')
            action.activate()

        uim = self.sp.get_property('ui-manager')
        uim.insert_action_group(self.action_group, 0)
        self.ui_id = uim.add_ui_from_string(tab_search_ui)
        uim.ensure_update()
    def clean(self):
        used = False
        for tab in self.application.tabs_list:
            if tab.get_category().get_name() == self.entry.get():
                used = True
        if used:
            window = InvalidInputWindow(self.master, self.application,
                                        "This category already exists.")
        else:

            if self.valid_input_checker(self.entry.get()):
                self.value = self.entry.get()
                DatabaseHandler.create_category_database(self.entry.get())
                new_tab = Tab(self.application.get_notebook(),
                              Category(self.entry.get()), self.application,
                              self.favorites_tab, self.expired_tab)
                new_tab.populate_tab()
                self.application.tabs_list.append(new_tab)
                self.top.destroy()
            else:
                window = InvalidInputWindow(
                    self.master, self.application,
                    "Use only capital and lowercase letters,\nnumbers or apostrophe, please."
                )
	def add_tab_to_notebook(self, data, params):
		#print data
		#print "add_tab_to_notebook !!!!"
		if not self.settings.get_boolean('preventautoweblookup'):
			doAutoLookup = True
		else:
			doAutoLookup = False

		# local file not found
		if data is None:
			if params['source'] == 'hdd':
				data = "\t   No tabs found on your hard disk."
				if doAutoLookup:
					data = data + "\n\t   Try checking the tab sites on the internet\n\t   by clicking on the 'load from web' button above."
				else:
					data = data + "\n\t   Wait for the plugin research from web..."

				self.update_info_tab('\t-> Nothing found!\n' + data)
				self.load_tabs('web')
			else:
				data = "you should not see this, check source code!"			
				self.update_info_tab('\t-> Nothing found!\n' + data)
		else:
			if params['source'] == 'hdd':
				if doAutoLookup:
					self.load_tabs('web')
				else:
					self.update_info_tab('\t-> You choose not to lookup when local tab is found...');
			else:
				# inform user on info tab about success at fetching data
				self.update_info_tab('\t-> tabs found on ' + params['source'] + ' for \'' + params['artist'] + '\' - \'' + params['title'] + '\'.')
				tab = Tab('#' + str(len(self.notebook.get_children())) + ' ' + params['source'], data)
				tab.set_meta('artist', params['artist'])
				tab.set_meta('title', params['title'])
				self.tab_list.append(tab)
				self.update_notebook(params['source'], params['artist'], params['title'])
Exemplo n.º 21
0
Arquivo: App.py Projeto: balu/fm
 def open_dir(self, new_tab = False, background = False):
     if new_tab:
         curt = self.gettab()
         dentry = curt.dentry()
         if dentry.isdir():
             t = Tab.create(self, dentry.path())
             if t:
                 self.tablist.append(t)
                 if not background: self.curtab = len(self.tablist) - 1
                 curt.winexit()
                 self.UI.draw()
     else:
         self.gettab().open_dir()
         self.UI.draw(False)
     return True
Exemplo n.º 22
0
Arquivo: App.py Projeto: balu/fm
    def goto_path(self, path, new_tab = False, background = False):
        if not os.path.exists(path): return True

        if new_tab:
            curt = self.gettab()
            t = Tab.create(self, path)
            if t:
                self.tablist.append(t)
                if not background: self.curtab = len(self.tablist) - 1
                curt.winexit()
                self.UI.draw()
        else:
            self.gettab().goto_path(path)
            self.UI.draw(False)
        return True
Exemplo n.º 23
0
class TestBase(unittest.TestCase):

    # Method getting the test name
    def getTestName(self):
        testMethodName = re.sub(constants.TEST_NUMBER_PATTERN, constants.EMPTY,
                                self._testMethodName, 1)
        return testMethodName.replace(constants.UNDERSCORE, constants.SPACE)

    # setup method, called once before all the tests
    @classmethod
    def setUpClass(self):
        username = os.getenv(constants.USERNAME, "")
        password = os.getenv(constants.PASSWORD, "")
        """Start web browser"""
        self._browser = Tab()
        self._browser.login_on_page(constants.DERA_SCM_URL, username, password)

    # setup method, called before each test
    def setUp(self):
        time.sleep(2)
        Log.info(constants.STARS_START_LINE)
        Log.info(constants.TEST_START + self.getTestName())

    # This will run at end of each test
    def tearDown(self):
        Log.info(constants.TEST_FINSIH + self.getTestName())
        self.logResult()
        Log.info(constants.STARS_END_LINE)

    # This will run at end of all tests
    @classmethod
    def tearDownClass(self):
        """Logout browser"""
        try:
            time.sleep(2)
            self._browser.logout()
        except Exception as ex:
            raise Exception("Tear Down Failed : {}.".format(ex))
        time.sleep(4)
        self._browser.quit()

    # Method to log the result
    def logResult(self):
        if sys.exc_info() == (None, None, None):
            Log.info(constants.TEST_PASS)
        else:
            Log.info(constants.TEST_FAIL)
	def __init__(self, shell, plugin):
		GObject.Object.__init__(self)
		self.shell = shell
		self.sp = shell.get_property('shell-player')
		self.db = shell.get_property('db')
		self.plugin = plugin

		self.settings = Gio.Settings("org.gnome.rhythmbox.plugins.tabsearch")
		self.sites = self.get_sites()
		self.nr_sites = len(self.sites)
		self.tab_list = []
		self.info_tab = Tab('Info', 'Infos\n=====')
		self.stock = self.get_stock_icon(ICON_FILENAME)

		self.visible = True

		self.init_gui()
		self.connect_signals()		

		self.action_toggle = ('ToggleTabSearch', self.stock, _('TabSearch'),
		 		None, _('Change the visibility of the tab search pane'),
		 		self.toggle_visibility, True)

		self.action_group = Gtk.ActionGroup('TabSearchActions')
		self.action_group.add_toggle_actions([self.action_toggle])
		
		# since the visibility toggle is per default set to TRUE,
		# click it once, if visibility in gconf is set to false!
		if self.settings.get_boolean('visible') == False:
			action = self.action_group.get_action('ToggleTabSearch')
			action.activate();

		uim = self.sp.get_property('ui-manager')
		uim.insert_action_group (self.action_group, 0)
		self.ui_id = uim.add_ui_from_string(tab_search_ui)
		uim.ensure_update()
Exemplo n.º 25
0
    def add_tab_to_notebook(self, data, params):
        #print data
        #print "add_tab_to_notebook !!!!"
        if not self.settings.get_boolean('preventautoweblookup'):
            doAutoLookup = True
        else:
            doAutoLookup = False

        # local file not found
        if data is None:
            if params['source'] == 'hdd':
                data = "\t   No tabs found on your hard disk."
                if doAutoLookup:
                    data = data + "\n\t   Try checking the tab sites on the internet\n\t   by clicking on the 'load from web' button above."
                else:
                    data = data + "\n\t   Wait for the plugin research from web..."

                self.update_info_tab('\t-> Nothing found!\n' + data)
                self.load_tabs('web')
            else:
                data = "you should not see this, check source code!"
                self.update_info_tab('\t-> Nothing found!\n' + data)
        else:
            if params['source'] == 'hdd':
                if doAutoLookup:
                    self.load_tabs('web')
                else:
                    self.update_info_tab(
                        '\t-> You choose not to lookup when local tab is found...'
                    )
            else:
                # inform user on info tab about success at fetching data
                self.update_info_tab('\t-> tabs found on ' + params['source'] +
                                     ' for \'' + params['artist'] + '\' - \'' +
                                     params['title'] + '\'.')
                tab = Tab(
                    '#' + str(len(self.notebook.get_children())) + ' ' +
                    params['source'], data)
                tab.set_meta('artist', params['artist'])
                tab.set_meta('title', params['title'])
                self.tab_list.append(tab)
                self.update_notebook(params['source'], params['artist'],
                                     params['title'])
Exemplo n.º 26
0
    def __init__(self, parent, id, title):
        self._settings = Settings()
        
        if self._settings.val('phenix'):
            import sys
                
            p = self._settings.val('phenix')
            base = p + '/Contents/' + os.path.basename(p).lower()
            if os.path.exists(base):
                sys.path.append(base + '/elbow')
                sys.path.append(base)
                libtbx.env.add_repository(base)
                libtbx.env.process_module(None, 'elbow', False)
        
        CootClient.set_start_coot(self.start_coot)
        SettingsDialog.set_settings(self._settings)
        HelpDialog.set_settings(self._settings)
        
        wx.Frame.__init__(self, parent, id, title, size=(850,540))
        self.Bind(wx.EVT_CLOSE, self._on_close)
        
        self.toolbar = wx.ToolBar(self, style=wx.TB_3DBUTTONS|wx.TB_TEXT)
        quit = self.toolbar.AddLabelTool(wx.ID_ANY, 'Quit', wxtbx.bitmaps.fetch_icon_bitmap('actions', 'exit'))
        settings = self.toolbar.AddLabelTool(wx.ID_ANY, 'Settings', wxtbx.bitmaps.fetch_icon_bitmap('actions', 'configure'))
        about = self.toolbar.AddLabelTool(wx.ID_ANY, 'About', wxtbx.bitmaps.fetch_icon_bitmap('actions', 'info'))
        help = self.toolbar.AddLabelTool(wx.ID_ANY, 'Help', wxtbx.bitmaps.fetch_icon_bitmap('actions', 'agt_support'))
        self.toolbar.AddSeparator()
        coot = self.toolbar.AddLabelTool(wx.ID_ANY, 'Coot', wx.Bitmap(self._settings.proot + 'Resources/gui_resources/coot.png'))
        ligand = self.toolbar.AddLabelTool(wx.ID_ANY, 'Ligands', wx.Bitmap(self._settings.proot + 'Resources/gui_resources/ligand_32.png'))
        self.SetToolBar(self.toolbar)
        self.toolbar.Realize()
        
        self.Bind(wx.EVT_TOOL, self._on_close, quit)
        self.Bind(wx.EVT_TOOL, self.start_coot, coot)
        self.Bind(wx.EVT_TOOL, self._show_settings, settings)
        self.Bind(wx.EVT_TOOL, self._show_about, about)
        self.Bind(wx.EVT_TOOL, self._show_help, help)
        self.Bind(wx.EVT_TOOL, self._view_ligand, ligand)
        
        self._coot_timer = None
        self._coot_process = None
        self._coot_client = CootClient()

        nb = wx.aui.AuiNotebook(self, -1, style=wx.NB_TOP)
        self.sheet1 = Manager(nb)
        
        Tab.set_settings(self._settings)
        CootClient.set_p8(self._settings.proot)
        
        Tab.set_coot_client(self._coot_client)
        Tab.set_start_coot(self.start_coot)
        Tab.set_update_sb(self.set_status)
        
        self.sheet2 = ProcessManager(nb)
        self.sheet3 = Compare(nb)
        
        Jobs.set_new_refinement(self.sheet2.new_refinement)
        Jobs.set_load_refinement(self.sheet2.load_refinement)
        Jobs.set_auto_refinement(self.sheet2.auto_refinement)

        nb.AddPage(self.sheet1, 'Manage')
        nb.AddPage(self.sheet2, 'Process')
        nb.AddPage(self.sheet3, 'Compare')

        self.sb = self.CreateStatusBar()
        self.sb.SetFieldsCount(2)
        self.sb.SetStatusWidths([-4, -1])
        self.sheet2.SetFocus()

        self.sheet1.load_project()
        self.sheet1.refresh_tabs()
Exemplo n.º 27
0
def smoothUpdate(A, C, verb=0):
  '''
  Create an update operator from a coarse mesh to a fine mesh, based on
  a matrix A and a set of coarse-mesh nodes C
  '''
  tab0 = Tab()
  timer = Timer('AMG update formation')

  Debug.msg3(verb, tab0, 'forming update operator')
  Debug.msg3(verb, tab0, 'C=', C)
  if not sp.isspmatrix_csr(A):
    raise ValueError('makeUpdate() expected a CSR matrix as input')

  M = A.shape[0]
  if A.shape[1] != A.shape[0]:
    raise ValueError('Non-square matrix in makeUpdate(): size is %d by %d' %
    (A.shape[0], A.shape[1]))

  c_to_f, f_to_c = makeIndexMaps(C)
  Debug.msg3(verb, tab0, 'f2c map is ', f_to_c)

  I_up = sp.dok_matrix((M,len(C)))

  ip = A.indptr
  allVals = A.data
  allCols = A.indices

  tab1 = Tab()
  tab2 = Tab()
  tab3 = Tab()
  tab4 = Tab()
  tab5 = Tab()


  # Main loop over rows
  for i in range(M):
    Debug.msg3(verb, tab0, 'row %d' % i)
    # If the current index is in the coarse mesh, take its value directly
    # from the fine mesh
    if i in C:
      I_up[i, f_to_c[i]] = 1.0
      Debug.msg3(verb, tab1, 'coarse-coarse connection, entry is 1')
      continue

    Debug.msg3(verb, tab1, 'interpolating value for fine row ', i)
    # Get arrays of column indices and values for this row
    cols_i = allCols[ip[i] : ip[i+1]]
    vals_i = allVals[ip[i] : ip[i+1]]

    # Find diagonal
    diag = vals_i[np.where(cols_i==i)]
    Debug.msg3(verb, tab1, 'diagonal is %g' % diag)

    # Diagonal must be nonzero!
    if diag == 0.0:
      raise ValueError('zero diagonal detected in row %d' % i)

    # build interpolation matrix
    for j, a_ij in zip(cols_i, vals_i):
      if j==i:
        continue
      if j not in C:
        continue
      Debug.msg3(verb, tab2, 'contrib from coarse node f=%d, c=%d' % (j, f_to_c[j]))

      w_ij = a_ij
      Debug.msg3(verb, tab2, 'direct connection: (%d,%d)=%g' % (i,j,w_ij))
      Debug.msg3(verb, tab2, 'finding indirect contributions')
      Debug.msg3(verb, tab2, 'looking at neighbors ', cols_i)
      for m, a_im in zip(cols_i, vals_i):
        if m==i: # <--- I forgot this on first pass!
          continue
        if m not in C: # Approximate values on F by averaging
          Debug.msg3(verb, tab3, 'approximating fine node m=%d' % m)
          cols_m = allCols[ip[m] : ip[m+1]]
          vals_m = allVals[ip[m] : ip[m+1]]
          denom = 0.0
          num = 0.0
          Debug.msg3(verb, tab3, 'neighbors of m=%d are ' % m, cols_m)
          count = 0
          for k,a_mk in zip(cols_m, vals_m):
            if k in C and k in cols_i:
              Debug.msg3(verb, tab4, 'indirect contribution from coarse node k=', k)
              denom += a_mk
              count += 1
            if k==j:
              num = a_im * a_mk
          Debug.msg3(verb, tab4, 'numerator=%g, denominator=%g' % (num,denom))
          if count>0:
            if denom==0.0:
              raise ValueError('zero denominator detected in (%d,%d)' %(i,j))
            Debug.msg3(verb, tab3, 'indirect connection through fine node %d: %g' % (m,num/denom))
            w_ij += num/denom
        else: # No need to approximate coarse node values
          Debug.msg3(verb, tab3, 'no need to approximate value at coarse node m=', m)
          continue
      Debug.msg3(verb, tab2, '(%d,%d), val=%g' %(i,j,w_ij))
      I_up[i, f_to_c[j]] = -w_ij/diag
    # end second pass through row i
  # end loop over rows

  Debug.msg3(verb, tab0, 'done forming update operator')
  return I_up.tocsr()
Exemplo n.º 28
0
    def solve(self, func, uInit):

        # Report all parameters
        if self.verb > 0:
            self.describe()

        # Set up formatting
        tab0 = Tab()
        tab1 = Tab()

        # Make a copy of the initial estimate
        u0 = uInit.copy()

        # Evaluate residual and its norm at initial iterate
        F0 = func.evalF(u0)
        r0 = npla.norm(F0)

        # Newton step vector. Initialize to all ones (this will be overwritten
        # before use)
        du = np.ones_like(u0)

        # We'll keep a count of the total Krylov iterations
        totalKrylovIters = 0

        # Run the loop!
        if self.verb > 0:
            print('\n', tab0, 'Newton-Krylov loop')

        for i in range(self.maxIters):

            # Evaluate residual at current iterate (already done if i=0)
            if i > 0:
                F0 = func.evalF(u0)
            # Compute residual norm
            r = npla.norm(F0)

            # Output convergence information if desired
            if self.verb > 0:
                print(
                    tab1, 'iter %6d r=%12.5g r/r0=%12.5g dx=%12.5g' %
                    (i, r, r / r0, npla.norm(du)))

            # Check for convergence
            if r <= r0 * self.tau_r + self.tau_a:
                print(tab0, 'Converged!')
                print(tab0, 'totalKrylovIters=', totalKrylovIters)
                return (True, u0)

            # Compute Jacobian at current iterate
            J = func.evalJ(u0)

            # Update tolerance for linear solve
            if self.fixLinTol:  # Use fixed tolerance if desired (for testing)
                tau_lin = self.minLinTol
            else:  # Adjust linear tol according to nonlinear resid
                # new linear tolerance is the larger of:
                # (*) "fudge factor" times relative residual of nonlinear solve
                # (*) a minimum linear tolerance.
                # The minimum tolerance avoids pointlessly small tolerances
                # for the linear solver
                tau_lin = max(self.tolFudge * r / r0, self.minLinTol)

            # Update the preconditioner if desired
            if i == 0 or not self.reusePrecond:
                print(tab1, 'Building ILU prec')
                drop = self.iluDrop
                fill = self.iluFill
                ILU = ILURightPreconditioner(J,
                                             drop_tol=drop,
                                             fill_factor=fill)

            (conv, krylovIters, du) = GMRES(J,
                                            -F0,
                                            maxiters=self.maxLinIters,
                                            tol=tau_lin,
                                            verb=self.linVerb,
                                            precond=ILU)
            totalKrylovIters += krylovIters

            if not conv:
                if self.verb > 0:
                    print('Newton-Krylov: linear solver failed to converge')
                return (False, u0)

            # Update solution estimate
            u0 = u0 + du

        if self.verb > 0:
            print(tab0, 'Newton-Krylov failed to converge!')
        return (False, u0)
Exemplo n.º 29
0
 def func(verb):
     tab = Tab()
     Debug.msg1(verb, tab, 'verb=%s, message 1' % verb)
     Debug.msg2(verb, tab, 'verb=%s, message 2' % verb)
     Debug.msg3(verb, tab, 'verb=%s, message 3' % verb)
     Debug.msg4(verb, tab, 'verb=%s, message 4' % verb)
Exemplo n.º 30
0
 def __init__(self, store):
     Tab.__init__(self, store)
Exemplo n.º 31
0
        if verb >= 3:
            Debug._write(args)

    @classmethod
    def msg4(cls, verb, *args):
        '''Write the arguments when verb >= 4.'''
        if verb >= 4:
            Debug._write(args)

    @classmethod
    def _write(cls, args):
        for a in args:
            print(a, end='', file=Debug.outstream)
        print('', file=Debug.outstream)


if __name__ == '__main__':

    t = Tab()

    def func(verb):
        tab = Tab()
        Debug.msg1(verb, tab, 'verb=%s, message 1' % verb)
        Debug.msg2(verb, tab, 'verb=%s, message 2' % verb)
        Debug.msg3(verb, tab, 'verb=%s, message 3' % verb)
        Debug.msg4(verb, tab, 'verb=%s, message 4' % verb)

    for i in range(1, 5):
        print('i=', i)
        func(i)
Exemplo n.º 32
0
class TabSearch(GObject.Object):
    def __init__(self, shell, plugin):
        GObject.Object.__init__(self)
        self.shell = shell
        self.sp = shell.get_property('shell-player')
        self.db = shell.get_property('db')
        self.plugin = plugin

        self.settings = Gio.Settings("org.gnome.rhythmbox.plugins.tabsearch")
        self.sites = self.get_sites()
        self.nr_sites = len(self.sites)
        self.tab_list = []
        self.info_tab = Tab('Info', 'Infos\n=====')
        self.stock = self.get_stock_icon(ICON_FILENAME)

        self.visible = True

        self.init_gui()
        self.connect_signals()

        self.action_toggle = (
            'ToggleTabSearch', self.stock, _('TabSearch'), None,
            _('Change the visibility of the tab search pane'),
            self.toggle_visibility, True)

        self.action_group = Gtk.ActionGroup('TabSearchActions')
        self.action_group.add_toggle_actions([self.action_toggle])

        # since the visibility toggle is per default set to TRUE,
        # click it once, if visibility in gconf is set to false!
        if self.settings.get_boolean('visible') == False:
            action = self.action_group.get_action('ToggleTabSearch')
            action.activate()

        uim = self.sp.get_property('ui-manager')
        uim.insert_action_group(self.action_group, 0)
        self.ui_id = uim.add_ui_from_string(tab_search_ui)
        uim.ensure_update()

    def init_gui(self):
        print "TabSearch->init_gui"
        self.vbox = Gtk.VBox()

        self.toolbar = Gtk.Toolbar()
        self.toolitemSave = Gtk.ToolButton()
        self.toolitemSave.set_label('Save')
        self.toolitemSave.set_stock_id(Gtk.STOCK_SAVE)
        self.toolitemSave.connect('clicked', self.save_tabs)
        self.toolitemSave.set_sensitive(False)
        self.toolbar.add(self.toolitemSave)
        self.toolitemEdit = Gtk.ToolButton()
        self.toolitemEdit.set_label('Edit')
        self.toolitemEdit.set_stock_id(Gtk.STOCK_EDIT)
        self.toolitemEdit.connect('clicked', self.edit_tabs)
        self.toolitemEdit.set_sensitive(False)
        self.toolbar.add(self.toolitemEdit)
        self.toolitemLoad = Gtk.ToolButton()
        self.toolitemLoad.set_label('Load From Web')
        self.toolitemLoad.set_stock_id(Gtk.STOCK_FIND)
        self.toolitemLoad.connect('clicked', self.load_tabs_from_web)
        self.toolitemLoad.set_sensitive(False)
        self.toolbar.add(self.toolitemLoad)
        self.vbox.pack_start(self.toolbar, expand=False, fill=True, padding=0)

        self.notebook = Gtk.Notebook()
        self.notebook.set_scrollable(True)

        self.progressbar = Gtk.ProgressBar()
        self.timeout = GObject.timeout_add(100, self.start_pulse)

        self.vbox.set_size_request(250, -1)
        self.shell.add_widget(self.vbox,
                              RB.ShellUILocation.RIGHT_SIDEBAR,
                              expand=True,
                              fill=True)
        self.vbox.show_all()

    def show_pulse(self):
        if self.progressbar is not None:
            self.vbox.remove(self.progressbar)
            GObject.source_remove(self.timeout)
        self.vbox.pack_end(self.progressbar,
                           expand=False,
                           fill=True,
                           padding=0)
        self.timeout = GObject.timeout_add(100, self.start_pulse)
        self.start_pulse()

    def hide_pulse(self):
        self.nr_sites = self.nr_sites - 1
        print "Sites left to stop progressbar: " + str(self.nr_sites)
        if self.nr_sites == 0:
            self.vbox.remove(self.progressbar)
            GObject.source_remove(self.timeout)

    def start_pulse(self):
        self.progressbar.pulse()
        return True

    def get_stock_icon(self, filename):
        icon_file_path = rb.find_plugin_file(self.plugin, filename)
        #icon_file_path = os.path.join(plugin.plugin_info.get_data_dir(), filename)
        if icon_file_path is None:
            print filename + " not found in " + self.plugin.plugin_info.get_data_dir(
            )
            return Gtk.STOCK_INFO
        else:
            iconsource = Gtk.IconSource()
            iconsource.set_filename(icon_file_path)
            iconset = Gtk.IconSet()
            iconset.add_source(iconsource)
            iconfactory = Gtk.IconFactory()
            iconfactory.add(STOCK_IMAGE, iconset)
            iconfactory.add_default()
            return STOCK_IMAGE

    # set the callback function 'playing_changed_cb'
    def connect_signals(self):
        self.player_cb_ids = (self.sp.connect('playing-song-changed',
                                              self.playing_changed_cb))

    # which sites did the user check in the configuration dialog?
    def get_sites(self):
        try:
            sites = self.settings['sites']
            if sites is None:
                sites = []
        except:
            print "Error: can't load the sites from configuration"
            sites = []
        print "tabs sites: " + str(sites)
        return sites

    # which folder did the user specify in the configuration dialog?
    # TODO: what's happening when the path is not valid?
    def get_tabfolder(self):
        try:
            #			folder = gconf.client_get_default().get_string(self.gconf_keys['folder'])
            folder = self.settings.get_string('folder')
        except:
            print "Error: can't load the tab folder path from configuration"
        print "tabs folder: " + folder
        return folder

    def load_tabs_from_web(self, action):
        return self.load_tabs('web')

    # callback function that is triggered whenever there's
    # a change in played song title
    def playing_changed_cb(self, playing, user_data):
        print "There's been a change in playback ..."
        self.info_tab.set_content('Infos\n=====')
        return self.load_tabs('hdd')

    def load_tabs(self, source):
        if self.visible is False:
            print "no visibility -> no need to look for tabs"
            return

        playing_entry = None
        if self.sp:
            playing_entry = self.sp.get_playing_entry()
        if playing_entry is None:
            return

#		playing_artist = self.db.entry_get (playing_entry, rhythmdb.PROP_ARTIST)
#		playing_title = self.db.entry_get (playing_entry, rhythmdb.PROP_TITLE)
        playing_artist = playing_entry.get_string(RB.RhythmDBPropType.ARTIST)
        playing_title = playing_entry.get_string(RB.RhythmDBPropType.TITLE)

        print "looking for '" + playing_artist + "' and the song '" + playing_title + "'"

        # passing the song info to the tab site parser
        # without removing the é and è from it.
        playing_artist = remove_accents(playing_artist)
        playing_title = remove_accents(playing_title)

        if playing_artist.upper() == "UNKNOWN":
            playing_artist = ""

        # resetting notebook
        if self.notebook in self.vbox.get_children():
            self.vbox.remove(self.notebook)
        self.vbox.show_all()
        self.notebook = None
        self.notebook = Gtk.Notebook()
        self.notebook.set_scrollable(True)
        self.notebook.connect('switch-page', self.update_toolbar)

        self.vbox.pack_start(self.notebook, expand=True, fill=True, padding=0)
        self.vbox.show_all()

        # Remove tabs from notebook
        self.tab_list = []
        self.info_tab.set_meta('artist', playing_artist)
        self.info_tab.set_meta('title', playing_title)

        if source == 'hdd':
            self.update_info_tab("\nchecking hdd for '" + playing_artist +
                                 "' and the song '" + playing_title + "'")
            self.hide_pulse()
            self.open_tabs_from_hdd(playing_artist, playing_title)
        if source == 'web':
            self.update_info_tab("\nchecking web for '" + playing_artist +
                                 "' and the song '" + playing_title + "'")
            if not (playing_artist == ""):
                # reset the number of sites in order to detect when the research finished
                self.nr_sites = len(self.sites)
                self.show_pulse()

                self.sites = self.get_sites()
                for s in self.sites:
                    site_id = s
                    if s == 'gt':
                        #gt = GuitareTabParser(self.add_tab_to_notebook, self.update_info_tab)
                        gt = GuitareTabParser(self.add_tab_to_notebook,
                                              self.notify_finish)
                        gt.tabs_finder(playing_artist, playing_title)
                    elif s == 'ug':
                        #ug = UltimateGuitarParser(self.add_tab_to_notebook, self.update_info_tab)
                        ug = UltimateGuitarParser(self.add_tab_to_notebook,
                                                  self.notify_finish)
                        ug.tabs_finder(playing_artist, playing_title)
                    elif s == 'az':
                        #az = AZChordsParser(self.add_tab_to_notebook, self.update_info_tab)
                        az = AZChordsParser(self.add_tab_to_notebook,
                                            self.notify_finish)
                        az.tabs_finder(playing_artist, playing_title)
                    elif s == 'ec':
                        #ec = EChordsParser(self.add_tab_to_notebook, self.update_info_tab)
                        ec = EChordsParser(self.add_tab_to_notebook,
                                           self.notify_finish)
                        ec.tabs_finder(playing_artist, playing_title)
                    elif s == 'lc':
                        #lc = LacuerdaParser(self.add_tab_to_notebook, self.update_info_tab)
                        lc = LacuerdaParser(self.add_tab_to_notebook,
                                            self.notify_finish)
                        lc.tabs_finder(playing_artist, playing_title)

    def deactivate(self, shell):
        print "Plugin deactivated."
        self.shell = None
        self.sp = None
        self.db = None
        self.plugin = None
        shell.remove_widget(self.vbox, RB.ShellUILocation.RIGHT_SIDEBAR)
        uim = self.sp.get_property('ui-manager')
        uim.remove_ui(self.ui_id)
        uim.remove_action_group(self.action_group)

    # toggles the visibility of the tab widget
    def toggle_visibility(self, action):
        print "Visibility set to " + str(not self.visible)
        if not self.visible:
            self.shell.add_widget(self.vbox,
                                  RB.ShellUILocation.RIGHT_SIDEBAR,
                                  expand=True,
                                  fill=True)
            self.visible = True
            self.load_tabs('hdd')
        else:
            self.shell.remove_widget(self.vbox,
                                     RB.ShellUILocation.RIGHT_SIDEBAR)
            self.visible = False
#		gconf.client_get_default().set_bool(self.gconf_keys['visible'], self.visible)
        self.settings.set_boolean('visible', self.visible)

    def edit_tabs(self, action):
        self.toolitemEdit.set_sensitive(False)
        self.get_current_tab().set_editable(True)
        self.toolitemSave.set_sensitive(True)

    # (de)activates the buttons on the toolbar depending on whether
    # they're useful in the current situation
    def update_toolbar(self, notebook, page, page_num):
        self.toolitemEdit.set_sensitive(False)
        self.toolitemSave.set_sensitive(False)
        self.toolitemLoad.set_sensitive(False)
        if page_num == 0:
            self.toolitemLoad.set_sensitive(True)
        if page_num > 0:
            self.toolitemEdit.set_sensitive(True)

    # returns the currently selected tab content
    def get_current_tab(self):
        currentTab = self.notebook.get_current_page()
        return self.notebook.get_nth_page(currentTab).get_child()

    # returns the currently selected tab content
    def get_current_tab_title(self):
        currentTab = self.notebook.get_current_page()
        currentTab = self.notebook.get_nth_page(currentTab)
        return self.notebook.get_tab_label(currentTab).get_text()

    # copies currently selected tabs to the hard disk
    def save_tabs(self, action):
        print 'saving tabs to hdd ...'
        self.toolitemSave.set_sensitive(False)
        self.toolitemEdit.set_sensitive(True)
        self.get_current_tab().set_editable(False)

        textbuffer = ""
        try:
            textbuffer = self.get_current_tab().get_buffer()
            textbuffer = textbuffer.get_text(textbuffer.get_start_iter(),
                                             textbuffer.get_end_iter(), 0)
        except:
            print 'Error: can\'t read current\'s tabs content'

        if textbuffer is None:
            print 'Error: loading current tabs failed'
            return

        directory = self.get_tabfolder(
        ) + '/' + self.info_tab.meta['artist'] + '/'

        try:
            os.makedirs(directory)
        except os.error:
            print 'Notice: directory\'s already existing'

        filename = directory + self.info_tab.meta['title'] + '.txt'

        try:
            file = open(filename, 'w')
        except:
            print "Error: can't open file"
            return

        file.write(textbuffer)
        file.close()
        print "-> saved successfully to hdd"
        self.load_tabs('hdd')

    def open_tabs_from_hdd(self, artist, title):
        filename = self.get_tabfolder() + '/' + artist + '/' + title + '.txt'
        print filename
        self.file_res = Gio.File.new_for_path(filename)
        self.file_res.load_contents_async(None, self.open_tabs_from_hdd_cb, {
            'source': 'hdd',
            'artist': artist,
            'title': title
        })

    def open_tabs_from_hdd_cb(self, gdaemonfile, result, params):
        try:
            result = self.file_res.load_contents_finish(result)
        except GError:
            print "Error: can't open file, maybe it's not there at all..."
            self.add_tab_to_notebook(None, params)
            return
        successful = result[0]
        data = result[1]

        self.add_tab_to_notebook(data, params)

    def add_tab_to_notebook(self, data, params):
        #print data
        #print "add_tab_to_notebook !!!!"
        if not self.settings.get_boolean('preventautoweblookup'):
            doAutoLookup = True
        else:
            doAutoLookup = False

        # local file not found
        if data is None:
            if params['source'] == 'hdd':
                data = "\t   No tabs found on your hard disk."
                if doAutoLookup:
                    data = data + "\n\t   Try checking the tab sites on the internet\n\t   by clicking on the 'load from web' button above."
                else:
                    data = data + "\n\t   Wait for the plugin research from web..."

                self.update_info_tab('\t-> Nothing found!\n' + data)
                self.load_tabs('web')
            else:
                data = "you should not see this, check source code!"
                self.update_info_tab('\t-> Nothing found!\n' + data)
        else:
            if params['source'] == 'hdd':
                if doAutoLookup:
                    self.load_tabs('web')
                else:
                    self.update_info_tab(
                        '\t-> You choose not to lookup when local tab is found...'
                    )
            else:
                # inform user on info tab about success at fetching data
                self.update_info_tab('\t-> tabs found on ' + params['source'] +
                                     ' for \'' + params['artist'] + '\' - \'' +
                                     params['title'] + '\'.')
                tab = Tab(
                    '#' + str(len(self.notebook.get_children())) + ' ' +
                    params['source'], data)
                tab.set_meta('artist', params['artist'])
                tab.set_meta('title', params['title'])
                self.tab_list.append(tab)
                self.update_notebook(params['source'], params['artist'],
                                     params['title'])

    def update_info_tab(self, new_content):
        self.info_tab.add_content(new_content)

        if len(self.notebook.get_children()) == 0:
            # create info tab for the first time
            scroll = self.create_page(self.info_tab.content)
            self.notebook.prepend_page(scroll, Gtk.Label(self.info_tab.label))
        else:
            # update existing info tab
            infoTab = self.notebook.get_nth_page(0).get_child()
            textbuffer = infoTab.get_buffer()
            textbuffer.set_text(self.info_tab.content)
        self.notebook.show()
        self.vbox.show_all()

    def notify_finish(self, content):
        self.update_info_tab(content)
        self.hide_pulse()

    def update_notebook(self, source, artist, title):
        """ Update notebook """
        if len(self.tab_list) == 0:
            print 'no tabs in tab_list !'
        else:
            # data tabs
            for tab in self.tab_list:
                if not (tab.label == "Not Found"):
                    scroll = self.create_page(tab.content)
                    self.notebook.append_page(scroll, Gtk.Label(tab.label))
        self.tab_list = []
        self.notebook.show()
        self.vbox.show_all()

    def create_page(self, text):
        fontdesc = Pango.FontDescription("Courier New 8")
        textbuffer = Gtk.TextBuffer()
        textbuffer.set_text(text)
        textview = Gtk.TextView()
        textview.set_buffer(textbuffer)
        textview.set_editable(False)
        textview.modify_font(fontdesc)
        scroll = Gtk.ScrolledWindow()
        scroll.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
        scroll.set_shadow_type(Gtk.ShadowType.IN)
        scroll.add(textview)
        scroll.show()
        return scroll
Exemplo n.º 33
0
    def __init__(self, nb):
        Tab.__init__(self, nb)

        self.fig = Figure((5.0, 4.0), dpi=100)
        col = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BACKGROUND)
        self.fig.patch.set_facecolor((col[0]/255.0, col[1]/255.0, col[2]/255.0))
        self.canvas = FigCanvas(self, -1, self.fig)
        self.canvas.mpl_connect('button_press_event', self._on_click)
        self.ax1 = self.fig.add_subplot(111)
        self.ax1.set_position([0.10,0.153,0.80,0.81])
        #self.ax2 = self.ax1.twinx()
        self.ax1.tick_params(labelsize=8)
        #self.ax2.tick_params(labelsize=8)   
        
        self.hist_fig = Figure((2,1.5), dpi=100)
        self.hist_fig.set_facecolor((col[0]/255.0, col[1]/255.0, col[2]/255.0))
        self.hist_canvas = FigCanvas(self, -1, self.hist_fig)
        self.hist_ax1 = self.hist_fig.add_subplot(111)
        
        self.shist_fig = Figure((2,1.5), dpi=100)
        self.shist_fig.set_facecolor((col[0]/255.0, col[1]/255.0, col[2]/255.0))
        self.shist_canvas = FigCanvas(self, -1, self.shist_fig)
        self.shist_ax1 = self.shist_fig.add_subplot(111)
        
        self.refinements = wx.ListBox(self, 26, wx.DefaultPosition, (60, 100), [], wx.LB_MULTIPLE)
        self.refinements.Bind(wx.EVT_LISTBOX, self._set_refinements)
        
        self.res_sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.res_sizer.Add(wx.StaticText(self, -1, 'Residue Type'), 0, wx.EXPAND)
        self.res_type = wx.ComboBox(self, -1, choices=[], style=wx.CB_READONLY)
        self.res_type.Bind(wx.EVT_COMBOBOX, self._set_residue_type)
        self.res_sizer.Add(self.res_type, 0, wx.EXPAND)

        self._flds = [ wx.StaticText(self, -1, '') for i in range(4) ]
        
        self.avg_info = wx.FlexGridSizer(rows=0, cols=2, vgap=5, hgap=5)
        self.avg_info.Add(wx.StaticText(self, -1, 'Average Std Dev'), 0, wx.EXPAND)
        self.avg_info.Add(self._flds[0], 0, wx.EXPAND)
        #self.avg_info.Add(wx.StaticText(self, -1, 'Number of Vals'), wx.EXPAND|wx.ALL, 5)
        #self.avg_info.Add(self._flds[1], wx.EXPAND|wx.ALL, 5)
        
        self.res_info = wx.FlexGridSizer(rows=0, cols=2, vgap=5, hgap=5)
        self.res_info.Add(wx.StaticText(self, -1, 'Average Values'), 0, wx.EXPAND)
        self.res_info.Add(self._flds[1], 0, wx.EXPAND)
        self.res_info.Add(wx.StaticText(self, -1, 'Standard Dev'), 0, wx.EXPAND)
        self.res_info.Add(self._flds[2], 0, wx.EXPAND)
        #self.res_info.Add(wx.StaticText(self, -1, 'Number of Vals'), wx.EXPAND|wx.ALL, 5)
        #self.res_info.Add(self._flds[3], wx.EXPAND|wx.ALL, 5)
        
        self.side_sizer = wx.BoxSizer(wx.VERTICAL)
        self.side_sizer.Add(wx.StaticText(self, -1, 'Refinements'), 0, wx.EXPAND|wx.LEFT, 5)
        self.side_sizer.Add(self.refinements, 0, wx.EXPAND|wx.LEFT, 5)
        self.side_sizer.Add(self.res_sizer, 0, wx.EXPAND|wx.LEFT, 5)
        self.side_sizer.Add(self.avg_info, 0, wx.EXPAND|wx.LEFT, 5)
        self.side_sizer.Add(self.shist_canvas, 1, wx.EXPAND|wx.LEFT, 5)
        self.side_sizer.Add(self.res_info, 0, wx.EXPAND|wx.LEFT, 5)
        self.side_sizer.Add(self.hist_canvas, 1, wx.EXPAND|wx.LEFT, 5)
        
        
        self.sizer = wx.BoxSizer(wx.HORIZONTAL)
        
        self.sizer.Add(self.side_sizer, 0, wx.EXPAND|wx.ALL, 5)
        self.sizer.Add(self.canvas, 1, wx.EXPAND|wx.ALL, 5)
        
        self._rtypes = ['Aspartate', 'Glutamate', 'Histidine', 'Arginine']
        self._rtypess = ['Asp', 'Glu', 'His', 'Arg']
        
        self._residue_type = 0
        self._highlight = -1
        self._selected_residue = -1
        self._residue_types = []
        self._all_data = []
        self._averaged = []
        self._files = []
                            
        self.SetSizer(self.sizer)
        self.Fit()
from Tab import Tab

print("============================")
print("\tWeb Browser ")
print("============================")

active = True

tab = Tab()
while (active):
    print("1. Forward")
    print("2. Backward")
    print("3. Reload")
    print("4. Show History")
    print("5. Exit")

    inp = int(input("Enter your choice: "))
    if inp == 1:
        pageName = input("Enter URL: ")
        tab.goForward(pageName)
    elif inp == 2:
        active = tab.goBack()
    elif inp == 3:
        print(tab.getCurrentPage)
    elif inp == 4:
        tab.getCurrentVisitedPage()
    elif inp == 5:
        active = False
        print("Tab is clear!!!")
    else:
        print("Look at instruction, you idiot!!!")
Exemplo n.º 35
0
 def __init__(self, nb):
     Tab.__init__(self, nb)
     
     self.sizer = wx.BoxSizer(wx.HORIZONTAL)
     self.SetSizer(self.sizer)
class TabSearch(GObject.Object):
	def __init__(self, shell, plugin):
		GObject.Object.__init__(self)
		self.shell = shell
		self.sp = shell.get_property('shell-player')
		self.db = shell.get_property('db')
		self.plugin = plugin

		self.settings = Gio.Settings("org.gnome.rhythmbox.plugins.tabsearch")
		self.sites = self.get_sites()
		self.nr_sites = len(self.sites)
		self.tab_list = []
		self.info_tab = Tab('Info', 'Infos\n=====')
		self.stock = self.get_stock_icon(ICON_FILENAME)

		self.visible = True

		self.init_gui()
		self.connect_signals()		

		self.action_toggle = ('ToggleTabSearch', self.stock, _('TabSearch'),
		 		None, _('Change the visibility of the tab search pane'),
		 		self.toggle_visibility, True)

		self.action_group = Gtk.ActionGroup('TabSearchActions')
		self.action_group.add_toggle_actions([self.action_toggle])
		
		# since the visibility toggle is per default set to TRUE,
		# click it once, if visibility in gconf is set to false!
		if self.settings.get_boolean('visible') == False:
			action = self.action_group.get_action('ToggleTabSearch')
			action.activate();

		uim = self.sp.get_property('ui-manager')
		uim.insert_action_group (self.action_group, 0)
		self.ui_id = uim.add_ui_from_string(tab_search_ui)
		uim.ensure_update()


	def init_gui(self) :
		print "TabSearch->init_gui"
		self.vbox = Gtk.VBox()
		
		self.toolbar = Gtk.Toolbar()
		self.toolitemSave = Gtk.ToolButton()
		self.toolitemSave.set_label('Save')
		self.toolitemSave.set_stock_id(Gtk.STOCK_SAVE)
		self.toolitemSave.connect('clicked', self.save_tabs)
		self.toolitemSave.set_sensitive(False)
		self.toolbar.add(self.toolitemSave)
		self.toolitemEdit = Gtk.ToolButton()
		self.toolitemEdit.set_label('Edit')
		self.toolitemEdit.set_stock_id(Gtk.STOCK_EDIT)
		self.toolitemEdit.connect('clicked', self.edit_tabs)
		self.toolitemEdit.set_sensitive(False)
		self.toolbar.add(self.toolitemEdit)
		self.toolitemLoad = Gtk.ToolButton()
		self.toolitemLoad.set_label('Load From Web')
		self.toolitemLoad.set_stock_id(Gtk.STOCK_FIND)
		self.toolitemLoad.connect('clicked', self.load_tabs_from_web)
		self.toolitemLoad.set_sensitive(False)
		self.toolbar.add(self.toolitemLoad)
		self.vbox.pack_start(self.toolbar, expand = False, fill = True, padding = 0)

		self.notebook = Gtk.Notebook()
		self.notebook.set_scrollable(True)

		self.progressbar = Gtk.ProgressBar()
		self.timeout = GObject.timeout_add(100, self.start_pulse)
		
		self.vbox.set_size_request(250, -1)
		self.shell.add_widget(self.vbox, RB.ShellUILocation.RIGHT_SIDEBAR, expand=True, fill=True)
		self.vbox.show_all()

	def show_pulse(self):
		if self.progressbar is not None:
			self.vbox.remove(self.progressbar)
			GObject.source_remove(self.timeout)
		self.vbox.pack_end(self.progressbar, expand = False, fill = True, padding = 0)
		self.timeout = GObject.timeout_add(100, self.start_pulse)
		self.start_pulse()
		
	def hide_pulse(self):
		self.nr_sites = self.nr_sites-1
		print "Sites left to stop progressbar: "+str(self.nr_sites)
		if self.nr_sites == 0:
			self.vbox.remove(self.progressbar)
			GObject.source_remove(self.timeout)

	def start_pulse(self):
		self.progressbar.pulse()
		return True

	def get_stock_icon(self, filename):
		icon_file_path = rb.find_plugin_file(self.plugin, filename)
		#icon_file_path = os.path.join(plugin.plugin_info.get_data_dir(), filename)
		if icon_file_path is None:
			print filename +" not found in "+self.plugin.plugin_info.get_data_dir()
			return Gtk.STOCK_INFO
		else:
			iconsource = Gtk.IconSource()
			iconsource.set_filename(icon_file_path)
			iconset = Gtk.IconSet()
			iconset.add_source(iconsource)
			iconfactory = Gtk.IconFactory()
			iconfactory.add(STOCK_IMAGE, iconset)
			iconfactory.add_default()
			return STOCK_IMAGE

	# set the callback function 'playing_changed_cb'
	def connect_signals(self):
		self.player_cb_ids = (self.sp.connect('playing-song-changed', self.playing_changed_cb))

	# which sites did the user check in the configuration dialog?
	def get_sites(self):
		try:
			sites = self.settings['sites']
			if sites is None:
				sites = []
		except:
			print "Error: can't load the sites from configuration"
			sites = []
		print "tabs sites: " + str(sites)
		return sites
		
	# which folder did the user specify in the configuration dialog?
	# TODO: what's happening when the path is not valid?
	def get_tabfolder(self):
		try:
#			folder = gconf.client_get_default().get_string(self.gconf_keys['folder'])
			folder = self.settings.get_string('folder')
		except:
			print "Error: can't load the tab folder path from configuration"
		print "tabs folder: " + folder
		return folder

	def load_tabs_from_web(self, action):
		return self.load_tabs('web')

	# callback function that is triggered whenever there's 
	# a change in played song title
	def playing_changed_cb (self, playing, user_data):
		print "There's been a change in playback ..."		
		self.info_tab.set_content('Infos\n=====')
		return self.load_tabs('hdd')

	def load_tabs(self, source):
		if self.visible is False:
			print "no visibility -> no need to look for tabs"
			return
		
		playing_entry = None
		if self.sp:
			playing_entry = self.sp.get_playing_entry()
		if playing_entry is None:
			return

#		playing_artist = self.db.entry_get (playing_entry, rhythmdb.PROP_ARTIST)
#		playing_title = self.db.entry_get (playing_entry, rhythmdb.PROP_TITLE)
		playing_artist = playing_entry.get_string(RB.RhythmDBPropType.ARTIST)
		playing_title = playing_entry.get_string(RB.RhythmDBPropType.TITLE)
		
		print "looking for '" + playing_artist + "' and the song '" + playing_title + "'"
		
		# passing the song info to the tab site parser
		# without removing the é and è from it.
		playing_artist = remove_accents(playing_artist)
		playing_title = remove_accents(playing_title)

		if playing_artist.upper() == "UNKNOWN":
			playing_artist = ""
			
		# resetting notebook
		if self.notebook in self.vbox.get_children():
			self.vbox.remove(self.notebook)
		self.vbox.show_all()
		self.notebook = None
		self.notebook = Gtk.Notebook()
		self.notebook.set_scrollable(True)
		self.notebook.connect('switch-page', self.update_toolbar)

		self.vbox.pack_start(self.notebook, expand = True, fill = True, padding=0)
		self.vbox.show_all()
		
		# Remove tabs from notebook
		self.tab_list = []
		self.info_tab.set_meta('artist', playing_artist)
		self.info_tab.set_meta('title', playing_title)
		
		if source == 'hdd':
			self.update_info_tab("\nchecking hdd for '" + playing_artist + "' and the song '" + playing_title + "'")
			self.hide_pulse()
			self.open_tabs_from_hdd(playing_artist, playing_title)
		if source == 'web':
			self.update_info_tab("\nchecking web for '" + playing_artist + "' and the song '" + playing_title + "'")
			if not(playing_artist == ""):
				# reset the number of sites in order to detect when the research finished
				self.nr_sites = len(self.sites)		
				self.show_pulse()

				self.sites = self.get_sites()
				for s in self.sites:
					site_id = s
					if s == 'gt':
						#gt = GuitareTabParser(self.add_tab_to_notebook, self.update_info_tab)
						gt = GuitareTabParser(self.add_tab_to_notebook, self.notify_finish)
						gt.tabs_finder(playing_artist, playing_title)
					elif s == 'ug':
						#ug = UltimateGuitarParser(self.add_tab_to_notebook, self.update_info_tab)
						ug = UltimateGuitarParser(self.add_tab_to_notebook, self.notify_finish)
						ug.tabs_finder(playing_artist, playing_title)
					elif s == 'az':
						#az = AZChordsParser(self.add_tab_to_notebook, self.update_info_tab)
						az = AZChordsParser(self.add_tab_to_notebook, self.notify_finish)
						az.tabs_finder(playing_artist, playing_title)
					elif s == 'ec':
						#ec = EChordsParser(self.add_tab_to_notebook, self.update_info_tab)
						ec = EChordsParser(self.add_tab_to_notebook, self.notify_finish)
						ec.tabs_finder(playing_artist, playing_title)
					elif s == 'lc':
						#lc = LacuerdaParser(self.add_tab_to_notebook, self.update_info_tab)
						lc = LacuerdaParser(self.add_tab_to_notebook, self.notify_finish)
						lc.tabs_finder(playing_artist, playing_title)

	def deactivate (self, shell):
		print "Plugin deactivated."
		self.shell = None
		self.sp = None
		self.db = None
		self.plugin = None
		shell.remove_widget(self.vbox, RB.ShellUILocation.RIGHT_SIDEBAR)
		uim = self.sp.get_property('ui-manager')		
		uim.remove_ui(self.ui_id)
		uim.remove_action_group(self.action_group)

	# toggles the visibility of the tab widget
	def toggle_visibility(self, action):
		print "Visibility set to " + str(not self.visible)
		if not self.visible:
			self.shell.add_widget(self.vbox, RB.ShellUILocation.RIGHT_SIDEBAR, expand=True, fill=True)
			self.visible = True
			self.load_tabs('hdd')
		else:
			self.shell.remove_widget(self.vbox, RB.ShellUILocation.RIGHT_SIDEBAR)
			self.visible = False
#		gconf.client_get_default().set_bool(self.gconf_keys['visible'], self.visible)
		self.settings.set_boolean('visible', self.visible)

	def edit_tabs(self, action):
		self.toolitemEdit.set_sensitive(False)
		self.get_current_tab().set_editable(True)
		self.toolitemSave.set_sensitive(True)

	# (de)activates the buttons on the toolbar depending on whether
	# they're useful in the current situation
	def update_toolbar(self, notebook, page, page_num):
		self.toolitemEdit.set_sensitive(False)
		self.toolitemSave.set_sensitive(False)
		self.toolitemLoad.set_sensitive(False)
		if page_num == 0:
			self.toolitemLoad.set_sensitive(True)
		if page_num > 0:
			self.toolitemEdit.set_sensitive(True)

	# returns the currently selected tab content
	def get_current_tab(self):
		currentTab = self.notebook.get_current_page()
		return self.notebook.get_nth_page(currentTab).get_child()
		
	# returns the currently selected tab content
	def get_current_tab_title(self):
		currentTab = self.notebook.get_current_page()
		currentTab = self.notebook.get_nth_page(currentTab)
		return self.notebook.get_tab_label(currentTab).get_text()

	# copies currently selected tabs to the hard disk
	def save_tabs(self, action):
		print 'saving tabs to hdd ...'
		self.toolitemSave.set_sensitive(False)
		self.toolitemEdit.set_sensitive(True)
		self.get_current_tab().set_editable(False)
		
		textbuffer = ""
		try:
			textbuffer = self.get_current_tab().get_buffer()
			textbuffer = textbuffer.get_text(textbuffer.get_start_iter() , textbuffer.get_end_iter(), 0)
		except:
			print 'Error: can\'t read current\'s tabs content'
		
		if textbuffer is None:
			print 'Error: loading current tabs failed'
			return
		
		directory = self.get_tabfolder() + '/' + self.info_tab.meta['artist'] + '/'
		
		try:
			os.makedirs(directory)
		except os.error:
			print 'Notice: directory\'s already existing'
		
		filename = directory + self.info_tab.meta['title'] + '.txt'
		
		try:
			file = open(filename, 'w')
		except:
			print "Error: can't open file"
			return
		
		file.write(textbuffer)
		file.close()
		print "-> saved successfully to hdd"
		self.load_tabs('hdd')


	def open_tabs_from_hdd(self, artist, title):
		filename = self.get_tabfolder() + '/' + artist + '/' + title + '.txt'
		print filename
		self.file_res = Gio.File.new_for_path(filename)
		self.file_res.load_contents_async(None, self.open_tabs_from_hdd_cb, {'source': 'hdd', 'artist': artist, 'title': title})

	def open_tabs_from_hdd_cb(self, gdaemonfile, result, params):
		try:
			result = self.file_res.load_contents_finish(result)
		except GError:
			print "Error: can't open file, maybe it's not there at all..."
			self.add_tab_to_notebook(None, params)
			return
		successful = result[0]
		data = result[1]
		
		self.add_tab_to_notebook(data, params)

	def add_tab_to_notebook(self, data, params):
		#print data
		#print "add_tab_to_notebook !!!!"
		if not self.settings.get_boolean('preventautoweblookup'):
			doAutoLookup = True
		else:
			doAutoLookup = False

		# local file not found
		if data is None:
			if params['source'] == 'hdd':
				data = "\t   No tabs found on your hard disk."
				if doAutoLookup:
					data = data + "\n\t   Try checking the tab sites on the internet\n\t   by clicking on the 'load from web' button above."
				else:
					data = data + "\n\t   Wait for the plugin research from web..."

				self.update_info_tab('\t-> Nothing found!\n' + data)
				self.load_tabs('web')
			else:
				data = "you should not see this, check source code!"			
				self.update_info_tab('\t-> Nothing found!\n' + data)
		else:
			if params['source'] == 'hdd':
				if doAutoLookup:
					self.load_tabs('web')
				else:
					self.update_info_tab('\t-> You choose not to lookup when local tab is found...');
			else:
				# inform user on info tab about success at fetching data
				self.update_info_tab('\t-> tabs found on ' + params['source'] + ' for \'' + params['artist'] + '\' - \'' + params['title'] + '\'.')
				tab = Tab('#' + str(len(self.notebook.get_children())) + ' ' + params['source'], data)
				tab.set_meta('artist', params['artist'])
				tab.set_meta('title', params['title'])
				self.tab_list.append(tab)
				self.update_notebook(params['source'], params['artist'], params['title'])

	def update_info_tab(self, new_content):
		self.info_tab.add_content(new_content)
		
		if len(self.notebook.get_children()) == 0:
			# create info tab for the first time
			scroll = self.create_page(self.info_tab.content)
			self.notebook.prepend_page(scroll, Gtk.Label(self.info_tab.label))
		else:
			# update existing info tab
			infoTab = self.notebook.get_nth_page(0).get_child()
			textbuffer = infoTab.get_buffer()
			textbuffer.set_text(self.info_tab.content)
		self.notebook.show()
		self.vbox.show_all()

	def notify_finish(self, content):
		self.update_info_tab(content)
		self.hide_pulse()

	def update_notebook(self, source, artist, title):
		""" Update notebook """
		if len(self.tab_list) == 0:
			print 'no tabs in tab_list !'
		else:
			# data tabs
			for tab in self.tab_list:
				if not(tab.label == "Not Found"): 
					scroll = self.create_page(tab.content)
					self.notebook.append_page(scroll, Gtk.Label(tab.label))
		self.tab_list = []
		self.notebook.show()
		self.vbox.show_all()

	def create_page(self, text):
		fontdesc = Pango.FontDescription("Courier New 8")
		textbuffer = Gtk.TextBuffer()
		textbuffer.set_text(text)
		textview = Gtk.TextView()
		textview.set_buffer(textbuffer)
		textview.set_editable(False)
		textview.modify_font(fontdesc)
		scroll = Gtk.ScrolledWindow()
		scroll.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
		scroll.set_shadow_type(Gtk.ShadowType.IN)
		scroll.add(textview) 
		scroll.show()
		return scroll
Exemplo n.º 37
0
N = int(sys.argv[1])
iterations = int(sys.argv[2])
# debug = True
debugger = Debugger(on=False, cell=False, table=False, program_info=False, history=True)

rank = comm.Get_rank()
processes = comm.Get_size()

if N % processes != 0:
    print("Error - cannot partition the problem")
    comm.Abort()

rows = int(N / processes)
mapper = Mapper(N, rank, rows, debugger)
table = Tab(N, rank, rows, mapper, debugger)

initial_rank = int(processes / 2)
debugger.print_program_info("initial_rank = " + str(initial_rank))
if rank == initial_rank:
    target_x = int(N / 2)
    target_y = int(N / 2)
    debugger.print_program_info("First cell = " + str(target_x) + "," + str(target_y))
    initial_bacteria = Bacteria(target_x, target_y, chance=1)
    table.update_table([initial_bacteria])


def split_bacterias_per_process(bacterias_info, min_x, max_x):
    send_up = list(filter(lambda bacteria: bacteria.target_x == min_x - 1, bacterias_info))
    send_down = list(filter(lambda bacteria: bacteria.target_x == max_x + 1, bacterias_info))
    # print(len(send_up), len(send_down), len(bacterias_info))
Exemplo n.º 38
0
    def __init__(self, nb):
        Tab.__init__(self, nb)
        
        self.fig = Figure((5.0, 4.0), dpi=100)
        col = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BACKGROUND)
        self.fig.patch.set_facecolor((col[0]/255.0, col[1]/255.0, col[2]/255.0))
        self.canvas = FigCanvas(self, -1, self.fig)
        self.ax1 = self.fig.add_subplot(111)        
        self.ax1.set_position([0.1,0.1,0.85,0.86])
        self.ax1.set_ylabel('sig(x)', fontsize=9)
        self.ax1.set_xlabel('Resolution', fontsize=9)
        self.ax1.tick_params(labelsize=8)
        [i.set_linewidth(0.5) for i in self.ax1.spines.itervalues()]
        
        self.side_sizer = wx.FlexGridSizer(rows=0, cols=2, vgap=5, hgap=5)
        
        self.side_sizer.Add(wx.StaticText(self, -1, 'Vm'), 0, wx.EXPAND)
        self._mv = wx.StaticText(self, -1, '')
        self.side_sizer.Add(self._mv, 0, wx.EXPAND)

        self.side_sizer.Add(wx.StaticText(self, -1, 'Solvent'), 0, wx.EXPAND)
        self._s = wx.StaticText(self, -1, '')
        self.side_sizer.Add(self._s, 0, wx.EXPAND)
        
        self.side_sizer.Add(wx.StaticText(self, -1, 'Resolution'), 0, wx.EXPAND)
        self._dmin = wx.StaticText(self, -1, '')
        self.side_sizer.Add(self._dmin, 0, wx.EXPAND)

        self.side_sizer.Add(wx.StaticText(self, -1, 'Completeness'), 0, wx.EXPAND)
        self._c = wx.StaticText(self, -1, '')
        self.side_sizer.Add(self._c, 0, wx.EXPAND)

        self.side_sizer.Add(wx.StaticText(self, -1, 'R Factor'), 0, wx.EXPAND)
        self._r = wx.StaticText(self, -1, '')
        self.side_sizer.Add(self._r, 0, wx.EXPAND)

        self.side_sizer.Add(wx.StaticText(self, -1, 'R Free'), 0, wx.EXPAND)
        self._rfree = wx.StaticText(self, -1, '')
        self.side_sizer.Add(self._rfree, 0, wx.EXPAND)

        self.side_sizer.AddSpacer(20)
        self.side_sizer.AddSpacer(20)
        
        self.side_sizer.Add(wx.StaticText(self, -1, 'sig(x) R'), 0, wx.EXPAND)
        self._sigxr = wx.StaticText(self, -1, '')
        self.side_sizer.Add(self._sigxr, 0, wx.EXPAND)
        
        self.side_sizer.Add(wx.StaticText(self, -1, 'sig(x) Rfree'), 0, wx.EXPAND)
        self._sigxrf = wx.StaticText(self, -1, '')
        self.side_sizer.Add(self._sigxrf, 0, wx.EXPAND)
        
        self.side_sizer.AddSpacer(20)
        self.side_sizer.AddSpacer(20)
        
        self.side_sizer.Add(wx.StaticText(self, -1, 'sig(x) - 3sig (ASP)'), 0, wx.EXPAND)
        self.side_sizer.Add(wx.StaticText(self, -1, '0.024'), 0, wx.EXPAND)
        
        self.side_sizer.Add(wx.StaticText(self, -1, 'sig(x) - 3sig (HIS)'), 0, wx.EXPAND)
        self.side_sizer.Add(wx.StaticText(self, -1, ''), 0, wx.EXPAND)
        
        self.sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.sizer.Add(self.side_sizer, 0, wx.EXPAND|wx.ALL, 10)
        self.sizer.Add(self.canvas, 1, wx.EXPAND|wx.ALL, 5)
        
        
        self.SetSizer(self.sizer)
Exemplo n.º 39
0
Arquivo: App.py Projeto: balu/fm
 def __init__(self, names, ui, config):
     self.config = config
     self.tablist = []
     for name in names:
         tab = Tab.create(self, name)
         if tab: self.tablist.append(tab)
     if not self.tablist:
         self.tablist = [Tab.create(self)]
     self.curtab = 0
     self.UI = ui
     self.UI.init(self)
     self.Registers = {
         'a': [],
         'b': [],
         'c': [],
         'd': [],
         'e': [],
         'f': [],
         'g': [],
         'h': [],
         'i': [],
         'j': [],
         'k': [],
         'l': [],
         'm': [],
         'n': [],
         'o': [],
         'p': [],
         'q': [],
         'r': [],
         's': [],
         't': [],
         'u': [],
         'v': [],
         'w': [],
         'x': [],
         'y': [],
         'z': [],
         'A': [],
         'B': [],
         'C': [],
         'D': [],
         'E': [],
         'F': [],
         'G': [],
         'H': [],
         'I': [],
         'J': [],
         'K': [],
         'L': [],
         'M': [],
         'N': [],
         'O': [],
         'P': [],
         'Q': [],
         'R': [],
         'S': [],
         'T': [],
         'U': [],
         'V': [],
         'W': [],
         'X': [],
         'Y': [],
         'Z': [],
         '0': [],
         '1': [],
         '2': [],
         '3': [],
         '4': [],
         '5': [],
         '6': [],
         '7': [],
         '8': [],
         '9': []
     }
Exemplo n.º 40
0
    def __init__(self, nb):
        Tab.__init__(self, nb)

        self._pdbt = PDBTools()
        
        self._res_size = (200,170)
        self._to_save = []
        
        self.fig = Figure((5.0, 4.0), dpi=100)
        col = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BACKGROUND)
        self.fig.patch.set_facecolor((col[0]/255.0, col[1]/255.0, col[2]/255.0))
        self.canvas = FigCanvas(self, -1, self.fig)

        self.res = wx.StaticBitmap(self, size=self._res_size)
        self.res.SetBitmap(wx.EmptyImage(self._res_size[0], self._res_size[1]).ConvertToBitmap())

        self._rtypes = ['Aspartate', 'Glutamate', 'Histidine', 'Arginine']
        self._rtypess = ['Asp', 'Glu', 'His', 'Arg']
        
        self.ax1 = self.fig.add_subplot(111)
        self.ax1.set_position([0.10,0.153,0.80,0.81])
        #self.ax1.set_frame_on(False)
        [i.set_linewidth(0.5) for i in self.ax1.spines.itervalues()]
        self.ax2 = self.ax1.twinx()
        self.ax2.set_position([0.10,0.153,0.80,0.81])
        self.ax1.tick_params(labelsize=8)
        self.ax2.tick_params(labelsize=8)   
        
        self._highlight = -2
        
        self._bond_lengths = ''
        self._std_devs = ''
        self._residue_selection = []
        self._chain_lookup = {}
        
        self._residue_type = 0
        
        self._residues = {'asp': {}, 'glu': {}, 'his': {}, 'arg': {}}
        self._omitted = {'asp': [], 'glu': [], 'his': [], 'arg': []}
        
        self.omitted_title = wx.StaticBox( self, -1, "Omitted" ) 
        self.omitted_sizer = wx.StaticBoxSizer( self.omitted_title, wx.HORIZONTAL)        
        
        self.selected_title = wx.StaticBox( self, -1, "Displayed" ) 
        self.selected_sizer = wx.StaticBoxSizer( self.selected_title, wx.HORIZONTAL)        
        
        self.residue_info_title = wx.StaticBox( self, -1, "Residue Info: " ) 
        self.residue_info_sizer = wx.StaticBoxSizer( self.residue_info_title, wx.VERTICAL)
        
        #self.residue_info = wx.FlexGridSizer(rows=0, cols=2, vgap=5, hgap=5)
        
        #self.residue_info.Add(wx.StaticText(self, -1, 'D(C-O)'))
        #self._dco = wx.StaticText(self, -1, '')
        #self.residue_info.Add(self._dco)

        #self.residue_info.Add(wx.StaticText(self, -1, 'S(D(C-O))'))
        #self._sdco = wx.StaticText(self, -1, '')
        #self.residue_info.Add(self._sdco)
            
        #self.residue_info.Add(wx.StaticText(self, -1, 'Level'))
        #self._lev = wx.StaticText(self, -1, '')
        #self.residue_info.Add(self._lev)
        
        #self.residue_info_sizer.Add(self.residue_info, 0)
        self.residue_info_sizer.Add(self.res, 0)        
        
        self.residue_sel = wx.ListBox(self, 26, wx.DefaultPosition, (70, 80), [], wx.LB_MULTIPLE)
        self.residue_sel.Bind(wx.EVT_LISTBOX, self._update_sel)
        self.omitted_res = wx.ListBox(self, 26, wx.DefaultPosition, (70, 80), [], wx.LB_SINGLE)
        self.omitted_res.Bind(wx.EVT_LISTBOX, self._goto_omitted)

        self.data_box = wx.BoxSizer(wx.HORIZONTAL)
        self.data_box.Add(wx.StaticText(self, -1, 'Residue Type'), 0, wx.EXPAND|wx.ALL, 5)

        self.res_type = wx.ComboBox(self, -1, choices=[], style=wx.CB_READONLY)
        self.res_type.Bind(wx.EVT_COMBOBOX, self._set_residue_type)
        self.data_box.Add(self.res_type, 0, wx.EXPAND|wx.ALL, 5)

        self.omitted_sizer.Add(self.omitted_res, 1, wx.EXPAND|wx.ALL, 0)
        self.selected_sizer.Add(self.residue_sel, 1, wx.EXPAND|wx.ALL, 0)
                                                 
        self.ressel_sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.ressel_sizer.Add(self.omitted_sizer, 1, wx.EXPAND|wx.ALL, 5)
        self.ressel_sizer.Add(self.selected_sizer, 1, wx.EXPAND|wx.ALL, 5)
        
        lig = metallicbutton.MetallicButton(self, -1, 'Ligands', '', bitmaps.fetch_icon_bitmap('actions', 'viewmag', scale=(16,16)), size=(75, 25))
        save = metallicbutton.MetallicButton(self, -1, 'Figure', '', bitmaps.fetch_icon_bitmap('actions', 'save_all', scale=(16,16)), size=(65, 25))
        tab = metallicbutton.MetallicButton(self, -1, 'Data', '', bitmaps.fetch_icon_bitmap('actions', 'save_all', scale=(16,16)), size=(65, 25))
        self.Bind(wx.EVT_BUTTON, self._view_ligands, lig)
        self.Bind(wx.EVT_BUTTON, self._save_figure, save)
        self.Bind(wx.EVT_BUTTON, self._save_data, tab)
        
        self.button_sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.button_sizer.Add(save, 0, wx.LEFT, 5)
        self.button_sizer.Add(tab, 0, wx.LEFT, 5)
        self.button_sizer.Add(lig, 0, wx.LEFT, 5)
        
        self.residue_box = wx.BoxSizer(wx.VERTICAL)
        self.residue_box.Add(self.data_box, 0)
        self.residue_box.Add(self.residue_info_sizer, 0, wx.EXPAND, 10)
        self.residue_box.Add(self.ressel_sizer, 0)
        self.residue_box.Add(self.button_sizer, 0)
        
        self.main = wx.BoxSizer(wx.HORIZONTAL)
        self.main.Add(self.residue_box, 1, wx.EXPAND|wx.ALL, 5)
        
        self.averages = wx.StaticText(self, -1, '', style=wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
        self.bottom_sizer = wx.BoxSizer(wx.HORIZONTAL)
        #self.bottom_sizer.Add(self.button_sizer, 0)
        self.bottom_sizer.Add(self.averages, 1, wx.EXPAND)
        
        self.canvas_sizer = wx.BoxSizer(wx.VERTICAL)
        self.canvas_sizer.Add(self.canvas, 1, wx.EXPAND|wx.ALL)
        self.canvas_sizer.Add(self.bottom_sizer, 0, wx.EXPAND)
                
        self.main.Add(self.canvas_sizer, 3, wx.EXPAND|wx.ALL, 5)
        
        self.SetSizer(self.main)
        self.main.Fit(self)
        
        self.canvas.mpl_connect('button_press_event', self._on_click)
        self.canvas.mpl_connect('pick_event', self._show_series)
Exemplo n.º 41
0
    def main():
        tab = Tab()
        history = History()

        tab.setUrl("http://tutorialspoint.com")
        history.add(tab.saveUrl())

        tab.setUrl("https://www.python.org/doc/")
        history.add(tab.saveUrl())

        tab.setUrl("http://www.trome.com.pe")

        print("Current web url: " + tab.getUrl())

        print("Back button is clicked.. ")
        tab.restoreFromSavedUrl(history.get(1))
        print("Saved url: " + tab.getUrl())

        print("Back button again.. ")
        tab.restoreFromSavedUrl(history.get(0))
        print("Saved url: " + tab.getUrl())
Exemplo n.º 42
0
 def generate_tab(self):
     newTab = Tab(self.name.text())
     self.main.tabList.append(newTab)
     print(newTab.title)
     self.main.add_tab(newTab)
     self.close()
Exemplo n.º 43
0
    def __init__(self, nb):
        Tab.__init__(self, nb)

        self.fig = Figure((5.0, 4.0), dpi=100)
        col = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BACKGROUND)
        self.fig.patch.set_facecolor((col[0]/255.0, col[1]/255.0, col[2]/255.0))
        self.canvas = FigCanvas(self, -1, self.fig)             

        self.res = wx.StaticBitmap(self, size=(200,237))
        self.res.SetBitmap(wx.EmptyImage( 200,237 ).ConvertToBitmap())

        self._rtypes = ['Aspartate', 'Glutamate', 'Histidine', 'Arginine']
        self._rtypess = ['Asp', 'Glu', 'His', 'Arg']
        
        self.ax1 = self.fig.add_subplot(111)
        self.ax1.set_position([0.10,0.153,0.80,0.81])
        self.ax2 = self.ax1.twinx()
        self.ax1.tick_params(labelsize=8)
        self.ax2.tick_params(labelsize=8)   
        
        self._highlight = 0
        
        self._bond_lengths = ''
        self._std_devs = ''
        self._residue_selection = []
        
        self._residue_type = 0
        
        self._residues = {'asp': {}, 'glu': {}, 'his': {}, 'arg': {}}
        self._omitted = {'asp': [], 'glu': [], 'his': [], 'arg': []}
        
        self.omitted_title = wx.StaticBox( self, -1, "Omitted" ) 
        self.omitted_sizer = wx.StaticBoxSizer( self.omitted_title, wx.HORIZONTAL)        
        
        self.selected_title = wx.StaticBox( self, -1, "Displayed" ) 
        self.selected_sizer = wx.StaticBoxSizer( self.selected_title, wx.HORIZONTAL)        
        
        self.residue_info_title = wx.StaticBox( self, -1, "Residue Info: " ) 
        self.residue_info_sizer = wx.StaticBoxSizer( self.residue_info_title, wx.HORIZONTAL)        
        
        self._labels = [ 
                        wx.StaticText(self, -1, 'D(C-O)'),
                        wx.StaticText(self, -1, 'S(D(C-O))'),
                        wx.StaticText(self, -1, 'Level'),
                        
                        wx.StaticText(self, -1, 'Avg S'),
                        wx.StaticText(self, -1, 'Avg B'),
                      ]
                      
        self._values = [ wx.StaticText(self, -1, '') for x in range(len(self._labels)) ]
                              
                              
        self.residue_info = wx.GridSizer(rows=5, cols=2, vgap=5, hgap=5)
        for i in range(len(self._labels)):
            self.residue_info.Add(self._labels[i], 0, wx.EXPAND)
            self.residue_info.Add(self._values[i], 0, wx.EXPAND)
        
        self.residue_info_sizer.Add(self.residue_info, 0)
        self.residue_info_sizer.Add(self.res, 0)        
        
        self.residue_sel = wx.ListBox(self, 26, wx.DefaultPosition, (80, 100), [], wx.LB_MULTIPLE)
        self.residue_sel.Bind(wx.EVT_LISTBOX, self._update_sel)
        self.omitted_res = wx.ListBox(self, 26, wx.DefaultPosition, (80, 100), [], wx.LB_SINGLE)
        self.omitted_res.Bind(wx.EVT_LISTBOX, self._goto_omitted)
                
        self._data_widgets = [ wx.StaticText(self, -1, 'Bond Lengths'),
                               wx.ComboBox(self, -1, '', choices=[], style=wx.CB_READONLY),
                               wx.StaticText(self, -1, 'Standard Deviations'),
                               wx.ComboBox(self, -1, choices=[], style=wx.CB_READONLY),
                               wx.StaticText(self, -1, 'Residue Type'),
                               wx.ComboBox(self, -1, choices=[], style=wx.CB_READONLY)]

        self._data_widgets[1].Bind(wx.EVT_COMBOBOX, self._set_data)
        self._data_widgets[3].Bind(wx.EVT_COMBOBOX, self._set_data)
        self._data_widgets[5].Bind(wx.EVT_COMBOBOX, self._set_residue_type)
        self._data_widgets[5].SetStringSelection('Aspartate')

        self.data_box = wx.GridSizer(rows=3, cols=2, vgap=5, hgap=5)
        for i in range(len(self._data_widgets)):
            self.data_box.Add(self._data_widgets[i], 0, wx.EXPAND)  
        
        self.omitted_sizer.Add(self.omitted_res)
        self.selected_sizer.Add(self.residue_sel)
        
        self.button_sizer = wx.BoxSizer(wx.VERTICAL)
        
        coot = wx.BitmapButton(self, 1, wx.Image('Resources/Icons/coot_logo.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap())
        pymol = wx.BitmapButton(self, 2, wx.Image('Resources/Icons/pymol.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap())
        plot = wx.BitmapButton(self, 3, wx.Image('Resources/Icons/plot_tiny.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap())        
        self.button_sizer.Add(coot, 0, wx.EXPAND)
        self.button_sizer.Add(pymol, 0, wx.EXPAND)                        
        self.button_sizer.Add(plot, 0, wx.EXPAND)                      
        plot.Bind(wx.EVT_BUTTON, self._save_figure)
                                                 
        self.ressel_sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.ressel_sizer.Add(self.omitted_sizer)
        self.ressel_sizer.Add(self.selected_sizer)
        self.ressel_sizer.Add(self.button_sizer)
                                            
        self.residue_box = wx.BoxSizer(wx.VERTICAL)
        self.residue_box.Add(self.data_box)
        self.residue_box.Add(self.residue_info_sizer, 0, wx.EXPAND | wx.TOP, 10)
        self.residue_box.Add(self.ressel_sizer)
        
        self.main = wx.BoxSizer(wx.HORIZONTAL)
        self.main.Add(self.residue_box, 0, wx.ALL, 10)
        self.main.Add(self.canvas, 0, wx.ALL, 5)
        
        self.SetSizer(self.main)
        self.main.Fit(self)
        
        self.canvas.mpl_connect('button_press_event', self._on_click)
        self.update_inputs()