sinh, tanh, acosh     """ <ins>    def _eval_is_positive(self):        arg = self.args[0]        if arg.is_real:            return True        re, im = arg.as_real_imag()        im_mod = im % (2*pi)        if im_mod == 0:            return True        if re == 0:            if im_mod < pi/2 or im_mod > 3*pi/2:                return True            elif im_mod >= pi/2 or im_mod <= 3*pi/2:                return False        return fuzzy_or([fuzzy_and([fuzzy_bool(Eq(re, 0)),                         fuzzy_or([fuzzy_bool(im_mod < pi/2),                                   fuzzy_bool(im_mod > 3*pi/2)])]),                         fuzzy_bool(Eq(im_mod, 0))])    def _eval_is_nonnegative(self):        arg = self.args[0]        if arg.is_real:            return True        re, im = arg.as_real_imag()        im_mod = im % (2*pi)        if im_mod == 0:            return True        if re == 0:            if im_mod <= pi/2 or im_mod >= 3*pi/2:                return True            elif im_mod > pi/2 or im_mod < 3*pi/2:                return False        return fuzzy_or([fuzzy_and([fuzzy_bool(Eq(re, 0)),                         fuzzy_or([fuzzy_bool(im_mod <= pi/2), fuzzy_bool(im_mod >= 3*pi/2)])]),                         fuzzy_bool(Eq(im_mod, 0))])</ins>     def fdiff(self, argindex=1):         if argindex == 1:             return sinh(self.args[0])


re, im = arg.as_real_imag()         return (im%pi).is_zero <del>    def _eval_is_positive(self):        if self.args[0].is_extended_real:            return True</del>     def _eval_is_finite(self):         arg = self.args[0]         return arg.is_finite


return None     base_set = self.base_sets[0]     # Intersection between ImageSets with Integers as base set    # For {f(n) : n in Integers} & {g(m) : m in Integers} we solve the    # diophantine equations f(n)=g(m).    # If the solutions for n are {h(t) : t in Integers} then we return    # {f(h(t)) : t in integers}.     if base_set is S.Integers:        g = None        gm = None         if isinstance(other, ImageSet) and other.base_sets == (S.Integers,):            g = other.lamda.expr            gm = other.lamda.expr             m = other.lamda.variables[0]         elif other is S.Integers:            m = g = Dummy('x')        if g is not None:            f = self.lamda.expr            m = gm = Dummy('x')        if gm is not None:            fn = self.lamda.expr             n = self.lamda.variables[0]            # Diophantine sorts the solutions according to the alphabetic            # order of the variable names, since the result should not depend            # on the variable name, they are replaced by the dummy variables            # below            a, b = Dummy('a'), Dummy('b')            fa, ga = f.subs(n, a), g.subs(m, b)            solns = list(diophantine(fa - ga))            if not solns:            solns = list(diophantine(fn - gm, syms=(n, m)))            if len(solns) == 0:                 return EmptySet()            if len(solns) != 1:            elif len(solns) != 1:                 return            nsol = solns[0][0]  # since 'a' < 'b', nsol is first            t = nsol.free_symbols.pop()  # diophantine supplied symbol            nsol = nsol.subs(t, n)            if nsol != n:                # if nsol == n and we know were are working with                # a base_set of Integers then this was an unevaluated                # ImageSet representation of Integers, otherwise                # it is a new ImageSet intersection with a subset                # of integers                nsol = f.subs(n, nsol)            return imageset(Lambda(n, nsol), S.Integers)            else:                soln, solm = solns[0]                (t,) = soln.free_symbols                expr = fn.subs(n, soln.subs(t, n))                return imageset(Lambda(n, expr), S.Integers)      if other == S.Reals:         from sympy.solvers.solveset import solveset_real


elif issubclass(number_cls, Rational):             return (Rational(9, 10), S.One) <ins>    def _eval_rewrite_as_Sum(self, k_sym=None, symbols=None):        from sympy import Sum, Dummy        if (k_sym is not None) or (symbols is not None):            return self        k = Dummy('k', integer=True, nonnegative=True)        return Sum((-1)**k / (2*k+1)**2, (k, 0, S.Infinity))</ins>     def _sage_(self):         import sage.all as sage         return sage.catalan


from __future__ import print_function, division from sympy.core import S, Basic, Add, Mul, symbolsfrom sympy.core import S, Basic, Add, Mul, symbols, Dummy from sympy.core.compatibility import range from sympy.functions.combinatorial.factorials import factorial from sympy.polys.polyerrors import (


@public def interpolate(data, x):     """    Construct an interpolating polynomial for the data points.    Construct an interpolating polynomial for the data points    evaluated at point x (which can be symbolic or numeric).      Examples     ========      >>> from sympy.polys.polyfuncs import interpolate    >>> from sympy.abc import x    >>> from sympy.abc import a, b, x      A list is interpreted as though it were paired with a range starting     from 1:


