code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
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 | def host_in_set (ip, hosts, nets) | Return True if given ip is in host or network list. | 4.654376 | 4.200468 | 1.108061 |
hostset = set()
nets = []
for host in hosts:
if _host_cidrmask_re.match(host):
host, mask = host.split("/")
mask = int(mask)
if not is_valid_cidrmask(mask):
log.error(LOG_CHECK,
"CIDR mask %d is not a valid network ma... | def hosts2map (hosts) | Return a set of named hosts, and a list of subnets (host/netmask
adresses).
Only IPv4 host/netmasks are supported. | 2.689803 | 2.581265 | 1.042048 |
ret = hostmap[0].copy()
for net, mask in hostmap[1]:
ret.add("%s/%d" % (num2dq(net), mask2netmask(mask)))
return ret | def map2hosts (hostmap) | Convert a tuple (hosts, networks) into a host/network list
suitable for storing in a config file. | 8.765202 | 7.53242 | 1.163663 |
hosts = set()
for ip in ips:
try:
hosts.add(socket.gethostbyaddr(ip)[0])
except socket.error:
hosts.add(ip)
return hosts | def lookup_ips (ips) | Return set of host names that resolve to given ips. | 2.202038 | 1.923869 | 1.144588 |
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 | def obfuscate_ip(ip) | Obfuscate given host in IP form.
@ip: IPv4 address string
@return: hexadecimal IP string ('0x1ab...')
@raise: ValueError on invalid IP addresses | 4.368541 | 4.189511 | 1.042733 |
headers = []
for name, value in url_data.headers.items():
if name.startswith(self.prefixes):
headers.append(name)
if headers:
items = [u"%s=%s" % (name.capitalize(), url_data.headers[name]) for name in headers]
info = u"HTTP headers %s... | def check(self, url_data) | Check content for invalid anchors. | 3.406189 | 3.558384 | 0.957229 |
config = dict()
section = cls.__name__
option = "prefixes"
if configparser.has_option(section, option):
value = configparser.get(section, option)
names = [x.strip().lower() for x in value.split(",")]
else:
names = []
config[opt... | def read_config(cls, configparser) | Read configuration file options. | 2.760329 | 2.694097 | 1.024584 |
if timeout is None:
while self._empty():
self.not_empty.wait()
else:
if timeout < 0:
raise ValueError("'timeout' must be a positive number")
endtime = _time() + timeout
while self._empty():
remaining... | def _get (self, timeout) | Non thread-safe utility function of self.get() doing the real
work. | 2.465735 | 2.355629 | 1.046742 |
with self.mutex:
self._put(item)
self.not_empty.notify() | def put (self, item) | Put an item into the queue.
Block if necessary until a free slot is available. | 5.666511 | 4.269649 | 1.327161 |
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_da... | def _put (self, url_data) | Put URL in queue, increase number of unfished tasks. | 4.705723 | 4.298774 | 1.094666 |
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_to... | def cleanup(self) | Move cached elements to top. | 7.487144 | 6.133033 | 1.22079 |
if pos > 0:
self.queue.rotate(-pos)
item = self.queue.popleft()
self.queue.rotate(pos)
self.queue.appendleft(item) | def _move_to_top(self, pos) | Move element at given position to top of queue. | 3.213489 | 2.431668 | 1.321516 |
with self.all_tasks_done:
log.debug(LOG_CACHE, "task_done %s", url_data.url)
self.finished_tasks += 1
self.unfinished_tasks -= 1
self.in_progress -= 1
if self.unfinished_tasks <= 0:
if self.unfinished_tasks < 0:
... | def task_done (self, url_data) | Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently blocking, it will resume when all items
... | 3.510078 | 3.276565 | 1.071268 |
with self.all_tasks_done:
if timeout is None:
while self.unfinished_tasks:
self.all_tasks_done.wait()
else:
if timeout < 0:
raise ValueError("'timeout' must be a positive number")
endtime = _... | def join (self, timeout=None) | Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work on it is complete.
When the... | 2.200343 | 1.883475 | 1.168236 |
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()
se... | def do_shutdown (self) | Shutdown the queue by not accepting any more URLs. | 4.133818 | 3.793344 | 1.089755 |
if not item in self.items:
self.items.append(item) | def add(self, item) | Add an item to the set. | 3.578075 | 2.925663 | 1.222996 |
cls = self.__class__
obj = cls.__new__(cls)
obj.items = list(self.items)
return obj | def _clone(self) | Make a (shallow) copy of the set.
There is a 'clone protocol' that subclasses of this class
should use. To make a copy, first call your super's _clone()
method, and use the object returned as the new instance. Then
make shallow copies of the attributes defined in the subclass.
... | 4.454652 | 4.163722 | 1.069873 |
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) | def union_update(self, other) | Update the set, adding any elements from other which are not
already in the set.
@param other: the collection of items with which to update the set
@type other: Set object | 3.2797 | 3.338494 | 0.982389 |
if not isinstance(other, Set):
raise ValueError('other must be a Set instance')
if self is other:
return
# we make a copy of the list so that we can remove items from
# the list without breaking the iterator.
for item in list(self.items):
... | def intersection_update(self, other) | Update the set, removing any elements from other which are not
in both sets.
@param other: the collection of items with which to update the set
@type other: Set object | 3.812191 | 3.817242 | 0.998677 |
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) | def difference_update(self, other) | Update the set, removing any elements from other which are in
the set.
@param other: the collection of items with which to update the set
@type other: Set object | 3.38713 | 3.348206 | 1.011626 |
obj = self._clone()
obj.union_update(other)
return obj | def union(self, other) | Return a new set which is the union of I{self} and I{other}.
@param other: the other set
@type other: Set object
@rtype: the same type as I{self} | 9.718466 | 12.257861 | 0.792835 |
obj = self._clone()
obj.intersection_update(other)
return obj | def intersection(self, other) | Return a new set which is the intersection of I{self} and I{other}.
@param other: the other set
@type other: Set object
@rtype: the same type as I{self} | 8.002795 | 9.308939 | 0.859689 |
obj = self._clone()
obj.difference_update(other)
return obj | def difference(self, other) | Return a new set which I{self} - I{other}, i.e. the items
in I{self} which are not also in I{other}.
@param other: the other set
@type other: Set object
@rtype: the same type as I{self} | 7.674725 | 10.54881 | 0.727544 |
if not isinstance(other, Set):
raise ValueError('other must be a Set instance')
for item in other.items:
if not item in self.items:
return False
return True | def issuperset(self, other) | Is I{self} a superset of I{other}?
@rtype: bool | 3.644554 | 3.630828 | 1.00378 |
if urlutil.url_is_absolute(url):
return url
return urlparse.urljoin(parent, url) | def urljoin (parent, url) | If url is relative, join parent and url. Else leave url as-is.
@return joined url | 4.250457 | 5.240685 | 0.81105 |
try:
return urlutil.url_norm(url, encoding=encoding)
except UnicodeError:
msg = _("URL has unparsable domain name: %(name)s") % \
{"name": sys.exc_info()[1]}
raise LinkCheckerError(msg) | def url_norm (url, encoding=None) | Wrapper for url.url_norm() to convert UnicodeError in
LinkCheckerError. | 6.38605 | 4.553205 | 1.402539 |
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_url else base_url
if self.base_url is not None:
assert isinstance(self.base_url, unicode), repr(... | def init (self, base_ref, base_url, parent_url, recursion_level,
aggregate, line, column, page, name, url_encoding, extern) | Initialize internal data. | 2.374791 | 2.358172 | 1.007047 |
# self.url is constructed by self.build_url() out of base_url
# and (base_ref or parent) as absolute and normed url.
# This the real url we use when checking so it also referred to
# as 'real url'
self.url = None
# a splitted version of url for convenience
... | def reset (self) | Reset all variables to default values. | 7.6009 | 7.565479 | 1.004682 |
if self.has_result and not overwrite:
log.warn(LOG_CHECK,
"Double result %r (previous %r) for %s", msg, self.result, self)
else:
self.has_result = True
if not isinstance(msg, unicode):
log.warn(LOG_CHECK, "Non-unicode result for %s: %r",... | def set_result (self, msg, valid=True, overwrite=False) | Set result string and validity. | 3.927819 | 3.761136 | 1.044317 |
if self.title is None:
url = u""
if self.base_url:
url = self.base_url
elif self.url:
url = self.url
self.title = url
if "/" in url:
title = url.rsplit("/", 1)[1]
if title:
... | def get_title (self) | Return title of page the URL refers to.
This is per default the filename or the URL. | 2.856878 | 2.521493 | 1.133011 |
if not self.valid:
return False
mime = self.content_type
return self.ContentMimetypes.get(mime) == ctype | def _is_ctype(self, ctype) | Return True iff content is valid and of the given type. | 10.790115 | 7.202024 | 1.498206 |
item = (tag, s)
if item not in self.warnings and \
tag not in self.aggregate.config["ignorewarnings"]:
self.warnings.append(item) | def add_warning (self, s, tag=None) | Add a warning string. | 8.371995 | 6.967313 | 1.20161 |
if s not in self.info:
self.info.append(s) | def add_info (self, s) | Add an info string. | 4.602441 | 3.297068 | 1.395919 |
# remove anchor from cached target url since we assume
# URLs with different anchors to have the same content
self.cache_url = urlutil.urlunsplit(self.urlparts[:4]+[u''])
if self.cache_url is not None:
assert isinstance(self.cache_url, unicode), repr(self.cache_url) | def set_cache_url (self) | Set the URL to be used for caching. | 8.513409 | 8.739091 | 0.974176 |
log.debug(LOG_CHECK, "checking syntax")
if self.base_url is None:
self.base_url = u""
if not (self.base_url or self.parent_url):
self.set_result(_("URL is empty"), valid=False)
return
try:
self.build_url()
self.check_ur... | def check_syntax (self) | Called before self.check(), this function inspects the
url syntax. Success enables further checking, failure
immediately logs this url. Syntax checks must not
use any network resources. | 6.780708 | 6.044795 | 1.121743 |
effectiveurl = urlutil.urlunsplit(self.urlparts)
if self.url != effectiveurl:
self.add_warning(_("Effective URL %(url)r.") %
{"url": effectiveurl},
tag=WARN_URL_EFFECTIVE_URL)
self.url = effectiveurl
if le... | def check_url_warnings(self) | Check URL name and length. | 4.249555 | 3.991851 | 1.064558 |
# norm base url - can raise UnicodeError from url.idna_encode()
base_url, is_idn = url_norm(self.base_url, self.encoding)
# make url absolute
if self.base_ref:
# use base reference as parent url
if ":" not in self.base_ref:
# some websites... | def build_url (self) | Construct self.url and self.urlparts out of the given base
url information self.base_url, self.parent_url and self.base_ref. | 4.185127 | 3.844171 | 1.088694 |
# check userinfo@host:port syntax
self.userinfo, host = urllib.splituser(self.urlparts[1])
port = urlutil.default_ports.get(self.scheme, 0)
host, port = urlutil.splitport(host, port=port)
if port is None:
raise LinkCheckerError(_("URL host %(host)r has invali... | def build_url_parts (self) | Set userinfo, host, port and anchor from self.urlparts.
Also checks for obfuscated IP addresses. | 3.668658 | 3.149006 | 1.165021 |
# check if self.host can be an IP address
# check for obfuscated IP address
if iputil.is_obfuscated_ip(self.host):
ips = iputil.resolve_host(self.host)
if ips:
self.host = ips[0]
self.add_warning(
_("URL %(url)s ... | def check_obfuscated_ip (self) | Warn if host of this URL is obfuscated IP address. | 4.566704 | 4.099906 | 1.113856 |
if self.aggregate.config["trace"]:
trace.trace_on()
try:
self.local_check()
except (socket.error, select.error):
# on Unix, ctrl-c can raise
# error: (4, 'Interrupted system call')
etype, value = sys.exc_info()[:2]
... | def check (self) | Main check function for checking this URL. | 6.336452 | 6.184735 | 1.024531 |
log.debug(LOG_CHECK, "Checking %s", unicode(self))
# strict extern URLs should not be checked
assert not self.extern[1], 'checking strict extern URL'
# check connection
log.debug(LOG_CHECK, "checking connection")
try:
self.check_connection()
... | def local_check (self) | Local check function can be overridden in subclasses. | 8.435662 | 8.2699 | 1.020044 |
if self.do_check_content and self.valid:
# check content and recursion
try:
if self.can_get_content():
self.aggregate.plugin_manager.run_content_plugins(self)
if self.allows_recursion():
return True
... | def check_content(self) | Check content of URL.
@return: True if content can be parsed, else False | 10.303008 | 9.722225 | 1.059738 |
if self.url_connection is None:
# no connection is open
return
try:
self.url_connection.close()
except Exception:
# ignore close errors
pass
self.url_connection = None | def close_connection (self) | Close an opened url connection. | 3.801682 | 2.756687 | 1.379076 |
etype, evalue = sys.exc_info()[:2]
log.debug(LOG_CHECK, "Error in %s: %s %s", self.url, etype, evalue, exception=True)
# note: etype must be the exact class, not a subclass
if (etype in ExcNoCacheList) or \
(etype == socket.error and evalue.args[0]==errno.EBADF) or \
... | def handle_exception (self) | An exception occurred. Log it and set the cache flag. | 8.009268 | 7.648149 | 1.047216 |
maxbytes = self.aggregate.config["maxfilesizedownload"]
if self.size > maxbytes:
self.add_warning(
_("Content size %(size)s is larger than %(maxbytes)s.") %
dict(size=strformat.strsize(self.size),
maxbytes=strformat.strsize(maxb... | def add_size_info (self) | Set size of URL content (if any)..
Should be overridden in subclasses. | 7.328966 | 6.071908 | 1.207028 |
rec_level = self.aggregate.config["recursionlevel"]
if rec_level >= 0 and self.recursion_level >= rec_level:
log.debug(LOG_CHECK, "... no, maximum recursion level reached.")
return False
if self.extern[0]:
log.debug(LOG_CHECK, "... no, extern.")
... | def allows_simple_recursion(self) | Check recursion level and extern status. | 8.353824 | 6.457038 | 1.293755 |
log.debug(LOG_CHECK, "checking recursion of %r ...", self.url)
if not self.valid:
log.debug(LOG_CHECK, "... no, invalid.")
return False
if not self.can_get_content():
log.debug(LOG_CHECK, "... no, cannot get content.")
return False
... | def allows_recursion (self) | Return True iff we can recurse into the url's content. | 3.654868 | 3.383072 | 1.08034 |
if self.extern:
return
if not url:
self.extern = (1, 1)
return
for entry in self.aggregate.config["externlinks"]:
match = entry['pattern'].search(url)
if (entry['negate'] and not match) or \
(match and not entry[... | def set_extern (self, url) | Match URL against extern and intern link patterns. If no pattern
matches the URL is extern. Sets self.extern to a tuple (bool,
bool) with content (is_extern, is_strict).
@return: None | 2.72269 | 2.457399 | 1.107956 |
if self.data is None:
log.debug(LOG_CHECK, "Get content of %r", self.url)
t = time.time()
self.data = self.read_content()
self.size = len(self.data)
self.dltime = time.time() - t
if self.size == 0:
self.add_warning(... | def get_content (self) | Precondition: url_connection is an opened URL. | 5.358075 | 5.039004 | 1.06332 |
buf = StringIO()
data = self.read_content_chunk()
while data:
if buf.tell() + len(data) > self.aggregate.config["maxfilesizedownload"]:
raise LinkCheckerError(_("File size too large"))
buf.write(data)
data = self.read_content_chunk()
... | def read_content(self) | Return data for this URL. Can be overridden in subclasses. | 5.979719 | 5.605715 | 1.066718 |
if self.userinfo:
# URL itself has authentication info
return urllib.splitpasswd(self.userinfo)
return self.aggregate.config.get_user_password(self.url) | def get_user_password (self) | Get tuple (user, password) from configured authentication.
Both user and password can be None. | 16.853157 | 12.727868 | 1.324115 |
if base:
base_ref = urlutil.url_norm(base)[0]
else:
base_ref = None
url_data = get_url_from(url, self.recursion_level+1, self.aggregate,
parent_url=self.url, base_ref=base_ref, line=line, column=column,
page=page, name=name, parent_content... | def add_url (self, url, line=0, column=0, page=0, name=u"", base=None) | Add new URL to queue. | 4.744291 | 4.373616 | 1.084753 |
return unicode_safe(sep).join([
u"%s link" % self.scheme,
u"base_url=%r" % self.base_url,
u"parent_url=%r" % self.parent_url,
u"base_ref=%r" % self.base_ref,
u"recursion_level=%d" % self.recursion_level,
u"url_connection=%s" % self... | def serialized (self, sep=os.linesep) | Return serialized url check data as unicode string. | 2.990147 | 2.808363 | 1.064729 |
try:
pat = self.get_intern_pattern(url=url)
if pat:
log.debug(LOG_CHECK, "Add intern pattern %r", pat)
self.aggregate.config['internlinks'].append(get_link_pat(pat))
except UnicodeError as msg:
res = _("URL has unparsable domai... | def add_intern_pattern(self, url=None) | Add intern URL regex to config. | 8.008582 | 7.781847 | 1.029136 |
return dict(valid=self.valid,
extern=self.extern[0],
result=self.result,
warnings=self.warnings[:],
name=self.name or u"",
title=self.get_title(),
parent_url=self.parent_url or u"",
base_ref=self.base_ref or u"",
base_url=s... | def to_wire_dict (self) | Return a simplified transport object for logging and caching.
The transport object must contain these attributes:
- url_data.valid: bool
Indicates if URL is valid
- url_data.result: unicode
Result string
- url_data.warnings: list of tuples (tag, warning message)
... | 4.062926 | 2.08382 | 1.949749 |
self.write(u"<!-- ")
self.write(s, **args)
self.writeln(u" -->") | def comment (self, s, **args) | Write XML comment. | 4.689817 | 3.570501 | 1.31349 |
self.writeln(u'<?xml version="1.0" encoding="%s"?>' %
xmlquoteattr(self.get_charset_encoding()))
if self.has_part("intro"):
self.write_intro()
self.writeln() | def xml_start_output (self) | Write start of checking info as xml comment. | 6.536695 | 5.906562 | 1.106683 |
self.write(self.indent*self.level)
self.write(u"<%s" % xmlquote(name))
if attrs:
for name, value in attrs.items():
args = (xmlquote(name), xmlquoteattr(value))
self.write(u' %s="%s"' % args)
self.writeln(u">")
self.level += 1 | def xml_starttag (self, name, attrs=None) | Write XML start tag. | 2.744845 | 2.592206 | 1.058884 |
self.level -= 1
assert self.level >= 0
self.write(self.indent*self.level)
self.writeln(u"</%s>" % xmlquote(name)) | def xml_endtag (self, name) | Write XML end tag. | 4.556657 | 4.161319 | 1.095003 |
self.write(self.indent*self.level)
self.write(u"<%s" % xmlquote(name))
if attrs:
for aname, avalue in attrs.items():
args = (xmlquote(aname), xmlquoteattr(avalue))
self.write(u' %s="%s"' % args)
self.writeln(u">%s</%s>" % (xmlquote(con... | def xml_tag (self, name, content, attrs=None) | Write XML tag with content. | 2.841494 | 2.656709 | 1.069554 |
if chunksize is None:
chunksize = _hex_chunksize
hex = data.encode('hex_codec')
l = len(hex)
if l > chunksize:
chunks = []
i = 0
while i < l:
chunks.append(hex[i : i + chunksize])
i += chunksize
hex = ' '.join(chunks)
return hex | def _hexify(data, chunksize=None) | Convert a binary string into its hex encoding, broken up into chunks
of I{chunksize} characters separated by a space.
@param data: the binary string
@type data: string
@param chunksize: the chunk size. Default is L{dns.rdata._hex_chunksize}
@rtype: string | 2.467011 | 2.307519 | 1.069118 |
if chunksize is None:
chunksize = _base64_chunksize
b64 = data.encode('base64_codec')
b64 = b64.replace('\n', '')
l = len(b64)
if l > chunksize:
chunks = []
i = 0
while i < l:
chunks.append(b64[i : i + chunksize])
i += chunksize
b... | def _base64ify(data, chunksize=None) | Convert a binary string into its base64 encoding, broken up into chunks
of I{chunksize} characters separated by a space.
@param data: the binary string
@type data: string
@param chunksize: the chunk size. Default is
L{dns.rdata._base64_chunksize}
@rtype: string | 2.197937 | 2.085999 | 1.053662 |
text = ''
for c in qstring:
if c in __escaped:
text += '\\' + c
elif ord(c) >= 0x20 and ord(c) < 0x7F:
text += c
else:
text += '\\%03d' % ord(c)
return text | def _escapify(qstring) | Escape the characters in a quoted string which need it.
@param qstring: the string
@type qstring: string
@returns: the escaped string
@rtype: string | 2.590919 | 2.697569 | 0.960465 |
for i in xrange(len(what) - 1, -1, -1):
if what[i] != '\x00':
break
return ''.join(what[0 : i + 1]) | def _truncate_bitmap(what) | Determine the index of greatest byte that isn't all zeros, and
return the bitmap that contains all the bytes less than that index.
@param what: a string of octets representing a bitmap.
@type what: string
@rtype: string | 3.051703 | 3.019881 | 1.010537 |
if isinstance(tok, str):
tok = dns.tokenizer.Tokenizer(tok)
cls = get_rdata_class(rdclass, rdtype)
if cls != GenericRdata:
# peek at first token
token = tok.get()
tok.unget(token)
if token.is_identifier() and \
token.value == r'\#':
#
... | def from_text(rdclass, rdtype, tok, origin = None, relativize = True) | Build an rdata object from text format.
This function attempts to dynamically load a class which
implements the specified rdata class and type. If there is no
class-and-type-specific implementation, the GenericRdata class
is used.
Once a class is chosen, its from_text() class method is called
... | 4.413972 | 4.012576 | 1.100034 |
wire = dns.wiredata.maybe_wrap(wire)
cls = get_rdata_class(rdclass, rdtype)
return cls.from_wire(rdclass, rdtype, wire, current, rdlen, origin) | def from_wire(rdclass, rdtype, wire, current, rdlen, origin = None) | Build an rdata object from wire format
This function attempts to dynamically load a class which
implements the specified rdata class and type. If there is no
class-and-type-specific implementation, the GenericRdata class
is used.
Once a class is chosen, its from_wire() class method is called
... | 4.321015 | 4.562548 | 0.947062 |
dns.rdata.from_text(self.rdclass, self.rdtype, self.to_text()) | def validate(self) | Check that the current contents of the rdata's fields are
valid. If you change an rdata by assigning to its fields,
it is a good idea to call validate() when you are done making
changes. | 6.94474 | 4.63154 | 1.499445 |
if self.verbose:
return True
if self.warnings and url_data.warnings:
return True
return not url_data.valid | def do_print (self, url_data) | Determine if URL entry should be logged or not. | 9.178374 | 7.240268 | 1.267684 |
self.check_active_loggers()
do_print = self.do_print(url_data)
# Only send a transport object to the loggers, not the complete
# object instance.
for log in self.loggers:
log.log_filter_url(url_data, do_print) | def log_url (self, url_data) | Send new url to all configured loggers. | 8.152222 | 6.908842 | 1.179969 |
res = []
for c in s:
if ord(c) <= 127:
# ASCII
if c == u'&':
res.append(u"&")
elif c == u'"':
res.append(u""")
else:
res.append(c)
else:
res.append(u"&#%d;" % ord(c))
ret... | def quote_attrval (s) | Quote a HTML attribute to be able to wrap it in double quotes.
@param s: the attribute string to quote
@type s: string
@return: the quoted HTML attribute
@rtype: string | 2.024248 | 2.134684 | 0.948266 |
data = data.encode(self.encoding, "ignore")
self.fd.write("<!--%s-->" % data) | def comment (self, data) | Print HTML comment.
@param data: the comment
@type data: string
@return: None | 6.317894 | 5.776218 | 1.093777 |
tag = tag.encode(self.encoding, "ignore")
self.fd.write("<%s" % tag.replace("/", ""))
for key, val in attrs.items():
key = key.encode(self.encoding, "ignore")
if val is None:
self.fd.write(" %s" % key)
else:
val = val.e... | def _start_element (self, tag, attrs, end) | Print HTML element with end string.
@param tag: tag name
@type tag: string
@param attrs: tag attributes
@type attrs: dict
@param end: either > or />
@type end: string
@return: None | 2.451687 | 2.410743 | 1.016984 |
tag = tag.encode(self.encoding, "ignore")
self.fd.write("</%s>" % tag) | def end_element (self, tag) | Print HTML end element.
@param tag: tag name
@type tag: string
@return: None | 6.427684 | 6.616267 | 0.971497 |
data = data.encode(self.encoding, "ignore")
self.fd.write("<!DOCTYPE%s>" % data) | def doctype (self, data) | Print HTML document type.
@param data: the document type
@type data: string
@return: None | 7.481161 | 6.854777 | 1.091379 |
data = data.encode(self.encoding, "ignore")
self.fd.write("<?%s?>" % data) | def pi (self, data) | Print HTML pi.
@param data: the tag data
@type data: string
@return: None | 8.624822 | 6.360145 | 1.356073 |
data = data.encode(self.encoding, "ignore")
self.fd.write("<![CDATA[%s]]>" % data) | def cdata (self, data) | Print HTML cdata.
@param data: the character data
@type data: string
@return: None | 4.948439 | 5.663469 | 0.873747 |
data = data.encode(self.encoding, "ignore")
self.fd.write(data) | def characters (self, data) | Print characters.
@param data: the character data
@type data: string
@return: None | 7.035774 | 7.515889 | 0.93612 |
if os.name == 'posix':
clamavconf = "/etc/clamav/clamd.conf"
elif os.name == 'nt':
clamavconf = r"c:\clamav-devel\etc\clamd.conf"
else:
clamavconf = "clamd.conf"
return clamavconf | def canonical_clamav_conf () | Default clamav configs for various platforms. | 2.607823 | 2.595805 | 1.00463 |
if os.path.isfile(filename):
return ClamavConfig(filename)
log.warn(LOG_PLUGIN, "No ClamAV config file found at %r.", filename) | def get_clamav_conf(filename) | Initialize clamav configuration. | 6.060436 | 6.052896 | 1.001246 |
family, socktype = socket.AF_INET, socket.SOCK_STREAM
return socket.getaddrinfo(host, port, family, socktype) | def get_sockinfo (host, port=None) | Return socket.getaddrinfo for given host and port. | 3.104533 | 2.80841 | 1.105441 |
try:
scanner = ClamdScanner(clamconf)
except socket.error:
errmsg = _("Could not connect to ClamAV daemon.")
return ([], [errmsg])
try:
scanner.scan(data)
finally:
scanner.close()
return scanner.infected, scanner.errors | def scan (data, clamconf) | Scan data for viruses.
@return (infection msgs, errors)
@rtype ([], []) | 4.387933 | 3.612632 | 1.214608 |
data = url_data.get_content()
infected, errors = scan(data, self.clamav_conf)
if infected or errors:
for msg in infected:
url_data.add_warning(u"Virus scan infection: %s" % msg)
for msg in errors:
url_data.add_warning(u"Virus scan ... | def check(self, url_data) | Try to ask GeoIP database for country info. | 4.00249 | 4.337026 | 0.922865 |
port = None
try:
self.sock.sendall("STREAM")
port = None
for dummy in range(60):
data = self.sock.recv(self.sock_rcvbuf)
i = data.find("PORT")
if i != -1:
port = int(data[i+5:])
... | def new_scansock (self) | Return a connected socket for sending scan data to it. | 3.767058 | 3.590186 | 1.049266 |
self.wsock.close()
data = self.sock.recv(self.sock_rcvbuf)
while data:
if "FOUND\n" in data:
self.infected.append(data)
if "ERROR\n" in data:
self.errors.append(data)
data = self.sock.recv(self.sock_rcvbuf)
self... | def close (self) | Get results and close clamd daemon sockets. | 3.701178 | 3.050667 | 1.213236 |
with open(filename) as fd:
# yet another config format, sigh
for line in fd:
line = line.strip()
if not line or line.startswith("#"):
# ignore empty lines and comments
continue
split = line.s... | def parseconf (self, filename) | Parse clamav configuration from given file. | 2.891461 | 2.902532 | 0.996186 |
if self.get('LocalSocket'):
host = 'localhost'
sock = self.create_local_socket()
elif self.get('TCPSocket'):
host = self.get('TCPAddr', 'localhost')
sock = self.create_tcp_socket(host)
else:
raise ClamavError(_("one of TCPSocke... | def new_connection (self) | Connect to clamd for stream scanning.
@return: tuple (connected socket, host) | 5.113609 | 4.162782 | 1.228412 |
sock = create_socket(socket.AF_UNIX, socket.SOCK_STREAM)
addr = self['LocalSocket']
try:
sock.connect(addr)
except socket.error:
sock.close()
raise
return sock | def create_local_socket (self) | Create local socket, connect to it and return socket object. | 3.770558 | 3.509569 | 1.074365 |
port = int(self['TCPSocket'])
sockinfo = get_sockinfo(host, port=port)
sock = create_socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect(sockinfo[0][4])
except socket.error:
sock.close()
raise
return sock | def create_tcp_socket (self, host) | Create tcp socket, connect to it and return socket object. | 3.925295 | 3.688714 | 1.064137 |
'''zonalstats generates summary statistics of geospatial raster datasets
based on vector features.
The input arguments to zonalstats should be valid GeoJSON Features. (see cligj)
The output GeoJSON will be mostly unchanged but have additional properties per feature
describing the summary statistic... | def zonalstats(features, raster, all_touched, band, categorical,
indent, info, nodata, prefix, stats, sequence, use_rs) | zonalstats generates summary statistics of geospatial raster datasets
based on vector features.
The input arguments to zonalstats should be valid GeoJSON Features. (see cligj)
The output GeoJSON will be mostly unchanged but have additional properties per feature
describing the summary statistics (min,... | 5.253491 | 2.096219 | 2.506175 |
results = gen_point_query(
features,
raster,
band=band,
nodata=nodata,
interpolate=interpolate,
property_name=property_name,
geojson_out=True)
if sequence:
for feature in results:
if use_rs:
click.echo(b'\x1e', nl... | def pointquery(features, raster, band, indent, nodata,
interpolate, property_name, sequence, use_rs) | Queries the raster values at the points of the input GeoJSON Features.
The raster values are added to the features properties and output as GeoJSON
Feature Collection.
If the Features are Points, the point geometery is used.
For other Feauture types, all of the verticies of the geometry will be queried... | 3.060415 | 3.432975 | 0.891476 |
fcol, frow = ~affine * (x, y)
r, c = int(round(frow)), int(round(fcol))
# The new source window for our 2x2 array
new_win = ((r - 1, r + 1), (c - 1, c + 1))
# the new x, y coords on the unit square
unitxy = (0.5 - (c - fcol),
0.5 + (r - frow))
return new_win, unitxy | def point_window_unitxy(x, y, affine) | Given an x, y and a geotransform
Returns
- rasterio window representing 2x2 window whose center points encompass point
- the cartesian x, y coordinates of the point on the unit square
defined by the array center points.
((row1, row2), (col1, col2)), (unitx, unity) | 4.768222 | 3.904964 | 1.221067 |
# for now, only 2x2 arrays
assert arr.shape == (2, 2)
ulv, urv, llv, lrv = arr[0:2, 0:2].flatten().tolist()
# not valid if not on unit square
assert 0.0 <= x <= 1.0
assert 0.0 <= y <= 1.0
if hasattr(arr, 'count') and arr.count() != 4:
# a masked array with at least one nodata
... | def bilinear(arr, x, y) | Given a 2x2 array, an x, and y, treat center points as a unit square
return the value for the fractional row/col
using bilinear interpolation between the cells
+---+---+
| A | B | +----+
+---+---+ => | |
| C | D | +----+
+---+---+
e.g.: Center of ... | 3.720131 | 3.70342 | 1.004512 |
if geom.has_z:
# hack to convert to 2D, https://gist.github.com/ThomasG77/cad711667942826edc70
geom = wkt.loads(geom.to_wkt())
assert not geom.has_z
if hasattr(geom, "geoms"):
geoms = geom.geoms
else:
geoms = [geom]
for g in geoms:
arr = g.array_int... | def geom_xys(geom) | Given a shapely geometry,
generate a flattened series of 2D points as x,y tuples | 5.475423 | 5.215932 | 1.04975 |
if interpolate not in ['nearest', 'bilinear']:
raise ValueError("interpolate must be nearest or bilinear")
features_iter = read_features(vectors, layer)
with Raster(raster, nodata=nodata, affine=affine, band=band) as rast:
for feat in features_iter:
geom = shape(feat['geo... | def gen_point_query(
vectors,
raster,
band=1,
layer=0,
nodata=None,
affine=None,
interpolate='bilinear',
property_name='value',
geojson_out=False) | Given a set of vector features and a raster,
generate raster values at each vertex of the geometry
For features with point geometry,
the values will be a 1D with the index refering to the feature
For features with other geometry types,
it effectively creates a 2D list, such that
the first inde... | 2.809746 | 2.996643 | 0.937631 |
geoms = [(geom, 1)]
rv_array = features.rasterize(
geoms,
out_shape=like.shape,
transform=like.affine,
fill=0,
dtype='uint8',
all_touched=all_touched)
return rv_array.astype(bool) | def rasterize_geom(geom, like, all_touched=False) | Parameters
----------
geom: GeoJSON geometry
like: raster object with desired shape and transform
all_touched: rasterization strategy
Returns
-------
ndarray: boolean | 2.899085 | 4.435285 | 0.653641 |
vs = list(d.values())
ks = list(d.keys())
key = ks[vs.index(func(vs))]
return key | def key_assoc_val(d, func, exclude=None) | return the key associated with the value returned by func | 3.862468 | 3.376735 | 1.143847 |
if 'Point' not in geom.type:
raise ValueError("Points or multipoints only")
buff = -0.01 * abs(min(rast.affine.a, rast.affine.e))
if geom.type == 'Point':
pts = [geom]
elif geom.type == "MultiPoint":
pts = geom.geoms
geoms = []
for pt in pts:
row, col = ras... | def boxify_points(geom, rast) | Point and MultiPoint don't play well with GDALRasterize
convert them into box polygons 99% cellsize, centered on the raster cell | 3.159927 | 3.116809 | 1.013834 |
# object implementing geo_interface
if hasattr(obj, '__geo_interface__'):
gi = obj.__geo_interface__
if gi['type'] in geom_types:
return wrap_geom(gi)
elif gi['type'] == 'Feature':
return gi
# wkt
try:
shape = wkt.loads(obj)
return w... | def parse_feature(obj) | Given a python object
attemp to a GeoJSON-like Feature from it | 2.862792 | 2.775207 | 1.03156 |
r = int(op((y - affine.f) / affine.e))
c = int(op((x - affine.c) / affine.a))
return r, c | def rowcol(x, y, affine, op=math.floor) | Get row/col for a x/y | 2.884816 | 3.174164 | 0.908843 |
w, s, e, n = bounds
row_start, col_start = rowcol(w, n, affine)
row_stop, col_stop = rowcol(e, s, affine, op=math.ceil)
return (row_start, row_stop), (col_start, col_stop) | def bounds_window(bounds, affine) | Create a full cover rasterio-style window | 3.452161 | 2.817698 | 1.225171 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.