gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _query_select_options(self, query, select_columns=None):
    """
        Add select load options to query. The goal
        is to only SQL select what is requested

    :param query: SQLAlchemy Query obj
    :param select_columns: (list) of columns
    :return: SQLAlchemy Query obj
    """
    if select_columns:
        _load_options = list()
        for column in select_columns:
            if "." in column:
                model_relation = self.get_related_model(column.split(".")[0])
                if not self.is_model_already_joinded(query, model_relation):
                    query = query.join(model_relation)
                _load_options.append(
                    Load(model_relation).load_only(column.split(".")[1])
                )
            else:
                # is a custom property method field?
                if hasattr(getattr(self.obj, column), "fget"):
                    pass
                # is not a relation and not a function?
                elif not self.is_relation(column) and not hasattr(
                    getattr(self.obj, column), "__call__"
                ):
                    _load_options.append(Load(self.obj).load_only(column))
                else:
                    _load_options.append(Load(self.obj))
        query = query.options(*tuple(_load_options))
    return query


# Traceback (sqlalchemy.exc.AmbiguousForeignKeysError)
sqlalchemy.exc.AmbiguousForeignKeysError: Can't determine join between 'project' and 'ab_user'; tables have more than one foreign key constraint relationship between them. Please specify the 'onclause' of this join explicitly.

# Fixed code
def _query_select_options(self, query, select_columns=None):
    """
        Add select load options to query. The goal
        is to only SQL select what is requested

    :param query: SQLAlchemy Query obj
    :param select_columns: (list) of columns
    :return: SQLAlchemy Query obj
    """
    if select_columns:
        _load_options = list()
        for column in select_columns:
            query, relation_tuple = self._query_join_dotted_column(
                query,
                column,
            )
            model_relation, relation_join = relation_tuple or (None, None)
            if model_relation:
                _load_options.append(
                    Load(model_relation).load_only(column.split(".")[1])
                )
            else:
                # is a custom property method field?
                if hasattr(getattr(self.obj, column), "fget"):
                    pass
                # is not a relation and not a function?
                elif not self.is_relation(column) and not hasattr(
                    getattr(self.obj, column), "__call__"
                ):
                    _load_options.append(Load(self.obj).load_only(column))
                else:
                    _load_options.append(Load(self.obj))
        query = query.options(*tuple(_load_options))
    return query
# Buggy code
def query(
    self,
    filters=None,
    order_column="",
    order_direction="",
    page=None,
    page_size=None,
    select_columns=None,
):
    """
    QUERY
    :param filters:
        dict with filters {<col_name>:<value,...}
    :param order_column:
        name of the column to order
    :param order_direction:
        the direction to order <'asc'|'desc'>
    :param page:
        the current page
    :param page_size:
        the current page size

    """
    query = self.session.query(self.obj)
    query = self._query_select_options(query, select_columns)
    if len(order_column.split(".")) >= 2:
        for join_relation in order_column.split(".")[:-1]:
            relation_tuple = self.get_related_model_and_join(join_relation)
            model_relation, relation_join = relation_tuple
            if not self.is_model_already_joinded(query, model_relation):
                query = query.join(model_relation, relation_join, isouter=True)
    query_count = self.session.query(func.count("*")).select_from(self.obj)

    query_count = self._get_base_query(query=query_count, filters=filters)
    query = self._get_base_query(
        query=query,
        filters=filters,
        order_column=order_column,
        order_direction=order_direction,
    )

    count = query_count.scalar()

    if page:
        query = query.offset(page * page_size)
    if page_size:
        query = query.limit(page_size)
    return count, query.all()


# Traceback (sqlalchemy.exc.AmbiguousForeignKeysError)
sqlalchemy.exc.AmbiguousForeignKeysError: Can't determine join between 'project' and 'ab_user'; tables have more than one foreign key constraint relationship between them. Please specify the 'onclause' of this join explicitly.

# Fixed code
def query(
    self,
    filters=None,
    order_column="",
    order_direction="",
    page=None,
    page_size=None,
    select_columns=None,
):
    """
    QUERY
    :param filters:
        dict with filters {<col_name>:<value,...}
    :param order_column:
        name of the column to order
    :param order_direction:
        the direction to order <'asc'|'desc'>
    :param page:
        the current page
    :param page_size:
        the current page size

    """
    query = self.session.query(self.obj)
    query, relation_tuple = self._query_join_dotted_column(query, order_column)
    query = self._query_select_options(query, select_columns)
    query_count = self.session.query(func.count("*")).select_from(self.obj)

    query_count = self._get_base_query(query=query_count, filters=filters)
    query = self._get_base_query(
        query=query,
        filters=filters,
        order_column=order_column,
        order_direction=order_direction,
    )

    count = query_count.scalar()

    if page:
        query = query.offset(page * page_size)
    if page_size:
        query = query.limit(page_size)
    return count, query.all()
# Buggy code
def _get_base_query(
    self, query=None, filters=None, order_column="", order_direction=""
):
    if filters:
        query = filters.apply_all(query)
    if order_column != "":
        # if Model has custom decorator **renders('<COL_NAME>')**
        # this decorator will add a property to the method named *_col_name*
        if hasattr(self.obj, order_column):
            if hasattr(getattr(self.obj, order_column), "_col_name"):
                order_column = getattr(getattr(self.obj, order_column), "_col_name")
        query = query.order_by(order_column + " " + order_direction)
    return query


