# For two numbers, the second number is the number of bits         # on which it is expressed, so IntQubit(0,5) == |00000>.         elif len(args) == 2 and args[1] > 1:            need = bitcount(abs(args[0]))            if args[1] < need:                raise ValueError(                    'cannot represent %s with %s bits' % (args[0], args[1]))            qubit_values = [(args[0] >> i) & 1 for i in reversed(range(args[1]))]            return QubitState._eval_args(qubit_values)            return cls._eval_args_with_nqubits(args[0], args[1])         else:             return QubitState._eval_args(args)     @classmethod    def _eval_args_with_nqubits(cls, number, nqubits):        need = bitcount(abs(number))        if nqubits < need:            raise ValueError(                'cannot represent %s with %s bits' % (number, nqubits))        qubit_values = [(number >> i) & 1 for i in reversed(range(nqubits))]        return QubitState._eval_args(qubit_values)     def as_int(self):         """Return the numerical value of the qubit."""         number = 0


values : int, tuple         If a single argument, the integer we want to represent in the qubit         values. This integer will be represented using the fewest possible        number of qubits. If a pair of integers, the first integer gives the        integer to represent in binary form and the second integer gives        the number of qubits to use.        number of qubits.        If a pair of integers and the second value is more than one, the first        integer gives the integer to represent in binary form and the second        integer gives the number of qubits to use.        List of zeros and ones is also accepted to generate qubit by bit pattern.    nqubits : int        The integer that represents the number of qubits.        This number should be passed with keyword ``nqubits=N``.        You can use this in order to avoid ambiguity of Qubit-style tuple of bits.        Please see the example below for more details.      Examples     ========


>>> Qubit(q)         |101><ins>    Please note that ``IntQubit`` also accepts a ``Qubit``-style list of bits.    So, the code below yields qubits 3, not a single bit ``1``.        >>> IntQubit(1, 1)        |3>    To avoid ambiguity, use ``nqubits`` parameter.    Use of this keyword is recommended especially when you provide the values by variables.        >>> IntQubit(1, nqubits=1)        |1>        >>> a = 1        >>> IntQubit(a, nqubits=1)        |1></ins>     """     @classmethod     def dual_class(self):


for i in range(size):             if m[i] != 0.0:                 results.append(                    (Qubit(IntQubit(i, nqubits)), m[i]*conjugate(m[i]))                    (Qubit(IntQubit(i, nqubits=nqubits)), m[i]*conjugate(m[i]))                 )         return results     else:


def _print_tuple(self, expr):         return r"\left( %s\right)" % \            r", \quad ".join([ self._print(i) for i in expr ])            r", \  ".join([ self._print(i) for i in expr ])      def _print_TensorProduct(self, expr):         elements = [self._print(a) for a in expr.args]


def _print_list(self, expr):         return r"\left[ %s\right]" % \            r", \quad ".join([ self._print(i) for i in expr ])            r", \  ".join([ self._print(i) for i in expr ])      def _print_dict(self, d):         keys = sorted(d.keys(), key=default_sort_key)


val = d[key]             items.append("%s : %s" % (self._print(key), self._print(val)))         return r"\left\{ %s\right\}" % r", \quad ".join(items)        return r"\left\{ %s\right\}" % r", \  ".join(items)      def _print_Dict(self, expr):         return self._print_dict(expr)


dictionary.      >>> print(latex([2/x, y], mode='inline'))    $\left[ 2 / x, \quad y\right]$    $\left[ 2 / x, \  y\right]$      """     if symbol_names is None:


