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 only_self(self): """Only match in self not others."""
others, self.others = self.others, [] try: yield finally: self.others = others + self.others
<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_var(self): """Gets the next match_temp_var."""
tempvar = match_temp_var + "_" + str(self.var_index) self.var_index += 1 return tempvar
<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_all_in(self, matches, item): """Matches all matches to elements of item."""
for i, match in enumerate(matches): self.match(match, item + "[" + str(i) + "]")
<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_function(self, args, kwargs, match_args=(), star_arg=None, kwd_args=(), dubstar_arg=None): """Matches a pattern-matching function."""
self.match_in_args_kwargs(match_args, args, kwargs, allow_star_args=star_arg is not None) if star_arg is not None: self.match(star_arg, args + "[" + str(len(match_args)) + ":]") self.match_in_kwargs(kwd_args, kwargs) with self.down_a_level(): if dubstar_arg is None: self.add_check("not " + kwargs) else: self.match(dubstar_arg, 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 match_in_kwargs(self, match_args, kwargs): """Matches against kwargs."""
for match, default in match_args: names = get_match_names(match) if names: tempvar = self.get_temp_var() self.add_def( tempvar + " = " + "".join( kwargs + '.pop("' + name + '") if "' + name + '" in ' + kwargs + " else " for name in names ) + default, ) with self.down_a_level(): self.match(match, tempvar) else: raise CoconutDeferredSyntaxError("keyword-only pattern-matching function arguments must have names", self.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 match_dict(self, tokens, item): """Matches a dictionary."""
if len(tokens) == 1: matches, rest = tokens[0], None else: matches, rest = tokens self.add_check("_coconut.isinstance(" + item + ", _coconut.abc.Mapping)") if rest is None: self.add_check("_coconut.len(" + item + ") == " + str(len(matches))) if matches: self.use_sentinel = True for k, v in matches: key_var = self.get_temp_var() self.add_def(key_var + " = " + item + ".get(" + k + ", " + sentinel_var + ")") with self.down_a_level(): self.add_check(key_var + " is not " + sentinel_var) self.match(v, key_var) if rest is not None and rest != wildcard: match_keys = [k for k, v in matches] with self.down_a_level(): self.add_def( rest + " = dict((k, v) for k, v in " + item + ".items() if k not in set((" + ", ".join(match_keys) + ("," if len(match_keys) == 1 else "") + ")))", )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assign_to_series(self, name, series_type, item): """Assign name to item converted to the given series_type."""
if series_type == "(": self.add_def(name + " = _coconut.tuple(" + item + ")") elif series_type == "[": self.add_def(name + " = _coconut.list(" + item + ")") else: raise CoconutInternalException("invalid series match type", series_type)
<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_sequence(self, tokens, item): """Matches a sequence."""
tail = None if len(tokens) == 2: series_type, matches = tokens else: series_type, matches, tail = tokens self.add_check("_coconut.isinstance(" + item + ", _coconut.abc.Sequence)") if tail is None: self.add_check("_coconut.len(" + item + ") == " + str(len(matches))) else: self.add_check("_coconut.len(" + item + ") >= " + str(len(matches))) if tail != wildcard: if len(matches) > 0: splice = "[" + str(len(matches)) + ":]" else: splice = "" self.assign_to_series(tail, series_type, item + splice) self.match_all_in(matches, 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 match_iterator(self, tokens, item): """Matches a lazy list or a chain."""
tail = None if len(tokens) == 2: _, matches = tokens else: _, matches, tail = tokens self.add_check("_coconut.isinstance(" + item + ", _coconut.abc.Iterable)") if tail is None: itervar = self.get_temp_var() self.add_def(itervar + " = _coconut.tuple(" + item + ")") elif matches: itervar = self.get_temp_var() if tail == wildcard: tail = item else: self.add_def(tail + " = _coconut.iter(" + item + ")") self.add_def(itervar + " = _coconut.tuple(_coconut_igetitem(" + tail + ", _coconut.slice(None, " + str(len(matches)) + ")))") else: itervar = None if tail != wildcard: self.add_def(tail + " = " + item) if itervar is not None: with self.down_a_level(): self.add_check("_coconut.len(" + itervar + ") == " + str(len(matches))) self.match_all_in(matches, itervar)
<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_star(self, tokens, item): """Matches starred assignment."""
head_matches, last_matches = None, None if len(tokens) == 1: middle = tokens[0] elif len(tokens) == 2: if isinstance(tokens[0], str): middle, last_matches = tokens else: head_matches, middle = tokens else: head_matches, middle, last_matches = tokens self.add_check("_coconut.isinstance(" + item + ", _coconut.abc.Iterable)") if head_matches is None and last_matches is None: if middle != wildcard: self.add_def(middle + " = _coconut.list(" + item + ")") else: itervar = self.get_temp_var() self.add_def(itervar + " = _coconut.list(" + item + ")") with self.down_a_level(): req_length = (len(head_matches) if head_matches is not None else 0) + (len(last_matches) if last_matches is not None else 0) self.add_check("_coconut.len(" + itervar + ") >= " + str(req_length)) if middle != wildcard: head_splice = str(len(head_matches)) if head_matches is not None else "" last_splice = "-" + str(len(last_matches)) if last_matches is not None else "" self.add_def(middle + " = " + itervar + "[" + head_splice + ":" + last_splice + "]") if head_matches is not None: self.match_all_in(head_matches, itervar) if last_matches is not None: for x in range(1, len(last_matches) + 1): self.match(last_matches[-x], itervar + "[-" + str(x) + "]")
<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_rsequence(self, tokens, item): """Matches a reverse sequence."""
front, series_type, matches = tokens self.add_check("_coconut.isinstance(" + item + ", _coconut.abc.Sequence)") self.add_check("_coconut.len(" + item + ") >= " + str(len(matches))) if front != wildcard: if len(matches): splice = "[:" + str(-len(matches)) + "]" else: splice = "" self.assign_to_series(front, series_type, item + splice) for i, match in enumerate(matches): self.match(match, item + "[" + str(i - len(matches)) + "]")
<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_msequence(self, tokens, item): """Matches a middle sequence."""
series_type, head_matches, middle, _, last_matches = tokens self.add_check("_coconut.isinstance(" + item + ", _coconut.abc.Sequence)") self.add_check("_coconut.len(" + item + ") >= " + str(len(head_matches) + len(last_matches))) if middle != wildcard: if len(head_matches) and len(last_matches): splice = "[" + str(len(head_matches)) + ":" + str(-len(last_matches)) + "]" elif len(head_matches): splice = "[" + str(len(head_matches)) + ":]" elif len(last_matches): splice = "[:" + str(-len(last_matches)) + "]" else: splice = "" self.assign_to_series(middle, series_type, item + splice) self.match_all_in(head_matches, item) for i, match in enumerate(last_matches): self.match(match, item + "[" + str(i - len(last_matches)) + "]")
<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_string(self, tokens, item): """Match prefix string."""
prefix, name = tokens return self.match_mstring((prefix, name, None), item, use_bytes=prefix.startswith("b"))
<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_rstring(self, tokens, item): """Match suffix string."""
name, suffix = tokens return self.match_mstring((None, name, suffix), item, use_bytes=suffix.startswith("b"))
<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_mstring(self, tokens, item, use_bytes=None): """Match prefix and suffix string."""
prefix, name, suffix = tokens if use_bytes is None: if prefix.startswith("b") or suffix.startswith("b"): if prefix.startswith("b") and suffix.startswith("b"): use_bytes = True else: raise CoconutDeferredSyntaxError("string literals and byte literals cannot be added in patterns", self.loc) if use_bytes: self.add_check("_coconut.isinstance(" + item + ", _coconut.bytes)") else: self.add_check("_coconut.isinstance(" + item + ", _coconut.str)") if prefix is not None: self.add_check(item + ".startswith(" + prefix + ")") if suffix is not None: self.add_check(item + ".endswith(" + suffix + ")") if name != wildcard: self.add_def( name + " = " + item + "[" + ("" if prefix is None else "_coconut.len(" + prefix + ")") + ":" + ("" if suffix is None else "-_coconut.len(" + suffix + ")") + "]", )
<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_const(self, tokens, item): """Matches a constant."""
match, = tokens if match in const_vars: self.add_check(item + " is " + match) else: self.add_check(item + " == " + match)
<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_var(self, tokens, item): """Matches a variable."""
setvar, = tokens if setvar != wildcard: if setvar in self.names: self.add_check(self.names[setvar] + " == " + item) else: self.add_def(setvar + " = " + item) self.names[setvar] = 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 match_set(self, tokens, item): """Matches a set."""
match, = tokens self.add_check("_coconut.isinstance(" + item + ", _coconut.abc.Set)") self.add_check("_coconut.len(" + item + ") == " + str(len(match))) for const in match: self.add_check(const + " in " + 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 match_data(self, tokens, item): """Matches a data type."""
if len(tokens) == 2: data_type, matches = tokens star_match = None elif len(tokens) == 3: data_type, matches, star_match = tokens else: raise CoconutInternalException("invalid data match tokens", tokens) self.add_check("_coconut.isinstance(" + item + ", " + data_type + ")") if star_match is None: self.add_check("_coconut.len(" + item + ") == " + str(len(matches))) elif len(matches): self.add_check("_coconut.len(" + item + ") >= " + str(len(matches))) self.match_all_in(matches, item) if star_match is not None: self.match(star_match, item + "[" + str(len(matches)) + ":]")
<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_paren(self, tokens, item): """Matches a paren."""
match, = tokens return self.match(match, 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 match_trailer(self, tokens, item): """Matches typedefs and as patterns."""
internal_assert(len(tokens) > 1 and len(tokens) % 2 == 1, "invalid trailer match tokens", tokens) match, trailers = tokens[0], tokens[1:] for i in range(0, len(trailers), 2): op, arg = trailers[i], trailers[i + 1] if op == "is": self.add_check("_coconut.isinstance(" + item + ", " + arg + ")") elif op == "as": if arg in self.names: self.add_check(self.names[arg] + " == " + item) elif arg != wildcard: self.add_def(arg + " = " + item) self.names[arg] = item else: raise CoconutInternalException("invalid trailer match operation", op) self.match(match, 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 match_and(self, tokens, item): """Matches and."""
for match in tokens: self.match(match, 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 match_or(self, tokens, item): """Matches or."""
for x in range(1, len(tokens)): self.duplicate().match(tokens[x], item) with self.only_self(): self.match(tokens[0], 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 match(self, tokens, item): """Performs pattern-matching processing."""
for flag, get_handler in self.matchers.items(): if flag in tokens: return get_handler(self)(tokens, item) raise CoconutInternalException("invalid pattern-matching 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 out(self): """Return pattern-matching code."""
out = "" if self.use_sentinel: out += sentinel_var + " = _coconut.object()\n" closes = 0 for checks, defs in self.checkdefs: if checks: out += "if " + paren_join(checks, "and") + ":\n" + openindent closes += 1 if defs: out += "\n".join(defs) + "\n" return out + ( self.check_var + " = True\n" + closeindent * closes + "".join(other.out() for other in self.others) + ( "if " + self.check_var + " and not (" + paren_join(self.guards, "and") + "):\n" + openindent + self.check_var + " = False\n" + closeindent if self.guards else "" ) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build(self, stmts=None, set_check_var=True, invert=False): """Construct code for performing the match then executing stmts."""
out = "" if set_check_var: out += self.check_var + " = False\n" out += self.out() if stmts is not None: out += "if " + ("not " if invert else "") + self.check_var + ":" + "\n" + openindent + "".join(stmts) + closeindent 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 _indent(code, by=1): """Indents every nonempty line of the given code."""
return "".join( (" " * by if line else "") + line for line in code.splitlines(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 clean(inputline, strip=True, rem_indents=True, encoding_errors="replace"): """Clean and strip a line."""
stdout_encoding = get_encoding(sys.stdout) inputline = str(inputline) if rem_indents: inputline = inputline.replace(openindent, "").replace(closeindent, "") if strip: inputline = inputline.strip() return inputline.encode(stdout_encoding, encoding_errors).decode(stdout_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 displayable(inputstr, strip=True): """Make a string displayable with minimal loss of information."""
return clean(str(inputstr), strip, rem_indents=False, encoding_errors="backslashreplace")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def internal_assert(condition, message=None, item=None, extra=None): """Raise InternalException if condition is False. If condition is a function, execute it on DEVELOP only."""
if DEVELOP and callable(condition): condition = condition() if not condition: if message is None: message = "assertion failed" if item is None: item = condition raise CoconutInternalException(message, item, extra)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def message(self, message, item, extra): """Uses arguments to create the message."""
if item is not None: message += ": " + ascii(item) if extra is not None: message += " (" + str(extra) + ")" 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 message(self, message, source, point, ln): """Creates a SyntaxError-like message."""
if message is None: message = "parsing failed" if ln is not None: message += " (line " + str(ln) + ")" if source: if point is None: message += "\n" + " " * taberrfmt + clean(source) else: part = clean(source.splitlines()[lineno(point, source) - 1], False).lstrip() point -= len(source) - len(part) # adjust all points based on lstrip part = part.rstrip() # adjust only points that are too large based on rstrip message += "\n" + " " * taberrfmt + part if point > 0: if point >= len(part): point = len(part) - 1 message += "\n" + " " * (taberrfmt + point) + "^" 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 syntax_err(self): """Creates a SyntaxError."""
args = self.args[:2] + (None, None) + self.args[4:] err = SyntaxError(self.message(*args)) err.offset = args[2] err.lineno = args[3] return 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 message(self, message, item, extra): """Creates the Coconut internal exception message."""
return ( super(CoconutInternalException, self).message(message, item, extra) + " " + report_this_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 memoized_parse_block(code): """Memoized version of parse_block."""
success, result = parse_block_memo.get(code, (None, None)) if success is None: try: parsed = COMPILER.parse_block(code) except Exception as err: success, result = False, err else: success, result = True, parsed parse_block_memo[code] = (success, result) if success: return result else: raise 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 patched_nested_parse(self, *args, **kwargs): """Sets match_titles then calls stored_nested_parse."""
kwargs["match_titles"] = True return self.stored_nested_parse(*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 auto_code_block(self, *args, **kwargs): """Modified auto_code_block that patches nested_parse."""
self.stored_nested_parse = self.state_machine.state.nested_parse self.state_machine.state.nested_parse = self.patched_nested_parse try: return super(PatchedAutoStructify, self).auto_code_block(*args, **kwargs) finally: self.state_machine.state.nested_parse = self.stored_nested_parse
<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, *args, **kwargs): """Set parameters for the compiler."""
if self.comp is None: self.comp = Compiler(*args, **kwargs) else: self.comp.setup(*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 exit_on_error(self): """Exit if exit_code is abnormal."""
if self.exit_code: if self.errmsg is not None: logger.show("Exiting due to " + self.errmsg + ".") self.errmsg = None if self.using_jobs: kill_children() sys.exit(self.exit_code)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_error(self, code=1, errmsg=None): """Update the exit code."""
if errmsg is not None: if self.errmsg is None: self.errmsg = errmsg elif errmsg not in self.errmsg: self.errmsg += ", " + errmsg if code is not None: self.exit_code = max(self.exit_code, code)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handling_exceptions(self): """Perform proper exception handling."""
try: if self.using_jobs: with handling_broken_process_pool(): yield else: yield except SystemExit as err: self.register_error(err.code) except BaseException as err: if isinstance(err, CoconutException): logger.display_exc() elif not isinstance(err, KeyboardInterrupt): traceback.print_exc() printerr(report_this_text) self.register_error(errmsg=err.__class__.__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 compile_path(self, path, write=True, package=None, *args, **kwargs): """Compile a path and returns paths to compiled files."""
path = fixpath(path) if not isinstance(write, bool): write = fixpath(write) if os.path.isfile(path): if package is None: package = False destpath = self.compile_file(path, write, package, *args, **kwargs) return [destpath] if destpath is not None else [] elif os.path.isdir(path): if package is None: package = True return self.compile_folder(path, write, package, *args, **kwargs) else: raise CoconutException("could not find source path", 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 compile_folder(self, directory, write=True, package=True, *args, **kwargs): """Compile a directory and returns paths to compiled files."""
if not isinstance(write, bool) and os.path.isfile(write): raise CoconutException("destination path cannot point to a file when compiling a directory") filepaths = [] for dirpath, dirnames, filenames in os.walk(directory): if isinstance(write, bool): writedir = write else: writedir = os.path.join(write, os.path.relpath(dirpath, directory)) for filename in filenames: if os.path.splitext(filename)[1] in code_exts: with self.handling_exceptions(): destpath = self.compile_file(os.path.join(dirpath, filename), writedir, package, *args, **kwargs) if destpath is not None: filepaths.append(destpath) for name in dirnames[:]: if not is_special_dir(name) and name.startswith("."): if logger.verbose: logger.show_tabulated("Skipped directory", name, "(explicitly pass as source to override).") dirnames.remove(name) # directories removed from dirnames won't appear in further os.walk iterations return filepaths
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compile_file(self, filepath, write=True, package=False, *args, **kwargs): """Compile a file and returns the compiled file's path."""
set_ext = False if write is False: destpath = None elif write is True: destpath = filepath set_ext = True elif os.path.splitext(write)[1]: # write is a file; it is the destination filepath destpath = write else: # write is a dir; make the destination filepath by adding the filename destpath = os.path.join(write, os.path.basename(filepath)) set_ext = True if set_ext: base, ext = os.path.splitext(os.path.splitext(destpath)[0]) if not ext: ext = comp_ext destpath = fixpath(base + ext) if filepath == destpath: raise CoconutException("cannot compile " + showpath(filepath) + " to itself", extra="incorrect file extension") self.compile(filepath, destpath, package, *args, **kwargs) return destpath
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compile(self, codepath, destpath=None, package=False, run=False, force=False, show_unchanged=True): """Compile a source Coconut file to a destination Python file."""
with openfile(codepath, "r") as opened: code = readfile(opened) if destpath is not None: destdir = os.path.dirname(destpath) if not os.path.exists(destdir): os.makedirs(destdir) if package is True: self.create_package(destdir) foundhash = None if force else self.has_hash_of(destpath, code, package) if foundhash: if show_unchanged: logger.show_tabulated("Left unchanged", showpath(destpath), "(pass --force to override).") if self.show: print(foundhash) if run: self.execute_file(destpath) else: logger.show_tabulated("Compiling", showpath(codepath), "...") if package is True: compile_method = "parse_package" elif package is False: compile_method = "parse_file" else: raise CoconutInternalException("invalid value for package", package) def callback(compiled): if destpath is None: logger.show_tabulated("Compiled", showpath(codepath), "without writing to file.") else: with openfile(destpath, "w") as opened: writefile(opened, compiled) logger.show_tabulated("Compiled to", showpath(destpath), ".") if self.show: print(compiled) if run: if destpath is None: self.execute(compiled, path=codepath, allow_show=False) else: self.execute_file(destpath) self.submit_comp_job(codepath, callback, compile_method, code)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def running_jobs(self, exit_on_error=True): """Initialize multiprocessing."""
with self.handling_exceptions(): if self.using_jobs: from concurrent.futures import ProcessPoolExecutor try: with ProcessPoolExecutor(self.jobs) as self.executor: yield finally: self.executor = None else: yield if exit_on_error: self.exit_on_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 create_package(self, dirpath): """Set up a package directory."""
dirpath = fixpath(dirpath) filepath = os.path.join(dirpath, "__coconut__.py") with openfile(filepath, "w") as opened: writefile(opened, self.comp.getheader("__coconut__"))
<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_hash_of(self, destpath, code, package): """Determine if a file has the hash of the code."""
if destpath is not None and os.path.isfile(destpath): with openfile(destpath, "r") as opened: compiled = readfile(opened) hashash = gethash(compiled) if hashash is not None and hashash == self.comp.genhash(package, code): return compiled 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 start_running(self): """Start running the Runner."""
self.comp.warm_up() self.check_runner() self.running = 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 start_prompt(self): """Start the interpreter."""
logger.show("Coconut Interpreter:") logger.show("(type 'exit()' or press Ctrl-D to end)") self.start_running() while self.running: try: code = self.get_input() if code: compiled = self.handle_input(code) if compiled: self.execute(compiled, use_eval=None) except KeyboardInterrupt: printerr("\nKeyboardInterrupt")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_input(self, code): """Compile Coconut interpreter input."""
if not self.prompt.multiline: if not should_indent(code): try: return self.comp.parse_block(code) except CoconutException: pass while True: line = self.get_input(more=True) if line is None: return None elif line: code += "\n" + line else: break try: return self.comp.parse_block(code) except CoconutException: logger.display_exc() 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 execute(self, compiled=None, path=None, use_eval=False, allow_show=True): """Execute compiled code."""
self.check_runner() if compiled is not None: if allow_show and self.show: print(compiled) if path is not None: # path means header is included, and thus encoding must be removed compiled = rem_encoding(compiled) self.runner.run(compiled, use_eval=use_eval, path=path, all_errors_exit=(path is not None)) self.run_mypy(code=self.runner.was_run_code())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_runner(self): """Make sure there is a runner."""
if os.getcwd() not in sys.path: sys.path.append(os.getcwd()) if self.runner is None: self.runner = Runner(self.comp, exit=self.exit_runner, store=self.mypy)
<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_mypy_args(self, mypy_args=None): """Set MyPy arguments."""
if mypy_args is None: self.mypy_args = None else: self.mypy_errs = [] self.mypy_args = list(mypy_args) if not any(arg.startswith("--python-version") for arg in mypy_args): self.mypy_args += [ "--python-version", ".".join(str(v) for v in get_target_info_len2(self.comp.target, mode="nearest")), ] if logger.verbose: for arg in verbose_mypy_args: if arg not in self.mypy_args: self.mypy_args.append(arg) logger.log("MyPy args:", self.mypy_args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_mypy(self, paths=(), code=None): """Run MyPy with arguments."""
if self.mypy: set_mypy_path(stub_dir) from coconut.command.mypy import mypy_run args = list(paths) + self.mypy_args if code is not None: args += ["-c", code] for line, is_err in mypy_run(args): if code is None or line not in self.mypy_errs: printerr(line) if line not in self.mypy_errs: self.mypy_errs.append(line) self.register_error(errmsg="MyPy error")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_jupyter(self, args): """Start Jupyter with the Coconut kernel."""
install_func = partial(run_cmd, show_output=logger.verbose) try: install_func(["jupyter", "--version"]) except CalledProcessError: jupyter = "ipython" else: jupyter = "jupyter" # always install kernels if given no args, otherwise only if there's a kernel missing do_install = not args if not do_install: kernel_list = run_cmd([jupyter, "kernelspec", "list"], show_output=False, raise_errs=False) do_install = any(ker not in kernel_list for ker in icoconut_kernel_names) if do_install: success = True for icoconut_kernel_dir in icoconut_kernel_dirs: install_args = [jupyter, "kernelspec", "install", icoconut_kernel_dir, "--replace"] try: install_func(install_args) except CalledProcessError: user_install_args = install_args + ["--user"] try: install_func(user_install_args) except CalledProcessError: logger.warn("kernel install failed on command'", " ".join(install_args)) self.register_error(errmsg="Jupyter error") success = False if success: logger.show_sig("Successfully installed Coconut Jupyter kernel.") if args: if args[0] == "console": ver = "2" if PY2 else "3" try: install_func(["python" + ver, "-m", "coconut.main", "--version"]) except CalledProcessError: kernel_name = "coconut" else: kernel_name = "coconut" + ver run_args = [jupyter, "console", "--kernel", kernel_name] + args[1:] else: run_args = [jupyter] + args self.register_error(run_cmd(run_args, raise_errs=False), errmsg="Jupyter 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 watch(self, source, write=True, package=None, run=False, force=False): """Watch a source and recompiles on change."""
from coconut.command.watch import Observer, RecompilationWatcher source = fixpath(source) logger.show() logger.show_tabulated("Watching", showpath(source), "(press Ctrl-C to end)...") def recompile(path): path = fixpath(path) if os.path.isfile(path) and os.path.splitext(path)[1] in code_exts: with self.handling_exceptions(): if write is True or write is None: writedir = write else: # correct the compilation path based on the relative position of path to source dirpath = os.path.dirname(path) writedir = os.path.join(write, os.path.relpath(dirpath, source)) filepaths = self.compile_path(path, writedir, package, run, force, show_unchanged=False) self.run_mypy(filepaths) watcher = RecompilationWatcher(recompile) observer = Observer() observer.schedule(watcher, source, recursive=True) with self.running_jobs(): observer.start() try: while True: time.sleep(watch_interval) watcher.keep_watching() except KeyboardInterrupt: logger.show_sig("Got KeyboardInterrupt; stopping watcher.") finally: observer.stop() observer.join()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_ipython_extension(ipython): """Loads Coconut as an IPython extension."""
# add Coconut built-ins from coconut import __coconut__ newvars = {} for var, val in vars(__coconut__).items(): if not var.startswith("__"): newvars[var] = val ipython.push(newvars) # import here to avoid circular dependencies from coconut.convenience import cmd, parse, CoconutException from coconut.terminal import logger # add magic function def magic(line, cell=None): """Provides %coconut and %%coconut magics.""" try: if cell is None: code = line else: # first line in block is cmd, rest is code line = line.strip() if line: cmd(line, interact=False) code = cell compiled = parse(code) except CoconutException: logger.display_exc() else: ipython.run_cell(compiled, shell_futures=False) ipython.register_magic_function(magic, "line_cell", "coconut")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def evaluate_tokens(tokens): """Evaluate the given tokens in the computation graph."""
if isinstance(tokens, str): return tokens elif isinstance(tokens, ParseResults): # evaluate the list portion of the ParseResults toklist, name, asList, modal = tokens.__getnewargs__() new_toklist = [evaluate_tokens(toks) for toks in toklist] new_tokens = ParseResults(new_toklist, name, asList, modal) # evaluate the dictionary portion of the ParseResults new_tokdict = {} for name, occurrences in tokens._ParseResults__tokdict.items(): new_occurences = [] for value, position in occurrences: if isinstance(value, ParseResults) and value._ParseResults__toklist == toklist: new_value = new_tokens else: try: new_value = new_toklist[toklist.index(value)] except ValueError: complain(lambda: CoconutInternalException("inefficient reevaluation of tokens: {} not in {}".format( value, toklist, ))) new_value = evaluate_tokens(value) new_occurences.append(_ParseResultsWithOffset(new_value, position)) new_tokdict[name] = occurrences new_tokens._ParseResults__accumNames.update(tokens._ParseResults__accumNames) new_tokens._ParseResults__tokdict.update(new_tokdict) return new_tokens elif isinstance(tokens, ComputationNode): return tokens.evaluate() elif isinstance(tokens, (list, tuple)): return [evaluate_tokens(inner_toks) for inner_toks in tokens] else: raise CoconutInternalException("invalid computation graph 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 attach(item, action, greedy=False, ignore_no_tokens=None, ignore_one_token=None): """Set the parse action for the given item to create a node in the computation graph."""
if use_computation_graph: # use the action's annotations to generate the defaults if ignore_no_tokens is None: ignore_no_tokens = getattr(action, "ignore_no_tokens", False) if ignore_one_token is None: ignore_one_token = getattr(action, "ignore_one_token", False) # only include True keyword arguments in the partial, since False is the default kwargs = {} if greedy: kwargs["greedy"] = greedy if ignore_no_tokens: kwargs["ignore_no_tokens"] = ignore_no_tokens if ignore_one_token: kwargs["ignore_one_token"] = ignore_one_token action = partial(ComputationNode, action, **kwargs) return add_action(item, action)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unpack(tokens): """Evaluate and unpack the given computation graph."""
logger.log_tag("unpack", tokens) if use_computation_graph: tokens = evaluate_tokens(tokens) if isinstance(tokens, ParseResults) and len(tokens) == 1: tokens = tokens[0] return 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 all_matches(grammar, text): """Find all matches for grammar in text."""
for tokens, start, stop in grammar.parseWithTabs().scanString(text): yield unpack(tokens), start, stop
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def match_in(grammar, text): """Determine if there is a match for grammar in text."""
for result in grammar.parseWithTabs().scanString(text): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_vers_for_target(target): """Gets a list of the versions supported by the given target."""
target_info = get_target_info(target) if not target_info: return py2_vers + py3_vers elif len(target_info) == 1: if target_info == (2,): return py2_vers elif target_info == (3,): return py3_vers else: raise CoconutInternalException("invalid target info", target_info) elif target_info == (3, 3): return [(3, 3), (3, 4)] else: return [target_info[:2]]
<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_target_info_len2(target, mode="lowest"): """Converts target into a length 2 Python version tuple. Modes: - "lowest" (default): Gets the lowest version supported by the target. - "highest": Gets the highest version supported by the target. - "nearest": If the current version is supported, returns that, otherwise gets the highest."""
supported_vers = get_vers_for_target(target) if mode == "lowest": return supported_vers[0] elif mode == "highest": return supported_vers[-1] elif mode == "nearest": if sys.version_info[:2] in supported_vers: return sys.version_info[:2] else: return supported_vers[-1] else: raise CoconutInternalException("unknown get_target_info_len2 mode", mode)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def longest(*args): """Match the longest of the given grammar elements."""
internal_assert(len(args) >= 2, "longest expects at least two args") matcher = args[0] + skip_whitespace for elem in args[1:]: matcher ^= elem + skip_whitespace return matcher
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addskip(skips, skip): """Add a line skip to the skips."""
if skip < 1: complain(CoconutInternalException("invalid skip of line " + str(skip))) else: skips.append(skip) return 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 count_end(teststr, testchar): """Count instances of testchar at end of teststr."""
count = 0 x = len(teststr) - 1 while x >= 0 and teststr[x] == testchar: count += 1 x -= 1 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 maybeparens(lparen, item, rparen): """Wrap an item in optional parentheses, only applying them if necessary."""
return item | lparen.suppress() + item + rparen.suppress()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tokenlist(item, sep, suppress=True): """Create a list of tokens matching the item."""
if suppress: sep = sep.suppress() return item + ZeroOrMore(sep + item) + Optional(sep)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def itemlist(item, sep, suppress_trailing=True): """Create a list of items seperated by seps."""
return condense(item + ZeroOrMore(addspace(sep + item)) + Optional(sep.suppress() if suppress_trailing else sep))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def should_indent(code): """Determines whether the next line should be indented."""
last = rem_comment(code.splitlines()[-1]) return last.endswith(":") or last.endswith("\\") or paren_change(last) < 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 split_leading_comment(inputstring): """Split into leading comment and rest."""
if inputstring.startswith("#"): comment, rest = inputstring.split("\n", 1) return comment + "\n", rest else: 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 split_leading_trailing_indent(line, max_indents=None): """Split leading and trailing indent."""
leading_indent, line = split_leading_indent(line, max_indents) line, trailing_indent = split_trailing_indent(line, max_indents) return leading_indent, line, trailing_indent
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collapse_indents(indentation): """Removes all openindent-closeindent pairs."""
change_in_level = ind_change(indentation) if change_in_level == 0: indents = "" elif change_in_level < 0: indents = closeindent * (-change_in_level) else: indents = openindent * change_in_level return indentation.replace(openindent, "").replace(closeindent, "") + indents
<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(grammar, text): """Transform text by replacing matches to grammar."""
results = [] intervals = [] for result, start, stop in all_matches(grammar, text): if result is not ignore_transform: internal_assert(isinstance(result, str), "got non-string transform result", result) if start == 0 and stop == len(text): return result results.append(result) intervals.append((start, stop)) if not results: return None split_indices = [0] split_indices.extend(start for start, _ in intervals) split_indices.extend(stop for _, stop in intervals) split_indices.sort() split_indices.append(None) out = [] for i in range(len(split_indices) - 1): if i % 2 == 0: start, stop = split_indices[i], split_indices[i + 1] out.append(text[start:stop]) else: out.append(results[i // 2]) if i // 2 < len(results) - 1: raise CoconutInternalException("unused transform results", results[i // 2 + 1:]) if stop is not None: raise CoconutInternalException("failed to properly split text to be transformed") 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 disable_inside(item, *elems, **kwargs): """Prevent elems from matching inside of item. Returns (item with elem disabled, *new versions of elems). """
_invert = kwargs.get("_invert", False) internal_assert(set(kwargs.keys()) <= set(("_invert",)), "excess keyword arguments passed to disable_inside") level = [0] # number of wrapped items deep we are; in a list to allow modification @contextmanager def manage_item(self, instring, loc): level[0] += 1 try: yield finally: level[0] -= 1 yield Wrap(item, manage_item) @contextmanager def manage_elem(self, instring, loc): if level[0] == 0 if not _invert else level[0] > 0: yield else: raise ParseException(instring, loc, self.errmsg, self) for elem in elems: yield Wrap(elem, manage_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 name(self): """Get the name of the action."""
name = getattr(self.action, "__name__", None) # ascii(action) not defined for all actions, so must only be evaluated if getattr fails return name if name is not None else ascii(self.action)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def evaluate(self): """Get the result of evaluating the computation graph at this node."""
if DEVELOP: internal_assert(not self.been_called, "inefficient reevaluation of action " + self.name + " with tokens", self.tokens) self.been_called = True evaluated_toks = evaluate_tokens(self.tokens) if logger.tracing: # avoid the overhead of the call if not tracing logger.log_trace(self.name, self.original, self.loc, evaluated_toks, self.tokens) try: return _trim_arity(self.action)( self.original, self.loc, evaluated_toks, ) except CoconutException: raise except (Exception, AssertionError): traceback.print_exc() raise CoconutInternalException("error computing action " + self.name + " of evaluated tokens", evaluated_toks)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _combine(self, original, loc, tokens): """Implement the parse action for Combine."""
combined_tokens = super(CombineNode, self).postParse(original, loc, tokens) internal_assert(len(combined_tokens) == 1, "Combine produced multiple tokens", combined_tokens) return combined_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 postParse(self, original, loc, tokens): """Create a ComputationNode for Combine."""
return ComputationNode(self._combine, original, loc, tokens, ignore_no_tokens=True, ignore_one_token=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 parseImpl(self, instring, loc, *args, **kwargs): """Wrapper around ParseElementEnhance.parseImpl."""
with self.wrapper(self, instring, loc): return super(Wrap, self).parseImpl(instring, loc, *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 gethash(compiled): """Retrieve a hash from a header."""
lines = compiled.splitlines() if len(lines) < 3 or not lines[2].startswith(hash_prefix): return None else: return lines[2][len(hash_prefix):]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def minify(compiled): """Perform basic minifications. Fails on non-tabideal indentation or a string with a #. """
compiled = compiled.strip() if compiled: out = [] for line in compiled.splitlines(): line = line.split("#", 1)[0].rstrip() if line: ind = 0 while line.startswith(" "): line = line[1:] ind += 1 internal_assert(ind % tabideal == 0, "invalid indentation in", line) out.append(" " * (ind // tabideal) + line) compiled = "\n".join(out) + "\n" return compiled
<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_template(template): """Read the given template file."""
with open(os.path.join(template_dir, template) + template_ext, "r") as template_file: return template_file.read()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fixpath(path): """Uniformly format a path."""
return os.path.normpath(os.path.realpath(os.path.expanduser(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 ver_str_to_tuple(ver_str): """Convert a version string into a version tuple."""
out = [] for x in ver_str.split("."): try: x = int(x) except ValueError: pass out.append(x) return tuple(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 mypy_run(args): """Runs mypy with given arguments and shows the result."""
logger.log_cmd(["mypy"] + args) try: stdout, stderr, exit_code = run(args) except BaseException: traceback.print_exc() else: for line in stdout.splitlines(): yield line, False for line in stderr.splitlines(): yield line, True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_coconut_to_path(): """Adds coconut to sys.path if it isn't there already."""
try: import coconut # NOQA except ImportError: sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def writefile(openedfile, newcontents): """Set the contents of a file."""
openedfile.seek(0) openedfile.truncate() openedfile.write(newcontents)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def showpath(path): """Format a path for displaying."""
if logger.verbose: return os.path.abspath(path) else: path = os.path.relpath(path) if path.startswith(os.curdir + os.sep): path = path[len(os.curdir + os.sep):] 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 rem_encoding(code): """Remove encoding declarations from compiled code so it can be passed to exec."""
old_lines = code.splitlines() new_lines = [] for i in range(min(2, len(old_lines))): line = old_lines[i] if not (line.lstrip().startswith("#") and "coding" in line): new_lines.append(line) new_lines += old_lines[2:] return "\n".join(new_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 exec_func(code, glob_vars, loc_vars=None): """Wrapper around exec."""
if loc_vars is None: exec(code, glob_vars) else: exec(code, glob_vars, loc_vars)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interpret(code, in_vars): """Try to evaluate the given code, otherwise execute it."""
try: result = eval(code, in_vars) except SyntaxError: pass # exec code outside of exception context else: if result is not None: print(ascii(result)) return # don't also exec code exec_func(code, in_vars)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kill_children(): """Terminate all child processes."""
try: import psutil except ImportError: logger.warn( "missing psutil; --jobs may not properly terminate", extra="run 'pip install coconut[jobs]' to fix", ) else: master = psutil.Process() children = master.children(recursive=True) while children: for child in children: try: child.terminate() except psutil.NoSuchProcess: pass # process is already dead, so do nothing children = master.children(recursive=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 splitname(path): """Split a path into a directory, name, and extensions."""
dirpath, filename = os.path.split(path) # we don't use os.path.splitext here because we want all extensions, # not just the last, to be put in exts name, exts = filename.split(os.extsep, 1) return dirpath, name, exts
<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_file(path): """Run a module from a path and return its variables."""
if PY26: dirpath, name, _ = splitname(path) found = imp.find_module(name, [dirpath]) module = imp.load_module("__main__", *found) return vars(module) else: return runpy.run_path(path, run_name="__main__")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def call_output(cmd, stdin=None, encoding_errors="replace", **kwargs): """Run command and read output."""
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs) stdout, stderr, retcode = [], [], None while retcode is None: if stdin is not None: logger.log_prefix("<0 ", stdin.rstrip()) raw_out, raw_err = p.communicate(stdin) stdin = None out = raw_out.decode(get_encoding(sys.stdout), encoding_errors) if raw_out else "" if out: logger.log_prefix("1> ", out.rstrip()) stdout.append(out) err = raw_err.decode(get_encoding(sys.stderr), encoding_errors) if raw_err else "" if err: logger.log_prefix("2> ", err.rstrip()) stderr.append(err) retcode = p.poll() return stdout, stderr, retcode
<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_cmd(cmd, show_output=True, raise_errs=True, **kwargs): """Run a console command. When show_output=True, prints output and returns exit code, otherwise returns output. When raise_errs=True, raises a subprocess.CalledProcessError if the command fails. """
internal_assert(cmd and isinstance(cmd, list), "console commands must be passed as non-empty lists") try: from shutil import which except ImportError: pass else: cmd[0] = which(cmd[0]) or cmd[0] logger.log_cmd(cmd) try: if show_output and raise_errs: return subprocess.check_call(cmd, **kwargs) elif show_output: return subprocess.call(cmd, **kwargs) else: stdout, stderr, retcode = call_output(cmd, **kwargs) output = "".join(stdout + stderr) if retcode and raise_errs: raise subprocess.CalledProcessError(retcode, cmd, output=output) return output except OSError: logger.log_exc() if raise_errs: raise subprocess.CalledProcessError(oserror_retcode, cmd) elif show_output: return oserror_retcode else: 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 set_mypy_path(mypy_path): """Prepend to MYPYPATH."""
original = os.environ.get(mypy_path_env_var) if original is None: new_mypy_path = mypy_path elif not original.startswith(mypy_path): new_mypy_path = mypy_path + os.pathsep + original else: new_mypy_path = None if new_mypy_path is not None: logger.log(mypy_path_env_var + ":", new_mypy_path) os.environ[mypy_path_env_var] = new_mypy_path