>>> interpolate({-1: 2, 1: 2, 2: 5}, x)     x**2 + 1     If the interpolation is going to be used only once then the    value of interest can be passed instead of passing a symbol:    >>> interpolate([1, 4, 9], 5)    25    Symbolic coordinates are also supported:    >>> [(i,interpolate((a, b), i)) for i in range(1, 4)]    [(1, a), (2, b), (3, -a + 2*b)]     """     n = len(data)    poly = None      if isinstance(data, dict):        if x in data:            return S(data[x])         X, Y = list(zip(*data.items()))        poly = interpolating_poly(n, x, X, Y)     else:         if isinstance(data[0], tuple):             X, Y = list(zip(*data))            poly = interpolating_poly(n, x, X, Y)            if x in X:                return S(Y[X.index(x)])         else:            if x in range(1, n + 1):                return S(data[x - 1])             Y = list(data)            X = list(range(1, n + 1))             numert = Mul(*[(x - i) for i in range(1, n + 1)])            denom = -factorial(n - 1) if n%2 == 0 else factorial(n - 1)            coeffs = []            for i in range(1, n + 1):                coeffs.append(numert/(x - i)/denom)                denom = denom/(i - n)*i            poly = Add(*[coeff*y for coeff, y in zip(coeffs, Y)])    return poly.expand()    try:        return interpolating_poly(n, x, X, Y).expand()    except ValueError:        d = Dummy()        return interpolating_poly(n, d, X, Y).expand().subs(d, x)   @publicdiff --git a/sympy/polys/specialpolys.py b/sympy/polys/specialpolys.py-- a/sympy/polys/specialpolys.py++ b/sympy/polys/specialpolys.py


from sympy.core import Add, Mul, Symbol, sympify, Dummy, symbols from sympy.core.compatibility import range, string_types<ins>from sympy.core.containers import Tuple</ins> from sympy.core.singleton import S from sympy.functions.elementary.miscellaneous import sqrt from sympy.ntheory import nextprime


from sympy.polys.polyclasses import DMP from sympy.polys.polytools import Poly, PurePoly from sympy.polys.polyutils import _analyze_gensfrom sympy.utilities import subsets, publicfrom sympy.utilities import subsets, public, filldedent   @public


@public def interpolating_poly(n, x, X='x', Y='y'):    """Construct Lagrange interpolating polynomial for ``n`` data points. """    """Construct Lagrange interpolating polynomial for ``n``    data points. If a sequence of values are given for ``X`` and ``Y``    then the first ``n`` values will be used.    """    ok = getattr(x, 'free_symbols', None)     if isinstance(X, string_types):         X = symbols("%s:%s" % (X, n))    elif ok and ok & Tuple(*X).free_symbols:        ok = False      if isinstance(Y, string_types):         Y = symbols("%s:%s" % (Y, n))    elif ok and ok & Tuple(*Y).free_symbols:        ok = False    if not ok:        raise ValueError(filldedent('''            Expecting symbol for x that does not appear in X or Y.            Use `interpolate(list(zip(X, Y)), x)` instead.'''))      coeffs = []    numert = Mul(*[(x - u) for u in X])    numert = Mul(*[x - X[i] for i in range(n)])      for i in range(n):         numer = numert/(x - X[i])


def __eq__(self, other):         try:            other = sympify(other)            other = _sympify(other)             if not isinstance(other, Expr):                 return False         except (SympifyError, SyntaxError):


from sympy.sets import (imageset, Interval, FiniteSet, Union, ImageSet,                         EmptySet, Intersection, Range) from sympy.sets.fancysets import Integers, Naturals, Reals<ins>from sympy.functions.elementary.exponential import match_real_imag</ins>   _x, _y = symbols("x y")


match = expr.match(a*n + b)     if match and match[a]:         # canonical shift        b = match[b]        if abs(match[a]) == 1:        a, b = match[a], match[b]        if a in [1, -1]:            # drop integer addends in b             nonint = []             for bi in Add.make_args(b):                 if not bi.is_integer:                     nonint.append(bi)             b = Add(*nonint)        if b.is_number and match[a].is_real:            mod = b % match[a]            reps = dict([(m, m.args[0]) for m in mod.atoms(Mod)                if not m.args[0].is_real])            mod = mod.xreplace(reps)            expr = match[a]*n + mod        else:            expr = match[a]*n + b        if b.is_number and a.is_real:            # avoid Mod for complex numbers, #11391            br, bi = match_real_imag(b)            if br and br.is_comparable and a.is_comparable:                br %= a                b = br + S.ImaginaryUnit*bi        elif b.is_number and a.is_imaginary:            br, bi = match_real_imag(b)            ai = a/S.ImaginaryUnit            if bi and bi.is_comparable and ai.is_comparable:                bi %= ai                b = br + S.ImaginaryUnit*bi        expr = a*n + b      if expr != f.expr:         return ImageSet(Lambda(n, expr), S.Integers)


for f in list(factors.keys()):                 if isinstance(f, Rational) and not isinstance(f, Integer):                     p, q = Integer(f.p), Integer(f.q)                    factors[p] = (factors[p] if p in factors else 0) + factors[f]                    factors[q] = (factors[q] if q in factors else 0) - factors[f]                    factors[p] = (factors[p] if p in factors else S.Zero) + factors[f]                    factors[q] = (factors[q] if q in factors else S.Zero) - factors[f]                     factors.pop(f)             if i:                 factors[I] = S.One*i


args = []         for factor, exp in self.factors.items():             if exp != 1:                b, e = factor.as_base_exp()                if isinstance(exp, int):                    e = _keep_coeff(Integer(exp), e)                elif isinstance(exp, Rational):                if isinstance(exp, Integer):                    b, e = factor.as_base_exp()                     e = _keep_coeff(exp, e)                    args.append(b**e)                 else:                    e *= exp                args.append(b**e)                    args.append(factor**exp)             else:                 args.append(factor)         return Mul(*args)


@_sympifyit('other', NotImplemented)     def __add__(self, other):        if isinstance(other, Number):        if isinstance(other, Number) and global_evaluate[0]:             if other is S.NegativeInfinity or other is S.NaN:                 return S.NaN             return self        return NotImplemented        return Number.__add__(self, other)     __radd__ = __add__      @_sympifyit('other', NotImplemented)     def __sub__(self, other):        if isinstance(other, Number):        if isinstance(other, Number) and global_evaluate[0]:             if other is S.Infinity or other is S.NaN:                 return S.NaN             return self        return NotImplemented        return Number.__sub__(self, other)      @_sympifyit('other', NotImplemented)     def __rsub__(self, other):


@_sympifyit('other', NotImplemented)     def __mul__(self, other):        if isinstance(other, Number):        if isinstance(other, Number) and global_evaluate[0]:             if other.is_zero or other is S.NaN:                 return S.NaN             if other.is_extended_positive:                 return self             return S.NegativeInfinity        return NotImplemented        return Number.__mul__(self, other)     __rmul__ = __mul__      @_sympifyit('other', NotImplemented)     def __div__(self, other):        if isinstance(other, Number):        if isinstance(other, Number) and global_evaluate[0]:             if other is S.Infinity or \                 other is S.NegativeInfinity or \                     other is S.NaN:


if other.is_extended_nonnegative:                 return self             return S.NegativeInfinity        return NotImplemented        return Number.__div__(self, other)      __truediv__ = __div__


@_sympifyit('other', NotImplemented)     def __add__(self, other):        if isinstance(other, Number):        if isinstance(other, Number) and global_evaluate[0]:             if other is S.Infinity or other is S.NaN:                 return S.NaN             return self        return NotImplemented        return Number.__add__(self, other)     __radd__ = __add__      @_sympifyit('other', NotImplemented)     def __sub__(self, other):        if isinstance(other, Number):        if isinstance(other, Number) and global_evaluate[0]:             if other is S.NegativeInfinity or other is S.NaN:                 return S.NaN             return self        return NotImplemented        return Number.__sub__(self, other)      @_sympifyit('other', NotImplemented)     def __rsub__(self, other):


@_sympifyit('other', NotImplemented)     def __mul__(self, other):        if isinstance(other, Number):        if isinstance(other, Number) and global_evaluate[0]:             if other.is_zero or other is S.NaN:                 return S.NaN             if other.is_extended_positive:                 return self             return S.Infinity        return NotImplemented        return Number.__mul__(self, other)     __rmul__ = __mul__      @_sympifyit('other', NotImplemented)     def __div__(self, other):        if isinstance(other, Number):        if isinstance(other, Number) and global_evaluate[0]:             if other is S.Infinity or \                 other is S.NegativeInfinity or \                     other is S.NaN:


if other.is_extended_nonnegative:                 return self             return S.Infinity        return NotImplemented        return Number.__div__(self, other)      __truediv__ = __div__


for z0 in range(0, abs(_c)):                     # Check if the coefficients of y and x obtained are integers or not                     if (divisible(sqa*g*z0**2 + D*z0 + sqa*F, _c) and                            divisible(e*sqc**g*z0**2 + E*z0 + e*sqc*F, _c)):                            divisible(e*sqc*g*z0**2 + E*z0 + e*sqc*F, _c)):                         sol.add((solve_x(z0), solve_y(z0)))      # (3) Method used when B**2 - 4*A*C is a square, is described in p. 6 of the below paper


ref = self.start         elif self.stop.is_finite:             ref = self.stop        else:            return other.is_Integer        if (ref - other) % self.step:  # off sequence        else:  # both infinite; step is +/- 1 (enforced by __new__)            return S.true        if self.size == 1:            return Eq(other, self[0])        res = (ref - other) % self.step        if res == S.Zero:            return And(other >= self.inf, other <= self.sup)        elif res.is_Integer:  # off sequence             return S.false        return _sympify(other >= self.inf and other <= self.sup)        else:  # symbolic/unsimplified residue modulo step            return None      def __iter__(self):         if self.has(Symbol):


def as_relational(self, x):         """Rewrite a Range in terms of equalities and logic operators. """         from sympy.functions.elementary.integers import floor        return And(            Eq(x, floor(x)),            x >= self.inf if self.inf in self else x > self.inf,            x <= self.sup if self.sup in self else x < self.sup)        if self.size == 1:            return Eq(x, self[0])        else:            return And(                Eq(x, floor(x)),                x >= self.inf if self.inf in self else x > self.inf,                x <= self.sup if self.sup in self else x < self.sup)   # Using range from compatibility above (xrange on Py2)diff --git a/sympy/sets/handlers/issubset.py b/sympy/sets/handlers/issubset.py-- a/sympy/sets/handlers/issubset.py++ b/sympy/sets/handlers/issubset.py


from sympy import Sfrom sympy import S, Symbol from sympy.core.logic import fuzzy_and, fuzzy_bool, fuzzy_not, fuzzy_or from sympy.core.relational import Eq from sympy.sets.sets import FiniteSet, Interval, Set, Union


cond_right = a_range.sup <= b_interval.right         return fuzzy_and([cond_left, cond_right]) @dispatch(Range, FiniteSet)def is_subset_sets(a_range, b_finiteset): # noqa:F811    try:        a_size = a_range.size    except ValueError:        # symbolic Range of unknown size        return None    if a_size > len(b_finiteset):        return False    elif any(arg.has(Symbol) for arg in a_range.args):        return fuzzy_and(b_finiteset.contains(x) for x in a_range)    else:        # Checking A \ B == EmptySet is more efficient than repeated naive        # membership checks on an arbitrary FiniteSet.        a_set = set(a_range)        b_remaining = len(b_finiteset)        # Symbolic expressions and numbers of unknown type (integer or not) are        # all counted as "candidates", i.e. *potentially* matching some a in        # a_range.        cnt_candidate = 0        for b in b_finiteset:            if b.is_Integer:                a_set.discard(b)            elif fuzzy_not(b.is_integer):                pass            else:                cnt_candidate += 1            b_remaining -= 1            if len(a_set) > b_remaining + cnt_candidate:                return False            if len(a_set) == 0:                return True        return None @dispatch(Interval, Range) def is_subset_sets(a_interval, b_range): # noqa:F811     if a_interval.measure.is_extended_nonzero:diff --git a/sympy/sets/sets.py b/sympy/sets/sets.py-- a/sympy/sets/sets.py++ b/sympy/sets/sets.py


else:             args = list(map(sympify, args))         args = list(ordered(set(args), Set._infimum_key))        _args_set = set(args)        args = list(ordered(_args_set, Set._infimum_key))         obj = Basic.__new__(cls, *args)        obj._args_set = _args_set         return obj      def _eval_Eq(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        The actual test is for mathematical equality (as opposed to        syntactical equality). In the worst case all elements of the        set must be checked.          Examples         ========


False          """        # evaluate=True is needed to override evaluate=False context;        # we need Eq to do the evaluation        return fuzzy_or(fuzzy_bool(Eq(e, other, evaluate=True)) for e in self.args)        if other in self._args_set:            return True        else:            # evaluate=True is needed to override evaluate=False context;            # we need Eq to do the evaluation            return fuzzy_or(fuzzy_bool(Eq(e, other, evaluate=True))                for e in self.args)      def _eval_is_subset(self, other):         return fuzzy_and(other._contains(e) for e in self.args)


@property     def _boundary(self):        return self        return S.Reals   class Naturals(with_metaclass(Singleton, Set)):diff --git a/sympy/sets/handlers/union.py b/sympy/sets/handlers/union.py-- a/sympy/sets/handlers/union.py++ b/sympy/sets/handlers/union.py


from sympy import (Interval, Intersection, Set, EmptySet, S, sympify,                    FiniteSet, Union, ComplexRegion, ProductSet) from sympy.multipledispatch import dispatchfrom sympy.sets.fancysets import Integersfrom sympy.sets.fancysets import (Naturals, Naturals0, Integers, Rationals,                                  Reals) from sympy.sets.sets import UniversalSet  @dispatch(Naturals0, Naturals)def union_sets(a, b): # noqa:F811    return a@dispatch(Rationals, Naturals)def union_sets(a, b): # noqa:F811    return a@dispatch(Rationals, Naturals0)def union_sets(a, b): # noqa:F811    return a@dispatch(Reals, Naturals)def union_sets(a, b): # noqa:F811    return a@dispatch(Reals, Naturals0)def union_sets(a, b): # noqa:F811    return a@dispatch(Reals, Rationals)def union_sets(a, b): # noqa:F811    return a @dispatch(Integers, Set) def union_sets(a, b): # noqa:F811     intersect = Intersection(a, b)diff --git a/sympy/sets/sets.py b/sympy/sets/sets.py-- a/sympy/sets/sets.py++ b/sympy/sets/sets.py


def is_open(self):         """         Property method to check whether a set is open.         A set is open if and only if it has an empty intersection with its        boundary.        boundary. In particular, a subset A of the reals is open if and only        if each one of its points is contained in an open interval that is a        subset of A.          Examples         ========         >>> from sympy import S         >>> S.Reals.is_open         True        >>> S.Rationals.is_open        False         """        if not Intersection(self, self.boundary):            return True        # We can't confidently claim that an intersection exists        return None        return Intersection(self, self.boundary).is_empty      @property     def is_closed(self):         """        A property method to check whether a set is closed. A set is closed        if its complement is an open set.        A property method to check whether a set is closed.        A set is closed if its complement is an open set. The closedness of a        subset of the reals is determined with respect to R and its standard        topology.          Examples         ========


if syms != var:                 dict_sym_index = dict(zip(syms, range(len(syms))))                 return {tuple([t[dict_sym_index[i]] for i in var])                            for t in diophantine(eq, param)}                            for t in diophantine(eq, param, permute=permute)}         n, d = eq.as_numer_denom()         if n.is_number:             return set()


if _half(other):                         if b.is_negative is True:                             return S.NegativeOne**other*Pow(-b, e*other)                        if b.is_extended_real is False:                            return Pow(b.conjugate()/Abs(b)**2, other)                        elif b.is_negative is False:                            return Pow(b, -other)                 elif e.is_even:                     if b.is_extended_real:                         b = abs(b)


from sympy.core.compatibility import as_int, range from sympy.core.function import Function<ins>from sympy.utilities.iterables import cartes</ins> from sympy.core.numbers import igcd, igcdex, mod_inverse from sympy.core.power import isqrt from sympy.core.singleton import S


