gurudesh/pytracebugs huggingface dataset:
# Buggy code
def get_docs(self, key, default=None):
    """Gets the documentation for the environment variable."""
    vd = self._vars.get(key, None)
    if vd is None:
        if default is None:
            default = Var()
        return default
    if vd.doc_default is DefaultNotGiven:
        dval = pprint.pformat(self._vars.get(key, "<default not set>").default)
        vd = vd._replace(doc_default=dval)
    return vd


# Traceback (AttributeError)
Traceback (most recent call last):
File "c:\users\bobhy\src\xonsh\xonsh\proc.py", line 1439, in run
r = self.f(self.args, sp_stdin, sp_stdout, sp_stderr, spec, spec.stack)
File "c:\users\bobhy\src\xonsh\xonsh\proc.py", line 1232, in proxy_two
return f(args, stdin)
File "c:\users\bobhy\src\xonsh\xonsh\aliases.py", line 703, in xonfig
return xonfig_main(args)
File "c:\users\bobhy\src\xonsh\xonsh\xonfig.py", line 689, in xonfig_main
return _XONFIG_MAIN_ACTIONS[ns.action](ns)
File "c:\users\bobhy\src\xonsh\xonsh\xonfig.py", line 450, in _wizard
w = make_xonfig_wizard(
File "c:\users\bobhy\src\xonsh\xonsh\xonfig.py", line 410, in make_xonfig_wizard
wiz.YesNo(question=WIZARD_ENV_QUESTION, yes=make_env_wiz(), no=wiz.Pass()),
File "c:\users\bobhy\src\xonsh\xonsh\xonfig.py", line 343, in make_env_wiz
w = _make_flat_wiz(make_envvar, sorted(builtins.__xonsh__.env._docs.keys()))
AttributeError: 'Env' object has no attribute '_docs'

# Fixed code
def get_docs(self, key, default=None):
    """Gets the documentation for the environment variable."""
    vd = self._vars.get(key, default)
    if vd is None:
        vd = Var(default="", doc_default="")
    if vd.doc_default is DefaultNotGiven:
        dval = pprint.pformat(vd.default)
        vd = vd._replace(doc_default=dval)
    return vd
# Buggy code
def make_envvar(name):
    """Makes a StoreNonEmpty node for an environment variable."""
    env = builtins.__xonsh__.env
    vd = env.get_docs(name)
    if not vd.configurable:
        return
    default = vd.default
    if "\n" in default:
        default = "\n" + _wrap_paragraphs(default, width=69)
    curr = env.get(name)
    if is_string(curr) and is_template_string(curr):
        curr = curr.replace("{", "{{").replace("}", "}}")
    curr = pprint.pformat(curr, width=69)
    if "\n" in curr:
        curr = "\n" + curr
    msg = ENVVAR_MESSAGE.format(
        name=name,
        default=default,
        current=curr,
        docstr=_wrap_paragraphs(vd.docstr, width=69),
    )
    mnode = wiz.Message(message=msg)
    converter = env.get_converter(name)
    path = "/env/" + name
    pnode = wiz.StoreNonEmpty(
        ENVVAR_PROMPT,
        converter=converter,
        show_conversion=True,
        path=path,
        retry=True,
        store_raw=vd.store_as_str,
    )
    return mnode, pnode


# Traceback (AttributeError)
Traceback (most recent call last):
File "c:\users\bobhy\src\xonsh\xonsh\proc.py", line 1439, in run
r = self.f(self.args, sp_stdin, sp_stdout, sp_stderr, spec, spec.stack)
File "c:\users\bobhy\src\xonsh\xonsh\proc.py", line 1232, in proxy_two
return f(args, stdin)
File "c:\users\bobhy\src\xonsh\xonsh\aliases.py", line 703, in xonfig
return xonfig_main(args)
File "c:\users\bobhy\src\xonsh\xonsh\xonfig.py", line 689, in xonfig_main
return _XONFIG_MAIN_ACTIONS[ns.action](ns)
File "c:\users\bobhy\src\xonsh\xonsh\xonfig.py", line 450, in _wizard
w = make_xonfig_wizard(
File "c:\users\bobhy\src\xonsh\xonsh\xonfig.py", line 410, in make_xonfig_wizard
wiz.YesNo(question=WIZARD_ENV_QUESTION, yes=make_env_wiz(), no=wiz.Pass()),
File "c:\users\bobhy\src\xonsh\xonsh\xonfig.py", line 343, in make_env_wiz
w = _make_flat_wiz(make_envvar, sorted(builtins.__xonsh__.env._docs.keys()))
AttributeError: 'Env' object has no attribute '_docs'

# Fixed code
def make_envvar(name):
    """Makes a StoreNonEmpty node for an environment variable."""
    env = builtins.__xonsh__.env
    vd = env.get_docs(name)
    if not vd.doc_configurable:
        return
    default = vd.doc_default
    if "\n" in default:
        default = "\n" + _wrap_paragraphs(default, width=69)
    curr = env.get(name)
    if is_string(curr) and is_template_string(curr):
        curr = curr.replace("{", "{{").replace("}", "}}")
    curr = pprint.pformat(curr, width=69)
    if "\n" in curr:
        curr = "\n" + curr
    msg = ENVVAR_MESSAGE.format(
        name=name,
        default=default,
        current=curr,
        docstr=_wrap_paragraphs(vd.doc, width=69),
    )
    mnode = wiz.Message(message=msg)
    converter = env.get_converter(name)
    path = "/env/" + name
    pnode = wiz.StoreNonEmpty(
        ENVVAR_PROMPT,
        converter=converter,
        show_conversion=True,
        path=path,
        retry=True,
        store_raw=vd.doc_store_as_str,
    )
    return mnode, pnode
# Buggy code
def make_env_wiz():
    """Makes an environment variable wizard."""
    w = _make_flat_wiz(make_envvar, sorted(builtins.__xonsh__.env._docs.keys()))
    return w


# Traceback (AttributeError)
Traceback (most recent call last):
File "c:\users\bobhy\src\xonsh\xonsh\proc.py", line 1439, in run
r = self.f(self.args, sp_stdin, sp_stdout, sp_stderr, spec, spec.stack)
File "c:\users\bobhy\src\xonsh\xonsh\proc.py", line 1232, in proxy_two
return f(args, stdin)
File "c:\users\bobhy\src\xonsh\xonsh\aliases.py", line 703, in xonfig
return xonfig_main(args)
File "c:\users\bobhy\src\xonsh\xonsh\xonfig.py", line 689, in xonfig_main
return _XONFIG_MAIN_ACTIONS[ns.action](ns)
File "c:\users\bobhy\src\xonsh\xonsh\xonfig.py", line 450, in _wizard
w = make_xonfig_wizard(
File "c:\users\bobhy\src\xonsh\xonsh\xonfig.py", line 410, in make_xonfig_wizard
wiz.YesNo(question=WIZARD_ENV_QUESTION, yes=make_env_wiz(), no=wiz.Pass()),
File "c:\users\bobhy\src\xonsh\xonsh\xonfig.py", line 343, in make_env_wiz
w = _make_flat_wiz(make_envvar, sorted(builtins.__xonsh__.env._docs.keys()))
AttributeError: 'Env' object has no attribute '_docs'

# Fixed code
def make_env_wiz():
    """Makes an environment variable wizard."""
    w = _make_flat_wiz(make_envvar, sorted(builtins.__xonsh__.env.keys()))
    return w
# Buggy code
def active(self):
    """Get the name of the active virtual environment.

    You can use this as a key to get further information.

    Returns None if no environment is active.
    """
    if "VIRTUAL_ENV" not in builtins.__xonsh__.env:
        return
    env_path = builtins.__xonsh__.env["VIRTUAL_ENV"]
    if env_path.startswith(self.venvdir):
        name = env_path[len(self.venvdir) :]
        if name[0] in "/\\":
            name = name[1:]
        return name
    else:
        return env_path


# Traceback (KeyError)
Traceback (most recent call last):
File "/home/me/tmp_virtualenv/lib/python3.6/site-packages/xonsh/__amalgam__.py", line 9661, in _call
handler(**self._kwargs)
File "/home/me/tmp_virtualenv/lib/python3.6/site-packages/xontrib/autovox.py", line 106, in load_handler
check_for_new_venv(Path.cwd(), None)
File "/home/me/tmp_virtualenv/lib/python3.6/site-packages/xontrib/autovox.py", line 77, in check_for_new_venv
vox.deactivate()
File "/home/me/tmp_virtualenv/lib/python3.6/site-packages/xontrib/voxapi.py", line 385, in deactivate
events.vox_on_deactivate.fire(name=env_name, path=self[env_name].env)
File "/home/me/tmp_virtualenv/lib/python3.6/site-packages/xontrib/voxapi.py", line 297, in __getitem__
raise KeyError()
KeyError

# Fixed code
def active(self):
    """Get the name of the active virtual environment.

    You can use this as a key to get further information.

    Returns None if no environment is active.
    """
    env = builtins.__xonsh__.env
    if not env["VIRTUAL_ENV"]:
        return
    env_path = env["VIRTUAL_ENV"]
    if env_path.startswith(self.venvdir):
        name = env_path[len(self.venvdir) :]
        if name[0] in "/\\":
            name = name[1:]
        return name
    else:
        return env_path
# Buggy code
def activate(self, name):
    """
    Activate a virtual environment.

    Parameters
    ----------
    name : str
        Virtual environment name or absolute path.
    """
    env = builtins.__xonsh__.env
    ve = self[name]
    if "VIRTUAL_ENV" in env:
        self.deactivate()

    type(self).oldvars = {"PATH": list(env["PATH"])}
    env["PATH"].insert(0, ve.bin)
    env["VIRTUAL_ENV"] = ve.env
    if "PYTHONHOME" in env:
        type(self).oldvars["PYTHONHOME"] = env.pop("PYTHONHOME")

    events.vox_on_activate.fire(name=name, path=ve.env)


# Traceback (KeyError)
Traceback (most recent call last):
File "/home/me/tmp_virtualenv/lib/python3.6/site-packages/xonsh/__amalgam__.py", line 9661, in _call
handler(**self._kwargs)
File "/home/me/tmp_virtualenv/lib/python3.6/site-packages/xontrib/autovox.py", line 106, in load_handler
check_for_new_venv(Path.cwd(), None)
File "/home/me/tmp_virtualenv/lib/python3.6/site-packages/xontrib/autovox.py", line 77, in check_for_new_venv
vox.deactivate()
File "/home/me/tmp_virtualenv/lib/python3.6/site-packages/xontrib/voxapi.py", line 385, in deactivate
events.vox_on_deactivate.fire(name=env_name, path=self[env_name].env)
File "/home/me/tmp_virtualenv/lib/python3.6/site-packages/xontrib/voxapi.py", line 297, in __getitem__
raise KeyError()
KeyError

# Fixed code
def activate(self, name):
    """
    Activate a virtual environment.

    Parameters
    ----------
    name : str
        Virtual environment name or absolute path.
    """
    env = builtins.__xonsh__.env
    ve = self[name]
    if env["VIRTUAL_ENV"]:
        self.deactivate()

    type(self).oldvars = {"PATH": list(env["PATH"])}
    env["PATH"].insert(0, ve.bin)
    env["VIRTUAL_ENV"] = ve.env
    if "PYTHONHOME" in env:
        type(self).oldvars["PYTHONHOME"] = env.pop("PYTHONHOME")

    events.vox_on_activate.fire(name=name, path=ve.env)
# Buggy code
def deactivate(self):
    """
    Deactivate the active virtual environment. Returns its name.
    """
    env = builtins.__xonsh__.env
    if "VIRTUAL_ENV" not in env:
        raise NoEnvironmentActive("No environment currently active.")

    env_name = self.active()

    if hasattr(type(self), "oldvars"):
        for k, v in type(self).oldvars.items():
            env[k] = v
        del type(self).oldvars

    env.pop("VIRTUAL_ENV")

    events.vox_on_deactivate.fire(name=env_name, path=self[env_name].env)
    return env_name


# Traceback (KeyError)
Traceback (most recent call last):
File "/home/me/tmp_virtualenv/lib/python3.6/site-packages/xonsh/__amalgam__.py", line 9661, in _call
handler(**self._kwargs)
File "/home/me/tmp_virtualenv/lib/python3.6/site-packages/xontrib/autovox.py", line 106, in load_handler
check_for_new_venv(Path.cwd(), None)
File "/home/me/tmp_virtualenv/lib/python3.6/site-packages/xontrib/autovox.py", line 77, in check_for_new_venv
vox.deactivate()
File "/home/me/tmp_virtualenv/lib/python3.6/site-packages/xontrib/voxapi.py", line 385, in deactivate
events.vox_on_deactivate.fire(name=env_name, path=self[env_name].env)
File "/home/me/tmp_virtualenv/lib/python3.6/site-packages/xontrib/voxapi.py", line 297, in __getitem__
raise KeyError()
KeyError

# Fixed code
def deactivate(self):
    """
    Deactivate the active virtual environment. Returns its name.
    """
    env = builtins.__xonsh__.env
    if not env["VIRTUAL_ENV"]:
        raise NoEnvironmentActive("No environment currently active.")

    env_name = self.active()

    if hasattr(type(self), "oldvars"):
        for k, v in type(self).oldvars.items():
            env[k] = v
        del type(self).oldvars

    del env["VIRTUAL_ENV"]

    events.vox_on_deactivate.fire(name=env_name, path=self[env_name].env)
    return env_name
# Buggy code
def __init__(self, filename, buffer, queue, cond, at_exit=False, *args, **kwargs):
    """Thread for flushing history."""
    super(JsonHistoryFlusher, self).__init__(*args, **kwargs)
    self.filename = filename
    self.buffer = buffer
    self.queue = queue
    queue.append(self)
    self.cond = cond
    self.at_exit = at_exit
    if at_exit:
        self.dump()
        queue.popleft()
    else:
        self.start()


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/str/code/xonsh/xonsh/prompt/base.py", line 47, in __call__
prompt = self._format_prompt(template=template)
File "/home/str/code/xonsh/xonsh/prompt/base.py", line 55, in _format_prompt
template = template() if callable(template) else template
File "/usr/lib/python3.8/site-packages/xontrib/powerline.xsh", line 170, in prompt
r = s()
File "/usr/lib/python3.8/site-packages/xontrib/powerline.xsh", line 105, in rtns
if __xonsh__.history.rtns and __xonsh__.history.rtns[-1] != 0:
File "/home/str/code/xonsh/xonsh/history/json.py", line 273, in __getitem__
rtn = lj["cmds"][key].get(self.field, self.default)
AttributeError: 'list' object has no attribute 'get'

# Fixed code
def __init__(
    self, filename, buffer, queue, cond, at_exit=False, skip=None, *args, **kwargs
):
    """Thread for flushing history."""
    super(JsonHistoryFlusher, self).__init__(*args, **kwargs)
    self.filename = filename
    self.buffer = buffer
    self.queue = queue
    queue.append(self)
    self.cond = cond
    self.at_exit = at_exit
    self.skip = skip
    if at_exit:
        self.dump()
        queue.popleft()
    else:
        self.start()
# Buggy code
def dump(self):
    """Write the cached history to external storage."""
    opts = builtins.__xonsh__.env.get("HISTCONTROL")
    last_inp = None
    cmds = []
    for cmd in self.buffer:
        if "ignoredups" in opts and cmd["inp"] == last_inp:
            # Skipping dup cmd
            continue
        if "ignoreerr" in opts and cmd["rtn"] != 0:
            # Skipping failed cmd
            continue
        cmds.append(cmd)
        last_inp = cmd["inp"]
    with open(self.filename, "r", newline="\n") as f:
        hist = xlj.LazyJSON(f).load()
    load_hist_len = len(hist["cmds"])
    hist["cmds"].extend(cmds)
    if self.at_exit:
        hist["ts"][1] = time.time()  # apply end time
        hist["locked"] = False
    if not builtins.__xonsh__.env.get("XONSH_STORE_STDOUT", False):
        [cmd.pop("out") for cmd in hist["cmds"][load_hist_len:] if "out" in cmd]
    with open(self.filename, "w", newline="\n") as f:
        xlj.ljdump(hist, f, sort_keys=True)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/str/code/xonsh/xonsh/prompt/base.py", line 47, in __call__
prompt = self._format_prompt(template=template)
File "/home/str/code/xonsh/xonsh/prompt/base.py", line 55, in _format_prompt
template = template() if callable(template) else template
File "/usr/lib/python3.8/site-packages/xontrib/powerline.xsh", line 170, in prompt
r = s()
File "/usr/lib/python3.8/site-packages/xontrib/powerline.xsh", line 105, in rtns
if __xonsh__.history.rtns and __xonsh__.history.rtns[-1] != 0:
File "/home/str/code/xonsh/xonsh/history/json.py", line 273, in __getitem__
rtn = lj["cmds"][key].get(self.field, self.default)
AttributeError: 'list' object has no attribute 'get'

# Fixed code
def dump(self):
    """Write the cached history to external storage."""
    opts = builtins.__xonsh__.env.get("HISTCONTROL")
    last_inp = None
    cmds = []
    for cmd in self.buffer:
        if "ignoredups" in opts and cmd["inp"] == last_inp:
            # Skipping dup cmd
            if self.skip is not None:
                self.skip(1)
            continue
        if "ignoreerr" in opts and cmd["rtn"] != 0:
            # Skipping failed cmd
            if self.skip is not None:
                self.skip(1)
            continue
        cmds.append(cmd)
        last_inp = cmd["inp"]
    with open(self.filename, "r", newline="\n") as f:
        hist = xlj.LazyJSON(f).load()
    load_hist_len = len(hist["cmds"])
    hist["cmds"].extend(cmds)
    if self.at_exit:
        hist["ts"][1] = time.time()  # apply end time
        hist["locked"] = False
    if not builtins.__xonsh__.env.get("XONSH_STORE_STDOUT", False):
        [cmd.pop("out") for cmd in hist["cmds"][load_hist_len:] if "out" in cmd]
    with open(self.filename, "w", newline="\n") as f:
        xlj.ljdump(hist, f, sort_keys=True)
# Buggy code
def __len__(self):
    return self._len


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/str/code/xonsh/xonsh/prompt/base.py", line 47, in __call__
prompt = self._format_prompt(template=template)
File "/home/str/code/xonsh/xonsh/prompt/base.py", line 55, in _format_prompt
template = template() if callable(template) else template
File "/usr/lib/python3.8/site-packages/xontrib/powerline.xsh", line 170, in prompt
r = s()
File "/usr/lib/python3.8/site-packages/xontrib/powerline.xsh", line 105, in rtns
if __xonsh__.history.rtns and __xonsh__.history.rtns[-1] != 0:
File "/home/str/code/xonsh/xonsh/history/json.py", line 273, in __getitem__
rtn = lj["cmds"][key].get(self.field, self.default)
AttributeError: 'list' object has no attribute 'get'

# Fixed code
def __len__(self):
    return self._len - self._skipped
# Buggy code
def flush(self, at_exit=False):
    """Flushes the current command buffer to disk.

    Parameters
    ----------
    at_exit : bool, optional
        Whether the JsonHistoryFlusher should act as a thread in the
        background, or execute immediately and block.

    Returns
    -------
    hf : JsonHistoryFlusher or None
        The thread that was spawned to flush history
    """
    if len(self.buffer) == 0:
        return
    hf = JsonHistoryFlusher(
        self.filename, tuple(self.buffer), self._queue, self._cond, at_exit=at_exit
    )
    self.buffer.clear()
    return hf


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/str/code/xonsh/xonsh/prompt/base.py", line 47, in __call__
prompt = self._format_prompt(template=template)
File "/home/str/code/xonsh/xonsh/prompt/base.py", line 55, in _format_prompt
template = template() if callable(template) else template
File "/usr/lib/python3.8/site-packages/xontrib/powerline.xsh", line 170, in prompt
r = s()
File "/usr/lib/python3.8/site-packages/xontrib/powerline.xsh", line 105, in rtns
if __xonsh__.history.rtns and __xonsh__.history.rtns[-1] != 0:
File "/home/str/code/xonsh/xonsh/history/json.py", line 273, in __getitem__
rtn = lj["cmds"][key].get(self.field, self.default)
AttributeError: 'list' object has no attribute 'get'

# Fixed code
def flush(self, at_exit=False):
    """Flushes the current command buffer to disk.

    Parameters
    ----------
    at_exit : bool, optional
        Whether the JsonHistoryFlusher should act as a thread in the
        background, or execute immediately and block.

    Returns
    -------
    hf : JsonHistoryFlusher or None
        The thread that was spawned to flush history
    """
    if len(self.buffer) == 0:
        return

    def skip(num):
        self._skipped += num

    hf = JsonHistoryFlusher(
        self.filename,
        tuple(self.buffer),
        self._queue,
        self._cond,
        at_exit=at_exit,
        skip=skip,
    )
    self.buffer = []
    return hf
# Buggy code
def parse_proxy_return(r, stdout, stderr):
    """Proxies may return a variety of outputs. This handles them generally.

    Parameters
    ----------
    r : tuple, str, int, or None
        Return from proxy function
    stdout : file-like
        Current stdout stream
    stdout : file-like
        Current stderr stream

    Returns
    -------
    cmd_result : int
        The return code of the proxy
    """
    cmd_result = 0
    if isinstance(r, str):
        stdout.write(r)
        stdout.flush()
    elif isinstance(r, int):
        cmd_result = r
    elif isinstance(r, cabc.Sequence):
        rlen = len(r)
        if rlen > 0 and r[0] is not None:
            stdout.write(r[0])
            stdout.flush()
        if rlen > 1 and r[1] is not None:
            stderr.write(r[1])
            stderr.flush()
        if rlen > 2 and r[2] is not None:
            cmd_result = r[2]
    elif r is not None:
        # for the random object...
        stdout.write(str(r))
        stdout.flush()
    return cmd_result


# Traceback (TypeError)
ftian@ftian-desktop:~$ xonsh
ftian@ftian-desktop ~ $ def _foo(args):
.......................     return [1, 2], [3, 4]
.......................
ftian@ftian-desktop ~ $ aliases['foo'] = _foo
ftian@ftian-desktop ~ $ foo
Exception in thread Thread-138:
Traceback (most recent call last):
File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/usr/local/lib/python3.8/dist-packages/xonsh/__amalgam__.py", line 15040, in run
self.returncode = parse_proxy_return(r, sp_stdout, sp_stderr)
File "/usr/local/lib/python3.8/dist-packages/xonsh/__amalgam__.py", line 14785, in parse_proxy_return
stdout.write(r[0])
TypeError: write() argument must be str, not list

# Fixed code
def parse_proxy_return(r, stdout, stderr):
    """Proxies may return a variety of outputs. This handles them generally.

    Parameters
    ----------
    r : tuple, str, int, or None
        Return from proxy function
    stdout : file-like
        Current stdout stream
    stdout : file-like
        Current stderr stream

    Returns
    -------
    cmd_result : int
        The return code of the proxy
    """
    cmd_result = 0
    if isinstance(r, str):
        stdout.write(r)
        stdout.flush()
    elif isinstance(r, int):
        cmd_result = r
    elif isinstance(r, cabc.Sequence):
        rlen = len(r)
        if rlen > 0 and r[0] is not None:
            stdout.write(str(r[0]))
            stdout.flush()
        if rlen > 1 and r[1] is not None:
            stderr.write(str(r[1]))
            stderr.flush()
        if rlen > 2 and isinstance(r[2], int):
            cmd_result = r[2]
    elif r is not None:
        # for the random object...
        stdout.write(str(r))
        stdout.flush()
    return cmd_result
# Buggy code
def __init__(self, *args, **kwargs):
    self._d = dict(*args, **kwargs)
    self._style = self._style_name = None
    self._detyped = None


# Traceback (ValueError)
Traceback (most recent call last):
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/__amalgam__.py, line 24210, in main
return main_xonsh(args)
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/__amalgam__.py, line 24239, in main_xonsh
shell.shell.cmdloop()
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/ptk_shell/shell.py, line 197, in cmdloop
line = self.singleline(auto_suggest=auto_suggest)
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/ptk_shell/shell.py, line 101, in singleline
self.styler.style_name = env.get(XONSH_COLOR_STYLE)
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/__amalgam__.py, line 17732, in styler
self._styler = XonshStyle(env.get(XONSH_COLOR_STYLE))
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/pyghooks.py, line 345, in __init__
self.style_name = style_name
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/pyghooks.py, line 384, in style_name
color_token = color_token_by_name(xonsh_color, self.styles)
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/pyghooks.py, line 223, in color_token_by_name
pc = color_name_to_pygments_code(xc[0], styles)
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/pyghooks.py, line 143, in color_name_to_pygments_code
if token in styles:
File /usr/lib64/python3.7/collections/__init__.py, line 931, in __contains__
return any(key in m for m in self.maps)
File /usr/lib64/python3.7/collections/__init__.py, line 931, in <genexpr>
return any(key in m for m in self.maps)
File /usr/lib64/python3.7/_collections_abc.py, line 666, in __contains__
self[key]
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/pyghooks.py, line 312, in __getitem__
value = code_by_name(name, self.styles)
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/pyghooks.py, line 205, in code_by_name
code = color_name_to_pygments_code(fg, styles)
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/pyghooks.py, line 147, in color_name_to_pygments_code
raise ValueError(!r is not a color!.format(name))
ValueError: 'TARGET' is not a color!
Xonsh encountered an issue during launch
Failback to /bin/sh

# Fixed code
def __init__(self, ini_dict: dict = None):
    self._style = self._style_name = None
    self._detyped = None
    self._d = dict()
    self._targets = set()
    if ini_dict:
        for key, value in ini_dict.items():
            self[key] = value  # in case init includes ln=target
# Buggy code
def __setitem__(self, key, value):
    self._detyped = None
    old_value = self._d.get(key, None)
    self._d[key] = value
    if old_value != value:
        events.on_lscolors_change.fire(key=key, oldvalue=old_value, newvalue=value)


# Traceback (ValueError)
Traceback (most recent call last):
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/__amalgam__.py, line 24210, in main
return main_xonsh(args)
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/__amalgam__.py, line 24239, in main_xonsh
shell.shell.cmdloop()
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/ptk_shell/shell.py, line 197, in cmdloop
line = self.singleline(auto_suggest=auto_suggest)
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/ptk_shell/shell.py, line 101, in singleline
self.styler.style_name = env.get(XONSH_COLOR_STYLE)
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/__amalgam__.py, line 17732, in styler
self._styler = XonshStyle(env.get(XONSH_COLOR_STYLE))
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/pyghooks.py, line 345, in __init__
self.style_name = style_name
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/pyghooks.py, line 384, in style_name
color_token = color_token_by_name(xonsh_color, self.styles)
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/pyghooks.py, line 223, in color_token_by_name
pc = color_name_to_pygments_code(xc[0], styles)
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/pyghooks.py, line 143, in color_name_to_pygments_code
if token in styles:
File /usr/lib64/python3.7/collections/__init__.py, line 931, in __contains__
return any(key in m for m in self.maps)
File /usr/lib64/python3.7/collections/__init__.py, line 931, in <genexpr>
return any(key in m for m in self.maps)
File /usr/lib64/python3.7/_collections_abc.py, line 666, in __contains__
self[key]
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/pyghooks.py, line 312, in __getitem__
value = code_by_name(name, self.styles)
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/pyghooks.py, line 205, in code_by_name
code = color_name_to_pygments_code(fg, styles)
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/pyghooks.py, line 147, in color_name_to_pygments_code
raise ValueError(!r is not a color!.format(name))
ValueError: 'TARGET' is not a color!
Xonsh encountered an issue during launch
Failback to /bin/sh

# Fixed code
def __setitem__(self, key, value):
    self._detyped = None
    old_value = self._d.get(key, None)
    self._targets.discard(key)
    if value == LsColors.target_value:
        value = LsColors.target_color
        self._targets.add(key)
    self._d[key] = value
    if (
        old_value != value
    ):  # bug won't fire if new value is 'target' and old value happened to be no color.
        events.on_lscolors_change.fire(key=key, oldvalue=old_value, newvalue=value)
# Buggy code
def __delitem__(self, key):
    self._detyped = None
    old_value = self._d.get(key, None)
    del self._d[key]
    events.on_lscolors_change.fire(key=key, oldvalue=old_value, newvalue=None)


# Traceback (ValueError)
Traceback (most recent call last):
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/__amalgam__.py, line 24210, in main
return main_xonsh(args)
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/__amalgam__.py, line 24239, in main_xonsh
shell.shell.cmdloop()
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/ptk_shell/shell.py, line 197, in cmdloop
line = self.singleline(auto_suggest=auto_suggest)
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/ptk_shell/shell.py, line 101, in singleline
self.styler.style_name = env.get(XONSH_COLOR_STYLE)
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/__amalgam__.py, line 17732, in styler
self._styler = XonshStyle(env.get(XONSH_COLOR_STYLE))
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/pyghooks.py, line 345, in __init__
self.style_name = style_name
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/pyghooks.py, line 384, in style_name
color_token = color_token_by_name(xonsh_color, self.styles)
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/pyghooks.py, line 223, in color_token_by_name
pc = color_name_to_pygments_code(xc[0], styles)
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/pyghooks.py, line 143, in color_name_to_pygments_code
if token in styles:
File /usr/lib64/python3.7/collections/__init__.py, line 931, in __contains__
return any(key in m for m in self.maps)
File /usr/lib64/python3.7/collections/__init__.py, line 931, in <genexpr>
return any(key in m for m in self.maps)
File /usr/lib64/python3.7/_collections_abc.py, line 666, in __contains__
self[key]
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/pyghooks.py, line 312, in __getitem__
value = code_by_name(name, self.styles)
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/pyghooks.py, line 205, in code_by_name
code = color_name_to_pygments_code(fg, styles)
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/pyghooks.py, line 147, in color_name_to_pygments_code
raise ValueError(!r is not a color!.format(name))
ValueError: 'TARGET' is not a color!
Xonsh encountered an issue during launch
Failback to /bin/sh

# Fixed code
def __delitem__(self, key):
    self._detyped = None
    old_value = self._d.get(key, None)
    self._targets.discard(key)
    del self._d[key]
    events.on_lscolors_change.fire(key=key, oldvalue=old_value, newvalue=None)
# Buggy code
def __repr__(self):
    return "{0}.{1}(...)".format(
        self.__class__.__module__, self.__class__.__name__, self._d
    )


# Traceback (ValueError)
Traceback (most recent call last):
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/__amalgam__.py, line 24210, in main
return main_xonsh(args)
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/__amalgam__.py, line 24239, in main_xonsh
shell.shell.cmdloop()
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/ptk_shell/shell.py, line 197, in cmdloop
line = self.singleline(auto_suggest=auto_suggest)
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/ptk_shell/shell.py, line 101, in singleline
self.styler.style_name = env.get(XONSH_COLOR_STYLE)
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/__amalgam__.py, line 17732, in styler
self._styler = XonshStyle(env.get(XONSH_COLOR_STYLE))
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/pyghooks.py, line 345, in __init__
self.style_name = style_name
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/pyghooks.py, line 384, in style_name
color_token = color_token_by_name(xonsh_color, self.styles)
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/pyghooks.py, line 223, in color_token_by_name
pc = color_name_to_pygments_code(xc[0], styles)
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/pyghooks.py, line 143, in color_name_to_pygments_code
if token in styles:
File /usr/lib64/python3.7/collections/__init__.py, line 931, in __contains__
return any(key in m for m in self.maps)
File /usr/lib64/python3.7/collections/__init__.py, line 931, in <genexpr>
return any(key in m for m in self.maps)
File /usr/lib64/python3.7/_collections_abc.py, line 666, in __contains__
self[key]
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/pyghooks.py, line 312, in __getitem__
value = code_by_name(name, self.styles)
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/pyghooks.py, line 205, in code_by_name
code = color_name_to_pygments_code(fg, styles)
File /home/tim/.xonsh/lib64/python3.7/site-packages/xonsh/pyghooks.py, line 147, in color_name_to_pygments_code
raise ValueError(!r is not a color!.format(name))
ValueError: 'TARGET' is not a color!
Xonsh encountered an issue during launch
Failback to /bin/sh

# Fixed code
def __repr__(self):
    return "{0}.{1}(...)".format(  # noqa F523
        self.__class__.__module__, self.__class__.__name__, self._d
    )
# Buggy code
def p_factor_unary(self, p):
    """factor : PLUS factor
    | MINUS factor
    | TILDE factor
    """
    op = self._factor_ops[p[1]]()
    p[0] = ast.UnaryOp(op=op, operand=p[2], lineno=self.lineno, col_offset=self.col)


# Traceback (NameError)
xonsh: To log full traceback to a file set: $XONSH_TRACEBACK_LOGFILE = <filename>
Traceback (most recent call last):
File "/nix/store/y22pwfk39i9r22ga10c3ifbp345gdl0p-xonsh-0.9.17/lib/python3.7/site-packages/xonsh/base_shell.py", line 362, in default
run_compiled_code(code, self.ctx, None, "single")
File "/nix/store/y22pwfk39i9r22ga10c3ifbp345gdl0p-xonsh-0.9.17/lib/python3.7/site-packages/xonsh/codecache.py", line 67, in run_compiled_code
func(code, glb, loc)
File "<xonsh-code>", line 1, in <module>
NameError: name 'nix' is not defined

# Fixed code
def p_factor_unary(self, p):
    """factor : plus_tok factor
    | minus_tok factor
    | tilde_tok factor
    """
    p1 = p[1]
    op = self._factor_ops[p1.value]()
    p[0] = ast.UnaryOp(op=op, operand=p[2], lineno=self.lineno, col_offset=p1.lexpos)
# Buggy code
def __init__(self, wait_for_shell=True, size=None, *args, **kwargs):
    """Thread responsible for garbage collecting old history.

    May wait for shell (and for xonshrc to have been loaded) to start work.
    """
    super().__init__(*args, **kwargs)
    self.daemon = True
    self.size = size
    self.wait_for_shell = wait_for_shell
    self.start()
    self.gc_units_to_rmfiles = {
        "commands": _xhj_gc_commands_to_rmfiles,
        "files": _xhj_gc_files_to_rmfiles,
        "s": _xhj_gc_seconds_to_rmfiles,
        "b": _xhj_gc_bytes_to_rmfiles,
    }


# Traceback (AttributeError)
┌─18-12:44[confus@confusion6 ~]
└$ xonfig info
+------------------+----------------------+
| xonsh            | 0.9.3                |
| Git SHA          | 679d4e06             |
| Commit Date      | May 14 17:45:24 2019 |
| Python           | 3.6.7                |
| PLY              | 3.11                 |
| have readline    | True                 |
| prompt toolkit   | 2.0.9                |
| shell type       | prompt_toolkit2      |
| pygments         | 2.4.0                |
| on posix         | True                 |
| on linux         | True                 |
| distro           | ubuntu               |
| on darwin        | False                |
| on windows       | False                |
| on cygwin        | False                |
| on msys2         | False                |
| is superuser     | False                |
| default encoding | utf-8                |
| xonsh encoding   | utf-8                |
| encoding errors  | surrogateescape      |
+------------------+----------------------+

┌─18-12:46[confus@confusion6 ~]
└$ history gc
Exception in thread Thread-451:
Traceback (most recent call last):
File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/home/jan/.local/lib/python3.6/site-packages/xonsh/history/__amalgam__.py", line 352, in run
rmfiles_fn = self.gc_units_to_rmfiles.get(units)
AttributeError: 'JsonHistoryGC' object has no attribute 'gc_units_to_rmfiles'

# Fixed code
def __init__(self, wait_for_shell=True, size=None, *args, **kwargs):
    """Thread responsible for garbage collecting old history.

    May wait for shell (and for xonshrc to have been loaded) to start work.
    """
    super().__init__(*args, **kwargs)
    self.daemon = True
    self.size = size
    self.wait_for_shell = wait_for_shell
    self.gc_units_to_rmfiles = {
        "commands": _xhj_gc_commands_to_rmfiles,
        "files": _xhj_gc_files_to_rmfiles,
        "s": _xhj_gc_seconds_to_rmfiles,
        "b": _xhj_gc_bytes_to_rmfiles,
    }
    self.start()
# Buggy code
def complete_base(prefix, line, start, end, ctx):
    """If the line is empty, complete based on valid commands, python names,
    and paths.  If we are completing the first argument, complete based on
    valid commands and python names.
    """
    if line.strip() == "":
        out = complete_python(prefix, line, start, end, ctx) | complete_command(
            prefix, line, start, end, ctx
        )
        paths = complete_path(prefix, line, start, end, ctx, False)
        return (out | paths[0]), paths[1]
    elif prefix == line:
        python_comps = complete_python(prefix, line, start, end, ctx)
        if isinstance(python_comps, cabc.Sequence):
            return (
                python_comps[0] | complete_command(prefix, line, start, end, ctx),
                python_comps[1],
            )
        else:
            return python_comps | complete_command(prefix, line, start, end, ctx)
    return set()


# Traceback (TypeError)
➤ ls &amp;&amp;Exception in thread Thread-35:
Traceback (most recent call last):
File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/usr/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "/usr/lib/python3.6/site-packages/prompt_toolkit/interface.py", line 860, in run
completions = list(buffer.completer.get_completions(document, complete_event))
File "/usr/lib/python3.6/site-packages/xonsh/ptk/completer.py", line 49, in get_completions
self.ctx)
File "/usr/lib/python3.6/site-packages/xonsh/__amalgam__.py", line 124, in complete
out = func(prefix, line, begidx, endidx, ctx)
File "/usr/lib/python3.6/site-packages/xonsh/completers/__amalgam__.py", line 831, in complete_skipper
ctx)
File "/usr/lib/python3.6/site-packages/xonsh/__amalgam__.py", line 124, in complete
out = func(prefix, line, begidx, endidx, ctx)
File "/usr/lib/python3.6/site-packages/xonsh/completers/__amalgam__.py", line 1427, in complete_base
complete_command(prefix, line, start, end, ctx))
TypeError: unsupported operand type(s) for |: 'tuple' and 'set'

