gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _run_npm(argv):
    if _nodejs is None:
        raise RuntimeError(
            "node.js is needed to allow compilation of custom models "
            + '("conda install -c bokeh nodejs" or follow https://nodejs.org/en/download/)'
        )

    _npm = join(dirname(_nodejs), "npm")
    proc = Popen([_npm] + argv, stdout=PIPE, stderr=PIPE, stdin=PIPE)
    (_stdout, errout) = proc.communicate()

    if len(errout) > 0:
        raise RuntimeError(errout)
    else:
        return None


# Traceback (RuntimeError)
[bryan:...xamples/custom/font-awesome]$ BOKEH_RESOURCES=inline python font-awesome.py                                   (bryanv/5626_properties_py)
Traceback (most recent call last):
File "font-awesome.py", line 10, in <module>
show(column(btn))
File "/Users/bryan/work/bokeh/bokeh/io.py", line 300, in show
return _show_with_state(obj, _state, browser, new, notebook_handle=notebook_handle)
File "/Users/bryan/work/bokeh/bokeh/io.py", line 318, in _show_with_state
_show_file_with_state(obj, state, new, controller)
File "/Users/bryan/work/bokeh/bokeh/io.py", line 323, in _show_file_with_state
filename = save(obj, state=state)
File "/Users/bryan/work/bokeh/bokeh/io.py", line 382, in save
_save_helper(obj, filename, resources, title, validate)
File "/Users/bryan/work/bokeh/bokeh/io.py", line 447, in _save_helper
html = standalone_html_page_for_models(obj, resources, title)
File "/Users/bryan/work/bokeh/bokeh/embed.py", line 600, in standalone_html_page_for_models
return file_html(models, resources, title)
File "/Users/bryan/work/bokeh/bokeh/embed.py", line 309, in file_html
bundle = _bundle_for_objs_and_resources(models, resources)
File "/Users/bryan/work/bokeh/bokeh/embed.py", line 206, in _bundle_for_objs_and_resources
bokeh_js = js_resources.render_js()
File "/Users/bryan/work/bokeh/bokeh/resources.py", line 395, in render_js
return JS_RESOURCES.render(js_raw=self.js_raw, js_files=self.js_files)
File "/Users/bryan/work/bokeh/bokeh/resources.py", line 388, in js_raw
custom_models = gen_custom_models_static()
File "/Users/bryan/work/bokeh/bokeh/util/compiler.py", line 298, in gen_custom_models_static
_run_npm(["install"] + [ name + "@" + version for (name, version) in dependencies ])
File "/Users/bryan/work/bokeh/bokeh/util/compiler.py", line 149, in _run_npm
raise RuntimeError(errout)
RuntimeError: b"npm WARN enoent ENOENT: no such file or directory, open '/Users/bryan/work/bokeh/examples/custom/font-awesome/package.json'\nnpm WARN font-awesome No description\nnpm WARN font-awesome No repository field.\nnpm WARN font-awesome No README data\nnpm WARN font-awesome No license field.\n"

# Fixed code
def _run_npm(argv):
    if _nodejs is None:
        raise RuntimeError(
            "node.js is needed to allow compilation of custom models "
            + '("conda install -c bokeh nodejs" or follow https://nodejs.org/en/download/)'
        )

    _npm = join(dirname(_nodejs), "npm")
    proc = Popen([_npm] + argv, stdout=PIPE, stderr=PIPE, stdin=PIPE)
    (_stdout, errout) = proc.communicate()

    if proc.returncode != 0:
        raise RuntimeError(errout)
    else:
        return None
# Buggy code
def __init__(self, source, path, argv):
    self._failed = False
    self._error = None
    self._error_detail = None

    import ast

    self._code = None

    try:
        nodes = ast.parse(source, path)
        self._code = compile(nodes, filename=path, mode="exec")
    except SyntaxError as e:
        self._failed = True
        self._error = 'Invalid syntax in "%s" on line %d:\n%s' % (
            os.path.basename(e.filename),
            e.lineno,
            e.text,
        )
        import traceback

        self._error_detail = traceback.format_exc()

    self._path = path
    self._source = source
    self._argv = argv
    self.ran = False


# Traceback (SyntaxError)
2016-12-20 07:52:02,473 Error running application handler <bokeh.application.handlers.script.ScriptHandler object at 0x10bb20f50>: invalid syntax (step3.py, line 41)
File "step4.py", line 3, in <module>:
execfile("step3.py") Traceback (most recent call last):
File "/Users/pwang/anaconda/envs/bokehdemo/lib/python2.7/site-packages/bokeh/application/handlers/code_runner.py", line 83, in run
exec(self._code, module.__dict__)
File "/Users/pwang/src/bokeh.demo/webinar/demo1/step4.py", line 3, in <module>
execfile("step3.py")
File "step3.py", line 41
print attribute, "changed from '%s' to '%s'" % (old, new)
^
SyntaxError: invalid syntax

# Fixed code
def __init__(self, source, path, argv):
    self._failed = False
    self._error = None
    self._error_detail = None

    import ast

    self._code = None

    try:
        nodes = ast.parse(source, path)
        self._code = compile(nodes, filename=path, mode="exec", dont_inherit=True)
    except SyntaxError as e:
        self._failed = True
        self._error = 'Invalid syntax in "%s" on line %d:\n%s' % (
            os.path.basename(e.filename),
            e.lineno,
            e.text,
        )
        import traceback

        self._error_detail = traceback.format_exc()

    self._path = path
    self._source = source
    self._argv = argv
    self.ran = False
