Commits

Volker Braun committed 0fd8cd5

update to sage-5.10.beta3

Comments (0)

Files changed (11)

+trac_13213-quadratic_field_comparison.patch
+trac_14587_m2.patch
+trac_14587_doctests.patch
+trac_14014_libgap_cyclotomic_matrix.patch
+trac_14014_deletions.patch
+trac_14014_parents_for_matrix_groups.patch
+trac_14014_parents_group_dependents.patch
+trac_14014_iterator.patch
+trac_14039_doctest_fixes.patch
+trac_14578-add-face.patch
 trac_13736-content-take2.patch
 trac_13736-unit_primpart.patch
 trac_14232_ppl_doctest_fixes.patch
+trac_10508_doctest.rebased.patch
+trac_10508_update_atlas_docs.rebased.patch
 trac_14523_improve_attach.patch
 trac_13084_ppl_lattice_polygon.patch
 trac_13084_toric_weierstrass.patch
 trac_13458_toric_Weierstrass_covering.patch
 ppl_reflexive_polytope.patch
 debug_memory_leak.patch
-trac_14014_libgap_cyclotomic_matrix.patch
-trac_14014_deletions.patch
-trac_14014_parents_for_matrix_groups.patch
-trac_14014_parents_group_dependents.patch
-trac_14014_iterator.patch
-trac_14039_doctest_fixes.patch
 trac_14469_repr_graphics.patch
-trac_14375_ansi_escapes_indication.2.patch
 trac_12892_orbit_closure_morphism.patch
 trac_12892_toric_morphism_fibers.patch
 trac_12892_toric_morphism_divisors.patch

trac_10508_doctest.rebased.patch

+# HG changeset patch
+# User Jeroen Demeyer <jdemeyer@cage.ugent.be>
+# Date 1342098436 -7200
+# Node ID b7822096e3e2d5b7011ae77470d297febc3c01a8
+# Parent  96b55269c018aa8ebeed0672671a31e5ab7e9267
+Increase the tolerance for a test depending on ATLAS
+
+diff --git a/sage/rings/polynomial/polynomial_element.pyx b/sage/rings/polynomial/polynomial_element.pyx
+--- a/sage/rings/polynomial/polynomial_element.pyx
++++ b/sage/rings/polynomial/polynomial_element.pyx
+@@ -1037,11 +1037,12 @@
+         polynomial 1 and have extra terms with coefficients close to zero. ::
+         
+             sage: R.<x> = RDF[]
++            sage: epsilon = RDF(1).ulp()*50   # Allow an error of up to 50 ulp
+             sage: f = inverse_mod(x^2 + 1, x^5 + x + 1); f
+             0.4*x^4 - 0.2*x^3 - 0.4*x^2 + 0.2*x + 0.8
+             sage: poly = f * (x^2 + 1) % (x^5 + x + 1)
+             sage: # Remove noisy zero terms:
+-            sage: parent(poly)([ 0.0 if abs(c)<=1e-14 else c for c in poly.coeffs() ])
++            sage: parent(poly)([ 0.0 if abs(c)<=epsilon else c for c in poly.coeffs() ])
+             1.0
+             sage: f = inverse_mod(x^3 - x + 1, x - 2); f
+             0.142857142857
+@@ -1051,7 +1052,7 @@
+             -0.0319636125...*x^3 - 0.0383269759...*x^2 - 0.0463050900...*x + 0.346479687...
+             sage: poly = f*g % m
+             sage: # Remove noisy zero terms:
+-            sage: parent(poly)([ 0.0 if abs(c)<=1e-14 else c for c in poly.coeffs() ])
++            sage: parent(poly)([ 0.0 if abs(c)<=epsilon else c for c in poly.coeffs() ])
+             1.0
+ 
+         ALGORITHM: Solve the system as + mt = 1, returning s as the inverse

trac_10508_update_atlas_docs.rebased.patch

+# HG changeset patch
+# User Jean-Pierre Flori <jean-pierre.flori@ssi.gouv.fr>
+# Date 1367848249 -3600
+# Node ID bf2ce48989e67501125c0d8a2d51beca43d2ea09
+# Parent  b25479d0a27ab01d59063b4a3406b030e0411717
+Update the installation guide for ATLAS 3.10.0
+
+diff --git a/doc/en/installation/source.rst b/doc/en/installation/source.rst
+--- a/doc/en/installation/source.rst
++++ b/doc/en/installation/source.rst
+@@ -983,16 +983,20 @@
+   systems with CPU throttling or if you want to distribute the binaries.
+   Available architectures are
+ 
+-    ``POWER3``, ``POWER4``, ``POWER5``, ``PPCG4``, ``PPCG5``, ``P5``,
++    ``POWER3``, ``POWER4``, ``POWER5``, ``PPCG4``, ``PPCG5``,
++    ``POWER6``, ``POWER7``, ``IBMz9``, ``IBMz10``, ``IBMz196``,
++    ``x86x87``, ``x86SSE1``, ``x86SSE2``, ``x86SSE3``, ``P5``,
+     ``P5MMX``, ``PPRO``, ``PII``, ``PIII``, ``PM``, ``CoreSolo``,
+-    ``CoreDuo``, ``Core2Solo``, ``Core2``, ``Corei7``, ``P4``,
+-    ``P4E``, ``Efficeon``, ``K7``, ``HAMMER``, ``AMD64K10h``,
+-    ``IA64Itan``, ``IA64Itan2``, ``USI``, ``USII``, ``USIII``,
+-    ``USIV``, ``UnknownUS``, ``MIPSR1xK``, ``MIPSICE9``
++    ``CoreDuo``, ``Core2Solo``, ``Core2``, ``Corei1``, ``Corei2``,
++    ``Atom``, ``P4``, ``P4E``, ``Efficeon``, ``K7``, ``HAMMER``,
++    ``AMD64K10h``, ``AMDDOZER``, ``UNKNOWNx86``, ``IA64Itan``,
++    ``IA64Itan2``, ``USI``, ``USII``, ``USIII``, ``USIV``, ``UST2``,
++    ``UnknownUS``, ``MIPSR1xK``, ``MIPSICE9``, ``ARMv7``.
+ 
+   and instruction set extensions are
+ 
+-    ``AltiVec``, ``SSE3``, ``SSE2``, ``SSE1``, ``3DNow``.
++    ``VSX``, ``AltiVec``, ``AVXMAC``, ``AVXFMA4``, ``AVX``, ``SSE3``,
++    ``SSE2``, ``SSE1``, ``3DNow``, ``NEON``.
+ 
+   In addition, you can also set
+ 
+@@ -1004,7 +1008,7 @@
+ 
+   For example,
+ 
+-    ``SAGE_ATLAS_ARCH=Corei7,SSE3,SSE2,SSE1``
++    ``SAGE_ATLAS_ARCH=Corei2,AVX,SSE3,SSE2,SSE1``
+ 
+   would be appropriate for a Core i7 CPU.
+ 
+@@ -1013,8 +1017,8 @@
+   own version of ATLAS, set this variable to be the directory containing your
+   ATLAS installation.
+   It should contain the files :file:`libatlas`, :file:`liblapack`,
+-  :file:`libcblas`, and :file:`libf77blas` with extensions ``.a``, ``.so``, or
+-  ``.dylib``.
++  :file:`libcblas`, :file:`libptcblas`, :file:`libf77blas`, and
++  :file:`libptf77blas`, with extensions ``.a``, ``.so``, or ``.dylib``.
+   For backward compatibility, the libraries may also be in the subdirectory
+   :file:`SAGE_ATLAS_LIB/lib/`.
+ 
+@@ -1254,18 +1258,42 @@
+ ATLAS
+ ~~~~~
+ 
+-Sometimes the ATLAS spkg can fail to build.
+-Some things to check for:
++Usually Sage will build ATLAS with architectural defaults that are not tuned
++to your particular CPU.
++In particular, if your CPU has powersaving enabled then no accurate timings
++can be made to tune the ATLAS build for your hardware.
++If BLAS performance is critical for you, you must recompile ATLAS after
++installing Sage either with architecture settings that match your hardware,
++or run through ATLAS' automatic tuning process where timings of different
++implementations are compared and the best choice used to build a custom ATLAS
++library.
++To do so, you have to
+ 
+-- Make sure that CPU throttling mode (i.e. power-saving mode) is turned off
+-  when building ATLAS.
++- Leave the computer idle while you are reinstalling ATLAS.
++  Most of ATLAS will intentionally only compile/run on a single core.
++  Accurate timings of cache edges require that the CPU is otherwise idle.
+ 
+-- The ATLAS build can also fail if the system load is too high, and in
+-  particular this has been known to happen when building with
+-  ``MAKE='make -jNUM'`` with ``NUM`` large.
+-  If this happens, just try running ``make`` again.
+-  If ``make`` fails after five or six attempts, report your problem to the
+-  sage-devel mailing list at http://groups.google.com/group/sage-devel.
++- Make sure that CPU powersaving mode (that is, anything but the
++  ``performance`` CPU scaling governor in Linux) is turned off when building
++  ATLAS.
++  This requires administrator privileges.
++
++- If your architecture is listed in :envvar:`SAGE_ATLAS_ARCH`, you should set
++  it as it can help ATLAS in narrowing down the timing search.
++
++To help you disable CPU power saving, Sage includes an ``atlas-config`` script
++that will turn off CPU powersave and rebuild ATLAS.
++The script will call ``sudo`` to gain the necessary rights, which may prompt
++you for your password. For example::
++
++    atlas-config
++
++will run through the full automated tuning, and::
++
++    SAGE_ATLAS_ARCH=Corei2,AVX,SSE3,SSE2,SSE1 atlas-config
++
++would be appropriate if you have a Core i3/5/7 processor with AVX support.
++
+ 
+ zn_poly
+ ~~~~~~~

trac_13213-quadratic_field_comparison.patch

