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_ar... | 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 = {... | 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, tararchiv... | 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:
... | 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 suspicio... | 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 = ['_templ... | 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... | 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 TestSimpl... | (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(... | 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... | 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-Rele... | 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-memb... | 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(... | 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... | 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,
... | 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)
... | 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(
... | 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,
preprocesso... | 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... | 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 te... | 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')
... | 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... | 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.de... | 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():
... | _, 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'):
... | 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'):
... | 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):
s... | 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... | 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... | 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_s... | 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_s... | 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_d... | 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=Fal... | 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 = Opti... | 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_netli... | 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 = pyud... | 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 s... | 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... | 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-Identi... | 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", "b... | 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 con... | 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")
... | 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(arg... | 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 Cha... | 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,
... | 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 fil... | 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",
... | 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)
... | 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:
... | 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=... | 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 toolchai... | 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... | 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)... | 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")
... | 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:
... | 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_cac... | 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... | 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 ... | 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_... | 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 n... | 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_... | 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.Te... | 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):
... | 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... | 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 so... | 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 signa... | 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
S... | 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 introsp... | 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 = ['python... | 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
... | 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 ... | 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 == 'n... | 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" \
... | 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[in... | _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_t... | 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... | 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
... | 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_... | 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 nam... | 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(im... | 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.
... | 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, im... | 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`, s... | 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... | 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 fi... | 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... | 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 p... | 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'... | 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... | 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_impor... | 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... | 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 ... | 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'``.
Retu... | 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.
... | 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_... | 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 ... | 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 h... | 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.item... | 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:
.. c... | 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 = subpa... | enable_debug(self.args) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.