# Fixed code
def complete_base(prefix, line, start, end, ctx):
    """If the line is empty, complete based on valid commands, python names,
    and paths.  If we are completing the first argument, complete based on
    valid commands and python names.
    """
    # get and unpack python completions
    python_comps = complete_python(prefix, line, start, end, ctx)
    if isinstance(python_comps, cabc.Sequence):
        python_comps, python_comps_len = python_comps
    else:
        python_comps_len = None
    # add command completions
    out = python_comps | complete_command(prefix, line, start, end, ctx)
    # add paths, if needed
    if line.strip() == "":
        paths = complete_path(prefix, line, start, end, ctx, False)
        return (out | paths[0]), paths[1]
    elif prefix == line:
        if python_comps_len is None:
            return out
        else:
            return out, python_comps_len
    return set()
# Buggy code
def rgb_to_256(rgb):
    """Find the closest ANSI 256 approximation to the given RGB value.

        >>> rgb2short('123456')
        ('23', '005f5f')
        >>> rgb2short('ffffff')
        ('231', 'ffffff')
        >>> rgb2short('0DADD6') # vimeo logo
        ('38', '00afd7')

    Parameters
    ----------
    rgb : Hex code representing an RGB value, eg, 'abcdef'

    Returns
    -------
    String between 0 and 255, compatible with xterm.
    """
    rgb = rgb.lstrip("#")
    if len(rgb) == 0:
        return "0", "000000"
    incs = (0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF)
    # Break 6-char RGB code into 3 integer vals.
    parts = rgb_to_ints(rgb)
    res = []
    for part in parts:
        i = 0
        while i < len(incs) - 1:
            s, b = incs[i], incs[i + 1]  # smaller, bigger
            if s <= part <= b:
                s1 = abs(s - part)
                b1 = abs(b - part)
                if s1 < b1:
                    closest = s
                else:
                    closest = b
                res.append(closest)
                break
            i += 1
    res = "".join([("%02.x" % i) for i in res])
    equiv = RGB_TO_SHORT[res]
    return equiv, res


