gurudesh/pytracebugs huggingface dataset:
# Buggy code
def execute(self, context):
    emr = EmrHook(aws_conn_id=self.aws_conn_id).get_conn()

    job_flow_id = self.job_flow_id

    if not job_flow_id:
        job_flow_id = emr.get_cluster_id_by_name(
            self.job_flow_name, self.cluster_states
        )

    if self.do_xcom_push:
        context["ti"].xcom_push(key="job_flow_id", value=job_flow_id)

    self.log.info("Adding steps to %s", job_flow_id)
    response = emr.add_job_flow_steps(JobFlowId=job_flow_id, Steps=self.steps)

    if not response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        raise AirflowException("Adding steps failed: %s" % response)
    else:
        self.log.info("Steps %s added to JobFlow", response["StepIds"])
        return response["StepIds"]


# Traceback (AttributeError)
[2020-06-03 18:05:06,862] {taskinstance.py:1145} ERROR - 'EMR' object has no attribute 'get_cluster_id_by_name'
Traceback (most recent call last):
File "/home/ubuntu/.pyenv/versions/3.7.7/envs/.venv_python377/lib/python3.7/site-packages/airflow/models/taskinstance.py", line 983, in _run_raw_task
result = task_copy.execute(context=context)
File "/home/ubuntu/.pyenv/versions/3.7.7/envs/.venv_python377/lib/python3.7/site-packages/airflow/contrib/operators/emr_add_steps_operator.py", line 74, in execute
job_flow_id = emr.get_cluster_id_by_name(self.job_flow_name, self.cluster_states)
File "/home/ubuntu/.pyenv/versions/3.7.7/envs/.venv_python377/lib/python3.7/site-packages/botocore/client.py", line 575, in _getattr_
self._class.name_, item)
AttributeError: 'EMR' object has no attribute 'get_cluster_id_by_name'
[2020-06-03 18:05:06,864] {taskinstance.py:1202} INFO - Marking task as FAILED.dag_id=my_spark_job_dag_id, task_id=my_spark_job_emr_add_step_id, execution_date=20200603T180500, start_date=20200603T180506, end_date=20200603T180506
[2020-06-03 18:05:16,153] {logging_mixin.py:112} INFO - [2020-06-03 18:05:16,153] {local_task_job.py:103} INFO - Task exited with return code 1*

# Fixed code
def execute(self, context):
    emr_hook = EmrHook(aws_conn_id=self.aws_conn_id)

    emr = emr_hook.get_conn()

    job_flow_id = self.job_flow_id or emr_hook.get_cluster_id_by_name(
        self.job_flow_name, self.cluster_states
    )
    if not job_flow_id:
        raise AirflowException("No cluster found for name: " + self.job_flow_name)

    if self.do_xcom_push:
        context["ti"].xcom_push(key="job_flow_id", value=job_flow_id)

    self.log.info("Adding steps to %s", job_flow_id)
    response = emr.add_job_flow_steps(JobFlowId=job_flow_id, Steps=self.steps)

    if not response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        raise AirflowException("Adding steps failed: %s" % response)
    else:
        self.log.info("Steps %s added to JobFlow", response["StepIds"])
        return response["StepIds"]
# Buggy code
def factorial_notation(tokens, local_dict, global_dict):
    """Allows standard notation for factorial."""
    result = []
    prevtoken = ""
    for toknum, tokval in tokens:
        if toknum == OP:
            op = tokval

            if op == "!!":
                if prevtoken == "!" or prevtoken == "!!":
                    raise TokenError
                result = _add_factorial_tokens("factorial2", result)
            elif op == "!":
                if prevtoken == "!" or prevtoken == "!!":
                    raise TokenError
                result = _add_factorial_tokens("factorial", result)
            else:
                result.append((OP, op))
        else:
            result.append((toknum, tokval))

        prevtoken = tokval

    return result


# Traceback (SympifyError)
In [37]: S("α")
--------------------------------------------------------------------------
-
SympifyError                              Traceback (most recent call last)

/Users/aaronmeurer/Documents/Python/sympy/sympy/<ipython console> in <module>()

/Users/aaronmeurer/Documents/Python/sympy/sympy/sympy/core/sympify.pyc in sympify(a,
locals, convert_xor)
114             a = a.replace('^','**')
115         import ast_parser
--> 116         return ast_parser.parse_expr(a, locals)
117     raise SympifyError("%r is NOT a valid SymPy expression" % a)
118

/Users/aaronmeurer/Documents/Python/sympy/sympy/sympy/core/ast_parser.pyc in
parse_expr(s, local_dict)
89             a = parse(s.strip(), mode="eval")
90         except SyntaxError:
---> 91             raise SympifyError("Cannot parse.")
92         a = Transform(local_dict, global_dict).visit(a)
93         e = compile(a, "<string>", "eval")

SympifyError: SympifyError: Cannot parse.

sympify() should be able to parse greek letters, as they are pretty printed for symbols of that
name:

In [44]: alpha = Symbol('alpha')

In [45]: alpha
Out[45]: α

# Fixed code
def factorial_notation(tokens, local_dict, global_dict):
    """Allows standard notation for factorial."""
    result = []
    nfactorial = 0
    for toknum, tokval in tokens:
        if toknum == ERRORTOKEN:
            op = tokval
            if op == "!":
                nfactorial += 1
            else:
                nfactorial = 0
                result.append((OP, op))
        else:
            if nfactorial == 1:
                result = _add_factorial_tokens("factorial", result)
            elif nfactorial == 2:
                result = _add_factorial_tokens("factorial2", result)
            elif nfactorial > 2:
                raise TokenError
            nfactorial = 0
            result.append((toknum, tokval))
    return result
# Buggy code
def __pow__(self, other):
    return Pow(self, other)