# Buggy code
def _load_stock(filename):
    data = {
        "date": [],
        "open": [],
        "high": [],
        "low": [],
        "close": [],
        "volume": [],
        "adj_close": [],
    }
    with open(filename) as f:
        next(f)
        reader = csv.reader(f, delimiter=",")
        for row in reader:
            date, open_price, high, low, close, volume, adj_close = row
            data["date"].append(date)
            data["open"].append(float(open_price))
            data["high"].append(float(high))
            data["low"].append(float(low))
            data["close"].append(float(close))
            data["volume"].append(int(volume))
            data["adj_close"].append(float(adj_close))
    return data


# Traceback (UnicodeDecodeError)
---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-6-a97873fe504b> in <module>()
2 from bokeh.palettes import Viridis6
3 from bokeh.plotting import figure, show, output_file, ColumnDataSource
----> 4 from bokeh.sampledata.us_counties import data as counties
5 from bokeh.sampledata.unemployment import data as unemployment

/home/nbuser/anaconda3_410/lib/python3.5/site-packages/bokeh/sampledata/us_counties.py in <module>()
24     next(f)
25     reader = csv.reader(f, delimiter=',', quotechar='"')
---> 26     for row in reader:
27         name, dummy, state, dummy, geometry, dummy, dummy, dummy, dummy, state_id, county_id, dummy, dummy = row
28         xml = et.fromstring(geometry)

/home/nbuser/anaconda3_410/lib/python3.5/encodings/ascii.py in decode(self, input, final)
24 class IncrementalDecoder(codecs.IncrementalDecoder):
25     def decode(self, input, final=False):
---> 26         return codecs.ascii_decode(input, self.errors)[0]
27
28 class StreamWriter(Codec,codecs.StreamWriter):

UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 2514: ordinal not in range(128)

# Fixed code
def _load_stock(filename):
    data = {
        "date": [],
        "open": [],
        "high": [],
        "low": [],
        "close": [],
        "volume": [],
        "adj_close": [],
    }
    with _open_csv_file(filename) as f:
        next(f)
        reader = csv.reader(f, delimiter=",")
        for row in reader:
            date, open_price, high, low, close, volume, adj_close = row
            data["date"].append(date)
            data["open"].append(float(open_price))
            data["high"].append(float(high))
            data["low"].append(float(low))
            data["close"].append(float(close))
            data["volume"].append(int(volume))
            data["adj_close"].append(float(adj_close))
    return data
# Buggy code
def __init__(
    self, session_id=None, websocket_url=DEFAULT_SERVER_WEBSOCKET_URL, io_loop=None
):
    """
    A connection which attaches to a particular named session on the server.

    Always call either pull() or push() immediately after creating the session
    (until these are called session.document will be None).

    The bokeh.client.push_session() and bokeh.client.pull_session() functions
    will construct a ClientSession and push or pull in one step, so they are
    a good way to obtain a ClientSession.

    Args:
        session_id (str) :
            The name of the session or None to generate one
        websocket_url (str) :
            Websocket URL to connect to
        io_loop (``tornado.ioloop.IOLoop``, optional) :
            The IOLoop to use for the websocket
    """
    self._document = None
    self._id = self._ensure_session_id(session_id)

    self._connection = ClientConnection(
        session=self, io_loop=io_loop, websocket_url=websocket_url
    )

    self._current_patch = None
    self._callbacks = _DocumentCallbackGroup(self._connection.io_loop)


# Traceback (ImportError)
$ python -c 'import bokeh.io'
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "bokeh/io.py", line 29, in <module>
from .core.state import State
File "bokeh/core/state.py", line 46, in <module>
from ..client import DEFAULT_SESSION_ID
File "bokeh/client/__init__.py", line 6, in <module>
from .session import ClientSession, pull_session, push_session, show_session, DEFAULT_SESSION_ID
File "bokeh/client/session.py", line 10, in <module>
from ._connection import ClientConnection
File "bokeh/client/_connection.py", line 11, in <module>
from tornado import gen, locks
ImportError: No module named tornado

# Fixed code
def __init__(
    self, session_id=None, websocket_url=DEFAULT_SERVER_WEBSOCKET_URL, io_loop=None
):
    """
    A connection which attaches to a particular named session on the server.

    Always call either pull() or push() immediately after creating the session
    (until these are called session.document will be None).

    The bokeh.client.push_session() and bokeh.client.pull_session() functions
    will construct a ClientSession and push or pull in one step, so they are
    a good way to obtain a ClientSession.

    Args:
        session_id (str) :
            The name of the session or None to generate one
        websocket_url (str) :
            Websocket URL to connect to
        io_loop (``tornado.ioloop.IOLoop``, optional) :
            The IOLoop to use for the websocket
    """
    self._document = None
    self._id = self._ensure_session_id(session_id)

    from ._connection import ClientConnection

    self._connection = ClientConnection(
        session=self, io_loop=io_loop, websocket_url=websocket_url
    )

    self._current_patch = None
    from bokeh.util.tornado import _DocumentCallbackGroup

    self._callbacks = _DocumentCallbackGroup(self._connection.io_loop)
# Buggy code
def build_source(self):
    return {"x": self.x, "y": self.y}