# Traceback (NameError)
$ rm -f a &amp;&amp; make &amp;&amp; ./c
xonsh: To log full traceback to a file set: $XONSH_TRACEBACK_LOGFILE = <filename>
Traceback (most recent call last):
File "/home/niklas/python35env/lib/python3.5/site-packages/xonsh/__amalgam__.py", line 15472, in default
run_compiled_code(code, self.ctx, None, 'single')
File "/home/niklas/python35env/lib/python3.5/site-packages/xonsh/__amalgam__.py", line 3634, in run_compiled_code
func(code, glb, loc)
File "/home/niklas/src/xontrib-fzf-widgets/xontrib/fzf-widgets.xsh", line 1, in <module>
import os
NameError: name 'make' is not defined

# Fixed code
def rgb_to_256(rgb):
    """Find the closest ANSI 256 approximation to the given RGB value.

        >>> rgb2short('123456')
        ('23', '005f5f')
        >>> rgb2short('ffffff')
        ('231', 'ffffff')
        >>> rgb2short('0DADD6') # vimeo logo
        ('38', '00afd7')

    Parameters
    ----------
    rgb : Hex code representing an RGB value, eg, 'abcdef'

    Returns
    -------
    String between 0 and 255, compatible with xterm.
    """
    rgb = rgb.lstrip("#")
    if len(rgb) == 0:
        return "0", "000000"
    incs = (0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF)
    # Break 6-char RGB code into 3 integer vals.
    parts = rgb_to_ints(rgb)
    res = []
    for part in parts:
        i = 0
        while i < len(incs) - 1:
            s, b = incs[i], incs[i + 1]  # smaller, bigger
            if s <= part <= b:
                s1 = abs(s - part)
                b1 = abs(b - part)
                if s1 < b1:
                    closest = s
                else:
                    closest = b
                res.append(closest)
                break
            i += 1
    res = "".join([("%02.x" % i) for i in res])
    equiv = RGB_TO_SHORT[res]
    return equiv, res
