idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
24,700 | def init_and_start ( self , taskParent , override = { } ) : tag = self . initialize ( taskParent , override = override ) self . start ( ) return tag | Convenience method to initialize and start a task . |
24,701 | def wait ( self , timeout = None ) : self . ev_done . wait ( timeout = timeout ) if not self . ev_done . is_set ( ) : raise TaskTimeout ( "Task %s timed out." % self ) if isinstance ( self . result , Exception ) : raise self . result return self . result | This method waits for an executing task to finish . Subclass can override this method if necessary . |
24,702 | def done ( self , result , noraise = False ) : if self . ev_done . is_set ( ) : if isinstance ( self . result , Exception ) and ( not noraise ) : raise self . result return self . result self . endtime = time . time ( ) try : self . totaltime = self . endtime - self . starttime except AttributeError : self . totaltime = 0.0 self . result = result self . ev_done . set ( ) self . make_callback ( 'resolved' , self . result ) if isinstance ( result , Exception ) and ( not noraise ) : raise result return result | This method is called when a task has finished executing . Subclass can override this method if desired but should call superclass method at the end . |
24,703 | def runTask ( self , task , timeout = None ) : task . initialize ( self ) task . start ( ) time . sleep ( 0 ) res = task . wait ( timeout = timeout ) return res | Run a child task to completion . Returns the result of the child task . |
24,704 | def execute ( self ) : while self . index < len ( self . tasklist ) : res = self . step ( ) self . logger . debug ( 'SeqSet task %i has completed with result %s' % ( self . index , res ) ) return res | Run all child tasks in order waiting for completion of each . Return the result of the final child task s execution . |
24,705 | def execute ( self ) : self . count = 0 self . taskset = [ ] self . results = { } self . totaltime = time . time ( ) for task in list ( self . taskseq ) : self . taskset . append ( task ) task . add_callback ( 'resolved' , self . child_done , self . count ) self . count += 1 self . numtasks = self . count with self . regcond : for task in list ( self . taskset ) : task . initialize ( self ) task . start ( ) self . totaltime = time . time ( ) - self . totaltime while self . count > 0 : self . regcond . wait ( ) for key in self . results . keys ( ) : value = self . results [ key ] if isinstance ( value , Exception ) : ( count , task ) = key self . logger . error ( "Child task %s terminated with exception: %s" % ( task . tag , str ( value ) ) ) raise value return 0 | Run all child tasks concurrently in separate threads . Return 0 after all child tasks have completed execution . |
24,706 | def execute ( self ) : with self . _lock_c : self . count = 0 self . numtasks = 0 self . taskset = [ ] self . results = { } self . totaltime = time . time ( ) for task in self . taskseq : self . taskset . append ( task ) self . numtasks += 1 task . init_and_start ( self ) num_tasks = self . getNumTasks ( ) while num_tasks > 0 : self . check_state ( ) for i in range ( num_tasks ) : try : try : task = self . getTask ( i ) except IndexError : break res = task . wait ( timeout = self . idletime ) self . child_done ( res , task ) except TaskTimeout : continue except Exception as e : self . child_done ( e , task ) continue num_tasks = self . getNumTasks ( ) for key in self . results . keys ( ) : value = self . results [ key ] if isinstance ( value , Exception ) : ( count , task ) = key self . logger . error ( "Child task %s terminated with exception: %s" % ( task . tag , str ( value ) ) ) raise value return value | Run all child tasks concurrently in separate threads . Return last result after all child tasks have completed execution . |
24,707 | def execute ( self , task ) : taskid = str ( task ) res = None try : self . time_start = time . time ( ) self . setstatus ( 'executing %s' % taskid ) self . logger . debug ( "now executing task '%s'" % taskid ) try : res = task . execute ( ) except UserTaskException as e : res = e except Exception as e : self . logger . error ( "Task '%s' raised exception: %s" % ( str ( task ) , str ( e ) ) ) res = e try : ( type , value , tb ) = sys . exc_info ( ) self . logger . debug ( "Traceback:\n%s" % "" . join ( traceback . format_tb ( tb ) ) ) tb = None except Exception as e : self . logger . debug ( "Traceback information unavailable." ) finally : self . logger . debug ( "done executing task '%s'" % str ( task ) ) self . setstatus ( 'cleaning %s' % taskid ) task . done ( res , noraise = True ) self . time_start = 0.0 self . setstatus ( 'idle' ) | Execute a task . |
24,708 | def startall ( self , wait = False , ** kwdargs ) : self . logger . debug ( "startall called" ) with self . regcond : while self . status != 'down' : if self . status in ( 'start' , 'up' ) or self . ev_quit . is_set ( ) : self . logger . error ( "ignoring duplicate request to start thread pool" ) return self . logger . debug ( "waiting for threads: count=%d" % self . runningcount ) self . regcond . wait ( ) if self . ev_quit . is_set ( ) : return self . runningcount = 0 self . status = 'start' self . workers = [ ] if wait : tpool = self else : tpool = None self . logger . debug ( "starting threads in thread pool" ) for i in range ( self . numthreads ) : t = self . workerClass ( self . queue , logger = self . logger , ev_quit = self . ev_quit , tpool = tpool , ** kwdargs ) self . workers . append ( t ) t . start ( ) if wait : while self . status != 'up' and not self . ev_quit . is_set ( ) : self . logger . debug ( "waiting for threads: count=%d" % self . runningcount ) self . regcond . wait ( ) else : self . status = 'up' self . logger . debug ( "startall done" ) | Start all of the threads in the thread pool . If _wait_ is True then don t return until all threads are up and running . Any extra keyword arguments are passed to the worker thread constructor . |
24,709 | def stopall ( self , wait = False ) : self . logger . debug ( "stopall called" ) with self . regcond : while self . status != 'up' : if self . status in ( 'stop' , 'down' ) or self . ev_quit . is_set ( ) : self . logger . warning ( "ignoring duplicate request to stop thread pool." ) return self . logger . debug ( "waiting for threads: count=%d" % self . runningcount ) self . regcond . wait ( ) self . logger . debug ( "stopping threads in thread pool" ) self . status = 'stop' self . ev_quit . set ( ) if wait : while self . status != 'down' : self . logger . debug ( "waiting for threads: count=%d" % self . runningcount ) self . regcond . wait ( ) self . logger . debug ( "stopall done" ) | Stop all threads in the worker pool . If _wait_ is True then don t return until all threads are down . |
24,710 | def wcs_pix_transform ( ct , i , format = 0 ) : z1 = float ( ct . z1 ) z2 = float ( ct . z2 ) i = float ( i ) yscale = 128.0 / ( z2 - z1 ) if ( format == 'T' or format == 't' ) : format = 1 if ( i == 0 ) : t = 0. else : if ( ct . zt == W_LINEAR ) : t = ( ( i - 1 ) * ( z2 - z1 ) / 199.0 ) + z1 t = max ( z1 , min ( z2 , t ) ) else : t = float ( i ) if ( format > 1 ) : t = ( z2 - t ) * yscale return ( t ) | Computes the WCS corrected pixel value given a coordinate transformation and the raw pixel value . |
24,711 | def handle_request ( self ) : try : ( request , client_address ) = self . get_request ( ) except socket . error as e : self . logger . error ( "error opening the connection: %s" % ( str ( e ) ) ) for exctn in sys . exc_info ( ) : print ( exctn ) return try : self . RequestHandlerClass ( request , client_address , self ) except Exception as e : self . logger . error ( 'error handling the request: %s' % ( str ( e ) ) ) for exctn in sys . exc_info ( ) : print ( exctn ) return | Handles incoming connections one at the time . |
24,712 | def mainloop ( self ) : try : while ( not self . ev_quit . is_set ( ) ) : try : self . handle_request ( ) except socketTimeout : continue finally : self . socket . close ( ) | main control loop . |
24,713 | def handle_feedback ( self , pkt ) : self . logger . debug ( "handle feedback" ) self . frame = self . decode_frameno ( pkt . z & 0o7777 ) - 1 self . server . controller . init_frame ( self . frame ) self . server . controller . set_frame ( self . frame ) | This part of the protocol is used by IRAF to erase a frame in the framebuffers . |
24,714 | def handle_lut ( self , pkt ) : self . logger . debug ( "handle lut" ) if pkt . subunit & COMMAND : data_type = str ( pkt . nbytes / 2 ) + 'h' line = pkt . datain . read ( pkt . nbytes ) n = len ( line ) if ( n < pkt . nbytes ) : return try : x = struct . unpack ( data_type , line ) except Exception as e : self . logger . error ( "Error unpacking struct: %s" % ( str ( e ) ) ) return if len ( x ) < 14 : y = [ ] for i in range ( 14 ) : try : y . append ( x [ i ] ) except Exception : y . append ( 0 ) x = y del ( y ) if len ( x ) == 14 : z = int ( x [ 0 ] ) self . frame = self . decode_frameno ( z ) - 1 if ( self . frame > MAX_FRAMES ) : self . logger . error ( "attempt to select non existing frame." ) return try : self . server . controller . get_frame ( self . frame ) except KeyError : self . server . controller . init_frame ( self . frame ) return self . logger . error ( "unable to select a frame." ) return self . logger . error ( "what shall I do?" ) | This part of the protocol is used by IRAF to set the frame number . |
24,715 | def handle_imcursor ( self , pkt ) : self . logger . debug ( "handle imcursor" ) if pkt . tid & IIS_READ : if pkt . tid & IMC_SAMPLE : self . logger . debug ( "SAMPLE" ) wcsflag = int ( pkt . z ) res = self . server . controller . get_keystroke ( ) self . return_cursor ( pkt . dataout , res . x , res . y , res . frame , wcsflag , '0' , '' ) else : self . logger . debug ( "OTHER" ) res = self . server . controller . get_keystroke ( ) self . logger . debug ( "FRAME=%d X,Y=%f,%f" % ( res . frame , res . x , res . y ) ) self . x = res . x self . y = res . y self . frame = res . frame wcsflag = 0 self . return_cursor ( pkt . dataout , res . x , res . y , res . frame , wcsflag , res . key , '' ) else : self . logger . debug ( "READ" ) sx = int ( pkt . x ) sy = int ( pkt . y ) wx = float ( pkt . x ) wy = float ( pkt . y ) wcs = int ( pkt . z ) if wcs : try : fb = self . server . controller . get_frame ( self . frame ) except KeyError : fb = self . server . controller . init_frame ( self . frame ) fb . ct = self . wcs_update ( fb . wcs ) if fb . ct . valid : if abs ( fb . ct . a ) > 0.001 : sx = int ( ( wx - fb . ct . tx ) / fb . ct . a ) if abs ( fb . ct . d ) > 0.001 : sy = int ( ( wy - fb . ct . ty ) / fb . ct . d ) self . server . controller . set_cursor ( sx , sy ) | This part of the protocol is used by IRAF to read the cursor position and keystrokes from the display client . |
24,716 | def handle ( self ) : self . logger = self . server . logger packet = iis ( ) packet . datain = self . rfile packet . dataout = self . wfile size = struct . calcsize ( '8h' ) line = packet . datain . read ( size ) n = len ( line ) if n < size : return while n > 0 : try : bytes = struct . unpack ( '8h' , line ) except Exception : self . logger . error ( 'error unpacking the data.' ) for exctn in sys . exc_info ( ) : print ( exctn ) subunit = bytes [ 2 ] subunit077 = subunit & 0o77 tid = bytes [ 0 ] x = bytes [ 4 ] & 0o177777 y = bytes [ 5 ] & 0o177777 z = bytes [ 6 ] & 0o177777 t = bytes [ 7 ] & 0o17777 ndatabytes = - bytes [ 1 ] if ( not ( tid & PACKED ) ) : ndatabytes *= 2 packet . subunit = subunit packet . subunit077 = subunit077 packet . tid = tid packet . x = x packet . y = y packet . z = z packet . t = t packet . nbytes = ndatabytes self . logger . debug ( "PACKET IS %o" % packet . subunit ) if packet . subunit077 == FEEDBACK : self . handle_feedback ( packet ) elif packet . subunit077 == LUT : self . handle_lut ( packet ) line = packet . datain . read ( size ) n = len ( line ) continue elif packet . subunit077 == MEMORY : self . handle_memory ( packet ) if self . needs_update : pass line = packet . datain . read ( size ) n = len ( line ) continue elif packet . subunit077 == WCS : self . handle_wcs ( packet ) line = packet . datain . read ( size ) n = len ( line ) continue elif packet . subunit077 == IMCURSOR : self . handle_imcursor ( packet ) line = packet . datain . read ( size ) n = len ( line ) continue else : self . logger . debug ( '?NO OP (0%o)' % ( packet . subunit077 ) ) if not ( packet . tid & IIS_READ ) : nbytes = packet . nbytes while nbytes > 0 : if nbytes < SZ_FIFOBUF : n = nbytes else : n = SZ_FIFOBUF m = self . rfile . read ( n ) if m <= 0 : break nbytes -= n line = packet . datain . read ( size ) n = len ( line ) if n < size : return if self . needs_update : self . display_image ( ) self . needs_update = False | This is where the action starts . |
24,717 | def display_image ( self , reset = 1 ) : try : fb = self . server . controller . get_frame ( self . frame ) except KeyError : fb = self . server . controller . init_frame ( self . frame ) if not fb . height : width = fb . width height = int ( len ( fb . buffer ) / width ) fb . height = height if ( len ( fb . buffer ) > 0 ) and ( height > 0 ) : self . server . controller . display ( self . frame , width , height , True ) else : self . server . controller . display ( self . frame , fb . width , fb . height , False ) | Utility routine used to display an updated frame from a framebuffer . |
24,718 | def _highlight_path ( self , hl_path , tf ) : fc = self . settings . get ( 'row_font_color' , 'green' ) try : self . treeview . highlight_path ( hl_path , tf , font_color = fc ) except Exception as e : self . logger . info ( 'Error changing highlight on treeview path ' '({0}): {1}' . format ( hl_path , str ( e ) ) ) | Highlight or unhighlight a single entry . |
24,719 | def update_highlights ( self , old_highlight_set , new_highlight_set ) : if not self . gui_up : return un_hilite_set = old_highlight_set - new_highlight_set re_hilite_set = new_highlight_set - old_highlight_set for key in un_hilite_set : self . _highlight_path ( key , False ) for key in re_hilite_set : self . _highlight_path ( key , True ) | Unhighlight the entries represented by old_highlight_set and highlight the ones represented by new_highlight_set . |
24,720 | def show_selection ( self , star ) : try : self . _select_flag = True self . mark_selection ( star ) finally : self . _select_flag = False | This method is called when the user clicks on a plotted star in the fitsviewer . |
24,721 | def select_star_cb ( self , widget , res_dict ) : keys = list ( res_dict . keys ( ) ) if len ( keys ) == 0 : self . selected = [ ] self . replot_stars ( ) else : idx = int ( keys [ 0 ] ) star = self . starlist [ idx ] if not self . _select_flag : self . mark_selection ( star , fromtable = True ) return True | This method is called when the user selects a star from the table . |
24,722 | def _calc_order ( self , order ) : if order is not None and order != '' : self . order = order . upper ( ) else : shape = self . shape if len ( shape ) <= 2 : self . order = 'M' else : depth = shape [ - 1 ] if depth == 1 : self . order = 'M' elif depth == 2 : self . order = 'AM' elif depth == 3 : self . order = 'RGB' elif depth == 4 : self . order = 'RGBA' | Called to set the order of a multi - channel image . The order should be determined by the loader but this will make a best guess if passed order is None . |
24,723 | def cutout_data ( self , x1 , y1 , x2 , y2 , xstep = 1 , ystep = 1 , astype = None ) : view = np . s_ [ y1 : y2 : ystep , x1 : x2 : xstep ] data = self . _slice ( view ) if astype : data = data . astype ( astype , copy = False ) return data | cut out data area based on coords . |
24,724 | def get_shape_mask ( self , shape_obj ) : wd , ht = self . get_size ( ) yi = np . mgrid [ : ht ] . reshape ( - 1 , 1 ) xi = np . mgrid [ : wd ] . reshape ( 1 , - 1 ) pts = np . asarray ( ( xi , yi ) ) . T contains = shape_obj . contains_pts ( pts ) return contains | Return full mask where True marks pixels within the given shape . |
24,725 | def get_shape_view ( self , shape_obj , avoid_oob = True ) : x1 , y1 , x2 , y2 = [ int ( np . round ( n ) ) for n in shape_obj . get_llur ( ) ] if avoid_oob : wd , ht = self . get_size ( ) x1 , x2 = max ( 0 , x1 ) , min ( x2 , wd - 1 ) y1 , y2 = max ( 0 , y1 ) , min ( y2 , ht - 1 ) yi = np . mgrid [ y1 : y2 + 1 ] . reshape ( - 1 , 1 ) xi = np . mgrid [ x1 : x2 + 1 ] . reshape ( 1 , - 1 ) pts = np . asarray ( ( xi , yi ) ) . T contains = shape_obj . contains_pts ( pts ) view = np . s_ [ y1 : y2 + 1 , x1 : x2 + 1 ] return ( view , contains ) | Calculate a bounding box in the data enclosing shape_obj and return a view that accesses it and a mask that is True only for pixels enclosed in the region . |
24,726 | def cutout_shape ( self , shape_obj ) : view , mask = self . get_shape_view ( shape_obj ) data = self . _slice ( view ) mdata = np . ma . array ( data , mask = np . logical_not ( mask ) ) return mdata | Cut out and return a portion of the data corresponding to shape_obj . A masked numpy array is returned where the pixels not enclosed in the shape are masked out . |
24,727 | def remove_callback ( self , name , fn , * args , ** kwargs ) : try : tup = ( fn , args , kwargs ) if tup in self . cb [ name ] : self . cb [ name ] . remove ( tup ) except KeyError : raise CallbackError ( "No callback category of '%s'" % ( name ) ) | Remove a specific callback that was added . |
24,728 | def cmap2pixmap ( cmap , steps = 50 ) : import numpy as np inds = np . linspace ( 0 , 1 , steps ) n = len ( cmap . clst ) - 1 tups = [ cmap . clst [ int ( x * n ) ] for x in inds ] rgbas = [ QColor ( int ( r * 255 ) , int ( g * 255 ) , int ( b * 255 ) , 255 ) . rgba ( ) for r , g , b in tups ] im = QImage ( steps , 1 , QImage . Format_Indexed8 ) im . setColorTable ( rgbas ) for i in range ( steps ) : im . setPixel ( i , 0 , i ) im = im . scaled ( 128 , 32 ) pm = QPixmap . fromImage ( im ) return pm | Convert a Ginga colormap into a QPixmap |
24,729 | def start ( self , duration = None ) : if duration is None : duration = self . duration self . set ( duration ) | Start the timer . If duration is not None it should specify the time to expiration in seconds . |
24,730 | def _snap_cb ( self , w ) : self . scrnimage . clear ( ) self . scrnimage . redraw_now ( whence = 0 ) self . fv . update_pending ( ) format = self . tosave_type if self . _screen_size : self . fv . error_wrap ( self . fitsimage . save_rgb_image_as_file , self . tmpname , format = format ) else : self . check_and_adjust_dimensions ( ) bg = self . fitsimage . get_bg ( ) self . shot_generator . set_bg ( * bg ) c1 = self . fitsimage . get_canvas ( ) c2 = self . shot_generator . get_canvas ( ) c2 . delete_all_objects ( redraw = False ) c2 . add ( c1 , redraw = False ) self . shot_generator . _imgobj = self . fitsimage . _imgobj scale_x , scale_y = self . fitsimage . get_scale_xy ( ) c1_wd , c1_ht = self . fitsimage . get_window_size ( ) c2_wd , c2_ht = self . shot_generator . get_window_size ( ) scale_wd = float ( c2_wd ) / float ( c1_wd ) scale_ht = float ( c2_ht ) / float ( c1_ht ) scale = max ( scale_wd , scale_ht ) scale_x *= scale scale_y *= scale self . shot_generator . scale_to ( scale_x , scale_y ) self . fitsimage . copy_attributes ( self . shot_generator , self . transfer_attrs ) self . fv . error_wrap ( self . shot_generator . save_rgb_image_as_file , self . tmpname , format = format ) c2 . delete_all_objects ( redraw = False ) self . shot_generator . _imgobj = None self . saved_type = format img = RGBImage ( logger = self . logger ) img . load_file ( self . tmpname ) self . scrnimage . set_image ( img ) | This function is called when the user clicks the Snap button . |
24,731 | def _save_cb ( self , w ) : format = self . saved_type if format is None : return self . fv . show_error ( "Please save an image first." ) filename = self . w . name . get_text ( ) . strip ( ) if len ( filename ) == 0 : return self . fv . show_error ( "Please set a name for saving the file" ) self . save_name = filename if not filename . lower ( ) . endswith ( '.' + format ) : filename = filename + '.' + format path = self . w . folder . get_text ( ) . strip ( ) if path == '' : path = filename else : self . save_path = path path = os . path . join ( path , filename ) self . fv . error_wrap ( shutil . copyfile , self . tmpname , path ) | This function is called when the user clicks the Save button . We save the last taken shot to the folder and name specified . |
24,732 | def _lock_aspect_cb ( self , w , tf ) : self . _lock_aspect = tf self . w . aspect . set_enabled ( tf ) if self . _lock_aspect : self . _set_aspect_cb ( ) else : wd , ht = self . get_wdht ( ) _as = self . calc_aspect_str ( wd , ht ) self . w . aspect . set_text ( _as ) | This function is called when the user clicks the Lock aspect checkbox . tf is True if checked False otherwise . |
24,733 | def _screen_size_cb ( self , w , tf ) : self . _screen_size = tf self . w . width . set_enabled ( not tf ) self . w . height . set_enabled ( not tf ) self . w . lock_aspect . set_enabled ( not tf ) if self . _screen_size : wd , ht = self . fitsimage . get_window_size ( ) self . _configure_cb ( self . fitsimage , wd , ht ) | This function is called when the user clicks the Screen size checkbox . tf is True if checked False otherwise . |
24,734 | def load_asdf ( asdf_obj , data_key = 'sci' , wcs_key = 'wcs' , header_key = 'meta' ) : asdf_keys = asdf_obj . keys ( ) if wcs_key in asdf_keys : wcs = asdf_obj [ wcs_key ] else : wcs = None if header_key in asdf_keys : ahdr = asdf_obj [ header_key ] else : ahdr = { } if data_key in asdf_keys : data = np . asarray ( asdf_obj [ data_key ] ) else : data = None return data , wcs , ahdr | Load from an ASDF object . |
24,735 | def _match_cmap ( self , fitsimage , colorbar ) : rgbmap = fitsimage . get_rgbmap ( ) loval , hival = fitsimage . get_cut_levels ( ) colorbar . set_range ( loval , hival ) colorbar . set_rgbmap ( rgbmap ) | Help method to change the ColorBar to match the cut levels or colormap used in a ginga ImageView . |
24,736 | def rgbmap_cb ( self , rgbmap , channel ) : if not self . gui_up : return fitsimage = channel . fitsimage if fitsimage != self . fv . getfocus_fitsimage ( ) : return False self . change_cbar ( self . fv , channel ) | This method is called when the RGBMap is changed . We update the ColorBar to match . |
24,737 | def show_mode_indicator ( viewer , tf , corner = 'ur' ) : tag = '_$mode_indicator' canvas = viewer . get_private_canvas ( ) try : indic = canvas . get_object_by_tag ( tag ) if not tf : canvas . delete_object_by_tag ( tag ) else : indic . corner = corner except KeyError : if tf : bm = viewer . get_bindmap ( ) bm . add_callback ( 'mode-set' , lambda * args : viewer . redraw ( whence = 3 ) ) Indicator = canvas . get_draw_class ( 'modeindicator' ) canvas . add ( Indicator ( corner = corner ) , tag = tag , redraw = False ) canvas . update_canvas ( whence = 3 ) | Show a keyboard mode indicator in one of the corners . |
24,738 | def show_color_bar ( viewer , tf , side = 'bottom' ) : tag = '_$color_bar' canvas = viewer . get_private_canvas ( ) try : cbar = canvas . get_object_by_tag ( tag ) if not tf : canvas . delete_object_by_tag ( tag ) else : cbar . side = side except KeyError : if tf : Cbar = canvas . get_draw_class ( 'colorbar' ) canvas . add ( Cbar ( side = side ) , tag = tag , redraw = False ) canvas . update_canvas ( whence = 3 ) | Show a color bar in the window . |
24,739 | def show_focus_indicator ( viewer , tf , color = 'white' ) : tag = '_$focus_indicator' canvas = viewer . get_private_canvas ( ) try : fcsi = canvas . get_object_by_tag ( tag ) if not tf : canvas . delete_object_by_tag ( tag ) else : fcsi . color = color except KeyError : if tf : Fcsi = canvas . get_draw_class ( 'focusindicator' ) fcsi = Fcsi ( color = color ) canvas . add ( fcsi , tag = tag , redraw = False ) viewer . add_callback ( 'focus' , fcsi . focus_cb ) canvas . update_canvas ( whence = 3 ) | Show a focus indicator in the window . |
24,740 | def add_zoom_buttons ( viewer , canvas = None , color = 'black' ) : def zoom ( box , canvas , event , pt , viewer , n ) : zl = viewer . get_zoom ( ) zl += n if zl == 0.0 : zl += n viewer . zoom_to ( zl + n ) def add_buttons ( viewer , canvas , tag ) : objs = [ ] wd , ht = viewer . get_window_size ( ) SquareBox = canvas . get_draw_class ( 'squarebox' ) Text = canvas . get_draw_class ( 'text' ) Compound = canvas . get_draw_class ( 'compoundobject' ) x1 , y1 = wd - 20 , ht // 2 + 20 zoomin = SquareBox ( x1 , y1 , 15 , color = 'yellow' , fill = True , fillcolor = 'gray' , fillalpha = 0.5 , coord = 'window' ) zoomin . editable = False zoomin . pickable = True zoomin . add_callback ( 'pick-down' , zoom , viewer , 1 ) objs . append ( zoomin ) x2 , y2 = wd - 20 , ht // 2 - 20 zoomout = SquareBox ( x2 , y2 , 15 , color = 'yellow' , fill = True , fillcolor = 'gray' , fillalpha = 0.5 , coord = 'window' ) zoomout . editable = False zoomout . pickable = True zoomout . add_callback ( 'pick-down' , zoom , viewer , - 1 ) objs . append ( zoomout ) objs . append ( Text ( x1 - 4 , y1 + 6 , text = '+' , fontsize = 18 , color = color , coord = 'window' ) ) objs . append ( Text ( x2 - 4 , y2 + 6 , text = '--' , fontsize = 18 , color = color , coord = 'window' ) ) obj = Compound ( * objs ) obj . opaque = False canvas . add ( obj , tag = tag ) def zoom_resize ( viewer , width , height , canvas , tag ) : try : canvas . get_object_by_tag ( tag ) except KeyError : return False canvas . delete_object_by_tag ( tag ) add_buttons ( viewer , canvas , tag ) tag = '_$zoom_buttons' if canvas is None : canvas = viewer . get_private_canvas ( ) canvas . ui_set_active ( True ) canvas . register_for_cursor_drawing ( viewer ) canvas . set_draw_mode ( 'pick' ) viewer . add_callback ( 'configure' , zoom_resize , canvas , tag ) add_buttons ( viewer , canvas , tag ) | Add zoom buttons to a canvas . |
24,741 | def expose_event ( self , widget , event ) : x , y , width , height = event . area self . logger . debug ( "surface is %s" % self . surface ) if self . surface is not None : win = widget . get_window ( ) cr = win . cairo_create ( ) cr . rectangle ( x , y , width , height ) cr . clip ( ) cr . set_source_surface ( self . surface , 0 , 0 ) cr . set_operator ( cairo . OPERATOR_SOURCE ) cr . paint ( ) return False | When an area of the window is exposed we just copy out of the server - side off - screen surface to that area . |
24,742 | def size_request ( self , widget , requisition ) : requisition . width , requisition . height = self . get_desired_size ( ) return True | Callback function to request our desired size . |
24,743 | def get_plugin_spec ( self , name ) : l_name = name . lower ( ) for spec in self . plugins : name = spec . get ( 'name' , spec . get ( 'klass' , spec . module ) ) if name . lower ( ) == l_name : return spec raise KeyError ( name ) | Get the specification attributes for plugin with name name . |
24,744 | def help_text ( self , name , text , text_kind = 'plain' , trim_pfx = 0 ) : if trim_pfx > 0 : text = toolbox . trim_prefix ( text , trim_pfx ) if text_kind == 'rst' : try : overrides = { 'input_encoding' : 'ascii' , 'output_encoding' : 'utf-8' } text_html = publish_string ( text , writer_name = 'html' , settings_overrides = overrides ) text = text_html . decode ( 'utf-8' ) text_kind = 'html' except Exception as e : self . logger . error ( "Error converting help text to HTML: %s" % ( str ( e ) ) ) else : raise ValueError ( "I don't know how to display text of kind '%s'" % ( text_kind ) ) if text_kind == 'html' : self . help ( text = text , text_kind = 'html' ) else : self . show_help_text ( name , text ) | Provide help text for the user . |
24,745 | def load_file ( self , filepath , chname = None , wait = True , create_channel = True , display_image = True , image_loader = None ) : if not chname : channel = self . get_current_channel ( ) else : if not self . has_channel ( chname ) and create_channel : self . gui_call ( self . add_channel , chname ) channel = self . get_channel ( chname ) chname = channel . name if image_loader is None : image_loader = self . load_image cache_dir = self . settings . get ( 'download_folder' , self . tmpdir ) info = iohelper . get_fileinfo ( filepath , cache_dir = cache_dir ) if not info . ondisk : errmsg = "File must be locally loadable: %s" % ( filepath ) self . gui_do ( self . show_error , errmsg ) return filepath = info . filepath kwargs = { } idx = None if info . numhdu is not None : kwargs [ 'idx' ] = info . numhdu try : image = image_loader ( filepath , ** kwargs ) except Exception as e : errmsg = "Failed to load '%s': %s" % ( filepath , str ( e ) ) self . gui_do ( self . show_error , errmsg ) return future = Future . Future ( ) future . freeze ( image_loader , filepath , ** kwargs ) image . set ( loader = image_loader , image_future = future ) if image . get ( 'path' , None ) is None : image . set ( path = filepath ) name = image . get ( 'name' , None ) if name is None : name = iohelper . name_image_from_path ( filepath , idx = idx ) image . set ( name = name ) if display_image : if wait : self . gui_call ( self . add_image , name , image , chname = chname ) else : self . gui_do ( self . add_image , name , image , chname = chname ) else : self . gui_do ( self . bulk_add_image , name , image , chname ) return image | Load a file and display it . |
24,746 | def add_download ( self , info , future ) : if self . gpmon . has_plugin ( 'Downloads' ) : obj = self . gpmon . get_plugin ( 'Downloads' ) self . gui_do ( obj . add_download , info , future ) else : self . show_error ( "Please activate the 'Downloads' plugin to" " enable download functionality" ) | Hand off a download to the Downloads plugin if it is present . |
24,747 | def open_file_cont ( self , pathspec , loader_cont_fn ) : info = iohelper . get_fileinfo ( pathspec ) filepath = info . filepath if not os . path . exists ( filepath ) : errmsg = "File does not appear to exist: '%s'" % ( filepath ) self . gui_do ( self . show_error , errmsg ) return try : typ , subtyp = iohelper . guess_filetype ( filepath ) except Exception as e : self . logger . warning ( "error determining file type: %s; " "assuming 'image/fits'" % ( str ( e ) ) ) typ , subtyp = 'image' , 'fits' mimetype = "%s/%s" % ( typ , subtyp ) try : opener_class = loader . get_opener ( mimetype ) except KeyError : errmsg = "No registered opener for: '%s'" % ( mimetype ) self . gui_do ( self . show_error , errmsg ) return kwargs = dict ( ) inherit_prihdr = self . settings . get ( 'inherit_primary_header' , False ) kwargs [ 'inherit_primary_header' ] = inherit_prihdr opener = opener_class ( self . logger ) try : with opener . open_file ( filepath ) as io_f : io_f . load_idx_cont ( info . idx , loader_cont_fn , ** kwargs ) except Exception as e : errmsg = "Error opening '%s': %s" % ( filepath , str ( e ) ) try : ( type , value , tb ) = sys . exc_info ( ) tb_str = "\n" . join ( traceback . format_tb ( tb ) ) except Exception as e : tb_str = "Traceback information unavailable." self . gui_do ( self . show_error , errmsg + '\n' + tb_str ) | Open a file and do some action on it . |
24,748 | def open_uris ( self , uris , chname = None , bulk_add = False ) : if len ( uris ) == 0 : return if chname is None : channel = self . get_channel_info ( ) if channel is None : return chname = channel . name channel = self . get_channel_on_demand ( chname ) def show_dataobj_bulk ( data_obj ) : self . gui_do ( channel . add_image , data_obj , bulk_add = True ) def load_file_bulk ( filepath ) : self . nongui_do ( self . open_file_cont , filepath , show_dataobj_bulk ) def show_dataobj ( data_obj ) : self . gui_do ( channel . add_image , data_obj , bulk_add = False ) def load_file ( filepath ) : self . nongui_do ( self . open_file_cont , filepath , show_dataobj ) if bulk_add : self . open_uri_cont ( uris [ 0 ] , load_file_bulk ) else : self . open_uri_cont ( uris [ 0 ] , load_file ) self . update_pending ( ) for uri in uris [ 1 : ] : self . open_uri_cont ( uri , load_file_bulk ) self . update_pending ( ) | Open a set of URIs . |
24,749 | def zoom_in ( self ) : viewer = self . getfocus_viewer ( ) if hasattr ( viewer , 'zoom_in' ) : viewer . zoom_in ( ) return True | Zoom the view in one zoom step . |
24,750 | def zoom_out ( self ) : viewer = self . getfocus_viewer ( ) if hasattr ( viewer , 'zoom_out' ) : viewer . zoom_out ( ) return True | Zoom the view out one zoom step . |
24,751 | def zoom_fit ( self ) : viewer = self . getfocus_viewer ( ) if hasattr ( viewer , 'zoom_fit' ) : viewer . zoom_fit ( ) return True | Zoom the view to fit the image entirely in the window . |
24,752 | def prev_img_ws ( self , ws , loop = True ) : channel = self . get_active_channel_ws ( ws ) if channel is None : return channel . prev_image ( ) return True | Go to the previous image in the focused channel in the workspace . |
24,753 | def next_img_ws ( self , ws , loop = True ) : channel = self . get_active_channel_ws ( ws ) if channel is None : return channel . next_image ( ) return True | Go to the next image in the focused channel in the workspace . |
24,754 | def prev_img ( self , loop = True ) : channel = self . get_current_channel ( ) if channel is None : self . show_error ( "Please create a channel." , raisetab = True ) return channel . prev_image ( ) return True | Go to the previous image in the channel . |
24,755 | def next_img ( self , loop = True ) : channel = self . get_current_channel ( ) if channel is None : self . show_error ( "Please create a channel." , raisetab = True ) return channel . next_image ( ) return True | Go to the next image in the channel . |
24,756 | def close_plugins ( self , channel ) : opmon = channel . opmon for key in opmon . get_active ( ) : obj = opmon . get_plugin ( key ) try : self . gui_call ( obj . close ) except Exception as e : self . logger . error ( "Failed to continue operation: %s" % ( str ( e ) ) ) | Close all plugins associated with the channel . |
24,757 | def add_channel ( self , chname , workspace = None , num_images = None , settings = None , settings_template = None , settings_share = None , share_keylist = None ) : with self . lock : if self . has_channel ( chname ) : return self . get_channel ( chname ) if chname in self . ds . get_tabnames ( None ) : raise ValueError ( "Tab name already in use: '%s'" % ( chname ) ) name = chname if settings is None : settings = self . prefs . create_category ( 'channel_' + name ) try : settings . load ( onError = 'raise' ) except Exception as e : self . logger . warning ( "no saved preferences found for channel " "'%s': %s" % ( name , str ( e ) ) ) if settings_template is not None : osettings = settings_template osettings . copy_settings ( settings ) else : try : osettings = self . prefs . get_settings ( 'channel_Image' ) self . logger . debug ( "Copying settings from 'Image' to " "'%s'" % ( name ) ) osettings . copy_settings ( settings ) except KeyError : pass if ( share_keylist is not None ) and ( settings_share is not None ) : settings_share . share_settings ( settings , keylist = share_keylist ) if num_images is None : num_images = settings . get ( 'numImages' , self . settings . get ( 'numImages' , 1 ) ) settings . set_defaults ( switchnew = True , numImages = num_images , raisenew = True , genthumb = True , focus_indicator = False , preload_images = False , sort_order = 'loadtime' ) self . logger . debug ( "Adding channel '%s'" % ( chname ) ) channel = Channel ( chname , self , datasrc = None , settings = settings ) bnch = self . add_viewer ( chname , settings , workspace = workspace ) bnch . image_viewer . set_name ( 'channel:%s' % ( chname ) ) opmon = self . get_plugin_manager ( self . logger , self , self . ds , self . mm ) channel . widget = bnch . widget channel . container = bnch . container channel . workspace = bnch . workspace channel . connect_viewer ( bnch . image_viewer ) channel . viewer = bnch . image_viewer channel . fitsimage = bnch . image_viewer channel . opmon = opmon name = chname . lower ( ) self . channel [ name ] = channel self . channel_names . append ( chname ) self . channel_names . sort ( ) if len ( self . channel_names ) == 1 : self . cur_channel = channel for spec in self . get_plugins ( ) : opname = spec . get ( 'klass' , spec . get ( 'module' ) ) if spec . get ( 'ptype' , 'global' ) == 'local' : opmon . load_plugin ( opname , spec , chinfo = channel ) self . make_gui_callback ( 'add-channel' , channel ) return channel | Create a new Ginga channel . |
24,758 | def delete_channel ( self , chname ) : name = chname . lower ( ) if len ( self . channel_names ) < 1 : self . logger . error ( 'Delete channel={0} failed. ' 'No channels left.' . format ( chname ) ) return with self . lock : channel = self . channel [ name ] self . close_plugins ( channel ) try : idx = self . channel_names . index ( chname ) except ValueError : idx = 0 self . channel_names . remove ( channel . name ) self . channel_names . sort ( ) self . ds . remove_tab ( chname ) del self . channel [ name ] self . prefs . remove_settings ( 'channel_' + chname ) num_channels = len ( self . channel_names ) if num_channels > 0 : if idx >= num_channels : idx = num_channels - 1 self . change_channel ( self . channel_names [ idx ] ) else : self . cur_channel = None self . make_gui_callback ( 'delete-channel' , channel ) | Delete a given channel from viewer . |
24,759 | def add_menu ( self , name ) : if self . menubar is None : raise ValueError ( "No menu bar configured" ) return self . menubar . add_name ( name ) | Add a menu with name name to the global menu bar . Returns a menu widget . |
24,760 | def get_menu ( self , name ) : if self . menubar is None : raise ValueError ( "No menu bar configured" ) return self . menubar . get_menu ( name ) | Get the menu with name name from the global menu bar . Returns a menu widget . |
24,761 | def register_viewer ( self , vclass ) : self . viewer_db [ vclass . vname ] = Bunch . Bunch ( vname = vclass . vname , vclass = vclass , vtypes = vclass . vtypes ) | Register a channel viewer with the reference viewer . vclass is the class of the viewer . |
24,762 | def get_viewer_names ( self , dataobj ) : res = [ ] for bnch in self . viewer_db . values ( ) : for vtype in bnch . vtypes : if isinstance ( dataobj , vtype ) : res . append ( bnch . vname ) return res | Returns a list of viewer names that are registered that can view dataobj . |
24,763 | def make_viewer ( self , vname , channel ) : if vname not in self . viewer_db : raise ValueError ( "I don't know how to build a '%s' viewer" % ( vname ) ) stk_w = channel . widget bnch = self . viewer_db [ vname ] viewer = bnch . vclass ( logger = self . logger , settings = channel . settings ) stk_w . add_widget ( viewer . get_widget ( ) , title = vname ) self . update_pending ( ) channel . connect_viewer ( viewer ) viewer . initialize_channel ( self , channel ) | Make a viewer whose type name is vname and add it to channel . |
24,764 | def collapse_pane ( self , side ) : hsplit = self . w [ 'hpnl' ] sizes = hsplit . get_sizes ( ) lsize , msize , rsize = sizes if self . _lsize is None : self . _lsize , self . _rsize = lsize , rsize self . logger . debug ( "left=%d mid=%d right=%d" % ( lsize , msize , rsize ) ) if side == 'right' : if rsize < 10 : rsize = self . _rsize msize -= rsize else : self . _rsize = rsize msize += rsize rsize = 0 elif side == 'left' : if lsize < 10 : lsize = self . _lsize msize -= lsize else : self . _lsize = lsize msize += lsize lsize = 0 hsplit . set_sizes ( [ lsize , msize , rsize ] ) | Toggle collapsing the left or right panes . |
24,765 | def quit ( self , * args ) : self . logger . info ( "Attempting to shut down the application..." ) if self . layout_file is not None : self . error_wrap ( self . ds . write_layout_conf , self . layout_file ) self . stop ( ) self . w . root = None while len ( self . ds . toplevels ) > 0 : w = self . ds . toplevels . pop ( ) w . delete ( ) | Quit the application . |
24,766 | def showxy ( self , viewer , data_x , data_y ) : cur_time = time . time ( ) elapsed = cur_time - self . _cursor_last_update if elapsed > self . cursor_interval : self . _cursor_task . clear ( ) self . gui_do_oneshot ( 'field-info' , self . _showxy , viewer , data_x , data_y ) else : self . _cursor_task . data . setvals ( viewer = viewer , data_x = data_x , data_y = data_y ) period = self . cursor_interval - elapsed self . _cursor_task . cond_set ( period ) return True | Called by the mouse - tracking callback to handle reporting of cursor position to various plugins that subscribe to the field - info callback . |
24,767 | def _cursor_timer_cb ( self , timer ) : data = timer . data self . gui_do_oneshot ( 'field-info' , self . _showxy , data . viewer , data . data_x , data . data_y ) | Callback when the cursor timer expires . |
24,768 | def _showxy ( self , viewer , data_x , data_y ) : self . _cursor_last_update = time . time ( ) try : image = viewer . get_image ( ) if ( image is None ) or not isinstance ( image , BaseImage . BaseImage ) : return settings = viewer . get_settings ( ) info = image . info_xy ( data_x , data_y , settings ) off = self . settings . get ( 'pixel_coords_offset' , 0.0 ) info . x += off info . y += off except Exception as e : self . logger . warning ( "Can't get info under the cursor: %s" % ( str ( e ) ) ) return chname = self . get_channel_name ( viewer ) channel = self . get_channel ( chname ) self . make_callback ( 'field-info' , channel , info ) self . update_pending ( ) return True | Update the info from the last position recorded under the cursor . |
24,769 | def motion_cb ( self , viewer , button , data_x , data_y ) : self . showxy ( viewer , data_x , data_y ) return True | Motion event in the channel viewer window . Show the pointing information under the cursor . |
24,770 | def keypress ( self , viewer , event , data_x , data_y ) : keyname = event . key chname = self . get_channel_name ( viewer ) self . logger . debug ( "key press (%s) in channel %s" % ( keyname , chname ) ) if keyname == 'Z' : self . ds . raise_tab ( 'Zoom' ) elif keyname == 'I' : self . ds . raise_tab ( 'Info' ) elif keyname == 'H' : self . ds . raise_tab ( 'Header' ) elif keyname == 'C' : self . ds . raise_tab ( 'Contents' ) elif keyname == 'D' : self . ds . raise_tab ( 'Dialogs' ) elif keyname == 'F' : self . build_fullscreen ( ) elif keyname == 'f' : self . toggle_fullscreen ( ) elif keyname == 'm' : self . maximize ( ) elif keyname == '<' : self . collapse_pane ( 'left' ) elif keyname == '>' : self . collapse_pane ( 'right' ) elif keyname == 'n' : self . next_channel ( ) elif keyname == 'J' : self . cycle_workspace_type ( ) elif keyname == 'k' : self . add_channel_auto ( ) elif keyname == 'K' : self . remove_channel_auto ( ) elif keyname == 'f1' : self . show_channel_names ( ) elif keyname in ( 'up' , ) : self . prev_img ( ) elif keyname in ( 'down' , ) : self . next_img ( ) elif keyname in ( 'left' , ) : self . prev_channel ( ) elif keyname in ( 'right' , ) : self . next_channel ( ) return True | Key press event in a channel window . |
24,771 | def show_channel_names ( self ) : for name in self . get_channel_names ( ) : channel = self . get_channel ( name ) channel . fitsimage . onscreen_message ( name , delay = 2.5 ) | Show each channel s name in its image viewer . Useful in grid or stack workspace type to identify which window is which . |
24,772 | def _short_color_list ( self ) : return [ c for c in colors . get_colors ( ) if not re . search ( r'\d' , c ) ] | Color list is too long . Discard variations with numbers . |
24,773 | def _get_markobj ( self , x , y , marktype , marksize , markcolor , markwidth ) : if marktype == 'circle' : obj = self . dc . Circle ( x = x , y = y , radius = marksize , color = markcolor , linewidth = markwidth ) elif marktype in ( 'cross' , 'plus' ) : obj = self . dc . Point ( x = x , y = y , radius = marksize , color = markcolor , linewidth = markwidth , style = marktype ) elif marktype == 'box' : obj = self . dc . Box ( x = x , y = y , xradius = marksize , yradius = marksize , color = markcolor , linewidth = markwidth ) else : obj = self . dc . Box ( x = x , y = y , xradius = 1 , yradius = 1 , color = markcolor , linewidth = markwidth , fill = True , fillcolor = markcolor ) return obj | Generate canvas object for given mark parameters . |
24,774 | def clear_marking ( self ) : if self . marktag : try : self . canvas . delete_object_by_tag ( self . marktag , redraw = False ) except Exception : pass if self . markhltag : try : self . canvas . delete_object_by_tag ( self . markhltag , redraw = False ) except Exception : pass self . treeview . clear ( ) self . w . nshown . set_text ( '0' ) self . fitsimage . redraw ( ) | Clear marking from image . This does not clear loaded coordinates from memory . |
24,775 | def load_file ( self , filename ) : if not os . path . isfile ( filename ) : return self . logger . info ( 'Loading coordinates from {0}' . format ( filename ) ) if filename . endswith ( '.fits' ) : fmt = 'fits' else : fmt = 'ascii' try : tab = Table . read ( filename , format = fmt ) except Exception as e : self . logger . error ( '{0}: {1}' . format ( e . __class__ . __name__ , str ( e ) ) ) return if self . use_radec : colname0 = self . settings . get ( 'ra_colname' , 'ra' ) colname1 = self . settings . get ( 'dec_colname' , 'dec' ) else : colname0 = self . settings . get ( 'x_colname' , 'x' ) colname1 = self . settings . get ( 'y_colname' , 'y' ) try : col_0 = tab [ colname0 ] col_1 = tab [ colname1 ] except Exception as e : self . logger . error ( '{0}: {1}' . format ( e . __class__ . __name__ , str ( e ) ) ) return nrows = len ( col_0 ) dummy_col = [ None ] * nrows try : oldrows = int ( self . w . ntotal . get_text ( ) ) except ValueError : oldrows = 0 self . w . ntotal . set_text ( str ( oldrows + nrows ) ) if self . use_radec : ra = self . _convert_radec ( col_0 ) dec = self . _convert_radec ( col_1 ) x = y = dummy_col else : ra = dec = dummy_col x = col_0 . data - self . pixelstart y = col_1 . data - self . pixelstart args = [ ra , dec , x , y ] for colname in self . extra_columns : try : col = tab [ colname ] . data except Exception as e : self . logger . error ( '{0}: {1}' . format ( e . __class__ . __name__ , str ( e ) ) ) col = dummy_col args . append ( col ) key = ( self . marktype , self . marksize , self . markcolor ) self . coords_dict [ key ] += list ( zip ( * args ) ) self . redo ( ) | Load coordinates file . |
24,776 | def _convert_radec ( self , val ) : try : ans = val . to ( 'deg' ) except Exception as e : self . logger . error ( 'Cannot convert, assume already in degrees' ) ans = val . data else : ans = ans . value return ans | Convert RA or DEC table column to degrees and extract data . Assume already in degrees if cannot convert . |
24,777 | def hl_table2canvas ( self , w , res_dict ) : objlist = [ ] width = self . markwidth + self . _dwidth if self . markhltag : try : self . canvas . delete_object_by_tag ( self . markhltag , redraw = False ) except Exception : pass self . treeviewsel . set_tree ( res_dict ) for kstr , sub_dict in res_dict . items ( ) : s = kstr . split ( ',' ) marktype = s [ 0 ] marksize = float ( s [ 1 ] ) markcolor = s [ 2 ] for bnch in sub_dict . values ( ) : obj = self . _get_markobj ( bnch . X - self . pixelstart , bnch . Y - self . pixelstart , marktype , marksize , markcolor , width ) objlist . append ( obj ) nsel = len ( objlist ) self . w . nselected . set_text ( str ( nsel ) ) if nsel > 0 : self . markhltag = self . canvas . add ( self . dc . CompoundObject ( * objlist ) ) self . fitsimage . redraw ( ) | Highlight marking on canvas when user click on table . |
24,778 | def hl_canvas2table_box ( self , canvas , tag ) : self . treeview . clear_selection ( ) cobj = canvas . get_object_by_tag ( tag ) if cobj . kind != 'rectangle' : return canvas . delete_object_by_tag ( tag , redraw = False ) if self . markhltag : try : canvas . delete_object_by_tag ( self . markhltag , redraw = True ) except Exception : pass try : obj = canvas . get_object_by_tag ( self . marktag ) except Exception : return if obj . kind != 'compound' : return if ( len ( self . _xarr ) == 0 or len ( self . _yarr ) == 0 or len ( self . _treepaths ) == 0 ) : return mask = cobj . contains_arr ( self . _xarr , self . _yarr ) for hlpath in self . _treepaths [ mask ] : self . _highlight_path ( hlpath ) | Highlight all markings inside user drawn box on table . |
24,779 | def hl_canvas2table ( self , canvas , button , data_x , data_y ) : self . treeview . clear_selection ( ) if self . markhltag : try : canvas . delete_object_by_tag ( self . markhltag , redraw = True ) except Exception : pass try : obj = canvas . get_object_by_tag ( self . marktag ) except Exception : return if obj . kind != 'compound' : return if ( len ( self . _xarr ) == 0 or len ( self . _yarr ) == 0 or len ( self . _treepaths ) == 0 ) : return sr = 10 dx = data_x - self . _xarr dy = data_y - self . _yarr dr = np . sqrt ( dx * dx + dy * dy ) mask = dr <= sr for hlpath in self . _treepaths [ mask ] : self . _highlight_path ( hlpath ) | Highlight marking on table when user click on canvas . |
24,780 | def _highlight_path ( self , hlpath ) : self . logger . debug ( 'Highlighting {0}' . format ( hlpath ) ) self . treeview . select_path ( hlpath ) self . treeview . scroll_to_path ( hlpath ) | Highlight an entry in the table and associated marking . |
24,781 | def set_marktype_cb ( self , w , index ) : self . marktype = self . _mark_options [ index ] if self . marktype != 'point' : self . w . mark_size . set_enabled ( True ) else : self . w . mark_size . set_enabled ( False ) | Set type of marking . |
24,782 | def set_markwidth ( self ) : try : sz = int ( self . w . mark_width . get_text ( ) ) except ValueError : self . logger . error ( 'Cannot set mark width' ) self . w . mark_width . set_text ( str ( self . markwidth ) ) else : self . markwidth = sz | Set width of marking . |
24,783 | def redo ( self , channel , image ) : self . _image = None info = channel . extdata . _header_info self . set_header ( info , image ) | This is called when image changes . |
24,784 | def blank ( self , channel ) : self . _image = None info = channel . extdata . _header_info info . table . clear ( ) | This is called when image is cleared . |
24,785 | def clock_resized_cb ( self , viewer , width , height ) : self . logger . info ( "resized canvas to %dx%d" % ( width , height ) ) self . canvas . delete_all_objects ( ) Text = self . canvas . get_draw_class ( 'text' ) x , y = 20 , int ( height * 0.55 ) self . time_txt = Text ( x , y , text = '' , color = self . color , font = self . font , fontsize = self . largesize , coord = 'window' ) self . canvas . add ( self . time_txt , tag = '_time' , redraw = False ) self . suppl_txt = Text ( x , height - 10 , text = '' , color = self . color , font = self . font , fontsize = self . smallsize , coord = 'window' ) self . canvas . add ( self . suppl_txt , tag = '_suppl' , redraw = False ) self . canvas . update_canvas ( whence = 3 ) | This method is called when an individual clock is resized . It deletes and reconstructs the placement of the text objects in the canvas . |
24,786 | def update_clock ( self , dt ) : dt = dt . astimezone ( self . tzinfo ) fmt = "%H:%M" if self . show_seconds : fmt = "%H:%M:%S" self . time_txt . text = dt . strftime ( fmt ) suppl_text = "{0} {1}" . format ( dt . strftime ( "%Y-%m-%d" ) , self . timezone ) self . suppl_txt . text = suppl_text self . viewer . redraw ( whence = 3 ) | This method is called by the ClockApp whenever the timer fires to update the clock . dt is a timezone - aware datetime object . |
24,787 | def add_clock ( self , timezone , color = 'lightgreen' , show_seconds = None ) : if show_seconds is None : show_seconds = self . options . show_seconds clock = Clock ( self . app , self . logger , timezone , color = color , font = self . options . font , show_seconds = show_seconds ) clock . widget . cfg_expand ( 0x7 , 0x7 ) num_clocks = len ( self . clocks ) cols = self . settings . get ( 'columns' ) row = num_clocks // cols col = num_clocks % cols self . clocks [ timezone ] = clock self . grid . add_widget ( clock . widget , row , col , stretch = 1 ) | Add a clock to the grid . timezone is a string representing a valid timezone . |
24,788 | def timer_cb ( self , timer ) : dt_now = datetime . utcnow ( ) . replace ( tzinfo = pytz . utc ) self . logger . debug ( "timer fired. utc time is '%s'" % ( str ( dt_now ) ) ) for clock in self . clocks . values ( ) : clock . update_clock ( dt_now ) timer . start ( 1.0 ) | Timer callback . Update all our clocks . |
24,789 | def set_table_cb ( self , viewer , table ) : self . clear ( ) tree_dict = OrderedDict ( ) a_tab = table . get_data ( ) try : a_tab = a_tab . filled ( ) except Exception : pass i_fmt = '{{0:0{0}d}}' . format ( len ( str ( len ( a_tab ) ) ) ) columns = [ ( 'Row' , '_DISPLAY_ROW' ) ] for c in a_tab . columns . values ( ) : col_str = '{0:^s}\n{1:^s}' . format ( c . name , str ( c . unit ) ) columns . append ( ( col_str , c . name ) ) self . widget . setup_table ( columns , 1 , '_DISPLAY_ROW' ) for i , row in enumerate ( a_tab , 1 ) : bnch = Bunch . Bunch ( zip ( row . colnames , row . as_void ( ) ) ) i_str = i_fmt . format ( i ) bnch [ '_DISPLAY_ROW' ] = i_str tree_dict [ i_str ] = bnch self . widget . set_tree ( tree_dict ) n_rows = len ( tree_dict ) if n_rows < self . settings . get ( 'max_rows_for_col_resize' , 5000 ) : self . widget . set_optimal_column_widths ( ) self . logger . debug ( 'Resized columns for {0} row(s)' . format ( n_rows ) ) tablename = table . get ( 'name' , 'NoName' ) self . logger . debug ( 'Displayed {0}' . format ( tablename ) ) | Display the given table object . |
24,790 | def build_gui ( self , container ) : vbox , sw , self . orientation = Widgets . get_oriented_box ( container ) vbox . set_border_width ( 4 ) vbox . set_spacing ( 2 ) always_expand = self . settings . get ( 'always_expand' , True ) color_alternate = self . settings . get ( 'color_alternate_rows' , True ) treeview = Widgets . TreeView ( auto_expand = always_expand , sortable = True , use_alt_row_color = color_alternate ) self . treeview = treeview treeview . setup_table ( self . columns , 3 , 'MODIFIED' ) treeview . set_column_width ( 0 , self . settings . get ( 'ts_colwidth' , 250 ) ) treeview . add_callback ( 'selected' , self . show_more ) vbox . add_widget ( treeview , stretch = 1 ) fr = Widgets . Frame ( 'Selected History' ) captions = ( ( 'Channel:' , 'label' , 'chname' , 'llabel' ) , ( 'Image:' , 'label' , 'imname' , 'llabel' ) , ( 'Timestamp:' , 'label' , 'modified' , 'llabel' ) ) w , b = Widgets . build_info ( captions ) self . w . update ( b ) b . chname . set_text ( '' ) b . chname . set_tooltip ( 'Channel name' ) b . imname . set_text ( '' ) b . imname . set_tooltip ( 'Image name' ) b . modified . set_text ( '' ) b . modified . set_tooltip ( 'Timestamp (UTC)' ) captions = ( ( 'Description:-' , 'llabel' ) , ( 'descrip' , 'textarea' ) ) w2 , b = Widgets . build_info ( captions ) self . w . update ( b ) b . descrip . set_editable ( False ) b . descrip . set_wrap ( True ) b . descrip . set_text ( '' ) b . descrip . set_tooltip ( 'Displays selected history entry' ) vbox2 = Widgets . VBox ( ) vbox2 . set_border_width ( 4 ) vbox2 . add_widget ( w ) vbox2 . add_widget ( w2 ) fr . set_widget ( vbox2 , stretch = 0 ) vbox . add_widget ( fr , stretch = 0 ) container . add_widget ( vbox , stretch = 1 ) btns = Widgets . HBox ( ) btns . set_spacing ( 3 ) btn = Widgets . Button ( 'Close' ) btn . add_callback ( 'activated' , lambda w : self . close ( ) ) btns . add_widget ( btn , stretch = 0 ) btn = Widgets . Button ( "Help" ) btn . add_callback ( 'activated' , lambda w : self . help ( ) ) btns . add_widget ( btn , stretch = 0 ) btns . add_widget ( Widgets . Label ( '' ) , stretch = 1 ) container . add_widget ( btns , stretch = 0 ) self . gui_up = True | This method is called when the plugin is invoked . It builds the GUI used by the plugin into the widget layout passed as container . |
24,791 | def redo ( self , channel , image ) : chname = channel . name if image is None : return imname = image . get ( 'name' , 'none' ) iminfo = channel . get_image_info ( imname ) timestamp = iminfo . time_modified if timestamp is None : reason = iminfo . get ( 'reason_modified' , None ) if reason is not None : self . fv . show_error ( "{0} invoked 'modified' callback to ChangeHistory with a " "reason but without a timestamp. The plugin invoking the " "callback is no longer be compatible with Ginga. " "Please contact plugin developer to update the plugin " "to use self.fv.update_image_info() like Mosaic " "plugin." . format ( imname ) ) self . remove_image_info_cb ( self . fv , channel , iminfo ) return self . add_entry ( chname , iminfo ) | Add an entry with image modification info . |
24,792 | def remove_image_info_cb ( self , gshell , channel , iminfo ) : chname = channel . name if chname not in self . name_dict : return fileDict = self . name_dict [ chname ] name = iminfo . name if name not in fileDict : return del fileDict [ name ] self . logger . debug ( '{0} removed from ChangeHistory' . format ( name ) ) if not self . gui_up : return False self . clear_selected_history ( ) self . recreate_toc ( ) | Delete entries related to deleted image . |
24,793 | def add_image_info_cb ( self , gshell , channel , iminfo ) : timestamp = iminfo . time_modified if timestamp is None : return self . add_entry ( channel . name , iminfo ) | Add entries related to an added image . |
24,794 | def drag_drop_cb ( self , viewer , urls ) : channel = self . fv . get_current_channel ( ) if channel is None : return self . fv . open_uris ( urls , chname = channel . name , bulk_add = True ) return True | Punt drag - drops to the ginga shell . |
24,795 | def update_highlights ( self , old_highlight_set , new_highlight_set ) : with self . thmblock : un_hilite_set = old_highlight_set - new_highlight_set re_hilite_set = new_highlight_set - old_highlight_set bg = self . settings . get ( 'label_bg_color' , 'lightgreen' ) fg = self . settings . get ( 'label_font_color' , 'black' ) for thumbkey in un_hilite_set : if thumbkey in self . thumb_dict : namelbl = self . thumb_dict [ thumbkey ] . get ( 'namelbl' ) namelbl . color = fg for thumbkey in re_hilite_set : if thumbkey in self . thumb_dict : namelbl = self . thumb_dict [ thumbkey ] . get ( 'namelbl' ) namelbl . color = bg if self . gui_up : self . c_view . redraw ( whence = 3 ) | Unhighlight the thumbnails represented by old_highlight_set and highlight the ones represented by new_highlight_set . |
24,796 | def have_thumbnail ( self , fitsimage , image ) : chname = self . fv . get_channel_name ( fitsimage ) idx = image . get ( 'idx' , None ) path = image . get ( 'path' , None ) if path is not None : path = os . path . abspath ( path ) name = iohelper . name_image_from_path ( path , idx = idx ) else : name = 'NoName' name = image . get ( 'name' , name ) thumbkey = self . get_thumb_key ( chname , name , path ) with self . thmblock : return thumbkey in self . thumb_dict | Returns True if we already have a thumbnail version of this image cached False otherwise . |
24,797 | def auto_scroll ( self , thumbkey ) : if not self . gui_up : return scrollp = self . w . auto_scroll . get_state ( ) if not scrollp : return bnch = self . thumb_dict [ thumbkey ] pan_x , pan_y = self . c_view . get_pan ( ) self . c_view . panset_xy ( pan_x , bnch . image . y ) | Scroll the window to the thumb . |
24,798 | def clear_widget ( self ) : if not self . gui_up : return canvas = self . c_view . get_canvas ( ) canvas . delete_all_objects ( ) self . c_view . redraw ( whence = 0 ) | Clears the thumbnail display widget of all thumbnails but does not remove them from the thumb_dict or thumb_list . |
24,799 | def load_nddata ( self , ndd , naxispath = None ) : self . clear_metadata ( ) ahdr = self . get_header ( ) ahdr . update ( ndd . meta ) self . setup_data ( ndd . data , naxispath = naxispath ) if ndd . wcs is None : self . wcs = wcsmod . WCS ( logger = self . logger ) self . wcs . load_header ( ahdr ) else : wcsinfo = wcsmod . get_wcs_class ( 'astropy' ) self . wcs = wcsinfo . wrapper_class ( logger = self . logger ) self . wcs . load_nddata ( ndd ) | Load from an astropy . nddata . NDData object . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.