return res     return min(res) <ins>def _nthroot_mod_composite(a, n, m):    """    Find the solutions to ``x**n = a mod m`` when m is not prime.    """    from sympy.ntheory.modular import crt    f = factorint(m)    dd = {}    for p, e in f.items():        tot_roots = set()        if e == 1:            tot_roots.update(nthroot_mod(a, n, p, True) or [])        else:            for root in nthroot_mod(a, n, p, True) or []:                rootn = pow(root, n)                diff = (rootn // (root or 1) * n) % p                if diff != 0:                    ppow = p                    for j in range(1, e):                        ppow *= p                        root = (root - (rootn - a) * mod_inverse(diff, p)) % ppow                    tot_roots.add(root)                else:                    new_base = p                    roots_in_base = {root}                    while new_base < pow(p, e):                        new_base *= p                        new_roots = set()                        for k in roots_in_base:                            if (pow(k, n) - a) % (new_base) != 0:                                continue                            while k not in new_roots:                                new_roots.add(k)                                k = (k + (new_base // p)) % new_base                        roots_in_base = new_roots                    tot_roots = tot_roots | roots_in_base        dd[pow(p, e)] = tot_roots    a = []    m = []    for x, y in dd.items():        m.append(x)        a.append(list(y))    return sorted(set(crt(m, list(i))[0] for i in cartes(*a)))</ins>  def nthroot_mod(a, n, p, all_roots=False):     """


if n == 2:         return sqrt_mod(a, p, all_roots)     # see Hackman "Elementary Number Theory" (2009), page 76    if not isprime(p):        return _nthroot_mod_composite(a, n, p)    if a % p == 0:        return [0]     if not is_nthpow_residue(a, n, p):         return None    if not isprime(p):        raise NotImplementedError("Not implemented for composite p")     if (p - 1) % n == 0:         return _nthroot_mod1(a, n, p, all_roots)     # The roots of ``x**n - a = 0 (mod p)`` are roots of


# diophantine equations f(n)=g(m).     # If the solutions for n are {h(t) : t in Integers} then we return     # {f(h(t)) : t in integers}.    # If the solutions for n are {n_1, n_2, ..., n_k} then we return    # {f(n_i) : 1 <= i <= k}.     if base_set is S.Integers:         gm = None         if isinstance(other, ImageSet) and other.base_sets == (S.Integers,):             gm = other.lamda.expr            m = other.lamda.variables[0]            var = other.lamda.variables[0]            # Symbol of second ImageSet lambda must be distinct from first            m = Dummy('m')            gm = gm.subs(var, m)         elif other is S.Integers:            m = gm = Dummy('x')            m = gm = Dummy('m')         if gm is not None:             fn = self.lamda.expr             n = self.lamda.variables[0]            solns = list(diophantine(fn - gm, syms=(n, m)))            try:                solns = list(diophantine(fn - gm, syms=(n, m), permute=True))            except (TypeError, NotImplementedError):                # TypeError if equation not polynomial with rational coeff.                # NotImplementedError if correct format but no solver.                return            # 3 cases are possible for solns:            # - empty set,            # - one or more parametric (infinite) solutions,            # - a finite number of (non-parametric) solution couples.            # Among those, there is one type of solution set that is            # not helpful here: multiple parametric solutions.             if len(solns) == 0:                 return EmptySet            elif len(solns) != 1:                return            elif any(not isinstance(s, int) and s.free_symbols                     for tupl in solns for s in tupl):                if len(solns) == 1:                    soln, solm = solns[0]                    (t,) = soln.free_symbols                    expr = fn.subs(n, soln.subs(t, n)).expand()                    return imageset(Lambda(n, expr), S.Integers)                else:                    return             else:                soln, solm = solns[0]                (t,) = soln.free_symbols                expr = fn.subs(n, soln.subs(t, n))                return imageset(Lambda(n, expr), S.Integers)                return FiniteSet(*(fn.subs(n, s[0]) for s in solns))      if other == S.Reals:         from sympy.solvers.solveset import solveset_realdiff --git a/sympy/solvers/diophantine.py b/sympy/solvers/diophantine.py-- a/sympy/solvers/diophantine.py++ b/sympy/solvers/diophantine.py


else:             raise TypeError     except (TypeError, NotImplementedError):        terms = factor_list(eq)[1]        fl = factor_list(eq)        if fl[0].is_Rational and fl[0] != 1:            return diophantine(eq/fl[0], param=param, syms=syms, permute=permute)        terms = fl[1]      sols = set([])


def _eval_as_set(self):         # self is univariate and periodicity(self, x) in (0, None)         from sympy.solvers.inequalities import solve_univariate_inequality        from sympy.sets.conditionset import ConditionSet         syms = self.free_symbols         assert len(syms) == 1         x = syms.pop()        return solve_univariate_inequality(self, x, relational=False)        try:            xset = solve_univariate_inequality(self, x, relational=False)        except NotImplementedError:            # solve_univariate_inequality raises NotImplementedError for            # unsolvable equations/inequalities.            xset = ConditionSet(x, self, S.Reals)        return xset      @property     def binary_symbols(self):


"gothic_re_im": False,         "decimal_separator": "period",         "perm_cyclic": True,<ins>        "parenthesize_super": True,</ins>         "min": None,         "max": None,     }  # type: Dict[str, Any]


def parenthesize_super(self, s):         """ Parenthesize s if there is a superscript in s"""        if "^" in s:        if "^" in s and self._settings['parenthesize_super']:             return r"\left({}\right)".format(s)        elif "^" in s and not self._settings['parenthesize_super']:            return self.embed_super(s)         return s      def embed_super(self, s):


p, q = expr.exp.p, expr.exp.q             # issue #12886: add parentheses for superscripts raised to powers             if '^' in base and expr.base.is_Symbol:                base = r"\left(%s\right)" % base                base = self.parenthesize_super(base)             if expr.base.is_Function:                 return self._print(expr.base, exp="%s/%s" % (p, q))             return r"%s^{%s/%s}" % (base, p, q)


# to powers         base = self.parenthesize(expr.base, PRECEDENCE['Pow'])         if '^' in base and expr.base.is_Symbol:            base = r"\left(%s\right)" % base            base = self.parenthesize_super(base)         elif (isinstance(expr.base, Derivative)             and base.startswith(r'\left(')             and re.match(r'\\left\(\\d?d?dot', base)


else:                     name = r"\operatorname{%s}^{-1}" % func             elif exp is not None:                name = r'%s^{%s}' % (self._hprint_Function(func), exp)                func_tex = self._hprint_Function(func)                func_tex = self.parenthesize_super(func_tex)                name = r'%s^{%s}' % (func_tex, exp)             else:                 name = self._hprint_Function(func)