# Buggy code
def ansicolors_to_ptk1_names(stylemap):
    """Converts ansicolor names in a stylemap to old PTK1 color names"""
    modified_stylemap = {}
    for token, style_str in stylemap.items():
        for color, ptk1_color in ANSICOLOR_NAMES_MAP.items():
            if ptk1_color not in style_str:
                style_str = style_str.replace(color, ptk1_color)
        modified_stylemap[token] = style_str
    return modified_stylemap


# Traceback (ValueError)
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/xonsh/__amalgam__.py", line 21008, in main
return main_xonsh(args)
File "/usr/local/lib/python3.5/dist-packages/xonsh/__amalgam__.py", line 21034, in main_xonsh
shell.shell.cmdloop()
File "/usr/local/lib/python3.5/dist-packages/xonsh/ptk/shell.py", line 168, in cmdloop
line = self.singleline(auto_suggest=auto_suggest)
File "/usr/local/lib/python3.5/dist-packages/xonsh/ptk/shell.py", line 133, in singleline
prompt_args['style'] = style_from_dict(DEFAULT_STYLE_DICT)
File "/usr/local/lib/python3.5/dist-packages/prompt_toolkit/styles/from_dict.py", line 122, in style_from_dict
attrs = attrs._replace(bgcolor=_colorformat(part[3:]))
File "/usr/local/lib/python3.5/dist-packages/prompt_toolkit/styles/from_dict.py", line 39, in _colorformat
raise ValueError('Wrong color format %r' % text)
ValueError: Wrong color format '##ansidarkblue'
Xonsh encountered an issue during launch
Failback to /bin/sh