# Traceback (TypeError)
Sorry, something went wrong

500 - Internal Server Error

Stacktrace

Traceback (most recent call last):
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/security/decorators.py", line 26, in wraps
return f(self, *args, **kwargs)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/views.py", line 450, in list
widgets = self._list()
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py", line 870, in _list
page_size=page_size)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py", line 786, in _get_list_widget
count, lst = self.datamodel.query(joined_filters, order_column, order_direction, page=page, page_size=page_size)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py", line 103, in query
order_direction=order_direction)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py", line 67, in _get_base_query
query = query.order_by(order_column + ' ' + order_direction)
TypeError: coercing to Unicode: need string or buffer, NoneType found

# Fixed code
def _get_base_query(
    self, query=None, filters=None, order_column="", order_direction=""
):
    if filters:
        query = filters.apply_all(query)
    if order_column != "":
        # if Model has custom decorator **renders('<COL_NAME>')**
        # this decorator will add a property to the method named *_col_name*
        if hasattr(self.obj, order_column):
            if hasattr(getattr(self.obj, order_column), "_col_name"):
                order_column = getattr(getattr(self.obj, order_column), "_col_name")
        query = query.order_by("%s %s" % (order_column, order_direction))
    return query
# Buggy code
def get_order_args():
    """
    Get order arguments, return a dictionary
    { <VIEW_NAME>: (ORDER_COL, ORDER_DIRECTION) }

    Arguments are passed like: _oc_<VIEW_NAME>=<COL_NAME>&_od_<VIEW_NAME>='asc'|'desc'

    """
    orders = {}
    for arg in request.args:
        re_match = re.findall("_oc_(.*)", arg)
        if re_match:
            orders[re_match[0]] = (
                request.args.get(arg),
                request.args.get("_od_" + re_match[0]),
            )
    return orders


# Traceback (TypeError)
Sorry, something went wrong

500 - Internal Server Error

Stacktrace

Traceback (most recent call last):
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/security/decorators.py", line 26, in wraps
return f(self, *args, **kwargs)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/views.py", line 450, in list
widgets = self._list()
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py", line 870, in _list
page_size=page_size)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py", line 786, in _get_list_widget
count, lst = self.datamodel.query(joined_filters, order_column, order_direction, page=page, page_size=page_size)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py", line 103, in query
order_direction=order_direction)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py", line 67, in _get_base_query
query = query.order_by(order_column + ' ' + order_direction)
TypeError: coercing to Unicode: need string or buffer, NoneType found

# Fixed code
def get_order_args():
    """
    Get order arguments, return a dictionary
    { <VIEW_NAME>: (ORDER_COL, ORDER_DIRECTION) }

    Arguments are passed like: _oc_<VIEW_NAME>=<COL_NAME>&_od_<VIEW_NAME>='asc'|'desc'

    """
    orders = {}
    for arg in request.args:
        re_match = re.findall("_oc_(.*)", arg)
        if re_match:
            order_direction = request.args.get("_od_" + re_match[0])
            if order_direction in ("asc", "desc"):
                orders[re_match[0]] = (request.args.get(arg), order_direction)
    return orders
# Buggy code
def _get_attr_value(self, item, col):
    if not hasattr(item, col):
        # it's an inner obj attr
        try:
            return reduce(getattr, col.split("."), item)
        except Exception as e:
            return ""
    if hasattr(getattr(item, col), "__call__"):
        # its a function
        return getattr(item, col)()
    else:
        # its an attribute
        value = getattr(item, col)
        # if value is an Enum instance than list and show widgets should display
        # its .value rather than its .name:
        if _has_enum and isinstance(value, enum.Enum):
            return value.value
        return value


# Traceback (TypeError)
Sorry, something went wrong

500 - Internal Server Error

Stacktrace

Traceback (most recent call last):
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/security/decorators.py", line 26, in wraps
return f(self, *args, **kwargs)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/views.py", line 450, in list
widgets = self._list()
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py", line 870, in _list
page_size=page_size)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py", line 786, in _get_list_widget
count, lst = self.datamodel.query(joined_filters, order_column, order_direction, page=page, page_size=page_size)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py", line 103, in query
order_direction=order_direction)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py", line 67, in _get_base_query
query = query.order_by(order_column + ' ' + order_direction)
TypeError: coercing to Unicode: need string or buffer, NoneType found

# Fixed code
def _get_attr_value(item, col):
    if not hasattr(item, col):
        # it's an inner obj attr
        try:
            return reduce(getattr, col.split("."), item)
        except Exception as e:
            return ""
    if hasattr(getattr(item, col), "__call__"):
        # its a function
        return getattr(item, col)()
    else:
        # its an attribute
        value = getattr(item, col)
        # if value is an Enum instance than list and show widgets should display
        # its .value rather than its .name:
        if _has_enum and isinstance(value, enum.Enum):
            return value.value
        return value
