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 simulate(self, steps, initial_lr): """ Simulates the learning rate scheduler. Parameters steps: int Number of steps to simulate initial_lr: float Initial learning rate Returns ------- lrs: numpy ndarray Simulated learning rates """
test = torch.ones(1, requires_grad=True) opt = torch.optim.SGD([{'params': test, 'lr': initial_lr}]) policy_cls = self._get_policy_cls() sch = policy_cls(opt, **self.kwargs) if hasattr(sch, 'batch_step') and callable(sch.batch_step): step = sch.batch_step else: step = sch.step lrs = [] for _ in range(steps): step() lrs.append(sch.get_lr()[0]) return np.array(lrs)
<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_scheduler(self, net, policy, **scheduler_kwargs): """Return scheduler, based on indicated policy, with appropriate parameters. """
if policy not in [CyclicLR, ReduceLROnPlateau] and \ 'last_epoch' not in scheduler_kwargs: last_epoch = len(net.history) - 1 scheduler_kwargs['last_epoch'] = last_epoch if policy is CyclicLR and \ 'last_batch_idx' not in scheduler_kwargs: scheduler_kwargs['last_batch_idx'] = self.batch_idx_ - 1 return policy(net.optimizer_, **scheduler_kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_verified(self): """ Verifies an SES bounce message. """
if self._verified is None: signature = self._data.get('Signature') if not signature: self._verified = False return self._verified # Decode the signature from base64 signature = bytes(base64.b64decode(signature)) # Get the message to sign sign_bytes = self._get_bytes_to_sign() if not sign_bytes: self._verified = False return self._verified if not self.certificate: self._verified = False return self._verified # Extract the public key pkey = self.certificate.get_pubkey() # Use the public key to verify the signature. pkey.verify_init() pkey.verify_update(sign_bytes) verify_result = pkey.verify_final(signature) self._verified = verify_result == 1 return self._verified
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def certificate(self): """ Retrieves the certificate used to sign the bounce message. TODO: Cache the certificate based on the cert URL so we don't have to retrieve it for each bounce message. *We would need to do it in a secure way so that the cert couldn't be overwritten in the cache* """
if not hasattr(self, '_certificate'): cert_url = self._get_cert_url() # Only load certificates from a certain domain? # Without some kind of trusted domain check, any old joe could # craft a bounce message and sign it using his own certificate # and we would happily load and verify it. if not cert_url: self._certificate = None return self._certificate try: import requests except ImportError: raise ImproperlyConfigured("requests is required for bounce message verification.") try: import M2Crypto except ImportError: raise ImproperlyConfigured("M2Crypto is required for bounce message verification.") # We use requests because it verifies the https certificate # when retrieving the signing certificate. If https was somehow # hijacked then all bets are off. response = requests.get(cert_url) if response.status_code != 200: logger.warning(u'Could not download certificate from %s: "%s"', cert_url, response.status_code) self._certificate = None return self._certificate # Handle errors loading the certificate. # If the certificate is invalid then return # false as we couldn't verify the message. try: self._certificate = M2Crypto.X509.load_cert_string(response.content) except M2Crypto.X509.X509Error as e: logger.warning(u'Could not load certificate from %s: "%s"', cert_url, e) self._certificate = None return self._certificate
<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_bytes_to_sign(self): """ Creates the message used for signing SNS notifications. This is used to verify the bounce message when it is received. """
# Depending on the message type the fields to add to the message # differ so we handle that here. msg_type = self._data.get('Type') if msg_type == 'Notification': fields_to_sign = [ 'Message', 'MessageId', 'Subject', 'Timestamp', 'TopicArn', 'Type', ] elif (msg_type == 'SubscriptionConfirmation' or msg_type == 'UnsubscribeConfirmation'): fields_to_sign = [ 'Message', 'MessageId', 'SubscribeURL', 'Timestamp', 'Token', 'TopicArn', 'Type', ] else: # Unrecognized type logger.warning(u'Unrecognized SNS message Type: "%s"', msg_type) return None outbytes = StringIO() for field_name in fields_to_sign: field_value = smart_str(self._data.get(field_name, ''), errors="replace") if field_value: outbytes.write(text(field_name)) outbytes.write(text("\n")) outbytes.write(text(field_value)) outbytes.write(text("\n")) response = outbytes.getvalue() return bytes(response, '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 superuser_only(view_func): """ Limit a view to superuser only. """
def _inner(request, *args, **kwargs): if not request.user.is_superuser: raise PermissionDenied return view_func(request, *args, **kwargs) return _inner
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sum_stats(stats_data): """ Summarize the bounces, complaints, delivery attempts and rejects from a list of datapoints. """
t_bounces = 0 t_complaints = 0 t_delivery_attempts = 0 t_rejects = 0 for dp in stats_data: t_bounces += int(dp['Bounces']) t_complaints += int(dp['Complaints']) t_delivery_attempts += int(dp['DeliveryAttempts']) t_rejects += int(dp['Rejects']) return { 'Bounces': t_bounces, 'Complaints': t_complaints, 'DeliveryAttempts': t_delivery_attempts, 'Rejects': t_rejects, }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dashboard(request): """ Graph SES send statistics over time. """
cache_key = 'vhash:django_ses_stats' cached_view = cache.get(cache_key) if cached_view: return cached_view region = RegionInfo( name=settings.AWS_SES_REGION_NAME, endpoint=settings.AWS_SES_REGION_ENDPOINT) ses_conn = SESConnection( aws_access_key_id=settings.ACCESS_KEY, aws_secret_access_key=settings.SECRET_KEY, region=region, proxy=settings.AWS_SES_PROXY, proxy_port=settings.AWS_SES_PROXY_PORT, ) quota_dict = ses_conn.get_send_quota() verified_emails_dict = ses_conn.list_verified_email_addresses() stats = ses_conn.get_send_statistics() quota = quota_parse(quota_dict) verified_emails = emails_parse(verified_emails_dict) ordered_data = stats_to_list(stats) summary = sum_stats(ordered_data) extra_context = { 'title': 'SES Statistics', 'datapoints': ordered_data, '24hour_quota': quota['Max24HourSend'], '24hour_sent': quota['SentLast24Hours'], '24hour_remaining': float(quota['Max24HourSend']) - float(quota['SentLast24Hours']), 'persecond_rate': quota['MaxSendRate'], 'verified_emails': verified_emails, 'summary': summary, 'access_key': ses_conn.gs_access_key_id, 'local_time': True, } response = render(request, 'django_ses/send_stats.html', extra_context) cache.set(cache_key, response, 60 * 15) # Cache for 15 minutes return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dkim_sign(message, dkim_domain=None, dkim_key=None, dkim_selector=None, dkim_headers=None): """Return signed email message if dkim package and settings are available."""
try: import dkim except ImportError: pass else: if dkim_domain and dkim_key: sig = dkim.sign(message, dkim_selector, dkim_domain, dkim_key, include_headers=dkim_headers) message = sig + message return message
<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(self): """Create a connection to the AWS API server. This can be reused for sending multiple emails. """
if self.connection: return False try: self.connection = SESConnection( aws_access_key_id=self._access_key_id, aws_secret_access_key=self._access_key, region=self._region, proxy=self._proxy, proxy_port=self._proxy_port, proxy_user=self._proxy_user, proxy_pass=self._proxy_pass, ) except Exception: if not self.fail_silently: raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """Close any open HTTP connections to the API server. """
try: self.connection.close() self.connection = None except Exception: if not self.fail_silently: raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_to_tuple(tokens): """Converts set literal tokens to tuples."""
internal_assert(len(tokens) == 1, "invalid set maker tokens", tokens) if "comp" in tokens or "list" in tokens: return "(" + tokens[0] + ")" elif "test" in tokens: return "(" + tokens[0] + ",)" else: raise CoconutInternalException("invalid set maker item", tokens[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 single_import(path, imp_as): """Generate import statements from a fully qualified import and the name to bind it to."""
out = [] parts = path.split("./") # denotes from ... import ... if len(parts) == 1: imp_from, imp = None, parts[0] else: imp_from, imp = parts if imp == imp_as: imp_as = None elif imp.endswith("." + imp_as): if imp_from is None: imp_from = "" imp_from += imp.rsplit("." + imp_as, 1)[0] imp, imp_as = imp_as, None if imp_from is None and imp == "sys": out.append((imp_as if imp_as is not None else imp) + " = _coconut_sys") elif imp_as is not None and "." in imp_as: fake_mods = imp_as.split(".") out.append(import_stmt(imp_from, imp, import_as_var)) for i in range(1, len(fake_mods)): mod_name = ".".join(fake_mods[:i]) out.extend(( "try:", openindent + mod_name, closeindent + "except:", openindent + mod_name + ' = _coconut.types.ModuleType("' + mod_name + '")', closeindent + "else:", openindent + "if not _coconut.isinstance(" + mod_name + ", _coconut.types.ModuleType):", openindent + mod_name + ' = _coconut.types.ModuleType("' + mod_name + '")' + closeindent * 2, )) out.append(".".join(fake_mods) + " = " + import_as_var) else: out.append(import_stmt(imp_from, imp, imp_as)) return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def split_args_list(tokens, loc): """Splits function definition arguments."""
req_args, def_args, star_arg, kwd_args, dubstar_arg = [], [], None, [], None pos = 0 for arg in tokens: if len(arg) == 1: if arg[0] == "*": # star sep (pos = 3) if pos >= 3: raise CoconutDeferredSyntaxError("star separator at invalid position in function definition", loc) pos = 3 else: # pos arg (pos = 0) if pos > 0: raise CoconutDeferredSyntaxError("positional arguments must come first in function definition", loc) req_args.append(arg[0]) elif len(arg) == 2: if arg[0] == "*": # star arg (pos = 2) if pos >= 2: raise CoconutDeferredSyntaxError("star argument at invalid position in function definition", loc) pos = 2 star_arg = arg[1] elif arg[0] == "**": # dub star arg (pos = 4) if pos == 4: raise CoconutDeferredSyntaxError("double star argument at invalid position in function definition", loc) pos = 4 dubstar_arg = arg[1] else: # def arg (pos = 1) if pos <= 1: pos = 1 def_args.append((arg[0], arg[1])) # kwd arg (pos = 3) elif pos <= 3: pos = 3 kwd_args.append((arg[0], arg[1])) else: raise CoconutDeferredSyntaxError("invalid default argument in function definition", loc) else: raise CoconutInternalException("invalid function definition argument", arg) return req_args, def_args, star_arg, kwd_args, dubstar_arg
<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_case_tokens(loc, tokens, check_var, top): """Build code for matching the given case."""
if len(tokens) == 2: matches, stmts = tokens cond = None elif len(tokens) == 3: matches, cond, stmts = tokens else: raise CoconutInternalException("invalid case match tokens", tokens) matching = Matcher(loc, check_var) matching.match(matches, match_to_var) if cond: matching.add_guard(cond) return matching.build(stmts, set_check_var=top)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup(self, target=None, strict=False, minify=False, line_numbers=False, keep_lines=False, no_tco=False): """Initializes parsing parameters."""
if target is None: target = "" else: target = str(target).replace(".", "") if target in pseudo_targets: target = pseudo_targets[target] if target not in targets: raise CoconutException( "unsupported target Python version " + ascii(target), extra="supported targets are " + ', '.join(ascii(t) for t in specific_targets) + ", or leave blank for universal", ) logger.log_vars("Compiler args:", locals()) self.target, self.strict, self.minify, self.line_numbers, self.keep_lines, self.no_tco = ( target, strict, minify, line_numbers, keep_lines, no_tco, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def genhash(self, package, code): """Generate a hash from code."""
return hex(checksum( hash_sep.join( str(item) for item in (VERSION_STR,) + self.__reduce__()[1] + (package, code) ).encode(default_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 reset(self): """Resets references."""
self.indchar = None self.comments = {} self.refs = [] self.set_skips([]) self.docstring = "" self.ichain_count = 0 self.tre_store_count = 0 self.case_check_count = 0 self.stmt_lambdas = [] if self.strict: self.unused_imports = set() self.bind()
<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_skips(self, skips): """Set the line skips."""
skips.sort() internal_assert(lambda: len(set(skips)) == len(skips), "duplicate line skip(s) in skips", skips) self.skips = skips
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def adjust(self, ln): """Converts a parsing line number into an original line number."""
adj_ln = ln need_unskipped = 0 for i in self.skips: if i <= ln: need_unskipped += 1 elif adj_ln + need_unskipped < i: break else: need_unskipped -= i - adj_ln - 1 adj_ln = i return adj_ln + need_unskipped
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reformat(self, snip, index=None): """Post process a preprocessed snippet."""
if index is not None: return self.reformat(snip), len(self.reformat(snip[:index])) else: return self.repl_proc(snip, reformatting=True, log=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 eval_now(self, code): """Reformat and evaluate a code snippet and return code for the result."""
result = eval(self.reformat(code)) if result is None or isinstance(result, (bool, int, float, complex)): return repr(result) elif isinstance(result, bytes): return "b" + self.wrap_str_of(result) elif isinstance(result, str): return self.wrap_str_of(result) else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_err(self, errtype, message, original, loc, ln=None, reformat=True, *args, **kwargs): """Generate an error of the specified type."""
if ln is None: ln = self.adjust(lineno(loc, original)) errstr, index = getline(loc, original), col(loc, original) - 1 if reformat: errstr, index = self.reformat(errstr, index) return errtype(message, errstr, index, ln, *args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def strict_err_or_warn(self, *args, **kwargs): """Raises an error if in strict mode, otherwise raises a warning."""
if self.strict: raise self.make_err(CoconutStyleError, *args, **kwargs) else: logger.warn_err(self.make_err(CoconutSyntaxWarning, *args, **kwargs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_ref(self, reftype, data): """Add a reference and returns the identifier."""
ref = (reftype, data) try: index = self.refs.index(ref) except ValueError: self.refs.append(ref) index = len(self.refs) - 1 return str(index)
<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_ref(self, reftype, index): """Retrieve a reference."""
try: got_reftype, data = self.refs[int(index)] except (IndexError, ValueError): raise CoconutInternalException("no reference at invalid index", index) internal_assert(got_reftype == reftype, "wanted " + reftype + " reference; got " + got_reftype + " reference") 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 wrap_str(self, text, strchar, multiline=False): """Wrap a string."""
if multiline: strchar *= 3 return strwrapper + self.add_ref("str", (text, strchar)) + unwrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wrap_str_of(self, text): """Wrap a string of a string."""
text_repr = ascii(text) internal_assert(text_repr[0] == text_repr[-1] and text_repr[0] in ("'", '"'), "cannot wrap str of", text) return self.wrap_str(text_repr[1:-1], text_repr[-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 wrap_passthrough(self, text, multiline=True): """Wrap a passthrough."""
if not multiline: text = text.lstrip() if multiline: out = "\\" else: out = "\\\\" out += self.add_ref("passthrough", text) + unwrapper if not multiline: out += "\n" return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wrap_comment(self, text, reformat=True): """Wrap a comment."""
if reformat: text = self.reformat(text) return "#" + self.add_ref("comment", text) + unwrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_procs(self, procs, kwargs, inputstring, log=True): """Apply processors to inputstring."""
for get_proc in procs: proc = get_proc(self) inputstring = proc(inputstring, **kwargs) if log: logger.log_tag(proc.__name__, inputstring, multiline=True) return inputstring
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pre(self, inputstring, **kwargs): """Perform pre-processing."""
out = self.apply_procs(self.preprocs, kwargs, str(inputstring)) logger.log_tag("skips", self.skips) return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getheader(self, which, use_hash=None, polish=True): """Get a formatted header."""
header = getheader( which, use_hash=use_hash, target=self.target, no_tco=self.no_tco, strict=self.strict, ) if polish: header = self.polish(header) return header
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_syntax_err(self, err, original): """Make a CoconutSyntaxError from a CoconutDeferredSyntaxError."""
msg, loc = err.args return self.make_err(CoconutSyntaxError, msg, original, 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 make_parse_err(self, err, reformat=True, include_ln=True): """Make a CoconutParseError from a ParseBaseException."""
err_line = err.line err_index = err.col - 1 err_lineno = err.lineno if include_ln else None if reformat: err_line, err_index = self.reformat(err_line, err_index) if err_lineno is not None: err_lineno = self.adjust(err_lineno) return CoconutParseError(None, err_line, err_index, err_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 parse(self, inputstring, parser, preargs, postargs): """Use the parser to parse the inputstring with appropriate setup and teardown."""
self.reset() pre_procd = None with logger.gather_parsing_stats(): try: pre_procd = self.pre(inputstring, **preargs) parsed = parse(parser, pre_procd) out = self.post(parsed, **postargs) except ParseBaseException as err: raise self.make_parse_err(err) except CoconutDeferredSyntaxError as err: internal_assert(pre_procd is not None, "invalid deferred syntax error in pre-processing", err) raise self.make_syntax_err(err, pre_procd) except RuntimeError as err: raise CoconutException( str(err), extra="try again with --recursion-limit greater than the current " + str(sys.getrecursionlimit()), ) if self.strict: for name in self.unused_imports: if name != "*": logger.warn("found unused import", name, extra="disable --strict to dismiss") return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare(self, inputstring, strip=False, nl_at_eof_check=False, **kwargs): """Prepare a string for processing."""
if self.strict and nl_at_eof_check and inputstring and not inputstring.endswith("\n"): end_index = len(inputstring) - 1 if inputstring else 0 raise self.make_err(CoconutStyleError, "missing new line at end of file", inputstring, end_index) original_lines = inputstring.splitlines() if self.keep_lines: self.original_lines = original_lines inputstring = "\n".join(original_lines) if strip: inputstring = inputstring.strip() return inputstring
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def passthrough_proc(self, inputstring, **kwargs): """Process python passthroughs."""
out = [] found = None # store of characters that might be the start of a passthrough hold = None # the contents of the passthrough so far count = None # current parenthetical level (num closes - num opens) multiline = None # if in a passthrough, is it a multiline passthrough skips = self.copy_skips() for i, c in enumerate(append_it(inputstring, "\n")): if hold is not None: # we specify that we only care about parens, not brackets or braces count += paren_change(c, opens="(", closes=")") if count >= 0 and c == hold: out.append(self.wrap_passthrough(found, multiline)) found = None hold = None count = None multiline = None else: if c == "\n": skips = addskip(skips, self.adjust(lineno(i, inputstring))) found += c elif found: if c == "\\": found = "" hold = "\n" count = 0 multiline = False elif c == "(": found = "" hold = ")" count = -1 multiline = True else: out.append("\\" + c) found = None elif c == "\\": found = True else: out.append(c) if hold is not None or found is not None: raise self.make_err(CoconutSyntaxError, "unclosed passthrough", inputstring, i) self.set_skips(skips) return "".join(out)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def leading_whitespace(self, inputstring): """Count leading whitespace."""
count = 0 for i, c in enumerate(inputstring): if c == " ": count += 1 elif c == "\t": count += tabworth - (i % tabworth) else: break if self.indchar is None: self.indchar = c elif c != self.indchar: self.strict_err_or_warn("found mixing of tabs and spaces", inputstring, i) return count
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stmt_lambda_proc(self, inputstring, **kwargs): """Add statement lambda definitions."""
regexes = [] for i in range(len(self.stmt_lambdas)): name = self.stmt_lambda_name(i) regex = compile_regex(r"\b%s\b" % (name,)) regexes.append(regex) out = [] for line in inputstring.splitlines(): for i, regex in enumerate(regexes): if regex.search(line): indent, line = split_leading_indent(line) out.append(indent + self.stmt_lambdas[i]) out.append(line) return "\n".join(out)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reind_proc(self, inputstring, **kwargs): """Add back indentation."""
out = [] level = 0 for line in inputstring.splitlines(): line, comment = split_comment(line.strip()) indent, line = split_leading_indent(line) level += ind_change(indent) if line: line = " " * self.tabideal * level + line line, indent = split_trailing_indent(line) level += ind_change(indent) line = (line + comment).rstrip() out.append(line) if level != 0: complain(CoconutInternalException("non-zero final indentation level", level)) return "\n".join(out)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ln_comment(self, ln): """Get an end line comment. CoconutInternalExceptions should always be caught and complained."""
if self.keep_lines: if not 1 <= ln <= len(self.original_lines) + 1: raise CoconutInternalException( "out of bounds line number", ln, "not in range [1, " + str(len(self.original_lines) + 1) + "]", ) elif ln == len(self.original_lines) + 1: # trim too large lni = -1 else: lni = ln - 1 if self.line_numbers and self.keep_lines: if self.minify: comment = str(ln) + " " + self.original_lines[lni] else: comment = " line " + str(ln) + ": " + self.original_lines[lni] elif self.keep_lines: if self.minify: comment = self.original_lines[lni] else: comment = " " + self.original_lines[lni] elif self.line_numbers: if self.minify: comment = str(ln) else: comment = " line " + str(ln) else: return "" return self.wrap_comment(comment, reformat=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 endline_repl(self, inputstring, reformatting=False, **kwargs): """Add end of line comments."""
out = [] ln = 1 # line number for line in inputstring.splitlines(): add_one_to_ln = False try: if line.endswith(lnwrapper): line, index = line[:-1].rsplit("#", 1) new_ln = self.get_ref("ln", index) if new_ln < ln: raise CoconutInternalException("line number decreased", (ln, new_ln)) ln = new_ln line = line.rstrip() add_one_to_ln = True if not reformatting or add_one_to_ln: # add_one_to_ln here is a proxy for whether there was a ln comment or not line += self.comments.get(ln, "") if not reformatting and line.rstrip() and not line.lstrip().startswith("#"): line += self.ln_comment(ln) except CoconutInternalException as err: complain(err) out.append(line) if add_one_to_ln: ln += 1 return "\n".join(out)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def passthrough_repl(self, inputstring, **kwargs): """Add back passthroughs."""
out = [] index = None for c in append_it(inputstring, None): try: if index is not None: if c is not None and c in nums: index += c elif c == unwrapper and index: ref = self.get_ref("passthrough", index) out.append(ref) index = None elif c != "\\" or index: out.append("\\" + index) if c is not None: out.append(c) index = None elif c is not None: if c == "\\": index = "" else: out.append(c) except CoconutInternalException as err: complain(err) if index is not None: out.append(index) index = None out.append(c) return "".join(out)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def str_repl(self, inputstring, **kwargs): """Add back strings."""
out = [] comment = None string = None for i, c in enumerate(append_it(inputstring, None)): try: if comment is not None: if c is not None and c in nums: comment += c elif c == unwrapper and comment: ref = self.get_ref("comment", comment) if out and not out[-1].endswith("\n"): out[-1] = out[-1].rstrip(" ") if not self.minify: out[-1] += " " # put two spaces before comment out.append("#" + ref) comment = None else: raise CoconutInternalException("invalid comment marker in", getline(i, inputstring)) elif string is not None: if c is not None and c in nums: string += c elif c == unwrapper and string: text, strchar = self.get_ref("str", string) out.append(strchar + text + strchar) string = None else: raise CoconutInternalException("invalid string marker in", getline(i, inputstring)) elif c is not None: if c == "#": comment = "" elif c == strwrapper: string = "" else: out.append(c) except CoconutInternalException as err: complain(err) if comment is not None: out.append(comment) comment = None if string is not None: out.append(string) string = None out.append(c) return "".join(out)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def repl_proc(self, inputstring, log=True, **kwargs): """Process using replprocs."""
return self.apply_procs(self.replprocs, kwargs, inputstring, log=log)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def header_proc(self, inputstring, header="file", initial="initial", use_hash=None, **kwargs): """Add the header."""
pre_header = self.getheader(initial, use_hash=use_hash, polish=False) main_header = self.getheader(header, polish=False) if self.minify: main_header = minify(main_header) return pre_header + self.docstring + main_header + inputstring
<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_docstring(self, loc, tokens): """Set the docstring."""
internal_assert(len(tokens) == 2, "invalid docstring tokens", tokens) self.docstring = self.reformat(tokens[0]) + "\n\n" return tokens[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 yield_from_handle(self, tokens): """Process Python 3.3 yield from."""
internal_assert(len(tokens) == 1, "invalid yield from tokens", tokens) if self.target_info < (3, 3): return ( yield_from_var + " = " + tokens[0] + "\nfor " + yield_item_var + " in " + yield_from_var + ":\n" + openindent + "yield " + yield_item_var + "\n" + closeindent ) else: return "yield from " + tokens[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 endline_handle(self, original, loc, tokens): """Add line number information to end of line."""
internal_assert(len(tokens) == 1, "invalid endline tokens", tokens) lines = tokens[0].splitlines(True) if self.minify: lines = lines[0] out = [] ln = lineno(loc, original) for endline in lines: out.append(self.wrap_line_number(self.adjust(ln)) + endline) ln += 1 return "".join(out)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def comment_handle(self, original, loc, tokens): """Store comment in comments."""
internal_assert(len(tokens) == 1, "invalid comment tokens", tokens) ln = self.adjust(lineno(loc, original)) internal_assert(lambda: ln not in self.comments, "multiple comments on line", ln) self.comments[ln] = tokens[0] return ""
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def augassign_handle(self, tokens): """Process assignments."""
internal_assert(len(tokens) == 3, "invalid assignment tokens", tokens) name, op, item = tokens out = "" if op == "|>=": out += name + " = (" + item + ")(" + name + ")" elif op == "|*>=": out += name + " = (" + item + ")(*" + name + ")" elif op == "<|=": out += name + " = " + name + "((" + item + "))" elif op == "<*|=": out += name + " = " + name + "(*(" + item + "))" elif op == "..=" or op == "<..=": out += name + " = _coconut_forward_compose((" + item + "), " + name + ")" elif op == "..>=": out += name + " = _coconut_forward_compose(" + name + ", (" + item + "))" elif op == "<*..=": out += name + " = _coconut_forward_star_compose((" + item + "), " + name + ")" elif op == "..*>=": out += name + " = _coconut_forward_star_compose(" + name + ", (" + item + "))" elif op == "??=": out += name + " = " + item + " if " + name + " is None else " + name elif op == "::=": ichain_var = lazy_chain_var + "_" + str(self.ichain_count) self.ichain_count += 1 # this is necessary to prevent a segfault caused by self-reference out += ( ichain_var + " = " + name + "\n" + name + " = _coconut.itertools.chain.from_iterable(" + lazy_list_handle([ichain_var, "(" + item + ")"]) + ")" ) else: out += name + " " + op + " " + item return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def classlist_handle(self, original, loc, tokens): """Process class inheritance lists."""
if len(tokens) == 0: if self.target.startswith("3"): return "" else: return "(_coconut.object)" elif len(tokens) == 1 and len(tokens[0]) == 1: if "tests" in tokens[0]: if self.strict and tokens[0][0] == "(object)": raise self.make_err(CoconutStyleError, "unnecessary inheriting from object (Coconut does this automatically)", original, loc) return tokens[0][0] elif "args" in tokens[0]: if self.target.startswith("3"): return tokens[0][0] else: raise self.make_err(CoconutTargetError, "found Python 3 keyword class definition", original, loc, target="3") else: raise CoconutInternalException("invalid inner classlist token", tokens[0]) else: raise CoconutInternalException("invalid classlist tokens", tokens)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_handle(self, original, loc, tokens): """Universalizes imports."""
if len(tokens) == 1: imp_from, imports = None, tokens[0] elif len(tokens) == 2: imp_from, imports = tokens if imp_from == "__future__": self.strict_err_or_warn("unnecessary from __future__ import (Coconut does these automatically)", original, loc) return "" else: raise CoconutInternalException("invalid import tokens", tokens) if self.strict: self.unused_imports.update(imported_names(imports)) return universal_import(imports, imp_from=imp_from, target=self.target)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def complex_raise_stmt_handle(self, tokens): """Process Python 3 raise from statement."""
internal_assert(len(tokens) == 2, "invalid raise from tokens", tokens) if self.target.startswith("3"): return "raise " + tokens[0] + " from " + tokens[1] else: return ( raise_from_var + " = " + tokens[0] + "\n" + raise_from_var + ".__cause__ = " + tokens[1] + "\n" + "raise " + raise_from_var )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dict_comp_handle(self, loc, tokens): """Process Python 2.7 dictionary comprehension."""
internal_assert(len(tokens) == 3, "invalid dictionary comprehension tokens", tokens) if self.target.startswith("3"): key, val, comp = tokens return "{" + key + ": " + val + " " + comp + "}" else: key, val, comp = tokens return "dict(((" + key + "), (" + val + ")) " + comp + ")"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pattern_error(self, original, loc, value_var, check_var): """Construct a pattern-matching error message."""
base_line = clean(self.reformat(getline(loc, original))) line_wrap = self.wrap_str_of(base_line) repr_wrap = self.wrap_str_of(ascii(base_line)) return ( "if not " + check_var + ":\n" + openindent + match_err_var + ' = _coconut_MatchError("pattern-matching failed for " ' + repr_wrap + ' " in " + _coconut.repr(_coconut.repr(' + value_var + ")))\n" + match_err_var + ".pattern = " + line_wrap + "\n" + match_err_var + ".value = " + value_var + "\nraise " + match_err_var + "\n" + closeindent )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def destructuring_stmt_handle(self, original, loc, tokens): """Process match assign blocks."""
internal_assert(len(tokens) == 2, "invalid destructuring assignment tokens", tokens) matches, item = tokens out = match_handle(loc, [matches, "in", item, None]) out += self.pattern_error(original, loc, match_to_var, match_check_var) return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def name_match_funcdef_handle(self, original, loc, tokens): """Process match defs. Result must be passed to insert_docstring_handle."""
if len(tokens) == 2: func, matches = tokens cond = None elif len(tokens) == 3: func, matches, cond = tokens else: raise CoconutInternalException("invalid match function definition tokens", tokens) matcher = Matcher(loc, match_check_var) req_args, def_args, star_arg, kwd_args, dubstar_arg = split_args_list(matches, loc) matcher.match_function(match_to_args_var, match_to_kwargs_var, req_args + def_args, star_arg, kwd_args, dubstar_arg) if cond is not None: matcher.add_guard(cond) before_docstring = ( "def " + func + "(*" + match_to_args_var + ", **" + match_to_kwargs_var + "):\n" + openindent ) after_docstring = ( match_check_var + " = False\n" + matcher.out() # we only include match_to_args_var here because match_to_kwargs_var is modified during matching + self.pattern_error(original, loc, match_to_args_var, match_check_var) + closeindent ) return before_docstring, after_docstring
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def op_match_funcdef_handle(self, original, loc, tokens): """Process infix match defs. Result must be passed to insert_docstring_handle."""
if len(tokens) == 3: func, args = get_infix_items(tokens) cond = None elif len(tokens) == 4: func, args = get_infix_items(tokens[:-1]) cond = tokens[-1] else: raise CoconutInternalException("invalid infix match function definition tokens", tokens) name_tokens = [func, args] if cond is not None: name_tokens.append(cond) return self.name_match_funcdef_handle(original, loc, name_tokens)
<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_literal_handle(self, tokens): """Converts set literals to the right form for the target Python."""
internal_assert(len(tokens) == 1 and len(tokens[0]) == 1, "invalid set literal tokens", tokens) if self.target_info < (2, 7): return "_coconut.set(" + set_to_tuple(tokens[0]) + ")" else: return "{" + tokens[0][0] + "}"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_letter_literal_handle(self, tokens): """Process set literals."""
if len(tokens) == 1: set_type = tokens[0] if set_type == "s": return "_coconut.set()" elif set_type == "f": return "_coconut.frozenset()" else: raise CoconutInternalException("invalid set type", set_type) elif len(tokens) == 2: set_type, set_items = tokens internal_assert(len(set_items) == 1, "invalid set literal item", tokens[0]) if set_type == "s": return self.set_literal_handle([set_items]) elif set_type == "f": return "_coconut.frozenset(" + set_to_tuple(set_items) + ")" else: raise CoconutInternalException("invalid set type", set_type) else: raise CoconutInternalException("invalid set literal tokens", tokens)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exec_stmt_handle(self, tokens): """Process Python-3-style exec statements."""
internal_assert(1 <= len(tokens) <= 3, "invalid exec statement tokens", tokens) if self.target.startswith("2"): out = "exec " + tokens[0] if len(tokens) > 1: out += " in " + ", ".join(tokens[1:]) return out else: return "exec(" + ", ".join(tokens) + ")"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stmt_lambdef_handle(self, original, loc, tokens): """Process multi-line lambdef statements."""
if len(tokens) == 2: params, stmts = tokens elif len(tokens) == 3: params, stmts, last = tokens if "tests" in tokens: stmts = stmts.asList() + ["return " + last] else: stmts = stmts.asList() + [last] else: raise CoconutInternalException("invalid statement lambda tokens", tokens) name = self.stmt_lambda_name() body = openindent + self.stmt_lambda_proc("\n".join(stmts)) + closeindent if isinstance(params, str): self.stmt_lambdas.append( "def " + name + params + ":\n" + body, ) else: params.insert(0, name) # construct match tokens self.stmt_lambdas.append( "".join(self.name_match_funcdef_handle(original, loc, params)) + body, ) return 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 complain_on_err(self): """Complain about any parsing-related errors raised inside."""
try: yield except ParseBaseException as err: complain(self.make_parse_err(err, reformat=False, include_ln=False)) except CoconutException as err: complain(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 split_docstring(self, block): """Split a code block into a docstring and a body."""
try: first_line, rest_of_lines = block.split("\n", 1) except ValueError: pass else: raw_first_line = split_leading_trailing_indent(rem_comment(first_line))[1] if match_in(self.just_a_string, raw_first_line): return first_line, rest_of_lines return None, block
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tre_return(self, func_name, func_args, func_store, use_mock=True): """Generate grammar element that matches a string which is just a TRE return statement."""
def tre_return_handle(loc, tokens): internal_assert(len(tokens) == 1, "invalid tail recursion elimination tokens", tokens) args = tokens[0][1:-1] # strip parens # check if there is anything in the arguments that will store a reference # to the current scope, and if so, abort TRE, since it can't handle that if match_in(self.stores_scope, args): return ignore_transform # this is the only way to make the outer transform call return None if self.no_tco: tco_recurse = "return " + func_name + "(" + args + ")" else: tco_recurse = "return _coconut_tail_call(" + func_name + (", " + args if args else "") + ")" if not func_args or func_args == args: tre_recurse = "continue" elif use_mock: tre_recurse = func_args + " = " + tre_mock_var + "(" + args + ")" + "\ncontinue" else: tre_recurse = func_args + " = " + args + "\ncontinue" return ( "try:\n" + openindent + tre_check_var + " = " + func_name + " is " + func_store + "\n" + closeindent + "except _coconut.NameError:\n" + openindent + tre_check_var + " = False\n" + closeindent + "if " + tre_check_var + ":\n" + openindent + tre_recurse + "\n" + closeindent + "else:\n" + openindent + tco_recurse + "\n" + closeindent ) return attach( self.start_marker + (keyword("return") + keyword(func_name)).suppress() + self.parens + self.end_marker, tre_return_handle, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transform_returns(self, raw_lines, tre_return_grammar=None, use_mock=None, is_async=False): """Apply TCO, TRE, or async universalization to the given function."""
lines = [] # transformed lines tco = False # whether tco was done tre = False # whether tre was done level = 0 # indentation level disabled_until_level = None # whether inside of a disabled block attempt_tre = tre_return_grammar is not None # whether to even attempt tre attempt_tco = not is_async and not self.no_tco # whether to even attempt tco if is_async: internal_assert(not attempt_tre and not attempt_tco, "cannot tail call optimize async functions") for line in raw_lines: indent, body, dedent = split_leading_trailing_indent(line) base, comment = split_comment(body) level += ind_change(indent) if disabled_until_level is not None: if level <= disabled_until_level: disabled_until_level = None if disabled_until_level is None: # tco and tre don't support generators if not is_async and self.yield_regex.search(body): lines = raw_lines # reset lines break # don't touch inner functions elif self.def_regex.match(body): disabled_until_level = level # tco and tre shouldn't touch scopes that depend on actual return statements # or scopes where we can't insert a continue elif not is_async and self.tre_disable_regex.match(body): disabled_until_level = level else: if is_async: if self.return_regex.match(base): to_return = base[len("return"):].strip() if to_return: # leave empty return statements alone line = indent + "raise _coconut.asyncio.Return(" + to_return + ")" + comment + dedent tre_base = None if attempt_tre: with self.complain_on_err(): tre_base = transform(tre_return_grammar, base) if tre_base is not None: line = indent + tre_base + comment + dedent tre = True # when tco is available, tre falls back on it if the function is changed tco = not self.no_tco if attempt_tco and tre_base is None: # don't attempt tco if tre succeeded tco_base = None with self.complain_on_err(): tco_base = transform(self.tco_return, base) if tco_base is not None: line = indent + tco_base + comment + dedent tco = True level += ind_change(dedent) lines.append(line) func_code = "".join(lines) if is_async: return func_code else: return func_code, tco, tre
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decoratable_funcdef_stmt_handle(self, original, loc, tokens, is_async=False): """Determines if TCO or TRE can be done and if so does it, handles dotted function names, and universalizes async functions."""
if len(tokens) == 1: decorators, funcdef = "", tokens[0] elif len(tokens) == 2: decorators, funcdef = tokens else: raise CoconutInternalException("invalid function definition tokens", tokens) # extract information about the function raw_lines = funcdef.splitlines(True) def_stmt = raw_lines.pop(0) func_name, func_args, func_params = None, None, None with self.complain_on_err(): func_name, func_args, func_params = parse(self.split_func_name_args_params, def_stmt) undotted_name = None # the function __name__ if func_name is a dotted name if func_name is not None: if "." in func_name: undotted_name = func_name.rsplit(".", 1)[-1] def_stmt = def_stmt.replace(func_name, undotted_name) # handle async functions if is_async: if not self.target: raise self.make_err( CoconutTargetError, "async function definition requires a specific target", original, loc, target="sys", ) elif self.target_info >= (3, 5): def_stmt = "async " + def_stmt else: decorators += "@_coconut.asyncio.coroutine\n" # only Python 3.3+ supports returning values inside generators if self.target_info < (3, 3): func_code = self.transform_returns(raw_lines, is_async=True) else: func_code = "".join(raw_lines) # handle normal functions else: # tre does not work with decorators, though tco does attempt_tre = func_name is not None and not decorators if attempt_tre: use_mock = func_args and func_args != func_params[1:-1] func_store = tre_store_var + "_" + str(self.tre_store_count) self.tre_store_count += 1 tre_return_grammar = self.tre_return(func_name, func_args, func_store, use_mock) else: use_mock = func_store = tre_return_grammar = None func_code, tco, tre = self.transform_returns( raw_lines, tre_return_grammar, use_mock, ) if tre: comment, rest = split_leading_comment(func_code) indent, base, dedent = split_leading_trailing_indent(rest, 1) base, base_dedent = split_trailing_indent(base) docstring, base = self.split_docstring(base) func_code = ( comment + indent + (docstring + "\n" if docstring is not None else "") + ( "def " + tre_mock_var + func_params + ": return " + func_args + "\n" if use_mock else "" ) + "while True:\n" + openindent + base + base_dedent + ("\n" if "\n" not in base_dedent else "") + "return None" + ("\n" if "\n" not in dedent else "") + closeindent + dedent + func_store + " = " + (func_name if undotted_name is None else undotted_name) + "\n" ) if tco: decorators += "@_coconut_tco\n" # binds most tightly out = decorators + def_stmt + func_code if undotted_name is not None: out += func_name + " = " + undotted_name + "\n" return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def await_item_handle(self, original, loc, tokens): """Check for Python 3.5 await expression."""
internal_assert(len(tokens) == 1, "invalid await statement tokens", tokens) if not self.target: self.make_err( CoconutTargetError, "await requires a specific target", original, loc, target="sys", ) elif self.target_info >= (3, 5): return "await " + tokens[0] elif self.target_info >= (3, 3): return "(yield from " + tokens[0] + ")" else: return "(yield _coconut.asyncio.From(" + tokens[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 typedef_handle(self, tokens): """Process Python 3 type annotations."""
if len(tokens) == 1: # return typedef if self.target.startswith("3"): return " -> " + self.wrap_typedef(tokens[0]) + ":" else: return ":\n" + self.wrap_comment(" type: (...) -> " + tokens[0]) else: # argument typedef if len(tokens) == 3: varname, typedef, comma = tokens default = "" elif len(tokens) == 4: varname, typedef, default, comma = tokens else: raise CoconutInternalException("invalid type annotation tokens", tokens) if self.target.startswith("3"): return varname + ": " + self.wrap_typedef(typedef) + default + comma else: return varname + default + comma + self.wrap_passthrough(self.wrap_comment(" type: " + typedef) + "\n" + " " * self.tabideal)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def typed_assign_stmt_handle(self, tokens): """Process Python 3.6 variable type annotations."""
if len(tokens) == 2: if self.target_info >= (3, 6): return tokens[0] + ": " + self.wrap_typedef(tokens[1]) else: return tokens[0] + " = None" + self.wrap_comment(" type: " + tokens[1]) elif len(tokens) == 3: if self.target_info >= (3, 6): return tokens[0] + ": " + self.wrap_typedef(tokens[1]) + " = " + tokens[2] else: return tokens[0] + " = " + tokens[2] + self.wrap_comment(" type: " + tokens[1]) else: raise CoconutInternalException("invalid variable type annotation tokens", tokens)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def with_stmt_handle(self, tokens): """Process with statements."""
internal_assert(len(tokens) == 2, "invalid with statement tokens", tokens) withs, body = tokens if len(withs) == 1 or self.target_info >= (2, 7): return "with " + ", ".join(withs) + body else: return ( "".join("with " + expr + ":\n" + openindent for expr in withs[:-1]) + "with " + withs[-1] + body + closeindent * (len(withs) - 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 case_stmt_handle(self, loc, tokens): """Process case blocks."""
if len(tokens) == 2: item, cases = tokens default = None elif len(tokens) == 3: item, cases, default = tokens else: raise CoconutInternalException("invalid case tokens", tokens) check_var = case_check_var + "_" + str(self.case_check_count) self.case_check_count += 1 out = ( match_to_var + " = " + item + "\n" + match_case_tokens(loc, cases[0], check_var, True) ) for case in cases[1:]: out += ( "if not " + check_var + ":\n" + openindent + match_case_tokens(loc, case, check_var, False) + closeindent ) if default is not None: out += "if not " + check_var + default return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lambdef_check(self, original, loc, tokens): """Check for Python-style lambdas."""
return self.check_strict("Python-style lambda", original, loc, tokens)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def endline_semicolon_check(self, original, loc, tokens): """Check for semicolons at the end of lines."""
return self.check_strict("semicolon at end of line", original, loc, tokens)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def u_string_check(self, original, loc, tokens): """Check for Python2-style unicode strings."""
return self.check_strict("Python-2-style unicode string", original, loc, tokens)
<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_py(self, version, name, original, loc, tokens): """Check for Python-version-specific syntax."""
internal_assert(len(tokens) == 1, "invalid " + name + " tokens", tokens) if self.target_info < get_target_info(version): raise self.make_err(CoconutTargetError, "found Python " + ".".join(version) + " " + name, original, loc, target=version) else: return tokens[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 name_check(self, original, loc, tokens): """Check the given base name."""
internal_assert(len(tokens) == 1, "invalid name tokens", tokens) if self.strict: self.unused_imports.discard(tokens[0]) if tokens[0] == "exec": return self.check_py("3", "exec function", original, loc, tokens) elif tokens[0].startswith(reserved_prefix): raise self.make_err(CoconutSyntaxError, "variable names cannot start with reserved prefix " + reserved_prefix, original, loc) else: return tokens[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 nonlocal_check(self, original, loc, tokens): """Check for Python 3 nonlocal statement."""
return self.check_py("3", "nonlocal statement", original, loc, tokens)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def star_assign_item_check(self, original, loc, tokens): """Check for Python 3 starred assignment."""
return self.check_py("3", "starred assignment (add 'match' to front to produce universal code)", original, loc, tokens)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def star_expr_check(self, original, loc, tokens): """Check for Python 3.5 star unpacking."""
return self.check_py("35", "star unpacking (add 'match' to front to produce universal code)", original, loc, tokens)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def star_sep_check(self, original, loc, tokens): """Check for Python 3 keyword-only arguments."""
return self.check_py("3", "keyword-only argument separator (add 'match' to front to produce universal code)", original, loc, tokens)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def matrix_at_check(self, original, loc, tokens): """Check for Python 3.5 matrix multiplication."""
return self.check_py("35", "matrix multiplication", original, loc, tokens)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def async_comp_check(self, original, loc, tokens): """Check for Python 3.6 async comprehension."""
return self.check_py("36", "async comprehension", original, loc, tokens)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def f_string_check(self, original, loc, tokens): """Handle Python 3.6 format strings."""
return self.check_py("36", "format string", original, loc, tokens)
<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_file(self, inputstring, addhash=True): """Parse file code."""
if addhash: use_hash = self.genhash(False, inputstring) else: use_hash = None return self.parse(inputstring, self.file_parser, {"nl_at_eof_check": True}, {"header": "file", "use_hash": use_hash})
<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_package(self, inputstring, addhash=True): """Parse package code."""
if addhash: use_hash = self.genhash(True, inputstring) else: use_hash = None return self.parse(inputstring, self.file_parser, {"nl_at_eof_check": True}, {"header": "package", "use_hash": use_hash})
<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_debug(self, inputstring): """Parse debug code."""
return self.parse(inputstring, self.file_parser, {"strip": True}, {"header": "none", "initial": "none", "final_endline": 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_match_names(match): """Gets keyword names for the given match."""
names = [] if "paren" in match: (match,) = match names += get_match_names(match) elif "var" in match: (setvar,) = match if setvar != wildcard: names.append(setvar) elif "trailer" in match: match, trailers = match[0], match[1:] for i in range(0, len(trailers), 2): op, arg = trailers[i], trailers[i + 1] if op == "as": names.append(arg) names += get_match_names(match) return names
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def duplicate(self): """Duplicates the matcher to others."""
other = Matcher(self.loc, self.check_var, self.checkdefs, self.names, self.var_index) other.insert_check(0, "not " + self.check_var) self.others.append(other) return other
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_checks(self, position=None): """Gets the checks at the position."""
if position is None: position = self.position return self.checkdefs[position][0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_checks(self, checks, position=None): """Sets the checks at the position."""
if position is None: position = self.position self.checkdefs[position][0] = checks
<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_defs(self, position=None): """Gets the defs at the position."""
if position is None: position = self.position return self.checkdefs[position][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 set_defs(self, defs, position=None): """Sets the defs at the position."""
if position is None: position = self.position self.checkdefs[position][1] = defs
<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_check(self, check_item): """Adds a check universally."""
self.checks.append(check_item) for other in self.others: other.add_check(check_item)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_def(self, def_item): """Adds a def universally."""
self.defs.append(def_item) for other in self.others: other.add_def(def_item)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert_check(self, index, check_item): """Inserts a check universally."""
self.checks.insert(index, check_item) for other in self.others: other.insert_check(index, check_item)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert_def(self, index, def_item): """Inserts a def universally."""
self.defs.insert(index, def_item) for other in self.others: other.insert_def(index, def_item)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_position(self, position): """Sets the if-statement position."""
if position < 0: position += len(self.checkdefs) while position >= len(self.checkdefs): self.checkdefs.append(([], [])) self.position = position