# Traceback (TypeError)
According to http://docs.python.org/release/2.5.2/ref/numeric-types.html , __pow__ should define a third, optional argument to work with ternary pow().  We should do that for at least Integer, though it would be cool to do it for arbitrary expressions (this will require Mod from issue 5589 , and also some care to make sure that it still evaluates efficiently when values are substituted in).  Right now, we get:

In [1]: pow(S(2), S(3), S(5))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

/Users/aaronmeurer/Documents/python/sympy/sympy/<ipython console> in <module>()

TypeError: __sympifyit_wrapper() takes exactly 2 arguments (3 given)

# Fixed code
def __pow__(self, other, mod=None):
    if mod is None:
        return self._pow(other)
    try:
        _self, other, mod = as_int(self), as_int(other), as_int(mod)
        if other >= 0:
            return pow(_self, other, mod)
        else:
            from sympy.core.numbers import mod_inverse

            return mod_inverse(pow(_self, -other, mod), mod)
    except ValueError:
        power = self._pow(other)
        try:
            return power % mod
        except TypeError:
            return NotImplemented
# Buggy code
def make_args(cls, expr):
    """
    Return a sequence of elements `args` such that cls(*args) == expr

    >>> from sympy import Symbol, Mul, Add
    >>> x, y = map(Symbol, 'xy')

    >>> Mul.make_args(x*y)
    (x, y)
    >>> Add.make_args(x*y)
    (x*y,)
    >>> set(Add.make_args(x*y + y)) == set([y, x*y])
    True

    """
    if isinstance(expr, cls):
        return expr.args
    else:
        return (expr,)


# Traceback (TypeError)
Following function call generate an error in Python3 but work well in Python2.

factor_list(x*(x+y))

Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/thilinarmtb/GSoC/sympy/sympy/polys/polytools.py", line 5675, in factor_list
return _generic_factor_list(f, gens, args, method='factor')
File "/home/thilinarmtb/GSoC/sympy/sympy/polys/polytools.py", line 5423, in _generic_factor_list
fp = _sorted_factors(fp, method)
File "/home/thilinarmtb/GSoC/sympy/sympy/polys/polytools.py", line 5322, in _sorted_factors
return sorted(factors, key=key)
TypeError: unorderable types: list() < int()


Similarly following calls generate the same error:
[1] factor_list(y*(x+y)),  factor_list(x*y + y**2)
[2] factor_list(x*(x+y+z)), factor_list(x**2+x*y+x*z)
[3] factor_list((x + 1)*(x + y))

But the following don't:
[4] factor_list(x*(x**2 + y**2)), factor_list(x**3 + x*y**2)
[5] factor_list(x**3 - x),  factor_list(x*(x**2 - 1))
[6] factor_list(x**2 + x*y + x + y)
[7] factor_list((x + z)*(x + y)), factor_list(x**2 + x*z + y*x + y*z)

Here [6] is mathematically same as [3]. But only [3] gives the error.

# Fixed code
def make_args(cls, expr):
    """
    Return a sequence of elements `args` such that cls(*args) == expr

    >>> from sympy import Symbol, Mul, Add
    >>> x, y = map(Symbol, 'xy')

    >>> Mul.make_args(x*y)
    (x, y)
    >>> Add.make_args(x*y)
    (x*y,)
    >>> set(Add.make_args(x*y + y)) == set([y, x*y])
    True

    """
    if isinstance(expr, cls):
        return expr.args
    else:
        return (sympify(expr),)
# Buggy code
def make_args(cls, expr):
    """
    Return a sequence of elements `args` such that cls(*args) == expr

    >>> from sympy import Symbol, Mul, Add
    >>> x, y = map(Symbol, 'xy')

    >>> Mul.make_args(x*y)
    (x, y)
    >>> Add.make_args(x*y)
    (x*y,)
    >>> set(Add.make_args(x*y + y)) == set([y, x*y])
    True

    """
    if isinstance(expr, cls):
        return expr._argset
    else:
        return frozenset([expr])


# Traceback (TypeError)
Following function call generate an error in Python3 but work well in Python2.

factor_list(x*(x+y))

Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/thilinarmtb/GSoC/sympy/sympy/polys/polytools.py", line 5675, in factor_list
return _generic_factor_list(f, gens, args, method='factor')
File "/home/thilinarmtb/GSoC/sympy/sympy/polys/polytools.py", line 5423, in _generic_factor_list
fp = _sorted_factors(fp, method)
File "/home/thilinarmtb/GSoC/sympy/sympy/polys/polytools.py", line 5322, in _sorted_factors
return sorted(factors, key=key)
TypeError: unorderable types: list() < int()


Similarly following calls generate the same error:
[1] factor_list(y*(x+y)),  factor_list(x*y + y**2)
[2] factor_list(x*(x+y+z)), factor_list(x**2+x*y+x*z)
[3] factor_list((x + 1)*(x + y))

But the following don't:
[4] factor_list(x*(x**2 + y**2)), factor_list(x**3 + x*y**2)
[5] factor_list(x**3 - x),  factor_list(x*(x**2 - 1))
[6] factor_list(x**2 + x*y + x + y)
[7] factor_list((x + z)*(x + y)), factor_list(x**2 + x*z + y*x + y*z)

Here [6] is mathematically same as [3]. But only [3] gives the error.

# Fixed code
def make_args(cls, expr):
    """
    Return a set of args such that cls(*arg_set) == expr.
    """
    if isinstance(expr, cls):
        return expr._argset
    else:
        return frozenset([sympify(expr)])
# Buggy code
def _sorted_factors(factors, method):
    """Sort a list of ``(expr, exp)`` pairs."""
    if method == "sqf":

        def key(obj):
            poly, exp = obj
            rep = poly.rep.rep
            return (exp, len(rep), rep)
    else:

        def key(obj):
            poly, exp = obj
            rep = poly.rep.rep
            return (len(rep), exp, rep)

    return sorted(factors, key=key)


# Traceback (TypeError)
Following function call generate an error in Python3 but work well in Python2.