# Buggy code
def _get_probs(self, qc: QuantumCircuit) -> Dict[str, float]:
    """Gets probabilities from a given backend."""
    # Execute job and filter results.
    result = self.quantum_instance.execute(qc)
    if self.quantum_instance.is_statevector:
        state = np.round(result.get_statevector(qc), 5)
        keys = [
            bin(i)[2::].rjust(int(np.log2(len(state))), "0")[::-1]
            for i in range(0, len(state))
        ]
        probs = [np.round(abs(a) * abs(a), 5) for a in state]
        hist = dict(zip(keys, probs))
    else:
        state = result.get_counts(qc)
        shots = self.quantum_instance.run_config.shots
        hist = {}
        for key in state:
            hist[key] = state[key] / shots
    hist = dict(filter(lambda p: p[1] > 0, hist.items()))

    return hist


# Traceback (IndexError)
No classical registers in circuit "circuit9", counts will be empty.
Traceback (most recent call last):
File "scratch.py", line 101, in <module>
results = grover_optimizer.solve(qp)
File "/home/will/miniconda3/envs/dev/lib/python3.8/site-packages/qiskit/optimization/algorithms/grover_optimizer.py", line 218, in solve
outcome = self._measure(circuit)
File "/home/will/miniconda3/envs/dev/lib/python3.8/site-packages/qiskit/optimization/algorithms/grover_optimizer.py", line 283, in _measure
freq[-1] = (freq[-1][0], 1.0 - sum(x[1] for x in freq[0:len(freq) - 1]))
IndexError: list index out of range

# Fixed code
def _get_probs(self, qc: QuantumCircuit) -> Dict[str, float]:
    """Gets probabilities from a given backend."""
    # Execute job and filter results.
    result = self.quantum_instance.execute(qc)
    if self.quantum_instance.is_statevector:
        state = np.round(result.get_statevector(qc), 5)
        keys = [
            bin(i)[2::].rjust(int(np.log2(len(state))), "0")[::-1]
            for i in range(0, len(state))
        ]
        probs = [np.round(abs(a) * abs(a), 5) for a in state]
        hist = dict(zip(keys, probs))
    else:
        state = result.get_counts(qc)
        shots = self.quantum_instance.run_config.shots
        hist = {}
        for key in state:
            hist[key[::-1]] = state[key] / shots
    hist = dict(filter(lambda p: p[1] > 0, hist.items()))
    return hist
