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_class' : v = kw [ k ] . __name__ else : v = str ( v ) l . append ( '{0}_{1}' . format ( n , v ) ) return '-' . join ( l )
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 . es_extra_test , popsize = self . _popsize , random_generations = self . _random_generations , negative_selection = self . _negative_selection ) return self . _p
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 . population . estopping if self . _tr_fraction < 1 : if est is not None and est . fitness_vs == 0 : return True esr = self . _early_stopping_rounds if self . _tr_fraction < 1 and esr is not None and est is not None : position = self . population . estopping . position if position < self . init_popsize : position = self . init_popsize return ( len ( self . population . hist ) + self . _unfeasible_counter - position ) > esr return flag
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 %i (%i/%i); variables: %s\n' % ( self . count , candidate_i + 1 , len ( candidates ) , sim_var ) ) self . count += 1 t , v = self . run_individual ( sim_var ) traces . append ( [ t , v ] ) else : import pp ppservers = ( ) job_server = pp . Server ( self . num_parallel_evaluations , ppservers = ppservers ) pyneuroml . pynml . print_comment_v ( 'Running %i candidates across %i local processes' % ( len ( candidates ) , job_server . get_ncpus ( ) ) ) jobs = [ ] for candidate_i in range ( len ( candidates ) ) : candidate = candidates [ candidate_i ] sim_var = dict ( zip ( parameters , candidate ) ) pyneuroml . pynml . print_comment_v ( '\n\n - PARALLEL RUN %i (%i/%i of curr candidates); variables: %s\n' % ( self . count , candidate_i + 1 , len ( candidates ) , sim_var ) ) self . count += 1 cand_dir = self . generate_dir + "/CANDIDATE_%s" % candidate_i if not os . path . exists ( cand_dir ) : os . mkdir ( cand_dir ) vars = ( sim_var , self . ref , self . neuroml_file , self . nml_doc , self . still_included , cand_dir , self . target , self . sim_time , self . dt , self . simulator ) job = job_server . submit ( run_individual , vars , ( ) , ( "pyneuroml.pynml" , 'pyneuroml.tune.NeuroMLSimulation' , 'shutil' , 'neuroml' ) ) jobs . append ( job ) for job_i in range ( len ( jobs ) ) : job = jobs [ job_i ] pyneuroml . pynml . print_comment_v ( "Checking parallel job %i/%i; set running so far: %i" % ( job_i , len ( jobs ) , self . count ) ) t , v = job ( ) traces . append ( [ t , v ] ) job_server . destroy ( ) print ( "-------------------------------------------" ) end_time = time . time ( ) tot = ( end_time - start_time ) pyneuroml . pynml . print_comment_v ( 'Ran %i candidates in %s seconds (~%ss per job)' % ( len ( candidates ) , tot , tot / len ( candidates ) ) ) return traces
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 context . request . remainder = context . request . path_info . split ( '/' ) if context . request . remainder and not context . request . remainder [ 0 ] : del context . request . remainder [ 0 ] context . path = Bread ( )
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 . path_info_peek ( ) == '' : consumed = [ '' ] nConsumed = 0 if consumed : if not isinstance ( consumed , ( list , tuple ) ) : consumed = consumed . split ( '/' ) for element in consumed : if element == context . request . path_info_peek ( ) : context . request . path_info_pop ( ) nConsumed += 1 else : break context . path . append ( Crumb ( handler , Path ( request . script_name ) ) ) if consumed : request . remainder = request . remainder [ nConsumed : ]
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 . last_modified = datetime . fromtimestamp ( modified ) ct , ce = guess_type ( result . name ) if not ct : ct = 'application/octet-stream' response . content_type , response . content_encoding = ct , ce response . etag = unicode ( modified ) result . seek ( 0 , 2 ) response . content_length = result . tell ( ) result . seek ( 0 ) response . body_file = result return True
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 : raise TerminalColorMapException ( 'colorize: must specify only one named parameter: rgb or ansi' ) if bg is not None and ansi_bg is not None : raise TerminalColorMapException ( 'colorize: must specify only one named parameter: bg or ansi_bg' ) if rgb is not None : ( closestAnsi , closestRgb ) = self . convert ( rgb ) elif ansi is not None : ( closestAnsi , closestRgb ) = ( ansi , self . colors [ ansi ] ) if bg is None and ansi_bg is None : return "\033[38;5;{ansiCode:d}m{string:s}\033[0m" . format ( ansiCode = closestAnsi , string = string ) if bg is not None : ( closestBgAnsi , unused ) = self . convert ( bg ) elif ansi_bg is not None : ( closestBgAnsi , unused ) = ( ansi_bg , self . colors [ ansi_bg ] ) return "\033[38;5;{ansiCode:d}m\033[48;5;{bf:d}m{string:s}\033[0m" . format ( ansiCode = closestAnsi , bf = closestBgAnsi , string = string )
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' ) resp . charset = 'utf-8' resp . content_type = match resp . text = result return True
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 , grid = grid ) if type ( i ) is dict : i = [ i [ v ] for v in hold_v ] plt . plot ( [ v * 1e3 for v in hold_v ] , [ ii * 1e12 for ii in i ] , * plt_args , ** plt_kwargs ) plt . legend ( loc = 2 )
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 [ 'django_application_folder' ] , folder_name , '__init__.py' ) , 'w+' ) view_file = create_or_open ( os . path . join ( folder_name , '{}.py' . format ( file_name ) ) , '' , args ) render_template_with_args_in_file ( view_file , os . path . join ( BASE_TEMPLATES_DIR , template_name ) , model_name = args [ 'model_name' ] , model_prefix = args [ 'model_prefix' ] , model_name_lower = args [ 'model_name' ] . lower ( ) , application_name = args [ 'django_application_folder' ] . split ( "/" ) [ - 1 ] ) view_file . close ( )
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 . print_comment ( "First you have to 'go()' the simulation." , True ) plt . show ( )
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' ) : colorize . cmap = XTermColorMap ( ) elif environ [ 'TERM' ] == 'vt100' : colorize . cmap = VT100ColorMap ( ) else : colorize . is_term = False else : colorize . is_term = False if colorize . is_term : string = colorize . cmap . colorize ( string , rgb , ansi , bg , ansi_bg ) return string
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 = tuple ( parts ) raise return val annotations = getattr ( handler . __func__ if hasattr ( handler , '__func__' ) else handler , '__annotations__' , None ) if not annotations : return argspec = getfullargspec ( handler ) arglist = list ( argspec . args ) if ismethod ( handler ) : del arglist [ 0 ] for i , value in enumerate ( list ( args ) ) : key = arglist [ i ] if key in annotations : args [ i ] = cast ( key , value ) for key , value in list ( items ( kw ) ) : if key in annotations : kw [ key ] = cast ( key , value )
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 env variables %s" % ( env ) , verbose ) try : if os . name == 'nt' : return_string = subprocess . check_output ( command , cwd = directory , shell = True , env = env , close_fds = False ) else : return_string = subprocess . check_output ( command , cwd = directory , shell = True , stderr = subprocess . STDOUT , env = env , close_fds = True ) return_string = return_string . decode ( "utf-8" ) print_comment ( 'Command completed. Output: \n %s%s' % ( prefix , return_string . replace ( '\n' , '\n ' + prefix ) ) , verbose ) return return_string except AttributeError : print_comment_v ( 'Assuming Python 2.6...' ) return_string = subprocess . Popen ( command , cwd = directory , shell = True , stdout = subprocess . PIPE ) . communicate ( ) [ 0 ] return return_string except subprocess . CalledProcessError as e : print_comment_v ( '*** Problem running command: \n %s' % e ) print_comment_v ( '%s%s' % ( prefix , e . output . decode ( ) . replace ( '\n' , '\n' + prefix ) ) ) return None except : print_comment_v ( '*** Unknown problem running command: %s' % e ) return None print_comment ( "Finished execution" , verbose )
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." , extra = dict ( duration = duration , request = id ( context ) ) )
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 . ArgumentExtension ) for ext in config [ 'extensions' ] ) : config [ 'extensions' ] . extend ( [ arguments . ValidateArgumentsExtension ( ) , arguments . ContextArgsExtension ( ) , arguments . RemainderArgsExtension ( ) , arguments . QueryStringArgsExtension ( ) , arguments . FormEncodedKwargsExtension ( ) , arguments . JSONKwargsExtension ( ) , ] ) config [ 'extensions' ] . append ( self ) try : addLoggingLevel ( 'trace' , logging . DEBUG - 5 ) except AttributeError : pass level = config . get ( 'logging' , { } ) . get ( 'level' , None ) if level : logging . basicConfig ( level = getattr ( logging , level . upper ( ) ) ) elif 'logging' in config : logging . config . dictConfig ( config [ 'logging' ] ) return config
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 . ref_length self . ref_name , self . qry_name = self . qry_name , self . ref_name
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 . diagdiff ) if self . diagfactor : command += ' -d ' + str ( self . diagfactor ) if self . maxgap : command += ' -g ' + str ( self . maxgap ) if self . maxmatch : command += ' --maxmatch' if self . mincluster is not None : command += ' -c ' + str ( self . mincluster ) if not self . simplify and not self . use_promer : command += ' --nosimplify' return command + ' ' + ref + ' ' + qry
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' , outfile ) , file = f ) if self . show_snps : print ( self . _show_snps_command ( 'p.delta.filter' , outfile + '.snps' ) , file = f ) pyfastaq . utils . close ( f )
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 . _write_script ( script , ref , qry , outfile ) syscall . run ( 'bash ' + script , verbose = self . verbose ) os . chdir ( original_dir ) shutil . rmtree ( tmpdir )
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 . var_type == INS and self . ref_start == new_variant . ref_start and self . qry_end + 1 == new_variant . qry_start : self . qry_base += new_variant . qry_base self . qry_end += 1 return True if self . var_type == DEL and self . qry_start == new_variant . qry_start and self . ref_end + 1 == new_variant . ref_start : self . ref_base += new_variant . ref_base self . ref_end += 1 return True return False
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 , url = self . host + self . key + url , params = params , headers = headers , data = data ) try : response . raise_for_status ( ) response_code = response . status_code success = True if response_code // 100 == 2 else False if response . text : try : data = response . json ( ) except ValueError : data = response . content else : data = '' response_headers = response . headers return BurpResponse ( success = success , response_code = response_code , data = data , response_headers = response_headers ) except ValueError as e : return BurpResponse ( success = False , message = "JSON response could not be decoded {}." . format ( e ) ) except requests . exceptions . HTTPError as e : if response . status_code == 400 : return BurpResponse ( success = False , response_code = 400 , message = 'Bad Request' ) else : return BurpResponse ( message = 'There was an error while handling the request. {}' . format ( response . content ) , success = False ) except Exception as e : return BurpResponse ( success = False , message = 'Eerror is %s' % e )
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 = inliner . document . settings . env . app . config if config . issues_user_uri : ref = config . issues_user_uri . format ( user = target ) else : ref = "https://github.com/{0}" . format ( target ) if has_explicit_title : text = title else : text = "@{0}" . format ( target ) link = nodes . reference ( text = text , refuri = ref , ** options ) return [ link ] , [ ]
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 . load ( open ( file , 'r' ) . read ( ) ) for file in doc . mustache_files ] doc . mhash = { k : v for mdict in doc . mustache_hashes for k , v in mdict . items ( ) } doc . mrenderer = pystache . Renderer ( escape = lambda u : u , missing_tags = 'strict' ) else : doc . mhash = None
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 ) + b'(' + json + b');'
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 = [ ] for file in list1 : name = os . path . split ( file ) [ - 1 ] fitsname = name [ : - 4 ] + '_' + name [ - 3 : - 1 ] + 'f.fits' list2 . append ( os . path . join ( f2 , fitsname ) ) else : list2 = [ s . strip ( ) for s in f2 . split ( "," ) ] if list1 == [ ] or list2 == [ ] : err_msg = "" if list1 == [ ] : err_msg += "Input files `{:s}` not usable/available. " . format ( f1 ) if list2 == [ ] : err_msg += "Input files `{:s}` not usable/available. " . format ( f2 ) raise IOError ( err_msg ) else : return list1 , list2
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 ( server . summarize ( read ( logfile , time_format , only_elapsed = True ) ) )
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_format ) , 'green' ) print " to now, %s" % colored ( server . date_to_txt ( now ( ) , time_format ) , 'green' ) print " => %s elapsed" % colored ( time_elapsed ( r [ 1 ] [ 0 ] ) , 'red' ) except IndexError : return cmdapp . help ( )
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_txt ( r [ 1 ] [ 0 ] , time_format ) , 'green' ) print " to now, %s" % colored ( server . date_to_txt ( r [ 1 ] [ 1 ] , time_format ) , 'green' ) print " => %s elapsed" % colored ( time_elapsed ( r [ 1 ] [ 0 ] , r [ 1 ] [ 1 ] ) , 'red' ) output ( records [ - 1 ] ) save_and_output ( read ( logfile , time_format ) )
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 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 ( server . summarize ( records ) )
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_str ) for n in range ( nbits + 1 ) : i = 2 ** n if input & i > 0 : result [ n ] = i return np . delete ( np . unique ( result ) , 0 ) . tolist ( )
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 permission!' ) for fname in not_writable : print ( ' ' , fname ) return writable
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." ) for suffix in _extlist : _indx = filename . find ( suffix ) if _indx > 0 : break if _indx < 0 : _indx = len ( filename ) if extn is None : extn = '' return filename [ : _indx ] + extn
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 . curdir flist = os . listdir ( fpath ) rootname = None for name in flist : if name == froot : rootname = froot break elif name == froot + '.fits' : rootname = froot + '.fits' break _extlist = [ ] for extn in EXTLIST : _extlist . append ( extn ) if rootname is None : if ext is not None : for i in ext : _extlist . insert ( 0 , i ) for extn in _extlist : rname = froot + extn for name in flist : if rname == name : rootname = name break if rootname is None : rname = froot . lower ( ) + extn for name in flist : if rname == name : rootname = name break if rootname is not None : break if rootname is None and ext is not None : _indx = froot . find ( '.' ) if _indx > 0 : rootname = froot [ : _indx ] + ext [ 0 ] else : rootname = froot + ext [ 0 ] if fpath not in [ '.' , '' , ' ' , None ] : rootname = os . path . join ( fpath , rootname ) return rootname
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 %r object!' % fits . HDUList ) _hdr = getExtn ( _fimg , _extn ) . header try : value = _hdr [ keyword ] except KeyError : _nextn = findKeywordExtn ( _fimg , keyword ) try : value = _fimg [ _nextn ] . header [ keyword ] except KeyError : value = '' if not handle : _fimg . close ( ) del _fimg if value == '' : if default is None : value = None else : value = default elif isinstance ( value , string_types ) : if value [ - 1 : ] == '/' : value = value [ : - 1 ] return value
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 : _extn = fimg [ _extns [ 0 ] , int ( _extns [ 1 ] ) ] except KeyError : _extn = None for e in fimg : hdr = e . header if ( 'extname' in hdr and hdr [ 'extname' ] . lower ( ) == _extns [ 0 ] . lower ( ) and hdr [ 'extver' ] == int ( _extns [ 1 ] ) ) : _extn = e break elif repr ( extn ) . find ( '/' ) > 1 : _indx = str ( extn [ : extn . find ( '/' ) ] ) _extn = fimg [ int ( _indx ) ] elif isinstance ( extn , string_types ) : if extn . strip ( ) == '' : _extn = None elif extn . isdigit ( ) : _nextn = int ( extn ) else : _nextn = None if extn . lower ( ) == 'primary' : _nextn = 0 else : i = 0 for hdu in fimg : isimg = 'extname' in hdu . header hdr = hdu . header if isimg and extn . lower ( ) == hdr [ 'extname' ] . lower ( ) : _nextn = i break i += 1 if _nextn < len ( fimg ) : _extn = fimg [ _nextn ] else : _extn = None else : if int ( extn ) < len ( fimg ) : _extn = fimg [ int ( extn ) ] else : _extn = None if _extn is None : raise KeyError ( 'Extension %s not found' % extn ) return _extn
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 = yes continue else : _split = _extn . split ( ',' ) _extnum = None _extver = None if _split [ 0 ] . isdigit ( ) : _extname = None _extnum = int ( _split [ 0 ] ) else : _extname = _split [ 0 ] if len ( _split ) > 1 : _extver = int ( _split [ 1 ] ) else : _extver = 1 f = openImage ( _root ) f . close ( ) if _extnum is not None : if _extnum < len ( f ) : found = yes del f continue else : del f else : _fext = findExtname ( f , _extname , extver = _extver ) if _fext is not None : found = yes del f continue return 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 ( file ) : _remove ( file ) else : _remove ( f ) else : _remove ( inlist )
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 : return default elif var == 'TERM' : print ( "Using default TERM value for session." ) return 'xterm' else : raise KeyError ( "Undefined environment variable `%s'" % var )
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 ( epath ) if fname [ - 1 ] != os . sep and dlist [ - 1 ] in [ '' , os . curdir , os . pardir ] : fname = fname + os . sep return fname
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 isinstance ( args [ 0 ] , string_types ) or args [ 0 ] [ : 1 ] != '@' ) : raise SyntaxError ( "set requires name=value pairs" )
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 ) return ( year , month , day )
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