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 get_name(self, origin=None):
"""Read the next token and interpret it as a DNS name. @raises dns.exception.SyntaxError: @rtype: dns.name.Name object""" |
token = self.get()
if not token.is_identifier():
raise dns.exception.SyntaxError('expecting an identifier')
return dns.name.from_text(token.value, 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 get_eol(self):
"""Read the next token and raise an exception if it isn't EOL or EOF. @raises dns.exception.SyntaxError: @rtype: string """ |
token = self.get()
if not token.is_eol_or_eof():
raise dns.exception.SyntaxError('expected EOL or EOF, got %d "%s"' % (token.ttype, token.value))
return token.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 from_rdata_list(ttl, rdatas):
"""Create an rdataset with the specified TTL, and with the specified list of rdata objects. @rtype: dns.rdataset.Rdataset object """ |
if len(rdatas) == 0:
raise ValueError("rdata list must not be empty")
r = None
for rd in rdatas:
if r is None:
r = Rdataset(rd.rdclass, rd.rdtype)
r.update_ttl(ttl)
first_time = False
r.add(rd)
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 update_ttl(self, ttl):
"""Set the TTL of the rdataset to be the lesser of the set's current TTL or the specified TTL. If the set contains no rdatas, set the TTL to the specified TTL. @param ttl: The TTL @type ttl: int""" |
if len(self) == 0:
self.ttl = ttl
elif ttl < self.ttl:
self.ttl = ttl |
<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, rd, ttl=None):
"""Add the specified rdata to the rdataset. If the optional I{ttl} parameter is supplied, then self.update_ttl(ttl) will be called prior to adding the rdata. @param rd: The rdata @type rd: dns.rdata.Rdata object @param ttl: The TTL @type ttl: int""" |
#
# If we're adding a signature, do some special handling to
# check that the signature covers the same type as the
# other rdatas in this rdataset. If this is the first rdata
# in the set, initialize the covers field.
#
if self.rdclass != rd.rdclass or self.rdtype != rd.rdtype:
raise IncompatibleTypes
if not ttl is None:
self.update_ttl(ttl)
if self.rdtype == dns.rdatatype.RRSIG or \
self.rdtype == dns.rdatatype.SIG:
covers = rd.covers()
if len(self) == 0 and self.covers == dns.rdatatype.NONE:
self.covers = covers
elif self.covers != covers:
raise DifferingCovers
if dns.rdatatype.is_singleton(rd.rdtype) and len(self) > 0:
self.clear()
super(Rdataset, self).add(rd) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, other):
"""Add all rdatas in other to self. @param other: The rdataset from which to update @type other: dns.rdataset.Rdataset object""" |
self.update_ttl(other.ttl)
super(Rdataset, self).update(other) |
<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_text(self, name=None, origin=None, relativize=True, override_rdclass=None, **kw):
"""Convert the rdataset into DNS master file format. @see: L{dns.name.Name.choose_relativity} for more information on how I{origin} and I{relativize} determine the way names are emitted. Any additional keyword arguments are passed on to the rdata to_text() method. @param name: If name is not None, emit a RRs with I{name} as the owner name. @type name: dns.name.Name object @param origin: The origin for relative names, or None. @type origin: dns.name.Name object @param relativize: True if names should names be relativized @type relativize: bool""" |
if not name is None:
name = name.choose_relativity(origin, relativize)
ntext = str(name)
pad = ' '
else:
ntext = ''
pad = ''
s = StringIO.StringIO()
if not override_rdclass is None:
rdclass = override_rdclass
else:
rdclass = self.rdclass
if len(self) == 0:
#
# Empty rdatasets are used for the question section, and in
# some dynamic updates, so we don't need to print out the TTL
# (which is meaningless anyway).
#
print >> s, '%s%s%s %s' % (ntext, pad,
dns.rdataclass.to_text(rdclass),
dns.rdatatype.to_text(self.rdtype))
else:
for rd in self:
print >> s, '%s%s%d %s %s %s' % \
(ntext, pad, self.ttl, dns.rdataclass.to_text(rdclass),
dns.rdatatype.to_text(self.rdtype),
rd.to_text(origin=origin, relativize=relativize, **kw))
#
# We strip off the final \n for the caller's convenience in printing
#
return s.getvalue()[:-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 to_wire(self, name, file, compress=None, origin=None, override_rdclass=None, want_shuffle=True):
"""Convert the rdataset to wire format. @param name: The owner name of the RRset that will be emitted @type name: dns.name.Name object @param file: The file to which the wire format data will be appended @type file: file @param compress: The compression table to use; the default is None. @type compress: dict @param origin: The origin to be appended to any relative names when they are emitted. The default is None. @returns: the number of records emitted @rtype: int """ |
if not override_rdclass is None:
rdclass = override_rdclass
want_shuffle = False
else:
rdclass = self.rdclass
file.seek(0, 2)
if len(self) == 0:
name.to_wire(file, compress, origin)
stuff = struct.pack("!HHIH", self.rdtype, rdclass, 0, 0)
file.write(stuff)
return 1
else:
if want_shuffle:
l = list(self)
random.shuffle(l)
else:
l = self
for rd in l:
name.to_wire(file, compress, origin)
stuff = struct.pack("!HHIH", self.rdtype, rdclass,
self.ttl, 0)
file.write(stuff)
start = file.tell()
rd.to_wire(file, compress, origin)
end = file.tell()
assert end - start < 65536
file.seek(start - 2)
stuff = struct.pack("!H", end - start)
file.write(stuff)
file.seek(0, 2)
return len(self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def match(self, rdclass, rdtype, covers):
"""Returns True if this rdataset matches the specified class, type, and covers""" |
if self.rdclass == rdclass and \
self.rdtype == rdtype and \
self.covers == covers:
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 get_plugin_modules(folders, package='plugins', parentpackage='linkcheck.dummy'):
"""Get plugin modules for given folders.""" |
for folder in folders:
for module in loader.get_folder_modules(folder, parentpackage):
yield module
for module in loader.get_package_modules(package):
yield module |
<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_plugin_classes(modules):
"""Get plugin classes for given modules.""" |
classes = (_ConnectionPlugin, _ContentPlugin, _ParserPlugin)
return loader.get_plugins(modules, classes) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_modules(self, modules, config):
"""Load plugin modules.""" |
for pluginclass in get_plugin_classes(modules):
name = pluginclass.__name__
if name in config["enabledplugins"]:
if issubclass(pluginclass, _ConnectionPlugin):
log.debug(LOG_PLUGIN, "Enable connection plugin %s", name)
self.connection_plugins.append(pluginclass(config[name]))
elif issubclass(pluginclass, _ContentPlugin):
log.debug(LOG_PLUGIN, "Enable content plugin %s", name)
self.content_plugins.append(pluginclass(config[name]))
elif issubclass(pluginclass, _ParserPlugin):
log.debug(LOG_PLUGIN, "Enable parser plugin %s", name)
self.parser_plugins.append(pluginclass(config[name]))
else:
raise ValueError("Invalid plugin class %s" % pluginclass) |
<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_parser_plugins(self, url_data, pagetype):
"""Run parser plugins for given pagetype.""" |
run_plugins(self.parser_plugins, url_data, stop_after_match=True, pagetype=pagetype) |
<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_urls (aggregate):
"""Main check function; checks all configured URLs until interrupted with Ctrl-C. @return: None """ |
try:
aggregate.visit_loginurl()
except Exception as msg:
log.warn(LOG_CHECK, _("Error using login URL: %(msg)s.") % \
dict(msg=msg))
raise
try:
aggregate.logger.start_log_output()
except Exception as msg:
log.error(LOG_CHECK, _("Error starting log output: %(msg)s.") % \
dict(msg=msg))
raise
try:
if not aggregate.urlqueue.empty():
aggregate.start_threads()
check_url(aggregate)
aggregate.finish()
aggregate.end_log_output()
except LinkCheckerInterrupt:
raise
except KeyboardInterrupt:
interrupt(aggregate)
except thread.error:
log.warn(LOG_CHECK,
_("Could not start a new thread. Check that the current user" \
" is allowed to start new threads."))
abort(aggregate)
except Exception:
# Catching "Exception" is intentionally done. This saves the program
# from libraries that raise all kinds of strange exceptions.
console.internal_error()
aggregate.logger.log_internal_error()
abort(aggregate) |
<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 (aggregate):
"""Helper function waiting for URL queue.""" |
while True:
try:
aggregate.urlqueue.join(timeout=30)
break
except urlqueue.Timeout:
# Cleanup threads every 30 seconds
aggregate.remove_stopped_threads()
if not any(aggregate.get_check_threads()):
break |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interrupt (aggregate):
"""Interrupt execution and shutdown, ignoring any subsequent interrupts.""" |
while True:
try:
log.warn(LOG_CHECK,
_("interrupt; waiting for active threads to finish"))
log.warn(LOG_CHECK,
_("another interrupt will exit immediately"))
abort(aggregate)
break
except KeyboardInterrupt:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def abort (aggregate):
"""Helper function to ensure a clean shutdown.""" |
while True:
try:
aggregate.abort()
aggregate.finish()
aggregate.end_log_output(interrupt=True)
break
except KeyboardInterrupt:
log.warn(LOG_CHECK, _("user abort; force shutdown"))
aggregate.end_log_output(interrupt=True)
abort_now() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def abort_now ():
"""Force exit of current process without cleanup.""" |
if os.name == 'posix':
# Unix systems can use signals
import signal
os.kill(os.getpid(), signal.SIGTERM)
time.sleep(1)
os.kill(os.getpid(), signal.SIGKILL)
elif os.name == 'nt':
# NT has os.abort()
os.abort()
else:
# All other systems have os._exit() as best shot.
os._exit(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 get_aggregate (config):
"""Get an aggregator instance with given configuration.""" |
_urlqueue = urlqueue.UrlQueue(max_allowed_urls=config["maxnumurls"])
_robots_txt = robots_txt.RobotsTxt(config["useragent"])
plugin_manager = plugins.PluginManager(config)
result_cache = results.ResultCache()
return aggregator.Aggregate(config, _urlqueue, _robots_txt, plugin_manager,
result_cache) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inet_ntoa(address):
"""Convert a network format IPv6 address into text. @param address: the binary address @type address: string @rtype: string @raises ValueError: the address isn't 16 bytes long """ |
if len(address) != 16:
raise ValueError("IPv6 addresses are 16 bytes long")
hex = address.encode('hex_codec')
chunks = []
i = 0
l = len(hex)
while i < l:
chunk = hex[i : i + 4]
# strip leading zeros. we do this with an re instead of
# with lstrip() because lstrip() didn't support chars until
# python 2.2.2
m = _leading_zero.match(chunk)
if not m is None:
chunk = m.group(1)
chunks.append(chunk)
i += 4
#
# Compress the longest subsequence of 0-value chunks to ::
#
best_start = 0
best_len = 0
start = -1
last_was_zero = False
for i in xrange(8):
if chunks[i] != '0':
if last_was_zero:
end = i
current_len = end - start
if current_len > best_len:
best_start = start
best_len = current_len
last_was_zero = False
elif not last_was_zero:
start = i
last_was_zero = True
if last_was_zero:
end = 8
current_len = end - start
if current_len > best_len:
best_start = start
best_len = current_len
if best_len > 0:
if best_start == 0 and \
(best_len == 6 or
best_len == 5 and chunks[5] == 'ffff'):
# We have an embedded IPv4 address
if best_len == 6:
prefix = '::'
else:
prefix = '::ffff:'
hex = prefix + dns.ipv4.inet_ntoa(address[12:])
else:
hex = ':'.join(chunks[:best_start]) + '::' + \
':'.join(chunks[best_start + best_len:])
else:
hex = ':'.join(chunks)
return hex |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inet_aton(text):
"""Convert a text format IPv6 address into network format. @param text: the textual address @type text: string @rtype: string @raises dns.exception.SyntaxError: the text was not properly formatted """ |
#
# Our aim here is not something fast; we just want something that works.
#
if text == '::':
text = '0::'
#
# Get rid of the icky dot-quad syntax if we have it.
#
m = _v4_ending.match(text)
if not m is None:
text = "%s:%04x:%04x" % (m.group(1),
int(m.group(2)) * 256 + int(m.group(3)),
int(m.group(4)) * 256 + int(m.group(5)))
#
# Try to turn '::<whatever>' into ':<whatever>'; if no match try to
# turn '<whatever>::' into '<whatever>:'
#
m = _colon_colon_start.match(text)
if not m is None:
text = text[1:]
else:
m = _colon_colon_end.match(text)
if not m is None:
text = text[:-1]
#
# Now canonicalize into 8 chunks of 4 hex digits each
#
chunks = text.split(':')
l = len(chunks)
if l > 8:
raise dns.exception.SyntaxError
seen_empty = False
canonical = []
for c in chunks:
if c == '':
if seen_empty:
raise dns.exception.SyntaxError
seen_empty = True
for i in xrange(0, 8 - l + 1):
canonical.append('0000')
else:
lc = len(c)
if lc > 4:
raise dns.exception.SyntaxError
if lc != 4:
c = ('0' * (4 - lc)) + c
canonical.append(c)
if l < 8 and not seen_empty:
raise dns.exception.SyntaxError
text = ''.join(canonical)
#
# Finally we can go to binary.
#
try:
return text.decode('hex_codec')
except TypeError:
raise dns.exception.SyntaxError |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode (text):
"""Encode text with default encoding if its Unicode.""" |
if isinstance(text, unicode):
return text.encode(i18n.default_encoding, 'ignore')
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 print_locale_info (out=stderr):
"""Print locale info.""" |
for key in ("LANGUAGE", "LC_ALL", "LC_CTYPE", "LANG"):
print_env_info(key, out=out)
print(_("Default locale:"), i18n.get_locale(), file=out) |
<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, checked, in_progress, queue, duration, num_urls):
"""Write status message to file descriptor.""" |
msg = _n("%2d thread active", "%2d threads active", in_progress) % \
in_progress
self.write(u"%s, " % msg)
msg = _n("%5d link queued", "%5d links queued", queue) % queue
self.write(u"%s, " % msg)
msg = _n("%4d link", "%4d links", checked) % checked
self.write(u"%s" % msg)
msg = _n("%3d URL", "%3d URLs", num_urls) % num_urls
self.write(u" in %s checked, " % msg)
msg = _("runtime %s") % strformat.strduration_long(duration)
self.writeln(msg)
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 writeln (self, msg):
"""Write status message and line break to file descriptor.""" |
self.fd.write(u"%s%s" % (msg, unicode(os.linesep))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deprecated (func):
"""A decorator which can be used to mark functions as deprecated. It emits a warning when the function is called.""" |
def newfunc (*args, **kwargs):
"""Print deprecated warning and execute original function."""
warnings.warn("Call to deprecated function %s." % func.__name__,
category=DeprecationWarning)
return func(*args, **kwargs)
return update_func_meta(newfunc, func) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def synchronize (lock, func, log_duration_secs=0):
"""Return synchronized function acquiring the given lock.""" |
def newfunc (*args, **kwargs):
"""Execute function synchronized."""
t = time.time()
with lock:
duration = time.time() - t
if duration > log_duration_secs > 0:
print("WARN:", func.__name__, "locking took %0.2f seconds" % duration, file=sys.stderr)
return func(*args, **kwargs)
return update_func_meta(newfunc, func) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def notimplemented (func):
"""Raises a NotImplementedError if the function is called.""" |
def newfunc (*args, **kwargs):
"""Raise NotImplementedError"""
co = func.func_code
attrs = (co.co_name, co.co_filename, co.co_firstlineno)
raise NotImplementedError("function %s at %s:%d is not implemented" % attrs)
return update_func_meta(newfunc, func) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def timeit (func, log, limit):
"""Print execution time of the function. For quick'n'dirty profiling.""" |
def newfunc (*args, **kwargs):
"""Execute function and print execution time."""
t = time.time()
res = func(*args, **kwargs)
duration = time.time() - t
if duration > limit:
print(func.__name__, "took %0.2f seconds" % duration, file=log)
print(args, file=log)
print(kwargs, file=log)
return res
return update_func_meta(newfunc, func) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def timed (log=sys.stderr, limit=2.0):
"""Decorator to run a function with timing info.""" |
return lambda func: timeit(func, log, limit) |
<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 the text form of a TTL to an integer. The BIND 8 units syntax for TTLs (e.g. '1w6d4h3m10s') is supported. @param text: the textual TTL @type text: string @raises dns.ttl.BadTTL: the TTL is not well-formed @rtype: int """ |
if text.isdigit():
total = long(text)
else:
if not text[0].isdigit():
raise BadTTL
total = 0L
current = 0L
for c in text:
if c.isdigit():
current *= 10
current += long(c)
else:
c = c.lower()
if c == 'w':
total += current * 604800L
elif c == 'd':
total += current * 86400L
elif c == 'h':
total += current * 3600L
elif c == 'm':
total += current * 60L
elif c == 's':
total += current
else:
raise BadTTL("unknown unit '%s'" % c)
current = 0
if not current == 0:
raise BadTTL("trailing integer")
if total < 0L or total > 2147483647L:
raise BadTTL("TTL should be between 0 and 2^31 - 1 (inclusive)")
return total |
<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 (self):
"""Handle keyboard interrupt and other errors.""" |
try:
self.run_checked()
except KeyboardInterrupt:
thread.interrupt_main()
except Exception:
self.internal_error() |
<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(self, url_data):
"""Parse XML URL data.""" |
self.url_data = url_data
self.loc = False
self.url = u""
data = url_data.get_content()
isfinal = True
try:
self.parser.Parse(data, isfinal)
except ExpatError as expaterr:
self.url_data.add_warning(expaterr.message,tag=WARN_XML_PARSE_ERROR) |
<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, name, attrs):
"""Set tag status for start element.""" |
self.in_tag = (name == self.tag)
self.url = 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 add_url(self):
"""Add non-empty URLs to the queue.""" |
if self.url:
self.url_data.add_url(self.url, line=self.parser.CurrentLineNumber,
column=self.parser.CurrentColumnNumber)
self.url = 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 get_shell_folder (name):
"""Get Windows Shell Folder locations from the registry.""" |
try:
import _winreg as winreg
except ImportError:
import winreg
lm = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER)
try:
key = winreg.OpenKey(lm, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
try:
return winreg.QueryValueEx(key, name)[0]
finally:
key.Close()
finally:
lm.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 on_connect(client):
""" Sample on_connect function. Handles new connections. """ |
print "++ Opened connection to %s" % client.addrport()
broadcast('%s joins the conversation.\n' % client.addrport() )
CLIENT_LIST.append(client)
client.send("Welcome to the Chat Server, %s.\n" % client.addrport() ) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_disconnect(client):
""" Sample on_disconnect function. Handles lost connections. """ |
print "-- Lost connection to %s" % client.addrport()
CLIENT_LIST.remove(client)
broadcast('%s leaves the conversation.\n' % client.addrport() ) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def kick_idle():
""" Looks for idle clients and disconnects them by setting active to False. """ |
## Who hasn't been typing?
for client in CLIENT_LIST:
if client.idle() > IDLE_TIMEOUT:
print('-- Kicking idle lobby client from %s' % client.addrport())
client.active = 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 chat(client):
""" Echo whatever client types to everyone. """ |
global SERVER_RUN
msg = client.get_command()
print '%s says, "%s"' % (client.addrport(), msg)
for guest in CLIENT_LIST:
if guest != client:
guest.send('%s says, %s\n' % (client.addrport(), msg))
else:
guest.send('You say, %s\n' % msg)
cmd = msg.lower()
## bye = disconnect
if cmd == 'bye':
client.active = False
## shutdown == stop the server
elif cmd == 'shutdown':
SERVER_RUN = 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 get_netloc(self):
"""Determine scheme, host and port for this connection taking proxy data into account. @return: tuple (scheme, host, port) @rtype: tuple(string, string, int) """ |
if self.proxy:
scheme = self.proxytype
host = self.proxyhost
port = self.proxyport
else:
scheme = self.scheme
host = self.host
port = self.port
return (scheme, host, port) |
<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(wire, keyname, secret, now, request_mac, tsig_start, tsig_rdata, tsig_rdlen, ctx=None, multi=False, first=True):
"""Validate the specified TSIG rdata against the other input parameters. @raises FormError: The TSIG is badly formed. @raises BadTime: There is too much time skew between the client and the server. @raises BadSignature: The TSIG signature did not validate @rtype: hmac.HMAC object""" |
(adcount,) = struct.unpack("!H", wire[10:12])
if adcount == 0:
raise dns.exception.FormError
adcount -= 1
new_wire = wire[0:10] + struct.pack("!H", adcount) + wire[12:tsig_start]
current = tsig_rdata
(aname, used) = dns.name.from_wire(wire, current)
current = current + used
(upper_time, lower_time, fudge, mac_size) = \
struct.unpack("!HIHH", wire[current:current + 10])
time = ((upper_time + 0L) << 32) + (lower_time + 0L)
current += 10
mac = wire[current:current + mac_size]
current += mac_size
(original_id, error, other_size) = \
struct.unpack("!HHH", wire[current:current + 6])
current += 6
other_data = wire[current:current + other_size]
current += other_size
if current != tsig_rdata + tsig_rdlen:
raise dns.exception.FormError
if error != 0:
if error == BADSIG:
raise PeerBadSignature
elif error == BADKEY:
raise PeerBadKey
elif error == BADTIME:
raise PeerBadTime
elif error == BADTRUNC:
raise PeerBadTruncation
else:
raise PeerError('unknown TSIG error code %d' % error)
time_low = time - fudge
time_high = time + fudge
if now < time_low or now > time_high:
raise BadTime
(junk, our_mac, ctx) = sign(new_wire, keyname, secret, time, fudge,
original_id, error, other_data,
request_mac, ctx, multi, first, aname)
if (our_mac != mac):
raise BadSignature
return ctx |
<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_algorithm(algorithm):
"""Returns the wire format string and the hash module to use for the specified TSIG algorithm @rtype: (string, hash constructor) @raises NotImplementedError: I{algorithm} is not supported """ |
global _hashes
if _hashes is None:
_setup_hashes()
if isinstance(algorithm, (str, unicode)):
algorithm = dns.name.from_text(algorithm)
if sys.hexversion < 0x02050200 and \
(algorithm == HMAC_SHA384 or algorithm == HMAC_SHA512):
raise NotImplementedError("TSIG algorithm " + str(algorithm) +
" requires Python 2.5.2 or later")
try:
return (algorithm.to_digestable(), _hashes[algorithm])
except KeyError:
raise NotImplementedError("TSIG algorithm " + str(algorithm) +
" is not supported") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inet_pton(family, text):
"""Convert the textual form of a network address into its binary form. @param family: the address family @type family: int @param text: the textual address @type text: string @raises NotImplementedError: the address family specified is not implemented. @rtype: string """ |
if family == AF_INET:
return dns.ipv4.inet_aton(text)
elif family == AF_INET6:
return dns.ipv6.inet_aton(text)
else:
raise NotImplementedError |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inet_ntop(family, address):
"""Convert the binary form of a network address into its textual form. @param family: the address family @type family: int @param address: the binary address @type address: string @raises NotImplementedError: the address family specified is not implemented. @rtype: string """ |
if family == AF_INET:
return dns.ipv4.inet_ntoa(address)
elif family == AF_INET6:
return dns.ipv6.inet_ntoa(address)
else:
raise NotImplementedError |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def af_for_address(text):
"""Determine the address family of a textual-form network address. @param text: the textual address @type text: string @raises ValueError: the address family cannot be determined from the input. @rtype: int """ |
try:
junk = dns.ipv4.inet_aton(text)
return AF_INET
except Exception:
try:
junk = dns.ipv6.inet_aton(text)
return AF_INET6
except Exception:
raise ValueError |
<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_multicast(text):
"""Is the textual-form network address a multicast address? @param text: the textual address @raises ValueError: the address family cannot be determined from the input. @rtype: bool """ |
try:
first = ord(dns.ipv4.inet_aton(text)[0])
return (first >= 224 and first <= 239)
except Exception:
try:
first = ord(dns.ipv6.inet_aton(text)[0])
return (first == 255)
except Exception:
raise ValueError |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _stack_format (stack):
"""Format a stack trace to a message. @return: formatted stack message @rtype: string """ |
s = StringIO()
s.write('Traceback:')
s.write(os.linesep)
for frame, fname, lineno, method, lines, dummy in reversed(stack):
s.write(' File %r, line %d, in %s' % (fname, lineno, method))
s.write(os.linesep)
s.write(' %s' % lines[0].lstrip())
if PRINT_LOCALVARS:
for key, value in frame.f_locals.items():
s.write(" %s = " % key)
# be careful not to cause a new error in the error output
try:
s.write(repr(value))
s.write(os.linesep)
except Exception:
s.write("error in repr() call%s" % os.linesep)
return s.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 debug (logname, msg, *args, **kwargs):
"""Log a debug message. return: None """ |
log = logging.getLogger(logname)
if log.isEnabledFor(logging.DEBUG):
_log(log.debug, msg, args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def info (logname, msg, *args, **kwargs):
"""Log an informational message. return: None """ |
log = logging.getLogger(logname)
if log.isEnabledFor(logging.INFO):
_log(log.info, msg, args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def warn (logname, msg, *args, **kwargs):
"""Log a warning. return: None """ |
log = logging.getLogger(logname)
if log.isEnabledFor(logging.WARN):
_log(log.warn, msg, args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def error (logname, msg, *args, **kwargs):
"""Log an error. return: None """ |
log = logging.getLogger(logname)
if log.isEnabledFor(logging.ERROR):
_log(log.error, msg, args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def critical (logname, msg, *args, **kwargs):
"""Log a critical error. return: None """ |
log = logging.getLogger(logname)
if log.isEnabledFor(logging.CRITICAL):
_log(log.critical, msg, args, **kwargs) |
<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_files (dirname):
"""Get iterator of entries in directory. Only allows regular files and directories, no symlinks.""" |
for entry in os.listdir(dirname):
fullentry = os.path.join(dirname, entry)
if os.path.islink(fullentry):
continue
if os.path.isfile(fullentry):
yield entry
elif os.path.isdir(fullentry):
yield entry+"/" |
<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_nt_filename (path):
"""Return case sensitive filename for NT path.""" |
unc, rest = os.path.splitunc(path)
head, tail = os.path.split(rest)
if not tail:
return path
for fname in os.listdir(unc+head):
if fname.lower() == tail.lower():
return os.path.join(get_nt_filename(unc+head), fname)
log.error(LOG_CHECK, "could not find %r in %r", tail, head)
return path |
<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_os_filename (path):
"""Return filesystem path for given URL path.""" |
if os.name == 'nt':
path = prepare_urlpath_for_nt(path)
res = urllib.url2pathname(fileutil.pathencode(path))
if os.name == 'nt' and res.endswith(':') and len(res) == 2:
# Work around http://bugs.python.org/issue11474
res += os.sep
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 is_absolute_path (path):
"""Check if given path is absolute. On Windows absolute paths start with a drive letter. On all other systems absolute paths start with a slash.""" |
if os.name == 'nt':
if re.search(r"^[a-zA-Z]:", path):
return True
path = path.replace("\\", "/")
return path.startswith("/") |
<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 the scheme.""" |
super(FileUrl, self).init(base_ref, base_url, parent_url,
recursion_level, aggregate, line, column, page, name, url_encoding, extern)
self.scheme = u'file' |
<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_size_info (self):
"""Get size of file content and modification time from filename path.""" |
if self.is_directory():
# Directory size always differs from the customer index.html
# that is generated. So return without calculating any size.
return
filename = self.get_os_filename()
self.size = fileutil.get_size(filename)
self.modified = datetime.utcfromtimestamp(fileutil.get_mtime(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 check_connection (self):
""" Try to open the local file. Under NT systems the case sensitivity is checked. """ |
if (self.parent_url is not None and
not self.parent_url.startswith(u"file:")):
msg = _("local files are only checked without parent URL or when the parent URL is also a file")
raise LinkCheckerError(msg)
if self.is_directory():
self.set_result(_("directory"))
else:
url = fileutil.pathencode(self.url)
self.url_connection = urlopen(url)
self.check_case_sensitivity() |
<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_case_sensitivity (self):
""" Check if url and windows path name match cases else there might be problems when copying such files on web servers that are case sensitive. """ |
if os.name != 'nt':
return
path = self.get_os_filename()
realpath = get_nt_filename(path)
if path != realpath:
self.add_warning(_("The URL path %(path)r is not the same as the "
"system path %(realpath)r. You should always use "
"the system path in URLs.") % \
{"path": path, "realpath": realpath},
tag=WARN_FILE_SYSTEM_PATH) |
<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 file content, or in case of directories a dummy HTML file with links to the files.""" |
if self.is_directory():
data = get_index_html(get_files(self.get_os_filename()))
if isinstance(data, unicode):
data = data.encode("iso8859-1", "ignore")
else:
data = super(FileUrl, self).read_content()
return 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 is_directory (self):
""" Check if file is a directory. @return: True iff file is a directory @rtype: bool """ |
filename = self.get_os_filename()
return os.path.isdir(filename) and not os.path.islink(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 set_content_type (self):
"""Return URL content type, or an empty string if content type could not be found.""" |
if self.url:
self.content_type = mimeutil.guess_mimetype(self.url, read=self.get_content)
else:
self.content_type = 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 add_url (self, url, line=0, column=0, page=0, name=u"", base=None):
"""If a local webroot directory is configured, replace absolute URLs with it. After that queue the URL data for checking.""" |
webroot = self.aggregate.config["localwebroot"]
if webroot and url and url.startswith(u"/"):
url = webroot + url[1:]
log.debug(LOG_CHECK, "Applied local webroot `%s' to `%s'.", webroot, url)
super(FileUrl, self).add_url(url, line=line, column=column, page=page, name=name, base=base) |
<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_request_session(config, cookies):
"""Create a new request session.""" |
session = requests.Session()
if cookies:
session.cookies = cookies
session.max_redirects = config["maxhttpredirects"]
session.headers.update({
"User-Agent": config["useragent"],
})
if config["cookiefile"]:
for cookie in cookies.from_file(config["cookiefile"]):
session.cookies = requests.cookies.merge_cookies(session.cookies, cookie)
return session |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_loginurl(self):
"""Check for a login URL and visit it.""" |
url = self.config["loginurl"]
if not url:
return
user, password = self.config.get_user_password(url)
session = requests.Session()
# XXX user-agent header
# XXX timeout
response = session.get(url)
cgiuser = self.config["loginuserfield"]
cgipassword = self.config["loginpasswordfield"]
form = formsearch.search_form(response.content, cgiuser, cgipassword,
encoding=response.encoding)
form.data[cgiuser] = user
form.data[cgipassword] = password
for key, value in self.config["loginextrafields"].items():
form.data[key] = value
formurl = urlparse.urljoin(url, form.url)
response = session.post(formurl, data=form.data)
self.cookies = session.cookies
if len(self.cookies) == 0:
raise LinkCheckerError("No cookies set by login URL %s" % 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 start_threads (self):
"""Spawn threads for URL checking and status printing.""" |
if self.config["status"]:
t = status.Status(self, self.config["status_wait_seconds"])
t.start()
self.threads.append(t)
if self.config["maxrunseconds"]:
t = interrupt.Interrupt(self.config["maxrunseconds"])
t.start()
self.threads.append(t)
num = self.config["threads"]
if num > 0:
for dummy in range(num):
t = checker.Checker(self.urlqueue, self.logger, self.add_request_session)
self.threads.append(t)
t.start()
else:
self.request_sessions[thread.get_ident()] = new_request_session(self.config, self.cookies)
checker.check_urls(self.urlqueue, self.logger) |
<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_request_session(self):
"""Add a request session for current thread.""" |
session = new_request_session(self.config, self.cookies)
self.request_sessions[thread.get_ident()] = session |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wait_for_host(self, host):
"""Throttle requests to one host.""" |
t = time.time()
if host in self.times:
due_time = self.times[host]
if due_time > t:
wait = due_time - t
time.sleep(wait)
t = time.time()
wait_time = random.uniform(self.wait_time_min, self.wait_time_max)
self.times[host] = t + wait_time |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_active_threads (self):
"""Log all currently active threads.""" |
debug = log.is_debug(LOG_CHECK)
if debug:
first = True
for name in self.get_check_threads():
if first:
log.info(LOG_CHECK, _("These URLs are still active:"))
first = False
log.info(LOG_CHECK, name[12:])
args = dict(
num=len([x for x in self.threads if x.getName().startswith("CheckThread-")]),
timeout=strformat.strduration_long(self.config["aborttimeout"]),
)
log.info(LOG_CHECK, _("%(num)d URLs are still active. After a timeout of %(timeout)s the active URLs will stop.") % args) |
<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_check_threads(self):
"""Return iterator of checker threads.""" |
for t in self.threads:
name = t.getName()
if name.startswith("CheckThread-"):
yield 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 abort (self):
"""Print still-active URLs and empty the URL queue.""" |
self.print_active_threads()
self.cancel()
timeout = self.config["aborttimeout"]
try:
self.urlqueue.join(timeout=timeout)
except urlqueue.Timeout:
log.warn(LOG_CHECK, "Abort timed out after %d seconds, stopping application." % timeout)
raise KeyboardInterrupt() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_stopped_threads (self):
"""Remove the stopped threads from the internal thread list.""" |
self.threads = [t for t in self.threads if t.is_alive()] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def finish (self):
"""Wait for checker threads to finish.""" |
if not self.urlqueue.empty():
# This happens when all checker threads died.
self.cancel()
for t in self.threads:
t.stop() |
<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_log_output(self, **kwargs):
"""Print ending output to log.""" |
kwargs.update(dict(
downloaded_bytes=self.downloaded_bytes,
num_urls = len(self.result_cache),
))
self.logger.end_log_output(**kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def x509_to_dict(x509):
"""Parse a x509 pyopenssl object to a dictionary with keys subject, subjectAltName and optional notAfter. """ |
from requests.packages.urllib3.contrib.pyopenssl import get_subj_alt_name
res = {
'subject': (
(('commonName', x509.get_subject().CN),),
),
'subjectAltName': [
('DNS', value)
for value in get_subj_alt_name(x509)
]
}
notAfter = x509.get_notAfter()
if notAfter is not None:
parsedtime = asn1_generaltime_to_seconds(notAfter)
if parsedtime is not None:
res['notAfter'] = parsedtime.strftime('%b %d %H:%M:%S %Y')
if parsedtime.tzinfo is None:
res['notAfter'] += ' GMT'
else:
# give up parsing, just set the string
res['notAfter'] = notAfter
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 asn1_generaltime_to_seconds(timestr):
"""The given string has one of the following formats YYYYMMDDhhmmssZ YYYYMMDDhhmmss+hhmm YYYYMMDDhhmmss-hhmm @return: a datetime object or None on error """ |
res = None
timeformat = "%Y%m%d%H%M%S"
try:
res = datetime.strptime(timestr, timeformat + 'Z')
except ValueError:
try:
res = datetime.strptime(timestr, timeformat + '%z')
except ValueError:
pass
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 has_header_value (headers, name, value):
""" Look in headers for a specific header name and value. Both name and value are case insensitive. @return: True if header name and value are found @rtype: bool """ |
name = name.lower()
value = value.lower()
for hname, hvalue in headers:
if hname.lower()==name and hvalue.lower()==value:
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 http_persistent (response):
""" See if the HTTP connection can be kept open according the the header values found in the response object. @param response: response instance @type response: httplib.HTTPResponse @return: True if connection is persistent @rtype: bool """ |
headers = response.getheaders()
if response.version == 11:
return not has_header_value(headers, 'Connection', 'Close')
return has_header_value(headers, "Connection", "Keep-Alive") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def http_keepalive (headers):
""" Get HTTP keepalive value, either from the Keep-Alive header or a default value. @param headers: HTTP headers @type headers: dict @return: keepalive in seconds @rtype: int """ |
keepalive = headers.get("Keep-Alive")
if keepalive is not None:
try:
keepalive = int(keepalive[8:].strip())
except (ValueError, OverflowError):
keepalive = DEFAULT_KEEPALIVE
else:
keepalive = DEFAULT_KEEPALIVE
return keepalive |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_plugins(folders, exit_code=0):
"""Print available plugins and exit.""" |
modules = plugins.get_plugin_modules(folders)
pluginclasses = sorted(plugins.get_plugin_classes(modules), key=lambda x: x.__name__)
for pluginclass in pluginclasses:
print(pluginclass.__name__)
doc = strformat.wrap(pluginclass.__doc__, 80)
print(strformat.indent(doc))
print()
sys.exit(exit_code) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_usage (msg, exit_code=2):
"""Print a program msg text to stderr and exit.""" |
program = sys.argv[0]
print(_("Error: %(msg)s") % {"msg": msg}, file=console.stderr)
print(_("Execute '%(program)s -h' for help") % {"program": program}, file=console.stderr)
sys.exit(exit_code) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def aggregate_url (aggregate, url, err_exit_code=2):
"""Append given commandline URL to input queue.""" |
get_url_from = checker.get_url_from
url = checker.guess_url(url)
url_data = get_url_from(url, 0, aggregate, extern=(0, 0))
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 print_help(self, file=sys.stdout):
"""Print a help message to stdout.""" |
msg = console.encode(self.format_help())
if fileutil.is_tty(file):
strformat.paginate(msg)
else:
print(msg, file=file) |
<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(wire, keyring=None, request_mac='', xfr=False, origin=None, tsig_ctx = None, multi = False, first = True, question_only = False, one_rr_per_rrset = False):
"""Convert a DNS wire format message into a message object. @param keyring: The keyring to use if the message is signed. @type keyring: dict @param request_mac: If the message is a response to a TSIG-signed request, I{request_mac} should be set to the MAC of that request. @type request_mac: string @param xfr: Is this message part of a zone transfer? @type xfr: bool @param origin: If the message is part of a zone transfer, I{origin} should be the origin name of the zone. @type origin: dns.name.Name object @param tsig_ctx: The ongoing TSIG context, used when validating zone transfers. @type tsig_ctx: hmac.HMAC object @param multi: Is this message part of a multiple message sequence? @type multi: bool @param first: Is this message standalone, or the first of a multi message sequence? @type first: bool @param question_only: Read only up to the end of the question section? @type question_only: bool @param one_rr_per_rrset: Put each RR into its own RRset @type one_rr_per_rrset: bool @raises ShortHeader: The message is less than 12 octets long. @raises TrailingJunk: There were octets in the message past the end of the proper DNS message. @raises BadEDNS: An OPT record was in the wrong section, or occurred more than once. @raises BadTSIG: A TSIG record was not the last record of the additional data section. @rtype: dns.message.Message object""" |
m = Message(id=0)
m.keyring = keyring
m.request_mac = request_mac
m.xfr = xfr
m.origin = origin
m.tsig_ctx = tsig_ctx
m.multi = multi
m.first = first
reader = _WireReader(wire, m, question_only, one_rr_per_rrset)
reader.read()
return m |
<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 the text format message into a message object. @param text: The text format message. @type text: string @raises UnknownHeaderField: @raises dns.exception.SyntaxError: @rtype: dns.message.Message object""" |
# 'text' can also be a file, but we don't publish that fact
# since it's an implementation detail. The official file
# interface is from_file().
m = Message()
reader = _TextReader(text, m)
reader.read()
return m |
<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_file(f):
"""Read the next text format message from the specified file. @param f: file or string. If I{f} is a string, it is treated as the name of a file to open. @raises UnknownHeaderField: @raises dns.exception.SyntaxError: @rtype: dns.message.Message object""" |
if sys.hexversion >= 0x02030000:
# allow Unicode filenames; turn on universal newline support
str_type = basestring
opts = 'rU'
else:
str_type = str
opts = 'r'
if isinstance(f, str_type):
f = file(f, opts)
want_close = True
else:
want_close = False
try:
m = from_text(f)
finally:
if want_close:
f.close()
return m |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_query(qname, rdtype, rdclass = dns.rdataclass.IN, use_edns=None, want_dnssec=False):
"""Make a query message. The query name, type, and class may all be specified either as objects of the appropriate type, or as strings. The query will have a randomly choosen query id, and its DNS flags will be set to dns.flags.RD. @param qname: The query name. @type qname: dns.name.Name object or string @param rdtype: The desired rdata type. @type rdtype: int @param rdclass: The desired rdata class; the default is class IN. @type rdclass: int @param use_edns: The EDNS level to use; the default is None (no EDNS). See the description of dns.message.Message.use_edns() for the possible values for use_edns and their meanings. @type use_edns: int or bool or None @param want_dnssec: Should the query indicate that DNSSEC is desired? @type want_dnssec: bool @rtype: dns.message.Message object""" |
if isinstance(qname, (str, unicode)):
qname = dns.name.from_text(qname)
if isinstance(rdtype, (str, unicode)):
rdtype = dns.rdatatype.from_text(rdtype)
if isinstance(rdclass, (str, unicode)):
rdclass = dns.rdataclass.from_text(rdclass)
m = Message()
m.flags |= dns.flags.RD
m.find_rrset(m.question, qname, rdclass, rdtype, create=True,
force_unique=True)
m.use_edns(use_edns)
m.want_dnssec(want_dnssec)
return m |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_response(query, recursion_available=False, our_payload=8192):
"""Make a message which is a response for the specified query. The message returned is really a response skeleton; it has all of the infrastructure required of a response, but none of the content. The response's question section is a shallow copy of the query's question section, so the query's question RRsets should not be changed. @param query: the query to respond to @type query: dns.message.Message object @param recursion_available: should RA be set in the response? @type recursion_available: bool @param our_payload: payload size to advertise in EDNS responses; default is 8192. @type our_payload: int @rtype: dns.message.Message object""" |
if query.flags & dns.flags.QR:
raise dns.exception.FormError('specified query message is not a query')
response = dns.message.Message(query.id)
response.flags = dns.flags.QR | (query.flags & dns.flags.RD)
if recursion_available:
response.flags |= dns.flags.RA
response.set_opcode(query.opcode())
response.question = list(query.question)
if query.edns >= 0:
response.use_edns(0, 0, our_payload, query.payload)
if not query.keyname is None:
response.keyname = query.keyname
response.keyring = query.keyring
response.request_mac = query.mac
return response |
<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_text(self, origin=None, relativize=True, **kw):
"""Convert the message to text. The I{origin}, I{relativize}, and any other keyword arguments are passed to the rrset to_wire() method. @rtype: string """ |
s = cStringIO.StringIO()
print >> s, 'id %d' % self.id
print >> s, 'opcode %s' % \
dns.opcode.to_text(dns.opcode.from_flags(self.flags))
rc = dns.rcode.from_flags(self.flags, self.ednsflags)
print >> s, 'rcode %s' % dns.rcode.to_text(rc)
print >> s, 'flags %s' % dns.flags.to_text(self.flags)
if self.edns >= 0:
print >> s, 'edns %s' % self.edns
if self.ednsflags != 0:
print >> s, 'eflags %s' % \
dns.flags.edns_to_text(self.ednsflags)
print >> s, 'payload', self.payload
is_update = dns.opcode.is_update(self.flags)
if is_update:
print >> s, ';ZONE'
else:
print >> s, ';QUESTION'
for rrset in self.question:
print >> s, rrset.to_text(origin, relativize, **kw)
if is_update:
print >> s, ';PREREQ'
else:
print >> s, ';ANSWER'
for rrset in self.answer:
print >> s, rrset.to_text(origin, relativize, **kw)
if is_update:
print >> s, ';UPDATE'
else:
print >> s, ';AUTHORITY'
for rrset in self.authority:
print >> s, rrset.to_text(origin, relativize, **kw)
print >> s, ';ADDITIONAL'
for rrset in self.additional:
print >> s, rrset.to_text(origin, relativize, **kw)
#
# We strip off the final \n so the caller can print the result without
# doing weird things to get around eccentricities in Python print
# formatting
#
return s.getvalue()[:-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 is_response(self, other):
"""Is other a response to self? @rtype: bool""" |
if other.flags & dns.flags.QR == 0 or \
self.id != other.id or \
dns.opcode.from_flags(self.flags) != \
dns.opcode.from_flags(other.flags):
return False
if dns.rcode.from_flags(other.flags, other.ednsflags) != \
dns.rcode.NOERROR:
return True
if dns.opcode.is_update(self.flags):
return True
for n in self.question:
if n not in other.question:
return False
for n in other.question:
if n not in self.question:
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 find_rrset(self, section, name, rdclass, rdtype, covers=dns.rdatatype.NONE, deleting=None, create=False, force_unique=False):
"""Find the RRset with the given attributes in the specified section. @param section: the section of the message to look in, e.g. self.answer. @type section: list of dns.rrset.RRset objects @param name: the name of the RRset @type name: dns.name.Name object @param rdclass: the class of the RRset @type rdclass: int @param rdtype: the type of the RRset @type rdtype: int @param covers: the covers value of the RRset @type covers: int @param deleting: the deleting value of the RRset @type deleting: int @param create: If True, create the RRset if it is not found. The created RRset is appended to I{section}. @type create: bool @param force_unique: If True and create is also True, create a new RRset regardless of whether a matching RRset exists already. @type force_unique: bool @raises KeyError: the RRset was not found and create was False @rtype: dns.rrset.RRset object""" |
key = (self.section_number(section),
name, rdclass, rdtype, covers, deleting)
if not force_unique:
if not self.index is None:
rrset = self.index.get(key)
if not rrset is None:
return rrset
else:
for rrset in section:
if rrset.match(name, rdclass, rdtype, covers, deleting):
return rrset
if not create:
raise KeyError
rrset = dns.rrset.RRset(name, rdclass, rdtype, covers, deleting)
section.append(rrset)
if not self.index is None:
self.index[key] = rrset
return rrset |
<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_rrset(self, section, name, rdclass, rdtype, covers=dns.rdatatype.NONE, deleting=None, create=False, force_unique=False):
"""Get the RRset with the given attributes in the specified section. If the RRset is not found, None is returned. @param section: the section of the message to look in, e.g. self.answer. @type section: list of dns.rrset.RRset objects @param name: the name of the RRset @type name: dns.name.Name object @param rdclass: the class of the RRset @type rdclass: int @param rdtype: the type of the RRset @type rdtype: int @param covers: the covers value of the RRset @type covers: int @param deleting: the deleting value of the RRset @type deleting: int @param create: If True, create the RRset if it is not found. The created RRset is appended to I{section}. @type create: bool @param force_unique: If True and create is also True, create a new RRset regardless of whether a matching RRset exists already. @type force_unique: bool @rtype: dns.rrset.RRset object or None""" |
try:
rrset = self.find_rrset(section, name, rdclass, rdtype, covers,
deleting, create, force_unique)
except KeyError:
rrset = None
return rrset |
<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(self, origin=None, max_size=0, **kw):
"""Return a string containing the message in DNS compressed wire format. Additional keyword arguments are passed to the rrset to_wire() method. @param origin: The origin to be appended to any relative names. @type origin: dns.name.Name object @param max_size: The maximum size of the wire format output; default is 0, which means 'the message's request payload, if nonzero, or 65536'. @type max_size: int @raises dns.exception.TooBig: max_size was exceeded @rtype: string """ |
if max_size == 0:
if self.request_payload != 0:
max_size = self.request_payload
else:
max_size = 65535
if max_size < 512:
max_size = 512
elif max_size > 65535:
max_size = 65535
r = dns.renderer.Renderer(self.id, self.flags, max_size, origin)
for rrset in self.question:
r.add_question(rrset.name, rrset.rdtype, rrset.rdclass)
for rrset in self.answer:
r.add_rrset(dns.renderer.ANSWER, rrset, **kw)
for rrset in self.authority:
r.add_rrset(dns.renderer.AUTHORITY, rrset, **kw)
if self.edns >= 0:
r.add_edns(self.edns, self.ednsflags, self.payload, self.options)
for rrset in self.additional:
r.add_rrset(dns.renderer.ADDITIONAL, rrset, **kw)
r.write_header()
if not self.keyname is None:
r.add_tsig(self.keyname, self.keyring[self.keyname],
self.fudge, self.original_id, self.tsig_error,
self.other_data, self.request_mac,
self.keyalgorithm)
self.mac = r.mac
return r.get_wire() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def use_tsig(self, keyring, keyname=None, fudge=300, original_id=None, tsig_error=0, other_data='', algorithm=dns.tsig.default_algorithm):
"""When sending, a TSIG signature using the specified keyring and keyname should be added. @param keyring: The TSIG keyring to use; defaults to None. @type keyring: dict @param keyname: The name of the TSIG key to use; defaults to None. The key must be defined in the keyring. If a keyring is specified but a keyname is not, then the key used will be the first key in the keyring. Note that the order of keys in a dictionary is not defined, so applications should supply a keyname when a keyring is used, unless they know the keyring contains only one key. @type keyname: dns.name.Name or string @param fudge: TSIG time fudge; default is 300 seconds. @type fudge: int @param original_id: TSIG original id; defaults to the message's id @type original_id: int @param tsig_error: TSIG error code; default is 0. @type tsig_error: int @param other_data: TSIG other data. @type other_data: string @param algorithm: The TSIG algorithm to use; defaults to dns.tsig.default_algorithm """ |
self.keyring = keyring
if keyname is None:
self.keyname = self.keyring.keys()[0]
else:
if isinstance(keyname, (str, unicode)):
keyname = dns.name.from_text(keyname)
self.keyname = keyname
self.keyalgorithm = algorithm
self.fudge = fudge
if original_id is None:
self.original_id = self.id
else:
self.original_id = original_id
self.tsig_error = tsig_error
self.other_data = other_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 use_edns(self, edns=0, ednsflags=0, payload=1280, request_payload=None, options=None):
"""Configure EDNS behavior. @param edns: The EDNS level to use. Specifying None, False, or -1 means 'do not use EDNS', and in this case the other parameters are ignored. Specifying True is equivalent to specifying 0, i.e. 'use EDNS0'. @type edns: int or bool or None @param ednsflags: EDNS flag values. @type ednsflags: int @param payload: The EDNS sender's payload field, which is the maximum size of UDP datagram the sender can handle. @type payload: int @param request_payload: The EDNS payload size to use when sending this message. If not specified, defaults to the value of payload. @type request_payload: int or None @param options: The EDNS options @type options: None or list of dns.edns.Option objects @see: RFC 2671 """ |
if edns is None or edns is False:
edns = -1
if edns is True:
edns = 0
if request_payload is None:
request_payload = payload
if edns < 0:
ednsflags = 0
payload = 0
request_payload = 0
options = []
else:
# make sure the EDNS version in ednsflags agrees with edns
ednsflags &= 0xFF00FFFFL
ednsflags |= (edns << 16)
if options is None:
options = []
self.edns = edns
self.ednsflags = ednsflags
self.payload = payload
self.options = options
self.request_payload = request_payload |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def want_dnssec(self, wanted=True):
"""Enable or disable 'DNSSEC desired' flag in requests. @param wanted: Is DNSSEC desired? If True, EDNS is enabled if required, and then the DO bit is set. If False, the DO bit is cleared if EDNS is enabled. @type wanted: bool """ |
if wanted:
if self.edns < 0:
self.use_edns()
self.ednsflags |= dns.flags.DO
elif self.edns >= 0:
self.ednsflags &= ~dns.flags.DO |
<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_rcode(self, rcode):
"""Set the rcode. @param rcode: the rcode @type rcode: int """ |
(value, evalue) = dns.rcode.to_flags(rcode)
self.flags &= 0xFFF0
self.flags |= value
self.ednsflags &= 0x00FFFFFFL
self.ednsflags |= evalue
if self.ednsflags != 0 and self.edns < 0:
self.edns = 0 |
<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_opcode(self, opcode):
"""Set the opcode. @param opcode: the opcode @type opcode: int """ |
self.flags &= 0x87FF
self.flags |= dns.opcode.to_flags(opcode) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.