# Traceback (OverflowError)
Traceback (most recent call last):
File "test.py", line 22, in <module>
hist = Histogram(df, values='values',  legend=True,
File "/Users/<username>/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/bokeh/charts/builder/histogram_builder.py", line 53, in Histogram
return create_and_build(HistogramBuilder, data, **kw)
File "/Users/<username>/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/bokeh/charts/_builder.py", line 64, in create_and_build
chart.add_builder(builder)
File "/Users/<username>/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/bokeh/charts/_chart.py", line 134, in add_builder
builder.create(self)
File "/Users/<username>/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/bokeh/charts/_builder.py", line 303, in create
chart.add_renderers(self, renderers)
File "/Users/<username>/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/bokeh/charts/_chart.py", line 129, in add_renderers
self.renderers += renderers
File "/Users/<username>/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/bokeh/charts/builder/bar_builder.py", line 228, in _yield_renderers
**group_kwargs)
File "/Users/<username>/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/bokeh/charts/glyphs.py", line 469, in __init__
super(HistogramGlyph, self).__init__(**kwargs)
File "/Users/<username>/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/bokeh/charts/_models.py", line 61, in __init__
self.setup()
File "/Users/<username>/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/bokeh/charts/_models.py", line 64, in setup
self.renderers = [renderer for renderer in self.build_renderers()]
File "/Users/<username>/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/bokeh/charts/glyphs.py", line 478, in build_renderers
self.bins = Bins(values=self.values, bin_count=self.bin_count)
File "/Users/<username>/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/bokeh/charts/stats.py", line 164, in __init__
super(Bins, self).__init__(**properties)
File "/Users/<username>/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/bokeh/charts/stats.py", line 23, in __init__
self._refresh()
File "/Users/<username>/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/bokeh/charts/stats.py", line 29, in _refresh
self.calculate()
File "/Users/<username>/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/bokeh/charts/stats.py", line 174, in calculate
binned, bin_edges = pd.cut(self.get_data(), self.bin_count, retbins=True, precision=0)
File "/Users/<username>/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pandas/tools/tile.py", line 100, in cut
bins = np.linspace(mn, mx, bins + 1, endpoint=True)
File "/Users/<username>/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/numpy/core/function_base.py", line 84, in linspace
num = int(num)
OverflowError: cannot convert float infinity to integer

# Fixed code
def build_source(self):
    return {"x": self.x, "y": self.y, "values": self.values}
# Buggy code
def _iter_path_collection(paths, path_transforms, offsets, styles):
    """Build an iterator over the elements of the path collection"""
    N = max(len(paths), len(offsets))

    if not path_transforms:
        path_transforms = [np.eye(3)]

    edgecolor = styles["edgecolor"]
    if np.size(edgecolor) == 0:
        edgecolor = ["none"]
    facecolor = styles["facecolor"]
    if np.size(facecolor) == 0:
        facecolor = ["none"]

    elements = [
        paths,
        path_transforms,
        offsets,
        edgecolor,
        styles["linewidth"],
        facecolor,
    ]

    it = itertools
    return it.islice(py3k.zip(*py3k.map(it.cycle, elements)), N)


# Traceback (ValueError)
Traceback (most recent call last):
File "violin.py", line 29, in <module>
show(mpl.to_bokeh())
File "/Users/mmari/Desktop/continuum/bokeh/bokeh/compat/mpl.py", line 77, in to_bokeh
exporter.run(fig)
File "/Users/mmari/Desktop/continuum/bokeh/bokeh/compat/mplexporter/exporter.py", line 51, in run
self.crawl_fig(fig)
File "/Users/mmari/Desktop/continuum/bokeh/bokeh/compat/mplexporter/exporter.py", line 118, in crawl_fig
self.crawl_ax(ax)
File "/Users/mmari/Desktop/continuum/bokeh/bokeh/compat/mplexporter/exporter.py", line 140, in crawl_ax
self.draw_collection(ax, collection)
File "/Users/mmari/Desktop/continuum/bokeh/bokeh/compat/bokeh_exporter.py", line 34, in draw_collection
super(BokehExporter, self).draw_collection(ax, collection, force_pathtrans, force_offsettrans)
File "/Users/mmari/Desktop/continuum/bokeh/bokeh/compat/mplexporter/exporter.py", line 272, in draw_collection
mplobj=collection)
File "/Users/mmari/Desktop/continuum/bokeh/bokeh/compat/mplexporter/renderers/base.py", line 255, in draw_path_collection
offsets, styles):
File "/Users/mmari/Desktop/continuum/bokeh/bokeh/compat/mplexporter/renderers/base.py", line 192, in _iter_path_collection
if not path_transforms:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

# Fixed code
def _iter_path_collection(paths, path_transforms, offsets, styles):
    """Build an iterator over the elements of the path collection"""
    N = max(len(paths), len(offsets))

    if len(path_transforms) == 0:
        path_transforms = [np.eye(3)]

    edgecolor = styles["edgecolor"]
    if np.size(edgecolor) == 0:
        edgecolor = ["none"]
    facecolor = styles["facecolor"]
    if np.size(facecolor) == 0:
        facecolor = ["none"]

    elements = [
        paths,
        path_transforms,
        offsets,
        edgecolor,
        styles["linewidth"],
        facecolor,
    ]

    it = itertools
    return it.islice(py3k.zip(*py3k.map(it.cycle, elements)), N)
# Buggy code
def transform(self, value):
    value = super(DashPattern, self).transform(value)

    if isinstance(value, string_types):
        try:
            return self._dash_patterns[value]
        except KeyError:
            return map(int, value.split())
    else:
        return value


# Traceback (AssertionError)
======================================================================
FAIL: test_string (bokeh.tests.test_properties.TestDashPattern)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/bryan/work/bokeh/bokeh/tests/test_properties.py", line 305, in test_string
self.assertEqual(f.pat, [])
AssertionError: <map object at 0x105c012e8> != []

# Fixed code
def transform(self, value):
    value = super(DashPattern, self).transform(value)

    if isinstance(value, string_types):
        try:
            return self._dash_patterns[value]
        except KeyError:
            return [int(x) for x in value.split()]
    else:
        return value
# Buggy code
def fetch_albums_from_artist(artist_url, album_type="album"):
    """
    This funcction returns all the albums from a give artist_url using the US
    market
    :param artist_url - spotify artist url
    :param album_type - the type of album to fetch (ex: single) the default is
                        a standard album
    :param return - the album from the artist
    """

    # fetching artist's albums limitting the results to the US to avoid duplicate
    # albums from multiple markets
    artist_id = internals.extract_spotify_id(artist_url)
    results = spotify.artist_albums(artist_id, album_type=album_type, country="US")

    albums = results["items"]

    # indexing all pages of results
    while results["next"]:
        results = spotify.next(results)
        albums.extend(results["items"])

    return albums


