idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
31,700
def _create_ssh_keys ( self ) : ret , _ , _ = utils . run_command ( [ 'ssh-keygen' , '-t' , 'rsa' , '-m' , 'PEM' , '-N' , '' , '-f' , self . paths . ssh_id_rsa ( ) , ] ) if ret != 0 : raise RuntimeError ( 'Failed to crate ssh keys at %s' , self . paths . ssh_id_rsa ( ) , )
Generate a pair of ssh keys for this prefix
31,701
def cleanup ( self ) : with LogTask ( 'Stop prefix' ) : self . stop ( ) with LogTask ( "Tag prefix as uninitialized" ) : os . unlink ( self . paths . prefix_lagofile ( ) )
Stops any running entities in the prefix and uninitializes it usually you want to do this if you are going to remove the prefix afterwards
31,702
def _init_net_specs ( conf ) : for net_name , net_spec in conf . get ( 'nets' , { } ) . items ( ) : net_spec [ 'name' ] = net_name net_spec [ 'mapping' ] = { } net_spec . setdefault ( 'type' , 'nat' ) return conf
Given a configuration specification initializes all the net definitions in it so they can be used comfortably
31,703
def _allocate_subnets ( self , conf ) : allocated_subnets = [ ] try : for net_spec in conf . get ( 'nets' , { } ) . itervalues ( ) : if net_spec [ 'type' ] != 'nat' : continue gateway = net_spec . get ( 'gw' ) if gateway : allocated_subnet = self . _subnet_store . acquire ( self . paths . uuid ( ) , gateway ) else : al...
Allocate all the subnets needed by the given configuration spec
31,704
def _select_mgmt_networks ( self , conf ) : nets = conf [ 'nets' ] mgmts = sorted ( [ name for name , net in nets . iteritems ( ) if net . get ( 'management' ) is True ] ) if len ( mgmts ) == 0 : mgmt_name = sorted ( ( nets . keys ( ) ) ) [ 0 ] LOGGER . debug ( 'No management network configured, selecting network %s' ,...
Select management networks . If no management network is found it will mark the first network found by sorted the network lists . Also adding default DNS domain if none is set .
31,705
def _register_preallocated_ips ( self , conf ) : for dom_name , dom_spec in conf . get ( 'domains' , { } ) . items ( ) : for idx , nic in enumerate ( dom_spec . get ( 'nics' , [ ] ) ) : if 'ip' not in nic : continue net = conf [ 'nets' ] [ nic [ 'net' ] ] if self . _subnet_store . is_leasable_subnet ( net [ 'gw' ] ) : ...
Parse all the domains in the given conf and preallocate all their ips into the networks mappings raising exception on duplicated ips or ips out of the allowed ranges
31,706
def _allocate_ips_to_nics ( self , conf ) : for dom_name , dom_spec in conf . get ( 'domains' , { } ) . items ( ) : for idx , nic in enumerate ( dom_spec . get ( 'nics' , [ ] ) ) : if 'ip' in nic : continue net = self . _get_net ( conf , dom_name , nic ) if net [ 'type' ] != 'nat' : continue allocated = net [ 'mapping'...
For all the nics of all the domains in the conf that have dynamic ip allocate one and addit to the network mapping
31,707
def _set_mtu_to_nics ( self , conf ) : for dom_name , dom_spec in conf . get ( 'domains' , { } ) . items ( ) : for idx , nic in enumerate ( dom_spec . get ( 'nics' , [ ] ) ) : net = self . _get_net ( conf , dom_name , nic ) mtu = net . get ( 'mtu' , 1500 ) if mtu != 1500 : nic [ 'mtu' ] = mtu
For all the nics of all the domains in the conf that have MTU set save the MTU on the NIC definition .
31,708
def _config_net_topology ( self , conf ) : conf = self . _init_net_specs ( conf ) mgmts = self . _select_mgmt_networks ( conf ) self . _validate_netconfig ( conf ) allocated_subnets , conf = self . _allocate_subnets ( conf ) try : self . _add_mgmt_to_domains ( conf , mgmts ) self . _register_preallocated_ips ( conf ) s...
Initialize and populate all the network related elements like reserving ips and populating network specs of the given confiiguration spec
31,709
def _validate_netconfig ( self , conf ) : nets = conf . get ( 'nets' , { } ) if len ( nets ) == 0 : raise LagoInitException ( 'No networks configured.' ) no_mgmt_dns = [ name for name , net in nets . iteritems ( ) if net . get ( 'management' , None ) is None and ( net . get ( 'main_dns' ) or net . get ( 'dns_domain_nam...
Validate network configuration
31,710
def _create_disk ( self , name , spec , template_repo = None , template_store = None , ) : LOGGER . debug ( "Spec: %s" % spec ) with LogTask ( "Create disk %s" % spec [ 'name' ] ) : disk_metadata = { } if spec [ 'type' ] == 'template' : disk_path , disk_metadata = self . _handle_template ( host_name = name , template_s...
Creates a disc with the given name from the given repo or store
31,711
def _ova_to_spec ( self , filename ) : ova_extracted_dir = os . path . splitext ( filename ) [ 0 ] if not os . path . exists ( ova_extracted_dir ) : os . makedirs ( ova_extracted_dir ) subprocess . check_output ( [ "tar" , "-xvf" , filename , "-C" , ova_extracted_dir ] , stderr = subprocess . STDOUT ) ovf = glob . glob...
Retrieve the given ova and makes a template of it . Creates a disk from network provided ova . Calculates the needed memory from the ovf . The disk will be cached in the template repo
31,712
def _use_prototype ( self , spec , prototypes ) : prototype = spec [ 'based-on' ] del spec [ 'based-on' ] for attr in prototype : if attr not in spec : spec [ attr ] = copy . deepcopy ( prototype [ attr ] ) return spec
Populates the given spec with the values of it s declared prototype
31,713
def fetch_url ( self , url ) : url_path = urlparse . urlsplit ( url ) . path dst_path = os . path . basename ( url_path ) dst_path = self . paths . prefixed ( dst_path ) with LogTask ( 'Downloading %s' % url ) : urllib . urlretrieve ( url = os . path . expandvars ( url ) , filename = dst_path ) return dst_path
Retrieves the given url to the prefix
31,714
def export_vms ( self , vms_names = None , standalone = False , export_dir = '.' , compress = False , init_file_name = 'LagoInitFile' , out_format = YAMLOutFormatPlugin ( ) , collect_only = False , with_threads = True , ) : return self . virt_env . export_vms ( vms_names , standalone , export_dir , compress , init_file...
Export vm images disks and init file . The exported images and init file can be used to recreate the environment .
31,715
def shutdown ( self , vm_names = None , reboot = False ) : self . virt_env . shutdown ( vm_names , reboot )
Shutdown this prefix
31,716
def virt_env ( self ) : if self . _virt_env is None : self . _virt_env = self . _create_virt_env ( ) return self . _virt_env
Getter for this instance s virt env creates it if needed
31,717
def destroy ( self ) : subnets = ( str ( net . gw ( ) ) for net in self . virt_env . get_nets ( ) . itervalues ( ) ) self . _subnet_store . release ( subnets ) self . cleanup ( ) shutil . rmtree ( self . paths . prefix_path ( ) )
Destroy this prefix running any cleanups and removing any files inside it .
31,718
def is_prefix ( cls , path ) : lagofile = paths . Paths ( path ) . prefix_lagofile ( ) return os . path . isfile ( lagofile )
Check if a path is a valid prefix
31,719
def _get_scripts ( self , host_metadata ) : deploy_scripts = host_metadata . get ( 'deploy-scripts' , [ ] ) if deploy_scripts : return deploy_scripts ovirt_scripts = host_metadata . get ( 'ovirt-scripts' , [ ] ) if ovirt_scripts : warnings . warn ( 'Deprecated entry "ovirt-scripts" will not be supported in ' 'the futur...
Temporary method to retrieve the host scripts
31,720
def _set_scripts ( self , host_metadata , scripts ) : scripts_key = 'deploy-scripts' if 'ovirt-scritps' in host_metadata : scripts_key = 'ovirt-scripts' host_metadata [ scripts_key ] = scripts return host_metadata
Temporary method to set the host scripts
31,721
def _copy_deploy_scripts_for_hosts ( self , domains ) : with LogTask ( 'Copying any deploy scripts' ) : for host_name , host_spec in domains . iteritems ( ) : host_metadata = host_spec . get ( 'metadata' , { } ) deploy_scripts = self . _get_scripts ( host_metadata ) new_scripts = self . _copy_delpoy_scripts ( deploy_sc...
Copy the deploy scripts for all the domains into the prefix scripts dir
31,722
def _copy_delpoy_scripts ( self , scripts ) : if not os . path . exists ( self . paths . scripts ( ) ) : os . makedirs ( self . paths . scripts ( ) ) new_scripts = [ ] for script in scripts : script = os . path . expandvars ( script ) if not os . path . exists ( script ) : raise RuntimeError ( 'Script %s does not exist...
Copy the given deploy scripts to the scripts dir in the prefix
31,723
def update_args ( self , args ) : for arg in vars ( args ) : if self . get ( arg ) and getattr ( args , arg ) is not None : self . _config [ self . root_section ] [ arg ] = getattr ( args , arg )
Update config dictionary with parsed args as resolved by argparse . Only root positional arguments that already exist will overridden .
31,724
def update_parser ( self , parser ) : self . _parser = parser ini_str = argparse_to_ini ( parser ) configp = configparser . ConfigParser ( allow_no_value = True ) configp . read_dict ( self . _config ) configp . read_string ( ini_str ) self . _config . update ( { s : dict ( configp . items ( s ) ) for s in configp . se...
Update config dictionary with declared arguments in an argparse . parser New variables will be created and existing ones overridden .
31,725
def _request_submit ( self , func , ** kwargs ) : resp = func ( headers = self . _get_headers ( ) , ** kwargs ) self . _log_response_from_method ( func . __name__ , resp ) self . _validate_response_success ( resp ) return resp
A helper function that will wrap any requests we make .
31,726
def add_records ( self , domain , records ) : url = self . API_TEMPLATE + self . RECORDS . format ( domain = domain ) self . _patch ( url , json = records ) self . logger . debug ( 'Added records @ {}' . format ( records ) ) return True
Adds the specified DNS records to a domain .
31,727
def get_domain_info ( self , domain ) : url = self . API_TEMPLATE + self . DOMAIN_INFO . format ( domain = domain ) return self . _get_json_from_response ( url )
Get the GoDaddy supplied information about a specific domain .
31,728
def get_domains ( self ) : url = self . API_TEMPLATE + self . DOMAINS data = self . _get_json_from_response ( url ) domains = list ( ) for item in data : domain = item [ 'domain' ] domains . append ( domain ) self . logger . debug ( 'Discovered domains: {}' . format ( domain ) ) return domains
Returns a list of domains for the authenticated user .
31,729
def replace_records ( self , domain , records , record_type = None , name = None ) : url = self . _build_record_url ( domain , name = name , record_type = record_type ) self . _put ( url , json = records ) return True
This will replace all records at the domain . Record type and record name can be provided to filter which records to replace .
31,730
def update_record ( self , domain , record , record_type = None , name = None ) : if record_type is None : record_type = record [ 'type' ] if name is None : name = record [ 'name' ] url = self . API_TEMPLATE + self . RECORDS_TYPE_NAME . format ( domain = domain , type = record_type , name = name ) self . _put ( url , j...
Call to GoDaddy API to update a single DNS record
31,731
def parse_ports ( ports_text ) : ports_set = set ( ) for bit in ports_text . split ( ',' ) : if '-' in bit : low , high = bit . split ( '-' , 1 ) ports_set = ports_set . union ( range ( int ( low ) , int ( high ) + 1 ) ) else : ports_set . add ( int ( bit ) ) return sorted ( list ( ports_set ) )
Parse ports text
31,732
def make_server ( server_class , handler_class , authorizer_class , filesystem_class , host_port , file_access_user = None , ** handler_options ) : from . import compat if isinstance ( handler_class , compat . string_type ) : handler_class = import_class ( handler_class ) if isinstance ( authorizer_class , compat . str...
make server instance
31,733
def apply ( cls , fs ) : logger . debug ( 'Patching %s with %s.' , fs . __class__ . __name__ , cls . __name__ ) fs . _patch = cls for method_name in cls . patch_methods : origin = getattr ( fs , method_name ) method = getattr ( cls , method_name ) bound_method = method . __get__ ( fs , fs . __class__ ) setattr ( fs , m...
replace bound methods of fs .
31,734
def _exists ( self , path ) : if path . endswith ( '/' ) : return True return self . storage . exists ( path )
S3 directory is not S3Ojbect .
31,735
def apply_patch ( self ) : patch = self . patches . get ( self . storage . __class__ . __name__ ) if patch : patch . apply ( self )
apply adjustment patch for storage
31,736
def has_user ( self , username ) : return self . model . objects . filter ( ** self . _filter_user_by ( username ) ) . exists ( )
return True if exists user .
31,737
def get_account ( self , username ) : try : account = self . model . objects . get ( ** self . _filter_user_by ( username ) ) except self . model . DoesNotExist : return None return account
return user by username .
31,738
def validate_authentication ( self , username , password , handler ) : user = authenticate ( ** { self . username_field : username , 'password' : password } ) account = self . get_account ( username ) if not ( user and account ) : raise AuthenticationFailed ( "Authentication failed." )
authenticate user with password
31,739
def get_msg_login ( self , username ) : account = self . get_account ( username ) if account : account . update_last_login ( ) account . save ( ) return 'welcome.'
message for welcome .
31,740
def has_perm ( self , username , perm , path = None ) : account = self . get_account ( username ) return account and account . has_perm ( perm , path )
check user permission
31,741
def get_perms ( self , username ) : account = self . get_account ( username ) return account and account . get_perms ( )
return user permissions
31,742
def impersonate_user ( self , username , password ) : if self . personate_user : self . personate_user . impersonate_user ( username , password )
delegate to personate_user method
31,743
def hex_to_rgb ( self , h ) : rgb = ( self . hex_to_red ( h ) , self . hex_to_green ( h ) , self . hex_to_blue ( h ) ) return rgb
Converts a valid hex color string to an RGB array .
31,744
def cross_product ( self , p1 , p2 ) : return ( p1 . x * p2 . y - p1 . y * p2 . x )
Returns the cross product of two XYPoints .
31,745
def get_distance_between_two_points ( self , one , two ) : dx = one . x - two . x dy = one . y - two . y return math . sqrt ( dx * dx + dy * dy )
Returns the distance between two XYPoints .
31,746
def get_xy_point_from_rgb ( self , red_i , green_i , blue_i ) : red = red_i / 255.0 green = green_i / 255.0 blue = blue_i / 255.0 r = ( ( red + 0.055 ) / ( 1.0 + 0.055 ) ) ** 2.4 if ( red > 0.04045 ) else ( red / 12.92 ) g = ( ( green + 0.055 ) / ( 1.0 + 0.055 ) ) ** 2.4 if ( green > 0.04045 ) else ( green / 12.92 ) b ...
Returns an XYPoint object containing the closest available CIE 1931 x y coordinates based on the RGB input values .
31,747
def hex_to_xy ( self , h ) : rgb = self . color . hex_to_rgb ( h ) return self . rgb_to_xy ( rgb [ 0 ] , rgb [ 1 ] , rgb [ 2 ] )
Converts hexadecimal colors represented as a String to approximate CIE 1931 x and y coordinates .
31,748
def rgb_to_xy ( self , red , green , blue ) : point = self . color . get_xy_point_from_rgb ( red , green , blue ) return ( point . x , point . y )
Converts red green and blue integer values to approximate CIE 1931 x and y coordinates .
31,749
def get_random_xy_color ( self ) : r = self . color . random_rgb_value ( ) g = self . color . random_rgb_value ( ) b = self . color . random_rgb_value ( ) return self . rgb_to_xy ( r , g , b )
Returns the approximate CIE 1931 x y coordinates represented by the supplied hexColor parameter or of a random color if the parameter is not passed .
31,750
def become_daemon ( * args , ** kwargs ) : if django . VERSION >= ( 1 , 9 ) : from . daemonize import become_daemon else : from django . utils . daemonize import become_daemon return become_daemon ( * args , ** kwargs )
become_daemon function wrapper
31,751
def setUpClass ( cls ) : self . obsmode = None self . spectrum = None self . bp = None self . sp = None self . obs = None self . setup2 ( )
Always overridden by the child cases but let s put some real values in here to test with
31,752
def validate ( self ) : msg = list ( ) previously_seen = set ( ) currently_seen = set ( [ 1 ] ) problemset = set ( ) while currently_seen : node = currently_seen . pop ( ) if node in previously_seen : problemset . add ( node ) else : previously_seen . add ( node ) self . add_descendants ( node , currently_seen ) unreac...
Simulataneously checks for loops and unreachable nodes
31,753
def set_default_waveset ( minwave = 500 , maxwave = 26000 , num = 10000 , delta = None , log = True ) : global _default_waveset global _default_waveset_str num = int ( num ) s = 'Min: %s, Max: %s, Num: %s, Delta: %s, Log: %s' if log and not delta : s = s % tuple ( [ str ( x ) for x in ( minwave , maxwave , num , None ,...
Set the default wavelength set pysynphot . refs . _default_waveset .
31,754
def _set_default_refdata ( ) : global GRAPHTABLE , COMPTABLE , THERMTABLE , PRIMARY_AREA try : GRAPHTABLE = _refTable ( os . path . join ( 'mtab' , '*_tmg.fits' ) ) COMPTABLE = _refTable ( os . path . join ( 'mtab' , '*_tmc.fits' ) ) except IOError as e : GRAPHTABLE = None COMPTABLE = None warnings . warn ( 'No graph o...
Default refdata set on import .
31,755
def setref ( graphtable = None , comptable = None , thermtable = None , area = None , waveset = None ) : global GRAPHTABLE , COMPTABLE , THERMTABLE , PRIMARY_AREA , GRAPHDICT , COMPDICT , THERMDICT GRAPHDICT = { } COMPDICT = { } THERMDICT = { } kwds = set ( [ graphtable , comptable , thermtable , area , waveset ] ) if ...
Set default graph and component tables primary area and wavelength set .
31,756
def getref ( ) : ans = dict ( graphtable = GRAPHTABLE , comptable = COMPTABLE , thermtable = THERMTABLE , area = PRIMARY_AREA , waveset = _default_waveset_str ) return ans
Current default values for graph and component tables primary area and wavelength set .
31,757
def read_kwfile ( fname ) : d = { } f = open ( fname ) for line in f : try : kvpair = re . findall ( "(.*):: (.*)=(.*)$" , line ) [ 0 ] d [ 'name' ] = os . path . basename ( kvpair [ 0 ] ) key , val = kvpair [ 1 : ] d [ key . lower ( ) ] = val except ( ValueError , IndexError ) : break f . close ( ) return d
Syntax used as of r452 in commissioning tests
31,758
def ObsBandpass ( obstring , graphtable = None , comptable = None , component_dict = { } ) : ob = ObservationMode ( obstring , graphtable = graphtable , comptable = comptable , component_dict = component_dict ) if len ( ob ) > 1 : return ObsModeBandpass ( ob ) else : return TabularSpectralElement ( ob . components [ 0 ...
Generate a bandpass object from observation mode .
31,759
def thermback ( self ) : sp = self . obsmode . ThermalSpectrum ( ) ans = sp . integrate ( ) * ( self . obsmode . pixscale ** 2 * self . obsmode . primary_area ) return ans
Calculate thermal background count rate for self . obsmode .
31,760
def MergeWaveSets ( waveset1 , waveset2 ) : if waveset1 is None and waveset2 is not None : MergedWaveSet = waveset2 elif waveset2 is None and waveset1 is not None : MergedWaveSet = waveset1 elif waveset1 is None and waveset2 is None : MergedWaveSet = None else : MergedWaveSet = N . union1d ( waveset1 , waveset2 ) delta...
Return the union of the two wavelength sets .
31,761
def trimSpectrum ( sp , minw , maxw ) : wave = sp . GetWaveSet ( ) flux = sp ( wave ) new_wave = N . compress ( wave >= minw , wave ) new_flux = N . compress ( wave >= minw , flux ) new_wave = N . compress ( new_wave <= maxw , new_wave ) new_flux = N . compress ( new_wave <= maxw , new_flux ) result = TabularSourceSpec...
Create a new spectrum with trimmed upper and lower ranges .
31,762
def trapezoidIntegration ( self , x , y ) : npoints = x . size if npoints > 0 : indices = N . arange ( npoints ) [ : - 1 ] deltas = x [ indices + 1 ] - x [ indices ] integrand = 0.5 * ( y [ indices + 1 ] + y [ indices ] ) * deltas sum = integrand . sum ( ) if x [ - 1 ] < x [ 0 ] : sum *= - 1.0 return sum else : return ...
Perform trapezoid integration .
31,763
def validate_wavetable ( self ) : wave = self . _wavetable if N . any ( wave <= 0 ) : wrong = N . where ( wave <= 0 ) [ 0 ] raise exceptions . ZeroWavelength ( 'Negative or Zero wavelength occurs in wavelength array' , rows = wrong ) sorted = N . sort ( wave ) if not N . alltrue ( sorted == wave ) : if N . alltrue ( so...
Enforce monotonic ascending wavelength array with no zero or negative values .
31,764
def validate_fluxtable ( self ) : if ( ( not self . fluxunits . isMag ) and ( self . _fluxtable . min ( ) < 0 ) ) : idx = N . where ( self . _fluxtable < 0 ) self . _fluxtable [ idx ] = 0.0 print ( "Warning, %d of %d bins contained negative fluxes; they " "have been set to zero." % ( len ( idx [ 0 ] ) , len ( self . _f...
Check for non - negative fluxes . If found the negative flux values are set to zero and a warning is printed to screen . This check is not done if flux unit is a magnitude because negative magnitude values are legal .
31,765
def addmag ( self , magval ) : if N . isscalar ( magval ) : factor = 10 ** ( - 0.4 * magval ) return self * factor else : raise TypeError ( ".addmag() only takes a constant scalar argument" )
Add a scalar magnitude to existing flux values .
31,766
def getArrays ( self ) : if hasattr ( self , 'primary_area' ) : area = self . primary_area else : area = None wave = self . GetWaveSet ( ) flux = self ( wave ) flux = units . Photlam ( ) . Convert ( wave , flux , self . fluxunits . name , area = area ) wave = units . Angstrom ( ) . Convert ( wave , self . waveunits . n...
Return wavelength and flux arrays in user units .
31,767
def validate_units ( self ) : if ( not isinstance ( self . waveunits , units . WaveUnits ) ) : raise TypeError ( "%s is not a valid WaveUnit" % self . waveunits ) if ( not isinstance ( self . fluxunits , units . FluxUnits ) ) : raise TypeError ( "%s is not a valid FluxUnit" % self . fluxunits )
Ensure that wavelenth and flux units belong to the correct classes .
31,768
def writefits ( self , filename , clobber = True , trimzero = True , binned = False , precision = None , hkeys = None ) : pcodes = { 'd' : 'D' , 's' : 'E' } if precision is None : precision = self . flux . dtype . char _precision = precision . lower ( ) [ 0 ] pcodes = { 'd' : 'D' , 's' : 'E' , 'f' : 'E' } if clobber : ...
Write the spectrum to a FITS table .
31,769
def integrate ( self , fluxunits = 'photlam' ) : u = self . fluxunits self . convert ( fluxunits ) wave , flux = self . getArrays ( ) self . convert ( u ) return self . trapezoidIntegration ( wave , flux )
Integrate the flux in given unit .
31,770
def convert ( self , targetunits ) : nunits = units . Units ( targetunits ) if nunits . isFlux : self . fluxunits = nunits else : self . waveunits = nunits
Set new user unit for either wavelength or flux .
31,771
def setMagnitude ( self , band , value ) : objectFlux = band . calcTotalFlux ( self ) vegaFlux = band . calcVegaFlux ( ) magDiff = - 2.5 * math . log10 ( objectFlux / vegaFlux ) factor = 10 ** ( - 0.4 * ( value - magDiff ) ) return self * factor
Makes the magnitude of the source in the band equal to value . band is a SpectralElement . This method is marked for deletion once the . renorm method is well tested .
31,772
def tabulate ( self ) : sp = ArraySourceSpectrum ( wave = self . wave , flux = self . flux , waveunits = self . waveunits , fluxunits = self . fluxunits , name = '%s (tabulated)' % self . name ) return sp
Return a simplified version of the spectrum .
31,773
def _readASCII ( self , filename ) : self . waveunits = units . Units ( 'angstrom' ) self . fluxunits = units . Units ( 'flam' ) wlist , flist = self . _columnsFromASCII ( filename ) self . _wavetable = N . array ( wlist , dtype = N . float64 ) self . _fluxtable = N . array ( flist , dtype = N . float64 )
ASCII files have no headers . Following synphot this routine will assume the first column is wavelength in Angstroms and the second column is flux in Flam .
31,774
def redshift ( self , z ) : tmp = SourceSpectrum . redshift ( self , z ) ans = FlatSpectrum ( tmp . flux . max ( ) , fluxunits = tmp . fluxunits ) return ans
Apply redshift to the flat spectrum .
31,775
def validate_units ( self ) : if ( not isinstance ( self . waveunits , units . WaveUnits ) ) : raise TypeError ( "%s is not a valid WaveUnit" % self . waveunits )
Ensure that wavelenth unit belongs to the correct class . There is no check for throughput because it is unitless .
31,776
def integrate ( self , wave = None ) : if wave is None : wave = self . wave ans = self . trapezoidIntegration ( wave , self ( wave ) ) return ans
Integrate the throughput over the specified wavelength set . If no wavelength set is specified the built - in one is used .
31,777
def convert ( self , targetunits ) : nunits = units . Units ( targetunits ) self . waveunits = nunits
Set new user unit for wavelength only .
31,778
def sample ( self , wave ) : angwave = self . waveunits . ToAngstrom ( wave ) return self . __call__ ( angwave )
Sample the spectrum .
31,779
def writefits ( self , * args , ** kwargs ) : old_wave = self . wave self . wave = self . _wavetable try : super ( UniformTransmission , self ) . writefits ( * args , ** kwargs ) finally : self . wave = old_wave
Write to file using default waveset .
31,780
def ToInternal ( self ) : self . validate_units ( ) savewunits = self . waveunits angwave = self . waveunits . Convert ( self . _wavetable , 'angstrom' ) self . _wavetable = angwave . copy ( ) self . waveunits = savewunits
Convert wavelengths to the internal representation of angstroms . For internal use only .
31,781
def sample ( self , wavelength ) : wave = self . waveunits . Convert ( wavelength , 'angstrom' ) return self ( wave )
Input wavelengths assumed to be in user unit .
31,782
def Throughput ( self ) : try : throughput = spectrum . TabularSpectralElement ( ) product = self . _multiplyThroughputs ( 0 ) throughput . _wavetable = product . GetWaveSet ( ) throughput . _throughputtable = product ( throughput . _wavetable ) throughput . waveunits = product . waveunits throughput . name = '*' . joi...
Combined throughput from multiplying all the components together .
31,783
def ThermalSpectrum ( self ) : try : thom = _ThermalObservationMode ( self . _obsmode ) self . pixscale = thom . pixscale return thom . _getSpectrum ( ) except IndexError : raise IndexError ( "Cannot calculate thermal spectrum; graphtable may be broken" )
Calculate thermal spectrum .
31,784
def _multiplyThroughputs ( self ) : index = 0 for component in self . components : if component . throughput != None : break index += 1 return BaseObservationMode . _multiplyThroughputs ( self , index )
Overrides base class in order to deal with opaque components .
31,785
def reverse ( d ) : r = { } for k in d : r [ d [ k ] ] = k return r
Return a reverse lookup dictionary for the input dictionary
31,786
def print_red_laws ( ) : laws = { } for k in Cache . RedLaws : if isinstance ( Cache . RedLaws [ k ] , str ) : Cache . RedLaws [ k ] = RedLaw ( Cache . RedLaws [ k ] ) laws [ str ( k ) ] = Cache . RedLaws [ k ] . litref maxname = max ( [ len ( name ) for name in laws . keys ( ) ] ) maxref = max ( [ len ( ref ) for ref ...
Print available extinction laws to screen .
31,787
def Extinction ( extval , name = None ) : try : ext = Cache . RedLaws [ name ] . reddening ( extval ) except AttributeError : Cache . RedLaws [ name ] = RedLaw ( Cache . RedLaws [ name ] ) ext = Cache . RedLaws [ name ] . reddening ( extval ) except KeyError : try : Cache . RedLaws [ name ] = RedLaw ( name ) ext = Cach...
Generate extinction curve to be used with spectra .
31,788
def _getWaveProp ( self ) : wave = units . Angstrom ( ) . Convert ( self . _wavetable , self . waveunits . name ) return wave
Return wavelength in user units .
31,789
def reddening ( self , extval ) : T = 10.0 ** ( - 0.4 * extval * self . obscuration ) ans = ExtinctionSpectralElement ( wave = self . wave , waveunits = self . waveunits , throughput = T , name = '%s(EBV=%g)' % ( self . name , extval ) ) ans . citation = self . litref return ans
Compute the reddening for the given extinction .
31,790
def GetNextNode ( self , modes , innode ) : nodes = N . where ( self . innodes == innode ) if nodes [ 0 ] . size == 0 : return - 1 defaultindex = N . where ( self . keywords [ nodes ] == 'default' ) if len ( defaultindex [ 0 ] ) != 0 : outnode = self . outnodes [ nodes [ 0 ] [ defaultindex [ 0 ] ] ] for mode in modes :...
GetNextNode returns the outnode that matches an element from the modes list starting at the given innode . This method isnt actually used its just a helper method for debugging purposes .
31,791
def GetComponentsFromGT ( self , modes , innode ) : components = [ ] thcomponents = [ ] outnode = 0 inmodes = set ( modes ) used_modes = set ( ) count = 0 while outnode >= 0 : if ( DEBUG and ( outnode < 0 ) ) : print ( "outnode == %d: stop condition" % outnode ) previous_outnode = outnode nodes = N . where ( self . inn...
Obtain components from graph table for the given observation mode keywords and starting node .
31,792
def fincre ( oldname ) : x = re . search ( '_(?P<version>[0-9][0-9][0-9])_syn' , oldname ) version = x . group ( 'version' ) newversion = "%03d" % ( int ( version ) + 1 ) ans = oldname . replace ( version , newversion ) return ans
Increment the synphot version number from a filename
31,793
def run_crbox ( self , spstring , form , output = "" , wavecat = "INDEF" , lowave = 0 , hiwave = 30000 ) : range = hiwave - lowave midwave = range / 2.0 iraf . countrate ( spectrum = spstring , magnitude = "" , instrument = "box(%f,%f)" % ( midwave , range ) , form = form , wavecat = wavecat , output = output )
Calcspec has a bug . We will use countrate instead and force it to use a box function of uniform transmission as the obsmode .
31,794
def validate_overlap ( comp1 , comp2 , force ) : warnings = dict ( ) if force is None : stat = comp2 . check_overlap ( comp1 ) if stat == 'full' : pass elif stat == 'partial' : raise ( exceptions . PartialOverlap ( 'Spectrum and bandpass do not fully overlap. You may use force=[extrap|taper] to force this Observation a...
Validate the overlap between the wavelength sets of the two given components .
31,795
def validate_overlap ( self , force ) : self . spectrum , self . bandpass , warn = validate_overlap ( self . spectrum , self . bandpass , force ) self . warnings . update ( warn )
Validate that spectrum and bandpass overlap . Warnings are stored in self . warnings .
31,796
def initbinset ( self , binset = None ) : if binset is None : msg = "(%s) does not have a defined binset in the wavecat table. The waveset of the spectrum will be used instead." % str ( self . bandpass ) try : self . binwave = self . bandpass . binset except ( KeyError , AttributeError ) : self . binwave = self . spect...
Set self . binwave .
31,797
def initbinflux ( self ) : endpoints = binning . calculate_bin_edges ( self . binwave ) spwave = spectrum . MergeWaveSets ( self . wave , endpoints ) spwave = spectrum . MergeWaveSets ( spwave , self . binwave ) indices = np . searchsorted ( spwave , endpoints ) self . _indices = indices [ : - 1 ] self . _indices_last ...
Calculate binned flux and edges .
31,798
def as_spectrum ( self , binned = True ) : if binned : wave , flux = self . binwave , self . binflux else : wave , flux = self . wave , self . flux result = ArraySourceSpectrum ( wave , flux , self . waveunits , self . fluxunits , name = self . name , keepneg = True ) return result
Reduce the observation to a simple spectrum object .
31,799
def irafconvert ( iraffilename ) : convertdict = CONVERTDICT if not iraffilename . lower ( ) . startswith ( ( 'http' , 'ftp' ) ) : iraffilename = os . path . normpath ( iraffilename ) if iraffilename . startswith ( '$' ) : pat = re . compile ( r'\$(\w*)' ) match = re . match ( pat , iraffilename ) dirname = match . gro...
Convert the IRAF file name to its Unix equivalent .