idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
41,800 | def get_svnpath ( ) : svnpathtmp = __file__ splitsvnpath = svnpathtmp . split ( '/' ) if len ( splitsvnpath ) == 1 : svnpath = os . path . abspath ( '.' ) + '/../../' else : svnpath = '' for i in range ( len ( splitsvnpath ) - 3 ) : svnpath += splitsvnpath [ i ] + '/' return svnpath | This subroutine gives back the path of the whole svn tree installation which is necessary for the script to run . |
41,801 | def reset_filter ( self ) : self . header_desc = self . _header_desc self . header_data = self . _header_data self . header_style = self . _header_style self . desc = self . _desc self . data = self . _data self . style = self . _style self . descdict = self . _descdict self . datadict = self . _datadict self . styledict = self . _styledict | Resets the filter and goes back to initialized value . This routine also resets the style if you have changed it . |
41,802 | def info ( self , graintype = True , group = True , reference = False , phase = True ) : gtype_info = [ ] group_info = [ ] ref_info = [ ] phase_info = [ ] print ( 'There are ' + str ( len ( self . data ) ) + ' grains in your database.\n' ) if graintype : for i in range ( len ( self . desc ) ) : gtype_tmp = self . desc [ i ] [ self . descdict [ 'Type' ] ] wrtchk = True for j in range ( len ( gtype_info ) ) : if gtype_info [ j ] == gtype_tmp : wrtchk = False break if wrtchk : gtype_info . append ( gtype_tmp ) print ( 'Available graintypes are:' ) print ( '-------------------------' ) print ( gtype_info ) if group : for i in range ( len ( self . desc ) ) : group_tmp = self . desc [ i ] [ self . descdict [ 'Group' ] ] wrtchk = True for j in range ( len ( group_info ) ) : if group_info [ j ] == group_tmp : wrtchk = False break if wrtchk : group_info . append ( group_tmp ) print ( '\nAvailable groups of grains (for silicates and oxides) are:' ) print ( '----------------------------------------------------------' ) print ( group_info ) if phase : for i in range ( len ( self . desc ) ) : phase_tmp = self . desc [ i ] [ self . descdict [ 'Phase' ] ] wrtchk = True for j in range ( len ( phase_info ) ) : if phase_info [ j ] == phase_tmp : wrtchk = False break if wrtchk : phase_info . append ( phase_tmp ) print ( '\nAvailable Phases of grains are:' ) print ( '----------------------------------------------------------' ) print ( phase_info ) if reference : for i in range ( len ( self . desc ) ) : ref_tmp = self . desc [ i ] [ self . descdict [ 'Reference' ] ] wrtchk = True for j in range ( len ( ref_info ) ) : if ref_info [ j ] == ref_tmp : wrtchk = False break if wrtchk : ref_info . append ( ref_tmp ) print ( '\nReferences for grains:' ) print ( '----------------------' ) print ( ref_info ) | This routine gives you informations what kind of grains are currently available in your filtered version . It gives you the type of grains available . More to be implemented upon need . |
41,803 | def _filter_desc ( self , indexing ) : if len ( indexing ) > 0 : desc_tmp = np . zeros ( ( len ( indexing ) , len ( self . header_desc ) ) , dtype = '|S1024' ) data_tmp = np . zeros ( ( len ( indexing ) , len ( self . header_data ) ) ) style_tmp = np . zeros ( ( len ( indexing ) , len ( self . header_style ) ) , dtype = '|S1024' ) for i in range ( len ( indexing ) ) : for j in range ( len ( self . header_desc ) ) : desc_tmp [ i ] [ j ] = self . desc [ indexing [ i ] ] [ j ] for k in range ( len ( self . header_data ) ) : data_tmp [ i ] [ k ] = self . data [ indexing [ i ] ] [ k ] for l in range ( len ( self . header_style ) ) : style_tmp [ i ] [ l ] = self . style [ indexing [ i ] ] [ l ] self . desc = desc_tmp self . data = data_tmp self . style = style_tmp else : print ( 'No filter selected or no data found!' ) | Private function to filter data goes with filter_desc |
41,804 | def filter_data ( self , isos , limit , delta = True ) : dat_index , delta_b , ratio_b = self . check_availability ( isos ) if dat_index == - 1 : print ( 'Isotopes selected are not available. Check i.datadict (where i is your instance) for availability of isotopes.' ) return None if limit [ 0 : 1 ] == '>' : comperator = 'gt' elif limit [ 0 : 1 ] == '<' : comperator = 'st' else : print ( 'Comperator not specified. Limit must be given as \'>5.\' for example.' ) return None try : limit = float ( limit [ 1 : len ( limit ) ] ) except ValueError : print ( 'Limit must be given as \'>5.\' for example.' ) return None if delta == delta_b : if ratio_b : if delta : tmp = self . delta_to_ratio ( isos , limit , oneover = True ) comp_lim = self . ratio_to_delta ( isos , tmp ) else : comp_lim = old_div ( 1. , limit ) else : comp_lim = limit else : if ratio_b : if delta : comp_lim = self . delta_to_ratio ( isos , limit , oneover = True ) else : comp_lim = self . ratio_to_delta ( isos , limit , oneover = True ) else : if delta : comp_lim = self . delta_to_ratio ( isos , limit ) else : comp_lim = self . ratio_to_delta ( isos , limit ) indexing = [ ] for i in range ( len ( self . data ) ) : dat_val = self . data [ i ] [ dat_index ] if comperator == 'st' : if dat_val < comp_lim : indexing . append ( i ) else : if dat_val > comp_lim : indexing . append ( i ) if len ( indexing ) > 0 : desc_tmp = np . zeros ( ( len ( indexing ) , len ( self . header_desc ) ) , dtype = '|S1024' ) data_tmp = np . zeros ( ( len ( indexing ) , len ( self . header_data ) ) ) for i in range ( len ( indexing ) ) : for j in range ( len ( self . header_desc ) ) : desc_tmp [ i ] [ j ] = self . desc [ indexing [ i ] ] [ j ] for k in range ( len ( self . header_data ) ) : data_tmp [ i ] [ k ] = self . data [ indexing [ i ] ] [ k ] self . desc = desc_tmp self . data = data_tmp else : print ( 'No filter selected!' ) | This subroutine filters isotopic values according to the limit you give . You can filter in ratio or in delta space . |
41,805 | def check_availability ( self , isos ) : iso1name = iso_name_converter ( isos [ 0 ] ) iso2name = iso_name_converter ( isos [ 1 ] ) ratio = iso1name + '/' + iso2name ratio_inv = iso2name + '/' + iso1name delta = 'd(' + iso1name + '/' + iso2name + ')' delta_inv = 'd(' + iso2name + '/' + iso1name + ')' index = - 1 try : index = self . datadict [ ratio ] delta_b = False ratio_b = False except KeyError : try : index = self . datadict [ ratio_inv ] delta_b = False ratio_b = True except KeyError : try : index = self . datadict [ delta ] delta_b = True ratio_b = False except KeyError : try : index = self . datadict [ delta_inv ] delta_b = True ratio_b = True except KeyError : index = - 1 delta_b = None ratio_b = None return index , delta_b , ratio_b | This routine checks if the requested set of isotopes is available in the dataset . |
41,806 | def ratio_to_delta ( self , isos_ss , ratio , oneover = False ) : if type ( isos_ss ) == float : ss_ratio = isos_ss elif type ( isos_ss ) == list : ss_ratio = self . inut . isoratio_init ( isos_ss ) else : print ( 'Check input of isos_ss into ratio_to_delta routine' ) return None if oneover : ratio = old_div ( 1 , ratio ) delta = ( old_div ( ratio , ss_ratio ) - 1. ) * 1000. return delta | Transforms an isotope ratio into a delta value |
41,807 | def with_filter ( self , filter ) : res = copy . deepcopy ( self ) old_filter = self . _filter def new_filter ( request ) : return filter ( request , old_filter ) res . _filter = new_filter return res | Returns a new service which will process requests with the specified filter . Filtering operations can include logging automatic retrying etc ... The filter is a lambda which receives the HTTPRequest and another lambda . The filter can perform any pre - processing on the request pass it off to the next lambda and then perform any post - processing on the response . |
41,808 | def _validate_snmp ( self ) : cred = self . snmp_credentials if cred is not None : if cred . get ( 'snmp_inspection' ) is True : if not all ( [ cred . get ( 'auth_user' ) , cred . get ( 'auth_prot_pp' ) , cred . get ( 'auth_priv_pp' ) ] ) : msg = self . _ ( 'Either few or all mandatory ' 'SNMP credentials ' 'are missing.' ) LOG . error ( msg ) raise exception . IloInvalidInputError ( msg ) try : auth_protocol = cred [ 'auth_protocol' ] if auth_protocol not in [ "SHA" , "MD5" ] : msg = self . _ ( 'Invalid SNMP auth protocol ' 'provided. ' 'Valid values are SHA or MD5' ) LOG . error ( msg ) raise exception . IloInvalidInputError ( msg ) except KeyError : msg = self . _ ( 'Auth protocol not provided by user. ' 'The default value of MD5 will ' 'be considered.' ) LOG . debug ( msg ) pass try : priv_protocol = cred [ 'priv_protocol' ] if priv_protocol not in [ "AES" , "DES" ] : msg = self . _ ( 'Invalid SNMP privacy protocol ' 'provided. ' 'Valid values are AES or DES' ) LOG . error ( msg ) raise exception . IloInvalidInputError ( msg ) except KeyError : msg = self . _ ( 'Privacy protocol not provided ' 'by user. ' 'The default value of DES will ' 'be considered.' ) LOG . debug ( msg ) pass else : LOG . debug ( self . _ ( 'snmp_inspection set to False. SNMP' 'inspection will not be performed.' ) ) else : LOG . debug ( self . _ ( 'SNMP credentials not provided. SNMP ' 'inspection will not be performed.' ) ) | Validates SNMP credentials . |
41,809 | def _call_method ( self , method_name , * args , ** kwargs ) : if self . use_redfish_only : if method_name in SUPPORTED_REDFISH_METHODS : the_operation_object = self . redfish else : raise NotImplementedError ( ) else : the_operation_object = self . ribcl if 'Gen10' in self . model : if method_name in SUPPORTED_REDFISH_METHODS : the_operation_object = self . redfish else : if ( self . is_ribcl_enabled is not None and not self . is_ribcl_enabled ) : raise NotImplementedError ( ) elif ( 'Gen9' in self . model ) and ( method_name in SUPPORTED_RIS_METHODS ) : the_operation_object = self . ris method = getattr ( the_operation_object , method_name ) LOG . debug ( self . _ ( "Using %(class)s for method %(method)s." ) , { 'class' : type ( the_operation_object ) . __name__ , 'method' : method_name } ) return method ( * args , ** kwargs ) | Call the corresponding method using RIBCL RIS or REDFISH |
41,810 | def set_vm_status ( self , device = 'FLOPPY' , boot_option = 'BOOT_ONCE' , write_protect = 'YES' ) : return self . _call_method ( 'set_vm_status' , device , boot_option , write_protect ) | Sets the Virtual Media drive status and allows the |
41,811 | def get_essential_properties ( self ) : data = self . _call_method ( 'get_essential_properties' ) if ( data [ 'properties' ] [ 'local_gb' ] == 0 ) : cred = self . snmp_credentials if cred and cred . get ( 'snmp_inspection' ) : disksize = snmp . get_local_gb ( self . host , cred ) if disksize : data [ 'properties' ] [ 'local_gb' ] = disksize else : msg = self . _ ( 'SNMP inspection failed to ' 'get the disk size. Returning ' 'local_gb as 0.' ) LOG . debug ( msg ) else : msg = self . _ ( "SNMP credentials were not set and " "RIBCL/Redfish failed to get the disk size. " "Returning local_gb as 0." ) LOG . debug ( msg ) return data | Get the essential scheduling properties |
41,812 | def get_server_capabilities ( self ) : capabilities = self . _call_method ( 'get_server_capabilities' ) if ( 'Gen10' not in self . model ) : major_minor = ( self . _call_method ( 'get_ilo_firmware_version_as_major_minor' ) ) nic_capacity = ipmi . get_nic_capacity ( self . ipmi_host_info , major_minor ) if nic_capacity : capabilities . update ( { 'nic_capacity' : nic_capacity } ) if capabilities : return capabilities | Get hardware properties which can be used for scheduling |
41,813 | def _read_mesafile ( filename , data_rows = 0 , only = 'all' ) : f = open ( filename , 'r' ) vv = [ ] v = [ ] lines = [ ] line = '' for i in range ( 0 , 6 ) : line = f . readline ( ) lines . extend ( [ line ] ) hval = lines [ 2 ] . split ( ) hlist = lines [ 1 ] . split ( ) header_attr = { } for a , b in zip ( hlist , hval ) : header_attr [ a ] = float ( b ) if only is 'header_attr' : return header_attr cols = { } colnum = lines [ 4 ] . split ( ) colname = lines [ 5 ] . split ( ) for a , b in zip ( colname , colnum ) : cols [ a ] = int ( b ) data = [ ] old_percent = 0 for i in range ( data_rows ) : percent = int ( i * 100 / np . max ( [ 1 , data_rows - 1 ] ) ) if percent >= old_percent + 5 : sys . stdout . flush ( ) sys . stdout . write ( "\r reading " + "...%d%%" % percent ) old_percent = percent line = f . readline ( ) v = line . split ( ) try : vv = np . array ( v , dtype = 'float64' ) except ValueError : for item in v : if item . __contains__ ( '.' ) and not item . __contains__ ( 'E' ) : v [ v . index ( item ) ] = '0' data . append ( vv ) print ( ' \n' ) f . close ( ) a = np . array ( data ) data = [ ] return header_attr , cols , a | private routine that is not directly called by the user |
41,814 | def _profiles_index ( self ) : prof_ind_name = self . prof_ind_name f = open ( self . sldir + '/' + prof_ind_name , 'r' ) line = f . readline ( ) numlines = int ( line . split ( ) [ 0 ] ) print ( str ( numlines ) + ' in profiles.index file ...' ) model = [ ] log_file_num = [ ] for line in f : model . append ( int ( line . split ( ) [ 0 ] ) ) log_file_num . append ( int ( line . split ( ) [ 2 ] ) ) log_ind = { } for a , b in zip ( model , log_file_num ) : log_ind [ a ] = b self . log_ind = log_ind self . model = model | read profiles . index and make hash array |
41,815 | def _log_file_ind ( self , inum ) : self . _profiles_index ( ) if inum <= 0 : print ( "Smallest argument is 1" ) return inum_max = len ( self . log_ind ) inum -= 1 if inum > inum_max : print ( 'There are only ' + str ( inum_max ) + ' profile file available.' ) log_data_number = - 1 return log_data_number else : log_data_number = self . log_ind [ self . model [ inum ] ] print ( 'The ' + str ( inum + 1 ) + '. profile.data file is ' + str ( log_data_number ) ) return log_data_number | Information about available profile . data or log . data files . |
41,816 | def get ( self , str_name ) : column_array = self . data [ : , self . cols [ str_name ] - 1 ] . astype ( 'float' ) return column_array | return a column of data with the name str_name . |
41,817 | def write_LEAFS_model ( self , nzn = 30000000 , dr = 5.e4 , rhostrip = 5.e-4 ) : from scipy import interpolate ye = self . get ( 'ye' ) newye = [ ] rho = 10. ** self . get ( 'logRho' ) [ : : - 1 ] idx = np . abs ( rho - rhostrip ) . argmin ( ) + 1 rho = rho [ : idx ] rhoc = rho [ 0 ] rad = 10. ** self . get ( 'logR' ) * ast . rsun_cm rad = rad [ : : - 1 ] [ : idx ] ye = ye [ : : - 1 ] [ : idx ] print ( 'there will be about ' , old_div ( rad [ - 1 ] , dr ) , 'mass cells...' ) rad = np . insert ( rad , 0 , 0 ) ye = np . insert ( ye , 0 , ye [ 0 ] ) rho = np . insert ( rho , 0 , rho [ 0 ] ) print ( rad ) fye = interpolate . interp1d ( rad , ye ) frho = interpolate . interp1d ( rad , rho ) newye = [ ] newrho = [ ] newrad = [ ] Tc = 10. ** self . get ( 'logT' ) [ - 1 ] for i in range ( nzn ) : if i * dr > rad [ - 1 ] : break newye . append ( fye ( i * dr ) ) newrho . append ( frho ( i * dr ) ) newrad . append ( i * dr ) f = open ( 'M875.inimod' , 'w' ) f . write ( str ( Tc ) + ' \n' ) f . write ( str ( rhoc ) + ' \n' ) for i in range ( len ( newye ) ) : f . write ( str ( i + 1 ) + ' ' + str ( newrad [ i ] ) + ' ' + str ( newrho [ i ] ) + ' ' + str ( newye [ i ] ) + ' \n' ) f . close ( ) | write an ascii file that will be read by Sam s version of inimod . F90 in order to make an initial model for LEAFS |
41,818 | def energy_profile ( self , ixaxis ) : mass = self . get ( 'mass' ) radius = self . get ( 'radius' ) * ast . rsun_cm eps_nuc = self . get ( 'eps_nuc' ) eps_neu = self . get ( 'non_nuc_neu' ) if ixaxis == 'mass' : xaxis = mass xlab = 'Mass / M$_\odot$' else : xaxis = old_div ( radius , 1.e8 ) xlab = 'Radius (Mm)' pl . plot ( xaxis , np . log10 ( eps_nuc ) , 'k-' , label = '$\epsilon_\mathrm{nuc}>0$' ) pl . plot ( xaxis , np . log10 ( - eps_nuc ) , 'k--' , label = '$\epsilon_\mathrm{nuc}<0$' ) pl . plot ( xaxis , np . log10 ( eps_neu ) , 'r-' , label = '$\epsilon_\\nu$' ) pl . xlabel ( xlab ) pl . ylabel ( '$\log(\epsilon_\mathrm{nuc},\epsilon_\\nu)$' ) pl . legend ( loc = 'best' ) . draw_frame ( False ) | Plot radial profile of key energy generations eps_nuc eps_neu etc . |
41,819 | def _read_starlog ( self ) : sldir = self . sldir slname = self . slname slaname = slname + 'sa' if not os . path . exists ( sldir + '/' + slaname ) : print ( 'No ' + self . slname + 'sa file found, create new one from ' + self . slname ) _cleanstarlog ( sldir + '/' + slname ) else : if self . clean_starlog : print ( 'Requested new ' + self . slname + 'sa; create new from ' + self . slname ) _cleanstarlog ( sldir + '/' + slname ) else : print ( 'Using old ' + self . slname + 'sa file ...' ) cmd = os . popen ( 'wc ' + sldir + '/' + slaname ) cmd_out = cmd . readline ( ) cnum_cycles = cmd_out . split ( ) [ 0 ] num_cycles = int ( cnum_cycles ) - 6 filename = sldir + '/' + slaname header_attr , cols , data = _read_mesafile ( filename , data_rows = num_cycles ) self . cols = cols self . header_attr = header_attr self . data = data | read history . data or star . log file again |
41,820 | def hrd ( self , ifig = None , label = None , colour = None , s2ms = False , dashes = None , ** kwargs ) : if ifig is not None : pl . figure ( ifig ) if s2ms : h1 = self . get ( 'center_h1' ) idx = np . where ( h1 [ 0 ] - h1 >= 3.e-3 ) [ 0 ] [ 0 ] skip = idx else : skip = 0 x = self . get ( 'log_Teff' ) [ skip : ] y = self . get ( 'log_L' ) [ skip : ] if label is not None : if colour is not None : line , = pl . plot ( x , y , label = label , color = colour , ** kwargs ) else : line , = pl . plot ( x , y , label = label , ** kwargs ) else : if colour is not None : line , = pl . plot ( x , y , color = colour , ** kwargs ) else : line , = pl . plot ( x , y , ** kwargs ) if dashes is not None : line . set_dashes ( dashes ) if label is not None : pl . legend ( loc = 'best' ) . draw_frame ( False ) pyl . xlabel ( '$\log T_{\\rm eff}$' ) pyl . ylabel ( '$\log L$' ) x1 , x2 = pl . xlim ( ) if x2 > x1 : ax = pl . gca ( ) ax . invert_xaxis ( ) | Plot an HR diagram |
41,821 | def hrd_key ( self , key_str ) : pyl . plot ( self . data [ : , self . cols [ 'log_Teff' ] - 1 ] , self . data [ : , self . cols [ 'log_L' ] - 1 ] , label = key_str ) pyl . legend ( ) pyl . xlabel ( 'log Teff' ) pyl . ylabel ( 'log L' ) x1 , x2 = pl . xlim ( ) if x2 > x1 : self . _xlimrev ( ) | plot an HR diagram |
41,822 | def hrd_new ( self , input_label = "" , skip = 0 ) : xl_old = pyl . gca ( ) . get_xlim ( ) if input_label == "" : my_label = "M=" + str ( self . header_attr [ 'initial_mass' ] ) + ", Z=" + str ( self . header_attr [ 'initial_z' ] ) else : my_label = "M=" + str ( self . header_attr [ 'initial_mass' ] ) + ", Z=" + str ( self . header_attr [ 'initial_z' ] ) + "; " + str ( input_label ) pyl . plot ( self . data [ skip : , self . cols [ 'log_Teff' ] - 1 ] , self . data [ skip : , self . cols [ 'log_L' ] - 1 ] , label = my_label ) pyl . legend ( loc = 0 ) xl_new = pyl . gca ( ) . get_xlim ( ) pyl . xlabel ( 'log Teff' ) pyl . ylabel ( 'log L' ) if any ( array ( xl_old ) == 0 ) : pyl . gca ( ) . set_xlim ( max ( xl_new ) , min ( xl_new ) ) elif any ( array ( xl_new ) == 0 ) : pyl . gca ( ) . set_xlim ( max ( xl_old ) , min ( xl_old ) ) else : pyl . gca ( ) . set_xlim ( [ max ( xl_old + xl_new ) , min ( xl_old + xl_new ) ] ) | plot an HR diagram with options to skip the first N lines and add a label string |
41,823 | def xche4_teff ( self , ifig = None , lims = [ 1. , 0. , 3.4 , 4.7 ] , label = None , colour = None , s2ms = True , dashes = None ) : fsize = 18 params = { 'axes.labelsize' : fsize , 'font.family' : 'Times New Roman' , 'figure.facecolor' : 'white' , 'text.fontsize' : fsize , 'legend.fontsize' : fsize , 'xtick.labelsize' : fsize * 0.8 , 'ytick.labelsize' : fsize * 0.8 , 'text.usetex' : False } try : pl . rcParams . update ( params ) except : pass if s2ms : h1 = self . get ( 'center_h1' ) idx = np . where ( h1 [ 0 ] - h1 >= 1.e-3 ) [ 0 ] [ 0 ] skip = idx else : skip = 0 x = self . get ( 'center_he4' ) [ skip : ] y = self . get ( 'log_Teff' ) [ skip : ] if ifig is not None : pl . figure ( ifig ) if label is not None : if colour is not None : line , = pl . plot ( x , y , label = label , color = colour ) else : line , = pl . plot ( x , y , label = label ) pl . legend ( loc = 'best' ) . draw_frame ( False ) else : if colour is not None : line , = pl . plot ( x , y , color = colour ) else : line , = pl . plot ( x , y ) if dashes is not None : line . set_dashes ( dashes ) if label is not None : pl . legend ( loc = 'best' ) . draw_frame ( False ) pl . xlim ( lims [ : 2 ] ) pl . ylim ( lims [ 2 : ] ) pl . xlabel ( '$X_{\\rm c}(\,^4{\\rm He}\,)$' ) pl . ylabel ( '$\log\,T_{\\rm eff}$' ) | Plot effective temperature against central helium abundance . |
41,824 | def tcrhoc ( self , ifig = None , lims = [ 3. , 10. , 8. , 10. ] , label = None , colour = None , dashes = None ) : if ifig is not None : pl . figure ( ifig ) if label is not None : if colour is not None : line , = pl . plot ( self . get ( 'log_center_Rho' ) , self . get ( 'log_center_T' ) , label = label , color = colour ) else : line , = pl . plot ( self . get ( 'log_center_Rho' ) , self . get ( 'log_center_T' ) , label = label ) else : if colour is not None : line , = pl . plot ( self . get ( 'log_center_Rho' ) , self . get ( 'log_center_T' ) , color = colour ) else : line , = pl . plot ( self . get ( 'log_center_Rho' ) , self . get ( 'log_center_T' ) ) if dashes is not None : line . set_dashes ( dashes ) if label is not None : pl . legend ( loc = 'best' ) . draw_frame ( False ) pl . xlim ( lims [ : 2 ] ) pl . ylim ( lims [ 2 : ] ) pl . xlabel ( 'log $\\rho_{\\rm c}$' ) pl . ylabel ( 'log $T_{\\rm c}$' ) | Central temperature again central density plot |
41,825 | def mdot_t ( self , ifig = None , lims = [ 7.4 , 2.6 , - 8.5 , - 4.5 ] , label = None , colour = None , s2ms = False , dashes = None ) : fsize = 18 params = { 'axes.labelsize' : fsize , 'font.family' : 'Times New Roman' , 'figure.facecolor' : 'white' , 'text.fontsize' : fsize , 'legend.fontsize' : fsize , 'xtick.labelsize' : fsize * 0.8 , 'ytick.labelsize' : fsize * 0.8 , 'text.usetex' : False } try : pl . rcParams . update ( params ) except : pass if ifig is not None : pl . figure ( ifig ) if s2ms : h1 = self . get ( 'center_h1' ) idx = np . where ( h1 [ 0 ] - h1 >= 3.e-3 ) [ 0 ] [ 0 ] skip = idx else : skip = 0 gage = self . get ( 'star_age' ) lage = np . zeros ( len ( gage ) ) agemin = max ( old_div ( abs ( gage [ - 1 ] - gage [ - 2 ] ) , 5. ) , 1.e-10 ) for i in np . arange ( len ( gage ) ) : if gage [ - 1 ] - gage [ i ] > agemin : lage [ i ] = np . log10 ( gage [ - 1 ] - gage [ i ] + agemin ) else : lage [ i ] = np . log10 ( agemin ) x = lage [ skip : ] y = self . get ( 'log_abs_mdot' ) [ skip : ] if ifig is not None : pl . figure ( ifig ) if label is not None : if colour is not None : line , = pl . plot ( x , y , label = label , color = colour ) else : line , = pl . plot ( x , y , label = label ) else : if colour is not None : line , = pl . plot ( x , y , color = colour ) else : line , = pl . plot ( x , y ) if dashes is not None : line . set_dashes ( dashes ) if label is not None : pl . legend ( loc = 'best' ) . draw_frame ( False ) pl . xlim ( lims [ : 2 ] ) pl . ylim ( lims [ 2 : ] ) pl . ylabel ( '$\mathrm{log}_{10}(\|\dot{M}\|/M_\odot\,\mathrm{yr}^{-1})$' ) pl . xlabel ( '$\mathrm{log}_{10}(t^*/\mathrm{yr})$' ) | Plot mass loss history as a function of log - time - left |
41,826 | def t_surfabu ( self , num_frame , xax , t0_model = 0 , title = 'surface abundance' , t_eps = 1.e-3 , plot_CO_ratio = False ) : if num_frame >= 0 : pyl . figure ( num_frame ) if xax == 'time' : xaxisarray = self . get ( 'star_age' ) [ t0_model : ] elif xax == 'model' : xaxisarray = self . get ( 'model_number' ) [ t0_model : ] elif xax == 'logrevtime' : xaxisarray = self . get ( 'star_age' ) xaxisarray = np . log10 ( max ( xaxisarray [ t0_model : ] ) + t_eps - xaxisarray [ t0_model : ] ) else : print ( 't-surfabu error: invalid string for x-axis selction.' + ' needs to be "time" or "model"' ) star_mass = self . get ( 'star_mass' ) surface_c12 = self . get ( 'surface_c12' ) surface_c13 = self . get ( 'surface_c13' ) surface_n14 = self . get ( 'surface_n14' ) surface_o16 = self . get ( 'surface_o16' ) target_n14 = - 3.5 COratio = old_div ( ( surface_c12 * 4. ) , ( surface_o16 * 3. ) ) t0_mod = xaxisarray [ t0_model ] log10_c12 = np . log10 ( surface_c12 [ t0_model : ] ) symbs = [ 'k:' , '-' , '--' , '-.' , 'b:' , '-' , '--' , 'k-.' , ':' , '-' , '--' , '-.' ] pyl . plot ( xaxisarray , log10_c12 , symbs [ 0 ] , label = '$^{12}\mathrm{C}$' ) pyl . plot ( xaxisarray , np . log10 ( surface_c13 [ t0_model : ] ) , symbs [ 1 ] , label = '$^{13}\mathrm{C}$' ) pyl . plot ( xaxisarray , np . log10 ( surface_n14 [ t0_model : ] ) , symbs [ 2 ] , label = '$^{14}\mathrm{N}$' ) pyl . plot ( xaxisarray , np . log10 ( surface_o16 [ t0_model : ] ) , symbs [ 3 ] , label = '$^{16}\mathrm{O}$' ) pyl . ylabel ( 'mass fraction $\log X$' ) pyl . legend ( loc = 2 ) if xax == 'time' : pyl . xlabel ( 't / yrs' ) elif xax == 'model' : pyl . xlabel ( 'model number' ) elif xax == 'logrevtime' : pyl . xlabel ( '$\\log t-tfinal$' ) if plot_CO_ratio : pyl . twinx ( ) pyl . plot ( xaxisarray , COratio [ t0_model : ] , '-k' , label = 'CO ratio' ) pyl . ylabel ( 'C/O ratio' ) pyl . legend ( loc = 4 ) pyl . title ( title ) if xax == 'logrevtime' : self . _xlimrev ( ) | t_surfabu plots surface abundance evolution as a function of time . |
41,827 | def t_lumi ( self , num_frame , xax ) : pyl . figure ( num_frame ) if xax == 'time' : xaxisarray = self . get ( 'star_age' ) elif xax == 'model' : xaxisarray = self . get ( 'model_number' ) else : print ( 'kippenhahn_error: invalid string for x-axis selction. needs to be "time" or "model"' ) logLH = self . get ( 'log_LH' ) logLHe = self . get ( 'log_LHe' ) pyl . plot ( xaxisarray , logLH , label = 'L_(H)' ) pyl . plot ( xaxisarray , logLHe , label = 'L(He)' ) pyl . ylabel ( 'log L' ) pyl . legend ( loc = 2 ) if xax == 'time' : pyl . xlabel ( 't / yrs' ) elif xax == 'model' : pyl . xlabel ( 'model number' ) | Luminosity evolution as a function of time or model . |
41,828 | def t_surf_parameter ( self , num_frame , xax ) : pyl . figure ( num_frame ) if xax == 'time' : xaxisarray = self . get ( 'star_age' ) elif xax == 'model' : xaxisarray = self . get ( 'model_number' ) else : print ( 'kippenhahn_error: invalid string for x-axis selction. needs to be "time" or "model"' ) logL = self . get ( 'log_L' ) logTeff = self . get ( 'log_Teff' ) pyl . plot ( xaxisarray , logL , '-k' , label = 'log L' ) pyl . plot ( xaxisarray , logTeff , '-k' , label = 'log Teff' ) pyl . ylabel ( 'log L, log Teff' ) pyl . legend ( loc = 2 ) if xax == 'time' : pyl . xlabel ( 't / yrs' ) elif xax == 'model' : pyl . xlabel ( 'model number' ) | Surface parameter evolution as a function of time or model . |
41,829 | def find_first_TP ( self ) : star_mass = self . get ( 'star_mass' ) he_lumi = self . get ( 'log_LHe' ) h_lumi = self . get ( 'log_LH' ) mx2_bot = self . get ( 'mx2_bot' ) * star_mass try : h1_boundary_mass = self . get ( 'h1_boundary_mass' ) he4_boundary_mass = self . get ( 'he4_boundary_mass' ) except : try : h1_boundary_mass = self . get ( 'he_core_mass' ) he4_boundary_mass = self . get ( 'c_core_mass' ) except : pass TP_bot = np . array ( self . get ( 'conv_mx2_bot' ) ) * np . array ( self . get ( 'star_mass' ) ) TP_top = np . array ( self . get ( 'conv_mx2_top' ) ) * np . array ( self . get ( 'star_mass' ) ) lum_array = [ ] activate = False models = [ ] pdcz_size = [ ] for i in range ( len ( h1_boundary_mass ) ) : if ( h1_boundary_mass [ i ] - he4_boundary_mass [ i ] < 0.2 ) and ( he4_boundary_mass [ i ] > 0.2 ) : if ( mx2_bot [ i ] > he4_boundary_mass [ i ] ) and ( he_lumi [ i ] > h_lumi [ i ] ) : if TP_top [ i ] > he4_boundary_mass [ i ] : pdcz_size . append ( TP_top [ i ] - TP_bot [ i ] ) activate = True lum_array . append ( he_lumi [ i ] ) models . append ( i ) if ( activate == True ) and ( he_lumi [ i ] < h_lumi [ i ] ) : if max ( pdcz_size ) < 1e-5 : active = False lum_array = [ ] models = [ ] print ( 'fake tp' ) else : break t0_model = models [ np . argmax ( lum_array ) ] return t0_model | Find first TP of the TPAGB phase and returns the model number at its LHe maximum . |
41,830 | def calc_DUP_parameter ( self , modeln , label , fig = 10 , color = 'r' , marker_type = '*' , h_core_mass = False ) : number_DUP = ( old_div ( len ( modeln ) , 2 ) - 1 ) try : h1_bnd_m = self . get ( 'h1_boundary_mass' ) except : try : h1_bnd_m = self . get ( 'he_core_mass' ) except : pass star_mass = self . get ( 'star_mass' ) age = self . get ( "star_age" ) firstTP = h1_bnd_m [ modeln [ 0 ] ] first_m_dredge = h1_bnd_m [ modeln [ 1 ] ] DUP_parameter = np . zeros ( number_DUP ) DUP_xaxis = np . zeros ( number_DUP ) j = 0 for i in np . arange ( 2 , len ( modeln ) , 2 ) : TP = h1_bnd_m [ modeln [ i ] ] m_dredge = h1_bnd_m [ modeln [ i + 1 ] ] if i == 2 : last_m_dredge = first_m_dredge if h_core_mass == True : DUP_xaxis [ j ] = h1_bnd_m [ modeln [ i ] ] else : DUP_xaxis [ j ] = star_mass [ modeln [ i ] ] DUP_parameter [ j ] = old_div ( ( TP - m_dredge ) , ( TP - last_m_dredge ) ) last_m_dredge = m_dredge j += 1 pl . figure ( fig ) pl . rcParams . update ( { 'font.size' : 18 } ) pl . rc ( 'xtick' , labelsize = 18 ) pl . rc ( 'ytick' , labelsize = 18 ) pl . plot ( DUP_xaxis , DUP_parameter , marker = marker_type , markersize = 12 , mfc = color , color = 'k' , linestyle = '-' , label = label ) if h_core_mass == True : pl . xlabel ( "$M_H$" , fontsize = 20 ) else : pl . xlabel ( "M/M$_{\odot}$" , fontsize = 24 ) pl . ylabel ( "$\lambda_{DUP}$" , fontsize = 24 ) pl . minorticks_on ( ) pl . legend ( ) | Method to calculate the DUP parameter evolution for different TPs specified specified by their model number . |
41,831 | def _create_usm_user_obj ( snmp_cred ) : auth_protocol = snmp_cred . get ( 'auth_protocol' ) priv_protocol = snmp_cred . get ( 'priv_protocol' ) auth_user = snmp_cred . get ( 'auth_user' ) auth_prot_pp = snmp_cred . get ( 'auth_prot_pp' ) auth_priv_pp = snmp_cred . get ( 'auth_priv_pp' ) if ( ( not auth_protocol ) and priv_protocol ) : priv_protocol = ( MAPPED_SNMP_ATTRIBUTES [ 'privProtocol' ] [ priv_protocol ] ) usm_user_obj = hlapi . UsmUserData ( auth_user , auth_prot_pp , auth_priv_pp , privProtocol = priv_protocol ) elif ( ( not priv_protocol ) and auth_protocol ) : auth_protocol = ( MAPPED_SNMP_ATTRIBUTES [ 'authProtocol' ] [ auth_protocol ] ) usm_user_obj = hlapi . UsmUserData ( auth_user , auth_prot_pp , auth_priv_pp , authProtocol = auth_protocol ) elif not all ( [ priv_protocol and auth_protocol ] ) : usm_user_obj = hlapi . UsmUserData ( auth_user , auth_prot_pp , auth_priv_pp ) else : auth_protocol = ( MAPPED_SNMP_ATTRIBUTES [ 'authProtocol' ] [ auth_protocol ] ) priv_protocol = ( MAPPED_SNMP_ATTRIBUTES [ 'privProtocol' ] [ priv_protocol ] ) usm_user_obj = hlapi . UsmUserData ( auth_user , auth_prot_pp , auth_priv_pp , authProtocol = auth_protocol , privProtocol = priv_protocol ) return usm_user_obj | Creates the UsmUserData obj for the given credentials . |
41,832 | def _parse_mibs ( iLOIP , snmp_credentials ) : result = { } usm_user_obj = _create_usm_user_obj ( snmp_credentials ) try : for ( errorIndication , errorStatus , errorIndex , varBinds ) in hlapi . nextCmd ( hlapi . SnmpEngine ( ) , usm_user_obj , hlapi . UdpTransportTarget ( ( iLOIP , 161 ) , timeout = 3 , retries = 3 ) , hlapi . ContextData ( ) , hlapi . ObjectType ( hlapi . ObjectIdentity ( '1.3.6.1.4.1.232.3.2.5.1' ) ) , hlapi . ObjectType ( hlapi . ObjectIdentity ( '1.3.6.1.4.1.232.5.2.4.1' ) ) , hlapi . ObjectType ( hlapi . ObjectIdentity ( '1.3.6.1.4.1.232.5.5.2.1' ) ) , lexicographicMode = False , ignoreNonIncreasingOid = True ) : if errorIndication : LOG . error ( errorIndication ) msg = "SNMP failed to traverse MIBs %s" , errorIndication raise exception . IloSNMPInvalidInputFailure ( msg ) else : if errorStatus : msg = ( 'Parsing MIBs failed. %s at %s' % ( errorStatus . prettyPrint ( ) , errorIndex and varBinds [ - 1 ] [ int ( errorIndex ) - 1 ] or '?' ) ) LOG . error ( msg ) raise exception . IloSNMPInvalidInputFailure ( msg ) else : for varBindTableRow in varBinds : name , val = tuple ( varBindTableRow ) oid , label , suffix = ( mibViewController . getNodeName ( name ) ) key = name . prettyPrint ( ) if not ( key . find ( "SNMPv2-SMI::enterprises.232.3" ) >= 0 or ( key . find ( "SNMPv2-SMI::enterprises.232.5" ) >= 0 ) ) : break if key not in result : result [ key ] = { } result [ key ] [ label [ - 1 ] ] = { } result [ key ] [ label [ - 1 ] ] [ suffix ] = val except Exception as e : msg = "SNMP library failed with error %s" , e LOG . error ( msg ) raise exception . IloSNMPExceptionFailure ( msg ) return result | Parses the MIBs . |
41,833 | def _get_disksize_MiB ( iLOIP , cred ) : result = _parse_mibs ( iLOIP , cred ) disksize = { } for uuid in sorted ( result ) : for key in result [ uuid ] : if key . find ( 'PhyDrvSize' ) >= 0 : disksize [ uuid ] = dict ( ) for suffix in sorted ( result [ uuid ] [ key ] ) : size = result [ uuid ] [ key ] [ suffix ] disksize [ uuid ] [ key ] = str ( size ) return disksize | Reads the dictionary of parsed MIBs and gets the disk size . |
41,834 | def get_local_gb ( iLOIP , snmp_credentials ) : disk_sizes = _get_disksize_MiB ( iLOIP , snmp_credentials ) max_size = 0 for uuid in disk_sizes : for key in disk_sizes [ uuid ] : if int ( disk_sizes [ uuid ] [ key ] ) > max_size : max_size = int ( disk_sizes [ uuid ] [ key ] ) max_size_gb = max_size / 1024 return max_size_gb | Gets the maximum disk size among all disks . |
41,835 | def summary ( self ) : mac_dict = { } for eth in self . get_members ( ) : if eth . mac_address is not None : if ( eth . status is not None and eth . status . health == sys_cons . HEALTH_OK and eth . status . state == sys_cons . HEALTH_STATE_ENABLED ) : mac_dict . update ( { 'Port ' + eth . identity : eth . mac_address } ) return mac_dict | property to return the summary MAC addresses and state |
41,836 | def _update_physical_disk_details ( raid_config , server ) : raid_config [ 'physical_disks' ] = [ ] physical_drives = server . get_physical_drives ( ) for physical_drive in physical_drives : physical_drive_dict = physical_drive . get_physical_drive_dict ( ) raid_config [ 'physical_disks' ] . append ( physical_drive_dict ) | Adds the physical disk details to the RAID configuration passed . |
41,837 | def validate ( raid_config ) : raid_schema_fobj = open ( RAID_CONFIG_SCHEMA , 'r' ) raid_config_schema = json . load ( raid_schema_fobj ) try : jsonschema . validate ( raid_config , raid_config_schema ) except json_schema_exc . ValidationError as e : raise exception . InvalidInputError ( e . message ) for logical_disk in raid_config [ 'logical_disks' ] : raid_level = logical_disk [ 'raid_level' ] min_disks_reqd = constants . RAID_LEVEL_MIN_DISKS [ raid_level ] no_of_disks_specified = None if 'number_of_physical_disks' in logical_disk : no_of_disks_specified = logical_disk [ 'number_of_physical_disks' ] elif 'physical_disks' in logical_disk : no_of_disks_specified = len ( logical_disk [ 'physical_disks' ] ) if ( no_of_disks_specified and no_of_disks_specified < min_disks_reqd ) : msg = ( "RAID level %(raid_level)s requires at least %(number)s " "disks." % { 'raid_level' : raid_level , 'number' : min_disks_reqd } ) raise exception . InvalidInputError ( msg ) | Validates the RAID configuration provided . |
41,838 | def _select_controllers_by ( server , select_condition , msg ) : all_controllers = server . controllers supported_controllers = [ c for c in all_controllers if select_condition ( c ) ] if not supported_controllers : reason = ( "None of the available SSA controllers %(controllers)s " "have %(msg)s" % { 'controllers' : ', ' . join ( [ c . id for c in all_controllers ] ) , 'msg' : msg } ) raise exception . HPSSAOperationError ( reason = reason ) server . controllers = supported_controllers | Filters out the hpssa controllers based on the condition . |
41,839 | def create_configuration ( raid_config ) : server = objects . Server ( ) select_controllers = lambda x : not x . properties . get ( 'HBA Mode Enabled' , False ) _select_controllers_by ( server , select_controllers , 'RAID enabled' ) validate ( raid_config ) logical_disks_sorted = ( sorted ( ( x for x in raid_config [ 'logical_disks' ] if x [ 'size_gb' ] != "MAX" ) , reverse = True , key = lambda x : x [ 'size_gb' ] ) + [ x for x in raid_config [ 'logical_disks' ] if x [ 'size_gb' ] == "MAX" ] ) if any ( logical_disk [ 'share_physical_disks' ] for logical_disk in logical_disks_sorted if 'share_physical_disks' in logical_disk ) : logical_disks_sorted = _sort_shared_logical_disks ( logical_disks_sorted ) wwns_before_create = set ( [ x . wwn for x in server . get_logical_drives ( ) ] ) for logical_disk in logical_disks_sorted : if 'physical_disks' not in logical_disk : disk_allocator . allocate_disks ( logical_disk , server , raid_config ) controller_id = logical_disk [ 'controller' ] controller = server . get_controller_by_id ( controller_id ) if not controller : msg = ( "Unable to find controller named '%(controller)s'." " The available controllers are '%(ctrl_list)s'." % { 'controller' : controller_id , 'ctrl_list' : ', ' . join ( [ c . id for c in server . controllers ] ) } ) raise exception . InvalidInputError ( reason = msg ) if 'physical_disks' in logical_disk : for physical_disk in logical_disk [ 'physical_disks' ] : disk_obj = controller . get_physical_drive_by_id ( physical_disk ) if not disk_obj : msg = ( "Unable to find physical disk '%(physical_disk)s' " "on '%(controller)s'" % { 'physical_disk' : physical_disk , 'controller' : controller_id } ) raise exception . InvalidInputError ( msg ) controller . create_logical_drive ( logical_disk ) server . refresh ( ) wwns_after_create = set ( [ x . wwn for x in server . get_logical_drives ( ) ] ) new_wwn = wwns_after_create - wwns_before_create if not new_wwn : reason = ( "Newly created logical disk with raid_level " "'%(raid_level)s' and size %(size_gb)s GB not " "found." % { 'raid_level' : logical_disk [ 'raid_level' ] , 'size_gb' : logical_disk [ 'size_gb' ] } ) raise exception . HPSSAOperationError ( reason = reason ) new_logical_disk = server . get_logical_drive_by_wwn ( new_wwn . pop ( ) ) new_log_drive_properties = new_logical_disk . get_logical_drive_dict ( ) logical_disk . update ( new_log_drive_properties ) wwns_before_create = wwns_after_create . copy ( ) _update_physical_disk_details ( raid_config , server ) return raid_config | Create a RAID configuration on this server . |
41,840 | def _sort_shared_logical_disks ( logical_disks ) : is_shared = ( lambda x : True if ( 'share_physical_disks' in x and x [ 'share_physical_disks' ] ) else False ) num_of_disks = ( lambda x : x [ 'number_of_physical_disks' ] if 'number_of_physical_disks' in x else constants . RAID_LEVEL_MIN_DISKS [ x [ 'raid_level' ] ] ) logical_disks_shared = [ ] logical_disks_nonshared = [ ] for x in logical_disks : target = ( logical_disks_shared if is_shared ( x ) else logical_disks_nonshared ) target . append ( x ) logical_disks_shared_raid1 = [ ] logical_disks_shared_excl_raid1 = [ ] for x in logical_disks_shared : target = ( logical_disks_shared_raid1 if x [ 'raid_level' ] == '1' else logical_disks_shared_excl_raid1 ) target . append ( x ) logical_disks_shared = sorted ( logical_disks_shared_excl_raid1 , reverse = True , key = num_of_disks ) check = True for x in logical_disks_shared : if x [ 'raid_level' ] == "1+0" : x_num = num_of_disks ( x ) for y in logical_disks_shared : if y [ 'raid_level' ] != "1+0" : y_num = num_of_disks ( y ) if x_num < y_num : check = ( True if y_num % 2 == 0 else False ) if check : break if not check : logical_disks_shared . remove ( x ) logical_disks_shared . insert ( 0 , x ) check = True logical_disks_sorted = ( logical_disks_nonshared + logical_disks_shared_raid1 + logical_disks_shared ) return logical_disks_sorted | Sort the logical disks based on the following conditions . |
41,841 | def delete_configuration ( ) : server = objects . Server ( ) select_controllers = lambda x : not x . properties . get ( 'HBA Mode Enabled' , False ) _select_controllers_by ( server , select_controllers , 'RAID enabled' ) for controller in server . controllers : if controller . raid_arrays : controller . delete_all_logical_drives ( ) return get_configuration ( ) | Delete a RAID configuration on this server . |
41,842 | def get_configuration ( ) : server = objects . Server ( ) logical_drives = server . get_logical_drives ( ) raid_config = { } raid_config [ 'logical_disks' ] = [ ] for logical_drive in logical_drives : logical_drive_dict = logical_drive . get_logical_drive_dict ( ) raid_config [ 'logical_disks' ] . append ( logical_drive_dict ) _update_physical_disk_details ( raid_config , server ) return raid_config | Get the current RAID configuration . |
41,843 | def erase_devices ( ) : server = objects . Server ( ) for controller in server . controllers : drives = [ x for x in controller . unassigned_physical_drives if ( x . get_physical_drive_dict ( ) . get ( 'erase_status' , '' ) == 'OK' ) ] if drives : controller . erase_devices ( drives ) while not has_erase_completed ( ) : time . sleep ( 300 ) server . refresh ( ) status = { } for controller in server . controllers : drive_status = { x . id : x . erase_status for x in controller . unassigned_physical_drives } sanitize_supported = controller . properties . get ( 'Sanitize Erase Supported' , 'False' ) if sanitize_supported == 'False' : msg = ( "Drives overwritten with zeros because sanitize erase " "is not supported on the controller." ) else : msg = ( "Sanitize Erase performed on the disks attached to " "the controller." ) drive_status . update ( { 'Summary' : msg } ) status [ controller . id ] = drive_status return status | Erase all the drives on this server . |
41,844 | def _parse_queue_message_from_headers ( response ) : headers = _parse_response_for_dict ( response ) message = QueueMessage ( ) message . pop_receipt = headers . get ( 'x-ms-popreceipt' ) message . time_next_visible = parser . parse ( headers . get ( 'x-ms-time-next-visible' ) ) return message | Extracts pop receipt and time next visible from headers . |
41,845 | def volumes ( self ) : return sys_volumes . VolumeCollection ( self . _conn , utils . get_subresource_path_by ( self , 'Volumes' ) , redfish_version = self . redfish_version ) | This property prepares the list of volumes |
41,846 | def _drives_list ( self ) : drives_list = [ ] for member in self . drives : drives_list . append ( sys_drives . Drive ( self . _conn , member . get ( '@odata.id' ) , self . redfish_version ) ) return drives_list | Gets the list of drives |
41,847 | def has_ssd ( self ) : for member in self . _drives_list ( ) : if member . media_type == constants . MEDIA_TYPE_SSD : return True return False | Return true if any of the drive is ssd |
41,848 | def has_rotational ( self ) : for member in self . _drives_list ( ) : if member . media_type == constants . MEDIA_TYPE_HDD : return True return False | Return true if any of the drive is HDD |
41,849 | def has_nvme_ssd ( self ) : for member in self . _drives_list ( ) : if ( member . media_type == constants . MEDIA_TYPE_SSD and member . protocol == constants . PROTOCOL_NVMe ) : return True return False | Return True if the drive is SSD and protocol is NVMe |
41,850 | def create_table_service ( self ) : try : from . . table . tableservice import TableService return TableService ( self . account_name , self . account_key , sas_token = self . sas_token , is_emulated = self . is_emulated ) except ImportError : raise Exception ( 'The package azure-storage-table is required. ' + 'Please install it using "pip install azure-storage-table"' ) | Creates a TableService object with the settings specified in the CloudStorageAccount . |
41,851 | def get_queue_service_properties ( self , timeout = None ) : request = HTTPRequest ( ) request . method = 'GET' request . host = self . _get_host ( ) request . path = _get_path ( ) request . query = [ ( 'restype' , 'service' ) , ( 'comp' , 'properties' ) , ( 'timeout' , _int_to_str ( timeout ) ) , ] response = self . _perform_request ( request ) return _convert_xml_to_service_properties ( response . body ) | Gets the properties of a storage account s Queue service including logging analytics and CORS rules . |
41,852 | def get_queue_acl ( self , queue_name , timeout = None ) : _validate_not_none ( 'queue_name' , queue_name ) request = HTTPRequest ( ) request . method = 'GET' request . host = self . _get_host ( ) request . path = _get_path ( queue_name ) request . query = [ ( 'comp' , 'acl' ) , ( 'timeout' , _int_to_str ( timeout ) ) , ] response = self . _perform_request ( request ) return _convert_xml_to_signed_identifiers ( response . body ) | Returns details about any stored access policies specified on the queue that may be used with Shared Access Signatures . |
41,853 | def get_allowed_reset_keys_values ( self ) : reset_keys_action = self . _get_reset_keys_action_element ( ) if not reset_keys_action . allowed_values : LOG . warning ( 'Could not figure out the allowed values for the ' 'reset keys in secure boot %s' , self . path ) return set ( mappings . SECUREBOOT_RESET_KEYS_MAP_REV ) return set ( [ mappings . SECUREBOOT_RESET_KEYS_MAP [ v ] for v in set ( mappings . SECUREBOOT_RESET_KEYS_MAP ) . intersection ( reset_keys_action . allowed_values ) ] ) | Get the allowed values for resetting the system . |
41,854 | def reset_keys ( self , target_value ) : valid_keys_resets = self . get_allowed_reset_keys_values ( ) if target_value not in valid_keys_resets : msg = ( 'The parameter "%(parameter)s" value "%(target_value)s" is ' 'invalid. Valid values are: %(valid_keys_reset_values)s' % { 'parameter' : 'target_value' , 'target_value' : target_value , 'valid_keys_reset_values' : valid_keys_resets } ) raise exception . InvalidInputError ( msg ) value = mappings . SECUREBOOT_RESET_KEYS_MAP_REV [ target_value ] target_uri = ( self . _get_reset_keys_action_element ( ) . target_uri ) self . _conn . post ( target_uri , data = { 'ResetKeysType' : value } ) | Resets the secure boot keys . |
41,855 | def _parse_response_for_dict ( response ) : if response is None : return None http_headers = [ 'server' , 'date' , 'location' , 'host' , 'via' , 'proxy-connection' , 'connection' ] return_dict = _HeaderDict ( ) if response . headers : for name , value in response . headers : if not name . lower ( ) in http_headers : return_dict [ name ] = value return return_dict | Extracts name - values from response header . Filter out the standard http headers . |
41,856 | def iscsi_settings ( self ) : return ISCSISettings ( self . _conn , utils . get_subresource_path_by ( self , [ "@Redfish.Settings" , "SettingsObject" ] ) , redfish_version = self . redfish_version ) | Property to provide reference to iSCSI settings instance |
41,857 | def update_iscsi_settings ( self , iscsi_data ) : self . _conn . patch ( self . path , data = iscsi_data ) | Update iscsi data |
41,858 | def array_controllers ( self ) : return array_controller . HPEArrayControllerCollection ( self . _conn , utils . get_subresource_path_by ( self , [ 'Links' , 'ArrayControllers' ] ) , redfish_version = self . redfish_version ) | This property gets the list of instances for array controllers |
41,859 | def wait_for_operation_to_complete ( has_operation_completed , retries = 10 , delay_bw_retries = 5 , delay_before_attempts = 10 , failover_exc = exception . IloError , failover_msg = ( "Operation did not complete even after multiple " "attempts." ) , is_silent_loop_exit = False ) : retry_count = retries time . sleep ( delay_before_attempts ) while retry_count : try : LOG . debug ( "Calling '%s', retries left: %d" , has_operation_completed . __name__ , retry_count ) if has_operation_completed ( ) : break except exception . IloError : pass time . sleep ( delay_bw_retries ) retry_count -= 1 else : LOG . debug ( "Max retries exceeded with: '%s'" , has_operation_completed . __name__ ) if not is_silent_loop_exit : raise failover_exc ( failover_msg ) | Attempts the provided operation for a specified number of times . |
41,860 | def wait_for_ilo_after_reset ( ilo_object ) : is_ilo_up_after_reset = lambda : ilo_object . get_product_name ( ) is not None is_ilo_up_after_reset . __name__ = 'is_ilo_up_after_reset' wait_for_operation_to_complete ( is_ilo_up_after_reset , failover_exc = exception . IloConnectionError , failover_msg = 'iLO is not up after reset.' ) | Continuously polls for iLO to come up after reset . |
41,861 | def wait_for_ribcl_firmware_update_to_complete ( ribcl_object ) : def is_ilo_reset_initiated ( ) : try : LOG . debug ( ribcl_object . _ ( 'Checking for iLO reset...' ) ) ribcl_object . get_product_name ( ) return False except exception . IloError : LOG . debug ( ribcl_object . _ ( 'iLO is being reset...' ) ) return True wait_for_operation_to_complete ( is_ilo_reset_initiated , delay_bw_retries = 6 , delay_before_attempts = 5 , is_silent_loop_exit = True ) wait_for_ilo_after_reset ( ribcl_object ) | Continuously checks for iLO firmware update to complete . |
41,862 | def get_filename_and_extension_of ( target_file ) : base_target_filename = os . path . basename ( target_file ) file_name , file_ext_with_dot = os . path . splitext ( base_target_filename ) return file_name , file_ext_with_dot | Gets the base filename and extension of the target file . |
41,863 | def add_exec_permission_to ( target_file ) : mode = os . stat ( target_file ) . st_mode os . chmod ( target_file , mode | stat . S_IXUSR ) | Add executable permissions to the file |
41,864 | def get_major_minor ( ilo_ver_str ) : if not ilo_ver_str : return None try : pattern = re . search ( ILO_VER_STR_PATTERN , ilo_ver_str ) if pattern : matched = pattern . group ( 0 ) if matched : return matched return None except Exception : return None | Extract the major and minor number from the passed string |
41,865 | def get_supported_boot_modes ( supported_boot_mode_constant ) : boot_mode_bios = 'false' boot_mode_uefi = 'false' if ( supported_boot_mode_constant == constants . SUPPORTED_BOOT_MODE_LEGACY_BIOS_ONLY ) : boot_mode_bios = 'true' elif ( supported_boot_mode_constant == constants . SUPPORTED_BOOT_MODE_UEFI_ONLY ) : boot_mode_uefi = 'true' elif ( supported_boot_mode_constant == constants . SUPPORTED_BOOT_MODE_LEGACY_BIOS_AND_UEFI ) : boot_mode_bios = 'true' boot_mode_uefi = 'true' return SupportedBootModes ( boot_mode_bios = boot_mode_bios , boot_mode_uefi = boot_mode_uefi ) | Retrieves the server supported boot modes |
41,866 | def refresh ( self ) : config = self . _get_all_details ( ) raid_info = _convert_to_dict ( config ) self . controllers = [ ] for key , value in raid_info . items ( ) : self . controllers . append ( Controller ( key , value , self ) ) self . last_updated = time . time ( ) | Refresh the server and it s child objects . |
41,867 | def get_controller_by_id ( self , id ) : for controller in self . controllers : if controller . id == id : return controller return None | Get the controller object given the id . |
41,868 | def get_logical_drives ( self ) : logical_drives = [ ] for controller in self . controllers : for array in controller . raid_arrays : for logical_drive in array . logical_drives : logical_drives . append ( logical_drive ) return logical_drives | Get all the RAID logical drives in the Server . |
41,869 | def get_physical_drives ( self ) : physical_drives = [ ] for controller in self . controllers : for physical_drive in controller . unassigned_physical_drives : physical_drives . append ( physical_drive ) for array in controller . raid_arrays : for physical_drive in array . physical_drives : physical_drives . append ( physical_drive ) return physical_drives | Get all the RAID physical drives on the Server . |
41,870 | def get_logical_drive_by_wwn ( self , wwn ) : disk = [ x for x in self . get_logical_drives ( ) if x . wwn == wwn ] if disk : return disk [ 0 ] return None | Get the logical drive object given the wwn . |
41,871 | def get_physical_drive_by_id ( self , id ) : for phy_drive in self . unassigned_physical_drives : if phy_drive . id == id : return phy_drive for array in self . raid_arrays : for phy_drive in array . physical_drives : if phy_drive . id == id : return phy_drive return None | Get a PhysicalDrive object for given id . |
41,872 | def create_logical_drive ( self , logical_drive_info ) : cmd_args = [ ] if 'array' in logical_drive_info : cmd_args . extend ( [ 'array' , logical_drive_info [ 'array' ] ] ) cmd_args . extend ( [ 'create' , "type=logicaldrive" ] ) if 'physical_disks' in logical_drive_info : phy_drive_ids = ',' . join ( logical_drive_info [ 'physical_disks' ] ) cmd_args . append ( "drives=%s" % phy_drive_ids ) raid_level = logical_drive_info [ 'raid_level' ] raid_level = constants . RAID_LEVEL_INPUT_TO_HPSSA_MAPPING . get ( raid_level , raid_level ) cmd_args . append ( "raid=%s" % raid_level ) if logical_drive_info [ 'size_gb' ] != "MAX" : size_mb = logical_drive_info [ 'size_gb' ] * 1024 cmd_args . append ( "size=%s" % size_mb ) self . execute_cmd ( * cmd_args , process_input = 'y' ) | Create a logical drive on the controller . |
41,873 | def _get_erase_command ( self , drive , pattern ) : cmd_args = [ ] cmd_args . append ( "pd %s" % drive ) cmd_args . extend ( [ 'modify' , 'erase' , pattern ] ) if pattern != 'erasepattern=zero' : cmd_args . append ( 'unrestricted=off' ) cmd_args . append ( 'forced' ) return cmd_args | Return the command arguments based on the pattern . |
41,874 | def erase_devices ( self , drives ) : for drive in drives : pattern = 'overwrite' if ( drive . disk_type == constants . DISK_TYPE_HDD ) else 'block' cmd_args = self . _get_erase_command ( drive . id , 'erasepattern=%s' % pattern ) stdout = self . execute_cmd ( * cmd_args ) LOG . debug ( "Sanitize disk erase invoked with erase pattern as " "'%(pattern)s' on disk type: %(disk_type)s." % { 'pattern' : pattern , 'disk_type' : drive . disk_type } ) if "not supported" in str ( stdout ) : new_pattern = 'zero' cmd_args = self . _get_erase_command ( drive . id , 'erasepattern=zero' ) self . execute_cmd ( * cmd_args ) LOG . debug ( "Sanitize disk erase invoked with erase pattern as " "'%(pattern)s' is not supported on disk type: " "%(disk_type)s. Now its invoked with erase pattern " "as %(new_pattern)s." % { 'pattern' : pattern , 'disk_type' : drive . disk_type , 'new_pattern' : new_pattern } ) | Perform Erase on all the drives in the controller . |
41,875 | def can_accomodate ( self , logical_disk ) : raid_level = constants . RAID_LEVEL_INPUT_TO_HPSSA_MAPPING . get ( logical_disk [ 'raid_level' ] , logical_disk [ 'raid_level' ] ) args = ( "array" , self . id , "create" , "type=logicaldrive" , "raid=%s" % raid_level , "size=?" ) if logical_disk [ 'size_gb' ] != "MAX" : desired_disk_size = logical_disk [ 'size_gb' ] else : desired_disk_size = constants . MINIMUM_DISK_SIZE try : stdout , stderr = self . parent . execute_cmd ( * args , dont_transform_to_hpssa_exception = True ) except processutils . ProcessExecutionError as ex : if ex . exit_code == 1 : return False else : raise exception . HPSSAOperationError ( reason = ex ) except Exception as ex : raise exception . HPSSAOperationError ( reason = ex ) match = re . search ( 'Max: (\d+)' , stdout ) if not match : return False max_size_gb = int ( match . group ( 1 ) ) / 1024 return desired_disk_size <= max_size_gb | Check if this RAID array can accomodate the logical disk . |
41,876 | def get_physical_drive_dict ( self ) : if isinstance ( self . parent , RaidArray ) : controller = self . parent . parent . id status = 'active' else : controller = self . parent . id status = 'ready' return { 'size_gb' : self . size_gb , 'controller' : controller , 'id' : self . id , 'disk_type' : self . disk_type , 'interface_type' : self . interface_type , 'model' : self . model , 'firmware' : self . firmware , 'status' : status , 'erase_status' : self . erase_status } | Returns a dictionary of with the details of the physical drive . |
41,877 | def send_stream ( stream , filename , size , mtime , mimetype = None , restricted = True , as_attachment = False , etag = None , content_md5 = None , chunk_size = None , conditional = True , trusted = False ) : chunk_size = chunk_size_or_default ( chunk_size ) if mimetype is None and filename : mimetype = mimetypes . guess_type ( filename ) [ 0 ] if mimetype is None : mimetype = 'application/octet-stream' headers = Headers ( ) headers [ 'Content-Length' ] = size if content_md5 : headers [ 'Content-MD5' ] = content_md5 if not trusted : mimetype = sanitize_mimetype ( mimetype , filename = filename ) headers [ 'Content-Security-Policy' ] = "default-src 'none';" headers [ 'X-Content-Type-Options' ] = 'nosniff' headers [ 'X-Download-Options' ] = 'noopen' headers [ 'X-Permitted-Cross-Domain-Policies' ] = 'none' headers [ 'X-Frame-Options' ] = 'deny' headers [ 'X-XSS-Protection' ] = '1; mode=block' if as_attachment or mimetype == 'application/octet-stream' : try : filenames = { 'filename' : filename . encode ( 'latin-1' ) } except UnicodeEncodeError : filenames = { 'filename*' : "UTF-8''%s" % url_quote ( filename ) } encoded_filename = ( unicodedata . normalize ( 'NFKD' , filename ) . encode ( 'latin-1' , 'ignore' ) ) if encoded_filename : filenames [ 'filename' ] = encoded_filename headers . add ( 'Content-Disposition' , 'attachment' , ** filenames ) else : headers . add ( 'Content-Disposition' , 'inline' ) rv = current_app . response_class ( FileWrapper ( stream , buffer_size = chunk_size ) , mimetype = mimetype , headers = headers , direct_passthrough = True , ) if etag : rv . set_etag ( etag ) if mtime is not None : rv . last_modified = int ( mtime ) if not restricted : rv . cache_control . public = True cache_timeout = current_app . get_send_file_max_age ( filename ) if cache_timeout is not None : rv . cache_control . max_age = cache_timeout rv . expires = int ( time ( ) + cache_timeout ) if conditional : rv = rv . make_conditional ( request ) return rv | Send the contents of a file to the client . |
41,878 | def sanitize_mimetype ( mimetype , filename = None ) : if mimetype in MIMETYPE_WHITELIST : return mimetype if mimetype in MIMETYPE_PLAINTEXT or ( filename and filename . lower ( ) in MIMETYPE_TEXTFILES ) : return 'text/plain' return 'application/octet-stream' | Sanitize a MIME type so the browser does not render the file . |
41,879 | def make_path ( base_uri , path , filename , path_dimensions , split_length ) : assert len ( path ) > path_dimensions * split_length uri_parts = [ ] for i in range ( path_dimensions ) : uri_parts . append ( path [ 0 : split_length ] ) path = path [ split_length : ] uri_parts . append ( path ) uri_parts . append ( filename ) return os . path . join ( base_uri , * uri_parts ) | Generate a path as base location for file instance . |
41,880 | def populate_from_path ( bucket , source , checksum = True , key_prefix = '' , chunk_size = None ) : from . models import FileInstance , ObjectVersion def create_file ( key , path ) : key = key_prefix + key if checksum : file_checksum = compute_md5_checksum ( open ( path , 'rb' ) , chunk_size = chunk_size ) file_instance = FileInstance . query . filter_by ( checksum = file_checksum , size = os . path . getsize ( path ) ) . first ( ) if file_instance : return ObjectVersion . create ( bucket , key , _file_id = file_instance . id ) return ObjectVersion . create ( bucket , key , stream = open ( path , 'rb' ) ) if os . path . isfile ( source ) : yield create_file ( os . path . basename ( source ) , source ) else : for root , dirs , files in os . walk ( source , topdown = False ) : for name in files : filename = os . path . join ( root , name ) assert filename . startswith ( source ) parts = [ p for p in filename [ len ( source ) : ] . split ( os . sep ) if p ] yield create_file ( '/' . join ( parts ) , os . path . join ( root , name ) ) | Populate a bucket from all files in path . |
41,881 | def set_options ( self , options ) : self . wipe = options . get ( "wipe" ) self . test_run = options . get ( "test_run" ) self . quiet = options . get ( "test_run" ) self . container_name = options . get ( "container" ) self . verbosity = int ( options . get ( "verbosity" ) ) self . syncmedia = options . get ( "syncmedia" ) self . syncstatic = options . get ( "syncstatic" ) if self . test_run : self . verbosity = 2 cli_includes = options . get ( "includes" ) cli_excludes = options . get ( "excludes" ) if self . syncmedia and self . syncstatic : raise CommandError ( "options --media and --static are mutually exclusive" ) if not self . container_name : if self . syncmedia : self . container_name = CUMULUS [ "CONTAINER" ] elif self . syncstatic : self . container_name = CUMULUS [ "STATIC_CONTAINER" ] else : raise CommandError ( "must select one of the required options, either --media or --static" ) settings_includes = CUMULUS [ "INCLUDE_LIST" ] settings_excludes = CUMULUS [ "EXCLUDE_LIST" ] if self . syncmedia : self . file_root = os . path . abspath ( settings . MEDIA_ROOT ) self . file_url = settings . MEDIA_URL elif self . syncstatic : self . file_root = os . path . abspath ( settings . STATIC_ROOT ) self . file_url = settings . STATIC_URL if not self . file_root . endswith ( "/" ) : self . file_root = self . file_root + "/" if self . file_url . startswith ( "/" ) : self . file_url = self . file_url [ 1 : ] self . includes = list ( set ( cli_includes + settings_includes ) ) self . excludes = list ( set ( cli_excludes + settings_excludes ) ) self . local_filenames = [ ] self . create_count = 0 self . upload_count = 0 self . update_count = 0 self . skip_count = 0 self . delete_count = 0 | Sets instance variables based on an options dict |
41,882 | def match_cloud ( self , includes , excludes ) : cloud_objs = [ cloud_obj . name for cloud_obj in self . container . get_objects ( ) ] includes_pattern = r"|" . join ( [ fnmatch . translate ( x ) for x in includes ] ) excludes_pattern = r"|" . join ( [ fnmatch . translate ( x ) for x in excludes ] ) or r"$." excludes = [ o for o in cloud_objs if re . match ( excludes_pattern , o ) ] includes = [ o for o in cloud_objs if re . match ( includes_pattern , o ) ] return [ o for o in includes if o not in excludes ] | Returns the cloud objects that match the include and exclude patterns . |
41,883 | def upload_files ( self , abspaths , relpaths , remote_objects ) : for relpath in relpaths : abspath = [ p for p in abspaths if p [ len ( self . file_root ) : ] == relpath ] [ 0 ] cloud_datetime = remote_objects [ relpath ] if relpath in remote_objects else None local_datetime = datetime . datetime . utcfromtimestamp ( os . stat ( abspath ) . st_mtime ) if cloud_datetime and local_datetime < cloud_datetime : self . skip_count += 1 if not self . quiet : print ( "Skipped {0}: not modified." . format ( relpath ) ) continue if relpath in remote_objects : self . update_count += 1 else : self . create_count += 1 self . upload_file ( abspath , relpath ) | Determines files to be uploaded and call upload_file on each . |
41,884 | def upload_file ( self , abspath , cloud_filename ) : if not self . test_run : content = open ( abspath , "rb" ) content_type = get_content_type ( cloud_filename , content ) headers = get_headers ( cloud_filename , content_type ) if headers . get ( "Content-Encoding" ) == "gzip" : content = get_gzipped_contents ( content ) size = content . size else : size = os . stat ( abspath ) . st_size self . container . create ( obj_name = cloud_filename , data = content , content_type = content_type , content_length = size , content_encoding = headers . get ( "Content-Encoding" , None ) , headers = headers , ttl = CUMULUS [ "FILE_TTL" ] , etag = None , ) self . upload_count += 1 if not self . quiet or self . verbosity > 1 : print ( "Uploaded: {0}" . format ( cloud_filename ) ) | Uploads a file to the container . |
41,885 | def delete_extra_files ( self , relpaths , cloud_objs ) : for cloud_obj in cloud_objs : if cloud_obj not in relpaths : if not self . test_run : self . delete_cloud_obj ( cloud_obj ) self . delete_count += 1 if not self . quiet or self . verbosity > 1 : print ( "Deleted: {0}" . format ( cloud_obj ) ) | Deletes any objects from the container that do not exist locally . |
41,886 | def delete_cloud_obj ( self , cloud_obj ) : self . _connection . delete_object ( container = self . container_name , obj = cloud_obj , ) | Deletes an object from the container . |
41,887 | def wipe_container ( self ) : if self . test_run : print ( "Wipe would delete {0} objects." . format ( len ( self . container . object_count ) ) ) else : if not self . quiet or self . verbosity > 1 : print ( "Deleting {0} objects..." . format ( len ( self . container . object_count ) ) ) self . _connection . delete_all_objects ( ) | Completely wipes out the contents of the container . |
41,888 | def print_tally ( self ) : self . update_count = self . upload_count - self . create_count if self . test_run : print ( "Test run complete with the following results:" ) print ( "Skipped {0}. Created {1}. Updated {2}. Deleted {3}." . format ( self . skip_count , self . create_count , self . update_count , self . delete_count ) ) | Prints the final tally to stdout . |
41,889 | def handle ( self , * args , ** options ) : self . _connection = Auth ( ) . _get_connection ( ) if len ( args ) == 0 : containers = self . _connection . list_containers ( ) if not containers : print ( "No containers were found for this account." ) elif len ( args ) == 1 : containers = self . _connection . list_container_object_names ( args [ 0 ] ) if not containers : print ( "No matching container found." ) else : raise CommandError ( "Pass one and only one [container_name] as an argument" ) for container in containers : print ( container ) | Lists all the items in a container to stdout . |
41,890 | def progress_updater ( size , total ) : current_task . update_state ( state = state ( 'PROGRESS' ) , meta = dict ( size = size , total = total ) ) | Progress reporter for checksum verification . |
41,891 | def verify_checksum ( file_id , pessimistic = False , chunk_size = None , throws = True , checksum_kwargs = None ) : f = FileInstance . query . get ( uuid . UUID ( file_id ) ) if pessimistic : f . clear_last_check ( ) db . session . commit ( ) f . verify_checksum ( progress_callback = progress_updater , chunk_size = chunk_size , throws = throws , checksum_kwargs = checksum_kwargs ) db . session . commit ( ) | Verify checksum of a file instance . |
41,892 | def schedule_checksum_verification ( frequency = None , batch_interval = None , max_count = None , max_size = None , files_query = None , checksum_kwargs = None ) : assert max_count is not None or max_size is not None frequency = timedelta ( ** frequency ) if frequency else timedelta ( days = 30 ) if batch_interval : batch_interval = timedelta ( ** batch_interval ) else : celery_schedule = current_celery . conf . get ( 'CELERYBEAT_SCHEDULE' , { } ) batch_interval = batch_interval or next ( ( v [ 'schedule' ] for v in celery_schedule . values ( ) if v . get ( 'task' ) == schedule_checksum_verification . name ) , None ) if not batch_interval or not isinstance ( batch_interval , timedelta ) : raise Exception ( u'No "batch_interval" could be decided' ) total_batches = int ( frequency . total_seconds ( ) / batch_interval . total_seconds ( ) ) files = obj_or_import_string ( files_query , default = default_checksum_verification_files_query ) ( ) files = files . order_by ( sa . func . coalesce ( FileInstance . last_check_at , date . min ) ) if max_count is not None : all_files_count = files . count ( ) min_count = int ( math . ceil ( all_files_count / total_batches ) ) max_count = min_count if max_count == 0 else max_count if max_count < min_count : current_app . logger . warning ( u'The "max_count" you specified ({0}) is smaller than the ' 'minimum batch file count required ({1}) in order to achieve ' 'the file checks over the specified period ({2}).' . format ( max_count , min_count , frequency ) ) files = files . limit ( max_count ) if max_size is not None : all_files_size = db . session . query ( sa . func . sum ( FileInstance . size ) ) . scalar ( ) min_size = int ( math . ceil ( all_files_size / total_batches ) ) max_size = min_size if max_size == 0 else max_size if max_size < min_size : current_app . logger . warning ( u'The "max_size" you specified ({0}) is smaller than the ' 'minimum batch total file size required ({1}) in order to ' 'achieve the file checks over the specified period ({2}).' . format ( max_size , min_size , frequency ) ) files = files . yield_per ( 1000 ) scheduled_file_ids = [ ] total_size = 0 for f in files : scheduled_file_ids . append ( str ( f . id ) ) total_size += f . size if max_size and max_size <= total_size : break group ( verify_checksum . s ( file_id , pessimistic = True , throws = False , checksum_kwargs = ( checksum_kwargs or { } ) ) for file_id in scheduled_file_ids ) . apply_async ( ) | Schedule a batch of files for checksum verification . |
41,893 | def migrate_file ( src_id , location_name , post_fixity_check = False ) : location = Location . get_by_name ( location_name ) f_src = FileInstance . get ( src_id ) f_dst = FileInstance . create ( ) db . session . commit ( ) try : f_dst . copy_contents ( f_src , progress_callback = progress_updater , default_location = location . uri , ) db . session . commit ( ) except Exception : db . session . delete ( f_dst ) db . session . commit ( ) raise ObjectVersion . relink_all ( f_src , f_dst ) db . session . commit ( ) if post_fixity_check : verify_checksum . delay ( str ( f_dst . id ) ) | Task to migrate a file instance to a new location . |
41,894 | def remove_file_data ( file_id , silent = True ) : try : f = FileInstance . get ( file_id ) if not f . writable : return f . delete ( ) db . session . commit ( ) f . storage ( ) . delete ( ) except IntegrityError : if not silent : raise | Remove file instance and associated data . |
41,895 | def merge_multipartobject ( upload_id , version_id = None ) : mp = MultipartObject . query . filter_by ( upload_id = upload_id ) . one_or_none ( ) if not mp : raise RuntimeError ( 'Upload ID does not exists.' ) if not mp . completed : raise RuntimeError ( 'MultipartObject is not completed.' ) try : obj = mp . merge_parts ( version_id = version_id , progress_callback = progress_updater ) db . session . commit ( ) return str ( obj . version_id ) except Exception : db . session . rollback ( ) raise | Merge multipart object . |
41,896 | def remove_expired_multipartobjects ( ) : delta = current_app . config [ 'FILES_REST_MULTIPART_EXPIRES' ] expired_dt = datetime . utcnow ( ) - delta file_ids = [ ] for mp in MultipartObject . query_expired ( expired_dt ) : file_ids . append ( str ( mp . file_id ) ) mp . delete ( ) for fid in file_ids : remove_file_data . delay ( fid ) | Remove expired multipart objects . |
41,897 | def pyfs_storage_factory ( fileinstance = None , default_location = None , default_storage_class = None , filestorage_class = PyFSFileStorage , fileurl = None , size = None , modified = None , clean_dir = True ) : assert fileinstance or ( fileurl and size ) if fileinstance : fileurl = None size = fileinstance . size modified = fileinstance . updated if fileinstance . uri : fileurl = fileinstance . uri else : assert default_location fileurl = make_path ( default_location , str ( fileinstance . id ) , 'data' , current_app . config [ 'FILES_REST_STORAGE_PATH_DIMENSIONS' ] , current_app . config [ 'FILES_REST_STORAGE_PATH_SPLIT_LENGTH' ] , ) return filestorage_class ( fileurl , size = size , modified = modified , clean_dir = clean_dir ) | Get factory function for creating a PyFS file storage instance . |
41,898 | def _get_fs ( self , create_dir = True ) : filedir = dirname ( self . fileurl ) filename = basename ( self . fileurl ) return ( opener . opendir ( filedir , writeable = True , create_dir = create_dir ) , filename ) | Return tuple with filesystem and filename . |
41,899 | def open ( self , mode = 'rb' ) : fs , path = self . _get_fs ( ) return fs . open ( path , mode = mode ) | Open file . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.