+# HG changeset patch
+# User Vincent Delecroix <20100.delecroix at gmail.com>
+# Date 1342612563 -32400
+# Node ID 837b06a5a0ecf085e1d6848b4ce2ac04808936f9
+# Parent  75a1095ab5b4f6bcb7c8467bb37256d4b1841ae3
+trac 13213
+Comparisons in quadratic number field
+
+This patch implements comparisons of elements of quadratic number fields
+compatible with their (real or complex) embedding. The main modification
+is in sage/rings/number_field/number_field_element_quadratic.pyx but it
+affects many tests as it modifies some output order.
+
+diff --git a/doc/de/tutorial/tour_advanced.rst b/doc/de/tutorial/tour_advanced.rst
+--- a/doc/de/tutorial/tour_advanced.rst
++++ b/doc/de/tutorial/tour_advanced.rst
+@@ -481,7 +481,7 @@
+     Modular Symbols space of dimension 4 and level 13, weight 2, character 
+     [zeta6], sign 0, over Cyclotomic Field of order 6 and degree 2
+     sage: M.T(2).charpoly('x').factor()
+-    (x - 2*zeta6 - 1) * (x - zeta6 - 2) * (x + zeta6 + 1)^2
++    (x - zeta6 - 2) * (x - 2*zeta6 - 1) * (x + zeta6 + 1)^2
+     sage: S = M.cuspidal_submodule(); S
+     Modular Symbols subspace of dimension 2 of Modular Symbols space of 
+     dimension 4 and level 13, weight 2, character [zeta6], sign 0, over 
+diff --git a/doc/en/tutorial/tour_advanced.rst b/doc/en/tutorial/tour_advanced.rst
+--- a/doc/en/tutorial/tour_advanced.rst
++++ b/doc/en/tutorial/tour_advanced.rst
+@@ -478,7 +478,7 @@
+     Modular Symbols space of dimension 4 and level 13, weight 2, character 
+     [zeta6], sign 0, over Cyclotomic Field of order 6 and degree 2
+     sage: M.T(2).charpoly('x').factor()
+-    (x - 2*zeta6 - 1) * (x - zeta6 - 2) * (x + zeta6 + 1)^2
++    (x - zeta6 - 2) * (x - 2*zeta6 - 1) * (x + zeta6 + 1)^2
+     sage: S = M.cuspidal_submodule(); S
+     Modular Symbols subspace of dimension 2 of Modular Symbols space of 
+     dimension 4 and level 13, weight 2, character [zeta6], sign 0, over 
+diff --git a/doc/fr/tutorial/tour_advanced.rst b/doc/fr/tutorial/tour_advanced.rst
+--- a/doc/fr/tutorial/tour_advanced.rst
++++ b/doc/fr/tutorial/tour_advanced.rst
+@@ -478,7 +478,7 @@
+     Modular Symbols space of dimension 4 and level 13, weight 2, character 
+     [zeta6], sign 0, over Cyclotomic Field of order 6 and degree 2
+     sage: M.T(2).charpoly('x').factor()
+-    (x - 2*zeta6 - 1) * (x - zeta6 - 2) * (x + zeta6 + 1)^2
++    (x - zeta6 - 2) * (x - 2*zeta6 - 1) * (x + zeta6 + 1)^2
+     sage: S = M.cuspidal_submodule(); S
+     Modular Symbols subspace of dimension 2 of Modular Symbols space of 
+     dimension 4 and level 13, weight 2, character [zeta6], sign 0, over 
+diff --git a/doc/ru/tutorial/tour_advanced.rst b/doc/ru/tutorial/tour_advanced.rst
+--- a/doc/ru/tutorial/tour_advanced.rst
++++ b/doc/ru/tutorial/tour_advanced.rst
+@@ -439,7 +439,7 @@
+     Modular Symbols space of dimension 4 and level 13, weight 2, character 
+     [zeta6], sign 0, over Cyclotomic Field of order 6 and degree 2
+     sage: M.T(2).charpoly('x').factor()
+-    (x - 2*zeta6 - 1) * (x - zeta6 - 2) * (x + zeta6 + 1)^2
++    (x - zeta6 - 2) * (x - 2*zeta6 - 1) * (x + zeta6 + 1)^2
+     sage: S = M.cuspidal_submodule(); S
+     Modular Symbols subspace of dimension 2 of Modular Symbols space of 
+     dimension 4 and level 13, weight 2, character [zeta6], sign 0, over 
+diff --git a/sage/calculus/calculus.py b/sage/calculus/calculus.py
+--- a/sage/calculus/calculus.py
++++ b/sage/calculus/calculus.py
+@@ -379,7 +379,7 @@
+ 
+     sage: k = var("k")
+     sage: sum(1/(1+k^2), k, -oo, oo)
+-    -1/2*I*psi(I + 1) - 1/2*I*psi(I) + 1/2*I*psi(-I) + 1/2*I*psi(-I + 1)
++    1/2*I*psi(-I) - 1/2*I*psi(I) + 1/2*I*psi(-I + 1) - 1/2*I*psi(I + 1)
+ 
+ Ensure that ticket #8624 is fixed::
+ 
+diff --git a/sage/calculus/tests.py b/sage/calculus/tests.py
+--- a/sage/calculus/tests.py
++++ b/sage/calculus/tests.py
+@@ -109,7 +109,7 @@
+     sage: integrate(exp(1-x^2),x)
+     1/2*sqrt(pi)*e*erf(x)
+     sage: integrate(sin(x^2),x)
+-    1/8*((I + 1)*sqrt(2)*erf((1/2*I + 1/2)*sqrt(2)*x) + (I - 1)*sqrt(2)*erf((1/2*I - 1/2)*sqrt(2)*x))*sqrt(pi)
++    1/8*((I - 1)*sqrt(2)*erf((1/2*I - 1/2)*sqrt(2)*x) + (I + 1)*sqrt(2)*erf((1/2*I + 1/2)*sqrt(2)*x))*sqrt(pi)
+ 
+     sage: integrate((1-x^2)^n,x)
+     integrate((-x^2 + 1)^n, x)
+diff --git a/sage/functions/other.py b/sage/functions/other.py
+--- a/sage/functions/other.py
++++ b/sage/functions/other.py
+@@ -1522,7 +1522,7 @@
+         The result is symbolic if exact input is given::
+ 
+             sage: beta(2,1+5*I)
+-            beta(2, 5*I + 1)
++            beta(5*I + 1, 2)
+             sage: beta(2, 2.)
+             0.166666666666667
+             sage: beta(I, 2.)
+diff --git a/sage/modular/modform/constructor.py b/sage/modular/modform/constructor.py
+--- a/sage/modular/modform/constructor.py
++++ b/sage/modular/modform/constructor.py
+@@ -214,19 +214,19 @@
+         sage: f = M.T(2).charpoly('x'); f
+         x^3 + (-2*zeta6 - 2)*x^2 - 2*zeta6*x + 14*zeta6 - 7
+         sage: f.factor()
+-        (x - 2*zeta6 - 1) * (x - zeta6 - 2) * (x + zeta6 + 1)
+-    
+-    We can also create spaces corresponding to the groups `\Gamma_H(N)` intermediate 
++        (x - zeta6 - 2) * (x - 2*zeta6 - 1) * (x + zeta6 + 1)
++
++    We can also create spaces corresponding to the groups `\Gamma_H(N)` intermediate
+     between `\Gamma_0(N)` and `\Gamma_1(N)`::
+-    
++
+         sage: G = GammaH(30, [11])
+         sage: M = ModularForms(G, 2); M
+         Modular Forms space of dimension 20 for Congruence Subgroup Gamma_H(30) with H generated by [11] of weight 2 over Rational Field
+         sage: M.T(7).charpoly().factor()  # long time (7s on sage.math, 2011)
+         (x + 4) * x^2 * (x - 6)^4 * (x + 6)^4 * (x - 8)^7 * (x^2 + 4)
+-       
++
+     More examples of spaces with character::
+-    
++
+         sage: e = DirichletGroup(5, RationalField()).gen(); e
+         Dirichlet character modulo 5 of conductor 5 mapping 2 |--> -1
+ 
+@@ -257,13 +257,13 @@
+         sage: M = ModularForms(Gamma1(11), 1); M
+         Modular Forms space of dimension 5 for Congruence Subgroup Gamma1(11) of weight 1 over Rational Field
+         sage: M.basis()
+-        [                                                                                           
+-        1 + 22*q^5 + O(q^6),                                                                        
+-        q + 4*q^5 + O(q^6),                                                                         
+-        q^2 - 4*q^5 + O(q^6),                                                                       
+-        q^3 - 5*q^5 + O(q^6),                                                                       
+-        q^4 - 3*q^5 + O(q^6)                                                                        
+-        ]                                                                                           
++        [
++        1 + 22*q^5 + O(q^6),
++        q + 4*q^5 + O(q^6),
++        q^2 - 4*q^5 + O(q^6),
++        q^3 - 5*q^5 + O(q^6),
++        q^4 - 3*q^5 + O(q^6)
++        ]
+         sage: M.cuspidal_subspace().basis()
+         [
+         ]
+diff --git a/sage/modular/modform/eisenstein_submodule.py b/sage/modular/modform/eisenstein_submodule.py
+--- a/sage/modular/modform/eisenstein_submodule.py
++++ b/sage/modular/modform/eisenstein_submodule.py
+@@ -543,9 +543,9 @@
+         q + (-zeta6 - 1)*q^2 + (zeta6 + 2)*q^4 + (zeta6 - 5)*q^5 + O(q^6)
+         ]
+         sage: M.eisenstein_subspace().T(2).matrix().fcp()
+-        (x + zeta3 + 2) * (x + 2*zeta3 + 1) * (x - 2*zeta3 - 1)^2 * (x - zeta3 - 2)^2
++        (x + 2*zeta3 + 1) * (x + zeta3 + 2) * (x - zeta3 - 2)^2 * (x - 2*zeta3 - 1)^2
+         sage: ModularSymbols(e,2).eisenstein_subspace().T(2).matrix().fcp()
+-        (x + zeta3 + 2) * (x + 2*zeta3 + 1) * (x - 2*zeta3 - 1)^2 * (x - zeta3 - 2)^2
++        (x + 2*zeta3 + 1) * (x + zeta3 + 2) * (x - zeta3 - 2)^2 * (x - 2*zeta3 - 1)^2
+ 
+         sage: M.basis()
+         [
+diff --git a/sage/modular/modsym/modsym.py b/sage/modular/modsym/modsym.py
+--- a/sage/modular/modsym/modsym.py
++++ b/sage/modular/modsym/modsym.py
+@@ -250,35 +250,35 @@
+         sage: f = M.T(2).charpoly('x'); f
+         x^4 + (-zeta6 - 1)*x^3 - 8*zeta6*x^2 + (10*zeta6 - 5)*x + 21*zeta6 - 21
+         sage: f.factor()
+-        (x - 2*zeta6 - 1) * (x - zeta6 - 2) * (x + zeta6 + 1)^2
+-   
++        (x - zeta6 - 2) * (x - 2*zeta6 - 1) * (x + zeta6 + 1)^2
++
+     We create a space with character over a larger base ring than the values of the character::
+ 
+         sage: ModularSymbols(e, 2, base_ring = CyclotomicField(24))
+         Modular Symbols space of dimension 4 and level 13, weight 2, character [zeta24^4], sign 0, over Cyclotomic Field of order 24 and degree 8
+ 
+     More examples of spaces with character::
+-    
++
+         sage: e = DirichletGroup(5, RationalField()).gen(); e
+         Dirichlet character modulo 5 of conductor 5 mapping 2 |--> -1
+ 
+         sage: m = ModularSymbols(e, 2); m
+         Modular Symbols space of dimension 2 and level 5, weight 2, character [-1], sign 0, over Rational Field
+-    
++
+     ::
+-    
++
+         sage: m.T(2).charpoly('x')
+         x^2 - 1
+         sage: m = ModularSymbols(e, 6); m.dimension()
+         6
+         sage: m.T(2).charpoly('x')
+         x^6 - 873*x^4 - 82632*x^2 - 1860496
+-    
++
+     We create a space of modular symbols with nontrivial character in
+     characteristic 2.
+-    
++
+     ::
+-    
++
+         sage: G = DirichletGroup(13,GF(4,'a')); G
+         Group of Dirichlet characters of modulus 13 over Finite Field in a of size 2^2
+         sage: e = G.list()[2]; e
+diff --git a/sage/rings/arith.py b/sage/rings/arith.py
+--- a/sage/rings/arith.py
++++ b/sage/rings/arith.py
+@@ -2418,30 +2418,30 @@
+         -1
+         sage: factor(2^(2^7)+1)
+         59649589127497217 * 5704689200685129054721
+-    
+-    Sage calls PARI's factor, which has proof False by default. 
++
++    Sage calls PARI's factor, which has proof False by default.
+     Sage has a global proof flag, set to True by default (see
+-    :mod:`sage.structure.proof.proof`, or proof.[tab]). To override 
++    :mod:`sage.structure.proof.proof`, or proof.[tab]). To override
+     the default, call this function with proof=False.
+-    
++
+     ::
+-    
++
+         sage: factor(3^89-1, proof=False)
+         2 * 179 * 1611479891519807 * 5042939439565996049162197
+-    
++
+     ::
+-    
++
+         sage: factor(2^197 + 1)  # long time (2s)
+         3 * 197002597249 * 1348959352853811313 * 251951573867253012259144010843
+-    
++
+     Any object which has a factor method can be factored like this::
+ 
+         sage: K.<i> = QuadraticField(-1)
+         sage: factor(122 - 454*i)
+-        (-1) * (-3*i - 2) * (-i - 4) * (i + 1)^3 * (-i - 2)^3
++        (-1) * (-i - 4) * (-3*i - 2) * (-i - 2)^3 * (i + 1)^3
+ 
+     To access the data in a factorization::
+-    
++
+         sage: f = factor(420); f
+         2^2 * 3 * 5 * 7
+         sage: [x for x in f]
+diff --git a/sage/rings/number_field/number_field.py b/sage/rings/number_field/number_field.py
+--- a/sage/rings/number_field/number_field.py
++++ b/sage/rings/number_field/number_field.py
+@@ -7671,6 +7671,13 @@
+             self.__zeta_order = n
+         ## quadratic number fields require this:
+         if f.degree() == 2:
++            # define a boolean flag as for NumberField_quadratic to know, which
++            # square root we choose (True means no embedding or positive
++            # imaginary value).
++            # Note that the test is done with NumberFieldElement and not with
++            # NumberFieldElement_quadratic which requires somehow this flag.
++            self._standard_embedding = not CDF.has_coerce_map_from(self) or CDF(self.gen()).imag() > 0
++
+             self._element_class = number_field_element_quadratic.NumberFieldElement_quadratic
+             if n == 4:
+                 self._D = ZZ(-1)
+@@ -8855,6 +8862,7 @@
+         NumberField_absolute.__init__(self, polynomial, name=name, check=check,
+                                       embedding=embedding, latex_name=latex_name,
+                                       assume_disc_small=assume_disc_small, maximize_at_primes=maximize_at_primes)
++        self._standard_embedding = True
+         self._element_class = number_field_element_quadratic.NumberFieldElement_quadratic
+         c, b, a = [rational.Rational(t) for t in self.defining_polynomial().list()]
+         # set the generator
+@@ -8864,17 +8872,10 @@
+         parts = -b/(2*a), (Dpoly/D).sqrt()/(2*a)
+         self._NumberField_generic__gen = self._element_class(self, parts)
+ 
+-        # NumberField_absolute.__init__(...) set _zero_element and
+-        # _one_element to NumberFieldElement_absolute values, which is
+-        # wrong (and dangerous; such elements can actually be used to
+-        # crash Sage: see #5316).  Overwrite them with correct values.
+-        self._zero_element = self(0)
+-        self._one_element =  self(1)
+-
++        # we must set the flag _standard_embedding *before* any element creation
++        # Note that in the following code, no element is built.
+         emb = self.coerce_embedding()
+-        if emb is None:
+-            self._standard_embedding = True
+-        else:
++        if emb is not None:
+             rootD = number_field_element_quadratic.NumberFieldElement_quadratic(self, (QQ(0),QQ(1)))
+             if D > 0:
+                 from sage.rings.real_double import RDF
+@@ -8883,6 +8884,19 @@
+                 from sage.rings.complex_double import CDF
+                 self._standard_embedding = CDF.has_coerce_map_from(self) and CDF(rootD).imag() > 0
+ 
++        # we reset _NumberField_generic__gen has the flag standard_embedding
++        # might be modified
++        self._NumberField_generic__gen = self._element_class(self, parts)
++
++
++        # NumberField_absolute.__init__(...) set _zero_element and
++        # _one_element to NumberFieldElement_absolute values, which is
++        # wrong (and dangerous; such elements can actually be used to
++        # crash Sage: see #5316).  Overwrite them with correct values.
++        self._zero_element = self(0)
++        self._one_element =  self(1)
++
++
+     def _coerce_map_from_(self, K):
+         """
+         EXAMPLES::
+diff --git a/sage/rings/number_field/number_field_element.pyx b/sage/rings/number_field/number_field_element.pyx
+--- a/sage/rings/number_field/number_field_element.pyx
++++ b/sage/rings/number_field/number_field_element.pyx
+@@ -1411,7 +1411,7 @@
+         
+             sage: K.<a> = NumberField(x^2-10)
+             sage: factor(169*a + 531)
+-            (-6*a - 19) * (-2*a + 9) * (-3*a - 1)
++            (-6*a - 19) * (-3*a - 1) * (-2*a + 9)
+             sage: factor(K(3))
+             Traceback (most recent call last):
+             ...
+diff --git a/sage/rings/number_field/number_field_element_quadratic.pxd b/sage/rings/number_field/number_field_element_quadratic.pxd
+--- a/sage/rings/number_field/number_field_element_quadratic.pxd
++++ b/sage/rings/number_field/number_field_element_quadratic.pxd
+@@ -11,13 +11,15 @@
+ from number_field_element cimport NumberFieldElement, NumberFieldElement_absolute
+ 
+ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute):
+-    # (a + b sqrt(D)) / denom 
++    # (a + b sqrt(D)) / denom
+     cdef mpz_t a, b, denom
+     cdef Integer D
++    cdef bint standard_embedding
+     cdef NumberFieldElement conjugate_c(self)
+     cdef bint is_sqrt_disc(self)
+ 
+     cdef int _randomize(self, num_bound, den_bound, distribution) except -1
+ 
++
+ cdef class OrderElement_quadratic(NumberFieldElement_quadratic):
+     pass
+diff --git a/sage/rings/number_field/number_field_element_quadratic.pyx b/sage/rings/number_field/number_field_element_quadratic.pyx
+--- a/sage/rings/number_field/number_field_element_quadratic.pyx
++++ b/sage/rings/number_field/number_field_element_quadratic.pyx
+@@ -9,12 +9,12 @@
+ - Robert Bradshaw (2007-09): Initial version
+ - David Harvey (2007-10): fix up a few bugs, polish around the edges
+ - David Loeffler (2009-05): add more documentation and tests
++- Vincent Delecroix (2012-07): comparisons for quadratic number fields (#13213)
+ 
+ TODO:
+ 
+     The ``_new()`` method should be overridden in this class to copy the ``D``
+-    attribute
+-
++    and ``standard_embedding`` attributes
+ """
+ #*****************************************************************************
+ #     Copyright (C) 2007 Robert Bradshaw <robertwb@math.washington.edu>
+@@ -31,12 +31,15 @@
+ #                  http://www.gnu.org/licenses/
+ #*****************************************************************************
+ 
+-include '../../ext/interrupt.pxi'
++include "../../ext/interrupt.pxi"
+ include "../../ext/stdsage.pxi"
+-    
+-cdef object QQ, ZZ
++
++from sage.structure.element cimport Element
++
++from sage.rings.integer_ring import ZZ
+ from sage.rings.rational_field import QQ
+-from sage.rings.integer_ring import ZZ
++from sage.rings.real_double import RDF
++from sage.rings.complex_double import CDF
+ from sage.categories.morphism cimport Morphism
+ from sage.rings.number_field.number_field_element import _inverse_mod_generic
+ 
+@@ -82,7 +85,6 @@
+     return cls(parent, (a, b, denom))
+ 
+ 
+-
+ cdef class NumberFieldElement_quadratic(NumberFieldElement_absolute):
+     r"""
+     A NumberFieldElement_quadratic object gives an efficient representation of
+@@ -209,10 +211,27 @@
+                 mpz_set_ui(self.denom, 1)
+             self._reduce_c_()
+ 
++        # set the attribute standard embedding which is used in the method
++        # __cmp__
++        try:
++            self.standard_embedding = parent._standard_embedding
++        except AttributeError:
++            emb = parent.coerce_embedding()
++            if emb is None:
++                self.standard_embedding = True
++                try:
++                    parent._standard_embedding = True
++                except AttributeError:
++                    pass
++            else:
++                raise ValueError("A parent of NumberFieldElement_quadratic with "
++                      "a canonical embedding should have an attribute "
++                      "_standard_embedding (used for comparisons of elements)")
++
+     cdef _new(self):
+         """
+-        Quickly creates a new initialized NumberFieldElement with the same
+-        parent as self.
++        Quickly creates a new initialized NumberFieldElement_quadratic with the
++        same parent as self.
+ 
+         EXAMPLE::
+ 
+@@ -223,6 +242,7 @@
+         cdef NumberFieldElement_quadratic x
+         x = <NumberFieldElement_quadratic>PY_NEW_SAME_TYPE(self)
+         x._parent = self._parent
++        x.standard_embedding = self.standard_embedding
+         x.D = self.D
+         return x
+ 
+@@ -564,8 +584,323 @@
+             1
+         """
+         return mpz_cmp_ui(self.denom, 1)==0 and mpz_cmp_ui(self.a, 0)==0 and mpz_cmp_ui(self.b, 1)==0
+-                
+-                
++
++#########################################################
++# Comparisons
++#########################################################
++
++    def sign(self):
++        r"""
++        Returns the sign of self (0 if zero, +1 if positive and -1 if negative).
++
++        EXAMPLES::
++
++            sage: K.<sqrt2> = QuadraticField(2, name='sqrt2')
++            sage: K(0).sign()
++            0
++            sage: sqrt2.sign()
++            1
++            sage: (sqrt2+1).sign()
++            1
++            sage: (sqrt2-1).sign()
++            1
++            sage: (sqrt2-2).sign()
++            -1
++            sage: (-sqrt2).sign()
++            -1
++            sage: (-sqrt2+1).sign()
++            -1
++            sage: (-sqrt2+2).sign()
++            1
++
++            sage: K.<a> = QuadraticField(2, embedding=-1.4142)
++            sage: K(0).sign()
++            0
++            sage: a.sign()
++            -1
++            sage: (a+1).sign()
++            -1
++            sage: (a+2).sign()
++            1
++            sage: (a-1).sign()
++            -1
++            sage: (-a).sign()
++            1
++            sage: (-a-1).sign()
++            1
++            sage: (-a-2).sign()
++            -1
++
++            sage: K.<b> = NumberField(x^2 + 2*x + 7, 'b', embedding=CC(-1,-sqrt(6)))
++            sage: b.sign()
++            Traceback (most recent call last):
++            ...
++            ValueError: a complex number has no sign!
++            sage: K(1).sign()
++            1
++            sage: K(0).sign()
++            0
++            sage: K(-2/3).sign()
++            -1
++        """
++        cdef mpz_t i, j
++        cdef int s = 1, test
++
++        if mpz_sgn(self.b) == 0:
++            return mpz_sgn(self.a)
++
++        if mpz_sgn(self.D.value) == -1:
++            raise ValueError("a complex number has no sign!")
++
++        if not self.standard_embedding:
++            s = -1
++
++        if mpz_sgn(self.a) == 0:
++            return s*mpz_sgn(self.b)
++
++        if mpz_sgn(self.a) == 1:
++            if mpz_sgn(self.b) == s:
++                return 1
++
++        elif mpz_sgn(self.b) == -s:
++            return -1
++
++        mpz_init_set(i,self.a)
++        mpz_mul(i,i,i)
++        mpz_init_set(j,self.b)
++        mpz_mul(j,j,j)
++        mpz_mul(j,j,self.D.value)
++        test = mpz_cmp(i,j)
++        mpz_clear(i)
++        mpz_clear(j)
++        if mpz_sgn(self.a) == 1 and mpz_sgn(self.b) == -s:
++            return test
++        return -test
++
++    def __richcmp__(left, right, int op):
++        r"""
++        Note: we may implement a more direct way of comparison for integer,
++        float and quadratic numbers input (ie avoiding coercion).
++
++        TESTS::
++
++            sage: K.<i> = QuadraticField(-1)
++            sage: sorted([5*i+1, 2, 3*i+1, 2-i])
++            [3*i + 1, 5*i + 1, -i + 2, 2]
++        """
++        return (<Element>left)._richcmp(right, op)
++
++    cdef _richcmp_c_impl(left, Element _right, int op):
++        r"""
++        C implementation of comparison.
++
++        TESTS:
++
++        Make some random tests to check that the order is compatible with the
++        ones of the real field (RR) and complex field (CC)::
++
++            sage: K1 = NumberField(x^2 - 2, 'a', embedding=RR(1.4))
++            sage: K2 = NumberField(x^2 - 2, 'a', embedding=RR(-1.4))
++            sage: for _ in xrange(500):
++            ...       for K in K1, K2:
++            ...           a = K.random_element()
++            ...           b = K.random_element()
++            ...           assert (a < b) == (RR(a) < RR(b))
++            ...           assert (a > b) == (RR(a) > RR(b))
++            ...           assert (a == b) == (RR(a) == RR(b))
++            ...           assert (a != b) == (RR(a) != RR(b))
++            ...           assert (a >= b) == (RR(a) >= RR(b))
++            ...           assert (a <= b) == (RR(a) <= RR(b))
++
++        ::
++
++            sage: K1 = NumberField(x^2 + 2, 'a', embedding=CC(0,1))
++            sage: K2 = NumberField(x^2 + 2, 'a', embedding=CC(0,-1))
++            sage: for _ in xrange(500):
++            ...       for K in K1, K2:
++            ...           a = K.random_element()
++            ...           b = K.random_element()
++            ...           assert (a < b) == (CC(a) < CC(b))
++            ...           assert (a > b) == (CC(a) > CC(b))
++            ...           assert (a == b) == (CC(a) == CC(b))
++            ...           assert (a != b) == (CC(a) != CC(b))
++            ...           assert (a >= b) == (CC(a) >= CC(b))
++            ...           assert (a <= b) == (CC(a) <= CC(b))
++
++        The following is tested because of the implementation of
++        func:`Q_to_quadratic_field_element` which was the cause of some problems
++        with #13213::
++
++            sage: K.<sqrt2> = QuadraticField(2,name='sqrt2')
++            sage: 1/2 + sqrt2 > 0
++            True
++        """
++        # When D > 0 and standard embedding, we compare (a + b * sqrt(D)) / d and (aa +
++        # bb * sqrt(D)) / dd using the comparison of (dd*a - d * aa)^2 and (d*bb - dd*b)^2 * D
++        # mpz_sgn: returns 1 if > 0, 0 if 0 and -1 if < 0
++        cdef mpz_t i, j
++        cdef NumberFieldElement_quadratic right = <NumberFieldElement_quadratic> _right
++        cdef int test
++
++        # inequality and equality
++        if mpz_cmp(left.a, right.a) or mpz_cmp(left.b, right.b) or mpz_cmp(left.denom, right.denom):
++            if op == Py_EQ:
++                return False
++            elif op == Py_NE:
++                return True
++        else: # equality
++            if op == Py_EQ or op == Py_LE or op == Py_GE:
++                return True
++            if op == Py_NE or op == Py_LT or op == Py_GT:
++                return False
++
++        # comparisons are valid only in *real* quadratic number field
++        # when no embedding is specified or in the case of complex embeddings we
++        # use a lexicographic order.
++        if mpz_sgn(left.D.value) == -1:
++            mpz_init(i)
++            mpz_init(j)
++            mpz_mul(i, left.a, right.denom)
++            mpz_mul(j, right.a, left.denom)
++            test = mpz_cmp(i,j)
++            if test:
++                mpz_clear(i)
++                mpz_clear(j)
++                return (<Element>left)._rich_to_bool(op, test)
++            mpz_mul(i, left.b, right.denom)
++            mpz_mul(j, right.b, left.denom)
++            test = mpz_cmp(i,j)
++            if test:
++                if not left.standard_embedding:
++                    test = -test
++                mpz_clear(i)
++                mpz_clear(j)
++                return (<Element>left)._rich_to_bool(op, test)
++            test = mpz_cmp(left.denom, right.denom)
++            mpz_clear(i)
++            mpz_clear(j)
++            return (<Element>left)._rich_to_bool(op, test)
++
++        # comparison in the real case
++        mpz_init(i)
++        mpz_mul(i,  right.denom, left.a)
++        mpz_submul(i, left.denom, right.a)
++
++        mpz_init(j)
++        mpz_mul(j, left.denom, right.b)
++        mpz_submul(j, right.denom, left.b)
++
++        if not left.standard_embedding:
++            mpz_neg(j, j)
++
++        if mpz_sgn(i) == 1:
++            if mpz_sgn(j) == 1:
++                mpz_mul(i, i, i)
++                mpz_mul(j, j, j)
++                mpz_mul(j, j, left.D.value)
++                test = mpz_cmp(i, j)
++            else:
++                test = 1
++
++        else:
++            if mpz_sgn(j) == -1:
++                mpz_mul(i, i, i)
++                mpz_mul(j, j, j)
++                mpz_mul(j, j, left.D.value)
++                test = mpz_cmp(j, i)
++            else:
++                test = -1
++
++        mpz_clear(i)
++        mpz_clear(j)
++        return (<Element>left)._rich_to_bool(op, test)
++
++    def __cmp__(left, right):
++        r"""
++        Comparisons of elements.
++
++        When there is a real embedding defined, the comparisons uses comparison
++        induced from the reals. Otherwise, comparison is a lexicographic
++        comparison on coefficients.
++
++        EXAMPLES:
++
++        Two examples from the same number field with its two possible real
++        embeddings::
++
++            sage: K.<phi> = NumberField(x^2-x-1, 'phi', embedding=1.618)
++            sage: phi > 0
++            True
++            sage: -phi > 0
++            False
++            sage: phi - 3 == 2*phi + 1
++            False
++            sage: fibonacci(10)*phi < fibonacci(11)
++            True
++            sage: RDF(fibonacci(10)*phi)
++            88.9918693812
++            sage: fibonacci(11)
++            89
++            sage: l = [-2, phi+3, 2*phi-1, 2*phi-5, 0, -phi+2, fibonacci(20)*phi - fibonacci(21)]
++            sage: l.sort()
++            sage: l
++            [-2, 2*phi - 5, 6765*phi - 10946, 0, -phi + 2, 2*phi - 1, phi + 3]
++            sage: map(RDF, l)
++            [-2.0, -1.7639320225, -6.61069607304e-05, 0.0, 0.38196601125, 2.2360679775, 4.61803398875]
++
++            sage: L.<psi> = NumberField(x^2-x-1, 'psi', embedding=-0.618)
++            sage: psi < 0
++            True
++            sage: 2*psi + 3 == 2*psi + 3
++            True
++            sage: fibonacci(10)*psi < -fibonacci(9)
++            False
++            sage: RDF(fibonacci(10)*psi)
++            -33.9918693812
++            sage: fibonacci(9)
++            34
++            sage: l = [-1, psi, 0, fibonacci(20)*psi + fibonacci(19), 3*psi+2]
++            sage: l.sort()
++            sage: l
++            [-1, psi, 0, 6765*psi + 4181, 3*psi + 2]
++            sage: map(RDF, l)
++            [-1.0, -0.61803398875, 0.0, 6.61069607304e-05, 0.14589803375]
++
++        For a field with no specified embedding the comparison uses the standard
++        embedding::
++
++            sage: K.<sqrt2> = NumberField(x^2-2, 'sqrt2')
++            sage: sqrt2 > 1 and sqrt2 < 2
++            True
++
++        The following examples illustrate the same behavior for a complex
++        quadratic field::
++
++            sage: K.<i> = QuadraticField(-1)
++            sage: l = [-2, i-3, 2*i-2, 2*i+2, 5*i, 1-3*i, -1+i, 1]
++            sage: l.sort()
++            sage: l
++            [i - 3, -2, 2*i - 2, i - 1, 5*i, -3*i + 1, 1, 2*i + 2]
++            sage: map(CDF, l)
++            [-3.0 + 1.0*I, -2.0, -2.0 + 2.0*I, -1.0 + 1.0*I, 5.0*I, 1.0 - 3.0*I, 1.0, 2.0 + 2.0*I]
++            sage: map(CDF, l) == sorted(map(CDF, l))
++            True
++        """
++        return (<Element>left)._cmp(right)
++
++    cdef int _cmp_c_impl(left, Element _right) except -2:
++        """
++        C implementation of comparison.
++        """
++        cdef NumberFieldElement_quadratic right = <NumberFieldElement_quadratic> _right
++        cdef int test
++
++        if left == right:
++             return 0
++        if left > right:
++            return 1
++        return -1
++
+ #########################################################
+ # Arithmetic
+ #########################################################
+@@ -915,34 +1250,6 @@
+         """
+         return hash(self.polynomial())
+ 
+-    def __richcmp__(left, right, int op):
+-        r"""
+-        EXAMPLE::
+-        
+-            sage: K.<a> = NumberField(x^2+163)
+-            sage: K(1/2) < K(2/3) # indirect doctest
+-            False
+-            sage: K(1/2) > K(1/3) # indirect doctest
+-            True
+-        """
+-        return (<Element>left)._richcmp(right, op)
+-
+-    cdef int _cmp_c_impl(self, Element _right) except -2:
+-        """
+-        EXAMPLES: 
+-            sage: K.<a> = NumberField(x^2+163)
+-            sage: K(1/2)==1/2
+-            True
+-            sage: a == 1/2
+-            False
+-            sage: 2+a == a+2
+-            True
+-        """
+-        cdef NumberFieldElement_quadratic right = _right
+-        return not mpz_cmp(self.a, right.a)==0  \
+-            or not mpz_cmp(self.b, right.b)==0  \
+-            or not mpz_cmp(self.denom, right.denom) == 0
+-
+ 
+     def __nonzero__(self):
+         """
+@@ -1077,7 +1384,6 @@
+         mpz_set_ui(q.b, 1)
+         mpz_set_ui(q.denom, 1)
+         from sage.rings.complex_double import CDF
+-        cdef bint standard_embedding = embedding is None or self._parent._standard_embedding
+         cdef Rational res
+         if mpz_cmp_ui(negD.value, 1) == 0 or negD.is_square():
+             # D = -1 is the most common case we'll see here
+@@ -1091,7 +1397,7 @@
+                 mpz_mul(mpq_numref(res.value), mpq_numref(res.value), self.b)
+             mpz_set(mpq_denref(res.value), self.denom)
+             mpq_canonicalize(res.value)
+-            if not standard_embedding:
++            if not self.standard_embedding:
+                 mpq_neg(res.value, res.value)
+             return res
+         else:
+@@ -1104,7 +1410,7 @@
+                 K = QuadraticField(negD, 'sqrt%s' % negD)
+             q = K(0)
+             mpz_set(q.denom, self.denom)
+-            if standard_embedding:
++            if self.standard_embedding:
+                 mpz_set(q.b, self.b)
+             else:
+                 mpz_neg(q.b, self.b)
+@@ -1118,12 +1424,12 @@
+             sage: abs(a+1)
+             sqrt(2)
+         """
+-        from sage.functions.all import sqrt
+-        return sqrt(self.imag()**2 + self.real()**2)
++        return (self.imag()**2 + self.real()**2).sqrt()
+ 
+     def _coefficients(self):
+         """
+-        EXAMPLES: 
++        EXAMPLES::
++
+             sage: K.<a> = NumberField(x^2+41)
+             sage: a._coefficients()
+             [0, 1]
+@@ -1637,10 +1943,7 @@
+         """
+         import sage.categories.homset
+         Morphism.__init__(self, sage.categories.homset.Hom(QQ, K))
+-        self.zero_element = PY_NEW(NumberFieldElement_quadratic)
+-        self.zero_element._parent = K
+-        self.zero_element.D = K._D
+-        
++        self.zero_element = K.zero_element()
+ 
+     cpdef Element _call_(self, x):
+         r"""
+diff --git a/sage/rings/number_field/order.py b/sage/rings/number_field/order.py
+--- a/sage/rings/number_field/order.py
++++ b/sage/rings/number_field/order.py
+@@ -1022,6 +1022,9 @@
+ 
+         if K.degree() == 2:
+             self._element_type = OrderElement_quadratic
++            # adding the following attribute makes the comparison of elements
++            # faster.
++            self._standard_embedding = K._standard_embedding
+         else:
+             self._element_type = OrderElement_absolute
+             
+diff --git a/sage/rings/number_field/totallyreal_rel.py b/sage/rings/number_field/totallyreal_rel.py
+--- a/sage/rings/number_field/totallyreal_rel.py
++++ b/sage/rings/number_field/totallyreal_rel.py
+@@ -125,23 +125,21 @@
+ 
+         sage: v = sage.rings.number_field.totallyreal_rel.integral_elements_in_box(K, C)
+         sage: sorted(v)
+-        [-alpha + 3, -alpha + 2, 5, 4, 3, 2, 1, 0, alpha + 6, alpha + 5, alpha + 4, alpha + 3, alpha + 2, 2*alpha + 7, 2*alpha + 6, 2*alpha + 5, 2*alpha + 4, 2*alpha + 3, 3*alpha + 5]
+-
++         [0, -alpha + 2, 1, -alpha + 3, 2, 3, alpha + 2, 4, alpha + 3, 5, alpha + 4, 2*alpha + 3, alpha + 5, 2*alpha + 4, alpha + 6, 2*alpha + 5, 2*alpha + 6, 3*alpha + 5, 2*alpha + 7]
+ 
+     A cubic field::
+ 
+         sage: x = polygen(QQ)
+         sage: K.<a> = NumberField(x^3 - 16*x +16)
+         sage: eps = 10e-6
+-        sage: C = [[0-eps,5+eps]]*3 
++        sage: C = [[0-eps,5+eps]]*3
+         sage: v = sage.rings.number_field.totallyreal_rel.integral_elements_in_box(K, C)
+ 
+     Note that the output is platform dependent (sometimes a 5 is listed below, and
+     sometimes it isn't)::
+-    
+-        sage: sorted(v) 
++
++        sage: sorted(v)
+         [-1/2*a + 2, 1/4*a^2 + 1/2*a, 0, 1, 2, 3, 4,...-1/4*a^2 - 1/2*a + 5, 1/2*a + 3, -1/4*a^2 + 5]
+-        
+     """
+     d = K.degree()
+     Z_F = K.maximal_order()
+diff --git a/sage/schemes/elliptic_curves/cm.py b/sage/schemes/elliptic_curves/cm.py
+--- a/sage/schemes/elliptic_curves/cm.py
++++ b/sage/schemes/elliptic_curves/cm.py
+@@ -158,31 +158,31 @@
+     Return a list of all CM `j`-invariants in the field `K`.
+ 
+     INPUT:
+-    
++
+     - ``K`` -- a number field
+     - ``proof`` -- (default: proof.number_field())
+ 
+     OUTPUT:
+-    
++
+     (list) -- A list of CM `j`-invariants in the field `K`.
+ 
+     EXAMPLE::
+-    
++
+         sage: cm_j_invariants(QQ)
+         [-262537412640768000, -147197952000, -884736000, -12288000, -884736, -32768, -3375, 0, 1728, 8000, 54000, 287496, 16581375]
+ 
+     Over imaginary quadratic fields there are no more than over `QQ`::
+-    
+-        sage: cm_j_invariants(QuadraticField(-1, 'i'))   # sorted differently since QQ[i] sorts funny
+-        [-12288000, 54000, 0, 287496, 1728, 16581375, -3375, 8000, -32768, -884736, -884736000, -147197952000, -262537412640768000]
+-        
++
++        sage: cm_j_invariants(QuadraticField(-1, 'i'))
++        [-262537412640768000, -147197952000, -884736000, -12288000, -884736, -32768, -3375, 0, 1728, 8000, 54000, 287496, 16581375]
++
+     Over real quadratic fields there may be more, for example::
+-    
++
+         sage: len(cm_j_invariants(QuadraticField(5, 'a')))
+         31
+-        
++
+     Over number fields K of many higher degrees this also works::
+-    
++
+         sage: K.<a> = NumberField(x^3 - 2)
+         sage: cm_j_invariants(K)
+         [-12288000, 54000, 0, 287496, 1728, 16581375, -3375, 8000, -32768, -884736, -884736000, -147197952000, -262537412640768000, 31710790944000*a^2 + 39953093016000*a + 50337742902000]
+diff --git a/sage/schemes/elliptic_curves/ell_curve_isogeny.py b/sage/schemes/elliptic_curves/ell_curve_isogeny.py
+--- a/sage/schemes/elliptic_curves/ell_curve_isogeny.py
++++ b/sage/schemes/elliptic_curves/ell_curve_isogeny.py
+@@ -738,9 +738,8 @@
+         sage: phi.codomain() == phi.domain()
+         True
+         sage: phi.rational_maps()
+-        (((-4/25*i - 3/25)*x^5 + (-4/5*i + 2/5)*x^3 + x)/(x^4 + (-4/5*i + 2/5)*x^2 + (-4/25*i - 3/25)),
+-        ((2/125*i - 11/125)*x^6*y + (64/125*i + 23/125)*x^4*y + (162/125*i - 141/125)*x^2*y + (-4/25*i - 3/25)*y)/(x^6 + (-6/5*i + 3/5)*x^4 + (-12/25*i - 9/25)*x^2 + (2/125*i - 11/125)))
+-
++        (((4/25*i + 3/25)*x^5 + (4/5*i - 2/5)*x^3 - x)/(x^4 + (-4/5*i + 2/5)*x^2 + (-4/25*i - 3/25)),
++         ((11/125*i + 2/125)*x^6*y + (-23/125*i + 64/125)*x^4*y + (141/125*i + 162/125)*x^2*y + (3/25*i - 4/25)*y)/(x^6 + (-6/5*i + 3/5)*x^4 + (-12/25*i - 9/25)*x^2 + (2/125*i - 11/125)))
+     """
+ 
+     ####################
+@@ -4513,8 +4512,8 @@
+         [Isogeny of degree 5 from Elliptic Curve defined by y^2 = x^3 + x over Number Field in i with defining polynomial x^2 + 1 to Elliptic Curve defined by y^2 = x^3 + x over Number Field in i with defining polynomial x^2 + 1,
+         Isogeny of degree 5 from Elliptic Curve defined by y^2 = x^3 + x over Number Field in i with defining polynomial x^2 + 1 to Elliptic Curve defined by y^2 = x^3 + x over Number Field in i with defining polynomial x^2 + 1]
+         sage: _[0].rational_maps()
+-        (((-4/25*i - 3/25)*x^5 + (-4/5*i + 2/5)*x^3 + x)/(x^4 + (-4/5*i + 2/5)*x^2 + (-4/25*i - 3/25)),
+-        ((2/125*i - 11/125)*x^6*y + (64/125*i + 23/125)*x^4*y + (162/125*i - 141/125)*x^2*y + (-4/25*i - 3/25)*y)/(x^6 + (-6/5*i + 3/5)*x^4 + (-12/25*i - 9/25)*x^2 + (2/125*i - 11/125)))
++        (((4/25*i + 3/25)*x^5 + (4/5*i - 2/5)*x^3 - x)/(x^4 + (-4/5*i + 2/5)*x^2 + (-4/25*i - 3/25)),
++         ((11/125*i + 2/125)*x^6*y + (-23/125*i + 64/125)*x^4*y + (141/125*i + 162/125)*x^2*y + (3/25*i - 4/25)*y)/(x^6 + (-6/5*i + 3/5)*x^4 + (-12/25*i - 9/25)*x^2 + (2/125*i - 11/125)))
+ 
+     An example of 5-isogenies over a number field::
+ 
+@@ -4774,7 +4773,7 @@
+         [Isogeny of degree 13 from Elliptic Curve defined by y^2 = x^3 + r over Number Field in r with defining polynomial x^2 + 3 to Elliptic Curve defined by y^2 = x^3 + r over Number Field in r with defining polynomial x^2 + 3,
+         Isogeny of degree 13 from Elliptic Curve defined by y^2 = x^3 + r over Number Field in r with defining polynomial x^2 + 3 to Elliptic Curve defined by y^2 = x^3 + r over Number Field in r with defining polynomial x^2 + 3]
+         sage: isogenies_13_0(E)[0].rational_maps()
+-        (((-4/169*r - 11/169)*x^13 + (-128/13*r - 456/13)*x^10 + (-1224/13*r - 2664/13)*x^7 + (-2208/13*r + 5472/13)*x^4 + (1152/13*r - 8064/13)*x)/(x^12 + (4*r - 36)*x^9 + (-1080/13*r + 3816/13)*x^6 + (2112/13*r + 5184/13)*x^3 + (17280/169*r - 1152/169)), ((18/2197*r - 35/2197)*x^18*y + (-23142/2197*r + 35478/2197)*x^15*y + (-1127520/2197*r + 1559664/2197)*x^12*y + (87744/2197*r + 5992704/2197)*x^9*y + (-6625152/2197*r + 9085824/2197)*x^6*y + (28919808/2197*r - 2239488/2197)*x^3*y + (-1990656/2197*r + 3870720/2197)*y)/(x^18 + (6*r - 54)*x^15 + (-3024/13*r + 11808/13)*x^12 + (31296/13*r - 51840/13)*x^9 + (-487296/169*r - 2070144/169)*x^6 + (-940032/169*r - 248832/169)*x^3 + (-1990656/2197*r + 3870720/2197)))
++        (((7/338*r + 23/338)*x^13 + (-164/13*r - 420/13)*x^10 + (720/13*r + 3168/13)*x^7 + (3840/13*r - 576/13)*x^4 + (4608/13*r + 2304/13)*x)/(x^12 + (4*r + 36)*x^9 + (1080/13*r + 3816/13)*x^6 + (2112/13*r - 5184/13)*x^3 + (-17280/169*r - 1152/169)), ((18/2197*r + 35/2197)*x^18*y + (23142/2197*r + 35478/2197)*x^15*y + (-1127520/2197*r - 1559664/2197)*x^12*y + (-87744/2197*r + 5992704/2197)*x^9*y + (-6625152/2197*r - 9085824/2197)*x^6*y + (-28919808/2197*r - 2239488/2197)*x^3*y + (-1990656/2197*r - 3870720/2197)*y)/(x^18 + (6*r + 54)*x^15 + (3024/13*r + 11808/13)*x^12 + (31296/13*r + 51840/13)*x^9 + (487296/169*r - 2070144/169)*x^6 + (-940032/169*r + 248832/169)*x^3 + (1990656/2197*r + 3870720/2197)))
+ 
+     An example of endomorphisms over a finite field::
+     
+diff --git a/sage/schemes/elliptic_curves/ell_field.py b/sage/schemes/elliptic_curves/ell_field.py
+--- a/sage/schemes/elliptic_curves/ell_field.py
++++ b/sage/schemes/elliptic_curves/ell_field.py
+@@ -939,10 +939,8 @@
+             Elliptic Curve defined by y^2 + x*y + y = x^3 + 4*x + (-6) over Number Field in e with defining polynomial x^2 - 2
+             sage: E.isogenies_prime_degree(2)
+             [Isogeny of degree 2 from Elliptic Curve defined by y^2 + x*y + y = x^3 + 4*x + (-6) over Number Field in e with defining polynomial x^2 - 2 to Elliptic Curve defined by y^2 + x*y + y = x^3 + (-36)*x + (-70) over Number Field in e with defining polynomial x^2 - 2]
+-            sage: E.isogenies_prime_degree(3)            
+-            [Isogeny of degree 3 from Elliptic Curve defined by y^2 + x*y + y = x^3 + 4*x + (-6) over Number Field in e with defining polynomial x^2 - 2 to Elliptic Curve defined by y^2 + x*y + y = x^3 + (-171)*x + (-874) over Number Field in e with defining polynomial x^2 - 2, Isogeny of degree 3 from Elliptic Curve defined by y^2 + x*y + y = x^3 + 4*x + (-6) over Number Field in e with defining polynomial x^2 - 2 to Elliptic Curve defined by y^2 + x*y + y = x^3 + (-128/3)*x + 5662/27 over Number Field in e with defining polynomial x^2 - 2]
+-
+-
++            sage: E.isogenies_prime_degree(3)
++            [Isogeny of degree 3 from Elliptic Curve defined by y^2 + x*y + y = x^3 + 4*x + (-6) over Number Field in e with defining polynomial x^2 - 2 to Elliptic Curve defined by y^2 + x*y + y = x^3 + (-128/3)*x + 5662/27 over Number Field in e with defining polynomial x^2 - 2, Isogeny of degree 3 from Elliptic Curve defined by y^2 + x*y + y = x^3 + 4*x + (-6) over Number Field in e with defining polynomial x^2 - 2 to Elliptic Curve defined by y^2 + x*y + y = x^3 + (-171)*x + (-874) over Number Field in e with defining polynomial x^2 - 2]
+         """
+         F = self.base_ring()
+         if rings.is_RealField(F):
+diff --git a/sage/schemes/elliptic_curves/ell_generic.py b/sage/schemes/elliptic_curves/ell_generic.py
+--- a/sage/schemes/elliptic_curves/ell_generic.py
++++ b/sage/schemes/elliptic_curves/ell_generic.py
+@@ -2260,10 +2260,10 @@
+             sage: K.<a> = NumberField(x^2+3) # adjoin roots of unity
+             sage: E.automorphisms(K)
+             [Generic endomorphism of Abelian group of points on Elliptic Curve defined by y^2 + y = x^3 over Number Field in a with defining polynomial x^2 + 3
+-            Via:  (u,r,s,t) = (1, 0, 0, 0),
++            Via:  (u,r,s,t) = (-1, 0, 0, -1),
+             ...
+             Generic endomorphism of Abelian group of points on Elliptic Curve defined by y^2 + y = x^3 over Number Field in a with defining polynomial x^2 + 3
+-            Via:  (u,r,s,t) = (-1/2*a - 1/2, 0, 0, 0)]
++            Via:  (u,r,s,t) = (1, 0, 0, 0)]
+         
+         ::
+         
+diff --git a/sage/schemes/elliptic_curves/ell_number_field.py b/sage/schemes/elliptic_curves/ell_number_field.py
+--- a/sage/schemes/elliptic_curves/ell_number_field.py
++++ b/sage/schemes/elliptic_curves/ell_number_field.py
+@@ -1348,7 +1348,7 @@
+             sage: [(p.norm(), e) for p, e in E.conductor().factor()]
+             [(9, 1), (5, 1)]
+             sage: [(p.norm(), e) for p, e in E.discriminant().factor()]
+-            [(9, 1), (-5, 2)]
++            [(-5, 2), (9, 1)]
+ 
+         See :trac:`14472`, this used not to work over a relative extension::
+ 
+@@ -1578,7 +1578,7 @@
+         except AttributeError:
+             self.__torsion_order = self.torsion_subgroup().order()
+             return self.__torsion_order
+-  
++
+     def torsion_points(self):
+         r"""
+         Returns a list of the torsion points of this elliptic curve.
+@@ -1595,61 +1595,61 @@
+             sage: K.<t> = NumberField(x^4 + x^3 + 11*x^2 + 41*x + 101)
+             sage: EK = E.base_extend(K)
+             sage: EK.torsion_points()
+-            [(16 : 60 : 1), 
+-             (5 : 5 : 1), 
++            [(16 : 60 : 1),
++             (5 : 5 : 1),
+              (5 : -6 : 1),
+              (16 : -61 : 1),
+-             (t : 1/11*t^3 + 6/11*t^2 + 19/11*t + 48/11 : 1), 
+-             (-3/55*t^3 - 7/55*t^2 - 2/55*t - 133/55 : 6/55*t^3 + 3/55*t^2 + 25/11*t + 156/55 : 1), 
+-             (-9/121*t^3 - 21/121*t^2 - 127/121*t - 377/121 : -7/121*t^3 + 24/121*t^2 + 197/121*t + 16/121 : 1), 
++             (t : 1/11*t^3 + 6/11*t^2 + 19/11*t + 48/11 : 1),
++             (-3/55*t^3 - 7/55*t^2 - 2/55*t - 133/55 : 6/55*t^3 + 3/55*t^2 + 25/11*t + 156/55 : 1),
++             (-9/121*t^3 - 21/121*t^2 - 127/121*t - 377/121 : -7/121*t^3 + 24/121*t^2 + 197/121*t + 16/121 : 1),
+              (5/121*t^3 - 14/121*t^2 - 158/121*t - 453/121 : -49/121*t^3 - 129/121*t^2 - 315/121*t - 207/121 : 1),
+-             (10/121*t^3 + 49/121*t^2 + 168/121*t + 73/121 : 32/121*t^3 + 60/121*t^2 - 261/121*t - 807/121 : 1), 
+-             (1/11*t^3 - 5/11*t^2 + 19/11*t - 40/11 : -6/11*t^3 - 3/11*t^2 - 26/11*t - 321/11 : 1), 
+-             (14/121*t^3 - 15/121*t^2 + 90/121*t + 232/121 : 16/121*t^3 - 69/121*t^2 + 293/121*t - 46/121 : 1), 
+-             (3/55*t^3 + 7/55*t^2 + 2/55*t + 78/55 : 7/55*t^3 - 24/55*t^2 + 9/11*t + 17/55 : 1), 
++             (10/121*t^3 + 49/121*t^2 + 168/121*t + 73/121 : 32/121*t^3 + 60/121*t^2 - 261/121*t - 807/121 : 1),
++             (1/11*t^3 - 5/11*t^2 + 19/11*t - 40/11 : -6/11*t^3 - 3/11*t^2 - 26/11*t - 321/11 : 1),
++             (14/121*t^3 - 15/121*t^2 + 90/121*t + 232/121 : 16/121*t^3 - 69/121*t^2 + 293/121*t - 46/121 : 1),
++             (3/55*t^3 + 7/55*t^2 + 2/55*t + 78/55 : 7/55*t^3 - 24/55*t^2 + 9/11*t + 17/55 : 1),
+              (-5/121*t^3 + 36/121*t^2 - 84/121*t + 24/121 : 34/121*t^3 - 27/121*t^2 + 305/121*t + 708/121 : 1),
+-             (-26/121*t^3 + 20/121*t^2 - 219/121*t - 995/121 : 15/121*t^3 + 156/121*t^2 - 232/121*t + 2766/121 : 1), 
+-             (1/11*t^3 - 5/11*t^2 + 19/11*t - 40/11 : 6/11*t^3 + 3/11*t^2 + 26/11*t + 310/11 : 1), 
+-             (-26/121*t^3 + 20/121*t^2 - 219/121*t - 995/121 : -15/121*t^3 - 156/121*t^2 + 232/121*t - 2887/121 : 1), 
+-             (-5/121*t^3 + 36/121*t^2 - 84/121*t + 24/121 : -34/121*t^3 + 27/121*t^2 - 305/121*t - 829/121 : 1), 
+-             (3/55*t^3 + 7/55*t^2 + 2/55*t + 78/55 : -7/55*t^3 + 24/55*t^2 - 9/11*t - 72/55 : 1), 
+-             (14/121*t^3 - 15/121*t^2 + 90/121*t + 232/121 : -16/121*t^3 + 69/121*t^2 - 293/121*t - 75/121 : 1), 
++             (-26/121*t^3 + 20/121*t^2 - 219/121*t - 995/121 : 15/121*t^3 + 156/121*t^2 - 232/121*t + 2766/121 : 1),
++             (1/11*t^3 - 5/11*t^2 + 19/11*t - 40/11 : 6/11*t^3 + 3/11*t^2 + 26/11*t + 310/11 : 1),
++             (-26/121*t^3 + 20/121*t^2 - 219/121*t - 995/121 : -15/121*t^3 - 156/121*t^2 + 232/121*t - 2887/121 : 1),
++             (-5/121*t^3 + 36/121*t^2 - 84/121*t + 24/121 : -34/121*t^3 + 27/121*t^2 - 305/121*t - 829/121 : 1),
++             (3/55*t^3 + 7/55*t^2 + 2/55*t + 78/55 : -7/55*t^3 + 24/55*t^2 - 9/11*t - 72/55 : 1),
++             (14/121*t^3 - 15/121*t^2 + 90/121*t + 232/121 : -16/121*t^3 + 69/121*t^2 - 293/121*t - 75/121 : 1),
+              (t : -1/11*t^3 - 6/11*t^2 - 19/11*t - 59/11 : 1),
+-             (10/121*t^3 + 49/121*t^2 + 168/121*t + 73/121 : -32/121*t^3 - 60/121*t^2 + 261/121*t + 686/121 : 1), 
+-             (5/121*t^3 - 14/121*t^2 - 158/121*t - 453/121 : 49/121*t^3 + 129/121*t^2 + 315/121*t + 86/121 : 1), 
+-             (-9/121*t^3 - 21/121*t^2 - 127/121*t - 377/121 : 7/121*t^3 - 24/121*t^2 - 197/121*t - 137/121 : 1), 
+-             (-3/55*t^3 - 7/55*t^2 - 2/55*t - 133/55 : -6/55*t^3 - 3/55*t^2 - 25/11*t - 211/55 : 1), 
++             (10/121*t^3 + 49/121*t^2 + 168/121*t + 73/121 : -32/121*t^3 - 60/121*t^2 + 261/121*t + 686/121 : 1),
++             (5/121*t^3 - 14/121*t^2 - 158/121*t - 453/121 : 49/121*t^3 + 129/121*t^2 + 315/121*t + 86/121 : 1),
++             (-9/121*t^3 - 21/121*t^2 - 127/121*t - 377/121 : 7/121*t^3 - 24/121*t^2 - 197/121*t - 137/121 : 1),
++             (-3/55*t^3 - 7/55*t^2 - 2/55*t - 133/55 : -6/55*t^3 - 3/55*t^2 - 25/11*t - 211/55 : 1),
+              (0 : 1 : 0)]
+ 
+         ::
+-    
++
+             sage: E = EllipticCurve('15a1')
+             sage: K.<t> = NumberField(x^2 + 2*x + 10)
+             sage: EK = E.base_extend(K)
+             sage: EK.torsion_points()
+-            [(8 : 18 : 1), 
+-             (3 : -2 : 1), 
+-             (8 : -27 : 1), 
+-             (t : t - 5 : 1), 
+-             (1/2 : 5/4*t + 1/2 : 1), 
+-             (-t - 2 : 2*t + 8 : 1), 
+-             (-7 : -5*t - 2 : 1), 
+-             (-1 : 0 : 1), 
+-             (-2 : 3 : 1), 
+-             (-13/4 : 9/8 : 1), 
+-             (-2 : -2 : 1), 
++            [(-7 : -5*t - 2 : 1),
++             (-7 : 5*t + 8 : 1),
++             (-13/4 : 9/8 : 1),
++             (-2 : -2 : 1),
++             (-2 : 3 : 1),
++             (-t - 2 : -t - 7 : 1),
++             (-t - 2 : 2*t + 8 : 1),
++             (-1 : 0 : 1),
++             (t : t - 5 : 1),
+              (t : -2*t + 4 : 1),
+-             (-7 : 5*t + 8 : 1),
+-             (-t - 2 : -t - 7 : 1), 
++             (0 : 1 : 0),
+              (1/2 : -5/4*t - 2 : 1),
+-             (0 : 1 : 0)]
++             (1/2 : 5/4*t + 1/2 : 1),
++             (3 : -2 : 1),
++             (8 : -27 : 1),
++             (8 : 18 : 1)]
+ 
+         ::
+-    
++
+             sage: K.<i> = QuadraticField(-1)
+             sage: EK = EllipticCurve(K,[0,0,0,0,-1])
+             sage: EK.torsion_points ()
+-            [(-2 : -3*i : 1), (0 : -i : 1), (1 : 0 : 1), (0 : i : 1), (-2 : 3*i : 1), (0 : 1 : 0)]
++             [(-2 : -3*i : 1), (-2 : 3*i : 1), (0 : -i : 1), (0 : i : 1), (0 : 1 : 0), (1 : 0 : 1)]
+          """
+         T = self.torsion_subgroup() # make sure it is cached
+         return sorted(T.points())           # these are also cached in T
+diff --git a/sage/schemes/elliptic_curves/ell_point.py b/sage/schemes/elliptic_curves/ell_point.py
+--- a/sage/schemes/elliptic_curves/ell_point.py
++++ b/sage/schemes/elliptic_curves/ell_point.py
+@@ -842,7 +842,7 @@
+             sage: tor = E.torsion_points(); len(tor)
+             8
+             sage: [T.order() for T in tor]
+-            [4, 2, 4, 2, 4, 2, 4, 1]
++            [2, 4, 4, 2, 1, 2, 4, 4]
+             sage: all([T.is_divisible_by(3) for T in tor])
+             True
+             sage: Set([T for T in tor if T.is_divisible_by(2)])
+@@ -2509,7 +2509,7 @@
+             sage: K.<i> = NumberField(x^2+1)
+             sage: E = EllipticCurve(K, [0,0,4,6*i,0])
+             sage: Q = E.lift_x(-9/4); Q
+-            (-9/4 : 27/8*i - 4 : 1)
++            (-9/4 : -27/8*i : 1)
+             sage: Q.height()
+             2.69518560017909
+             sage: (15*Q).height() / Q.height()
+@@ -2629,7 +2629,7 @@
+             0.510184995162373
+ 
+             sage: Q = E.lift_x(-9/4); Q
+-            (-9/4 : 27/8*i - 4 : 1)
++            (-9/4 : -27/8*i : 1)
+             sage: Q.archimedian_local_height(K.places()[0]) / 2
+             0.654445619529600
+         """
+@@ -2738,7 +2738,7 @@
+             0
+             
+             sage: Q = E.lift_x(-9/4); Q
+-            (-9/4 : 27/8*i - 4 : 1)
++            (-9/4 : -27/8*i : 1)
+             sage: Q.nonarchimedian_local_height(K.ideal(1+i))
+             2*log(2)
+             sage: Q.nonarchimedian_local_height(K.ideal(3))
+diff --git a/sage/schemes/elliptic_curves/ell_torsion.py b/sage/schemes/elliptic_curves/ell_torsion.py
+--- a/sage/schemes/elliptic_curves/ell_torsion.py
++++ b/sage/schemes/elliptic_curves/ell_torsion.py
+@@ -108,7 +108,7 @@
+         sage: T.ngens()
+         1
+         sage: T.gen(0)
+-        (16 : 60 : 1)
++        (5 : -6 : 1)
+ 
+     Note: this class is normally constructed indirectly as follows::
+ 
+@@ -276,6 +276,6 @@
+             sage: E = EllipticCurve(K,[0,0,0,1,0])
+             sage: tor = E.torsion_subgroup()
+             sage: tor.points()
+-            [(0 : 1 : 0), (0 : 0 : 1), (i : 0 : 1), (-i : 0 : 1)]
++            [(0 : 1 : 0), (-i : 0 : 1), (0 : 0 : 1), (i : 0 : 1)]
+         """
+         return [x.element() for x in self]
+diff --git a/sage/schemes/elliptic_curves/heegner.py b/sage/schemes/elliptic_curves/heegner.py
+--- a/sage/schemes/elliptic_curves/heegner.py
++++ b/sage/schemes/elliptic_curves/heegner.py
+@@ -1433,16 +1433,16 @@
+             sage: G = K3.galois_group(K1)
+             sage: orb = sorted([g.alpha() for g in G]); orb # random (the sign depends on the database being installed or not)
+             [1, 1/2*sqrt_minus_52 + 1, -1/2*sqrt_minus_52, 1/2*sqrt_minus_52 - 1]
+-            sage: [x^2 for x in orb] # this is just for testing 
+-            [1, sqrt_minus_52 - 12, -13, -sqrt_minus_52 - 12] 
++            sage: sorted([x^2 for x in orb]) # this is just for testing
++            [-13, -sqrt_minus_52 - 12, sqrt_minus_52 - 12, 1]
+ 
+             sage: K5 = heegner_points(389,-52,5).ring_class_field()
+             sage: K1 = heegner_points(389,-52,1).ring_class_field()
+             sage: G = K5.galois_group(K1)
+             sage: orb = sorted([g.alpha() for g in G]); orb # random (the sign depends on the database being installed or not)
+             [1, -1/2*sqrt_minus_52, 1/2*sqrt_minus_52 + 1, 1/2*sqrt_minus_52 - 1, 1/2*sqrt_minus_52 - 2, -1/2*sqrt_minus_52 - 2]
+-            sage: [x^2 for x in orb] # just for testing
+-            [1, -13, sqrt_minus_52 - 12, -sqrt_minus_52 - 12, -2*sqrt_minus_52 - 9, 2*sqrt_minus_52 - 9]
++            sage: sorted([x^2 for x in orb]) # just for testing
++            [-13, -sqrt_minus_52 - 12, sqrt_minus_52 - 12, -2*sqrt_minus_52 - 9, 2*sqrt_minus_52 - 9, 1]
+ 
+         """
+         if self.__alpha is None:
+@@ -6185,7 +6185,7 @@
+         sage: P.curve()
+         Elliptic Curve defined by y^2 + y = x^3 - x over Rational Field
+         sage: P = E.heegner_point(-40).point_exact(); P
+-        (a : a - 2 : 1)
++        (a : -a + 1 : 1)
+         sage: P = E.heegner_point(-47).point_exact(); P
+         (a : a^4 + a - 1 : 1)
+         sage: P[0].parent()
+diff --git a/sage/stats/basic_stats.py b/sage/stats/basic_stats.py
+--- a/sage/stats/basic_stats.py
++++ b/sage/stats/basic_stats.py
+@@ -165,7 +165,7 @@
+         sage: std([])
+         NaN
+         sage: std([I, sqrt(2), 3/5])
+-        sqrt(1/450*(-5*sqrt(2) - 5*I + 6)^2 + 1/450*(10*sqrt(2) - 5*I - 3)^2 + 1/450*(-5*sqrt(2) + 10*I - 3)^2)
++        sqrt(1/450*(5*sqrt(2) + 5*I - 6)^2 + 1/450*(5*sqrt(2) - 10*I + 3)^2 + 1/450*(10*sqrt(2) - 5*I - 3)^2)
+         sage: std([RIF(1.0103, 1.0103), RIF(2)])
+         0.6998235813403261?
+         sage: import numpy
+@@ -225,12 +225,12 @@
+         7/2
+         sage: variance([1..6], bias=True)
+         35/12
+-        sage: variance([e, pi])                 
++        sage: variance([e, pi])
+         1/2*(pi - e)^2
+-        sage: variance([])                      
++        sage: variance([])
+         NaN
+-        sage: variance([I, sqrt(2), 3/5])       
+-        1/450*(-5*sqrt(2) - 5*I + 6)^2 + 1/450*(10*sqrt(2) - 5*I - 3)^2 + 1/450*(-5*sqrt(2) + 10*I - 3)^2
++        sage: variance([I, sqrt(2), 3/5])
++        1/450*(5*sqrt(2) + 5*I - 6)^2 + 1/450*(5*sqrt(2) - 10*I + 3)^2 + 1/450*(10*sqrt(2) - 5*I - 3)^2
+         sage: variance([RIF(1.0103, 1.0103), RIF(2)])
+         0.4897530450000000?
+         sage: import numpy
+diff --git a/sage/symbolic/integration/integral.py b/sage/symbolic/integration/integral.py
+--- a/sage/symbolic/integration/integral.py
++++ b/sage/symbolic/integration/integral.py
+@@ -456,7 +456,7 @@
+                  x y  + Sqrt[--] FresnelS[Sqrt[--] x]
+                              2                 Pi
+         sage: print f.integral(x)
+-        y^z*x + 1/8*((I + 1)*sqrt(2)*erf((1/2*I + 1/2)*sqrt(2)*x) + (I - 1)*sqrt(2)*erf((1/2*I - 1/2)*sqrt(2)*x))*sqrt(pi)
++        y^z*x + 1/8*((I - 1)*sqrt(2)*erf((1/2*I - 1/2)*sqrt(2)*x) + (I + 1)*sqrt(2)*erf((1/2*I + 1/2)*sqrt(2)*x))*sqrt(pi)
+ 
+     Alternatively, just use algorithm='mathematica_free' to integrate via Mathematica
+     over the internet (does NOT require a Mathematica license!)::
+@@ -527,7 +527,7 @@
+     see #3013::
+ 
+         sage: integrate(sin(x)*cos(10*x)*log(x), x)
+-        1/198*(11*cos(9*x) - 9*cos(11*x))*log(x) + 1/44*Ei(-11*I*x) + 1/44*Ei(11*I*x) - 1/36*Ei(-9*I*x) - 1/36*Ei(9*I*x)
++        1/198*(11*cos(9*x) - 9*cos(11*x))*log(x) + 1/44*Ei(-11*I*x) - 1/36*Ei(-9*I*x) - 1/36*Ei(9*I*x) + 1/44*Ei(11*I*x)
+ 
+     It is no longer possible to use certain functions without an
+     explicit variable.  Instead, evaluate the function at a variable,

trac_14014_iterator.patch

 # HG changeset patch
-# Parent 74a822bf61aff6dca6884cf51852c8264af160bc
+# Parent bd222b5a9638259fc640610f1aa027f95b08a63a
 
 Implement the matrix group iterator via the GAP permutation group
 iterator, and make it consistent with the list() method.
  
      ::
  
+diff --git a/sage/games/quantumino.py b/sage/games/quantumino.py
+--- a/sage/games/quantumino.py
++++ b/sage/games/quantumino.py
+@@ -80,22 +80,22 @@
+ pentamino::
+ 
+     sage: for p in s: p                                   # long time (<1s)
+-    Polyomino: [(0, 0, 0), (1, 0, 0), (1, 1, 0), (1, 1, 1), (1, 2, 0)], Color: deeppink
+-    Polyomino: [(0, 0, 1), (0, 1, 0), (0, 1, 1), (0, 2, 1), (1, 2, 1)], Color: deeppink
+-    Polyomino: [(0, 2, 0), (0, 3, 0), (0, 4, 0), (1, 4, 0), (1, 4, 1)], Color: green
+-    Polyomino: [(0, 3, 1), (1, 3, 1), (2, 2, 0), (2, 2, 1), (2, 3, 1)], Color: green
+-    Polyomino: [(1, 3, 0), (2, 3, 0), (2, 4, 0), (2, 4, 1), (3, 4, 0)], Color: red
+-    Polyomino: [(1, 0, 1), (2, 0, 1), (2, 1, 0), (2, 1, 1), (3, 1, 1)], Color: red
+-    Polyomino: [(2, 0, 0), (3, 0, 0), (3, 0, 1), (3, 1, 0), (4, 0, 0)], Color: gray
+-    Polyomino: [(3, 2, 0), (4, 0, 1), (4, 1, 0), (4, 1, 1), (4, 2, 0)], Color: purple
+-    Polyomino: [(3, 2, 1), (3, 3, 0), (3, 3, 1), (4, 2, 1), (4, 3, 1)], Color: yellow
+-    Polyomino: [(3, 4, 1), (3, 5, 1), (4, 3, 0), (4, 4, 0), (4, 4, 1)], Color: blue
+-    Polyomino: [(0, 4, 1), (0, 5, 0), (0, 5, 1), (0, 6, 1), (1, 5, 0)], Color: midnightblue
+-    Polyomino: [(0, 6, 0), (0, 7, 0), (0, 7, 1), (1, 7, 0), (2, 7, 0)], Color: darkblue
+-    Polyomino: [(1, 7, 1), (2, 6, 0), (2, 6, 1), (2, 7, 1), (3, 6, 0)], Color: blue
+-    Polyomino: [(1, 5, 1), (1, 6, 0), (1, 6, 1), (2, 5, 0), (2, 5, 1)], Color: yellow
+-    Polyomino: [(3, 6, 1), (3, 7, 0), (3, 7, 1), (4, 5, 1), (4, 6, 1)], Color: purple
+-    Polyomino: [(3, 5, 0), (4, 5, 0), (4, 6, 0), (4, 7, 0), (4, 7, 1)], Color: orange
++    Polyomino: [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 2, 0), (1, 1, 0)], Color: deeppink
++    Polyomino: [(0, 1, 1), (1, 0, 1), (1, 1, 1), (1, 2, 0), (1, 2, 1)], Color: deeppink
++    Polyomino: [(0, 2, 1), (0, 3, 1), (0, 4, 0), (0, 4, 1), (1, 4, 0)], Color: green
++    Polyomino: [(0, 3, 0), (1, 3, 0), (2, 2, 1), (2, 3, 0), (2, 3, 1)], Color: green
++    Polyomino: [(1, 3, 1), (1, 4, 1), (2, 4, 0), (2, 4, 1), (2, 5, 1)], Color: red
++    Polyomino: [(1, 0, 0), (2, 0, 0), (2, 0, 1), (2, 1, 1), (3, 0, 1)], Color: red
++    Polyomino: [(2, 1, 0), (2, 2, 0), (3, 2, 0), (3, 2, 1), (3, 3, 1)], Color: blue
++    Polyomino: [(3, 0, 0), (3, 1, 0), (4, 0, 0), (4, 0, 1), (4, 1, 0)], Color: yellow
++    Polyomino: [(3, 1, 1), (4, 1, 1), (4, 2, 0), (4, 2, 1), (4, 3, 0)], Color: purple
++    Polyomino: [(3, 3, 0), (3, 4, 0), (3, 4, 1), (4, 3, 1), (4, 4, 1)], Color: yellow
++    Polyomino: [(3, 5, 1), (4, 4, 0), (4, 5, 0), (4, 5, 1), (4, 6, 0)], Color: midnightblue
++    Polyomino: [(2, 6, 1), (2, 7, 1), (3, 7, 0), (3, 7, 1), (4, 7, 0)], Color: purple
++    Polyomino: [(3, 5, 0), (3, 6, 0), (3, 6, 1), (4, 6, 1), (4, 7, 1)], Color: blue
++    Polyomino: [(0, 5, 0), (0, 5, 1), (0, 6, 0), (1, 5, 0), (2, 5, 0)], Color: darkblue
++    Polyomino: [(0, 7, 0), (0, 7, 1), (1, 7, 0), (2, 6, 0), (2, 7, 0)], Color: orange
++    Polyomino: [(0, 6, 1), (1, 5, 1), (1, 6, 0), (1, 6, 1), (1, 7, 1)], Color: gray
+ 
+ To get all the solutions, use the iterator returned by the ``solve``
+ method. Note that finding the first solution is the most time consuming
+@@ -483,22 +483,22 @@
+         The explicit solution::
+ 
+             sage: for p in s: p                                  # long time (fast)
+-            Polyomino: [(0, 0, 0), (1, 0, 0), (1, 1, 0), (1, 1, 1), (1, 2, 0)], Color: deeppink
+-            Polyomino: [(0, 0, 1), (0, 1, 0), (0, 1, 1), (0, 2, 1), (1, 2, 1)], Color: deeppink
+-            Polyomino: [(0, 2, 0), (0, 3, 0), (0, 4, 0), (1, 4, 0), (1, 4, 1)], Color: green
+-            Polyomino: [(0, 3, 1), (1, 3, 1), (2, 2, 0), (2, 2, 1), (2, 3, 1)], Color: green
+-            Polyomino: [(1, 3, 0), (2, 3, 0), (2, 4, 0), (2, 4, 1), (3, 4, 0)], Color: red
+-            Polyomino: [(1, 0, 1), (2, 0, 0), (2, 0, 1), (2, 1, 0), (3, 0, 1)], Color: midnightblue
+-            Polyomino: [(0, 4, 1), (0, 5, 0), (0, 5, 1), (0, 6, 0), (1, 5, 0)], Color: red
+-            Polyomino: [(2, 1, 1), (3, 0, 0), (3, 1, 0), (3, 1, 1), (4, 0, 0)], Color: blue
+-            Polyomino: [(3, 2, 0), (4, 0, 1), (4, 1, 0), (4, 1, 1), (4, 2, 0)], Color: purple
+-            Polyomino: [(3, 2, 1), (3, 3, 0), (4, 2, 1), (4, 3, 0), (4, 3, 1)], Color: yellow
+-            Polyomino: [(3, 3, 1), (3, 4, 1), (4, 4, 0), (4, 4, 1), (4, 5, 0)], Color: blue
+-            Polyomino: [(0, 6, 1), (0, 7, 0), (0, 7, 1), (1, 5, 1), (1, 6, 1)], Color: purple
+-            Polyomino: [(1, 6, 0), (1, 7, 0), (1, 7, 1), (2, 7, 0), (3, 7, 0)], Color: darkblue
+-            Polyomino: [(2, 5, 0), (2, 6, 0), (3, 6, 0), (4, 6, 0), (4, 6, 1)], Color: orange
+-            Polyomino: [(2, 5, 1), (3, 5, 0), (3, 5, 1), (3, 6, 1), (4, 5, 1)], Color: gray
+-            Polyomino: [(2, 6, 1), (2, 7, 1), (3, 7, 1), (4, 7, 0), (4, 7, 1)], Color: orange
++            Polyomino: [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 2, 0), (1, 1, 0)], Color: deeppink
++            Polyomino: [(0, 1, 1), (1, 0, 1), (1, 1, 1), (1, 2, 0), (1, 2, 1)], Color: deeppink
++            Polyomino: [(0, 2, 1), (0, 3, 1), (0, 4, 0), (0, 4, 1), (1, 4, 0)], Color: green
++            Polyomino: [(0, 3, 0), (1, 3, 0), (2, 2, 1), (2, 3, 0), (2, 3, 1)], Color: green
++            Polyomino: [(1, 3, 1), (1, 4, 1), (2, 4, 0), (2, 4, 1), (2, 5, 1)], Color: red
++            Polyomino: [(1, 0, 0), (2, 0, 0), (2, 0, 1), (2, 1, 1), (3, 0, 1)], Color: red
++            Polyomino: [(3, 0, 0), (4, 0, 0), (4, 0, 1), (4, 1, 0), (4, 2, 0)], Color: darkblue
++            Polyomino: [(2, 1, 0), (2, 2, 0), (3, 1, 0), (3, 1, 1), (4, 1, 1)], Color: purple
++            Polyomino: [(3, 2, 0), (3, 3, 0), (3, 3, 1), (3, 4, 0), (4, 3, 0)], Color: gray
++            Polyomino: [(3, 2, 1), (4, 2, 1), (4, 3, 1), (4, 4, 0), (4, 4, 1)], Color: orange
++            Polyomino: [(3, 4, 1), (3, 5, 1), (4, 5, 0), (4, 5, 1), (4, 6, 0)], Color: blue
++            Polyomino: [(3, 6, 0), (3, 7, 0), (4, 6, 1), (4, 7, 0), (4, 7, 1)], Color: yellow
++            Polyomino: [(1, 5, 0), (2, 5, 0), (2, 6, 0), (2, 6, 1), (3, 5, 0)], Color: midnightblue
++            Polyomino: [(1, 7, 0), (2, 7, 0), (2, 7, 1), (3, 6, 1), (3, 7, 1)], Color: purple
++            Polyomino: [(0, 5, 1), (0, 6, 1), (0, 7, 0), (0, 7, 1), (1, 5, 1)], Color: orange
++            Polyomino: [(0, 5, 0), (0, 6, 0), (1, 6, 0), (1, 6, 1), (1, 7, 1)], Color: blue
+ 
+         Enumerate the solutions::
+ 
 diff --git a/sage/groups/libgap_mixin.py b/sage/groups/libgap_mixin.py
 --- a/sage/groups/libgap_mixin.py
 +++ b/sage/groups/libgap_mixin.py

trac_14375_ansi_escapes_indication.2.patch

-# HG changeset patch
-# User Volker Braun <vbraun@stp.dias.ie>
-# Date 1364338386 -3600
-# Node ID 408b9532187cb64af222f3be6299bed2d28b4687
-# Parent d36b7ed7a101997566257ac68a02393c6c2a2076
-Mention in got<->want diff that there are ansi escape sequences
-
-diff --git a/sage/doctest/parsing.py b/sage/doctest/parsing.py
---- a/sage/doctest/parsing.py
-+++ b/sage/doctest/parsing.py
-@@ -33,6 +33,18 @@
- backslash_replacer = re.compile(r"""(\s*)sage:(.*)\\\ *
- \ *(((\.){4}:)|((\.){3}))?\ *""")
- 
-+
-+# This is the correct pattern to match ISO/IEC 6429 ANSI escape sequences:
-+#
-+#ansi_escape_sequence = re.compile(r'(\x1b[@-Z\\-~]|\x1b\[.*?[@-~]|\x9b.*?[@-~])')
-+#
-+# We use this incorrect version to avoid accidental matches for \x9b
-+# in UTF-8 bytestrings, even though there are none in the Sage
-+# library. Once we have a unicode-aware doctest framework, we should
-+# use the correct pattern including \x9b
-+ansi_escape_sequence = re.compile(r'(\x1b[@-Z\\-~]|\x1b\[.*?[@-~])')
-+
-+
- def parse_optional_tags(string):
-     """
-     Returns a set consisting of the optional tags from the following
-@@ -579,6 +591,36 @@
-         sage: OC.check_output(ex.want, 'x + 0.8935153492877', optflag)
-         False
-     """
-+    def human_readable_escape_sequences(self, string):
-+        """
-+        Make ANSI escape sequences human readable.
-+    
-+        EXAMPLES::
-+
-+            sage: print 'This ist \x1b[1mbold\x1b[0m text'
-+            This ist <CSI-1m>bold<CSI-0m> text
-+
-+        TESTS::
-+        
-+            sage: from sage.doctest.parsing import SageOutputChecker
-+            sage: OC = SageOutputChecker()
-+            sage: teststr = '-'.join([
-+            ...       'bold\x1b[1m', 
-+            ...       'newlinemode\x9b20h', 
-+            ...       'red\x1b[31m',
-+            ...       'oscmd\x1ba'])
-+            sage: OC.human_readable_escape_sequences(teststr)
-+            'bold<CSI-1m>-newlinemode\x9b20h-red<CSI-31m>-oscmd<ESC-a>'
-+        """
-+        def human_readable(match):
-+            ansi_escape = match.group(1)
-+            assert len(ansi_escape) >= 2
-+            if len(ansi_escape) == 2:
-+                return '<ESC-'+ansi_escape[1]+'>'
-+            else:
-+                return '<CSI-'+ansi_escape.lstrip('\x1b[\x9b')+'>'
-+        return ansi_escape_sequence.subn(human_readable, string)[0]
-+
-     def check_output(self, want, got, optionflags):
-         """
-         Checks to see if the output matches the desired output.
-@@ -674,6 +716,7 @@
-             sage: print "1.000009"   # abs tol 1e-5
-             1.0
-         """
-+        got = self.human_readable_escape_sequences(got)
-         if isinstance(want, MarkedOutput):
-             if want.random:
-                 return True
-@@ -817,6 +860,7 @@
-             Tolerance exceeded: infinity > 1e-01
- 
-         """
-+        got = self.human_readable_escape_sequences(got)
-         want = example.want
-         diff = doctest.OutputChecker.output_difference(self, example, got, optionflags)
-         if isinstance(want, MarkedOutput) and (want.tol or want.abs_tol or want.rel_tol):