factor_list(x*(x+y))

Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/thilinarmtb/GSoC/sympy/sympy/polys/polytools.py", line 5675, in factor_list
return _generic_factor_list(f, gens, args, method='factor')
File "/home/thilinarmtb/GSoC/sympy/sympy/polys/polytools.py", line 5423, in _generic_factor_list
fp = _sorted_factors(fp, method)
File "/home/thilinarmtb/GSoC/sympy/sympy/polys/polytools.py", line 5322, in _sorted_factors
return sorted(factors, key=key)
TypeError: unorderable types: list() < int()


Similarly following calls generate the same error:
[1] factor_list(y*(x+y)),  factor_list(x*y + y**2)
[2] factor_list(x*(x+y+z)), factor_list(x**2+x*y+x*z)
[3] factor_list((x + 1)*(x + y))

But the following don't:
[4] factor_list(x*(x**2 + y**2)), factor_list(x**3 + x*y**2)
[5] factor_list(x**3 - x),  factor_list(x*(x**2 - 1))
[6] factor_list(x**2 + x*y + x + y)
[7] factor_list((x + z)*(x + y)), factor_list(x**2 + x*z + y*x + y*z)

Here [6] is mathematically same as [3]. But only [3] gives the error.

# Fixed code
def _sorted_factors(factors, method):
    """Sort a list of ``(expr, exp)`` pairs."""
    if method == "sqf":

        def key(obj):
            poly, exp = obj
            rep = poly.rep.rep
            return (exp, len(rep), len(poly.gens), rep)
    else:

        def key(obj):
            poly, exp = obj
            rep = poly.rep.rep
            return (len(rep), len(poly.gens), exp, rep)

    return sorted(factors, key=key)
# Buggy code
def key(obj):
    poly, exp = obj
    rep = poly.rep.rep
    return (len(rep), exp, rep)


# Traceback (TypeError)
Following function call generate an error in Python3 but work well in Python2.

factor_list(x*(x+y))

Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/thilinarmtb/GSoC/sympy/sympy/polys/polytools.py", line 5675, in factor_list
return _generic_factor_list(f, gens, args, method='factor')
File "/home/thilinarmtb/GSoC/sympy/sympy/polys/polytools.py", line 5423, in _generic_factor_list
fp = _sorted_factors(fp, method)
File "/home/thilinarmtb/GSoC/sympy/sympy/polys/polytools.py", line 5322, in _sorted_factors
return sorted(factors, key=key)
TypeError: unorderable types: list() < int()


Similarly following calls generate the same error:
[1] factor_list(y*(x+y)),  factor_list(x*y + y**2)
[2] factor_list(x*(x+y+z)), factor_list(x**2+x*y+x*z)
[3] factor_list((x + 1)*(x + y))

But the following don't:
[4] factor_list(x*(x**2 + y**2)), factor_list(x**3 + x*y**2)
[5] factor_list(x**3 - x),  factor_list(x*(x**2 - 1))
[6] factor_list(x**2 + x*y + x + y)
[7] factor_list((x + z)*(x + y)), factor_list(x**2 + x*z + y*x + y*z)

Here [6] is mathematically same as [3]. But only [3] gives the error.

# Fixed code
def key(obj):
    poly, exp = obj
    rep = poly.rep.rep
    return (len(rep), len(poly.gens), exp, rep)
# Buggy code
def _eval_imageset(self, f):
    expr = f.expr
    if len(f.variables) > 1:
        return
    n = f.variables[0]

    a = Wild("a")
    b = Wild("b")

    match = expr.match(a * n + b)
    if match[a].is_negative:
        expr = -expr

    match = expr.match(a * n + b)
    if match[a] is S.One and match[b].is_integer:
        expr = expr - match[b]

    return ImageSet(Lambda(n, expr), S.Integers)


# Traceback (TypeError)
Following function call generate an error in Python3 but work well in Python2.

factor_list(x*(x+y))

Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/thilinarmtb/GSoC/sympy/sympy/polys/polytools.py", line 5675, in factor_list
return _generic_factor_list(f, gens, args, method='factor')
File "/home/thilinarmtb/GSoC/sympy/sympy/polys/polytools.py", line 5423, in _generic_factor_list
fp = _sorted_factors(fp, method)
File "/home/thilinarmtb/GSoC/sympy/sympy/polys/polytools.py", line 5322, in _sorted_factors
return sorted(factors, key=key)
TypeError: unorderable types: list() < int()


Similarly following calls generate the same error:
[1] factor_list(y*(x+y)),  factor_list(x*y + y**2)
[2] factor_list(x*(x+y+z)), factor_list(x**2+x*y+x*z)
[3] factor_list((x + 1)*(x + y))

But the following don't:
[4] factor_list(x*(x**2 + y**2)), factor_list(x**3 + x*y**2)
[5] factor_list(x**3 - x),  factor_list(x*(x**2 - 1))
[6] factor_list(x**2 + x*y + x + y)
[7] factor_list((x + z)*(x + y)), factor_list(x**2 + x*z + y*x + y*z)

Here [6] is mathematically same as [3]. But only [3] gives the error.

# Fixed code
def _eval_imageset(self, f):
    expr = f.expr
    if not isinstance(expr, Expr):
        return

    if len(f.variables) > 1:
        return

    n = f.variables[0]

    # f(x) + c and f(-x) + c cover the same integers
    # so choose the form that has the fewest negatives
    c = f(0)
    fx = f(n) - c
    f_x = f(-n) - c
    neg_count = lambda e: sum(_coeff_isneg(_) for _ in Add.make_args(e))
    if neg_count(f_x) < neg_count(fx):
        expr = f_x + c

    a = Wild("a", exclude=[n])
    b = Wild("b", exclude=[n])
    match = expr.match(a * n + b)
    if match and match[a]:
        # canonical shift
        expr = match[a] * n + match[b] % match[a]

    if expr != f.expr:
        return ImageSet(Lambda(n, expr), S.Integers)
