idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
16,800 | def check_scan_process ( self , scan_id ) : scan_process = self . scan_processes [ scan_id ] progress = self . get_scan_progress ( scan_id ) if progress < 100 and not scan_process . is_alive ( ) : self . set_scan_status ( scan_id , ScanStatus . STOPPED ) self . add_scan_error ( scan_id , name = "" , host = "" , value = "Scan process failure." ) logger . info ( "%s: Scan stopped with errors." , scan_id ) elif progress == 100 : scan_process . join ( ) | Check the scan s process and terminate the scan if not alive . | 137 | 13 |
16,801 | def add_scan_log ( self , scan_id , host = '' , name = '' , value = '' , port = '' , test_id = '' , qod = '' ) : self . scan_collection . add_result ( scan_id , ResultType . LOG , host , name , value , port , test_id , 0.0 , qod ) | Adds a log result to scan_id scan . | 79 | 10 |
16,802 | def add_scan_error ( self , scan_id , host = '' , name = '' , value = '' , port = '' ) : self . scan_collection . add_result ( scan_id , ResultType . ERROR , host , name , value , port ) | Adds an error result to scan_id scan . | 57 | 10 |
16,803 | def add_scan_host_detail ( self , scan_id , host = '' , name = '' , value = '' ) : self . scan_collection . add_result ( scan_id , ResultType . HOST_DETAIL , host , name , value ) | Adds a host detail result to scan_id scan . | 58 | 11 |
16,804 | def add_scan_alarm ( self , scan_id , host = '' , name = '' , value = '' , port = '' , test_id = '' , severity = '' , qod = '' ) : self . scan_collection . add_result ( scan_id , ResultType . ALARM , host , name , value , port , test_id , severity , qod ) | Adds an alarm result to scan_id scan . | 83 | 10 |
16,805 | def parse_filters ( self , vt_filter ) : filter_list = vt_filter . split ( ';' ) filters = list ( ) for single_filter in filter_list : filter_aux = re . split ( '(\W)' , single_filter , 1 ) if len ( filter_aux ) < 3 : raise OSPDError ( "Invalid number of argument in the filter" , "get_vts" ) _element , _oper , _val = filter_aux if _element not in self . allowed_filter : raise OSPDError ( "Invalid filter element" , "get_vts" ) if _oper not in self . filter_operator : raise OSPDError ( "Invalid filter operator" , "get_vts" ) filters . append ( filter_aux ) return filters | Parse a string containing one or more filters and return a list of filters | 180 | 15 |
16,806 | def format_filter_value ( self , element , value ) : format_func = self . allowed_filter . get ( element ) return format_func ( value ) | Calls the specific function to format value depending on the given element . | 35 | 14 |
16,807 | def get_filtered_vts_list ( self , vts , vt_filter ) : if not vt_filter : raise RequiredArgument ( 'vt_filter: A valid filter is required.' ) filters = self . parse_filters ( vt_filter ) if not filters : return None _vts_aux = vts . copy ( ) for _element , _oper , _filter_val in filters : for vt_id in _vts_aux . copy ( ) : if not _vts_aux [ vt_id ] . get ( _element ) : _vts_aux . pop ( vt_id ) continue _elem_val = _vts_aux [ vt_id ] . get ( _element ) _val = self . format_filter_value ( _element , _elem_val ) if self . filter_operator [ _oper ] ( _val , _filter_val ) : continue else : _vts_aux . pop ( vt_id ) return _vts_aux | Gets a collection of vulnerability test from the vts dictionary which match the filter . | 227 | 17 |
16,808 | def inet_pton ( address_family , ip_string ) : global __inet_pton if __inet_pton is None : if hasattr ( socket , 'inet_pton' ) : __inet_pton = socket . inet_pton else : from ospd import win_socket __inet_pton = win_socket . inet_pton return __inet_pton ( address_family , ip_string ) | A platform independent version of inet_pton | 89 | 9 |
16,809 | def inet_ntop ( address_family , packed_ip ) : global __inet_ntop if __inet_ntop is None : if hasattr ( socket , 'inet_ntop' ) : __inet_ntop = socket . inet_ntop else : from ospd import win_socket __inet_ntop = win_socket . inet_ntop return __inet_ntop ( address_family , packed_ip ) | A platform independent version of inet_ntop | 98 | 10 |
16,810 | def ipv4_range_to_list ( start_packed , end_packed ) : new_list = list ( ) start = struct . unpack ( '!L' , start_packed ) [ 0 ] end = struct . unpack ( '!L' , end_packed ) [ 0 ] for value in range ( start , end + 1 ) : new_ip = socket . inet_ntoa ( struct . pack ( '!L' , value ) ) new_list . append ( new_ip ) return new_list | Return a list of IPv4 entries from start_packed to end_packed . | 115 | 16 |
16,811 | def target_to_ipv4_short ( target ) : splitted = target . split ( '-' ) if len ( splitted ) != 2 : return None try : start_packed = inet_pton ( socket . AF_INET , splitted [ 0 ] ) end_value = int ( splitted [ 1 ] ) except ( socket . error , ValueError ) : return None start_value = int ( binascii . hexlify ( bytes ( start_packed [ 3 ] ) ) , 16 ) if end_value < 0 or end_value > 255 or end_value < start_value : return None end_packed = start_packed [ 0 : 3 ] + struct . pack ( 'B' , end_value ) return ipv4_range_to_list ( start_packed , end_packed ) | Attempt to return a IPv4 short range list from a target string . | 178 | 14 |
16,812 | def target_to_ipv4_cidr ( target ) : splitted = target . split ( '/' ) if len ( splitted ) != 2 : return None try : start_packed = inet_pton ( socket . AF_INET , splitted [ 0 ] ) block = int ( splitted [ 1 ] ) except ( socket . error , ValueError ) : return None if block <= 0 or block > 30 : return None start_value = int ( binascii . hexlify ( start_packed ) , 16 ) >> ( 32 - block ) start_value = ( start_value << ( 32 - block ) ) + 1 end_value = ( start_value | ( 0xffffffff >> block ) ) - 1 start_packed = struct . pack ( '!I' , start_value ) end_packed = struct . pack ( '!I' , end_value ) return ipv4_range_to_list ( start_packed , end_packed ) | Attempt to return a IPv4 CIDR list from a target string . | 212 | 15 |
16,813 | def target_to_ipv6_cidr ( target ) : splitted = target . split ( '/' ) if len ( splitted ) != 2 : return None try : start_packed = inet_pton ( socket . AF_INET6 , splitted [ 0 ] ) block = int ( splitted [ 1 ] ) except ( socket . error , ValueError ) : return None if block <= 0 or block > 126 : return None start_value = int ( binascii . hexlify ( start_packed ) , 16 ) >> ( 128 - block ) start_value = ( start_value << ( 128 - block ) ) + 1 end_value = ( start_value | ( int ( 'ff' * 16 , 16 ) >> block ) ) - 1 high = start_value >> 64 low = start_value & ( ( 1 << 64 ) - 1 ) start_packed = struct . pack ( '!QQ' , high , low ) high = end_value >> 64 low = end_value & ( ( 1 << 64 ) - 1 ) end_packed = struct . pack ( '!QQ' , high , low ) return ipv6_range_to_list ( start_packed , end_packed ) | Attempt to return a IPv6 CIDR list from a target string . | 265 | 15 |
16,814 | def target_to_ipv4_long ( target ) : splitted = target . split ( '-' ) if len ( splitted ) != 2 : return None try : start_packed = inet_pton ( socket . AF_INET , splitted [ 0 ] ) end_packed = inet_pton ( socket . AF_INET , splitted [ 1 ] ) except socket . error : return None if end_packed < start_packed : return None return ipv4_range_to_list ( start_packed , end_packed ) | Attempt to return a IPv4 long - range list from a target string . | 118 | 15 |
16,815 | def ipv6_range_to_list ( start_packed , end_packed ) : new_list = list ( ) start = int ( binascii . hexlify ( start_packed ) , 16 ) end = int ( binascii . hexlify ( end_packed ) , 16 ) for value in range ( start , end + 1 ) : high = value >> 64 low = value & ( ( 1 << 64 ) - 1 ) new_ip = inet_ntop ( socket . AF_INET6 , struct . pack ( '!2Q' , high , low ) ) new_list . append ( new_ip ) return new_list | Return a list of IPv6 entries from start_packed to end_packed . | 144 | 16 |
16,816 | def target_to_ipv6_short ( target ) : splitted = target . split ( '-' ) if len ( splitted ) != 2 : return None try : start_packed = inet_pton ( socket . AF_INET6 , splitted [ 0 ] ) end_value = int ( splitted [ 1 ] , 16 ) except ( socket . error , ValueError ) : return None start_value = int ( binascii . hexlify ( start_packed [ 14 : ] ) , 16 ) if end_value < 0 or end_value > 0xffff or end_value < start_value : return None end_packed = start_packed [ : 14 ] + struct . pack ( '!H' , end_value ) return ipv6_range_to_list ( start_packed , end_packed ) | Attempt to return a IPv6 short - range list from a target string . | 181 | 15 |
16,817 | def target_to_ipv6_long ( target ) : splitted = target . split ( '-' ) if len ( splitted ) != 2 : return None try : start_packed = inet_pton ( socket . AF_INET6 , splitted [ 0 ] ) end_packed = inet_pton ( socket . AF_INET6 , splitted [ 1 ] ) except socket . error : return None if end_packed < start_packed : return None return ipv6_range_to_list ( start_packed , end_packed ) | Attempt to return a IPv6 long - range list from a target string . | 120 | 15 |
16,818 | def target_to_hostname ( target ) : if len ( target ) == 0 or len ( target ) > 255 : return None if not re . match ( r'^[\w.-]+$' , target ) : return None return [ target ] | Attempt to return a single hostname list from a target string . | 54 | 13 |
16,819 | def target_to_list ( target ) : # Is it an IPv4 address ? new_list = target_to_ipv4 ( target ) # Is it an IPv6 address ? if not new_list : new_list = target_to_ipv6 ( target ) # Is it an IPv4 CIDR ? if not new_list : new_list = target_to_ipv4_cidr ( target ) # Is it an IPv6 CIDR ? if not new_list : new_list = target_to_ipv6_cidr ( target ) # Is it an IPv4 short-range ? if not new_list : new_list = target_to_ipv4_short ( target ) # Is it an IPv4 long-range ? if not new_list : new_list = target_to_ipv4_long ( target ) # Is it an IPv6 short-range ? if not new_list : new_list = target_to_ipv6_short ( target ) # Is it an IPv6 long-range ? if not new_list : new_list = target_to_ipv6_long ( target ) # Is it a hostname ? if not new_list : new_list = target_to_hostname ( target ) return new_list | Attempt to return a list of single hosts from a target string . | 286 | 13 |
16,820 | def target_str_to_list ( target_str ) : new_list = list ( ) for target in target_str . split ( ',' ) : target = target . strip ( ) target_list = target_to_list ( target ) if target_list : new_list . extend ( target_list ) else : LOGGER . info ( "{0}: Invalid target value" . format ( target ) ) return None return list ( collections . OrderedDict . fromkeys ( new_list ) ) | Parses a targets string into a list of individual targets . | 108 | 13 |
16,821 | def port_range_expand ( portrange ) : if not portrange or '-' not in portrange : LOGGER . info ( "Invalid port range format" ) return None port_list = list ( ) for single_port in range ( int ( portrange [ : portrange . index ( '-' ) ] ) , int ( portrange [ portrange . index ( '-' ) + 1 : ] ) + 1 ) : port_list . append ( single_port ) return port_list | Receive a port range and expands it in individual ports . | 105 | 12 |
16,822 | def ports_str_check_failed ( port_str ) : pattern = r'[^TU:0-9, \-]' if ( re . search ( pattern , port_str ) or port_str . count ( 'T' ) > 1 or port_str . count ( 'U' ) > 1 or port_str . count ( ':' ) < ( port_str . count ( 'T' ) + port_str . count ( 'U' ) ) ) : return True return False | Check if the port string is well formed . Return True if fail False other case . | 108 | 17 |
16,823 | def ports_as_list ( port_str ) : if not port_str : LOGGER . info ( "Invalid port value" ) return [ None , None ] if ports_str_check_failed ( port_str ) : LOGGER . info ( "{0}: Port list malformed." ) return [ None , None ] tcp_list = list ( ) udp_list = list ( ) ports = port_str . replace ( ' ' , '' ) b_tcp = ports . find ( "T" ) b_udp = ports . find ( "U" ) if ports [ b_tcp - 1 ] == ',' : ports = ports [ : b_tcp - 1 ] + ports [ b_tcp : ] if ports [ b_udp - 1 ] == ',' : ports = ports [ : b_udp - 1 ] + ports [ b_udp : ] ports = port_str_arrange ( ports ) tports = '' uports = '' # TCP ports listed first, then UDP ports if b_udp != - 1 and b_tcp != - 1 : tports = ports [ ports . index ( 'T:' ) + 2 : ports . index ( 'U:' ) ] uports = ports [ ports . index ( 'U:' ) + 2 : ] # Only UDP ports elif b_tcp == - 1 and b_udp != - 1 : uports = ports [ ports . index ( 'U:' ) + 2 : ] # Only TCP ports elif b_udp == - 1 and b_tcp != - 1 : tports = ports [ ports . index ( 'T:' ) + 2 : ] else : tports = ports if tports : for port in tports . split ( ',' ) : if '-' in port : tcp_list . extend ( port_range_expand ( port ) ) else : tcp_list . append ( int ( port ) ) tcp_list . sort ( ) if uports : for port in uports . split ( ',' ) : if '-' in port : udp_list . extend ( port_range_expand ( port ) ) else : udp_list . append ( int ( port ) ) udp_list . sort ( ) return ( tcp_list , udp_list ) | Parses a ports string into two list of individual tcp and udp ports . | 494 | 17 |
16,824 | def port_list_compress ( port_list ) : if not port_list or len ( port_list ) == 0 : LOGGER . info ( "Invalid or empty port list." ) return '' port_list = sorted ( set ( port_list ) ) compressed_list = [ ] for key , group in itertools . groupby ( enumerate ( port_list ) , lambda t : t [ 1 ] - t [ 0 ] ) : group = list ( group ) if group [ 0 ] [ 1 ] == group [ - 1 ] [ 1 ] : compressed_list . append ( str ( group [ 0 ] [ 1 ] ) ) else : compressed_list . append ( str ( group [ 0 ] [ 1 ] ) + '-' + str ( group [ - 1 ] [ 1 ] ) ) return ',' . join ( compressed_list ) | Compress a port list and return a string . | 181 | 10 |
16,825 | def valid_uuid ( value ) : try : uuid . UUID ( value , version = 4 ) return True except ( TypeError , ValueError , AttributeError ) : return False | Check if value is a valid UUID . | 40 | 9 |
16,826 | def create_args_parser ( description ) : parser = argparse . ArgumentParser ( description = description ) def network_port ( string ) : """ Check if provided string is a valid network port. """ value = int ( string ) if not 0 < value <= 65535 : raise argparse . ArgumentTypeError ( 'port must be in ]0,65535] interval' ) return value def cacert_file ( cacert ) : """ Check if provided file is a valid CA Certificate """ try : context = ssl . create_default_context ( cafile = cacert ) except AttributeError : # Python version < 2.7.9 return cacert except IOError : raise argparse . ArgumentTypeError ( 'CA Certificate not found' ) try : not_after = context . get_ca_certs ( ) [ 0 ] [ 'notAfter' ] not_after = ssl . cert_time_to_seconds ( not_after ) not_before = context . get_ca_certs ( ) [ 0 ] [ 'notBefore' ] not_before = ssl . cert_time_to_seconds ( not_before ) except ( KeyError , IndexError ) : raise argparse . ArgumentTypeError ( 'CA Certificate is erroneous' ) if not_after < int ( time . time ( ) ) : raise argparse . ArgumentTypeError ( 'CA Certificate expired' ) if not_before > int ( time . time ( ) ) : raise argparse . ArgumentTypeError ( 'CA Certificate not active yet' ) return cacert def log_level ( string ) : """ Check if provided string is a valid log level. """ value = getattr ( logging , string . upper ( ) , None ) if not isinstance ( value , int ) : raise argparse . ArgumentTypeError ( 'log level must be one of {debug,info,warning,error,critical}' ) return value def filename ( string ) : """ Check if provided string is a valid file path. """ if not os . path . isfile ( string ) : raise argparse . ArgumentTypeError ( '%s is not a valid file path' % string ) return string parser . add_argument ( '-p' , '--port' , default = PORT , type = network_port , help = 'TCP Port to listen on. Default: {0}' . format ( PORT ) ) parser . add_argument ( '-b' , '--bind-address' , default = ADDRESS , help = 'Address to listen on. Default: {0}' . format ( ADDRESS ) ) parser . add_argument ( '-u' , '--unix-socket' , help = 'Unix file socket to listen on.' ) parser . add_argument ( '-k' , '--key-file' , type = filename , help = 'Server key file. Default: {0}' . format ( KEY_FILE ) ) parser . add_argument ( '-c' , '--cert-file' , type = filename , help = 'Server cert file. Default: {0}' . format ( CERT_FILE ) ) parser . add_argument ( '--ca-file' , type = cacert_file , help = 'CA cert file. Default: {0}' . format ( CA_FILE ) ) parser . add_argument ( '-L' , '--log-level' , default = 'warning' , type = log_level , help = 'Wished level of logging. Default: WARNING' ) parser . add_argument ( '--foreground' , action = 'store_true' , help = 'Run in foreground and logs all messages to console.' ) parser . add_argument ( '-l' , '--log-file' , type = filename , help = 'Path to the logging file.' ) parser . add_argument ( '--version' , action = 'store_true' , help = 'Print version then exit.' ) return parser | Create a command - line arguments parser for OSPD . | 850 | 12 |
16,827 | def go_to_background ( ) : try : if os . fork ( ) : sys . exit ( ) except OSError as errmsg : LOGGER . error ( 'Fork failed: {0}' . format ( errmsg ) ) sys . exit ( 'Fork failed' ) | Daemonize the running process . | 63 | 7 |
16,828 | def get_common_args ( parser , args = None ) : options = parser . parse_args ( args ) # TCP Port to listen on. port = options . port # Network address to bind listener to address = options . bind_address # Unix file socket to listen on unix_socket = options . unix_socket # Debug level. log_level = options . log_level # Server key path. keyfile = options . key_file or KEY_FILE # Server cert path. certfile = options . cert_file or CERT_FILE # CA cert path. cafile = options . ca_file or CA_FILE common_args = dict ( ) common_args [ 'port' ] = port common_args [ 'address' ] = address common_args [ 'unix_socket' ] = unix_socket common_args [ 'keyfile' ] = keyfile common_args [ 'certfile' ] = certfile common_args [ 'cafile' ] = cafile common_args [ 'log_level' ] = log_level common_args [ 'foreground' ] = options . foreground common_args [ 'log_file' ] = options . log_file common_args [ 'version' ] = options . version return common_args | Return list of OSPD common command - line arguments from parser after validating provided values or setting default ones . | 272 | 23 |
16,829 | def print_version ( wrapper ) : scanner_name = wrapper . get_scanner_name ( ) server_version = wrapper . get_server_version ( ) print ( "OSP Server for {0} version {1}" . format ( scanner_name , server_version ) ) protocol_version = wrapper . get_protocol_version ( ) print ( "OSP Version: {0}" . format ( protocol_version ) ) daemon_name = wrapper . get_daemon_name ( ) daemon_version = wrapper . get_daemon_version ( ) print ( "Using: {0} {1}" . format ( daemon_name , daemon_version ) ) print ( "Copyright (C) 2014, 2015 Greenbone Networks GmbH\n" "License GPLv2+: GNU GPL version 2 or later\n" "This is free software: you are free to change" " and redistribute it.\n" "There is NO WARRANTY, to the extent permitted by law." ) | Prints the server version and license information . | 213 | 9 |
16,830 | def main ( name , klass ) : # Common args parser. parser = create_args_parser ( name ) # Common args cargs = get_common_args ( parser ) logging . getLogger ( ) . setLevel ( cargs [ 'log_level' ] ) wrapper = klass ( certfile = cargs [ 'certfile' ] , keyfile = cargs [ 'keyfile' ] , cafile = cargs [ 'cafile' ] ) if cargs [ 'version' ] : print_version ( wrapper ) sys . exit ( ) if cargs [ 'foreground' ] : console = logging . StreamHandler ( ) console . setFormatter ( logging . Formatter ( '%(asctime)s %(name)s: %(levelname)s: %(message)s' ) ) logging . getLogger ( ) . addHandler ( console ) elif cargs [ 'log_file' ] : logfile = logging . handlers . WatchedFileHandler ( cargs [ 'log_file' ] ) logfile . setFormatter ( logging . Formatter ( '%(asctime)s %(name)s: %(levelname)s: %(message)s' ) ) logging . getLogger ( ) . addHandler ( logfile ) go_to_background ( ) else : syslog = logging . handlers . SysLogHandler ( '/dev/log' ) syslog . setFormatter ( logging . Formatter ( '%(name)s: %(levelname)s: %(message)s' ) ) logging . getLogger ( ) . addHandler ( syslog ) # Duplicate syslog's file descriptor to stout/stderr. syslog_fd = syslog . socket . fileno ( ) os . dup2 ( syslog_fd , 1 ) os . dup2 ( syslog_fd , 2 ) go_to_background ( ) if not wrapper . check ( ) : return 1 return wrapper . run ( cargs [ 'address' ] , cargs [ 'port' ] , cargs [ 'unix_socket' ] ) | OSPD Main function . | 458 | 5 |
16,831 | def add_result ( self , scan_id , result_type , host = '' , name = '' , value = '' , port = '' , test_id = '' , severity = '' , qod = '' ) : assert scan_id assert len ( name ) or len ( value ) result = dict ( ) result [ 'type' ] = result_type result [ 'name' ] = name result [ 'severity' ] = severity result [ 'test_id' ] = test_id result [ 'value' ] = value result [ 'host' ] = host result [ 'port' ] = port result [ 'qod' ] = qod results = self . scans_table [ scan_id ] [ 'results' ] results . append ( result ) # Set scan_info's results to propagate results to parent process. self . scans_table [ scan_id ] [ 'results' ] = results | Add a result to a scan in the table . | 193 | 10 |
16,832 | def get_hosts_unfinished ( self , scan_id ) : unfinished_hosts = list ( ) for target in self . scans_table [ scan_id ] [ 'finished_hosts' ] : unfinished_hosts . extend ( target_str_to_list ( target ) ) for target in self . scans_table [ scan_id ] [ 'finished_hosts' ] : for host in self . scans_table [ scan_id ] [ 'finished_hosts' ] [ target ] : unfinished_hosts . remove ( host ) return unfinished_hosts | Get a list of finished hosts . | 125 | 7 |
16,833 | def results_iterator ( self , scan_id , pop_res ) : if pop_res : result_aux = self . scans_table [ scan_id ] [ 'results' ] self . scans_table [ scan_id ] [ 'results' ] = list ( ) return iter ( result_aux ) return iter ( self . scans_table [ scan_id ] [ 'results' ] ) | Returns an iterator over scan_id scan s results . If pop_res is True it removed the fetched results from the list . | 85 | 27 |
16,834 | def del_results_for_stopped_hosts ( self , scan_id ) : unfinished_hosts = self . get_hosts_unfinished ( scan_id ) for result in self . results_iterator ( scan_id , False ) : if result [ 'host' ] in unfinished_hosts : self . remove_single_result ( scan_id , result ) | Remove results from the result table for those host | 82 | 9 |
16,835 | def create_scan ( self , scan_id = '' , targets = '' , options = None , vts = '' ) : if self . data_manager is None : self . data_manager = multiprocessing . Manager ( ) # Check if it is possible to resume task. To avoid to resume, the # scan must be deleted from the scans_table. if scan_id and self . id_exists ( scan_id ) and ( self . get_status ( scan_id ) == ScanStatus . STOPPED ) : return self . resume_scan ( scan_id , options ) if not options : options = dict ( ) scan_info = self . data_manager . dict ( ) scan_info [ 'results' ] = list ( ) scan_info [ 'finished_hosts' ] = dict ( [ [ target , [ ] ] for target , _ , _ in targets ] ) scan_info [ 'progress' ] = 0 scan_info [ 'target_progress' ] = dict ( [ [ target , { } ] for target , _ , _ in targets ] ) scan_info [ 'targets' ] = targets scan_info [ 'vts' ] = vts scan_info [ 'options' ] = options scan_info [ 'start_time' ] = int ( time . time ( ) ) scan_info [ 'end_time' ] = "0" scan_info [ 'status' ] = ScanStatus . INIT if scan_id is None or scan_id == '' : scan_id = str ( uuid . uuid4 ( ) ) scan_info [ 'scan_id' ] = scan_id self . scans_table [ scan_id ] = scan_info return scan_id | Creates a new scan with provided scan information . | 373 | 10 |
16,836 | def set_option ( self , scan_id , name , value ) : self . scans_table [ scan_id ] [ 'options' ] [ name ] = value | Set a scan_id scan s name option to value . | 36 | 12 |
16,837 | def get_target_progress ( self , scan_id , target ) : total_hosts = len ( target_str_to_list ( target ) ) host_progresses = self . scans_table [ scan_id ] [ 'target_progress' ] . get ( target ) try : t_prog = sum ( host_progresses . values ( ) ) / total_hosts except ZeroDivisionError : LOGGER . error ( "Zero division error in " , get_target_progress . __name__ ) raise return t_prog | Get a target s current progress value . The value is calculated with the progress of each single host in the target . | 118 | 23 |
16,838 | def get_target_list ( self , scan_id ) : target_list = [ ] for target , _ , _ in self . scans_table [ scan_id ] [ 'targets' ] : target_list . append ( target ) return target_list | Get a scan s target list . | 57 | 7 |
16,839 | def get_ports ( self , scan_id , target ) : if target : for item in self . scans_table [ scan_id ] [ 'targets' ] : if target == item [ 0 ] : return item [ 1 ] return self . scans_table [ scan_id ] [ 'targets' ] [ 0 ] [ 1 ] | Get a scan s ports list . If a target is specified it will return the corresponding port for it . If not it returns the port item of the first nested list in the target s list . | 75 | 39 |
16,840 | def get_credentials ( self , scan_id , target ) : if target : for item in self . scans_table [ scan_id ] [ 'targets' ] : if target == item [ 0 ] : return item [ 2 ] | Get a scan s credential list . It return dictionary with the corresponding credential for a given target . | 53 | 19 |
16,841 | def delete_scan ( self , scan_id ) : if self . get_status ( scan_id ) == ScanStatus . RUNNING : return False self . scans_table . pop ( scan_id ) if len ( self . scans_table ) == 0 : del self . data_manager self . data_manager = None return True | Delete a scan if fully finished . | 71 | 7 |
16,842 | def is_timestamp ( obj ) : return isinstance ( obj , datetime . datetime ) or is_string ( obj ) or is_int ( obj ) or is_float ( obj ) | Yaml either have automatically converted it to a datetime object or it is a string that will be validated later . | 42 | 23 |
16,843 | def init_logging ( log_level ) : log_level = log_level_to_string_map [ min ( log_level , 5 ) ] msg = "%(levelname)s - %(name)s:%(lineno)s - %(message)s" if log_level in os . environ else "%(levelname)s - %(message)s" logging_conf = { "version" : 1 , "root" : { "level" : log_level , "handlers" : [ "console" ] } , "handlers" : { "console" : { "class" : "logging.StreamHandler" , "level" : log_level , "formatter" : "simple" , "stream" : "ext://sys.stdout" } } , "formatters" : { "simple" : { "format" : " {0}" . format ( msg ) } } } logging . config . dictConfig ( logging_conf ) | Init logging settings with default set to INFO | 214 | 8 |
16,844 | def keywords ( self ) : defined_keywords = [ ( 'allowempty_map' , 'allowempty_map' ) , ( 'assertion' , 'assertion' ) , ( 'default' , 'default' ) , ( 'class' , 'class' ) , ( 'desc' , 'desc' ) , ( 'enum' , 'enum' ) , ( 'example' , 'example' ) , ( 'extensions' , 'extensions' ) , ( 'format' , 'format' ) , ( 'func' , 'func' ) , ( 'ident' , 'ident' ) , ( 'include_name' , 'include' ) , ( 'length' , 'length' ) , ( 'map_regex_rule' , 'map_regex_rule' ) , ( 'mapping' , 'mapping' ) , ( 'matching' , 'matching' ) , ( 'matching_rule' , 'matching_rule' ) , ( 'name' , 'name' ) , ( 'nullable' , 'nullable' ) ( 'parent' , 'parent' ) , ( 'pattern' , 'pattern' ) , ( 'pattern_regexp' , 'pattern_regexp' ) , ( 'range' , 'range' ) , ( 'regex_mappings' , 'regex_mappings' ) , ( 'required' , 'required' ) , ( 'schema' , 'schema' ) , ( 'schema_str' , 'schema_str' ) , ( 'sequence' , 'sequence' ) , ( 'type' , 'type' ) , ( 'type_class' , 'type_class' ) , ( 'unique' , 'unique' ) , ( 'version' , 'version' ) , ] found_keywords = [ ] for var_name , keyword_name in defined_keywords : if getattr ( self , var_name , None ) : found_keywords . append ( keyword_name ) return found_keywords | Returns a list of all keywords that this rule object has defined . A keyword is considered defined if the value it returns ! = None . | 444 | 27 |
16,845 | def _load_extensions ( self ) : log . debug ( u"loading all extensions : %s" , self . extensions ) self . loaded_extensions = [ ] for f in self . extensions : if not os . path . isabs ( f ) : f = os . path . abspath ( f ) if not os . path . exists ( f ) : raise CoreError ( u"Extension file: {0} not found on disk" . format ( f ) ) self . loaded_extensions . append ( imp . load_source ( "" , f ) ) log . debug ( self . loaded_extensions ) log . debug ( [ dir ( m ) for m in self . loaded_extensions ] ) | Load all extension files into the namespace pykwalify . ext | 153 | 13 |
16,846 | def _handle_func ( self , value , rule , path , done = None ) : func = rule . func # func keyword is not defined so nothing to do if not func : return found_method = False for extension in self . loaded_extensions : method = getattr ( extension , func , None ) if method : found_method = True # No exception will should be caught. If one is raised it should bubble up all the way. ret = method ( value , rule , path ) if ret is not True and ret is not None : msg = '%s. Path: {path}' % unicode ( ret ) self . errors . append ( SchemaError . SchemaErrorEntry ( msg = msg , path = path , value = None ) ) # If False or None or some other object that is interpreted as False if not ret : raise CoreError ( u"Error when running extension function : {0}" . format ( func ) ) # Only run the first matched function. Sinc loading order is determined # it should be easy to determine which file is used before others break if not found_method : raise CoreError ( u"Did not find method '{0}' in any loaded extension file" . format ( func ) ) | Helper function that should check if func is specified for this rule and then handle it for all cases in a generic way . | 260 | 24 |
16,847 | def _validate_range ( self , max_ , min_ , max_ex , min_ex , value , path , prefix ) : if not isinstance ( value , int ) and not isinstance ( value , float ) : raise CoreError ( "Value must be a integer type" ) log . debug ( u"Validate range : %s : %s : %s : %s : %s : %s" , max_ , min_ , max_ex , min_ex , value , path , ) if max_ is not None and max_ < value : self . errors . append ( SchemaError . SchemaErrorEntry ( msg = u"Type '{prefix}' has size of '{value}', greater than max limit '{max_}'. Path: '{path}'" , path = path , value = nativestr ( value ) if tt [ 'str' ] ( value ) else value , prefix = prefix , max_ = max_ ) ) if min_ is not None and min_ > value : self . errors . append ( SchemaError . SchemaErrorEntry ( msg = u"Type '{prefix}' has size of '{value}', less than min limit '{min_}'. Path: '{path}'" , path = path , value = nativestr ( value ) if tt [ 'str' ] ( value ) else value , prefix = prefix , min_ = min_ ) ) if max_ex is not None and max_ex <= value : self . errors . append ( SchemaError . SchemaErrorEntry ( msg = u"Type '{prefix}' has size of '{value}', greater than or equals to max limit(exclusive) '{max_ex}'. Path: '{path}'" , path = path , value = nativestr ( value ) if tt [ 'str' ] ( value ) else value , prefix = prefix , max_ex = max_ex ) ) if min_ex is not None and min_ex >= value : self . errors . append ( SchemaError . SchemaErrorEntry ( msg = u"Type '{prefix}' has size of '{value}', less than or equals to min limit(exclusive) '{min_ex}'. Path: '{path}'" , path = path , value = nativestr ( value ) if tt [ 'str' ] ( value ) else value , prefix = prefix , min_ex = min_ex ) ) | Validate that value is within range values . | 536 | 9 |
16,848 | def run ( cli_args ) : from . core import Core c = Core ( source_file = cli_args [ "--data-file" ] , schema_files = cli_args [ "--schema-file" ] , extensions = cli_args [ '--extension' ] , strict_rule_validation = cli_args [ '--strict-rule-validation' ] , fix_ruby_style_regex = cli_args [ '--fix-ruby-style-regex' ] , allow_assertions = cli_args [ '--allow-assertions' ] , file_encoding = cli_args [ '--encoding' ] , ) c . validate ( ) return c | Split the functionality into 2 methods . | 162 | 7 |
16,849 | def to_bedtool ( iterator ) : def gen ( ) : for i in iterator : yield helpers . asinterval ( i ) return pybedtools . BedTool ( gen ( ) ) | Convert any iterator into a pybedtools . BedTool object . | 40 | 14 |
16,850 | def tsses ( db , merge_overlapping = False , attrs = None , attrs_sep = ":" , merge_kwargs = None , as_bed6 = False , bedtools_227_or_later = True ) : _override = os . environ . get ( 'GFFUTILS_USES_BEDTOOLS_227_OR_LATER' , None ) if _override is not None : if _override == 'true' : bedtools_227_or_later = True elif _override == 'false' : bedtools_227_or_later = False else : raise ValueError ( "Unknown value for GFFUTILS_USES_BEDTOOLS_227_OR_LATER " "environment variable: {0}" . format ( _override ) ) if bedtools_227_or_later : _merge_kwargs = dict ( o = 'distinct' , s = True , c = '4,5,6' ) else : _merge_kwargs = dict ( o = 'distinct' , s = True , c = '4' ) if merge_kwargs is not None : _merge_kwargs . update ( merge_kwargs ) def gen ( ) : """ Generator of pybedtools.Intervals representing TSSes. """ for gene in db . features_of_type ( 'gene' ) : for transcript in db . children ( gene , level = 1 ) : if transcript . strand == '-' : transcript . start = transcript . stop else : transcript . stop = transcript . start transcript . featuretype = transcript . featuretype + '_TSS' yield helpers . asinterval ( transcript ) # GFF/GTF format x = pybedtools . BedTool ( gen ( ) ) . sort ( ) # Figure out default attrs to use, depending on the original format. if attrs is None : if db . dialect [ 'fmt' ] == 'gtf' : attrs = 'gene_id' else : attrs = 'ID' if merge_overlapping or as_bed6 : if isinstance ( attrs , six . string_types ) : attrs = [ attrs ] def to_bed ( f ) : """ Given a pybedtools.Interval, return a new Interval with the name set according to the kwargs provided above. """ name = attrs_sep . join ( [ f . attrs [ i ] for i in attrs ] ) return pybedtools . Interval ( f . chrom , f . start , f . stop , name , str ( f . score ) , f . strand ) x = x . each ( to_bed ) . saveas ( ) if merge_overlapping : if bedtools_227_or_later : x = x . merge ( * * _merge_kwargs ) else : def fix_merge ( f ) : f = featurefuncs . extend_fields ( f , 6 ) return pybedtools . Interval ( f . chrom , f . start , f . stop , f [ 4 ] , '.' , f [ 3 ] ) x = x . merge ( * * _merge_kwargs ) . saveas ( ) . each ( fix_merge ) . saveas ( ) return x | Create 1 - bp transcription start sites for all transcripts in the database and return as a sorted pybedtools . BedTool object pointing to a temporary file . | 720 | 32 |
16,851 | def close ( self ) : self . out_stream . close ( ) # If we're asked to write in place, substitute the named # temporary file for the current file if self . in_place : shutil . move ( self . temp_file . name , self . out ) | Close the stream . Assumes stream has close method . | 59 | 11 |
16,852 | def to_seqfeature ( feature ) : if isinstance ( feature , six . string_types ) : feature = feature_from_line ( feature ) qualifiers = { 'source' : [ feature . source ] , 'score' : [ feature . score ] , 'seqid' : [ feature . seqid ] , 'frame' : [ feature . frame ] , } qualifiers . update ( feature . attributes ) return SeqFeature ( # Convert from GFF 1-based to standard Python 0-based indexing used by # BioPython FeatureLocation ( feature . start - 1 , feature . stop ) , id = feature . id , type = feature . featuretype , strand = _biopython_strand [ feature . strand ] , qualifiers = qualifiers ) | Converts a gffutils . Feature object to a Bio . SeqFeature object . | 158 | 18 |
16,853 | def from_seqfeature ( s , * * kwargs ) : source = s . qualifiers . get ( 'source' , '.' ) [ 0 ] score = s . qualifiers . get ( 'score' , '.' ) [ 0 ] seqid = s . qualifiers . get ( 'seqid' , '.' ) [ 0 ] frame = s . qualifiers . get ( 'frame' , '.' ) [ 0 ] strand = _feature_strand [ s . strand ] # BioPython parses 1-based GenBank positions into 0-based for use within # Python. We need to convert back to 1-based GFF format here. start = s . location . start . position + 1 stop = s . location . end . position featuretype = s . type id = s . id attributes = dict ( s . qualifiers ) attributes . pop ( 'source' , '.' ) attributes . pop ( 'score' , '.' ) attributes . pop ( 'seqid' , '.' ) attributes . pop ( 'frame' , '.' ) return Feature ( seqid , source , featuretype , start , stop , score , strand , frame , attributes , id = id , * * kwargs ) | Converts a Bio . SeqFeature object to a gffutils . Feature object . | 253 | 18 |
16,854 | def set_pragmas ( self , pragmas ) : self . pragmas = pragmas c = self . conn . cursor ( ) c . executescript ( ';\n' . join ( [ 'PRAGMA %s=%s' % i for i in self . pragmas . items ( ) ] ) ) self . conn . commit ( ) | Set pragmas for the current database connection . | 76 | 9 |
16,855 | def _feature_returner ( self , * * kwargs ) : kwargs . setdefault ( 'dialect' , self . dialect ) kwargs . setdefault ( 'keep_order' , self . keep_order ) kwargs . setdefault ( 'sort_attribute_values' , self . sort_attribute_values ) return Feature ( * * kwargs ) | Returns a feature adding additional database - specific defaults | 83 | 9 |
16,856 | def schema ( self ) : c = self . conn . cursor ( ) c . execute ( ''' SELECT sql FROM sqlite_master ''' ) results = [ ] for i , in c : if i is not None : results . append ( i ) return '\n' . join ( results ) | Returns the database schema as a string . | 63 | 8 |
16,857 | def featuretypes ( self ) : c = self . conn . cursor ( ) c . execute ( ''' SELECT DISTINCT featuretype from features ''' ) for i , in c : yield i | Iterate over feature types found in the database . | 42 | 10 |
16,858 | def execute ( self , query ) : c = self . conn . cursor ( ) return c . execute ( query ) | Execute arbitrary queries on the db . | 24 | 8 |
16,859 | def interfeatures ( self , features , new_featuretype = None , merge_attributes = True , dialect = None , attribute_func = None , update_attributes = None ) : for i , f in enumerate ( features ) : # no inter-feature for the first one if i == 0 : interfeature_start = f . stop last_feature = f continue interfeature_stop = f . start if new_featuretype is None : new_featuretype = 'inter_%s_%s' % ( last_feature . featuretype , f . featuretype ) if last_feature . strand != f . strand : new_strand = '.' else : new_strand = f . strand if last_feature . chrom != f . chrom : # We've moved to a new chromosome. For example, if we're # getting intergenic regions from all genes, they will be on # different chromosomes. We still assume sorted features, but # don't complain if they're on different chromosomes -- just # move on. last_feature = f continue strand = new_strand chrom = last_feature . chrom # Shrink interfeature_start += 1 interfeature_stop -= 1 if merge_attributes : new_attributes = helpers . merge_attributes ( last_feature . attributes , f . attributes ) else : new_attributes = { } if update_attributes : new_attributes . update ( update_attributes ) new_bin = bins . bins ( interfeature_start , interfeature_stop , one = True ) _id = None fields = dict ( seqid = chrom , source = 'gffutils_derived' , featuretype = new_featuretype , start = interfeature_start , end = interfeature_stop , score = '.' , strand = strand , frame = '.' , attributes = new_attributes , bin = new_bin ) if dialect is None : # Support for @classmethod -- if calling from the class, then # self.dialect is not defined, so defer to Feature's default # (which will be constants.dialect, or GFF3). try : dialect = self . dialect except AttributeError : dialect = None yield self . _feature_returner ( * * fields ) interfeature_start = f . stop | Construct new features representing the space between features . | 486 | 9 |
16,860 | def update ( self , data , make_backup = True , * * kwargs ) : from gffutils import create from gffutils import iterators if make_backup : if isinstance ( self . dbfn , six . string_types ) : shutil . copy2 ( self . dbfn , self . dbfn + '.bak' ) # get iterator-specific kwargs _iterator_kwargs = { } for k , v in kwargs . items ( ) : if k in constants . _iterator_kwargs : _iterator_kwargs [ k ] = v # Handle all sorts of input data = iterators . DataIterator ( data , * * _iterator_kwargs ) if self . dialect [ 'fmt' ] == 'gtf' : if 'id_spec' not in kwargs : kwargs [ 'id_spec' ] = { 'gene' : 'gene_id' , 'transcript' : 'transcript_id' } db = create . _GTFDBCreator ( data = data , dbfn = self . dbfn , dialect = self . dialect , * * kwargs ) elif self . dialect [ 'fmt' ] == 'gff3' : if 'id_spec' not in kwargs : kwargs [ 'id_spec' ] = 'ID' db = create . _GFFDBCreator ( data = data , dbfn = self . dbfn , dialect = self . dialect , * * kwargs ) else : raise ValueError db . _populate_from_lines ( data ) db . _update_relations ( ) db . _finalize ( ) return db | Update database with features in data . | 372 | 7 |
16,861 | def create_introns ( self , exon_featuretype = 'exon' , grandparent_featuretype = 'gene' , parent_featuretype = None , new_featuretype = 'intron' , merge_attributes = True ) : if ( grandparent_featuretype and parent_featuretype ) or ( grandparent_featuretype is None and parent_featuretype is None ) : raise ValueError ( "exactly one of `grandparent_featuretype` or " "`parent_featuretype` should be provided" ) if grandparent_featuretype : def child_gen ( ) : for gene in self . features_of_type ( grandparent_featuretype ) : for child in self . children ( gene , level = 1 ) : yield child elif parent_featuretype : def child_gen ( ) : for child in self . features_of_type ( parent_featuretype ) : yield child for child in child_gen ( ) : exons = self . children ( child , level = 1 , featuretype = exon_featuretype , order_by = 'start' ) for intron in self . interfeatures ( exons , new_featuretype = new_featuretype , merge_attributes = merge_attributes , dialect = self . dialect ) : yield intron | Create introns from existing annotations . | 278 | 7 |
16,862 | def merge ( self , features , ignore_strand = False ) : # Consume iterator up front... features = list ( features ) if len ( features ) == 0 : raise StopIteration # Either set all strands to '+' or check for strand-consistency. if ignore_strand : strand = '.' else : strands = [ i . strand for i in features ] if len ( set ( strands ) ) > 1 : raise ValueError ( 'Specify ignore_strand=True to force merging ' 'of multiple strands' ) strand = strands [ 0 ] # Sanity check to make sure all features are from the same chromosome. chroms = [ i . chrom for i in features ] if len ( set ( chroms ) ) > 1 : raise NotImplementedError ( 'Merging multiple chromosomes not ' 'implemented' ) chrom = chroms [ 0 ] # To start, we create a merged feature of just the first feature. current_merged_start = features [ 0 ] . start current_merged_stop = features [ 0 ] . stop # We don't need to check the first one, so start at feature #2. for feature in features [ 1 : ] : # Does this feature start within the currently merged feature?... if feature . start <= current_merged_stop + 1 : # ...It starts within, so leave current_merged_start where it # is. Does it extend any farther? if feature . stop >= current_merged_stop : # Extends further, so set a new stop position current_merged_stop = feature . stop else : # If feature.stop < current_merged_stop, it's completely # within the previous feature. Nothing more to do. continue else : # The start position is outside the merged feature, so we're # done with the current merged feature. Prepare for output... merged_feature = dict ( seqid = feature . chrom , source = '.' , featuretype = feature . featuretype , start = current_merged_start , end = current_merged_stop , score = '.' , strand = strand , frame = '.' , attributes = '' ) yield self . _feature_returner ( * * merged_feature ) # and we start a new one, initializing with this feature's # start and stop. current_merged_start = feature . start current_merged_stop = feature . stop # need to yield the last one. if len ( features ) == 1 : feature = features [ 0 ] merged_feature = dict ( seqid = feature . chrom , source = '.' , featuretype = feature . featuretype , start = current_merged_start , end = current_merged_stop , score = '.' , strand = strand , frame = '.' , attributes = '' ) yield self . _feature_returner ( * * merged_feature ) | Merge overlapping features together . | 611 | 6 |
16,863 | def children_bp ( self , feature , child_featuretype = 'exon' , merge = False , ignore_strand = False ) : children = self . children ( feature , featuretype = child_featuretype , order_by = 'start' ) if merge : children = self . merge ( children , ignore_strand = ignore_strand ) total = 0 for child in children : total += len ( child ) return total | Total bp of all children of a featuretype . | 92 | 11 |
16,864 | def bed12 ( self , feature , block_featuretype = [ 'exon' ] , thick_featuretype = [ 'CDS' ] , thin_featuretype = None , name_field = 'ID' , color = None ) : if thick_featuretype and thin_featuretype : raise ValueError ( "Can only specify one of `thick_featuertype` or " "`thin_featuretype`" ) exons = list ( self . children ( feature , featuretype = block_featuretype , order_by = 'start' ) ) if len ( exons ) == 0 : exons = [ feature ] feature = self [ feature ] first = exons [ 0 ] . start last = exons [ - 1 ] . stop if first != feature . start : raise ValueError ( "Start of first exon (%s) does not match start of feature (%s)" % ( first , feature . start ) ) if last != feature . stop : raise ValueError ( "End of last exon (%s) does not match end of feature (%s)" % ( last , feature . stop ) ) if color is None : color = '0,0,0' color = color . replace ( ' ' , '' ) . strip ( ) # Use field names as defined at # http://genome.ucsc.edu/FAQ/FAQformat.html#format1 chrom = feature . chrom chromStart = feature . start - 1 chromEnd = feature . stop orig = constants . always_return_list constants . always_return_list = True try : name = feature [ name_field ] [ 0 ] except KeyError : name = "." constants . always_return_list = orig score = feature . score if score == '.' : score = '0' strand = feature . strand itemRgb = color blockCount = len ( exons ) blockSizes = [ len ( i ) for i in exons ] blockStarts = [ i . start - 1 - chromStart for i in exons ] if thick_featuretype : thick = list ( self . children ( feature , featuretype = thick_featuretype , order_by = 'start' ) ) if len ( thick ) == 0 : thickStart = feature . start thickEnd = feature . stop else : thickStart = thick [ 0 ] . start - 1 # BED 0-based coords thickEnd = thick [ - 1 ] . stop if thin_featuretype : thin = list ( self . children ( feature , featuretype = thin_featuretype , order_by = 'start' ) ) if len ( thin ) == 0 : thickStart = feature . start thickEnd = feature . stop else : thickStart = thin [ 0 ] . stop thickEnd = thin [ - 1 ] . start - 1 # BED 0-based coords tst = chromStart + blockStarts [ - 1 ] + blockSizes [ - 1 ] assert tst == chromEnd , "tst=%s; chromEnd=%s" % ( tst , chromEnd ) fields = [ chrom , chromStart , chromEnd , name , score , strand , thickStart , thickEnd , itemRgb , blockCount , ',' . join ( map ( str , blockSizes ) ) , ',' . join ( map ( str , blockStarts ) ) ] return '\t' . join ( map ( str , fields ) ) | Converts feature into a BED12 format . | 719 | 10 |
16,865 | def DataIterator ( data , checklines = 10 , transform = None , force_dialect_check = False , from_string = False , * * kwargs ) : _kwargs = dict ( data = data , checklines = checklines , transform = transform , force_dialect_check = force_dialect_check , * * kwargs ) if isinstance ( data , six . string_types ) : if from_string : return _StringIterator ( * * _kwargs ) else : if os . path . exists ( data ) : return _FileIterator ( * * _kwargs ) elif is_url ( data ) : return _UrlIterator ( * * _kwargs ) elif isinstance ( data , FeatureDB ) : _kwargs [ 'data' ] = data . all_features ( ) return _FeatureIterator ( * * _kwargs ) else : return _FeatureIterator ( * * _kwargs ) | Iterate over features no matter how they are provided . | 200 | 11 |
16,866 | def inspect ( data , look_for = [ 'featuretype' , 'chrom' , 'attribute_keys' , 'feature_count' ] , limit = None , verbose = True ) : results = { } obj_attrs = [ ] for i in look_for : if i not in [ 'attribute_keys' , 'feature_count' ] : obj_attrs . append ( i ) results [ i ] = Counter ( ) attr_keys = 'attribute_keys' in look_for d = iterators . DataIterator ( data ) feature_count = 0 for f in d : if verbose : sys . stderr . write ( '\r%s features inspected' % feature_count ) sys . stderr . flush ( ) for obj_attr in obj_attrs : results [ obj_attr ] . update ( [ getattr ( f , obj_attr ) ] ) if attr_keys : results [ 'attribute_keys' ] . update ( f . attributes . keys ( ) ) feature_count += 1 if limit and feature_count == limit : break new_results = { } for k , v in results . items ( ) : new_results [ k ] = dict ( v ) new_results [ 'feature_count' ] = feature_count return new_results | Inspect a GFF or GTF data source . | 280 | 11 |
16,867 | def clean_gff ( gff , cleaned , add_chr = False , chroms_to_ignore = None , featuretypes_to_ignore = None ) : logger . info ( "Cleaning GFF" ) chroms_to_ignore = chroms_to_ignore or [ ] featuretypes_to_ignore = featuretypes_to_ignore or [ ] with open ( cleaned , 'w' ) as fout : for i in gffutils . iterators . DataIterator ( gff ) : if add_chr : i . chrom = "chr" + i . chrom if i . chrom in chroms_to_ignore : continue if i . featuretype in featuretypes_to_ignore : continue fout . write ( str ( i ) + '\n' ) return cleaned | Cleans a GFF file by removing features on unwanted chromosomes and of unwanted featuretypes . Optionally adds chr to chrom names . | 172 | 27 |
16,868 | def feature_from_line ( line , dialect = None , strict = True , keep_order = False ) : if not strict : lines = line . splitlines ( False ) _lines = [ ] for i in lines : i = i . strip ( ) if len ( i ) > 0 : _lines . append ( i ) assert len ( _lines ) == 1 , _lines line = _lines [ 0 ] if '\t' in line : fields = line . rstrip ( '\n\r' ) . split ( '\t' ) else : fields = line . rstrip ( '\n\r' ) . split ( None , 8 ) else : fields = line . rstrip ( '\n\r' ) . split ( '\t' ) try : attr_string = fields [ 8 ] except IndexError : attr_string = "" attrs , _dialect = parser . _split_keyvals ( attr_string , dialect = dialect ) d = dict ( list ( zip ( constants . _gffkeys , fields ) ) ) d [ 'attributes' ] = attrs d [ 'extra' ] = fields [ 9 : ] d [ 'keep_order' ] = keep_order if dialect is None : dialect = _dialect return Feature ( dialect = dialect , * * d ) | Given a line from a GFF file return a Feature object | 283 | 12 |
16,869 | def calc_bin ( self , _bin = None ) : if _bin is None : try : _bin = bins . bins ( self . start , self . end , one = True ) except TypeError : _bin = None return _bin | Calculate the smallest UCSC genomic bin that will contain this feature . | 51 | 15 |
16,870 | def astuple ( self , encoding = None ) : if not encoding : return ( self . id , self . seqid , self . source , self . featuretype , self . start , self . end , self . score , self . strand , self . frame , helpers . _jsonify ( self . attributes ) , helpers . _jsonify ( self . extra ) , self . calc_bin ( ) ) return ( self . id . decode ( encoding ) , self . seqid . decode ( encoding ) , self . source . decode ( encoding ) , self . featuretype . decode ( encoding ) , self . start , self . end , self . score . decode ( encoding ) , self . strand . decode ( encoding ) , self . frame . decode ( encoding ) , helpers . _jsonify ( self . attributes ) . decode ( encoding ) , helpers . _jsonify ( self . extra ) . decode ( encoding ) , self . calc_bin ( ) ) | Return a tuple suitable for import into a database . | 200 | 10 |
16,871 | def sequence ( self , fasta , use_strand = True ) : if isinstance ( fasta , six . string_types ) : fasta = Fasta ( fasta , as_raw = False ) # recall GTF/GFF is 1-based closed; pyfaidx uses Python slice notation # and is therefore 0-based half-open. seq = fasta [ self . chrom ] [ self . start - 1 : self . stop ] if use_strand and self . strand == '-' : seq = seq . reverse . complement return seq . seq | Retrieves the sequence of this feature as a string . | 121 | 12 |
16,872 | def infer_dialect ( attributes ) : if isinstance ( attributes , six . string_types ) : attributes = [ attributes ] dialects = [ parser . _split_keyvals ( i ) [ 1 ] for i in attributes ] return _choose_dialect ( dialects ) | Infer the dialect based on the attributes . | 60 | 9 |
16,873 | def _choose_dialect ( dialects ) : # NOTE: can use helpers.dialect_compare if you need to make this more # complex.... # For now, this function favors the first dialect, and then appends the # order of additional fields seen in the attributes of other lines giving # priority to dialects that come first in the iterable. if len ( dialects ) == 0 : return constants . dialect final_order = [ ] for dialect in dialects : for o in dialect [ 'order' ] : if o not in final_order : final_order . append ( o ) dialect = dialects [ 0 ] dialect [ 'order' ] = final_order return dialect | Given a list of dialects choose the one to use as the canonical version . | 146 | 16 |
16,874 | def _bin_from_dict ( d ) : try : start = int ( d [ 'start' ] ) end = int ( d [ 'end' ] ) return bins . bins ( start , end , one = True ) # e.g., if "." except ValueError : return None | Given a dictionary yielded by the parser return the genomic UCSC bin | 62 | 13 |
16,875 | def _jsonify ( x ) : if isinstance ( x , dict_class ) : return json . dumps ( x . _d , separators = ( ',' , ':' ) ) return json . dumps ( x , separators = ( ',' , ':' ) ) | Use most compact form of JSON | 58 | 6 |
16,876 | def _unjsonify ( x , isattributes = False ) : if isattributes : obj = json . loads ( x ) return dict_class ( obj ) return json . loads ( x ) | Convert JSON string to an ordered defaultdict . | 42 | 10 |
16,877 | def _feature_to_fields ( f , jsonify = True ) : x = [ ] for k in constants . _keys : v = getattr ( f , k ) if jsonify and ( k in ( 'attributes' , 'extra' ) ) : x . append ( _jsonify ( v ) ) else : x . append ( v ) return tuple ( x ) | Convert feature to tuple for faster sqlite3 import | 80 | 11 |
16,878 | def _dict_to_fields ( d , jsonify = True ) : x = [ ] for k in constants . _keys : v = d [ k ] if jsonify and ( k in ( 'attributes' , 'extra' ) ) : x . append ( _jsonify ( v ) ) else : x . append ( v ) return tuple ( x ) | Convert dict to tuple for faster sqlite3 import | 77 | 11 |
16,879 | def merge_attributes ( attr1 , attr2 ) : new_d = copy . deepcopy ( attr1 ) new_d . update ( attr2 ) #all of attr2 key : values just overwrote attr1, fix it for k , v in new_d . items ( ) : if not isinstance ( v , list ) : new_d [ k ] = [ v ] for k , v in six . iteritems ( attr1 ) : if k in attr2 : if not isinstance ( v , list ) : v = [ v ] new_d [ k ] . extend ( v ) return dict ( ( k , sorted ( set ( v ) ) ) for k , v in new_d . items ( ) ) | Merges two attribute dictionaries into a single dictionary . | 164 | 11 |
16,880 | def dialect_compare ( dialect1 , dialect2 ) : orig = set ( dialect1 . items ( ) ) new = set ( dialect2 . items ( ) ) return dict ( added = dict ( list ( new . difference ( orig ) ) ) , removed = dict ( list ( orig . difference ( new ) ) ) ) | Compares two dialects . | 68 | 6 |
16,881 | def sanitize_gff_db ( db , gid_field = "gid" ) : def sanitized_iterator ( ) : # Iterate through the database by each gene's records for gene_recs in db . iter_by_parent_childs ( ) : # The gene's ID gene_id = gene_recs [ 0 ] . id for rec in gene_recs : # Fixup coordinates if necessary if rec . start > rec . stop : rec . start , rec . stop = rec . stop , rec . start # Add a gene id field to each gene's records rec . attributes [ gid_field ] = [ gene_id ] yield rec # Return sanitized GFF database sanitized_db = gffutils . create_db ( sanitized_iterator ( ) , ":memory:" , verbose = False ) return sanitized_db | Sanitize given GFF db . Returns a sanitized GFF db . | 187 | 16 |
16,882 | def sanitize_gff_file ( gff_fname , in_memory = True , in_place = False ) : db = None if is_gff_db ( gff_fname ) : # It's a database filename, so load it db = gffutils . FeatureDB ( gff_fname ) else : # Need to create a database for file if in_memory : db = gffutils . create_db ( gff_fname , ":memory:" , verbose = False ) else : db = get_gff_db ( gff_fname ) if in_place : gff_out = gffwriter . GFFWriter ( gff_fname , in_place = in_place ) else : gff_out = gffwriter . GFFWriter ( sys . stdout ) sanitized_db = sanitize_gff_db ( db ) for gene_rec in sanitized_db . all_features ( featuretype = "gene" ) : gff_out . write_gene_recs ( sanitized_db , gene_rec . id ) gff_out . close ( ) | Sanitize a GFF file . | 253 | 8 |
16,883 | def is_gff_db ( db_fname ) : if not os . path . isfile ( db_fname ) : return False if db_fname . endswith ( ".db" ) : return True return False | Return True if the given filename is a GFF database . | 50 | 12 |
16,884 | def get_gff_db ( gff_fname , ext = ".db" ) : if not os . path . isfile ( gff_fname ) : # Not sure how we should deal with errors normally in # gffutils -- Ryan? raise ValueError ( "GFF %s does not exist." % ( gff_fname ) ) candidate_db_fname = "%s.%s" % ( gff_fname , ext ) if os . path . isfile ( candidate_db_fname ) : # Standard .db file found, so return it return candidate_db_fname # Otherwise, we need to create a temporary but non-deleted # file to store the db in. It'll be up to the user # of the function the delete the file when done. ## NOTE: Ryan must have a good scheme for dealing with this ## since pybedtools does something similar under the hood, i.e. ## creating temporary files as needed without over proliferation db_fname = tempfile . NamedTemporaryFile ( delete = False ) # Create the database for the gff file (suppress output # when using function internally) print ( "Creating db for %s" % ( gff_fname ) ) t1 = time . time ( ) db = gffutils . create_db ( gff_fname , db_fname . name , merge_strategy = "merge" , verbose = False ) t2 = time . time ( ) print ( " - Took %.2f seconds" % ( t2 - t1 ) ) return db | Get db for GFF file . If the database has a . db file load that . Otherwise create a named temporary file serialize the db to that and return the loaded database . | 342 | 36 |
16,885 | def _reconstruct ( keyvals , dialect , keep_order = False , sort_attribute_values = False ) : if not dialect : raise AttributeStringError ( ) if not keyvals : return "" parts = [ ] # Re-encode when reconstructing attributes if constants . ignore_url_escape_characters or dialect [ 'fmt' ] != 'gff3' : attributes = keyvals else : attributes = { } for k , v in keyvals . items ( ) : attributes [ k ] = [ ] for i in v : attributes [ k ] . append ( '' . join ( [ quoter [ j ] for j in i ] ) ) # May need to split multiple values into multiple key/val pairs if dialect [ 'repeated keys' ] : items = [ ] for key , val in attributes . items ( ) : if len ( val ) > 1 : for v in val : items . append ( ( key , [ v ] ) ) else : items . append ( ( key , val ) ) else : items = list ( attributes . items ( ) ) def sort_key ( x ) : # sort keys by their order in the dialect; anything not in there will # be in arbitrary order at the end. try : return dialect [ 'order' ] . index ( x [ 0 ] ) except ValueError : return 1e6 if keep_order : items . sort ( key = sort_key ) for key , val in items : # Multival sep is usually a comma: if val : if sort_attribute_values : val = sorted ( val ) val_str = dialect [ 'multival separator' ] . join ( val ) if val_str : # Surround with quotes if needed if dialect [ 'quoted GFF2 values' ] : val_str = '"%s"' % val_str # Typically "=" for GFF3 or " " otherwise part = dialect [ 'keyval separator' ] . join ( [ key , val_str ] ) else : if dialect [ 'fmt' ] == 'gtf' : part = dialect [ 'keyval separator' ] . join ( [ key , '""' ] ) else : part = key parts . append ( part ) # Typically ";" or "; " parts_str = dialect [ 'field separator' ] . join ( parts ) # Sometimes need to add this if dialect [ 'trailing semicolon' ] : parts_str += ';' return parts_str | Reconstructs the original attributes string according to the dialect . | 524 | 13 |
16,886 | def create_db ( data , dbfn , id_spec = None , force = False , verbose = False , checklines = 10 , merge_strategy = 'error' , transform = None , gtf_transcript_key = 'transcript_id' , gtf_gene_key = 'gene_id' , gtf_subfeature = 'exon' , force_gff = False , force_dialect_check = False , from_string = False , keep_order = False , text_factory = sqlite3 . OptimizedUnicode , force_merge_fields = None , pragmas = constants . default_pragmas , sort_attribute_values = False , dialect = None , _keep_tempfiles = False , infer_gene_extent = True , disable_infer_genes = False , disable_infer_transcripts = False , * * kwargs ) : _locals = locals ( ) # Check if any older kwargs made it in deprecation_handler ( kwargs ) kwargs = dict ( ( i , _locals [ i ] ) for i in constants . _iterator_kwargs ) # First construct an iterator so that we can identify the file format. # DataIterator figures out what kind of data was provided (string of lines, # filename, or iterable of Features) and checks `checklines` lines to # identify the dialect. iterator = iterators . DataIterator ( * * kwargs ) kwargs . update ( * * _locals ) if dialect is None : dialect = iterator . dialect # However, a side-effect of this is that if `data` was a generator, then # we've just consumed `checklines` items (see # iterators.BaseIterator.__init__, which calls iterators.peek). # # But it also chains those consumed items back onto the beginning, and the # result is available as as iterator._iter. # # That's what we should be using now for `data: kwargs [ 'data' ] = iterator . _iter kwargs [ 'directives' ] = iterator . directives # Since we've already checked lines, we don't want to do it again kwargs [ 'checklines' ] = 0 if force_gff or ( dialect [ 'fmt' ] == 'gff3' ) : cls = _GFFDBCreator id_spec = id_spec or 'ID' add_kwargs = dict ( id_spec = id_spec , ) elif dialect [ 'fmt' ] == 'gtf' : cls = _GTFDBCreator id_spec = id_spec or { 'gene' : 'gene_id' , 'transcript' : 'transcript_id' } add_kwargs = dict ( transcript_key = gtf_transcript_key , gene_key = gtf_gene_key , subfeature = gtf_subfeature , id_spec = id_spec , ) kwargs . update ( * * add_kwargs ) kwargs [ 'dialect' ] = dialect c = cls ( * * kwargs ) c . create ( ) if dbfn == ':memory:' : db = interface . FeatureDB ( c . conn , keep_order = keep_order , pragmas = pragmas , sort_attribute_values = sort_attribute_values , text_factory = text_factory ) else : db = interface . FeatureDB ( c , keep_order = keep_order , pragmas = pragmas , sort_attribute_values = sort_attribute_values , text_factory = text_factory ) return db | Create a database from a GFF or GTF file . | 805 | 12 |
16,887 | def _id_handler ( self , f ) : # If id_spec is a string, convert to iterable for later if isinstance ( self . id_spec , six . string_types ) : id_key = [ self . id_spec ] elif hasattr ( self . id_spec , '__call__' ) : id_key = [ self . id_spec ] # If dict, then assume it's a feature -> attribute mapping, e.g., # {'gene': 'gene_id'} for GTF elif isinstance ( self . id_spec , dict ) : try : id_key = self . id_spec [ f . featuretype ] if isinstance ( id_key , six . string_types ) : id_key = [ id_key ] # Otherwise, use default auto-increment. except KeyError : return self . _increment_featuretype_autoid ( f . featuretype ) # Otherwise assume it's an iterable. else : id_key = self . id_spec # Then try them in order, returning the first one that works: for k in id_key : if hasattr ( k , '__call__' ) : _id = k ( f ) if _id : if _id . startswith ( 'autoincrement:' ) : return self . _increment_featuretype_autoid ( _id [ 14 : ] ) return _id else : # use GFF fields rather than attributes for cases like :seqid: # or :strand: if ( len ( k ) > 3 ) and ( k [ 0 ] == ':' ) and ( k [ - 1 ] == ':' ) : # No [0] here -- only attributes key/vals are forced into # lists, not standard GFF fields. return getattr ( f , k [ 1 : - 1 ] ) else : try : return f . attributes [ k ] [ 0 ] except ( KeyError , IndexError ) : pass # If we get here, then default autoincrement return self . _increment_featuretype_autoid ( f . featuretype ) | Given a Feature from self . iterator figure out what the ID should be . | 452 | 15 |
16,888 | def create ( self ) : # Calls each of these methods in order. _populate_from_lines and # _update_relations must be implemented in subclasses. self . _init_tables ( ) self . _populate_from_lines ( self . iterator ) self . _update_relations ( ) self . _finalize ( ) | Calls various methods sequentially in order to fully build the database . | 73 | 14 |
16,889 | def execute ( self , query ) : c = self . conn . cursor ( ) result = c . execute ( query ) for i in result : yield i | Execute a query directly on the database . | 32 | 9 |
16,890 | def wait_for_js ( function ) : @ functools . wraps ( function ) def wrapper ( * args , * * kwargs ) : # pylint: disable=missing-docstring # If not a method, then just call the function if len ( args ) < 1 : return function ( * args , * * kwargs ) # Otherwise, retrieve `self` as the first arg else : self = args [ 0 ] # If the class has been decorated by one of the # JavaScript dependency decorators, it should have # a `wait_for_js` method if hasattr ( self , 'wait_for_js' ) : self . wait_for_js ( ) # Call the function return function ( * args , * * kwargs ) return wrapper | Method decorator that waits for JavaScript dependencies before executing function . If the function is not a method the decorator has no effect . | 165 | 26 |
16,891 | def _wait_for_js ( self ) : # No Selenium browser available, so return without doing anything if not hasattr ( self , 'browser' ) : return # pylint: disable=protected-access # Wait for JavaScript variables to be defined if hasattr ( self , '_js_vars' ) and self . _js_vars : EmptyPromise ( lambda : _are_js_vars_defined ( self . browser , self . _js_vars ) , u"JavaScript variables defined: {0}" . format ( ", " . join ( self . _js_vars ) ) ) . fulfill ( ) # Wait for RequireJS dependencies to load if hasattr ( self , '_requirejs_deps' ) and self . _requirejs_deps : EmptyPromise ( lambda : _are_requirejs_deps_loaded ( self . browser , self . _requirejs_deps ) , u"RequireJS dependencies loaded: {0}" . format ( ", " . join ( self . _requirejs_deps ) ) , try_limit = 5 ) . fulfill ( ) | Class method added by the decorators to allow decorated classes to manually re - check JavaScript dependencies . | 243 | 19 |
16,892 | def _are_js_vars_defined ( browser , js_vars ) : # This script will evaluate to True iff all of # the required vars are defined. script = u" && " . join ( [ u"!(typeof {0} === 'undefined')" . format ( var ) for var in js_vars ] ) try : return browser . execute_script ( u"return {}" . format ( script ) ) except WebDriverException as exc : if "is not defined" in exc . msg or "is undefined" in exc . msg : return False else : raise | Return a boolean indicating whether all the JavaScript variables js_vars are defined on the current page . | 128 | 20 |
16,893 | def _are_requirejs_deps_loaded ( browser , deps ) : # This is a little complicated # # We're going to use `execute_async_script` to give control to # the browser. The browser indicates that it wants to return # control to us by calling `callback`, which is the last item # in the global `arguments` array. # # We install a RequireJS module with the dependencies we want # to ensure are loaded. When our module loads, we return # control to the test suite. script = dedent ( u""" // Retrieve the callback function used to return control to the test suite var callback = arguments[arguments.length - 1]; // If RequireJS isn't defined, then return immediately if (!window.require) {{ callback("RequireJS not defined"); }} // Otherwise, install a RequireJS module that depends on the modules // we're waiting for. else {{ // Catch errors reported by RequireJS requirejs.onError = callback; // Install our module require({deps}, function() {{ callback('Success'); }}); }} """ ) . format ( deps = json . dumps ( list ( deps ) ) ) # Set a timeout to ensure we get control back browser . set_script_timeout ( 30 ) # Give control to the browser # `result` will be the argument passed to the callback function try : result = browser . execute_async_script ( script ) return result == 'Success' except TimeoutException : return False | Return a boolean indicating whether all the RequireJS dependencies deps have loaded on the current page . | 317 | 20 |
16,894 | def no_selenium_errors ( func ) : def _inner ( * args , * * kwargs ) : # pylint: disable=missing-docstring try : return_val = func ( * args , * * kwargs ) except WebDriverException : LOGGER . warning ( u'Exception ignored during retry loop:' , exc_info = True ) return False else : return return_val return _inner | Decorator to create an EmptyPromise check function that is satisfied only when func executes without a Selenium error . | 90 | 24 |
16,895 | def set_rules ( self , rules ) : self . rules_to_ignore = rules . get ( "ignore" , [ ] ) self . rules_to_run = rules . get ( "apply" , [ ] ) | Sets the rules to be run or ignored for the audit . | 48 | 13 |
16,896 | def set_scope ( self , include = None , exclude = None ) : if include : self . scope = u"document.querySelector(\"{}\")" . format ( u', ' . join ( include ) ) else : self . scope = "null" if exclude is not None : raise NotImplementedError ( "The argument `exclude` has not been implemented in " "AxsAuditConfig.set_scope method." ) | Sets scope the start point for the audit . | 96 | 10 |
16,897 | def _check_rules ( browser , rules_js , config ) : if config . rules_to_run is None : msg = 'No accessibility rules were specified to check.' log . warning ( msg ) return None # This line will only be included in the script if rules to check on # this page are specified, as the default behavior of the js is to # run all rules. rules = config . rules_to_run if rules : rules_config = u"auditConfig.auditRulesToRun = {rules};" . format ( rules = rules ) else : rules_config = "" ignored_rules = config . rules_to_ignore if ignored_rules : rules_config += ( u"\nauditConfig.auditRulesToIgnore = {rules};" . format ( rules = ignored_rules ) ) script = dedent ( u""" {rules_js} var auditConfig = new axs.AuditConfiguration(); {rules_config} auditConfig.scope = {scope}; var run_results = axs.Audit.run(auditConfig); var audit_results = axs.Audit.auditResults(run_results) return audit_results; """ . format ( rules_js = rules_js , rules_config = rules_config , scope = config . scope ) ) result = browser . execute_script ( script ) # audit_results is report of accessibility errors for that session audit_results = AuditResults ( errors = result . get ( 'errors_' ) , warnings = result . get ( 'warnings_' ) ) return audit_results | Check the page for violations of the configured rules . By default all rules in the ruleset will be checked . | 339 | 22 |
16,898 | def fulfill ( self ) : is_fulfilled , result = self . _check_fulfilled ( ) if is_fulfilled : return result else : raise BrokenPromise ( self ) | Evaluate the promise and return the result . | 39 | 10 |
16,899 | def search ( self ) : self . q ( css = 'button.btn' ) . click ( ) GitHubSearchResultsPage ( self . browser ) . wait_for_page ( ) | Click on the Search button and wait for the results page to be displayed | 40 | 14 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.