code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
lm = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) want_scan = False try: try: # XP, 2000 tcp_params = _winreg.OpenKey(lm, r'SYSTEM\CurrentControlSet' ...
def read_registry(self)
Extract resolver configuration from the Windows registry.
2.815764
2.73834
1.028274
self.keyring = keyring if keyname is None: self.keyname = self.keyring.keys()[0] else: self.keyname = keyname self.keyalgorithm = algorithm
def use_tsig(self, keyring, keyname=None, algorithm=dns.tsig.default_algorithm)
Add a TSIG signature to the query. @param keyring: The TSIG keyring to use; defaults to None. @type keyring: dict @param keyname: The name of the TSIG key to use; defaults to None. The key must be defined in the keyring. If a keyring is specified but a keyname is not, then the ...
2.201363
2.44536
0.900221
if edns is None: edns = -1 self.edns = edns self.ednsflags = ednsflags self.payload = payload
def use_edns(self, edns, ednsflags, payload)
Configure Edns. @param edns: The EDNS level to use. The default is -1, no Edns. @type edns: int @param ednsflags: The EDNS flags @type ednsflags: int @param payload: The EDNS payload size. The default is 0. @type payload: int
2.793982
2.553238
1.09429
try: import __builtin__ as builtins except ImportError: # Python 3 import builtins # Python 3 has no ugettext has_unicode = hasattr(translator, 'ugettext') if do_unicode and has_unicode: builtins.__dict__['_'] = translator.ugettext # also install ngettext...
def install_builtin (translator, do_unicode)
Install _() and _n() gettext methods into default namespace.
2.697377
2.412565
1.118054
global default_language, default_encoding, default_domain, default_directory default_directory = directory default_domain = domain if os.path.isdir(directory): # get supported languages for lang in os.listdir(directory): path = os.path.join(directory, lang, 'LC_MESSAGES'...
def init (domain, directory, loc=None)
Initialize this gettext i18n module. Searches for supported languages and installs the gettext translator class.
3.134727
2.938514
1.066773
translator = get_translator(default_domain, default_directory, languages=[get_lang(language)], fallback=True) do_unicode = True translator.install(do_unicode)
def install_language(language)
Install translation service routines into default namespace.
10.466417
9.1034
1.149726
translator = gettext.translation(domain, localedir=directory, languages=languages, class_=translatorklass, fallback=fallback) if not isinstance(translator, gettext.GNUTranslations) and fallbackklass: translator = fallbackklass() return translator
def get_translator (domain, directory, languages=None, translatorklass=Translator, fallback=False, fallbackklass=NullTranslator)
Search the appropriate GNUTranslations class.
3.721114
3.495266
1.064616
if 'Accept-Language' not in headers: return default_language languages = headers['Accept-Language'].split(",") # sort with preference values pref_languages = [] for lang in languages: pref = 1.0 if ";" in lang: lang, _pref = lang.split(';', 1) try...
def get_headers_lang (headers)
Return preferred supported language in given HTTP headers.
2.951646
2.727124
1.082329
try: loc, encoding = locale.getdefaultlocale() except ValueError: # locale configuration is broken - ignore that loc, encoding = None, None if loc is None: loc = "C" else: loc = norm_locale(loc) if encoding is None: encoding = "ascii" return (...
def get_locale ()
Search the default platform locale and norm it. @returns (locale, encoding) @rtype (string, string)
3.708318
3.498234
1.060054
loc = locale.normalize(loc) # split up the locale into its base components pos = loc.find('@') if pos >= 0: loc = loc[:pos] pos = loc.find('.') if pos >= 0: loc = loc[:pos] pos = loc.find('_') if pos >= 0: loc = loc[:pos] return loc
def norm_locale (loc)
Normalize a locale.
2.328579
2.364764
0.984698
if encoding is None: encoding = default_encoding Writer = codecs.getwriter(encoding) return Writer(out, errors)
def get_encoded_writer (out=sys.stdout, encoding=None, errors='replace')
Get wrapped output writer with given encoding and error handling.
3.406953
2.908455
1.171396
if section is None: section = self.authority covers = rd.covers() rrset = self.find_rrset(section, name, self.zone_rdclass, rd.rdtype, covers, deleting, True, True) rrset.add(rd, ttl)
def _add_rr(self, name, ttl, rd, deleting=None, section=None)
Add a single RR to the update section.
5.97834
6.056533
0.987089
if isinstance(name, (str, unicode)): name = dns.name.from_text(name, None) if isinstance(args[0], dns.rdataset.Rdataset): for rds in args: if replace: self.delete(name, rds.rdtype) for rd in rds: se...
def _add(self, replace, section, name, *args)
Add records. The first argument is the replace mode. If false, RRs are added to an existing RRset; if true, the RRset is replaced with the specified contents. The second argument is the section to add to. The third argument is always a name. The other arguments can be: ...
2.168895
1.946799
1.114083
self._add(False, self.authority, name, *args)
def add(self, name, *args)
Add records. The first argument is always a name. The other arguments can be: - rdataset... - ttl, rdata... - ttl, rdtype, string...
17.077574
17.609901
0.969771
if isinstance(name, (str, unicode)): name = dns.name.from_text(name, None) if len(args) == 0: rrset = self.find_rrset(self.authority, name, dns.rdataclass.ANY, dns.rdatatype.ANY, dns.rdatatype.NONE, ...
def delete(self, name, *args)
Delete records. The first argument is always a name. The other arguments can be: - I{nothing} - rdataset... - rdata... - rdtype, [string...]
2.1236
2.01195
1.055493
self._add(True, self.authority, name, *args)
def replace(self, name, *args)
Replace records. The first argument is always a name. The other arguments can be: - rdataset... - ttl, rdata... - ttl, rdtype, string... Note that if you want to replace the entire node, you should do a delete of the name followed by one or m...
29.624813
17.241163
1.718261
if isinstance(name, (str, unicode)): name = dns.name.from_text(name, None) if len(args) == 0: rrset = self.find_rrset(self.answer, name, dns.rdataclass.ANY, dns.rdatatype.ANY, dns.rdatatype.NONE, No...
def present(self, name, *args)
Require that an owner name (and optionally an rdata type, or specific rdataset) exists as a prerequisite to the execution of the update. The first argument is always a name. The other arguments can be: - rdataset... - rdata... - rdtype, string....
2.357654
2.211183
1.066241
if isinstance(name, (str, unicode)): name = dns.name.from_text(name, None) if rdtype is None: rrset = self.find_rrset(self.answer, name, dns.rdataclass.NONE, dns.rdatatype.ANY, dns.rdatatype.NONE, N...
def absent(self, name, rdtype=None)
Require that an owner name (and optionally an rdata type) does not exist as a prerequisite to the execution of the update.
2.018204
2.02391
0.997181
if origin is None: origin = self.origin return super(Update, self).to_wire(origin, max_size)
def to_wire(self, origin=None, max_size=65535)
Return a string containing the update in DNS compressed wire format. @rtype: string
3.910026
2.777414
1.407794
self.write(u"-- ") self.writeln(s=s, **args)
def comment (self, s, **args)
Write SQL comment.
11.393759
7.63974
1.49138
super(SQLLogger, self).start_output() if self.has_part("intro"): self.write_intro() self.writeln() self.flush()
def start_output (self)
Write start of checking info as sql comment.
9.68084
7.269353
1.331733
self.writeln(u"insert into %(table)s(urlname," "parentname,baseref,valid,result,warning,info,url,line,col," "name,checktime,dltime,size,cached,level,modified) values (" "%(base_url)s," "%(url_parent)s," "%(base_ref)s," ...
def log_url (self, url_data)
Store url check info into the database.
2.468237
2.423398
1.018503
mo = imgtag_re.search(txt) if mo: name = strformat.unquote(mo.group('name').strip()) return _unquote(name) return u''
def image_name (txt)
Return the alt part of the first <img alt=""> tag in txt.
9.34675
8.333134
1.121637
name = u"" endtag = a_end_search(txt) if not endtag: return name name = txt[:endtag.start()] if img_re.search(name): return image_name(name) return _unquote(name)
def href_name (txt)
Return the name part of the first <a href="">name</a> link in txt.
6.646449
5.571405
1.192957
name = u"" endtag = title_end_search(txt) if not endtag: return name name = txt[:endtag.start()] return _unquote(name)
def title_name (txt)
Return the part of the first <title>name</title> in txt.
6.894169
5.916862
1.165173
# first do a full garbage collection run gc.collect() if gc.garbage: log.warn(LOG_CHECK, "Unreachabe objects: %s", pprint.pformat(gc.garbage)) from meliae import scanner fo, filename = get_temp_file(mode='wb', suffix='.json', prefix='lcdump_') try: scanner.dump_all_objects(f...
def write_memory_dump()
Dump memory to a temporary filename with the meliae package. @return: JSON filename where memory dump has been written to @rtype: string
9.413094
7.513913
1.252755
parts = [d for d in text if d.isdigit()] parts.reverse() return dns.name.from_text('.'.join(parts), origin=origin)
def from_e164(text, origin=public_enum_domain)
Convert an E.164 number in textual form into a Name object whose value is the ENUM domain name for that number. @param text: an E.164 number in textual form. @type text: str @param origin: The domain in which the number should be constructed. The default is e164.arpa. @type: dns.name.Name object...
4.927854
4.07746
1.20856
if not origin is None: name = name.relativize(origin) dlabels = [d for d in name.labels if (d.isdigit() and len(d) == 1)] if len(dlabels) != len(name.labels): raise dns.exception.SyntaxError('non-digit labels in ENUM domain name') dlabels.reverse() text = ''.join(dlabels) if...
def to_e164(name, origin=public_enum_domain, want_plus_prefix=True)
Convert an ENUM domain name into an E.164 number. @param name: the ENUM domain name. @type name: dns.name.Name object. @param origin: A domain containing the ENUM domain name. The name is relativized to this domain before being converted to text. @type: dns.name.Name object or None @param want_...
4.020656
2.837611
1.416916
if resolver is None: resolver = dns.resolver.get_default_resolver() for domain in domains: if isinstance(domain, (str, unicode)): domain = dns.name.from_text(domain) qname = dns.e164.from_e164(number, domain) try: return resolver.query(qname, 'NAPTR')...
def query(number, domains, resolver=None)
Look for NAPTR RRs for the specified number in the specified domains. e.g. lookup('16505551212', ['e164.dnspython.org.', 'e164.arpa.'])
2.467276
2.423242
1.018171
if not url_data.url: return None elif url_data.url in self.nodes: return None node = { "url": url_data.url, "parent_url": url_data.parent_url, "id": self.nodeid, "label": quote(url_data.title if url_data.title else ...
def get_node (self, url_data)
Return new node data or None if node already exists.
2.906873
2.70164
1.075966
for node in self.nodes.values(): if node["parent_url"] in self.nodes: self.write_edge(node) self.flush()
def write_edges (self)
Write all edges we can find in the graph in a brute-force manner.
6.547495
5.549711
1.17979
self.write_edges() self.end_graph() if self.has_part("outro"): self.write_outro() self.close_fileoutput()
def end_output (self, **kwargs)
Write edges and end of checking info as gml comment.
11.059347
7.827627
1.412861
entries = [] with open(filename) as fd: lines = [] for line in fd.readlines(): line = line.rstrip() if not line: if lines: entries.append(from_headers("\r\n".join(lines))) lines = [] else: ...
def from_file (filename)
Parse cookie data from a text file in HTTP header format. @return: list of tuples (headers, scheme, host, path)
2.328486
2.310408
1.007824
res = [] fp = StringIO(strheader) headers = httplib.HTTPMessage(fp, seekable=True) if "Host" not in headers: raise ValueError("Required header 'Host:' missing") host = headers["Host"] path= headers.get("Path", "/") for header in headers.getallmatchingheaders("Set-Cookie"): ...
def from_headers (strheader)
Parse cookie data from a string in HTTP header (RFC 2616) format. @return: list of cookies @raises: ValueError for incomplete or invalid data
4.147459
4.322272
0.959555
handle = handles[stream_id] csbi = CONSOLE_SCREEN_BUFFER_INFO() success = windll.kernel32.GetConsoleScreenBufferInfo( handle, byref(csbi)) if not success: raise WinError() return csbi
def GetConsoleScreenBufferInfo(stream_id=STDOUT)
Get console screen buffer info object.
2.254839
2.359661
0.955578
handle = handles[stream_id] return windll.kernel32.SetConsoleTextAttribute(handle, attrs)
def SetConsoleTextAttribute(stream_id, attrs)
Set a console text attribute.
4.278483
4.336666
0.986584
global _default_foreground, _default_background, _default_style try: attrs = GetConsoleScreenBufferInfo().wAttributes except (ArgumentError, WindowsError): _default_foreground = GREY _default_background = BLACK _default_style = NORMAL else: _default_foregroun...
def init()
Initialize foreground and background attributes.
3.815815
3.432315
1.111732
if foreground is None: foreground = _default_foreground if background is None: background = _default_background if style is None: style = _default_style attrs = get_attrs(foreground, background, style) SetConsoleTextAttribute(stream, attrs)
def set_console(stream=STDOUT, foreground=None, background=None, style=None)
Set console foreground and background attributes.
2.342937
2.275987
1.029416
super(FtpUrl, self).reset() # list of files for recursion self.files = [] # last part of URL filename self.filename = None self.filename_encoding = 'iso-8859-1'
def reset (self)
Initialize FTP url data.
8.041488
5.776147
1.392189
# proxy support (we support only http) self.set_proxy(self.aggregate.config["proxy"].get(self.scheme)) if self.proxy: # using a (HTTP) proxy http = httpurl.HttpUrl(self.base_url, self.recursion_level, self.aggregate, ...
def check_connection (self)
In case of proxy, delegate to HttpUrl. Else check in this order: login, changing directory, list the file.
8.037491
6.74531
1.191567
self.url_connection = ftplib.FTP(timeout=self.aggregate.config["timeout"]) if log.is_debug(LOG_CHECK): self.url_connection.set_debuglevel(1) try: self.url_connection.connect(self.host, self.port) _user, _password = self.get_user_password() ...
def login (self)
Log into ftp server and check the welcome message.
4.412897
4.151723
1.062907
try: features = self.url_connection.sendcmd("FEAT") except ftplib.error_perm as msg: log.debug(LOG_CHECK, "Ignoring error when getting FTP features: %s" % msg) pass else: log.debug(LOG_CHECK, "FTP features %s", features) if " U...
def negotiate_encoding (self)
Check if server can handle UTF-8 encoded filenames. See also RFC 2640.
5.518542
4.900966
1.126011
path = self.urlparts[2].encode(self.filename_encoding, 'replace') dirname = path.strip('/') dirs = dirname.split('/') filename = dirs.pop() self.url_connection.cwd('/') for d in dirs: self.url_connection.cwd(d) return filename
def cwd (self)
Change to URL parent directory. Return filename of last path component.
5.81334
4.800801
1.21091
if not self.filename: return files = self.get_files() log.debug(LOG_CHECK, "FTP files %s", str(files)) if self.filename in files: # file found return # it could be a directory if the trailing slash was forgotten if "%s/" % self...
def listfile (self)
See if filename is in the current FTP directory.
7.120192
6.335216
1.123907
files = [] def add_entry (line): log.debug(LOG_CHECK, "Directory entry %r", line) from ..ftpparse import ftpparse fpo = ftpparse(line) if fpo is not None and fpo["name"]: name = fpo["name"] if fpo["tryc...
def get_files (self)
Get list of filenames in directory. Subdirectories have an ending slash.
8.031877
7.619134
1.054172
if self.is_directory(): return True if self.content_type in self.ContentMimetypes: return True log.debug(LOG_CHECK, "URL with content type %r is not parseable.", self.content_type) return False
def is_parseable (self)
See if URL target is parseable for recursion.
7.751025
5.968872
1.298575
self.content_type = mimeutil.guess_mimetype(self.url, read=self.get_content)
def set_content_type (self)
Set URL content type, or an empty string if content type could not be found.
10.32303
8.702844
1.186168
if self.is_directory(): self.url_connection.cwd(self.filename) self.files = self.get_files() # XXX limit number of files? data = get_index_html(self.files) else: # download file in BINARY mode ftpcmd = "RETR %s" % self.file...
def read_content (self)
Return URL target content, or in case of directories a dummy HTML file with links to the files.
5.393059
4.984352
1.081998
if self.url_connection is not None: try: self.url_connection.quit() except Exception: pass self.url_connection = None
def close_connection (self)
Release the open connection from the connection pool.
3.541189
2.997348
1.181441
if os.name == 'nt': basedir = unicode(os.environ["APPDATA"], nt_filename_encoding) dirpath = os.path.join(basedir, u"Opera", u"Opera") elif os.name == 'posix': basedir = unicode(os.environ["HOME"]) dirpath = os.path.join(basedir, u".opera") return dirpath
def get_profile_dir ()
Return path where all profiles of current user are stored.
3.195037
3.147636
1.015059
try: dirname = get_profile_dir() if os.path.isdir(dirname): for name in OperaBookmarkFiles: fname = os.path.join(dirname, name) if os.path.isfile(fname): return fname except Exception: pass return u""
def find_bookmark_file ()
Return the bookmark file of the Opera profile. Returns absolute filename if found, or empty string if no bookmark file could be found.
3.780162
3.1238
1.210116
name = None lineno = 0 for line in data.splitlines(): lineno += 1 line = line.strip() if line.startswith("NAME="): name = line[5:] elif line.startswith("URL="): url = line[4:] if url and name is not None: yield (url, na...
def parse_bookmark_data (data)
Return iterator for bookmarks of the form (url, name, line number). Bookmarks are not sorted.
2.585973
2.326457
1.11155
filename = args[0] marker = args[1] for line in fileinput.input(filename, inplace=1): print(line.rstrip()) if line.startswith(marker): break
def main(args)
Remove lines after marker.
4.253359
2.594608
1.639307
try: dirname = os.path.join(get_profile_dir(), profile) if os.path.isdir(dirname): fname = os.path.join(dirname, "Bookmarks") if os.path.isfile(fname): return fname except Exception: pass return u""
def find_bookmark_file (profile="Default")
Return the bookmark file of the Default profile. Returns absolute filename if found, or empty string if no bookmark file could be found.
2.556508
2.3869
1.071058
for url, name in parse_bookmark_json(json.loads(data)): yield url, name
def parse_bookmark_data (data)
Parse data string. Return iterator for bookmarks of the form (url, name). Bookmarks are not sorted.
6.500032
4.846496
1.341182
for url, name in parse_bookmark_json(json.load(file)): yield url, name
def parse_bookmark_file (file)
Parse file object. Return iterator for bookmarks of the form (url, name). Bookmarks are not sorted.
6.457742
4.854646
1.330219
for entry in data["roots"].values(): for url, name in parse_bookmark_node(entry): yield url, name
def parse_bookmark_json (data)
Parse complete JSON data for Chromium Bookmarks.
7.448291
6.590068
1.13023
if node["type"] == "url": yield node["url"], node["name"] elif node["type"] == "folder": for child in node["children"]: for entry in parse_bookmark_node(child): yield entry
def parse_bookmark_node (node)
Parse one JSON node of Chromium Bookmarks.
2.692595
2.461624
1.093829
s = StringIO.StringIO() for rds in self.rdatasets: print >> s, rds.to_text(name, **kw) return s.getvalue()[:-1]
def to_text(self, name, **kw)
Convert a node to text format. Each rdataset at the node is printed. Any keyword arguments to this method are passed on to the rdataset's to_text() method. @param name: the owner name of the rdatasets @type name: dns.name.Name object @rtype: string
4.768046
3.827385
1.245771
for rds in self.rdatasets: if rds.match(rdclass, rdtype, covers): return rds if not create: raise KeyError rds = dns.rdataset.Rdataset(rdclass, rdtype) self.rdatasets.append(rds) return rds
def find_rdataset(self, rdclass, rdtype, covers=dns.rdatatype.NONE, create=False)
Find an rdataset matching the specified properties in the current node. @param rdclass: The class of the rdataset @type rdclass: int @param rdtype: The type of the rdataset @type rdtype: int @param covers: The covered type. Usually this value is dns.rdatatype.NO...
2.13697
2.194981
0.973571
try: rds = self.find_rdataset(rdclass, rdtype, covers, create) except KeyError: rds = None return rds
def get_rdataset(self, rdclass, rdtype, covers=dns.rdatatype.NONE, create=False)
Get an rdataset matching the specified properties in the current node. None is returned if an rdataset of the specified type and class does not exist and I{create} is not True. @param rdclass: The class of the rdataset @type rdclass: int @param rdtype: The type of the r...
2.778332
3.044308
0.912632
rds = self.get_rdataset(rdclass, rdtype, covers) if not rds is None: self.rdatasets.remove(rds)
def delete_rdataset(self, rdclass, rdtype, covers=dns.rdatatype.NONE)
Delete the rdataset matching the specified properties in the current node. If a matching rdataset does not exist, it is not an error. @param rdclass: The class of the rdataset @type rdclass: int @param rdtype: The type of the rdataset @type rdtype: int @param co...
2.99413
3.399542
0.880745
self.delete_rdataset(replacement.rdclass, replacement.rdtype, replacement.covers) self.rdatasets.append(replacement)
def replace_rdataset(self, replacement)
Replace an rdataset. It is not an error if there is no rdataset matching I{replacement}. Ownership of the I{replacement} object is transferred to the node; in other words, this method does not store a copy of I{replacement} at the node, it stores I{replacement} itself.
6.128534
5.046092
1.214511
#print len(self.connections) ## Build a list of connections to test for receive data pending recv_list = [self.server_fileno] # always add the server for client in self.clients.values(): if client.active: recv_list.append(client.fileno) ...
def poll(self)
Perform a non-blocking scan of recv and send states on the server and client connection sockets. Process new connection requests, read incomming data, and send outgoing data. Sends and receives may be partial.
3.808247
3.743644
1.017257
keyring = {} for keytext in textring: keyname = dns.name.from_text(keytext) secret = base64.decodestring(textring[keytext]) keyring[keyname] = secret return keyring
def from_text(textring)
Convert a dictionary containing (textual DNS name, base64 secret) pairs into a binary keyring which has (dns.name.Name, binary secret) pairs. @rtype: dict
4.319221
2.529176
1.707758
textring = {} for keyname in keyring: keytext = dns.name.to_text(keyname) secret = base64.encodestring(keyring[keyname]) textring[keytext] = secret return textring
def to_text(keyring)
Convert a dictionary containing (dns.name.Name, binary secret) pairs into a text keyring which has (textual DNS name, base64 secret) pairs. @rtype: dict
5.251658
3.566337
1.472564
for applog in lognames.values(): # propagate except for root app logger 'linkcheck' propagate = (applog != LOG_ROOT) configdict['loggers'][applog] = dict(level='INFO', propagate=propagate) logging.config.dictConfig(configdict) if handler is None: handler = ansicolor.Col...
def init_log_config(handler=None)
Set up the application logging (not to be confused with check loggers).
8.378105
7.838799
1.0688
format = "%(levelname)s %(name)s %(asctime)s %(threadName)s %(message)s" handler.setFormatter(logging.Formatter(format)) logging.getLogger(LOG_ROOT).addHandler(handler) logging.getLogger().addHandler(handler)
def add_loghandler (handler)
Add log handler to root logger and LOG_ROOT and set formatting.
2.764863
2.123168
1.302235
logging.getLogger(LOG_ROOT).removeHandler(handler) logging.getLogger().removeHandler(handler)
def remove_loghandler (handler)
Remove log handler from root logger and LOG_ROOT.
4.519761
2.785058
1.622861
if not loggers: return if 'all' in loggers: loggers = lognames.keys() for key in loggers: logging.getLogger(lognames[key]).setLevel(level)
def set_loglevel(loggers, level)
Set logging levels for given loggers.
3.40059
3.298233
1.031034
super(GraphXMLLogger, self).start_output() self.xml_start_output() self.xml_starttag(u'GraphXML') self.xml_starttag(u'graph', attrs={u"isDirected": u"true"}) self.flush()
def start_output (self)
Write start of checking info as xml comment.
7.379971
5.951662
1.239985
node = self.get_node(url_data) if node: self.xml_starttag(u'node', attrs={u"name": u"%d" % node["id"]}) self.xml_tag(u"label", node["label"]) if self.has_part("realurl"): self.xml_tag(u"url", node["url"]) self.xml_starttag(u"data")...
def log_url (self, url_data)
Write one node and all possible edges.
2.47237
2.374513
1.041211
attrs = { u"source": u"%d" % self.nodes[node["parent_url"]]["id"], u"target": u"%d" % node["id"], } self.xml_starttag(u"edge", attrs=attrs) self.xml_tag(u"label", node["label"]) self.xml_starttag(u"data") if self.has_part("result"): ...
def write_edge (self, node)
Write one edge.
3.439324
3.347289
1.027496
self.xml_endtag(u"graph") self.xml_endtag(u"GraphXML") self.xml_end_output() self.close_fileoutput()
def end_output (self, **kwargs)
Finish graph output, and print end of checking info as xml comment.
9.952268
8.103933
1.228079
value = _by_text.get(text.upper()) if value is None: match = _unknown_class_pattern.match(text) if match == None: raise UnknownRdataclass value = int(match.group(1)) if value < 0 or value > 65535: raise ValueError("class must be between >= 0 and <= 6...
def from_text(text)
Convert text into a DNS rdata class value. @param text: the text @type text: string @rtype: int @raises dns.rdataclass.UnknownRdataClass: the class is unknown @raises ValueError: the rdata class value is not >= 0 and <= 65535
4.899251
2.966476
1.651539
if value < 0 or value > 65535: raise ValueError("class must be between >= 0 and <= 65535") text = _by_value.get(value) if text is None: text = 'CLASS' + repr(value) return text
def to_text(value)
Convert a DNS rdata class to text. @param value: the rdata class value @type value: int @rtype: string @raises ValueError: the rdata class value is not >= 0 and <= 65535
4.775144
3.417575
1.397232
client.send('You connected from %s\n' % client.addrport()) if CLIENTS: client.send('Also connected are:\n') for neighbor in CLIENTS: client.send('%s\n' % neighbor.addrport()) else: client.send('Sadly, you are alone.\n') CLIENTS.append(client)
def my_on_connect(client)
Example on_connect handler.
4.688486
4.540258
1.032648
self.entries = [] self.default_entry = None self.disallow_all = False self.allow_all = False self.last_checked = 0 # list of tuples (sitemap url, line number) self.sitemap_urls = []
def _reset (self)
Reset internal flags and entry lists.
7.028715
6.098741
1.152486
self.url = url self.host, self.path = urlparse.urlparse(url)[1:3]
def set_url (self, url)
Set the URL referring to a robots.txt file.
3.567791
3.077477
1.159324
self._reset() kwargs = dict( headers = { 'User-Agent': configuration.UserAgent, 'Accept-Encoding': ACCEPT_ENCODING, } ) if self.auth: kwargs["auth"] = self.auth if self.proxies: kwargs["proxi...
def read (self)
Read the robots.txt URL and feeds it to the parser.
2.673576
2.525283
1.058723
if "*" in entry.useragents: # the default entry is considered last self.default_entry = entry else: self.entries.append(entry)
def _add_entry (self, entry)
Add a parsed entry to entry list. @return: None
10.43085
10.713945
0.973577
log.debug(LOG_CHECK, "%r parse lines", self.url) state = 0 linenumber = 0 entry = Entry() for line in lines: line = line.strip() linenumber += 1 if not line: if state == 1: log.debug(LOG_CHECK, "%r ...
def parse (self, lines)
Parse the input lines from a robot.txt file. We allow that a user-agent: line is not preceded by one or more blank lines. @return: None
2.243501
2.177756
1.030189
log.debug(LOG_CHECK, "%r check allowance for:\n user agent: %r\n url: %r ...", self.url, useragent, url) if not isinstance(useragent, str): useragent = useragent.encode("ascii", "ignore") if not isinstance(url, str): url = url.encode("ascii", "ignore") ...
def can_fetch (self, useragent, url)
Using the parsed robots.txt decide if useragent can fetch url. @return: True if agent can fetch url, else False @rtype: bool
3.880986
3.86072
1.005249
for entry in self.entries: if entry.applies_to(useragent): return entry.crawldelay return 0
def get_crawldelay (self, useragent)
Look for a configured crawl delay. @return: crawl delay in seconds or zero @rtype: integer >= 0
5.040678
5.189588
0.971306
if not useragent: return True useragent = useragent.lower() for agent in self.useragents: if agent == '*': # we have the catch-all agent return True if agent.lower() in useragent: return True ret...
def applies_to (self, useragent)
Check if this entry applies to the specified agent. @return: True if this entry applies to the agent, else False. @rtype: bool
3.598606
3.695089
0.973889
for line in self.rulelines: log.debug(LOG_CHECK, "%s %s %s", filename, str(line), line.allowance) if line.applies_to(filename): log.debug(LOG_CHECK, " ... rule line %s", line) return line.allowance log.debug(LOG_CHECK, " ... no rule lines ...
def allowance (self, filename)
Preconditions: - our agent applies to this entry - filename is URL decoded Check if given filename is allowed to acces this entry. @return: True if allowed, else False @rtype: bool
5.977896
5.936532
1.006968
if len(self.cache) > self.max_size: return if key is not None: self.cache[key] = result
def add_result(self, key, result)
Add result object to cache with given key. The request is ignored when the cache is already full or the key is None.
3.995578
2.992389
1.335247
to_remove = [] for elem in tree.findall('urldata'): valid = elem.find('valid') if valid is not None and valid.text == '0' and \ valid.attrib.get('result', '').startswith('401'): to_remove.append(elem) root = tree.getroot() for elem in to_remove: root.r...
def filter_tree(tree)
Filter all 401 errors.
3.63586
3.104235
1.171258
nntpserver = self.host or self.aggregate.config["nntpserver"] if not nntpserver: self.add_warning( _("No NNTP server was specified, skipping this URL."), tag=WARN_NNTP_NO_SERVER) return nntp = self._connect_nntp(nntpserver)...
def check_connection (self)
Connect to NNTP server and try to request the URL article resource (if specified).
6.310556
5.914822
1.066906
tries = 0 nntp = None while tries < 2: tries += 1 try: nntp = nntplib.NNTP(nntpserver, usenetrc=False) except nntplib.NNTPTemporaryError: self.wait() except nntplib.NNTPPermanentError as msg: ...
def _connect_nntp (self, nntpserver)
This is done only once per checking task. Also, the newly introduced error codes 504 and 505 (both inclining "Too busy, retry later", are caught.
4.272736
3.903789
1.09451
super(TextLogger, self).init_fileoutput(args) if self.fd is not None: self.fd = ansicolor.Colorizer(self.fd)
def init_fileoutput (self, args)
Colorize file output if possible.
6.22738
5.132619
1.213295
init_color = self.fd is None super(TextLogger, self).start_fileoutput() if init_color: self.fd = ansicolor.Colorizer(self.fd)
def start_fileoutput (self)
Needed to make file descriptor color aware.
7.148959
5.477
1.305269
super(TextLogger, self).start_output() if self.has_part('intro'): self.write_intro() self.flush()
def start_output (self)
Write generic start checking info.
8.487254
7.113506
1.193118
self.writeln(configuration.AppInfo) self.writeln(configuration.Freeware) self.writeln(_("Get the newest version at %(url)s") % {'url': configuration.Url}) self.writeln(_("Write comments and bugs to %(url)s") % {'url': configuration.Suppo...
def write_intro (self)
Log introduction text.
5.636712
5.273069
1.068962
self.writeln() if self.has_part('url'): self.write_url(url_data) if url_data.name and self.has_part('name'): self.write_name(url_data) if url_data.parent_url and self.has_part('parenturl'): self.write_parent(url_data) if url_data.base_...
def log_url (self, url_data)
Write url checking info.
1.931062
1.866322
1.034689
self.writeln() self.write(self.part('id') + self.spaces('id')) self.writeln(u"%d" % self.stats.number, color=self.colorinfo)
def write_id (self)
Write unique ID of url_data.
14.532362
13.147966
1.105294
self.write(self.part('url') + self.spaces('url')) txt = strformat.strline(url_data.base_url) self.writeln(txt, color=self.colorurl)
def write_url (self, url_data)
Write url_data.base_url.
18.734196
13.735824
1.363893
self.write(self.part("name") + self.spaces("name")) self.writeln(strformat.strline(url_data.name), color=self.colorname)
def write_name (self, url_data)
Write url_data.name.
19.592321
15.454803
1.267717
self.write(self.part('parenturl') + self.spaces("parenturl")) txt = url_data.parent_url if url_data.line > 0: txt += _(", line %d") % url_data.line if url_data.column > 0: txt += _(", col %d") % url_data.column if url_data.page > 0: tx...
def write_parent (self, url_data)
Write url_data.parent_url.
4.03468
3.677724
1.097059
self.write(self.part("base") + self.spaces("base")) self.writeln(url_data.base_ref, color=self.colorbase)
def write_base (self, url_data)
Write url_data.base_ref.
18.216152
10.984284
1.658383