mat_delim="[", mat_str=None, mode="plain", mul_symbol=None,           order=None, symbol_names=None, root_notation=True,           mat_symbol_style="plain", imaginary_unit="i", gothic_re_im=False,          decimal_separator="period", perm_cyclic=True):          decimal_separator="period", perm_cyclic=True, parenthesize_super=True):     r"""Convert the given expression to LaTeX string representation.      Parameters


when ``comma`` is specified. Lists, sets, and tuple are printed with semicolon         separating the elements when ``comma`` is chosen. For example, [1; 2; 3] when         ``comma`` is chosen and [1,2,3] for when ``period`` is chosen.<ins>    parenthesize_super : boolean, optional        If set to ``False``, superscripted expressions will not be parenthesized when        powered. Default is ``True``, which parenthesizes the expression when powered.</ins>     min: Integer or None, optional         Sets the lower bound for the exponent to print floating point numbers in         fixed-point format.


'gothic_re_im': gothic_re_im,         'decimal_separator': decimal_separator,         'perm_cyclic' : perm_cyclic,<ins>        'parenthesize_super' : parenthesize_super,</ins>         'min': min,         'max': max,     }


self._print(expr.matrix),                                self._print(expr.vector)) <ins>    def _print_ZeroMatrix(self, expr):        return '{}({})'.format(self._module_format('numpy.zeros'),            self._print(expr.shape))    def _print_OneMatrix(self, expr):        return '{}({})'.format(self._module_format('numpy.ones'),            self._print(expr.shape))    def _print_FunctionMatrix(self, expr):        from sympy.core.function import Lambda        from sympy.abc import i, j        lamda = expr.lamda        if not isinstance(lamda, Lambda):            lamda = Lambda((i, j), lamda(i, j))        return '{}(lambda {}: {}, {})'.format(self._module_format('numpy.fromfunction'),            ', '.join(self._print(arg) for arg in lamda.args[0]),            self._print(lamda.args[1]), self._print(expr.shape))    def _print_HadamardProduct(self, expr):        func = self._module_format('numpy.multiply')        return ''.join('{}({}, '.format(func, self._print(arg)) \            for arg in expr.args[:-1]) + "{}{}".format(self._print(expr.args[-1]),            ')' * (len(expr.args) - 1))    def _print_KroneckerProduct(self, expr):        func = self._module_format('numpy.kron')        return ''.join('{}({}, '.format(func, self._print(arg)) \            for arg in expr.args[:-1]) + "{}{}".format(self._print(expr.args[-1]),            ')' * (len(expr.args) - 1))    def _print_Adjoint(self, expr):        return '{}({}({}))'.format(            self._module_format('numpy.conjugate'),            self._module_format('numpy.transpose'),            self._print(expr.args[0]))    def _print_DiagonalOf(self, expr):        vect = '{}({})'.format(            self._module_format('numpy.diag'),            self._print(expr.arg))        return '{}({}, (-1, 1))'.format(            self._module_format('numpy.reshape'), vect)    def _print_DiagMatrix(self, expr):        return '{}({})'.format(self._module_format('numpy.diagflat'),            self._print(expr.args[0]))    def _print_DiagonalMatrix(self, expr):        return '{}({}, {}({}, {}))'.format(self._module_format('numpy.multiply'),            self._print(expr.arg), self._module_format('numpy.eye'),            self._print(expr.shape[0]), self._print(expr.shape[1]))</ins>     def _print_Piecewise(self, expr):         "Piecewise function printer"         exprs = '[{0}]'.format(','.join(self._print(arg.expr) for arg in expr.args))


if types:             types = tuple(                 [t if isinstance(t, type) else type(t) for t in types])        nodes = preorder_traversal(self)        if types:            result = {node for node in nodes if isinstance(node, types)}         else:            types = (Atom,)        result = set()        for expr in preorder_traversal(self):            if isinstance(expr, types):                result.add(expr)            result = {node for node in nodes if not node.args}         return result      @property


if isinstance(a, Cycle):  # f                 return cls._af_new(a.list(size))             if not is_sequence(a):  # b<ins>                if size is not None and a + 1 > size:                    raise ValueError('size is too small when max is %s' % a)</ins>                 return cls._af_new(list(range(a + 1)))             if has_variety(is_sequence(ai) for ai in a):                 ok = False


raise ValueError('there were repeated elements.')         temp = set(temp)         if not is_cycle and \                any(i not in temp for i in range(len(temp))):            raise ValueError("Integers 0 through %s must be present." %                             max(temp))        if not is_cycle:            if any(i not in temp for i in range(len(temp))):                raise ValueError('Integers 0 through %s must be present.' %                max(temp))            if size is not None and temp and max(temp) + 1 > size:                raise ValueError('max element should not exceed %s' % (size - 1))          if is_cycle:             # it's not necessarily canonical so we won't storediff --git a/sympy/matrices/common.py b/sympy/matrices/common.py-- a/sympy/matrices/common.py++ b/sympy/matrices/common.py


isinstance(perm[0], Iterable):             if direction == 'forward':                 perm = list(reversed(perm))            perm = Permutation(perm, size=max_index)            perm = Permutation(perm, size=max_index+1)         else:            perm = Permutation(perm, size=max_index)            perm = Permutation(perm, size=max_index+1)          if orientation == 'rows':             return self._eval_permute_rows(perm)


from sympy.core.symbol import _filter_assumptions, Symbol from sympy.core.compatibility import (is_sequence, NotIterable,                                       Iterable)from sympy.core.logic import fuzzy_boolfrom sympy.core.logic import fuzzy_bool, fuzzy_not from sympy.core.sympify import _sympify from sympy.functions.special.tensor_functions import KroneckerDelta


raise TypeError("Idx object requires integer bounds.")             args = label, Tuple(*range)         elif isinstance(range, Expr):            if not (range.is_integer or range is S.Infinity):            if range is not S.Infinity and fuzzy_not(range.is_integer):                 raise TypeError("Idx object requires an integer dimension.")             args = label, Tuple(0, range - 1)         elif range:


data = [[mats[i] if i == j else ZeroMatrix(mats[i].rows, mats[j].cols)                         for j in range(len(mats))]                         for i in range(len(mats))]        return ImmutableDenseMatrix(data)        return ImmutableDenseMatrix(data, evaluate=False)      @property     def shape(self):


return Piecewise((Sum(coeff * z**n / factorial(n), (n, 0, oo)),                          self.convergence_statement), (self, True)) <ins>    def _eval_nseries(self, x, n, logx):        from sympy.functions import factorial, RisingFactorial        from sympy import Order, Add        arg = self.args[2]        x0 = arg.limit(x, 0)        ap = self.args[0]        bq = self.args[1]        if x0 != 0:            return super(hyper, self)._eval_nseries(x, n, logx)        terms = []        for i in range(n):            num = 1            den = 1            for a in ap:                num *= RisingFactorial(a, i)            for b in bq:                den *= RisingFactorial(b, i)            terms.append(((num/den) * (arg**i)) / factorial(i))        return (Add(*terms) + Order(x**n,x))</ins>     @property     def argument(self):         """ Argument of the hypergeometric function. """


expr = expr.expr          args, indices, free, dum = cls._contract_indices_for_derivative(            expr, variables)            S(expr), variables)          obj = TensExpr.__new__(cls, *args)


result = obj         if isinstance(obj.expr, TensAdd):        if not args[0].free_symbols:            return S.Zero        elif isinstance(obj.expr, TensAdd):             # take care of sums of multi PDs             result = obj.expr.func(*[                     self.func(a, *obj.variables)._expand_partial_derivative()


rv = S.One         if cargs:<ins>            if e.is_Rational:                npow, cargs = sift(cargs, lambda x: x.is_Pow and                    x.exp.is_Rational and x.base.is_number,                    binary=True)                rv = Mul(*[self.func(b.func(*b.args), e) for b in npow])</ins>             rv *= Mul(*[self.func(b, e, evaluate=False) for b in cargs])         if other:             rv *= self.func(Mul(*other), e, evaluate=False)


<ins>"""The Schur number S(k) is the largest integer n for which the interval [1,n]can be partitioned into k sum-free sets.(http://mathworld.wolfram.com/SchurNumber.html)"""import mathfrom sympy.core import Sfrom sympy.core.basic import Basicfrom sympy.core.function import Functionfrom sympy.core.numbers import Integerclass SchurNumber(Function):    """    This function creates a SchurNumber object    which is evaluated for k <= 4 otherwise only    the lower bound information can be retrieved.    Examples    ========    >>> from sympy.combinatorics.schur_number import SchurNumber    Since S(3) = 13, hence the output is a number    >>> SchurNumber(3)    13    We don't know the schur number for values greater than 4, hence    only the object is returned    >>> SchurNumber(6)    SchurNumber(6)    Now, the lower bound information can be retrieved using lower_bound()    method    >>> SchurNumber(6).lower_bound()    364    """    @classmethod    def eval(cls, k):        if k.is_Number:            if k is S.Infinity:                return S.Infinity            if k.is_zero:                return 0            if not k.is_integer or k.is_negative:                raise ValueError("k should be a positive integer")            first_known_schur_numbers = {1: 1, 2: 4, 3: 13, 4: 44}            if k <= 4:                return Integer(first_known_schur_numbers[k])    def lower_bound(self):        f_ = self.args[0]        return (3**f_ - 1)/2def _schur_subsets_number(n):    if n is S.Infinity:        raise ValueError("Input must be finite")    if n <= 0:        raise ValueError("n must be a non-zero positive integer.")    elif n <= 3:        min_k = 1    else:        min_k = math.ceil(math.log(2*n + 1, 3))    return Integer(min_k)def schur_partition(n):    """    This function returns the partition in the minimum number of sum-free subsets    according to the lower bound given by the Schur Number.    Parameters    ==========    n: a number        n is the upper limit of the range [1, n] for which we need to find and        return the minimum number of free subsets according to the lower bound        of schur number    Returns    =======    List of lists        List of the minimum number of sum-free subsets    Notes    =====    It is possible for some n to make the partition into less    subsets since the only known Schur numbers are:    S(1) = 1, S(2) = 4 , S(3) = 13, S(4) = 44.    e.g for n = 44 the lower bound from the function above is 5 subsets but it has been proven    that can be done with 4 subsets.    Examples    ========    For n = 1, 2, 3 the answer is the set itself    >>> from sympy.combinatorics.schur_number import schur_partition    >>> schur_partition(2)    [[1, 2]]    For n > 3, the answer is the minimum number of sum-free subsets:    >>> schur_partition(5)    [[3, 2], [5], [1, 4]]    >>> schur_partition(8)    [[3, 2], [6, 5, 8], [1, 4, 7]]    """    if isinstance(n, Basic) and not n.is_Number:        raise ValueError("Input value must be a number")    number_of_subsets = _schur_subsets_number(n)    if n == 1:        sum_free_subsets = [[1]]    elif n == 2:        sum_free_subsets = [[1, 2]]    elif n == 3:        sum_free_subsets = [[1, 2, 3]]    else:        sum_free_subsets = [[1, 4], [2, 3]]    while len(sum_free_subsets) < number_of_subsets:        sum_free_subsets = _generate_next_list(sum_free_subsets, n)        missed_elements = [3*k + 1 for k in range(len(sum_free_subsets), (n-1)//3 + 1)]        sum_free_subsets[-1] += missed_elements    return sum_free_subsetsdef _generate_next_list(current_list, n):    new_list = []    for item in current_list:        temp_1 = [number*3 for number in item if number*3 <= n]        temp_2 = [number*3 - 1 for number in item if number*3 - 1 <= n]        new_item = temp_1 + temp_2        new_list.append(new_item)    last_list = [3*k + 1 for k in range(0, len(current_list)+1) if 3*k + 1 <= n]    new_list.append(last_list)    current_list = new_list    return current_list</ins>


from __future__ import print_function, division from functools import wrapsfrom functools import wraps, reducefrom operator import mul  from sympy.core import (     S, Basic, Expr, I, Integer, Add, Mul, Dummy, Tuple


if arg.is_Number:             coeff *= arg             continue        if arg.is_Mul:            args.extend(arg.args)            continue        if arg.is_Pow:        elif arg.is_Pow:             base, exp = arg.args             if base.is_Number and exp.is_Number:                 coeff *= arg


other.append((f, k))                  factors.append((_factors_product(other), exp))<ins>    if method == 'sqf':        factors = [(reduce(mul, (f for f, _ in factors if _ == k)), k)                   for k in set(i for _, i in factors)]</ins>      return coeff, factors


elif self.exp.is_extended_nonpositive:                 return False         elif self.base.is_zero is False:            if self.exp.is_negative:            if self.base.is_finite and self.exp.is_finite:                return False            elif self.exp.is_negative:                 return self.base.is_infinite             elif self.exp.is_nonnegative:                 return False            elif self.exp.is_infinite:            elif self.exp.is_infinite and self.exp.is_extended_real:                 if (1 - abs(self.base)).is_extended_positive:                     return self.exp.is_extended_positive                 elif (1 - abs(self.base)).is_extended_negative:                     return self.exp.is_extended_negative        else:            # when self.base.is_zero is None            return None        else: # when self.base.is_zero is None            if self.base.is_finite and self.exp.is_negative:                return False      def _eval_is_integer(self):         b, e = self.args


if real_b is False:  # we already know it's not imag             i = arg(self.base)*self.exp/S.Pi            return i.is_integer            if i.is_complex: # finite                return i.is_integer      def _eval_is_complex(self):


latex_new = (self._print(e) for e in new)         latex_subs = r'\\ '.join(             e[0] + '=' + e[1] for e in zip(latex_old, latex_new))        return r'\left. %s \right|_{\substack{ %s }}' % (latex_expr,        return r'\left. \left(%s\right) \right|_{\substack{ %s }}' % (latex_expr,                                                          latex_subs)      def _print_Integral(self, expr):


"""     is_HadamardProduct = True     def __new__(cls, *args, **kwargs):    def __new__(cls, *args, evaluate=False, **kwargs):         args = list(map(sympify, args))         check = kwargs.get('check', True)         if check:             validate(*args)         return super(HadamardProduct, cls).__new__(cls, *args)        obj = super(HadamardProduct, cls).__new__(cls, *args)        if evaluate:            obj = obj.doit(deep=False)        return obj      @property     def shape(self):diff --git a/sympy/matrices/expressions/matadd.py b/sympy/matrices/expressions/matadd.py-- a/sympy/matrices/expressions/matadd.py++ b/sympy/matrices/expressions/matadd.py


identity = GenericZeroMatrix()     def __new__(cls, *args, **kwargs):    def __new__(cls, *args, evaluate=False, **kwargs):         if not args:             return cls.identity


check = kwargs.get('check', False)          obj = Basic.__new__(cls, *args)         if check:             if all(not isinstance(i, MatrixExpr) for i in args):                 return Add.fromiter(args)             validate(*args)        if evaluate:            if all(not isinstance(i, MatrixExpr) for i in args):                return Add(*args, evaluate=True)            obj = canonicalize(obj)         return obj      @propertydiff --git a/sympy/matrices/expressions/matmul.py b/sympy/matrices/expressions/matmul.py-- a/sympy/matrices/expressions/matmul.py++ b/sympy/matrices/expressions/matmul.py


identity = GenericIdentity()     def __new__(cls, *args, **kwargs):    def __new__(cls, *args, evaluate=False, **kwargs):         check = kwargs.get('check', True)          if not args:


args = list(map(sympify, args))         obj = Basic.__new__(cls, *args)         factor, matrices = obj.as_coeff_matrices()         if check:             validate(*matrices)         if not matrices:             # Should it be             #             # return Basic.__neq__(cls, factor, GenericIdentity()) ?             return factor        if evaluate:            return canonicalize(obj)         return obj      @propertydiff --git a/sympy/matrices/expressions/matpow.py b/sympy/matrices/expressions/matpow.py-- a/sympy/matrices/expressions/matpow.py++ b/sympy/matrices/expressions/matpow.py


class MatPow(MatrixExpr):     def __new__(cls, base, exp):    def __new__(cls, base, exp, evaluate=False, **options):         base = _sympify(base)         if not base.is_Matrix:             raise TypeError("Function parameter should be a matrix")         exp = _sympify(exp)        return super(MatPow, cls).__new__(cls, base, exp)        obj = super(MatPow, cls).__new__(cls, base, exp)        if evaluate:            obj = obj.doit(deep=False)        return obj      @property     def base(self):


========     sympy.functions.combinatorial.factorials.subfactorial     """    p = multiset_permutations(perm)    indices = range(len(perm))    p0 = next(p)    for pi in p:        if all(pi[i] != p0[i] for i in indices):            yield pi    for p in multiset_permutations(perm):        if not any(i == j for i, j in zip(perm, p)):            yield p   def necklaces(n, k, free=False):


def uniq(seq, result=None):     """     Yield unique elements from ``seq`` as an iterator. The second    parameter ``result``  is used internally; it is not necessary to pass    anything for this.    parameter ``result``  is used internally; it is not necessary    to pass anything for this.    Note: changing the sequence during iteration will raise a    RuntimeError if the size of the sequence is known; if you pass    an iterator and advance the iterator you will change the    output of this routine but there will be no warning.      Examples     ========


>>> list(uniq([[1], [2, 1], [1]]))     [[1], [2, 1]]     """    try:        n = len(seq)    except TypeError:        n = None    def check():        # check that size of seq did not change during iteration;        # if n == None the object won't support size changing, e.g.        # an iterator can't be changed        if n is not None and len(seq) != n:            raise RuntimeError('sequence changed size during iteration')     try:         seen = set()         result = result or []         for i, s in enumerate(seq):             if not (s in seen or seen.add(s)):                 yield s                check()     except TypeError:         if s not in result:             yield s            check()             result.append(s)         if hasattr(seq, '__getitem__'):             for s in uniq(seq[i + 1:], result):


self._module_format("scipy.special.fresnel"),                 self._print(expr.args[0])) <ins>    def _print_airyai(self, expr):        return "{0}({1})[0]".format(                self._module_format("scipy.special.airy"),                self._print(expr.args[0]))    def _print_airyaiprime(self, expr):        return "{0}({1})[1]".format(                self._module_format("scipy.special.airy"),                self._print(expr.args[0]))    def _print_airybi(self, expr):        return "{0}({1})[2]".format(                self._module_format("scipy.special.airy"),                self._print(expr.args[0]))    def _print_airybiprime(self, expr):        return "{0}({1})[3]".format(                self._module_format("scipy.special.airy"),                self._print(expr.args[0]))</ins>  for k in SciPyPrinter._kf:     setattr(SciPyPrinter, '_print_%s' % k, _print_known_func)


return [start + (stop - start) * x / (num-1) for x in range(num)]  def textplot_str(expr, a, b, W=55, H=18):def textplot_str(expr, a, b, W=55, H=21):     """Generator for the lines of the plot"""     free = expr.free_symbols     if len(free) > 1:


mi, ma = -1, 1     else:         mi, ma = -1, 1<ins>    y_range = ma - mi    precision = math.floor(math.log(y_range, 10)) - 1    precision *= -1    mi = round(mi, precision)    ma = round(ma, precision)</ins>     y = rescale(y, W, H, mi, ma)      y_bins = linspace(mi, ma, H)


else:                     s[i] = '.' <ins>        if h == 0:            for i in range(W):                s[i] = '_'</ins>         # Print y values         if h in (0, H//2, H - 1):             prefix = ("%g" % y_bins[h]).rjust(margin)[:margin]


s = "".join(s)         if h == H//2:             s = s.replace(" ", "-")        yield prefix + " | " + s        yield prefix + " |" + s      # Print x values    bottom = " " * (margin + 3)    bottom = " " * (margin + 2)     bottom += ("%g" % x[0]).ljust(W//2)     if W % 2 == 1:         bottom += ("%g" % x[W//2]).ljust(W//2)


yield bottom  def textplot(expr, a, b, W=55, H=18):def textplot(expr, a, b, W=55, H=21):     r"""     Print a crude ASCII art plot of the SymPy expression 'expr' (which     should contain a single symbol, e.g. x or something else) over the


>>> from sympy.plotting import textplot     >>> t = Symbol('t')     >>> textplot(sin(t)*t, 0, 15)    14.1605 |                                                   ...            |                                                      .            |                                                  .            |                                                 .     .            |                             ..            |                            /  ..               .            |                           /     .            |                          /    2.30284 | ------...---------------/--------.------------.--------            |   ....   ...           /            | ..          \         /           .          .            |              ..      /             .            |                ..   /                       .            |                  ...                .            |                                            .            |                                      .            |                                       \   .    -11.037 |                                        ...            0                          7.5                        15     14 |                                                  ...        |                                                     .        |                                                 .        |                                                      .        |                                                .        |                            ...        |                           /   .               .        |                          /        |                         /      .        |                        .        .            .    1.5 |----.......--------------------------------------------        |....       \           .          .        |            \         /                      .        |             ..      /             .        |               \    /                       .        |                ....        |                                    .        |                                     .     .        |        |                                      .   .    -11 |_______________________________________________________         0                          7.5                        15     """     for line in textplot_str(expr, a, b, W, H):         print(line)


from sympy.utilities.iterables import multiset, is_palindromic as _palindromic  def digits(n, b=10):def digits(n, b=10, digits=None):     """     Return a list of the digits of ``n`` in base ``b``. The first     element in the list is ``b`` (or ``-b`` if ``n`` is negative).


>>> from sympy.ntheory.digits import digits     >>> digits(35)     [10, 3, 5]    >>> digits(27, 2)    If the number is negative, the negative sign will be placed on the    base (which is the first element in the returned list):    >>> digits(-35)    [-10, 3, 5]    Bases other than 10 (and greater than 1) can be selected with ``b``:    >>> digits(27, b=2)     [2, 1, 1, 0, 1, 1]    >>> digits(65536, 256)    [256, 1, 0, 0]    >>> digits(-3958, 27)    [-27, 5, 11, 16]    Use the ``digits`` keyword if a certain number of digits is desired:    >>> digits(35, digits=4)    [10, 0, 0, 3, 5]    Parameters    ==========    n: integer        The number whose digits are returned.    b: integer        The base in which digits are computed.    digits: integer (or None for all digits)        The number of digits to be returned (padded with zeros, if        necessary).     """      b = as_int(b)     n = as_int(n)    if b <= 1:        raise ValueError("b must be >= 2")    if b < 2:        raise ValueError("b must be greater than 1")     else:         x, y = abs(n), []         while x >= b:


y.append(x)         y.append(-b if n < 0 else b)         y.reverse()<ins>        ndig = len(y) - 1        if digits is not None:            if ndig > digits:                raise ValueError(                    "For %s, at least %s digits are needed." % (n, ndig))            elif ndig < digits:                y[1:1] = [0]*(digits - ndig)</ins>         return y


from sympy.utilities import sift from sympy.utilities.misc import filldedent from sympy.matrices.expressions.matexpr import MatrixExpr, ZeroMatrix, Identityfrom sympy.matrices.expressions.matexpr import MatrixExpr, ZeroMatrix, Identity, MatrixElement from sympy.matrices.expressions.matmul import MatMul from sympy.matrices.expressions.matadd import MatAdd from sympy.matrices.expressions.matpow import MatPow


def _entry(self, i, j, **kwargs):         # Find row entry        orig_i, orig_j = i, j         for row_block, numrows in enumerate(self.rowblocksizes):            if (i < numrows) != False:            cmp = i < numrows            if cmp == True:                 break            else:            elif cmp == False:                 i -= numrows            elif row_block < self.blockshape[0] - 1:                # Can't tell which block and it's not the last one, return unevaluated                return MatrixElement(self, orig_i, orig_j)         for col_block, numcols in enumerate(self.colblocksizes):            if (j < numcols) != False:            cmp = j < numcols            if cmp == True:                 break            else:            elif cmp == False:                 j -= numcols            elif col_block < self.blockshape[1] - 1:                return MatrixElement(self, orig_i, orig_j)         return self.blocks[row_block, col_block][i, j]      @property


return S.Infinity         return Integer(abs(dif//self.step)) <ins>    @property    def is_finite_set(self):        if self.start.is_integer and self.stop.is_integer:            return True        return self.size.is_finite</ins>     def __nonzero__(self):         return self.start != self.stop


return lc, []      f, F = dmp_sqf_part(f, u, K), f    s, g, r = dmp_sqf_norm(f, u, K)    s, g, r = dmp_sqf_norm(F, u, K)      factors = dmp_factor_list_include(r, u, K.dom)


return recursor(self, ())      @staticmethod    def _match_indices_with_other_tensor(array, free_ind1, free_ind2, replacement_dict):    def _contract_and_permute_with_metric(metric, array, pos, dim):        # TODO: add possibility of metric after (spinors)         from .array import tensorcontraction, tensorproduct, permutedims         array = tensorcontraction(tensorproduct(metric, array), (1, 2+pos))        permu = list(range(dim))        permu[0], permu[pos] = permu[pos], permu[0]        return permutedims(array, permu)    @staticmethod    def _match_indices_with_other_tensor(array, free_ind1, free_ind2, replacement_dict):        from .array import permutedims         index_types1 = [i.tensor_index_type for i in free_ind1]          # Check if variance of indices needs to be fixed:


if len(set(free_ind1) & set(free_ind2)) < len(free_ind1):             raise ValueError("incompatible indices: %s and %s" % (free_ind1, free_ind2)) <del>        # TODO: add possibility of metric after (spinors)        def contract_and_permute(metric, array, pos):            array = tensorcontraction(tensorproduct(metric, array), (1, 2+pos))            permu = list(range(len(free_ind1)))            permu[0], permu[pos] = permu[pos], permu[0]            return permutedims(array, permu)</del>         # Raise indices:         for pos in pos2up:             index_type_pos = index_types1[pos]  # type: TensorIndexType


raise ValueError("No metric provided to lower index")             metric = replacement_dict[index_type_pos]             metric_inverse = _TensorDataLazyEvaluator.inverse_matrix(metric)            array = contract_and_permute(metric_inverse, array, pos)            array = TensExpr._contract_and_permute_with_metric(metric_inverse, array, pos, len(free_ind1))         # Lower indices:         for pos in pos2down:             index_type_pos = index_types1[pos]  # type: TensorIndexType             if index_type_pos not in replacement_dict:                 raise ValueError("No metric provided to lower index")             metric = replacement_dict[index_type_pos]            array = contract_and_permute(metric, array, pos)            array = TensExpr._contract_and_permute_with_metric(metric, array, pos, len(free_ind1))          if free_ind1:             permutation = TensExpr._get_indices_permutation(free_ind2, free_ind1)


# Remove elements in `dum2` from `dum1`:             dum1 = [pair for pair in dum1 if pair not in dum2]         if len(dum1) > 0:            indices1 = self.get_indices()             indices2 = other.get_indices()             repl = {}             for p1, p2 in dum1:                 repl[indices2[p2]] = -indices2[p1]                for pos in (p1, p2):                    if indices1[pos].is_up ^ indices2[pos].is_up:                        metric = replacement_dict[indices1[pos].tensor_index_type]                        if indices1[pos].is_up:                            metric = _TensorDataLazyEvaluator.inverse_matrix(metric)                        array = self._contract_and_permute_with_metric(metric, array, pos, len(indices2))             other = other.xreplace(repl).doit()             array = _TensorDataLazyEvaluator.data_contract_dum([array], dum1, len(indices2))


def _entry(self, i, j, **kwargs):         return S.Zero <del>    def __nonzero__(self):        return False    __bool__ = __nonzero__</del> class GenericZeroMatrix(ZeroMatrix):     """     A zero matrix without a specified shape


from .singleton import S from .operations import AssocOp from .cache import cacheitfrom .logic import fuzzy_not, _fuzzy_groupfrom .logic import fuzzy_not, _fuzzy_group, fuzzy_and from .compatibility import reduce from .expr import Expr from .parameters import global_parameters


def _eval_is_integer(self):         from sympy import fraction        from sympy.core.numbers import Float          is_rational = self._eval_is_rational()         if is_rational is False:             return False         n, d = fraction(self)        if not is_rational:            _self = n/d            if _self != self:                return _self.is_integer        # use exact=True to avoid recomputing num or den        n, d = fraction(self, exact=True)         if is_rational:             if d is S.One:                 return True            elif d == S(2):        if d.is_even:            if d.is_prime:  # literal or symbolic 2                 return n.is_even        # if d is even -- 0 or not -- the        # result is not an integer        if n.is_odd and d.is_even:            return False            if n.is_odd:                return False  # true even if d = 0        if n == d:            return fuzzy_and([not bool(self.atoms(Float)),            fuzzy_not(d.is_zero)])      def _eval_is_polar(self):         has_polar = any(arg.is_polar for arg in self.args)


>>> X[:, 1:5][5:8, :]     X[5:8, 1:5]     >>> X[1:9:2, 2:6][1:3, 2]    X[3:7:2, 4]    X[3:7:2, 4:5]     """     row = slice_of_slice(parent.rowslice, rowslice)     col = slice_of_slice(parent.colslice, colslice)diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py-- a/sympy/printing/latex.py++ b/sympy/printing/latex.py


+ '_{%s, %s}' % (self._print(expr.i), self._print(expr.j))      def _print_MatrixSlice(self, expr):        def latexslice(x):        def latexslice(x, dim):             x = list(x)             if x[2] == 1:                 del x[2]            if x[1] == x[0] + 1:                del x[1]             if x[0] == 0:                 x[0] = ''            if x[1] == dim:                x[1] = ''             return ':'.join(map(self._print, x))        return (self._print(expr.parent) + r'\left[' +                latexslice(expr.rowslice) + ', ' +                latexslice(expr.colslice) + r'\right]')        return (self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) + r'\left[' +                latexslice(expr.rowslice, expr.parent.rows) + ', ' +                latexslice(expr.colslice, expr.parent.cols) + r'\right]')      def _print_BlockMatrix(self, expr):         return self._print(expr.blocks)diff --git a/sympy/printing/pretty/pretty.py b/sympy/printing/pretty/pretty.py-- a/sympy/printing/pretty/pretty.py++ b/sympy/printing/pretty/pretty.py


def _print_MatrixSlice(self, m):         # XXX works only for applied functions        from sympy.matrices import MatrixSymbol         prettyFunc = self._print(m.parent)        def ppslice(x):        if not isinstance(m.parent, MatrixSymbol):            prettyFunc = prettyForm(*prettyFunc.parens())        def ppslice(x, dim):             x = list(x)             if x[2] == 1:                 del x[2]            if x[1] == x[0] + 1:                del x[1]             if x[0] == 0:                 x[0] = ''            if x[1] == dim:                x[1] = ''             return prettyForm(*self._print_seq(x, delimiter=':'))        prettyArgs = self._print_seq((ppslice(m.rowslice),            ppslice(m.colslice)), delimiter=', ').parens(left='[', right=']')[0]        prettyArgs = self._print_seq((ppslice(m.rowslice, m.parent.rows),            ppslice(m.colslice, m.parent.cols)), delimiter=', ').parens(left='[', right=']')[0]          pform = prettyForm(             binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs))diff --git a/sympy/printing/str.py b/sympy/printing/str.py-- a/sympy/printing/str.py++ b/sympy/printing/str.py


+ '[%s, %s]' % (self._print(expr.i), self._print(expr.j))      def _print_MatrixSlice(self, expr):        def strslice(x):        def strslice(x, dim):             x = list(x)             if x[2] == 1:                 del x[2]            if x[1] == x[0] + 1:                del x[1]             if x[0] == 0:                 x[0] = ''            if x[1] == dim:                x[1] = ''             return ':'.join(map(lambda arg: self._print(arg), x))        return (self._print(expr.parent) + '[' +                strslice(expr.rowslice) + ', ' +                strslice(expr.colslice) + ']')        return (self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) + '[' +                strslice(expr.rowslice, expr.parent.rows) + ', ' +                strslice(expr.colslice, expr.parent.cols) + ']')      def _print_DeferredVector(self, expr):         return expr.name


def dup_zz_mignotte_bound(f, K):    """Mignotte bound for univariate polynomials in `K[x]`. """    a = dup_max_norm(f, K)    b = abs(dup_LC(f, K))    n = dup_degree(f)    """    The Knuth-Cohen variant of Mignotte bound for    univariate polynomials in `K[x]`.     return K.sqrt(K(n + 1))*2**n*a*b    Examples    ========    >>> from sympy.polys import ring, ZZ    >>> R, x = ring("x", ZZ)    >>> f = x**3 + 14*x**2 + 56*x + 64    >>> R.dup_zz_mignotte_bound(f)    152    By checking `factor(f)` we can see that max coeff is 8    Also consider a case that `f` is irreducible for example `f = 2*x**2 + 3*x + 4`    To avoid a bug for these cases, we return the bound plus the max coefficient of `f`    >>> f = 2*x**2 + 3*x + 4    >>> R.dup_zz_mignotte_bound(f)    6    Lastly,To see the difference between the new and the old Mignotte bound    consider the irreducible polynomial::    >>> f = 87*x**7 + 4*x**6 + 80*x**5 + 17*x**4 + 9*x**3 + 12*x**2 + 49*x + 26    >>> R.dup_zz_mignotte_bound(f)    744    The new Mignotte bound is 744 whereas the old one (SymPy 1.5.1) is 1937664.    References    ==========    ..[1] [Abbott2013]_    """    from sympy import binomial    d = dup_degree(f)    delta = _ceil(d / 2)    delta2 = _ceil(delta / 2)    # euclidean-norm    eucl_norm = K.sqrt( sum( [cf**2 for cf in f] ) )    # biggest values of binomial coefficients (p. 538 of reference)    t1 = binomial(delta - 1, delta2)    t2 = binomial(delta - 1, delta2 - 1)    lc = K.abs(dup_LC(f, K))   # leading coefficient    bound = t1 * eucl_norm + t2 * lc   # (p. 538 of reference)    bound += dup_max_norm(f, K) # add max coeff for irreducible polys    bound = _ceil(bound / 2) * 2   # round up to even integer     return bound  def dmp_zz_mignotte_bound(f, u, K):     """Mignotte bound for multivariate polynomials in `K[X]`. """


def _print_list(self, expr):         return "[%s]" % self.reprify(expr, ", ") <ins>    def _print_dict(self, expr):        sep = ", "        dict_kvs = ["%s: %s" % (self.doprint(key), self.doprint(value)) for key, value in expr.items()]        return "{%s}" % sep.join(dict_kvs)    def _print_set(self, expr):        if not expr:            return "set()"        return "{%s}" % self.reprify(expr, ", ")</ins>     def _print_MatrixBase(self, expr):         # special case for some empty matrices         if (expr.rows == 0) ^ (expr.cols == 0):


if arg.is_extended_real:             return Heaviside(arg, H0=S(1)/2) * 2 - 1 <ins>    def _eval_rewrite_as_Abs(self, arg, **kwargs):        return Piecewise((0, Eq(arg, 0)), (arg / Abs(arg), True))</ins>     def _eval_simplify(self, **kwargs):         return self.func(self.args[0].factor())  # XXX include doit?


>>> _.subs(y, 1)     ConditionSet(y, y < 1, FiniteSet(z)) <del>    Notes    =====</del>     If no base set is specified, the universal set is implied:      >>> ConditionSet(x, x < 1).base_set


Although the name is usually respected, it must be replaced if     the base set is another ConditionSet and the dummy symbol    and appears as a free symbol in the base set and the dummy symbol    appears as a free symbol in the base set and the dummy symbol     of the base set appears as a free symbol in the condition:      >>> ConditionSet(x, x < y, ConditionSet(y, x + y < 2, S.Integers))


>>> _.subs(_.sym, Symbol('_x'))     ConditionSet(_x, (_x < y) & (_x + x < 2), Integers)<ins></ins>     """     def __new__(cls, sym, condition, base_set=S.UniversalSet):         # nonlinsolve uses ConditionSet to return an unsolved system


# the base set should be filtered and if new is not in             # the base set then this substitution is ignored             return self.func(sym, cond, base)        cond = self.condition.subs(old, new)        base = self.base_set.subs(old, new)        if cond is S.true:            return ConditionSet(new, Contains(new, base), base)        return self.func(self.sym, cond, base)        else:            cond = self.condition.subs(old, new)            base = self.base_set.subs(old, new)            # The condition may have become true due to assumptions            # on 'sym'. In order for .subs() to be consistent with            # __new__ we *don't* check if 'sym' actually belongs to            # 'base'. In other words: assumptions are ignored.            return self.func(self.sym, cond, base)      def dummy_eq(self, other, symbol=None):         if not isinstance(other, self.func):


if not isinstance(rv, dict):             return rv.xreplace(urep)         else:            return {urep.get(k, k): v for k, v in rv.items()}            return {urep.get(k, k): v.xreplace(urep) for k, v in rv.items()}      if evaluate is None:         evaluate = global_parameters.evaluate


while kern in s:                 kern += choice(string.ascii_letters + string.digits)             s = s.replace(' ', kern)        hit = kern in s            hit = kern in s        else:            hit = False      for i in range(2):         try:


if isinstance(element, FracElement):             if self == element.field:                 return element            if isinstance(self.domain, FractionField) and \                self.domain.field == element.field:                return self.ground_new(element)            elif isinstance(self.domain, PolynomialRing) and \                self.domain.ring.to_field() == element.field:                return self.ground_new(element)             else:                 raise NotImplementedError("conversion")         elif isinstance(element, PolyElement):             denom, numer = element.clear_denoms()            numer = numer.set_ring(self.ring)            if isinstance(self.domain, PolynomialRing) and \                numer.ring == self.domain.ring:                numer = self.ring.ground_new(numer)            elif isinstance(self.domain, FractionField) and \                numer.ring == self.domain.field.to_ring():                numer = self.ring.ground_new(numer)            else:                numer = numer.set_ring(self.ring)             denom = self.ring.ground_new(denom)             return self.raw_new(numer, denom)         elif isinstance(element, tuple) and len(element) == 2:


"""Hermitian conjugation.""" from __future__ import print_function, divisionfrom sympy.core import Exprfrom sympy.core import Expr, Mul from sympy.functions.elementary.complexes import adjoint  __all__ = [


return obj         return Expr.__new__(cls, arg)     def __mul__(self, other):        from sympy.physics.quantum import IdentityOperator        if isinstance(other, IdentityOperator):            return self        return Mul(self, other) adjoint.__name__ = "Dagger" adjoint._sympyrepr = lambda a, b: "Dagger(%s)" % b._print(a.args[0])diff --git a/sympy/physics/quantum/operator.py b/sympy/physics/quantum/operator.py-- a/sympy/physics/quantum/operator.py++ b/sympy/physics/quantum/operator.py


def __mul__(self, other):         if isinstance(other, Operator):        if isinstance(other, (Operator, Dagger)):             return other          return Mul(self, other)


pivots    = list(filter(lambda p: p < col, pivots))     rank      = len(pivots)     # Bring to block form    permutation = Matrix(range(col)).T    # Get index of free symbols (free parameters)    # non-pivots columns are free variables    free_var_index = [c for c in range(A.cols) if c not in pivots]     for i, c in enumerate(pivots):        permutation.col_swap(i, c)    # Bring to block form    permutation = Matrix(pivots + free_var_index).T      # check for existence of solutions     # rank of aug Matrix should be equal to rank of coefficient matrix     if not v[rank:, :].is_zero_matrix:         raise ValueError("Linear system has no solution")     # Get index of free symbols (free parameters)    # non-pivots columns are free variables    free_var_index = permutation[len(pivots):]     # Free parameters     # what are current unnumbered free symbol names?     name = uniquely_named_symbol('tau', aug,


col - rank, B_cols)      # Full parametric solution    V        = A[:rank, [c for c in range(A.cols) if c not in pivots]]    V        = A[:rank, free_var_index]     vt       = v[:rank, :]     free_sol = tau.vstack(vt - V * tau, tau)


# check if the system is minimal with                 # respect to the already discovere ones                 minimal = True                to_remove = []                blocks_remove_mask = [False] * len(blocks)                 for i, r in enumerate(rep_blocks):                     if len(r) > len(rep) and rep.issubset(r):                         # i-th block system is not minimal                        del num_blocks[i], blocks[i]                        to_remove.append(rep_blocks[i])                        blocks_remove_mask[i] = True                     elif len(r) < len(rep) and r.issubset(rep):                         # the system being checked is not minimal                         minimal = False                         break                 # remove non-minimal representative blocks                rep_blocks = [r for r in rep_blocks if r not in to_remove]                blocks = [b for i, b in enumerate(blocks) if not blocks_remove_mask[i]]                num_blocks = [n for i, n in enumerate(num_blocks) if not blocks_remove_mask[i]]                rep_blocks = [r for i, r in enumerate(rep_blocks) if not blocks_remove_mask[i]]                  if minimal and num_block not in num_blocks:                     blocks.append(block)


Examples         ========         >>> from sympy.physics.vector import Point, ReferenceFrame        >>> from sympy.physics.vector import Point, ReferenceFrame, dynamicsymbols         >>> N = ReferenceFrame('N')         >>> p1 = Point('p1')         >>> p1.set_vel(N, 10 * N.x)         >>> p1.vel(N)         10*N.x         Velocities will be automatically calculated if possible, otherwise a ``ValueError`` will be returned. If it is possible to calculate multiple different velocities from the relative points, the points defined most directly relative to this point will be used. In the case of inconsistent relative positions of points, incorrect velocities may be returned. It is up to the user to define prior relative positions and velocities of points in a self-consistent way.        >>> p = Point('p')        >>> q = dynamicsymbols('q')        >>> p.set_vel(N, 10 * N.x)        >>> p2 = Point('p2')        >>> p2.set_pos(p, q*N.x)        >>> p2.vel(N)        (Derivative(q(t), t) + 10)*N.x         """          _check_frame(frame)         if not (frame in self._vel_dict):            raise ValueError('Velocity of point ' + self.name + ' has not been'            visited = []            queue = [self]            while queue: #BFS to find nearest point                node = queue.pop(0)                if node not in visited:                    visited.append(node)                    for neighbor, neighbor_pos in node._pos_dict.items():                        try:                            neighbor_pos.express(frame) #Checks if pos vector is valid                        except ValueError:                            continue                        try :                            neighbor_velocity = neighbor._vel_dict[frame] #Checks if point has its vel defined in req frame                        except KeyError:                            queue.append(neighbor)                            continue                        self.set_vel(frame, self.pos_from(neighbor).dt(frame) + neighbor_velocity)                        return self._vel_dict[frame]            else:                raise ValueError('Velocity of point ' + self.name + ' has not been'                              ' defined in ReferenceFrame ' + frame.name)         return self._vel_dict[frame]      def partial_velocity(self, frame, *gen_speeds):


def _print_NoneToken(self, arg):         return 'None' <del>class PythonCodePrinter(AbstractPythonCodePrinter):    def _print_sign(self, e):        return '(0.0 if {e} == 0 else {f}(1, {e}))'.format(            f=self._module_format('math.copysign'), e=self._print(e.args[0]))    def _print_Not(self, expr):        PREC = precedence(expr)        return self._operators['not'] + self.parenthesize(expr.args[0], PREC)    def _print_Indexed(self, expr):        base = expr.args[0]        index = expr.args[1:]        return "{}[{}]".format(str(base), ", ".join([self._print(ind) for ind in index]))</del>     def _hprint_Pow(self, expr, rational=False, sqrt='math.sqrt'):         """Printing helper function for ``Pow``


exp_str = self.parenthesize(expr.exp, PREC, strict=False)         return "{}**{}".format(base_str, exp_str) <ins>class PythonCodePrinter(AbstractPythonCodePrinter):    def _print_sign(self, e):        return '(0.0 if {e} == 0 else {f}(1, {e}))'.format(            f=self._module_format('math.copysign'), e=self._print(e.args[0]))    def _print_Not(self, expr):        PREC = precedence(expr)        return self._operators['not'] + self.parenthesize(expr.args[0], PREC)    def _print_Indexed(self, expr):        base = expr.args[0]        index = expr.args[1:]        return "{}[{}]".format(str(base), ", ".join([self._print(ind) for ind in index]))</ins>     def _print_Pow(self, expr, rational=False):         return self._hprint_Pow(expr, rational=rational)


def _print_Half(self, expr):         return self._print_Rational(expr) <ins>    def _print_frac(self, expr):        from sympy import Mod        return self._print_Mod(Mod(expr.args[0], 1))</ins>     _print_lowergamma = CodePrinter._print_not_supported     _print_uppergamma = CodePrinter._print_not_supported     _print_fresnelc = CodePrinter._print_not_supported


_in_mpmath = [(k, v) for k, v in _known_functions_math.items() if k not in _not_in_mpmath] _known_functions_mpmath = dict(_in_mpmath, **{     'beta': 'beta',<ins>    'frac': 'frac',</ins>     'fresnelc': 'fresnelc',     'fresnels': 'fresnels',     'sign': 'sign',


setattr(SciPyPrinter, '_print_%s' % k, _print_known_const)  class SymPyPrinter(PythonCodePrinter):class SymPyPrinter(AbstractPythonCodePrinter):      language = "Python with SymPy"     _kf = {k: 'sympy.' + v for k, v in chain(        _known_functions.items(),        _known_functions_math.items()    )}     def _print_Function(self, expr):         mod = expr.func.__module__ or ''         return '%s(%s)' % (self._module_format(mod + ('.' if mod else '') + expr.func.__name__),


from __future__ import print_function, division from .vector import Vector, _check_vector from .frame import _check_frame<ins>from warnings import warn</ins>  __all__ = ['Point']


_check_frame(frame)         if not (frame in self._vel_dict):            valid_neighbor_found = False            is_cyclic = False             visited = []             queue = [self]            candidate_neighbor = []             while queue: #BFS to find nearest point                 node = queue.pop(0)                 if node not in visited:                     visited.append(node)                     for neighbor, neighbor_pos in node._pos_dict.items():                        if neighbor in visited:                            continue                         try:                             neighbor_pos.express(frame) #Checks if pos vector is valid                         except ValueError:                             continue                        if neighbor in queue:                            is_cyclic = True                         try :                             neighbor_velocity = neighbor._vel_dict[frame] #Checks if point has its vel defined in req frame                         except KeyError:                             queue.append(neighbor)                             continue                        self.set_vel(frame, self.pos_from(neighbor).dt(frame) + neighbor_velocity)                        return self._vel_dict[frame]                        candidate_neighbor.append(neighbor)                        if not valid_neighbor_found:                            self.set_vel(frame, self.pos_from(neighbor).dt(frame) + neighbor_velocity)                            valid_neighbor_found = True            if is_cyclic:                warn('Kinematic loops are defined among the positions of points. This is likely not desired and may cause errors in your calculations.')            if len(candidate_neighbor) > 1:                warn('Velocity automatically calculated based on point ' +                    candidate_neighbor[0].name + ' but it is also possible from points(s):' +                    str(candidate_neighbor[1:]) + '. Velocities from these points are not necessarily the same. This may cause errors in your calculations.')            if valid_neighbor_found:                return self._vel_dict[frame]             else:                 raise ValueError('Velocity of point ' + self.name + ' has not been'                              ' defined in ReferenceFrame ' + frame.name)


def _hashable_content(self):         return (self.name,)  def _filter_assumptions(kwargs):     """Split the given dict into assumptions and non-assumptions.     Keys are taken as assumptions if they correspond to andiff --git a/sympy/matrices/expressions/matexpr.py b/sympy/matrices/expressions/matexpr.py-- a/sympy/matrices/expressions/matexpr.py++ b/sympy/matrices/expressions/matexpr.py


from sympy.core import S, Symbol, Integer, Basic, Expr, Mul, Add from sympy.core.decorators import call_highest_priority from sympy.core.compatibility import SYMPY_INTS, default_sort_key<ins>from sympy.core.symbol import Str</ins> from sympy.core.sympify import SympifyError, _sympify from sympy.functions import conjugate, adjoint from sympy.functions.special.tensor_functions import KroneckerDelta


cls._check_dim(n)          if isinstance(name, str):            name = Symbol(name)            name = Str(name)         obj = Basic.__new__(cls, name, n, m)         return obj diff --git a/sympy/printing/dot.py b/sympy/printing/dot.py-- a/sympy/printing/dot.py++ b/sympy/printing/dot.py


>>> from sympy import Float, Symbol, MatrixSymbol     >>> from sympy import Integer # noqa: F401<ins>    >>> from sympy.core.symbol import Str # noqa: F401</ins>     >>> from sympy.printing.dot import purestr      Applying ``purestr`` for basic symbolic object:


For matrix symbol:     >>> code = purestr(MatrixSymbol('x', 2, 2))     >>> code    "MatrixSymbol(Symbol('x'), Integer(2), Integer(2))"    "MatrixSymbol(Str('x'), Integer(2), Integer(2))"     >>> eval(code) == MatrixSymbol('x', 2, 2)     True


>>> purestr(Float(2), with_args=True)     ("Float('2.0', precision=53)", ())     >>> purestr(MatrixSymbol('x', 2, 2), with_args=True)    ("MatrixSymbol(Symbol('x'), Integer(2), Integer(2))",     ("Symbol('x')", 'Integer(2)', 'Integer(2)'))    ("MatrixSymbol(Str('x'), Integer(2), Integer(2))",     ("Str('x')", 'Integer(2)', 'Integer(2)'))     """     sargs = ()     if not isinstance(x, Basic):


{2: 1, 4: 1}     {3: 2} <del>    Note that the _same_ dictionary object is returned each time.    This is for speed:  generating each partition goes quickly,    taking constant time, independent of n.    >>> [p for p in partitions(6, k=2)]    [{1: 6}, {1: 6}, {1: 6}, {1: 6}]    If you want to build a list of the returned dictionaries then    make a copy of them:    >>> [p.copy() for p in partitions(6, k=2)]  # doctest: +SKIP    [{2: 3}, {1: 2, 2: 2}, {1: 4, 2: 1}, {1: 6}]    >>> [(M, p.copy()) for M, p in partitions(6, k=2, size=True)]  # doctest: +SKIP    [(3, {2: 3}), (4, {1: 2, 2: 2}), (5, {1: 4, 2: 1}), (6, {1: 6})]</del>     References     ==========


keys.append(r)     room = m - q - bool(r)     if size:        yield sum(ms.values()), ms        yield sum(ms.values()), ms.copy()     else:        yield ms        yield ms.copy()      while keys != [1]:         # Reuse any 1's.


break         room -= need         if size:            yield sum(ms.values()), ms            yield sum(ms.values()), ms.copy()         else:            yield ms            yield ms.copy()   def ordered_partitions(n, m=None, sort=True):


]  from sympy import Symbol, sympify, sqrt, Matrix, acos, oo, Limit, atan2, asin,\cos, sin, tan, I, cancel, pi, Floatcos, sin, tan, I, cancel, pi, Float, S, zoo from sympy.core.compatibility import is_sequence from sympy.geometry.line import Ray3D from sympy.geometry.util import intersection


def lens_makers_formula(n_lens, n_surr, r1, r2):def lens_makers_formula(n_lens, n_surr, r1, r2, d=0):     """    This function calculates focal length of a thin lens.    This function calculates focal length of a lens.     It follows cartesian sign convention.      Parameters


Radius of curvature of first surface.     r2 : sympifiable         Radius of curvature of second surface.    d : sympifiable, optional        Thickness of lens, default value is 0.      Examples     ========      >>> from sympy.physics.optics import lens_makers_formula    >>> from sympy import S     >>> lens_makers_formula(1.33, 1, 10, -10)     15.1515151515151    >>> lens_makers_formula(1.2, 1, 10, S.Infinity)    50.0000000000000    >>> lens_makers_formula(1.33, 1, 10, -10, d=1)    15.3418463277618      """     if isinstance(n_lens, Medium):         n_lens = n_lens.refractive_index     else:


n_surr = n_surr.refractive_index     else:         n_surr = sympify(n_surr)    d = sympify(d)     r1 = sympify(r1)    r2 = sympify(r2)    focal_length = 1/((n_lens - n_surr) / n_surr*(1/r1 - 1/r2 + (((n_lens - n_surr) * d) / (n_lens * r1 * r2))))     return 1/((n_lens - n_surr)/n_surr*(1/r1 - 1/r2))    if focal_length == zoo:        return S.Infinity    return focal_length   def mirror_formula(focal_length=None, u=None, v=None):


).warn()          if evaluate:<ins>            if b is S.Zero and e is S.NegativeInfinity:                return S.ComplexInfinity</ins>             if e is S.ComplexInfinity:                 return S.NaN             if e is S.Zero:


# special case for 1^(-x), issue 9216             if expr.base == 1:                 return r"%s^{%s}" % (expr.base, expr.exp)<ins>            # special case for (1/x)^(-y) and (-1/-x)^(-y), issue 20252            if expr.base.is_Rational and \                    expr.base.p*expr.base.q == abs(expr.base.q):                if expr.exp == -1:                    return r"\frac{1}{\frac{%s}{%s}}" % (expr.base.p, expr.base.q)                else:                    return r"\frac{1}{(\frac{%s}{%s})^{%s}}" % (expr.base.p, expr.base.q, abs(expr.exp))</ins>             # things like 1/x             return self._print_Mul(expr)         else:


from .singleton import S from .operations import AssocOp, AssocOpDispatcher from .cache import cacheitfrom .logic import fuzzy_not, _fuzzy_group, fuzzy_andfrom .logic import fuzzy_not, _fuzzy_group from .compatibility import reduce from .expr import Expr from .parameters import global_parameters


zero = None         return zero     # without involving odd/even checks this code would suffice:    #_eval_is_integer = lambda self: _fuzzy_group(    #    (a.is_integer for a in self.args), quick_exit=True)     def _eval_is_integer(self):        from sympy import fraction        from sympy.core.numbers import Float         is_rational = self._eval_is_rational()         if is_rational is False:             return False         # use exact=True to avoid recomputing num or den        n, d = fraction(self, exact=True)        if is_rational:            if d is S.One:                return True        if d.is_even:            if d.is_prime:  # literal or symbolic 2                return n.is_even            if n.is_odd:                return False  # true even if d = 0        if n == d:            return fuzzy_and([not bool(self.atoms(Float)),            fuzzy_not(d.is_zero)])        numerators = []        denominators = []        for a in self.args:            if a.is_integer:                numerators.append(a)            elif a.is_Rational:                n, d = a.as_numer_denom()                numerators.append(n)                denominators.append(d)            elif a.is_Pow:                b, e = a.as_base_exp()                if not b.is_integer or not e.is_integer: return                if e.is_negative:                    denominators.append(b)                else:                    # for integer b and positive integer e: a = b**e would be integer                    assert not e.is_positive                    # for self being rational and e equal to zero: a = b**e would be 1                    assert not e.is_zero                    return # sign of e unknown -> self.is_integer cannot be decided            else:                return        if not denominators:            return True        odd = lambda ints: all(i.is_odd for i in ints)        even = lambda ints: any(i.is_even for i in ints)        if odd(numerators) and even(denominators):            return False        elif even(numerators) and denominators == [2]:            return True      def _eval_is_polar(self):         has_polar = any(arg.is_polar for arg in self.args)


return not f == g          def __bool__(f):            return f.ex != 0            return not f.ex.is_zero          def gcd(f, g):             from sympy.polys import gcd


from sympy import Add, Mul, Pow, Tuple, sympify from sympy.core.compatibility import reduce, Iterable, ordered<ins>from sympy.matrices.common import NonInvertibleMatrixError</ins> from sympy.physics.units.dimensions import Dimension from sympy.physics.units.prefixes import Prefix from sympy.physics.units.quantities import Quantity


camat = Matrix([[dimension_system.get_dimensional_dependencies(i, mark_dimensionless=True).get(j, 0) for i in target_dims] for j in canon_dim_units])     exprmat = Matrix([dim_dependencies.get(k, 0) for k in canon_dim_units])     res_exponents = camat.solve_least_squares(exprmat, method=None)    try:        res_exponents = camat.solve(exprmat)    except NonInvertibleMatrixError:        return None     return res_exponents


for a in args:             c = args[a]             c.sort()<del>            no = []</del>             while c:                 k = 0                 cc = ci = c[0]


c.remove(cc)                     new.append(newarg**take)                 else:                    no.append(c.pop(0))            c[:] = no                    b = cos(c.pop(0)*a)                    other.append(b**coss[b])          if new:             rv = Mul(*(new + other + [


This also adds support for LaTeX printing in jupyter notebooks.     """ <ins>    # Since this class is used as a mixin we set empty slots. That means that    # instances of any subclasses that use slots will not need to have a    # __dict__.    __slots__ = ()</ins>     # Note, we always use the default ordering (lex) in __str__ and __repr__,     # regardless of the global setting. See issue 5487.     def __str__(self):


return prettyForm.__mul__(*a)/prettyForm.__mul__(*b)      # A helper function for _print_Pow to print x**(1/n)    def _print_nth_root(self, base, expt):    def _print_nth_root(self, base, root):         bpretty = self._print(base)          # In very simple cases, use a single-char root sign         if (self._settings['use_unicode_sqrt_char'] and self._use_unicode            and expt is S.Half and bpretty.height() == 1            and root == 2 and bpretty.height() == 1             and (bpretty.width() == 1                  or (base.is_Integer and base.is_nonnegative))):             return prettyForm(*bpretty.left('\N{SQUARE ROOT}'))


# Construct root sign, start with the \/ shape         _zZ = xobj('/', 1)         rootsign = xobj('\\', 1) + _zZ        # Make exponent number to put above it        if isinstance(expt, Rational):            exp = str(expt.q)            if exp == '2':                exp = ''        else:            exp = str(expt.args[0])        exp = exp.ljust(2)        # Constructing the number to put on root        rpretty = self._print(root)        # roots look bad if they are not a single line        if rpretty.height() != 1:            return self._print(base)**self._print(1/root)        # If power is half, no number should appear on top of root sign        exp = '' if root == 2 else str(rpretty).ljust(2)         if len(exp) > 2:             rootsign = ' '*(len(exp) - 2) + rootsign         # Stack the exponent


if e is S.NegativeOne:                 return prettyForm("1")/self._print(b)             n, d = fraction(e)            if n is S.One and d.is_Atom and not e.is_Integer and self._settings['root_notation']:                return self._print_nth_root(b, e)            if n is S.One and d.is_Atom and not e.is_Integer and (e.is_Rational or d.is_Symbol) \                    and self._settings['root_notation']:                return self._print_nth_root(b, d)             if e.is_Rational and e < 0:                 return prettyForm("1")/self._print(Pow(b, -e, evaluate=False))


other = _sympify(other)         except SympifyError:             return NotImplemented<del>        if not self:            return not other</del>         if isinstance(other, Boolean):             return False         if other.is_NumberSymbol:


# the mpf tuples             ompf = other._as_mpf_val(self._prec)             return bool(mlib.mpf_eq(self._mpf_, ompf))<ins>        if not self:            return not other</ins>         return False    # Float != non-Number      def __ne__(self, other):


from collections.abc import Iterable from sympy import Derivative _name_with_digits_p = re.compile(r'^([a-zA-Z]+)([0-9]+)$')_name_with_digits_p = re.compile(r'^([^\W\d_]+)(\d+)$', re.U)   def split_super_sub(text):


else:             raise RuntimeError("This should never happen.")     # make a little exception when a name ends with digits, i.e. treat them    # Make a little exception when a name ends with digits, i.e. treat them     # as a subscript too.     m = _name_with_digits_p.match(name)     if m:


return - S.ImaginaryUnit * arg     return _refine_reim(expr, assumptions) <ins>def refine_arg(expr, assumptions):    """    Handler for complex argument    Explanation    ===========    >>> from sympy.assumptions.refine import refine_arg    >>> from sympy import Q, arg    >>> from sympy.abc import x    >>> refine_arg(arg(x), Q.positive(x))    0    >>> refine_arg(arg(x), Q.negative(x))    pi    """    rg = expr.args[0]    if ask(Q.positive(rg), assumptions):        return S.Zero    if ask(Q.negative(rg), assumptions):        return S.Pi    return None</ins>  def _refine_reim(expr, assumptions):     # Helper function for refine_re & refine_im


'atan2': refine_atan2,     're': refine_re,     'im': refine_im,<ins>    'arg': refine_arg,</ins>     'sign': refine_sign,     'MatrixElement': refine_matrixelement }  # type: Dict[str, Callable[[Expr, Boolean], Expr]]


tex = r"\left(%s\right)^{%s}" % (tex, exp)         return tex     def _print_SingularityFunction(self, expr):    def _print_SingularityFunction(self, expr, exp=None):         shift = self._print(expr.args[0] - expr.args[1])         power = self._print(expr.args[2])         tex = r"{\left\langle %s \right\rangle}^{%s}" % (shift, power)        if exp is not None:            tex = r"{\left({\langle %s \rangle}^{%s}\right)}^{%s}" % (shift, power, exp)         return tex      def _print_Heaviside(self, expr, exp=None):


from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix     parts = [[convert_array_to_matrix(j).doit() for j in i] for i in parts]    parts = [[convert_array_to_matrix(j) for j in i] for i in parts]      def _get_shape(elem):         if isinstance(elem, MatrixExpr):


data = [self._build(i) for i in self._lines]         if self.higher != 1:             data += [self._build(self.higher)]        data = [i.doit() for i in data]        data = [i for i in data]         return data      def matrix_form(self):


from sympy.core.expr import Expr from sympy.core.function import Lambda from sympy.core.logic import fuzzy_not, fuzzy_or, fuzzy_andfrom sympy.core.numbers import oo, Integerfrom sympy.core.numbers import oo from sympy.core.relational import Eq from sympy.core.singleton import Singleton, S from sympy.core.symbol import Dummy, symbols, Symbol


if not self:             return S.Zero         dif = self.stop - self.start        if self.has(Symbol):            if dif.has(Symbol) or self.step.has(Symbol) or (                    not self.start.is_integer and not self.stop.is_integer):                raise ValueError('invalid method for symbolic range')        if dif.is_infinite:            return S.Infinity        return Integer(abs(dif//self.step))        n = abs(dif // self.step)        if not n.is_Integer:            if n.is_infinite:                return S.Infinity            raise ValueError('invalid method for symbolic range')        return n      @property     def is_finite_set(self):