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 check_origin(self): """Do some simple checking of the zone's origin. @raises dns.zone.NoSOA: there is no SOA RR @raises dns.zone.NoNS: there is no NS RRset @raises KeyError: there is no origin node """
if self.relativize: name = dns.name.empty else: name = self.origin if self.get_rdataset(name, dns.rdatatype.SOA) is None: raise NoSOA if self.get_rdataset(name, dns.rdatatype.NS) is None: raise NoNS
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _rr_line(self): """Process one line from a DNS master file."""
# Name if self.current_origin is None: raise UnknownOrigin token = self.tok.get(want_leading = True) if not token.is_whitespace(): self.last_name = dns.name.from_text(token.value, self.current_origin) else: token = self.tok.get() if token.is_eol_or_eof(): # treat leading WS followed by EOL/EOF as if they were EOL/EOF. return self.tok.unget(token) name = self.last_name if not name.is_subdomain(self.zone.origin): self._eat_line() return if self.relativize: name = name.relativize(self.zone.origin) token = self.tok.get() if not token.is_identifier(): raise dns.exception.SyntaxError # TTL try: ttl = dns.ttl.from_text(token.value) token = self.tok.get() if not token.is_identifier(): raise dns.exception.SyntaxError except dns.ttl.BadTTL: ttl = self.ttl # Class try: rdclass = dns.rdataclass.from_text(token.value) token = self.tok.get() if not token.is_identifier(): raise dns.exception.SyntaxError except dns.exception.SyntaxError: raise except Exception: rdclass = self.zone.rdclass if rdclass != self.zone.rdclass: raise dns.exception.SyntaxError("RR class is not zone's class") # Type try: rdtype = dns.rdatatype.from_text(token.value) except Exception: raise dns.exception.SyntaxError("unknown rdatatype '%s'" % token.value) n = self.zone.nodes.get(name) if n is None: n = self.zone.node_factory() self.zone.nodes[name] = n try: rd = dns.rdata.from_text(rdclass, rdtype, self.tok, self.current_origin, False) except dns.exception.SyntaxError: # Catch and reraise. (ty, va) = sys.exc_info()[:2] raise va except Exception: # All exceptions that occur in the processing of rdata # are treated as syntax errors. This is not strictly # correct, but it is correct almost all of the time. # We convert them to syntax errors so that we can emit # helpful filename:line info. (ty, va) = sys.exc_info()[:2] raise dns.exception.SyntaxError("caught exception %s: %s" % (str(ty), str(va))) rd.choose_relativity(self.zone.origin, self.relativize) covers = rd.covers() rds = n.find_rdataset(rdclass, rdtype, covers, True) rds.add(rd, 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 read(self): """Read a DNS master file and build a zone object. @raises dns.zone.NoSOA: No SOA RR was found at the zone origin @raises dns.zone.NoNS: No NS RRset was found at the zone origin """
try: while 1: token = self.tok.get(True, True).unescape() if token.is_eof(): if not self.current_file is None: self.current_file.close() if len(self.saved_state) > 0: (self.tok, self.current_origin, self.last_name, self.current_file, self.ttl) = self.saved_state.pop(-1) continue break elif token.is_eol(): continue elif token.is_comment(): self.tok.get_eol() continue elif token.value[0] == '$': u = token.value.upper() if u == '$TTL': token = self.tok.get() if not token.is_identifier(): raise dns.exception.SyntaxError("bad $TTL") self.ttl = dns.ttl.from_text(token.value) self.tok.get_eol() elif u == '$ORIGIN': self.current_origin = self.tok.get_name() self.tok.get_eol() if self.zone.origin is None: self.zone.origin = self.current_origin elif u == '$INCLUDE' and self.allow_include: token = self.tok.get() if not token.is_quoted_string(): raise dns.exception.SyntaxError("bad filename in $INCLUDE") filename = token.value token = self.tok.get() if token.is_identifier(): new_origin = dns.name.from_text(token.value, \ self.current_origin) self.tok.get_eol() elif not token.is_eol_or_eof(): raise dns.exception.SyntaxError("bad origin in $INCLUDE") else: new_origin = self.current_origin self.saved_state.append((self.tok, self.current_origin, self.last_name, self.current_file, self.ttl)) self.current_file = file(filename, 'r') self.tok = dns.tokenizer.Tokenizer(self.current_file, filename) self.current_origin = new_origin else: raise dns.exception.SyntaxError("Unknown master file directive '" + u + "'") continue self.tok.unget(token) self._rr_line() except dns.exception.SyntaxError, detail: (filename, line_number) = self.tok.where() if detail is None: detail = "syntax error" raise dns.exception.SyntaxError("%s:%d: %s" % (filename, line_number, detail)) # Now that we're done reading, do some basic checking of the zone. if self.check_origin: self.zone.check_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 cnormpath (path): """Norm a path name to platform specific notation and make it absolute."""
path = normpath(path) if os.name == 'nt': # replace slashes with backslashes path = path.replace("/", "\\") if not os.path.isabs(path): path = normpath(os.path.join(sys.prefix, path)) 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 cc_run (args): """Run the C compiler with a simple main program. @return: successful exit flag @rtype: bool """
prog = b"int main(){}\n" pipe = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True) pipe.communicate(input=prog) if os.WIFEXITED(pipe.returncode): return os.WEXITSTATUS(pipe.returncode) == 0 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 list_message_files (package, suffix=".mo"): """Return list of all found message files and their installation paths."""
for fname in glob.glob("po/*" + suffix): # basename (without extension) is a locale name localename = os.path.splitext(os.path.basename(fname))[0] domainname = "%s.mo" % package.lower() yield (fname, os.path.join( "share", "locale", localename, "LC_MESSAGES", domainname))
<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_manifest (): """Snatched from roundup.sf.net. Check that the files listed in the MANIFEST are present when the source is unpacked."""
try: f = open('MANIFEST') except Exception: print('\n*** SOURCE WARNING: The MANIFEST file is missing!') return try: manifest = [l.strip() for l in f.readlines() if not l.startswith('#')] finally: f.close() err = [line for line in manifest if not os.path.exists(line)] if err: n = len(manifest) print('\n*** SOURCE WARNING: There are files missing (%d/%d found)!' % (n - len(err), n)) print('\nMissing: '.join(err))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install (self): """Install the generated config file."""
outs = super(MyInstallLib, self).install() infile = self.create_conf_file() outfile = os.path.join(self.install_dir, os.path.basename(infile)) self.copy_file(infile, outfile) outs.append(outfile) return outs
<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_conf_file (self): """Create configuration file."""
cmd_obj = self.distribution.get_command_obj("install") cmd_obj.ensure_finalized() # we have to write a configuration file because we need the # <install_data> directory (and other stuff like author, url, ...) # all paths are made absolute by cnormpath() data = [] for d in ['purelib', 'platlib', 'lib', 'headers', 'scripts', 'data']: attr = 'install_%s' % d if cmd_obj.root: # cut off root path prefix cutoff = len(cmd_obj.root) # don't strip the path separator if cmd_obj.root.endswith(os.sep): cutoff -= 1 val = getattr(cmd_obj, attr)[cutoff:] else: val = getattr(cmd_obj, attr) if attr == 'install_data': cdir = os.path.join(val, "share", "linkchecker") data.append('config_dir = %r' % cnormpath(cdir)) elif attr == 'install_lib': if cmd_obj.root: _drive, tail = os.path.splitdrive(val) if tail.startswith(os.sep): tail = tail[1:] self.install_lib = os.path.join(cmd_obj.root, tail) else: self.install_lib = val data.append("%s = %r" % (attr, cnormpath(val))) self.distribution.create_conf_file(data, directory=self.install_lib) return self.get_conf_output()
<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_outputs (self): """Add the generated config file to the list of outputs."""
outs = super(MyInstallLib, self).get_outputs() conf_output = self.get_conf_output() outs.append(conf_output) if self.compile: outs.extend(self._bytecode_filenames([conf_output])) return outs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fix_permissions (self): """Set correct read permissions on POSIX systems. Might also be possible by setting umask?"""
if os.name == 'posix' and not self.dry_run: # Make the data files we just installed world-readable, # and the directories world-executable as well. for path in self.get_outputs(): mode = os.stat(path)[stat.ST_MODE] if stat.S_ISDIR(mode): mode |= 0o11 mode |= 0o44 os.chmod(path, mode)
<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_commands (self): """Generate config file and run commands."""
cwd = os.getcwd() data = [] data.append('config_dir = %r' % os.path.join(cwd, "config")) data.append("install_data = %r" % cwd) data.append("install_scripts = %r" % cwd) self.create_conf_file(data) super(MyDistribution, self).run_commands()
<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_extensions (self): """Add -std=gnu99 to build options if supported."""
# For gcc >= 3 we can add -std=gnu99 to get rid of warnings. extra = [] if self.compiler.compiler_type == 'unix': option = "-std=gnu99" if cc_supports_option(self.compiler.compiler, option): extra.append(option) # First, sanity-check the 'extensions' list self.check_extensions_list(self.extensions) for ext in self.extensions: for opt in extra: if opt not in ext.extra_compile_args: ext.extra_compile_args.append(opt) self.build_extension(ext)
<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): """Remove share directory on clean."""
if self.all: # remove share directory directory = os.path.join("build", "share") if os.path.exists(directory): remove_tree(directory, dry_run=self.dry_run) else: log.warn("'%s' does not exist -- can't clean it", directory) clean.run(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 from_address(text): """Convert an IPv4 or IPv6 address in textual form into a Name object whose value is the reverse-map domain name of the address. @param text: an IPv4 or IPv6 address in textual form (e.g. '127.0.0.1', '::1') @type text: str @rtype: dns.name.Name object """
try: parts = list(dns.ipv6.inet_aton(text).encode('hex_codec')) origin = ipv6_reverse_domain except Exception: parts = ['%d' % ord(byte) for byte in dns.ipv4.inet_aton(text)] origin = ipv4_reverse_domain parts.reverse() return dns.name.from_text('.'.join(parts), origin=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 to_address(name): """Convert a reverse map domain name into textual address form. @param name: an IPv4 or IPv6 address in reverse-map form. @type name: dns.name.Name object @rtype: str """
if name.is_subdomain(ipv4_reverse_domain): name = name.relativize(ipv4_reverse_domain) labels = list(name.labels) labels.reverse() text = '.'.join(labels) # run through inet_aton() to check syntax and make pretty. return dns.ipv4.inet_ntoa(dns.ipv4.inet_aton(text)) elif name.is_subdomain(ipv6_reverse_domain): name = name.relativize(ipv6_reverse_domain) labels = list(name.labels) labels.reverse() parts = [] i = 0 l = len(labels) while i < l: parts.append(''.join(labels[i:i+4])) i += 4 text = ':'.join(parts) # run through inet_aton() to check syntax and make pretty. return dns.ipv6.inet_ntoa(dns.ipv6.inet_aton(text)) else: raise dns.exception.SyntaxError('unknown reverse-map address family')
<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 an rcode. @param text: the texual rcode @type text: string @raises UnknownRcode: the rcode is unknown @rtype: int """
if text.isdigit(): v = int(text) if v >= 0 and v <= 4095: return v v = _by_text.get(text.upper()) if v is None: raise UnknownRcode return v
<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_flags(flags, ednsflags): """Return the rcode value encoded by flags and ednsflags. @param flags: the DNS flags @type flags: int @param ednsflags: the EDNS flags @type ednsflags: int @raises ValueError: rcode is < 0 or > 4095 @rtype: int """
value = (flags & 0x000f) | ((ednsflags >> 20) & 0xff0) if value < 0 or value > 4095: raise ValueError('rcode must be >= 0 and <= 4095') 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 to_text(value): """Convert rcode into text. @param value: the rcode @type value: int @rtype: string """
text = _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 _resolve_entity (mo): """ Resolve a HTML entity. @param mo: matched _entity_re object with a "entity" match group @type mo: MatchObject instance @return: resolved entity char, or empty string on error @rtype: unicode string """
ent = mo.group("entity") s = mo.group() if s.startswith('&#'): if s[2] in 'xX': radix = 16 else: radix = 10 try: num = int(ent, radix) except (ValueError, OverflowError): return u'' else: num = name2codepoint.get(ent) if num is None or num < 0: # unknown entity -> ignore return u'' try: return unichr(num) except ValueError: return 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_geoip_dat (): """Find a GeoIP database, preferring city over country lookup."""
datafiles = ("GeoIPCity.dat", "GeoIP.dat") if os.name == 'nt': paths = (sys.exec_prefix, r"c:\geoip") else: paths = ("/usr/local/share/GeoIP", "/usr/share/GeoIP") for path in paths: for datafile in datafiles: filename = os.path.join(path, datafile) if os.path.isfile(filename): return 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_location (host): """Get translated country and optional city name. @return: country with optional city or an boolean False if not found """
if geoip is None: # no geoip available return None try: record = get_geoip_record(host) except (geoip_error, socket.error): log.debug(LOG_PLUGIN, "Geoip error for %r", host, exception=True) # ignore lookup errors return None value = u"" if record and record.get("city"): value += unicode_safe(record["city"]) if record and record.get("country_name"): if value: value += u", " value += unicode_safe(record["country_name"]) 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 get_intern_pattern (url): """Return intern pattern for given URL. Redirections to the same domain with or without "www." prepended are allowed."""
parts = strformat.url_unicode_split(url) scheme = parts[0].lower() domain = parts[1].lower() domain, is_idn = urlutil.idna_encode(domain) # allow redirection www.example.com -> example.com and vice versa if domain.startswith('www.'): domain = domain[4:] if not (domain and scheme): return None path = urlutil.splitparams(parts[2])[0] segments = path.split('/')[:-1] path = "/".join(segments) if url.endswith('/'): path += '/' args = list(re.escape(x) for x in (scheme, domain, path)) if args[0] in ('http', 'https'): args[0] = 'https?' args[1] = r"(www\.|)%s" % args[1] return "^%s://%s%s" % tuple(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 setdefault (self, key, *args): """Remember key order if key not found."""
if key not in self: self._keys.append(key) return super(ListDict, self).setdefault(key, *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 pop (self, key): """Remove key from dict and return value."""
if key in self._keys: self._keys.remove(key) super(ListDict, self).pop(key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def popitem (self): """Remove oldest key from dict and return item."""
if self._keys: k = self._keys[0] v = self[k] del self[k] return (k, v) raise KeyError("popitem() on empty dictionary")
<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 (self, key, def_val=None): """Return lowercase key value."""
assert isinstance(key, basestring) return dict.get(self, key.lower(), def_val)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setdefault (self, key, *args): """Set lowercase key value and return."""
assert isinstance(key, basestring) return dict.setdefault(self, key.lower(), *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 fromkeys (cls, iterable, value=None): """Construct new caseless dict from given data."""
d = cls() for k in iterable: dict.__setitem__(d, k.lower(), value) return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pop (self, key, *args): """Remove lowercase key from dict and return value."""
assert isinstance(key, basestring) return dict.pop(self, key.lower(), *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 shrink (self): """Shrink ca. 5% of entries."""
trim = int(0.05*len(self)) if trim: items = super(LFUCache, self).items() # sorting function for items keyfunc = lambda x: x[1][0] values = sorted(items, key=keyfunc) for item in values[0:trim]: del self[item[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 setdefault (self, key, def_val=None): """Update key usage if found and return value, else set and return default."""
if key in self: return self[key] self[key] = def_val return def_val
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def items (self): """Return list of items, not updating usage count."""
return [(key, value[1]) for key, value in super(LFUCache, self).items()]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def popitem (self): """Remove and return an item."""
key, value = super(LFUCache, self).popitem() return (key, value[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 unicode_safe (s, encoding=i18n.default_encoding, errors='replace'): """Get unicode string without raising encoding errors. Unknown characters of the given encoding will be ignored. @param s: the string to be decoded @type s: any object except None @return: if s is already unicode, return s unchanged; else return decoded unicode string of str(s) @rtype: unicode """
assert s is not None, "argument to unicode_safe was None" if isinstance(s, unicode): # s is already unicode, nothing to do return s return unicode(str(s), encoding, 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 unquote (s, matching=False): """Remove leading and ending single and double quotes. The quotes need to match if matching is True. Only one quote from each end will be stripped. @return: if s evaluates to False, return s as is, else return string with stripped quotes @rtype: unquoted string, or s unchanged if it is evaluting to False """
if not s: return s if len(s) < 2: return s if matching: if s[0] in ("\"'") and s[0] == s[-1]: s = s[1:-1] else: if s[0] in ("\"'"): s = s[1:] if s[-1] in ("\"'"): s = s[:-1] return 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 indent (text, indent_string=" "): """Indent each line of text with the given indent string."""
lines = str(text).splitlines() return os.linesep.join("%s%s" % (indent_string, x) for x in lines)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def strtime (t, func=time.localtime): """Return ISO 8601 formatted time."""
return time.strftime("%Y-%m-%d %H:%M:%S", func(t)) + strtimezone()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def strduration_long (duration, do_translate=True): """Turn a time value in seconds into x hours, x minutes, etc."""
if do_translate: # use global translator functions global _, _n else: # do not translate _ = lambda x: x _n = lambda a, b, n: a if n==1 else b if duration < 0: duration = abs(duration) prefix = "-" else: prefix = "" if duration < 1: return _("%(prefix)s%(duration).02f seconds") % \ {"prefix": prefix, "duration": duration} # translation dummies _n("%d second", "%d seconds", 1) _n("%d minute", "%d minutes", 1) _n("%d hour", "%d hours", 1) _n("%d day", "%d days", 1) _n("%d year", "%d years", 1) cutoffs = [ (60, "%d second", "%d seconds"), (60, "%d minute", "%d minutes"), (24, "%d hour", "%d hours"), (365, "%d day", "%d days"), (None, "%d year", "%d years"), ] time_str = [] for divisor, single, plural in cutoffs: if duration < 1: break if divisor is None: duration, unit = 0, duration else: duration, unit = divmod(duration, divisor) if unit: time_str.append(_n(single, plural, unit) % unit) time_str.reverse() if len(time_str) > 2: time_str.pop() return "%s%s" % (prefix, ", ".join(time_str))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def strtimezone (): """Return timezone info, %z on some platforms, but not supported on all. """
if time.daylight: zone = time.altzone else: zone = time.timezone return "%+04d" % (-zone//SECONDS_PER_HOUR)
<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_socket (family, socktype, proto=0, timeout=60): """ Create a socket with given family and type. If SSL context is given an SSL socket is created. """
sock = socket.socket(family, socktype, proto=proto) sock.settimeout(timeout) socktypes_inet = [socket.AF_INET] if has_ipv6: socktypes_inet.append(socket.AF_INET6) if family in socktypes_inet and socktype == socket.SOCK_STREAM: # disable NAGLE algorithm, which means sending pending data # immediately, possibly wasting bandwidth but improving # responsiveness for fast networks sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) 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 applies_to(self, url_data): """Check validity, scheme, extern and url_connection."""
return url_data.valid and url_data.scheme == 'https' and \ not url_data.extern[0] and url_data.url_connection is not 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 check(self, url_data): """Run all SSL certificate checks that have not yet been done. OpenSSL already checked the SSL notBefore and notAfter dates. """
host = url_data.urlparts[1] if host in self.checked_hosts: return self.checked_hosts.add(host) cert = url_data.ssl_cert config = url_data.aggregate.config if cert and 'notAfter' in cert: self.check_ssl_valid_date(url_data, cert) elif config['sslverify']: msg = _('certificate did not include "notAfter" information') url_data.add_warning(msg) else: msg = _('SSL verification is disabled; enable the sslverify option') url_data.add_warning(msg)
<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_ssl_valid_date(self, url_data, cert): """Check if the certificate is still valid, or if configured check if it's at least a number of days valid. """
import ssl try: notAfter = ssl.cert_time_to_seconds(cert['notAfter']) except ValueError as msg: msg = _('Invalid SSL certficate "notAfter" value %r') % cert['notAfter'] url_data.add_warning(msg) return curTime = time.time() # Calculate seconds until certifcate expires. Can be negative if # the certificate is already expired. secondsValid = notAfter - curTime args = dict(expire=cert['notAfter']) if secondsValid < 0: msg = _('SSL certficate is expired on %(expire)s.') url_data.add_warning(msg % args) else: args['valid'] = strformat.strduration_long(secondsValid) if secondsValid < self.warn_ssl_cert_secs_valid: msg = _('SSL certificate expires on %(expire)s and is only %(valid)s valid.') url_data.add_warning(msg % args) else: msg = _('SSL certificate expires on %(expire)s and is %(valid)s valid.') url_data.add_info(msg % 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 add_anchor (self, url, line, column, name, base): """Add anchor URL."""
self.anchors.append((url, line, column, name, 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 check_anchor(self, url_data): """If URL is valid, parseable and has an anchor, check it. A warning is logged and True is returned if the anchor is not found. """
log.debug(LOG_PLUGIN, "checking anchor %r in %s", url_data.anchor, self.anchors) enc = lambda anchor: urlutil.url_quote_part(anchor, encoding=url_data.encoding) if any(x for x in self.anchors if enc(x[0]) == url_data.anchor): return if self.anchors: anchornames = sorted(set(u"`%s'" % x[0] for x in self.anchors)) anchors = u", ".join(anchornames) else: anchors = u"-" args = {"name": url_data.anchor, "anchors": anchors} msg = u"%s %s" % (_("Anchor `%(name)s' not found.") % args, _("Available anchors: %(anchors)s.") % args) url_data.add_warning(msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def zone_for_name(name, rdclass=dns.rdataclass.IN, tcp=False, resolver=None): """Find the name of the zone which contains the specified name. @param name: the query name @type name: absolute dns.name.Name object or string @param rdclass: The query class @type rdclass: int @param tcp: use TCP to make the query (default is False). @type tcp: bool @param resolver: the resolver to use @type resolver: dns.resolver.Resolver object or None @rtype: dns.name.Name"""
if isinstance(name, basestring): name = dns.name.from_text(name, dns.name.root) if resolver is None: resolver = get_default_resolver() if not name.is_absolute(): raise NotAbsolute(name) while 1: try: answer = resolver.query(name, dns.rdatatype.SOA, rdclass, tcp) if answer.rrset.name == name: return name # otherwise we were CNAMEd or DNAMEd and need to look higher except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer): pass try: name = name.parent() except dns.name.NoParent: raise NoRootSOA
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def maybe_clean(self): """Clean the cache if it's time to do so."""
now = time.time() if self.next_cleaning <= now: keys_to_delete = [] for (k, v) in self.data.iteritems(): if v.expiration <= now: keys_to_delete.append(k) for k in keys_to_delete: del self.data[k] now = time.time() self.next_cleaning = now + self.cleaning_interval
<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, key, value): """Associate key and value in the cache. @param key: the key @type key: (dns.name.Name, int, int) tuple whose values are the query name, rdtype, and rdclass. @param value: The answer being cached @type value: dns.resolver.Answer object """
self.maybe_clean() self.data[key] = 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 flush(self, key=None): """Flush the cache. If I{key} is specified, only that item is flushed. Otherwise the entire cache is flushed. @param key: the key to flush @type key: (dns.name.Name, int, int) tuple or None """
if not key is None: if key in self.data: del self.data[key] else: self.data = {} self.next_cleaning = time.time() + self.cleaning_interval
<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 resolver configuration to the defaults."""
self.domain = \ dns.name.Name(dns.name.from_text(socket.gethostname())[1:]) if len(self.domain) == 0: self.domain = dns.name.root self.nameservers = [] self.localhosts = set([ 'localhost', 'loopback', '127.0.0.1', '0.0.0.0', '::1', 'ip6-localhost', 'ip6-loopback', ]) # connected and active network interfaces self.interfaces = set() self.search = set() self.search_patterns = ['www.%s.com', 'www.%s.org', 'www.%s.net', ] self.port = 53 self.timeout = 2.0 self.lifetime = 30.0 self.keyring = None self.keyname = None self.keyalgorithm = dns.tsig.default_algorithm self.edns = -1 self.ednsflags = 0 self.payload = 0 self.cache = 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 read_local_ifaddrs (self): """ IP addresses for all active interfaces. @return: list of IP addresses @rtype: list of strings """
if os.name != 'posix': # only POSIX is supported right now return [] try: from linkcheck.network import IfConfig except ImportError: return [] ifaddrs = [] ifc = IfConfig() for iface in ifc.getInterfaceList(flags=IfConfig.IFF_UP): addr = ifc.getAddr(iface) if addr: ifaddrs.append(addr) return ifaddrs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _config_win32_nameservers(self, nameservers): """Configure a NameServer registry entry."""
# we call str() on nameservers to convert it from unicode to ascii nameservers = str(nameservers) split_char = self._determine_split_char(nameservers) ns_list = nameservers.split(split_char) for ns in ns_list: if not ns in self.nameservers: self.nameservers.append(ns)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _config_win32_domain(self, domain): """Configure a Domain registry entry."""
# we call str() on domain to convert it from unicode to ascii self.domain = dns.name.from_text(str(domain))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _config_win32_search(self, search): """Configure a Search registry entry."""
# we call str() on search to convert it from unicode to ascii search = str(search) split_char = self._determine_split_char(search) search_list = search.split(split_char) for s in search_list: if not s in self.search: self.search.add(dns.name.from_text(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 _config_win32_add_ifaddr (self, key, name): """Add interface ip address to self.localhosts."""
try: ip, rtype = _winreg.QueryValueEx(key, name) if isinstance(ip, basestring) and ip: ip = str(ip).lower() self.localhosts.add(ip) self.interfaces.add(ip) except WindowsError: 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 _config_win32_fromkey(self, key): """Extract DNS info from a registry key."""
try: enable_dhcp, rtype = _winreg.QueryValueEx(key, 'EnableDHCP') except WindowsError: enable_dhcp = False if enable_dhcp: try: servers, rtype = _winreg.QueryValueEx(key, 'DhcpNameServer') except WindowsError: servers = None if servers: self._config_win32_nameservers(servers) try: dom, rtype = _winreg.QueryValueEx(key, 'DhcpDomain') if dom: self._config_win32_domain(servers) except WindowsError: pass self._config_win32_add_ifaddr(key, 'DhcpIPAddress') else: try: servers, rtype = _winreg.QueryValueEx(key, 'NameServer') except WindowsError: servers = None if servers: self._config_win32_nameservers(servers) try: dom, rtype = _winreg.QueryValueEx(key, 'Domain') if dom: self._config_win32_domain(servers) except WindowsError: pass self._config_win32_add_ifaddr(key, 'IPAddress') try: search, rtype = _winreg.QueryValueEx(key, 'SearchList') except WindowsError: search = None if search: self._config_win32_search(search)
<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_registry(self): """Extract resolver configuration from the Windows registry."""
lm = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) want_scan = False try: try: # XP, 2000 tcp_params = _winreg.OpenKey(lm, r'SYSTEM\CurrentControlSet' r'\Services\Tcpip\Parameters') want_scan = True except EnvironmentError: # ME tcp_params = _winreg.OpenKey(lm, r'SYSTEM\CurrentControlSet' r'\Services\VxD\MSTCP') try: self._config_win32_fromkey(tcp_params) finally: tcp_params.Close() if want_scan: interfaces = _winreg.OpenKey(lm, r'SYSTEM\CurrentControlSet' r'\Services\Tcpip\Parameters' r'\Interfaces') try: i = 0 while True: try: guid = _winreg.EnumKey(interfaces, i) i += 1 key = _winreg.OpenKey(interfaces, guid) if not self._win32_is_nic_enabled(lm, guid, key): continue try: self._config_win32_fromkey(key) finally: key.Close() except EnvironmentError: break finally: interfaces.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 use_tsig(self, keyring, keyname=None, algorithm=dns.tsig.default_algorithm): """Add a TSIG signature to the query. @param keyring: The TSIG keyring to use; defaults to None. @type keyring: dict @param keyname: The name of the TSIG key to use; defaults to None. The key must be defined in the keyring. If a keyring is specified but a keyname is not, then the 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. @param algorithm: The TSIG key algorithm to use. The default is dns.tsig.default_algorithm. @type algorithm: string"""
self.keyring = keyring if keyname is None: self.keyname = self.keyring.keys()[0] else: self.keyname = keyname self.keyalgorithm = algorithm
<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, ednsflags, payload): """Configure Edns. @param edns: The EDNS level to use. The default is -1, no Edns. @type edns: int @param ednsflags: The EDNS flags @type ednsflags: int @param payload: The EDNS payload size. The default is 0. @type payload: int"""
if edns is None: edns = -1 self.edns = edns self.ednsflags = ednsflags self.payload = 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 init (domain, directory, loc=None): """Initialize this gettext i18n module. Searches for supported languages and installs the gettext translator class."""
global default_language, default_encoding, default_domain, default_directory default_directory = directory default_domain = domain if os.path.isdir(directory): # get supported languages for lang in os.listdir(directory): path = os.path.join(directory, lang, 'LC_MESSAGES') mo_file = os.path.join(path, '%s.mo' % domain) if os.path.exists(mo_file): supported_languages.add(lang) if loc is None: loc, encoding = get_locale() else: encoding = get_locale()[1] if loc in supported_languages: default_language = loc else: default_language = "en" # Even if the default language is not supported, the encoding should # be installed. Otherwise the Python installation is borked. default_encoding = encoding install_language(default_language)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install_language(language): """Install translation service routines into default namespace."""
translator = get_translator(default_domain, default_directory, languages=[get_lang(language)], fallback=True) do_unicode = True translator.install(do_unicode)
<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_translator (domain, directory, languages=None, translatorklass=Translator, fallback=False, fallbackklass=NullTranslator): """Search the appropriate GNUTranslations class."""
translator = gettext.translation(domain, localedir=directory, languages=languages, class_=translatorklass, fallback=fallback) if not isinstance(translator, gettext.GNUTranslations) and fallbackklass: translator = fallbackklass() return translator
<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_headers_lang (headers): """Return preferred supported language in given HTTP headers."""
if 'Accept-Language' not in headers: return default_language languages = headers['Accept-Language'].split(",") # sort with preference values pref_languages = [] for lang in languages: pref = 1.0 if ";" in lang: lang, _pref = lang.split(';', 1) try: pref = float(_pref) except ValueError: pass pref_languages.append((pref, lang)) pref_languages.sort() # search for lang for lang in (x[1] for x in pref_languages): if lang in supported_languages: return lang return default_language
<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_locale (): """Search the default platform locale and norm it. @returns (locale, encoding) @rtype (string, string)"""
try: loc, encoding = locale.getdefaultlocale() except ValueError: # locale configuration is broken - ignore that loc, encoding = None, None if loc is None: loc = "C" else: loc = norm_locale(loc) if encoding is None: encoding = "ascii" return (loc, encoding)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def norm_locale (loc): """Normalize a locale."""
loc = locale.normalize(loc) # split up the locale into its base components pos = loc.find('@') if pos >= 0: loc = loc[:pos] pos = loc.find('.') if pos >= 0: loc = loc[:pos] pos = loc.find('_') if pos >= 0: loc = loc[:pos] return loc
<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_encoded_writer (out=sys.stdout, encoding=None, errors='replace'): """Get wrapped output writer with given encoding and error handling."""
if encoding is None: encoding = default_encoding Writer = codecs.getwriter(encoding) return Writer(out, 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 _add_rr(self, name, ttl, rd, deleting=None, section=None): """Add a single RR to the update section."""
if section is None: section = self.authority covers = rd.covers() rrset = self.find_rrset(section, name, self.zone_rdclass, rd.rdtype, covers, deleting, True, True) rrset.add(rd, ttl)
<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=65535): """Return a string containing the update in DNS compressed wire format. @rtype: string"""
if origin is None: origin = self.origin return super(Update, self).to_wire(origin, max_size)
<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 SQL comment. """
self.write(u"-- ") self.writeln(s=s, **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 start_output (self): """ Write start of checking info as sql comment. """
super(SQLLogger, self).start_output() if self.has_part("intro"): self.write_intro() self.writeln() 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 log_url (self, url_data): """ Store url check info into the database. """
self.writeln(u"insert into %(table)s(urlname," "parentname,baseref,valid,result,warning,info,url,line,col," "name,checktime,dltime,size,cached,level,modified) values (" "%(base_url)s," "%(url_parent)s," "%(base_ref)s," "%(valid)d," "%(result)s," "%(warning)s," "%(info)s," "%(url)s," "%(line)d," "%(column)d," "%(name)s," "%(checktime)d," "%(dltime)d," "%(size)d," "%(cached)d," "%(level)d," "%(modified)s" ")%(separator)s" % {'table': self.dbname, 'base_url': sqlify(url_data.base_url), 'url_parent': sqlify((url_data.parent_url)), 'base_ref': sqlify((url_data.base_ref)), 'valid': intify(url_data.valid), 'result': sqlify(url_data.result), 'warning': sqlify(os.linesep.join(x[1] for x in url_data.warnings)), 'info': sqlify(os.linesep.join(url_data.info)), 'url': sqlify(urlutil.url_quote(url_data.url)), 'line': url_data.line, 'column': url_data.column, 'name': sqlify(url_data.name), 'checktime': url_data.checktime, 'dltime': url_data.dltime, 'size': url_data.size, 'cached': 0, 'separator': self.separator, "level": url_data.level, "modified": sqlify(self.format_modified(url_data.modified)), }) 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_memory_dump(): """Dump memory to a temporary filename with the meliae package. @return: JSON filename where memory dump has been written to @rtype: string """
# first do a full garbage collection run gc.collect() if gc.garbage: log.warn(LOG_CHECK, "Unreachabe objects: %s", pprint.pformat(gc.garbage)) from meliae import scanner fo, filename = get_temp_file(mode='wb', suffix='.json', prefix='lcdump_') try: scanner.dump_all_objects(fo) finally: fo.close() return 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 from_e164(text, origin=public_enum_domain): """Convert an E.164 number in textual form into a Name object whose value is the ENUM domain name for that number. @param text: an E.164 number in textual form. @type text: str @param origin: The domain in which the number should be constructed. The default is e164.arpa. @type: dns.name.Name object or None @rtype: dns.name.Name object """
parts = [d for d in text if d.isdigit()] parts.reverse() return dns.name.from_text('.'.join(parts), origin=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 to_e164(name, origin=public_enum_domain, want_plus_prefix=True): """Convert an ENUM domain name into an E.164 number. @param name: the ENUM domain name. @type name: dns.name.Name object. @param origin: A domain containing the ENUM domain name. The name is relativized to this domain before being converted to text. @type: dns.name.Name object or None @param want_plus_prefix: if True, add a '+' to the beginning of the returned number. @rtype: str """
if not origin is None: name = name.relativize(origin) dlabels = [d for d in name.labels if (d.isdigit() and len(d) == 1)] if len(dlabels) != len(name.labels): raise dns.exception.SyntaxError('non-digit labels in ENUM domain name') dlabels.reverse() text = ''.join(dlabels) if want_plus_prefix: text = '+' + text 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 query(number, domains, resolver=None): """Look for NAPTR RRs for the specified number in the specified domains. e.g. lookup('16505551212', ['e164.dnspython.org.', 'e164.arpa.']) """
if resolver is None: resolver = dns.resolver.get_default_resolver() for domain in domains: if isinstance(domain, (str, unicode)): domain = dns.name.from_text(domain) qname = dns.e164.from_e164(number, domain) try: return resolver.query(qname, 'NAPTR') except dns.resolver.NXDOMAIN: pass raise dns.resolver.NXDOMAIN
<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_node (self, url_data): """Return new node data or None if node already exists."""
if not url_data.url: return None elif url_data.url in self.nodes: return None node = { "url": url_data.url, "parent_url": url_data.parent_url, "id": self.nodeid, "label": quote(url_data.title if url_data.title else url_data.name), "extern": 1 if url_data.extern else 0, "checktime": url_data.checktime, "size": url_data.size, "dltime": url_data.dltime, "edge": quote(url_data.name), "valid": 1 if url_data.valid else 0, } self.nodes[node["url"]] = node self.nodeid += 1 return node
<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_edges (self): """ Write all edges we can find in the graph in a brute-force manner. """
for node in self.nodes.values(): if node["parent_url"] in self.nodes: self.write_edge(node) 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 end_output (self, **kwargs): """Write edges and end of checking info as gml comment."""
self.write_edges() self.end_graph() 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 from_file (filename): """Parse cookie data from a text file in HTTP header format. @return: list of tuples (headers, scheme, host, path) """
entries = [] with open(filename) as fd: lines = [] for line in fd.readlines(): line = line.rstrip() if not line: if lines: entries.append(from_headers("\r\n".join(lines))) lines = [] else: lines.append(line) if lines: entries.append(from_headers("\r\n".join(lines))) return entries
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GetConsoleScreenBufferInfo(stream_id=STDOUT): """Get console screen buffer info object."""
handle = handles[stream_id] csbi = CONSOLE_SCREEN_BUFFER_INFO() success = windll.kernel32.GetConsoleScreenBufferInfo( handle, byref(csbi)) if not success: raise WinError() return csbi
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def SetConsoleTextAttribute(stream_id, attrs): """Set a console text attribute."""
handle = handles[stream_id] return windll.kernel32.SetConsoleTextAttribute(handle, attrs)
<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(): """Initialize foreground and background attributes."""
global _default_foreground, _default_background, _default_style try: attrs = GetConsoleScreenBufferInfo().wAttributes except (ArgumentError, WindowsError): _default_foreground = GREY _default_background = BLACK _default_style = NORMAL else: _default_foreground = attrs & 7 _default_background = (attrs >> 4) & 7 _default_style = attrs & BRIGHT
<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_console(stream=STDOUT, foreground=None, background=None, style=None): """Set console foreground and background attributes."""
if foreground is None: foreground = _default_foreground if background is None: background = _default_background if style is None: style = _default_style attrs = get_attrs(foreground, background, style) SetConsoleTextAttribute(stream, attrs)
<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): """ Initialize FTP url data. """
super(FtpUrl, self).reset() # list of files for recursion self.files = [] # last part of URL filename self.filename = None self.filename_encoding = 'iso-8859-1'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def login (self): """Log into ftp server and check the welcome message."""
self.url_connection = ftplib.FTP(timeout=self.aggregate.config["timeout"]) if log.is_debug(LOG_CHECK): self.url_connection.set_debuglevel(1) try: self.url_connection.connect(self.host, self.port) _user, _password = self.get_user_password() if _user is None: self.url_connection.login() elif _password is None: self.url_connection.login(_user) else: self.url_connection.login(_user, _password) info = self.url_connection.getwelcome() if info: # note that the info may change every time a user logs in, # so don't add it to the url_data info. log.debug(LOG_CHECK, "FTP info %s", info) pass else: raise LinkCheckerError(_("Got no answer from FTP server")) except EOFError as msg: raise LinkCheckerError( _("Remote host has closed connection: %(msg)s") % str(msg))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def negotiate_encoding (self): """Check if server can handle UTF-8 encoded filenames. See also RFC 2640."""
try: features = self.url_connection.sendcmd("FEAT") except ftplib.error_perm as msg: log.debug(LOG_CHECK, "Ignoring error when getting FTP features: %s" % msg) pass else: log.debug(LOG_CHECK, "FTP features %s", features) if " UTF-8" in features.splitlines(): self.filename_encoding = "utf-8"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cwd (self): """ Change to URL parent directory. Return filename of last path component. """
path = self.urlparts[2].encode(self.filename_encoding, 'replace') dirname = path.strip('/') dirs = dirname.split('/') filename = dirs.pop() self.url_connection.cwd('/') for d in dirs: self.url_connection.cwd(d) return filename
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listfile (self): """ See if filename is in the current FTP directory. """
if not self.filename: return files = self.get_files() log.debug(LOG_CHECK, "FTP files %s", str(files)) if self.filename in files: # file found return # it could be a directory if the trailing slash was forgotten if "%s/" % self.filename in files: if not self.url.endswith('/'): self.add_warning( _("Missing trailing directory slash in ftp url."), tag=WARN_FTP_MISSING_SLASH) self.url += '/' return raise ftplib.error_perm("550 File not found")
<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 (self): """Get list of filenames in directory. Subdirectories have an ending slash."""
files = [] def add_entry (line): """Parse list line and add the entry it points to to the file list.""" log.debug(LOG_CHECK, "Directory entry %r", line) from ..ftpparse import ftpparse fpo = ftpparse(line) if fpo is not None and fpo["name"]: name = fpo["name"] if fpo["trycwd"]: name += "/" if fpo["trycwd"] or fpo["tryretr"]: files.append(name) self.url_connection.dir(add_entry) return files
<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_parseable (self): """See if URL target is parseable for recursion."""
if self.is_directory(): return True if self.content_type in self.ContentMimetypes: return True log.debug(LOG_CHECK, "URL with content type %r is not parseable.", self.content_type) return False
<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): """Set URL content type, or an empty string if content type could not be found."""
self.content_type = mimeutil.guess_mimetype(self.url, read=self.get_content)
<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 URL target content, or in case of directories a dummy HTML file with links to the files."""
if self.is_directory(): self.url_connection.cwd(self.filename) self.files = self.get_files() # XXX limit number of files? data = get_index_html(self.files) else: # download file in BINARY mode ftpcmd = "RETR %s" % self.filename buf = StringIO() def stor_data (s): """Helper method storing given data""" # limit the download size if (buf.tell() + len(s)) > self.max_size: raise LinkCheckerError(_("FTP file size too large")) buf.write(s) self.url_connection.retrbinary(ftpcmd, stor_data) data = buf.getvalue() buf.close() 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 close_connection (self): """Release the open connection from the connection pool."""
if self.url_connection is not None: try: self.url_connection.quit() except Exception: 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 find_bookmark_file (): """Return the bookmark file of the Opera profile. Returns absolute filename if found, or empty string if no bookmark file could be found. """
try: dirname = get_profile_dir() if os.path.isdir(dirname): for name in OperaBookmarkFiles: fname = os.path.join(dirname, name) if os.path.isfile(fname): return fname except Exception: pass return u""
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(args): """Remove lines after marker."""
filename = args[0] marker = args[1] for line in fileinput.input(filename, inplace=1): print(line.rstrip()) if line.startswith(marker): 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 parse_bookmark_json (data): """Parse complete JSON data for Chromium Bookmarks."""
for entry in data["roots"].values(): for url, name in parse_bookmark_node(entry): yield url, 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 parse_bookmark_node (node): """Parse one JSON node of Chromium Bookmarks."""
if node["type"] == "url": yield node["url"], node["name"] elif node["type"] == "folder": for child in node["children"]: for entry in parse_bookmark_node(child): yield entry
<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, **kw): """Convert a node to text format. Each rdataset at the node is printed. Any keyword arguments to this method are passed on to the rdataset's to_text() method. @param name: the owner name of the rdatasets @type name: dns.name.Name object @rtype: string """
s = StringIO.StringIO() for rds in self.rdatasets: print >> s, rds.to_text(name, **kw) 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 find_rdataset(self, rdclass, rdtype, covers=dns.rdatatype.NONE, create=False): """Find an rdataset matching the specified properties in the current node. @param rdclass: The class of the rdataset @type rdclass: int @param rdtype: The type of the rdataset @type rdtype: int @param covers: The covered type. Usually this value is dns.rdatatype.NONE, but if the rdtype is dns.rdatatype.SIG or dns.rdatatype.RRSIG, then the covers value will be the rdata type the SIG/RRSIG covers. The library treats the SIG and RRSIG types as if they were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA). This makes RRSIGs much easier to work with than if RRSIGs covering different rdata types were aggregated into a single RRSIG rdataset. @type covers: int @param create: If True, create the rdataset if it is not found. @type create: bool @raises KeyError: An rdataset of the desired type and class does not exist and I{create} is not True. @rtype: dns.rdataset.Rdataset object """
for rds in self.rdatasets: if rds.match(rdclass, rdtype, covers): return rds if not create: raise KeyError rds = dns.rdataset.Rdataset(rdclass, rdtype) self.rdatasets.append(rds) return rds