trac_14523_improve_attach.patch

 # HG changeset patch
-# Parent b4db5e332c582a8b104cf14494d5aeda84295792
+# Parent 9b20ae7695f0ec58dfdbea451c1707e41d5aa452
 
 Improve attach()
 
 diff --git a/sage/misc/all.py b/sage/misc/all.py
 --- a/sage/misc/all.py
 +++ b/sage/misc/all.py
-@@ -28,7 +28,7 @@
+@@ -1,3 +1,6 @@
++from lazy_attribute import lazy_attribute, lazy_class_attribute
++from lazy_import import lazy_import
++
+ from misc import (alarm, ellipsis_range, ellipsis_iter, srange, xsrange, sxrange, getitem,
+                   cputime, verbose, set_verbose, set_verbose_files,
+                   get_verbose_files, unset_verbose_files, get_verbose, 
+@@ -28,7 +31,7 @@
  
  from map_threaded import map_threaded
  
  
  from remote_file import get_remote_file
  
-@@ -65,7 +65,9 @@
+@@ -65,7 +68,11 @@
  
  from defaults import set_default_variable_name
  
 -from preparser import preparse, implicit_multiplication, BackslashOperator, attached_files, detach, load_attach_path, reset_load_attach_path, load_attach_mode
 +from preparser import preparse, implicit_multiplication, BackslashOperator
 +
-+from attached_files import attach, detach, attached_files, load_attach_path, reset_load_attach_path, load_attach_mode
++lazy_import('sage.misc.attached_files', [
++        'attach', 'detach', 'attached_files', 'load_attach_path', 
++        'reset_load_attach_path', 'load_attach_mode'])
  
  from interpreter import preparser
  
+@@ -157,11 +164,6 @@
+ 
+ from cachefunc import CachedFunction, cached_function, cached_method, cached_in_parent_method, disk_cached_function
+ 
+-from lazy_attribute import lazy_attribute, lazy_class_attribute
+-
+-
+-from lazy_import import lazy_import
+-
+ from abstract_method import abstract_method
+ 
+ from randstate import seed, set_random_seed, initial_seed, current_randstate
 diff --git a/sage/misc/attach.py b/sage/misc/attach.py
 deleted file mode 100644
 --- a/sage/misc/attach.py
 new file mode 100644
 --- /dev/null
 +++ b/sage/misc/attached_files.py
-@@ -0,0 +1,523 @@
+@@ -0,0 +1,589 @@
 +"""
 +Keep track of attached files
++
++TESTS::
++
++    sage: attach('http://wstein.org/loadtest.py')
++    Traceback (most recent call last):
++    ...
++    NotImplementedError: you can't attach a URL
++
++Check that no file clutter is produced::
++
++    sage: dir = tmp_dir()
++    sage: src = os.path.join(dir, 'foobar.sage')
++    sage: with open(src, 'w') as f:
++    ....:     f.write('print "<output from attached file>"\n')
++    sage: attach(src)
++    <output from attached file>
++    sage: os.listdir(dir)
++    ['foobar.sage']
++    sage: detach(src)
++    
++In debug mode backtraces contain code snippets. We need to manually
++print the traceback because the python doctest module has special
++support for exceptions and does not match them
++character-by-character::
++
++    sage: import traceback
++    sage: with open(src, 'w') as f:
++    ....:     f.write('print "first"\n')
++    ....:     f.write('print "second"\n')
++    ....:     f.write('raise ValueError("third")   # this should appear in the source snippet\n')
++    ....:     f.write('print "fourth"\n')
++
++    sage: load_attach_mode(attach_debug=False)
++    sage: try:
++    ....:     attach(src)
++    ....: except StandardError:
++    ....:     print 'EXCEPTION'
++    ....:     traceback.print_exc()
++    first
++    second
++    EXCEPTION
++    Traceback (most recent call last):
++    ...
++        exec preparse_file(open(fpath).read()) + "\n" in globals
++      File "<string>", line 3, in <module>
++    ValueError: third
++    sage: detach(src)
++
++    sage: load_attach_mode(attach_debug=True)
++    sage: try:
++    ....:     attach(src)
++    ....: except StandardError:
++    ....:     print 'EXCEPTION'
++    ....:     traceback.print_exc()
++    first
++    second
++    EXCEPTION
++    ...
++        execfile(preparse_file_named(fpath), globals)
++      File ".../foobar.sage....py", line ..., in <module>
++        raise ValueError("third")   # this should appear in the source snippet
++    ValueError: third
++    sage: detach(src)
 +"""
 +
 +###########################################################################
 +    At startup, debug mode is ``True`` for attaching and ``False``
 +    for loading.
 +
++    .. NOTE::
++
++        This function should really be deprecated and code executed
++        from memory should raise proper tracebacks.
++
 +    INPUT:
 +
 +    - ``load_debug`` -- boolean or ``None`` (default); if not
 +
 +    EXAMPLES::
 +    
-+    EXAMPLES::
-+    
 +        sage: sage.misc.attached_files.reset()
 +        sage: from sage.misc.interpreter import get_test_shell
 +        sage: shell = get_test_shell()
  
  implicit_mul_level = False
  numeric_literal_prefix = '_sage_const_'
-@@ -1137,24 +1139,7 @@
+@@ -833,7 +835,8 @@
+         vars = ','.join(stripped_vars)
+ 
+         new_code.append(code[last_end:m.start()])
+-        new_code.append(';%s__tmp__=var("%s"); %s = symbolic_expression(%s).function(%s)' % (ident, vars, func, expr, vars))
++        new_code.append(';%s__tmp__=var("%s"); %s = symbolic_expression(%s).function(%s)' % 
++                        (ident, vars, func, expr, vars))
+         last_end = m.end()
+ 
+     if last_end == 0:
+@@ -983,7 +986,8 @@
+             pass
+         gens_tuple = "(%s,)" % ', '.join(gens)
+         new_code.append(code[last_end:m.start()])
+-        new_code.append(";%s%s%s = %s; %s = %s._first_ngens(%s)" % (ident, obj, other_objs, constructor, gens_tuple, obj, len(gens)))
++        new_code.append(";%s%s%s = %s; %s = %s._first_ngens(%s)" % 
++                        (ident, obj, other_objs, constructor, gens_tuple, obj, len(gens)))
+         last_end = m.end()
+         
+     if last_end == 0:
+@@ -1137,24 +1141,7 @@
  ## Apply the preparser to an entire file
  ######################################################
  
      """
      Preparses input, attending to numeric literals and load/attach
      file directives.
-@@ -1187,21 +1172,12 @@
+@@ -1187,21 +1174,12 @@
          _sage_const_100 = Integer(100)
          type(100 ), type(_sage_const_100 )
      """
      # We keep track of which files have been loaded so far
      # in order to avoid a recursive load that would result
      # in creating a massive file and crashing.
-@@ -1444,54 +1420,6 @@
+@@ -1444,54 +1422,6 @@
          return True
      return False
  
  def load_cython(name):
      import cython
      cur = os.path.abspath(os.curdir)
-@@ -1613,7 +1541,7 @@
+@@ -1613,35 +1543,29 @@
      out.write("# -*- coding: utf-8 -*-\n")
      return contents
      
      r"""
      Preparse file named \code{name} (presumably a .sage file), outputting to
      stream \code{out}.
-@@ -1624,7 +1552,7 @@
-     os.chdir(dir)
+     """
+     name = os.path.abspath(name)
+-    dir, _ = os.path.split(name)
+-    cur = os.path.abspath(os.curdir)
+-    os.chdir(dir)
      contents = open(name).read()
      contents = handle_encoding_declaration(contents, out)
 -    parsed = preparse_file(contents, run_attached=run_attached) 
+-    os.chdir(cur)
+-    out.write("# -*- encoding: utf-8 -*-\n")
 +    parsed = preparse_file(contents) 
-     os.chdir(cur)
-     out.write("# -*- encoding: utf-8 -*-\n")
      out.write('#'*70+'\n')
-@@ -1632,7 +1560,7 @@
+     out.write('# This file was *autogenerated* from the file %s.\n' % name)
      out.write('#'*70+'\n')
      out.write(parsed)
  
      r"""
      Preparse file named \code{name} (presumably a .sage file), outputting to a
      temporary file.  Returns name of temporary file.
-@@ -1641,7 +1569,7 @@
-     name = os.path.abspath(name)
-     tmpfilename = os.path.abspath(sage.misc.misc.tmp_filename(name) + ".py")
-     out = open(tmpfilename,'w')
+     """
+-    import sage.misc.misc
+-    name = os.path.abspath(name)
+-    tmpfilename = os.path.abspath(sage.misc.misc.tmp_filename(name) + ".py")
+-    out = open(tmpfilename,'w')
 -    preparse_file_named_to_stream(name, out, run_attached=run_attached)
++    from sage.misc.misc import tmp_filename
++    tmpfilename = tmp_filename(os.path.basename(name)) + '.py'
++    out = open(tmpfilename, 'w')
 +    preparse_file_named_to_stream(name, out)
      out.close()
      return tmpfilename
  
-@@ -1733,7 +1661,7 @@
+@@ -1733,7 +1657,7 @@
          sage: open(t,'w').write("print 'hello world'")
          sage: sage.misc.preparser.load(t, globals(), attach=True)
          hello world
          True
  
      You can't attach remote URLs (yet)::
-@@ -1747,7 +1675,7 @@
+@@ -1747,7 +1671,7 @@
      current working directory, i.e., ``'.'``.  But you can modify the
      path with :func:`load_attach_path`::
  
          sage: load_attach_path()
          ['.']
          sage: t_dir = tmp_dir()
-@@ -1756,7 +1684,7 @@
+@@ -1756,7 +1680,7 @@
          sage: load_attach_path(t_dir)
          sage: attach('test.py')
          111
  
      or by setting the environment variable ``SAGE_LOAD_ATTACH_PATH``
      to a colon-separated list before starting Sage::
-@@ -1772,6 +1700,12 @@
+@@ -1772,6 +1696,12 @@
          sage: sage.misc.preparser.load(t, globals())
          2
      """
      try:
          filename = eval(filename, globals)
      except Exception:
-@@ -1809,8 +1743,8 @@
+@@ -1809,8 +1739,8 @@
          if not os.path.exists(fpath):
              raise IOError('did not find file %r to load or attach' % filename)
      else:
              fpath = os.path.join(path, filename)
              fpath = os.path.expanduser(fpath)
              if os.path.exists(fpath):
-@@ -1820,19 +1754,25 @@
+@@ -1820,19 +1750,25 @@
                  % filename)
  
      if fpath.endswith('.py'):
          execfile(fpath, globals)
      elif fpath.endswith('.sage'):
 +        from sage.misc.attached_files import load_attach_mode
-+        attach_debug_mode, load_debug_mode = load_attach_mode()
++        load_debug_mode, attach_debug_mode = load_attach_mode()
          if (attach and attach_debug_mode) or ((not attach) and load_debug_mode):
              # Preparse to a file to enable tracebacks with
              # code snippets. Use preparse_file_named to make