# Buggy code
def doit(self):
    if self.args[0].is_zero is False:
        return self.args[0] / Abs(self.args[0])
    return self


# Traceback (TypeError)
In [63]: integrate((sign(x - 1) - sign(x - 2))*cos(x), x)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-63-4e67770ec27d> in <module>()
----> 1 integrate((sign(x - 1) - sign(x - 2))*cos(x), x)

/home/pape/sympy/sympy/utilities/decorator.pyc in threaded_func(expr, *args, **kwargs)
33                                       func(expr.rhs, *args, **kwargs))
34             else:
---> 35                 return func(expr, *args, **kwargs)
36
37     return threaded_func

/home/pape/sympy/sympy/integrals/integrals.pyc in integrate(*args, **kwargs)
1638     if isinstance(integral, Integral):
1639         return integral.doit(deep=False, meijerg=meijerg, conds=conds,
-> 1640                              risch=risch, manual=manual)
1641     else:
1642         return integral

/home/pape/sympy/sympy/integrals/integrals.pyc in doit(self, **hints)
892                     function, xab[0],
893                     meijerg=meijerg1, risch=risch, manual=manual,
--> 894                     conds=conds)
895                 if antideriv is None and meijerg1 is True:
896                     ret = try_meijerg(function, xab)

/home/pape/sympy/sympy/integrals/integrals.pyc in _eval_integral(self, f, x, meijerg, risch, manual, conds)
1298                             result = result.func(*[
1299                                 arg.doit(manual=False) if arg.has(Integral) else arg
-> 1300                                 for arg in result.args
1301                             ]).expand(multinomial=False,
1302                                       log=False,

/home/pape/sympy/sympy/integrals/integrals.pyc in doit(self, **hints)
809         function = self.function
810         if deep:
--> 811             function = function.doit(**hints)
812
813         if function.is_zero:

/home/pape/sympy/sympy/core/basic.pyc in doit(self, **hints)
1533         if hints.get('deep', True):
1534             terms = [ term.doit(**hints) if isinstance(term, Basic) else term
-> 1535                                          for term in self.args ]
1536             return self.func(*terms)
1537         else:

TypeError: doit() got an unexpected keyword argument 'manual'

# Fixed code
def doit(self, **hints):
    if self.args[0].is_zero is False:
        return self.args[0] / Abs(self.args[0])
    return self
# Buggy code
def _eval_Eq(self, other):
    if not other.is_FiniteSet:
        if (
            other.is_Union
            or other.is_Complement
            or other.is_Intersection
            or other.is_ProductSet
        ):
            return

        return false

    return And(*map(lambda x, y: Eq(x, y), self.args, other.args))


# Traceback (TypeError)
In [5]: b in FiniteSet(-a)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-66c50e010c80> in <module>()
----> 1 b in FiniteSet(-a)

/home/hargup/210fs/sympy/sympy/sets/sets.py in __contains__(self, other)
495         symb = self.contains(other)
496         if symb not in (true, false):
--> 497             raise TypeError('contains did not evaluate to a bool: %r' % symb)
498         return bool(symb)
499

TypeError: contains did not evaluate to a bool: Contains(b, {-a})

# Fixed code
def _eval_Eq(self, other):
    if not other.is_FiniteSet:
        if (
            other.is_Union
            or other.is_Complement
            or other.is_Intersection
            or other.is_ProductSet
        ):
            return

        return false

    if len(self) != len(other):
        return false

    return And(*map(lambda x, y: Eq(x, y), self.args, other.args))
# Buggy code
def _contains(self, other):
    """
    Tests whether an element, other, is in the set.

    Relies on Python's set class. This tests for object equality
    All inputs are sympified

    Examples
    ========

    >>> from sympy import FiniteSet
    >>> 1 in FiniteSet(1, 2)
    True
    >>> 5 in FiniteSet(1, 2)
    False

    """
    if other in self._elements:
        return true
    else:
        if not other.free_symbols:
            return false
        elif all(e.is_Symbol for e in self._elements):
            return false


# Traceback (TypeError)
In [5]: b in FiniteSet(-a)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-66c50e010c80> in <module>()
----> 1 b in FiniteSet(-a)

/home/hargup/210fs/sympy/sympy/sets/sets.py in __contains__(self, other)
495         symb = self.contains(other)
496         if symb not in (true, false):
--> 497             raise TypeError('contains did not evaluate to a bool: %r' % symb)
498         return bool(symb)
499

TypeError: contains did not evaluate to a bool: Contains(b, {-a})

# Fixed code
def _contains(self, other):
    """
    Tests whether an element, other, is in the set.

    Relies on Python's set class. This tests for object equality
    All inputs are sympified

    Examples
    ========

    >>> from sympy import FiniteSet
    >>> 1 in FiniteSet(1, 2)
    True
    >>> 5 in FiniteSet(1, 2)
    False

    """
    r = false
    for e in self._elements:
        t = Eq(e, other, evaluate=True)
        if isinstance(t, Eq):
            t = t.simplify()
        if t == true:
            return t
        elif t != false:
            r = None
    return r
# Buggy code
def __contains__(self, other):
    # Split event into each subdomain
    for domain in self.domains:
        # Collect the parts of this event which associate to this domain
        elem = frozenset([item for item in other if item[0] in domain.symbols])
        # Test this sub-event
        if elem not in domain:
            return False
    # All subevents passed
    return True


# Traceback (TypeError)
In [5]: b in FiniteSet(-a)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-66c50e010c80> in <module>()
----> 1 b in FiniteSet(-a)

/home/hargup/210fs/sympy/sympy/sets/sets.py in __contains__(self, other)
495         symb = self.contains(other)
496         if symb not in (true, false):
--> 497             raise TypeError('contains did not evaluate to a bool: %r' % symb)
498         return bool(symb)
499

TypeError: contains did not evaluate to a bool: Contains(b, {-a})

# Fixed code
def __contains__(self, other):
    # Split event into each subdomain
    for domain in self.domains:
        # Collect the parts of this event which associate to this domain
        elem = frozenset(
            [item for item in other if domain.symbols.contains(item[0]) == S.true]
        )
        # Test this sub-event
        if elem not in domain:
            return False
    # All subevents passed
    return True
# Buggy code
def __init__(self, settings={}):
    CodePrinter.__init__(self, settings)
    self.known_functions = dict(known_functions)
    userfuncs = settings.get("user_functions", {})
    for k, v in userfuncs.items():
        if not isinstance(v, list):
            userfuncs[k] = [(lambda *x: True, v)]
    self.known_functions.update(userfuncs)


# Traceback (CodeWrapError)
ufuncify(x, x*log(10)) produces the following exception


---------------------------------------------------------------------------
CodeWrapError                             Traceback (most recent call last)
<ipython-input-12-f6cc06919001> in <module>()
----> 1 ufuncify(x, x*log(10))

/home/thomas/gitrepos/sympy/sympy/utilities/autowrap.py in ufuncify(args, expr, **kwargs)
479     # first argument accepts an array
480     args[0] = x[i]
--> 481     return autowrap(C.Equality(y[i], f(*args)), **kwargs)

/home/thomas/gitrepos/sympy/sympy/utilities/autowrap.py in autowrap(expr, language, backend, tempdir, args, flags, verbose, helpers)
404         helps.append(Routine(name, expr, args))
405
--> 406     return code_wrapper.wrap_code(routine, helpers=helps)
407
408

/home/thomas/gitrepos/sympy/sympy/utilities/autowrap.py in wrap_code(self, routine, helpers)
133             self._generate_code(routine, helpers)
134             self._prepare_files(routine)
--> 135             self._process_files(routine)
136             mod = __import__(self.module_name)
137         finally:

/home/thomas/gitrepos/sympy/sympy/utilities/autowrap.py in _process_files(self, routine)
158         if retcode:
159             raise CodeWrapError(
--> 160                 "Error while executing command: %s" % " ".join(command))
161
162

CodeWrapError: Error while executing command: f2py -m wrapper_module_6 -c wrapped_code_6.f90

If I replace log(2) by its numerical value ufuncify works as expected.

# Fixed code
def __init__(self, settings={}):
    CodePrinter.__init__(self, settings)
    self.known_functions = dict(known_functions)
    userfuncs = settings.get("user_functions", {})
    self.known_functions.update(userfuncs)
# Buggy code
def __init__(self, settings=None):
    CodePrinter.__init__(self, settings)
    # leading columns depend on fixed or free format
    if self._settings["source_format"] == "fixed":
        self._lead_code = "      "
        self._lead_cont = "     @ "
        self._lead_comment = "C     "
    elif self._settings["source_format"] == "free":
        self._lead_code = ""
        self._lead_cont = "      "
        self._lead_comment = "! "
    else:
        raise ValueError("Unknown source format: %s" % self._settings["source_format"])
    standards = set([66, 77, 90, 95, 2003, 2008])
    if self._settings["standard"] not in standards:
        raise ValueError("Unknown Fortran standard: %s" % self._settings["standard"])


# Traceback (CodeWrapError)
ufuncify(x, x*log(10)) produces the following exception


---------------------------------------------------------------------------
CodeWrapError                             Traceback (most recent call last)
<ipython-input-12-f6cc06919001> in <module>()
----> 1 ufuncify(x, x*log(10))

/home/thomas/gitrepos/sympy/sympy/utilities/autowrap.py in ufuncify(args, expr, **kwargs)
479     # first argument accepts an array
480     args[0] = x[i]
--> 481     return autowrap(C.Equality(y[i], f(*args)), **kwargs)

/home/thomas/gitrepos/sympy/sympy/utilities/autowrap.py in autowrap(expr, language, backend, tempdir, args, flags, verbose, helpers)
404         helps.append(Routine(name, expr, args))
405
--> 406     return code_wrapper.wrap_code(routine, helpers=helps)
407
408

/home/thomas/gitrepos/sympy/sympy/utilities/autowrap.py in wrap_code(self, routine, helpers)
133             self._generate_code(routine, helpers)
134             self._prepare_files(routine)
--> 135             self._process_files(routine)
136             mod = __import__(self.module_name)
137         finally:

/home/thomas/gitrepos/sympy/sympy/utilities/autowrap.py in _process_files(self, routine)
158         if retcode:
159             raise CodeWrapError(
--> 160                 "Error while executing command: %s" % " ".join(command))
161
162

CodeWrapError: Error while executing command: f2py -m wrapper_module_6 -c wrapped_code_6.f90

If I replace log(2) by its numerical value ufuncify works as expected.

# Fixed code
def __init__(self, settings={}):
    CodePrinter.__init__(self, settings)
    self.known_functions = dict(known_functions)
    userfuncs = settings.get("user_functions", {})
    self.known_functions.update(userfuncs)
    # leading columns depend on fixed or free format
    if self._settings["source_format"] == "fixed":
        self._lead_code = "      "
        self._lead_cont = "     @ "
        self._lead_comment = "C     "
    elif self._settings["source_format"] == "free":
        self._lead_code = ""
        self._lead_cont = "      "
        self._lead_comment = "! "
    else:
        raise ValueError("Unknown source format: %s" % self._settings["source_format"])
    standards = set([66, 77, 90, 95, 2003, 2008])
    if self._settings["standard"] not in standards:
        raise ValueError("Unknown Fortran standard: %s" % self._settings["standard"])
# Buggy code
def _print_Function(self, expr):
    name = self._settings["user_functions"].get(expr.__class__)
    eargs = expr.args
    if name is None:
        from sympy.functions import conjugate

        if expr.func == conjugate:
            name = "conjg"
        else:
            name = expr.func.__name__
        if hasattr(expr, "_imp_") and isinstance(expr._imp_, C.Lambda):
            # inlined function.
            # the expression is printed with _print to avoid loops
            return self._print(expr._imp_(*eargs))
        if expr.func.__name__ not in self._implicit_functions:
            self._not_supported.add(expr)
        else:
            # convert all args to floats
            eargs = map(N, eargs)
    return "%s(%s)" % (name, self.stringify(eargs, ", "))


# Traceback (CodeWrapError)
ufuncify(x, x*log(10)) produces the following exception


---------------------------------------------------------------------------
CodeWrapError                             Traceback (most recent call last)
<ipython-input-12-f6cc06919001> in <module>()
----> 1 ufuncify(x, x*log(10))

/home/thomas/gitrepos/sympy/sympy/utilities/autowrap.py in ufuncify(args, expr, **kwargs)
479     # first argument accepts an array
480     args[0] = x[i]
--> 481     return autowrap(C.Equality(y[i], f(*args)), **kwargs)

/home/thomas/gitrepos/sympy/sympy/utilities/autowrap.py in autowrap(expr, language, backend, tempdir, args, flags, verbose, helpers)
404         helps.append(Routine(name, expr, args))
405
--> 406     return code_wrapper.wrap_code(routine, helpers=helps)
407
408

/home/thomas/gitrepos/sympy/sympy/utilities/autowrap.py in wrap_code(self, routine, helpers)
133             self._generate_code(routine, helpers)
134             self._prepare_files(routine)
--> 135             self._process_files(routine)
136             mod = __import__(self.module_name)
137         finally:

/home/thomas/gitrepos/sympy/sympy/utilities/autowrap.py in _process_files(self, routine)
158         if retcode:
159             raise CodeWrapError(
--> 160                 "Error while executing command: %s" % " ".join(command))
161
162

CodeWrapError: Error while executing command: f2py -m wrapper_module_6 -c wrapped_code_6.f90

If I replace log(2) by its numerical value ufuncify works as expected.

# Fixed code
def _print_Function(self, expr):
    # All constant function args are evaluated as floats
    prec = self._settings["precision"]
    args = [N(a, prec) for a in expr.args]
    eval_expr = expr.func(*args)
    if not isinstance(eval_expr, C.Function):
        return self._print(eval_expr)
    else:
        return CodePrinter._print_Function(self, expr.func(*args))
# Buggy code
def __init__(self, settings={}):
    CodePrinter.__init__(self, settings)
    self.known_functions = dict(known_functions)
    userfuncs = settings.get("user_functions", {})
    for k, v in userfuncs.items():
        if not isinstance(v, tuple):
            userfuncs[k] = (lambda *x: True, v)
    self.known_functions.update(userfuncs)


# Traceback (CodeWrapError)
ufuncify(x, x*log(10)) produces the following exception


---------------------------------------------------------------------------
CodeWrapError                             Traceback (most recent call last)
<ipython-input-12-f6cc06919001> in <module>()
----> 1 ufuncify(x, x*log(10))

/home/thomas/gitrepos/sympy/sympy/utilities/autowrap.py in ufuncify(args, expr, **kwargs)
479     # first argument accepts an array
480     args[0] = x[i]
--> 481     return autowrap(C.Equality(y[i], f(*args)), **kwargs)

/home/thomas/gitrepos/sympy/sympy/utilities/autowrap.py in autowrap(expr, language, backend, tempdir, args, flags, verbose, helpers)
404         helps.append(Routine(name, expr, args))
405
--> 406     return code_wrapper.wrap_code(routine, helpers=helps)
407
408

/home/thomas/gitrepos/sympy/sympy/utilities/autowrap.py in wrap_code(self, routine, helpers)
133             self._generate_code(routine, helpers)
134             self._prepare_files(routine)
--> 135             self._process_files(routine)
136             mod = __import__(self.module_name)
137         finally:

/home/thomas/gitrepos/sympy/sympy/utilities/autowrap.py in _process_files(self, routine)
158         if retcode:
159             raise CodeWrapError(
--> 160                 "Error while executing command: %s" % " ".join(command))
161
162

CodeWrapError: Error while executing command: f2py -m wrapper_module_6 -c wrapped_code_6.f90

If I replace log(2) by its numerical value ufuncify works as expected.

# Fixed code
def __init__(self, settings={}):
    CodePrinter.__init__(self, settings)
    self.known_functions = dict(known_functions)
    userfuncs = settings.get("user_functions", {})
    self.known_functions.update(userfuncs)
# Buggy code
def _print_Indexed(self, expr):
    # calculate index for 1d array
    dims = expr.shape
    inds = [i.label for i in expr.indices]
    elem = S.Zero
    offset = S.One
    for i in reversed(range(expr.rank)):
        elem += offset * inds[i]
        offset *= dims[i]
    return "%s[%s]" % (self._print(expr.base.label), self._print(elem))


# Traceback (CodeWrapError)
ufuncify(x, x*log(10)) produces the following exception


---------------------------------------------------------------------------
CodeWrapError                             Traceback (most recent call last)
<ipython-input-12-f6cc06919001> in <module>()
----> 1 ufuncify(x, x*log(10))

/home/thomas/gitrepos/sympy/sympy/utilities/autowrap.py in ufuncify(args, expr, **kwargs)
479     # first argument accepts an array
480     args[0] = x[i]
--> 481     return autowrap(C.Equality(y[i], f(*args)), **kwargs)

/home/thomas/gitrepos/sympy/sympy/utilities/autowrap.py in autowrap(expr, language, backend, tempdir, args, flags, verbose, helpers)
404         helps.append(Routine(name, expr, args))
405
--> 406     return code_wrapper.wrap_code(routine, helpers=helps)
407
408

/home/thomas/gitrepos/sympy/sympy/utilities/autowrap.py in wrap_code(self, routine, helpers)
133             self._generate_code(routine, helpers)
134             self._prepare_files(routine)
--> 135             self._process_files(routine)
136             mod = __import__(self.module_name)
137         finally:

/home/thomas/gitrepos/sympy/sympy/utilities/autowrap.py in _process_files(self, routine)
158         if retcode:
159             raise CodeWrapError(
--> 160                 "Error while executing command: %s" % " ".join(command))
161
162

CodeWrapError: Error while executing command: f2py -m wrapper_module_6 -c wrapped_code_6.f90

If I replace log(2) by its numerical value ufuncify works as expected.

# Fixed code
def _print_Indexed(self, expr):
    # calculate index for 1d array
    dims = expr.shape
    elem = S.Zero
    offset = S.One
    for i in reversed(range(expr.rank)):
        elem += expr.indices[i] * offset
        offset *= dims[i]
    return "%s[%s]" % (self._print(expr.base.label), self._print(elem))
# Buggy code
def load_ipython_extension(ip):
    """Load the extension in IPython."""
    import IPython

    global _loaded
    # Use extension manager to track loaded status if available
    # This is currently in IPython 0.14.dev
    if hasattr(ip.extension_manager, "loaded"):
        loaded = "sympy.interactive.ipythonprinting" not in ip.extension_manager.loaded
    else:
        loaded = _loaded

    if not loaded:
        init_printing(ip=ip)
        _loaded = True


# Traceback (ImportError)
Traceback (most recent call last):
File "./setup.py", line 34, in ?
import sympy
File "/tmp/sympy/sympy/**init**.py", line 29, in ?
from printing import pretty, pretty_print, pprint, pprint_use_unicode, \
File "/tmp/sympy/sympy/printing/**init**.py", line 8, in ?
from preview import preview, view, pngview, pdfview, dviview
File "/tmp/sympy/sympy/printing/preview.py", line 4, in ?
import pexpect
ImportError: No module named pexpect

# Fixed code
def load_ipython_extension(ip):
    """Load the extension in IPython."""
    init_printing(ip=ip)
# Buggy code
def _expand_batch(self, batch_shape):
    lazy_tensors = [
        lazy_tensor._expand_batch(batch_shape) for lazy_tensor in self.lazy_tensors
    ]
    res = self.__class__(
        *lazy_tensors, dim=self.cat_dim, output_device=self.output_device
    )
    return res


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-16-0d626e17adaf> in <module>
----> 1 cmtlt + torch.randn(100, 100)

~/Documents/GitHub/gpytorch/gpytorch/lazy/lazy_tensor.py in __add__(self, other)
1625             other = lazify(other)
1626             shape = _mul_broadcast_shape(self.shape, other.shape)
-> 1627             return SumLazyTensor(self.expand(shape), other.expand(shape))
1628         else:
1629             return SumLazyTensor(self, other)

~/Documents/GitHub/gpytorch/gpytorch/lazy/lazy_tensor.py in expand(self, *sizes)
857             raise RuntimeError("Invalid arguments {} to expand.".format(sizes))
858
--> 859         res = self._expand_batch(batch_shape=shape[:-2])
860         return res
861

~/Documents/GitHub/gpytorch/gpytorch/lazy/constant_mul_lazy_tensor.py in _expand_batch(self, batch_shape)
70     def _expand_batch(self, batch_shape):
---> 71         return self.__class__(self.base_lazy_tensor._expand_batch(batch_shape), self._constant.expand(*batch_shape))
72
73     def _get_indices(self, row_index, col_index, *batch_indices):

TypeError: expand() missing 1 required positional arguments: "size"

# Fixed code
def _expand_batch(self, batch_shape):
    batch_dim = self.cat_dim + 2
    if batch_dim < 0:
        if batch_shape[batch_dim] != self.batch_shape[batch_dim]:
            raise RuntimeError(
                f"Trying to expand a CatLazyTensor in dimension {self.cat_dim}, but this is the concatenated "
                f"dimension.\nCurrent shape: {self.shape} - expanded shape: {batch_shape + self.matrix_shape}."
            )
        lazy_tensors = []
        for lazy_tensor in self.lazy_tensors:
            sub_batch_shape = list(batch_shape).copy()
            sub_batch_shape[batch_dim] = lazy_tensor.shape[self.cat_dim]
            lazy_tensors.append(lazy_tensor._expand_batch(sub_batch_shape))
    else:
        lazy_tensors = [
            lazy_tensor._expand_batch(batch_shape) for lazy_tensor in self.lazy_tensors
        ]
    res = self.__class__(
        *lazy_tensors, dim=self.cat_dim, output_device=self.output_device
    )
    return res
# Buggy code
def _expand_batch(self, batch_shape):
    return self.__class__(
        self.base_lazy_tensor._expand_batch(batch_shape),
        self._constant.expand(*batch_shape),
    )


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-16-0d626e17adaf> in <module>
----> 1 cmtlt + torch.randn(100, 100)

~/Documents/GitHub/gpytorch/gpytorch/lazy/lazy_tensor.py in __add__(self, other)
1625             other = lazify(other)
1626             shape = _mul_broadcast_shape(self.shape, other.shape)
-> 1627             return SumLazyTensor(self.expand(shape), other.expand(shape))
1628         else:
1629             return SumLazyTensor(self, other)

~/Documents/GitHub/gpytorch/gpytorch/lazy/lazy_tensor.py in expand(self, *sizes)
857             raise RuntimeError("Invalid arguments {} to expand.".format(sizes))
858
--> 859         res = self._expand_batch(batch_shape=shape[:-2])
860         return res
861

~/Documents/GitHub/gpytorch/gpytorch/lazy/constant_mul_lazy_tensor.py in _expand_batch(self, batch_shape)
70     def _expand_batch(self, batch_shape):
---> 71         return self.__class__(self.base_lazy_tensor._expand_batch(batch_shape), self._constant.expand(*batch_shape))
72
73     def _get_indices(self, row_index, col_index, *batch_indices):

TypeError: expand() missing 1 required positional arguments: "size"

# Fixed code
def _expand_batch(self, batch_shape):
    return self.__class__(
        self.base_lazy_tensor._expand_batch(batch_shape),
        self._constant.expand(*batch_shape) if len(batch_shape) else self._constant,
    )
# Buggy code
def get_base_samples(self, sample_shape=torch.Size()):
    """Get i.i.d. standard Normal samples (to be used with rsample(base_samples=base_samples))"""
    base_samples = super().get_base_samples(sample_shape)
    if not self._interleaved:
        # flip shape of last two dimensions
        new_shape = sample_shape + self._output_shape[:-2] + self._output_shape[:-3:-1]
        return base_samples.view(new_shape).transpose(-1, -2).contiguous()
    return base_samples.view(*sample_shape, *self._output_shape)


# Traceback (AttributeError)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-6-c955f39ee560> in <module>
4 with torch.no_grad():
5     for x_batch, y_batch in test_loader:
----> 6         preds = model(x_batch)
7         means = torch.cat([means, preds.mean.cpu()])
8 means = means[1:]

~/miniconda3/envs/mbrl/lib/python3.7/site-packages/gpytorch/models/abstract_variational_gp.py in __call__(self, inputs, **kwargs)
20             inputs = inputs.unsqueeze(-1)
21
---> 22         return self.variational_strategy(inputs)

~/miniconda3/envs/mbrl/lib/python3.7/site-packages/gpytorch/variational/variational_strategy.py in __call__(self, x)
228                 self._memoize_cache = dict()
229
--> 230         return super(VariationalStrategy, self).__call__(x)

~/miniconda3/envs/mbrl/lib/python3.7/site-packages/gpytorch/module.py in __call__(self, *inputs, **kwargs)
20
21     def __call__(self, *inputs, **kwargs):
---> 22         outputs = self.forward(*inputs, **kwargs)
23         if isinstance(outputs, list):
24             return [_validate_module_outputs(output) for output in outputs]

~/miniconda3/envs/mbrl/lib/python3.7/site-packages/gpytorch/variational/variational_strategy.py in forward(self, x)
214                     induc_induc_covar.inv_matmul(induc_data_covar)
215                 )
--> 216                 data_covariance = data_data_covar + neg_induc_data_data_covar
217             predictive_covar = PsdSumLazyTensor(predictive_covar, data_covariance)
218

