idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
11,800 | def atoms ( lines ) : conv_charge_table = { 0 : 0 , 1 : 3 , 2 : 2 , 3 : 1 , 4 : 0 , 5 : - 1 , 6 : - 2 , 7 : - 3 } results = { } for i , line in enumerate ( lines ) : symbol = line [ 31 : 34 ] . rstrip ( ) try : atom = Atom ( symbol ) except KeyError : raise ValueError ( symbol ) xpos = float ( line [ 0 : 10 ] ) ypos = float ( line [ 10 : 20 ] ) zpos = float ( line [ 20 : 30 ] ) atom . coords = ( xpos , ypos , zpos ) atom . mass_diff = int ( line [ 34 : 37 ] ) old_sdf_charge = int ( line [ 37 : 40 ] ) atom . charge = conv_charge_table [ old_sdf_charge ] if old_sdf_charge == 4 : atom . radical = 1 results [ i + 1 ] = { "atom" : atom } return results | Parse atom block into atom objects |
11,801 | def bonds ( lines , atoms ) : conv_stereo_table = { 0 : 0 , 1 : 1 , 3 : 3 , 4 : 3 , 6 : 2 } results = { a : { } for a in atoms } for line in lines : bond = Bond ( ) first = int ( line [ 0 : 3 ] ) second = int ( line [ 3 : 6 ] ) if first > second : bond . is_lower_first = 0 order = int ( line [ 6 : 9 ] ) if order < 4 : bond . order = order bond . type = conv_stereo_table [ int ( line [ 9 : 12 ] ) ] results [ first ] [ second ] = { "bond" : bond } results [ second ] [ first ] = { "bond" : bond } return results | Parse bond block into bond objects |
11,802 | def properties ( lines ) : results = { } for i , line in enumerate ( lines ) : type_ = line [ 3 : 6 ] if type_ not in [ "CHG" , "RAD" , "ISO" ] : continue count = int ( line [ 6 : 9 ] ) results [ type_ ] = [ ] for j in range ( count ) : idx = int ( line [ 10 + j * 8 : 13 + j * 8 ] ) val = int ( line [ 14 + j * 8 : 17 + j * 8 ] ) results [ type_ ] . append ( ( idx , val ) ) return results | Parse properties block |
11,803 | def add_properties ( props , mol ) : if not props : return for _ , atom in mol . atoms_iter ( ) : atom . charge = 0 atom . multi = 1 atom . mass = None for prop in props . get ( "CHG" , [ ] ) : mol . atom ( prop [ 0 ] ) . charge = prop [ 1 ] for prop in props . get ( "RAD" , [ ] ) : mol . atom ( prop [ 0 ] ) . multi = prop [ 1 ] for prop in props . get ( "ISO" , [ ] ) : mol . atom ( prop [ 0 ] ) . mass = prop [ 1 ] | apply properties to the molecule object |
11,804 | def molecule ( lines ) : count_line = lines [ 3 ] num_atoms = int ( count_line [ 0 : 3 ] ) num_bonds = int ( count_line [ 3 : 6 ] ) compound = Compound ( ) compound . graph . _node = atoms ( lines [ 4 : num_atoms + 4 ] ) compound . graph . _adj = bonds ( lines [ num_atoms + 4 : num_atoms + num_bonds + 4 ] , compound . graph . _node . keys ( ) ) props = properties ( lines [ num_atoms + num_bonds + 4 : ] ) add_properties ( props , compound ) return compound | Parse molfile part into molecule object |
11,805 | def mol_supplier ( lines , no_halt , assign_descriptors ) : def sdf_block ( lns ) : mol = [ ] opt = [ ] is_mol = True for line in lns : if line . startswith ( "$$$$" ) : yield mol [ : ] , opt [ : ] is_mol = True mol . clear ( ) opt . clear ( ) elif line . startswith ( "M END" ) : is_mol = False elif is_mol : mol . append ( line . rstrip ( ) ) else : opt . append ( line . rstrip ( ) ) if mol : yield mol , opt for i , ( mol , opt ) in enumerate ( sdf_block ( lines ) ) : try : c = molecule ( mol ) if assign_descriptors : molutil . assign_descriptors ( c ) except ValueError as err : if no_halt : print ( "Unsupported symbol: {} (#{} in v2000reader)" . format ( err , i + 1 ) ) c = molutil . null_molecule ( assign_descriptors ) else : raise ValueError ( "Unsupported symbol: {}" . format ( err ) ) except RuntimeError as err : if no_halt : print ( "Failed to minimize ring: {} (#{} in v2000reader)" . format ( err , i + 1 ) ) else : raise RuntimeError ( "Failed to minimize ring: {}" . format ( err ) ) except : if no_halt : print ( "Unexpected error (#{} in v2000reader)" . format ( i + 1 ) ) c = molutil . null_molecule ( assign_descriptors ) c . data = optional_data ( opt ) yield c continue else : print ( traceback . format_exc ( ) ) raise Exception ( "Unsupported Error" ) c . data = optional_data ( opt ) yield c | Yields molecules generated from CTAB text |
11,806 | def mols_from_text ( text , no_halt = True , assign_descriptors = True ) : if isinstance ( text , bytes ) : t = tx . decode ( text ) else : t = text exp = re . compile ( r"[^\n]*\n|." ) sp = ( x . group ( 0 ) for x in re . finditer ( exp , t ) ) for c in mol_supplier ( sp , no_halt , assign_descriptors ) : yield c | Returns molecules generated from sdfile text |
11,807 | def mol_from_text ( text , assign_descriptors = True ) : cg = mols_from_text ( text , False , assign_descriptors ) return next ( cg ) | Parse CTAB text and return first one as a Compound object . |
11,808 | def mol_from_file ( path , assign_descriptors = True ) : cs = mols_from_file ( path , False , assign_descriptors ) return next ( cs ) | Parse CTAB file and return first one as a Compound object . |
11,809 | def load_from_resource ( name ) : filepath = Path ( USER_DIR ) / name if filepath . exists ( ) : with filepath . open ( ) as fh : return fh . read ( ) else : return resource_string ( 'wdiffhtml' , 'data/' + name ) . decode ( 'utf-8' ) | Returns the contents of a file resource . |
11,810 | def connect ( token , protocol = RtmProtocol , factory = WebSocketClientFactory , factory_kwargs = None , api_url = None , debug = False ) : if factory_kwargs is None : factory_kwargs = dict ( ) metadata = request_session ( token , api_url ) wsfactory = factory ( metadata . url , ** factory_kwargs ) if debug : warnings . warn ( 'debug=True has been deprecated in autobahn 0.14.0' ) wsfactory . protocol = lambda * a , ** k : protocol ( * a , ** k ) . _seedMetadata ( metadata ) connection = connectWS ( wsfactory ) return connection | Creates a new connection to the Slack Real - Time API . |
11,811 | def next_block ( self ) : assert self . pos <= self . input_len if self . pos == self . input_len : return None i = self . START_OVERSHOOT while True : try_size = int ( self . bs * i ) size = self . check_request_size ( try_size ) c , d = self . compress_next_chunk ( size ) if size != try_size : break if len ( d ) < self . bs : i += self . OVERSHOOT_INCREASE else : break while True : if len ( d ) <= self . bs : self . c = c crc32 = zlib . crc32 ( self . get_input ( size ) , 0xffffffff ) & 0xffffffff self . pos += size self . compressed_bytes += len ( d ) return crc32 , size , d size -= 1 if size == 0 : return None c , d = self . compress_next_chunk ( size ) | This could probably be improved ; at the moment it starts by trying to overshoot the desired compressed block size then it reduces the input bytes one by one until it has met the required block size |
11,812 | def set_up_logging ( log_file , console_log_level ) : logger = logging . getLogger ( ) logger . setLevel ( logging . DEBUG ) fh = logging . FileHandler ( str ( log_file ) ) fh . setLevel ( logging . DEBUG ) ch = logging . StreamHandler ( ) ch . setLevel ( console_log_level ) formatter = logging . Formatter ( "{asctime} {levelname} ({name}): {message}" , style = '{' ) fh . setFormatter ( formatter ) ch . setFormatter ( formatter ) logger . addHandler ( fh ) logger . addHandler ( ch ) return logger | Configure logging settings and return a logger object . |
11,813 | def main ( ) : args = get_args ( ) DATA_DIR = pathlib . Path ( appdirs . user_data_dir ( __title__ ) ) LOG_FILE = pathlib . Path ( appdirs . user_log_dir ( __title__ ) , 'debug.log' ) os . makedirs ( str ( DATA_DIR ) , exist_ok = True ) os . makedirs ( str ( LOG_FILE . parent ) , exist_ok = True ) if args . version : print ( '{} {}' . format ( __title__ , __version__ ) ) raise SystemExit if args . debug : CONSOLE_LOG_LEVEL = logging . DEBUG elif args . verbose : CONSOLE_LOG_LEVEL = logging . INFO else : CONSOLE_LOG_LEVEL = logging . WARNING logger = set_up_logging ( LOG_FILE , CONSOLE_LOG_LEVEL ) logger . debug ( '-' * 80 ) logger . info ( '{} {}' . format ( __title__ , __version__ ) ) logger . debug ( 'Log File: {}' . format ( LOG_FILE ) ) logger . debug ( 'Data Directory: {}' . format ( DATA_DIR ) ) if args . testdb : DATABASE_FILE = DATA_DIR . joinpath ( 'test.sqlite' ) logger . info ( 'Using test database.' ) else : DATABASE_FILE = DATA_DIR . joinpath ( 'chronophore.sqlite' ) logger . debug ( 'Database File: {}' . format ( DATABASE_FILE ) ) engine = create_engine ( 'sqlite:///{}' . format ( str ( DATABASE_FILE ) ) ) Base . metadata . create_all ( engine ) Session . configure ( bind = engine ) if args . log_sql : logging . getLogger ( 'sqlalchemy.engine' ) . setLevel ( logging . INFO ) if args . testdb : add_test_users ( session = Session ( ) ) controller . flag_forgotten_entries ( session = Session ( ) ) if args . tk : from chronophore . tkview import TkChronophoreUI TkChronophoreUI ( ) else : try : from PyQt5 . QtWidgets import QApplication except ImportError : print ( 'Error: PyQt5, which chronophore uses for its' + ' graphical interface, is not installed.' + "\nInstall it with 'pip install PyQt5'" + " or use the old Tk ui with 'chronophore --tk'." ) raise SystemExit else : from chronophore . qtview import QtChronophoreUI app = QApplication ( sys . argv ) chrono_ui = QtChronophoreUI ( ) chrono_ui . show ( ) sys . exit ( app . exec_ ( ) ) logger . debug ( '{} stopping' . format ( __title__ ) ) | Run Chronophore based on the command line arguments . |
11,814 | def filter ( self , record ) : fmt = LogManager . spec . context_format if fmt : data = self . context . to_dict ( ) if data : record . context = fmt % "," . join ( "%s=%s" % ( key , val ) for key , val in sorted ( data . items ( ) ) if key and val ) else : record . context = "" return True | Determines if the record should be logged and injects context info into the record . Always returns True |
11,815 | def enable_faulthandler ( cls , signum = signal . SIGUSR1 ) : with cls . _lock : if not signum : cls . _disable_faulthandler ( ) return if not cls . file_handler or faulthandler is None : return cls . faulthandler_signum = signum dump_file = cls . file_handler . stream faulthandler . enable ( file = dump_file , all_threads = True ) faulthandler . register ( signum , file = dump_file , all_threads = True , chain = False ) | Enable dumping thread stack traces when specified signals are received similar to java s handling of SIGQUIT |
11,816 | def override_spec ( cls , ** kwargs ) : cls . _default_spec . set ( ** kwargs ) cls . spec . set ( ** kwargs ) | OVerride spec and _default_spec with given values |
11,817 | def _fix_logging_shortcuts ( cls ) : if cls . is_using_format ( "%(pathname)s %(filename)s %(funcName)s %(module)s" ) : logging . _srcfile = cls . _logging_snapshot . _srcfile else : logging . _srcfile = None logging . logProcesses = cls . is_using_format ( "%(process)d" ) logging . logThreads = cls . is_using_format ( "%(thread)d %(threadName)s" ) def getframe ( ) : return sys . _getframe ( 4 ) def log ( level , msg , * args , ** kwargs ) : name = get_caller_name ( ) logger = logging . getLogger ( name ) try : logging . currentframe = getframe logger . log ( level , msg , * args , ** kwargs ) finally : logging . currentframe = ORIGINAL_CF def wrap ( level , ** kwargs ) : original = getattr ( logging , logging . getLevelName ( level ) . lower ( ) ) f = partial ( log , level , ** kwargs ) f . __doc__ = original . __doc__ return f logging . critical = wrap ( logging . CRITICAL ) logging . fatal = logging . critical logging . error = wrap ( logging . ERROR ) logging . exception = partial ( logging . error , exc_info = True ) logging . warning = wrap ( logging . WARNING ) logging . info = wrap ( logging . INFO ) logging . debug = wrap ( logging . DEBUG ) logging . log = log | Fix standard logging shortcuts to correctly report logging module . |
11,818 | def _parse_single ( self , text , tagname ) : return minidom . parseString ( text ) . getElementsByTagName ( tagname ) [ 0 ] . firstChild . data | A hack to get the content of the XML responses from the CAS server . |
11,819 | def quick ( self , q , context = None , task_name = "quickie" , system = False ) : if not context : context = self . context params = { "qry" : q , "context" : context , "taskname" : task_name , "isSystem" : system } r = self . _send_request ( "ExecuteQuickJob" , params = params ) return self . _parse_single ( r . text , "string" ) | Run a quick job . |
11,820 | def submit ( self , q , context = None , task_name = "casjobs" , estimate = 30 ) : if not context : context = self . context params = { "qry" : q , "context" : context , "taskname" : task_name , "estimate" : estimate } r = self . _send_request ( "SubmitJob" , params = params ) job_id = int ( self . _parse_single ( r . text , "long" ) ) return job_id | Submit a job to CasJobs . |
11,821 | def status ( self , job_id ) : params = { "jobid" : job_id } r = self . _send_request ( "GetJobStatus" , params = params ) status = int ( self . _parse_single ( r . text , "int" ) ) return status , self . status_codes [ status ] | Check the status of a job . |
11,822 | def monitor ( self , job_id , timeout = 5 ) : while True : status = self . status ( job_id ) logging . info ( "Monitoring job: %d - Status: %d, %s" % ( job_id , status [ 0 ] , status [ 1 ] ) ) if status [ 0 ] in [ 3 , 4 , 5 ] : return status time . sleep ( timeout ) | Monitor the status of a job . |
11,823 | def request_output ( self , table , outtype ) : job_types = [ "CSV" , "DataSet" , "FITS" , "VOTable" ] assert outtype in job_types params = { "tableName" : table , "type" : outtype } r = self . _send_request ( "SubmitExtractJob" , params = params ) job_id = int ( self . _parse_single ( r . text , "long" ) ) return job_id | Request the output for a given table . |
11,824 | def get_output ( self , job_id , outfn ) : job_info = self . job_info ( jobid = job_id ) [ 0 ] status = int ( job_info [ "Status" ] ) if status != 5 : raise Exception ( "The status of job %d is %d (%s)" % ( job_id , status , self . status_codes [ status ] ) ) remotefn = job_info [ "OutputLoc" ] r = requests . get ( remotefn ) code = r . status_code if code != 200 : raise Exception ( "Getting file %s yielded status: %d" % ( remotefn , code ) ) try : outfn . write ( r . content ) except AttributeError : f = open ( outfn , "wb" ) f . write ( r . content ) f . close ( ) | Download an output file given the id of the output request job . |
11,825 | def request_and_get_output ( self , table , outtype , outfn ) : job_id = self . request_output ( table , outtype ) status = self . monitor ( job_id ) if status [ 0 ] != 5 : raise Exception ( "Output request failed." ) self . get_output ( job_id , outfn ) | Shorthand for requesting an output file and then downloading it when ready . |
11,826 | def drop_table ( self , table ) : job_id = self . submit ( "DROP TABLE %s" % table , context = "MYDB" ) status = self . monitor ( job_id ) if status [ 0 ] != 5 : raise Exception ( "Couldn't drop table %s" % table ) | Drop a table from the MyDB context . |
11,827 | def count ( self , q ) : q = "SELECT COUNT(*) %s" % q return int ( self . quick ( q ) . split ( "\n" ) [ 1 ] ) | Shorthand for counting the results of a specific query . |
11,828 | def list_tables ( self ) : q = 'SELECT Distinct TABLE_NAME FROM information_schema.TABLES' res = self . quick ( q , context = 'MYDB' , task_name = 'listtables' , system = True ) return [ l [ 1 : - 1 ] for l in res . split ( '\n' ) [ 1 : - 1 ] ] | Lists the tables in mydb . |
11,829 | def multiply_and_add ( n ) : multiplier , offset = di . resolver . unpack ( multiply_and_add ) return ( multiplier * n ) + offset | Multiply the given number n by some configured multiplier and then add a configured offset . |
11,830 | def flush_buffer ( self ) : if len ( self . buffer ) > 0 : return_value = '' . join ( self . buffer ) self . buffer . clear ( ) self . send_message ( return_value ) self . last_flush_date = datetime . datetime . now ( ) | Flush the buffer of the tail |
11,831 | def set ( self , * args , ** kwargs ) : if args : for arg in args : if arg is not None : for name in self . __slots__ : self . _set ( name , getattr ( arg , name , UNSET ) ) for name in kwargs : self . _set ( name , kwargs . get ( name , UNSET ) ) | Conveniently set one or more fields at a time . |
11,832 | def enable ( self ) : with self . _lock : if self . filter is None : self . filter = self . _filter_type ( self ) | Enable contextual logging |
11,833 | def set_threadlocal ( self , ** values ) : with self . _lock : self . _ensure_threadlocal ( ) self . _tpayload . context = values | Set current thread s logging context to specified values |
11,834 | def add_threadlocal ( self , ** values ) : with self . _lock : self . _ensure_threadlocal ( ) self . _tpayload . context . update ( ** values ) | Add values to current thread s logging context |
11,835 | def add_global ( self , ** values ) : with self . _lock : self . _ensure_global ( ) self . _gpayload . update ( ** values ) | Add values to global logging context |
11,836 | def display_terminal_carbon ( mol ) : for i , a in mol . atoms_iter ( ) : if mol . neighbor_count ( i ) == 1 : a . visible = True | Set visible = True to the terminal carbon atoms . |
11,837 | def equalize_terminal_double_bond ( mol ) : for i , a in mol . atoms_iter ( ) : if mol . neighbor_count ( i ) == 1 : nb = list ( mol . neighbors ( i ) . values ( ) ) [ 0 ] if nb . order == 2 : nb . type = 2 | Show equalized double bond if it is connected to terminal atom . |
11,838 | def spine_to_terminal_wedge ( mol ) : for i , a in mol . atoms_iter ( ) : if mol . neighbor_count ( i ) == 1 : ni , nb = list ( mol . neighbors ( i ) . items ( ) ) [ 0 ] if nb . order == 1 and nb . type in ( 1 , 2 ) and ni > i != nb . is_lower_first : nb . is_lower_first = not nb . is_lower_first nb . type = { 1 : 2 , 2 : 1 } [ nb . type ] | Arrange stereo wedge direction from spine to terminal atom |
11,839 | def format_ring_double_bond ( mol ) : mol . require ( "Topology" ) mol . require ( "ScaleAndCenter" ) for r in sorted ( mol . rings , key = len , reverse = True ) : vertices = [ mol . atom ( n ) . coords for n in r ] try : if geometry . is_clockwise ( vertices ) : cpath = iterator . consecutive ( itertools . cycle ( r ) , 2 ) else : cpath = iterator . consecutive ( itertools . cycle ( reversed ( r ) ) , 2 ) except ValueError : continue for _ in r : u , v = next ( cpath ) b = mol . bond ( u , v ) if b . order == 2 : b . type = int ( ( u > v ) == b . is_lower_first ) | Set double bonds around the ring . |
11,840 | def ready_to_draw ( mol ) : copied = molutil . clone ( mol ) equalize_terminal_double_bond ( copied ) scale_and_center ( copied ) format_ring_double_bond ( copied ) return copied | Shortcut function to prepare molecule to draw . Overwrite this function for customized appearance . It is recommended to clone the molecule before draw because all the methods above are destructive . |
11,841 | def update_from_object ( self , obj , criterion = lambda key : key . isupper ( ) ) : log . debug ( 'Loading config from {0}' . format ( obj ) ) if isinstance ( obj , basestring ) : if '.' in obj : path , name = obj . rsplit ( '.' , 1 ) mod = __import__ ( path , globals ( ) , locals ( ) , [ name ] , 0 ) obj = getattr ( mod , name ) else : obj = __import__ ( obj , globals ( ) , locals ( ) , [ ] , 0 ) self . update ( ( key , getattr ( obj , key ) ) for key in filter ( criterion , dir ( obj ) ) ) | Update dict from the attributes of a module class or other object . |
11,842 | def update_from_env_namespace ( self , namespace ) : self . update ( ConfigLoader ( os . environ ) . namespace ( namespace ) ) | Update dict from any environment variables that have a given prefix . |
11,843 | def update_from ( self , obj = None , yaml_env = None , yaml_file = None , json_env = None , json_file = None , env_namespace = None , ) : if obj : self . update_from_object ( obj ) if yaml_env : self . update_from_yaml_env ( yaml_env ) if yaml_file : self . update_from_yaml_file ( yaml_file ) if json_env : self . update_from_json_env ( json_env ) if json_file : self . update_from_json_file ( json_file ) if env_namespace : self . update_from_env_namespace ( env_namespace ) | Update dict from several sources at once . |
11,844 | def namespace ( self , namespace , key_transform = lambda key : key ) : namespace = namespace . rstrip ( '_' ) + '_' return ConfigLoader ( ( key_transform ( key [ len ( namespace ) : ] ) , value ) for key , value in self . items ( ) if key [ : len ( namespace ) ] == namespace ) | Return a copy with only the keys from a given namespace . |
11,845 | def namespace_lower ( self , namespace ) : return self . namespace ( namespace , key_transform = lambda key : key . lower ( ) ) | Return a copy with only the keys from a given namespace lower - cased . |
11,846 | def render_diagram ( root_task , out_base , max_param_len = 20 , horizontal = False , colored = False ) : import re import codecs import subprocess from ozelot import config from ozelot . etl . tasks import get_task_name , get_task_param_string lines = [ u"digraph G {" ] if horizontal : lines . append ( u"rankdir=LR;" ) def get_id ( task ) : s = get_task_name ( task ) + "_" + get_task_param_string ( task ) return re . sub ( r'\W+' , '' , re . sub ( ' ' , '_' , s ) ) existing_nodes = set ( ) existing_edges = set ( ) def _build ( task , parent_id = None ) : tid = get_id ( task ) if tid not in existing_nodes : params = task . to_str_params ( ) param_list = "" for k , v in params . items ( ) : if len ( v ) > max_param_len : v = v [ : max_param_len ] + "..." param_list += "<TR><TD ALIGN=\"LEFT\">" "<FONT POINT-SIZE=\"10\">{:s}</FONT>" "</TD><TD ALIGN=\"LEFT\">" "<FONT POINT-SIZE=\"10\">{:s}</FONT>" "</TD></TR>" . format ( k , v ) label = "<TABLE BORDER=\"0\" CELLSPACING=\"1\" CELLPADDING=\"1\">" "<TR><TD COLSPAN=\"2\" ALIGN=\"CENTER\">" "<FONT POINT-SIZE=\"12\">{:s}</FONT>" "</TD></TR>" "" . format ( get_task_name ( task ) ) + param_list + "</TABLE>" style = getattr ( task , 'diagram_style' , [ ] ) if colored : color = ', color="{:s}"' . format ( "green" if task . complete ( ) else "red" ) else : color = '' lines . append ( u"{name:s} [label=< {label:s} >, shape=\"rect\" {color:s}, style=\"{style:s}\"];\n" u"" . format ( name = tid , label = label , color = color , style = ',' . join ( style ) ) ) existing_nodes . add ( tid ) for req in task . requires ( ) : _build ( req , parent_id = tid ) if parent_id is not None and ( tid , parent_id ) not in existing_edges : lines . append ( u"{source:s} -> {target:s};\n" . format ( source = tid , target = parent_id ) ) _build ( root_task ) lines . append ( u"}" ) with codecs . open ( out_base + '.dot' , 'w' , encoding = 'utf-8' ) as f : f . write ( u"\n" . join ( lines ) ) if not hasattr ( config , 'DOT_EXECUTABLE' ) : raise RuntimeError ( "Please configure the 'DOT_EXECUTABLE' variable in your 'project_config.py'" ) if not os . path . exists ( config . DOT_EXECUTABLE ) : raise IOError ( "Could not find file pointed to by 'DOT_EXECUTABLE': " + str ( config . DOT_EXECUTABLE ) ) subprocess . check_call ( [ config . DOT_EXECUTABLE , '-T' , 'png' , '-o' , out_base + '.png' , out_base + '.dot' ] ) | Render a diagram of the ETL pipeline |
11,847 | def sanitize ( s , normalize_whitespace = True , normalize_unicode = True , form = 'NFKC' , enforce_encoding = True , encoding = 'utf-8' ) : if enforce_encoding : s = s . encode ( encoding , errors = 'ignore' ) . decode ( encoding , errors = 'ignore' ) if normalize_unicode : s = unicodedata . normalize ( form , s ) if normalize_whitespace : s = re . sub ( r'\s+' , ' ' , s ) . strip ( ) return s | Normalize a string |
11,848 | def get_ticket_for_sns_token ( self ) : self . logger . info ( "%s\t%s" % ( self . request_method , self . request_url ) ) return { "openid" : self . get_openid ( ) , "persistent_code" : self . get_persistent_code ( ) , } | This is a shortcut for getting the sns_token as a post data of request body . |
11,849 | def reinitialize ( ) : from ozelot import client from ozelot . orm . target import ORMTargetMarker client = client . get_client ( ) base . Base . drop_all ( client ) base . Base . create_all ( client ) | Drop all tables for all models then re - create them |
11,850 | def _unwrap_func ( cls , decorated_func ) : if click is not None : if isinstance ( decorated_func , click . Command ) : return cls . _unwrap_func ( decorated_func . callback ) if hasattr ( decorated_func , '__wrapped__' ) : return cls . _unwrap_func ( decorated_func . __wrapped__ ) else : return decorated_func | This unwraps a decorated func returning the inner wrapped func . |
11,851 | def _register_dependent ( self , dependent , resource_name ) : if dependent not in self . dependents : self . dependents [ dependent ] = [ ] self . dependents [ dependent ] . insert ( 0 , resource_name ) | Register a mapping of the dependent to resource name . |
11,852 | def register ( self , resource_name , dependent = None ) : if dependent is None : return partial ( self . register , resource_name ) dependent = self . _unwrap_dependent ( dependent ) self . _register_dependent ( dependent , resource_name ) self . _register_resource_dependency ( resource_name , dependent ) return dependent | Register the given dependent as depending on the resource named by resource_name . |
11,853 | def verify_ocsp ( cls , certificate , issuer ) : return OCSPVerifier ( certificate , issuer , cls . get_ocsp_url ( ) , cls . get_ocsp_responder_certificate_path ( ) ) . verify ( ) | Runs OCSP verification and returns error code - 0 means success |
11,854 | def requests_retry_session ( retries = 3 , backoff_factor = 0.3 , status_forcelist = ( 500 , 502 , 504 ) , session = None ) : session = session or requests . Session ( ) retry = Retry ( total = retries , read = retries , connect = retries , backoff_factor = backoff_factor , status_forcelist = status_forcelist , ) adapter = HTTPAdapter ( max_retries = retry ) session . mount ( 'http://' , adapter ) session . mount ( 'https://' , adapter ) return session | Create a requests session that handles errors by retrying . |
11,855 | def configure_technote ( meta_stream ) : _metadata = yaml . load ( meta_stream ) confs = _build_confs ( _metadata ) return confs | Builds a dict of Sphinx configuration variables given a central configuration for LSST Design Documents and a metadata YAML file . |
11,856 | def ocsp_responder_certificate_path ( ) : certificate_path = getattr ( settings , 'ESTEID_OCSP_RESPONDER_CERTIFICATE_PATH' , 'TEST_of_SK_OCSP_RESPONDER_2011.pem' ) if certificate_path in [ 'TEST_of_SK_OCSP_RESPONDER_2011.pem' , 'sk-ocsp-responder-certificates.pem' ] : return os . path . join ( os . path . dirname ( __file__ ) , 'certs' , certificate_path ) return certificate_path | Get ocsp responder certificate path |
11,857 | def new ( self , ** kwargs ) : app = self . app or current_app mailer = app . extensions [ 'marrowmailer' ] msg = mailer . new ( ** kwargs ) msg . __class__ = Message return msg | Return a new Message instance . The arguments are passed to the marrow . mailer . Message constructor . |
11,858 | def send ( self , msg ) : app = self . app or current_app mailer = app . extensions [ 'marrowmailer' ] mailer . start ( ) if not hasattr ( msg , '__iter__' ) : result = mailer . send ( msg ) else : result = map ( lambda message : mailer . send ( message ) , msg ) mailer . stop ( ) return result | Send the message . If message is an iterable then send all the messages . |
11,859 | def wdiff ( settings , wrap_with_html = False , fold_breaks = False , hard_breaks = False ) : diff = generate_wdiff ( settings . org_file , settings . new_file , fold_breaks ) if wrap_with_html : return wrap_content ( diff , settings , hard_breaks ) else : return diff | Returns the results of wdiff in a HTML compatible format . |
11,860 | def _load_config ( config_file ) : logger . debug ( 'Config file: {}' . format ( config_file ) ) parser = configparser . ConfigParser ( ) try : with config_file . open ( 'r' ) as f : parser . read_file ( f ) except FileNotFoundError as e : logger . warning ( 'Config file not found' ) parser = _use_default ( config_file ) except configparser . ParsingError as e : logger . warning ( 'Error in config file: {}' . format ( e ) ) parser = _use_default ( config_file ) finally : try : config = _load_options ( parser ) except ( configparser . NoOptionError ) : parser = _use_default ( config_file ) config = _load_options ( parser ) logger . debug ( 'Config loaded: {}' . format ( config_file ) ) return config | Load settings from config file and return them as a dict . If the config file is not found or if it is invalid create and use a default config file . |
11,861 | def _load_options ( parser ) : config = dict ( MESSAGE_DURATION = parser . getint ( 'gui' , 'message_duration' ) , GUI_WELCOME_LABLE = parser . get ( 'gui' , 'gui_welcome_label' ) , FULL_USER_NAMES = parser . getboolean ( 'gui' , 'full_user_names' ) , LARGE_FONT_SIZE = parser . getint ( 'gui' , 'large_font_size' ) , MEDIUM_FONT_SIZE = parser . getint ( 'gui' , 'medium_font_size' ) , SMALL_FONT_SIZE = parser . getint ( 'gui' , 'small_font_size' ) , TINY_FONT_SIZE = parser . getint ( 'gui' , 'tiny_font_size' ) , MAX_INPUT_LENGTH = parser . getint ( 'gui' , 'max_input_length' ) , ) return config | Load config options from parser and return them as a dict . |
11,862 | def _use_default ( config_file ) : default_config = OrderedDict ( ( ( 'gui' , OrderedDict ( ( ( 'message_duration' , 5 ) , ( 'gui_welcome_label' , 'Welcome to the STEM Learning Center!' ) , ( 'full_user_names' , True ) , ( 'large_font_size' , 30 ) , ( 'medium_font_size' , 18 ) , ( 'small_font_size' , 15 ) , ( 'tiny_font_size' , 10 ) , ( 'max_input_length' , 9 ) , ) ) , ) , ) ) parser = configparser . ConfigParser ( ) parser . read_dict ( default_config ) if config_file . exists ( ) : backup = config_file . with_suffix ( '.bak' ) os . rename ( str ( config_file ) , str ( backup ) ) logger . info ( '{} moved to {}.' . format ( config_file , backup ) ) with config_file . open ( 'w' ) as f : parser . write ( f ) logger . info ( 'Default config file created.' ) return parser | Write default values to a config file . If another config file already exists back it up before replacing it with the new file . |
11,863 | def add_atom ( self , key , atom ) : self . graph . add_node ( key , atom = atom ) | Set an atom . Existing atom will be overwritten . |
11,864 | def atoms_iter ( self ) : for n , atom in self . graph . nodes . data ( "atom" ) : yield n , atom | Iterate over atoms . |
11,865 | def add_bond ( self , key1 , key2 , bond ) : self . graph . add_edge ( key1 , key2 , bond = bond ) | Set a bond . Existing bond will be overwritten . |
11,866 | def bonds_iter ( self ) : for u , v , bond in self . graph . edges . data ( "bond" ) : yield u , v , bond | Iterate over bonds . |
11,867 | def neighbors ( self , key ) : return { n : attr [ "bond" ] for n , attr in self . graph [ key ] . items ( ) } | Return dict of neighbor atom index and connecting bond . |
11,868 | def neighbors_iter ( self ) : for n , adj in self . graph . adj . items ( ) : yield n , { n : attr [ "bond" ] for n , attr in adj . items ( ) } | Iterate over atoms and return its neighbors . |
11,869 | def clear ( self ) : self . graph . clear ( ) self . data . clear ( ) self . descriptors . clear ( ) self . size2d = None self . rings = None self . scaffolds = None self . isolated = None | Empty the instance |
11,870 | def _convert ( self , pos ) : px = pos [ 0 ] + self . logical_size . width ( ) / 2 py = self . logical_size . height ( ) / 2 - pos [ 1 ] return px , py | For QPainter coordinate system reflect over X axis and translate from center to top - left |
11,871 | def run_sphinx ( root_dir ) : logger = logging . getLogger ( __name__ ) root_dir = os . path . abspath ( root_dir ) srcdir = root_dir confdir = root_dir outdir = os . path . join ( root_dir , '_build' , 'html' ) doctreedir = os . path . join ( root_dir , '_build' , 'doctree' ) builder = 'html' confoverrides = { } status = sys . stdout warning = sys . stderr error = sys . stderr freshenv = False warningiserror = False tags = [ ] verbosity = 0 jobs = 1 force_all = True filenames = [ ] logger . debug ( 'Sphinx config: srcdir={0}' . format ( srcdir ) ) logger . debug ( 'Sphinx config: confdir={0}' . format ( confdir ) ) logger . debug ( 'Sphinx config: outdir={0}' . format ( outdir ) ) logger . debug ( 'Sphinx config: doctreedir={0}' . format ( doctreedir ) ) logger . debug ( 'Sphinx config: builder={0}' . format ( builder ) ) logger . debug ( 'Sphinx config: freshenv={0:b}' . format ( freshenv ) ) logger . debug ( 'Sphinx config: warningiserror={0:b}' . format ( warningiserror ) ) logger . debug ( 'Sphinx config: verbosity={0:d}' . format ( verbosity ) ) logger . debug ( 'Sphinx config: jobs={0:d}' . format ( jobs ) ) logger . debug ( 'Sphinx config: force_all={0:b}' . format ( force_all ) ) app = None try : with patch_docutils ( ) , docutils_namespace ( ) : app = Sphinx ( srcdir , confdir , outdir , doctreedir , builder , confoverrides , status , warning , freshenv , warningiserror , tags , verbosity , jobs ) app . build ( force_all , filenames ) return app . statuscode except ( Exception , KeyboardInterrupt ) as exc : args = MockSphinxNamespace ( verbosity = verbosity , traceback = True ) handle_exception ( app , args , exc , error ) return 1 | Run the Sphinx build process . |
11,872 | def get_settings ( config_file ) : default_settings = { 'general' : { 'endpoint' : 'http://guacamole.antojitos.io/files/' , 'shortener' : 'http://t.antojitos.io/api/v1/urls' , } } settings = configparser . ConfigParser ( ) try : settings . read_dict ( default_settings ) except AttributeError : for section , options in default_settings . items ( ) : settings . add_section ( section ) for option , value in options . items ( ) : settings . set ( section , option , value ) if config_file is not None and os . path . exists ( config_file ) : settings . read ( config_file ) return settings if os . path . exists ( CONFIG_FILE ) : settings . read ( CONFIG_FILE ) return settings return settings | Search and load a configuration file . |
11,873 | def encrypt ( self , message , public_key ) : max_str_len = rsa . common . byte_size ( public_key . n ) - 11 if len ( message ) > max_str_len : message = textwrap . wrap ( message , width = max_str_len ) else : message = [ message ] enc_msg = [ ] for line in message : enc_line = rsa . encrypt ( line , public_key ) enc_line_converted = binascii . b2a_base64 ( enc_line ) enc_msg . append ( enc_line_converted ) enc_msg = json . dumps ( enc_msg ) return enc_msg | Encrypts a string using a given rsa . PublicKey object . If the message is larger than the key it will split it up into a list and encrypt each line in the list . |
11,874 | def decrypt ( self , message ) : message = json . loads ( message ) unencrypted_msg = [ ] for line in message : enc_line = binascii . a2b_base64 ( line ) unencrypted_line = rsa . decrypt ( enc_line , self . private_key ) unencrypted_msg . append ( unencrypted_line ) unencrypted_msg = "" . join ( unencrypted_msg ) return unencrypted_msg | Decrypts a string using our own private key object . |
11,875 | def on_any_event ( self , event ) : for delegate in self . delegates : if hasattr ( delegate , "on_any_event" ) : delegate . on_any_event ( event ) | On any event method |
11,876 | def on_created ( self , event ) : for delegate in self . delegates : if hasattr ( delegate , "on_created" ) : delegate . on_created ( event ) | On created method |
11,877 | def on_deleted ( self , event ) : for delegate in self . delegates : if hasattr ( delegate , "on_deleted" ) : delegate . on_deleted ( event ) | On deleted method |
11,878 | def on_modified ( self , event ) : for delegate in self . delegates : if hasattr ( delegate , "on_modified" ) : delegate . on_modified ( event ) | On modified method |
11,879 | def on_moved ( self , event ) : for delegate in self . delegates : if hasattr ( delegate , "on_moved" ) : delegate . on_moved ( event ) | On moved method |
11,880 | def on_created ( self , event ) : if self . trigger != "create" : return action_input = ActionInput ( event , "" , self . name ) flows . Global . MESSAGE_DISPATCHER . send_message ( action_input ) | Fired when something s been created |
11,881 | def start ( cls ) : if cls . _thread is None : cls . _thread = threading . Thread ( target = cls . _run , name = "Heartbeat" ) cls . _thread . daemon = True cls . _thread . start ( ) | Start background thread if not already started |
11,882 | def resolved_task ( cls , task ) : for t in cls . tasks : if t is task or t . execute is task : return t | Task instance representing task if any |
11,883 | def _run ( cls ) : if cls . _thread : with cls . _lock : for task in cls . tasks : cls . _execute_task ( task ) cls . tasks . sort ( ) cls . _last_execution = time . time ( ) while cls . _thread : with cls . _lock : if cls . tasks : for task in cls . tasks : if task . next_execution - cls . _last_execution < 0.5 : cls . _execute_task ( task ) else : break cls . tasks . sort ( ) cls . _last_execution = time . time ( ) cls . _sleep_delay = cls . tasks [ 0 ] . next_execution - cls . _last_execution else : cls . _sleep_delay = 1 sleep_delay = max ( 0.1 , cls . _sleep_delay ) time . sleep ( sleep_delay ) | Background thread s main function execute registered tasks accordingly to their frequencies |
11,884 | def parity_plot ( X , Y , model , devmodel , axes_labels = None ) : model_outputs = Y . shape [ 1 ] with plt . style . context ( 'seaborn-whitegrid' ) : fig = plt . figure ( figsize = ( 2.5 * model_outputs , 2.5 ) , dpi = 300 ) for i in range ( model_outputs ) : ax = fig . add_subplot ( 1 , model_outputs , i + 1 ) minval = np . min ( [ np . exp ( model . predict ( X ) [ : , i ] ) , np . exp ( Y ) [ : , i ] ] ) maxval = np . max ( [ np . exp ( model . predict ( X ) [ : , i ] ) , np . exp ( Y ) [ : , i ] ] ) buffer = ( maxval - minval ) / 100 * 2 minval = minval - buffer maxval = maxval + buffer ax . plot ( [ minval , maxval ] , [ minval , maxval ] , linestyle = "-" , label = None , c = "black" , linewidth = 1 ) ax . plot ( np . exp ( Y ) [ : , i ] , np . exp ( model . predict ( X ) ) [ : , i ] , marker = "*" , linestyle = "" , alpha = 0.4 ) if axes_labels : ax . set_ylabel ( "Predicted {}" . format ( axes_labels [ '{}' . format ( i ) ] ) ) ax . set_xlabel ( "Actual {}" . format ( axes_labels [ '{}' . format ( i ) ] ) ) else : ax . set_ylabel ( "Predicted {}" . format ( devmodel . Data . columns [ - ( 6 - i ) ] . split ( "<" ) [ 0 ] ) , wrap = True , fontsize = 5 ) ax . set_xlabel ( "Actual {}" . format ( devmodel . Data . columns [ - ( 6 - i ) ] . split ( "<" ) [ 0 ] ) , wrap = True , fontsize = 5 ) plt . xlim ( minval , maxval ) plt . ylim ( minval , maxval ) ax . grid ( ) plt . tight_layout ( ) return plt | A standard method of creating parity plots between predicted and experimental values for trained models . |
11,885 | def expand_dates ( df , columns = [ ] ) : columns = df . columns . intersection ( columns ) df2 = df . reindex ( columns = set ( df . columns ) . difference ( columns ) ) for column in columns : df2 [ column + '_year' ] = df [ column ] . apply ( lambda x : x . year ) df2 [ column + '_month' ] = df [ column ] . apply ( lambda x : x . month ) df2 [ column + '_day' ] = df [ column ] . apply ( lambda x : x . day ) return df2 | generate year month day features from specified date features |
11,886 | def binarize ( df , category_classes , all_classes = True , drop = True , astype = None , inplace = True , min_freq = None ) : if type ( category_classes ) is not dict : columns = set ( category_classes ) category_classes = { column : df [ column ] . unique ( ) for column in columns } else : columns = category_classes . keys ( ) df_new = df if inplace else df . drop ( columns , axis = 1 ) for category in columns : classes = category_classes [ category ] for i in range ( len ( classes ) - 1 if not all_classes else len ( classes ) ) : c = df [ category ] == classes [ i ] if not min_freq or c . sum ( ) >= min_freq : if astype is not None : c = c . astype ( astype ) df_new [ '%s_%s' % ( category , str ( classes [ i ] ) . replace ( ' ' , '_' ) ) ] = c if drop and inplace : df_new . drop ( columns , axis = 1 , inplace = True ) return df_new | Binarize specified categoricals . Works inplace! |
11,887 | def select_regexes ( strings , regexes ) : strings = set ( strings ) select = set ( ) if isinstance ( strings , collections . Iterable ) : for r in regexes : s = set ( filter ( re . compile ( '^' + r + '$' ) . search , strings ) ) strings -= s select |= s return select else : raise ValueError ( "exclude should be iterable" ) | select subset of strings matching a regex treats strings as a set |
11,888 | def parse_delta ( s ) : if s == 'all' : return None else : ls = delta_regex . findall ( s ) if len ( ls ) == 1 : return relativedelta ( ** { delta_chars [ ls [ 0 ] [ 1 ] ] : int ( ls [ 0 ] [ 0 ] ) } ) else : raise ValueError ( 'Invalid delta string: %s' % s ) | parse a string to a delta all is represented by None |
11,889 | def apply ( self , df ) : if hasattr ( self . definition , '__call__' ) : r = self . definition ( df ) elif self . definition in df . columns : r = df [ self . definition ] elif not isinstance ( self . definition , string_types ) : r = pd . Series ( self . definition , index = df . index ) else : raise ValueError ( "Invalid column definition: %s" % str ( self . definition ) ) return r . astype ( self . astype ) if self . astype else r | Takes a pd . DataFrame and returns the newly defined column i . e . a pd . Series that has the same index as df . |
11,890 | def ip_to_long ( ip ) : quad = ip . split ( '.' ) if len ( quad ) == 1 : quad = quad + [ 0 , 0 , 0 ] elif len ( quad ) < 4 : host = quad [ - 1 : ] quad = quad [ : - 1 ] + [ 0 , ] * ( 4 - len ( quad ) ) + host lip = 0 for q in quad : lip = ( lip << 8 ) | int ( q ) return lip | Convert ip address to a network byte order 32 - bit integer . |
11,891 | def lsst_doc_shortlink_role ( name , rawtext , text , lineno , inliner , options = None , content = None ) : options = options or { } content = content or [ ] node = nodes . reference ( text = '{0}-{1}' . format ( name . upper ( ) , text ) , refuri = 'https://ls.st/{0}-{1}' . format ( name , text ) , ** options ) return [ node ] , [ ] | Link to LSST documents given their handle using LSST s ls . st link shortener . |
11,892 | def lsst_doc_shortlink_titlecase_display_role ( name , rawtext , text , lineno , inliner , options = None , content = None ) : options = options or { } content = content or [ ] node = nodes . reference ( text = '{0}-{1}' . format ( name . title ( ) , text ) , refuri = 'https://ls.st/{0}-{1}' . format ( name , text ) , ** options ) return [ node ] , [ ] | Link to LSST documents given their handle using LSST s ls . st link shortener with the document handle displayed in title case . |
11,893 | def run ( ) : args = parse_args ( ) if args . verbose : log_level = logging . DEBUG else : log_level = logging . INFO logging . basicConfig ( level = log_level , format = '%(asctime)s %(levelname)s %(name)s: %(message)s' ) if not args . verbose : req_logger = logging . getLogger ( 'requests' ) req_logger . setLevel ( logging . WARNING ) logger = logging . getLogger ( __name__ ) logger . info ( 'refresh-lsst-bib version {}' . format ( __version__ ) ) error_count = process_bib_files ( args . dir ) sys . exit ( error_count ) | Command line entrypoint for the refresh - lsst - bib program . |
11,894 | def run_build_cli ( ) : args = parse_args ( ) if args . verbose : log_level = logging . DEBUG else : log_level = logging . INFO logging . basicConfig ( level = log_level , format = '%(asctime)s %(levelname)s %(name)s: %(message)s' ) logger = logging . getLogger ( __name__ ) logger . info ( 'build-stack-docs version {0}' . format ( __version__ ) ) return_code = build_stack_docs ( args . root_project_dir ) if return_code == 0 : logger . info ( 'build-stack-docs succeeded' ) sys . exit ( 0 ) else : logger . error ( 'Sphinx errored: code {0:d}' . format ( return_code ) ) sys . exit ( 1 ) | Command line entrypoint for the build - stack - docs program . |
11,895 | def parse_args ( ) : parser = argparse . ArgumentParser ( description = "Build a Sphinx documentation site for an EUPS stack, " "such as pipelines.lsst.io." , epilog = "Version {0}" . format ( __version__ ) ) parser . add_argument ( '-d' , '--dir' , dest = 'root_project_dir' , help = "Root Sphinx project directory" ) parser . add_argument ( '-v' , '--verbose' , dest = 'verbose' , action = 'store_true' , default = False , help = 'Enable Verbose output (debug level logging)' ) return parser . parse_args ( ) | Create an argument parser for the build - stack - docs program . |
11,896 | def discover_setup_packages ( ) : logger = logging . getLogger ( __name__ ) import eups eups_client = eups . Eups ( ) products = eups_client . getSetupProducts ( ) packages = { } for package in products : name = package . name info = { 'dir' : package . dir , 'version' : package . version } packages [ name ] = info logger . debug ( 'Found setup package: {name} {version} {dir}' . format ( name = name , ** info ) ) return packages | Summarize packages currently set up by EUPS listing their set up directories and EUPS version names . |
11,897 | def find_table_file ( root_project_dir ) : ups_dir_path = os . path . join ( root_project_dir , 'ups' ) table_path = None for name in os . listdir ( ups_dir_path ) : if name . endswith ( '.table' ) : table_path = os . path . join ( ups_dir_path , name ) break if not os . path . exists ( table_path ) : raise RuntimeError ( 'Could not find the EUPS table file at {}' . format ( table_path ) ) return table_path | Find the EUPS table file for a project . |
11,898 | def list_packages_in_eups_table ( table_text ) : logger = logging . getLogger ( __name__ ) pattern = re . compile ( r'setupRequired\((?P<name>\w+)\)' ) listed_packages = [ m . group ( 'name' ) for m in pattern . finditer ( table_text ) ] logger . debug ( 'Packages listed in the table file: %r' , listed_packages ) return listed_packages | List the names of packages that are required by an EUPS table file . |
11,899 | def find_package_docs ( package_dir , skippedNames = None ) : logger = logging . getLogger ( __name__ ) if skippedNames is None : skippedNames = [ ] doc_dir = os . path . join ( package_dir , 'doc' ) modules_yaml_path = os . path . join ( doc_dir , 'manifest.yaml' ) if not os . path . exists ( modules_yaml_path ) : raise NoPackageDocs ( 'Manifest YAML not found: {0}' . format ( modules_yaml_path ) ) with open ( modules_yaml_path ) as f : manifest_data = yaml . safe_load ( f ) module_dirs = { } package_dirs = { } static_dirs = { } if 'modules' in manifest_data : for module_name in manifest_data [ 'modules' ] : if module_name in skippedNames : logger . debug ( 'Skipping module {0}' . format ( module_name ) ) continue module_dir = os . path . join ( doc_dir , module_name ) if not os . path . isdir ( module_dir ) : message = 'module doc dir not found: {0}' . format ( module_dir ) logger . warning ( message ) continue module_dirs [ module_name ] = module_dir logger . debug ( 'Found module doc dir {0}' . format ( module_dir ) ) if 'package' in manifest_data : package_name = manifest_data [ 'package' ] full_package_dir = os . path . join ( doc_dir , package_name ) if os . path . isdir ( full_package_dir ) and package_name not in skippedNames : package_dirs [ package_name ] = full_package_dir logger . debug ( 'Found package doc dir {0}' . format ( full_package_dir ) ) else : logger . warning ( 'package doc dir excluded or not found: {0}' . format ( full_package_dir ) ) if 'statics' in manifest_data : for static_dirname in manifest_data [ 'statics' ] : full_static_dir = os . path . join ( doc_dir , static_dirname ) if not os . path . isdir ( full_static_dir ) : message = '_static doc dir not found: {0}' . format ( full_static_dir ) logger . warning ( message ) continue relative_static_dir = os . path . relpath ( full_static_dir , os . path . join ( doc_dir , '_static' ) ) static_dirs [ relative_static_dir ] = full_static_dir logger . debug ( 'Found _static doc dir: {0}' . format ( full_static_dir ) ) Dirs = namedtuple ( 'Dirs' , [ 'module_dirs' , 'package_dirs' , 'static_dirs' ] ) return Dirs ( module_dirs = module_dirs , package_dirs = package_dirs , static_dirs = static_dirs ) | Find documentation directories in a package using manifest . yaml . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.