# Buggy code
def _find_strongest_correlation(self, correlations):
    m_max = np.argmax(np.abs(correlations.flatten()))
    i = int(m_max // len(correlations))
    j = int(m_max - i * len(correlations))
    return (i, j)


# Traceback (QiskitOptimizationError)
------------------
rqaoa_result = rqaoa.solve(qubo)
print(rqaoa_result)
------------------

---------------------------------------------------------------------------
QiskitOptimizationError                   Traceback (most recent call last)
<ipython-input-11-6852684b0186> in <module>
----> 1 rqaoa_result = rqaoa.solve(qubo)
2 print(rqaoa_result)

/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/algorithms/recursive_minimum_eigen_optimizer.py in solve(self, problem)
171
172                 # 2. replace x_i by -x_j
--> 173                 problem_ = problem_.substitute_variables(variables={i: (j, -1)})
174                 if problem_.status == QuadraticProgram.Status.INFEASIBLE:
175                     raise QiskitOptimizationError('Infeasible due to variable substitution')

/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in substitute_variables(self, constants, variables)
856                 - Coefficient of variable substitution is zero.
857         """
--> 858         return SubstituteVariables().substitute_variables(self, constants, variables)
859
860

/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in substitute_variables(self, src, constants, variables)
901         self._src = src
902         self._dst = QuadraticProgram(src.name)
--> 903         self._subs_dict(constants, variables)
904         results = [
905             self._variables(),

/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in _subs_dict(self, constants, variables)
960                 j_2 = self._src.get_variable(j).name
961                 if i_2 == j_2:
--> 962                     raise QiskitOptimizationError(
963                         'Cannot substitute the same variable: {} <- {} {}'.format(i, j, v))
964                 if i_2 in subs:

QiskitOptimizationError: 'Cannot substitute the same variable: 0 <- 0 -1'
QiskitOptimizationError: 'Cannot substitute the same variable: 0 <- 0 -1'

# Fixed code
def _find_strongest_correlation(self, correlations):
    # get absolute values and set diagonal to -1 to make sure maximum is always on off-diagonal
    abs_correlations = np.abs(correlations)
    for i in range(len(correlations)):
        abs_correlations[i, i] = -1

    # get index of maximum (by construction on off-diagonal)
    m_max = np.argmax(abs_correlations.flatten())

    # translate back to indices
    i = int(m_max // len(correlations))
    j = int(m_max - i * len(correlations))
    return (i, j)
# Buggy code
def builder():
    log.info("Building documentation...")
    config = load_config(
        config_file=config_file,
        dev_addr=dev_addr,
        strict=strict,
        theme=theme,
        theme_dir=theme_dir,
    )
    # Override a few config settings after validation
    config["site_dir"] = tempdir
    config["site_url"] = "http://{0}/".format(config["dev_addr"])

    live_server = livereload in ["dirty", "livereload"]
    dirty = livereload == "dirty"
    build(config, live_server=live_server, dirty=dirty)
    return config


# Traceback (UnicodeDecodeError)
Exception in callback <bound method type.poll_tasks of <class 'livereload.handlers.LiveReloadHandler'>>
Traceback (most recent call last):
File "/Users/waylan/VirtualEnvs/mkdocs/lib/python2.7/site-packages/tornado/ioloop.py", line 1209, in _run
return self.callback()
File "/Users/waylan/VirtualEnvs/mkdocs/lib/python2.7/site-packages/livereload/handlers.py", line 67, in poll_tasks
filepath, delay = cls.watcher.examine()
File "/Users/waylan/VirtualEnvs/mkdocs/lib/python2.7/site-packages/livereload/watcher.py", line 73, in examine
func and func()
File "/Users/waylan/Code/mkdocs/mkdocs/commands/serve.py", line 112, in builder
build(config, live_server=live_server, dirty=dirty)
File "/Users/waylan/Code/mkdocs/mkdocs/commands/build.py", line 265, in build
utils.clean_directory(config['site_dir'])
File "/Users/waylan/Code/mkdocs/mkdocs/utils/__init__.py", line 144, in clean_directory
if entry.startswith('.'):
UnicodeDecodeError: 'ascii' codec can't decode byte 0xcc in position 1: ordinal not in range(128)

# Fixed code
def builder():
    log.info("Building documentation...")
    config = load_config(
        config_file=config_file,
        dev_addr=dev_addr,
        strict=strict,
        theme=theme,
        theme_dir=theme_dir,
        site_dir=site_dir,
    )
    # Override a few config settings after validation
    config["site_url"] = "http://{0}/".format(config["dev_addr"])

    live_server = livereload in ["dirty", "livereload"]
    dirty = livereload == "dirty"
    build(config, live_server=live_server, dirty=dirty)
    return config
# Buggy code
def _static_server(host, port, site_dir):
    # Importing here to seperate the code paths from the --livereload
    # alternative.
    from tornado import ioloop
    from tornado import web

    application = web.Application(
        [
            (
                r"/(.*)",
                _get_handler(site_dir, web.StaticFileHandler),
                {"path": site_dir, "default_filename": "index.html"},
            ),
        ]
    )
    application.listen(port=int(port), address=host)

    log.info("Running at: http://%s:%s/", host, port)
    log.info("Hold ctrl+c to quit.")
    try:
        ioloop.IOLoop.instance().start()
    except KeyboardInterrupt:
        log.info("Stopping server...")


# Traceback (ValueError)
INFO    -  Building documentation...
INFO    -  Cleaning site directory
Traceback (most recent call last):
File "/home/sybren/.virtualenvs/flamenco/bin/mkdocs", line 11, in <module>
sys.exit(cli())
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py", line 722, in __call__
return self.main(*args, **kwargs)
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py", line 697, in main
rv = self.invoke(ctx)
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py", line 535, in invoke
return callback(*args, **kwargs)
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/__main__.py", line 127, in serve_command
livereload=livereload
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/commands/serve.py", line 116, in serve
_livereload(host, port, config, builder, tempdir)
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/commands/serve.py", line 55, in _livereload
server.serve(root=site_dir, host=host, port=int(port), restart_delay=0)
ValueError: invalid literal for int() with base 10: ':0]:8081'

# Fixed code
def _static_server(host, port, site_dir):
    # Importing here to seperate the code paths from the --livereload
    # alternative.
    from tornado import ioloop
    from tornado import web

    application = web.Application(
        [
            (
                r"/(.*)",
                _get_handler(site_dir, web.StaticFileHandler),
                {"path": site_dir, "default_filename": "index.html"},
            ),
        ]
    )
    application.listen(port=port, address=host)

    log.info("Running at: http://%s:%s/", host, port)
    log.info("Hold ctrl+c to quit.")
    try:
        ioloop.IOLoop.instance().start()
    except KeyboardInterrupt:
        log.info("Stopping server...")
# Buggy code
def try_rebase(remote, branch):
    cmd = ["git", "rev-list", "--max-count=1", "%s/%s" % (remote, branch)]
    p = sp.Popen(cmd, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)
    (rev, _) = p.communicate()
    if p.wait() != 0:
        return True
    cmd = ["git", "update-ref", "refs/heads/%s" % branch, rev.strip()]
    if sp.call(cmd) != 0:
        return False
    return True


# Traceback (TypeError)
c:\docs>mkdocs gh-deploy --clean
INFO    -  Cleaning site directory
INFO    -  Building documentation to directory: c:\docs\site
INFO    -  Copying 'c:\docs\site' to 'gh-pages' branch and pushing to GitHub.
Traceback (most recent call last):
File "C:\Python34\lib\runpy.py", line 170, in _run_module_as_main
"__main__", mod_spec)
File "C:\Python34\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "c:\Python34\Scripts\mkdocs.exe\__main__.py", line 9, in <module>
File "C:\Python34\lib\site-packages\click\core.py", line 664, in __call__
return self.main(*args, **kwargs)
File "C:\Python34\lib\site-packages\click\core.py", line 644, in main
rv = self.invoke(ctx)
File "C:\Python34\lib\site-packages\click\core.py", line 991, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "C:\Python34\lib\site-packages\click\core.py", line 837, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "C:\Python34\lib\site-packages\click\core.py", line 464, in invoke
return callback(*args, **kwargs)
File "C:\Python34\lib\site-packages\mkdocs\cli.py", line 186, in gh_deploy_command
gh_deploy.gh_deploy(config, message=message)
File "C:\Python34\lib\site-packages\mkdocs\gh_deploy.py", line 69, in gh_deploy
remote_branch)
File "C:\Python34\lib\site-packages\mkdocs\utils\ghp_import.py", line 163, in ghp_import
if not try_rebase(remote, branch):
File "C:\Python34\lib\site-packages\mkdocs\utils\ghp_import.py", line 78, in try_rebase
if sp.call(cmd) != 0:
File "C:\Python34\lib\subprocess.py", line 537, in call
with Popen(*popenargs, **kwargs) as p:
File "C:\Python34\lib\subprocess.py", line 859, in __init__
restore_signals, start_new_session)
File "C:\Python34\lib\subprocess.py", line 1086, in _execute_child
args = list2cmdline(args)
File "C:\Python34\lib\subprocess.py", line 663, in list2cmdline
needquote = (" " in arg) or ("\t" in arg) or not arg
TypeError: 'str' does not support the buffer interface

# Fixed code
def try_rebase(remote, branch):
    cmd = ["git", "rev-list", "--max-count=1", "%s/%s" % (remote, branch)]
    p = sp.Popen(cmd, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)
    (rev, _) = p.communicate()
    if p.wait() != 0:
        return True
    cmd = ["git", "update-ref", "refs/heads/%s" % branch, dec(rev.strip())]
    if sp.call(cmd) != 0:
        return False
    return True
# Buggy code
def walk_docs_dir(self, docs_dir):
    if self.file_match is None:
        raise StopIteration

    for dirpath, dirs, filenames in os.walk(docs_dir):
        dirs.sort()
        for filename in sorted(filenames):
            fullpath = os.path.join(dirpath, filename)
            relpath = os.path.normpath(os.path.relpath(fullpath, docs_dir))
            if self.file_match(relpath):
                yield relpath


# Traceback (IOError)
INFO    -  Building documentation...
ERROR   -  file not found: /home/paulproteus/projects/sandstorm/docs/.#index.md
ERROR   -  Error building page .#index.md
[E 150617 17:22:21 ioloop:612] Exception in callback (3, <function null_wrapper at 0x7fc883190500>)
Traceback (most recent call last):
File "/home/paulproteus/.local/lib/python2.7/site-packages/tornado/ioloop.py", line 866, in start
handler_func(fd_obj, events)
File "/home/paulproteus/.local/lib/python2.7/site-packages/tornado/stack_context.py", line 275, in null_wrapper
return fn(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/pyinotify.py", line 1604, in handle_read
self.process_events()
File "/usr/lib/python2.7/dist-packages/pyinotify.py", line 1321, in process_events
self._default_proc_fun(revent)
File "/home/paulproteus/.local/lib/python2.7/site-packages/livereload/watcher.py", line 152, in inotify_event
self.callback()
File "/home/paulproteus/.local/lib/python2.7/site-packages/livereload/handlers.py", line 65, in poll_tasks
filepath, delay = cls.watcher.examine()
File "/home/paulproteus/.local/lib/python2.7/site-packages/livereload/watcher.py", line 72, in examine
func and func()
File "/usr/lib/python2.7/dist-packages/mkdocs/serve.py", line 74, in builder
build(config, live_server=True)
File "/usr/lib/python2.7/dist-packages/mkdocs/build.py", line 299, in build
build_pages(config)
File "/usr/lib/python2.7/dist-packages/mkdocs/build.py", line 259, in build_pages
dump_json)
File "/usr/lib/python2.7/dist-packages/mkdocs/build.py", line 171, in _build_page
input_content = io.open(input_path, 'r', encoding='utf-8').read()
IOError: [Errno 2] No such file or directory: '/home/paulproteus/projects/sandstorm/docs/.#index.md'

# Fixed code
def walk_docs_dir(self, docs_dir):
    if self.file_match is None:
        raise StopIteration

    for dirpath, dirs, filenames in os.walk(docs_dir):
        dirs.sort()
        for filename in sorted(filenames):
            fullpath = os.path.join(dirpath, filename)

            # Some editors (namely Emacs) will create temporary symlinks
            # for internal magic. We can just ignore these files.
            if os.path.islink(fullpath):
                if not os.path.exists(os.readlink(fullpath)):
                    continue

            relpath = os.path.normpath(os.path.relpath(fullpath, docs_dir))
            if self.file_match(relpath):
                yield relpath
# Buggy code
def walk_docs_dir(self, docs_dir):
    if self.file_match is None:
        raise StopIteration

    for dirpath, dirs, filenames in os.walk(docs_dir):
        dirs.sort()
        for filename in sorted(filenames):
            fullpath = os.path.join(dirpath, filename)

            # Some editors (namely Emacs) will create temporary symlinks
            # for internal magic. We can just ignore these files.
            if os.path.islink(fullpath):
                if not os.path.exists(os.readlink(fullpath)):
                    continue

            relpath = os.path.normpath(os.path.relpath(fullpath, docs_dir))
            if self.file_match(relpath):
                yield relpath


# Traceback (IOError)
INFO    -  Building documentation...
ERROR   -  file not found: /home/paulproteus/projects/sandstorm/docs/.#index.md
ERROR   -  Error building page .#index.md
[E 150617 17:22:21 ioloop:612] Exception in callback (3, <function null_wrapper at 0x7fc883190500>)
Traceback (most recent call last):
File "/home/paulproteus/.local/lib/python2.7/site-packages/tornado/ioloop.py", line 866, in start
handler_func(fd_obj, events)
File "/home/paulproteus/.local/lib/python2.7/site-packages/tornado/stack_context.py", line 275, in null_wrapper
return fn(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/pyinotify.py", line 1604, in handle_read
self.process_events()
File "/usr/lib/python2.7/dist-packages/pyinotify.py", line 1321, in process_events
self._default_proc_fun(revent)
File "/home/paulproteus/.local/lib/python2.7/site-packages/livereload/watcher.py", line 152, in inotify_event
self.callback()
File "/home/paulproteus/.local/lib/python2.7/site-packages/livereload/handlers.py", line 65, in poll_tasks
filepath, delay = cls.watcher.examine()
File "/home/paulproteus/.local/lib/python2.7/site-packages/livereload/watcher.py", line 72, in examine
func and func()
File "/usr/lib/python2.7/dist-packages/mkdocs/serve.py", line 74, in builder
build(config, live_server=True)
File "/usr/lib/python2.7/dist-packages/mkdocs/build.py", line 299, in build
build_pages(config)
File "/usr/lib/python2.7/dist-packages/mkdocs/build.py", line 259, in build_pages
dump_json)
File "/usr/lib/python2.7/dist-packages/mkdocs/build.py", line 171, in _build_page
input_content = io.open(input_path, 'r', encoding='utf-8').read()
IOError: [Errno 2] No such file or directory: '/home/paulproteus/projects/sandstorm/docs/.#index.md'

# Fixed code
def walk_docs_dir(self, docs_dir):
    if self.file_match is None:
        raise StopIteration

    for dirpath, dirs, filenames in os.walk(docs_dir):
        dirs.sort()
        for filename in sorted(filenames):
            fullpath = os.path.join(dirpath, filename)

            # Some editors (namely Emacs) will create temporary symlinks
            # for internal magic. We can just ignore these files.
            if os.path.islink(fullpath):
                fp = os.path.join(dirpath, os.readlink(fullpath))
                if not os.path.exists(fp):
                    continue

            relpath = os.path.normpath(os.path.relpath(fullpath, docs_dir))
            if self.file_match(relpath):
                yield relpath
# Buggy code
def __init__(self, file_match, **kwargs):
    super(Extras, self).__init__(**kwargs)
    self.file_match = file_match


# Traceback (TypeError)
Traceback (most recent call last):
File "/srv/mkdocs_head/bin/mkdocs", line 9, in <module>
load_entry_point('mkdocs==0.14.0.dev', 'console_scripts', 'mkdocs')()
File "/srv/mkdocs_head/local/lib/python2.7/site-packages/click/core.py", line 664, in __call__
return self.main(*args, **kwargs)
File "/srv/mkdocs_head/local/lib/python2.7/site-packages/click/core.py", line 644, in main
rv = self.invoke(ctx)
File "/srv/mkdocs_head/local/lib/python2.7/site-packages/click/core.py", line 991, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/srv/mkdocs_head/local/lib/python2.7/site-packages/click/core.py", line 837, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/srv/mkdocs_head/local/lib/python2.7/site-packages/click/core.py", line 464, in invoke
return callback(*args, **kwargs)
File "/home/zmousm/mkdocs/mkdocs/cli.py", line 134, in build_command
), clean_site_dir=clean)
File "/home/zmousm/mkdocs/mkdocs/build.py", line 299, in build
build_pages(config)
File "/home/zmousm/mkdocs/mkdocs/build.py", line 252, in build_pages
build_extra_templates(config['extra_templates'], config, site_navigation)
File "/home/zmousm/mkdocs/mkdocs/build.py", line 230, in build_extra_templates
output_content = template.render(context)
File "/srv/mkdocs_head/local/lib/python2.7/site-packages/jinja2/environment.py", line 969, in render
return self.environment.handle_exception(exc_info, True)
File "/srv/mkdocs_head/local/lib/python2.7/site-packages/jinja2/environment.py", line 742, in handle_exception
reraise(exc_type, exc_value, tb)
File "<template>", line 44, in top-level template code
TypeError: no loader for this environment specified

# Fixed code
def __init__(self, file_match=None, **kwargs):
    super(Extras, self).__init__(**kwargs)
    self.file_match = file_match
# Buggy code
def walk_docs_dir(self, docs_dir):
    for dirpath, _, filenames in os.walk(docs_dir):
        for filename in sorted(filenames):
            fullpath = os.path.join(dirpath, filename)
            relpath = os.path.normpath(os.path.relpath(fullpath, docs_dir))
            if self.file_match(relpath):
                yield relpath


# Traceback (TypeError)
Traceback (most recent call last):
File "/srv/mkdocs_head/bin/mkdocs", line 9, in <module>
load_entry_point('mkdocs==0.14.0.dev', 'console_scripts', 'mkdocs')()
File "/srv/mkdocs_head/local/lib/python2.7/site-packages/click/core.py", line 664, in __call__
return self.main(*args, **kwargs)
File "/srv/mkdocs_head/local/lib/python2.7/site-packages/click/core.py", line 644, in main
rv = self.invoke(ctx)
File "/srv/mkdocs_head/local/lib/python2.7/site-packages/click/core.py", line 991, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/srv/mkdocs_head/local/lib/python2.7/site-packages/click/core.py", line 837, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/srv/mkdocs_head/local/lib/python2.7/site-packages/click/core.py", line 464, in invoke
return callback(*args, **kwargs)
File "/home/zmousm/mkdocs/mkdocs/cli.py", line 134, in build_command
), clean_site_dir=clean)
File "/home/zmousm/mkdocs/mkdocs/build.py", line 299, in build
build_pages(config)
File "/home/zmousm/mkdocs/mkdocs/build.py", line 252, in build_pages
build_extra_templates(config['extra_templates'], config, site_navigation)
File "/home/zmousm/mkdocs/mkdocs/build.py", line 230, in build_extra_templates
output_content = template.render(context)
File "/srv/mkdocs_head/local/lib/python2.7/site-packages/jinja2/environment.py", line 969, in render
return self.environment.handle_exception(exc_info, True)
File "/srv/mkdocs_head/local/lib/python2.7/site-packages/jinja2/environment.py", line 742, in handle_exception
reraise(exc_type, exc_value, tb)
File "<template>", line 44, in top-level template code
TypeError: no loader for this environment specified

# Fixed code
def walk_docs_dir(self, docs_dir):
    if self.file_match is None:
        raise StopIteration

    for dirpath, _, filenames in os.walk(docs_dir):
        for filename in sorted(filenames):
            fullpath = os.path.join(dirpath, filename)
            relpath = os.path.normpath(os.path.relpath(fullpath, docs_dir))
            if self.file_match(relpath):
                yield relpath
# Buggy code
def load_config(filename="mkdocs.yml", options=None):
    options = options or {}
    if "config" in options:
        filename = options["config"]
    if not os.path.exists(filename):
        raise ConfigurationError("Config file '%s' does not exist." % filename)
    with open(filename, "r") as fp:
        user_config = yaml.load(fp)
    user_config.update(options)
    return validate_config(user_config)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/dougalmatthews/.virtualenvs/mkdocs/bin/mkdocs", line 9, in <module>
load_entry_point('mkdocs==0.11.1', 'console_scripts', 'mkdocs')()
File "/home/dougalmatthews/.virtualenvs/mkdocs/lib/python3.4/site-packages/mkdocs/main.py", line 60, in run_main
main(cmd, args=sys.argv[2:], options=dict(opts))
File "/home/dougalmatthews/.virtualenvs/mkdocs/lib/python3.4/site-packages/mkdocs/main.py", line 32, in main
config = load_config(options=options)
File "/home/dougalmatthews/.virtualenvs/mkdocs/lib/python3.4/site-packages/mkdocs/config.py", line 82, in load_config
user_config.update(options)
AttributeError: 'NoneType' object has no attribute 'update'

# Fixed code
def load_config(filename="mkdocs.yml", options=None):
    user_config = options or {}
    if "config" in user_config:
        filename = user_config.pop("config")
    if not os.path.exists(filename):
        raise ConfigurationError("Config file '%s' does not exist." % filename)
    with open(filename, "r") as fp:
        local_config = yaml.load(fp)
    if local_config:
        user_config.update(local_config)
    return validate_config(user_config)
# Buggy code
def base(
    net: network.TensorNetwork,
    algorithm: Callable[[List[Set[int]], Set[int], Dict[int, int]], List],
) -> network.TensorNetwork:
    """Base method for all `opt_einsum` contractors.

    Args:
      net: a TensorNetwork object. Should be connected.
      algorithm: `opt_einsum` contraction method to use.

    Returns:
      The network after full contraction.
    """
    net.check_connected()
    # First contract all trace edges
    edges = net.get_all_nondangling()
    for edge in edges:
        if edge in net and edge.is_trace():
            net.contract_parallel(edge)

    # Then apply `opt_einsum`'s algorithm
    nodes = sorted(net.nodes_set)
    input_sets = utils.get_input_sets(net)
    output_set = utils.get_output_set(net)
    size_dict = utils.get_size_dict(net)
    path = algorithm(input_sets, output_set, size_dict)
    for a, b in path:
        new_node = nodes[a] @ nodes[b]
        nodes.append(new_node)
        nodes = utils.multi_remove(nodes, [a, b])
    return net


# Traceback (ValueError)
Traceback (most recent call last):
File "check.py", line 8, in <module>
node = tensornetwork.contractors.optimal(net).get_final_node()
File "/usr/local/google/home/chaseriley/TensorNetwork/tensornetwork/contractors/opt_einsum_paths/path_contractors.py", line 59, in optimal
return base(net, alg)
File "/usr/local/google/home/chaseriley/TensorNetwork/tensornetwork/contractors/opt_einsum_paths/path_contractors.py", line 34, in base
path = algorithm(input_sets, output_set, size_dict)
File "/usr/local/google/home/chaseriley/.local/lib/python3.6/site-packages/opt_einsum/paths.py", line 196, in optimal
return ssa_to_linear(best['path'])
File "/usr/local/google/home/chaseriley/.local/lib/python3.6/site-packages/opt_einsum/paths.py", line 28, in ssa_to_linear
ids = np.arange(1 + max(map(max, ssa_path)), dtype=np.int32)
ValueError: max() arg is an empty sequence

# Fixed code
def base(
    net: network.TensorNetwork,
    algorithm: Callable[[List[Set[int]], Set[int], Dict[int, int]], List],
) -> network.TensorNetwork:
    """Base method for all `opt_einsum` contractors.

    Args:
      net: a TensorNetwork object. Should be connected.
      algorithm: `opt_einsum` contraction method to use.

    Returns:
      The network after full contraction.
    """
    net.check_connected()
    # First contract all trace edges
    edges = net.get_all_nondangling()
    for edge in edges:
        if edge in net and edge.is_trace():
            net.contract_parallel(edge)
    if not net.get_all_nondangling():
        # There's nothing to contract.
        return net

    # Then apply `opt_einsum`'s algorithm
    nodes = sorted(net.nodes_set)
    input_sets = utils.get_input_sets(net)
    output_set = utils.get_output_set(net)
    size_dict = utils.get_size_dict(net)
    path = algorithm(input_sets, output_set, size_dict)
    for a, b in path:
        new_node = nodes[a] @ nodes[b]
        nodes.append(new_node)
        nodes = utils.multi_remove(nodes, [a, b])
    return net
# Buggy code
def __str__(self):
    """String representation of an input/output system"""
    str = "System: " + (self.name if self.name else "(none)") + "\n"
    str += "Inputs (%d): " % self.ninputs
    for key in self.input_index:
        str += key + ", "
    str += "\nOutputs (%d): " % self.noutputs
    for key in self.output_index:
        str += key + ", "
    str += "\nStates (%d): " % self.nstates
    for key in self.state_index:
        str += key + ", "
    return str


# Traceback (TypeError)
sys = ctl.NonlinearIOSystem(lambda t, x, u, params: x)
print(sys)

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-85c64df40808> in <module>()
----> 1 print(sys)

/home/arnold/pythonBox/control_dev/python-control-rabraker/control/iosys.py in __str__(self)
214         """String representation of an input/output system"""
215         str = "System: " + (self.name if self.name else "(none)") + "\n"
--> 216         str += "Inputs (%d): " % self.ninputs
217         for key in self.input_index: str += key + ", "
218         str += "\nOutputs (%d): " % self.noutputs

TypeError: %d format: a number is required, not NoneType

# Fixed code
def __str__(self):
    """String representation of an input/output system"""
    str = "System: " + (self.name if self.name else "(None)") + "\n"
    str += "Inputs (%s): " % self.ninputs
    for key in self.input_index:
        str += key + ", "
    str += "\nOutputs (%s): " % self.noutputs
    for key in self.output_index:
        str += key + ", "
    str += "\nStates (%s): " % self.nstates
    for key in self.state_index:
        str += key + ", "
    return str
# Buggy code
def setup_static_dir():
    build_dir = os.path.join(
        os.path.dirname(os.path.abspath(__file__)), "client", "build"
    )
    module_name = os.path.basename(os.path.dirname(__file__))
    if not os.path.isdir(build_dir):
        raise OSError(
            errno.ENOENT,
            "Dashboard build directory not found. If installing "
            "from source, please follow the additional steps "
            "required to build the dashboard"
            f"(cd python/ray/{module_name}/client "
            "&& npm install "
            "&& npm ci "
            "&& npm run build)",
            build_dir,
        )

    static_dir = os.path.join(build_dir, "static")
    routes.static("/static", static_dir, follow_symlinks=True)
    return build_dir


# Traceback (OSError)
2021-01-07 03:57:35,395	WARNING worker.py:1044 -- The dashboard on node travis-job-a2c3f054-a588-45a5-b10a-2456ba486c28 failed with the following error:
Traceback (most recent call last):
File "/opt/miniconda/lib/python3.6/asyncio/base_events.py", line 1073, in create_server
sock.bind(sa)
OSError: [Errno 98] Address already in use
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/travis/build/ray-project/ray/python/ray/new_dashboard/dashboard.py", line 197, in <module>
loop.run_until_complete(dashboard.run())
File "/opt/miniconda/lib/python3.6/asyncio/base_events.py", line 488, in run_until_complete
return future.result()
File "/home/travis/build/ray-project/ray/python/ray/new_dashboard/dashboard.py", line 100, in run
await self.dashboard_head.run()
File "/home/travis/build/ray-project/ray/python/ray/new_dashboard/head.py", line 220, in run
*(m.run(self.server) for m in modules))
File "/opt/miniconda/lib/python3.6/site-packages/aiohttp/web.py", line 369, in _run_app
await site.start()
File "/opt/miniconda/lib/python3.6/site-packages/aiohttp/web_runner.py", line 103, in start
reuse_port=self._reuse_port)
File "/opt/miniconda/lib/python3.6/asyncio/base_events.py", line 1077, in create_server
% (sa, err.strerror.lower()))
OSError: [Errno 98] error while attempting to bind on address ('127.0.0.1', 8265): address already in use

# Fixed code
def setup_static_dir():
    build_dir = os.path.join(
        os.path.dirname(os.path.abspath(__file__)), "client", "build"
    )
    module_name = os.path.basename(os.path.dirname(__file__))
    if not os.path.isdir(build_dir):
        raise FrontendNotFoundError(
            errno.ENOENT,
            "Dashboard build directory not found. If installing "
            "from source, please follow the additional steps "
            "required to build the dashboard"
            f"(cd python/ray/{module_name}/client "
            "&& npm install "
            "&& npm ci "
            "&& npm run build)",
            build_dir,
        )

    static_dir = os.path.join(build_dir, "static")
    routes.static("/static", static_dir, follow_symlinks=True)
    return build_dir