~/miniconda3/envs/mbrl/lib/python3.7/site-packages/gpytorch/lazy/sum_lazy_tensor.py in __add__(self, other)
75             return SumLazyTensor(*(list(self.lazy_tensors) + [other]))
76         else:
---> 77             raise AttributeError("other must be a LazyTensor")
78
79     def diag(self):

AttributeError: other must be a LazyTensor

# Fixed code
def get_base_samples(self, sample_shape=torch.Size()):
    base_samples = super().get_base_samples(sample_shape)
    if not self._interleaved:
        # flip shape of last two dimensions
        new_shape = sample_shape + self._output_shape[:-2] + self._output_shape[:-3:-1]
        return base_samples.view(new_shape).transpose(-1, -2).contiguous()
    return base_samples.view(*sample_shape, *self._output_shape)
# Buggy code
def confidence_region(self):
    """
    Returns 2 standard deviations above and below the mean.

    Returns:
        Tuple[Tensor, Tensor]: pair of tensors of size (b x d) or (d), where
            b is the batch size and d is the dimensionality of the random
            variable. The first (second) Tensor is the lower (upper) end of
            the confidence region.

    """
    std2 = self.stddev.mul_(2)
    mean = self.mean
    return mean.sub(std2), mean.add(std2)


# Traceback (AttributeError)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-6-c955f39ee560> in <module>
4 with torch.no_grad():
5     for x_batch, y_batch in test_loader:
----> 6         preds = model(x_batch)
7         means = torch.cat([means, preds.mean.cpu()])
8 means = means[1:]

