idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
25,000
def build_gui ( self , container ) : top = Widgets . VBox ( ) top . set_border_width ( 4 ) vbox , sw , orientation = Widgets . get_oriented_box ( container ) vbox . set_border_width ( 4 ) vbox . set_spacing ( 2 ) self . msg_font = self . fv . get_font ( "sans" , 12 ) tw = Widgets . TextArea ( wrap = True , editable = F...
This method is called when the plugin is invoked . It builds the GUI used by the plugin into the widget layout passed as container . This method could be called several times if the plugin is opened and closed . The method may be omitted if there is no GUI for the plugin .
25,001
def focus_cb ( self , viewer , channel ) : chname = channel . name if self . active != chname : self . active = chname self . set_info ( "Focus is now in channel '%s'" % ( self . active ) ) return True
Callback from the reference viewer shell when the focus changes between channels .
25,002
def redo ( self , channel , image ) : chname = channel . name if self . active == chname : imname = image . get ( 'name' , 'NONAME' ) self . set_info ( "A new image '%s' has been added to channel %s" % ( imname , chname ) ) return True
Called from the reference viewer shell when a new image has been added to a channel .
25,003
def _main ( ) : usage = "usage: %prog [options] cmd [arg] ..." optprs = OptionParser ( usage = usage , version = version ) optprs . add_option ( "--debug" , dest = "debug" , default = False , action = "store_true" , help = "Enter the pdb debugger on main()" ) optprs . add_option ( "--host" , dest = "host" , metavar = "...
Run from command line .
25,004
def _imload ( self , filepath , kwds ) : start_time = time . time ( ) typ , enc = mimetypes . guess_type ( filepath ) if not typ : typ = 'image/jpeg' typ , subtyp = typ . split ( '/' ) self . logger . debug ( "MIME type is %s/%s" % ( typ , subtyp ) ) data_loaded = False if have_opencv and subtyp not in [ 'gif' ] : mean...
Load an image file guessing the format and return a numpy array containing an RGB image . If EXIF keywords can be read they are returned in the dict _kwds_ .
25,005
def imresize ( self , data , new_wd , new_ht , method = 'bilinear' ) : old_ht , old_wd = data . shape [ : 2 ] start_time = time . time ( ) if have_pilutil : means = 'PIL' zoom_x = float ( new_wd ) / float ( old_wd ) zoom_y = float ( new_ht ) / float ( old_ht ) if ( old_wd >= new_wd ) or ( old_ht >= new_ht ) : zoom = ma...
Scale an image in numpy array _data_ to the specified width and height . A smooth scaling is preferred .
25,006
def get_array ( self , order , dtype = None ) : if dtype is None : dtype = self . rgbarr . dtype order = order . upper ( ) if order == self . order : return self . rgbarr . astype ( dtype , copy = False ) res = trcalc . reorder_image ( order , self . rgbarr , self . order ) res = res . astype ( dtype , copy = False , c...
Get Numpy array that represents the RGB layers .
25,007
def set_cmap ( self , cmap , callback = True ) : self . cmap = cmap with self . suppress_changed : self . calc_cmap ( ) self . t_ . set ( color_map = cmap . name , callback = False )
Set the color map used by this RGBMapper .
25,008
def set_imap ( self , imap , callback = True ) : self . imap = imap self . calc_imap ( ) with self . suppress_changed : self . recalc ( ) self . t_ . set ( intensity_map = imap . name , callback = False )
Set the intensity map used by this RGBMapper .
25,009
def stretch ( self , scale_factor , callback = True ) : self . scale_pct *= scale_factor self . scale_and_shift ( self . scale_pct , 0.0 , callback = callback )
Stretch the color map via altering the shift map .
25,010
def _set_reference_channel_cb ( self , w , idx ) : chname = self . chnames [ idx ] self . _set_reference_channel ( chname )
This is the GUI callback for the control that sets the reference channel .
25,011
def set_reference_channel ( self , chname ) : idx = self . chnames . index ( str ( chname ) ) self . w . ref_channel . set_index ( idx ) return self . _set_reference_channel ( chname )
This is the API call to set the reference channel .
25,012
def zoomset_cb ( self , setting , value , chviewer , info ) : return self . zoomset ( chviewer , info . chinfo )
This callback is called when a channel window is zoomed .
25,013
def rotset_cb ( self , setting , value , chviewer , info ) : return self . rotset ( chviewer , info . chinfo )
This callback is called when a channel window is rotated .
25,014
def panset_cb ( self , setting , value , chviewer , info ) : return self . panset ( chviewer , info . chinfo )
This callback is called when a channel window is panned .
25,015
def timer_tick ( self ) : self . process_timers ( ) delta = datetime . timedelta ( milliseconds = self . base_interval_msec ) self . _timeout = IOLoop . current ( ) . add_timeout ( delta , self . timer_tick )
Callback executed every self . base_interval_msec to check timer expirations .
25,016
def select_cb ( self , viewer , event , data_x , data_y ) : if not ( self . _cmxoff <= data_x < self . _cmwd ) : return i = int ( data_y / ( self . _cmht + self . _cmsep ) ) if 0 <= i < len ( self . cm_names ) : name = self . cm_names [ i ] msg = "cmap => '%s'" % ( name ) self . logger . info ( msg ) channel = self . f...
Called when the user clicks on the color bar viewer . Calculate the index of the color bar they clicked on and set that color map in the current channel viewer .
25,017
def scroll_cb ( self , viewer , direction , amt , data_x , data_y ) : bd = viewer . get_bindings ( ) direction = bd . get_direction ( direction ) pan_x , pan_y = viewer . get_pan ( ) [ : 2 ] qty = self . _cmsep * amt * self . settings . get ( 'cbar_pan_accel' , 1.0 ) if direction == 'up' : pan_y -= qty else : pan_y += ...
Called when the user scrolls in the color bar viewer . Pan up or down to show additional bars .
25,018
def rebuild_cmaps ( self ) : self . logger . info ( "building color maps image" ) ht , wd , sep = self . _cmht , self . _cmwd , self . _cmsep viewer = self . p_view canvas = viewer . get_canvas ( ) canvas . delete_all_objects ( ) cm_names = self . cm_names num_cmaps = len ( cm_names ) viewer . configure_surface ( 500 ,...
Builds a color RGB image containing color bars of all the possible color maps and their labels .
25,019
def record_sizes ( self ) : for rec in self . node . values ( ) : w = rec . widget wd , ht = w . get_size ( ) rec . params . update ( dict ( name = rec . name , width = wd , height = ht ) ) if rec . kind in ( 'hpanel' , 'vpanel' ) : sizes = w . get_sizes ( ) rec . params . update ( dict ( sizes = sizes ) ) if rec . kin...
Record sizes of all container widgets in the layout . The sizes are recorded in the params mappings in the layout .
25,020
def help ( self , * args ) : if len ( args ) == 0 : return help_msg which = args [ 0 ] . lower ( ) if which == 'ginga' : method = args [ 1 ] _method = getattr ( self . fv , method ) return _method . __doc__ elif which == 'channel' : chname = args [ 1 ] method = args [ 2 ] chinfo = self . fv . get_channel ( chname ) _me...
Get help for a remote interface method .
25,021
def load_buffer ( self , imname , chname , img_buf , dims , dtype , header , metadata , compressed ) : self . logger . info ( "received image data len=%d" % ( len ( img_buf ) ) ) try : decompress = metadata . get ( 'decompress' , None ) if compressed or ( decompress == 'bz2' ) : img_buf = bz2 . decompress ( img_buf ) i...
Display a FITS image buffer .
25,022
def use ( name ) : global toolkit , family name = name . lower ( ) if name . startswith ( 'choose' ) : pass elif name . startswith ( 'qt' ) or name . startswith ( 'pyside' ) : family = 'qt' if name == 'qt' : name = 'qt4' assert name in ( 'qt4' , 'pyside' , 'qt5' ) , ToolKitError ( "ToolKit '%s' not supported!" % ( name...
Set the name of the GUI toolkit we should use .
25,023
def share_settings ( self , other , keylist = None , include_callbacks = True , callback = True ) : if keylist is None : keylist = self . group . keys ( ) if include_callbacks : for key in keylist : oset , mset = other . group [ key ] , self . group [ key ] other . group [ key ] = mset oset . merge_callbacks_to ( mset ...
Sharing settings with other
25,024
def use ( wcspkg , raise_err = True ) : global coord_types , wcs_configured , WCS if wcspkg not in common . custom_wcs : modname = 'wcs_%s' % ( wcspkg ) path = os . path . join ( wcs_home , '%s.py' % ( modname ) ) try : my_import ( modname , path ) except ImportError : return False if wcspkg in common . custom_wcs : bn...
Choose WCS package .
25,025
def _set_combobox ( self , attrname , vals , default = 0 ) : combobox = getattr ( self . w , attrname ) for val in vals : combobox . append_text ( val ) if default > len ( vals ) : default = 0 val = vals [ default ] combobox . show_text ( val ) return val
Populate combobox with given list .
25,026
def clear_data ( self ) : self . tab = None self . cols = [ ] self . _idx = [ ] self . x_col = '' self . y_col = '' self . w . xcombo . clear ( ) self . w . ycombo . clear ( ) self . w . x_lo . set_text ( '' ) self . w . x_hi . set_text ( '' ) self . w . y_lo . set_text ( '' ) self . w . y_hi . set_text ( '' )
Clear comboboxes and columns .
25,027
def clear_plot ( self ) : self . tab_plot . clear ( ) self . tab_plot . draw ( ) self . save_plot . set_enabled ( False )
Clear plot display .
25,028
def plot_two_columns ( self , reset_xlimits = False , reset_ylimits = False ) : self . clear_plot ( ) if self . tab is None : return plt_kw = { 'lw' : self . settings . get ( 'linewidth' , 1 ) , 'ls' : self . settings . get ( 'linestyle' , '-' ) , 'color' : self . settings . get ( 'linecolor' , 'blue' ) , 'ms' : self ....
Simple line plot for two selected columns .
25,029
def _get_plot_data ( self ) : _marker_type = self . settings . get ( 'markerstyle' , 'o' ) if self . x_col == self . _idxname : x_data = self . _idx else : x_data = self . tab [ self . x_col ] . data if self . y_col == self . _idxname : y_data = self . _idx else : y_data = self . tab [ self . y_col ] . data if self . t...
Extract only good data point for plotting .
25,030
def _get_label ( self , axis ) : if axis == 'x' : colname = self . x_col else : colname = self . y_col if colname == self . _idxname : label = 'Index' else : col = self . tab [ colname ] if col . unit : label = '{0} ({1})' . format ( col . name , col . unit ) else : label = col . name return label
Return plot label for column for the given axis .
25,031
def x_select_cb ( self , w , index ) : try : self . x_col = self . cols [ index ] except IndexError as e : self . logger . error ( str ( e ) ) else : self . plot_two_columns ( reset_xlimits = True )
Callback to set X - axis column .
25,032
def y_select_cb ( self , w , index ) : try : self . y_col = self . cols [ index ] except IndexError as e : self . logger . error ( str ( e ) ) else : self . plot_two_columns ( reset_ylimits = True )
Callback to set Y - axis column .
25,033
def save_cb ( self ) : w = Widgets . SaveDialog ( title = 'Save plot' ) target = w . get_path ( ) if target is None : return plot_ext = self . settings . get ( 'file_suffix' , '.png' ) if not target . endswith ( plot_ext ) : target += plot_ext fig_dpi = 100 try : fig = self . tab_plot . get_figure ( ) fig . savefig ( t...
Save plot to file .
25,034
def convert ( filepath , outfilepath ) : logger = logging . getLogger ( "example1" ) logger . setLevel ( logging . INFO ) fmt = logging . Formatter ( STD_FORMAT ) stderrHdlr = logging . StreamHandler ( ) stderrHdlr . setFormatter ( fmt ) logger . addHandler ( stderrHdlr ) fi = ImageViewCairo ( logger ) fi . configure (...
Convert FITS image to PDF .
25,035
def redo ( self ) : if not self . gui_up : return self . clear_mask ( ) image = self . fitsimage . get_image ( ) if image is None : return n_obj = len ( self . _maskobjs ) self . logger . debug ( 'Displaying {0} masks' . format ( n_obj ) ) if n_obj == 0 : return self . recreate_toc ( ) self . masktag = self . canvas . ...
Image or masks have changed . Clear and redraw .
25,036
def clear_mask ( self ) : if self . masktag : try : self . canvas . delete_object_by_tag ( self . masktag , redraw = False ) except Exception : pass if self . maskhltag : try : self . canvas . delete_object_by_tag ( self . maskhltag , redraw = False ) except Exception : pass self . treeview . clear ( ) self . fitsimage...
Clear mask from image . This does not clear loaded masks from memory .
25,037
def load_file ( self , filename ) : if not os . path . isfile ( filename ) : return self . logger . info ( 'Loading mask image from {0}' . format ( filename ) ) try : dat = fits . getdata ( filename ) . astype ( np . bool ) except Exception as e : self . logger . error ( '{0}: {1}' . format ( e . __class__ . __name__ ,...
Load mask image .
25,038
def _rgbtomask ( self , obj ) : dat = obj . get_image ( ) . get_data ( ) return dat . sum ( axis = 2 ) . astype ( np . bool )
Convert RGB arrays from mask canvas object back to boolean mask .
25,039
def hl_table2canvas ( self , w , res_dict ) : objlist = [ ] if self . maskhltag : try : self . canvas . delete_object_by_tag ( self . maskhltag , redraw = False ) except Exception : pass for sub_dict in res_dict . values ( ) : for seqno in sub_dict : mobj = self . _maskobjs [ int ( seqno ) - 1 ] dat = self . _rgbtomask...
Highlight mask on canvas when user click on table .
25,040
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 . maskhltag : try : canvas . delete_object_by_tag ( self . maskhltag , redraw = True ) e...
Highlight all masks inside user drawn box on table .
25,041
def hl_canvas2table ( self , canvas , button , data_x , data_y ) : self . treeview . clear_selection ( ) if self . maskhltag : try : canvas . delete_object_by_tag ( self . maskhltag , redraw = True ) except Exception : pass try : obj = canvas . get_object_by_tag ( self . masktag ) except Exception : return if obj . kin...
Highlight mask on table when user click on canvas .
25,042
def contains_pt ( self , pt ) : obj1 , obj2 = self . objects return obj2 . contains_pt ( pt ) and np . logical_not ( obj1 . contains_pt ( pt ) )
Containment test .
25,043
def contains_pts ( self , pts ) : obj1 , obj2 = self . objects arg1 = obj2 . contains_pts ( pts ) arg2 = np . logical_not ( obj1 . contains_pts ( pts ) ) return np . logical_and ( arg1 , arg2 )
Containment test on arrays .
25,044
def register_wcs ( name , wrapper_class , coord_types ) : global custom_wcs custom_wcs [ name ] = Bunch . Bunch ( name = name , wrapper_class = wrapper_class , coord_types = coord_types )
Register a custom WCS wrapper .
25,045
def choose_coord_units ( header ) : cunit = header [ 'CUNIT1' ] match = re . match ( r'^deg\s*$' , cunit ) if match : return 'degree' return 'degree'
Return the appropriate key code for the units value for the axes by examining the FITS header .
25,046
def get_coord_system_name ( header ) : try : ctype = header [ 'CTYPE1' ] . strip ( ) . upper ( ) except KeyError : try : ra = header [ 'RA' ] try : equinox = float ( header [ 'EQUINOX' ] ) if equinox < 1984.0 : radecsys = 'FK4' else : radecsys = 'FK5' except KeyError : radecsys = 'ICRS' return radecsys . lower ( ) exce...
Return an appropriate key code for the axes coordinate system by examining the FITS header .
25,047
def datapt_to_wcspt ( self , datapt , coords = 'data' , naxispath = None ) : if naxispath : raise NotImplementedError return np . asarray ( [ self . pixtoradec ( ( pt [ 0 ] , pt [ 1 ] ) , coords = coords ) for pt in datapt ] )
Convert multiple data points to WCS .
25,048
def wcspt_to_datapt ( self , wcspt , coords = 'data' , naxispath = None ) : if naxispath : raise NotImplementedError return np . asarray ( [ self . radectopix ( pt [ 0 ] , pt [ 1 ] , coords = coords ) for pt in wcspt ] )
Convert multiple WCS to data points .
25,049
def fix_bad_headers ( self ) : unit = self . header . get ( 'CUNIT1' , 'deg' ) if unit . upper ( ) == 'DEGREE' : self . header [ 'CUNIT1' ] = 'deg' unit = self . header . get ( 'CUNIT2' , 'deg' ) if unit . upper ( ) == 'DEGREE' : self . header [ 'CUNIT2' ] = 'deg'
Fix up bad headers that cause problems for the wrapped WCS module .
25,050
def fov_for_height_and_distance ( height , distance ) : vfov_deg = np . degrees ( 2.0 * np . arctan ( height * 0.5 / distance ) ) return vfov_deg
Calculate the FOV needed to get a given frustum height at a given distance .
25,051
def set_gl_transform ( self ) : tangent = np . tan ( self . fov_deg / 2.0 / 180.0 * np . pi ) vport_radius = self . near_plane * tangent if self . vport_wd_px < self . vport_ht_px : vport_wd = 2.0 * vport_radius vport_ht = vport_wd * self . vport_ht_px / float ( self . vport_wd_px ) else : vport_ht = 2.0 * vport_radius...
This side effects the OpenGL context to set the view to match the camera .
25,052
def get_translation_speed ( self , distance_from_target ) : return ( distance_from_target * np . tan ( self . fov_deg / 2.0 / 180.0 * np . pi ) )
Returns the translation speed for distance_from_target in units per radius .
25,053
def orbit ( self , x1_px , y1_px , x2_px , y2_px ) : px_per_deg = self . vport_radius_px / float ( self . orbit_speed ) radians_per_px = 1.0 / px_per_deg * np . pi / 180.0 t2p = self . position - self . target M = Matrix4x4 . rotation_around_origin ( ( x1_px - x2_px ) * radians_per_px , self . ground ) t2p = M * t2p se...
Causes the camera to orbit around the target point . This is also called tumbling in some software packages .
25,054
def track ( self , delta_pixels , push_target = False , adj_fov = False ) : direction = self . target - self . position distance_from_target = direction . length ( ) direction = direction . normalized ( ) initial_ht = frustum_height_at_distance ( self . fov_deg , distance_from_target ) speed_per_radius = self . get_tra...
This causes the camera to translate forward into the scene . This is also called dollying or tracking in some software packages . Passing in a negative delta causes the opposite motion .
25,055
def get_wireframe ( viewer , x , y , z , ** kwargs ) : n , m = x . shape objs = [ ] for i in range ( n ) : pts = np . asarray ( [ ( x [ i ] [ j ] , y [ i ] [ j ] , z [ i ] [ j ] ) for j in range ( m ) ] ) objs . append ( viewer . dc . Path ( pts , ** kwargs ) ) for j in range ( m ) : pts = np . asarray ( [ ( x [ i ] [ ...
Produce a compound object of paths implementing a wireframe . x y z are expected to be 2D arrays of points making up the mesh .
25,056
def get_fileinfo ( filespec , cache_dir = None ) : if cache_dir is None : cache_dir = tempfile . gettempdir ( ) idx = None name_ext = '' match = re . match ( r'^(.+)\[(.+)\]$' , filespec ) if match : filespec = match . group ( 1 ) idx = match . group ( 2 ) if ',' in idx : hduname , extver = idx . split ( ',' ) hduname ...
Parse a file specification and return information about it .
25,057
def shorten_name ( name , char_limit , side = 'right' ) : if char_limit is not None and len ( name ) > char_limit : info = get_fileinfo ( name ) if info . numhdu is not None : i = name . rindex ( '[' ) s = ( name [ : i ] , name [ i : ] ) len_sfx = len ( s [ 1 ] ) len_pfx = char_limit - len_sfx - 4 + 1 if len_pfx > 0 : ...
Shorten name if it is longer than char_limit . If side == right then the right side of the name is shortened ; if left then the left side is shortened . In either case the suffix of the name is preserved .
25,058
def update_params ( self , param_d ) : for param in self . paramlst : if param . name in param_d : value = param_d [ param . name ] setattr ( self . obj , param . name , value )
Update the attributes in self . obj that match the keys in param_d .
25,059
def hue_sat_to_cmap ( hue , sat ) : import colorsys hue = float ( hue ) / 360.0 sat = float ( sat ) / 100.0 res = [ ] for val in range ( 256 ) : hsv_val = float ( val ) / 255.0 r , g , b = colorsys . hsv_to_rgb ( hue , sat , hsv_val ) res . append ( ( r , g , b ) ) return res
Mkae a color map from a hue and saturation value .
25,060
def setitem ( self , key , value ) : with self . lock : self . tbl [ key ] = value
Maps dictionary keys to values for assignment . Called for dictionary style access with assignment .
25,061
def get ( self , key , alt = None ) : with self . lock : if key in self : return self . getitem ( key ) else : return alt
If dictionary contains _key_ return the associated value otherwise return _alt_ .
25,062
def setdefault ( self , key , value ) : with self . lock : if key in self : return self . getitem ( key ) else : self . setitem ( key , value ) return value
Atomic store conditional . Stores _value_ into dictionary at _key_ but only if _key_ does not already exist in the dictionary . Returns the old value found or the new value .
25,063
def help ( self ) : if not self . fv . gpmon . has_plugin ( 'WBrowser' ) : self . _help_docstring ( ) return self . fv . start_global_plugin ( 'WBrowser' ) self . fv . update_pending ( ) obj = self . fv . gpmon . get_plugin ( 'WBrowser' ) obj . show_help ( plugin = self , no_url_callback = self . _help_docstring )
Display help for the plugin .
25,064
def modes_off ( self ) : bm = self . fitsimage . get_bindmap ( ) bm . reset_mode ( self . fitsimage )
Turn off any mode user may be in .
25,065
def load_np ( self , imname , data_np , imtype , header ) : load_buffer = self . _client . lookup_attr ( 'load_buffer' ) return load_buffer ( imname , self . _chname , Blob ( data_np . tobytes ( ) ) , data_np . shape , str ( data_np . dtype ) , header , { } , False )
Display a numpy image buffer in a remote Ginga reference viewer .
25,066
def load_hdu ( self , imname , hdulist , num_hdu ) : buf_io = BytesIO ( ) hdulist . writeto ( buf_io ) load_fits_buffer = self . _client . lookup_attr ( 'load_fits_buffer' ) return load_fits_buffer ( imname , self . _chname , Blob ( buf_io . getvalue ( ) ) , num_hdu , { } )
Display an astropy . io . fits HDU in a remote Ginga reference viewer .
25,067
def load_fitsbuf ( self , imname , fitsbuf , num_hdu ) : load_fits_buffer = self . _client_ . lookup_attr ( 'load_fits_buffer' ) return load_fits_buffer ( imname , self . _chname , Blob ( fitsbuf ) , num_hdu , { } )
Display a FITS file buffer in a remote Ginga reference viewer .
25,068
def set_widget ( self , canvas ) : self . tkcanvas = canvas canvas . bind ( "<Configure>" , self . _resize_cb ) width = canvas . winfo_width ( ) height = canvas . winfo_height ( ) self . _defer_task = TkHelp . Timer ( tkcanvas = canvas ) self . _defer_task . add_callback ( 'expired' , lambda timer : self . delayed_redr...
Call this method with the Tkinter canvas that will be used for the display .
25,069
def _set_lim_and_transforms ( self ) : self . transAxes = BboxTransformTo ( self . bbox ) self . transData = self . GingaTransform ( ) self . transData . viewer = self . viewer self . _xaxis_transform = self . transData self . _yaxis_transform = self . transData
This is called once when the plot is created to set up all the transforms for the data text and grids .
25,070
def start_pan ( self , x , y , button ) : bd = self . viewer . get_bindings ( ) data_x , data_y = self . viewer . get_data_xy ( x , y ) event = PointEvent ( button = button , state = 'down' , data_x = data_x , data_y = data_y , viewer = self . viewer ) if button == 1 : bd . ms_pan ( self . viewer , event , data_x , dat...
Called when a pan operation has started .
25,071
def get_surface_as_bytes ( self , order = None ) : arr8 = self . get_surface_as_array ( order = order ) return arr8 . tobytes ( order = 'C' )
Returns the surface area as a bytes encoded RGB image buffer . Subclass should override if there is a more efficient conversion than from generating a numpy array first .
25,072
def reorder ( self , dst_order , arr , src_order = None ) : if dst_order is None : dst_order = self . viewer . rgb_order if src_order is None : src_order = self . rgb_order if src_order != dst_order : arr = trcalc . reorder_image ( dst_order , arr , src_order ) return arr
Reorder the output array to match that needed by the viewer .
25,073
def add_cmap ( name , clst ) : global cmaps assert len ( clst ) == min_cmap_len , ValueError ( "color map '%s' length mismatch %d != %d (needed)" % ( name , len ( clst ) , min_cmap_len ) ) cmaps [ name ] = ColorMap ( name , clst )
Add a color map .
25,074
def get_names ( ) : res = list ( cmaps . keys ( ) ) res = sorted ( res , key = lambda s : s . lower ( ) ) return res
Get colormap names .
25,075
def matplotlib_to_ginga_cmap ( cm , name = None ) : if name is None : name = cm . name arr = cm ( np . arange ( 0 , min_cmap_len ) / np . float ( min_cmap_len - 1 ) ) clst = arr [ : , 0 : 3 ] return ColorMap ( name , clst )
Convert matplotlib colormap to Ginga s .
25,076
def ginga_to_matplotlib_cmap ( cm , name = None ) : if name is None : name = cm . name from matplotlib . colors import ListedColormap carr = np . asarray ( cm . clst ) mpl_cm = ListedColormap ( carr , name = name , N = len ( carr ) ) return mpl_cm
Convert Ginga colormap to matplotlib s .
25,077
def add_matplotlib_cmap ( cm , name = None ) : global cmaps cmap = matplotlib_to_ginga_cmap ( cm , name = name ) cmaps [ cmap . name ] = cmap
Add a matplotlib colormap .
25,078
def add_matplotlib_cmaps ( fail_on_import_error = True ) : try : from matplotlib import cm as _cm from matplotlib . cbook import mplDeprecation except ImportError : if fail_on_import_error : raise return for name in _cm . cmap_d : if not isinstance ( name , str ) : continue try : with warnings . catch_warnings ( ) : wa...
Add all matplotlib colormaps .
25,079
def add_legend ( self ) : cuts = [ tag for tag in self . tags if tag is not self . _new_cut ] self . cuts_plot . ax . legend ( cuts , loc = 'best' , shadow = True , fancybox = True , prop = { 'size' : 8 } , labelspacing = 0.2 )
Add or update Cuts plot legend .
25,080
def cut_at ( self , cuttype ) : data_x , data_y = self . fitsimage . get_last_data_xy ( ) image = self . fitsimage . get_image ( ) wd , ht = image . get_size ( ) coords = [ ] if cuttype == 'horizontal' : coords . append ( ( 0 , data_y , wd , data_y ) ) elif cuttype == 'vertical' : coords . append ( ( data_x , 0 , data_...
Perform a cut at the last mouse position in the image . cuttype determines the type of cut made .
25,081
def width_radius_changed_cb ( self , widget , val ) : self . width_radius = val self . redraw_cuts ( ) self . replot_all ( ) return True
Callback executed when the Width radius is changed .
25,082
def save_cb ( self , mode ) : w = Widgets . SaveDialog ( title = 'Save {0} data' . format ( mode ) ) filename = w . get_path ( ) if filename is None : return fig_dpi = 100 if mode == 'cuts' : fig , xarr , yarr = self . cuts_plot . get_data ( ) elif mode == 'slit' : fig , xarr , yarr = self . slit_plot . get_data ( ) fi...
Save image figure and plot data arrays .
25,083
def zoom_cb ( self , fitsimage , event ) : chviewer = self . fv . getfocus_viewer ( ) bd = chviewer . get_bindings ( ) if hasattr ( bd , 'sc_zoom' ) : return bd . sc_zoom ( chviewer , event ) return False
Zoom event in the pan window . Just zoom the channel viewer .
25,084
def zoom_pinch_cb ( self , fitsimage , event ) : chviewer = self . fv . getfocus_viewer ( ) bd = chviewer . get_bindings ( ) if hasattr ( bd , 'pi_zoom' ) : return bd . pi_zoom ( chviewer , event ) return False
Pinch event in the pan window . Just zoom the channel viewer .
25,085
def pan_pan_cb ( self , fitsimage , event ) : chviewer = self . fv . getfocus_viewer ( ) bd = chviewer . get_bindings ( ) if hasattr ( bd , 'pa_pan' ) : return bd . pa_pan ( chviewer , event ) return False
Pan event in the pan window . Just pan the channel viewer .
25,086
def set_widget ( self , canvas_w ) : self . logger . debug ( "set widget canvas_w=%s" % canvas_w ) self . pgcanvas = canvas_w
Call this method with the widget that will be used for the display .
25,087
def run ( self ) : os . system ( "cp python-bugzilla.spec /tmp" ) try : os . system ( "rm -rf python-bugzilla-%s" % get_version ( ) ) self . run_command ( 'sdist' ) os . system ( 'rpmbuild -ta --clean dist/python-bugzilla-%s.tar.gz' % get_version ( ) ) finally : os . system ( "mv /tmp/python-bugzilla.spec ." )
Run sdist then rpmbuild the tar . gz
25,088
def parse_response ( self , response ) : parser , unmarshaller = self . getparser ( ) parser . feed ( response . text . encode ( 'utf-8' ) ) parser . close ( ) return unmarshaller . close ( )
Parse XMLRPC response
25,089
def _request_helper ( self , url , request_body ) : response = None try : response = self . session . post ( url , data = request_body , ** self . request_defaults ) response . encoding = 'UTF-8' if self . _cookiejar is not None : for cookie in response . cookies : self . _cookiejar . set_cookie ( cookie ) if self . _c...
A helper method to assist in making a request and provide a parsed response .
25,090
def open_without_clobber ( name , * args ) : fd = None count = 1 orig_name = name while fd is None : try : fd = os . open ( name , os . O_CREAT | os . O_EXCL , 0o666 ) except OSError as err : if err . errno == errno . EEXIST : name = "%s.%i" % ( orig_name , count ) count += 1 else : raise IOError ( err . errno , err . ...
Try to open the given file with the given mode ; if that filename exists try name . 1 name . 2 etc . until we find an unused filename .
25,091
def _do_info ( bz , opt ) : def _filter_components ( compdetails ) : ret = { } for k , v in compdetails . items ( ) : if v . get ( "is_active" , True ) : ret [ k ] = v return ret productname = ( opt . components or opt . component_owners or opt . versions ) include_fields = [ "name" , "id" ] fastcomponents = ( opt . co...
Handle the info subcommand
25,092
def _make_bz_instance ( opt ) : if opt . bztype != 'auto' : log . info ( "Explicit --bztype is no longer supported, ignoring" ) cookiefile = None tokenfile = None use_creds = False if opt . cache_credentials : cookiefile = opt . cookiefile or - 1 tokenfile = opt . tokenfile or - 1 use_creds = True bz = bugzilla . Bugzi...
Build the Bugzilla instance we will use
25,093
def _handle_login ( opt , action , bz ) : is_login_command = ( action == 'login' ) do_interactive_login = ( is_login_command or opt . login or opt . username or opt . password ) username = getattr ( opt , "pos_username" , None ) or opt . username password = getattr ( opt , "pos_password" , None ) or opt . password try ...
Handle all login related bits
25,094
def fix_url ( url ) : if '://' not in url : log . debug ( 'No scheme given for url, assuming https' ) url = 'https://' + url if url . count ( '/' ) < 3 : log . debug ( 'No path given for url, assuming /xmlrpc.cgi' ) url = url + '/xmlrpc.cgi' return url
Turn passed url into a bugzilla XMLRPC web url
25,095
def _init_class_from_url ( self ) : from bugzilla import RHBugzilla if isinstance ( self , RHBugzilla ) : return c = None if "bugzilla.redhat.com" in self . url : log . info ( "Using RHBugzilla for URL containing bugzilla.redhat.com" ) c = RHBugzilla else : try : extensions = self . _proxy . Bugzilla . extensions ( ) i...
Detect if we should use RHBugzilla class and if so set it
25,096
def _login ( self , user , password , restrict_login = None ) : payload = { 'login' : user , 'password' : password } if restrict_login : payload [ 'restrict_login' ] = True return self . _proxy . User . login ( payload )
Backend login method for Bugzilla3
25,097
def login ( self , user = None , password = None , restrict_login = None ) : if self . api_key : raise ValueError ( "cannot login when using an API key" ) if user : self . user = user if password : self . password = password if not self . user : raise ValueError ( "missing username" ) if not self . password : raise Val...
Attempt to log in using the given username and password . Subsequent method calls will use this username and password . Returns False if login fails otherwise returns some kind of login info - typically either a numeric userid or a dict of user info .
25,098
def interactive_login ( self , user = None , password = None , force = False , restrict_login = None ) : ignore = force log . debug ( 'Calling interactive_login' ) if not user : sys . stdout . write ( 'Bugzilla Username: ' ) sys . stdout . flush ( ) user = sys . stdin . readline ( ) . strip ( ) if not password : passwo...
Helper method to handle login for this bugzilla instance .
25,099
def logout ( self ) : self . _logout ( ) self . disconnect ( ) self . user = '' self . password = ''
Log out of bugzilla . Drops server connection and user info and destroys authentication cookies .