text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _net_write(sock, data, expiration):
"""Write the specified data to the socket. A Timeout exception will be raised if the operation is not completed by the expiration time. """ |
current = 0
l = len(data)
while current < l:
_wait_for_writable(sock, expiration)
current += sock.send(data[current:]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tcp(q, where, timeout=None, port=53, af=None, source=None, source_port=0, one_rr_per_rrset=False):
"""Return the response obtained after sending a query via TCP. @param q: the query @type q: dns.message.Message object @param where: where to send the message @type where: string containing an IPv4 or IPv6 address @param timeout: The number of seconds to wait before the query times out. If None, the default, wait forever. @type timeout: float @param port: The port to which to send the message. The default is 53. @type port: int @param af: the address family to use. The default is None, which causes the address family to use to be inferred from the form of of where. If the inference attempt fails, AF_INET is used. @type af: int @rtype: dns.message.Message object @param source: source address. The default is the IPv4 wildcard address. @type source: string @param source_port: The port from which to send the message. The default is 0. @type source_port: int @param one_rr_per_rrset: Put each RR into its own RRset @type one_rr_per_rrset: bool """ |
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)
if source is not None:
source = (source, source_port)
elif af == dns.inet.AF_INET6:
destination = (where, port, 0, 0)
if source is not None:
source = (source, source_port, 0, 0)
s = socket.socket(af, socket.SOCK_STREAM, 0)
try:
expiration = _compute_expiration(timeout)
s.setblocking(0)
if source is not None:
s.bind(source)
_connect(s, destination)
l = len(wire)
# copying the wire into tcpmsg is inefficient, but lets us
# avoid writev() or doing a short write that would get pushed
# onto the net
tcpmsg = struct.pack("!H", l) + wire
_net_write(s, tcpmsg, expiration)
ldata = _net_read(s, 2, expiration)
(l,) = struct.unpack("!H", ldata)
wire = _net_read(s, l, expiration)
finally:
s.close()
r = dns.message.from_wire(wire, keyring=q.keyring, request_mac=q.mac,
one_rr_per_rrset=one_rr_per_rrset)
if not q.is_response(r):
raise BadResponse
return r |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_text(text):
"""Convert text into a DNS rdata type value. @param text: the text @type text: string @raises dns.rdatatype.UnknownRdatatype: the type is unknown @raises ValueError: the rdata type value is not >= 0 and <= 65535 @rtype: int""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_metatype(rdtype):
"""True if the type is a metatype. @param rdtype: the type @type rdtype: int @rtype: bool""" |
if rdtype >= TKEY and rdtype <= ANY or rdtype in _metatypes:
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_checked (self):
"""Print periodic status messages.""" |
self.start_time = time.time()
self.setName("Status")
# the first status should be after a second
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log_status (self):
"""Log a status message.""" |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_mimedb():
"""Initialize the local MIME database.""" |
global mimedb
try:
mimedb = mimetypes.MimeTypes(strict=False)
except Exception as msg:
log.error(LOG_CHECK, "could not initialize MIME database: %s" % msg)
return
# For Opera bookmark files (opera6.adr)
add_mimetype(mimedb, 'text/plain', '.adr')
# To recognize PHP files as HTML with content check.
add_mimetype(mimedb, 'application/x-httpd-php', '.php')
# To recognize WML files
add_mimetype(mimedb, 'text/vnd.wap.wml', '.wml') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_mimetype(mimedb, mimetype, extension):
"""Add or replace a mimetype to be used with the given extension.""" |
# If extension is already a common type, strict=True must be used.
strict = extension in mimedb.types_map[True]
mimedb.add_type(mimetype, extension, strict=strict) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search_form(content, cgiuser, cgipassword, encoding='utf-8'):
"""Search for a HTML form in the given HTML content that has the given CGI fields. If no form is found return None. """ |
handler = FormFinder()
parser = htmlsax.parser(handler)
handler.parser = parser
parser.encoding = encoding
# parse
parser.feed(content)
parser.flush()
# break cyclic dependencies
handler.parser = None
parser.handler = None
log.debug(LOG_CHECK, "Found forms %s", handler.forms)
cginames = (cgiuser.lower(), cgipassword.lower())
for form in handler.forms:
for key, value in form.data.items():
if key.lower() in cginames:
return form
# not found
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def end_element(self, tag):
"""search for ending form values.""" |
if tag == u'form':
self.forms.append(self.form)
self.form = None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_i18n (loc=None):
"""Initialize i18n with the configured locale dir. The environment variable LOCPATH can also specify a locale dir. @return: 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)
# install translated log level names
import logging
logging.addLevelName(logging.CRITICAL, _('CRITICAL'))
logging.addLevelName(logging.ERROR, _('ERROR'))
logging.addLevelName(logging.WARN, _('WARN'))
logging.addLevelName(logging.WARNING, _('WARNING'))
logging.addLevelName(logging.INFO, _('INFO'))
logging.addLevelName(logging.DEBUG, _('DEBUG'))
logging.addLevelName(logging.NOTSET, _('NOTSET')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def drop_privileges ():
"""Make sure to drop root privileges on POSIX systems.""" |
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]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_third_party_modules ():
"""Find third party modules and add them to the python path.""" |
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")) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_plist_data_from_file (filename):
"""Parse plist data for a file. Tries biplist, falling back to plistlib.""" |
if has_biplist:
return biplist.readPlist(filename)
# fall back to normal plistlist
try:
return plistlib.readPlist(filename)
except Exception:
# not parseable (eg. not well-formed, or binary)
return {} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_plist_data_from_string (data):
"""Parse plist data for a string. Tries biplist, falling back to plistlib.""" |
if has_biplist:
return biplist.readPlistFromString(data)
# fall back to normal plistlist
try:
return plistlib.readPlistFromString(data)
except Exception:
# not parseable (eg. not well-formed, or binary)
return {} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_plist(entry):
"""Parse a XML dictionary 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def algorithm_from_text(text):
"""Convert text into a DNSSEC algorithm value @rtype: int""" |
value = _algorithm_by_text.get(text.upper())
if value is None:
value = int(text)
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def algorithm_to_text(value):
"""Convert a DNSSEC algorithm value to text @rtype: string""" |
text = _algorithm_by_value.get(value)
if text is None:
text = str(value)
return text |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate(rrset, rrsigset, keys, origin=None, now=None):
"""Validate an RRset @param rrset: The RRset to validate @type rrset: dns.rrset.RRset or (dns.name.Name, dns.rdataset.Rdataset) tuple @param rrsigset: The signature RRset @type rrsigset: dns.rrset.RRset or (dns.name.Name, dns.rdataset.Rdataset) tuple @param keys: The key dictionary. @type keys: a dictionary keyed by dns.name.Name with node or rdataset values @param origin: The origin to use for relative names @type origin: dns.name.Name or None @param now: The time to use when validating the signatures. The default is the current time. @type now: int """ |
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 = rrsigset[0]
rrsigrdataset = rrsigset[1]
else:
rrsigname = rrsigset.name
rrsigrdataset = rrsigset
rrname = rrname.choose_relativity(origin)
rrsigname = rrname.choose_relativity(origin)
if rrname != rrsigname:
raise ValidationFailure, "owner names do not match"
for rrsig in rrsigrdataset:
try:
_validate_rrsig(rrset, rrsig, keys, origin, now)
return
except ValidationFailure, e:
pass
raise ValidationFailure, "no RRSIGs validated" |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def allows_url (self, url_data):
"""Ask robots.txt allowance.""" |
roboturl = url_data.get_robots_txt_url()
with self.get_lock(roboturl):
return self._allows_url(url_data, roboturl) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _allows_url (self, url_data, roboturl):
"""Ask robots.txt allowance. Assumes only single thread per robots.txt URL calls this function.""" |
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, "proxy") and hasattr(url_data, "proxy_type"):
kwargs["proxies"] = {url_data.proxytype: url_data.proxy}
rp = robotparser2.RobotFileParser(**kwargs)
rp.set_url(roboturl)
rp.read()
with cache_lock:
self.cache[roboturl] = rp
self.add_sitemap_urls(rp, url_data, roboturl)
return rp.can_fetch(self.useragent, url_data.url) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_sitemap_urls(self, rp, url_data, roboturl):
"""Add sitemap URLs to queue.""" |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start_output (self):
"""Write start of checking info.""" |
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": self.colorerror,
"valid": self.colorok,
"warning": self.colorwarning,
}
self.write(HTML_HEADER % header)
self.comment("Generated by %s" % configuration.App)
if self.has_part('intro'):
self.write(u"<h2>"+configuration.App+
"</h2><br/><blockquote>"+
configuration.Freeware+"<br/><br/>"+
(_("Start checking at %s") %
strformat.strtime(self.starttime))+
os.linesep+"<br/>")
self.check_date()
self.flush() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_id (self):
"""Write ID for current URL.""" |
self.writeln(u"<tr>")
self.writeln(u'<td>%s</td>' % self.part("id"))
self.write(u"<td>%d</td></tr>" % self.stats.number) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_warning (self, url_data):
"""Write url_data.warnings.""" |
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>") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_stats (self):
"""Write check statistic infos.""" |
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_types)
self.writeln(u"<br/>")
self.writeln(_("URL lengths: min=%(min)d, max=%(max)d, avg=%(avg)d.") %
dict(min=self.stats.min_url_length,
max=self.stats.max_url_length,
avg=self.stats.avg_url_length))
else:
self.writeln(_("No statistics available since no URLs were checked."))
self.writeln(u"<br/>") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_outro (self):
"""Write end of check message.""" |
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 found",
self.stats.warnings_printed) % self.stats.warnings_printed)
if self.stats.warnings != self.stats.warnings_printed:
self.write(_(" (%d ignored or duplicates not printed)") %
(self.stats.warnings - self.stats.warnings_printed))
self.write(u". ")
self.write(_n("%d error found", "%d errors found",
self.stats.errors_printed) % self.stats.errors_printed)
if self.stats.errors != self.stats.errors_printed:
self.write(_(" (%d duplicates not printed)") %
(self.stats.errors - self.stats.errors_printed))
self.writeln(u".")
self.writeln(u"<br/>")
num = self.stats.internal_errors
if num:
self.write(_n("There was %(num)d internal error.",
"There were %(num)d internal errors.", num) % {"num": num})
self.writeln(u"<br/>")
self.stoptime = time.time()
duration = self.stoptime - self.starttime
self.writeln(_("Stopped checking at %(time)s (%(duration)s)") %
{"time": strformat.strtime(self.stoptime),
"duration": strformat.strduration_long(duration)})
self.writeln(u'</blockquote><br/><hr><small>'+
configuration.HtmlAppInfo+u"<br/>")
self.writeln(_("Get the newest version at %s") %
(u'<a href="'+configuration.Url+u'" target="_top">'+
configuration.Url+u"</a>.<br/>"))
self.writeln(_("Write comments and bugs to %s") %
(u'<a href="'+configuration.SupportUrl+u'">'+
configuration.SupportUrl+u"</a>.<br/>"))
self.writeln(_("Support this project at %s") %
(u'<a href="'+configuration.DonateUrl+u'">'+
configuration.DonateUrl+u"</a>."))
self.writeln(u"</small></body></html>") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def end_output (self, **kwargs):
"""Write end of checking info as HTML.""" |
if self.has_part("stats"):
self.write_stats()
if self.has_part("outro"):
self.write_outro()
self.close_fileoutput() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_valid_ipv4 (ip):
""" Return True if given ip is a valid IPv4 address. """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_valid_ipv6 (ip):
""" Return True if given ip is a valid IPv6 address. """ |
# XXX this is not complete: check ipv6 and ipv4 semantics too here
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def host_in_set (ip, hosts, nets):
""" Return True if given ip is in host or network list. """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lookup_ips (ips):
""" Return set of host names that resolve to given ips. """ |
hosts = set()
for ip in ips:
try:
hosts.add(socket.gethostbyaddr(ip)[0])
except socket.error:
hosts.add(ip)
return hosts |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def obfuscate_ip(ip):
"""Obfuscate given host in IP form. @ip: IPv4 address string @raise: ValueError on invalid IP addresses """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put (self, item):
"""Put an item into the queue. Block if necessary until a free slot is available. """ |
with self.mutex:
self._put(item)
self.not_empty.notify() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _put (self, url_data):
"""Put URL in queue, increase number of unfished tasks.""" |
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)
else:
assert key is not None, "no result for None key: %s" % url_data
if self.max_allowed_urls is not None:
self.max_allowed_urls -= 1
self.num_puts += 1
if self.num_puts >= NUM_PUTS_CLEANUP:
self.cleanup()
self.queue.append(url_data)
self.unfinished_tasks += 1 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cleanup(self):
"""Move cached elements to top.""" |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _move_to_top(self, pos):
"""Move element at given position to top of queue.""" |
if pos > 0:
self.queue.rotate(-pos)
item = self.queue.popleft()
self.queue.rotate(pos)
self.queue.appendleft(item) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_shutdown (self):
"""Shutdown the queue by not accepting any more URLs.""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add(self, item):
"""Add an item to the set.""" |
if not item in self.items:
self.items.append(item) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 """ |
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):
if item not in other.items:
self.items.remove(item) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def urljoin (parent, url):
""" If url is relative, join parent and url. Else leave url as-is. @return joined url """ |
if urlutil.url_is_absolute(url):
return url
return urlparse.urljoin(parent, url) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init (self, base_ref, base_url, parent_url, recursion_level, aggregate, line, column, page, name, url_encoding, extern):
""" Initialize internal data. """ |
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(self.base_url)
self.parent_url = parent_url
if self.parent_url is not None:
assert isinstance(self.parent_url, unicode), repr(self.parent_url)
self.recursion_level = recursion_level
self.aggregate = aggregate
self.line = line
self.column = column
self.page = page
self.name = name
assert isinstance(self.name, unicode), repr(self.name)
self.encoding = url_encoding
self.charset = None
self.extern = extern
if self.base_ref:
assert not urlutil.url_needs_quoting(self.base_ref), \
"unquoted base reference URL %r" % self.base_ref
if self.parent_url:
assert not urlutil.url_needs_quoting(self.parent_url), \
"unquoted parent URL %r" % self.parent_url
url = absolute_url(self.base_url, base_ref, parent_url)
# assume file link if no scheme is found
self.scheme = url.split(":", 1)[0].lower() or "file"
if self.base_url != base_url:
self.add_warning(_("Leading or trailing whitespace in URL `%(url)s'.") %
{"url": base_url}, tag=WARN_URL_WHITESPACE) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reset (self):
""" Reset all variables to default values. """ |
# 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
self.urlparts = None
# the scheme, host, port and anchor part of url
self.scheme = self.host = self.port = self.anchor = None
# the result message string and flag
self.result = u""
self.has_result = False
# valid or not
self.valid = True
# list of warnings (without duplicates)
self.warnings = []
# list of infos
self.info = []
# content size
self.size = -1
# last modification time of content in HTTP-date format as specified in RFC2616 chapter 3.3.1
self.modified = None
# download time
self.dltime = -1
# check time
self.checktime = 0
# connection object
self.url_connection = None
# data of url content, (data == None) means no data is available
self.data = None
# cache url is set by build_url() calling set_cache_url()
self.cache_url = None
# extern flags (is_extern, is_strict)
self.extern = None
# flag if the result should be cached
self.caching = True
# title is either the URL or parsed from content
self.title = None
# flag if content should be checked or not
self.do_check_content = True
# MIME content type
self.content_type = u""
# URLs seen through redirections
self.aliases = [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_result (self, msg, valid=True, overwrite=False):
""" Set result string and validity. """ |
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", self, msg)
elif not msg:
log.warn(LOG_CHECK, "Empty result for %s", self)
self.result = msg
self.valid = valid
# free content data
self.data = None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_title (self):
"""Return title of page the URL refers to. This is per default the filename or the URL.""" |
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:
self.title = title
return self.title |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _is_ctype(self, ctype):
"""Return True iff content is valid and of the given type.""" |
if not self.valid:
return False
mime = self.content_type
return self.ContentMimetypes.get(mime) == ctype |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_warning (self, s, tag=None):
""" Add a warning string. """ |
item = (tag, s)
if item not in self.warnings and \
tag not in self.aggregate.config["ignorewarnings"]:
self.warnings.append(item) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_info (self, s):
""" Add an info string. """ |
if s not in self.info:
self.info.append(s) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_cache_url (self):
"""Set the URL to be used for caching.""" |
# 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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_url_warnings(self):
"""Check URL name and length.""" |
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 len(self.url) > URL_MAX_LENGTH and self.scheme != u"data":
args = dict(len=len(self.url), max=URL_MAX_LENGTH)
self.add_warning(_("URL length %(len)d is longer than %(max)d.") % args, tag=WARN_URL_TOO_LONG) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. """ |
# 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 have a relative base reference
self.base_ref = urljoin(self.parent_url, self.base_ref)
self.url = urljoin(self.base_ref, base_url)
elif self.parent_url:
# strip the parent url query and anchor
urlparts = list(urlparse.urlsplit(self.parent_url))
urlparts[4] = ""
parent_url = urlutil.urlunsplit(urlparts)
self.url = urljoin(parent_url, base_url)
else:
self.url = base_url
# urljoin can unnorm the url path, so norm it again
urlparts = list(urlparse.urlsplit(self.url))
if urlparts[2]:
urlparts[2] = urlutil.collapse_segments(urlparts[2])
self.url = urlutil.urlunsplit(urlparts)
# split into (modifiable) list
self.urlparts = strformat.url_unicode_split(self.url)
self.build_url_parts()
# and unsplit again
self.url = urlutil.urlunsplit(self.urlparts) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_url_parts (self):
"""Set userinfo, host, port and anchor from self.urlparts. Also checks for obfuscated IP addresses. """ |
# 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 invalid port") %
{"host": host})
self.port = port
# set host lowercase
self.host = host.lower()
if self.scheme in scheme_requires_host:
if not self.host:
raise LinkCheckerError(_("URL has empty hostname"))
self.check_obfuscated_ip()
if not self.port or self.port == urlutil.default_ports.get(self.scheme):
host = self.host
else:
host = "%s:%d" % (self.host, self.port)
if self.userinfo:
self.urlparts[1] = "%s@%s" % (self.userinfo, host)
else:
self.urlparts[1] = host
# safe anchor for later checking
self.anchor = self.urlparts[4]
if self.anchor is not None:
assert isinstance(self.anchor, unicode), repr(self.anchor) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_obfuscated_ip (self):
"""Warn if host of this URL is obfuscated IP address.""" |
# 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 has obfuscated IP address %(ip)s") % \
{"url": self.base_url, "ip": ips[0]},
tag=WARN_URL_OBFUSCATED_IP) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check (self):
"""Main check function for checking this URL.""" |
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]
if etype == errno.EINTR:
raise KeyboardInterrupt(value)
else:
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def local_check (self):
"""Local check function can be overridden in subclasses.""" |
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()
self.set_content_type()
self.add_size_info()
self.aggregate.plugin_manager.run_connection_plugins(self)
except tuple(ExcList) as exc:
value = self.handle_exception()
# make nicer error msg for unknown hosts
if isinstance(exc, socket.error) and exc.args[0] == -2:
value = _('Hostname not found')
elif isinstance(exc, UnicodeError):
# idna.encode(host) failed
value = _('Bad hostname %(host)r: %(msg)s') % {'host': self.host, 'msg': str(value)}
self.set_result(unicode_safe(value), valid=False) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_content(self):
"""Check content of URL. @return: True if content can be parsed, else False """ |
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
except tuple(ExcList):
value = self.handle_exception()
self.add_warning(_("could not get content: %(msg)s") %
{"msg": str(value)}, tag=WARN_URL_ERROR_GETTING_CONTENT)
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close_connection (self):
""" Close an opened url connection. """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_exception (self):
""" An exception occurred. Log it and set the cache flag. """ |
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 \
not evalue:
# EBADF occurs when operating on an already socket
self.caching = False
# format unicode message "<exception name>: <error message>"
errmsg = unicode(etype.__name__)
uvalue = strformat.unicode_safe(evalue)
if uvalue:
errmsg += u": %s" % uvalue
# limit length to 240
return strformat.limit(errmsg, length=240) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def allows_simple_recursion(self):
"""Check recursion level and extern status.""" |
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.")
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def allows_recursion (self):
""" Return True iff we can recurse into the url's content. """ |
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
if not self.allows_simple_recursion():
return False
if self.size > self.aggregate.config["maxfilesizeparse"]:
log.debug(LOG_CHECK, "... no, maximum parse size.")
return False
if not self.is_parseable():
log.debug(LOG_CHECK, "... no, not parseable.")
return False
if not self.content_allows_robots():
log.debug(LOG_CHECK, "... no, robots.")
return False
log.debug(LOG_CHECK, "... yes, recursion.")
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_content(self):
"""Return data for this URL. Can be overridden in subclasses.""" |
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()
return buf.getvalue() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_url (self, url, line=0, column=0, page=0, name=u"", base=None):
"""Add new URL to queue.""" |
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_type=self.content_type)
self.aggregate.urlqueue.put(url_data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serialized (self, sep=os.linesep):
""" Return serialized url check data as unicode string. """ |
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.url_connection,
u"line=%d" % self.line,
u"column=%d" % self.column,
u"page=%d" % self.page,
u"name=%r" % self.name,
u"anchor=%r" % self.anchor,
u"cache_url=%s" % self.cache_url,
]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_intern_pattern(self, url=None):
"""Add intern URL regex to config.""" |
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 domain name: %(domain)s") % \
{"domain": msg}
self.set_result(res, valid=False) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) List of tagged warnings for this URL. - url_data.name: unicode string or None name of URL (eg. filename or link name) - url_data.parent_url: unicode or None Parent URL - url_data.base_ref: unicode HTML base reference URL of parent - url_data.url: unicode Fully qualified URL. - url_data.domain: unicode URL domain part. - url_data.checktime: int Number of seconds needed to check this link, default: zero. - url_data.dltime: int Number of seconds needed to download URL content, default: -1 - url_data.size: int Size of downloaded URL content, default: -1 - url_data.info: list of unicode Additional information about this URL. - url_data.line: int Line number of this URL at parent document, or -1 - url_data.column: int Column number of this URL at parent document, or -1 - url_data.page: int Page number of this URL at parent document, or -1 - url_data.cache_url: unicode Cache url for this URL. - url_data.content_type: unicode MIME content type for URL content. - url_data.level: int Recursion level until reaching this URL from start URL - url_data.last_modified: datetime Last modification date of retrieved page (or None). """ |
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=self.base_url or u"",
url=self.url or u"",
domain=(self.urlparts[1] if self.urlparts else u""),
checktime=self.checktime,
dltime=self.dltime,
size=self.size,
info=self.info,
line=self.line,
column=self.column,
page=self.page,
cache_url=self.cache_url,
content_type=self.content_type,
level=self.recursion_level,
modified=self.modified,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def comment (self, s, **args):
""" Write XML comment. """ |
self.write(u"<!-- ")
self.write(s, **args)
self.writeln(u" -->") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def xml_starttag (self, name, attrs=None):
""" Write XML start tag. """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def xml_tag (self, name, content, attrs=None):
""" Write XML tag with content. """ |
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(content), xmlquote(name))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 """ |
for i in xrange(len(what) - 1, -1, -1):
if what[i] != '\x00':
break
return ''.join(what[0 : i + 1]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 with the parameters to this function. @param rdclass: The rdata class @type rdclass: int @param rdtype: The rdata type @type rdtype: int @param tok: The tokenizer @type tok: dns.tokenizer.Tokenizer @param origin: The origin to use for relative names @type origin: dns.name.Name @param relativize: Should names be relativized? @type relativize: bool @rtype: dns.rdata.Rdata instance""" |
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'\#':
#
# Known type using the generic syntax. Extract the
# wire form from the generic syntax, and then run
# from_wire on it.
#
rdata = GenericRdata.from_text(rdclass, rdtype, tok, origin,
relativize)
return from_wire(rdclass, rdtype, rdata.data, 0, len(rdata.data),
origin)
return cls.from_text(rdclass, rdtype, tok, origin, relativize) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 with the parameters to this function. @param rdclass: The rdata class @type rdclass: int @param rdtype: The rdata type @type rdtype: int @param wire: The wire-format message @type wire: string @param current: The offet in wire of the beginning of the rdata. @type current: int @param rdlen: The length of the wire-format rdata @type rdlen: int @param origin: The origin to use for relative names @type origin: dns.name.Name @rtype: dns.rdata.Rdata instance""" |
wire = dns.wiredata.maybe_wrap(wire)
cls = get_rdata_class(rdclass, rdtype)
return cls.from_wire(rdclass, rdtype, wire, current, rdlen, origin) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_print (self, url_data):
"""Determine if URL entry should be logged or not.""" |
if self.verbose:
return True
if self.warnings and url_data.warnings:
return True
return not url_data.valid |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log_url (self, url_data):
"""Send new url to all configured loggers.""" |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 """ |
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))
return u"".join(res) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def comment (self, data):
""" Print HTML comment. @param data: the comment @type data: string @return: None """ |
data = data.encode(self.encoding, "ignore")
self.fd.write("<!--%s-->" % data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 """ |
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.encode(self.encoding, "ignore")
self.fd.write(' %s="%s"' % (key, quote_attrval(val)))
self.fd.write(end) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def end_element (self, tag):
""" Print HTML end element. @param tag: tag name @type tag: string @return: None """ |
tag = tag.encode(self.encoding, "ignore")
self.fd.write("</%s>" % tag) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def doctype (self, data):
""" Print HTML document type. @param data: the document type @type data: string @return: None """ |
data = data.encode(self.encoding, "ignore")
self.fd.write("<!DOCTYPE%s>" % data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pi (self, data):
""" Print HTML pi. @param data: the tag data @type data: string @return: None """ |
data = data.encode(self.encoding, "ignore")
self.fd.write("<?%s?>" % data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cdata (self, data):
""" Print HTML cdata. @param data: the character data @type data: string @return: None """ |
data = data.encode(self.encoding, "ignore")
self.fd.write("<![CDATA[%s]]>" % data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def characters (self, data):
""" Print characters. @param data: the character data @type data: string @return: None """ |
data = data.encode(self.encoding, "ignore")
self.fd.write(data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def canonical_clamav_conf ():
"""Default clamav configs for various platforms.""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_clamav_conf(filename):
"""Initialize clamav configuration.""" |
if os.path.isfile(filename):
return ClamavConfig(filename)
log.warn(LOG_PLUGIN, "No ClamAV config file found at %r.", filename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_sockinfo (host, port=None):
"""Return socket.getaddrinfo for given host and port.""" |
family, socktype = socket.AF_INET, socket.SOCK_STREAM
return socket.getaddrinfo(host, port, family, socktype) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scan (data, clamconf):
"""Scan data for viruses. @return (infection msgs, errors) @rtype ([], []) """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new_scansock (self):
"""Return a connected socket for sending scan data to it.""" |
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:])
break
except socket.error:
self.sock.close()
raise
if port is None:
raise ClamavError(_("clamd is not ready for stream scanning"))
sockinfo = get_sockinfo(self.host, port=port)
wsock = create_socket(socket.AF_INET, socket.SOCK_STREAM)
try:
wsock.connect(sockinfo[0][4])
except socket.error:
wsock.close()
raise
return wsock |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close (self):
"""Get results and close clamd daemon sockets.""" |
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.sock.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parseconf (self, filename):
"""Parse clamav configuration from given file.""" |
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.split(None, 1)
if len(split) == 1:
self[split[0]] = True
else:
self[split[0]] = split[1] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new_connection (self):
"""Connect to clamd for stream scanning. @return: tuple (connected socket, host) """ |
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 TCPSocket or LocalSocket must be enabled"))
return sock, host |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_local_socket (self):
"""Create local socket, connect to it and return socket object.""" |
sock = create_socket(socket.AF_UNIX, socket.SOCK_STREAM)
addr = self['LocalSocket']
try:
sock.connect(addr)
except socket.error:
sock.close()
raise
return sock |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_tcp_socket (self, host):
"""Create tcp socket, connect to it and return socket object.""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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, max, mean, etc.) of the underlying raster dataset.
The raster is specified by the required -r/--raster argument.
Example, calculate rainfall stats for each state and output to file:
\b
rio zonalstats states.geojson -r rainfall.tif > mean_rainfall_by_state.geojson
'''
if info:
logging.basicConfig(level=logging.INFO)
if stats is not None:
stats = stats.split(" ")
if 'all' in [x.lower() for x in stats]:
stats = "ALL"
zonal_results = gen_zonal_stats(
features,
raster,
all_touched=all_touched,
band=band,
categorical=categorical,
nodata=nodata,
stats=stats,
prefix=prefix,
geojson_out=True)
if sequence:
for feature in zonal_results:
if use_rs:
click.echo(b'\x1e', nl=False)
click.echo(json.dumps(feature))
else:
click.echo(json.dumps(
{'type': 'FeatureCollection',
'features': list(zonal_results)})) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. For example, you can provide a linestring and get the profile along the line if the verticies are spaced properly. You can use either bilinear (default) or nearest neighbor interpolation. """ |
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=False)
click.echo(json.dumps(feature))
else:
click.echo(json.dumps(
{'type': 'FeatureCollection',
'features': list(results)})) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def geom_xys(geom):
"""Given a shapely geometry, generate a flattened series of 2D points as x,y tuples """ |
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_interface_base['data']
for pair in zip(arr[::2], arr[1::2]):
yield pair |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 index is the feature, the second is the vertex within the geometry Parameters vectors: path to an vector source or geo-like python objects raster: ndarray or path to a GDAL raster source If ndarray is passed, the `transform` kwarg is required. layer: int or string, optional If `vectors` is a path to an fiona source, specify the vector layer to use either by name or number. defaults to 0 band: int, optional If `raster` is a GDAL source, the band number to use (counting from 1). defaults to 1. nodata: float, optional If `raster` is a GDAL source, this value overrides any NODATA value specified in the file's metadata. If `None`, the file's metadata's NODATA value (if any) will be used. defaults to `None`. affine: Affine instance required only for ndarrays, otherwise it is read from src interpolate: string 'bilinear' or 'nearest' interpolation property_name: string name of property key if geojson_out geojson_out: boolean generate GeoJSON-like features (default: False) original feature geometry and properties will be retained point query values appended as additional properties. Returns ------- generator of arrays (if ``geojson_out`` is False) generator of geojson features (if ``geojson_out`` is True) """ |
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['geometry'])
vals = []
for x, y in geom_xys(geom):
if interpolate == 'nearest':
r, c = rast.index(x, y)
window = ((int(r), int(r+1)), (int(c), int(c+1)))
src_array = rast.read(window=window, masked=True).array
val = src_array[0, 0]
if val is masked:
vals.append(None)
else:
vals.append(asscalar(val))
elif interpolate == 'bilinear':
window, unitxy = point_window_unitxy(x, y, rast.affine)
src_array = rast.read(window=window, masked=True).array
vals.append(bilinear(src_array, *unitxy))
if len(vals) == 1:
vals = vals[0] # flatten single-element lists
if geojson_out:
if 'properties' not in feat:
feat['properties'] = {}
feat['properties'][property_name] = vals
yield feat
else:
yield vals |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def key_assoc_val(d, func, exclude=None):
"""return the key associated with the value returned by func """ |
vs = list(d.values())
ks = list(d.keys())
key = ks[vs.index(func(vs))]
return key |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.