# Traceback (IndexError)
Traceback (most recent call last):
File "/usr/local/bin/spotdl", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python3.7/site-packages/spotdl/spotdl.py", line 62, in main
match_args()
File "/usr/local/lib/python3.7/site-packages/spotdl/spotdl.py", line 44, in match_args
spotify_tools.write_all_albums_from_artist(artist_url=const.args.all_albums)
File "/usr/local/lib/python3.7/site-packages/spotdl/spotify_tools.py", line 200, in write_all_albums_from_artist
text_file = albums[0]["artists"][0]["name"] + ".txt"
IndexError: list index out of range

# Fixed code
def fetch_albums_from_artist(artist_url, album_type=None):
    """
    This funcction returns all the albums from a give artist_url using the US
    market
    :param artist_url - spotify artist url
    :param album_type - the type of album to fetch (ex: single) the default is
                        all albums
    :param return - the album from the artist
    """

    # fetching artist's albums limitting the results to the US to avoid duplicate
    # albums from multiple markets
    artist_id = internals.extract_spotify_id(artist_url)
    results = spotify.artist_albums(artist_id, album_type=album_type, country="US")

    albums = results["items"]

    # indexing all pages of results
    while results["next"]:
        results = spotify.next(results)
        albums.extend(results["items"])

    return albums
# Buggy code
def write_all_albums_from_artist(artist_url, text_file=None):
    """
    This function gets all albums from an artist and writes it to a file in the
    current working directory called [ARTIST].txt, where [ARTIST] is the artist
    of the album
    :param artist_url - spotify artist url
    :param text_file - file to write albums to
    """

    album_base_url = "https://open.spotify.com/album/"

    # fetching all default albums
    albums = fetch_albums_from_artist(artist_url)

    # if no file if given, the default save file is in the current working
    # directory with the name of the artist
    if text_file is None:
        text_file = albums[0]["artists"][0]["name"] + ".txt"

    for album in albums:
        # logging album name
        log.info("Fetching album: " + album["name"])
        write_album(album_base_url + album["id"], text_file=text_file)

    # fetching all single albums
    singles = fetch_albums_from_artist(artist_url, album_type="single")

    for single in singles:
        log.info("Fetching single: " + single["name"])
        write_album(album_base_url + single["id"], text_file=text_file)


# Traceback (IndexError)
Traceback (most recent call last):
File "/usr/local/bin/spotdl", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python3.7/site-packages/spotdl/spotdl.py", line 62, in main
match_args()
File "/usr/local/lib/python3.7/site-packages/spotdl/spotdl.py", line 44, in match_args
spotify_tools.write_all_albums_from_artist(artist_url=const.args.all_albums)
File "/usr/local/lib/python3.7/site-packages/spotdl/spotify_tools.py", line 200, in write_all_albums_from_artist
text_file = albums[0]["artists"][0]["name"] + ".txt"
IndexError: list index out of range

# Fixed code
def write_all_albums_from_artist(artist_url, text_file=None):
    """
    This function gets all albums from an artist and writes it to a file in the
    current working directory called [ARTIST].txt, where [ARTIST] is the artist
    of the album
    :param artist_url - spotify artist url
    :param text_file - file to write albums to
    """

    album_base_url = "https://open.spotify.com/album/"

    # fetching all default albums
    albums = fetch_albums_from_artist(artist_url, album_type=None)

    # if no file if given, the default save file is in the current working
    # directory with the name of the artist
    if text_file is None:
        text_file = albums[0]["artists"][0]["name"] + ".txt"

    for album in albums:
        # logging album name
        log.info("Fetching album: " + album["name"])
        write_album(album_base_url + album["id"], text_file=text_file)
# Buggy code
def escape_xpath_value(value):
    if '"' in value and "'" in value:
        parts_wo_apos = value.split("'")
        escaped = "', \"'\", '".join(parts_wo_apos)
        return f"concat('{escaped}')"
    if "'" in value:
        return f'"{value}"'
    return f"'{value}'"