~/miniconda3/envs/mbrl/lib/python3.7/site-packages/gpytorch/models/abstract_variational_gp.py in __call__(self, inputs, **kwargs)
20             inputs = inputs.unsqueeze(-1)
21
---> 22         return self.variational_strategy(inputs)

~/miniconda3/envs/mbrl/lib/python3.7/site-packages/gpytorch/variational/variational_strategy.py in __call__(self, x)
228                 self._memoize_cache = dict()
229
--> 230         return super(VariationalStrategy, self).__call__(x)

~/miniconda3/envs/mbrl/lib/python3.7/site-packages/gpytorch/module.py in __call__(self, *inputs, **kwargs)
20
21     def __call__(self, *inputs, **kwargs):
---> 22         outputs = self.forward(*inputs, **kwargs)
23         if isinstance(outputs, list):
24             return [_validate_module_outputs(output) for output in outputs]

~/miniconda3/envs/mbrl/lib/python3.7/site-packages/gpytorch/variational/variational_strategy.py in forward(self, x)
214                     induc_induc_covar.inv_matmul(induc_data_covar)
215                 )
--> 216                 data_covariance = data_data_covar + neg_induc_data_data_covar
217             predictive_covar = PsdSumLazyTensor(predictive_covar, data_covariance)
218

~/miniconda3/envs/mbrl/lib/python3.7/site-packages/gpytorch/lazy/sum_lazy_tensor.py in __add__(self, other)
75             return SumLazyTensor(*(list(self.lazy_tensors) + [other]))
76         else:
---> 77             raise AttributeError("other must be a LazyTensor")
78
79     def diag(self):

AttributeError: other must be a LazyTensor

# Fixed code
def confidence_region(self):
    """
    Returns 2 standard deviations above and below the mean.

    :rtype: (torch.Tensor, torch.Tensor)
    :return: pair of tensors of size (b x d) or (d), where
        b is the batch size and d is the dimensionality of the random
        variable. The first (second) Tensor is the lower (upper) end of
        the confidence region.
    """
    std2 = self.stddev.mul_(2)
    mean = self.mean
    return mean.sub(std2), mean.add(std2)