idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
7,500
def write ( self , s , ** args ) : if self . filename is not None : self . start_fileoutput ( ) if self . fd is None : log . warn ( LOG_CHECK , "writing to unitialized or closed file" ) else : try : self . fd . write ( s , ** args ) except IOError : msg = sys . exc_info ( ) [ 1 ] log . warn ( LOG_CHECK , "Could not wri...
Write string to output descriptor . Strips control characters from string before writing .
7,501
def writeln ( self , s = u"" , ** args ) : self . write ( u"%s%s" % ( s , unicode ( os . linesep ) ) , ** args )
Write string to output descriptor plus a newline .
7,502
def start_output ( self ) : if self . logparts is None : parts = Fields . keys ( ) else : parts = self . logparts values = ( self . part ( x ) for x in parts ) self . max_indent = max ( len ( x ) for x in values ) + 1 for key in parts : numspaces = ( self . max_indent - len ( self . part ( key ) ) ) self . logspaces [ ...
Start log output .
7,503
def log_filter_url ( self , url_data , do_print ) : self . stats . log_url ( url_data , do_print ) if do_print : self . log_url ( url_data )
Log a new url with this logger if do_print is True . Else only update accounting data .
7,504
def write_intro ( self ) : self . comment ( _ ( "created by %(app)s at %(time)s" ) % { "app" : configuration . AppName , "time" : strformat . strtime ( self . starttime ) } ) self . comment ( _ ( "Get the newest version at %(url)s" ) % { 'url' : configuration . Url } ) self . comment ( _ ( "Write comments and bugs to %...
Write intro comments .
7,505
def write_outro ( self ) : self . stoptime = time . time ( ) duration = self . stoptime - self . starttime self . comment ( _ ( "Stopped checking at %(time)s (%(duration)s)" ) % { "time" : strformat . strtime ( self . stoptime ) , "duration" : strformat . strduration_long ( duration ) } )
Write outro comments .
7,506
def format_modified ( self , modified , sep = " " ) : if modified is not None : return modified . strftime ( "%Y-%m-%d{0}%H:%M:%S.%fZ" . format ( sep ) ) return u""
Format modification date in UTC if it s not None .
7,507
def formvalue ( form , key ) : field = form . get ( key ) if isinstance ( field , list ) : field = field [ 0 ] return field
Get value with given key from WSGI form .
7,508
def checklink ( form = None , env = os . environ ) : if form is None : form = { } try : checkform ( form , env ) except LCFormError as errmsg : log ( env , errmsg ) yield encode ( format_error ( errmsg ) ) return out = ThreadsafeIO ( ) config = get_configuration ( form , out ) url = strformat . stripurl ( formvalue ( f...
Validates the CGI form and checks the given links .
7,509
def start_check ( aggregate , out ) : t = threading . Thread ( target = director . check_urls , args = ( aggregate , ) ) t . start ( ) sleep_seconds = 2 run_seconds = 0 while not aggregate . is_finished ( ) : yield out . get_data ( ) time . sleep ( sleep_seconds ) run_seconds += sleep_seconds if run_seconds > MAX_REQUE...
Start checking in background and write encoded output to out .
7,510
def get_configuration ( form , out ) : config = configuration . Configuration ( ) config [ "recursionlevel" ] = int ( formvalue ( form , "level" ) ) config [ "logger" ] = config . logger_new ( 'html' , fd = out , encoding = HTML_ENCODING ) config [ "threads" ] = 2 if "anchors" in form : config [ "enabledplugins" ] . ap...
Initialize a CGI configuration .
7,511
def checkform ( form , env ) : if "language" in form : lang = formvalue ( form , 'language' ) if lang in _supported_langs : localestr = lang_locale [ lang ] try : locale . setlocale ( locale . LC_ALL , localestr ) init_i18n ( ) except locale . Error as errmsg : log ( env , "could not set locale %r: %s" % ( localestr , ...
Check form data . throw exception on error Be sure to NOT print out any user - given data as HTML code so use only plain strings as exception text .
7,512
def dump ( env , form ) : for var , value in env . items ( ) : log ( env , var + "=" + value ) for key in form : log ( env , str ( formvalue ( form , key ) ) )
Log environment and form .
7,513
def write ( self , data ) : assert isinstance ( data , unicode ) if self . closed : raise IOError ( "Write on closed I/O object" ) if data : self . buf . append ( data )
Write given unicode data to buffer .
7,514
def get_data ( self ) : data = u"" . join ( self . buf ) self . buf = [ ] return data
Get bufferd unicode data .
7,515
def parse_opera ( url_data ) : from . . bookmarks . opera import parse_bookmark_data for url , name , lineno in parse_bookmark_data ( url_data . get_content ( ) ) : url_data . add_url ( url , line = lineno , name = name )
Parse an opera bookmark file .
7,516
def parse_chromium ( url_data ) : from . . bookmarks . chromium import parse_bookmark_data for url , name in parse_bookmark_data ( url_data . get_content ( ) ) : url_data . add_url ( url , name = name )
Parse a Chromium or Google Chrome bookmark file .
7,517
def parse_safari ( url_data ) : from . . bookmarks . safari import parse_bookmark_data for url , name in parse_bookmark_data ( url_data . get_content ( ) ) : url_data . add_url ( url , name = name )
Parse a Safari bookmark file .
7,518
def parse_text ( url_data ) : lineno = 0 for line in url_data . get_content ( ) . splitlines ( ) : lineno += 1 line = line . strip ( ) if not line or line . startswith ( '#' ) : continue url_data . add_url ( line , line = lineno )
Parse a text file with one url per line ; comment and blank lines are ignored .
7,519
def parse_swf ( url_data ) : linkfinder = linkparse . swf_url_re . finditer for mo in linkfinder ( url_data . get_content ( ) ) : url = mo . group ( ) url_data . add_url ( url )
Parse a SWF file for URLs .
7,520
def find_links ( url_data , callback , tags ) : handler = linkparse . LinkFinder ( callback , tags ) parser = htmlsax . parser ( handler ) if url_data . charset : parser . encoding = url_data . charset handler . parser = parser try : parser . feed ( url_data . get_content ( ) ) parser . flush ( ) except linkparse . Sto...
Parse into content and search for URLs to check . Found URLs are added to the URL queue .
7,521
def parse_firefox ( url_data ) : filename = url_data . get_os_filename ( ) for url , name in firefox . parse_bookmark_file ( filename ) : url_data . add_url ( url , name = name )
Parse a Firefox3 bookmark file .
7,522
def parse_itms_services ( url_data ) : query = url_data . urlparts [ 3 ] for k , v , sep in urlutil . parse_qsl ( query , keep_blank_values = True ) : if k == "url" : url_data . add_url ( v ) break
Get url CGI parameter value as child URL .
7,523
def get_package_modules ( packagename ) : if is_frozen ( ) : zipname = os . path . dirname ( os . path . dirname ( __file__ ) ) parentmodule = os . path . basename ( os . path . dirname ( __file__ ) ) with zipfile . ZipFile ( zipname , 'r' ) as f : prefix = "%s/%s/" % ( parentmodule , packagename ) modnames = [ os . pa...
Find all valid modules in the given package which must be a folder in the same directory as this loader . py module . A valid module has a . py extension and is importable .
7,524
def get_lock ( name , debug = False ) : lock = threading . Lock ( ) if debug : lock = DebugLock ( lock , name ) return lock
Get a new lock .
7,525
def get_semaphore ( name , value = None , debug = False ) : if value is None : lock = threading . Semaphore ( ) else : lock = threading . BoundedSemaphore ( value ) if debug : lock = DebugLock ( lock , name ) return lock
Get a new semaphore .
7,526
def acquire ( self , blocking = 1 ) : threadname = threading . currentThread ( ) . getName ( ) log . debug ( LOG_THREAD , "Acquire %s for %s" , self . name , threadname ) self . lock . acquire ( blocking ) log . debug ( LOG_THREAD , "...acquired %s for %s" , self . name , threadname )
Acquire lock .
7,527
def read_multiline ( value ) : for line in value . splitlines ( ) : line = line . strip ( ) if not line or line . startswith ( '#' ) : continue yield line
Helper function reading multiline values .
7,528
def read_string_option ( self , section , option , allowempty = False ) : if self . has_option ( section , option ) : value = self . get ( section , option ) if not allowempty and not value : raise LinkCheckerError ( _ ( "invalid empty value for %s: %s\n" ) % ( option , value ) ) self . config [ option ] = value
Read a string option .
7,529
def read_boolean_option ( self , section , option ) : if self . has_option ( section , option ) : self . config [ option ] = self . getboolean ( section , option )
Read a boolean option .
7,530
def read_int_option ( self , section , option , key = None , min = None , max = None ) : if self . has_option ( section , option ) : num = self . getint ( section , option ) if min is not None and num < min : raise LinkCheckerError ( _ ( "invalid value for %s: %d must not be less than %d" ) % ( option , num , min ) ) i...
Read an integer option .
7,531
def read_output_config ( self ) : section = "output" from . . logger import LoggerClasses for c in LoggerClasses : key = c . LoggerName if self . has_section ( key ) : for opt in self . options ( key ) : self . config [ key ] [ opt ] = self . get ( key , opt ) if self . has_option ( key , 'parts' ) : val = self . get (...
Read configuration options in section output .
7,532
def read_checking_config ( self ) : section = "checking" self . read_int_option ( section , "threads" , min = - 1 ) self . config [ 'threads' ] = max ( 0 , self . config [ 'threads' ] ) self . read_int_option ( section , "timeout" , min = 1 ) self . read_int_option ( section , "aborttimeout" , min = 1 ) self . read_int...
Read configuration options in section checking .
7,533
def read_authentication_config ( self ) : section = "authentication" password_fields = [ ] if self . has_option ( section , "entry" ) : for val in read_multiline ( self . get ( section , "entry" ) ) : auth = val . split ( ) if len ( auth ) == 3 : self . config . add_auth ( pattern = auth [ 0 ] , user = auth [ 1 ] , pas...
Read configuration options in section authentication .
7,534
def check_password_readable ( self , section , fields ) : if not fields : return if len ( self . read_ok ) != 1 : return fn = self . read_ok [ 0 ] if fileutil . is_accessable_by_others ( fn ) : log . warn ( LOG_CHECK , "The configuration file %s contains password information (in section [%s] and options %s) and the fil...
Check if there is a readable configuration file and print a warning .
7,535
def read_filtering_config ( self ) : section = "filtering" if self . has_option ( section , "ignorewarnings" ) : self . config [ 'ignorewarnings' ] = [ f . strip ( ) . lower ( ) for f in self . get ( section , 'ignorewarnings' ) . split ( ',' ) ] if self . has_option ( section , "ignore" ) : for line in read_multiline ...
Read configuration options in section filtering .
7,536
def read_plugin_config ( self ) : folders = self . config [ "pluginfolders" ] modules = plugins . get_plugin_modules ( folders ) for pluginclass in plugins . get_plugin_classes ( modules ) : section = pluginclass . __name__ if self . has_section ( section ) : self . config [ "enabledplugins" ] . append ( section ) self...
Read plugin - specific configuration values .
7,537
def check ( self , url_data ) : log . debug ( LOG_PLUGIN , "checking content for warning regex" ) content = url_data . get_content ( ) match = self . warningregex . search ( content ) if match : line = content . count ( '\n' , 0 , match . start ( ) ) msg = _ ( "Found %(match)r at line %(line)d in link contents." ) url_...
Check content .
7,538
def _set_section ( self , section ) : if self . section != section : if self . section > section : raise dns . exception . FormError self . section = section
Set the renderer s current section .
7,539
def add_question ( self , qname , rdtype , rdclass = dns . rdataclass . IN ) : self . _set_section ( QUESTION ) before = self . output . tell ( ) qname . to_wire ( self . output , self . compress , self . origin ) self . output . write ( struct . pack ( "!HH" , rdtype , rdclass ) ) after = self . output . tell ( ) if a...
Add a question to the message .
7,540
def add_rrset ( self , section , rrset , ** kw ) : self . _set_section ( section ) before = self . output . tell ( ) n = rrset . to_wire ( self . output , self . compress , self . origin , ** kw ) after = self . output . tell ( ) if after >= self . max_size : self . _rollback ( before ) raise dns . exception . TooBig s...
Add the rrset to the specified section .
7,541
def add_rdataset ( self , section , name , rdataset , ** kw ) : self . _set_section ( section ) before = self . output . tell ( ) n = rdataset . to_wire ( name , self . output , self . compress , self . origin , ** kw ) after = self . output . tell ( ) if after >= self . max_size : self . _rollback ( before ) raise dns...
Add the rdataset to the specified section using the specified name as the owner name .
7,542
def add_edns ( self , edns , ednsflags , payload , options = None ) : ednsflags &= 0xFF00FFFFL ednsflags |= ( edns << 16 ) self . _set_section ( ADDITIONAL ) before = self . output . tell ( ) self . output . write ( struct . pack ( '!BHHIH' , 0 , dns . rdatatype . OPT , payload , ednsflags , 0 ) ) if not options is Non...
Add an EDNS OPT record to the message .
7,543
def add_tsig ( self , keyname , secret , fudge , id , tsig_error , other_data , request_mac , algorithm = dns . tsig . default_algorithm ) : self . _set_section ( ADDITIONAL ) before = self . output . tell ( ) s = self . output . getvalue ( ) ( tsig_rdata , self . mac , ctx ) = dns . tsig . sign ( s , keyname , secret ...
Add a TSIG signature to the message .
7,544
def write_header ( self ) : self . output . seek ( 0 ) self . output . write ( struct . pack ( '!HHHHHH' , self . id , self . flags , self . counts [ 0 ] , self . counts [ 1 ] , self . counts [ 2 ] , self . counts [ 3 ] ) ) self . output . seek ( 0 , 2 )
Write the DNS message header .
7,545
def option_from_wire ( otype , wire , current , olen ) : cls = get_option_class ( otype ) return cls . from_wire ( otype , wire , current , olen )
Build an EDNS option object from wire format
7,546
def comment ( self , s , ** args ) : self . writeln ( s = u"# %s" % s , ** args )
Write CSV comment .
7,547
def start_output ( self ) : super ( CSVLogger , self ) . start_output ( ) row = [ ] if self . has_part ( "intro" ) : self . write_intro ( ) self . flush ( ) else : self . write ( u"" ) self . queue = StringIO ( ) self . writer = csv . writer ( self . queue , dialect = self . dialect , delimiter = self . separator , lin...
Write checking start info as csv comment .
7,548
def log_url ( self , url_data ) : row = [ ] if self . has_part ( "urlname" ) : row . append ( url_data . base_url ) if self . has_part ( "parentname" ) : row . append ( url_data . parent_url ) if self . has_part ( "baseref" ) : row . append ( url_data . base_ref ) if self . has_part ( "result" ) : row . append ( url_da...
Write csv formatted url check info .
7,549
def check_urls ( urlqueue , logger ) : while not urlqueue . empty ( ) : url_data = urlqueue . get ( ) try : check_url ( url_data , logger ) finally : urlqueue . task_done ( url_data )
Check URLs without threading .
7,550
def check_url ( url_data , logger ) : if url_data . has_result : logger . log_url ( url_data . to_wire ( ) ) else : cache = url_data . aggregate . result_cache key = url_data . cache_url result = cache . get_result ( key ) if result is None : check_start = time . time ( ) try : url_data . check ( ) do_parse = url_data ...
Check a single URL with logging .
7,551
def check_url ( self ) : try : url_data = self . urlqueue . get ( timeout = QUEUE_POLL_INTERVALL_SECS ) if url_data is not None : try : self . check_url_data ( url_data ) finally : self . urlqueue . task_done ( url_data ) self . setName ( self . origname ) except urlqueue . Empty : pass except Exception : self . intern...
Try to get URL data from queue and check it .
7,552
def check_url_data ( self , url_data ) : if url_data . url is None : url = "" else : url = url_data . url . encode ( "ascii" , "replace" ) self . setName ( "CheckThread-%s" % url ) check_url ( url_data , self . logger )
Check one URL data instance .
7,553
def udp ( q , where , timeout = None , port = 53 , af = None , source = None , source_port = 0 , ignore_unexpected = False , one_rr_per_rrset = False ) : wire = q . to_wire ( ) if af is None : try : af = dns . inet . af_for_address ( where ) except Exception : af = dns . inet . AF_INET if af == dns . inet . AF_INET : d...
Return the response obtained after sending a query via UDP .
7,554
def _net_read ( sock , count , expiration ) : s = '' while count > 0 : _wait_for_readable ( sock , expiration ) n = sock . recv ( count ) if n == '' : raise EOFError count = count - len ( n ) s = s + n return s
Read the specified number of bytes from sock . Keep trying until we either get the desired amount or we hit EOF . A Timeout exception will be raised if the operation is not completed by the expiration time .
7,555
def _net_write ( sock , data , expiration ) : current = 0 l = len ( data ) while current < l : _wait_for_writable ( sock , expiration ) current += sock . send ( data [ current : ] )
Write the specified data to the socket . A Timeout exception will be raised if the operation is not completed by the expiration time .
7,556
def tcp ( q , where , timeout = None , port = 53 , af = None , source = None , source_port = 0 , one_rr_per_rrset = False ) : wire = q . to_wire ( ) if af is None : try : af = dns . inet . af_for_address ( where ) except Exception : af = dns . inet . AF_INET if af == dns . inet . AF_INET : destination = ( where , port ...
Return the response obtained after sending a query via TCP .
7,557
def from_text ( text ) : value = _by_text . get ( text . upper ( ) ) if value is None : match = _unknown_type_pattern . match ( text ) if match == None : raise UnknownRdatatype value = int ( match . group ( 1 ) ) if value < 0 or value > 65535 : raise ValueError ( "type must be between >= 0 and <= 65535" ) return value
Convert text into a DNS rdata type value .
7,558
def is_metatype ( rdtype ) : if rdtype >= TKEY and rdtype <= ANY or rdtype in _metatypes : return True return False
True if the type is a metatype .
7,559
def run_checked ( self ) : self . start_time = time . time ( ) self . setName ( "Status" ) wait_seconds = 1 first_wait = True while not self . stopped ( wait_seconds ) : self . log_status ( ) if first_wait : wait_seconds = self . wait_seconds first_wait = False
Print periodic status messages .
7,560
def log_status ( self ) : duration = time . time ( ) - self . start_time checked , in_progress , queue = self . aggregator . urlqueue . status ( ) num_urls = len ( self . aggregator . result_cache ) self . logger . log_status ( checked , in_progress , queue , duration , num_urls )
Log a status message .
7,561
def init_mimedb ( ) : global mimedb try : mimedb = mimetypes . MimeTypes ( strict = False ) except Exception as msg : log . error ( LOG_CHECK , "could not initialize MIME database: %s" % msg ) return add_mimetype ( mimedb , 'text/plain' , '.adr' ) add_mimetype ( mimedb , 'application/x-httpd-php' , '.php' ) add_mimetyp...
Initialize the local MIME database .
7,562
def add_mimetype ( mimedb , mimetype , extension ) : strict = extension in mimedb . types_map [ True ] mimedb . add_type ( mimetype , extension , strict = strict )
Add or replace a mimetype to be used with the given extension .
7,563
def search_form ( content , cgiuser , cgipassword , encoding = 'utf-8' ) : handler = FormFinder ( ) parser = htmlsax . parser ( handler ) handler . parser = parser parser . encoding = encoding parser . feed ( content ) parser . flush ( ) handler . parser = None parser . handler = None log . debug ( LOG_CHECK , "Found f...
Search for a HTML form in the given HTML content that has the given CGI fields . If no form is found return None .
7,564
def end_element ( self , tag ) : if tag == u'form' : self . forms . append ( self . form ) self . form = None
search for ending form values .
7,565
def init_i18n ( loc = None ) : if 'LOCPATH' in os . environ : locdir = os . environ [ 'LOCPATH' ] else : locdir = os . path . join ( get_install_data ( ) , 'share' , 'locale' ) i18n . init ( configdata . name . lower ( ) , locdir , loc = loc ) import logging logging . addLevelName ( logging . CRITICAL , _ ( 'CRITICAL' ...
Initialize i18n with the configured locale dir . The environment variable LOCPATH can also specify a locale dir .
7,566
def drop_privileges ( ) : if os . name != 'posix' : return if os . geteuid ( ) == 0 : log . warn ( LOG_CHECK , _ ( "Running as root user; " "dropping privileges by changing user to nobody." ) ) import pwd os . seteuid ( pwd . getpwnam ( 'nobody' ) [ 3 ] )
Make sure to drop root privileges on POSIX systems .
7,567
def find_third_party_modules ( ) : parent = os . path . dirname ( os . path . dirname ( __file__ ) ) third_party = os . path . join ( parent , "third_party" ) if os . path . isdir ( third_party ) : sys . path . append ( os . path . join ( third_party , "dnspython" ) )
Find third party modules and add them to the python path .
7,568
def get_plist_data_from_file ( filename ) : if has_biplist : return biplist . readPlist ( filename ) try : return plistlib . readPlist ( filename ) except Exception : return { }
Parse plist data for a file . Tries biplist falling back to plistlib .
7,569
def get_plist_data_from_string ( data ) : if has_biplist : return biplist . readPlistFromString ( data ) try : return plistlib . readPlistFromString ( data ) except Exception : return { }
Parse plist data for a string . Tries biplist falling back to plistlib .
7,570
def parse_plist ( entry ) : if is_leaf ( entry ) : url = entry [ KEY_URLSTRING ] title = entry [ KEY_URIDICTIONARY ] . get ( 'title' , url ) yield ( url , title ) elif has_children ( entry ) : for child in entry [ KEY_CHILDREN ] : for item in parse_plist ( child ) : yield item
Parse a XML dictionary entry .
7,571
def algorithm_from_text ( text ) : value = _algorithm_by_text . get ( text . upper ( ) ) if value is None : value = int ( text ) return value
Convert text into a DNSSEC algorithm value
7,572
def algorithm_to_text ( value ) : text = _algorithm_by_value . get ( value ) if text is None : text = str ( value ) return text
Convert a DNSSEC algorithm value to text
7,573
def _validate ( rrset , rrsigset , keys , origin = None , now = None ) : if isinstance ( origin , ( str , unicode ) ) : origin = dns . name . from_text ( origin , dns . name . root ) if isinstance ( rrset , tuple ) : rrname = rrset [ 0 ] else : rrname = rrset . name if isinstance ( rrsigset , tuple ) : rrsigname = rrsi...
Validate an RRset
7,574
def allows_url ( self , url_data ) : roboturl = url_data . get_robots_txt_url ( ) with self . get_lock ( roboturl ) : return self . _allows_url ( url_data , roboturl )
Ask robots . txt allowance .
7,575
def _allows_url ( self , url_data , roboturl ) : with cache_lock : if roboturl in self . cache : self . hits += 1 rp = self . cache [ roboturl ] return rp . can_fetch ( self . useragent , url_data . url ) self . misses += 1 kwargs = dict ( auth = url_data . auth , session = url_data . session ) if hasattr ( url_data , ...
Ask robots . txt allowance . Assumes only single thread per robots . txt URL calls this function .
7,576
def add_sitemap_urls ( self , rp , url_data , roboturl ) : if not rp . sitemap_urls or not url_data . allows_simple_recursion ( ) : return for sitemap_url , line in rp . sitemap_urls : url_data . add_url ( sitemap_url , line = line )
Add sitemap URLs to queue .
7,577
def start_output ( self ) : super ( HtmlLogger , self ) . start_output ( ) header = { "encoding" : self . get_charset_encoding ( ) , "title" : configuration . App , "body" : self . colorbackground , "link" : self . colorlink , "vlink" : self . colorlink , "alink" : self . colorlink , "url" : self . colorurl , "error" :...
Write start of checking info .
7,578
def write_id ( self ) : self . writeln ( u"<tr>" ) self . writeln ( u'<td>%s</td>' % self . part ( "id" ) ) self . write ( u"<td>%d</td></tr>" % self . stats . number )
Write ID for current URL .
7,579
def write_warning ( self , url_data ) : sep = u"<br/>" + os . linesep text = sep . join ( cgi . escape ( x [ 1 ] ) for x in url_data . warnings ) self . writeln ( u'<tr><td class="warning" ' + u'valign="top">' + self . part ( "warning" ) + u'</td><td class="warning">' + text + u"</td></tr>" )
Write url_data . warnings .
7,580
def write_stats ( self ) : self . writeln ( u'<br/><i>%s</i><br/>' % _ ( "Statistics" ) ) if self . stats . number > 0 : self . writeln ( _ ( "Content types: %(image)d image, %(text)d text, %(video)d video, " "%(audio)d audio, %(application)d application, %(mail)d mail" " and %(other)d other." ) % self . stats . link_t...
Write check statistic infos .
7,581
def write_outro ( self ) : self . writeln ( u"<br/>" ) self . write ( _ ( "That's it." ) + " " ) if self . stats . number >= 0 : self . write ( _n ( "%d link checked." , "%d links checked." , self . stats . number ) % self . stats . number ) self . write ( u" " ) self . write ( _n ( "%d warning found" , "%d warnings fo...
Write end of check message .
7,582
def end_output ( self , ** kwargs ) : if self . has_part ( "stats" ) : self . write_stats ( ) if self . has_part ( "outro" ) : self . write_outro ( ) self . close_fileoutput ( )
Write end of checking info as HTML .
7,583
def is_valid_ipv4 ( ip ) : if not _ipv4_re . match ( ip ) : return False a , b , c , d = [ int ( i ) for i in ip . split ( "." ) ] return a <= 255 and b <= 255 and c <= 255 and d <= 255
Return True if given ip is a valid IPv4 address .
7,584
def is_valid_ipv6 ( ip ) : if not ( _ipv6_re . match ( ip ) or _ipv6_ipv4_re . match ( ip ) or _ipv6_abbr_re . match ( ip ) or _ipv6_ipv4_abbr_re . match ( ip ) ) : return False return True
Return True if given ip is a valid IPv6 address .
7,585
def host_in_set ( ip , hosts , nets ) : if ip in hosts : return True if is_valid_ipv4 ( ip ) : n = dq2num ( ip ) for net in nets : if dq_in_net ( n , net ) : return True return False
Return True if given ip is in host or network list .
7,586
def lookup_ips ( ips ) : hosts = set ( ) for ip in ips : try : hosts . add ( socket . gethostbyaddr ( ip ) [ 0 ] ) except socket . error : hosts . add ( ip ) return hosts
Return set of host names that resolve to given ips .
7,587
def obfuscate_ip ( ip ) : if is_valid_ipv4 ( ip ) : res = "0x%s" % "" . join ( hex ( int ( x ) ) [ 2 : ] for x in ip . split ( "." ) ) else : raise ValueError ( 'Invalid IP value %r' % ip ) assert is_obfuscated_ip ( res ) , '%r obfuscation error' % res return res
Obfuscate given host in IP form .
7,588
def put ( self , item ) : with self . mutex : self . _put ( item ) self . not_empty . notify ( )
Put an item into the queue . Block if necessary until a free slot is available .
7,589
def _put ( self , url_data ) : if self . shutdown or self . max_allowed_urls == 0 : return log . debug ( LOG_CACHE , "queueing %s" , url_data . url ) key = url_data . cache_url cache = url_data . aggregate . result_cache if url_data . has_result or cache . has_result ( key ) : self . queue . appendleft ( url_data ) els...
Put URL in queue increase number of unfished tasks .
7,590
def cleanup ( self ) : self . num_puts = 0 cached = [ ] for i , url_data in enumerate ( self . queue ) : key = url_data . cache_url cache = url_data . aggregate . result_cache if cache . has_result ( key ) : cached . append ( i ) for pos in cached : self . _move_to_top ( pos )
Move cached elements to top .
7,591
def _move_to_top ( self , pos ) : if pos > 0 : self . queue . rotate ( - pos ) item = self . queue . popleft ( ) self . queue . rotate ( pos ) self . queue . appendleft ( item )
Move element at given position to top of queue .
7,592
def do_shutdown ( self ) : with self . mutex : unfinished = self . unfinished_tasks - len ( self . queue ) self . queue . clear ( ) if unfinished <= 0 : if unfinished < 0 : raise ValueError ( 'shutdown is in error' ) self . all_tasks_done . notifyAll ( ) self . unfinished_tasks = unfinished self . shutdown = True
Shutdown the queue by not accepting any more URLs .
7,593
def add ( self , item ) : if not item in self . items : self . items . append ( item )
Add an item to the set .
7,594
def union_update ( self , other ) : if not isinstance ( other , Set ) : raise ValueError ( 'other must be a Set instance' ) if self is other : return for item in other . items : self . add ( item )
Update the set adding any elements from other which are not already in the set .
7,595
def intersection_update ( self , other ) : if not isinstance ( other , Set ) : raise ValueError ( 'other must be a Set instance' ) if self is other : return for item in list ( self . items ) : if item not in other . items : self . items . remove ( item )
Update the set removing any elements from other which are not in both sets .
7,596
def difference_update ( self , other ) : if not isinstance ( other , Set ) : raise ValueError ( 'other must be a Set instance' ) if self is other : self . items = [ ] else : for item in other . items : self . discard ( item )
Update the set removing any elements from other which are in the set .
7,597
def urljoin ( parent , url ) : if urlutil . url_is_absolute ( url ) : return url return urlparse . urljoin ( parent , url )
If url is relative join parent and url . Else leave url as - is .
7,598
def init ( self , base_ref , base_url , parent_url , recursion_level , aggregate , line , column , page , name , url_encoding , extern ) : self . base_ref = base_ref if self . base_ref is not None : assert isinstance ( self . base_ref , unicode ) , repr ( self . base_ref ) self . base_url = base_url . strip ( ) if base...
Initialize internal data .
7,599
def reset ( self ) : self . url = None self . urlparts = None self . scheme = self . host = self . port = self . anchor = None self . result = u"" self . has_result = False self . valid = True self . warnings = [ ] self . info = [ ] self . size = - 1 self . modified = None self . dltime = - 1 self . checktime = 0 self ...
Reset all variables to default values .