# Fixed code
def ansicolors_to_ptk1_names(stylemap):
    """Converts ansicolor names in a stylemap to old PTK1 color names"""
    modified_stylemap = {}
    for token, style_str in stylemap.items():
        for color, ptk1_color in ANSICOLOR_NAMES_MAP.items():
            if "#" + color not in style_str:
                style_str = style_str.replace(color, ptk1_color)
        modified_stylemap[token] = style_str
    return modified_stylemap
# Buggy code
def all_items(self, **kwargs):
    """
    Returns all history as found in XONSH_DATA_DIR.

    yield format: {'inp': cmd, 'rtn': 0, ...}
    """
    while self.gc and self.gc.is_alive():
        time.sleep(0.011)  # gc sleeps for 0.01 secs, sleep a beat longer
    for f in _xhj_get_history_files():
        try:
            json_file = xlj.LazyJSON(f, reopen=False)
        except ValueError:
            # Invalid json file
            continue
        commands = json_file.load()["cmds"]
        for c in commands:
            yield {"inp": c["inp"].rstrip(), "ts": c["ts"][0]}
    # all items should also include session items
    yield from self.items()


# Traceback (json.decoder.JSONDecodeError)
Traceback (most recent call last):
File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
File "/usr/local/lib/python3.5/dist-packages/xonsh/ptk/history.py", line 54, in run
for cmd in hist.all_items():
File "/usr/local/lib/python3.5/dist-packages/xonsh/history/__amalgam__.py", line 618, in all_items
commands = json_file.load()['cmds']
File "/usr/local/lib/python3.5/dist-packages/xonsh/__amalgam__.py", line 752, in load
return self._load_or_node(offset, size)
File "/usr/local/lib/python3.5/dist-packages/xonsh/__amalgam__.py", line 759, in _load_or_node
val = json.loads(s)
File "/usr/lib/python3.5/json/__init__.py", line 319, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.5/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.5/json/decoder.py", line 355, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Unterminated string starting at: line 2 column 1493 (char 1504)

# Fixed code
def all_items(self, **kwargs):
    """
    Returns all history as found in XONSH_DATA_DIR.

    yield format: {'inp': cmd, 'rtn': 0, ...}
    """
    while self.gc and self.gc.is_alive():
        time.sleep(0.011)  # gc sleeps for 0.01 secs, sleep a beat longer
    for f in _xhj_get_history_files():
        try:
            json_file = xlj.LazyJSON(f, reopen=False)
        except ValueError:
            # Invalid json file
            continue
        try:
            commands = json_file.load()["cmds"]
        except json.decoder.JSONDecodeError:
            # file is corrupted somehow
            if builtins.__xonsh_env__.get("XONSH_DEBUG") > 0:
                msg = "xonsh history file {0!r} is not valid JSON"
                print(msg.format(f), file=sys.stderr)
            continue
        for c in commands:
            yield {"inp": c["inp"].rstrip(), "ts": c["ts"][0]}
    # all items should also include session items
    yield from self.items()