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_rdataset(self, rdclass, rdtype, covers=dns.rdatatype.NONE, create=False): """Get an rdataset matching the specified properties in the current node. None is returned if an rdataset of the specified type and class does not exist and I{create} is not True. @param rdclass: The class of the rdataset @type rdclass: int @param rdtype: The type of the rdataset @type rdtype: int @param covers: The covered type. @type covers: int @param create: If True, create the rdataset if it is not found. @type create: bool @rtype: dns.rdataset.Rdataset object or None """
try: rds = self.find_rdataset(rdclass, rdtype, covers, create) except KeyError: rds = None return rds
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_rdataset(self, rdclass, rdtype, covers=dns.rdatatype.NONE): """Delete the rdataset matching the specified properties in the current node. If a matching rdataset does not exist, it is not an error. @param rdclass: The class of the rdataset @type rdclass: int @param rdtype: The type of the rdataset @type rdtype: int @param covers: The covered type. @type covers: int """
rds = self.get_rdataset(rdclass, rdtype, covers) if not rds is None: self.rdatasets.remove(rds)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replace_rdataset(self, replacement): """Replace an rdataset. It is not an error if there is no rdataset matching I{replacement}. Ownership of the I{replacement} object is transferred to the node; in other words, this method does not store a copy of I{replacement} at the node, it stores I{replacement} itself. """
self.delete_rdataset(replacement.rdclass, replacement.rdtype, replacement.covers) self.rdatasets.append(replacement)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def poll(self): """ Perform a non-blocking scan of recv and send states on the server and client connection sockets. Process new connection requests, read incomming data, and send outgoing data. Sends and receives may be partial. """
#print len(self.connections) ## Build a list of connections to test for receive data pending recv_list = [self.server_fileno] # always add the server for client in self.clients.values(): if client.active: recv_list.append(client.fileno) ## Delete inactive connections from the dictionary else: #print "-- Lost connection to %s" % client.addrport() #client.sock.close() self.on_disconnect(client) del self.clients[client.fileno] ## Build a list of connections that need to send data send_list = [] for client in self.clients.values(): if client.send_pending: send_list.append(client.fileno) ## Get active socket file descriptors from select.select() try: rlist, slist, elist = select.select(recv_list, send_list, [], self.timeout) except select.error, err: ## If we can't even use select(), game over man, game over print >> sys.stderr, ("!! FATAL SELECT error '%d:%s'!" % (err[0], err[1])) sys.exit(1) ## Process socket file descriptors with data to recieve for sock_fileno in rlist: ## If it's coming from the server's socket then this is a new ## connection request. if sock_fileno == self.server_fileno: try: sock, addr_tup = self.server_socket.accept() except socket.error, err: print >> sys.stderr, ("!! ACCEPT error '%d:%s'." % (err[0], err[1])) continue ## Check for maximum connections if self.client_count() >= MAX_CONNECTIONS: print '?? Refusing new connection; maximum in use.' sock.close() continue new_client = TelnetClient(sock, addr_tup) #print "++ Opened connection to %s" % new_client.addrport() ## Add the connection to our dictionary and call handler self.clients[new_client.fileno] = new_client self.on_connect(new_client) else: ## Call the connection's recieve method try: self.clients[sock_fileno].socket_recv() except BogConnectionLost: self.clients[sock_fileno].deactivate() ## Process sockets with data to send for sock_fileno in slist: ## Call the connection's send method self.clients[sock_fileno].socket_send()
<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_loghandler (handler): """Add log handler to root logger and LOG_ROOT and set formatting."""
format = "%(levelname)s %(name)s %(asctime)s %(threadName)s %(message)s" handler.setFormatter(logging.Formatter(format)) logging.getLogger(LOG_ROOT).addHandler(handler) logging.getLogger().addHandler(handler)
<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_loghandler (handler): """Remove log handler from root logger and LOG_ROOT."""
logging.getLogger(LOG_ROOT).removeHandler(handler) logging.getLogger().removeHandler(handler)
<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_loglevel(loggers, level): """Set logging levels for given loggers."""
if not loggers: return if 'all' in loggers: loggers = lognames.keys() for key in loggers: logging.getLogger(lognames[key]).setLevel(level)
<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): """Write one node and all possible edges."""
node = self.get_node(url_data) if node: self.xml_starttag(u'node', attrs={u"name": u"%d" % node["id"]}) self.xml_tag(u"label", node["label"]) if self.has_part("realurl"): self.xml_tag(u"url", node["url"]) self.xml_starttag(u"data") if node["dltime"] >= 0 and self.has_part("dltime"): self.xml_tag(u"dltime", u"%f" % node["dltime"]) if node["size"] >= 0 and self.has_part("dlsize"): self.xml_tag(u"size", u"%d" % node["size"]) if node["checktime"] and self.has_part("checktime"): self.xml_tag(u"checktime", u"%f" % node["checktime"]) if self.has_part("extern"): self.xml_tag(u"extern", u"%d" % node["extern"]) self.xml_endtag(u"data") self.xml_endtag(u"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 end_output (self, **kwargs): """Finish graph output, and print end of checking info as xml comment."""
self.xml_endtag(u"graph") self.xml_endtag(u"GraphXML") self.xml_end_output() 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_text(text): """Convert text into a DNS rdata class value. @param text: the text @type text: string @rtype: int @raises dns.rdataclass.UnknownRdataClass: the class is unknown @raises ValueError: the rdata class value is not >= 0 and <= 65535 """
value = _by_text.get(text.upper()) if value is None: match = _unknown_class_pattern.match(text) if match == None: raise UnknownRdataclass value = int(match.group(1)) if value < 0 or value > 65535: raise ValueError("class must be between >= 0 and <= 65535") return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_text(value): """Convert a DNS rdata class to text. @param value: the rdata class value @type value: int @rtype: string @raises ValueError: the rdata class value is not >= 0 and <= 65535 """
if value < 0 or value > 65535: raise ValueError("class must be between >= 0 and <= 65535") text = _by_value.get(value) if text is None: text = 'CLASS' + repr(value) return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def my_on_connect(client): """ Example on_connect handler. """
client.send('You connected from %s\n' % client.addrport()) if CLIENTS: client.send('Also connected are:\n') for neighbor in CLIENTS: client.send('%s\n' % neighbor.addrport()) else: client.send('Sadly, you are alone.\n') CLIENTS.append(client)
<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 internal flags and entry lists."""
self.entries = [] self.default_entry = None self.disallow_all = False self.allow_all = False self.last_checked = 0 # list of tuples (sitemap url, line number) self.sitemap_urls = []
<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_url (self, url): """Set the URL referring to a robots.txt file."""
self.url = url self.host, self.path = urlparse.urlparse(url)[1: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 read (self): """Read the robots.txt URL and feeds it to the parser."""
self._reset() kwargs = dict( headers = { 'User-Agent': configuration.UserAgent, 'Accept-Encoding': ACCEPT_ENCODING, } ) if self.auth: kwargs["auth"] = self.auth if self.proxies: kwargs["proxies"] = self.proxies try: response = self.session.get(self.url, **kwargs) response.raise_for_status() content_type = response.headers.get('content-type') if content_type and content_type.lower().startswith('text/plain'): self.parse(response.iter_lines()) else: log.debug(LOG_CHECK, "%r allow all (no text content)", self.url) self.allow_all = True except requests.HTTPError as x: if x.response.status_code in (401, 403): self.disallow_all = True log.debug(LOG_CHECK, "%r disallow all (code %d)", self.url, x.response.status_code) else: self.allow_all = True log.debug(LOG_CHECK, "%r allow all (HTTP error)", self.url) except requests.exceptions.Timeout: raise except requests.exceptions.RequestException: # no network or other failure self.allow_all = True log.debug(LOG_CHECK, "%r allow all (request error)", self.url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_entry (self, entry): """Add a parsed entry to entry list. @return: None """
if "*" in entry.useragents: # the default entry is considered last self.default_entry = entry else: self.entries.append(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 can_fetch (self, useragent, url): """Using the parsed robots.txt decide if useragent can fetch url. @return: True if agent can fetch url, else False @rtype: bool """
log.debug(LOG_CHECK, "%r check allowance for:\n user agent: %r\n url: %r ...", self.url, useragent, url) if not isinstance(useragent, str): useragent = useragent.encode("ascii", "ignore") if not isinstance(url, str): url = url.encode("ascii", "ignore") if self.disallow_all: log.debug(LOG_CHECK, " ... disallow all.") return False if self.allow_all: log.debug(LOG_CHECK, " ... allow all.") return True # search for given user agent matches # the first match counts url = urllib.quote(urlparse.urlparse(urllib.unquote(url))[2]) or "/" for entry in self.entries: if entry.applies_to(useragent): return entry.allowance(url) # try the default entry last if self.default_entry is not None: return self.default_entry.allowance(url) # agent not found ==> access granted log.debug(LOG_CHECK, " ... agent not found, allow.") 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 get_crawldelay (self, useragent): """Look for a configured crawl delay. @return: crawl delay in seconds or zero @rtype: integer >= 0 """
for entry in self.entries: if entry.applies_to(useragent): return entry.crawldelay return 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 applies_to (self, useragent): """Check if this entry applies to the specified agent. @return: True if this entry applies to the agent, else False. @rtype: bool """
if not useragent: return True useragent = useragent.lower() for agent in self.useragents: if agent == '*': # we have the catch-all agent return True if agent.lower() in useragent: return True 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 add_result(self, key, result): """Add result object to cache with given key. The request is ignored when the cache is already full or the key is None. """
if len(self.cache) > self.max_size: return if key is not None: self.cache[key] = result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter_tree(tree): """Filter all 401 errors."""
to_remove = [] for elem in tree.findall('urldata'): valid = elem.find('valid') if valid is not None and valid.text == '0' and \ valid.attrib.get('result', '').startswith('401'): to_remove.append(elem) root = tree.getroot() for elem in to_remove: root.remove(elem)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _connect_nntp (self, nntpserver): """ This is done only once per checking task. Also, the newly introduced error codes 504 and 505 (both inclining "Too busy, retry later", are caught. """
tries = 0 nntp = None while tries < 2: tries += 1 try: nntp = nntplib.NNTP(nntpserver, usenetrc=False) except nntplib.NNTPTemporaryError: self.wait() except nntplib.NNTPPermanentError as msg: if re.compile("^50[45]").search(str(msg)): self.wait() else: raise if nntp is None: raise LinkCheckerError( _("NNTP server too busy; tried more than %d times.") % tries) if log.is_debug(LOG_CHECK): nntp.set_debuglevel(1) self.add_info(nntp.getwelcome()) return nntp
<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_fileoutput (self, args): """Colorize file output if possible."""
super(TextLogger, self).init_fileoutput(args) if self.fd is not None: self.fd = ansicolor.Colorizer(self.fd)
<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_fileoutput (self): """Needed to make file descriptor color aware."""
init_color = self.fd is None super(TextLogger, self).start_fileoutput() if init_color: self.fd = ansicolor.Colorizer(self.fd)
<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 generic start checking info."""
super(TextLogger, self).start_output() if self.has_part('intro'): self.write_intro() 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_intro (self): """Log introduction text."""
self.writeln(configuration.AppInfo) self.writeln(configuration.Freeware) self.writeln(_("Get the newest version at %(url)s") % {'url': configuration.Url}) self.writeln(_("Write comments and bugs to %(url)s") % {'url': configuration.SupportUrl}) self.writeln(_("Support this project at %(url)s") % {'url': configuration.DonateUrl}) self.check_date() self.writeln() self.writeln(_("Start checking at %s") % strformat.strtime(self.starttime))
<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): """Write url checking info."""
self.writeln() if self.has_part('url'): self.write_url(url_data) if url_data.name and self.has_part('name'): self.write_name(url_data) if url_data.parent_url and self.has_part('parenturl'): self.write_parent(url_data) if url_data.base_ref and self.has_part('base'): self.write_base(url_data) if url_data.url and self.has_part('realurl'): self.write_real(url_data) if url_data.checktime and self.has_part('checktime'): self.write_checktime(url_data) if url_data.dltime >= 0 and self.has_part('dltime'): self.write_dltime(url_data) if url_data.size >= 0 and self.has_part('dlsize'): self.write_size(url_data) if url_data.info and self.has_part('info'): self.write_info(url_data) if url_data.modified and self.has_part('modified'): self.write_modified(url_data) if url_data.warnings and self.has_part('warning'): self.write_warning(url_data) if self.has_part('result'): self.write_result(url_data) self.flush()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_id (self): """Write unique ID of url_data."""
self.writeln() self.write(self.part('id') + self.spaces('id')) self.writeln(u"%d" % self.stats.number, color=self.colorinfo)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_warning (self, url_data): """Write url_data.warning."""
self.write(self.part("warning") + self.spaces("warning")) warning_msgs = [u"[%s] %s" % x for x in url_data.warnings] self.writeln(self.wrap(warning_msgs, 65), color=self.colorwarning)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_outro (self, interrupt=False): """Write end of checking message."""
self.writeln() if interrupt: self.writeln(_("The check has been interrupted; results are not complete.")) self.write(_("That's it.") + " ") self.write(_n("%d link", "%d links", self.stats.number) % self.stats.number) self.write(u" ") if self.stats.num_urls is not None: self.write(_n("in %d URL", "in %d URLs", self.stats.num_urls) % self.stats.num_urls) self.write(u" checked. ") warning_text = _n("%d warning found", "%d warnings found", self.stats.warnings_printed) % self.stats.warnings_printed if self.stats.warnings_printed: warning_color = self.colorwarning else: warning_color = self.colorinfo self.write(warning_text, color=warning_color) if self.stats.warnings != self.stats.warnings_printed: self.write(_(" (%d ignored or duplicates not printed)") % (self.stats.warnings - self.stats.warnings_printed)) self.write(u". ") error_text = _n("%d error found", "%d errors found", self.stats.errors_printed) % self.stats.errors_printed if self.stats.errors_printed: error_color = self.colorinvalid else: error_color = self.colorvalid self.write(error_text, color=error_color) if self.stats.errors != self.stats.errors_printed: self.write(_(" (%d duplicates not printed)") % (self.stats.errors - self.stats.errors_printed)) self.writeln(u".") num = self.stats.internal_errors if num: self.writeln(_n("There was %(num)d internal error.", "There were %(num)d internal errors.", num) % {"num": num}) self.stoptime = time.time() duration = self.stoptime - self.starttime self.writeln(_("Stopped checking at %(time)s (%(duration)s)") % {"time": strformat.strtime(self.stoptime), "duration": strformat.strduration_long(duration)})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_stats (self): """Write check statistic info."""
self.writeln() self.writeln(_("Statistics:")) if self.stats.downloaded_bytes is not None: self.writeln(_("Downloaded: %s.") % strformat.strsize(self.stats.downloaded_bytes)) if self.stats.number > 0: self.writeln(_( "Content types: %(image)d image, %(text)d text, %(video)d video, " "%(audio)d audio, %(application)d application, %(mail)d mail" " and %(other)d other.") % self.stats.link_types) self.writeln(_("URL lengths: min=%(min)d, max=%(max)d, avg=%(avg)d.") % dict(min=self.stats.min_url_length, max=self.stats.max_url_length, avg=self.stats.avg_url_length)) else: self.writeln(_("No statistics available since no URLs were checked."))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def end_output (self, **kwargs): """Write end of output info, and flush all output buffers."""
self.stats.downloaded_bytes = kwargs.get("downloaded_bytes") self.stats.num_urls = kwargs.get("num_urls") if self.has_part('stats'): self.write_stats() if self.has_part('outro'): self.write_outro(interrupt=kwargs.get("interrupt")) 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 url_fix_host (urlparts): """Unquote and fix hostname. Returns is_idn."""
if not urlparts[1]: urlparts[2] = urllib.unquote(urlparts[2]) return False userpass, netloc = urllib.splituser(urlparts[1]) if userpass: userpass = urllib.unquote(userpass) netloc, is_idn = idna_encode(urllib.unquote(netloc).lower()) # a leading backslash in path causes urlsplit() to add the # path components up to the first slash to host # try to find this case... i = netloc.find("\\") if i != -1: # ...and fix it by prepending the misplaced components to the path comps = netloc[i:] # note: still has leading backslash if not urlparts[2] or urlparts[2] == '/': urlparts[2] = comps else: urlparts[2] = "%s%s" % (comps, urllib.unquote(urlparts[2])) netloc = netloc[:i] else: # a leading ? in path causes urlsplit() to add the query to the # host name i = netloc.find("?") if i != -1: netloc, urlparts[3] = netloc.split('?', 1) # path urlparts[2] = urllib.unquote(urlparts[2]) if userpass: # append AT for easy concatenation userpass += "@" else: userpass = "" if urlparts[0] in default_ports: dport = default_ports[urlparts[0]] host, port = splitport(netloc, port=dport) if host.endswith("."): host = host[:-1] if port != dport: host = "%s:%d" % (host, port) netloc = host urlparts[1] = userpass+netloc return is_idn
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def url_fix_common_typos (url): """Fix common typos in given URL like forgotten colon."""
if url.startswith("http//"): url = "http://" + url[6:] elif url.startswith("https//"): url = "https://" + url[7:] return 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 url_parse_query (query, encoding=None): """Parse and re-join the given CGI query."""
if isinstance(query, unicode): if encoding is None: encoding = url_encoding query = query.encode(encoding, 'ignore') # if ? is in the query, split it off, seen at msdn.microsoft.com append = "" while '?' in query: query, rest = query.rsplit('?', 1) append = '?'+url_parse_query(rest)+append l = [] for k, v, sep in parse_qsl(query, keep_blank_values=True): k = url_quote_part(k, '/-:,;') if v: v = url_quote_part(v, '/-:,;') l.append("%s=%s%s" % (k, v, sep)) elif v is None: l.append("%s%s" % (k, sep)) else: # some sites do not work when the equal sign is missing l.append("%s=%s" % (k, sep)) return ''.join(l) + append
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def urlunsplit (urlparts): """Same as urlparse.urlunsplit but with extra UNC path handling for Windows OS."""
res = urlparse.urlunsplit(urlparts) if os.name == 'nt' and urlparts[0] == 'file' and '|' not in urlparts[2]: # UNC paths must have 4 slashes: 'file:////server/path' # Depending on the path in urlparts[2], urlparse.urlunsplit() # left only two or three slashes. This is fixed below repl = 'file://' if urlparts[2].startswith('//') else 'file:/' res = res.replace('file:', repl) 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 url_quote (url): """Quote given URL."""
if not url_is_absolute(url): return document_quote(url) urlparts = list(urlparse.urlsplit(url)) urlparts[0] = url_quote_part(urlparts[0]) # scheme urlparts[1] = url_quote_part(urlparts[1], ':') # host urlparts[2] = url_quote_part(urlparts[2], '/=,') # path urlparts[3] = url_quote_part(urlparts[3], '&=,') # query l = [] for k, v, sep in parse_qsl(urlparts[3], True): # query k = url_quote_part(k, '/-:,;') if v: v = url_quote_part(v, '/-:,;') l.append("%s=%s%s" % (k, v, sep)) else: l.append("%s%s" % (k, sep)) urlparts[3] = ''.join(l) urlparts[4] = url_quote_part(urlparts[4]) # anchor return urlunsplit(urlparts)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def document_quote (document): """Quote given document."""
doc, query = urllib.splitquery(document) doc = url_quote_part(doc, '/=,') if query: return "%s?%s" % (doc, query) return doc
<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_host (host, domainlist): """Return True if host matches an entry in given domain list."""
if not host: return False for domain in domainlist: if domain.startswith('.'): if host.endswith(domain): return True elif host == domain: 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 url_unsplit (parts): """Rejoin URL parts to a string."""
if parts[2] == default_ports.get(parts[0]): return "%s://%s%s" % (parts[0], parts[1], parts[3]) return "%s://%s:%d%s" % parts
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def splitport (host, port=0): """Split optional port number from host. If host has no port number, the given default port is returned. @param host: host name @ptype host: string @param port: the port number (default 0) @ptype port: int @return: tuple of (host, port) @rtype: tuple of (string, int) """
if ":" in host: shost, sport = host.split(":", 1) iport = is_numeric_port(sport) if iport: host, port = shost, iport elif not sport: # empty port, ie. the host was "hostname:" host = shost else: # For an invalid non-empty port leave the host name as is pass return 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 get_content(url, user=None, password=None, proxy=None, data=None, addheaders=None): """Get URL content and info. @return: (decoded text content of URL, headers) or (None, errmsg) on error. @rtype: tuple (String, dict) or (None, String) """
from . import configuration headers = { 'User-Agent': configuration.UserAgent, } if addheaders: headers.update(addheaders) method = 'GET' kwargs = dict(headers=headers) if user and password: kwargs['auth'] = (user, password) if data: kwargs['data'] = data method = 'POST' if proxy: kwargs['proxy'] = dict(http=proxy) from .configuration import get_share_file try: kwargs["verify"] = get_share_file('cacert.pem') except ValueError: pass try: response = requests.request(method, url, **kwargs) return response.text, response.headers except (requests.exceptions.RequestException, requests.exceptions.BaseHTTPError) as msg: log.warn(LOG_CHECK, ("Could not get content of URL %(url)s: %(msg)s.") \ % {"url": url, "msg": str(msg)}) return None, 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 shorten_duplicate_content_url(url): """Remove anchor part and trailing index.html from URL."""
if '#' in url: url = url.split('#', 1)[0] if url.endswith('index.html'): return url[:-10] if url.endswith('index.htm'): return url[:-9] return 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 is_duplicate_content_url(url1, url2): """Check if both URLs are allowed to point to the same content."""
if url1 == url2: return True if url2 in url1: url1 = shorten_duplicate_content_url(url1) if not url2.endswith('/') and url1.endswith('/'): url2 += '/' return url1 == url2 if url1 in url2: url2 = shorten_duplicate_content_url(url2) if not url1.endswith('/') and url2.endswith('/'): url1 += '/' return url1 == url2 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 write_file (filename, content, backup=False, callback=None): """Overwrite a possibly existing file with new content. Do this in a manner that does not leave truncated or broken files behind. @param filename: name of file to write @type filename: string @param content: file content to write @type content: string @param backup: if backup file should be left @type backup: bool @param callback: non-default storage function @type callback: None or function taking two parameters (fileobj, content) """
# first write in a temp file f = file(filename+".tmp", 'wb') if callback is None: f.write(content) else: callback(f, content) f.close() # move orig file to backup if os.path.exists(filename): os.rename(filename, filename+".bak") # move temp file to orig os.rename(filename+".tmp", filename) # remove backup if not backup and os.path.exists(filename+".bak"): os.remove(filename+".bak")
<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_module (name, without_error=True): """Test if given module can be imported. @param without_error: True if module must not throw any errors when importing @return: flag if import is successful @rtype: bool """
try: importlib.import_module(name) return True except ImportError: return False except Exception: # some modules raise errors when intitializing return not without_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 pathencode (path): """Encode a path string with the platform file system encoding."""
if isinstance(path, unicode) and not os.path.supports_unicode_filenames: path = path.encode(FSCODING, "replace") 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 has_changed (filename): """Check if filename has changed since the last check. If this is the first check, assume the file is changed."""
key = os.path.abspath(filename) mtime = get_mtime(key) if key not in _mtime_cache: _mtime_cache[key] = mtime return True return mtime > _mtime_cache[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 is_readable(filename): """Check if file is a regular file and is readable."""
return os.path.isfile(filename) and os.access(filename, os.R_OK)
<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_accessable_by_others(filename): """Check if file is group or world accessable."""
mode = os.stat(filename)[stat.ST_MODE] return mode & (stat.S_IRWXG | stat.S_IRWXO)
<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_writable_by_others(filename): """Check if file or directory is world writable."""
mode = os.stat(filename)[stat.ST_MODE] return mode & stat.S_IWOTH
<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_writable(filename): """Check if - the file is a regular file and is writable, or - the file does not exist and its parent directory exists and is writable """
if not os.path.exists(filename): parentdir = os.path.dirname(filename) return os.path.isdir(parentdir) and os.access(parentdir, os.W_OK) return os.path.isfile(filename) and os.access(filename, os.W_OK)
<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 (self, data): """Write data to buffer."""
self.tmpbuf.append(data) self.pos += len(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 flush (self, overlap=0): """Flush buffered data and return it."""
self.buf += self.empty.join(self.tmpbuf) self.tmpbuf = [] if overlap and overlap < self.pos: data = self.buf[:-overlap] self.buf = self.buf[-overlap:] else: data = self.buf self.buf = self.empty 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 guess_url(url): """Guess if URL is a http or ftp URL. @param url: the URL to check @ptype url: unicode @return: url with http:// or ftp:// prepended if it's detected as a http respective ftp URL. @rtype: unicode """
if url.lower().startswith("www."): # syntactic sugar return "http://%s" % url elif url.lower().startswith("ftp."): # syntactic sugar return "ftp://%s" % url return 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 absolute_url (base_url, base_ref, parent_url): """ Search for the absolute url to detect the link type. This does not join any url fragments together! @param base_url: base url from a link tag @type base_url: string or None @param base_ref: base url from <base> tag @type base_ref: string or None @param parent_url: url of parent document @type parent_url: string or None """
if base_url and urlutil.url_is_absolute(base_url): return base_url elif base_ref and urlutil.url_is_absolute(base_ref): return base_ref elif parent_url and urlutil.url_is_absolute(parent_url): return parent_url 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_url_from (base_url, recursion_level, aggregate, parent_url=None, base_ref=None, line=0, column=0, page=0, name=u"", parent_content_type=None, extern=None): """ Get url data from given base data. @param base_url: base url from a link tag @type base_url: string or None @param recursion_level: current recursion level @type recursion_level: number @param aggregate: aggregate object @type aggregate: aggregate.Consumer @param parent_url: parent url @type parent_url: string or None @param base_ref: base url from <base> tag @type base_ref string or None @param line: line number @type line: number @param column: column number @type column: number @param page: page number @type page: number @param name: link name @type name: string @param extern: (is_extern, is_strict) or None @type extern: tuple(int, int) or None """
if base_url is not None: base_url = strformat.unicode_safe(base_url) # left strip for detection of URL scheme base_url_stripped = base_url.lstrip() else: base_url_stripped = base_url if parent_url is not None: parent_url = strformat.unicode_safe(parent_url) if base_ref is not None: base_ref = strformat.unicode_safe(base_ref) name = strformat.unicode_safe(name) url = absolute_url(base_url_stripped, base_ref, parent_url).lower() if ":" in url: scheme = url.split(":", 1)[0].lower() else: scheme = None if not (url or name): # use filename as base url, with slash as path seperator name = base_url.replace("\\", "/") allowed_schemes = aggregate.config["allowedschemes"] # ignore local PHP files with execution directives local_php = (parent_content_type == 'application/x-httpd-php' and '<?' in base_url and '?>' in base_url and scheme == 'file') if local_php or (allowed_schemes and scheme not in allowed_schemes): klass = ignoreurl.IgnoreUrl else: assume_local_file = (recursion_level == 0) klass = get_urlclass_from(scheme, assume_local_file=assume_local_file) log.debug(LOG_CHECK, "%s handles url %s", klass.__name__, base_url) return klass(base_url, recursion_level, aggregate, parent_url=parent_url, base_ref=base_ref, line=line, column=column, page=page, name=name, extern=extern)
<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_urlclass_from (scheme, assume_local_file=False): """Return checker class for given URL scheme. If the scheme cannot be matched and assume_local_file is True, assume a local file. """
if scheme in ("http", "https"): klass = httpurl.HttpUrl elif scheme == "ftp": klass = ftpurl.FtpUrl elif scheme == "file": klass = fileurl.FileUrl elif scheme == "telnet": klass = telneturl.TelnetUrl elif scheme == "mailto": klass = mailtourl.MailtoUrl elif scheme in ("nntp", "news", "snews"): klass = nntpurl.NntpUrl elif scheme == "dns": klass = dnsurl.DnsUrl elif scheme == "itms-services": klass = itmsservicesurl.ItmsServicesUrl elif scheme and unknownurl.is_unknown_scheme(scheme): klass = unknownurl.UnknownUrl elif assume_local_file: klass = fileurl.FileUrl else: klass = unknownurl.UnknownUrl return klass
<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_index_html (urls): """ Construct artificial index.html from given URLs. @param urls: URL strings @type urls: iterator of string """
lines = ["<html>", "<body>"] for entry in urls: name = cgi.escape(entry) try: url = cgi.escape(urllib.quote(entry)) except KeyError: # Some unicode entries raise KeyError. url = name lines.append('<a href="%s">%s</a>' % (url, name)) lines.extend(["</body>", "</html>"]) return os.linesep.join(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 run_checked (self): """Wait and raise KeyboardInterrupt after."""
self.start_time = time.time() self.setName("Interrupt") while not self.stopped(self.WaitSeconds): duration = time.time() - self.start_time if duration > self.duration: log.warn(LOG_CHECK, "Interrupt after %s" % strformat.strduration_long(duration)) 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 esc_ansicolor (color): """convert a named color definition to an escaped ANSI color"""
control = '' if ";" in color: control, color = color.split(";", 1) control = AnsiControl.get(control, '')+";" cnum = AnsiColor.get(color, '0') return AnsiEsc % (control+cnum)
<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_win_color(color): """Convert a named color definition to Windows console color foreground, background and style numbers."""
foreground = background = style = None control = '' if ";" in color: control, color = color.split(";", 1) if control == bold: style = colorama.BRIGHT if color in InverseColors: background = WinColor[color] else: foreground = WinColor.get(color) return foreground, background, style
<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_colors (fp): """Test if given file is an ANSI color enabled tty."""
# The is_tty() function ensures that we do not colorize # redirected streams, as this is almost never what we want if not is_tty(fp): return False if os.name == 'nt': return True elif has_curses: import curses try: curses.setupterm(os.environ.get("TERM"), fp.fileno()) # More than 8 colors are good enough. return curses.tigetnum("colors") >= 8 except curses.error: return False 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_columns (fp): """Return number of columns for given file."""
if not is_tty(fp): return 80 if os.name == 'nt': return colorama.get_console_size().X if has_curses: import curses try: curses.setupterm(os.environ.get("TERM"), fp.fileno()) return curses.tigetnum("cols") except curses.error: pass return 80
<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_color (self, text, color=None): """Print text with given color. If color is None, print text as-is."""
if color is None: self.fp.write(text) else: write_color(self.fp, text, color)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_url(obj, url_data, pageno, seen_objs): """Recurse through a PDF object, searching for URLs."""
if isinstance(obj, PDFObjRef): if obj.objid in seen_objs: # prevent recursive loops return seen_objs.add(obj.objid) obj = obj.resolve() if isinstance(obj, dict): for key, value in obj.items(): if key == 'URI' and isinstance(value, basestring): # URIs should be 7bit ASCII encoded, but be safe and encode # to unicode # XXX this does not use an optional specified base URL url = strformat.unicode_safe(value) url_data.add_url(url, page=pageno) else: search_url(value, url_data, pageno, seen_objs) elif isinstance(obj, list): for elem in obj: search_url(elem, url_data, pageno, seen_objs) elif isinstance(obj, PDFStream): search_url(obj.attrs, url_data, pageno, seen_objs)
<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): """Parse PDF data."""
# XXX user authentication from url_data password = '' data = url_data.get_content() # PDFParser needs a seekable file object fp = StringIO(data) try: parser = PDFParser(fp) doc = PDFDocument(parser, password=password) for (pageno, page) in enumerate(PDFPage.create_pages(doc), start=1): if "Contents" in page.attrs: search_url(page.attrs["Contents"], url_data, pageno, set()) if "Annots" in page.attrs: search_url(page.attrs["Annots"], url_data, pageno, set()) except PSException as msg: if not msg.args: # at least show the class name msg = repr(msg) log.warn(LOG_PLUGIN, "Error parsing PDF file: %s", 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 _escapify(label): """Escape the characters in label which need it. @returns: the escaped string @rtype: string"""
text = '' for c in label: if c in _escaped: text += '\\' + c elif ord(c) > 0x20 and ord(c) < 0x7F: text += c else: text += '\\%03d' % ord(c) return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validate_labels(labels): """Check for empty labels in the middle of a label sequence, labels that are too long, and for too many labels. @raises NameTooLong: the name as a whole is too long @raises LabelTooLong: an individual label is too long @raises EmptyLabel: a label is empty (i.e. the root label) and appears in a position other than the end of the label sequence"""
l = len(labels) total = 0 i = -1 j = 0 for label in labels: ll = len(label) total += ll + 1 if ll > 63: raise LabelTooLong if i < 0 and label == '': i = j j += 1 if total > 255: raise NameTooLong if i >= 0 and i != l - 1: raise EmptyLabel
<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_unicode(text, origin = root): """Convert unicode text into a Name object. Lables are encoded in IDN ACE form. @rtype: dns.name.Name object """
if not isinstance(text, unicode): raise ValueError("input to from_unicode() must be a unicode string") if not (origin is None or isinstance(origin, Name)): raise ValueError("origin must be a Name or None") labels = [] label = u'' escaping = False edigits = 0 total = 0 if text == u'@': text = u'' if text: if text == u'.': return Name(['']) # no Unicode "u" on this constant! for c in text: if escaping: if edigits == 0: if c.isdigit(): total = int(c) edigits += 1 else: label += c escaping = False else: if not c.isdigit(): raise BadEscape total *= 10 total += int(c) edigits += 1 if edigits == 3: escaping = False label += chr(total) elif c == u'.' or c == u'\u3002' or \ c == u'\uff0e' or c == u'\uff61': if len(label) == 0: raise EmptyLabel labels.append(encodings.idna.ToASCII(label)) label = u'' elif c == u'\\': escaping = True edigits = 0 total = 0 else: label += c if escaping: raise BadEscape if len(label) > 0: labels.append(encodings.idna.ToASCII(label)) else: labels.append('') if (len(labels) == 0 or labels[-1] != '') and not origin is None: labels.extend(list(origin.labels)) return Name(labels)
<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, origin = root): """Convert text into a Name object. @rtype: dns.name.Name object """
if not isinstance(text, str): if isinstance(text, unicode) and sys.hexversion >= 0x02030000: return from_unicode(text, origin) else: raise ValueError("input to from_text() must be a string") if not (origin is None or isinstance(origin, Name)): raise ValueError("origin must be a Name or None") labels = [] label = '' escaping = False edigits = 0 total = 0 if text == '@': text = '' if text: if text == '.': return Name(['']) for c in text: if escaping: if edigits == 0: if c.isdigit(): total = int(c) edigits += 1 else: label += c escaping = False else: if not c.isdigit(): raise BadEscape total *= 10 total += int(c) edigits += 1 if edigits == 3: escaping = False label += chr(total) elif c == '.': if len(label) == 0: raise EmptyLabel labels.append(label) label = '' elif c == '\\': escaping = True edigits = 0 total = 0 else: label += c if escaping: raise BadEscape if len(label) > 0: labels.append(label) else: labels.append('') if (len(labels) == 0 or labels[-1] != '') and not origin is None: labels.extend(list(origin.labels)) return Name(labels)
<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(message, current): """Convert possibly compressed wire format into a Name. @param message: the entire DNS message @type message: string @param current: the offset of the beginning of the name from the start of the message @type current: int @raises dns.name.BadPointer: a compression pointer did not point backwards in the message @raises dns.name.BadLabelType: an invalid label type was encountered. @returns: a tuple consisting of the name that was read and the number of bytes of the wire format message which were consumed reading it @rtype: (dns.name.Name object, int) tuple """
if not isinstance(message, str): raise ValueError("input to from_wire() must be a byte string") message = dns.wiredata.maybe_wrap(message) labels = [] biggest_pointer = current hops = 0 count = ord(message[current]) current += 1 cused = 1 while count != 0: if count < 64: labels.append(message[current : current + count].unwrap()) current += count if hops == 0: cused += count elif count >= 192: current = (count & 0x3f) * 256 + ord(message[current]) if hops == 0: cused += 1 if current >= biggest_pointer: raise BadPointer biggest_pointer = current hops += 1 else: raise BadLabelType count = ord(message[current]) current += 1 if hops == 0: cused += 1 labels.append('') return (Name(labels), cused)
<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_subdomain(self, other): """Is self a subdomain of other? The notion of subdomain includes equality. @rtype: bool """
(nr, o, nl) = self.fullcompare(other) if nr == NAMERELN_SUBDOMAIN or nr == NAMERELN_EQUAL: 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 is_superdomain(self, other): """Is self a superdomain of other? The notion of subdomain includes equality. @rtype: bool """
(nr, o, nl) = self.fullcompare(other) if nr == NAMERELN_SUPERDOMAIN or nr == NAMERELN_EQUAL: 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 to_text(self, omit_final_dot = False): """Convert name to text format. @param omit_final_dot: If True, don't emit the final dot (denoting the root label) for absolute names. The default is False. @rtype: string """
if len(self.labels) == 0: return '@' if len(self.labels) == 1 and self.labels[0] == '': return '.' if omit_final_dot and self.is_absolute(): l = self.labels[:-1] else: l = self.labels s = '.'.join(map(_escapify, l)) 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 to_unicode(self, omit_final_dot = False): """Convert name to Unicode text format. IDN ACE lables are converted to Unicode. @param omit_final_dot: If True, don't emit the final dot (denoting the root label) for absolute names. The default is False. @rtype: string """
if len(self.labels) == 0: return u'@' if len(self.labels) == 1 and self.labels[0] == '': return u'.' if omit_final_dot and self.is_absolute(): l = self.labels[:-1] else: l = self.labels s = u'.'.join([encodings.idna.ToUnicode(_escapify(x)) for x in l]) 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 to_digestable(self, origin=None): """Convert name to a format suitable for digesting in hashes. The name is canonicalized and converted to uncompressed wire format. @param origin: If the name is relative and origin is not None, then origin will be appended to it. @type origin: dns.name.Name object @raises NeedAbsoluteNameOrOrigin: All names in wire format are absolute. If self is a relative name, then an origin must be supplied; if it is missing, then this exception is raised @rtype: string """
if not self.is_absolute(): if origin is None or not origin.is_absolute(): raise NeedAbsoluteNameOrOrigin labels = list(self.labels) labels.extend(list(origin.labels)) else: labels = self.labels dlabels = ["%s%s" % (chr(len(x)), x.lower()) for x in labels] return ''.join(dlabels)
<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, file = None, compress = None, origin = None): """Convert name to wire format, possibly compressing it. @param file: the file where the name is emitted (typically a cStringIO file). If None, a string containing the wire name will be returned. @type file: file or None @param compress: The compression table. If None (the default) names will not be compressed. @type compress: dict @param origin: If the name is relative and origin is not None, then origin will be appended to it. @type origin: dns.name.Name object @raises NeedAbsoluteNameOrOrigin: All names in wire format are absolute. If self is a relative name, then an origin must be supplied; if it is missing, then this exception is raised """
if file is None: file = cStringIO.StringIO() want_return = True else: want_return = False if not self.is_absolute(): if origin is None or not origin.is_absolute(): raise NeedAbsoluteNameOrOrigin labels = list(self.labels) labels.extend(list(origin.labels)) else: labels = self.labels i = 0 for label in labels: n = Name(labels[i:]) i += 1 if not compress is None: pos = compress.get(n) else: pos = None if not pos is None: value = 0xc000 + pos s = struct.pack('!H', value) file.write(s) break else: if not compress is None and len(n) > 1: pos = file.tell() if pos < 0xc000: compress[n] = pos l = len(label) file.write(chr(l)) if l > 0: file.write(label) if want_return: return file.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 split(self, depth): """Split a name into a prefix and suffix at depth. @param depth: the number of labels in the suffix @type depth: int @raises ValueError: the depth was not >= 0 and <= the length of the name. @returns: the tuple (prefix, suffix) @rtype: tuple """
l = len(self.labels) if depth == 0: return (self, dns.name.empty) elif depth == l: return (dns.name.empty, self) elif depth < 0 or depth > l: raise ValueError('depth must be >= 0 and <= the length of the name') return (Name(self[: -depth]), Name(self[-depth :]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def concatenate(self, other): """Return a new name which is the concatenation of self and other. @rtype: dns.name.Name object @raises AbsoluteConcatenation: self is absolute and other is not the empty name """
if self.is_absolute() and len(other) > 0: raise AbsoluteConcatenation labels = list(self.labels) labels.extend(list(other.labels)) return Name(labels)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def relativize(self, origin): """If self is a subdomain of origin, return a new name which is self relative to origin. Otherwise return self. @rtype: dns.name.Name object """
if not origin is None and self.is_subdomain(origin): return Name(self[: -len(origin)]) else: return 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 choose_relativity(self, origin=None, relativize=True): """Return a name with the relativity desired by the caller. If origin is None, then self is returned. Otherwise, if relativize is true the name is relativized, and if relativize is false the name is derelativized. @rtype: dns.name.Name object """
if origin: if relativize: return self.relativize(origin) else: return self.derelativize(origin) else: return 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 parent(self): """Return the parent of the name. @rtype: dns.name.Name object @raises NoParent: the name is either the root name or the empty name, and thus has no parent. """
if self == root or self == empty: raise NoParent return Name(self.labels[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 init_win32com (): """Initialize the win32com.client cache."""
global _initialized if _initialized: return import win32com.client if win32com.client.gencache.is_readonly: #allow gencache to create the cached wrapper objects win32com.client.gencache.is_readonly = False # under py2exe the call in gencache to __init__() does not happen # so we use Rebuild() to force the creation of the gen_py folder # Note that the python...\win32com.client.gen_py dir must not exist # to allow creation of the cache in %temp% for py2exe. # This is ensured by excluding win32com.gen_py in setup.py win32com.client.gencache.Rebuild() _initialized = 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 has_word (): """Determine if Word is available on the current system."""
if not has_win32com: return False try: import _winreg as winreg except ImportError: import winreg try: key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, "Word.Application") winreg.CloseKey(key) return True except (EnvironmentError, ImportError): pass 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_word_app (): """Return open Word.Application handle, or None if Word is not available on this system."""
if not has_word(): return None # Since this function is called from different threads, initialize # the COM layer. pythoncom.CoInitialize() import win32com.client app = win32com.client.gencache.EnsureDispatch("Word.Application") app.Visible = False return app
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open_wordfile (app, filename): """Open given Word file with application object."""
return app.Documents.Open(filename, ReadOnly=True, AddToRecentFiles=False, Visible=False, NoEncodingDialog=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 get_line_number(doc, wrange): """Get line number for given range object."""
lineno = 1 wrange.Select() wdFirstCharacterLineNumber = constants("wdFirstCharacterLineNumber") wdGoToLine = constants("wdGoToLine") wdGoToPrevious = constants("wdGoToPrevious") while True: curline = doc.Selection.Information(wdFirstCharacterLineNumber) doc.Selection.GoTo(wdGoToLine, wdGoToPrevious, Count=1, Name="") lineno += 1 prevline = doc.Selection.Information(wdFirstCharacterLineNumber) if prevline == curline: break return lineno
<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_temp_filename (content): """Get temporary filename for content to parse."""
# store content in temporary file fd, filename = fileutil.get_temp_file(mode='wb', suffix='.doc', prefix='lc_') try: fd.write(content) finally: fd.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 check(self, url_data): """Parse Word data."""
content = url_data.get_content() filename = get_temp_filename(content) # open word file and parse hyperlinks try: app = get_word_app() try: doc = open_wordfile(app, filename) if doc is None: raise Error("could not open word file %r" % filename) try: for link in doc.Hyperlinks: line = get_line_number(link.Range) name=link.TextToDisplay url_data.add_url(link.Address, name=name, line=line) finally: close_wordfile(doc) finally: close_word_app(app) except Error as msg: log.warn(LOG_PLUGIN, "Error parsing word file: %s", 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 strip_caret_codes(text): """ Strip out any caret codes from a string. """
## temporarily escape out ^^ text = text.replace('^^', '\x00') for token, foo in _ANSI_CODES: text = text.replace(token, '') return text.replace('\x00', '^')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def word_wrap(text, columns=80, indent=4, padding=2): """ Given a block of text, breaks into a list of lines wrapped to length. """
paragraphs = _PARA_BREAK.split(text) lines = [] columns -= padding for para in paragraphs: if para.isspace(): continue line = ' ' * indent for word in para.split(): if (len(line) + 1 + len(word)) > columns: lines.append(line) line = ' ' * padding line += word else: line += ' ' + word if not line.isspace(): lines.append(line) return 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 _get_char(self): """Read a character from input. @rtype: string """
if self.ungotten_char is None: if self.eof: c = '' else: c = self.file.read(1) if c == '': self.eof = True elif c == '\n': self.line_number += 1 else: c = self.ungotten_char self.ungotten_char = None return c
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def skip_whitespace(self): """Consume input until a non-whitespace character is encountered. The non-whitespace character is then ungotten, and the number of whitespace characters consumed is returned. If the tokenizer is in multiline mode, then newlines are whitespace. @rtype: int """
skipped = 0 while True: c = self._get_char() if c != ' ' and c != '\t': if (c != '\n') or not self.multiline: self._unget_char(c) return skipped skipped += 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 get_int(self): """Read the next token and interpret it as an integer. @raises dns.exception.SyntaxError: @rtype: int """
token = self.get().unescape() if not token.is_identifier(): raise dns.exception.SyntaxError('expecting an identifier') if not token.value.isdigit(): raise dns.exception.SyntaxError('expecting an integer') return int(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 get_uint8(self): """Read the next token and interpret it as an 8-bit unsigned integer. @raises dns.exception.SyntaxError: @rtype: int """
value = self.get_int() if value < 0 or value > 255: raise dns.exception.SyntaxError('%d is not an unsigned 8-bit integer' % value) 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_uint16(self): """Read the next token and interpret it as a 16-bit unsigned integer. @raises dns.exception.SyntaxError: @rtype: int """
value = self.get_int() if value < 0 or value > 65535: raise dns.exception.SyntaxError('%d is not an unsigned 16-bit integer' % value) 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_uint32(self): """Read the next token and interpret it as a 32-bit unsigned integer. @raises dns.exception.SyntaxError: @rtype: int """
token = self.get().unescape() if not token.is_identifier(): raise dns.exception.SyntaxError('expecting an identifier') if not token.value.isdigit(): raise dns.exception.SyntaxError('expecting an integer') value = long(token.value) if value < 0 or value > 4294967296L: raise dns.exception.SyntaxError('%d is not an unsigned 32-bit integer' % value) 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_string(self, origin=None): """Read the next token and interpret it as a string. @raises dns.exception.SyntaxError: @rtype: string """
token = self.get().unescape() if not (token.is_identifier() or token.is_quoted_string()): raise dns.exception.SyntaxError('expecting a string') 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 get_identifier(self, origin=None): """Read the next token and raise an exception if it is not an identifier. @raises dns.exception.SyntaxError: @rtype: string """
token = self.get().unescape() if not token.is_identifier(): raise dns.exception.SyntaxError('expecting an identifier') return token.value