# Traceback (TypeError)
18:35:00.405    FAIL    TypeError: argument of type 'int' is not iterable
18:35:00.405    DEBUG   Traceback (most recent call last):
File "c:\python27\lib\site-packages\SeleniumLibrary\__init__.py", line 360, in run_keyword
return DynamicCore.run_keyword(self, name, args, kwargs)
File "c:\python27\lib\site-packages\SeleniumLibrary\base\robotlibcore.py", line 102, in run_keyword
return self.keywords[name](*args, **kwargs)
File "c:\python27\lib\site-packages\SeleniumLibrary\keywords\waiting.py", line 66, in wait_until_page_contains
timeout, error)
File "c:\python27\lib\site-packages\SeleniumLibrary\keywords\waiting.py", line 220, in _wait_until
self._wait_until_worker(condition, timeout, error)
File "c:\python27\lib\site-packages\SeleniumLibrary\keywords\waiting.py", line 227, in _wait_until_worker
if condition():
File "c:\python27\lib\site-packages\SeleniumLibrary\keywords\waiting.py", line 64, in <lambda>
self._wait_until(lambda: self.is_text_present(text),
File "c:\python27\lib\site-packages\SeleniumLibrary\base\context.py", line 81, in is_text_present
locator = "xpath://*[contains(., %s)]" % escape_xpath_value(text)
File "c:\python27\lib\site-packages\SeleniumLibrary\utils\__init__.py", line 27, i

# Fixed code
def escape_xpath_value(value: str):
    value = str(value)
    if '"' in value and "'" in value:
        parts_wo_apos = value.split("'")
        escaped = "', \"'\", '".join(parts_wo_apos)
        return f"concat('{escaped}')"
    if "'" in value:
        return f'"{value}"'
    return f"'{value}'"
# Buggy code
def __init__(
    self, name, value, path=None, domain=None, secure=False, httpOnly=False, expiry=None
):
    self.name = name
    self.value = value
    self.path = path
    self.domain = domain
    self.secure = secure
    self.httpOnly = httpOnly
    self.expiry = datetime.fromtimestamp(expiry) if expiry else None


# Traceback (TypeError)
20190212 16:54:43.113 :  FAIL : TypeError: __init__() got an unexpected keyword argument 'hCode'
20190212 16:54:43.113 : DEBUG :
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\SeleniumLibrary\__init__.py", line 369, in run_keyword
return DynamicCore.run_keyword(self, name, args, kwargs)
File "C:\Python27\lib\site-packages\SeleniumLibrary\base\robotlibcore.py", line 102, in run_keyword
return self.keywords[name](*args, **kwargs)
File "C:\Python27\lib\site-packages\SeleniumLibrary\keywords\cookie.py", line 99, in get_cookie
return CookieInformation(**cookie)

# Fixed code
def __init__(
    self,
    name,
    value,
    path=None,
    domain=None,
    secure=False,
    httpOnly=False,
    expiry=None,
    **extra,
):
    self.name = name
    self.value = value
    self.path = path
    self.domain = domain
    self.secure = secure
    self.httpOnly = httpOnly
    self.expiry = datetime.fromtimestamp(expiry) if expiry else None
    self.extra = extra
# Buggy code
def __str__(self):
    items = "name value path domain secure httpOnly expiry".split()
    return "\n".join("%s=%s" % (item, getattr(self, item)) for item in items)


# Traceback (TypeError)
20190212 16:54:43.113 :  FAIL : TypeError: __init__() got an unexpected keyword argument 'hCode'
20190212 16:54:43.113 : DEBUG :
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\SeleniumLibrary\__init__.py", line 369, in run_keyword
return DynamicCore.run_keyword(self, name, args, kwargs)
File "C:\Python27\lib\site-packages\SeleniumLibrary\base\robotlibcore.py", line 102, in run_keyword
return self.keywords[name](*args, **kwargs)
File "C:\Python27\lib\site-packages\SeleniumLibrary\keywords\cookie.py", line 99, in get_cookie
return CookieInformation(**cookie)

# Fixed code
def __str__(self):
    items = "name value path domain secure httpOnly expiry".split()
    string = "\n".join("%s=%s" % (item, getattr(self, item)) for item in items)
    if self.extra:
        string = "%s%s=%s\n" % (string, "extra", self.extra)
    return string
# Buggy code
def __str__(self):
    items = "name value path domain secure httpOnly expiry".split()
    string = "\n".join("%s=%s" % (item, getattr(self, item)) for item in items)
    if self.extra:
        string = "%s%s=%s\n" % (string, "extra", self.extra)
    return string


# Traceback (TypeError)
20190212 16:54:43.113 :  FAIL : TypeError: __init__() got an unexpected keyword argument 'hCode'
20190212 16:54:43.113 : DEBUG :
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\SeleniumLibrary\__init__.py", line 369, in run_keyword
return DynamicCore.run_keyword(self, name, args, kwargs)
File "C:\Python27\lib\site-packages\SeleniumLibrary\base\robotlibcore.py", line 102, in run_keyword
return self.keywords[name](*args, **kwargs)
File "C:\Python27\lib\site-packages\SeleniumLibrary\keywords\cookie.py", line 99, in get_cookie
return CookieInformation(**cookie)

# Fixed code
def __str__(self):
    items = "name value path domain secure httpOnly expiry".split()
    string = "\n".join("%s=%s" % (item, getattr(self, item)) for item in items)
    if self.extra:
        string = "%s\n%s=%s\n" % (string, "extra", self.extra)
    return string
# Buggy code
def get_rates(self):
    rates = requests.get(self.api_url).json()["rates"]
    rates[self.default] = 1.0
    return rates


# Traceback (sqlalchemy.exc.DataError)
INFO  [alembic.runtime.migration] Running upgrade cb038f79982e -> 927ed575acbd, Add currencies
Traceback (most recent call last):
File "/home/zorun/tmp/venv3-ihatemoney/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 1247, in _execute_context
self.dialect.do_execute(
File "/home/zorun/tmp/venv3-ihatemoney/lib/python3.8/site-packages/sqlalchemy/engine/default.py", line 590, in do_execute
cursor.execute(statement, parameters)
psycopg2.errors.StringDataRightTruncation: value too long for type character varying(3)

The above exception was the direct cause of the following exception:

sqlalchemy.exc.DataError: (psycopg2.errors.StringDataRightTruncation) value too long for type character varying(3)

[SQL: ALTER TABLE bill ADD COLUMN original_currency VARCHAR(3) DEFAULT 'No Currency']

# Fixed code
def get_rates(self):
    rates = requests.get(self.api_url).json()["rates"]
    rates[self.no_currency] = 1.0
    return rates
# Buggy code
def get_currencies(self):
    rates = [rate for rate in self.get_rates()]
    rates.sort(key=lambda rate: "" if rate == self.default else rate)
    return rates


# Traceback (sqlalchemy.exc.DataError)
INFO  [alembic.runtime.migration] Running upgrade cb038f79982e -> 927ed575acbd, Add currencies
Traceback (most recent call last):
File "/home/zorun/tmp/venv3-ihatemoney/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 1247, in _execute_context
self.dialect.do_execute(
File "/home/zorun/tmp/venv3-ihatemoney/lib/python3.8/site-packages/sqlalchemy/engine/default.py", line 590, in do_execute
cursor.execute(statement, parameters)
psycopg2.errors.StringDataRightTruncation: value too long for type character varying(3)

The above exception was the direct cause of the following exception:

sqlalchemy.exc.DataError: (psycopg2.errors.StringDataRightTruncation) value too long for type character varying(3)

[SQL: ALTER TABLE bill ADD COLUMN original_currency VARCHAR(3) DEFAULT 'No Currency']

# Fixed code
def get_currencies(self, with_no_currency=True):
    rates = [
        rate
        for rate in self.get_rates()
        if with_no_currency or rate != self.no_currency
    ]
    rates.sort(key=lambda rate: "" if rate == self.no_currency else rate)
    return rates
# Buggy code
def exchange_currency(self, amount, source_currency, dest_currency):
    if (
        source_currency == dest_currency
        or source_currency == self.default
        or dest_currency == self.default
    ):
        return amount

    rates = self.get_rates()
    source_rate = rates[source_currency]
    dest_rate = rates[dest_currency]
    new_amount = (float(amount) / source_rate) * dest_rate
    # round to two digits because we are dealing with money
    return round(new_amount, 2)


# Traceback (sqlalchemy.exc.DataError)
INFO  [alembic.runtime.migration] Running upgrade cb038f79982e -> 927ed575acbd, Add currencies
Traceback (most recent call last):
File "/home/zorun/tmp/venv3-ihatemoney/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 1247, in _execute_context
self.dialect.do_execute(
File "/home/zorun/tmp/venv3-ihatemoney/lib/python3.8/site-packages/sqlalchemy/engine/default.py", line 590, in do_execute
cursor.execute(statement, parameters)
psycopg2.errors.StringDataRightTruncation: value too long for type character varying(3)

The above exception was the direct cause of the following exception:

sqlalchemy.exc.DataError: (psycopg2.errors.StringDataRightTruncation) value too long for type character varying(3)

[SQL: ALTER TABLE bill ADD COLUMN original_currency VARCHAR(3) DEFAULT 'No Currency']

# Fixed code
def exchange_currency(self, amount, source_currency, dest_currency):
    if (
        source_currency == dest_currency
        or source_currency == self.no_currency
        or dest_currency == self.no_currency
    ):
        return amount

    rates = self.get_rates()
    source_rate = rates[source_currency]
    dest_rate = rates[dest_currency]
    new_amount = (float(amount) / source_rate) * dest_rate
    # round to two digits because we are dealing with money
    return round(new_amount, 2)
# Buggy code
def fake_form(self, bill, project):
    bill.payer_id = self.payer
    bill.amount = self.amount
    bill.what = self.what
    bill.external_link = ""
    bill.date = self.date
    bill.owers = [Person.query.get(ower, project) for ower in self.payed_for]
    bill.original_currency = CurrencyConverter.default
    bill.converted_amount = self.currency_helper.exchange_currency(
        bill.amount, bill.original_currency, project.default_currency
    )

    return bill


# Traceback (sqlalchemy.exc.DataError)
INFO  [alembic.runtime.migration] Running upgrade cb038f79982e -> 927ed575acbd, Add currencies
Traceback (most recent call last):
File "/home/zorun/tmp/venv3-ihatemoney/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 1247, in _execute_context
self.dialect.do_execute(
File "/home/zorun/tmp/venv3-ihatemoney/lib/python3.8/site-packages/sqlalchemy/engine/default.py", line 590, in do_execute
cursor.execute(statement, parameters)
psycopg2.errors.StringDataRightTruncation: value too long for type character varying(3)

The above exception was the direct cause of the following exception:

sqlalchemy.exc.DataError: (psycopg2.errors.StringDataRightTruncation) value too long for type character varying(3)

[SQL: ALTER TABLE bill ADD COLUMN original_currency VARCHAR(3) DEFAULT 'No Currency']

# Fixed code
def fake_form(self, bill, project):
    bill.payer_id = self.payer
    bill.amount = self.amount
    bill.what = self.what
    bill.external_link = ""
    bill.date = self.date
    bill.owers = [Person.query.get(ower, project) for ower in self.payed_for]
    bill.original_currency = CurrencyConverter.no_currency
    bill.converted_amount = self.currency_helper.exchange_currency(
        bill.amount, bill.original_currency, project.default_currency
    )

    return bill
# Buggy code
def fill(self, bill):
    self.payer.data = bill.payer_id
    self.amount.data = bill.amount
    self.what.data = bill.what
    self.external_link.data = bill.external_link
    self.original_currency.data = bill.original_currency
    self.date.data = bill.date
    self.payed_for.data = [int(ower.id) for ower in bill.owers]


# Traceback (sqlalchemy.exc.DataError)
INFO  [alembic.runtime.migration] Running upgrade cb038f79982e -> 927ed575acbd, Add currencies
Traceback (most recent call last):
File "/home/zorun/tmp/venv3-ihatemoney/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 1247, in _execute_context
self.dialect.do_execute(
File "/home/zorun/tmp/venv3-ihatemoney/lib/python3.8/site-packages/sqlalchemy/engine/default.py", line 590, in do_execute
cursor.execute(statement, parameters)
psycopg2.errors.StringDataRightTruncation: value too long for type character varying(3)

The above exception was the direct cause of the following exception:

sqlalchemy.exc.DataError: (psycopg2.errors.StringDataRightTruncation) value too long for type character varying(3)

[SQL: ALTER TABLE bill ADD COLUMN original_currency VARCHAR(3) DEFAULT 'No Currency']

# Fixed code
def fill(self, bill, project):
    self.payer.data = bill.payer_id
    self.amount.data = bill.amount
    self.what.data = bill.what
    self.external_link.data = bill.external_link
    self.original_currency.data = bill.original_currency
    self.date.data = bill.date
    self.payed_for.data = [int(ower.id) for ower in bill.owers]

    self.original_currency.label = Label("original_currency", _("Currency"))
    self.original_currency.description = _(
        "Project default: %(currency)s",
        currency=render_localized_currency(project.default_currency, detailed=False),
    )
# Buggy code
def edit_bill(bill_id):
    # FIXME: Test this bill belongs to this project !
    bill = Bill.query.get(g.project, bill_id)
    if not bill:
        raise NotFound()

    form = get_billform_for(g.project, set_default=False)

    if request.method == "POST" and form.validate():
        form.save(bill, g.project)
        db.session.commit()

        flash(_("The bill has been modified"))
        return redirect(url_for(".list_bills"))

    if not form.errors:
        form.fill(bill)

    return render_template("add_bill.html", form=form, edit=True)


# Traceback (sqlalchemy.exc.DataError)
INFO  [alembic.runtime.migration] Running upgrade cb038f79982e -> 927ed575acbd, Add currencies
Traceback (most recent call last):
File "/home/zorun/tmp/venv3-ihatemoney/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 1247, in _execute_context
self.dialect.do_execute(
File "/home/zorun/tmp/venv3-ihatemoney/lib/python3.8/site-packages/sqlalchemy/engine/default.py", line 590, in do_execute
cursor.execute(statement, parameters)
psycopg2.errors.StringDataRightTruncation: value too long for type character varying(3)

The above exception was the direct cause of the following exception:

sqlalchemy.exc.DataError: (psycopg2.errors.StringDataRightTruncation) value too long for type character varying(3)

[SQL: ALTER TABLE bill ADD COLUMN original_currency VARCHAR(3) DEFAULT 'No Currency']

# Fixed code
def edit_bill(bill_id):
    # FIXME: Test this bill belongs to this project !
    bill = Bill.query.get(g.project, bill_id)
    if not bill:
        raise NotFound()

    form = get_billform_for(g.project, set_default=False)

    if request.method == "POST" and form.validate():
        form.save(bill, g.project)
        db.session.commit()

        flash(_("The bill has been modified"))
        return redirect(url_for(".list_bills"))

    if not form.errors:
        form.fill(bill, g.project)

    return render_template("add_bill.html", form=form, edit=True)
# Buggy code
def clear_screen() -> None:  # pragma: no cover
    subprocess.call(["clear"])


# Traceback (FileNotFoundError)
C:\Files\Source\dataops-infra>detect-secrets audit .secrets.baseline
Traceback (most recent call last):
File "c:\python38\lib\runpy.py", line 193, in _run_module_as_main
return _run_code(code, main_globals, None,
File "c:\python38\lib\runpy.py", line 86, in _run_code
exec(code, run_globals)
File "C:\Python38\Scripts\detect-secrets.exe\__main__.py", line 7, in <module>
File "c:\python38\lib\site-packages\detect_secrets\main.py", line 73, in main
audit.audit_baseline(args.filename[0])
File "c:\python38\lib\site-packages\detect_secrets\core\audit.py", line 84, in audit_baseline
_clear_screen()
File "c:\python38\lib\site-packages\detect_secrets\core\audit.py", line 480, in _clear_screen
subprocess.call(['clear'])
File "c:\python38\lib\subprocess.py", line 340, in call
with Popen(*popenargs, **kwargs) as p:
File "c:\python38\lib\subprocess.py", line 854, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "c:\python38\lib\subprocess.py", line 1307, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

# Fixed code
def clear_screen() -> None:  # pragma: no cover
    command = "clear"
    if platform.system() == "Windows":
        command = "cls"
    os.system(command)
# Buggy code
def get_parser_to_add_opt_out_options_to(parser):
    """
    The pre-commit hook gets e.g. `--no-jwt-scan` type options
    as well as the subparser for `detect-secrets scan`.

    :rtype: argparse.ArgumentParser
    :returns: argparse.ArgumentParser to pass into PluginOptions
    """
    if parser.prog == "detect-secrets-hook":
        return parser

    for action in parser._actions:  # pragma: no cover (Always returns)
        if isinstance(action, argparse._SubParsersAction):
            for subparser in action.choices.values():
                if subparser.prog.endswith("scan"):
                    return subparser


# Traceback (AttributeError)
Detect secrets...........................................................Failed
- hook id: detect-secrets
- exit code: 1

Traceback (most recent call last):
File "c:\users\john.neville\appdata\local\programs\python\python38-32\lib\runpy.py", line 193, in _run_module_as_main
return _run_code(code, main_globals, None,
File "c:\users\john.neville\appdata\local\programs\python\python38-32\lib\runpy.py", line 86, in _run_code
exec(code, run_globals)
File "C:\Users\john.neville\.cache\pre-commit\repog21r_7q6\py_env-python3.8\Scripts\detect-secrets-hook.EXE\__main__.py", line 7, in <module>
File "c:\users\john.neville\.cache\pre-commit\repog21r_7q6\py_env-python3.8\lib\site-packages\detect_secrets\pre_commit_hook.py", line 27, in main
args = parse_args(argv)
File "c:\users\john.neville\.cache\pre-commit\repog21r_7q6\py_env-python3.8\lib\site-packages\detect_secrets\pre_commit_hook.py", line 21, in parse_args
return ParserBuilder()\
File "c:\users\john.neville\.cache\pre-commit\repog21r_7q6\py_env-python3.8\lib\site-packages\detect_secrets\core\usage.py", line 170, in parse_args
PluginOptions(
File "c:\users\john.neville\.cache\pre-commit\repog21r_7q6\py_env-python3.8\lib\site-packages\detect_secrets\core\usage.py", line 409, in __init__
self.parser = parser.add_argument_group(
AttributeError: 'NoneType' object has no attribute 'add_argument_group'

# Fixed code
def get_parser_to_add_opt_out_options_to(parser):
    """
    The pre-commit hook gets e.g. `--no-jwt-scan` type options
    as well as the subparser for `detect-secrets scan`.

    :rtype: argparse.ArgumentParser
    :returns: argparse.ArgumentParser to pass into PluginOptions
    """
    for action in parser._actions:  # pragma: no cover (Always returns)
        if isinstance(action, argparse._SubParsersAction):
            for subparser in action.choices.values():
                if subparser.prog.endswith("scan"):
                    return subparser
    # Assume it is the 'detect-secrets-hook' console script
    # Relying on parser.prog is too brittle
    return parser
# Buggy code
def _set_debug_level(self, debug_level):
    """
    :type debug_level: int, between 0-2
    :param debug_level: configure verbosity of log
    """
    mapping = {
        0: logging.ERROR,
        1: logging.INFO,
        2: logging.DEBUG,
    }

    self.setLevel(mapping[debug_level])


# Traceback (KeyError)
Traceback (most recent call last):
File "/hey/three_six/bin/detect-secrets", line 11, in <module>
sys.exit(main())
File "/hey/three_six/lib/python3.6/site-packages/detect_secrets/main.py", line 27, in main
log.set_debug_level(args.verbose)
File "/hey/three_six/lib/python3.6/site-packages/detect_secrets/core/log.py", line 46, in _set_debug_level
self.setLevel(mapping[debug_level])
KeyError: 3

# Fixed code
def _set_debug_level(self, debug_level):
    """
    :type debug_level: int, between 0-2
    :param debug_level: configure verbosity of log
    """
    mapping = {
        0: logging.ERROR,
        1: logging.INFO,
        2: logging.DEBUG,
    }

    self.setLevel(
        mapping[min(debug_level, 2)],
    )
# Buggy code
def __init__(self, typ, filename, lineno, secret):
    """
    :type typ: str
    :param typ: human-readable secret type, defined by the plugin
                that generated this PotentialSecret.
                Eg. "High Entropy String"

    :type filename: str
    :param filename: name of file that this secret was found

    :type lineno: int
    :param lineno: location of secret, within filename.
                   Merely used as a reference for easy triage.

    :type secret: str
    :param secret: the actual secret identified
    """
    self.type = typ
    self.filename = filename
    self.lineno = lineno
    self.secret_hash = self.hash_secret(secret)

    # If two PotentialSecrets have the same values for these fields,
    # they are considered equal. Note that line numbers aren't included
    # in this, because line numbers are subject to change.
    self.fields_to_compare = ["filename", "secret_hash", "type"]


# Traceback (KeyError)
Traceback (most recent call last):
File "/hey/three_six/bin/detect-secrets", line 11, in <module>
sys.exit(main())
File "/hey/three_six/lib/python3.6/site-packages/detect_secrets/main.py", line 27, in main
log.set_debug_level(args.verbose)
File "/hey/three_six/lib/python3.6/site-packages/detect_secrets/core/log.py", line 46, in _set_debug_level
self.setLevel(mapping[debug_level])
KeyError: 3

# Fixed code
def __init__(
    self,
    typ,
    filename,
    lineno,
    secret,
    is_secret=None,
):
    """
    :type typ: str
    :param typ: human-readable secret type, defined by the plugin
                that generated this PotentialSecret.
                e.g. "High Entropy String"

    :type filename: str
    :param filename: name of file that this secret was found

    :type lineno: int
    :param lineno: location of secret, within filename.
                   Merely used as a reference for easy triage.

    :type secret: str
    :param secret: the actual secret identified

    :type is_secret: bool|None
    :param is_secret: whether or not the secret is a true- or false- positive
    """
    self.type = typ
    self.filename = filename
    self.lineno = lineno
    self.secret_hash = self.hash_secret(secret)
    self.is_secret = is_secret

    # If two PotentialSecrets have the same values for these fields,
    # they are considered equal. Note that line numbers aren't included
    # in this, because line numbers are subject to change.
    self.fields_to_compare = ["filename", "secret_hash", "type"]
# Buggy code
def json(self):
    """Custom JSON encoder"""
    attributes = {
        "type": self.type,
        "filename": self.filename,
        "line_number": self.lineno,
        "hashed_secret": self.secret_hash,
    }

    return attributes


# Traceback (KeyError)
Traceback (most recent call last):
File "/hey/three_six/bin/detect-secrets", line 11, in <module>
sys.exit(main())
File "/hey/three_six/lib/python3.6/site-packages/detect_secrets/main.py", line 27, in main
log.set_debug_level(args.verbose)
File "/hey/three_six/lib/python3.6/site-packages/detect_secrets/core/log.py", line 46, in _set_debug_level
self.setLevel(mapping[debug_level])
KeyError: 3

# Fixed code
def json(self):
    """Custom JSON encoder"""
    attributes = {
        "type": self.type,
        "filename": self.filename,
        "line_number": self.lineno,
        "hashed_secret": self.secret_hash,
    }

    if self.is_secret is not None:
        attributes["is_secret"] = self.is_secret

    return attributes
# Buggy code
def __str__(self):  # pragma: no cover
    return (
        "Secret Type: %s\nLocation:    %s:%d\n"
        # "Hash:        %s\n"
    ) % (
        self.type,
        self.filename,
        self.lineno,
        # self.secret_hash
    )


# Traceback (KeyError)
Traceback (most recent call last):
File "/hey/three_six/bin/detect-secrets", line 11, in <module>
sys.exit(main())
File "/hey/three_six/lib/python3.6/site-packages/detect_secrets/main.py", line 27, in main
log.set_debug_level(args.verbose)
File "/hey/three_six/lib/python3.6/site-packages/detect_secrets/core/log.py", line 46, in _set_debug_level
self.setLevel(mapping[debug_level])
KeyError: 3

# Fixed code
def __str__(self):  # pragma: no cover
    return ("Secret Type: %s\nLocation:    %s:%d\n") % (
        self.type,
        self.filename,
        self.lineno,
    )