Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line for this snippet: <|code_start|> oparser.add_option("-o", "--output", dest="output", help="name of logfile") oparser.add_option("-n", "--name", dest="name", help="name of the project (included in the report)") (opt, args) = oparser.parse_args(argv) if len(args) != 1: print("Wrong number of arguments") oparser.print_help() sys.exit(20) if not opt.output: return 0 xml = etree(args[0]) xml_pkglist = xml.node("/target/pkg-list") xml_pkgs = [p.et.text for p in xml_pkglist] # TODO: install buildimage packages after target image generation # and remove theme before target image generation # we need to introduce additional arguments for this # in default copy mode chroot to the target and remove elbe-daemon # and its dependencies (if it is not in target/pkg-list. buildenv_pkgs = ["python3-elbe-buildenv"] if xml.has("./project/buildimage/pkg-list"): buildenv_pkgs.extend([p.et.text for p in xml.node( "project/buildimage/pkg-list")]) <|code_end|> with the help of current file imports: import logging import sys import apt import apt.progress from optparse import OptionParser from elbepack.treeutils import etree from elbepack.log import elbe_logging and context from other files: # Path: elbepack/treeutils.py # class etree(ebase): # def __init__(self, fname): # if fname is not None: # parser = XMLParser(huge_tree=True, remove_comments=False) # et = parse(fname, parser=parser) # else: # et = ElementTree(file=None) # # ebase.__init__(self, et) # # def write(self, fname, encoding=None): # # Make sure, that we end with a newline # self.et.getroot().tail = '\n' # self.et.write(fname, encoding=encoding) # # def tostring(self): # return self.et.tostring() # # def ensure_child(self, tag): # retval = self.et.find("./" + tag) # if retval is not None: # return elem(retval) # return elem(SubElement(self.et.getroot(), tag)) # # def set_child_position(self, child, pos): # root = self.et.getroot() # root.remove(child.et) # root.insert(pos, child.et) # # def setroot(self, tag): # retval = elem(Element(tag)) # # pylint: disable=protected-access # self.et._setroot(retval.et) # return retval # # @property # def root(self): # return elem(self.et.getroot()) # # Path: elbepack/log.py # @contextmanager # def elbe_logging(*args, **kwargs): # try: # open_logging(*args, **kwargs) # yield # finally: # close_logging() , which may contain function names, class names, or code. Output only the next line.
with elbe_logging({"files":opt.output}):
Continue the code snippet: <|code_start|> remove_re = re.compile(u'[\x00-\x08\x0B-\x0C\x0E-\x1F\x7F]') def do_heuristics(fp): c = Copyright() num_licenses = 0 for l in fp.readlines(): if l.startswith("License:"): num_licenses += 1 _, v = l.split(":", 1) data = {"License": v.strip()} lic_para = LicenseParagraph(data) c.add_license_paragraph(lic_para) if num_licenses > 0: return c return None def get_heuristics_license_list(c): licenses = [] for cc in c.all_license_paragraphs(): licenses.append(cc.license.synopsis) return set(licenses) class copyright_xml: def __init__(self): <|code_end|> . Use current file imports: import io import re import warnings import logging from debian.copyright import Copyright, LicenseParagraph, NotMachineReadableError, MachineReadableFormatError from elbepack.treeutils import etree and context (classes, functions, or code) from other files: # Path: elbepack/treeutils.py # class etree(ebase): # def __init__(self, fname): # if fname is not None: # parser = XMLParser(huge_tree=True, remove_comments=False) # et = parse(fname, parser=parser) # else: # et = ElementTree(file=None) # # ebase.__init__(self, et) # # def write(self, fname, encoding=None): # # Make sure, that we end with a newline # self.et.getroot().tail = '\n' # self.et.write(fname, encoding=encoding) # # def tostring(self): # return self.et.tostring() # # def ensure_child(self, tag): # retval = self.et.find("./" + tag) # if retval is not None: # return elem(retval) # return elem(SubElement(self.et.getroot(), tag)) # # def set_child_position(self, child, pos): # root = self.et.getroot() # root.remove(child.et) # root.insert(pos, child.et) # # def setroot(self, tag): # retval = elem(Element(tag)) # # pylint: disable=protected-access # self.et._setroot(retval.et) # return retval # # @property # def root(self): # return elem(self.et.getroot()) . Output only the next line.
self.outxml = etree(None)
Given snippet: <|code_start|> fp = NamedTemporaryFile() fp.write(standard_b64decode(arch_elem)) fp.file.flush() return fp def prepare_path(url): url = urlparse(url) path = url.geturl().replace("%s://"%url.scheme, '', 1) return re.sub(r'/$', "", path) def get_and_append_local(url, tararchive, keep): if urlparse(url).netloc: msg = "Reject suspicious file:// URI \"{}\". ".format(url) msg += "Please use an absolute URI (file:///a/b/c) or a " msg += "relative URI (a/b/c) instead." raise ArchivedirError(msg) collect(tararchive, prepare_path(url), keep) def get_and_append_unknown(url, _archive): msg = "unhandled scheme \"{}://\"".format(urlparse(url).scheme) raise NotImplementedError(msg) def get_and_append_method(url): return { '': get_and_append_local, 'file': get_and_append_local, }.get(urlparse(url).scheme, get_and_append_unknown) def _combinearchivedir(xml, xpath, use_volume): <|code_end|> , continue by predicting the next line. Consider current file imports: import bz2 import os import re import sys from urllib.parse import urljoin,urlparse from base64 import encodebytes, standard_b64decode from subprocess import CalledProcessError from tempfile import NamedTemporaryFile from elbepack.treeutils import etree from elbepack.shellhelper import system from elbepack.filesystem import TmpdirFilesystem and context: # Path: elbepack/treeutils.py # class etree(ebase): # def __init__(self, fname): # if fname is not None: # parser = XMLParser(huge_tree=True, remove_comments=False) # et = parse(fname, parser=parser) # else: # et = ElementTree(file=None) # # ebase.__init__(self, et) # # def write(self, fname, encoding=None): # # Make sure, that we end with a newline # self.et.getroot().tail = '\n' # self.et.write(fname, encoding=encoding) # # def tostring(self): # return self.et.tostring() # # def ensure_child(self, tag): # retval = self.et.find("./" + tag) # if retval is not None: # return elem(retval) # return elem(SubElement(self.et.getroot(), tag)) # # def set_child_position(self, child, pos): # root = self.et.getroot() # root.remove(child.et) # root.insert(pos, child.et) # # def setroot(self, tag): # retval = elem(Element(tag)) # # pylint: disable=protected-access # self.et._setroot(retval.et) # return retval # # @property # def root(self): # return elem(self.et.getroot()) # # Path: elbepack/shellhelper.py # def system(cmd, allow_fail=False, env_add=None): # """system() - Execute cmd in a shell. # # Throws a CommandError if cmd returns none-zero and allow_fail=False # # -- # # >>> system("true") # # >>> system("false", allow_fail=True) # # >>> system("$FALSE", env_add={"FALSE":"false"}) # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # # """ # new_env = os.environ.copy() # if env_add: # new_env.update(env_add) # # ret = call(cmd, shell=True, env=new_env) # # if ret != 0: # if not allow_fail: # raise CommandError(cmd, ret) # # Path: elbepack/filesystem.py # class TmpdirFilesystem (Filesystem): # def __init__(self, debug=False): # tmpdir = mkdtemp() # Filesystem.__init__(self, tmpdir) # self.debug = debug # # def __del__(self): # # dont delete files in debug mode # if self.debug: # print('leaving TmpdirFilesystem in "%s"' % self.path) # else: # self.delete() # # def delete(self): # shutil.rmtree(self.path, True) # # def __enter__(self): # return self # # def __exit__(self, exec_type, exec_value, tb): # shutil.rmtree(self.path) # return False which might include code, classes, or functions. Output only the next line.
elbexml = etree(None)
Given snippet: <|code_start|># ELBE - Debian Based Embedded Rootfilesystem Builder # Copyright (c) 2018 Benedikt Spranger <b.spranger@linutronix.de> # # SPDX-License-Identifier: GPL-3.0-or-later class ArchivedirError(Exception): pass def enbase(fname, compress=True): with open(fname, "rb") as infile: s = infile.read() if compress: s = bz2.compress(s) return encodebytes(s) def collect(tararchive, path, keep): if keep: cmd = 'tar rf ' + tararchive + ' -C ' else: cmd = 'tar rf ' + tararchive + ' --owner=root --group=root -C ' cmd += path + ' .' <|code_end|> , continue by predicting the next line. Consider current file imports: import bz2 import os import re import sys from urllib.parse import urljoin,urlparse from base64 import encodebytes, standard_b64decode from subprocess import CalledProcessError from tempfile import NamedTemporaryFile from elbepack.treeutils import etree from elbepack.shellhelper import system from elbepack.filesystem import TmpdirFilesystem and context: # Path: elbepack/treeutils.py # class etree(ebase): # def __init__(self, fname): # if fname is not None: # parser = XMLParser(huge_tree=True, remove_comments=False) # et = parse(fname, parser=parser) # else: # et = ElementTree(file=None) # # ebase.__init__(self, et) # # def write(self, fname, encoding=None): # # Make sure, that we end with a newline # self.et.getroot().tail = '\n' # self.et.write(fname, encoding=encoding) # # def tostring(self): # return self.et.tostring() # # def ensure_child(self, tag): # retval = self.et.find("./" + tag) # if retval is not None: # return elem(retval) # return elem(SubElement(self.et.getroot(), tag)) # # def set_child_position(self, child, pos): # root = self.et.getroot() # root.remove(child.et) # root.insert(pos, child.et) # # def setroot(self, tag): # retval = elem(Element(tag)) # # pylint: disable=protected-access # self.et._setroot(retval.et) # return retval # # @property # def root(self): # return elem(self.et.getroot()) # # Path: elbepack/shellhelper.py # def system(cmd, allow_fail=False, env_add=None): # """system() - Execute cmd in a shell. # # Throws a CommandError if cmd returns none-zero and allow_fail=False # # -- # # >>> system("true") # # >>> system("false", allow_fail=True) # # >>> system("$FALSE", env_add={"FALSE":"false"}) # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # # """ # new_env = os.environ.copy() # if env_add: # new_env.update(env_add) # # ret = call(cmd, shell=True, env=new_env) # # if ret != 0: # if not allow_fail: # raise CommandError(cmd, ret) # # Path: elbepack/filesystem.py # class TmpdirFilesystem (Filesystem): # def __init__(self, debug=False): # tmpdir = mkdtemp() # Filesystem.__init__(self, tmpdir) # self.debug = debug # # def __del__(self): # # dont delete files in debug mode # if self.debug: # print('leaving TmpdirFilesystem in "%s"' % self.path) # else: # self.delete() # # def delete(self): # shutil.rmtree(self.path, True) # # def __enter__(self): # return self # # def __exit__(self, exec_type, exec_value, tb): # shutil.rmtree(self.path) # return False which might include code, classes, or functions. Output only the next line.
system(cmd)
Predict the next line for this snippet: <|code_start|> return fp def prepare_path(url): url = urlparse(url) path = url.geturl().replace("%s://"%url.scheme, '', 1) return re.sub(r'/$', "", path) def get_and_append_local(url, tararchive, keep): if urlparse(url).netloc: msg = "Reject suspicious file:// URI \"{}\". ".format(url) msg += "Please use an absolute URI (file:///a/b/c) or a " msg += "relative URI (a/b/c) instead." raise ArchivedirError(msg) collect(tararchive, prepare_path(url), keep) def get_and_append_unknown(url, _archive): msg = "unhandled scheme \"{}://\"".format(urlparse(url).scheme) raise NotImplementedError(msg) def get_and_append_method(url): return { '': get_and_append_local, 'file': get_and_append_local, }.get(urlparse(url).scheme, get_and_append_unknown) def _combinearchivedir(xml, xpath, use_volume): elbexml = etree(None) elbexml.et = xml <|code_end|> with the help of current file imports: import bz2 import os import re import sys from urllib.parse import urljoin,urlparse from base64 import encodebytes, standard_b64decode from subprocess import CalledProcessError from tempfile import NamedTemporaryFile from elbepack.treeutils import etree from elbepack.shellhelper import system from elbepack.filesystem import TmpdirFilesystem and context from other files: # Path: elbepack/treeutils.py # class etree(ebase): # def __init__(self, fname): # if fname is not None: # parser = XMLParser(huge_tree=True, remove_comments=False) # et = parse(fname, parser=parser) # else: # et = ElementTree(file=None) # # ebase.__init__(self, et) # # def write(self, fname, encoding=None): # # Make sure, that we end with a newline # self.et.getroot().tail = '\n' # self.et.write(fname, encoding=encoding) # # def tostring(self): # return self.et.tostring() # # def ensure_child(self, tag): # retval = self.et.find("./" + tag) # if retval is not None: # return elem(retval) # return elem(SubElement(self.et.getroot(), tag)) # # def set_child_position(self, child, pos): # root = self.et.getroot() # root.remove(child.et) # root.insert(pos, child.et) # # def setroot(self, tag): # retval = elem(Element(tag)) # # pylint: disable=protected-access # self.et._setroot(retval.et) # return retval # # @property # def root(self): # return elem(self.et.getroot()) # # Path: elbepack/shellhelper.py # def system(cmd, allow_fail=False, env_add=None): # """system() - Execute cmd in a shell. # # Throws a CommandError if cmd returns none-zero and allow_fail=False # # -- # # >>> system("true") # # >>> system("false", allow_fail=True) # # >>> system("$FALSE", env_add={"FALSE":"false"}) # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # # """ # new_env = os.environ.copy() # if env_add: # new_env.update(env_add) # # ret = call(cmd, shell=True, env=new_env) # # if ret != 0: # if not allow_fail: # raise CommandError(cmd, ret) # # Path: elbepack/filesystem.py # class TmpdirFilesystem (Filesystem): # def __init__(self, debug=False): # tmpdir = mkdtemp() # Filesystem.__init__(self, tmpdir) # self.debug = debug # # def __del__(self): # # dont delete files in debug mode # if self.debug: # print('leaving TmpdirFilesystem in "%s"' % self.path) # else: # self.delete() # # def delete(self): # shutil.rmtree(self.path, True) # # def __enter__(self): # return self # # def __exit__(self, exec_type, exec_value, tb): # shutil.rmtree(self.path) # return False , which may contain function names, class names, or code. Output only the next line.
tmp = TmpdirFilesystem()
Here is a snippet: <|code_start|># needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General information about the project. project = u'ELBE' copyright = u'2017, Linutronix GmbH' #pylint: disable=redefined-builtin author = u'Torben Hohn, Manuel Traut' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. #pylint: disable=unused-import,wrong-import-position <|code_end|> . Write the next line using the current file imports: import os import sys from elbepack.version import elbe_version as version from elbepack.version import elbe_version as release and context from other files: # Path: elbepack/version.py # # Path: elbepack/version.py , which may include functions, classes, or code. Output only the next line.
from elbepack.version import elbe_version as version
Predict the next line after this snippet: <|code_start|># ELBE - Debian Based Embedded Rootfilesystem Builder # Copyright (c) 2020 Olivier Dion <dion@linutronix.de> # # SPDX-License-Identifier: GPL-3.0-or-later @unittest.skipIf(ElbeTestCase.level < ElbeTestLevel.INITVM, "Test level not set to INITVM") class TestSimpleXML(ElbeTestCase): <|code_end|> using the current file's imports: import os import unittest import tempfile from elbepack.directories import elbe_dir, elbe_exe from elbepack.commands.test import ElbeTestCase, ElbeTestLevel, system and any relevant context from other files: # Path: elbepack/directories.py # def init_directories(elbe_relpath): # def get_cmdlist(): # # Path: elbepack/commands/test.py # class ElbeTestCase(unittest.TestCase): # # level = ElbeTestLevel.BASE # # def __init__(self, methodName='runTest', param=None): # self.methodName = methodName # self.param = param # self.stdout = None # super().__init__(methodName) # # def __str__(self): # name = super(ElbeTestCase, self).__str__() # if self.param: # return "%s : param=%s" % (name, self.param) # return name # # def parameterize(self, param): # return self.__class__(methodName=self.methodName, param=param) # # class ElbeTestLevel(enum.IntEnum): # BASE = enum.auto() # EXTEND = enum.auto() # INITVM = enum.auto() # FULL = enum.auto() # # def system(cmd, allow_fail=False): # ret, out = command_out(cmd) # if ret != 0 and not allow_fail: # raise ElbeTestException(cmd, ret, out) . Output only the next line.
params = [os.path.join(elbe_dir, "tests", fname)
Given the code snippet: <|code_start|># ELBE - Debian Based Embedded Rootfilesystem Builder # Copyright (c) 2020 Olivier Dion <dion@linutronix.de> # # SPDX-License-Identifier: GPL-3.0-or-later @unittest.skipIf(ElbeTestCase.level < ElbeTestLevel.INITVM, "Test level not set to INITVM") class TestSimpleXML(ElbeTestCase): params = [os.path.join(elbe_dir, "tests", fname) for fname in os.listdir(os.path.join(elbe_dir, "tests")) if fname.startswith("simple") and fname.endswith(".xml")] def test_simple_build(self): with tempfile.TemporaryDirectory(prefix="elbe-test-simple-xml-") as build_dir: prj = os.path.join(build_dir, "uuid.prj") uuid = None try: system('%s initvm submit "%s" --output "%s" --keep-files ' '--build-sdk --writeproject "%s"' % <|code_end|> , generate the next line using the imports in this file: import os import unittest import tempfile from elbepack.directories import elbe_dir, elbe_exe from elbepack.commands.test import ElbeTestCase, ElbeTestLevel, system and context (functions, classes, or occasionally code) from other files: # Path: elbepack/directories.py # def init_directories(elbe_relpath): # def get_cmdlist(): # # Path: elbepack/commands/test.py # class ElbeTestCase(unittest.TestCase): # # level = ElbeTestLevel.BASE # # def __init__(self, methodName='runTest', param=None): # self.methodName = methodName # self.param = param # self.stdout = None # super().__init__(methodName) # # def __str__(self): # name = super(ElbeTestCase, self).__str__() # if self.param: # return "%s : param=%s" % (name, self.param) # return name # # def parameterize(self, param): # return self.__class__(methodName=self.methodName, param=param) # # class ElbeTestLevel(enum.IntEnum): # BASE = enum.auto() # EXTEND = enum.auto() # INITVM = enum.auto() # FULL = enum.auto() # # def system(cmd, allow_fail=False): # ret, out = command_out(cmd) # if ret != 0 and not allow_fail: # raise ElbeTestException(cmd, ret, out) . Output only the next line.
(elbe_exe, self.param, build_dir, prj))
Using the snippet: <|code_start|># ELBE - Debian Based Embedded Rootfilesystem Builder # Copyright (c) 2020 Olivier Dion <dion@linutronix.de> # # SPDX-License-Identifier: GPL-3.0-or-later @unittest.skipIf(ElbeTestCase.level < ElbeTestLevel.INITVM, "Test level not set to INITVM") class TestSimpleXML(ElbeTestCase): params = [os.path.join(elbe_dir, "tests", fname) for fname in os.listdir(os.path.join(elbe_dir, "tests")) if fname.startswith("simple") and fname.endswith(".xml")] def test_simple_build(self): with tempfile.TemporaryDirectory(prefix="elbe-test-simple-xml-") as build_dir: prj = os.path.join(build_dir, "uuid.prj") uuid = None try: <|code_end|> , determine the next line of code. You have imports: import os import unittest import tempfile from elbepack.directories import elbe_dir, elbe_exe from elbepack.commands.test import ElbeTestCase, ElbeTestLevel, system and context (class names, function names, or code) available: # Path: elbepack/directories.py # def init_directories(elbe_relpath): # def get_cmdlist(): # # Path: elbepack/commands/test.py # class ElbeTestCase(unittest.TestCase): # # level = ElbeTestLevel.BASE # # def __init__(self, methodName='runTest', param=None): # self.methodName = methodName # self.param = param # self.stdout = None # super().__init__(methodName) # # def __str__(self): # name = super(ElbeTestCase, self).__str__() # if self.param: # return "%s : param=%s" % (name, self.param) # return name # # def parameterize(self, param): # return self.__class__(methodName=self.methodName, param=param) # # class ElbeTestLevel(enum.IntEnum): # BASE = enum.auto() # EXTEND = enum.auto() # INITVM = enum.auto() # FULL = enum.auto() # # def system(cmd, allow_fail=False): # ret, out = command_out(cmd) # if ret != 0 and not allow_fail: # raise ElbeTestException(cmd, ret, out) . Output only the next line.
system('%s initvm submit "%s" --output "%s" --keep-files '
Given snippet: <|code_start|># Copyright (c) 2020 Olivier Dion <dion@linutronix.de> # # SPDX-License-Identifier: GPL-3.0-or-later # elbepack/commands/test.py - Elbe unit test wrapper class ElbeTestLevel(enum.IntEnum): BASE = enum.auto() EXTEND = enum.auto() INITVM = enum.auto() FULL = enum.auto() class ElbeTestException(Exception): def __init__(self, cmd, ret, out): super().__init__() self.cmd = cmd self.ret = ret self.out = out def __repr__(self): return f"ElbeTestException: \"{self.cmd}\" returns {self.ret}" def __str__(self): return f"ElbeTestException: \"{self.cmd}\" returns {self.ret}" def system(cmd, allow_fail=False): <|code_end|> , continue by predicting the next line. Consider current file imports: import enum import optparse import os import re import unittest import warnings import junit_xml as junit from elbepack.shellhelper import command_out and context: # Path: elbepack/shellhelper.py # def command_out(cmd, stdin=None, output=PIPE, env_add=None): # """command_out() - Execute cmd in a shell. # # Returns a tuple with the exitcode and the output of cmd. # # -- # # >>> command_out("true") # (0, '') # # >>> command_out("$TRUE && true", env_add={"TRUE":"true"}) # (0, '') # # >>> command_out("cat -", stdin=b"ELBE") # (0, 'ELBE') # # >>> command_out("2>&1 cat -", stdin=b"ELBE") # (0, 'ELBE') # # >>> command_out("2>&1 cat -", stdin="ELBE") # (0, 'ELBE') # # >>> command_out("false") # (1, '') # # """ # new_env = os.environ.copy() # if env_add: # new_env.update(env_add) # # if isinstance(stdin, str): # stdin = stdin.encode() # # if stdin is None: # p = Popen(cmd, shell=True, # stdout=output, stderr=STDOUT, env=new_env) # out, _ = p.communicate() # else: # p = Popen(cmd, shell=True, # stdout=output, stderr=STDOUT, stdin=PIPE, env=new_env) # out, _ = p.communicate(input=stdin) # # out = TextIOWrapper(BytesIO(out), encoding='utf-8', errors='replace').read() # # return p.returncode, out which might include code, classes, or functions. Output only the next line.
ret, out = command_out(cmd)
Given the code snippet: <|code_start|> self.source = apt_pkg.SourceList() self.source.read_main_list() self.cache = apt_pkg.Cache() try: self.cache.update(self, self.source) except BaseException as e: print(e) apt_pkg.config.set("APT::Default-Release", suite) self.cache = apt_pkg.Cache() try: self.cache.update(self, self.source) except BaseException as e: print(e) try: self.depcache = apt_pkg.DepCache(self.cache) prefs_name = self.basefs.fname("/etc/apt/preferences") self.depcache.read_pinfile(prefs_name) except BaseException as e: print(e) self.downloads = {} self.acquire = apt_pkg.Acquire(self) def add_key(self, key): cmd = 'echo "%s" > %s' % (key, self.basefs.fname("tmp/key.pub")) clean = 'rm -f %s' % self.basefs.fname("tmp/key.pub") <|code_end|> , generate the next line using the imports in this file: import os import sys import apt # pylint: disable=unused-import import apt_pkg from elbepack.shellhelper import system from elbepack.filesystem import TmpdirFilesystem from elbepack.rfs import create_apt_prefs and context (functions, classes, or occasionally code) from other files: # Path: elbepack/shellhelper.py # def system(cmd, allow_fail=False, env_add=None): # """system() - Execute cmd in a shell. # # Throws a CommandError if cmd returns none-zero and allow_fail=False # # -- # # >>> system("true") # # >>> system("false", allow_fail=True) # # >>> system("$FALSE", env_add={"FALSE":"false"}) # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # # """ # new_env = os.environ.copy() # if env_add: # new_env.update(env_add) # # ret = call(cmd, shell=True, env=new_env) # # if ret != 0: # if not allow_fail: # raise CommandError(cmd, ret) # # Path: elbepack/filesystem.py # class TmpdirFilesystem (Filesystem): # def __init__(self, debug=False): # tmpdir = mkdtemp() # Filesystem.__init__(self, tmpdir) # self.debug = debug # # def __del__(self): # # dont delete files in debug mode # if self.debug: # print('leaving TmpdirFilesystem in "%s"' % self.path) # else: # self.delete() # # def delete(self): # shutil.rmtree(self.path, True) # # def __enter__(self): # return self # # def __exit__(self, exec_type, exec_value, tb): # shutil.rmtree(self.path) # return False # # Path: elbepack/rfs.py # def create_apt_prefs(xml, rfs): # # filename = "etc/apt/preferences" # # if rfs.lexists(filename): # rfs.remove(filename) # # rfs.mkdir_p("/etc/apt") # # pinned_origins = [] # if xml.has('project/mirror/url-list'): # for url in xml.node('project/mirror/url-list'): # if not url.has('binary'): # continue # # repo = url.node('binary') # if 'pin' not in repo.et.attrib: # continue # # origin = urlsplit(repo.et.text.strip()).hostname # pin = repo.et.attrib['pin'] # if 'package' in repo.et.attrib: # package = repo.et.attrib['package'] # else: # package = '*' # pinning = {'pin': pin, # 'origin': origin, # 'package': package} # pinned_origins.append(pinning) # # d = {"xml": xml, # "prj": xml.node("/project"), # "pkgs": xml.node("/target/pkg-list"), # "porgs": pinned_origins} # # write_pack_template(rfs.fname(filename), "preferences.mako", d) . Output only the next line.
system(cmd)
Based on the snippet: <|code_start|> return "", "", "" x = v.source.find_index(c.file_list[0][0]) r = apt_pkg.PackageRecords(v.cache) r.lookup(c.file_list[0]) uri = x.archive_uri(r.filename) if not x.is_trusted: return target_pkg, uri, "" try: # pylint: disable=no-member hashval = str(r.hashes.find('SHA256')).split(':')[1] except AttributeError: # TODO: this fallback Code can be removed on stretch # but it throws DeprecationWarning already hashval = r.sha256_hash return target_pkg, uri, hashval class VirtApt: def __init__(self, xml): # pylint: disable=too-many-statements self.xml = xml arch = xml.text("project/buildimage/arch", key="arch") suite = xml.text("project/suite") <|code_end|> , predict the immediate next line with the help of imports: import os import sys import apt # pylint: disable=unused-import import apt_pkg from elbepack.shellhelper import system from elbepack.filesystem import TmpdirFilesystem from elbepack.rfs import create_apt_prefs and context (classes, functions, sometimes code) from other files: # Path: elbepack/shellhelper.py # def system(cmd, allow_fail=False, env_add=None): # """system() - Execute cmd in a shell. # # Throws a CommandError if cmd returns none-zero and allow_fail=False # # -- # # >>> system("true") # # >>> system("false", allow_fail=True) # # >>> system("$FALSE", env_add={"FALSE":"false"}) # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # # """ # new_env = os.environ.copy() # if env_add: # new_env.update(env_add) # # ret = call(cmd, shell=True, env=new_env) # # if ret != 0: # if not allow_fail: # raise CommandError(cmd, ret) # # Path: elbepack/filesystem.py # class TmpdirFilesystem (Filesystem): # def __init__(self, debug=False): # tmpdir = mkdtemp() # Filesystem.__init__(self, tmpdir) # self.debug = debug # # def __del__(self): # # dont delete files in debug mode # if self.debug: # print('leaving TmpdirFilesystem in "%s"' % self.path) # else: # self.delete() # # def delete(self): # shutil.rmtree(self.path, True) # # def __enter__(self): # return self # # def __exit__(self, exec_type, exec_value, tb): # shutil.rmtree(self.path) # return False # # Path: elbepack/rfs.py # def create_apt_prefs(xml, rfs): # # filename = "etc/apt/preferences" # # if rfs.lexists(filename): # rfs.remove(filename) # # rfs.mkdir_p("/etc/apt") # # pinned_origins = [] # if xml.has('project/mirror/url-list'): # for url in xml.node('project/mirror/url-list'): # if not url.has('binary'): # continue # # repo = url.node('binary') # if 'pin' not in repo.et.attrib: # continue # # origin = urlsplit(repo.et.text.strip()).hostname # pin = repo.et.attrib['pin'] # if 'package' in repo.et.attrib: # package = repo.et.attrib['package'] # else: # package = '*' # pinning = {'pin': pin, # 'origin': origin, # 'package': package} # pinned_origins.append(pinning) # # d = {"xml": xml, # "prj": xml.node("/project"), # "pkgs": xml.node("/target/pkg-list"), # "porgs": pinned_origins} # # write_pack_template(rfs.fname(filename), "preferences.mako", d) . Output only the next line.
self.basefs = TmpdirFilesystem()
Given the following code snippet before the placeholder: <|code_start|> r = apt_pkg.PackageRecords(v.cache) r.lookup(c.file_list[0]) uri = x.archive_uri(r.filename) if not x.is_trusted: return target_pkg, uri, "" try: # pylint: disable=no-member hashval = str(r.hashes.find('SHA256')).split(':')[1] except AttributeError: # TODO: this fallback Code can be removed on stretch # but it throws DeprecationWarning already hashval = r.sha256_hash return target_pkg, uri, hashval class VirtApt: def __init__(self, xml): # pylint: disable=too-many-statements self.xml = xml arch = xml.text("project/buildimage/arch", key="arch") suite = xml.text("project/suite") self.basefs = TmpdirFilesystem() self.initialize_dirs() <|code_end|> , predict the next line using imports from the current file: import os import sys import apt # pylint: disable=unused-import import apt_pkg from elbepack.shellhelper import system from elbepack.filesystem import TmpdirFilesystem from elbepack.rfs import create_apt_prefs and context including class names, function names, and sometimes code from other files: # Path: elbepack/shellhelper.py # def system(cmd, allow_fail=False, env_add=None): # """system() - Execute cmd in a shell. # # Throws a CommandError if cmd returns none-zero and allow_fail=False # # -- # # >>> system("true") # # >>> system("false", allow_fail=True) # # >>> system("$FALSE", env_add={"FALSE":"false"}) # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # # """ # new_env = os.environ.copy() # if env_add: # new_env.update(env_add) # # ret = call(cmd, shell=True, env=new_env) # # if ret != 0: # if not allow_fail: # raise CommandError(cmd, ret) # # Path: elbepack/filesystem.py # class TmpdirFilesystem (Filesystem): # def __init__(self, debug=False): # tmpdir = mkdtemp() # Filesystem.__init__(self, tmpdir) # self.debug = debug # # def __del__(self): # # dont delete files in debug mode # if self.debug: # print('leaving TmpdirFilesystem in "%s"' % self.path) # else: # self.delete() # # def delete(self): # shutil.rmtree(self.path, True) # # def __enter__(self): # return self # # def __exit__(self, exec_type, exec_value, tb): # shutil.rmtree(self.path) # return False # # Path: elbepack/rfs.py # def create_apt_prefs(xml, rfs): # # filename = "etc/apt/preferences" # # if rfs.lexists(filename): # rfs.remove(filename) # # rfs.mkdir_p("/etc/apt") # # pinned_origins = [] # if xml.has('project/mirror/url-list'): # for url in xml.node('project/mirror/url-list'): # if not url.has('binary'): # continue # # repo = url.node('binary') # if 'pin' not in repo.et.attrib: # continue # # origin = urlsplit(repo.et.text.strip()).hostname # pin = repo.et.attrib['pin'] # if 'package' in repo.et.attrib: # package = repo.et.attrib['package'] # else: # package = '*' # pinning = {'pin': pin, # 'origin': origin, # 'package': package} # pinned_origins.append(pinning) # # d = {"xml": xml, # "prj": xml.node("/project"), # "pkgs": xml.node("/target/pkg-list"), # "porgs": pinned_origins} # # write_pack_template(rfs.fname(filename), "preferences.mako", d) . Output only the next line.
create_apt_prefs(self.xml, self.basefs)
Given the following code snippet before the placeholder: <|code_start|> oparser.add_option("--pass", dest="passwd", default=cfg['elbepass'], help="Password (default is foo).") oparser.add_option("--user", dest="user", default=cfg['elbeuser'], help="Username (default is root).") oparser.add_option( "--retries", dest="retries", default="10", help="How many times to retry the connection to the server before\ giving up (default is 10 times, yielding 10 seconds).") devel = OptionGroup( oparser, "options for elbe developers", "Caution: Don't use these options in a productive environment") devel.add_option("--debug", action="store_true", dest="debug", default=False, help="Enable debug mode.") devel.add_option("--ignore-version-diff", action="store_true", dest="ignore_version", default=False, help="allow different elbe version on host and initvm") oparser.add_option_group(devel) (opt, args) = oparser.parse_args(argv) if not args: print("elbe prjrepo - no subcommand given", file=sys.stderr) <|code_end|> , predict the next line using imports from the current file: import socket import sys from http.client import BadStatusLine from optparse import (OptionParser, OptionGroup) from urllib.error import URLError from suds import WebFault from elbepack.soapclient import RepoAction, ElbeSoapClient from elbepack.version import elbe_version from elbepack.config import cfg and context including class names, function names, and sometimes code from other files: # Path: elbepack/soapclient.py # class RepoAction(ClientAction): # repoactiondict = {} # # @classmethod # def register(cls, action): # cls.repoactiondict[action.tag] = action # # @classmethod # def print_actions(cls): # print("available subcommands are:", file=sys.stderr) # for a in cls.repoactiondict: # print(" %s" % a, file=sys.stderr) # # def __new__(cls, node): # action = cls.repoactiondict[node] # return object.__new__(action) # # def execute(self, _client, _opt, _args): # raise NotImplementedError('execute() not implemented') # # class ElbeSoapClient: # def __init__(self, host, port, user, passwd, retries=10, debug=False): # # # pylint: disable=too-many-arguments # # # Mess with suds logging, for debug, or squelch warnings # set_suds_debug(debug) # # # Attributes # self.wsdl = "http://" + host + ":" + str(port) + "/soap/?wsdl" # self.control = None # self.retries = 0 # # # Loop and try to connect # while self.control is None: # self.retries += 1 # try: # self.control = Client(self.wsdl, timeout=cfg['soaptimeout']) # except URLError as e: # if self.retries > retries: # raise e # time.sleep(1) # except socket.error as e: # if self.retries > retries: # raise e # time.sleep(1) # except BadStatusLine as e: # if self.retries > retries: # raise e # time.sleep(1) # # # Make sure, that client.service still maps # # to the service object. # self.service = self.control.service # # # We have a Connection, now login # self.service.login(user, passwd) # # def download_file(self, builddir, filename, dst_fname): # fp = open(dst_fname, "wb") # part = 0 # # # XXX the retry logic might get removed in the future, if the error # # doesn't occur in real world. If it occurs, we should think about # # the root cause instead of stupid retrying. # retry = 5 # # while True: # try: # ret = self.service.get_file(builddir, filename, part) # except BadStatusLine as e: # retry = retry - 1 # # print("get_file part %d failed, retry %d times" % (part, retry), # file=sys.stderr) # print(str(e), file=sys.stderr) # print(repr(e.line), file=sys.stderr) # # if not retry: # fp.close() # print("file transfer failed", file=sys.stderr) # sys.exit(20) # # if ret == "FileNotFound": # print(ret, file=sys.stderr) # sys.exit(20) # if ret == "EndOfFile": # fp.close() # return # # fp.write(binascii.a2b_base64(ret)) # part = part + 1 # # Path: elbepack/version.py # # Path: elbepack/config.py # class Config(dict): # def __init__(self): . Output only the next line.
RepoAction.print_actions()
Based on the snippet: <|code_start|> oparser.add_option( "--retries", dest="retries", default="10", help="How many times to retry the connection to the server before\ giving up (default is 10 times, yielding 10 seconds).") devel = OptionGroup( oparser, "options for elbe developers", "Caution: Don't use these options in a productive environment") devel.add_option("--debug", action="store_true", dest="debug", default=False, help="Enable debug mode.") devel.add_option("--ignore-version-diff", action="store_true", dest="ignore_version", default=False, help="allow different elbe version on host and initvm") oparser.add_option_group(devel) (opt, args) = oparser.parse_args(argv) if not args: print("elbe prjrepo - no subcommand given", file=sys.stderr) RepoAction.print_actions() return # Try to connect to initvm via SOAP try: <|code_end|> , predict the immediate next line with the help of imports: import socket import sys from http.client import BadStatusLine from optparse import (OptionParser, OptionGroup) from urllib.error import URLError from suds import WebFault from elbepack.soapclient import RepoAction, ElbeSoapClient from elbepack.version import elbe_version from elbepack.config import cfg and context (classes, functions, sometimes code) from other files: # Path: elbepack/soapclient.py # class RepoAction(ClientAction): # repoactiondict = {} # # @classmethod # def register(cls, action): # cls.repoactiondict[action.tag] = action # # @classmethod # def print_actions(cls): # print("available subcommands are:", file=sys.stderr) # for a in cls.repoactiondict: # print(" %s" % a, file=sys.stderr) # # def __new__(cls, node): # action = cls.repoactiondict[node] # return object.__new__(action) # # def execute(self, _client, _opt, _args): # raise NotImplementedError('execute() not implemented') # # class ElbeSoapClient: # def __init__(self, host, port, user, passwd, retries=10, debug=False): # # # pylint: disable=too-many-arguments # # # Mess with suds logging, for debug, or squelch warnings # set_suds_debug(debug) # # # Attributes # self.wsdl = "http://" + host + ":" + str(port) + "/soap/?wsdl" # self.control = None # self.retries = 0 # # # Loop and try to connect # while self.control is None: # self.retries += 1 # try: # self.control = Client(self.wsdl, timeout=cfg['soaptimeout']) # except URLError as e: # if self.retries > retries: # raise e # time.sleep(1) # except socket.error as e: # if self.retries > retries: # raise e # time.sleep(1) # except BadStatusLine as e: # if self.retries > retries: # raise e # time.sleep(1) # # # Make sure, that client.service still maps # # to the service object. # self.service = self.control.service # # # We have a Connection, now login # self.service.login(user, passwd) # # def download_file(self, builddir, filename, dst_fname): # fp = open(dst_fname, "wb") # part = 0 # # # XXX the retry logic might get removed in the future, if the error # # doesn't occur in real world. If it occurs, we should think about # # the root cause instead of stupid retrying. # retry = 5 # # while True: # try: # ret = self.service.get_file(builddir, filename, part) # except BadStatusLine as e: # retry = retry - 1 # # print("get_file part %d failed, retry %d times" % (part, retry), # file=sys.stderr) # print(str(e), file=sys.stderr) # print(repr(e.line), file=sys.stderr) # # if not retry: # fp.close() # print("file transfer failed", file=sys.stderr) # sys.exit(20) # # if ret == "FileNotFound": # print(ret, file=sys.stderr) # sys.exit(20) # if ret == "EndOfFile": # fp.close() # return # # fp.write(binascii.a2b_base64(ret)) # part = part + 1 # # Path: elbepack/version.py # # Path: elbepack/config.py # class Config(dict): # def __init__(self): . Output only the next line.
control = ElbeSoapClient(
Next line prediction: <|code_start|> opt.retries)) except URLError as e: print("Failed to connect to Soap server %s:%s\n" % (opt.host, opt.port), file=sys.stderr) print("", file=sys.stderr) print("Check, wether the initvm is actually running.", file=sys.stderr) print("try `elbe initvm start`", file=sys.stderr) sys.exit(10) except socket.error as e: print("Failed to connect to Soap server %s:%s\n" % (opt.host, opt.port), file=sys.stderr) print("", file=sys.stderr) print( "Check, wether the Soap Server is running inside the initvm", file=sys.stderr) print("try 'elbe initvm attach'", file=sys.stderr) sys.exit(10) except BadStatusLine as e: print("Failed to connect to Soap server %s:%s\n" % (opt.host, opt.port), file=sys.stderr) print("", file=sys.stderr) print("Check, wether the initvm is actually running.", file=sys.stderr) print( "try 'elbe initvm --directory /path/to/initvm start'", file=sys.stderr) sys.exit(10) # Check Elbe version try: v_server = control.service.get_version() <|code_end|> . Use current file imports: (import socket import sys from http.client import BadStatusLine from optparse import (OptionParser, OptionGroup) from urllib.error import URLError from suds import WebFault from elbepack.soapclient import RepoAction, ElbeSoapClient from elbepack.version import elbe_version from elbepack.config import cfg) and context including class names, function names, or small code snippets from other files: # Path: elbepack/soapclient.py # class RepoAction(ClientAction): # repoactiondict = {} # # @classmethod # def register(cls, action): # cls.repoactiondict[action.tag] = action # # @classmethod # def print_actions(cls): # print("available subcommands are:", file=sys.stderr) # for a in cls.repoactiondict: # print(" %s" % a, file=sys.stderr) # # def __new__(cls, node): # action = cls.repoactiondict[node] # return object.__new__(action) # # def execute(self, _client, _opt, _args): # raise NotImplementedError('execute() not implemented') # # class ElbeSoapClient: # def __init__(self, host, port, user, passwd, retries=10, debug=False): # # # pylint: disable=too-many-arguments # # # Mess with suds logging, for debug, or squelch warnings # set_suds_debug(debug) # # # Attributes # self.wsdl = "http://" + host + ":" + str(port) + "/soap/?wsdl" # self.control = None # self.retries = 0 # # # Loop and try to connect # while self.control is None: # self.retries += 1 # try: # self.control = Client(self.wsdl, timeout=cfg['soaptimeout']) # except URLError as e: # if self.retries > retries: # raise e # time.sleep(1) # except socket.error as e: # if self.retries > retries: # raise e # time.sleep(1) # except BadStatusLine as e: # if self.retries > retries: # raise e # time.sleep(1) # # # Make sure, that client.service still maps # # to the service object. # self.service = self.control.service # # # We have a Connection, now login # self.service.login(user, passwd) # # def download_file(self, builddir, filename, dst_fname): # fp = open(dst_fname, "wb") # part = 0 # # # XXX the retry logic might get removed in the future, if the error # # doesn't occur in real world. If it occurs, we should think about # # the root cause instead of stupid retrying. # retry = 5 # # while True: # try: # ret = self.service.get_file(builddir, filename, part) # except BadStatusLine as e: # retry = retry - 1 # # print("get_file part %d failed, retry %d times" % (part, retry), # file=sys.stderr) # print(str(e), file=sys.stderr) # print(repr(e.line), file=sys.stderr) # # if not retry: # fp.close() # print("file transfer failed", file=sys.stderr) # sys.exit(20) # # if ret == "FileNotFound": # print(ret, file=sys.stderr) # sys.exit(20) # if ret == "EndOfFile": # fp.close() # return # # fp.write(binascii.a2b_base64(ret)) # part = part + 1 # # Path: elbepack/version.py # # Path: elbepack/config.py # class Config(dict): # def __init__(self): . Output only the next line.
if v_server != elbe_version:
Given the following code snippet before the placeholder: <|code_start|> return s.replace('\\\n', '${"\\\\"}\n') def template(fname, d, linebreak=False): try: if linebreak: return Template( filename=fname, preprocessor=fix_linebreak_escapes).render( **d) return Template(filename=fname).render(**d) except BaseException: print(exceptions.text_error_template().render()) raise def write_template(outname, fname, d, linebreak=False): outfile = open(outname, "w") outfile.write(template(fname, d, linebreak)) outfile.close() def write_pack_template(outname, fname, d, linebreak=False): template_name = os.path.join(mako_template_dir, fname) write_template(outname, template_name, d, linebreak) def get_preseed(xml): <|code_end|> , predict the next line using imports from the current file: import os from mako.template import Template from mako import exceptions from elbepack.treeutils import etree from elbepack.directories import mako_template_dir, default_preseed_fname and context including class names, function names, and sometimes code from other files: # Path: elbepack/treeutils.py # class etree(ebase): # def __init__(self, fname): # if fname is not None: # parser = XMLParser(huge_tree=True, remove_comments=False) # et = parse(fname, parser=parser) # else: # et = ElementTree(file=None) # # ebase.__init__(self, et) # # def write(self, fname, encoding=None): # # Make sure, that we end with a newline # self.et.getroot().tail = '\n' # self.et.write(fname, encoding=encoding) # # def tostring(self): # return self.et.tostring() # # def ensure_child(self, tag): # retval = self.et.find("./" + tag) # if retval is not None: # return elem(retval) # return elem(SubElement(self.et.getroot(), tag)) # # def set_child_position(self, child, pos): # root = self.et.getroot() # root.remove(child.et) # root.insert(pos, child.et) # # def setroot(self, tag): # retval = elem(Element(tag)) # # pylint: disable=protected-access # self.et._setroot(retval.et) # return retval # # @property # def root(self): # return elem(self.et.getroot()) # # Path: elbepack/directories.py # def init_directories(elbe_relpath): # def get_cmdlist(): . Output only the next line.
def_xml = etree(default_preseed_fname)
Based on the snippet: <|code_start|># SPDX-License-Identifier: GPL-3.0-or-later def fix_linebreak_escapes(s): return s.replace('\\\n', '${"\\\\"}\n') def template(fname, d, linebreak=False): try: if linebreak: return Template( filename=fname, preprocessor=fix_linebreak_escapes).render( **d) return Template(filename=fname).render(**d) except BaseException: print(exceptions.text_error_template().render()) raise def write_template(outname, fname, d, linebreak=False): outfile = open(outname, "w") outfile.write(template(fname, d, linebreak)) outfile.close() def write_pack_template(outname, fname, d, linebreak=False): <|code_end|> , predict the immediate next line with the help of imports: import os from mako.template import Template from mako import exceptions from elbepack.treeutils import etree from elbepack.directories import mako_template_dir, default_preseed_fname and context (classes, functions, sometimes code) from other files: # Path: elbepack/treeutils.py # class etree(ebase): # def __init__(self, fname): # if fname is not None: # parser = XMLParser(huge_tree=True, remove_comments=False) # et = parse(fname, parser=parser) # else: # et = ElementTree(file=None) # # ebase.__init__(self, et) # # def write(self, fname, encoding=None): # # Make sure, that we end with a newline # self.et.getroot().tail = '\n' # self.et.write(fname, encoding=encoding) # # def tostring(self): # return self.et.tostring() # # def ensure_child(self, tag): # retval = self.et.find("./" + tag) # if retval is not None: # return elem(retval) # return elem(SubElement(self.et.getroot(), tag)) # # def set_child_position(self, child, pos): # root = self.et.getroot() # root.remove(child.et) # root.insert(pos, child.et) # # def setroot(self, tag): # retval = elem(Element(tag)) # # pylint: disable=protected-access # self.et._setroot(retval.et) # return retval # # @property # def root(self): # return elem(self.et.getroot()) # # Path: elbepack/directories.py # def init_directories(elbe_relpath): # def get_cmdlist(): . Output only the next line.
template_name = os.path.join(mako_template_dir, fname)
Next line prediction: <|code_start|> return s.replace('\\\n', '${"\\\\"}\n') def template(fname, d, linebreak=False): try: if linebreak: return Template( filename=fname, preprocessor=fix_linebreak_escapes).render( **d) return Template(filename=fname).render(**d) except BaseException: print(exceptions.text_error_template().render()) raise def write_template(outname, fname, d, linebreak=False): outfile = open(outname, "w") outfile.write(template(fname, d, linebreak)) outfile.close() def write_pack_template(outname, fname, d, linebreak=False): template_name = os.path.join(mako_template_dir, fname) write_template(outname, template_name, d, linebreak) def get_preseed(xml): <|code_end|> . Use current file imports: (import os from mako.template import Template from mako import exceptions from elbepack.treeutils import etree from elbepack.directories import mako_template_dir, default_preseed_fname) and context including class names, function names, or small code snippets from other files: # Path: elbepack/treeutils.py # class etree(ebase): # def __init__(self, fname): # if fname is not None: # parser = XMLParser(huge_tree=True, remove_comments=False) # et = parse(fname, parser=parser) # else: # et = ElementTree(file=None) # # ebase.__init__(self, et) # # def write(self, fname, encoding=None): # # Make sure, that we end with a newline # self.et.getroot().tail = '\n' # self.et.write(fname, encoding=encoding) # # def tostring(self): # return self.et.tostring() # # def ensure_child(self, tag): # retval = self.et.find("./" + tag) # if retval is not None: # return elem(retval) # return elem(SubElement(self.et.getroot(), tag)) # # def set_child_position(self, child, pos): # root = self.et.getroot() # root.remove(child.et) # root.insert(pos, child.et) # # def setroot(self, tag): # retval = elem(Element(tag)) # # pylint: disable=protected-access # self.et._setroot(retval.et) # return retval # # @property # def root(self): # return elem(self.et.getroot()) # # Path: elbepack/directories.py # def init_directories(elbe_relpath): # def get_cmdlist(): . Output only the next line.
def_xml = etree(default_preseed_fname)
Predict the next line after this snippet: <|code_start|># ELBE - Debian Based Embedded Rootfilesystem Builder # Copyright (c) 2020 Olivier Dion <dion@linutronix.de> # Copyright (c) 2020 Torben Hohn <torbenh@linutronix.de> # # SPDX-License-Identifier: GPL-3.0-or-later # Since this is just an example on how to make tests, we skip them class TestElbepackVersion(unittest.TestCase): # This is a read-only state that is the same for every tests expected_version = "14.1" def setUp(self): # This is a mutable state that is different for every tests self.my_list = [] def tearDown(self): # You might want to cleanup your mutable states here pass def test_version(self): self.my_list.append(1) <|code_end|> using the current file's imports: import unittest from elbepack.version import elbe_version and any relevant context from other files: # Path: elbepack/version.py . Output only the next line.
self.assertEqual(elbe_version, self.expected_version)
Based on the snippet: <|code_start|># ELBE - Debian Based Embedded Rootfilesystem Builder # Copyright (c) 2019 Torben Hohn <torben.hohn@linutronix.de> # # SPDX-License-Identifier: GPL-3.0-or-later class Packer: def pack_file(self, _builddir, _fname): raise NotImplementedError('abstract method called') class NoPacker(Packer): def pack_file(self, _builddir, fname): return fname class InPlacePacker(Packer): def __init__(self, cmd, suffix): self.cmd = cmd self.suffix = suffix def pack_file(self, builddir, fname): try: fpath = os.path.join(builddir, fname) do('%s "%s"' % (self.cmd, fpath)) <|code_end|> , predict the immediate next line with the help of imports: import os from elbepack.shellhelper import CommandError, do and context (classes, functions, sometimes code) from other files: # Path: elbepack/shellhelper.py # class CommandError(Exception): # # def __init__(self, cmd, returncode): # super(CommandError, self).__init__(cmd, returncode) # self.returncode = returncode # self.cmd = cmd # # def __str__(self): # return "Error: %d returned from Command %s" % ( # self.returncode, self.cmd) # # def do(cmd, allow_fail=False, stdin=None, env_add=None): # """do() - Execute cmd in a shell and redirect outputs to logging. # # Throws a CommandError if cmd failed with allow_Fail=False. # # -- # # Let's redirect the loggers to current stdout # >>> import sys # >>> from elbepack.log import open_logging # >>> open_logging({"streams":sys.stdout}) # # >>> do("true") # [CMD] true # # >>> do("false", allow_fail=True) # [CMD] false # # >>> do("cat -", stdin=b"ELBE") # [CMD] cat - # # >>> do("cat - && false", stdin=b"ELBE") # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # # >>> do("false") # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # """ # # new_env = os.environ.copy() # if env_add: # new_env.update(env_add) # # if isinstance(stdin, str): # stdin = stdin.encode() # # logging.info(cmd, extra={"context":"[CMD] "}) # # r, w = os.pipe() # # if stdin is None: # p = Popen(cmd, shell=True, stdout=w, stderr=STDOUT, env=new_env) # else: # p = Popen(cmd, shell=True, stdin=PIPE, stdout=w, stderr=STDOUT, env=new_env) # # async_logging(r, w, soap, log) # p.communicate(input=stdin) # # if p.returncode and not allow_fail: # raise CommandError(cmd, p.returncode) . Output only the next line.
except CommandError:
Continue the code snippet: <|code_start|># ELBE - Debian Based Embedded Rootfilesystem Builder # Copyright (c) 2019 Torben Hohn <torben.hohn@linutronix.de> # # SPDX-License-Identifier: GPL-3.0-or-later class Packer: def pack_file(self, _builddir, _fname): raise NotImplementedError('abstract method called') class NoPacker(Packer): def pack_file(self, _builddir, fname): return fname class InPlacePacker(Packer): def __init__(self, cmd, suffix): self.cmd = cmd self.suffix = suffix def pack_file(self, builddir, fname): try: fpath = os.path.join(builddir, fname) <|code_end|> . Use current file imports: import os from elbepack.shellhelper import CommandError, do and context (classes, functions, or code) from other files: # Path: elbepack/shellhelper.py # class CommandError(Exception): # # def __init__(self, cmd, returncode): # super(CommandError, self).__init__(cmd, returncode) # self.returncode = returncode # self.cmd = cmd # # def __str__(self): # return "Error: %d returned from Command %s" % ( # self.returncode, self.cmd) # # def do(cmd, allow_fail=False, stdin=None, env_add=None): # """do() - Execute cmd in a shell and redirect outputs to logging. # # Throws a CommandError if cmd failed with allow_Fail=False. # # -- # # Let's redirect the loggers to current stdout # >>> import sys # >>> from elbepack.log import open_logging # >>> open_logging({"streams":sys.stdout}) # # >>> do("true") # [CMD] true # # >>> do("false", allow_fail=True) # [CMD] false # # >>> do("cat -", stdin=b"ELBE") # [CMD] cat - # # >>> do("cat - && false", stdin=b"ELBE") # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # # >>> do("false") # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # """ # # new_env = os.environ.copy() # if env_add: # new_env.update(env_add) # # if isinstance(stdin, str): # stdin = stdin.encode() # # logging.info(cmd, extra={"context":"[CMD] "}) # # r, w = os.pipe() # # if stdin is None: # p = Popen(cmd, shell=True, stdout=w, stderr=STDOUT, env=new_env) # else: # p = Popen(cmd, shell=True, stdin=PIPE, stdout=w, stderr=STDOUT, env=new_env) # # async_logging(r, w, soap, log) # p.communicate(input=stdin) # # if p.returncode and not allow_fail: # raise CommandError(cmd, p.returncode) . Output only the next line.
do('%s "%s"' % (self.cmd, fpath))
Based on the snippet: <|code_start|> tmpdir = mkdtemp() Filesystem.__init__(self, tmpdir) self.debug = debug def __del__(self): # dont delete files in debug mode if self.debug: print('leaving TmpdirFilesystem in "%s"' % self.path) else: self.delete() def delete(self): shutil.rmtree(self.path, True) def __enter__(self): return self def __exit__(self, exec_type, exec_value, tb): shutil.rmtree(self.path) return False class ImgMountFilesystem(Filesystem): def __init__(self, mntpoint, dev): Filesystem.__init__(self, mntpoint) self.dev = dev def __enter__(self): cmd = 'mount "%s" "%s"' % (self.dev, self.path) <|code_end|> , predict the immediate next line with the help of imports: import os import shutil import errno import gzip from glob import glob from tempfile import mkdtemp from string import digits from elbepack.shellhelper import do and context (classes, functions, sometimes code) from other files: # Path: elbepack/shellhelper.py # def do(cmd, allow_fail=False, stdin=None, env_add=None): # """do() - Execute cmd in a shell and redirect outputs to logging. # # Throws a CommandError if cmd failed with allow_Fail=False. # # -- # # Let's redirect the loggers to current stdout # >>> import sys # >>> from elbepack.log import open_logging # >>> open_logging({"streams":sys.stdout}) # # >>> do("true") # [CMD] true # # >>> do("false", allow_fail=True) # [CMD] false # # >>> do("cat -", stdin=b"ELBE") # [CMD] cat - # # >>> do("cat - && false", stdin=b"ELBE") # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # # >>> do("false") # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # """ # # new_env = os.environ.copy() # if env_add: # new_env.update(env_add) # # if isinstance(stdin, str): # stdin = stdin.encode() # # logging.info(cmd, extra={"context":"[CMD] "}) # # r, w = os.pipe() # # if stdin is None: # p = Popen(cmd, shell=True, stdout=w, stderr=STDOUT, env=new_env) # else: # p = Popen(cmd, shell=True, stdin=PIPE, stdout=w, stderr=STDOUT, env=new_env) # # async_logging(r, w, soap, log) # p.communicate(input=stdin) # # if p.returncode and not allow_fail: # raise CommandError(cmd, p.returncode) . Output only the next line.
do(cmd)
Given the code snippet: <|code_start|># Copyright (c) 2017 Manuel Traut <manut@linutronix.de> # # SPDX-License-Identifier: GPL-3.0-or-later kvm_exe_list = [ '/usr/bin/kvm', '/usr/bin/qemu-kvm', '/usr/libexec/qemu-kvm', '/usr/bin/qemu-system-x86_64' ] cached_kvm_infos = None def find_kvm_exe(): # pylint: disable=global-statement global cached_kvm_infos if cached_kvm_infos: return cached_kvm_infos version = "0.0.0" args = [] for fname in kvm_exe_list: if os.path.isfile(fname) and os.access(fname, os.X_OK): # determine kvm version <|code_end|> , generate the next line using the imports in this file: import os from elbepack.shellhelper import command_out and context (functions, classes, or occasionally code) from other files: # Path: elbepack/shellhelper.py # def command_out(cmd, stdin=None, output=PIPE, env_add=None): # """command_out() - Execute cmd in a shell. # # Returns a tuple with the exitcode and the output of cmd. # # -- # # >>> command_out("true") # (0, '') # # >>> command_out("$TRUE && true", env_add={"TRUE":"true"}) # (0, '') # # >>> command_out("cat -", stdin=b"ELBE") # (0, 'ELBE') # # >>> command_out("2>&1 cat -", stdin=b"ELBE") # (0, 'ELBE') # # >>> command_out("2>&1 cat -", stdin="ELBE") # (0, 'ELBE') # # >>> command_out("false") # (1, '') # # """ # new_env = os.environ.copy() # if env_add: # new_env.update(env_add) # # if isinstance(stdin, str): # stdin = stdin.encode() # # if stdin is None: # p = Popen(cmd, shell=True, # stdout=output, stderr=STDOUT, env=new_env) # out, _ = p.communicate() # else: # p = Popen(cmd, shell=True, # stdout=output, stderr=STDOUT, stdin=PIPE, env=new_env) # out, _ = p.communicate(input=stdin) # # out = TextIOWrapper(BytesIO(out), encoding='utf-8', errors='replace').read() # # return p.returncode, out . Output only the next line.
_, stdout = command_out(fname + ' --version')
Given snippet: <|code_start|># ELBE - Debian Based Embedded Rootfilesystem Builder # Copyright (c) 2016-2017 Manuel Traut <manut@linutronix.de> # Copyright (c) 2017 Torben Hohn <torben.hohn@linutronix.de> # # SPDX-License-Identifier: GPL-3.0-or-later def run_command(_args): if os.path.exists('debian'): print("debian folder already exists, nothing to do") sys.exit(10) try: <|code_end|> , continue by predicting the next line. Consider current file imports: import os import sys from elbepack.debianize.base.tui import TUI from elbepack.debianize.panels.factory import detect_panel and context: # Path: elbepack/debianize/base/tui.py # class TUI(object): # # palette = [ # ("blue_head", "dark blue", ""), # ("red_head", "dark red", ""), # ("header", "bold, underline, default", ""), # ("error", "bold, light red", ""), # ("normal_box", "default", "default"), # ("selected_box", "black", "light gray"), # ("confirm_button", "default", "dark green"), # ("abort_button", "light red", "dark red"), # ("progress_low", "default", "yellow"), # ("progress_hight", "default", "dark green"), # ("helper_key", "bold", "default"), # ("helper_text_brown", "black", "brown"), # ("helper_text_red", "black", "dark red"), # ("helper_text_green", "black", "dark green"), # ("helper_text_light", "white", "dark blue"), # ] # # main_helper_text = generate_helper_text([ # ("C-f", "Forward", "helper_text_brown"), # ("C-b", "Backward", "helper_text_brown"), # ("C-p", "Previous", "helper_text_brown"), # ("C-n", "Next", "helper_text_brown"), # ("TAB", "Next", "helper_text_brown"), # ("backtab", "Previous", "helper_text_brown"), # ("C-\\", "Quit", "helper_text_red"), # ]) # # keybind = {} # # def __init__(self, body): # # TUI.root = Frame(body.root, # Text(("header", ""), "center"), # Text(TUI.main_helper_text, "center")) # # TUI.loop = MainLoop(TUI.root, TUI.palette, # unhandled_input=TUI.unhandled_input) # # TUI.install_signals_handler() # # def __call__(self): # TUI.loop.run() # # @classmethod # def focus_header(cls): # cls.root.focus_position = "header" # # @classmethod # def focus_body(cls): # cls.root.focus_position = "body" # # @classmethod # def focus_footer(cls): # cls.root.focus_position = "footer" # # @classmethod # def header(cls, flow_widget=None): # if flow_widget is not None: # if "flow" not in flow_widget.sizing(): # raise TUIException("Header must be of sizing flow") # cls.root.contents["header"] = flow_widget # return cls.root.contents["header"] # # @classmethod # def body(cls, box_widget=None): # if box_widget is not None: # if "box" not in box_widget.sizing(): # raise TUIException("Body must be of sizing box") # cls.root.contents["body"] = (box_widget, TUI.root.options()) # return cls.root.contents["body"] # # @classmethod # def footer(cls, flow_widget=None): # if flow_widget is not None: # if "flow" not in flow_widget.sizing(): # raise TUIException("Header must be of sizing flow") # cls.root.contents["footer"] = flow_widget # return cls.root.contents["footer"] # # @classmethod # def unhandled_input(cls, key): # if key in cls.keybind: # cls.keybind[key]() # return None # # @classmethod # def bind_global(cls, key, callback): # cls.keybind[key] = callback # # @classmethod # def printf(cls, fmt, *args): # cls.header()[0].set_text(("header", fmt.format(*args))) # # @classmethod # def clear(cls): # cls.printf("") # # @staticmethod # def quit(*args): # raise ExitMainLoop() # # @staticmethod # def pause(*args): # TUI.loop.stop() # os.kill(os.getpid(), signal.SIGSTOP) # TUI.loop.start() # TUI.loop.draw_screen() # # @staticmethod # def interrupt(*kargs): # pass # # @staticmethod # def install_signals_handler(): # # if os.sys.platform != "win32": # signal.signal(signal.SIGQUIT, TUI.quit) # signal.signal(signal.SIGTSTP, TUI.pause) # # signal.signal(signal.SIGINT, TUI.interrupt) # # Path: elbepack/debianize/panels/factory.py # def detect_panel(): # for panel in panels: # match = True # for f in panel.match_files: # if not os.path.exists(f): # match = False # break # if match: # return panel() # # raise KeyError which might include code, classes, or functions. Output only the next line.
TUI(detect_panel())()
Given snippet: <|code_start|># ELBE - Debian Based Embedded Rootfilesystem Builder # Copyright (c) 2016-2017 Manuel Traut <manut@linutronix.de> # Copyright (c) 2017 Torben Hohn <torben.hohn@linutronix.de> # # SPDX-License-Identifier: GPL-3.0-or-later def run_command(_args): if os.path.exists('debian'): print("debian folder already exists, nothing to do") sys.exit(10) try: <|code_end|> , continue by predicting the next line. Consider current file imports: import os import sys from elbepack.debianize.base.tui import TUI from elbepack.debianize.panels.factory import detect_panel and context: # Path: elbepack/debianize/base/tui.py # class TUI(object): # # palette = [ # ("blue_head", "dark blue", ""), # ("red_head", "dark red", ""), # ("header", "bold, underline, default", ""), # ("error", "bold, light red", ""), # ("normal_box", "default", "default"), # ("selected_box", "black", "light gray"), # ("confirm_button", "default", "dark green"), # ("abort_button", "light red", "dark red"), # ("progress_low", "default", "yellow"), # ("progress_hight", "default", "dark green"), # ("helper_key", "bold", "default"), # ("helper_text_brown", "black", "brown"), # ("helper_text_red", "black", "dark red"), # ("helper_text_green", "black", "dark green"), # ("helper_text_light", "white", "dark blue"), # ] # # main_helper_text = generate_helper_text([ # ("C-f", "Forward", "helper_text_brown"), # ("C-b", "Backward", "helper_text_brown"), # ("C-p", "Previous", "helper_text_brown"), # ("C-n", "Next", "helper_text_brown"), # ("TAB", "Next", "helper_text_brown"), # ("backtab", "Previous", "helper_text_brown"), # ("C-\\", "Quit", "helper_text_red"), # ]) # # keybind = {} # # def __init__(self, body): # # TUI.root = Frame(body.root, # Text(("header", ""), "center"), # Text(TUI.main_helper_text, "center")) # # TUI.loop = MainLoop(TUI.root, TUI.palette, # unhandled_input=TUI.unhandled_input) # # TUI.install_signals_handler() # # def __call__(self): # TUI.loop.run() # # @classmethod # def focus_header(cls): # cls.root.focus_position = "header" # # @classmethod # def focus_body(cls): # cls.root.focus_position = "body" # # @classmethod # def focus_footer(cls): # cls.root.focus_position = "footer" # # @classmethod # def header(cls, flow_widget=None): # if flow_widget is not None: # if "flow" not in flow_widget.sizing(): # raise TUIException("Header must be of sizing flow") # cls.root.contents["header"] = flow_widget # return cls.root.contents["header"] # # @classmethod # def body(cls, box_widget=None): # if box_widget is not None: # if "box" not in box_widget.sizing(): # raise TUIException("Body must be of sizing box") # cls.root.contents["body"] = (box_widget, TUI.root.options()) # return cls.root.contents["body"] # # @classmethod # def footer(cls, flow_widget=None): # if flow_widget is not None: # if "flow" not in flow_widget.sizing(): # raise TUIException("Header must be of sizing flow") # cls.root.contents["footer"] = flow_widget # return cls.root.contents["footer"] # # @classmethod # def unhandled_input(cls, key): # if key in cls.keybind: # cls.keybind[key]() # return None # # @classmethod # def bind_global(cls, key, callback): # cls.keybind[key] = callback # # @classmethod # def printf(cls, fmt, *args): # cls.header()[0].set_text(("header", fmt.format(*args))) # # @classmethod # def clear(cls): # cls.printf("") # # @staticmethod # def quit(*args): # raise ExitMainLoop() # # @staticmethod # def pause(*args): # TUI.loop.stop() # os.kill(os.getpid(), signal.SIGSTOP) # TUI.loop.start() # TUI.loop.draw_screen() # # @staticmethod # def interrupt(*kargs): # pass # # @staticmethod # def install_signals_handler(): # # if os.sys.platform != "win32": # signal.signal(signal.SIGQUIT, TUI.quit) # signal.signal(signal.SIGTSTP, TUI.pause) # # signal.signal(signal.SIGINT, TUI.interrupt) # # Path: elbepack/debianize/panels/factory.py # def detect_panel(): # for panel in panels: # match = True # for f in panel.match_files: # if not os.path.exists(f): # match = False # break # if match: # return panel() # # raise KeyError which might include code, classes, or functions. Output only the next line.
TUI(detect_panel())()
Using the snippet: <|code_start|>class hdpart: def __init__(self): # These attributes are filled later # using set_geometry() self.size = 0 self.offset = 0 self.filename = '' self.partnum = 0 self.number = '' def set_geometry(self, ppart, disk): sector_size = 512 self.offset = ppart.geometry.start * sector_size self.size = ppart.getLength() * sector_size self.filename = disk.device.path self.partnum = ppart.number self.number = '{}{}'.format(disk.type, ppart.number) def losetup(self): cmd = ('losetup --offset %d --sizelimit %d --find --show "%s"' % (self.offset, self.size, self.filename)) while True: try: loopdev = get_command_out(cmd) except CommandError as e: if e.returncode != 1: raise <|code_end|> , determine the next line of code. You have imports: import os import time from elbepack.shellhelper import do, get_command_out, CommandError and context (class names, function names, or code) available: # Path: elbepack/shellhelper.py # def do(cmd, allow_fail=False, stdin=None, env_add=None): # """do() - Execute cmd in a shell and redirect outputs to logging. # # Throws a CommandError if cmd failed with allow_Fail=False. # # -- # # Let's redirect the loggers to current stdout # >>> import sys # >>> from elbepack.log import open_logging # >>> open_logging({"streams":sys.stdout}) # # >>> do("true") # [CMD] true # # >>> do("false", allow_fail=True) # [CMD] false # # >>> do("cat -", stdin=b"ELBE") # [CMD] cat - # # >>> do("cat - && false", stdin=b"ELBE") # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # # >>> do("false") # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # """ # # new_env = os.environ.copy() # if env_add: # new_env.update(env_add) # # if isinstance(stdin, str): # stdin = stdin.encode() # # logging.info(cmd, extra={"context":"[CMD] "}) # # r, w = os.pipe() # # if stdin is None: # p = Popen(cmd, shell=True, stdout=w, stderr=STDOUT, env=new_env) # else: # p = Popen(cmd, shell=True, stdin=PIPE, stdout=w, stderr=STDOUT, env=new_env) # # async_logging(r, w, soap, log) # p.communicate(input=stdin) # # if p.returncode and not allow_fail: # raise CommandError(cmd, p.returncode) # # def get_command_out(cmd, stdin=None, allow_fail=False, env_add=None): # """get_command_out() - Like do() but returns stdout. # # -- # # Let's quiet the loggers # # >>> import os # >>> from elbepack.log import open_logging # >>> open_logging({"files":os.devnull}) # # >>> get_command_out("echo ELBE") # b'ELBE\\n' # # >>> get_command_out("false") # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # # >>> get_command_out("false", allow_fail=True) # b'' # # >>> get_command_out("cat -", stdin=b"ELBE", env_add={"TRUE":"true"}) # b'ELBE' # # >>> get_command_out("cat -", stdin="ELBE", env_add={"TRUE":"true"}) # b'ELBE' # """ # # new_env = os.environ.copy() # # if env_add: # new_env.update(env_add) # # if isinstance(stdin, str): # stdin = stdin.encode() # # logging.info(cmd, extra={"context":"[CMD] "}) # # r, w = os.pipe() # # if stdin is None: # p = Popen(cmd, shell=True, stdout=PIPE, stderr=w, env=new_env) # else: # p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=w, env=new_env) # # async_logging(r, w, soap, log) # stdout, _ = p.communicate(input=stdin) # # if p.returncode and not allow_fail: # raise CommandError(cmd, p.returncode) # # return stdout # # class CommandError(Exception): # # def __init__(self, cmd, returncode): # super(CommandError, self).__init__(cmd, returncode) # self.returncode = returncode # self.cmd = cmd # # def __str__(self): # return "Error: %d returned from Command %s" % ( # self.returncode, self.cmd) . Output only the next line.
do('sync')
Predict the next line for this snippet: <|code_start|> mplist = sorted(self.keys(), key=mountpoint_dict.mountdepth) return [self[x] for x in mplist] class hdpart: def __init__(self): # These attributes are filled later # using set_geometry() self.size = 0 self.offset = 0 self.filename = '' self.partnum = 0 self.number = '' def set_geometry(self, ppart, disk): sector_size = 512 self.offset = ppart.geometry.start * sector_size self.size = ppart.getLength() * sector_size self.filename = disk.device.path self.partnum = ppart.number self.number = '{}{}'.format(disk.type, ppart.number) def losetup(self): cmd = ('losetup --offset %d --sizelimit %d --find --show "%s"' % (self.offset, self.size, self.filename)) while True: try: <|code_end|> with the help of current file imports: import os import time from elbepack.shellhelper import do, get_command_out, CommandError and context from other files: # Path: elbepack/shellhelper.py # def do(cmd, allow_fail=False, stdin=None, env_add=None): # """do() - Execute cmd in a shell and redirect outputs to logging. # # Throws a CommandError if cmd failed with allow_Fail=False. # # -- # # Let's redirect the loggers to current stdout # >>> import sys # >>> from elbepack.log import open_logging # >>> open_logging({"streams":sys.stdout}) # # >>> do("true") # [CMD] true # # >>> do("false", allow_fail=True) # [CMD] false # # >>> do("cat -", stdin=b"ELBE") # [CMD] cat - # # >>> do("cat - && false", stdin=b"ELBE") # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # # >>> do("false") # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # """ # # new_env = os.environ.copy() # if env_add: # new_env.update(env_add) # # if isinstance(stdin, str): # stdin = stdin.encode() # # logging.info(cmd, extra={"context":"[CMD] "}) # # r, w = os.pipe() # # if stdin is None: # p = Popen(cmd, shell=True, stdout=w, stderr=STDOUT, env=new_env) # else: # p = Popen(cmd, shell=True, stdin=PIPE, stdout=w, stderr=STDOUT, env=new_env) # # async_logging(r, w, soap, log) # p.communicate(input=stdin) # # if p.returncode and not allow_fail: # raise CommandError(cmd, p.returncode) # # def get_command_out(cmd, stdin=None, allow_fail=False, env_add=None): # """get_command_out() - Like do() but returns stdout. # # -- # # Let's quiet the loggers # # >>> import os # >>> from elbepack.log import open_logging # >>> open_logging({"files":os.devnull}) # # >>> get_command_out("echo ELBE") # b'ELBE\\n' # # >>> get_command_out("false") # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # # >>> get_command_out("false", allow_fail=True) # b'' # # >>> get_command_out("cat -", stdin=b"ELBE", env_add={"TRUE":"true"}) # b'ELBE' # # >>> get_command_out("cat -", stdin="ELBE", env_add={"TRUE":"true"}) # b'ELBE' # """ # # new_env = os.environ.copy() # # if env_add: # new_env.update(env_add) # # if isinstance(stdin, str): # stdin = stdin.encode() # # logging.info(cmd, extra={"context":"[CMD] "}) # # r, w = os.pipe() # # if stdin is None: # p = Popen(cmd, shell=True, stdout=PIPE, stderr=w, env=new_env) # else: # p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=w, env=new_env) # # async_logging(r, w, soap, log) # stdout, _ = p.communicate(input=stdin) # # if p.returncode and not allow_fail: # raise CommandError(cmd, p.returncode) # # return stdout # # class CommandError(Exception): # # def __init__(self, cmd, returncode): # super(CommandError, self).__init__(cmd, returncode) # self.returncode = returncode # self.cmd = cmd # # def __str__(self): # return "Error: %d returned from Command %s" % ( # self.returncode, self.cmd) , which may contain function names, class names, or code. Output only the next line.
loopdev = get_command_out(cmd)
Using the snippet: <|code_start|> return [self[x] for x in mplist] class hdpart: def __init__(self): # These attributes are filled later # using set_geometry() self.size = 0 self.offset = 0 self.filename = '' self.partnum = 0 self.number = '' def set_geometry(self, ppart, disk): sector_size = 512 self.offset = ppart.geometry.start * sector_size self.size = ppart.getLength() * sector_size self.filename = disk.device.path self.partnum = ppart.number self.number = '{}{}'.format(disk.type, ppart.number) def losetup(self): cmd = ('losetup --offset %d --sizelimit %d --find --show "%s"' % (self.offset, self.size, self.filename)) while True: try: loopdev = get_command_out(cmd) <|code_end|> , determine the next line of code. You have imports: import os import time from elbepack.shellhelper import do, get_command_out, CommandError and context (class names, function names, or code) available: # Path: elbepack/shellhelper.py # def do(cmd, allow_fail=False, stdin=None, env_add=None): # """do() - Execute cmd in a shell and redirect outputs to logging. # # Throws a CommandError if cmd failed with allow_Fail=False. # # -- # # Let's redirect the loggers to current stdout # >>> import sys # >>> from elbepack.log import open_logging # >>> open_logging({"streams":sys.stdout}) # # >>> do("true") # [CMD] true # # >>> do("false", allow_fail=True) # [CMD] false # # >>> do("cat -", stdin=b"ELBE") # [CMD] cat - # # >>> do("cat - && false", stdin=b"ELBE") # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # # >>> do("false") # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # """ # # new_env = os.environ.copy() # if env_add: # new_env.update(env_add) # # if isinstance(stdin, str): # stdin = stdin.encode() # # logging.info(cmd, extra={"context":"[CMD] "}) # # r, w = os.pipe() # # if stdin is None: # p = Popen(cmd, shell=True, stdout=w, stderr=STDOUT, env=new_env) # else: # p = Popen(cmd, shell=True, stdin=PIPE, stdout=w, stderr=STDOUT, env=new_env) # # async_logging(r, w, soap, log) # p.communicate(input=stdin) # # if p.returncode and not allow_fail: # raise CommandError(cmd, p.returncode) # # def get_command_out(cmd, stdin=None, allow_fail=False, env_add=None): # """get_command_out() - Like do() but returns stdout. # # -- # # Let's quiet the loggers # # >>> import os # >>> from elbepack.log import open_logging # >>> open_logging({"files":os.devnull}) # # >>> get_command_out("echo ELBE") # b'ELBE\\n' # # >>> get_command_out("false") # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # # >>> get_command_out("false", allow_fail=True) # b'' # # >>> get_command_out("cat -", stdin=b"ELBE", env_add={"TRUE":"true"}) # b'ELBE' # # >>> get_command_out("cat -", stdin="ELBE", env_add={"TRUE":"true"}) # b'ELBE' # """ # # new_env = os.environ.copy() # # if env_add: # new_env.update(env_add) # # if isinstance(stdin, str): # stdin = stdin.encode() # # logging.info(cmd, extra={"context":"[CMD] "}) # # r, w = os.pipe() # # if stdin is None: # p = Popen(cmd, shell=True, stdout=PIPE, stderr=w, env=new_env) # else: # p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=w, env=new_env) # # async_logging(r, w, soap, log) # stdout, _ = p.communicate(input=stdin) # # if p.returncode and not allow_fail: # raise CommandError(cmd, p.returncode) # # return stdout # # class CommandError(Exception): # # def __init__(self, cmd, returncode): # super(CommandError, self).__init__(cmd, returncode) # self.returncode = returncode # self.cmd = cmd # # def __str__(self): # return "Error: %d returned from Command %s" % ( # self.returncode, self.cmd) . Output only the next line.
except CommandError as e:
Predict the next line for this snippet: <|code_start|># ELBE - Debian Based Embedded Rootfilesystem Builder # Copyright (c) 2020 Olivier Dion <dion@linutronix.de> # Copyright (c) 2021 Torben Hohn <torben.hohn@linutronix.de> # # SPDX-License-Identifier: GPL-3.0-or-later class TestPreproc(ElbeTestCase): failure_set = {os.path.join(elbe_dir, path) for path in [ "tests/preproc-01.xml" ]} params = [os.path.join(elbe_dir, "tests", fname) for fname in os.listdir(os.path.join(elbe_dir, "tests")) if fname.startswith("preproc") and fname.endswith(".xml")] def test_preproc(self): try: <|code_end|> with the help of current file imports: import os from elbepack.commands.test import ElbeTestCase, system, ElbeTestException from elbepack.directories import elbe_exe, elbe_dir and context from other files: # Path: elbepack/commands/test.py # class ElbeTestCase(unittest.TestCase): # # level = ElbeTestLevel.BASE # # def __init__(self, methodName='runTest', param=None): # self.methodName = methodName # self.param = param # self.stdout = None # super().__init__(methodName) # # def __str__(self): # name = super(ElbeTestCase, self).__str__() # if self.param: # return "%s : param=%s" % (name, self.param) # return name # # def parameterize(self, param): # return self.__class__(methodName=self.methodName, param=param) # # def system(cmd, allow_fail=False): # ret, out = command_out(cmd) # if ret != 0 and not allow_fail: # raise ElbeTestException(cmd, ret, out) # # class ElbeTestException(Exception): # # def __init__(self, cmd, ret, out): # super().__init__() # self.cmd = cmd # self.ret = ret # self.out = out # # def __repr__(self): # return f"ElbeTestException: \"{self.cmd}\" returns {self.ret}" # # def __str__(self): # return f"ElbeTestException: \"{self.cmd}\" returns {self.ret}" # # Path: elbepack/directories.py # def init_directories(elbe_relpath): # def get_cmdlist(): , which may contain function names, class names, or code. Output only the next line.
system(f'{elbe_exe} preprocess "{self.param}"')
Predict the next line for this snippet: <|code_start|># ELBE - Debian Based Embedded Rootfilesystem Builder # Copyright (c) 2020 Olivier Dion <dion@linutronix.de> # Copyright (c) 2021 Torben Hohn <torben.hohn@linutronix.de> # # SPDX-License-Identifier: GPL-3.0-or-later class TestPreproc(ElbeTestCase): failure_set = {os.path.join(elbe_dir, path) for path in [ "tests/preproc-01.xml" ]} params = [os.path.join(elbe_dir, "tests", fname) for fname in os.listdir(os.path.join(elbe_dir, "tests")) if fname.startswith("preproc") and fname.endswith(".xml")] def test_preproc(self): try: system(f'{elbe_exe} preprocess "{self.param}"') <|code_end|> with the help of current file imports: import os from elbepack.commands.test import ElbeTestCase, system, ElbeTestException from elbepack.directories import elbe_exe, elbe_dir and context from other files: # Path: elbepack/commands/test.py # class ElbeTestCase(unittest.TestCase): # # level = ElbeTestLevel.BASE # # def __init__(self, methodName='runTest', param=None): # self.methodName = methodName # self.param = param # self.stdout = None # super().__init__(methodName) # # def __str__(self): # name = super(ElbeTestCase, self).__str__() # if self.param: # return "%s : param=%s" % (name, self.param) # return name # # def parameterize(self, param): # return self.__class__(methodName=self.methodName, param=param) # # def system(cmd, allow_fail=False): # ret, out = command_out(cmd) # if ret != 0 and not allow_fail: # raise ElbeTestException(cmd, ret, out) # # class ElbeTestException(Exception): # # def __init__(self, cmd, ret, out): # super().__init__() # self.cmd = cmd # self.ret = ret # self.out = out # # def __repr__(self): # return f"ElbeTestException: \"{self.cmd}\" returns {self.ret}" # # def __str__(self): # return f"ElbeTestException: \"{self.cmd}\" returns {self.ret}" # # Path: elbepack/directories.py # def init_directories(elbe_relpath): # def get_cmdlist(): , which may contain function names, class names, or code. Output only the next line.
except ElbeTestException as e:
Given snippet: <|code_start|># ELBE - Debian Based Embedded Rootfilesystem Builder # Copyright (c) 2020 Olivier Dion <dion@linutronix.de> # Copyright (c) 2021 Torben Hohn <torben.hohn@linutronix.de> # # SPDX-License-Identifier: GPL-3.0-or-later class TestPreproc(ElbeTestCase): failure_set = {os.path.join(elbe_dir, path) for path in [ "tests/preproc-01.xml" ]} params = [os.path.join(elbe_dir, "tests", fname) for fname in os.listdir(os.path.join(elbe_dir, "tests")) if fname.startswith("preproc") and fname.endswith(".xml")] def test_preproc(self): try: <|code_end|> , continue by predicting the next line. Consider current file imports: import os from elbepack.commands.test import ElbeTestCase, system, ElbeTestException from elbepack.directories import elbe_exe, elbe_dir and context: # Path: elbepack/commands/test.py # class ElbeTestCase(unittest.TestCase): # # level = ElbeTestLevel.BASE # # def __init__(self, methodName='runTest', param=None): # self.methodName = methodName # self.param = param # self.stdout = None # super().__init__(methodName) # # def __str__(self): # name = super(ElbeTestCase, self).__str__() # if self.param: # return "%s : param=%s" % (name, self.param) # return name # # def parameterize(self, param): # return self.__class__(methodName=self.methodName, param=param) # # def system(cmd, allow_fail=False): # ret, out = command_out(cmd) # if ret != 0 and not allow_fail: # raise ElbeTestException(cmd, ret, out) # # class ElbeTestException(Exception): # # def __init__(self, cmd, ret, out): # super().__init__() # self.cmd = cmd # self.ret = ret # self.out = out # # def __repr__(self): # return f"ElbeTestException: \"{self.cmd}\" returns {self.ret}" # # def __str__(self): # return f"ElbeTestException: \"{self.cmd}\" returns {self.ret}" # # Path: elbepack/directories.py # def init_directories(elbe_relpath): # def get_cmdlist(): which might include code, classes, or functions. Output only the next line.
system(f'{elbe_exe} preprocess "{self.param}"')
Using the snippet: <|code_start|># SPDX-License-Identifier: GPL-3.0-or-later def run_command(argv): oparser = OptionParser( usage="usage: %prog pin_versions [options] <xmlfile>") oparser.add_option("--skip-validation", action="store_true", dest="skip_validation", default=False, help="Skip xml schema validation") (opt, args) = oparser.parse_args(argv) if len(args) != 1: print("Wrong number of arguments") oparser.print_help() sys.exit(20) if not opt.skip_validation: validation = validate_xml(args[0]) if validation: print("xml validation failed. Bailing out") for i in validation: print(i) sys.exit(20) try: <|code_end|> , determine the next line of code. You have imports: import sys from optparse import OptionParser from elbepack.treeutils import etree from elbepack.validate import validate_xml and context (class names, function names, or code) available: # Path: elbepack/treeutils.py # class etree(ebase): # def __init__(self, fname): # if fname is not None: # parser = XMLParser(huge_tree=True, remove_comments=False) # et = parse(fname, parser=parser) # else: # et = ElementTree(file=None) # # ebase.__init__(self, et) # # def write(self, fname, encoding=None): # # Make sure, that we end with a newline # self.et.getroot().tail = '\n' # self.et.write(fname, encoding=encoding) # # def tostring(self): # return self.et.tostring() # # def ensure_child(self, tag): # retval = self.et.find("./" + tag) # if retval is not None: # return elem(retval) # return elem(SubElement(self.et.getroot(), tag)) # # def set_child_position(self, child, pos): # root = self.et.getroot() # root.remove(child.et) # root.insert(pos, child.et) # # def setroot(self, tag): # retval = elem(Element(tag)) # # pylint: disable=protected-access # self.et._setroot(retval.et) # return retval # # @property # def root(self): # return elem(self.et.getroot()) # # Path: elbepack/validate.py # def validate_xml(fname): # if os.path.getsize(fname) > (1 << 30): # return ["%s is greater than 1 GiB. " # "Elbe does not support files of this size." % fname] # # schema_file = "https://www.linutronix.de/projects/Elbe/dbsfed.xsd" # parser = XMLParser(huge_tree=True) # schema_tree = etree.parse(schema_file) # schema = etree.XMLSchema(schema_tree) # # try: # xml = parse(fname, parser=parser) # # if schema.validate(xml): # return validate_xml_content(xml) # except etree.XMLSyntaxError: # return ["XML Parse error\n" + str(sys.exc_info()[1])] # except BaseException: # return ["Unknown Exception during validation\n" + # str(sys.exc_info()[1])] # # # We have errors, return them in string form... # return error_log_to_strings(schema.error_log) . Output only the next line.
xml = etree(args[0])
Predict the next line after this snippet: <|code_start|># ELBE - Debian Based Embedded Rootfilesystem Builder # Copyright (c) 2016 Torben Hohn <torben.hohn@linutronix.de> # Copyright (c) 2017 Manuel Traut <manut@linutronix.de> # # SPDX-License-Identifier: GPL-3.0-or-later def run_command(argv): oparser = OptionParser( usage="usage: %prog pin_versions [options] <xmlfile>") oparser.add_option("--skip-validation", action="store_true", dest="skip_validation", default=False, help="Skip xml schema validation") (opt, args) = oparser.parse_args(argv) if len(args) != 1: print("Wrong number of arguments") oparser.print_help() sys.exit(20) if not opt.skip_validation: <|code_end|> using the current file's imports: import sys from optparse import OptionParser from elbepack.treeutils import etree from elbepack.validate import validate_xml and any relevant context from other files: # Path: elbepack/treeutils.py # class etree(ebase): # def __init__(self, fname): # if fname is not None: # parser = XMLParser(huge_tree=True, remove_comments=False) # et = parse(fname, parser=parser) # else: # et = ElementTree(file=None) # # ebase.__init__(self, et) # # def write(self, fname, encoding=None): # # Make sure, that we end with a newline # self.et.getroot().tail = '\n' # self.et.write(fname, encoding=encoding) # # def tostring(self): # return self.et.tostring() # # def ensure_child(self, tag): # retval = self.et.find("./" + tag) # if retval is not None: # return elem(retval) # return elem(SubElement(self.et.getroot(), tag)) # # def set_child_position(self, child, pos): # root = self.et.getroot() # root.remove(child.et) # root.insert(pos, child.et) # # def setroot(self, tag): # retval = elem(Element(tag)) # # pylint: disable=protected-access # self.et._setroot(retval.et) # return retval # # @property # def root(self): # return elem(self.et.getroot()) # # Path: elbepack/validate.py # def validate_xml(fname): # if os.path.getsize(fname) > (1 << 30): # return ["%s is greater than 1 GiB. " # "Elbe does not support files of this size." % fname] # # schema_file = "https://www.linutronix.de/projects/Elbe/dbsfed.xsd" # parser = XMLParser(huge_tree=True) # schema_tree = etree.parse(schema_file) # schema = etree.XMLSchema(schema_tree) # # try: # xml = parse(fname, parser=parser) # # if schema.validate(xml): # return validate_xml_content(xml) # except etree.XMLSyntaxError: # return ["XML Parse error\n" + str(sys.exc_info()[1])] # except BaseException: # return ["Unknown Exception during validation\n" + # str(sys.exc_info()[1])] # # # We have errors, return them in string form... # return error_log_to_strings(schema.error_log) . Output only the next line.
validation = validate_xml(args[0])
Given snippet: <|code_start|> raise NotImplementedError class USBMonitor (UpdateMonitor): def __init__(self, status, recursive=False): super(USBMonitor, self).__init__(status) self.recursive = recursive self.context = pyudev.Context() self.monitor = pyudev.Monitor.from_netlink(self.context) self.observer = pyudev.MonitorObserver( self.monitor, self.handle_event) def handle_event(self, action, device): if (action == 'add' and device.get('ID_BUS') == 'usb' and device.get('DEVTYPE') == 'partition'): mnt = self.get_mountpoint_for_device(device.device_node) if not mnt: self.status.log( "Detected USB drive but it was not mounted.") return for (dirpath, dirnames, filenames) in os.walk(mnt): # Make sure we process the files in alphabetical order # to get a deterministic behaviour dirnames.sort() filenames.sort() for f in filenames: upd_file = os.path.join(dirpath, f) <|code_end|> , continue by predicting the next line. Consider current file imports: import os import threading import pyinotify import pyudev from elbepack.updated import is_update_file, handle_update_file and context: # Path: elbepack/updated.py # def is_update_file(upd_file): # _, extension = os.path.splitext(upd_file) # if extension == ".gpg": # return True # # try: # upd_file_z = ZipFile(upd_file) # except BadZipfile: # return False # # if "new.xml" not in upd_file_z.namelist(): # return False # # return True # # def handle_update_file(upd_file, status, remove=False): # with update_lock: # status.log("checking file: " + str(upd_file)) # _, extension = os.path.splitext(upd_file) # # if extension == ".gpg": # fname = unsign_file(upd_file) # if remove: # os.remove(upd_file) # if fname: # action_select(fname, status) # if remove: # os.remove(fname) # else: # status.log("checking signature failed: " + str(upd_file)) # # elif status.nosign: # action_select(upd_file, status) # if remove: # os.remove(upd_file) # else: # status.log("ignore file: " + str(upd_file)) which might include code, classes, or functions. Output only the next line.
if is_update_file(upd_file):
Predict the next line for this snippet: <|code_start|> def __init__(self, status, recursive=False): super(USBMonitor, self).__init__(status) self.recursive = recursive self.context = pyudev.Context() self.monitor = pyudev.Monitor.from_netlink(self.context) self.observer = pyudev.MonitorObserver( self.monitor, self.handle_event) def handle_event(self, action, device): if (action == 'add' and device.get('ID_BUS') == 'usb' and device.get('DEVTYPE') == 'partition'): mnt = self.get_mountpoint_for_device(device.device_node) if not mnt: self.status.log( "Detected USB drive but it was not mounted.") return for (dirpath, dirnames, filenames) in os.walk(mnt): # Make sure we process the files in alphabetical order # to get a deterministic behaviour dirnames.sort() filenames.sort() for f in filenames: upd_file = os.path.join(dirpath, f) if is_update_file(upd_file): self.status.log( "Found update file '%s' on USB-Device." % upd_file) <|code_end|> with the help of current file imports: import os import threading import pyinotify import pyudev from elbepack.updated import is_update_file, handle_update_file and context from other files: # Path: elbepack/updated.py # def is_update_file(upd_file): # _, extension = os.path.splitext(upd_file) # if extension == ".gpg": # return True # # try: # upd_file_z = ZipFile(upd_file) # except BadZipfile: # return False # # if "new.xml" not in upd_file_z.namelist(): # return False # # return True # # def handle_update_file(upd_file, status, remove=False): # with update_lock: # status.log("checking file: " + str(upd_file)) # _, extension = os.path.splitext(upd_file) # # if extension == ".gpg": # fname = unsign_file(upd_file) # if remove: # os.remove(upd_file) # if fname: # action_select(fname, status) # if remove: # os.remove(fname) # else: # status.log("checking signature failed: " + str(upd_file)) # # elif status.nosign: # action_select(upd_file, status) # if remove: # os.remove(upd_file) # else: # status.log("ignore file: " + str(upd_file)) , which may contain function names, class names, or code. Output only the next line.
handle_update_file(
Given snippet: <|code_start|> def run_command(argv): oparser = OptionParser( usage="usage: %prog chg_archive [options] <xmlfile> " "[<archive>|<directory>]") oparser.add_option( "--keep-attributes", action="store_true", help="keep file owners and groups, if not specified all files will " "belong to root:root", dest="keep_attributes", default=False) (opt, args) = oparser.parse_args(argv) if len(args) != 2: print("Wrong number of arguments") oparser.print_help() sys.exit(20) try: xml = etree(args[0]) except BaseException: print("Error reading xml file!") sys.exit(20) try: <|code_end|> , continue by predicting the next line. Consider current file imports: import sys from optparse import OptionParser from elbepack.archivedir import chg_archive from elbepack.treeutils import etree and context: # Path: elbepack/archivedir.py # def chg_archive(xml, path, keep): # if os.path.isdir(path): # archive = '.archive.tar' # if os.path.exists(archive): # os.remove(archive) # # collect(archive, path, keep) # compress = True # else: # archive = path # compress = False # # arch = xml.ensure_child("archive") # arch.set_text(enbase(archive, compress)) # # if os.path.isdir(path): # os.remove(archive) # # return xml # # Path: elbepack/treeutils.py # class etree(ebase): # def __init__(self, fname): # if fname is not None: # parser = XMLParser(huge_tree=True, remove_comments=False) # et = parse(fname, parser=parser) # else: # et = ElementTree(file=None) # # ebase.__init__(self, et) # # def write(self, fname, encoding=None): # # Make sure, that we end with a newline # self.et.getroot().tail = '\n' # self.et.write(fname, encoding=encoding) # # def tostring(self): # return self.et.tostring() # # def ensure_child(self, tag): # retval = self.et.find("./" + tag) # if retval is not None: # return elem(retval) # return elem(SubElement(self.et.getroot(), tag)) # # def set_child_position(self, child, pos): # root = self.et.getroot() # root.remove(child.et) # root.insert(pos, child.et) # # def setroot(self, tag): # retval = elem(Element(tag)) # # pylint: disable=protected-access # self.et._setroot(retval.et) # return retval # # @property # def root(self): # return elem(self.et.getroot()) which might include code, classes, or functions. Output only the next line.
xml = chg_archive(xml, args[1], opt.keep_attributes)
Given the code snippet: <|code_start|># ELBE - Debian Based Embedded Rootfilesystem Builder # Copyright (c) 2013, 2015, 2017 Manuel Traut <manut@linutronix.de> # # SPDX-License-Identifier: GPL-3.0-or-later def run_command(argv): oparser = OptionParser( usage="usage: %prog chg_archive [options] <xmlfile> " "[<archive>|<directory>]") oparser.add_option( "--keep-attributes", action="store_true", help="keep file owners and groups, if not specified all files will " "belong to root:root", dest="keep_attributes", default=False) (opt, args) = oparser.parse_args(argv) if len(args) != 2: print("Wrong number of arguments") oparser.print_help() sys.exit(20) try: <|code_end|> , generate the next line using the imports in this file: import sys from optparse import OptionParser from elbepack.archivedir import chg_archive from elbepack.treeutils import etree and context (functions, classes, or occasionally code) from other files: # Path: elbepack/archivedir.py # def chg_archive(xml, path, keep): # if os.path.isdir(path): # archive = '.archive.tar' # if os.path.exists(archive): # os.remove(archive) # # collect(archive, path, keep) # compress = True # else: # archive = path # compress = False # # arch = xml.ensure_child("archive") # arch.set_text(enbase(archive, compress)) # # if os.path.isdir(path): # os.remove(archive) # # return xml # # Path: elbepack/treeutils.py # class etree(ebase): # def __init__(self, fname): # if fname is not None: # parser = XMLParser(huge_tree=True, remove_comments=False) # et = parse(fname, parser=parser) # else: # et = ElementTree(file=None) # # ebase.__init__(self, et) # # def write(self, fname, encoding=None): # # Make sure, that we end with a newline # self.et.getroot().tail = '\n' # self.et.write(fname, encoding=encoding) # # def tostring(self): # return self.et.tostring() # # def ensure_child(self, tag): # retval = self.et.find("./" + tag) # if retval is not None: # return elem(retval) # return elem(SubElement(self.et.getroot(), tag)) # # def set_child_position(self, child, pos): # root = self.et.getroot() # root.remove(child.et) # root.insert(pos, child.et) # # def setroot(self, tag): # retval = elem(Element(tag)) # # pylint: disable=protected-access # self.et._setroot(retval.et) # return retval # # @property # def root(self): # return elem(self.et.getroot()) . Output only the next line.
xml = etree(args[0])
Given the following code snippet before the placeholder: <|code_start|># ELBE - Debian Based Embedded Rootfilesystem Builder # Copyright (c) 2017 Torben Hohn <torben.hohn@linutronix.de> # Copyright (c) 2017 Manuel Traut <manut@linutronix.de> # Copyright (c) 2019 Olivier Dion <dion@linutronix.de> # # SPDX-License-Identifier: GPL-3.0-or-later class BareBox(Panel): match_files = ['Kbuild', 'Kconfig', 'README', 'Documentation/barebox.svg'] def __init__(self): <|code_end|> , predict the next line using imports from the current file: import os import stat from shutil import copyfile from elbepack.debianize.panels.base import Panel from elbepack.debianize.widgets.edit import Edit from elbepack.directories import mako_template_dir from elbepack.templates import template from elbepack.shellhelper import system and context including class names, function names, and sometimes code from other files: # Path: elbepack/debianize/panels/base.py # class Panel(Form): # # copyright_fname = "COPYING" # # def __init__(self, grid_elements): # # self.deb = {} # self.tmpl_dir = None # self.hint = None # # fullname = os.environ.get('DEBFULLNAME', "Max Mustermann") # email = os.environ.get('DEBEMAIL', "max@mustermann.org") # # p_name = Edit("Name", "elbe") # p_version = Edit("Version", "1.0") # p_arch = RadioGroup("Arch", Arch, Arch.ARM64) # src_fmt = RadioGroup("Format", Format, Format.NATIVE) # release = RadioGroup("Release", Release, Release.STABLE) # # m_name = Edit("Maintainer", fullname) # m_mail = Edit("Mail", email) # # grid = [ # {"p_name":p_name, "p_version":p_version}, # {"p_arch":p_arch,"release":release}, # {"source_format":src_fmt}, # {"m_name":m_name, "m_mail":m_mail}, # ] # # for element in grid_elements: # grid.append(element) # # super(Panel, self).__init__(grid) # # # def get_k_arch(self): # """ get_k_arch() may be used in debianize() """ # # if self.deb['p_arch'] == 'armhf': # return 'arm' # elif self.deb['p_arch'] == 'armel': # return 'arm' # elif self.deb['p_arch'] == 'amd64': # return 'x86_64' # else: # return self.deb['p_arch'] # # def on_submit(self, datas): # # for key, value in datas.items(): # self.deb[key] = str(value) # # self.deb['k_arch'] = self.get_k_arch() # # os.mkdir('debian') # os.mkdir('debian/source') # # self.debianize() # # with open('debian/source/format', 'w') as f: # mako = os.path.join(self.tmpl_dir, 'format.mako') # f.write(template(mako, self.deb)) # # copyfile(self.copyright_fname, 'debian/copyright') # with open('debian/compat', 'w') as f: # f.write('9') # # TUI.quit() # # Path: elbepack/debianize/widgets/edit.py # def Edit(header='', default='', linebox=True, multiline=False): # this = urwid.Edit(("header", "{}\n".format(header)), default, multiline=multiline) # if linebox: # this = urwid.LineBox(this) # return this # # Path: elbepack/directories.py # def init_directories(elbe_relpath): # def get_cmdlist(): # # Path: elbepack/templates.py # def template(fname, d, linebreak=False): # try: # if linebreak: # return Template( # filename=fname, # preprocessor=fix_linebreak_escapes).render( # **d) # # return Template(filename=fname).render(**d) # except BaseException: # print(exceptions.text_error_template().render()) # raise # # Path: elbepack/shellhelper.py # def system(cmd, allow_fail=False, env_add=None): # """system() - Execute cmd in a shell. # # Throws a CommandError if cmd returns none-zero and allow_fail=False # # -- # # >>> system("true") # # >>> system("false", allow_fail=True) # # >>> system("$FALSE", env_add={"FALSE":"false"}) # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # # """ # new_env = os.environ.copy() # if env_add: # new_env.update(env_add) # # ret = call(cmd, shell=True, env=new_env) # # if ret != 0: # if not allow_fail: # raise CommandError(cmd, ret) . Output only the next line.
imgname = Edit(
Here is a snippet: <|code_start|># Copyright (c) 2019 Olivier Dion <dion@linutronix.de> # # SPDX-License-Identifier: GPL-3.0-or-later class BareBox(Panel): match_files = ['Kbuild', 'Kconfig', 'README', 'Documentation/barebox.svg'] def __init__(self): imgname = Edit( "Image name", "barebox-phytec-phycore-imx6dl-som-nand-256mb.img") defconfig = Edit("Def config", "imx_v7_defconfig") cross = Edit("CROSS_COMPILE", "arm-linux-gnueabihf-") k_version = Edit("BareBox Version", "2016.10") grid_elements = [ {"imgname": imgname, "defconfig": defconfig}, {"cross_compile": cross, "k_version": k_version} ] super(BareBox, self).__init__(grid_elements) def debianize(self): <|code_end|> . Write the next line using the current file imports: import os import stat from shutil import copyfile from elbepack.debianize.panels.base import Panel from elbepack.debianize.widgets.edit import Edit from elbepack.directories import mako_template_dir from elbepack.templates import template from elbepack.shellhelper import system and context from other files: # Path: elbepack/debianize/panels/base.py # class Panel(Form): # # copyright_fname = "COPYING" # # def __init__(self, grid_elements): # # self.deb = {} # self.tmpl_dir = None # self.hint = None # # fullname = os.environ.get('DEBFULLNAME', "Max Mustermann") # email = os.environ.get('DEBEMAIL', "max@mustermann.org") # # p_name = Edit("Name", "elbe") # p_version = Edit("Version", "1.0") # p_arch = RadioGroup("Arch", Arch, Arch.ARM64) # src_fmt = RadioGroup("Format", Format, Format.NATIVE) # release = RadioGroup("Release", Release, Release.STABLE) # # m_name = Edit("Maintainer", fullname) # m_mail = Edit("Mail", email) # # grid = [ # {"p_name":p_name, "p_version":p_version}, # {"p_arch":p_arch,"release":release}, # {"source_format":src_fmt}, # {"m_name":m_name, "m_mail":m_mail}, # ] # # for element in grid_elements: # grid.append(element) # # super(Panel, self).__init__(grid) # # # def get_k_arch(self): # """ get_k_arch() may be used in debianize() """ # # if self.deb['p_arch'] == 'armhf': # return 'arm' # elif self.deb['p_arch'] == 'armel': # return 'arm' # elif self.deb['p_arch'] == 'amd64': # return 'x86_64' # else: # return self.deb['p_arch'] # # def on_submit(self, datas): # # for key, value in datas.items(): # self.deb[key] = str(value) # # self.deb['k_arch'] = self.get_k_arch() # # os.mkdir('debian') # os.mkdir('debian/source') # # self.debianize() # # with open('debian/source/format', 'w') as f: # mako = os.path.join(self.tmpl_dir, 'format.mako') # f.write(template(mako, self.deb)) # # copyfile(self.copyright_fname, 'debian/copyright') # with open('debian/compat', 'w') as f: # f.write('9') # # TUI.quit() # # Path: elbepack/debianize/widgets/edit.py # def Edit(header='', default='', linebox=True, multiline=False): # this = urwid.Edit(("header", "{}\n".format(header)), default, multiline=multiline) # if linebox: # this = urwid.LineBox(this) # return this # # Path: elbepack/directories.py # def init_directories(elbe_relpath): # def get_cmdlist(): # # Path: elbepack/templates.py # def template(fname, d, linebreak=False): # try: # if linebreak: # return Template( # filename=fname, # preprocessor=fix_linebreak_escapes).render( # **d) # # return Template(filename=fname).render(**d) # except BaseException: # print(exceptions.text_error_template().render()) # raise # # Path: elbepack/shellhelper.py # def system(cmd, allow_fail=False, env_add=None): # """system() - Execute cmd in a shell. # # Throws a CommandError if cmd returns none-zero and allow_fail=False # # -- # # >>> system("true") # # >>> system("false", allow_fail=True) # # >>> system("$FALSE", env_add={"FALSE":"false"}) # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # # """ # new_env = os.environ.copy() # if env_add: # new_env.update(env_add) # # ret = call(cmd, shell=True, env=new_env) # # if ret != 0: # if not allow_fail: # raise CommandError(cmd, ret) , which may include functions, classes, or code. Output only the next line.
self.tmpl_dir = os.path.join(mako_template_dir, 'debianize/barebox')
Predict the next line for this snippet: <|code_start|> class BareBox(Panel): match_files = ['Kbuild', 'Kconfig', 'README', 'Documentation/barebox.svg'] def __init__(self): imgname = Edit( "Image name", "barebox-phytec-phycore-imx6dl-som-nand-256mb.img") defconfig = Edit("Def config", "imx_v7_defconfig") cross = Edit("CROSS_COMPILE", "arm-linux-gnueabihf-") k_version = Edit("BareBox Version", "2016.10") grid_elements = [ {"imgname": imgname, "defconfig": defconfig}, {"cross_compile": cross, "k_version": k_version} ] super(BareBox, self).__init__(grid_elements) def debianize(self): self.tmpl_dir = os.path.join(mako_template_dir, 'debianize/barebox') pkg_name = self.deb['p_name'] + '-' + self.deb['k_version'] for tmpl in ['control', 'rules']: with open(os.path.join('debian/', tmpl), 'w') as f: mako = os.path.join(self.tmpl_dir, tmpl + '.mako') <|code_end|> with the help of current file imports: import os import stat from shutil import copyfile from elbepack.debianize.panels.base import Panel from elbepack.debianize.widgets.edit import Edit from elbepack.directories import mako_template_dir from elbepack.templates import template from elbepack.shellhelper import system and context from other files: # Path: elbepack/debianize/panels/base.py # class Panel(Form): # # copyright_fname = "COPYING" # # def __init__(self, grid_elements): # # self.deb = {} # self.tmpl_dir = None # self.hint = None # # fullname = os.environ.get('DEBFULLNAME', "Max Mustermann") # email = os.environ.get('DEBEMAIL', "max@mustermann.org") # # p_name = Edit("Name", "elbe") # p_version = Edit("Version", "1.0") # p_arch = RadioGroup("Arch", Arch, Arch.ARM64) # src_fmt = RadioGroup("Format", Format, Format.NATIVE) # release = RadioGroup("Release", Release, Release.STABLE) # # m_name = Edit("Maintainer", fullname) # m_mail = Edit("Mail", email) # # grid = [ # {"p_name":p_name, "p_version":p_version}, # {"p_arch":p_arch,"release":release}, # {"source_format":src_fmt}, # {"m_name":m_name, "m_mail":m_mail}, # ] # # for element in grid_elements: # grid.append(element) # # super(Panel, self).__init__(grid) # # # def get_k_arch(self): # """ get_k_arch() may be used in debianize() """ # # if self.deb['p_arch'] == 'armhf': # return 'arm' # elif self.deb['p_arch'] == 'armel': # return 'arm' # elif self.deb['p_arch'] == 'amd64': # return 'x86_64' # else: # return self.deb['p_arch'] # # def on_submit(self, datas): # # for key, value in datas.items(): # self.deb[key] = str(value) # # self.deb['k_arch'] = self.get_k_arch() # # os.mkdir('debian') # os.mkdir('debian/source') # # self.debianize() # # with open('debian/source/format', 'w') as f: # mako = os.path.join(self.tmpl_dir, 'format.mako') # f.write(template(mako, self.deb)) # # copyfile(self.copyright_fname, 'debian/copyright') # with open('debian/compat', 'w') as f: # f.write('9') # # TUI.quit() # # Path: elbepack/debianize/widgets/edit.py # def Edit(header='', default='', linebox=True, multiline=False): # this = urwid.Edit(("header", "{}\n".format(header)), default, multiline=multiline) # if linebox: # this = urwid.LineBox(this) # return this # # Path: elbepack/directories.py # def init_directories(elbe_relpath): # def get_cmdlist(): # # Path: elbepack/templates.py # def template(fname, d, linebreak=False): # try: # if linebreak: # return Template( # filename=fname, # preprocessor=fix_linebreak_escapes).render( # **d) # # return Template(filename=fname).render(**d) # except BaseException: # print(exceptions.text_error_template().render()) # raise # # Path: elbepack/shellhelper.py # def system(cmd, allow_fail=False, env_add=None): # """system() - Execute cmd in a shell. # # Throws a CommandError if cmd returns none-zero and allow_fail=False # # -- # # >>> system("true") # # >>> system("false", allow_fail=True) # # >>> system("$FALSE", env_add={"FALSE":"false"}) # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # # """ # new_env = os.environ.copy() # if env_add: # new_env.update(env_add) # # ret = call(cmd, shell=True, env=new_env) # # if ret != 0: # if not allow_fail: # raise CommandError(cmd, ret) , which may contain function names, class names, or code. Output only the next line.
f.write(template(mako, self.deb))
Based on the snippet: <|code_start|> imgname = Edit( "Image name", "barebox-phytec-phycore-imx6dl-som-nand-256mb.img") defconfig = Edit("Def config", "imx_v7_defconfig") cross = Edit("CROSS_COMPILE", "arm-linux-gnueabihf-") k_version = Edit("BareBox Version", "2016.10") grid_elements = [ {"imgname": imgname, "defconfig": defconfig}, {"cross_compile": cross, "k_version": k_version} ] super(BareBox, self).__init__(grid_elements) def debianize(self): self.tmpl_dir = os.path.join(mako_template_dir, 'debianize/barebox') pkg_name = self.deb['p_name'] + '-' + self.deb['k_version'] for tmpl in ['control', 'rules']: with open(os.path.join('debian/', tmpl), 'w') as f: mako = os.path.join(self.tmpl_dir, tmpl + '.mako') f.write(template(mako, self.deb)) st = os.stat(os.path.join('debian', 'rules')) os.chmod(os.path.join('debian', 'rules'), st.st_mode | stat.S_IEXEC) cmd = 'dch --package barebox-' + pkg_name + \ ' -v ' + self.deb['p_version'] + \ ' --create -M -D ' + self.deb['release'] + \ ' "generated by elbe debianize"' <|code_end|> , predict the immediate next line with the help of imports: import os import stat from shutil import copyfile from elbepack.debianize.panels.base import Panel from elbepack.debianize.widgets.edit import Edit from elbepack.directories import mako_template_dir from elbepack.templates import template from elbepack.shellhelper import system and context (classes, functions, sometimes code) from other files: # Path: elbepack/debianize/panels/base.py # class Panel(Form): # # copyright_fname = "COPYING" # # def __init__(self, grid_elements): # # self.deb = {} # self.tmpl_dir = None # self.hint = None # # fullname = os.environ.get('DEBFULLNAME', "Max Mustermann") # email = os.environ.get('DEBEMAIL', "max@mustermann.org") # # p_name = Edit("Name", "elbe") # p_version = Edit("Version", "1.0") # p_arch = RadioGroup("Arch", Arch, Arch.ARM64) # src_fmt = RadioGroup("Format", Format, Format.NATIVE) # release = RadioGroup("Release", Release, Release.STABLE) # # m_name = Edit("Maintainer", fullname) # m_mail = Edit("Mail", email) # # grid = [ # {"p_name":p_name, "p_version":p_version}, # {"p_arch":p_arch,"release":release}, # {"source_format":src_fmt}, # {"m_name":m_name, "m_mail":m_mail}, # ] # # for element in grid_elements: # grid.append(element) # # super(Panel, self).__init__(grid) # # # def get_k_arch(self): # """ get_k_arch() may be used in debianize() """ # # if self.deb['p_arch'] == 'armhf': # return 'arm' # elif self.deb['p_arch'] == 'armel': # return 'arm' # elif self.deb['p_arch'] == 'amd64': # return 'x86_64' # else: # return self.deb['p_arch'] # # def on_submit(self, datas): # # for key, value in datas.items(): # self.deb[key] = str(value) # # self.deb['k_arch'] = self.get_k_arch() # # os.mkdir('debian') # os.mkdir('debian/source') # # self.debianize() # # with open('debian/source/format', 'w') as f: # mako = os.path.join(self.tmpl_dir, 'format.mako') # f.write(template(mako, self.deb)) # # copyfile(self.copyright_fname, 'debian/copyright') # with open('debian/compat', 'w') as f: # f.write('9') # # TUI.quit() # # Path: elbepack/debianize/widgets/edit.py # def Edit(header='', default='', linebox=True, multiline=False): # this = urwid.Edit(("header", "{}\n".format(header)), default, multiline=multiline) # if linebox: # this = urwid.LineBox(this) # return this # # Path: elbepack/directories.py # def init_directories(elbe_relpath): # def get_cmdlist(): # # Path: elbepack/templates.py # def template(fname, d, linebreak=False): # try: # if linebreak: # return Template( # filename=fname, # preprocessor=fix_linebreak_escapes).render( # **d) # # return Template(filename=fname).render(**d) # except BaseException: # print(exceptions.text_error_template().render()) # raise # # Path: elbepack/shellhelper.py # def system(cmd, allow_fail=False, env_add=None): # """system() - Execute cmd in a shell. # # Throws a CommandError if cmd returns none-zero and allow_fail=False # # -- # # >>> system("true") # # >>> system("false", allow_fail=True) # # >>> system("$FALSE", env_add={"FALSE":"false"}) # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # # """ # new_env = os.environ.copy() # if env_add: # new_env.update(env_add) # # ret = call(cmd, shell=True, env=new_env) # # if ret != 0: # if not allow_fail: # raise CommandError(cmd, ret) . Output only the next line.
system(cmd)
Given the following code snippet before the placeholder: <|code_start|># Copyright (c) 2017 John Ogness <john.ogness@linutronix.de> # # SPDX-License-Identifier: GPL-3.0-or-later def unbase(s, fname): outfile = open(fname, "w+b") outfile.write(standard_b64decode(s)) outfile.close() def run_command(argv): oparser = OptionParser( usage="usage: %prog get_archive <xmlfile> <archive>") (_, args) = oparser.parse_args(argv) if len(args) != 2: print("Wrong number of arguments") oparser.print_help() sys.exit(20) if os.path.exists(args[1]): print("archive already exists, bailing out") sys.exit(20) try: <|code_end|> , predict the next line using imports from the current file: import os import sys from base64 import standard_b64decode from optparse import OptionParser from elbepack.treeutils import etree and context including class names, function names, and sometimes code from other files: # Path: elbepack/treeutils.py # class etree(ebase): # def __init__(self, fname): # if fname is not None: # parser = XMLParser(huge_tree=True, remove_comments=False) # et = parse(fname, parser=parser) # else: # et = ElementTree(file=None) # # ebase.__init__(self, et) # # def write(self, fname, encoding=None): # # Make sure, that we end with a newline # self.et.getroot().tail = '\n' # self.et.write(fname, encoding=encoding) # # def tostring(self): # return self.et.tostring() # # def ensure_child(self, tag): # retval = self.et.find("./" + tag) # if retval is not None: # return elem(retval) # return elem(SubElement(self.et.getroot(), tag)) # # def set_child_position(self, child, pos): # root = self.et.getroot() # root.remove(child.et) # root.insert(pos, child.et) # # def setroot(self, tag): # retval = elem(Element(tag)) # # pylint: disable=protected-access # self.et._setroot(retval.et) # return retval # # @property # def root(self): # return elem(self.et.getroot()) . Output only the next line.
xml = etree(args[0])
Using the snippet: <|code_start|> sz = os.path.getsize(fname) for sect in tf: if 'Files' in sect: files = sect['Files'].split('\n') files = [f.strip().split(' ') for f in files] for f in files: sz += int(f[1]) break return sz class ChangelogNeedsDependency(Exception): def __init__(self, pkgname): Exception.__init__(self, 'Changelog extraction depends on "%s"' % (pkgname)) self.pkgname = pkgname re_pkgfilename = r'(?P<name>.*)_(?P<ver>.*)_(?P<arch>.*).deb' def extract_pkg_changelog(fname, extra_pkg=None): pkgname = os.path.basename(fname) m = re.match(re_pkgfilename, pkgname) pkgname = m.group('name') pkgarch = m.group('arch') print('pkg: %s, arch: %s' % (pkgname, pkgarch)) <|code_end|> , determine the next line of code. You have imports: import os import re from apt_pkg import TagFile from elbepack.filesystem import TmpdirFilesystem from elbepack.shellhelper import system and context (class names, function names, or code) available: # Path: elbepack/filesystem.py # class TmpdirFilesystem (Filesystem): # def __init__(self, debug=False): # tmpdir = mkdtemp() # Filesystem.__init__(self, tmpdir) # self.debug = debug # # def __del__(self): # # dont delete files in debug mode # if self.debug: # print('leaving TmpdirFilesystem in "%s"' % self.path) # else: # self.delete() # # def delete(self): # shutil.rmtree(self.path, True) # # def __enter__(self): # return self # # def __exit__(self, exec_type, exec_value, tb): # shutil.rmtree(self.path) # return False # # Path: elbepack/shellhelper.py # def system(cmd, allow_fail=False, env_add=None): # """system() - Execute cmd in a shell. # # Throws a CommandError if cmd returns none-zero and allow_fail=False # # -- # # >>> system("true") # # >>> system("false", allow_fail=True) # # >>> system("$FALSE", env_add={"FALSE":"false"}) # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # # """ # new_env = os.environ.copy() # if env_add: # new_env.update(env_add) # # ret = call(cmd, shell=True, env=new_env) # # if ret != 0: # if not allow_fail: # raise CommandError(cmd, ret) . Output only the next line.
fs = TmpdirFilesystem()
Continue the code snippet: <|code_start|> files = [f.strip().split(' ') for f in files] for f in files: sz += int(f[1]) break return sz class ChangelogNeedsDependency(Exception): def __init__(self, pkgname): Exception.__init__(self, 'Changelog extraction depends on "%s"' % (pkgname)) self.pkgname = pkgname re_pkgfilename = r'(?P<name>.*)_(?P<ver>.*)_(?P<arch>.*).deb' def extract_pkg_changelog(fname, extra_pkg=None): pkgname = os.path.basename(fname) m = re.match(re_pkgfilename, pkgname) pkgname = m.group('name') pkgarch = m.group('arch') print('pkg: %s, arch: %s' % (pkgname, pkgarch)) fs = TmpdirFilesystem() if extra_pkg: print('with extra ' + extra_pkg) <|code_end|> . Use current file imports: import os import re from apt_pkg import TagFile from elbepack.filesystem import TmpdirFilesystem from elbepack.shellhelper import system and context (classes, functions, or code) from other files: # Path: elbepack/filesystem.py # class TmpdirFilesystem (Filesystem): # def __init__(self, debug=False): # tmpdir = mkdtemp() # Filesystem.__init__(self, tmpdir) # self.debug = debug # # def __del__(self): # # dont delete files in debug mode # if self.debug: # print('leaving TmpdirFilesystem in "%s"' % self.path) # else: # self.delete() # # def delete(self): # shutil.rmtree(self.path, True) # # def __enter__(self): # return self # # def __exit__(self, exec_type, exec_value, tb): # shutil.rmtree(self.path) # return False # # Path: elbepack/shellhelper.py # def system(cmd, allow_fail=False, env_add=None): # """system() - Execute cmd in a shell. # # Throws a CommandError if cmd returns none-zero and allow_fail=False # # -- # # >>> system("true") # # >>> system("false", allow_fail=True) # # >>> system("$FALSE", env_add={"FALSE":"false"}) # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # # """ # new_env = os.environ.copy() # if env_add: # new_env.update(env_add) # # ret = call(cmd, shell=True, env=new_env) # # if ret != 0: # if not allow_fail: # raise CommandError(cmd, ret) . Output only the next line.
system('dpkg -x "%s" "%s"' % (extra_pkg, fs.fname('/')))
Continue the code snippet: <|code_start|># ELBE - Debian Based Embedded Rootfilesystem Builder # Copyright (c) 2014, 2017 Manuel Traut <manut@linutronix.de> # # SPDX-License-Identifier: GPL-3.0-or-later def run_command(argv): if not argv: print("elbe db - no action given") <|code_end|> . Use current file imports: from elbepack.dbaction import DbAction and context (classes, functions, or code) from other files: # Path: elbepack/dbaction.py # class DbAction: # # actiondict = {} # # @classmethod # def register(cls, action): # cls.actiondict[action.tag] = action # # @classmethod # def print_actions(cls): # print("available actions are:") # for a in cls.actiondict: # print(" %s" % a) # # def __new__(cls, node): # action = cls.actiondict[node] # return object.__new__(action) # # def __init__(self, node): # self.node = node # # def execute(self, _args): # raise NotImplementedError('execute() not implemented') . Output only the next line.
DbAction.print_actions()
Given the code snippet: <|code_start|> def run_command(argv): oparser = OptionParser(usage="usage: %prog toolchainextract [options]") oparser.add_option("-p", "--path", dest="path", help="path to toolchain") oparser.add_option("-o", "--output", dest="output", help="output repository path") oparser.add_option("-c", "--codename", dest="codename", help="distro codename for repository") oparser.add_option("-b", "--buildtype", dest="buildtype", help="Override the buildtype") (opt, _) = oparser.parse_args(argv) if not opt.path: oparser.print_help() return 0 if not opt.output: oparser.print_help() return 0 if not opt.codename: oparser.print_help() return 0 if not opt.buildtype: oparser.print_help() return 0 <|code_end|> , generate the next line using the imports in this file: from optparse import OptionParser from tempfile import mkdtemp from elbepack.xmldefaults import ElbeDefaults from elbepack.repomanager import ToolchainRepo from elbepack.debpkg import build_binary_deb from elbepack.toolchain import get_toolchain from elbepack.log import elbe_logging import os import sys and context (functions, classes, or occasionally code) from other files: # Path: elbepack/xmldefaults.py # class ElbeDefaults: # # def __init__(self, build_type): # # assert build_type in defaults, ("Invalid buildtype %s\n" # "Valid buildtypes are:\n - %s" % # (build_type, "\n - ".join(defaults.keys()))) # # self.defaults = defaults[build_type] # self.defaults["nicmac"] = get_random_mac() # # self.generic_defaults = archindep_defaults # # def __getitem__(self, key): # if key in self.defaults: # return self.defaults[key] # if key in self.generic_defaults: # return self.generic_defaults[key] # # return None # # Path: elbepack/repomanager.py # class ToolchainRepo(RepoBase): # def __init__(self, arch, codename, path): # repo_attrs = RepoAttributes(codename, arch, "main") # RepoBase.__init__(self, # path, # None, # repo_attrs, # "toolchain", # "Toolchain binary packages Repo") # # Path: elbepack/debpkg.py # def build_binary_deb( # name, # arch, # version, # description, # files, # deps, # target_dir): # # # pylint: disable=too-many-arguments # # tmpdir = mkdtemp() # pkgfname = "%s_%s_%s" % (name, version, arch) # pkgdir = os.path.join(tmpdir, pkgfname) # # os.system('mkdir -p "%s"' % os.path.join(pkgdir, "DEBIAN")) # write_file( # os.path.join( # pkgdir, # "DEBIAN", # "control"), # 0o644, # gen_controlfile( # name, # version, # arch, # description, # deps)) # # for (fname, instpath) in files: # full_instpath = os.path.join(pkgdir, instpath) # os.system('mkdir -p "%s"' % full_instpath) # os.system('cp -a "%s" "%s"' % (fname, full_instpath)) # # os.system('dpkg-deb --build "%s"' % pkgdir) # # os.system( # 'cp -v "%s" "%s"' % # (os.path.join( # tmpdir, # pkgfname + # ".deb"), # target_dir)) # # os.system('rm -r "%s"' % tmpdir) # # return pkgfname + ".deb" # # Path: elbepack/toolchain.py # def get_toolchain(typ, path, arch): # if typ == "linaro": # return LinaroToolchain(path, arch) # if typ == "linaro_armel": # return LinaroToolchainArmel(path, arch) # # raise Exception # # Path: elbepack/log.py # @contextmanager # def elbe_logging(*args, **kwargs): # try: # open_logging(*args, **kwargs) # yield # finally: # close_logging() . Output only the next line.
defaults = ElbeDefaults(opt.buildtype)
Predict the next line for this snippet: <|code_start|> defaults = ElbeDefaults(opt.buildtype) toolchain = get_toolchain( defaults["toolchaintype"], opt.path, defaults["arch"]) tmpdir = mkdtemp() for lib in toolchain.pkg_libs: files = toolchain.get_files_for_pkg(lib) pkglibpath = os.path.join("usr/lib", defaults["triplet"]) fmap = [(f, pkglibpath) for f in files] build_binary_deb( lib, defaults["arch"], defaults["toolchainver"], lib + " extracted from toolchain", fmap, toolchain.pkg_deps[lib], tmpdir) pkgs = os.listdir(tmpdir) with elbe_logging({"streams":sys.stdout}): <|code_end|> with the help of current file imports: from optparse import OptionParser from tempfile import mkdtemp from elbepack.xmldefaults import ElbeDefaults from elbepack.repomanager import ToolchainRepo from elbepack.debpkg import build_binary_deb from elbepack.toolchain import get_toolchain from elbepack.log import elbe_logging import os import sys and context from other files: # Path: elbepack/xmldefaults.py # class ElbeDefaults: # # def __init__(self, build_type): # # assert build_type in defaults, ("Invalid buildtype %s\n" # "Valid buildtypes are:\n - %s" % # (build_type, "\n - ".join(defaults.keys()))) # # self.defaults = defaults[build_type] # self.defaults["nicmac"] = get_random_mac() # # self.generic_defaults = archindep_defaults # # def __getitem__(self, key): # if key in self.defaults: # return self.defaults[key] # if key in self.generic_defaults: # return self.generic_defaults[key] # # return None # # Path: elbepack/repomanager.py # class ToolchainRepo(RepoBase): # def __init__(self, arch, codename, path): # repo_attrs = RepoAttributes(codename, arch, "main") # RepoBase.__init__(self, # path, # None, # repo_attrs, # "toolchain", # "Toolchain binary packages Repo") # # Path: elbepack/debpkg.py # def build_binary_deb( # name, # arch, # version, # description, # files, # deps, # target_dir): # # # pylint: disable=too-many-arguments # # tmpdir = mkdtemp() # pkgfname = "%s_%s_%s" % (name, version, arch) # pkgdir = os.path.join(tmpdir, pkgfname) # # os.system('mkdir -p "%s"' % os.path.join(pkgdir, "DEBIAN")) # write_file( # os.path.join( # pkgdir, # "DEBIAN", # "control"), # 0o644, # gen_controlfile( # name, # version, # arch, # description, # deps)) # # for (fname, instpath) in files: # full_instpath = os.path.join(pkgdir, instpath) # os.system('mkdir -p "%s"' % full_instpath) # os.system('cp -a "%s" "%s"' % (fname, full_instpath)) # # os.system('dpkg-deb --build "%s"' % pkgdir) # # os.system( # 'cp -v "%s" "%s"' % # (os.path.join( # tmpdir, # pkgfname + # ".deb"), # target_dir)) # # os.system('rm -r "%s"' % tmpdir) # # return pkgfname + ".deb" # # Path: elbepack/toolchain.py # def get_toolchain(typ, path, arch): # if typ == "linaro": # return LinaroToolchain(path, arch) # if typ == "linaro_armel": # return LinaroToolchainArmel(path, arch) # # raise Exception # # Path: elbepack/log.py # @contextmanager # def elbe_logging(*args, **kwargs): # try: # open_logging(*args, **kwargs) # yield # finally: # close_logging() , which may contain function names, class names, or code. Output only the next line.
repo = ToolchainRepo(defaults["arch"],
Given the code snippet: <|code_start|> (opt, _) = oparser.parse_args(argv) if not opt.path: oparser.print_help() return 0 if not opt.output: oparser.print_help() return 0 if not opt.codename: oparser.print_help() return 0 if not opt.buildtype: oparser.print_help() return 0 defaults = ElbeDefaults(opt.buildtype) toolchain = get_toolchain( defaults["toolchaintype"], opt.path, defaults["arch"]) tmpdir = mkdtemp() for lib in toolchain.pkg_libs: files = toolchain.get_files_for_pkg(lib) pkglibpath = os.path.join("usr/lib", defaults["triplet"]) fmap = [(f, pkglibpath) for f in files] <|code_end|> , generate the next line using the imports in this file: from optparse import OptionParser from tempfile import mkdtemp from elbepack.xmldefaults import ElbeDefaults from elbepack.repomanager import ToolchainRepo from elbepack.debpkg import build_binary_deb from elbepack.toolchain import get_toolchain from elbepack.log import elbe_logging import os import sys and context (functions, classes, or occasionally code) from other files: # Path: elbepack/xmldefaults.py # class ElbeDefaults: # # def __init__(self, build_type): # # assert build_type in defaults, ("Invalid buildtype %s\n" # "Valid buildtypes are:\n - %s" % # (build_type, "\n - ".join(defaults.keys()))) # # self.defaults = defaults[build_type] # self.defaults["nicmac"] = get_random_mac() # # self.generic_defaults = archindep_defaults # # def __getitem__(self, key): # if key in self.defaults: # return self.defaults[key] # if key in self.generic_defaults: # return self.generic_defaults[key] # # return None # # Path: elbepack/repomanager.py # class ToolchainRepo(RepoBase): # def __init__(self, arch, codename, path): # repo_attrs = RepoAttributes(codename, arch, "main") # RepoBase.__init__(self, # path, # None, # repo_attrs, # "toolchain", # "Toolchain binary packages Repo") # # Path: elbepack/debpkg.py # def build_binary_deb( # name, # arch, # version, # description, # files, # deps, # target_dir): # # # pylint: disable=too-many-arguments # # tmpdir = mkdtemp() # pkgfname = "%s_%s_%s" % (name, version, arch) # pkgdir = os.path.join(tmpdir, pkgfname) # # os.system('mkdir -p "%s"' % os.path.join(pkgdir, "DEBIAN")) # write_file( # os.path.join( # pkgdir, # "DEBIAN", # "control"), # 0o644, # gen_controlfile( # name, # version, # arch, # description, # deps)) # # for (fname, instpath) in files: # full_instpath = os.path.join(pkgdir, instpath) # os.system('mkdir -p "%s"' % full_instpath) # os.system('cp -a "%s" "%s"' % (fname, full_instpath)) # # os.system('dpkg-deb --build "%s"' % pkgdir) # # os.system( # 'cp -v "%s" "%s"' % # (os.path.join( # tmpdir, # pkgfname + # ".deb"), # target_dir)) # # os.system('rm -r "%s"' % tmpdir) # # return pkgfname + ".deb" # # Path: elbepack/toolchain.py # def get_toolchain(typ, path, arch): # if typ == "linaro": # return LinaroToolchain(path, arch) # if typ == "linaro_armel": # return LinaroToolchainArmel(path, arch) # # raise Exception # # Path: elbepack/log.py # @contextmanager # def elbe_logging(*args, **kwargs): # try: # open_logging(*args, **kwargs) # yield # finally: # close_logging() . Output only the next line.
build_binary_deb(
Given the following code snippet before the placeholder: <|code_start|> def run_command(argv): oparser = OptionParser(usage="usage: %prog toolchainextract [options]") oparser.add_option("-p", "--path", dest="path", help="path to toolchain") oparser.add_option("-o", "--output", dest="output", help="output repository path") oparser.add_option("-c", "--codename", dest="codename", help="distro codename for repository") oparser.add_option("-b", "--buildtype", dest="buildtype", help="Override the buildtype") (opt, _) = oparser.parse_args(argv) if not opt.path: oparser.print_help() return 0 if not opt.output: oparser.print_help() return 0 if not opt.codename: oparser.print_help() return 0 if not opt.buildtype: oparser.print_help() return 0 defaults = ElbeDefaults(opt.buildtype) <|code_end|> , predict the next line using imports from the current file: from optparse import OptionParser from tempfile import mkdtemp from elbepack.xmldefaults import ElbeDefaults from elbepack.repomanager import ToolchainRepo from elbepack.debpkg import build_binary_deb from elbepack.toolchain import get_toolchain from elbepack.log import elbe_logging import os import sys and context including class names, function names, and sometimes code from other files: # Path: elbepack/xmldefaults.py # class ElbeDefaults: # # def __init__(self, build_type): # # assert build_type in defaults, ("Invalid buildtype %s\n" # "Valid buildtypes are:\n - %s" % # (build_type, "\n - ".join(defaults.keys()))) # # self.defaults = defaults[build_type] # self.defaults["nicmac"] = get_random_mac() # # self.generic_defaults = archindep_defaults # # def __getitem__(self, key): # if key in self.defaults: # return self.defaults[key] # if key in self.generic_defaults: # return self.generic_defaults[key] # # return None # # Path: elbepack/repomanager.py # class ToolchainRepo(RepoBase): # def __init__(self, arch, codename, path): # repo_attrs = RepoAttributes(codename, arch, "main") # RepoBase.__init__(self, # path, # None, # repo_attrs, # "toolchain", # "Toolchain binary packages Repo") # # Path: elbepack/debpkg.py # def build_binary_deb( # name, # arch, # version, # description, # files, # deps, # target_dir): # # # pylint: disable=too-many-arguments # # tmpdir = mkdtemp() # pkgfname = "%s_%s_%s" % (name, version, arch) # pkgdir = os.path.join(tmpdir, pkgfname) # # os.system('mkdir -p "%s"' % os.path.join(pkgdir, "DEBIAN")) # write_file( # os.path.join( # pkgdir, # "DEBIAN", # "control"), # 0o644, # gen_controlfile( # name, # version, # arch, # description, # deps)) # # for (fname, instpath) in files: # full_instpath = os.path.join(pkgdir, instpath) # os.system('mkdir -p "%s"' % full_instpath) # os.system('cp -a "%s" "%s"' % (fname, full_instpath)) # # os.system('dpkg-deb --build "%s"' % pkgdir) # # os.system( # 'cp -v "%s" "%s"' % # (os.path.join( # tmpdir, # pkgfname + # ".deb"), # target_dir)) # # os.system('rm -r "%s"' % tmpdir) # # return pkgfname + ".deb" # # Path: elbepack/toolchain.py # def get_toolchain(typ, path, arch): # if typ == "linaro": # return LinaroToolchain(path, arch) # if typ == "linaro_armel": # return LinaroToolchainArmel(path, arch) # # raise Exception # # Path: elbepack/log.py # @contextmanager # def elbe_logging(*args, **kwargs): # try: # open_logging(*args, **kwargs) # yield # finally: # close_logging() . Output only the next line.
toolchain = get_toolchain(
Given the following code snippet before the placeholder: <|code_start|> oparser.print_help() return 0 defaults = ElbeDefaults(opt.buildtype) toolchain = get_toolchain( defaults["toolchaintype"], opt.path, defaults["arch"]) tmpdir = mkdtemp() for lib in toolchain.pkg_libs: files = toolchain.get_files_for_pkg(lib) pkglibpath = os.path.join("usr/lib", defaults["triplet"]) fmap = [(f, pkglibpath) for f in files] build_binary_deb( lib, defaults["arch"], defaults["toolchainver"], lib + " extracted from toolchain", fmap, toolchain.pkg_deps[lib], tmpdir) pkgs = os.listdir(tmpdir) <|code_end|> , predict the next line using imports from the current file: from optparse import OptionParser from tempfile import mkdtemp from elbepack.xmldefaults import ElbeDefaults from elbepack.repomanager import ToolchainRepo from elbepack.debpkg import build_binary_deb from elbepack.toolchain import get_toolchain from elbepack.log import elbe_logging import os import sys and context including class names, function names, and sometimes code from other files: # Path: elbepack/xmldefaults.py # class ElbeDefaults: # # def __init__(self, build_type): # # assert build_type in defaults, ("Invalid buildtype %s\n" # "Valid buildtypes are:\n - %s" % # (build_type, "\n - ".join(defaults.keys()))) # # self.defaults = defaults[build_type] # self.defaults["nicmac"] = get_random_mac() # # self.generic_defaults = archindep_defaults # # def __getitem__(self, key): # if key in self.defaults: # return self.defaults[key] # if key in self.generic_defaults: # return self.generic_defaults[key] # # return None # # Path: elbepack/repomanager.py # class ToolchainRepo(RepoBase): # def __init__(self, arch, codename, path): # repo_attrs = RepoAttributes(codename, arch, "main") # RepoBase.__init__(self, # path, # None, # repo_attrs, # "toolchain", # "Toolchain binary packages Repo") # # Path: elbepack/debpkg.py # def build_binary_deb( # name, # arch, # version, # description, # files, # deps, # target_dir): # # # pylint: disable=too-many-arguments # # tmpdir = mkdtemp() # pkgfname = "%s_%s_%s" % (name, version, arch) # pkgdir = os.path.join(tmpdir, pkgfname) # # os.system('mkdir -p "%s"' % os.path.join(pkgdir, "DEBIAN")) # write_file( # os.path.join( # pkgdir, # "DEBIAN", # "control"), # 0o644, # gen_controlfile( # name, # version, # arch, # description, # deps)) # # for (fname, instpath) in files: # full_instpath = os.path.join(pkgdir, instpath) # os.system('mkdir -p "%s"' % full_instpath) # os.system('cp -a "%s" "%s"' % (fname, full_instpath)) # # os.system('dpkg-deb --build "%s"' % pkgdir) # # os.system( # 'cp -v "%s" "%s"' % # (os.path.join( # tmpdir, # pkgfname + # ".deb"), # target_dir)) # # os.system('rm -r "%s"' % tmpdir) # # return pkgfname + ".deb" # # Path: elbepack/toolchain.py # def get_toolchain(typ, path, arch): # if typ == "linaro": # return LinaroToolchain(path, arch) # if typ == "linaro_armel": # return LinaroToolchainArmel(path, arch) # # raise Exception # # Path: elbepack/log.py # @contextmanager # def elbe_logging(*args, **kwargs): # try: # open_logging(*args, **kwargs) # yield # finally: # close_logging() . Output only the next line.
with elbe_logging({"streams":sys.stdout}):
Continue the code snippet: <|code_start|># ELBE - Debian Based Embedded Rootfilesystem Builder # Copyright (c) 2013, 2017 Manuel Traut <manut@linutronix.de> # Copyright (c) 2014-2015 Torben Hohn <torbenh@linutronix.de> # # SPDX-License-Identifier: GPL-3.0-or-later def run_command(argv): oparser = OptionParser( usage="usage: %prog xsdtoasciidoc [options] <xsdfile>") oparser.add_option("--output", dest="out", help="specify output filename", metavar="FILE") (opt, args) = oparser.parse_args(argv) if len(args) != 1: print("Wrong number of arguments") oparser.print_help() sys.exit(20) <|code_end|> . Use current file imports: import sys from optparse import OptionParser from elbepack.treeutils import etree from elbepack.directories import xsdtoasciidoc_mako_fname from elbepack.templates import write_template and context (classes, functions, or code) from other files: # Path: elbepack/treeutils.py # class etree(ebase): # def __init__(self, fname): # if fname is not None: # parser = XMLParser(huge_tree=True, remove_comments=False) # et = parse(fname, parser=parser) # else: # et = ElementTree(file=None) # # ebase.__init__(self, et) # # def write(self, fname, encoding=None): # # Make sure, that we end with a newline # self.et.getroot().tail = '\n' # self.et.write(fname, encoding=encoding) # # def tostring(self): # return self.et.tostring() # # def ensure_child(self, tag): # retval = self.et.find("./" + tag) # if retval is not None: # return elem(retval) # return elem(SubElement(self.et.getroot(), tag)) # # def set_child_position(self, child, pos): # root = self.et.getroot() # root.remove(child.et) # root.insert(pos, child.et) # # def setroot(self, tag): # retval = elem(Element(tag)) # # pylint: disable=protected-access # self.et._setroot(retval.et) # return retval # # @property # def root(self): # return elem(self.et.getroot()) # # Path: elbepack/directories.py # def init_directories(elbe_relpath): # def get_cmdlist(): # # Path: elbepack/templates.py # def write_template(outname, fname, d, linebreak=False): # outfile = open(outname, "w") # outfile.write(template(fname, d, linebreak)) # outfile.close() . Output only the next line.
xml = etree(args[0])
Continue the code snippet: <|code_start|> def run_command(argv): oparser = OptionParser( usage="usage: %prog xsdtoasciidoc [options] <xsdfile>") oparser.add_option("--output", dest="out", help="specify output filename", metavar="FILE") (opt, args) = oparser.parse_args(argv) if len(args) != 1: print("Wrong number of arguments") oparser.print_help() sys.exit(20) xml = etree(args[0]) if not opt.out: print("--output is mandatory") sys.exit(20) d = {"opt": opt, "xml": xml} <|code_end|> . Use current file imports: import sys from optparse import OptionParser from elbepack.treeutils import etree from elbepack.directories import xsdtoasciidoc_mako_fname from elbepack.templates import write_template and context (classes, functions, or code) from other files: # Path: elbepack/treeutils.py # class etree(ebase): # def __init__(self, fname): # if fname is not None: # parser = XMLParser(huge_tree=True, remove_comments=False) # et = parse(fname, parser=parser) # else: # et = ElementTree(file=None) # # ebase.__init__(self, et) # # def write(self, fname, encoding=None): # # Make sure, that we end with a newline # self.et.getroot().tail = '\n' # self.et.write(fname, encoding=encoding) # # def tostring(self): # return self.et.tostring() # # def ensure_child(self, tag): # retval = self.et.find("./" + tag) # if retval is not None: # return elem(retval) # return elem(SubElement(self.et.getroot(), tag)) # # def set_child_position(self, child, pos): # root = self.et.getroot() # root.remove(child.et) # root.insert(pos, child.et) # # def setroot(self, tag): # retval = elem(Element(tag)) # # pylint: disable=protected-access # self.et._setroot(retval.et) # return retval # # @property # def root(self): # return elem(self.et.getroot()) # # Path: elbepack/directories.py # def init_directories(elbe_relpath): # def get_cmdlist(): # # Path: elbepack/templates.py # def write_template(outname, fname, d, linebreak=False): # outfile = open(outname, "w") # outfile.write(template(fname, d, linebreak)) # outfile.close() . Output only the next line.
write_template(opt.out, xsdtoasciidoc_mako_fname, d)
Predict the next line after this snippet: <|code_start|> def run_command(argv): oparser = OptionParser( usage="usage: %prog xsdtoasciidoc [options] <xsdfile>") oparser.add_option("--output", dest="out", help="specify output filename", metavar="FILE") (opt, args) = oparser.parse_args(argv) if len(args) != 1: print("Wrong number of arguments") oparser.print_help() sys.exit(20) xml = etree(args[0]) if not opt.out: print("--output is mandatory") sys.exit(20) d = {"opt": opt, "xml": xml} <|code_end|> using the current file's imports: import sys from optparse import OptionParser from elbepack.treeutils import etree from elbepack.directories import xsdtoasciidoc_mako_fname from elbepack.templates import write_template and any relevant context from other files: # Path: elbepack/treeutils.py # class etree(ebase): # def __init__(self, fname): # if fname is not None: # parser = XMLParser(huge_tree=True, remove_comments=False) # et = parse(fname, parser=parser) # else: # et = ElementTree(file=None) # # ebase.__init__(self, et) # # def write(self, fname, encoding=None): # # Make sure, that we end with a newline # self.et.getroot().tail = '\n' # self.et.write(fname, encoding=encoding) # # def tostring(self): # return self.et.tostring() # # def ensure_child(self, tag): # retval = self.et.find("./" + tag) # if retval is not None: # return elem(retval) # return elem(SubElement(self.et.getroot(), tag)) # # def set_child_position(self, child, pos): # root = self.et.getroot() # root.remove(child.et) # root.insert(pos, child.et) # # def setroot(self, tag): # retval = elem(Element(tag)) # # pylint: disable=protected-access # self.et._setroot(retval.et) # return retval # # @property # def root(self): # return elem(self.et.getroot()) # # Path: elbepack/directories.py # def init_directories(elbe_relpath): # def get_cmdlist(): # # Path: elbepack/templates.py # def write_template(outname, fname, d, linebreak=False): # outfile = open(outname, "w") # outfile.write(template(fname, d, linebreak)) # outfile.close() . Output only the next line.
write_template(opt.out, xsdtoasciidoc_mako_fname, d)
Next line prediction: <|code_start|># ELBE - Debian Based Embedded Rootfilesystem Builder # Copyright (c) 2014 Stefan Gast <stefan.gast@linutronix.de> # Copyright (c) 2014-2015, 2017 Manuel Traut <manut@linutronix.de> # # SPDX-License-Identifier: GPL-3.0-or-later def run_command(argv): if len(argv) != 2: print("Wrong number of arguments.") print("Please pass the name of the file to sign " "and a valid gnupg fingerprint.") return <|code_end|> . Use current file imports: (from elbepack.egpg import sign_file) and context including class names, function names, or small code snippets from other files: # Path: elbepack/egpg.py # def sign_file(fname, fingerprint): # outfilename = fname + '.gpg' # sign(fname, outfilename, fingerprint) . Output only the next line.
sign_file(argv[0], argv[1])
Given the following code snippet before the placeholder: <|code_start|> if p.current_state == apt_pkg.CURSTATE_INSTALLED: return True return False def bootup_check(xml): fpl = xml.node("fullpkgs") apt_pkg.init() cache = apt_pkg.Cache() hl_cache = apt.cache.Cache() for p in hl_cache: if p.is_installed: if not is_in_fpl(p, fpl): print("%s installed by user" % p.name) for ip in fpl: if not is_installed(ip, cache): print("%s removed by user" % ip.et.text) def bootup_info(): with open("/etc/elbe_version", 'r') as ev: print(ev.read()) def run_command(_argv): try: <|code_end|> , predict the next line using imports from the current file: import apt import apt_pkg from elbepack.treeutils import etree and context including class names, function names, and sometimes code from other files: # Path: elbepack/treeutils.py # class etree(ebase): # def __init__(self, fname): # if fname is not None: # parser = XMLParser(huge_tree=True, remove_comments=False) # et = parse(fname, parser=parser) # else: # et = ElementTree(file=None) # # ebase.__init__(self, et) # # def write(self, fname, encoding=None): # # Make sure, that we end with a newline # self.et.getroot().tail = '\n' # self.et.write(fname, encoding=encoding) # # def tostring(self): # return self.et.tostring() # # def ensure_child(self, tag): # retval = self.et.find("./" + tag) # if retval is not None: # return elem(retval) # return elem(SubElement(self.et.getroot(), tag)) # # def set_child_position(self, child, pos): # root = self.et.getroot() # root.remove(child.et) # root.insert(pos, child.et) # # def setroot(self, tag): # retval = elem(Element(tag)) # # pylint: disable=protected-access # self.et._setroot(retval.et) # return retval # # @property # def root(self): # return elem(self.et.getroot()) . Output only the next line.
xml = etree("/etc/elbe_base.xml")
Given the code snippet: <|code_start|> print("Error: While signing - %s", E) else: outdata.seek(0, os.SEEK_SET) signature = outdata.read() with open(outfile, 'w') as fd: fd.write(signature) def sign_file(fname, fingerprint): outfilename = fname + '.gpg' sign(fname, outfilename, fingerprint) def get_fingerprints(): ctx = core.Context() ctx.set_engine_info(PROTOCOL_OpenPGP, None, '/var/cache/elbe/gnupg') keys = ctx.op_keylist_all(None, False) fingerprints = [] for k in keys: fingerprints.append(k.subkeys[0].fpr) return fingerprints # End Of Time - Roughtly 136 years # # The argument parser of GPG use the type unsigned long for # default-cache-ttl and max-cache-ttl values. Thus we're setting the # least maximum value of the type unsigned long to ensure that the # passphrase is 'never' removed from gpg-agent. EOT = 4294967295 def generate_elbe_internal_key(): <|code_end|> , generate the next line using the imports in this file: import os from gpg import core from gpg.constants import sigsum, sig, PROTOCOL_OpenPGP from gpg.errors import GPGMEError, KeyNotFound, InvalidSigners from elbepack.filesystem import hostfs from elbepack.shellhelper import system and context (functions, classes, or occasionally code) from other files: # Path: elbepack/filesystem.py # def size_to_int(size): # def __init__(self, path, clean=False): # def fname(self, path): # def open(self, path, mode="r"): # def open_gz(self, path, mode="r"): # def isdir(self, path): # def islink(self, path): # def isfile(self, path): # def exists(self, path): # def lexists(self, path): # def mkdir(self, path): # def readlink(self, path): # def realpath(self, path): # def symlink(self, src, path, allow_exists=False): # def stat(self, path): # def chown(self, path, uid, gid): # def chmod(self, path, mode): # def utime(self, path, times=None): # def cat_file(self, inf): # def remove(self, path, noerr=False): # def rmtree(self, path): # def listdir(self, path='', ignore=None, skiplinks=False): # def glob(self, path): # def _write_file(path, f, cont, mode): # def write_file(self, path, mode, cont): # def append_file(self, path, cont, mode=None): # def read_file(self, path, gz=False): # def mkdir_p(self, newdir, mode=0o755): # def touch_file(self, fname): # def walk_files(self, directory='', exclude_dirs=None): # def mtime_snap(self, dirname='', exclude_dirs=None): # def __disk_usage(self, directory): # def disk_usage(self, dirname=''): # def __init__(self, debug=False): # def __del__(self): # def delete(self): # def __enter__(self): # def __exit__(self, exec_type, exec_value, tb): # def __init__(self, mntpoint, dev): # def __enter__(self): # def __exit__(self, typ, value, traceback): # class Filesystem: # class TmpdirFilesystem (Filesystem): # class ImgMountFilesystem(Filesystem): # # Path: elbepack/shellhelper.py # def system(cmd, allow_fail=False, env_add=None): # """system() - Execute cmd in a shell. # # Throws a CommandError if cmd returns none-zero and allow_fail=False # # -- # # >>> system("true") # # >>> system("false", allow_fail=True) # # >>> system("$FALSE", env_add={"FALSE":"false"}) # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # # """ # new_env = os.environ.copy() # if env_add: # new_env.update(env_add) # # ret = call(cmd, shell=True, env=new_env) # # if ret != 0: # if not allow_fail: # raise CommandError(cmd, ret) . Output only the next line.
hostfs.mkdir_p("/var/cache/elbe/gnupg")
Predict the next line for this snippet: <|code_start|> try: infile = core.Data(file=fname) outfile = core.Data(file=outfilename) except (GPGMEError, ValueError) as E: print("Error: Opening file %s or %s - %s" % (fname, outfilename, E)) else: # obtain signature and write unsigned file ctx.op_verify(infile, None, outfile) vres = ctx.op_verify_result() for signature in vres.signatures: status = check_signature(ctx, signature) overall_status.add(status) if overall_status.to_exitcode(): return None return outfilename return None def unlock_key(fingerprint): ctx = core.Context() ctx.set_engine_info(PROTOCOL_OpenPGP, None, '/var/cache/elbe/gnupg') key = ctx.get_key(fingerprint, secret=True) keygrip = key.subkeys[0].keygrip <|code_end|> with the help of current file imports: import os from gpg import core from gpg.constants import sigsum, sig, PROTOCOL_OpenPGP from gpg.errors import GPGMEError, KeyNotFound, InvalidSigners from elbepack.filesystem import hostfs from elbepack.shellhelper import system and context from other files: # Path: elbepack/filesystem.py # def size_to_int(size): # def __init__(self, path, clean=False): # def fname(self, path): # def open(self, path, mode="r"): # def open_gz(self, path, mode="r"): # def isdir(self, path): # def islink(self, path): # def isfile(self, path): # def exists(self, path): # def lexists(self, path): # def mkdir(self, path): # def readlink(self, path): # def realpath(self, path): # def symlink(self, src, path, allow_exists=False): # def stat(self, path): # def chown(self, path, uid, gid): # def chmod(self, path, mode): # def utime(self, path, times=None): # def cat_file(self, inf): # def remove(self, path, noerr=False): # def rmtree(self, path): # def listdir(self, path='', ignore=None, skiplinks=False): # def glob(self, path): # def _write_file(path, f, cont, mode): # def write_file(self, path, mode, cont): # def append_file(self, path, cont, mode=None): # def read_file(self, path, gz=False): # def mkdir_p(self, newdir, mode=0o755): # def touch_file(self, fname): # def walk_files(self, directory='', exclude_dirs=None): # def mtime_snap(self, dirname='', exclude_dirs=None): # def __disk_usage(self, directory): # def disk_usage(self, dirname=''): # def __init__(self, debug=False): # def __del__(self): # def delete(self): # def __enter__(self): # def __exit__(self, exec_type, exec_value, tb): # def __init__(self, mntpoint, dev): # def __enter__(self): # def __exit__(self, typ, value, traceback): # class Filesystem: # class TmpdirFilesystem (Filesystem): # class ImgMountFilesystem(Filesystem): # # Path: elbepack/shellhelper.py # def system(cmd, allow_fail=False, env_add=None): # """system() - Execute cmd in a shell. # # Throws a CommandError if cmd returns none-zero and allow_fail=False # # -- # # >>> system("true") # # >>> system("false", allow_fail=True) # # >>> system("$FALSE", env_add={"FALSE":"false"}) # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # # """ # new_env = os.environ.copy() # if env_add: # new_env.update(env_add) # # ret = call(cmd, shell=True, env=new_env) # # if ret != 0: # if not allow_fail: # raise CommandError(cmd, ret) , which may contain function names, class names, or code. Output only the next line.
system("/usr/lib/gnupg/gpg-preset-passphrase "
Next line prediction: <|code_start|># ELBE - Debian Based Embedded Rootfilesystem Builder # Copyright (c) 2016 Torben Hohn <torben.hohn@linutronix.de> # Copyright (c) 2017 Manuel Traut <manut@linutronix.de> # # SPDX-License-Identifier: GPL-3.0-or-later class license_dep5_to_spdx (dict): def __init__(self, xml_fname=None): dict.__init__(self) self.perpackage_mapping = {} self.perpackage_override = {} if xml_fname is None: return <|code_end|> . Use current file imports: (from optparse import OptionParser from datetime import datetime from tempfile import NamedTemporaryFile from elbepack.treeutils import etree from elbepack.version import elbe_version from elbepack.shellhelper import system_out import sys import os import io) and context including class names, function names, or small code snippets from other files: # Path: elbepack/treeutils.py # class etree(ebase): # def __init__(self, fname): # if fname is not None: # parser = XMLParser(huge_tree=True, remove_comments=False) # et = parse(fname, parser=parser) # else: # et = ElementTree(file=None) # # ebase.__init__(self, et) # # def write(self, fname, encoding=None): # # Make sure, that we end with a newline # self.et.getroot().tail = '\n' # self.et.write(fname, encoding=encoding) # # def tostring(self): # return self.et.tostring() # # def ensure_child(self, tag): # retval = self.et.find("./" + tag) # if retval is not None: # return elem(retval) # return elem(SubElement(self.et.getroot(), tag)) # # def set_child_position(self, child, pos): # root = self.et.getroot() # root.remove(child.et) # root.insert(pos, child.et) # # def setroot(self, tag): # retval = elem(Element(tag)) # # pylint: disable=protected-access # self.et._setroot(retval.et) # return retval # # @property # def root(self): # return elem(self.et.getroot()) # # Path: elbepack/version.py # # Path: elbepack/shellhelper.py # def system_out(cmd, stdin=None, allow_fail=False, env_add=None): # """system_out() - Wrapper around command_out(). # # On failure, raises an exception if allow_fail=False, on success, # returns the output of cmd. # # -- # # >>> system_out("false") # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # # >>> system_out("false", allow_fail=True) # '' # # """ # code, out = command_out(cmd, stdin=stdin, env_add=env_add) # # if code != 0: # if not allow_fail: # raise CommandError(cmd, code) # # return out . Output only the next line.
xml = etree(xml_fname)
Predict the next line for this snippet: <|code_start|> sp.et.text = '\n' for l in mapping.get_override(pkg_name): ll = sp.append('license') ll.et.text = l if opt.use_nomos: nomos_l = scan_nomos(pkg.text('text')) if nomos_l[0] != 'No_license_found': nomos_node = pkg.append('nomos_licenses') nomos_node.et.text = '\n' for l in nomos_l: ll = nomos_node.append('license') ll.et.text = l if errors: for e in errors: ee = pkg.append('error') ee.et.text = e err_pkg += 1 elif opt.only_errors: # No Errors, and only_errors is active # Remove package node tree.root.remove_child(pkg) if opt.tagvalue is not None: with io.open(opt.tagvalue, "wt", encoding='utf-8') as fp: fp.write(u'SPDXVersion: SPDX-1.2\n') fp.write(u'DataLicense: CC0-1.0\n') fp.write(u'\n') fp.write(u'## Creation Information\n') <|code_end|> with the help of current file imports: from optparse import OptionParser from datetime import datetime from tempfile import NamedTemporaryFile from elbepack.treeutils import etree from elbepack.version import elbe_version from elbepack.shellhelper import system_out import sys import os import io and context from other files: # Path: elbepack/treeutils.py # class etree(ebase): # def __init__(self, fname): # if fname is not None: # parser = XMLParser(huge_tree=True, remove_comments=False) # et = parse(fname, parser=parser) # else: # et = ElementTree(file=None) # # ebase.__init__(self, et) # # def write(self, fname, encoding=None): # # Make sure, that we end with a newline # self.et.getroot().tail = '\n' # self.et.write(fname, encoding=encoding) # # def tostring(self): # return self.et.tostring() # # def ensure_child(self, tag): # retval = self.et.find("./" + tag) # if retval is not None: # return elem(retval) # return elem(SubElement(self.et.getroot(), tag)) # # def set_child_position(self, child, pos): # root = self.et.getroot() # root.remove(child.et) # root.insert(pos, child.et) # # def setroot(self, tag): # retval = elem(Element(tag)) # # pylint: disable=protected-access # self.et._setroot(retval.et) # return retval # # @property # def root(self): # return elem(self.et.getroot()) # # Path: elbepack/version.py # # Path: elbepack/shellhelper.py # def system_out(cmd, stdin=None, allow_fail=False, env_add=None): # """system_out() - Wrapper around command_out(). # # On failure, raises an exception if allow_fail=False, on success, # returns the output of cmd. # # -- # # >>> system_out("false") # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # # >>> system_out("false", allow_fail=True) # '' # # """ # code, out = command_out(cmd, stdin=stdin, env_add=env_add) # # if code != 0: # if not allow_fail: # raise CommandError(cmd, code) # # return out , which may contain function names, class names, or code. Output only the next line.
fp.write(u'Creator: Tool: elbe-%s\n' % elbe_version)
Predict the next line for this snippet: <|code_start|> pkgname, with_split[0], errors) if mapped_lic is None: mapped_lic = u"UNKNOWN_MAPPING(%s)" % with_split[0] if len(with_split) == 2: ands.append(mapped_lic + u" WITH " + with_split[1]) else: ands.append(mapped_lic) ors.append(' AND '.join(ands)) retval = ' OR '.join(ors) return retval def map_lic(self, pkgname, licenses, errors): if pkgname in self.perpackage_override: if self.perpackage_override[pkgname]: return self.perpackage_override[pkgname] retval = [] for l in licenses: if l is not None: retval.append(self.map_license_string(pkgname, l, errors)) else: retval.append('Empty license') return retval def scan_nomos(license_text): with NamedTemporaryFile() as f: f.write(license_text.encode('utf-8')) <|code_end|> with the help of current file imports: from optparse import OptionParser from datetime import datetime from tempfile import NamedTemporaryFile from elbepack.treeutils import etree from elbepack.version import elbe_version from elbepack.shellhelper import system_out import sys import os import io and context from other files: # Path: elbepack/treeutils.py # class etree(ebase): # def __init__(self, fname): # if fname is not None: # parser = XMLParser(huge_tree=True, remove_comments=False) # et = parse(fname, parser=parser) # else: # et = ElementTree(file=None) # # ebase.__init__(self, et) # # def write(self, fname, encoding=None): # # Make sure, that we end with a newline # self.et.getroot().tail = '\n' # self.et.write(fname, encoding=encoding) # # def tostring(self): # return self.et.tostring() # # def ensure_child(self, tag): # retval = self.et.find("./" + tag) # if retval is not None: # return elem(retval) # return elem(SubElement(self.et.getroot(), tag)) # # def set_child_position(self, child, pos): # root = self.et.getroot() # root.remove(child.et) # root.insert(pos, child.et) # # def setroot(self, tag): # retval = elem(Element(tag)) # # pylint: disable=protected-access # self.et._setroot(retval.et) # return retval # # @property # def root(self): # return elem(self.et.getroot()) # # Path: elbepack/version.py # # Path: elbepack/shellhelper.py # def system_out(cmd, stdin=None, allow_fail=False, env_add=None): # """system_out() - Wrapper around command_out(). # # On failure, raises an exception if allow_fail=False, on success, # returns the output of cmd. # # -- # # >>> system_out("false") # doctest: +ELLIPSIS # Traceback (most recent call last): # ... # elbepack.shellhelper.CommandError: ... # # >>> system_out("false", allow_fail=True) # '' # # """ # code, out = command_out(cmd, stdin=stdin, env_add=env_add) # # if code != 0: # if not allow_fail: # raise CommandError(cmd, code) # # return out , which may contain function names, class names, or code. Output only the next line.
nomos_out = system_out(
Given the following code snippet before the placeholder: <|code_start|># ELBE - Debian Based Embedded Rootfilesystem Builder # Copyright (c) 2020 Olivier Dion <dion@linutronix.de> # Copyright (c) 2020 Torben Hohn <torbenh@linutronix.de> # # SPDX-License-Identifier: GPL-3.0-or-later class TestCopyFilelist(unittest.TestCase): def setUp(self): self.src = TmpdirFilesystem() self.dst = TmpdirFilesystem() def tearDown(self): del self.src del self.dst def test_usrmerge_abs(self): self.src.mkdir_p('/usr/bin') # this will link to /usr/bin in the host RFS, # when no special logic is applied. self.src.symlink('/usr/bin', '/bin') self.src.write_file('/bin/bla', 0o644, 'bla') <|code_end|> , predict the next line using imports from the current file: import unittest from elbepack.filesystem import TmpdirFilesystem from elbepack.efilesystem import copy_filelist and context including class names, function names, and sometimes code from other files: # Path: elbepack/filesystem.py # class TmpdirFilesystem (Filesystem): # def __init__(self, debug=False): # tmpdir = mkdtemp() # Filesystem.__init__(self, tmpdir) # self.debug = debug # # def __del__(self): # # dont delete files in debug mode # if self.debug: # print('leaving TmpdirFilesystem in "%s"' % self.path) # else: # self.delete() # # def delete(self): # shutil.rmtree(self.path, True) # # def __enter__(self): # return self # # def __exit__(self, exec_type, exec_value, tb): # shutil.rmtree(self.path) # return False # # Path: elbepack/efilesystem.py # def copy_filelist(src, file_lst, dst): # # # pylint: disable=too-many-branches # # files = set() # copied = set() # # # Make sure to copy parent directories # # # # For example, if file_lst = ['/usr/bin/bash'], # # we might get {'/usr/bin', '/usr', '/usr/bin/bash'} # for f in file_lst: # parts = f.rstrip('\n') # while parts != os.sep: # files.add(parts) # parts, _ = os.path.split(parts) # # # Start from closest to root first # files = list(files) # files.sort() # files.reverse() # # while files: # # f = files.pop() # copied.add(f) # # if src.islink(f): # # tgt = src.readlink(f) # # if not src.lexists(tgt): # dst.symlink(tgt, f, allow_exists=True) # continue # # # If the target is not yet in the destination RFS, we need # # to defer the copy of the symlink after the target is # # resolved. Thus, we recusively call copy_filelist # # # # Not that this will result in an infinite loop for # # circular symlinks # if not dst.lexists(tgt): # if not os.path.isabs(tgt): # lst = [os.path.join(os.path.dirname(f), tgt)] # else: # lst = [tgt] # copy_filelist(src, lst, dst) # # dst.symlink(tgt, f, allow_exists=True) # # elif src.isdir(f): # if not dst.isdir(f): # dst.mkdir(f) # st = src.stat(f) # dst.chown(f, st.st_uid, st.st_gid) # # else: # try: # system('cp -a --reflink=auto "%s" "%s"' % (src.realpath(f), # dst.realpath(f))) # except CommandError as E: # logging.warning("Error while copying from %s to %s of file %s - %s", # src.path, dst.path, f, E) # # # update utime which will change after a file has been copied into # # the directory # for f in copied: # if src.isdir(f) and not src.islink(f): # shutil.copystat(src.fname(f), dst.fname(f)) . Output only the next line.
copy_filelist(self.src, ['/bin/bla'], self.dst)
Given the following code snippet before the placeholder: <|code_start|># ELBE - Debian Based Embedded Rootfilesystem Builder # Copyright (c) 2014 Stefan Gast <stefan.gast@linutronix.de> # Copyright (c) 2014, 2017 Manuel Traut <manut@linutronix.de> # # SPDX-License-Identifier: GPL-3.0-or-later def run_command(argv): if len(argv) != 1: print("Wrong number of arguments.") print("Please pass the name of the file to unsign.") return <|code_end|> , predict the next line using imports from the current file: from elbepack.egpg import unsign_file and context including class names, function names, and sometimes code from other files: # Path: elbepack/egpg.py # def unsign_file(fname): # # check for .gpg extension and create an output filename without it # if len(fname) <= 4 or fname[len(fname) - 4:] != '.gpg': # print("The input file needs a .gpg extension") # return None # # outfilename = fname[:len(fname) - 4] # # ctx = core.Context() # ctx.set_engine_info(PROTOCOL_OpenPGP, # None, # '/var/cache/elbe/gnupg') # ctx.set_armor(False) # # overall_status = OverallStatus() # # try: # infile = core.Data(file=fname) # outfile = core.Data(file=outfilename) # except (GPGMEError, ValueError) as E: # print("Error: Opening file %s or %s - %s" % # (fname, outfilename, E)) # else: # # obtain signature and write unsigned file # ctx.op_verify(infile, None, outfile) # vres = ctx.op_verify_result() # # for signature in vres.signatures: # status = check_signature(ctx, signature) # overall_status.add(status) # # if overall_status.to_exitcode(): # return None # # return outfilename # # return None . Output only the next line.
fname = unsign_file(argv[0])
Given the following code snippet before the placeholder: <|code_start|> class SoapElbeInvalidState(Fault): def __init__(self): Fault.__init__(self, faultcode="ElbeInvalidState", faultstring="Project is Busy ! Operation Invalid") def soap_faults(func): """ decorator, which wraps Exceptions to the proper Soap Faults, and raises these. """ # Do not edit this code. Although using *args is tempting here, # it will not work because Spyne is doing introspection on the # function's signature. I think it would be possible to do # something with func.__code__.replace, but this requires deep # Python's internal knowledges. # pylint: disable=too-many-return-statements # pylint: disable=too-many-statements # pylint: disable=function-redefined if func.__code__.co_argcount == 1: @wraps(func) def wrapped(self): try: return func(self) except InvalidState as e: raise SoapElbeInvalidState() <|code_end|> , predict the next line using imports from the current file: from traceback import format_exc from functools import wraps from spyne.model.fault import Fault from elbepack.projectmanager import ProjectManagerError, InvalidState from elbepack.elbexml import ValidationError from elbepack.db import ElbeDBError, InvalidLogin and context including class names, function names, and sometimes code from other files: # Path: elbepack/projectmanager.py # class ProjectManagerError(Exception): # def __init__(self, message): # Exception.__init__(self, message) # # class InvalidState(ProjectManagerError): # def __init__(self, message): # ProjectManagerError.__init__(self, message) # # Path: elbepack/elbexml.py # class ValidationError(Exception): # def __init__(self, validation): # Exception.__init__(self) # self.validation = validation # # def __repr__(self): # rep = "Elbe XML Validation Error\n" # for v in self.validation: # rep += (v + '\n') # return rep # # def __str__(self): # retval = "" # for v in self.validation: # retval += (v + '\n') # return retval # # Path: elbepack/db.py # class ElbeDBError(Exception): # def __init__(self, message): # Exception.__init__(self, message) # # class InvalidLogin(Exception): # def __init__(self): # Exception.__init__(self, "Invalid login") . Output only the next line.
except ProjectManagerError as e:
Using the snippet: <|code_start|> faultcode="ElbeValidationError", faultstring=exc.__repr__()) class SoapElbeInvalidState(Fault): def __init__(self): Fault.__init__(self, faultcode="ElbeInvalidState", faultstring="Project is Busy ! Operation Invalid") def soap_faults(func): """ decorator, which wraps Exceptions to the proper Soap Faults, and raises these. """ # Do not edit this code. Although using *args is tempting here, # it will not work because Spyne is doing introspection on the # function's signature. I think it would be possible to do # something with func.__code__.replace, but this requires deep # Python's internal knowledges. # pylint: disable=too-many-return-statements # pylint: disable=too-many-statements # pylint: disable=function-redefined if func.__code__.co_argcount == 1: @wraps(func) def wrapped(self): try: return func(self) <|code_end|> , determine the next line of code. You have imports: from traceback import format_exc from functools import wraps from spyne.model.fault import Fault from elbepack.projectmanager import ProjectManagerError, InvalidState from elbepack.elbexml import ValidationError from elbepack.db import ElbeDBError, InvalidLogin and context (class names, function names, or code) available: # Path: elbepack/projectmanager.py # class ProjectManagerError(Exception): # def __init__(self, message): # Exception.__init__(self, message) # # class InvalidState(ProjectManagerError): # def __init__(self, message): # ProjectManagerError.__init__(self, message) # # Path: elbepack/elbexml.py # class ValidationError(Exception): # def __init__(self, validation): # Exception.__init__(self) # self.validation = validation # # def __repr__(self): # rep = "Elbe XML Validation Error\n" # for v in self.validation: # rep += (v + '\n') # return rep # # def __str__(self): # retval = "" # for v in self.validation: # retval += (v + '\n') # return retval # # Path: elbepack/db.py # class ElbeDBError(Exception): # def __init__(self, message): # Exception.__init__(self, message) # # class InvalidLogin(Exception): # def __init__(self): # Exception.__init__(self, "Invalid login") . Output only the next line.
except InvalidState as e:
Here is a snippet: <|code_start|> def soap_faults(func): """ decorator, which wraps Exceptions to the proper Soap Faults, and raises these. """ # Do not edit this code. Although using *args is tempting here, # it will not work because Spyne is doing introspection on the # function's signature. I think it would be possible to do # something with func.__code__.replace, but this requires deep # Python's internal knowledges. # pylint: disable=too-many-return-statements # pylint: disable=too-many-statements # pylint: disable=function-redefined if func.__code__.co_argcount == 1: @wraps(func) def wrapped(self): try: return func(self) except InvalidState as e: raise SoapElbeInvalidState() except ProjectManagerError as e: raise SoapElbeProjectError(str(e)) except ElbeDBError as e: raise SoapElbeDBError(str(e)) except OSError as e: raise SoapElbeProjectError("OSError: " + str(e)) <|code_end|> . Write the next line using the current file imports: from traceback import format_exc from functools import wraps from spyne.model.fault import Fault from elbepack.projectmanager import ProjectManagerError, InvalidState from elbepack.elbexml import ValidationError from elbepack.db import ElbeDBError, InvalidLogin and context from other files: # Path: elbepack/projectmanager.py # class ProjectManagerError(Exception): # def __init__(self, message): # Exception.__init__(self, message) # # class InvalidState(ProjectManagerError): # def __init__(self, message): # ProjectManagerError.__init__(self, message) # # Path: elbepack/elbexml.py # class ValidationError(Exception): # def __init__(self, validation): # Exception.__init__(self) # self.validation = validation # # def __repr__(self): # rep = "Elbe XML Validation Error\n" # for v in self.validation: # rep += (v + '\n') # return rep # # def __str__(self): # retval = "" # for v in self.validation: # retval += (v + '\n') # return retval # # Path: elbepack/db.py # class ElbeDBError(Exception): # def __init__(self, message): # Exception.__init__(self, message) # # class InvalidLogin(Exception): # def __init__(self): # Exception.__init__(self, "Invalid login") , which may include functions, classes, or code. Output only the next line.
except ValidationError as e:
Given the code snippet: <|code_start|>class SoapElbeInvalidState(Fault): def __init__(self): Fault.__init__(self, faultcode="ElbeInvalidState", faultstring="Project is Busy ! Operation Invalid") def soap_faults(func): """ decorator, which wraps Exceptions to the proper Soap Faults, and raises these. """ # Do not edit this code. Although using *args is tempting here, # it will not work because Spyne is doing introspection on the # function's signature. I think it would be possible to do # something with func.__code__.replace, but this requires deep # Python's internal knowledges. # pylint: disable=too-many-return-statements # pylint: disable=too-many-statements # pylint: disable=function-redefined if func.__code__.co_argcount == 1: @wraps(func) def wrapped(self): try: return func(self) except InvalidState as e: raise SoapElbeInvalidState() except ProjectManagerError as e: raise SoapElbeProjectError(str(e)) <|code_end|> , generate the next line using the imports in this file: from traceback import format_exc from functools import wraps from spyne.model.fault import Fault from elbepack.projectmanager import ProjectManagerError, InvalidState from elbepack.elbexml import ValidationError from elbepack.db import ElbeDBError, InvalidLogin and context (functions, classes, or occasionally code) from other files: # Path: elbepack/projectmanager.py # class ProjectManagerError(Exception): # def __init__(self, message): # Exception.__init__(self, message) # # class InvalidState(ProjectManagerError): # def __init__(self, message): # ProjectManagerError.__init__(self, message) # # Path: elbepack/elbexml.py # class ValidationError(Exception): # def __init__(self, validation): # Exception.__init__(self) # self.validation = validation # # def __repr__(self): # rep = "Elbe XML Validation Error\n" # for v in self.validation: # rep += (v + '\n') # return rep # # def __str__(self): # retval = "" # for v in self.validation: # retval += (v + '\n') # return retval # # Path: elbepack/db.py # class ElbeDBError(Exception): # def __init__(self, message): # Exception.__init__(self, message) # # class InvalidLogin(Exception): # def __init__(self): # Exception.__init__(self, "Invalid login") . Output only the next line.
except ElbeDBError as e:
Given the following code snippet before the placeholder: <|code_start|>def soap_faults(func): """ decorator, which wraps Exceptions to the proper Soap Faults, and raises these. """ # Do not edit this code. Although using *args is tempting here, # it will not work because Spyne is doing introspection on the # function's signature. I think it would be possible to do # something with func.__code__.replace, but this requires deep # Python's internal knowledges. # pylint: disable=too-many-return-statements # pylint: disable=too-many-statements # pylint: disable=function-redefined if func.__code__.co_argcount == 1: @wraps(func) def wrapped(self): try: return func(self) except InvalidState as e: raise SoapElbeInvalidState() except ProjectManagerError as e: raise SoapElbeProjectError(str(e)) except ElbeDBError as e: raise SoapElbeDBError(str(e)) except OSError as e: raise SoapElbeProjectError("OSError: " + str(e)) except ValidationError as e: raise SoapElbeValidationError(e) <|code_end|> , predict the next line using imports from the current file: from traceback import format_exc from functools import wraps from spyne.model.fault import Fault from elbepack.projectmanager import ProjectManagerError, InvalidState from elbepack.elbexml import ValidationError from elbepack.db import ElbeDBError, InvalidLogin and context including class names, function names, and sometimes code from other files: # Path: elbepack/projectmanager.py # class ProjectManagerError(Exception): # def __init__(self, message): # Exception.__init__(self, message) # # class InvalidState(ProjectManagerError): # def __init__(self, message): # ProjectManagerError.__init__(self, message) # # Path: elbepack/elbexml.py # class ValidationError(Exception): # def __init__(self, validation): # Exception.__init__(self) # self.validation = validation # # def __repr__(self): # rep = "Elbe XML Validation Error\n" # for v in self.validation: # rep += (v + '\n') # return rep # # def __str__(self): # retval = "" # for v in self.validation: # retval += (v + '\n') # return retval # # Path: elbepack/db.py # class ElbeDBError(Exception): # def __init__(self, message): # Exception.__init__(self, message) # # class InvalidLogin(Exception): # def __init__(self): # Exception.__init__(self, "Invalid login") . Output only the next line.
except InvalidLogin:
Based on the snippet: <|code_start|># ELBE - Debian Based Embedded Rootfilesystem Builder # Copyright (c) 2013, 2017-2018 Manuel Traut <manut@linutronix.de> # Copyright (c) 2015 Torben Hohn <torbenh@linutronix.de> # # SPDX-License-Identifier: GPL-3.0-or-later elbe_version = "14.1" elbe_initvm_packagelist = ['python3-elbe-buildenv', 'python3-elbe-soap', 'python3-elbe-common', 'python3-elbe-daemon', 'elbe-schema', 'python3-elbe-bin'] <|code_end|> , predict the immediate next line with the help of imports: from elbepack.directories import pack_dir and context (classes, functions, sometimes code) from other files: # Path: elbepack/directories.py # def init_directories(elbe_relpath): # def get_cmdlist(): . Output only the next line.
if pack_dir.startswith('/usr/lib/python'):
Next line prediction: <|code_start|> logger = get_logger() def read_or_write(data_f, fallback=None): """Loads the data file if it exists. Otherwise, if fallback is provided, call fallback and save its return to disk. Args: data_f (str): Path to the data file, whose extension will be used for deciding how to load the data. fallback (function, optional): Fallback function used if data file doesn't exist. Its return will be saved to ``data_f`` for future loadings. It should not take arguments, but if yours requires taking arguments, just wrap yours with:: fallback=lambda: your_fancy_func(var0, var1) Returns: Data loaded if ``data_f`` exists; otherwise, ``fallback``'s return (``None`` if no fallback). Writes - Return by the fallback, if provided. """ # Decide data file type ext = data_f.split('.')[-1].lower() def load_func(path): <|code_end|> . Use current file imports: (from os.path import dirname from ..os import open_file, exists_isdir, makedirs from ..log import get_logger import numpy as np) and context including class names, function names, or small code snippets from other files: # Path: third_party/xiuminglib/xiuminglib/os.py # def open_file(path, mode): # """Opens a file. # # Supports Google Colossus if ``gfile`` can be imported. # # Args: # path (str): Path to open. # mode (str): ``'r'``, ``'rb'``, ``'w'``, or ``'wb'``. # # Returns: # File handle that can be used as a context. # """ # gfile = preset_import('gfile') # # open_func = open if gfile is None else gfile.Open # handle = open_func(path, mode) # # return handle # # def exists_isdir(path): # """Determines whether a path exists, and if so, whether it is a file # or directory. # # Supports Google Colossus (CNS) paths by using ``gfile`` (preferred for # speed) or the ``fileutil`` CLI. # # Args: # path (str): A path. # # Returns: # tuple: # - **exists** (*bool*) -- Whether the path exists. # - **isdir** (*bool*) -- Whether the path is a file or directory. # ``None`` if the path doesn't exist. # """ # path = _no_trailing_slash(path) # # # If local path, do the job quickly and return # if not _is_cnspath(path): # path_exists = exists(path) # path_isdir = isdir(path) if path_exists else None # return path_exists, path_isdir # # gfile = preset_import('gfile', assert_success=True) # # # Using fileutil CLI # if gfile is None: # testf, _, _ = call('fileutil test -f %s' % path) # testd, _, _ = call('fileutil test -d %s' % path) # if testf == 1 and testd == 1: # path_exists = False # path_isdir = None # elif testf == 1 and testd == 0: # path_exists = True # path_isdir = True # elif testf == 0 and testd == 1: # path_exists = True # path_isdir = False # else: # raise NotImplementedError("What does this even mean?") # # # Using gfile # else: # path_exists = gfile.Exists(path) # if path_exists: # path_isdir = gfile.IsDirectory(path) # else: # path_isdir = None # # return path_exists, path_isdir # # def makedirs(directory, rm_if_exists=False): # """Wraps :func:`os.makedirs` to support removing the directory if it # alread exists. # # Google Colossus-compatible: it tries to use ``gfile`` first for speed. This # will fail if Blaze is not used, in which case it then falls back to using # ``fileutil`` CLI as external process calls. # # Args: # directory (str) # rm_if_exists (bool, optional): Whether to remove the directory (and # its contents) if it already exists. # """ # def exists_cns_cli(directory): # cmd = 'fileutil test -d %s' % directory # retcode, _, _ = call(cmd, quiet=True) # if retcode == 0: # return True # if retcode == 1: # return False # raise ValueError(retcode) # # def mkdir_cns_cli(directory): # cmd = 'fileutil mkdir -p %s' % directory # _call_assert_success(cmd, quiet=True) # # if _is_cnspath(directory): # # Is a CNS path # gfile = preset_import('gfile') # if gfile is None: # exists_func = exists_cns_cli # mkdir_func = mkdir_cns_cli # else: # exists_func = gfile.Exists # mkdir_func = gfile.MakeDirs # else: # # Is just a regular local path # exists_func = exists # mkdir_func = os.makedirs # # # Do the job # if exists_func(directory): # if rm_if_exists: # rm(directory) # mkdir_func(directory) # logger.info("Removed and then remade:\n\t%s", directory) # else: # mkdir_func(directory) # # Path: third_party/xiuminglib/xiuminglib/log.py # def get_logger(level=None): # """Creates a logger for functions in the library. # # Args: # level (str, optional): Logging level. Defaults to ``logging.INFO``. # # Returns: # logging.Logger: Logger created. # """ # if level is None: # level = logging.INFO # logging.basicConfig(level=level) # logger = logging.getLogger() # return logger . Output only the next line.
with open_file(path, 'rb') as h:
Predict the next line after this snippet: <|code_start|> arguments, just wrap yours with:: fallback=lambda: your_fancy_func(var0, var1) Returns: Data loaded if ``data_f`` exists; otherwise, ``fallback``'s return (``None`` if no fallback). Writes - Return by the fallback, if provided. """ # Decide data file type ext = data_f.split('.')[-1].lower() def load_func(path): with open_file(path, 'rb') as h: data = np.load(h) return data def save_func(data, path): if ext == 'npy': save = np.save elif ext == 'npz': save = np.savez else: raise NotImplementedError(ext) with open_file(path, 'wb') as h: save(h, data) # Load or call fallback <|code_end|> using the current file's imports: from os.path import dirname from ..os import open_file, exists_isdir, makedirs from ..log import get_logger import numpy as np and any relevant context from other files: # Path: third_party/xiuminglib/xiuminglib/os.py # def open_file(path, mode): # """Opens a file. # # Supports Google Colossus if ``gfile`` can be imported. # # Args: # path (str): Path to open. # mode (str): ``'r'``, ``'rb'``, ``'w'``, or ``'wb'``. # # Returns: # File handle that can be used as a context. # """ # gfile = preset_import('gfile') # # open_func = open if gfile is None else gfile.Open # handle = open_func(path, mode) # # return handle # # def exists_isdir(path): # """Determines whether a path exists, and if so, whether it is a file # or directory. # # Supports Google Colossus (CNS) paths by using ``gfile`` (preferred for # speed) or the ``fileutil`` CLI. # # Args: # path (str): A path. # # Returns: # tuple: # - **exists** (*bool*) -- Whether the path exists. # - **isdir** (*bool*) -- Whether the path is a file or directory. # ``None`` if the path doesn't exist. # """ # path = _no_trailing_slash(path) # # # If local path, do the job quickly and return # if not _is_cnspath(path): # path_exists = exists(path) # path_isdir = isdir(path) if path_exists else None # return path_exists, path_isdir # # gfile = preset_import('gfile', assert_success=True) # # # Using fileutil CLI # if gfile is None: # testf, _, _ = call('fileutil test -f %s' % path) # testd, _, _ = call('fileutil test -d %s' % path) # if testf == 1 and testd == 1: # path_exists = False # path_isdir = None # elif testf == 1 and testd == 0: # path_exists = True # path_isdir = True # elif testf == 0 and testd == 1: # path_exists = True # path_isdir = False # else: # raise NotImplementedError("What does this even mean?") # # # Using gfile # else: # path_exists = gfile.Exists(path) # if path_exists: # path_isdir = gfile.IsDirectory(path) # else: # path_isdir = None # # return path_exists, path_isdir # # def makedirs(directory, rm_if_exists=False): # """Wraps :func:`os.makedirs` to support removing the directory if it # alread exists. # # Google Colossus-compatible: it tries to use ``gfile`` first for speed. This # will fail if Blaze is not used, in which case it then falls back to using # ``fileutil`` CLI as external process calls. # # Args: # directory (str) # rm_if_exists (bool, optional): Whether to remove the directory (and # its contents) if it already exists. # """ # def exists_cns_cli(directory): # cmd = 'fileutil test -d %s' % directory # retcode, _, _ = call(cmd, quiet=True) # if retcode == 0: # return True # if retcode == 1: # return False # raise ValueError(retcode) # # def mkdir_cns_cli(directory): # cmd = 'fileutil mkdir -p %s' % directory # _call_assert_success(cmd, quiet=True) # # if _is_cnspath(directory): # # Is a CNS path # gfile = preset_import('gfile') # if gfile is None: # exists_func = exists_cns_cli # mkdir_func = mkdir_cns_cli # else: # exists_func = gfile.Exists # mkdir_func = gfile.MakeDirs # else: # # Is just a regular local path # exists_func = exists # mkdir_func = os.makedirs # # # Do the job # if exists_func(directory): # if rm_if_exists: # rm(directory) # mkdir_func(directory) # logger.info("Removed and then remade:\n\t%s", directory) # else: # mkdir_func(directory) # # Path: third_party/xiuminglib/xiuminglib/log.py # def get_logger(level=None): # """Creates a logger for functions in the library. # # Args: # level (str, optional): Logging level. Defaults to ``logging.INFO``. # # Returns: # logging.Logger: Logger created. # """ # if level is None: # level = logging.INFO # logging.basicConfig(level=level) # logger = logging.getLogger() # return logger . Output only the next line.
if exists_isdir(data_f)[0]:
Given snippet: <|code_start|> # Decide data file type ext = data_f.split('.')[-1].lower() def load_func(path): with open_file(path, 'rb') as h: data = np.load(h) return data def save_func(data, path): if ext == 'npy': save = np.save elif ext == 'npz': save = np.savez else: raise NotImplementedError(ext) with open_file(path, 'wb') as h: save(h, data) # Load or call fallback if exists_isdir(data_f)[0]: data = load_func(data_f) msg = "Loaded: " else: msg = "File doesn't exist " if fallback is None: data = None msg += "(fallback not provided): " else: data = fallback() out_dir = dirname(data_f) <|code_end|> , continue by predicting the next line. Consider current file imports: from os.path import dirname from ..os import open_file, exists_isdir, makedirs from ..log import get_logger import numpy as np and context: # Path: third_party/xiuminglib/xiuminglib/os.py # def open_file(path, mode): # """Opens a file. # # Supports Google Colossus if ``gfile`` can be imported. # # Args: # path (str): Path to open. # mode (str): ``'r'``, ``'rb'``, ``'w'``, or ``'wb'``. # # Returns: # File handle that can be used as a context. # """ # gfile = preset_import('gfile') # # open_func = open if gfile is None else gfile.Open # handle = open_func(path, mode) # # return handle # # def exists_isdir(path): # """Determines whether a path exists, and if so, whether it is a file # or directory. # # Supports Google Colossus (CNS) paths by using ``gfile`` (preferred for # speed) or the ``fileutil`` CLI. # # Args: # path (str): A path. # # Returns: # tuple: # - **exists** (*bool*) -- Whether the path exists. # - **isdir** (*bool*) -- Whether the path is a file or directory. # ``None`` if the path doesn't exist. # """ # path = _no_trailing_slash(path) # # # If local path, do the job quickly and return # if not _is_cnspath(path): # path_exists = exists(path) # path_isdir = isdir(path) if path_exists else None # return path_exists, path_isdir # # gfile = preset_import('gfile', assert_success=True) # # # Using fileutil CLI # if gfile is None: # testf, _, _ = call('fileutil test -f %s' % path) # testd, _, _ = call('fileutil test -d %s' % path) # if testf == 1 and testd == 1: # path_exists = False # path_isdir = None # elif testf == 1 and testd == 0: # path_exists = True # path_isdir = True # elif testf == 0 and testd == 1: # path_exists = True # path_isdir = False # else: # raise NotImplementedError("What does this even mean?") # # # Using gfile # else: # path_exists = gfile.Exists(path) # if path_exists: # path_isdir = gfile.IsDirectory(path) # else: # path_isdir = None # # return path_exists, path_isdir # # def makedirs(directory, rm_if_exists=False): # """Wraps :func:`os.makedirs` to support removing the directory if it # alread exists. # # Google Colossus-compatible: it tries to use ``gfile`` first for speed. This # will fail if Blaze is not used, in which case it then falls back to using # ``fileutil`` CLI as external process calls. # # Args: # directory (str) # rm_if_exists (bool, optional): Whether to remove the directory (and # its contents) if it already exists. # """ # def exists_cns_cli(directory): # cmd = 'fileutil test -d %s' % directory # retcode, _, _ = call(cmd, quiet=True) # if retcode == 0: # return True # if retcode == 1: # return False # raise ValueError(retcode) # # def mkdir_cns_cli(directory): # cmd = 'fileutil mkdir -p %s' % directory # _call_assert_success(cmd, quiet=True) # # if _is_cnspath(directory): # # Is a CNS path # gfile = preset_import('gfile') # if gfile is None: # exists_func = exists_cns_cli # mkdir_func = mkdir_cns_cli # else: # exists_func = gfile.Exists # mkdir_func = gfile.MakeDirs # else: # # Is just a regular local path # exists_func = exists # mkdir_func = os.makedirs # # # Do the job # if exists_func(directory): # if rm_if_exists: # rm(directory) # mkdir_func(directory) # logger.info("Removed and then remade:\n\t%s", directory) # else: # mkdir_func(directory) # # Path: third_party/xiuminglib/xiuminglib/log.py # def get_logger(level=None): # """Creates a logger for functions in the library. # # Args: # level (str, optional): Logging level. Defaults to ``logging.INFO``. # # Returns: # logging.Logger: Logger created. # """ # if level is None: # level = logging.INFO # logging.basicConfig(level=level) # logger = logging.getLogger() # return logger which might include code, classes, or functions. Output only the next line.
makedirs(out_dir)
Here is a snippet: <|code_start|> assert h > 3, "Input has height (%d) > width (%d); the height" \ % (h, w) + err_str pts_homo = np.hstack((pts, np.ones((h, 1)))) elif h < w: # fat assert w > 3, "Input has width (%d) > height (%d); the width" \ % (w, h) + err_str pts_homo = np.vstack((pts, np.ones((1, w)))) else: # square raise ValueError( "Ambiguous square matrix that I can't guess how to pad") else: raise ValueError(pts.ndim) return pts_homo def from_homo(pts, axis=None): """Converts from homogeneous to non-homogeneous coordinates. Args: pts (numpy.ndarray or mathutils.Vector): NumPy array of N-D point(s), or Blender vector of a single N-D point. axis (int, optional): The last slice of which dimension holds the :math:`w` values. Optional for 1D inputs. Returns: numpy.ndarray or mathutils.Vector: Non-homogeneous coordinates of the input point(s). """ <|code_end|> . Write the next line using the current file imports: import numpy as np from ..imprt import preset_import and context from other files: # Path: third_party/xiuminglib/xiuminglib/imprt.py # def preset_import(name, assert_success=False): # """A unified importer for both regular and ``google3`` modules, according # to specified presets/profiles (e.g., ignoring ``ModuleNotFoundError``). # """ # if name in ('cv2', 'opencv'): # try: # # BUILD dep: # # "//third_party/py/cvx2", # from cvx2 import latest as mod # # Or # # BUILD dep: # # "//third_party/OpenCVX:cvx2", # # from google3.third_party.OpenCVX import cvx2 as cv2 # except ModuleNotFoundError: # mod = import_module_404ok('cv2') # # elif name in ('tf', 'tensorflow'): # mod = import_module_404ok('tensorflow') # # elif name == 'gfile': # # BUILD deps: # # "//pyglib:gfile", # # "//file/colossus/cns", # mod = import_module_404ok('google3.pyglib.gfile') # # elif name == 'video_api': # # BUILD deps: # # "//learning/deepmind/video/python:video_api", # mod = import_module_404ok( # 'google3.learning.deepmind.video.python.video_api') # # elif name in ('bpy', 'bmesh', 'OpenEXR', 'Imath'): # # BUILD deps: # # "//third_party/py/Imath", # # "//third_party/py/OpenEXR", # mod = import_module_404ok(name) # # elif name in ('Vector', 'Matrix', 'Quaternion'): # mod = import_module_404ok('mathutils') # mod = _get_module_class(mod, name) # # elif name == 'BVHTree': # mod = import_module_404ok('mathutils.bvhtree') # mod = _get_module_class(mod, name) # # else: # raise NotImplementedError(name) # # if assert_success: # assert mod is not None, "Failed in importing '%s'" % name # # return mod , which may include functions, classes, or code. Output only the next line.
Vector = preset_import('Vector')
Given snippet: <|code_start|> # Radius is the same pts_r_lat_lng[:, 0] = pts_r_angle1_angle2[:, 0] # Angle 1 pts_r_lat_lng[:, 1] = np.pi / 2 - pts_r_angle1_angle2[:, 1] # Angle 2 ind = pts_r_angle1_angle2[:, 2] > np.pi pts_r_lat_lng[ind, 2] = pts_r_angle1_angle2[ind, 2] - 2 * np.pi pts_r_lat_lng[np.logical_not(ind), 2] = \ pts_r_angle1_angle2[np.logical_not(ind), 2] return pts_r_lat_lng raise NotImplementedError(what2what) def sph2cart(pts_sph, convention='lat-lng'): """Inverse of :func:`cart2sph`. See :func:`cart2sph`. """ pts_sph = np.array(pts_sph) # Validate inputs is_one_point = False if pts_sph.shape == (3,): is_one_point = True pts_sph = pts_sph.reshape(1, 3) elif pts_sph.ndim != 2 or pts_sph.shape[1] != 3: raise ValueError("Shape of input must be either (3,) or (n, 3)") # Degrees? <|code_end|> , continue by predicting the next line. Consider current file imports: import numpy as np from .rot import _warn_degree from ..log import get_logger from argparse import ArgumentParser and context: # Path: third_party/xiuminglib/xiuminglib/geometry/rot.py # def _warn_degree(angles): # if (np.abs(angles) > 2 * np.pi).any(): # logger.warning(( # "Some input value falls outside [-2pi, 2pi]. You sure inputs are " # "in radians")) # # Path: third_party/xiuminglib/xiuminglib/log.py # def get_logger(level=None): # """Creates a logger for functions in the library. # # Args: # level (str, optional): Logging level. Defaults to ``logging.INFO``. # # Returns: # logging.Logger: Logger created. # """ # if level is None: # level = logging.INFO # logging.basicConfig(level=level) # logger = logging.getLogger() # return logger which might include code, classes, or functions. Output only the next line.
_warn_degree(pts_sph[:, 1:])
Given the code snippet: <|code_start|>"""Add functions in this module usually provide no setter for the lamp's 3D rotation, because one usually implicitly sets the rotation by pointing the light to an object (and specifying an up vector), by using :func:`point_light_to`. """ logger = get_logger() def point_light_to(light, target): """Points the directional light to a target. Args: light (bpy_types.Object): Light object. target (tuple(float)): Target location to which light rays point. """ <|code_end|> , generate the next line using the imports in this file: from os.path import basename from ..imprt import preset_import from ..log import get_logger import numpy as np and context (functions, classes, or occasionally code) from other files: # Path: third_party/xiuminglib/xiuminglib/imprt.py # def preset_import(name, assert_success=False): # """A unified importer for both regular and ``google3`` modules, according # to specified presets/profiles (e.g., ignoring ``ModuleNotFoundError``). # """ # if name in ('cv2', 'opencv'): # try: # # BUILD dep: # # "//third_party/py/cvx2", # from cvx2 import latest as mod # # Or # # BUILD dep: # # "//third_party/OpenCVX:cvx2", # # from google3.third_party.OpenCVX import cvx2 as cv2 # except ModuleNotFoundError: # mod = import_module_404ok('cv2') # # elif name in ('tf', 'tensorflow'): # mod = import_module_404ok('tensorflow') # # elif name == 'gfile': # # BUILD deps: # # "//pyglib:gfile", # # "//file/colossus/cns", # mod = import_module_404ok('google3.pyglib.gfile') # # elif name == 'video_api': # # BUILD deps: # # "//learning/deepmind/video/python:video_api", # mod = import_module_404ok( # 'google3.learning.deepmind.video.python.video_api') # # elif name in ('bpy', 'bmesh', 'OpenEXR', 'Imath'): # # BUILD deps: # # "//third_party/py/Imath", # # "//third_party/py/OpenEXR", # mod = import_module_404ok(name) # # elif name in ('Vector', 'Matrix', 'Quaternion'): # mod = import_module_404ok('mathutils') # mod = _get_module_class(mod, name) # # elif name == 'BVHTree': # mod = import_module_404ok('mathutils.bvhtree') # mod = _get_module_class(mod, name) # # else: # raise NotImplementedError(name) # # if assert_success: # assert mod is not None, "Failed in importing '%s'" % name # # return mod # # Path: third_party/xiuminglib/xiuminglib/log.py # def get_logger(level=None): # """Creates a logger for functions in the library. # # Args: # level (str, optional): Logging level. Defaults to ``logging.INFO``. # # Returns: # logging.Logger: Logger created. # """ # if level is None: # level = logging.INFO # logging.basicConfig(level=level) # logger = logging.getLogger() # return logger . Output only the next line.
Vector = preset_import('Vector', assert_success=True)
Using the snippet: <|code_start|>"""Add functions in this module usually provide no setter for the lamp's 3D rotation, because one usually implicitly sets the rotation by pointing the light to an object (and specifying an up vector), by using :func:`point_light_to`. """ <|code_end|> , determine the next line of code. You have imports: from os.path import basename from ..imprt import preset_import from ..log import get_logger import numpy as np and context (class names, function names, or code) available: # Path: third_party/xiuminglib/xiuminglib/imprt.py # def preset_import(name, assert_success=False): # """A unified importer for both regular and ``google3`` modules, according # to specified presets/profiles (e.g., ignoring ``ModuleNotFoundError``). # """ # if name in ('cv2', 'opencv'): # try: # # BUILD dep: # # "//third_party/py/cvx2", # from cvx2 import latest as mod # # Or # # BUILD dep: # # "//third_party/OpenCVX:cvx2", # # from google3.third_party.OpenCVX import cvx2 as cv2 # except ModuleNotFoundError: # mod = import_module_404ok('cv2') # # elif name in ('tf', 'tensorflow'): # mod = import_module_404ok('tensorflow') # # elif name == 'gfile': # # BUILD deps: # # "//pyglib:gfile", # # "//file/colossus/cns", # mod = import_module_404ok('google3.pyglib.gfile') # # elif name == 'video_api': # # BUILD deps: # # "//learning/deepmind/video/python:video_api", # mod = import_module_404ok( # 'google3.learning.deepmind.video.python.video_api') # # elif name in ('bpy', 'bmesh', 'OpenEXR', 'Imath'): # # BUILD deps: # # "//third_party/py/Imath", # # "//third_party/py/OpenEXR", # mod = import_module_404ok(name) # # elif name in ('Vector', 'Matrix', 'Quaternion'): # mod = import_module_404ok('mathutils') # mod = _get_module_class(mod, name) # # elif name == 'BVHTree': # mod = import_module_404ok('mathutils.bvhtree') # mod = _get_module_class(mod, name) # # else: # raise NotImplementedError(name) # # if assert_success: # assert mod is not None, "Failed in importing '%s'" % name # # return mod # # Path: third_party/xiuminglib/xiuminglib/log.py # def get_logger(level=None): # """Creates a logger for functions in the library. # # Args: # level (str, optional): Logging level. Defaults to ``logging.INFO``. # # Returns: # logging.Logger: Logger created. # """ # if level is None: # level = logging.INFO # logging.basicConfig(level=level) # logger = logging.getLogger() # return logger . Output only the next line.
logger = get_logger()
Based on the snippet: <|code_start|> def normalize(normal_map, norm_thres=0.5): """Normalizes the normal vector at each pixel of the normal map. Args: normal_map (numpy.ndarray): H-by-W-by-3 array of normal vectors. norm_thres (float, optional): Normalize only vectors with a norm greater than this; helpful to avoid errors at the boundary or in the background. Returns: numpy.ndarray: Normalized normal map. """ norm = np.linalg.norm(normal_map, axis=-1) valid = norm > norm_thres <|code_end|> , predict the immediate next line with the help of imports: import numpy as np from ..linalg import normalize as normalize_vec and context (classes, functions, sometimes code) from other files: # Path: third_party/xiuminglib/xiuminglib/linalg.py # def normalize(vecs, axis=0): # """Normalizes vectors. # # Args: # vecs (array_like): 1D array for a single vector, 2D array for multiple # vectors, 3D array for an "image" of vectors, etc. # axis (int, optional): Along which axis normalization is done. # # Returns: # numpy.ndarray: Normalized vector(s) of the same shape as input. # """ # vecs = np.array(vecs) # # if axis < 0: # raise ValueError("Negative index not allowed for safety") # n_dims = vecs.ndim # if axis >= n_dims: # raise ValueError(( # "Can't normalize along axis %d when you only have %d dimension(s)" # ) % (axis, n_dims)) # # norms = np.linalg.norm(vecs, axis=axis) # if (norms == 0.).any(): # raise ValueError("Found zero-norm vectors") # # broadcastable = list(vecs.shape) # broadcastable[axis] = 1 # vecs_normalized = np.divide(vecs, norms.reshape(broadcastable)) # # return vecs_normalized . Output only the next line.
normal_map[valid] = normalize_vec(normal_map[valid], axis=1)
Predict the next line after this snippet: <|code_start|> class Microfacet: """As described in: Microfacet Models for Refraction through Rough Surfaces [EGSR '07] """ def __init__(self, default_rough=0.3, lambert_only=False, f0=0.91): self.default_rough = default_rough self.lambert_only = lambert_only self.f0 = f0 def __call__(self, pts2l, pts2c, normal, albedo=None, rough=None): """All in the world coordinates. Too low roughness is OK in the forward pass, but may be numerically unstable in the backward pass pts2l: NxLx3 pts2c: Nx3 normal: Nx3 albedo: Nx3 rough: Nx1 """ if albedo is None: albedo = tf.ones((tf.shape(pts2c)[0], 3), dtype=tf.float32) if rough is None: rough = self.default_rough * tf.ones( (tf.shape(pts2c)[0], 1), dtype=tf.float32) # Normalize directions and normals <|code_end|> using the current file's imports: import numpy as np import tensorflow as tf from nerfactor.util import math as mathutil and any relevant context from other files: # Path: nerfactor/util/math.py # def log10(x): # def safe_atan2(x, y, eps=1e-6): # def grad(dz): # def safe_acos(x, eps=1e-6): # def grad(dy): # def safe_l2_normalize(x, axis=None, eps=1e-6): # def safe_cumprod(x, eps=1e-6): # def inv_transform_sample(val, weights, n_samples, det=False, eps=1e-5): . Output only the next line.
pts2l = mathutil.safe_l2_normalize(pts2l, axis=2)
Predict the next line after this snippet: <|code_start|> :class:`xiuminglib.vis.html.Table`: Table added. """ table = Table(header=header, width=width, border=border) if name is None: i = 0 while True: name = 'table%d' % i if name not in self.children: break i += 1 else: assert name not in self.children, \ "A child already took the name '%s'" % name self.children[name] = table return table def save(self, index_file): """Saves the generated HTML string to the index file. Once called, this method also calls all children's :func:`close`, so that everything (e.g., a table) is properly closed. Args: index_file (str): Path to the generated index.html. Writes - An HTML index file. """ if not index_file.endswith('.html'): index_file += '.html' <|code_end|> using the current file's imports: from os.path import dirname from ..os import makedirs and any relevant context from other files: # Path: third_party/xiuminglib/xiuminglib/os.py # def makedirs(directory, rm_if_exists=False): # """Wraps :func:`os.makedirs` to support removing the directory if it # alread exists. # # Google Colossus-compatible: it tries to use ``gfile`` first for speed. This # will fail if Blaze is not used, in which case it then falls back to using # ``fileutil`` CLI as external process calls. # # Args: # directory (str) # rm_if_exists (bool, optional): Whether to remove the directory (and # its contents) if it already exists. # """ # def exists_cns_cli(directory): # cmd = 'fileutil test -d %s' % directory # retcode, _, _ = call(cmd, quiet=True) # if retcode == 0: # return True # if retcode == 1: # return False # raise ValueError(retcode) # # def mkdir_cns_cli(directory): # cmd = 'fileutil mkdir -p %s' % directory # _call_assert_success(cmd, quiet=True) # # if _is_cnspath(directory): # # Is a CNS path # gfile = preset_import('gfile') # if gfile is None: # exists_func = exists_cns_cli # mkdir_func = mkdir_cns_cli # else: # exists_func = gfile.Exists # mkdir_func = gfile.MakeDirs # else: # # Is just a regular local path # exists_func = exists # mkdir_func = os.makedirs # # # Do the job # if exists_func(directory): # if rm_if_exists: # rm(directory) # mkdir_func(directory) # logger.info("Removed and then remade:\n\t%s", directory) # else: # mkdir_func(directory) . Output only the next line.
makedirs(dirname(index_file))
Given snippet: <|code_start|> img = img.transpose( Image.ROTATE_270).transpose(Image.FLIP_TOP_BOTTOM) elif orientation in (8, '8'): img = img.transpose(Image.ROTATE_90) else: raise ValueError(f"Invalid orientation: {orientation}") img = np.array(img) logger.debug("Image read from:\n\t%s", path) return img def write_uint(arr_uint, outpath): r"""Writes an ``uint`` array as an image to disk. Args: arr_uint (numpy.ndarray): A ``uint`` array. outpath (str): Output path. Writes - The resultant image. """ if arr_uint.ndim == 3 and arr_uint.shape[2] == 1: arr_uint = np.dstack([arr_uint] * 3) img = Image.fromarray(arr_uint) # Write to disk <|code_end|> , continue by predicting the next line. Consider current file imports: from os.path import dirname from PIL import Image, ExifTags from ..log import get_logger from ..os import makedirs, open_file import numpy as np and context: # Path: third_party/xiuminglib/xiuminglib/log.py # def get_logger(level=None): # """Creates a logger for functions in the library. # # Args: # level (str, optional): Logging level. Defaults to ``logging.INFO``. # # Returns: # logging.Logger: Logger created. # """ # if level is None: # level = logging.INFO # logging.basicConfig(level=level) # logger = logging.getLogger() # return logger # # Path: third_party/xiuminglib/xiuminglib/os.py # def makedirs(directory, rm_if_exists=False): # """Wraps :func:`os.makedirs` to support removing the directory if it # alread exists. # # Google Colossus-compatible: it tries to use ``gfile`` first for speed. This # will fail if Blaze is not used, in which case it then falls back to using # ``fileutil`` CLI as external process calls. # # Args: # directory (str) # rm_if_exists (bool, optional): Whether to remove the directory (and # its contents) if it already exists. # """ # def exists_cns_cli(directory): # cmd = 'fileutil test -d %s' % directory # retcode, _, _ = call(cmd, quiet=True) # if retcode == 0: # return True # if retcode == 1: # return False # raise ValueError(retcode) # # def mkdir_cns_cli(directory): # cmd = 'fileutil mkdir -p %s' % directory # _call_assert_success(cmd, quiet=True) # # if _is_cnspath(directory): # # Is a CNS path # gfile = preset_import('gfile') # if gfile is None: # exists_func = exists_cns_cli # mkdir_func = mkdir_cns_cli # else: # exists_func = gfile.Exists # mkdir_func = gfile.MakeDirs # else: # # Is just a regular local path # exists_func = exists # mkdir_func = os.makedirs # # # Do the job # if exists_func(directory): # if rm_if_exists: # rm(directory) # mkdir_func(directory) # logger.info("Removed and then remade:\n\t%s", directory) # else: # mkdir_func(directory) # # def open_file(path, mode): # """Opens a file. # # Supports Google Colossus if ``gfile`` can be imported. # # Args: # path (str): Path to open. # mode (str): ``'r'``, ``'rb'``, ``'w'``, or ``'wb'``. # # Returns: # File handle that can be used as a context. # """ # gfile = preset_import('gfile') # # open_func = open if gfile is None else gfile.Open # handle = open_func(path, mode) # # return handle which might include code, classes, or functions. Output only the next line.
makedirs(dirname(outpath))
Next line prediction: <|code_start|> return write_uint(*args, **kwargs) def write_arr(*args, **kwargs): """Alias for :func:`write_float`, mostly for backward compatibility. TODO: remove """ return write_float(*args, **kwargs) def read(path, auto_rotate=False): """Reads an image from disk. Args: path (str): Path to the image file. Supported formats: whatever Pillow supports. auto_rotate (bool, optional): Whether to auto-rotate the read image array according to its EXIF orientation, if any. Returns: numpy.ndarray: Loaded image. """ # EXR and HDR have dedicated loading functions if path.endswith('.exr'): raise ValueError("Use the dedicated `io.exr.read()` for .exr") elif path.endswith('.hdr'): raise ValueError("Use the dedicated `io.hdr.read()` for .hdr") # Whatever supported by Pillow <|code_end|> . Use current file imports: (from os.path import dirname from PIL import Image, ExifTags from ..log import get_logger from ..os import makedirs, open_file import numpy as np) and context including class names, function names, or small code snippets from other files: # Path: third_party/xiuminglib/xiuminglib/log.py # def get_logger(level=None): # """Creates a logger for functions in the library. # # Args: # level (str, optional): Logging level. Defaults to ``logging.INFO``. # # Returns: # logging.Logger: Logger created. # """ # if level is None: # level = logging.INFO # logging.basicConfig(level=level) # logger = logging.getLogger() # return logger # # Path: third_party/xiuminglib/xiuminglib/os.py # def makedirs(directory, rm_if_exists=False): # """Wraps :func:`os.makedirs` to support removing the directory if it # alread exists. # # Google Colossus-compatible: it tries to use ``gfile`` first for speed. This # will fail if Blaze is not used, in which case it then falls back to using # ``fileutil`` CLI as external process calls. # # Args: # directory (str) # rm_if_exists (bool, optional): Whether to remove the directory (and # its contents) if it already exists. # """ # def exists_cns_cli(directory): # cmd = 'fileutil test -d %s' % directory # retcode, _, _ = call(cmd, quiet=True) # if retcode == 0: # return True # if retcode == 1: # return False # raise ValueError(retcode) # # def mkdir_cns_cli(directory): # cmd = 'fileutil mkdir -p %s' % directory # _call_assert_success(cmd, quiet=True) # # if _is_cnspath(directory): # # Is a CNS path # gfile = preset_import('gfile') # if gfile is None: # exists_func = exists_cns_cli # mkdir_func = mkdir_cns_cli # else: # exists_func = gfile.Exists # mkdir_func = gfile.MakeDirs # else: # # Is just a regular local path # exists_func = exists # mkdir_func = os.makedirs # # # Do the job # if exists_func(directory): # if rm_if_exists: # rm(directory) # mkdir_func(directory) # logger.info("Removed and then remade:\n\t%s", directory) # else: # mkdir_func(directory) # # def open_file(path, mode): # """Opens a file. # # Supports Google Colossus if ``gfile`` can be imported. # # Args: # path (str): Path to open. # mode (str): ``'r'``, ``'rb'``, ``'w'``, or ``'wb'``. # # Returns: # File handle that can be used as a context. # """ # gfile = preset_import('gfile') # # open_func = open if gfile is None else gfile.Open # handle = open_func(path, mode) # # return handle . Output only the next line.
with open_file(path, 'rb') as h:
Using the snippet: <|code_start|> class PSNR(Base): """Peak Signal-to-Noise Ratio (PSNR) in dB (higher is better). If the inputs are RGB, they are first converted to luma (or relative luminance, if the inputs are not gamma-corrected). PSNR is computed on the luma. """ def __call__(self, im1, im2, mask=None): """ Args: im1 im2 mask (numpy.ndarray, optional): An H-by-W logical array indicating pixels that contribute to the computation. Returns: float: PSNR in dB. """ self._assert_type(im1) self._assert_type(im2) im1 = im1.astype(float) # must be cast to an unbounded type im2 = im2.astype(float) im1 = self._ensure_3d(im1) im2 = self._ensure_3d(im2) self._assert_same_shape(im1, im2) self._assert_drange(im1) self._assert_drange(im2) # To luma if im1.shape[2] == 3: <|code_end|> , determine the next line of code. You have imports: import numpy as np from .img import rgb2lum from .const import Path from .os import open_file from .imprt import preset_import from .log import get_logger from scipy import stats and context (class names, function names, or code) available: # Path: third_party/xiuminglib/xiuminglib/img.py # def rgb2lum(im): # """Converts RGB to relative luminance (if input is linear RGB) or luma # (if input is gamma-corrected RGB). # # Args: # im (numpy.ndarray): RGB array of shape ``(..., 3)``. # # Returns: # numpy.ndarray: Relative luminance or luma array. # """ # assert im.shape[-1] == 3, "Input's last dimension must hold RGB" # # lum = 0.2126 * im[..., 0] + 0.7152 * im[..., 1] + 0.0722 * im[..., 2] # # return lum # # Path: third_party/xiuminglib/xiuminglib/os.py # def open_file(path, mode): # """Opens a file. # # Supports Google Colossus if ``gfile`` can be imported. # # Args: # path (str): Path to open. # mode (str): ``'r'``, ``'rb'``, ``'w'``, or ``'wb'``. # # Returns: # File handle that can be used as a context. # """ # gfile = preset_import('gfile') # # open_func = open if gfile is None else gfile.Open # handle = open_func(path, mode) # # return handle # # Path: third_party/xiuminglib/xiuminglib/imprt.py # def preset_import(name, assert_success=False): # """A unified importer for both regular and ``google3`` modules, according # to specified presets/profiles (e.g., ignoring ``ModuleNotFoundError``). # """ # if name in ('cv2', 'opencv'): # try: # # BUILD dep: # # "//third_party/py/cvx2", # from cvx2 import latest as mod # # Or # # BUILD dep: # # "//third_party/OpenCVX:cvx2", # # from google3.third_party.OpenCVX import cvx2 as cv2 # except ModuleNotFoundError: # mod = import_module_404ok('cv2') # # elif name in ('tf', 'tensorflow'): # mod = import_module_404ok('tensorflow') # # elif name == 'gfile': # # BUILD deps: # # "//pyglib:gfile", # # "//file/colossus/cns", # mod = import_module_404ok('google3.pyglib.gfile') # # elif name == 'video_api': # # BUILD deps: # # "//learning/deepmind/video/python:video_api", # mod = import_module_404ok( # 'google3.learning.deepmind.video.python.video_api') # # elif name in ('bpy', 'bmesh', 'OpenEXR', 'Imath'): # # BUILD deps: # # "//third_party/py/Imath", # # "//third_party/py/OpenEXR", # mod = import_module_404ok(name) # # elif name in ('Vector', 'Matrix', 'Quaternion'): # mod = import_module_404ok('mathutils') # mod = _get_module_class(mod, name) # # elif name == 'BVHTree': # mod = import_module_404ok('mathutils.bvhtree') # mod = _get_module_class(mod, name) # # else: # raise NotImplementedError(name) # # if assert_success: # assert mod is not None, "Failed in importing '%s'" % name # # return mod # # Path: third_party/xiuminglib/xiuminglib/log.py # def get_logger(level=None): # """Creates a logger for functions in the library. # # Args: # level (str, optional): Logging level. Defaults to ``logging.INFO``. # # Returns: # logging.Logger: Logger created. # """ # if level is None: # level = logging.INFO # logging.basicConfig(level=level) # logger = logging.getLogger() # return logger . Output only the next line.
im1 = np.expand_dims(rgb2lum(im1), -1)
Given the following code snippet before the placeholder: <|code_start|> r"""The Learned Perceptual Image Patch Similarity (LPIPS) metric (lower is better). Project page: https://richzhang.github.io/PerceptualSimilarity/ Note: This implementation assumes the minimum value allowed is :math:`0`, so data dynamic range becomes the maximum value allowed. Attributes: dtype (numpy.dtype): Data type, with which data dynamic range is derived. drange (float): Dynamic range, i.e., difference between the maximum and minimum allowed. lpips_func (tf.function): The LPIPS network packed into a function. """ def __init__(self, dtype, weight_pb=None): """ Args: dtype (str or numpy.dtype): Data type, from which maximum allowed will be derived. weight_pb (str, optional): Path to the network weight protobuf. Defaults to the bundled ``net-lin_alex_v0.1.pb``. """ super().__init__(dtype) tf = preset_import('tf', assert_success=True) if weight_pb is None: weight_pb = Path.lpips_weights # Pack LPIPS network into a tf function graph_def = tf.compat.v1.GraphDef() <|code_end|> , predict the next line using imports from the current file: import numpy as np from .img import rgb2lum from .const import Path from .os import open_file from .imprt import preset_import from .log import get_logger from scipy import stats and context including class names, function names, and sometimes code from other files: # Path: third_party/xiuminglib/xiuminglib/img.py # def rgb2lum(im): # """Converts RGB to relative luminance (if input is linear RGB) or luma # (if input is gamma-corrected RGB). # # Args: # im (numpy.ndarray): RGB array of shape ``(..., 3)``. # # Returns: # numpy.ndarray: Relative luminance or luma array. # """ # assert im.shape[-1] == 3, "Input's last dimension must hold RGB" # # lum = 0.2126 * im[..., 0] + 0.7152 * im[..., 1] + 0.0722 * im[..., 2] # # return lum # # Path: third_party/xiuminglib/xiuminglib/os.py # def open_file(path, mode): # """Opens a file. # # Supports Google Colossus if ``gfile`` can be imported. # # Args: # path (str): Path to open. # mode (str): ``'r'``, ``'rb'``, ``'w'``, or ``'wb'``. # # Returns: # File handle that can be used as a context. # """ # gfile = preset_import('gfile') # # open_func = open if gfile is None else gfile.Open # handle = open_func(path, mode) # # return handle # # Path: third_party/xiuminglib/xiuminglib/imprt.py # def preset_import(name, assert_success=False): # """A unified importer for both regular and ``google3`` modules, according # to specified presets/profiles (e.g., ignoring ``ModuleNotFoundError``). # """ # if name in ('cv2', 'opencv'): # try: # # BUILD dep: # # "//third_party/py/cvx2", # from cvx2 import latest as mod # # Or # # BUILD dep: # # "//third_party/OpenCVX:cvx2", # # from google3.third_party.OpenCVX import cvx2 as cv2 # except ModuleNotFoundError: # mod = import_module_404ok('cv2') # # elif name in ('tf', 'tensorflow'): # mod = import_module_404ok('tensorflow') # # elif name == 'gfile': # # BUILD deps: # # "//pyglib:gfile", # # "//file/colossus/cns", # mod = import_module_404ok('google3.pyglib.gfile') # # elif name == 'video_api': # # BUILD deps: # # "//learning/deepmind/video/python:video_api", # mod = import_module_404ok( # 'google3.learning.deepmind.video.python.video_api') # # elif name in ('bpy', 'bmesh', 'OpenEXR', 'Imath'): # # BUILD deps: # # "//third_party/py/Imath", # # "//third_party/py/OpenEXR", # mod = import_module_404ok(name) # # elif name in ('Vector', 'Matrix', 'Quaternion'): # mod = import_module_404ok('mathutils') # mod = _get_module_class(mod, name) # # elif name == 'BVHTree': # mod = import_module_404ok('mathutils.bvhtree') # mod = _get_module_class(mod, name) # # else: # raise NotImplementedError(name) # # if assert_success: # assert mod is not None, "Failed in importing '%s'" % name # # return mod # # Path: third_party/xiuminglib/xiuminglib/log.py # def get_logger(level=None): # """Creates a logger for functions in the library. # # Args: # level (str, optional): Logging level. Defaults to ``logging.INFO``. # # Returns: # logging.Logger: Logger created. # """ # if level is None: # level = logging.INFO # logging.basicConfig(level=level) # logger = logging.getLogger() # return logger . Output only the next line.
with open_file(weight_pb, 'rb') as h:
Using the snippet: <|code_start|> assert mask.shape == im1.shape, ( "Mask must be of shape {input_shape}, but is of shape " "{mask_shape}" ).format(input_shape=im1.shape, mask_shape=mask.shape) # Mask guaranteed to be HxWx1 now mask = mask.astype(bool) # in case it's not logical yet se = np.square(im1[mask] - im2[mask]) mse = np.sum(se) / np.sum(mask) psnr = 10 * np.log10((self.drange ** 2) / mse) # dB return psnr class SSIM(Base): r"""The (multi-scale) Structural Similarity Index (SSIM) :math:`\in [0,1]` (higher is better). If the inputs are RGB, they are first converted to luma (or relative luminance, if the inputs are not gamma-corrected). SSIM is computed on the luma. """ def __call__(self, im1, im2, multiscale=False): """ Args: im1 im2 multiscale (bool, optional): Whether to compute MS-SSIM. Returns: float: SSIM computed (higher is better). """ <|code_end|> , determine the next line of code. You have imports: import numpy as np from .img import rgb2lum from .const import Path from .os import open_file from .imprt import preset_import from .log import get_logger from scipy import stats and context (class names, function names, or code) available: # Path: third_party/xiuminglib/xiuminglib/img.py # def rgb2lum(im): # """Converts RGB to relative luminance (if input is linear RGB) or luma # (if input is gamma-corrected RGB). # # Args: # im (numpy.ndarray): RGB array of shape ``(..., 3)``. # # Returns: # numpy.ndarray: Relative luminance or luma array. # """ # assert im.shape[-1] == 3, "Input's last dimension must hold RGB" # # lum = 0.2126 * im[..., 0] + 0.7152 * im[..., 1] + 0.0722 * im[..., 2] # # return lum # # Path: third_party/xiuminglib/xiuminglib/os.py # def open_file(path, mode): # """Opens a file. # # Supports Google Colossus if ``gfile`` can be imported. # # Args: # path (str): Path to open. # mode (str): ``'r'``, ``'rb'``, ``'w'``, or ``'wb'``. # # Returns: # File handle that can be used as a context. # """ # gfile = preset_import('gfile') # # open_func = open if gfile is None else gfile.Open # handle = open_func(path, mode) # # return handle # # Path: third_party/xiuminglib/xiuminglib/imprt.py # def preset_import(name, assert_success=False): # """A unified importer for both regular and ``google3`` modules, according # to specified presets/profiles (e.g., ignoring ``ModuleNotFoundError``). # """ # if name in ('cv2', 'opencv'): # try: # # BUILD dep: # # "//third_party/py/cvx2", # from cvx2 import latest as mod # # Or # # BUILD dep: # # "//third_party/OpenCVX:cvx2", # # from google3.third_party.OpenCVX import cvx2 as cv2 # except ModuleNotFoundError: # mod = import_module_404ok('cv2') # # elif name in ('tf', 'tensorflow'): # mod = import_module_404ok('tensorflow') # # elif name == 'gfile': # # BUILD deps: # # "//pyglib:gfile", # # "//file/colossus/cns", # mod = import_module_404ok('google3.pyglib.gfile') # # elif name == 'video_api': # # BUILD deps: # # "//learning/deepmind/video/python:video_api", # mod = import_module_404ok( # 'google3.learning.deepmind.video.python.video_api') # # elif name in ('bpy', 'bmesh', 'OpenEXR', 'Imath'): # # BUILD deps: # # "//third_party/py/Imath", # # "//third_party/py/OpenEXR", # mod = import_module_404ok(name) # # elif name in ('Vector', 'Matrix', 'Quaternion'): # mod = import_module_404ok('mathutils') # mod = _get_module_class(mod, name) # # elif name == 'BVHTree': # mod = import_module_404ok('mathutils.bvhtree') # mod = _get_module_class(mod, name) # # else: # raise NotImplementedError(name) # # if assert_success: # assert mod is not None, "Failed in importing '%s'" % name # # return mod # # Path: third_party/xiuminglib/xiuminglib/log.py # def get_logger(level=None): # """Creates a logger for functions in the library. # # Args: # level (str, optional): Logging level. Defaults to ``logging.INFO``. # # Returns: # logging.Logger: Logger created. # """ # if level is None: # level = logging.INFO # logging.basicConfig(level=level) # logger = logging.getLogger() # return logger . Output only the next line.
tf = preset_import('tf', assert_success=True)
Next line prediction: <|code_start|> logger = get_logger() def read(path): """Reads a non-multi-layer OpenEXR image from disk. Reading a multi-layer OpenEXR cannot be done with OpenCV and would require installing OpenEXR and Imath (see `cli/exr2npz.py`). Args: path (str): Path to the .exr file. Returns: numpy.ndarray: Loaded (float) array with RGB channels in order. """ <|code_end|> . Use current file imports: (from ..imprt import preset_import from ..log import get_logger) and context including class names, function names, or small code snippets from other files: # Path: third_party/xiuminglib/xiuminglib/imprt.py # def preset_import(name, assert_success=False): # """A unified importer for both regular and ``google3`` modules, according # to specified presets/profiles (e.g., ignoring ``ModuleNotFoundError``). # """ # if name in ('cv2', 'opencv'): # try: # # BUILD dep: # # "//third_party/py/cvx2", # from cvx2 import latest as mod # # Or # # BUILD dep: # # "//third_party/OpenCVX:cvx2", # # from google3.third_party.OpenCVX import cvx2 as cv2 # except ModuleNotFoundError: # mod = import_module_404ok('cv2') # # elif name in ('tf', 'tensorflow'): # mod = import_module_404ok('tensorflow') # # elif name == 'gfile': # # BUILD deps: # # "//pyglib:gfile", # # "//file/colossus/cns", # mod = import_module_404ok('google3.pyglib.gfile') # # elif name == 'video_api': # # BUILD deps: # # "//learning/deepmind/video/python:video_api", # mod = import_module_404ok( # 'google3.learning.deepmind.video.python.video_api') # # elif name in ('bpy', 'bmesh', 'OpenEXR', 'Imath'): # # BUILD deps: # # "//third_party/py/Imath", # # "//third_party/py/OpenEXR", # mod = import_module_404ok(name) # # elif name in ('Vector', 'Matrix', 'Quaternion'): # mod = import_module_404ok('mathutils') # mod = _get_module_class(mod, name) # # elif name == 'BVHTree': # mod = import_module_404ok('mathutils.bvhtree') # mod = _get_module_class(mod, name) # # else: # raise NotImplementedError(name) # # if assert_success: # assert mod is not None, "Failed in importing '%s'" % name # # return mod # # Path: third_party/xiuminglib/xiuminglib/log.py # def get_logger(level=None): # """Creates a logger for functions in the library. # # Args: # level (str, optional): Logging level. Defaults to ``logging.INFO``. # # Returns: # logging.Logger: Logger created. # """ # if level is None: # level = logging.INFO # logging.basicConfig(level=level) # logger = logging.getLogger() # return logger . Output only the next line.
cv2 = preset_import('cv2', assert_success=True)
Continue the code snippet: <|code_start|> def resize(arr, new_h=None, new_w=None, method='cv2'): """Resizes an image, with the option of maintaining the aspect ratio. Args: arr (numpy.ndarray): Image to binarize. If multiple-channel, each channel is resized independently. new_h (int, optional): Target height. If ``None``, will be calculated according to the target width, assuming the same aspect ratio. new_w (int, optional): Target width. If ``None``, will be calculated according to the target height, assuming the same aspect ratio. method (str, optional): Accepted values: ``'cv2'`` and ``'tf'``. Returns: numpy.ndarray: Resized image. """ h, w = arr.shape[:2] if new_h is not None and new_w is not None: if int(h / w * new_w) != new_h: logger.warning(( "Aspect ratio changed in resizing: original size is %s; " "new size is %s"), (h, w), (new_h, new_w)) elif new_h is None and new_w is not None: new_h = int(h / w * new_w) elif new_h is not None and new_w is None: new_w = int(w / h * new_h) else: raise ValueError("At least one of new height or width must be given") if method in ('tf', 'tensorflow'): <|code_end|> . Use current file imports: from copy import deepcopy from .imprt import preset_import from .log import get_logger from scipy.interpolate import RectBivariateSpline, interp2d from scipy.interpolate import griddata from scipy.interpolate import Rbf from scipy.ndimage.filters import minimum_filter, maximum_filter import numpy as np and context (classes, functions, or code) from other files: # Path: third_party/xiuminglib/xiuminglib/imprt.py # def preset_import(name, assert_success=False): # """A unified importer for both regular and ``google3`` modules, according # to specified presets/profiles (e.g., ignoring ``ModuleNotFoundError``). # """ # if name in ('cv2', 'opencv'): # try: # # BUILD dep: # # "//third_party/py/cvx2", # from cvx2 import latest as mod # # Or # # BUILD dep: # # "//third_party/OpenCVX:cvx2", # # from google3.third_party.OpenCVX import cvx2 as cv2 # except ModuleNotFoundError: # mod = import_module_404ok('cv2') # # elif name in ('tf', 'tensorflow'): # mod = import_module_404ok('tensorflow') # # elif name == 'gfile': # # BUILD deps: # # "//pyglib:gfile", # # "//file/colossus/cns", # mod = import_module_404ok('google3.pyglib.gfile') # # elif name == 'video_api': # # BUILD deps: # # "//learning/deepmind/video/python:video_api", # mod = import_module_404ok( # 'google3.learning.deepmind.video.python.video_api') # # elif name in ('bpy', 'bmesh', 'OpenEXR', 'Imath'): # # BUILD deps: # # "//third_party/py/Imath", # # "//third_party/py/OpenEXR", # mod = import_module_404ok(name) # # elif name in ('Vector', 'Matrix', 'Quaternion'): # mod = import_module_404ok('mathutils') # mod = _get_module_class(mod, name) # # elif name == 'BVHTree': # mod = import_module_404ok('mathutils.bvhtree') # mod = _get_module_class(mod, name) # # else: # raise NotImplementedError(name) # # if assert_success: # assert mod is not None, "Failed in importing '%s'" % name # # return mod # # Path: third_party/xiuminglib/xiuminglib/log.py # def get_logger(level=None): # """Creates a logger for functions in the library. # # Args: # level (str, optional): Logging level. Defaults to ``logging.INFO``. # # Returns: # logging.Logger: Logger created. # """ # if level is None: # level = logging.INFO # logging.basicConfig(level=level) # logger = logging.getLogger() # return logger . Output only the next line.
tf = preset_import('tensorflow', assert_success=True)
Here is a snippet: <|code_start|> def _warn_degree(angles): if (np.abs(angles) > 2 * np.pi).any(): logger.warning(( "Some input value falls outside [-2pi, 2pi]. You sure inputs are " "in radians")) def axis_angle_to_rot_mat(axis, theta): r"""Gets rotation matrix that rotates points around an arbitrary axis by any angle. Rotating around the :math:`x`/:math:`y`/:math:`z` axis are special cases of this, where you simply specify the axis to be one of those axes. Args: axis (array_like): 3-vector that specifies the end point of the rotation axis (start point is the origin). This will be normalized to be unit-length. theta (float): Angle in radians, prescribed by the right-hand rule, so a negative value means flipping the rotation axis. Returns: numpy.ndarray: :math:`3\times 3` rotation matrix, to be pre-multiplied with the vector to rotate. """ # NOTE: not tested thoroughly. Use with caution! axis = np.array(axis) <|code_end|> . Write the next line using the current file imports: import math import numpy as np from ..linalg import normalize from ..log import get_logger and context from other files: # Path: third_party/xiuminglib/xiuminglib/linalg.py # def normalize(vecs, axis=0): # """Normalizes vectors. # # Args: # vecs (array_like): 1D array for a single vector, 2D array for multiple # vectors, 3D array for an "image" of vectors, etc. # axis (int, optional): Along which axis normalization is done. # # Returns: # numpy.ndarray: Normalized vector(s) of the same shape as input. # """ # vecs = np.array(vecs) # # if axis < 0: # raise ValueError("Negative index not allowed for safety") # n_dims = vecs.ndim # if axis >= n_dims: # raise ValueError(( # "Can't normalize along axis %d when you only have %d dimension(s)" # ) % (axis, n_dims)) # # norms = np.linalg.norm(vecs, axis=axis) # if (norms == 0.).any(): # raise ValueError("Found zero-norm vectors") # # broadcastable = list(vecs.shape) # broadcastable[axis] = 1 # vecs_normalized = np.divide(vecs, norms.reshape(broadcastable)) # # return vecs_normalized # # Path: third_party/xiuminglib/xiuminglib/log.py # def get_logger(level=None): # """Creates a logger for functions in the library. # # Args: # level (str, optional): Logging level. Defaults to ``logging.INFO``. # # Returns: # logging.Logger: Logger created. # """ # if level is None: # level = logging.INFO # logging.basicConfig(level=level) # logger = logging.getLogger() # return logger , which may include functions, classes, or code. Output only the next line.
ux, uy, uz = normalize(axis)
Predict the next line after this snippet: <|code_start|> logger = get_logger() def read(path): """Reads an HDR map from disk. Args: path (str): Path to the .hdr file. Returns: numpy.ndarray: Loaded (float) HDR map with RGB channels in order. """ <|code_end|> using the current file's imports: from os.path import dirname from ..imprt import preset_import from ..os import makedirs, open_file from ..log import get_logger import numpy as np and any relevant context from other files: # Path: third_party/xiuminglib/xiuminglib/imprt.py # def preset_import(name, assert_success=False): # """A unified importer for both regular and ``google3`` modules, according # to specified presets/profiles (e.g., ignoring ``ModuleNotFoundError``). # """ # if name in ('cv2', 'opencv'): # try: # # BUILD dep: # # "//third_party/py/cvx2", # from cvx2 import latest as mod # # Or # # BUILD dep: # # "//third_party/OpenCVX:cvx2", # # from google3.third_party.OpenCVX import cvx2 as cv2 # except ModuleNotFoundError: # mod = import_module_404ok('cv2') # # elif name in ('tf', 'tensorflow'): # mod = import_module_404ok('tensorflow') # # elif name == 'gfile': # # BUILD deps: # # "//pyglib:gfile", # # "//file/colossus/cns", # mod = import_module_404ok('google3.pyglib.gfile') # # elif name == 'video_api': # # BUILD deps: # # "//learning/deepmind/video/python:video_api", # mod = import_module_404ok( # 'google3.learning.deepmind.video.python.video_api') # # elif name in ('bpy', 'bmesh', 'OpenEXR', 'Imath'): # # BUILD deps: # # "//third_party/py/Imath", # # "//third_party/py/OpenEXR", # mod = import_module_404ok(name) # # elif name in ('Vector', 'Matrix', 'Quaternion'): # mod = import_module_404ok('mathutils') # mod = _get_module_class(mod, name) # # elif name == 'BVHTree': # mod = import_module_404ok('mathutils.bvhtree') # mod = _get_module_class(mod, name) # # else: # raise NotImplementedError(name) # # if assert_success: # assert mod is not None, "Failed in importing '%s'" % name # # return mod # # Path: third_party/xiuminglib/xiuminglib/os.py # def makedirs(directory, rm_if_exists=False): # """Wraps :func:`os.makedirs` to support removing the directory if it # alread exists. # # Google Colossus-compatible: it tries to use ``gfile`` first for speed. This # will fail if Blaze is not used, in which case it then falls back to using # ``fileutil`` CLI as external process calls. # # Args: # directory (str) # rm_if_exists (bool, optional): Whether to remove the directory (and # its contents) if it already exists. # """ # def exists_cns_cli(directory): # cmd = 'fileutil test -d %s' % directory # retcode, _, _ = call(cmd, quiet=True) # if retcode == 0: # return True # if retcode == 1: # return False # raise ValueError(retcode) # # def mkdir_cns_cli(directory): # cmd = 'fileutil mkdir -p %s' % directory # _call_assert_success(cmd, quiet=True) # # if _is_cnspath(directory): # # Is a CNS path # gfile = preset_import('gfile') # if gfile is None: # exists_func = exists_cns_cli # mkdir_func = mkdir_cns_cli # else: # exists_func = gfile.Exists # mkdir_func = gfile.MakeDirs # else: # # Is just a regular local path # exists_func = exists # mkdir_func = os.makedirs # # # Do the job # if exists_func(directory): # if rm_if_exists: # rm(directory) # mkdir_func(directory) # logger.info("Removed and then remade:\n\t%s", directory) # else: # mkdir_func(directory) # # def open_file(path, mode): # """Opens a file. # # Supports Google Colossus if ``gfile`` can be imported. # # Args: # path (str): Path to open. # mode (str): ``'r'``, ``'rb'``, ``'w'``, or ``'wb'``. # # Returns: # File handle that can be used as a context. # """ # gfile = preset_import('gfile') # # open_func = open if gfile is None else gfile.Open # handle = open_func(path, mode) # # return handle # # Path: third_party/xiuminglib/xiuminglib/log.py # def get_logger(level=None): # """Creates a logger for functions in the library. # # Args: # level (str, optional): Logging level. Defaults to ``logging.INFO``. # # Returns: # logging.Logger: Logger created. # """ # if level is None: # level = logging.INFO # logging.basicConfig(level=level) # logger = logging.getLogger() # return logger . Output only the next line.
cv2 = preset_import('cv2', assert_success=True)
Given the following code snippet before the placeholder: <|code_start|> path (str): Path to the .hdr file. Returns: numpy.ndarray: Loaded (float) HDR map with RGB channels in order. """ cv2 = preset_import('cv2', assert_success=True) with open_file(path, 'rb') as h: buffer_ = np.fromstring(h.read(), np.uint8) bgr = cv2.imdecode(buffer_, cv2.IMREAD_UNCHANGED) rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB) logger.debug("HDR map read from:\n\t%s", path) return rgb def write(rgb, outpath): r"""Writes a ``float32`` array as an HDR map to disk. Args: rgb (numpy.ndarray): ``float32`` RGB array. outpath (str): Output path. Writes - The resultant HDR map. """ cv2 = preset_import('cv2', assert_success=True) assert rgb.dtype == np.float32, "Input must be float32" <|code_end|> , predict the next line using imports from the current file: from os.path import dirname from ..imprt import preset_import from ..os import makedirs, open_file from ..log import get_logger import numpy as np and context including class names, function names, and sometimes code from other files: # Path: third_party/xiuminglib/xiuminglib/imprt.py # def preset_import(name, assert_success=False): # """A unified importer for both regular and ``google3`` modules, according # to specified presets/profiles (e.g., ignoring ``ModuleNotFoundError``). # """ # if name in ('cv2', 'opencv'): # try: # # BUILD dep: # # "//third_party/py/cvx2", # from cvx2 import latest as mod # # Or # # BUILD dep: # # "//third_party/OpenCVX:cvx2", # # from google3.third_party.OpenCVX import cvx2 as cv2 # except ModuleNotFoundError: # mod = import_module_404ok('cv2') # # elif name in ('tf', 'tensorflow'): # mod = import_module_404ok('tensorflow') # # elif name == 'gfile': # # BUILD deps: # # "//pyglib:gfile", # # "//file/colossus/cns", # mod = import_module_404ok('google3.pyglib.gfile') # # elif name == 'video_api': # # BUILD deps: # # "//learning/deepmind/video/python:video_api", # mod = import_module_404ok( # 'google3.learning.deepmind.video.python.video_api') # # elif name in ('bpy', 'bmesh', 'OpenEXR', 'Imath'): # # BUILD deps: # # "//third_party/py/Imath", # # "//third_party/py/OpenEXR", # mod = import_module_404ok(name) # # elif name in ('Vector', 'Matrix', 'Quaternion'): # mod = import_module_404ok('mathutils') # mod = _get_module_class(mod, name) # # elif name == 'BVHTree': # mod = import_module_404ok('mathutils.bvhtree') # mod = _get_module_class(mod, name) # # else: # raise NotImplementedError(name) # # if assert_success: # assert mod is not None, "Failed in importing '%s'" % name # # return mod # # Path: third_party/xiuminglib/xiuminglib/os.py # def makedirs(directory, rm_if_exists=False): # """Wraps :func:`os.makedirs` to support removing the directory if it # alread exists. # # Google Colossus-compatible: it tries to use ``gfile`` first for speed. This # will fail if Blaze is not used, in which case it then falls back to using # ``fileutil`` CLI as external process calls. # # Args: # directory (str) # rm_if_exists (bool, optional): Whether to remove the directory (and # its contents) if it already exists. # """ # def exists_cns_cli(directory): # cmd = 'fileutil test -d %s' % directory # retcode, _, _ = call(cmd, quiet=True) # if retcode == 0: # return True # if retcode == 1: # return False # raise ValueError(retcode) # # def mkdir_cns_cli(directory): # cmd = 'fileutil mkdir -p %s' % directory # _call_assert_success(cmd, quiet=True) # # if _is_cnspath(directory): # # Is a CNS path # gfile = preset_import('gfile') # if gfile is None: # exists_func = exists_cns_cli # mkdir_func = mkdir_cns_cli # else: # exists_func = gfile.Exists # mkdir_func = gfile.MakeDirs # else: # # Is just a regular local path # exists_func = exists # mkdir_func = os.makedirs # # # Do the job # if exists_func(directory): # if rm_if_exists: # rm(directory) # mkdir_func(directory) # logger.info("Removed and then remade:\n\t%s", directory) # else: # mkdir_func(directory) # # def open_file(path, mode): # """Opens a file. # # Supports Google Colossus if ``gfile`` can be imported. # # Args: # path (str): Path to open. # mode (str): ``'r'``, ``'rb'``, ``'w'``, or ``'wb'``. # # Returns: # File handle that can be used as a context. # """ # gfile = preset_import('gfile') # # open_func = open if gfile is None else gfile.Open # handle = open_func(path, mode) # # return handle # # Path: third_party/xiuminglib/xiuminglib/log.py # def get_logger(level=None): # """Creates a logger for functions in the library. # # Args: # level (str, optional): Logging level. Defaults to ``logging.INFO``. # # Returns: # logging.Logger: Logger created. # """ # if level is None: # level = logging.INFO # logging.basicConfig(level=level) # logger = logging.getLogger() # return logger . Output only the next line.
makedirs(dirname(outpath))
Given the following code snippet before the placeholder: <|code_start|> logger = get_logger() def read(path): """Reads an HDR map from disk. Args: path (str): Path to the .hdr file. Returns: numpy.ndarray: Loaded (float) HDR map with RGB channels in order. """ cv2 = preset_import('cv2', assert_success=True) <|code_end|> , predict the next line using imports from the current file: from os.path import dirname from ..imprt import preset_import from ..os import makedirs, open_file from ..log import get_logger import numpy as np and context including class names, function names, and sometimes code from other files: # Path: third_party/xiuminglib/xiuminglib/imprt.py # def preset_import(name, assert_success=False): # """A unified importer for both regular and ``google3`` modules, according # to specified presets/profiles (e.g., ignoring ``ModuleNotFoundError``). # """ # if name in ('cv2', 'opencv'): # try: # # BUILD dep: # # "//third_party/py/cvx2", # from cvx2 import latest as mod # # Or # # BUILD dep: # # "//third_party/OpenCVX:cvx2", # # from google3.third_party.OpenCVX import cvx2 as cv2 # except ModuleNotFoundError: # mod = import_module_404ok('cv2') # # elif name in ('tf', 'tensorflow'): # mod = import_module_404ok('tensorflow') # # elif name == 'gfile': # # BUILD deps: # # "//pyglib:gfile", # # "//file/colossus/cns", # mod = import_module_404ok('google3.pyglib.gfile') # # elif name == 'video_api': # # BUILD deps: # # "//learning/deepmind/video/python:video_api", # mod = import_module_404ok( # 'google3.learning.deepmind.video.python.video_api') # # elif name in ('bpy', 'bmesh', 'OpenEXR', 'Imath'): # # BUILD deps: # # "//third_party/py/Imath", # # "//third_party/py/OpenEXR", # mod = import_module_404ok(name) # # elif name in ('Vector', 'Matrix', 'Quaternion'): # mod = import_module_404ok('mathutils') # mod = _get_module_class(mod, name) # # elif name == 'BVHTree': # mod = import_module_404ok('mathutils.bvhtree') # mod = _get_module_class(mod, name) # # else: # raise NotImplementedError(name) # # if assert_success: # assert mod is not None, "Failed in importing '%s'" % name # # return mod # # Path: third_party/xiuminglib/xiuminglib/os.py # def makedirs(directory, rm_if_exists=False): # """Wraps :func:`os.makedirs` to support removing the directory if it # alread exists. # # Google Colossus-compatible: it tries to use ``gfile`` first for speed. This # will fail if Blaze is not used, in which case it then falls back to using # ``fileutil`` CLI as external process calls. # # Args: # directory (str) # rm_if_exists (bool, optional): Whether to remove the directory (and # its contents) if it already exists. # """ # def exists_cns_cli(directory): # cmd = 'fileutil test -d %s' % directory # retcode, _, _ = call(cmd, quiet=True) # if retcode == 0: # return True # if retcode == 1: # return False # raise ValueError(retcode) # # def mkdir_cns_cli(directory): # cmd = 'fileutil mkdir -p %s' % directory # _call_assert_success(cmd, quiet=True) # # if _is_cnspath(directory): # # Is a CNS path # gfile = preset_import('gfile') # if gfile is None: # exists_func = exists_cns_cli # mkdir_func = mkdir_cns_cli # else: # exists_func = gfile.Exists # mkdir_func = gfile.MakeDirs # else: # # Is just a regular local path # exists_func = exists # mkdir_func = os.makedirs # # # Do the job # if exists_func(directory): # if rm_if_exists: # rm(directory) # mkdir_func(directory) # logger.info("Removed and then remade:\n\t%s", directory) # else: # mkdir_func(directory) # # def open_file(path, mode): # """Opens a file. # # Supports Google Colossus if ``gfile`` can be imported. # # Args: # path (str): Path to open. # mode (str): ``'r'``, ``'rb'``, ``'w'``, or ``'wb'``. # # Returns: # File handle that can be used as a context. # """ # gfile = preset_import('gfile') # # open_func = open if gfile is None else gfile.Open # handle = open_func(path, mode) # # return handle # # Path: third_party/xiuminglib/xiuminglib/log.py # def get_logger(level=None): # """Creates a logger for functions in the library. # # Args: # level (str, optional): Logging level. Defaults to ``logging.INFO``. # # Returns: # logging.Logger: Logger created. # """ # if level is None: # level = logging.INFO # logging.basicConfig(level=level) # logger = logging.getLogger() # return logger . Output only the next line.
with open_file(path, 'rb') as h:
Given the following code snippet before the placeholder: <|code_start|>def main(test_id): """Unit tests that can also serve as example usage.""" if test_id == 'pca': pts = np.random.rand(5, 8) # 8 points in 5D # Find all principal components n_pcs = pts.shape[0] - 1 _, pcs, projs, data_mean = pca(pts, n_pcs=n_pcs) # Reconstruct data with only the top two PC's k = 2 pts_recon = pcs[:, :k].dot(projs[:k, :]) + \ np.tile(data_mean, (projs.shape[1], 1)).T print("Recon:") print(pts_recon) elif test_id == 'dct_1d_bases': signal = np.random.randint(0, 255, 8) n = len(signal) # Transform by my matrix dct_mat = dct_1d_bases(n) assert linalg.is_identity(dct_mat.T.dot(dct_mat), eps=1e-10) coeffs = dct_mat.dot(signal) recon = dct_mat.T.dot(coeffs) print("Max. difference between original and recon.: %e" % np.abs(signal - recon).max()) # Transform by SciPy coeffs_sp = dct(signal, norm='ortho') print("Max. magnitude difference: %e" % np.abs(coeffs - coeffs_sp).max()) elif test_id == 'dct_cameraman': <|code_end|> , predict the next line using imports from the current file: import numpy as np from .imprt import preset_import from scipy.sparse import issparse from scipy.sparse.linalg import eigsh from scipy.special import sph_harm from scipy.fftpack import dct from . import linalg from os.path import join from copy import deepcopy from scipy.fftpack import dct, idct from . import const, os as xm_os from .vis.matrix import matrix_as_heatmap, matrix_as_heatmap_complex from os.path import join from . import os as xm_os from .vis.matrix import matrix_as_heatmap_complex from os.path import join from .vis.matrix import matrix_as_heatmap from argparse import ArgumentParser and context including class names, function names, and sometimes code from other files: # Path: third_party/xiuminglib/xiuminglib/imprt.py # def preset_import(name, assert_success=False): # """A unified importer for both regular and ``google3`` modules, according # to specified presets/profiles (e.g., ignoring ``ModuleNotFoundError``). # """ # if name in ('cv2', 'opencv'): # try: # # BUILD dep: # # "//third_party/py/cvx2", # from cvx2 import latest as mod # # Or # # BUILD dep: # # "//third_party/OpenCVX:cvx2", # # from google3.third_party.OpenCVX import cvx2 as cv2 # except ModuleNotFoundError: # mod = import_module_404ok('cv2') # # elif name in ('tf', 'tensorflow'): # mod = import_module_404ok('tensorflow') # # elif name == 'gfile': # # BUILD deps: # # "//pyglib:gfile", # # "//file/colossus/cns", # mod = import_module_404ok('google3.pyglib.gfile') # # elif name == 'video_api': # # BUILD deps: # # "//learning/deepmind/video/python:video_api", # mod = import_module_404ok( # 'google3.learning.deepmind.video.python.video_api') # # elif name in ('bpy', 'bmesh', 'OpenEXR', 'Imath'): # # BUILD deps: # # "//third_party/py/Imath", # # "//third_party/py/OpenEXR", # mod = import_module_404ok(name) # # elif name in ('Vector', 'Matrix', 'Quaternion'): # mod = import_module_404ok('mathutils') # mod = _get_module_class(mod, name) # # elif name == 'BVHTree': # mod = import_module_404ok('mathutils.bvhtree') # mod = _get_module_class(mod, name) # # else: # raise NotImplementedError(name) # # if assert_success: # assert mod is not None, "Failed in importing '%s'" % name # # return mod . Output only the next line.
cv2 = preset_import('cv2', assert_success=True)
Based on the snippet: <|code_start|> def cursor_to(loc): """Moves the cursor to the given 3D location. Useful for inspecting where a 3D point is in the scene, to do which you first use this function, save the scene, and open the scene in GUI. Args: loc (array_like): 3D coordinates, of length 3. """ <|code_end|> , predict the immediate next line with the help of imports: from ..imprt import preset_import and context (classes, functions, sometimes code) from other files: # Path: third_party/xiuminglib/xiuminglib/imprt.py # def preset_import(name, assert_success=False): # """A unified importer for both regular and ``google3`` modules, according # to specified presets/profiles (e.g., ignoring ``ModuleNotFoundError``). # """ # if name in ('cv2', 'opencv'): # try: # # BUILD dep: # # "//third_party/py/cvx2", # from cvx2 import latest as mod # # Or # # BUILD dep: # # "//third_party/OpenCVX:cvx2", # # from google3.third_party.OpenCVX import cvx2 as cv2 # except ModuleNotFoundError: # mod = import_module_404ok('cv2') # # elif name in ('tf', 'tensorflow'): # mod = import_module_404ok('tensorflow') # # elif name == 'gfile': # # BUILD deps: # # "//pyglib:gfile", # # "//file/colossus/cns", # mod = import_module_404ok('google3.pyglib.gfile') # # elif name == 'video_api': # # BUILD deps: # # "//learning/deepmind/video/python:video_api", # mod = import_module_404ok( # 'google3.learning.deepmind.video.python.video_api') # # elif name in ('bpy', 'bmesh', 'OpenEXR', 'Imath'): # # BUILD deps: # # "//third_party/py/Imath", # # "//third_party/py/OpenEXR", # mod = import_module_404ok(name) # # elif name in ('Vector', 'Matrix', 'Quaternion'): # mod = import_module_404ok('mathutils') # mod = _get_module_class(mod, name) # # elif name == 'BVHTree': # mod = import_module_404ok('mathutils.bvhtree') # mod = _get_module_class(mod, name) # # else: # raise NotImplementedError(name) # # if assert_success: # assert mod is not None, "Failed in importing '%s'" % name # # return mod . Output only the next line.
bpy = preset_import('bpy', assert_success=True)
Given the following code snippet before the placeholder: <|code_start|> logger = get_logger() def open_file(path, mode): """Opens a file. Supports Google Colossus if ``gfile`` can be imported. Args: path (str): Path to open. mode (str): ``'r'``, ``'rb'``, ``'w'``, or ``'wb'``. Returns: File handle that can be used as a context. """ <|code_end|> , predict the next line using imports from the current file: import os from os.path import join, exists, isdir, dirname from shutil import rmtree, copy2, copytree from glob import glob from .log import get_logger from .imprt import preset_import from .interact import format_print from collections import OrderedDict from json import dump from shlex import split from subprocess import Popen, DEVNULL from subprocess import Popen, PIPE and context including class names, function names, and sometimes code from other files: # Path: third_party/xiuminglib/xiuminglib/log.py # def get_logger(level=None): # """Creates a logger for functions in the library. # # Args: # level (str, optional): Logging level. Defaults to ``logging.INFO``. # # Returns: # logging.Logger: Logger created. # """ # if level is None: # level = logging.INFO # logging.basicConfig(level=level) # logger = logging.getLogger() # return logger # # Path: third_party/xiuminglib/xiuminglib/imprt.py # def preset_import(name, assert_success=False): # """A unified importer for both regular and ``google3`` modules, according # to specified presets/profiles (e.g., ignoring ``ModuleNotFoundError``). # """ # if name in ('cv2', 'opencv'): # try: # # BUILD dep: # # "//third_party/py/cvx2", # from cvx2 import latest as mod # # Or # # BUILD dep: # # "//third_party/OpenCVX:cvx2", # # from google3.third_party.OpenCVX import cvx2 as cv2 # except ModuleNotFoundError: # mod = import_module_404ok('cv2') # # elif name in ('tf', 'tensorflow'): # mod = import_module_404ok('tensorflow') # # elif name == 'gfile': # # BUILD deps: # # "//pyglib:gfile", # # "//file/colossus/cns", # mod = import_module_404ok('google3.pyglib.gfile') # # elif name == 'video_api': # # BUILD deps: # # "//learning/deepmind/video/python:video_api", # mod = import_module_404ok( # 'google3.learning.deepmind.video.python.video_api') # # elif name in ('bpy', 'bmesh', 'OpenEXR', 'Imath'): # # BUILD deps: # # "//third_party/py/Imath", # # "//third_party/py/OpenEXR", # mod = import_module_404ok(name) # # elif name in ('Vector', 'Matrix', 'Quaternion'): # mod = import_module_404ok('mathutils') # mod = _get_module_class(mod, name) # # elif name == 'BVHTree': # mod = import_module_404ok('mathutils.bvhtree') # mod = _get_module_class(mod, name) # # else: # raise NotImplementedError(name) # # if assert_success: # assert mod is not None, "Failed in importing '%s'" % name # # return mod # # Path: third_party/xiuminglib/xiuminglib/interact.py # def format_print(msg, fmt): # """Prints a message with format. # # Args: # msg (str): Message to print. # fmt (str): Format; try your luck with any value -- don't worry; if # it's illegal, you will be prompted with all legal values. # """ # fmt_strs = { # 'header': '\033[95m', # 'okblue': '\033[94m', # 'okgreen': '\033[92m', # 'warn': '\033[93m', # 'fail': '\033[91m', # 'bold': '\033[1m', # 'underline': '\033[4m', # } # if fmt in fmt_strs.keys(): # start_str = fmt_strs[fmt] # end_str = '\033[0m' # elif len(fmt) == 1: # start_str = "\n<" + "".join([fmt] * 78) + '\n\n' # as per PEP8 # end_str = '\n' + start_str[2:-2] + ">\n" # else: # raise ValueError( # ("Legal values for fmt: %s, plus any single character " # "(which will be repeated into the line separator), " # "but input is '%s'") % (list(fmt_strs.keys()), fmt)) # print(start_str + msg + end_str) . Output only the next line.
gfile = preset_import('gfile')
Given the code snippet: <|code_start|> """Executes a command in shell. Args: cmd (str): Command to be executed. cwd (str, optional): Directory to execute the command in. ``None`` means current directory. wait (bool, optional): Whether to block until the call finishes. quiet (bool, optional): Whether to print out the output stream (if any) and error stream (if error occured). Returns: tuple: - **retcode** (*int*) -- Command exit code. 0 means a successful call. Always ``None`` if not waiting for the command to finish. - **stdout** (*str*) -- Standard output stream. Always ``None`` if not waiting. - **stderr** (*str*) -- Standard error stream. Always ``None`` if not waiting. """ process = Popen(cmd, stdout=PIPE, stderr=PIPE, cwd=cwd, shell=True) if not wait: return None, None, None stdout, stderr = process.communicate() # waits for completion stdout, stderr = stdout.decode(), stderr.decode() if not quiet: if stdout != '': <|code_end|> , generate the next line using the imports in this file: import os from os.path import join, exists, isdir, dirname from shutil import rmtree, copy2, copytree from glob import glob from .log import get_logger from .imprt import preset_import from .interact import format_print from collections import OrderedDict from json import dump from shlex import split from subprocess import Popen, DEVNULL from subprocess import Popen, PIPE and context (functions, classes, or occasionally code) from other files: # Path: third_party/xiuminglib/xiuminglib/log.py # def get_logger(level=None): # """Creates a logger for functions in the library. # # Args: # level (str, optional): Logging level. Defaults to ``logging.INFO``. # # Returns: # logging.Logger: Logger created. # """ # if level is None: # level = logging.INFO # logging.basicConfig(level=level) # logger = logging.getLogger() # return logger # # Path: third_party/xiuminglib/xiuminglib/imprt.py # def preset_import(name, assert_success=False): # """A unified importer for both regular and ``google3`` modules, according # to specified presets/profiles (e.g., ignoring ``ModuleNotFoundError``). # """ # if name in ('cv2', 'opencv'): # try: # # BUILD dep: # # "//third_party/py/cvx2", # from cvx2 import latest as mod # # Or # # BUILD dep: # # "//third_party/OpenCVX:cvx2", # # from google3.third_party.OpenCVX import cvx2 as cv2 # except ModuleNotFoundError: # mod = import_module_404ok('cv2') # # elif name in ('tf', 'tensorflow'): # mod = import_module_404ok('tensorflow') # # elif name == 'gfile': # # BUILD deps: # # "//pyglib:gfile", # # "//file/colossus/cns", # mod = import_module_404ok('google3.pyglib.gfile') # # elif name == 'video_api': # # BUILD deps: # # "//learning/deepmind/video/python:video_api", # mod = import_module_404ok( # 'google3.learning.deepmind.video.python.video_api') # # elif name in ('bpy', 'bmesh', 'OpenEXR', 'Imath'): # # BUILD deps: # # "//third_party/py/Imath", # # "//third_party/py/OpenEXR", # mod = import_module_404ok(name) # # elif name in ('Vector', 'Matrix', 'Quaternion'): # mod = import_module_404ok('mathutils') # mod = _get_module_class(mod, name) # # elif name == 'BVHTree': # mod = import_module_404ok('mathutils.bvhtree') # mod = _get_module_class(mod, name) # # else: # raise NotImplementedError(name) # # if assert_success: # assert mod is not None, "Failed in importing '%s'" % name # # return mod # # Path: third_party/xiuminglib/xiuminglib/interact.py # def format_print(msg, fmt): # """Prints a message with format. # # Args: # msg (str): Message to print. # fmt (str): Format; try your luck with any value -- don't worry; if # it's illegal, you will be prompted with all legal values. # """ # fmt_strs = { # 'header': '\033[95m', # 'okblue': '\033[94m', # 'okgreen': '\033[92m', # 'warn': '\033[93m', # 'fail': '\033[91m', # 'bold': '\033[1m', # 'underline': '\033[4m', # } # if fmt in fmt_strs.keys(): # start_str = fmt_strs[fmt] # end_str = '\033[0m' # elif len(fmt) == 1: # start_str = "\n<" + "".join([fmt] * 78) + '\n\n' # as per PEP8 # end_str = '\n' + start_str[2:-2] + ">\n" # else: # raise ValueError( # ("Legal values for fmt: %s, plus any single character " # "(which will be repeated into the line separator), " # "but input is '%s'") % (list(fmt_strs.keys()), fmt)) # print(start_str + msg + end_str) . Output only the next line.
format_print(stdout, 'O')
Next line prediction: <|code_start|> - Input files copied from Colossus to ``$TMP/``. - Output files generated to ``$TMP/``, to be copied to Colossus. """ # $TMP set by Borg or yourself (e.g., with .bashrc) tmp_dir = environ.get('TMP', '/tmp/') def gen_local_path(cns_path): keep_last_n = 3 cns_path = _no_trailing_slash(cns_path) local_basename = '_'.join(cns_path.split('/')[-keep_last_n:]) # Prefixed by time to avoid dupes local_path = join(tmp_dir, '%f_%s' % (time(), local_basename)) # local_path guaranteed to not end with '/' return local_path def cp_404ok(src, dst): try: cp(src, dst) logger.debug("\n%s\n\tcopied to\n%s", src, dst) except FileNotFoundError: logger.warning(("Source doesn't exist yet:\n\t%s\n" "OK if this will be the output"), src) def wrapper(*arg, **kwargs): t_eps = 0.05 # seconds buffer for super fast somefunc # Fetch info. for all CNS paths arg_local, kwargs_local = [], {} cns2local = {} # Positional arguments for x in arg: <|code_end|> . Use current file imports: (from time import time, sleep from os import makedirs, environ from os.path import join, dirname, getmtime from .os import _is_cnspath, _no_trailing_slash, cp, rm from .log import get_logger import os.path) and context including class names, function names, or small code snippets from other files: # Path: third_party/xiuminglib/xiuminglib/os.py # def _is_cnspath(path): # return isinstance(path, str) and path.startswith('/cns/') # # def _no_trailing_slash(path): # if path.endswith('/'): # path = path[:-1] # assert not path.endswith('/'), "path shouldn't end with '//'" # # Guaranteed to not end with '/', so basename() or dirname() # # will give the correct results # return path # # def cp(src, dst, cns_parallel_copy=10): # """Copies files, possibly from/to the Google Colossus Filesystem. # # Args: # src (str): Source file or directory. # dst (str): Destination file or directory. # cns_parallel_copy (int): The number of files to be copied in # parallel. Only effective when copying a directory from/to # Colossus. # """ # src = _no_trailing_slash(src) # dst = _no_trailing_slash(dst) # # srcexists, srcisdir = exists_isdir(src) # if not srcexists: # raise FileNotFoundError("Source must exist") # # # When no CNS paths involved, quickly do the job and return # if not _is_cnspath(src) and not _is_cnspath(dst): # if srcisdir: # for x in os.listdir(src): # s = join(src, x) # d = join(dst, x) # if isdir(s): # copytree(s, d) # else: # copy2(s, d) # else: # copy2(src, dst) # return # # gfile = preset_import('gfile', assert_success=True) # # if gfile is None: # cmd = 'fileutil cp -f -colossus_parallel_copy ' # if srcisdir: # cmd += '-R -parallel_copy=%d %s ' % \ # (cns_parallel_copy, join(src, '*')) # else: # cmd += '%s ' % src # cmd += '%s' % dst # # Destination directory may be owned by a Ganpati group # if _is_cnspath(dst): # cmd += ' --gfs_user %s' % _select_gfs_user(dst) # _call_assert_success(cmd) # # else: # with gfile.AsUser(_select_gfs_user(dst)): # if srcisdir: # gfile.RecursivelyCopyDir(src, dst, overwrite=True) # else: # gfile.Copy(src, dst, overwrite=True) # # def rm(path): # """Removes a file or recursively a directory, with Google Colossus # compatibility. # # Args: # path (str) # """ # if not _is_cnspath(path): # # Quickly do the job and return # if exists(path): # if isdir(path): # rmtree(path) # else: # os.remove(path) # return # # # OK, a CNS path # # Use gfile if available # gfile = preset_import('gfile') # if gfile is not None: # gfile.DeleteRecursively(path) # works for file and directory # else: # # Falls back to filter CLI # cmd = 'fileutil rm -R -f %s' % path # works for file and directory # _call_assert_success(cmd, quiet=True) # # Path: third_party/xiuminglib/xiuminglib/log.py # def get_logger(level=None): # """Creates a logger for functions in the library. # # Args: # level (str, optional): Logging level. Defaults to ``logging.INFO``. # # Returns: # logging.Logger: Logger created. # """ # if level is None: # level = logging.INFO # logging.basicConfig(level=level) # logger = logging.getLogger() # return logger . Output only the next line.
if _is_cnspath(x):
Continue the code snippet: <|code_start|> re-running the function to overwrite the old result), it will be copied to local, overwritten by ``somefunc`` locally, and finally copied back to CNS. This doesn't lead to wrong behaviors, but is inefficient. This decorator doesn't depend on Blaze, as it's using the ``fileutil`` CLI, rather than ``google3.pyglib.gfile``. This is convenient in at least two cases: - You are too lazy to use Blaze, want to run tests quickly on your local machine, but need access to CNS files. - Your IO is more complex than what ``with gfile.Open(...) as h:`` can do (e.g., a Blender function importing an object from a path), in which case you have to copy the CNS file to local ("local" here could also mean a Borglet's local). This interface generally works with resolved paths (e.g., ``/path/to/file``), but not with wildcard paths (e.g., ``/path/to/???``), sicne it's hard (if possible at all) to guess what your function tries to do with such wildcard paths. Writes - Input files copied from Colossus to ``$TMP/``. - Output files generated to ``$TMP/``, to be copied to Colossus. """ # $TMP set by Borg or yourself (e.g., with .bashrc) tmp_dir = environ.get('TMP', '/tmp/') def gen_local_path(cns_path): keep_last_n = 3 <|code_end|> . Use current file imports: from time import time, sleep from os import makedirs, environ from os.path import join, dirname, getmtime from .os import _is_cnspath, _no_trailing_slash, cp, rm from .log import get_logger import os.path and context (classes, functions, or code) from other files: # Path: third_party/xiuminglib/xiuminglib/os.py # def _is_cnspath(path): # return isinstance(path, str) and path.startswith('/cns/') # # def _no_trailing_slash(path): # if path.endswith('/'): # path = path[:-1] # assert not path.endswith('/'), "path shouldn't end with '//'" # # Guaranteed to not end with '/', so basename() or dirname() # # will give the correct results # return path # # def cp(src, dst, cns_parallel_copy=10): # """Copies files, possibly from/to the Google Colossus Filesystem. # # Args: # src (str): Source file or directory. # dst (str): Destination file or directory. # cns_parallel_copy (int): The number of files to be copied in # parallel. Only effective when copying a directory from/to # Colossus. # """ # src = _no_trailing_slash(src) # dst = _no_trailing_slash(dst) # # srcexists, srcisdir = exists_isdir(src) # if not srcexists: # raise FileNotFoundError("Source must exist") # # # When no CNS paths involved, quickly do the job and return # if not _is_cnspath(src) and not _is_cnspath(dst): # if srcisdir: # for x in os.listdir(src): # s = join(src, x) # d = join(dst, x) # if isdir(s): # copytree(s, d) # else: # copy2(s, d) # else: # copy2(src, dst) # return # # gfile = preset_import('gfile', assert_success=True) # # if gfile is None: # cmd = 'fileutil cp -f -colossus_parallel_copy ' # if srcisdir: # cmd += '-R -parallel_copy=%d %s ' % \ # (cns_parallel_copy, join(src, '*')) # else: # cmd += '%s ' % src # cmd += '%s' % dst # # Destination directory may be owned by a Ganpati group # if _is_cnspath(dst): # cmd += ' --gfs_user %s' % _select_gfs_user(dst) # _call_assert_success(cmd) # # else: # with gfile.AsUser(_select_gfs_user(dst)): # if srcisdir: # gfile.RecursivelyCopyDir(src, dst, overwrite=True) # else: # gfile.Copy(src, dst, overwrite=True) # # def rm(path): # """Removes a file or recursively a directory, with Google Colossus # compatibility. # # Args: # path (str) # """ # if not _is_cnspath(path): # # Quickly do the job and return # if exists(path): # if isdir(path): # rmtree(path) # else: # os.remove(path) # return # # # OK, a CNS path # # Use gfile if available # gfile = preset_import('gfile') # if gfile is not None: # gfile.DeleteRecursively(path) # works for file and directory # else: # # Falls back to filter CLI # cmd = 'fileutil rm -R -f %s' % path # works for file and directory # _call_assert_success(cmd, quiet=True) # # Path: third_party/xiuminglib/xiuminglib/log.py # def get_logger(level=None): # """Creates a logger for functions in the library. # # Args: # level (str, optional): Logging level. Defaults to ``logging.INFO``. # # Returns: # logging.Logger: Logger created. # """ # if level is None: # level = logging.INFO # logging.basicConfig(level=level) # logger = logging.getLogger() # return logger . Output only the next line.
cns_path = _no_trailing_slash(cns_path)
Given snippet: <|code_start|> - You are too lazy to use Blaze, want to run tests quickly on your local machine, but need access to CNS files. - Your IO is more complex than what ``with gfile.Open(...) as h:`` can do (e.g., a Blender function importing an object from a path), in which case you have to copy the CNS file to local ("local" here could also mean a Borglet's local). This interface generally works with resolved paths (e.g., ``/path/to/file``), but not with wildcard paths (e.g., ``/path/to/???``), sicne it's hard (if possible at all) to guess what your function tries to do with such wildcard paths. Writes - Input files copied from Colossus to ``$TMP/``. - Output files generated to ``$TMP/``, to be copied to Colossus. """ # $TMP set by Borg or yourself (e.g., with .bashrc) tmp_dir = environ.get('TMP', '/tmp/') def gen_local_path(cns_path): keep_last_n = 3 cns_path = _no_trailing_slash(cns_path) local_basename = '_'.join(cns_path.split('/')[-keep_last_n:]) # Prefixed by time to avoid dupes local_path = join(tmp_dir, '%f_%s' % (time(), local_basename)) # local_path guaranteed to not end with '/' return local_path def cp_404ok(src, dst): try: <|code_end|> , continue by predicting the next line. Consider current file imports: from time import time, sleep from os import makedirs, environ from os.path import join, dirname, getmtime from .os import _is_cnspath, _no_trailing_slash, cp, rm from .log import get_logger import os.path and context: # Path: third_party/xiuminglib/xiuminglib/os.py # def _is_cnspath(path): # return isinstance(path, str) and path.startswith('/cns/') # # def _no_trailing_slash(path): # if path.endswith('/'): # path = path[:-1] # assert not path.endswith('/'), "path shouldn't end with '//'" # # Guaranteed to not end with '/', so basename() or dirname() # # will give the correct results # return path # # def cp(src, dst, cns_parallel_copy=10): # """Copies files, possibly from/to the Google Colossus Filesystem. # # Args: # src (str): Source file or directory. # dst (str): Destination file or directory. # cns_parallel_copy (int): The number of files to be copied in # parallel. Only effective when copying a directory from/to # Colossus. # """ # src = _no_trailing_slash(src) # dst = _no_trailing_slash(dst) # # srcexists, srcisdir = exists_isdir(src) # if not srcexists: # raise FileNotFoundError("Source must exist") # # # When no CNS paths involved, quickly do the job and return # if not _is_cnspath(src) and not _is_cnspath(dst): # if srcisdir: # for x in os.listdir(src): # s = join(src, x) # d = join(dst, x) # if isdir(s): # copytree(s, d) # else: # copy2(s, d) # else: # copy2(src, dst) # return # # gfile = preset_import('gfile', assert_success=True) # # if gfile is None: # cmd = 'fileutil cp -f -colossus_parallel_copy ' # if srcisdir: # cmd += '-R -parallel_copy=%d %s ' % \ # (cns_parallel_copy, join(src, '*')) # else: # cmd += '%s ' % src # cmd += '%s' % dst # # Destination directory may be owned by a Ganpati group # if _is_cnspath(dst): # cmd += ' --gfs_user %s' % _select_gfs_user(dst) # _call_assert_success(cmd) # # else: # with gfile.AsUser(_select_gfs_user(dst)): # if srcisdir: # gfile.RecursivelyCopyDir(src, dst, overwrite=True) # else: # gfile.Copy(src, dst, overwrite=True) # # def rm(path): # """Removes a file or recursively a directory, with Google Colossus # compatibility. # # Args: # path (str) # """ # if not _is_cnspath(path): # # Quickly do the job and return # if exists(path): # if isdir(path): # rmtree(path) # else: # os.remove(path) # return # # # OK, a CNS path # # Use gfile if available # gfile = preset_import('gfile') # if gfile is not None: # gfile.DeleteRecursively(path) # works for file and directory # else: # # Falls back to filter CLI # cmd = 'fileutil rm -R -f %s' % path # works for file and directory # _call_assert_success(cmd, quiet=True) # # Path: third_party/xiuminglib/xiuminglib/log.py # def get_logger(level=None): # """Creates a logger for functions in the library. # # Args: # level (str, optional): Logging level. Defaults to ``logging.INFO``. # # Returns: # logging.Logger: Logger created. # """ # if level is None: # level = logging.INFO # logging.basicConfig(level=level) # logger = logging.getLogger() # return logger which might include code, classes, or functions. Output only the next line.
cp(src, dst)
Here is a snippet: <|code_start|> if _is_cnspath(x): local_path = gen_local_path(x) cns2local[x] = local_path arg_local.append(local_path) else: # intact arg_local.append(x) # Keyword arguments for k, v in kwargs.items(): if _is_cnspath(v): local_path = gen_local_path(v) cns2local[v] = local_path kwargs_local[k] = local_path else: # intact kwargs_local[k] = v # For reading: copy CNS paths that exist to local # TODO: what if some of those paths are not input? Copying them to # local is a waste (but harmless) for cns_path, local_path in cns2local.items(): cp_404ok(cns_path, local_path) # Run the real function t0 = time() sleep(t_eps) results = somefunc(*arg_local, **kwargs_local) # For writing: copy local paths that are just modified and correspond # to CNS paths back to CNS for cns_path, local_path in cns2local.items(): if os.path.exists(local_path) and getmtime(local_path) > t0: cp_404ok(local_path, cns_path) # Free up the space by deleting the temporary files for _, local_path in cns2local.items(): <|code_end|> . Write the next line using the current file imports: from time import time, sleep from os import makedirs, environ from os.path import join, dirname, getmtime from .os import _is_cnspath, _no_trailing_slash, cp, rm from .log import get_logger import os.path and context from other files: # Path: third_party/xiuminglib/xiuminglib/os.py # def _is_cnspath(path): # return isinstance(path, str) and path.startswith('/cns/') # # def _no_trailing_slash(path): # if path.endswith('/'): # path = path[:-1] # assert not path.endswith('/'), "path shouldn't end with '//'" # # Guaranteed to not end with '/', so basename() or dirname() # # will give the correct results # return path # # def cp(src, dst, cns_parallel_copy=10): # """Copies files, possibly from/to the Google Colossus Filesystem. # # Args: # src (str): Source file or directory. # dst (str): Destination file or directory. # cns_parallel_copy (int): The number of files to be copied in # parallel. Only effective when copying a directory from/to # Colossus. # """ # src = _no_trailing_slash(src) # dst = _no_trailing_slash(dst) # # srcexists, srcisdir = exists_isdir(src) # if not srcexists: # raise FileNotFoundError("Source must exist") # # # When no CNS paths involved, quickly do the job and return # if not _is_cnspath(src) and not _is_cnspath(dst): # if srcisdir: # for x in os.listdir(src): # s = join(src, x) # d = join(dst, x) # if isdir(s): # copytree(s, d) # else: # copy2(s, d) # else: # copy2(src, dst) # return # # gfile = preset_import('gfile', assert_success=True) # # if gfile is None: # cmd = 'fileutil cp -f -colossus_parallel_copy ' # if srcisdir: # cmd += '-R -parallel_copy=%d %s ' % \ # (cns_parallel_copy, join(src, '*')) # else: # cmd += '%s ' % src # cmd += '%s' % dst # # Destination directory may be owned by a Ganpati group # if _is_cnspath(dst): # cmd += ' --gfs_user %s' % _select_gfs_user(dst) # _call_assert_success(cmd) # # else: # with gfile.AsUser(_select_gfs_user(dst)): # if srcisdir: # gfile.RecursivelyCopyDir(src, dst, overwrite=True) # else: # gfile.Copy(src, dst, overwrite=True) # # def rm(path): # """Removes a file or recursively a directory, with Google Colossus # compatibility. # # Args: # path (str) # """ # if not _is_cnspath(path): # # Quickly do the job and return # if exists(path): # if isdir(path): # rmtree(path) # else: # os.remove(path) # return # # # OK, a CNS path # # Use gfile if available # gfile = preset_import('gfile') # if gfile is not None: # gfile.DeleteRecursively(path) # works for file and directory # else: # # Falls back to filter CLI # cmd = 'fileutil rm -R -f %s' % path # works for file and directory # _call_assert_success(cmd, quiet=True) # # Path: third_party/xiuminglib/xiuminglib/log.py # def get_logger(level=None): # """Creates a logger for functions in the library. # # Args: # level (str, optional): Logging level. Defaults to ``logging.INFO``. # # Returns: # logging.Logger: Logger created. # """ # if level is None: # level = logging.INFO # logging.basicConfig(level=level) # logger = logging.getLogger() # return logger , which may include functions, classes, or code. Output only the next line.
rm(local_path)
Using the snippet: <|code_start|>"""Decorators that wrap a function. If the function is defined in the file where you want to use the decorator, you can decorate the function at define time: .. code-block:: python @decorator def somefunc(): return If the function is defined somewhere else, do: .. code-block:: python from numpy import mean mean = decorator(mean) """ <|code_end|> , determine the next line of code. You have imports: from time import time, sleep from os import makedirs, environ from os.path import join, dirname, getmtime from .os import _is_cnspath, _no_trailing_slash, cp, rm from .log import get_logger import os.path and context (class names, function names, or code) available: # Path: third_party/xiuminglib/xiuminglib/os.py # def _is_cnspath(path): # return isinstance(path, str) and path.startswith('/cns/') # # def _no_trailing_slash(path): # if path.endswith('/'): # path = path[:-1] # assert not path.endswith('/'), "path shouldn't end with '//'" # # Guaranteed to not end with '/', so basename() or dirname() # # will give the correct results # return path # # def cp(src, dst, cns_parallel_copy=10): # """Copies files, possibly from/to the Google Colossus Filesystem. # # Args: # src (str): Source file or directory. # dst (str): Destination file or directory. # cns_parallel_copy (int): The number of files to be copied in # parallel. Only effective when copying a directory from/to # Colossus. # """ # src = _no_trailing_slash(src) # dst = _no_trailing_slash(dst) # # srcexists, srcisdir = exists_isdir(src) # if not srcexists: # raise FileNotFoundError("Source must exist") # # # When no CNS paths involved, quickly do the job and return # if not _is_cnspath(src) and not _is_cnspath(dst): # if srcisdir: # for x in os.listdir(src): # s = join(src, x) # d = join(dst, x) # if isdir(s): # copytree(s, d) # else: # copy2(s, d) # else: # copy2(src, dst) # return # # gfile = preset_import('gfile', assert_success=True) # # if gfile is None: # cmd = 'fileutil cp -f -colossus_parallel_copy ' # if srcisdir: # cmd += '-R -parallel_copy=%d %s ' % \ # (cns_parallel_copy, join(src, '*')) # else: # cmd += '%s ' % src # cmd += '%s' % dst # # Destination directory may be owned by a Ganpati group # if _is_cnspath(dst): # cmd += ' --gfs_user %s' % _select_gfs_user(dst) # _call_assert_success(cmd) # # else: # with gfile.AsUser(_select_gfs_user(dst)): # if srcisdir: # gfile.RecursivelyCopyDir(src, dst, overwrite=True) # else: # gfile.Copy(src, dst, overwrite=True) # # def rm(path): # """Removes a file or recursively a directory, with Google Colossus # compatibility. # # Args: # path (str) # """ # if not _is_cnspath(path): # # Quickly do the job and return # if exists(path): # if isdir(path): # rmtree(path) # else: # os.remove(path) # return # # # OK, a CNS path # # Use gfile if available # gfile = preset_import('gfile') # if gfile is not None: # gfile.DeleteRecursively(path) # works for file and directory # else: # # Falls back to filter CLI # cmd = 'fileutil rm -R -f %s' % path # works for file and directory # _call_assert_success(cmd, quiet=True) # # Path: third_party/xiuminglib/xiuminglib/log.py # def get_logger(level=None): # """Creates a logger for functions in the library. # # Args: # level (str, optional): Logging level. Defaults to ``logging.INFO``. # # Returns: # logging.Logger: Logger created. # """ # if level is None: # level = logging.INFO # logging.basicConfig(level=level) # logger = logging.getLogger() # return logger . Output only the next line.
logger = get_logger()
Based on the snippet: <|code_start|> parser_lab = subparsers.add_parser(name='lab') subparsers_infrastructure = parser_infrastructure.add_subparsers(dest='infrastructure') parser_infrastructure_deploy = subparsers_infrastructure.add_parser(name='deploy') parser_infrastructure_list = subparsers_infrastructure.add_parser(name='list') subparsers_lab = parser_lab.add_subparsers(dest='lab') parser_lab_deploy = subparsers_lab.add_parser(name='deploy') parser_lab_list = subparsers_lab.add_parser(name='list') subparsers_infrastructure_deploy = parser_infrastructure_deploy.add_subparsers(dest='deploy') subparsers_lab_deploy = parser_lab_deploy.add_subparsers(dest='deploy') for module in infrastructure_list: exec('parser_{0} = subparsers_infrastructure_deploy.add_parser(name=\'{0}\', add_help=False, parents=[{0}.parser])'.format(module)) for module in lab_list: exec('parser_{0} = subparsers_lab_deploy.add_parser(name=\'{0}\', add_help=False, parents=[{0}.parser])'.format(module)) parser_all = subparsers_infrastructure_deploy.add_parser(name='all') parser_all.add_argument('--debug', action='store_const', const=True, help='Enable debug mode') parser_all.add_argument('-e', '--environment', required=True, help='CloudFormation environment to deploy to') parser_all.add_argument('-r', '--region', required=True, help='Geographic area to deploy to') parser_all.add_argument('-z', '--availability-zone', required=True, help='Isolated location to deploy to') parser_all.add_argument('-i', '--instance-type', default='m1.small', help='AWS EC2 instance type of nat and bastion instances to deploy') parser_all.add_argument('-u', '--repo-url', default='https://git@github.com/stealthly/minotaur.git', help='Public repository url where user info is stored') parser_all.add_argument('-c', '--cidr-block', default='10.0.0.0/21', type=check_subnet, help='Subnet mask of VPC network to create, must be x.x.x.x/21') self.args, self.unknown = self.parser.parse_known_args() def deploy(self): # LIST self.print_labs() # DEPLOY if 'infrastructure' in self.args.__dict__ and self.args.infrastructure == 'deploy': if self.args.deploy == 'all': <|code_end|> , predict the immediate next line with the help of imports: from argparse import ArgumentParser, ArgumentTypeError from subprocess import call from boto import config from labs.lab import enable_debug import os and context (classes, functions, sometimes code) from other files: # Path: labs/lab.py # def enable_debug(args): # if "debug" in args.__dict__ and args.debug == True: # if not config.has_section('Boto'): # config.add_section('Boto') # config.set('Boto', 'debug', '2') . Output only the next line.
enable_debug(self.args)