def _special_function_classes(self):         from sympy.functions.special.tensor_functions import KroneckerDelta         from sympy.functions.special.gamma_functions import gamma, lowergamma        from sympy.functions.special.zeta_functions import lerchphi         from sympy.functions.special.beta_functions import beta         from sympy.functions.special.delta_functions import DiracDelta         from sympy.functions.special.error_functions import Chi         return {KroneckerDelta: [greek_unicode['delta'], 'delta'],                 gamma: [greek_unicode['Gamma'], 'Gamma'],                lerchphi: [greek_unicode['Phi'], 'lerchphi'],                 lowergamma: [greek_unicode['gamma'], 'gamma'],                 beta: [greek_unicode['Beta'], 'B'],                 DiracDelta: [greek_unicode['delta'], 'delta'],


# GeometryEntity is based on Tuple but should not print like a Tuple         return self.emptyPrinter(expr) <ins>    def _print_lerchphi(self, e):        func_name = greek_unicode['Phi'] if self._use_unicode else 'lerchphi'        return self._print_Function(e, func_name=func_name)</ins>     def _print_Lambda(self, e):         vars, expr = e.args         if self._use_unicode:


return mrow      def _print_Symbol(self, sym, style='plain'):<del>        x = self.dom.createElement('mi')        if style == 'bold':            x.setAttribute('mathvariant', 'bold')</del>         def join(items):             if len(items) > 1:                 mrow = self.dom.createElement('mrow')


mname.appendChild(self.dom.createTextNode(name))         if len(supers) == 0:             if len(subs) == 0:                x.appendChild(self.dom.createTextNode(name))                x = mname             else:                msub = self.dom.createElement('msub')                msub.appendChild(mname)                msub.appendChild(join(subs))                x.appendChild(msub)                x = self.dom.createElement('msub')                x.appendChild(mname)                x.appendChild(join(subs))         else:             if len(subs) == 0:                msup = self.dom.createElement('msup')                msup.appendChild(mname)                msup.appendChild(join(supers))                x.appendChild(msup)                x = self.dom.createElement('msup')                x.appendChild(mname)                x.appendChild(join(supers))             else:                msubsup = self.dom.createElement('msubsup')                msubsup.appendChild(mname)                msubsup.appendChild(join(subs))                msubsup.appendChild(join(supers))                x.appendChild(msubsup)                x = self.dom.createElement('msubsup')                x.appendChild(mname)                x.appendChild(join(subs))                x.appendChild(join(supers))        # Set bold font?        if style == 'bold':            x.setAttribute('mathvariant', 'bold')         return x      def _print_MatrixSymbol(self, sym):


if requires_partial(e):             diff_symbol = 'partialdiff'         x.appendChild(self.dom.createElement(diff_symbol))         x_1 = self.dom.createElement('bvar')        for sym in e.variables:        for sym, times in reversed(e.variable_count):             x_1.appendChild(self._print(sym))            if times > 1:                degree = self.dom.createElement('degree')                degree.appendChild(self._print(sympify(times)))                x_1.appendChild(degree)          x.appendChild(x_1)         x.appendChild(self._print(e.expr))


return x      def _print_Derivative(self, e):        mrow = self.dom.createElement('mrow')        x = self.dom.createElement('mo')         if requires_partial(e):            x.appendChild(self.dom.createTextNode('∂'))            y = self.dom.createElement('mo')            y.appendChild(self.dom.createTextNode('∂'))            d = '∂'         else:            x.appendChild(self.dom.createTextNode(self.mathml_tag(e)))            y = self.dom.createElement('mo')            y.appendChild(self.dom.createTextNode(self.mathml_tag(e)))        brac = self.dom.createElement('mfenced')        brac.appendChild(self._print(e.expr))        mrow = self.dom.createElement('mrow')        mrow.appendChild(x)        mrow.appendChild(brac)        for sym in e.variables:            frac = self.dom.createElement('mfrac')            m = self.dom.createElement('mrow')            x = self.dom.createElement('mo')            if requires_partial(e):                x.appendChild(self.dom.createTextNode('∂'))            d = self.mathml_tag(e)        # Determine denominator        m = self.dom.createElement('mrow')        dim = 0 # Total diff dimension, for numerator        for sym, num in reversed(e.variable_count):            dim += num            if num >= 2:                x = self.dom.createElement('msup')                xx = self.dom.createElement('mo')                xx.appendChild(self.dom.createTextNode(d))                x.appendChild(xx)                x.appendChild(self._print(num))             else:                x.appendChild(self.dom.createTextNode(self.mathml_tag(e)))            y = self._print(sym)                x = self.dom.createElement('mo')                x.appendChild(self.dom.createTextNode(d))             m.appendChild(x)            y = self._print(sym)             m.appendChild(y)            frac.appendChild(mrow)            frac.appendChild(m)            mrow = frac         return frac        mnum = self.dom.createElement('mrow')        if dim >= 2:            x = self.dom.createElement('msup')            xx = self.dom.createElement('mo')            xx.appendChild(self.dom.createTextNode(d))            x.appendChild(xx)            x.appendChild(self._print(dim))        else:            x = self.dom.createElement('mo')            x.appendChild(self.dom.createTextNode(d))        mnum.appendChild(x)        mrow = self.dom.createElement('mrow')        frac = self.dom.createElement('mfrac')        frac.appendChild(mnum)        frac.appendChild(m)        mrow.appendChild(frac)        # Print function        mrow.appendChild(self._print(e.expr))        return mrow      def _print_Function(self, e):         mrow = self.dom.createElement('mrow')


from .applyfunc import ElementwiseApplyFunction         return ElementwiseApplyFunction(func, self) <ins>    def _eval_Eq(self, other):        if not isinstance(other, MatrixExpr):            return False        if self.shape != other.shape:            return False        if (self - other).is_ZeroMatrix:            return True        return Eq(self, other, evaluate=False)</ins>  def _matrix_derivative(expr, x):     from sympy import Derivative


from __future__ import print_function, division from sympy.core.assumptions import StdFactKB, _assume_defined from sympy.core import Expr, Tuple, Symbol, sympify, S from sympy.core.compatibility import (is_sequence, string_types, NotIterable,                                       Iterable)from sympy.core.logic import fuzzy_bool from sympy.core.sympify import _sympify from sympy.functions.special.tensor_functions import KroneckerDelta


>>> Indexed('A', i, j)     A[i, j]     It is recommended that ``Indexed`` objects be created via ``IndexedBase``:    It is recommended that ``Indexed`` objects be created by indexing ``IndexedBase``:    ``IndexedBase('A')[i, j]`` instead of ``Indexed(IndexedBase('A'), i, j)``.      >>> A = IndexedBase('A')    >>> Indexed('A', i, j) == A[i, j]    >>> a_ij = A[i, j]           # Prefer this,    >>> b_ij = Indexed(A, i, j)  # over this.    >>> a_ij == b_ij     True      """


is_symbol = True     is_Atom = True <ins></ins>     def __new__(cls, base, *args, **kw_args):         from sympy.utilities.misc import filldedent         from sympy.tensor.array.ndim_array import NDimArray


else:                 return base[args]         return Expr.__new__(cls, base, *args, **kw_args)        obj = Expr.__new__(cls, base, *args, **kw_args)        try:            IndexedBase._set_assumptions(obj, base.assumptions0)        except AttributeError:            IndexedBase._set_assumptions(obj, {})        return obj    def _hashable_content(self):        return super(Indexed, self)._hashable_content() + tuple(sorted(self.assumptions0.items()))      @property     def name(self):


return S.NaN             return S.Zero <ins>    @property    def assumptions0(self):        return {k: v for k, v in self._assumptions.items() if v is not None}</ins>     @property     def base(self):         """Returns the ``IndexedBase`` of the ``Indexed`` object.


>>> B[i, j].shape     (o, p)     Assumptions can be specified with keyword arguments the same way as for Symbol:    >>> A_real = IndexedBase('A', real=True)    >>> A_real.is_real    True    >>> A != A_real    True     """     is_commutative = True     is_symbol = True     is_Atom = True     @staticmethod    def _filter_assumptions(kw_args):        """Split the given dict into two parts: assumptions and not assumptions.           Keys are taken as assumptions if they correspond to an entry in ``_assume_defined``."""        assumptions = {k: v for k, v in kw_args.items() if k in _assume_defined}        Symbol._sanitize(assumptions)        # return assumptions, not assumptions        return assumptions, {k: v for k, v in kw_args.items() if k not in assumptions}    @staticmethod    def _set_assumptions(obj, assumptions):        """Set assumptions on obj, making sure to apply consistent values."""        tmp_asm_copy = assumptions.copy()        is_commutative = fuzzy_bool(assumptions.get('commutative', True))        assumptions['commutative'] = is_commutative        obj._assumptions = StdFactKB(assumptions)        obj._assumptions._generator = tmp_asm_copy  # Issue #8873     def __new__(cls, label, shape=None, **kw_args):         from sympy import MatrixBase, NDimArray


obj._offset = offset         obj._strides = strides         obj._name = str(label)        assumptions, _ = IndexedBase._filter_assumptions(kw_args)        IndexedBase._set_assumptions(obj, assumptions)         return obj      @property     def name(self):         return self._name     def _hashable_content(self):        return super(IndexedBase, self)._hashable_content() + tuple(sorted(self.assumptions0.items()))    @property    def assumptions0(self):        return {k: v for k, v in self._assumptions.items() if v is not None}     def __getitem__(self, indices, **kw_args):         if is_sequence(indices):             # Special case needed because M[*my_tuple] is a syntax error.


return x  <ins>    def _print_tuple(self, e):        x = self.dom.createElement('mfenced')        for i in e:            x.appendChild(self._print(i))        return x    def _print_IndexedBase(self, e):        return self._print(e.label)    def _print_Indexed(self, e):        x = self.dom.createElement('msub')        x.appendChild(self._print(e.base))        if len(e.indices) == 1:            x.appendChild(self._print(e.indices[0]))            return x        x.appendChild(self._print(e.indices))        return x</ins> def mathml(expr, printer='content', **settings):     """Returns the MathML representation of expr. If printer is presentation then      prints Presentation MathML else prints content MathML.


return 'SparseArray[{}, {}]'.format(print_data(), print_dims()) <ins>    def _print_ImmutableDenseNDimArray(self, expr):        return self.doprint(expr.tolist())    def _print_ImmutableSparseNDimArray(self, expr):        def print_string_list(string_list):            return '{' + ', '.join(a for a in string_list) + '}'        def to_mathematica_index(*args):            """Helper function to change Python style indexing to            Pathematica indexing.            Python indexing (0, 1 ... n-1)            -> Mathematica indexing (1, 2 ... n)            """            return tuple(i + 1 for i in args)        def print_rule(pos, val):            """Helper function to print a rule of Mathematica"""            return '{} -> {}'.format(self.doprint(pos), self.doprint(val))        def print_data():            """Helper function to print data part of Mathematica            sparse array.            It uses the fourth notation ``SparseArray[data,{d1,d2,…}]``            from            https://reference.wolfram.com/language/ref/SparseArray.html            ``data`` must be formatted with rule.            """            return print_string_list(                [print_rule(                    to_mathematica_index(*(expr._get_tuple_index(key))),                    value)                for key, value in sorted(expr._sparse_array.items())]            )        def print_dims():            """Helper function to print dimensions part of Mathematica            sparse array.            It uses the fourth notation ``SparseArray[data,{d1,d2,…}]``            from            https://reference.wolfram.com/language/ref/SparseArray.html            """            return self.doprint(expr.shape)        return 'SparseArray[{}, {}]'.format(print_data(), print_dims())</ins>     def _print_Function(self, expr):         if expr.func.__name__ in self.known_functions:             cond_mfunc = self.known_functions[expr.func.__name__]


for lim in expr.limits:             width = (func_height + 2) * 5 // 3 - 2            sign_lines = []            sign_lines.append(corner_chr + (horizontal_chr*width) + corner_chr)            for i in range(func_height + 1):                sign_lines.append(vertical_chr + (' '*width) + vertical_chr)            sign_lines = [horizontal_chr + corner_chr + (horizontal_chr * (width-2)) + corner_chr + horizontal_chr]            for _ in range(func_height + 1):                sign_lines.append(' ' + vertical_chr + (' ' * (width-2)) + vertical_chr + ' ')              pretty_sign = stringPict('')             pretty_sign = prettyForm(*pretty_sign.stack(*sign_lines))


local_decs = []             for arg, val in py_inf.items():                 proto = self._prototype_arg(arg)                mat, ind = val                mat, ind = [self._string_var(v) for v in val]                 local_decs.append("    cdef {0} = {1}.shape[{2}]".format(proto, mat, ind))             local_decs.extend(["    cdef {0}".format(self._declare_arg(a)) for a in py_loc])             declarations = "\n".join(local_decs)


# Function Body             args_c = ", ".join([self._call_arg(a) for a in routine.arguments])            rets = ", ".join([str(r.name) for r in py_rets])            rets = ", ".join([self._string_var(r.name) for r in py_rets])             if routine.results:                 body = '    return %s(%s)' % (routine.name, args_c)                 if rets:


self._need_numpy = True             ndim = len(arg.dimensions)             mtype = np_types[t]            return mat_dec.format(mtype=mtype, ndim=ndim, name=arg.name)            return mat_dec.format(mtype=mtype, ndim=ndim, name=self._string_var(arg.name))         else:            return "%s %s" % (t, str(arg.name))            return "%s %s" % (t, self._string_var(arg.name))      def _declare_arg(self, arg):         proto = self._prototype_arg(arg)         if arg.dimensions:            shape = '(' + ','.join(str(i[1] + 1) for i in arg.dimensions) + ')'            shape = '(' + ','.join(self._string_var(i[1] + 1) for i in arg.dimensions) + ')'             return proto + " = np.empty({shape})".format(shape=shape)         else:             return proto + " = 0"


def _call_arg(self, arg):         if arg.dimensions:             t = arg.get_datatype('c')            return "<{0}*> {1}.data".format(t, arg.name)            return "<{0}*> {1}.data".format(t, self._string_var(arg.name))         elif isinstance(arg, ResultBase):            return "&{0}".format(arg.name)            return "&{0}".format(self._string_var(arg.name))         else:            return str(arg.name)            return self._string_var(arg.name)    def _string_var(self, var):        printer = self.generator.printer.doprint        return printer(var)   class F2PyCodeWrapper(CodeWrapper):


return True             if self.exp.is_odd:                 return False<ins>        elif self.base.is_zero:            if self.exp.is_real:                return self.exp.is_zero</ins>         elif self.base.is_nonpositive:             if self.exp.is_odd:                 return False


elif self.base.is_positive:             if self.exp.is_real:                 return False<ins>        elif self.base.is_zero:            if self.exp.is_real:                return False</ins>         elif self.base.is_nonnegative:             if self.exp.is_nonnegative:                 return False


vector_names = list(vector_names)         latex_vects = [(r'\mathbf{\hat{%s}_{%s}}' % (x, name)) for                            x in vector_names]        pretty_vects = [(name + '_' + x) for x in vector_names]        pretty_vects = ['%s_%s' % (x, name) for x in vector_names]          obj._vector_names = vector_names


variable_names = list(variable_names)         latex_scalars = [(r"\mathbf{{%s}_{%s}}" % (x, name)) for                          x in variable_names]        pretty_scalars = [(name + '_' + x) for x in variable_names]        pretty_scalars = ['%s_%s' % (x, name) for x in variable_names]          obj._variable_names = variable_names         obj._vector_names = vector_names


100.0      Float can automatically count significant figures if a null string    is sent for the precision; space are also allowed in the string. (Auto-    is sent for the precision; spaces or underscores are also allowed. (Auto-     counting is only allowed for strings, ints and longs).     >>> Float('123 456 789 . 123 456', '')    >>> Float('123 456 789.123_456', '')     123456789.123456     >>> Float('12e-3', '')     0.012


'Supply only one. ')          if isinstance(num, string_types):            # Float already accepts spaces as digit separators; in Py 3.6            # underscores are allowed. In anticipation of that, we ignore            # legally placed underscores             num = num.replace(' ', '')            if '_' in num:                if num.startswith('_') or num.endswith('_') or any(                        i in num for i in ('__', '_.', '._')):                    # copy Py 3.6 error                    raise ValueError("could not convert string to float: '%s'" % num)                num = num.replace('_', '')             if num.startswith('.') and len(num) > 1:                 num = '0' + num             elif num.startswith('-.') and len(num) > 2:


eq[i] = e.subs(reps)         return f(eq), {r: s for s, r in reps.items()}     reps = {s: Dummy(s.name, positive=True)    reps = {s: Dummy(s.name, positive=True, **s.assumptions0)                  for s in eq.free_symbols if s.is_positive is None}     eq = eq.subs(reps)     return eq, {r: s for s, r in reps.items()}


return self._print(expr.base, exp=self._print(expr.exp))             else:                 tex = r"%s^{%s}"                exp = self._print(expr.exp)                # issue #12886: add parentheses around superscripts raised                # to powers                base = self.parenthesize(expr.base, PRECEDENCE['Pow'])                if '^' in base and expr.base.is_Symbol:                    base = r"\left(%s\right)" % base                elif (isinstance(expr.base, Derivative)                        and base.startswith(r'\left(')                        and re.match(r'\\left\(\\d?d?dot', base)                        and base.endswith(r'\right)')):                    # don't use parentheses around dotted derivative                    base = base[6: -7]  # remove outermost added parens                return tex % (base, exp)                return self._helper_print_standard_power(expr, tex)    def _helper_print_standard_power(self, expr, template):        exp = self._print(expr.exp)        # issue #12886: add parentheses around superscripts raised        # to powers        base = self.parenthesize(expr.base, PRECEDENCE['Pow'])        if '^' in base and expr.base.is_Symbol:            base = r"\left(%s\right)" % base        elif (isinstance(expr.base, Derivative)            and base.startswith(r'\left(')            and re.match(r'\\left\(\\d?d?dot', base)            and base.endswith(r'\right)')):            # don't use parentheses around dotted derivative            base = base[6: -7]  # remove outermost added parens        return template % (base, exp)      def _print_UnevaluatedExpr(self, expr):         return self._print(expr.args[0])


if not isinstance(mat, MatrixSymbol):             return r"\left(%s\right)^{T}" % self._print(mat)         else:            return "%s^{T}" % self._print(mat)            return "%s^{T}" % self.parenthesize(mat, precedence_traditional(expr), True)      def _print_Trace(self, expr):         mat = expr.arg


self._print(expr.args[1]))      def _print_HadamardProduct(self, expr):        from sympy import Add, MatAdd, MatMul        args = expr.args        prec = PRECEDENCE['Pow']        parens = self.parenthesize        return r' \circ '.join(            map(lambda arg: parens(arg, prec, strict=True), args))         def parens(x):            if isinstance(x, (Add, MatAdd, MatMul)):                return r"\left(%s\right)" % self._print(x)            return self._print(x)        return r' \circ '.join(map(parens, expr.args))    def _print_HadamardPower(self, expr):        template = r"%s^{\circ {%s}}"        return self._helper_print_standard_power(expr, template)      def _print_KroneckerProduct(self, expr):        from sympy import Add, MatAdd, MatMul        args = expr.args        prec = PRECEDENCE['Pow']        parens = self.parenthesize         def parens(x):            if isinstance(x, (Add, MatAdd, MatMul)):                return r"\left(%s\right)" % self._print(x)            return self._print(x)        return r' \otimes '.join(map(parens, expr.args))        return r' \otimes '.join(            map(lambda arg: parens(arg, prec, strict=True), args))      def _print_MatPow(self, expr):         base, exp = expr.base, expr.exp         from sympy.matrices import MatrixSymbol         if not isinstance(base, MatrixSymbol):            return r"\left(%s\right)^{%s}" % (self._print(base),            return "\\left(%s\\right)^{%s}" % (self._print(base),                                               self._print(exp))         else:             return "%s^{%s}" % (self._print(base), self._print(exp))diff --git a/sympy/printing/precedence.py b/sympy/printing/precedence.py-- a/sympy/printing/precedence.py++ b/sympy/printing/precedence.py


# A dictionary assigning precedence values to certain classes. These values are # treated like they were inherited, so not every single class has to be named # here.<ins># Do not use this with printers other than StrPrinter</ins> PRECEDENCE_VALUES = {     "Equivalent": PRECEDENCE["Xor"],     "Xor": PRECEDENCE["Xor"],


def precedence(item):    """    Returns the precedence of a given object.    """Returns the precedence of a given object.    This is the precedence for StrPrinter.     """     if hasattr(item, "precedence"):         return item.precedence


def precedence_traditional(item):    """    Returns the precedence of a given object according to the traditional rules    of mathematics. This is the precedence for the LaTeX and pretty printer.    """Returns the precedence of a given object according to the    traditional rules of mathematics.    This is the precedence for the LaTeX and pretty printer.     """     # Integral, Sum, Product, Limit have the precedence of Mul in LaTeX,     # the precedence of Atom for other printers:    from sympy import Integral, Sum, Product, Limit, Derivative    from sympy import Integral, Sum, Product, Limit, Derivative, Transpose, Adjoint     from sympy.core.expr import UnevaluatedExpr     from sympy.tensor.functions import TensorProduct      if isinstance(item, (Integral, Sum, Product, Limit, Derivative, TensorProduct)):         return PRECEDENCE["Mul"]    if (item.__class__.__name__ in ("Dot", "Cross", "Gradient", "Divergence",    elif isinstance(item, (Transpose, Adjoint)):        return PRECEDENCE["Pow"]    elif (item.__class__.__name__ in ("Dot", "Cross", "Gradient", "Divergence",                                     "Curl", "Laplacian")):         return PRECEDENCE["Mul"]-1     elif isinstance(item, UnevaluatedExpr):


for i in reversed(range(1, d)):                     lines.append('%s/%s' % (' '*i, ' '*(w - i)))                 lines.append("/" + "_"*(w - 1) + ',')                return d, h + more, lines, 0                return d, h + more, lines, more             else:                 w = w + more                 d = d + more


if first:                 # change F baseline so it centers on the sign                 prettyF.baseline -= d - (prettyF.height()//2 -                                         prettyF.baseline) - adjustment                                         prettyF.baseline)                 first = False              # put padding to the right


# put the present prettyF to the right             prettyF = prettyForm(*prettySign.right(prettyF))         prettyF.baseline = max_upper + sign_height//2        # adjust baseline of ascii mode sigma with an odd height so that it is        # exactly through the center        ascii_adjustment = ascii_mode if not adjustment else 0        prettyF.baseline = max_upper + sign_height//2 + ascii_adjustment         prettyF.binding = prettyForm.MUL         return prettyF


"""         if isinstance(factors, (SYMPY_INTS, float)):             factors = S(factors)<del></del>         if isinstance(factors, Factors):             factors = factors.factors.copy()         elif factors is None or factors is S.One:


for _ in range(i):                 c.remove(I)             factors = dict(Mul._from_args(c).as_powers_dict())<ins>            # Handle all rational Coefficients            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.pop(f)</ins>             if i:                 factors[I] = S.One*i             if nc:


import ast import unicodedata from sympy.core.compatibility import exec_, StringIOfrom sympy.core.compatibility import exec_, StringIO, iterable from sympy.core.basic import Basic from sympy.core import Symbolfrom sympy.core.function import arityfrom sympy.utilities.misc import filldedent, func_name  def _token_splittable(token):     """


result = []         split = False         split_previous=False         for tok in tokens:             if split_previous:                 # throw out closing parenthesis of Symbol that was split                 split_previous=False                 continue             split_previous=False             if tok[0] == NAME and tok[1] in ['Symbol', 'Function']:                 split = True             elif split and tok[0] == NAME:                 symbol = tok[1][1:-1]                 if predicate(symbol):                     tok_type = result[-2][1]  # Symbol or Function                     del result[-2:]  # Get rid of the call to Symbol                    for char in symbol[:-1]:                    i = 0                    while i < len(symbol):                        char = symbol[i]                         if char in local_dict or char in global_dict:                             result.extend([(NAME, "%s" % char)])                        elif char.isdigit():                            char = [char]                            for i in range(i + 1, len(symbol)):                                if not symbol[i].isdigit():                                  i -= 1                                  break                                char.append(symbol[i])                            char = ''.join(char)                            result.extend([(NAME, 'Number'), (OP, '('),                                           (NAME, "'%s'" % char), (OP, ')')])                         else:                            result.extend([(NAME, 'Symbol'), (OP, '('),                            use = tok_type if i == len(symbol) else 'Symbol'                            result.extend([(NAME, use), (OP, '('),                                            (NAME, "'%s'" % char), (OP, ')')])                    char = symbol[-1]                    if char in local_dict or char in global_dict:                        result.extend([(NAME, "%s" % char)])                    else:                        result.extend([(NAME, tok_type), (OP, '('),                                       (NAME, "'%s'" % char), (OP, ')')])                        i += 1                      # Set split_previous=True so will skip                     # the closing parenthesis of the original Symbol                     split = False                     split_previous = True                     continue                 else:                     split = False             result.append(tok)         return result     return _split_symbols


return result <ins></ins> def repeated_decimals(tokens, local_dict, global_dict):     """     Allows 0.2[1] notation to represent the repeated decimal 0.2111... (19/90)


return result <ins></ins> def auto_number(tokens, local_dict, global_dict):     """     Converts numeric literals to use SymPy equivalents.


return result <ins></ins> def rationalize(tokens, local_dict, global_dict):     """Converts floats into ``Rational``. Run AFTER ``auto_number``."""     result = []


if local_dict is None:         local_dict = {}    elif not isinstance(local_dict, dict):        raise TypeError('expecting local_dict to be a dict')      if global_dict is None:         global_dict = {}         exec_('from sympy import *', global_dict)    elif not isinstance(global_dict, dict):        raise TypeError('expecting global_dict to be a dict')    transformations = transformations or ()    if transformations:        if not iterable(transformations):            raise TypeError(                '`transformations` should be a list of functions.')        for _ in transformations:            if not callable(_):                raise TypeError(filldedent('''                    expected a function in `transformations`,                    not %s''' % func_name(_)))            if arity(_) != 3:                raise TypeError(filldedent('''                    a transformation should be function that                    takes 3 arguments'''))     code = stringify_expr(s, local_dict, global_dict, transformations)      if not evaluate:


if self.intersection(o) != []:             return S.Zero         if isinstance(o, Point3D):           x, y, z = map(Dummy, 'xyz')           k = self.equation(x, y, z)           a, b, c = [k.coeff(i) for i in (x, y, z)]           d = k.xreplace({x: o.args[0], y: o.args[1], z: o.args[2]})           t = abs(d/sqrt(a**2 + b**2 + c**2))           return t        if isinstance(o, LinearEntity3D):            a, b = o.p1, self.p1            c = Matrix(a.direction_ratio(b))            d = Matrix(self.normal_vector)            e = c.dot(d)            f = sqrt(sum([i**2 for i in self.normal_vector]))            return abs(e / f)        if isinstance(o, Plane):            a, b = o.p1, self.p1            c = Matrix(a.direction_ratio(b))            d = Matrix(self.normal_vector)            e = c.dot(d)            f = sqrt(sum([i**2 for i in self.normal_vector]))            return abs(e / f)        if isinstance(o, (Segment3D, Ray3D)):            a, b = o.p1, o.p2            pi, = self.intersection(Line3D(a, b))            if pi in o:                return self.distance(pi)            elif a in Segment3D(pi, b):                return self.distance(a)            else:                assert isinstance(o, Segment3D) is True                return self.distance(b)        # following code handles `Point3D`, `LinearEntity3D`, `Plane`        a = o if isinstance(o, Point3D) else o.p1        n = Point3D(self.normal_vector).unit        d = (a - self.p1).dot(n)        return abs(d)       def equals(self, o):


raise ValueError('unhandled linear entity: %s' % o.func)                 return [o]             else:                x, y, z = map(Dummy, 'xyz')                 t = Dummy()  # unnamed else it may clash with a symbol in o                 a = Point3D(o.arbitrary_point(t))                b = self.equation(x, y, z)                p1, n = self.p1, Point3D(self.normal_vector)                  # TODO: Replace solve with solveset, when this line is tested                c = solve(b.subs(list(zip((x, y, z), a.args))), t)                c = solve((a - p1).dot(n), t)                 if not c:                     return []                 else:                     p = a.subs(t, c[0])                    if p not in self:                    if p not in o:                         return []  # e.g. a segment might not intersect a plane                     return [p]         if isinstance(o, Plane):


PREC = precedence(expr)         return self._operators['not'] + self.parenthesize(expr.args[0], PREC) <ins>    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>  for k in PythonCodePrinter._kf:     setattr(PythonCodePrinter, '_print_%s' % k, _print_known_func)


from sympy.core.compatibility import default_sort_key from sympy.core.add import Add from sympy.core.mul import Mul<ins>from sympy.printing.repr import srepr</ins>  __all__ = ['dotprint']


(Expr,  {'color': 'black'}))  sort_classes = (Add, Mul) slotClasses = (Symbol, Integer, Rational, Float)# XXX: Why not just use srepr()?def purestr(x):def purestr(x, with_args=False):     """ A string that follows obj = type(obj)(*obj.args) exactly """    sargs = ()     if not isinstance(x, Basic):        return str(x)    if type(x) in slotClasses:        args = [getattr(x, slot) for slot in x.__slots__]    elif type(x) in sort_classes:        args = sorted(x.args, key=default_sort_key)        rv = str(x)    elif not x.args:        rv = srepr(x)     else:         args = x.args    return "%s(%s)"%(type(x).__name__, ', '.join(map(purestr, args)))        if isinstance(x, Add) or \                isinstance(x, Mul) and x.is_commutative:            args = sorted(args, key=default_sort_key)        sargs = tuple(map(purestr, args))        rv = "%s(%s)"%(type(x).__name__, ', '.join(sargs))    if with_args:        rv = rv, sargs    return rv   def styleof(expr, styles=default_styles):


style.update(sty)     return style <ins></ins> def attrprint(d, delimiter=', '):     """ Print a dictionary of attributes


"""     return delimiter.join('"%s"="%s"'%item for item in sorted(d.items())) <ins></ins> def dotnode(expr, styles=default_styles, labelfunc=str, pos=(), repeat=True):     """ String defining a node


>>> from sympy.printing.dot import dotnode     >>> from sympy.abc import x     >>> print(dotnode(x))    "Symbol(x)_()" ["color"="black", "label"="x", "shape"="ellipse"];    "Symbol('x')_()" ["color"="black", "label"="x", "shape"="ellipse"];     """     style = styleof(expr, styles)


>>> from sympy.abc import x     >>> for e in dotedges(x+2):     ...     print(e)    "Add(Integer(2), Symbol(x))_()" -> "Integer(2)_(0,)";    "Add(Integer(2), Symbol(x))_()" -> "Symbol(x)_(1,)";    "Add(Integer(2), Symbol('x'))_()" -> "Integer(2)_(0,)";    "Add(Integer(2), Symbol('x'))_()" -> "Symbol('x')_(1,)";     """    from sympy.utilities.misc import func_name     if atom(expr):         return []     else:        # TODO: This is quadratic in complexity (purestr(expr) already        # contains [purestr(arg) for arg in expr.args]).        expr_str = purestr(expr)        arg_strs = [purestr(arg) for arg in expr.args]        expr_str, arg_strs = purestr(expr, with_args=True)         if repeat:             expr_str += '_%s' % str(pos)            arg_strs = [arg_str + '_%s' % str(pos + (i,)) for i, arg_str in enumerate(arg_strs)]        return ['"%s" -> "%s";' % (expr_str, arg_str) for arg_str in arg_strs]            arg_strs = ['%s_%s' % (a, str(pos + (i,)))                for i, a in enumerate(arg_strs)]        return ['"%s" -> "%s";' % (expr_str, a) for a in arg_strs]  template = \ """digraph{


``repeat=True``, it will have two nodes for ``x`` and with           ``repeat=False``, it will have one (warning: even if it appears           twice in the same object, like Pow(x, x), it will still only appear          only once.  Hence, with repeat=False, the number of arrows out of an          once.  Hence, with repeat=False, the number of arrows out of an           object might not equal the number of args it has).      ``labelfunc``: How to label leaf nodes.  The default is ``str``.  Another


# Nodes #     #########     <BLANKLINE>    "Add(Integer(2), Symbol(x))_()" ["color"="black", "label"="Add", "shape"="ellipse"];    "Add(Integer(2), Symbol('x'))_()" ["color"="black", "label"="Add", "shape"="ellipse"];     "Integer(2)_(0,)" ["color"="black", "label"="2", "shape"="ellipse"];    "Symbol(x)_(1,)" ["color"="black", "label"="x", "shape"="ellipse"];    "Symbol('x')_(1,)" ["color"="black", "label"="x", "shape"="ellipse"];     <BLANKLINE>     #########     # Edges #     #########     <BLANKLINE>    "Add(Integer(2), Symbol(x))_()" -> "Integer(2)_(0,)";    "Add(Integer(2), Symbol(x))_()" -> "Symbol(x)_(1,)";    "Add(Integer(2), Symbol('x'))_()" -> "Integer(2)_(0,)";    "Add(Integer(2), Symbol('x'))_()" -> "Symbol('x')_(1,)";     }      """


arg_list = []          # setup input argument list<ins>        # helper to get dimensions for data for array-like args        def dimensions(s):            return [(S.Zero, dim - 1) for dim in s.shape]</ins>         array_symbols = {}         for array in expressions.atoms(Indexed) | local_expressions.atoms(Indexed):             array_symbols[array.base.label] = array


for symbol in sorted(symbols, key=str):             if symbol in array_symbols:                dims = []                 array = array_symbols[symbol]                for dim in array.shape:                    dims.append((S.Zero, dim - 1))                metadata = {'dimensions': dims}                metadata = {'dimensions': dimensions(array)}             else:                 metadata = {}


try:                     new_args.append(name_arg_dict[symbol])                 except KeyError:                    new_args.append(InputArgument(symbol))                    if isinstance(symbol, (IndexedBase, MatrixSymbol)):                        metadata = {'dimensions': dimensions(symbol)}                    else:                        metadata = {}                    new_args.append(InputArgument(symbol, **metadata))             arg_list = new_args          return Routine(name, arg_list, return_val, local_vars, global_vars)


def _contains(self, other):         from sympy.matrices import Matrix         from sympy.solvers.solveset import solveset, linsolve<ins>        from sympy.solvers.solvers import solve</ins>         from sympy.utilities.iterables import is_sequence, iterable, cartes         L = self.lamda         if is_sequence(other):


solns = list(linsolve([e - val for e, val in                 zip(L.expr, other)], variables))             else:                syms = [e.free_symbols & free for e in eqs]                solns = {}                for i, (e, s, v) in enumerate(zip(eqs, syms, other)):                    if not s:                        if e != v:                            return S.false                        solns[vars[i]] = [v]                        continue                    elif len(s) == 1:                        sy = s.pop()                        sol = solveset(e, sy)                        if sol is S.EmptySet:                            return S.false                        elif isinstance(sol, FiniteSet):                            solns[sy] = list(sol)                try:                    syms = [e.free_symbols & free for e in eqs]                    solns = {}                    for i, (e, s, v) in enumerate(zip(eqs, syms, other)):                        if not s:                            if e != v:                                return S.false                            solns[vars[i]] = [v]                            continue                        elif len(s) == 1:                            sy = s.pop()                            sol = solveset(e, sy)                            if sol is S.EmptySet:                                return S.false                            elif isinstance(sol, FiniteSet):                                solns[sy] = list(sol)                            else:                                raise NotImplementedError                         else:                            # if there is more than 1 symbol from                            # variables in expr than this is a                            # coupled system                             raise NotImplementedError                    else:                        raise NotImplementedError                solns = cartes(*[solns[s] for s in variables])                    solns = cartes(*[solns[s] for s in variables])                except NotImplementedError:                    solns = solve([e - val for e, val in                        zip(L.expr, other)], variables, set=True)                    if solns:                        _v, solns = solns                        # watch for infinite solutions like solving                        # for x, y and getting (x, 0), (0, y), (0, 0)                        solns = [i for i in solns if not any(                            s in i for s in variables)]         else:             x = L.variables[0]             if isinstance(L.expr, Expr):


Either the start or end value of the Range must be finite.'''))          if start.is_infinite:            end = stop        else:            if step*(stop - start) < 0:                start = stop = S.One            else:                end = stop        if not start.is_infinite:             ref = start if start.is_finite else stop             n = ceiling((stop - ref)/step)             if n <= 0:


"..-": "U", "...-": "V",     ".--": "W", "-..-": "X",     "-.--": "Y", "--..": "Z",    "-----": "0", "----": "1",    "-----": "0", ".----": "1",     "..---": "2", "...--": "3",     "....-": "4", ".....": "5",     "-....": "6", "--...": "7",


>>> X = HadamardProduct(A, OneMatrix(2, 2))     >>> X    A.*OneMatrix(2, 2)    A.*1     >>> canonicalize(X)     A diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py-- a/sympy/printing/latex.py++ b/sympy/printing/latex.py


_print_RandomSymbol = _print_Symbol <del>    def _print_MatrixSymbol(self, expr):        return self._print_Symbol(expr,                                  style=self._settings['mat_symbol_style'])</del>     def _deal_with_super_sub(self, string):         if '{' in string:             return string


else:             return "%s^{%s}" % (self._print(base), self._print(exp))     def _print_MatrixSymbol(self, expr):        return self._print_Symbol(expr, style=self._settings[            'mat_symbol_style'])     def _print_ZeroMatrix(self, Z):        return r"\mathbb{0}"        return r"\mathbb{0}" if self._settings[            'mat_symbol_style'] == 'plain' else r"\mathbf{0}"      def _print_OneMatrix(self, O):        return r"\mathbb{1}"        return r"\mathbb{1}" if self._settings[            'mat_symbol_style'] == 'plain' else r"\mathbf{1}"      def _print_Identity(self, I):        return r"\mathbb{I}"        return r"\mathbb{I}" if self._settings[            'mat_symbol_style'] == 'plain' else r"\mathbf{I}"      def _print_NDimArray(self, expr): diff --git a/sympy/printing/mathml.py b/sympy/printing/mathml.py-- a/sympy/printing/mathml.py++ b/sympy/printing/mathml.py


x.appendChild(self.dom.createTextNode('&#x1D7D8'))         return x     def _print_OneMatrix(self, Z):        x = self.dom.createElement('mn')        x.appendChild(self.dom.createTextNode('&#x1D7D9'))        return x     def _print_Identity(self, I):         x = self.dom.createElement('mi')         x.appendChild(self.dom.createTextNode('𝕀'))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


return prettyForm.__mul__(*args)     def _print_Identity(self, expr):        if self._use_unicode:            return prettyForm(u'\N{MATHEMATICAL DOUBLE-STRUCK CAPITAL I}')        else:            return prettyForm('I')    def _print_ZeroMatrix(self, expr):        if self._use_unicode:            return prettyForm(u'\N{MATHEMATICAL DOUBLE-STRUCK DIGIT ZERO}')        else:            return prettyForm('0')    def _print_OneMatrix(self, expr):        if self._use_unicode:            return prettyForm(u'\N{MATHEMATICAL DOUBLE-STRUCK DIGIT ONE}')        else:            return prettyForm('1')     def _print_DotProduct(self, expr):         args = list(expr.args) diff --git a/sympy/printing/str.py b/sympy/printing/str.py-- a/sympy/printing/str.py++ b/sympy/printing/str.py


def _print_ZeroMatrix(self, expr):         return "0" <ins>    def _print_OneMatrix(self, expr):        return "1"</ins>     def _print_Predicate(self, expr):         return "Q.%s" % expr.name


result[2].subs(x, rep2 + rep2b))      if f.is_polynomial(x):        return None        k = Dummy('k')        ak = sequence(Coeff(f, x, k), (k, 1, oo))        xk = sequence(x**k, (k, 0, oo))        ind = f.coeff(x, 0)        return ak, xk, ind      #  Break instances of Add     #  this allows application of different


return _compute_fps(f, x, x0, dir, hyper, order, rational, full)  <ins>class Coeff(Function):    """    Coeff(p, x, n) represents the nth coefficient of the polynomial p in x    """    @classmethod    def eval(cls, p, x, n):        if p.is_polynomial(x) and n.is_integer:            return p.coeff(x, n)</ins> class FormalPowerSeries(SeriesBase):     """Represents Formal Power Series of a function.


evaluate = kwargs.get('evaluate', global_evaluate[0])          # flatten inputs to merge intersections and iterables        args = _sympify(args)        args = list(ordered(set(_sympify(args))))          # Reduce sets using known rules         if evaluate:


if n == S.NegativeOne:                     # n can not be -1 here                     return S.Zero                else:                elif not (-n - 2).could_extract_minus_sign():                     return -chebyshevu(-n - 2, x)             # We can evaluate for some special values of x             if x == S.Zero:


if x.could_extract_minus_sign():                 return S.NegativeOne**n * legendre(n, -x)             # L_{-n}(x)  --->  L_{n-1}(x)            if n.could_extract_minus_sign():            if n.could_extract_minus_sign() and not(-n - 1).could_extract_minus_sign():                 return legendre(-n - S.One, x)             # We can evaluate for some special values of x             if x == S.Zero:


@classmethod     def eval(cls, n, x):        if n.is_integer is False:            raise ValueError("Error: n should be an integer.")         if not n.is_Number:             # Symbolic result L_n(x)             # L_{n}(-x)  --->  exp(-x) * L_{-n-1}(x)             # L_{-n}(x)  --->  exp(x) * L_{n-1}(-x)            if n.could_extract_minus_sign():                return exp(x) * laguerre(n - 1, -x)            if n.could_extract_minus_sign() and not(-n - 1).could_extract_minus_sign():                return exp(x)*laguerre(-n - 1, -x)             # We can evaluate for some special values of x             if x == S.Zero:                 return S.One


elif x == S.Infinity:                 return S.NegativeOne**n * S.Infinity         else:            # n is a given fixed integer, evaluate into polynomial             if n.is_negative:                raise ValueError(                    "The index n must be nonnegative integer (got %r)" % n)                return exp(x)*laguerre(-n - 1, -x)             else:                 return cls._eval_at_order(n, x)


def _eval_rewrite_as_polynomial(self, n, x, **kwargs):         from sympy import Sum         # Make sure n \in N_0        if n.is_negative or n.is_integer is False:            raise ValueError("Error: n should be a non-negative integer.")        if n.is_negative:            return exp(x) * self._eval_rewrite_as_polynomial(-n - 1, -x, **kwargs)        if n.is_integer is False:            raise ValueError("Error: n should be an integer.")         k = Dummy("k")         kern = RisingFactorial(-n, k) / factorial(k)**2 * x**k         return Sum(kern, (k, 0, n))


References     ==========     .. [1] https://en.wikipedia.org/wiki/Laguerre_polynomial#Assoc_laguerre_polynomials    .. [1] https://en.wikipedia.org/wiki/Laguerre_polynomial#Generalized_Laguerre_polynomials     .. [2] http://mathworld.wolfram.com/AssociatedLaguerrePolynomial.html     .. [3] http://functions.wolfram.com/Polynomials/LaguerreL/     .. [4] http://functions.wolfram.com/Polynomials/LaguerreL3/


func = self._module_format('numpy.array')         return "%s(%s)" % (func, self._print(expr.tolist())) <ins>    def _print_Identity(self, expr):        shape = expr.shape        if all([dim.is_Integer for dim in shape]):            return "%s(%s)" % (self._module_format('numpy.eye'), self._print(expr.shape[0]))        else:            raise NotImplementedError("Symbolic matrix dimensions are not yet supported for identity matrices")</ins>     def _print_BlockMatrix(self, expr):         return '{0}({1})'.format(self._module_format('numpy.block'),                                  self._print(expr.args[0].tolist()))


def isqrt(n):     """Return the largest integer less than or equal to sqrt(n)."""    if n < 17984395633462800708566937239552:        return int(_sqrt(n))    return integer_nthroot(int(n), 2)[0]    if n < 0:        raise ValueError("n must be nonnegative")    n = int(n)    # Fast path: with IEEE 754 binary64 floats and a correctly-rounded    # math.sqrt, int(math.sqrt(n)) works for any integer n satisfying 0 <= n <    # 4503599761588224 = 2**52 + 2**27. But Python doesn't guarantee either    # IEEE 754 format floats *or* correct rounding of math.sqrt, so check the    # answer and fall back to the slow method if necessary.    if n < 4503599761588224:        s = int(_sqrt(n))        if 0 <= n - s*s <= 2*s:            return s    return integer_nthroot(n, 2)[0]   def integer_nthroot(y, n):


"""     def f(rv):    def f(rv, first=True):         if not rv.is_Mul:             return rv        if first:            n, d = rv.as_numer_denom()            return f(n, 0)/f(d, 0)          args = defaultdict(list)         coss = {}


isinstance(i, (Eq, Ne))])      def as_set(self):        return self        raise NotImplementedError()


# change is not going to allow a simplification as far as I can tell.         if not (rv.is_Pow and rv.base.func == f):             return rv<ins>        if not rv.exp.is_real:            return rv</ins>          if (rv.exp < 0) == True:             return rv


a logarithm of a different base ``b``, use ``log(x, b)``,     which is essentially short-hand for ``log(x)/log(b)``. <ins>    Examples    ========    >>> from sympy import log, S    >>> log(8, 2)    3    >>> log(S(8)/3, 2)    -log(3)/log(2) + 3</ins>     See Also     ========


# or else expand_log in Mul would have to handle this                 n = multiplicity(base, arg)                 if n:                    den = base**n                    if den.is_Integer:                        return n + log(arg // den) / log(base)                    else:                        return n + log(arg / den) / log(base)                    return n + log(arg / base**n) / log(base)                 else:                     return log(arg)/log(base)             except ValueError:


r*(x - i),                                             range(1, abs(int(k)) + 1), 1) <ins>        if k.is_integer == False:            if x.is_integer and x.is_negative:                return S.Zero</ins>     def _eval_rewrite_as_gamma(self, x, k, **kwargs):         from sympy import gamma         return gamma(x + k) / gamma(x)


"""     Assign a 5-item fingerprint to each symbol in the equation:     [    # of times it appeared as a Symbol,    # of times it appeared as a Not(symbol),    # of times it appeared as a Symbol in an And or Or,    # of times it appeared as a Not(Symbol) in an And or Or,    sum of the number of arguments with which it appeared    as a Symbol, counting Symbol as 1 and Not(Symbol) as 2    and counting self as 1    # of times it appeared as a Symbol;    # of times it appeared as a Not(symbol);    # of times it appeared as a Symbol in an And or Or;    # of times it appeared as a Not(Symbol) in an And or Or;    a sorted tuple of tuples, (i, j, k), where i is the number of arguments    in an And or Or with which it appeared as a Symbol, and j is    the number of arguments that were Not(Symbol); k is the number    of times that (i, j) was seen.     ]      Examples     ========      >>> from sympy.logic.boolalg import _finger as finger    >>> from sympy import And, Or, Not    >>> from sympy import And, Or, Not, Xor, to_cnf, symbols     >>> from sympy.abc import a, b, x, y     >>> eq = Or(And(Not(y), a), And(Not(y), b), And(x, y))     >>> dict(finger(eq))    {(0, 0, 1, 0, 2): [x], (0, 0, 1, 0, 3): [a, b], (0, 0, 1, 2, 2): [y]}    {(0, 0, 1, 0, ((2, 0, 1),)): [x],    (0, 0, 1, 0, ((2, 1, 1),)): [a, b],    (0, 0, 1, 2, ((2, 0, 1),)): [y]}     >>> dict(finger(x & ~y))    {(0, 1, 0, 0, 0): [y], (1, 0, 0, 0, 0): [x]}    {(0, 1, 0, 0, ()): [y], (1, 0, 0, 0, ()): [x]}    In the following, the (5, 2, 6) means that there were 6 Or    functions in which a symbol appeared as itself amongst 5 arguments in    which there were also 2 negated symbols, e.g. ``(a0 | a1 | a2 | ~a3 | ~a4)``    is counted once for a0, a1 and a2.    >>> dict(finger(to_cnf(Xor(*symbols('a:5')))))    {(0, 0, 8, 8, ((5, 0, 1), (5, 2, 6), (5, 4, 1))): [a0, a1, a2, a3, a4]}      The equation must not have more than one level of nesting:      >>> dict(finger(And(Or(x, y), y)))    {(0, 0, 1, 0, 2): [x], (1, 0, 1, 0, 2): [y]}    {(0, 0, 1, 0, ((2, 0, 1),)): [x], (1, 0, 1, 0, ((2, 0, 1),)): [y]}     >>> dict(finger(And(Or(x, And(a, x)), y)))     Traceback (most recent call last):     ...


So y and x have unique fingerprints, but a and b do not.     """     f = eq.free_symbols    d = dict(list(zip(f, [[0] * 5 for fi in f])))    d = dict(list(zip(f, [[0]*4 + [defaultdict(int)] for fi in f])))     for a in eq.args:         if a.is_Symbol:             d[a][0] += 1         elif a.is_Not:             d[a.args[0]][1] += 1         else:            o = len(a.args) + sum(isinstance(ai, Not) for ai in a.args)            o = len(a.args), sum(isinstance(ai, Not) for ai in a.args)             for ai in a.args:                 if ai.is_Symbol:                     d[ai][2] += 1                    d[ai][-1] += o                    d[ai][-1][o] += 1                 elif ai.is_Not:                     d[ai.args[0]][3] += 1                 else:                     raise NotImplementedError('unexpected level of nesting')     inv = defaultdict(list)     for k, v in ordered(iter(d.items())):        v[-1] = tuple(sorted([i + (j,) for i, j in v[-1].items()]))         inv[tuple(v)].append(k)     return inv


for e, c in self.args:             if hints.get('deep', True):                 if isinstance(e, Basic):                    e = e.doit(**hints)                    newe = e.doit(**hints)                    if newe != self:                        e = newe                 if isinstance(c, Basic):                     c = c.doit(**hints)             newargs.append((e, c))


import mpmath.libmp as mlib from mpmath.libmp import prec_to_dps <ins></ins> class MathMLPrinterBase(Printer):     """Contains common code required for MathMLContentPrinter and     MathMLPresentationPrinter.


'Number': 'cn',             'int': 'cn',             'Pow': 'power',<ins>            'Max': 'max',            'Min': 'min',            'Abs': 'abs',            'And': 'and',            'Or': 'or',            'Xor': 'xor',            'Not': 'not',            'Implies': 'implies',</ins>             'Symbol': 'ci',             'MatrixSymbol': 'ci',             'RandomSymbol': 'ci',


'cos': 'cos',             'tan': 'tan',             'cot': 'cot',            'csc': 'csc',            'sec': 'sec',            'sinh': 'sinh',            'cosh': 'cosh',            'tanh': 'tanh',            'coth': 'coth',            'csch': 'csch',            'sech': 'sech',             'asin': 'arcsin',             'asinh': 'arcsinh',             'acos': 'arccos',             'acosh': 'arccosh',             'atan': 'arctan',             'atanh': 'arctanh',            'acot': 'arccot',             'atan2': 'arctan',            'acot': 'arccot',            'acoth': 'arccoth',            'asec': 'arcsec',            'asech': 'arcsech',            'acsc': 'arccsc',            'acsch': 'arccsch',             'log': 'ln',             'Equality': 'eq',             'Unequality': 'neq',


def _print_Infinity(self, e):         return self.dom.createElement('infinity') <ins>    def _print_NaN(self, e):        return self.dom.createElement('notanumber')    def _print_EmptySet(self, e):        return self.dom.createElement('emptyset')    def _print_BooleanTrue(self, e):        return self.dom.createElement('true')    def _print_BooleanFalse(self, e):        return self.dom.createElement('false')</ins>     def _print_NegativeInfinity(self, e):         x = self.dom.createElement('apply')         x.appendChild(self.dom.createElement('minus'))


dom_element.appendChild(self.dom.createTextNode(str(p)))         return dom_element <ins>    _print_Implies = _print_AssocOp    _print_Not = _print_AssocOp    _print_Xor = _print_AssocOp</ins>  class MathMLPresentationPrinter(MathMLPrinterBase):     """Prints an expression to the Presentation MathML markup language.


return AssocOp._matches_commutative(self, expr, repl_dict, old)         elif self.is_commutative is not expr.is_commutative:             return None        # Proceed only if both both expressions are non-commutative         c1, nc1 = self.args_cnc()         c2, nc2 = expr.args_cnc()        repl_dict = repl_dict.copy()        if c1:            if not c2:                c2 = [1]            a = self.func(*c1)            if isinstance(a, AssocOp):                repl_dict = a._matches_commutative(self.func(*c2), repl_dict, old)            else:                repl_dict = a.matches(self.func(*c2), repl_dict)        if repl_dict:            a = self.func(*nc1)            if isinstance(a, self.func):                repl_dict = a._matches(self.func(*nc2), repl_dict)            else:                repl_dict = a.matches(self.func(*nc2), repl_dict)        c1, c2 = [c or [1] for c in [c1, c2]]        # TODO: Should these be self.func?        comm_mul_self = Mul(*c1)        comm_mul_expr = Mul(*c2)        repl_dict = comm_mul_self.matches(comm_mul_expr, repl_dict, old)        # If the commutative arguments didn't match and aren't equal, then        # then the expression as a whole doesn't match        if repl_dict is None and c1 != c2:            return None        # Now match the non-commutative arguments, expanding powers to        # multiplications        nc1 = Mul._matches_expand_pows(nc1)        nc2 = Mul._matches_expand_pows(nc2)        repl_dict = Mul._matches_noncomm(nc1, nc2, repl_dict)         return repl_dict or None     def _matches(self, expr, repl_dict={}):        # weed out negative one prefixes#        from sympy import Wild        sign = 1        a, b = self.as_two_terms()        if a is S.NegativeOne:            if b.is_Mul:                sign = -sign    @staticmethod    def _matches_expand_pows(arg_list):        new_args = []        for arg in arg_list:            if arg.is_Pow and arg.exp > 0:                new_args.extend([arg.base] * arg.exp)             else:                # the remainder, b, is not a Mul anymore                return b.matches(-expr, repl_dict)        expr = sympify(expr)        if expr.is_Mul and expr.args[0] is S.NegativeOne:            expr = -expr            sign = -sign        if not expr.is_Mul:            # expr can only match if it matches b and a matches +/- 1            if len(self.args) == 2:                # quickly test for equality                if b == expr:                    return a.matches(Rational(sign), repl_dict)                # do more expensive match                dd = b.matches(expr, repl_dict)                if dd is None:                    return None                dd = a.matches(Rational(sign), dd)                return dd            return None                new_args.append(arg)        return new_args         d = repl_dict.copy()    @staticmethod    def _matches_noncomm(nodes, targets, repl_dict={}):        """Non-commutative multiplication matcher.         # weed out identical terms        pp = list(self.args)        ee = list(expr.args)        for p in self.args:            if p in expr.args:                ee.remove(p)                pp.remove(p)        `nodes` is a list of symbols within the matcher multiplication        expression, while `targets` is a list of arguments in the        multiplication expression being matched against.        """        # List of possible future states to be considered        agenda = []        # The current matching state, storing index in nodes and targets        state = (0, 0)        node_ind, target_ind = state        # Mapping between wildcard indices and the index ranges they match        wildcard_dict = {}        repl_dict = repl_dict.copy()         # only one symbol left in pattern -> match the remaining expression        if len(pp) == 1 and isinstance(pp[0], Wild):            if len(ee) == 1:                d[pp[0]] = sign * ee[0]        while target_ind < len(targets) and node_ind < len(nodes):            node = nodes[node_ind]            if node.is_Wild:                Mul._matches_add_wildcard(wildcard_dict, state)            states_matches = Mul._matches_new_states(wildcard_dict, state,                                                     nodes, targets)            if states_matches:                new_states, new_matches = states_matches                agenda.extend(new_states)                if new_matches:                    for match in new_matches:                        repl_dict[match] = new_matches[match]            if not agenda:                return None             else:                d[pp[0]] = sign * expr.func(*ee)            return d                state = agenda.pop()                node_ind, target_ind = state        return repl_dict         if len(ee) != len(pp):    @staticmethod    def _matches_add_wildcard(dictionary, state):        node_ind, target_ind = state        if node_ind in dictionary:            begin, end = dictionary[node_ind]            dictionary[node_ind] = (begin, target_ind)        else:            dictionary[node_ind] = (target_ind, target_ind)    @staticmethod    def _matches_new_states(dictionary, state, nodes, targets):        node_ind, target_ind = state        node = nodes[node_ind]        target = targets[target_ind]        # Don't advance at all if we've exhausted the targets but not the nodes        if target_ind >= len(targets) - 1 and node_ind < len(nodes) - 1:             return None         for p, e in zip(pp, ee):            d = p.xreplace(d).matches(e, d)            if d is None:        if node.is_Wild:            match_attempt = Mul._matches_match_wilds(dictionary, node_ind,                                                     nodes, targets)            if match_attempt:                # If the same node has been matched before, don't return                # anything if the current match is diverging from the previous                # match                other_node_inds = Mul._matches_get_other_nodes(dictionary,                                                               nodes, node_ind)                for ind in other_node_inds:                    other_begin, other_end = dictionary[ind]                    curr_begin, curr_end = dictionary[node_ind]                    other_targets = targets[other_begin:other_end + 1]                    current_targets = targets[curr_begin:curr_end + 1]                    for curr, other in zip(current_targets, other_targets):                        if curr != other:                            return None                # A wildcard node can match more than one target, so only the                # target index is advanced                new_state = [(node_ind, target_ind + 1)]                # Only move on to the next node if there is one                if node_ind < len(nodes) - 1:                    new_state.append((node_ind + 1, target_ind + 1))                return new_state, match_attempt        else:            # If we're not at a wildcard, then make sure we haven't exhausted            # nodes but not targets, since in this case one node can only match            # one target            if node_ind >= len(nodes) - 1 and target_ind < len(targets) - 1:                return None            match_attempt = node.matches(target)            if match_attempt:                return [(node_ind + 1, target_ind + 1)], match_attempt            elif node == target:                return [(node_ind + 1, target_ind + 1)], None            else:                 return None        return d    @staticmethod    def _matches_match_wilds(dictionary, wildcard_ind, nodes, targets):        """Determine matches of a wildcard with sub-expression in `target`."""        wildcard = nodes[wildcard_ind]        begin, end = dictionary[wildcard_ind]        terms = targets[begin:end + 1]        # TODO: Should this be self.func?        mul = Mul(*terms) if len(terms) > 1 else terms[0]        return wildcard.matches(mul)    @staticmethod    def _matches_get_other_nodes(dictionary, nodes, node_ind):        """Find other wildcards that may have already been matched."""        other_node_inds = []        for ind in dictionary:            if nodes[ind] == nodes[node_ind]:                other_node_inds.append(ind)        return other_node_inds      @staticmethod     def _combine_inverse(lhs, rhs):


elif isinstance(arg, SetExpr):             return arg._eval_func(cls)         elif arg.is_Mul:            if arg.is_number or arg.is_Symbol:                coeff = arg.coeff(S.Pi*S.ImaginaryUnit)                if coeff:                    if ask(Q.integer(2*coeff)):                        if ask(Q.even(coeff)):                            return S.One                        elif ask(Q.odd(coeff)):                            return S.NegativeOne                        elif ask(Q.even(coeff + S.Half)):                            return -S.ImaginaryUnit                        elif ask(Q.odd(coeff + S.Half)):                            return S.ImaginaryUnit            coeff = arg.as_coefficient(S.Pi*S.ImaginaryUnit)            if coeff:                if (2*coeff).is_integer:                    if coeff.is_even:                        return S.One                    elif coeff.is_odd:                        return S.NegativeOne                    elif (coeff + S.Half).is_even:                        return -S.ImaginaryUnit                    elif (coeff + S.Half).is_odd:                        return S.ImaginaryUnit                elif coeff.is_Rational:                    ncoeff = coeff % 2 # restrict to [0, 2pi)                    if ncoeff > 1: # restrict to (-pi, pi]                        ncoeff -= 2                    if ncoeff != coeff:                        return cls(ncoeff*S.Pi*S.ImaginaryUnit)              # Warning: code in risch.py will be very sensitive to changes             # in this (see DifferentialExtension).


elif arg.is_Add:             out = []             add = []            argchanged = False             for a in arg.args:                 if a is S.One:                     add.append(a)                     continue                 newa = cls(a)                 if isinstance(newa, cls):                    add.append(a)                    if newa.args[0] != a:                        add.append(newa.args[0])                        argchanged = True                    else:                        add.append(a)                 else:                     out.append(newa)            if out:            if out or argchanged:                 return Mul(*out)*cls(Add(*add), evaluate=False)          elif isinstance(arg, MatrixBase):diff --git a/sympy/physics/matrices.py b/sympy/physics/matrices.py-- a/sympy/physics/matrices.py++ b/sympy/physics/matrices.py


>>> mdft(3)     Matrix([     [sqrt(3)/3,                sqrt(3)/3,                sqrt(3)/3],    [sqrt(3)/3, sqrt(3)*exp(-2*I*pi/3)/3, sqrt(3)*exp(-4*I*pi/3)/3],    [sqrt(3)/3, sqrt(3)*exp(-4*I*pi/3)/3, sqrt(3)*exp(-8*I*pi/3)/3]])    [sqrt(3)/3, sqrt(3)*exp(-2*I*pi/3)/3,  sqrt(3)*exp(2*I*pi/3)/3],    [sqrt(3)/3,  sqrt(3)*exp(2*I*pi/3)/3, sqrt(3)*exp(-2*I*pi/3)/3]])     """     mat = [[None for x in range(n)] for y in range(n)]     base = exp(-2*pi*I/n)


from sympy.core import Add, S from sympy.core.evalf import get_integer_part, PrecisionExhausted from sympy.core.function import Functionfrom sympy.core.logic import fuzzy_or from sympy.core.numbers import Integerfrom sympy.core.relational import Gt, Lt, Ge, Lefrom sympy.core.relational import Gt, Lt, Ge, Le, Relational from sympy.core.symbol import Symbolfrom sympy.core.sympify import _sympify   ###############################################################################


def __le__(self, other):         if self.args[0] == other and other.is_real:             return S.true<ins>        if other is S.Infinity and self.is_finite:            return S.true</ins>         return Le(self, other, evaluate=False)      def __gt__(self, other):


def __ge__(self, other):         if self.args[0] == other and other.is_real:             return S.true<ins>        if other is S.NegativeInfinity and self.is_real:            return S.true</ins>         return Ge(self, other, evaluate=False)


if arg is S.NaN:                     return S.NaN                 elif arg is S.ComplexInfinity:                    return None                    return S.NaN                 else:                     return arg - floor(arg)             return cls(arg, evaluate=False)


if (self.rewrite(floor) == other) or \                     (self.rewrite(ceiling) == other):                 return S.true            # Check if other < 0            if other.is_extended_negative:                return S.false            # Check if other >= 1            res = self._value_one_or_more(other)            if res is not None:                return S.false    def _eval_is_finite(self):        return True    def _eval_is_real(self):        return self.args[0].is_extended_real    def _eval_is_imaginary(self):        return self.args[0].is_imaginary    def _eval_is_integer(self):        return self.args[0].is_integer    def _eval_is_zero(self):        return fuzzy_or([self.args[0].is_zero, self.args[0].is_integer])    def _eval_is_negative(self):        return False    def __ge__(self, other):        if self.is_extended_real:            other = _sympify(other)            # Check if other <= 0            if other.is_extended_nonpositive:                return S.true            # Check if other >= 1            res = self._value_one_or_more(other)            if res is not None:                return not(res)        return Ge(self, other, evaluate=False)    def __gt__(self, other):        if self.is_extended_real:            other = _sympify(other)            # Check if other < 0            res = self._value_one_or_more(other)            if res is not None:                return not(res)            # Check if other >= 1            if other.is_extended_negative:                return S.true        return Gt(self, other, evaluate=False)    def __le__(self, other):        if self.is_extended_real:            other = _sympify(other)            # Check if other < 0            if other.is_extended_negative:                return S.false            # Check if other >= 1            res = self._value_one_or_more(other)            if res is not None:                return res        return Le(self, other, evaluate=False)    def __lt__(self, other):        if self.is_extended_real:            other = _sympify(other)            # Check if other <= 0            if other.is_extended_nonpositive:                return S.false            # Check if other >= 1            res = self._value_one_or_more(other)            if res is not None:                return res        return Lt(self, other, evaluate=False)    def _value_one_or_more(self, other):        if other.is_extended_real:            if other.is_number:                res = other >= 1                if res and not isinstance(res, Relational):                    return S.true            if other.is_integer and other.is_positive:                return S.truediff --git a/sympy/printing/latex.py b/sympy/printing/latex.py-- a/sympy/printing/latex.py++ b/sympy/printing/latex.py


def _print_UniversalSet(self, expr):         return r"\mathbb{U}" <ins>    def _print_frac(self, expr, exp=None):        if exp is None:            return r"\operatorname{frac}{\left(%s\right)}" % self._print(expr.args[0])        else:            return r"\operatorname{frac}{\left(%s\right)}^{%s}" % (                    self._print(expr.args[0]), self._print(exp))</ins>     def _print_tuple(self, expr):         if self._settings['decimal_separator'] =='comma':             return r"\left( %s\right)" % \


year, years, tropical_year,     G, gravitational_constant,     c, speed_of_light,<ins>    elementary_charge,</ins>     Z0,     hbar,     planck,


>>> from sympy.physics import units as u     >>> u.find_unit('charge')    ['C', 'coulomb', 'coulombs', 'planck_charge']    ['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge']     >>> u.find_unit(u.charge)    ['C', 'coulomb', 'coulombs', 'planck_charge']    ['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge']     >>> u.find_unit("ampere")     ['ampere', 'amperes']     >>> u.find_unit('volt')diff --git a/sympy/physics/units/definitions.py b/sympy/physics/units/definitions.py-- a/sympy/physics/units/definitions.py++ b/sympy/physics/units/definitions.py


#### CONSTANTS ####  # Newton constant# REF: NIST SP 959 (June 2019) G = gravitational_constant = Quantity("gravitational_constant", abbrev="G") gravitational_constant.set_dimension(length**3*mass**-1*time**-2)gravitational_constant.set_scale_factor(6.67408e-11*m**3/(kg*s**2))gravitational_constant.set_scale_factor(6.67430e-11*m**3/(kg*s**2))  # speed of light c = speed_of_light = Quantity("speed_of_light", abbrev="c") speed_of_light.set_dimension(velocity) speed_of_light.set_scale_factor(299792458*meter/second) # Reduced Planck constanthbar = Quantity("hbar", abbrev="hbar")hbar.set_dimension(action)hbar.set_scale_factor(1.05457266e-34*joule*second)# elementary charge# REF: NIST SP 959 (June 2019)elementary_charge = Quantity("elementary_charge", abbrev="e")elementary_charge.set_dimension(charge)elementary_charge.set_scale_factor(1.602176634e-19*coulomb)  # Planck constant# REF: NIST SP 959 (June 2019) planck = Quantity("planck", abbrev="h") planck.set_dimension(action)planck.set_scale_factor(2*pi*hbar)planck.set_scale_factor(6.62607015e-34*joule*second)# Reduced Planck constant# REF: NIST SP 959 (June 2019)hbar = Quantity("hbar", abbrev="hbar")hbar.set_dimension(action)hbar.set_scale_factor(planck / (2 * pi))  # Electronvolt# REF: NIST SP 959 (June 2019) eV = electronvolt = electronvolts = Quantity("electronvolt", abbrev="eV") electronvolt.set_dimension(energy)electronvolt.set_scale_factor(1.60219e-19*joule)electronvolt.set_scale_factor(1.602176634e-19*joule)  # Avogadro number# REF: NIST SP 959 (June 2019) avogadro_number = Quantity("avogadro_number") avogadro_number.set_dimension(One)avogadro_number.set_scale_factor(6.022140857e23)avogadro_number.set_scale_factor(6.02214076e23)  # Avogadro constant avogadro = avogadro_constant = Quantity("avogadro_constant")


avogadro_constant.set_scale_factor(avogadro_number / mol)  # Boltzmann constant# REF: NIST SP 959 (June 2019) boltzmann = boltzmann_constant = Quantity("boltzmann_constant") boltzmann_constant.set_dimension(energy/temperature)boltzmann_constant.set_scale_factor(1.38064852e-23*joule/kelvin)boltzmann_constant.set_scale_factor(1.380649e-23*joule/kelvin)  # Stefan-Boltzmann constant# REF: NIST SP 959 (June 2019) stefan = stefan_boltzmann_constant = Quantity("stefan_boltzmann_constant") stefan_boltzmann_constant.set_dimension(energy*time**-1*length**-2*temperature**-4)stefan_boltzmann_constant.set_scale_factor(5.670367e-8*joule/(s*m**2*kelvin**4))stefan_boltzmann_constant.set_scale_factor(pi**2 * boltzmann_constant**4 / (60 * hbar**3 * speed_of_light ** 2))  # Atomic mass# REF: NIST SP 959 (June 2019) amu = amus = atomic_mass_unit = atomic_mass_constant = Quantity("atomic_mass_constant") atomic_mass_constant.set_dimension(mass)atomic_mass_constant.set_scale_factor(1.660539040e-24*gram)atomic_mass_constant.set_scale_factor(1.66053906660e-24*gram)  # Molar gas constant# REF: NIST SP 959 (June 2019) R = molar_gas_constant = Quantity("molar_gas_constant", abbrev="R") molar_gas_constant.set_dimension(energy/(temperature * amount_of_substance))molar_gas_constant.set_scale_factor(8.3144598*joule/kelvin/mol)molar_gas_constant.set_scale_factor(boltzmann_constant * avogadro_constant)  # Faraday constant faraday_constant = Quantity("faraday_constant") faraday_constant.set_dimension(charge/amount_of_substance)faraday_constant.set_scale_factor(96485.33289*C/mol)faraday_constant.set_scale_factor(elementary_charge * avogadro_constant)  # Josephson constant josephson_constant = Quantity("josephson_constant", abbrev="K_j") josephson_constant.set_dimension(frequency/voltage)josephson_constant.set_scale_factor(483597.8525e9*hertz/V)josephson_constant.set_scale_factor(0.5 * planck / elementary_charge)  # Von Klitzing constant von_klitzing_constant = Quantity("von_klitzing_constant", abbrev="R_k") von_klitzing_constant.set_dimension(voltage/current)von_klitzing_constant.set_scale_factor(25812.8074555*ohm)von_klitzing_constant.set_scale_factor(hbar / elementary_charge ** 2)  # Acceleration due to gravity (on the Earth surface) gee = gees = acceleration_due_to_gravity = Quantity("acceleration_due_to_gravity", abbrev="g")diff --git a/sympy/physics/units/util.py b/sympy/physics/units/util.py-- a/sympy/physics/units/util.py++ b/sympy/physics/units/util.py


>>> from sympy.physics.units import speed_of_light, meter, gram, second, day     >>> from sympy.physics.units import mile, newton, kilogram, atomic_mass_constant     >>> from sympy.physics.units import kilometer, centimeter<ins>    >>> from sympy.physics.units import gravitational_constant, hbar</ins>     >>> from sympy.physics.units import convert_to     >>> convert_to(mile, kilometer)     25146*kilometer/15625


>>> convert_to(3*newton, kilogram*meter/second**2)     3*kilogram*meter/second**2     >>> convert_to(atomic_mass_constant, gram)    1.66053904e-24*gram    1.660539060e-24*gram      Conversion to multiple units:


>>> from sympy.physics.units import gravitational_constant, hbar     >>> convert_to(atomic_mass_constant, [gravitational_constant, speed_of_light, hbar]).n()    7.62950196312651e-20*gravitational_constant**(-0.5)*hbar**0.5*speed_of_light**0.5    7.62963085040767e-20*gravitational_constant**(-0.5)*hbar**0.5*speed_of_light**0.5      """     if not isinstance(target_units, (Iterable, Tuple)):


else:             return self._print(item) <ins>    def parenthesize_super(self, s):        """ Parenthesize s if there is a superscript in s"""        if "^" in s:            return r"\left({}\right)".format(s)        return s    def embed_super(self, s):        """ Embed s in {} if there is a superscript in s"""        if "^" in s:            return "{{{}}}".format(s)        return s</ins>     def doprint(self, expr):         tex = Printer.doprint(self, expr)


if num == 1:                 tex += r"%s %s" % (diff_symbol, self._print(x))             else:                tex += r"%s %s^{%s}" % (diff_symbol, self._print(x), num)                tex += r"%s %s^{%s}" % (diff_symbol,                                        self.parenthesize_super(self._print(x)),                                        num)          if dim == 1:             tex = r"\frac{%s}{%s}" % (diff_symbol, tex)


if isinstance(e.args[0], Implies):             return self._print_Implies(e.args[0], r"\not\Rightarrow")         if (e.args[0].is_Boolean):            return r"\neg (%s)" % self._print(e.args[0])            return r"\neg \left(%s\right)" % self._print(e.args[0])         else:             return r"\neg %s" % self._print(e.args[0])


else:             return r <ins>    def _eval_is_negative(self):        return self.args[0].is_negative    def _eval_is_nonnegative(self):        return self.args[0].is_nonnegative</ins>     def _eval_rewrite_as_ceiling(self, arg, **kwargs):         return -ceiling(-arg)


return S.true      def __le__(self, other):        other = S(other)        if self.args[0].is_real:            if other.is_integer:                return self.args[0] < other + 1            if other.is_number and other.is_real:                return self.args[0] < ceiling(other)         if self.args[0] == other and other.is_real:             return S.true         if other is S.Infinity and self.is_finite:             return S.true         return Le(self, other, evaluate=False)     def __ge__(self, other):        other = S(other)        if self.args[0].is_real:            if other.is_integer:                return self.args[0] >= other            if other.is_number and other.is_real:                return self.args[0] >= ceiling(other)        if self.args[0] == other and other.is_real:            return S.false        if other is S.NegativeInfinity and self.is_finite:            return S.true        return Ge(self, other, evaluate=False)     def __gt__(self, other):        other = S(other)        if self.args[0].is_real:            if other.is_integer:                return self.args[0] >= other + 1            if other.is_number and other.is_real:                return self.args[0] >= ceiling(other)         if self.args[0] == other and other.is_real:             return S.false        if other is S.NegativeInfinity and self.is_finite:            return S.true         return Gt(self, other, evaluate=False)     def __lt__(self, other):        other = S(other)        if self.args[0].is_real:            if other.is_integer:                return self.args[0] < other            if other.is_number and other.is_real:                return self.args[0] < ceiling(other)        if self.args[0] == other and other.is_real:            return S.false        if other is S.Infinity and self.is_finite:            return S.true        return Lt(self, other, evaluate=False)  class ceiling(RoundFunction):     """


def _eval_rewrite_as_frac(self, arg, **kwargs):         return arg + frac(-arg) <ins>    def _eval_is_positive(self):        return self.args[0].is_positive    def _eval_is_nonpositive(self):        return self.args[0].is_nonpositive</ins>     def _eval_Eq(self, other):         if isinstance(self, ceiling):             if (self.rewrite(floor) == other) or \


return S.true      def __lt__(self, other):        other = S(other)        if self.args[0].is_real:            if other.is_integer:                return self.args[0] <= other - 1            if other.is_number and other.is_real:                return self.args[0] <= floor(other)         if self.args[0] == other and other.is_real:             return S.false        if other is S.Infinity and self.is_finite:            return S.true         return Lt(self, other, evaluate=False)     def __gt__(self, other):        other = S(other)        if self.args[0].is_real:            if other.is_integer:                return self.args[0] > other            if other.is_number and other.is_real:                return self.args[0] > floor(other)        if self.args[0] == other and other.is_real:            return S.false        if other is S.NegativeInfinity and self.is_finite:            return S.true        return Gt(self, other, evaluate=False)     def __ge__(self, other):        other = S(other)        if self.args[0].is_real:            if other.is_integer:                return self.args[0] > other - 1            if other.is_number and other.is_real:                return self.args[0] > floor(other)         if self.args[0] == other and other.is_real:             return S.true        if other is S.NegativeInfinity and self.is_real:        if other is S.NegativeInfinity and self.is_finite:             return S.true         return Ge(self, other, evaluate=False)     def __le__(self, other):        other = S(other)        if self.args[0].is_real:            if other.is_integer:                return self.args[0] <= other            if other.is_number and other.is_real:                return self.args[0] <= floor(other)        if self.args[0] == other and other.is_real:            return S.false        if other is S.Infinity and self.is_finite:            return S.true        return Le(self, other, evaluate=False)  class frac(Function):     r"""Represents the fractional part of x


def rad_rationalize(num, den):     """     Rationalize num/den by removing square roots in the denominator;    num and den are sum of terms whose squares are rationals    num and den are sum of terms whose squares are positive rationals.      Examples     ========


def split_surds(expr):     """    split an expression with terms whose squares are rationals    Split an expression with terms whose squares are positive rationals     into a sum of terms whose surds squared have gcd equal to g    and a sum of terms with surds squared prime with g    and a sum of terms with surds squared prime with g.      Examples     ========diff --git a/sympy/simplify/sqrtdenest.py b/sympy/simplify/sqrtdenest.py-- a/sympy/simplify/sqrtdenest.py++ b/sympy/simplify/sqrtdenest.py


res = (p, S.Zero, S.Zero)     elif p.is_Add:         pargs = sorted(p.args, key=default_sort_key)        if all((x**2).is_Rational for x in pargs):        sqargs = [x**2 for x in pargs]        if all(sq.is_Rational and sq.is_positive for sq in sqargs):             r, b, a = split_surds(p)             res = a, b, r             return list(res)


from sympy.combinatorics import Permutation         expr = _sympify(expr)         permutation = Permutation(permutation)        plist = permutation.args[0]        plist = permutation.array_form         if plist == sorted(plist):             return expr         obj = Basic.__new__(cls, expr, permutation)


elif isinstance(expr, (MatrixSymbol, IndexedBase)):         return expr     elif isinstance(expr, CodegenArrayPermuteDims):        if expr.permutation.args[0] == [1, 0]:        if expr.permutation.array_form == [1, 0]:             return _RecognizeMatOp(Transpose, [_recognize_matrix_expression(expr.expr)])         elif isinstance(expr.expr, CodegenArrayTensorProduct):             ranks = expr.expr.subranksdiff --git a/sympy/combinatorics/perm_groups.py b/sympy/combinatorics/perm_groups.py-- a/sympy/combinatorics/perm_groups.py++ b/sympy/combinatorics/perm_groups.py


>>> from sympy.combinatorics import Permutation, PermutationGroup         >>> p = PermutationGroup(Permutation(1, 3), Permutation(1, 2))         >>> p.elements        {(3), (2 3), (3)(1 2), (1 2 3), (1 3 2), (1 3)}        {(1 2 3), (1 3 2), (1 3), (2 3), (3), (3)(1 2)}          """         return set(self._elements)diff --git a/sympy/combinatorics/permutations.py b/sympy/combinatorics/permutations.py-- a/sympy/combinatorics/permutations.py++ b/sympy/combinatorics/permutations.py


import random from collections import defaultdict from sympy.core import Basicfrom sympy.core.basic import Basic, Atom from sympy.core.compatibility import is_sequence, reduce, range, as_int from sympy.matrices import zeros from sympy.polys.polytools import lcm


return Cycle(self)  class Permutation(Basic):class Permutation(Atom):     """     A permutation, alternatively known as an 'arrangement number' or 'ordering'     is an arrangement of the elements of an ordered list into a one-to-one


Permutation([2, 1, 3, 0])          """        p = Basic.__new__(cls, perm)        p = super(Permutation, cls).__new__(cls)         p._array_form = perm         p._size = len(perm)         return pdiff --git a/sympy/printing/pycode.py b/sympy/printing/pycode.py-- a/sympy/printing/pycode.py++ b/sympy/printing/pycode.py


return "%s(%s, %s)" % (             self._module_format("numpy.transpose"),             self._print(expr.expr),            self._print(expr.permutation.args[0]),            self._print(expr.permutation.array_form),         )      def _print_CodegenArrayElementwiseAdd(self, expr):diff --git a/sympy/printing/tensorflow.py b/sympy/printing/tensorflow.py-- a/sympy/printing/tensorflow.py++ b/sympy/printing/tensorflow.py


return "%s(%s, %s)" % (             self._module_format("tensorflow.transpose"),             self._print(expr.expr),            self._print(expr.permutation.args[0]),            self._print(expr.permutation.array_form),         )      def _print_CodegenArrayElementwiseAdd(self, expr):


# manipulate them like non-commutative scalars.                 return cls._from_args(nonmatrices + [mat_class(*matrices).doit(deep=False)]) <ins>        if mat_class == MatAdd:            return mat_class(*matrices).doit(deep=False)</ins>         return mat_class(cls._from_args(nonmatrices), *matrices).doit(deep=False)     return _postprocessor


assumptions, kw_args = _filter_assumptions(kw_args)         if isinstance(label, string_types):            label = Symbol(label)            label = Symbol(label, **assumptions)         elif isinstance(label, Symbol):             assumptions = label._merge(assumptions)            label = Symbol(label.name)         elif isinstance(label, (MatrixBase, NDimArray)):             return label         elif isinstance(label, Iterable):


coords = [simplify(x*factor) for x in self.args]         return Point(coords, evaluate=False) <ins>    def __rmul__(self, factor):        """Multiply a factor by point's coordinates."""        return self.__mul__(factor)</ins>     def __neg__(self):         """Negate the point."""         coords = [-x for x in self.args]


return None  <ins>def refine_sign(expr, assumptions):    """    Handler for sign    Examples    ========    >>> from sympy.assumptions.refine import refine_sign    >>> from sympy import Symbol, Q, sign, im    >>> x = Symbol('x', real = True)    >>> expr = sign(x)    >>> refine_sign(expr, Q.positive(x) & Q.nonzero(x))    1    >>> refine_sign(expr, Q.negative(x) & Q.nonzero(x))    -1    >>> refine_sign(expr, Q.zero(x))    0    >>> y = Symbol('y', imaginary = True)    >>> expr = sign(y)    >>> refine_sign(expr, Q.positive(im(y)))    I    >>> refine_sign(expr, Q.negative(im(y)))    -I    """    arg = expr.args[0]    if ask(Q.zero(arg), assumptions):        return S.Zero    if ask(Q.real(arg)):        if ask(Q.positive(arg), assumptions):            return S.One        if ask(Q.negative(arg), assumptions):            return S.NegativeOne    if ask(Q.imaginary(arg)):        arg_re, arg_im = arg.as_real_imag()        if ask(Q.positive(arg_im), assumptions):            return S.ImaginaryUnit        if ask(Q.negative(arg_im), assumptions):            return -S.ImaginaryUnit    return expr</ins> handlers_dict = {     'Abs': refine_abs,     'Pow': refine_Pow,


'StrictGreaterThan': refine_Relational,     'StrictLessThan': refine_Relational,     're': refine_re,    'im': refine_im    'im': refine_im,    'sign': refine_sign }


facs = factorint(r, limit=limit, use_trial=use_trial,                                      use_rho=use_rho, use_pm1=use_pm1,                                      verbose=verbose)                    factors.update(facs)                    for k, v in facs.items():                        factors[k] = factors.get(k, 0) + v                 raise StopIteration              # ...see if factorization can be terminated


else:             return self.func(arg) <ins>    def _eval_is_real(self):        arg = self.args[0]        if arg.is_real:            return True        # if `im` is of the form n*pi        # else, check if it is a number        re, im = arg.as_real_imag()        return (im%pi).is_zero</ins>     def _eval_is_extended_real(self):         if self.args[0].is_extended_real:             return True


def _eval_is_finite(self):         arg = self.args[0]        if arg.is_imaginary:            return True        return arg.is_finite      def _eval_is_zero(self):         arg = self.args[0]


else:             return self.func(arg)     def _eval_is_real(self):        arg = self.args[0]        # `cosh(x)` is real for real OR purely imaginary `x`        if arg.is_real or arg.is_imaginary:            return True        # cosh(a+ib) = cos(b)*cosh(a) + i*sin(b)*sinh(a)        # the imaginary part can be an expression like n*pi        # if not, check if the imaginary part is a number        re, im = arg.as_real_imag()        return (im%pi).is_zero     def _eval_is_positive(self):         if self.args[0].is_extended_real:             return True      def _eval_is_finite(self):         arg = self.args[0]        if arg.is_imaginary:            return True        return arg.is_finite   class tanh(HyperbolicFunction):


else:             return self.func(arg) <ins>    def _eval_is_real(self):        from sympy import cos, sinh        arg = self.args[0]        if arg.is_real:            return True        re, im = arg.as_real_imag()        # if denom = 0, tanh(arg) = zoo        if re == 0 and im % pi == pi/2:            return None        # check if im is of the form n*pi/2 to make sin(2*im) = 0        # if not, im could be a number, return False in that case        return (im % (pi/2)).is_zero</ins>     def _eval_is_extended_real(self):         if self.args[0].is_extended_real:             return True


return self.args[0].is_negative      def _eval_is_finite(self):        from sympy import sinh, cos         arg = self.args[0]        re, im = arg.as_real_imag()        denom = cos(im)**2 + sinh(re)**2        if denom == 0:            return False        elif denom.is_number:            return True         if arg.is_extended_real:             return True


from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.integers import floor <ins>from sympy import pi, Eqfrom sympy.logic import Or, Andfrom sympy.core.logic import fuzzy_or, fuzzy_and, fuzzy_bool</ins>  def _rewrite_hyperbolics_as_exp(expr):     expr = sympify(expr)