idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
4,600
def bounds ( self ) -> typing . Tuple [ typing . Tuple [ float , float ] , typing . Tuple [ float , float ] ] : ...
Return the bounds property in relative coordinates .
4,601
def vector ( self ) -> typing . Tuple [ typing . Tuple [ float , float ] , typing . Tuple [ float , float ] ] : ...
Return the vector property in relative coordinates .
4,602
def add_widget_to_content ( self , widget ) : self . __section_content_column . add_spacing ( 4 ) self . __section_content_column . add ( widget )
Subclasses should call this to add content in the section s top level column .
4,603
def color_map_data ( self , data : numpy . ndarray ) -> None : self . __color_map_data = data self . update ( )
Set the data and mark the canvas item for updating .
4,604
def get_params ( self ) : "Parameters used to initialize the class" import inspect a = inspect . getargspec ( self . __init__ ) [ 0 ] out = dict ( ) for key in a [ 1 : ] : value = getattr ( self , "_%s" % key , None ) out [ key ] = value return out
Parameters used to initialize the class
4,605
def signature ( self ) : "Instance file name" kw = self . get_params ( ) keys = sorted ( kw . keys ( ) ) l = [ ] for k in keys : n = k [ 0 ] + k [ - 1 ] v = kw [ k ] if k == 'function_set' : v = "_" . join ( [ x . __name__ [ 0 ] + x . __name__ [ - 1 ] + str ( x . nargs ) for x in kw [ k ] ] ) elif k == 'population_clas...
Instance file name
4,606
def population ( self ) : "Class containing the population and all the individuals generated" try : return self . _p except AttributeError : self . _p = self . _population_class ( base = self , tournament_size = self . _tournament_size , classifier = self . classifier , labels = self . _labels , es_extra_test = self . ...
Class containing the population and all the individuals generated
4,607
def random_leaf ( self ) : "Returns a random variable with the associated weight" for i in range ( self . _number_tries_feasible_ind ) : var = np . random . randint ( self . nvar ) v = self . _random_leaf ( var ) if v is None : continue return v raise RuntimeError ( "Could not find a suitable random leaf" )
Returns a random variable with the associated weight
4,608
def stopping_criteria ( self ) : "Test whether the stopping criteria has been achieved." if self . stopping_criteria_tl ( ) : return True if self . generations < np . inf : inds = self . popsize * self . generations flag = inds <= len ( self . population . hist ) else : flag = False if flag : return True est = self . p...
Test whether the stopping criteria has been achieved .
4,609
def nclasses ( self , v ) : "Number of classes of v, also sets the labes" if not self . classifier : return 0 if isinstance ( v , list ) : self . _labels = np . arange ( len ( v ) ) return if not isinstance ( v , np . ndarray ) : v = tonparray ( v ) self . _labels = np . unique ( v ) return self . _labels . shape [ 0 ]
Number of classes of v also sets the labes
4,610
def predict ( self , v = None , X = None ) : if X is None : X = v v = None m = self . model ( v = v ) return m . predict ( X )
In classification this returns the classes in regression it is equivalent to the decision function
4,611
def serve ( application , host = '127.0.0.1' , port = 8080 ) : WSGIServer ( ( host , int ( port ) ) , application ) . serve_forever ( )
Gevent - based WSGI - HTTP server .
4,612
def get_subscribers ( obj ) : ctype = ContentType . objects . get_for_model ( obj ) return Subscription . objects . filter ( content_type = ctype , object_id = obj . pk )
Returns the subscribers for a given object .
4,613
def is_subscribed ( user , obj ) : if not user . is_authenticated ( ) : return False ctype = ContentType . objects . get_for_model ( obj ) try : Subscription . objects . get ( user = user , content_type = ctype , object_id = obj . pk ) except Subscription . DoesNotExist : return False return True
Returns True if the user is subscribed to the given object .
4,614
def _promote ( self , name , instantiate = True ) : metaclass = type ( self . __class__ ) contents = self . __dict__ . copy ( ) cls = metaclass ( str ( name ) , ( self . __class__ , ) , contents ) if instantiate : return cls ( ) return cls
Create a new subclass of Context which incorporates instance attributes and new descriptors . This promotes an instance and its instance attributes up to being a class with class attributes then returns an instance of that class .
4,615
def run ( self , candidates , parameters ) : traces = [ ] start_time = time . time ( ) if self . num_parallel_evaluations == 1 : for candidate_i in range ( len ( candidates ) ) : candidate = candidates [ candidate_i ] sim_var = dict ( zip ( parameters , candidate ) ) pyneuroml . pynml . print_comment_v ( '\n\n - RUN %...
Run simulation for each candidate This run method will loop through each candidate and run the simulation corresponding to its parameter values . It will populate an array called traces with the resulting voltage traces for the simulation and return it .
4,616
def prepare ( self , context ) : if __debug__ : log . debug ( "Assigning thread local request context." ) self . local . context = context
Executed prior to processing a request .
4,617
def simple ( application , host = '127.0.0.1' , port = 8080 ) : print ( "serving on http://{0}:{1}" . format ( host , port ) ) make_server ( host , int ( port ) , application ) . serve_forever ( )
Python - standard WSGI - HTTP server for testing purposes . The additional work performed here is to match the default startup output of waitress . This is not a production quality interface and will be have badly under load .
4,618
def iiscgi ( application ) : try : from wsgiref . handlers import IISCGIHandler except ImportError : print ( "Python 3.2 or newer is required." ) if not __debug__ : warnings . warn ( "Interactive debugging and other persistence-based processes will not work." ) IISCGIHandler ( ) . run ( application )
A specialized version of the reference WSGI - CGI server to adapt to Microsoft IIS quirks . This is not a production quality interface and will behave badly under load .
4,619
def serve ( application , host = '127.0.0.1' , port = 8080 , socket = None , ** options ) : if not socket : bindAddress = ( host , int ( port ) ) else : bindAddress = socket WSGIServer ( application , bindAddress = bindAddress , ** options ) . run ( )
Basic FastCGI support via flup . This web server has many many options . Please see the Flup project documentation for details .
4,620
def _get_method_kwargs ( self ) : method_kwargs = { 'user' : self . user , 'content_type' : self . ctype , 'object_id' : self . content_object . pk , } return method_kwargs
Helper method . Returns kwargs needed to filter the correct object .
4,621
def save ( self , * args , ** kwargs ) : method_kwargs = self . _get_method_kwargs ( ) try : subscription = Subscription . objects . get ( ** method_kwargs ) except Subscription . DoesNotExist : subscription = Subscription . objects . create ( ** method_kwargs ) return subscription
Adds a subscription for the given user to the given object .
4,622
def prepare ( self , context ) : if __debug__ : log . debug ( "Preparing request context." , extra = dict ( request = id ( context ) ) ) context . request = Request ( context . environ ) context . response = Response ( request = context . request ) context . environ [ 'web.base' ] = context . request . script_name cont...
Add the usual suspects to the context . This adds request response and path to the RequestContext instance .
4,623
def dispatch ( self , context , consumed , handler , is_endpoint ) : request = context . request if __debug__ : log . debug ( "Handling dispatch event." , extra = dict ( request = id ( context ) , consumed = consumed , handler = safe_name ( handler ) , endpoint = is_endpoint ) ) if not consumed and context . request . ...
Called as dispatch descends into a tier . The base extension uses this to maintain the current url .
4,624
def render_none ( self , context , result ) : context . response . body = b'' del context . response . content_length return True
Render empty responses .
4,625
def render_binary ( self , context , result ) : context . response . app_iter = iter ( ( result , ) ) return True
Return binary responses unmodified .
4,626
def render_file ( self , context , result ) : if __debug__ : log . debug ( "Processing file-like object." , extra = dict ( request = id ( context ) , result = repr ( result ) ) ) response = context . response response . conditional_response = True modified = mktime ( gmtime ( getmtime ( result . name ) ) ) response . l...
Perform appropriate metadata wrangling for returned open file handles .
4,627
def render_generator ( self , context , result ) : context . response . encoding = 'utf8' context . response . app_iter = ( ( i . encode ( 'utf8' ) if isinstance ( i , unicode ) else i ) for i in result if i is not None ) return True
Attempt to serve generator responses through stream encoding . This allows for direct use of cinje template functions which are generators as returned views .
4,628
def serve ( application , host = '127.0.0.1' , port = 8080 ) : server = CherryPyWSGIServer ( ( host , int ( port ) ) , application , server_name = host ) print ( "serving on http://{0}:{1}" . format ( host , port ) ) try : server . start ( ) except KeyboardInterrupt : server . stop ( )
CherryPy - based WSGI - HTTP server .
4,629
def colorize ( self , string , rgb = None , ansi = None , bg = None , ansi_bg = None ) : if not isinstance ( string , str ) : string = str ( string ) if rgb is None and ansi is None : raise TerminalColorMapException ( 'colorize: must specify one named parameter: rgb or ansi' ) if rgb is not None and ansi is not None : ...
Returns the colored string
4,630
def render_serialization ( self , context , result ) : resp = context . response serial = context . serialize match = context . request . accept . best_match ( serial . types , default_match = self . default ) result = serial [ match ] ( result ) if isinstance ( result , str ) : result = result . decode ( 'utf-8' ) res...
Render serialized responses .
4,631
def plot_iv_curve ( a , hold_v , i , * plt_args , ** plt_kwargs ) : grid = plt_kwargs . pop ( 'grid' , True ) same_fig = plt_kwargs . pop ( 'same_fig' , False ) if not len ( plt_args ) : plt_args = ( 'ko-' , ) if 'label' not in plt_kwargs : plt_kwargs [ 'label' ] = 'Current' if not same_fig : make_iv_curve_fig ( a , gr...
A single IV curve
4,632
def generic_insert_with_folder ( folder_name , file_name , template_name , args ) : if not os . path . isdir ( os . path . join ( args [ 'django_application_folder' ] , folder_name ) ) : os . mkdir ( os . path . join ( args [ 'django_application_folder' ] , folder_name ) ) codecs . open ( os . path . join ( args [ 'dja...
In general if we need to put a file on a folder we use this method
4,633
def serve ( application , host = '127.0.0.1' , port = 8080 , threads = 4 , ** kw ) : serve_ ( application , host = host , port = int ( port ) , threads = int ( threads ) , ** kw )
The recommended development HTTP server . Note that this server performs additional buffering and will not honour chunked encoding breaks .
4,634
def show ( self ) : from matplotlib import pyplot as plt if self . already_run : for ref in self . volts . keys ( ) : plt . plot ( self . t , self . volts [ ref ] , label = ref ) plt . title ( "Simulation voltage vs time" ) plt . legend ( ) plt . xlabel ( "Time [ms]" ) plt . ylabel ( "Voltage [mV]" ) else : pynml . pri...
Plot the result of the simulation once it s been intialized
4,635
def colorize ( string , rgb = None , ansi = None , bg = None , ansi_bg = None , fd = 1 ) : if colorize . fd != fd : colorize . init = False colorize . fd = fd if not colorize . init : colorize . init = True colorize . is_term = isatty ( fd ) if 'TERM' in environ : if environ [ 'TERM' ] . startswith ( 'xterm' ) : colori...
Returns the colored string to print on the terminal .
4,636
def mutate ( self , context , handler , args , kw ) : def cast ( arg , val ) : if arg not in annotations : return cast = annotations [ key ] try : val = cast ( val ) except ( ValueError , TypeError ) as e : parts = list ( e . args ) parts [ 0 ] = parts [ 0 ] + " processing argument '{}'" . format ( arg ) e . args = tup...
Inspect and potentially mutate the given handler s arguments . The args list and kw dictionary may be freely modified though invalid arguments to the handler will fail .
4,637
def transform ( self , context , handler , result ) : handler = handler . __func__ if hasattr ( handler , '__func__' ) else handler annotation = getattr ( handler , '__annotations__' , { } ) . get ( 'return' , None ) if annotation : return ( annotation , result ) return result
Transform the value returned by the controller endpoint . This extension transforms returned values if the endpoint has a return type annotation .
4,638
def execute_command_in_dir ( command , directory , verbose = DEFAULTS [ 'v' ] , prefix = "Output: " , env = None ) : if os . name == 'nt' : directory = os . path . normpath ( directory ) print_comment ( "Executing: (%s) in directory: %s" % ( command , directory ) , verbose ) if env is not None : print_comment ( "Extra ...
Execute a command in specific working directory
4,639
def after ( self , context , exc = None ) : duration = context . _duration = round ( ( time . time ( ) - context . _start_time ) * 1000 ) delta = unicode ( duration ) if self . header : context . response . headers [ self . header ] = delta if self . log : self . log ( "Response generated in " + delta + " seconds." , e...
Executed after dispatch has returned and the response populated prior to anything being sent to the client .
4,640
def _configure ( self , config ) : config = config or dict ( ) if 'extensions' not in config : config [ 'extensions' ] = list ( ) if not any ( isinstance ( ext , BaseExtension ) for ext in config [ 'extensions' ] ) : config [ 'extensions' ] . insert ( 0 , BaseExtension ( ) ) if not any ( isinstance ( ext , arguments . ...
Prepare the incoming configuration and ensure certain expected values are present . For example this ensures BaseExtension is included in the extension list and populates the logging config .
4,641
def _swap ( self ) : self . ref_start , self . qry_start = self . qry_start , self . ref_start self . ref_end , self . qry_end = self . qry_end , self . ref_end self . hit_length_ref , self . hit_length_qry = self . hit_length_qry , self . hit_length_ref self . ref_length , self . qry_length = self . qry_length , self ...
Swaps the alignment so that the reference becomes the query and vice - versa . Swaps their names coordinates etc . The frame is not changed
4,642
def qry_coords ( self ) : return pyfastaq . intervals . Interval ( min ( self . qry_start , self . qry_end ) , max ( self . qry_start , self . qry_end ) )
Returns a pyfastaq . intervals . Interval object of the start and end coordinates in the query sequence
4,643
def ref_coords ( self ) : return pyfastaq . intervals . Interval ( min ( self . ref_start , self . ref_end ) , max ( self . ref_start , self . ref_end ) )
Returns a pyfastaq . intervals . Interval object of the start and end coordinates in the reference sequence
4,644
def on_same_strand ( self ) : return ( self . ref_start < self . ref_end ) == ( self . qry_start < self . qry_end )
Returns true iff the direction of the alignment is the same in the reference and the query
4,645
def reverse_query ( self ) : self . qry_start = self . qry_length - self . qry_start - 1 self . qry_end = self . qry_length - self . qry_end - 1
Changes the coordinates as if the query sequence has been reverse complemented
4,646
def reverse_reference ( self ) : self . ref_start = self . ref_length - self . ref_start - 1 self . ref_end = self . ref_length - self . ref_end - 1
Changes the coordinates as if the reference sequence has been reverse complemented
4,647
def _nucmer_command ( self , ref , qry , outprefix ) : if self . use_promer : command = 'promer' else : command = 'nucmer' command += ' -p ' + outprefix if self . breaklen is not None : command += ' -b ' + str ( self . breaklen ) if self . diagdiff is not None and not self . use_promer : command += ' -D ' + str ( self ...
Construct the nucmer command
4,648
def _delta_filter_command ( self , infile , outfile ) : command = 'delta-filter' if self . min_id is not None : command += ' -i ' + str ( self . min_id ) if self . min_length is not None : command += ' -l ' + str ( self . min_length ) return command + ' ' + infile + ' > ' + outfile
Construct delta - filter command
4,649
def _show_coords_command ( self , infile , outfile ) : command = 'show-coords -dTlro' if not self . coords_header : command += ' -H' return command + ' ' + infile + ' > ' + outfile
Construct show - coords command
4,650
def _write_script ( self , script_name , ref , qry , outfile ) : f = pyfastaq . utils . open_file_write ( script_name ) print ( self . _nucmer_command ( ref , qry , 'p' ) , file = f ) print ( self . _delta_filter_command ( 'p.delta' , 'p.delta.filter' ) , file = f ) print ( self . _show_coords_command ( 'p.delta.filter...
Write commands into a bash script
4,651
def run ( self ) : qry = os . path . abspath ( self . qry ) ref = os . path . abspath ( self . ref ) outfile = os . path . abspath ( self . outfile ) tmpdir = tempfile . mkdtemp ( prefix = 'tmp.run_nucmer.' , dir = os . getcwd ( ) ) original_dir = os . getcwd ( ) os . chdir ( tmpdir ) script = 'run_nucmer.sh' self . _w...
Change to a temp directory Run bash script containing commands Place results in specified output file Clean up temp directory
4,652
def update_indel ( self , nucmer_snp ) : new_variant = Variant ( nucmer_snp ) if self . var_type not in [ INS , DEL ] or self . var_type != new_variant . var_type or self . qry_name != new_variant . qry_name or self . ref_name != new_variant . ref_name or self . reverse != new_variant . reverse : return False if self ....
Indels are reported over multiple lines 1 base insertion or deletion per line . This method extends the current variant by 1 base if it s an indel and adjacent to the new SNP and returns True . If the current variant is a SNP does nothing and returns False
4,653
def _request ( self , method , url , params = None , headers = None , data = None ) : if not params : params = { } if not headers : headers = { 'accept' : '*/*' } if method == 'POST' or method == 'PUT' : headers . update ( { 'Content-Type' : 'application/json' } ) try : response = requests . request ( method = method ,...
Common handler for all the HTTP requests .
4,654
def user_role ( name , rawtext , text , lineno , inliner , options = None , content = None ) : options = options or { } content = content or [ ] has_explicit_title , title , target = split_explicit_title ( text ) target = utils . unescape ( target ) . strip ( ) title = utils . unescape ( title ) . strip ( ) config = in...
Sphinx role for linking to a user profile . Defaults to linking to Github profiles but the profile URIS can be configured via the issues_user_uri config value .
4,655
def prepare ( doc ) : doc . mustache_files = doc . get_metadata ( 'mustache' ) if isinstance ( doc . mustache_files , basestring ) : if not doc . mustache_files : doc . mustache_files = None else : doc . mustache_files = [ doc . mustache_files ] if doc . mustache_files is not None : doc . mustache_hashes = [ yaml . loa...
Parse metadata to obtain list of mustache templates then load those templates .
4,656
def action ( elem , doc ) : if type ( elem ) == Str and doc . mhash is not None : elem . text = doc . mrenderer . render ( elem . text , doc . mhash ) return elem
Apply combined mustache template to all strings in document .
4,657
def get_callback ( self , renderer_context ) : request = renderer_context . get ( 'request' , None ) params = request and get_query_params ( request ) or { } return params . get ( self . callback_parameter , self . default_callback )
Determine the name of the callback to wrap around the json output .
4,658
def render ( self , data , accepted_media_type = None , renderer_context = None ) : renderer_context = renderer_context or { } callback = self . get_callback ( renderer_context ) json = super ( JSONPRenderer , self ) . render ( data , accepted_media_type , renderer_context ) return callback . encode ( self . charset ) ...
Renders into jsonp wrapping the json output in a callback function .
4,659
def to_jd ( year , week , day ) : return day + n_weeks ( SUN , gregorian . to_jd ( year - 1 , 12 , 28 ) , week )
Return Julian day count of given ISO year week and day
4,660
def weeks_per_year ( year ) : jan1 = jwday ( gregorian . to_jd ( year , 1 , 1 ) ) if jan1 == THU or ( jan1 == WED and isleap ( year ) ) : return 53 else : return 52
Number of ISO weeks in a year
4,661
def parse_path ( f1 , f2 ) : import glob f2 = f2 . strip ( ) if f2 == '' or f2 == '*' : f2 = './' if os . path . isdir ( f1 ) : f1 = os . path . join ( f1 , '*.??h' ) list1 = glob . glob ( f1 ) list1 = [ name for name in list1 if name [ - 1 ] == 'h' and name [ - 4 ] == '.' ] if os . path . isdir ( f2 ) : list2 = [ ] fo...
Parse two input arguments and return two lists of file names
4,662
def checkASN ( filename ) : extnType = filename [ filename . rfind ( '_' ) + 1 : filename . rfind ( '.' ) ] if isValidAssocExtn ( extnType ) : return True else : return False
Determine if the filename provided to the function belongs to an association .
4,663
def countinputs ( inputlist ) : numInputs = 0 numASNfiles = 0 files = irafglob ( inputlist , atfile = None ) numInputs = len ( files ) for file in files : if ( checkASN ( file ) == True ) : numASNfiles += 1 return numInputs , numASNfiles
Determine the number of inputfiles provided by the user and the number of those files that are association tables
4,664
def summary ( logfile , time_format ) : "show a summary of all projects" def output ( summary ) : width = max ( [ len ( p [ 0 ] ) for p in summary ] ) + 3 print '\n' . join ( [ "%s%s%s" % ( p [ 0 ] , ' ' * ( width - len ( p [ 0 ] ) ) , colored ( minutes_to_txt ( p [ 1 ] ) , 'red' ) ) for p in summary ] ) output ( serve...
show a summary of all projects
4,665
def status ( logfile , time_format ) : "show current status" try : r = read ( logfile , time_format ) [ - 1 ] if r [ 1 ] [ 1 ] : return summary ( logfile , time_format ) else : print "working on %s" % colored ( r [ 0 ] , attrs = [ 'bold' ] ) print " since %s" % colored ( server . date_to_txt ( r [ 1 ] [ 0 ] , time_...
show current status
4,666
def stop ( logfile , time_format ) : "stop tracking for the active project" def save_and_output ( records ) : records = server . stop ( records ) write ( records , logfile , time_format ) def output ( r ) : print "worked on %s" % colored ( r [ 0 ] , attrs = [ 'bold' ] ) print " from %s" % colored ( server . date_to...
stop tracking for the active project
4,667
def parse ( logfile , time_format ) : "parses a stream with text formatted as a Timed logfile and shows a summary" records = [ server . record_from_txt ( line , only_elapsed = True , time_format = time_format ) for line in sys . stdin . readlines ( ) ] def output ( summary ) : width = max ( [ len ( p [ 0 ] ) for p in s...
parses a stream with text formatted as a Timed logfile and shows a summary
4,668
def projects ( logfile , time_format ) : "prints a newline-separated list of all projects" print '\n' . join ( server . list_projects ( read ( logfile , time_format ) ) )
prints a newline - separated list of all projects
4,669
def getLTime ( ) : _ltime = _time . localtime ( _time . time ( ) ) tlm_str = _time . strftime ( '%H:%M:%S (%d/%m/%Y)' , _ltime ) return tlm_str
Returns a formatted string with the current local time .
4,670
def getDate ( ) : _ltime = _time . localtime ( _time . time ( ) ) date_str = _time . strftime ( '%Y-%m-%dT%H:%M:%S' , _ltime ) return date_str
Returns a formatted string with the current date .
4,671
def convertDate ( date ) : d , t = date . split ( 'T' ) return decimal_date ( d , timeobs = t )
Convert DATE string into a decimal year .
4,672
def interpretDQvalue ( input ) : nbits = 16 for iexp in [ 16 , 32 , 64 , 128 ] : if ( input // ( 2 ** iexp ) ) == 0 : nbits = iexp break a = np . zeros ( 1 , dtype = 'int16' ) atype_descr = a . dtype . descr [ 0 ] [ 1 ] dtype_str = atype_descr [ : 2 ] + str ( nbits // 8 ) result = np . zeros ( nbits + 1 , dtype = dtype...
Converts an integer input into its component bit values as a list of power of 2 integers .
4,673
def verifyWriteMode ( files ) : if not isinstance ( files , list ) : files = [ files ] not_writable = [ ] writable = True for fname in files : try : f = open ( fname , 'a' ) f . close ( ) del f except : not_writable . append ( fname ) writable = False if not writable : print ( 'The following file(s) do not have write p...
Checks whether files are writable . It is up to the calling routine to raise an Exception if desired .
4,674
def buildNewRootname ( filename , extn = None , extlist = None ) : _extlist = copy . deepcopy ( EXTLIST ) if extlist : _extlist += extlist if isinstance ( filename , fits . HDUList ) : try : filename = filename . filename ( ) except : raise ValueError ( "Can't determine the filename of an waivered HDUList object." ) fo...
Build rootname for a new file .
4,675
def buildRootname ( filename , ext = None ) : if filename in [ '' , ' ' , None ] : return None fpath , fname = os . path . split ( filename ) if ext is not None and '_' in ext [ 0 ] : froot = os . path . splitext ( fname ) [ 0 ] . split ( '_' ) [ 0 ] else : froot = fname if fpath in [ '' , ' ' , None ] : fpath = os . c...
Build a new rootname for an existing file and given extension .
4,676
def getKeyword ( filename , keyword , default = None , handle = None ) : if filename . find ( '[' ) < 0 : filename += '[0]' _fname , _extn = parseFilename ( filename ) if not handle : _fimg = openImage ( _fname ) else : if isinstance ( handle , fits . HDUList ) : _fimg = handle else : raise ValueError ( 'Handle must be...
General write - safe method for returning a keyword value from the header of a IRAF recognized image .
4,677
def buildFITSName ( geisname ) : _indx = geisname . rfind ( '.' ) _fitsname = geisname [ : _indx ] + '_' + geisname [ _indx + 1 : - 1 ] + 'h.fits' return _fitsname
Build a new FITS filename for a GEIS input image .
4,678
def parseFilename ( filename ) : _indx = filename . find ( '[' ) if _indx > 0 : _fname = filename [ : _indx ] _extn = filename [ _indx + 1 : - 1 ] else : _fname = filename _extn = None return _fname , _extn
Parse out filename from any specified extensions .
4,679
def countExtn ( fimg , extname = 'SCI' ) : closefits = False if isinstance ( fimg , string_types ) : fimg = fits . open ( fimg ) closefits = True n = 0 for e in fimg : if 'extname' in e . header and e . header [ 'extname' ] == extname : n += 1 if closefits : fimg . close ( ) return n
Return the number of extname extensions defaulting to counting the number of SCI extensions .
4,680
def getExtn ( fimg , extn = None ) : if extn is None : _extn = fimg [ 0 ] for _e in fimg : if _e . data is not None : _extn = _e break else : if repr ( extn ) . find ( ',' ) > 1 : if isinstance ( extn , tuple ) : _extns = list ( extn ) if '' in _extns : _extns . remove ( '' ) else : _extns = extn . split ( ',' ) try : ...
Returns the PyFITS extension corresponding to extension specified in filename .
4,681
def findFile ( input ) : if not input : return no _fdir , _fname = os . path . split ( osfn ( input ) ) if _fdir == '' : _fdir = os . curdir try : flist = os . listdir ( _fdir ) except OSError : return no _root , _extn = parseFilename ( _fname ) found = no for name in flist : if name == _root : if _extn is None : found...
Search a directory for full filename with optional path .
4,682
def checkFileExists ( filename , directory = None ) : if directory is not None : fname = os . path . join ( directory , filename ) else : fname = filename _exist = os . path . exists ( fname ) return _exist
Checks to see if file specified exists in current or specified directory .
4,683
def copyFile ( input , output , replace = None ) : _found = findFile ( output ) if not _found or ( _found and replace ) : shutil . copy2 ( input , output )
Copy a file whole from input to output .
4,684
def removeFile ( inlist ) : if not isinstance ( inlist , string_types ) : _ldir = os . listdir ( '.' ) for f in inlist : if f . find ( '*' ) >= 0 or f . find ( '?' ) >= 0 : regpatt = f . replace ( '?' , '.?' ) regpatt = regpatt . replace ( '*' , '.*' ) _reg = re . compile ( regpatt ) for file in _ldir : if _reg . match...
Utility function for deleting a list of files or a single file .
4,685
def findKeywordExtn ( ft , keyword , value = None ) : i = 0 extnum = - 1 for chip in ft : hdr = chip . header if keyword in hdr : if value is not None : if hdr [ keyword ] . strip ( ) == value : extnum = i break else : extnum = i break i += 1 return extnum
This function will return the index of the extension in a multi - extension FITS file which contains the desired keyword with the given value .
4,686
def findExtname ( fimg , extname , extver = None ) : i = 0 extnum = None for chip in fimg : hdr = chip . header if 'EXTNAME' in hdr : if hdr [ 'EXTNAME' ] . strip ( ) == extname . upper ( ) : if extver is None or hdr [ 'EXTVER' ] == extver : extnum = i break i += 1 return extnum
Returns the list number of the extension corresponding to EXTNAME given .
4,687
def rAsciiLine ( ifile ) : _line = ifile . readline ( ) . strip ( ) while len ( _line ) == 0 : _line = ifile . readline ( ) . strip ( ) return _line
Returns the next non - blank line in an ASCII file .
4,688
def listVars ( prefix = "" , equals = "\t= " , ** kw ) : keylist = getVarList ( ) if len ( keylist ) == 0 : print ( 'No IRAF variables defined' ) else : keylist . sort ( ) for word in keylist : print ( "%s%s%s%s" % ( prefix , word , equals , envget ( word ) ) )
List IRAF variables .
4,689
def untranslateName ( s ) : s = s . replace ( 'DOT' , '.' ) s = s . replace ( 'DOLLAR' , '$' ) if s [ : 2 ] == 'PY' : s = s [ 2 : ] s = s . replace ( '.PY' , '.' ) return s
Undo Python conversion of CL parameter or variable name .
4,690
def envget ( var , default = None ) : if 'pyraf' in sys . modules : from pyraf import iraf else : iraf = None try : if iraf : return iraf . envget ( var ) else : raise KeyError except KeyError : try : return _varDict [ var ] except KeyError : try : return os . environ [ var ] except KeyError : if default is not None : ...
Get value of IRAF or OS environment variable .
4,691
def osfn ( filename ) : if filename is None : return filename ename = Expand ( filename ) dlist = [ part . strip ( ) for part in ename . split ( os . sep ) ] if len ( dlist ) == 1 and dlist [ 0 ] not in [ os . curdir , os . pardir ] : return dlist [ 0 ] epath = os . sep . join ( dlist ) fname = os . path . abspath ( ep...
Convert IRAF virtual path name to OS pathname .
4,692
def defvar ( varname ) : if 'pyraf' in sys . modules : from pyraf import iraf else : iraf = None if iraf : _irafdef = iraf . envget ( varname ) else : _irafdef = 0 return varname in _varDict or varname in os . environ or _irafdef
Returns true if CL variable is defined .
4,693
def set ( * args , ** kw ) : if len ( args ) == 0 : if len ( kw ) != 0 : for keyword , value in kw . items ( ) : keyword = untranslateName ( keyword ) svalue = str ( value ) _varDict [ keyword ] = svalue else : listVars ( prefix = " " , equals = "=" ) else : if ( len ( args ) != 1 or len ( kw ) != 0 or not isinstanc...
Set IRAF environment variables .
4,694
def show ( * args , ** kw ) : if len ( kw ) : raise TypeError ( 'unexpected keyword argument: %r' % list ( kw ) ) if args : for arg in args : print ( envget ( arg ) ) else : listVars ( prefix = " " , equals = "=" )
Print value of IRAF or OS environment variables .
4,695
def unset ( * args , ** kw ) : if len ( kw ) != 0 : raise SyntaxError ( "unset requires a list of variable names" ) for arg in args : if arg in _varDict : del _varDict [ arg ]
Unset IRAF environment variables .
4,696
def legal_date ( year , month , day ) : daysinmonth = month_length ( year , month ) if not ( 0 < day <= daysinmonth ) : raise ValueError ( "Month {} doesn't have a day {}" . format ( month , day ) ) return True
Check if this is a legal date in the Julian calendar
4,697
def from_jd ( jd ) : jd += 0.5 z = trunc ( jd ) a = z b = a + 1524 c = trunc ( ( b - 122.1 ) / 365.25 ) d = trunc ( 365.25 * c ) e = trunc ( ( b - d ) / 30.6001 ) if trunc ( e < 14 ) : month = e - 1 else : month = e - 13 if trunc ( month > 2 ) : year = c - 4716 else : year = c - 4715 day = b - d - trunc ( 30.6001 * e )...
Calculate Julian calendar date from Julian day
4,698
def delay_1 ( year ) : months = trunc ( ( ( 235 * year ) - 234 ) / 19 ) parts = 12084 + ( 13753 * months ) day = trunc ( ( months * 29 ) + parts / 25920 ) if ( ( 3 * ( day + 1 ) ) % 7 ) < 3 : day += 1 return day
Test for delay of start of new year and to avoid
4,699
def delay_2 ( year ) : last = delay_1 ( year - 1 ) present = delay_1 ( year ) next_ = delay_1 ( year + 1 ) if next_ - present == 356 : return 2 elif present - last == 382 : return 1 else : return 0
Check for delay in start of new year due to length of adjacent years