From b12a3070dfd55041756c011ac1c6399819d422f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Chapoton?= Date: Mon, 20 Mar 2023 20:22:52 +0100 Subject: [PATCH 1/2] fixing some E502 outside of schemes and combinat --- .../affine_lie_conformal_algebra.py | 18 ++--- .../bosonic_ghosts_lie_conformal_algebra.py | 24 ++++--- .../fermionic_ghosts_lie_conformal_algebra.py | 32 +++++---- .../lie_conformal_algebra_element.py | 20 +++--- ..._conformal_algebra_with_structure_coefs.py | 40 +++++------ .../neveu_schwarz_lie_conformal_algebra.py | 18 ++--- .../weyl_lie_conformal_algebra.py | 34 +++++---- src/sage/categories/drinfeld_modules.py | 4 +- src/sage/coding/linear_code_no_metric.py | 11 ++- src/sage/crypto/mq/rijndael_gf.py | 38 +++++----- src/sage/databases/sql_db.py | 57 +++++++-------- src/sage/functions/wigner.py | 12 ++-- src/sage/groups/finitely_presented.py | 6 +- src/sage/interfaces/maxima_abstract.py | 6 +- src/sage/interfaces/rubik.py | 40 +++++------ src/sage/interfaces/singular.py | 8 +-- src/sage/libs/ntl/all.py | 25 +++---- .../differentiable/affine_connection.py | 15 ++-- .../manifolds/differentiable/mixed_form.py | 22 +++--- src/sage/misc/map_threaded.py | 5 +- .../quadratic_form__equivalence_testing.py | 60 ++++++++-------- .../quadratic_form__reduction_theory.py | 69 +++++++++---------- .../quadratic_forms/quadratic_form__theta.py | 22 +++--- .../drinfeld_modules/drinfeld_module.py | 4 +- src/sage/symbolic/assumptions.py | 8 +-- 25 files changed, 294 insertions(+), 304 deletions(-) diff --git a/src/sage/algebras/lie_conformal_algebras/affine_lie_conformal_algebra.py b/src/sage/algebras/lie_conformal_algebras/affine_lie_conformal_algebra.py index 2cd0e9fe2c4..9fdf888fe39 100644 --- a/src/sage/algebras/lie_conformal_algebras/affine_lie_conformal_algebra.py +++ b/src/sage/algebras/lie_conformal_algebras/affine_lie_conformal_algebra.py @@ -107,24 +107,24 @@ def __init__(self, R, ct, names=None, prefix=None, bracket=None): if S.rank(k2) <= S.rank(k1): myb = B[k1].bracket(B[k2]).monomial_coefficients() myf = R(2).inverse_of_unit()*R(hv).inverse_of_unit()\ - *g.killing_form(B[k1],B[k2]) + * g.killing_form(B[k1], B[k2]) if myb or myf: - gdict[(k1,k2)] = {} + gdict[(k1, k2)] = {} if myb: - gdict[(k1,k2)][0] = {(nk,0):v for nk,v in \ - myb.items()} + gdict[(k1, k2)][0] = {(nk, 0): v + for nk, v in myb.items()} if myf: - gdict[(k1,k2)][1] = {('K',0):myf} + gdict[(k1, k2)][1] = {('K', 0): myf} - weights = (1,)*B.cardinality() + weights = (1,) * B.cardinality() self._ct = ct if prefix is None and names is None: prefix = 'B' GradedLieConformalAlgebra.__init__(self, - R, gdict, index_set=S, - central_elements=('K',), weights=weights, - names=names, prefix=prefix,bracket=bracket) + R, gdict, index_set=S, + central_elements=('K',), weights=weights, + names=names, prefix=prefix, bracket=bracket) def cartan_type(self): """ diff --git a/src/sage/algebras/lie_conformal_algebras/bosonic_ghosts_lie_conformal_algebra.py b/src/sage/algebras/lie_conformal_algebras/bosonic_ghosts_lie_conformal_algebra.py index e5cddaed759..178493b13e8 100644 --- a/src/sage/algebras/lie_conformal_algebras/bosonic_ghosts_lie_conformal_algebra.py +++ b/src/sage/algebras/lie_conformal_algebras/bosonic_ghosts_lie_conformal_algebra.py @@ -87,29 +87,31 @@ def __init__(self, R, ngens=2, names=None, index_set=None): """ from sage.rings.integer_ring import ZZ try: - assert (ngens in ZZ and ngens > 0 and ngens % 2 == 0) + assert (ngens in ZZ and ngens > 0 and not ngens % 2) except AssertionError: raise ValueError("ngens should be an even positive integer, " + "got {}".format(ngens)) latex_names = None + half = ngens // 2 if (names is None) and (index_set is None): from sage.misc.defaults import variable_names as varnames from sage.misc.defaults import latex_variable_names as laxnames - names = varnames(ngens/2,'beta') + varnames(ngens/2,'gamma') - latex_names = tuple(laxnames(ngens/2,r'\beta') +\ - laxnames(ngens/2,r'\gamma')) + ('K',) + names = varnames(half, 'beta') + varnames(half, 'gamma') + latex_names = tuple(laxnames(half, r'\beta') + + laxnames(half, r'\gamma')) + ('K',) - names,index_set = standardize_names_index_set(names=names, + names, index_set = standardize_names_index_set(names=names, index_set=index_set, ngens=ngens) - A = identity_matrix(R, ngens // 2) + A = identity_matrix(R, half) from sage.matrix.special import block_matrix - gram_matrix = block_matrix([[R.zero(),A],[-A,R.zero()]]) - ghostsdict = { (i,j): {0: {('K',0): gram_matrix[index_set.rank(i), - index_set.rank(j)]}} for i in index_set for j in index_set} - weights = (1,)*(ngens//2) + (0,)*(ngens//2) + gram_matrix = block_matrix([[R.zero(), A], [-A, R.zero()]]) + ghostsdict = {(i, j): {0: {('K', 0): gram_matrix[index_set.rank(i), + index_set.rank(j)]}} + for i in index_set for j in index_set} + weights = (1,) * half + (0,) * half super().__init__(R, - ghostsdict,names=names, + ghostsdict, names=names, latex_names=latex_names, index_set=index_set, weights=weights, diff --git a/src/sage/algebras/lie_conformal_algebras/fermionic_ghosts_lie_conformal_algebra.py b/src/sage/algebras/lie_conformal_algebras/fermionic_ghosts_lie_conformal_algebra.py index 4a74d9f9357..e6bca4de671 100644 --- a/src/sage/algebras/lie_conformal_algebras/fermionic_ghosts_lie_conformal_algebra.py +++ b/src/sage/algebras/lie_conformal_algebras/fermionic_ghosts_lie_conformal_algebra.py @@ -80,33 +80,35 @@ def __init__(self,R,ngens=2,names=None,index_set=None): sage: TestSuite(V).run() """ try: - assert (ngens > 0 and ngens % 2 == 0) + assert (ngens > 0 and not ngens % 2) except AssertionError: raise ValueError("ngens should be an even positive integer, " + "got {}".format(ngens)) latex_names = None + half = ngens // 2 if (names is None) and (index_set is None): from sage.misc.defaults import variable_names as varnames from sage.misc.defaults import latex_variable_names as laxnames - names = varnames(ngens/2,'b') + varnames(ngens/2,'c') - latex_names = tuple(laxnames(ngens/2,'b') +\ - laxnames(ngens/2,'c')) + ('K',) + names = varnames(half, 'b') + varnames(half, 'c') + latex_names = tuple(laxnames(half, 'b') + + laxnames(half, 'c')) + ('K',) from sage.structure.indexed_generators import \ - standardize_names_index_set - names,index_set = standardize_names_index_set(names=names, - index_set=index_set, - ngens=ngens) + standardize_names_index_set + names, index_set = standardize_names_index_set(names=names, + index_set=index_set, + ngens=ngens) from sage.matrix.special import identity_matrix - A = identity_matrix(R, ngens // 2) + A = identity_matrix(R, half) from sage.matrix.special import block_matrix - gram_matrix = block_matrix([[R.zero(),A],[A,R.zero()]]) - ghostsdict = { (i,j): {0: {('K',0): gram_matrix[index_set.rank(i), - index_set.rank(j)]}} for i in index_set for j in index_set} - weights = (1,)*(ngens//2) + (0,)*(ngens//2) - parity = (1,)*ngens + gram_matrix = block_matrix([[R.zero(), A], [A, R.zero()]]) + ghostsdict = {(i, j): {0: {('K', 0): gram_matrix[index_set.rank(i), + index_set.rank(j)]}} + for i in index_set for j in index_set} + weights = (1,) * half + (0,) * half + parity = (1,) * ngens super().__init__(R, - ghostsdict,names=names, + ghostsdict, names=names, latex_names=latex_names, index_set=index_set, weights=weights, diff --git a/src/sage/algebras/lie_conformal_algebras/lie_conformal_algebra_element.py b/src/sage/algebras/lie_conformal_algebras/lie_conformal_algebra_element.py index d10426501f2..02c25a67297 100644 --- a/src/sage/algebras/lie_conformal_algebras/lie_conformal_algebra_element.py +++ b/src/sage/algebras/lie_conformal_algebras/lie_conformal_algebra_element.py @@ -121,23 +121,23 @@ def _bracket_(self, right): if self.is_zero() or right.is_zero(): return {} s_coeff = p._s_coeff - a,k = self.index() - coefa = self.monomial_coefficients()[(a,k)] - b,m = right.index() - coefb = right.monomial_coefficients()[(b,m)] + a, k = self.index() + coefa = self.monomial_coefficients()[(a, k)] + b, m = right.index() + coefb = right.monomial_coefficients()[(b, m)] try: - mbr = dict(s_coeff[(a,b)]) + mbr = dict(s_coeff[(a, b)]) except KeyError: return {} pole = max(mbr.keys()) - ret = {l: coefa*coefb*(-1)**k/factorial(k)*sum(factorial(l)\ - /factorial(m+k+j-l)/factorial(l-k-j)/factorial(j)*\ - mbr[j].T(m+k+j-l) for j in mbr if j >= l-m-k and\ + ret = {l: coefa*coefb*(-1)**k/factorial(k)*sum(factorial(l) + /factorial(m+k+j-l)/factorial(l-k-j)/factorial(j)* + mbr[j].T(m+k+j-l) for j in mbr if j >= l-m-k and j <= l-k) for l in range(m+k+pole+1)} return {k: v for k, v in ret.items() if v} - diclist = [i._bracket_(j) for i in self.terms() for - j in right.terms()] + diclist = [i._bracket_(j) for i in self.terms() + for j in right.terms()] ret = {} pz = p.zero() for d in diclist: diff --git a/src/sage/algebras/lie_conformal_algebras/lie_conformal_algebra_with_structure_coefs.py b/src/sage/algebras/lie_conformal_algebras/lie_conformal_algebra_with_structure_coefs.py index 46119ad45f1..a4669506314 100644 --- a/src/sage/algebras/lie_conformal_algebras/lie_conformal_algebra_with_structure_coefs.py +++ b/src/sage/algebras/lie_conformal_algebras/lie_conformal_algebra_with_structure_coefs.py @@ -158,18 +158,18 @@ def _standardize_s_coeff(s_coeff, index_set, ce, parity=None): if lth_product: vals[l]=lth_product - myvals = tuple([(k,tuple(v.items())) for k,v in vals.items() if v]) + myvals = tuple((k, tuple(v.items())) for k, v in vals.items() if v) if key in sc.keys() and sorted(sc[key]) != sorted(myvals): - raise ValueError("two distinct values given for one "\ - "and the same bracket, skew-symmetry"\ + raise ValueError("two distinct values given for one " + "and the same bracket, skew-symmetry" "is not satisfied?") if myvals: sc[key] = myvals - #We now add the skew-symmetric part to optimize - #brackets computations later - key=(mypair[1],mypair[0]) + # We now add the skew-symmetric part to optimize + # brackets computations later + key = (mypair[1], mypair[0]) if index_to_parity[mypair[0]]*index_to_parity[mypair[1]]: parsgn = -1 else: @@ -191,11 +191,11 @@ def _standardize_s_coeff(s_coeff, index_set, ce, parity=None): if kth_product: vals[k]=kth_product - myvals = tuple([(k,tuple(v.items())) for k,v in vals.items() if v]) + myvals = tuple((k, tuple(v.items())) for k, v in vals.items() if v) if key in sc.keys() and sorted(sc[key]) != sorted(myvals): - raise ValueError("two distinct values given for one "\ - "and the same bracket. "\ + raise ValueError("two distinct values given for one " + "and the same bracket. " "Skew-symmetry is not satisfied?") if myvals: sc[key] = myvals @@ -233,31 +233,31 @@ def __init__(self, R, s_coeff, index_set=None, central_elements=None, # index_set pass - issuper=kwds.pop('super', False) + issuper = kwds.pop('super', False) if parity is None: - parity = (0,)*index_set.cardinality() + parity = (0,) * index_set.cardinality() else: issuper = True try: assert len(parity) == index_set.cardinality() except AssertionError: - raise ValueError("parity should have the same length as the "\ - "number of generators, got {}".format(parity)) + raise ValueError("parity should have the same length as the " + f"number of generators, got {parity}") s_coeff = LieConformalAlgebraWithStructureCoefficients\ - ._standardize_s_coeff(s_coeff, index_set, central_elements, - parity) + ._standardize_s_coeff(s_coeff, index_set, central_elements, + parity) if names is not None and central_elements is not None: names += tuple(central_elements) - self._index_to_pos = {k: i for i,k in enumerate(index_set)} - #Add central parameters to index_to_pos so that we can - #represent names + self._index_to_pos = {k: i for i, k in enumerate(index_set)} + # Add central parameters to index_to_pos so that we can + # represent names if central_elements is not None: - for i,ce in enumerate(central_elements): - self._index_to_pos[ce] = len(index_set)+i + for i, ce in enumerate(central_elements): + self._index_to_pos[ce] = len(index_set) + i default_category = LieConformalAlgebras(R).WithBasis().FinitelyGenerated() if issuper: diff --git a/src/sage/algebras/lie_conformal_algebras/neveu_schwarz_lie_conformal_algebra.py b/src/sage/algebras/lie_conformal_algebras/neveu_schwarz_lie_conformal_algebra.py index d581558aafa..8f5756f993f 100644 --- a/src/sage/algebras/lie_conformal_algebras/neveu_schwarz_lie_conformal_algebra.py +++ b/src/sage/algebras/lie_conformal_algebras/neveu_schwarz_lie_conformal_algebra.py @@ -57,15 +57,17 @@ def __init__(self, R): sage: V = lie_conformal_algebras.NeveuSchwarz(QQ) sage: TestSuite(V).run() """ - nsdict = {('L','L'):{0:{('L',1):1}, 1:{('L',0): 2}, - 3:{('C', 0):R(2).inverse_of_unit()}}, - ('L','G'):{0:{('G',1):1}, 1:{('G',0):R(3)*R(2).\ - inverse_of_unit()}}, ('G','G'): {0:{('L',0):2}, - 2:{('C',0):R(2)*R(3).inverse_of_unit()}}} + nsdict = {('L', 'L'): {0: {('L', 1): 1}, + 1: {('L', 0): 2}, + 3: {('C', 0): R(2).inverse_of_unit()}}, + ('L', 'G'): {0: {('G', 1): 1}, + 1: {('G', 0): R(3) * R(2).inverse_of_unit()}}, + ('G', 'G'): {0: {('L', 0): 2}, + 2: {('C', 0): R(2) * R(3).inverse_of_unit()}}} from sage.rings.rational_field import QQ - weights = (2,QQ(3/2)) - parity = (0,1) - GradedLieConformalAlgebra.__init__(self, R, nsdict, names=('L','G'), + weights = (2, QQ((3, 2))) + parity = (0, 1) + GradedLieConformalAlgebra.__init__(self, R, nsdict, names=('L', 'G'), central_elements=('C',), weights=weights, parity=parity) def _repr_(self): diff --git a/src/sage/algebras/lie_conformal_algebras/weyl_lie_conformal_algebra.py b/src/sage/algebras/lie_conformal_algebras/weyl_lie_conformal_algebra.py index ee47970a31f..c51ed309ca5 100644 --- a/src/sage/algebras/lie_conformal_algebras/weyl_lie_conformal_algebra.py +++ b/src/sage/algebras/lie_conformal_algebras/weyl_lie_conformal_algebra.py @@ -119,7 +119,7 @@ class WeylLieConformalAlgebra(LieConformalAlgebraWithStructureCoefficients): [0 1 0] [0 0 1] """ - def __init__(self,R,ngens=None, gram_matrix=None, names=None, + def __init__(self, R, ngens=None, gram_matrix=None, names=None, index_set=None): """ Initialize self. @@ -131,31 +131,29 @@ def __init__(self,R,ngens=None, gram_matrix=None, names=None, """ from sage.matrix.matrix_space import MatrixSpace if ngens: - try: - from sage.rings.integer_ring import ZZ - assert ngens in ZZ and ngens % 2 == 0 - except AssertionError: - raise ValueError("ngens needs to be an even positive "+ - "Integer, got {}".format(ngens)) - if (gram_matrix is not None): + from sage.rings.integer_ring import ZZ + if not(ngens in ZZ and not ngens % 2): + raise ValueError("ngens needs to be an even positive Integer, " + f"got {ngens}") + if gram_matrix is not None: if ngens is None: ngens = gram_matrix.dimensions()[0] try: - assert (gram_matrix in MatrixSpace(R,ngens,ngens)) + assert (gram_matrix in MatrixSpace(R, ngens, ngens)) except AssertionError: - raise ValueError("The gram_matrix should be a skew-symmetric "+ - "{0} x {0} matrix, got {1}".format(ngens,gram_matrix)) - if (not gram_matrix.is_skew_symmetric()) or \ - (gram_matrix.is_singular()): - raise ValueError("The gram_matrix should be a non degenerate " + - "skew-symmetric {0} x {0} matrix, got {1}"\ - .format(ngens,gram_matrix)) - elif (gram_matrix is None): + raise ValueError("The gram_matrix should be a skew-symmetric " + "{0} x {0} matrix, got {1}".format(ngens, gram_matrix)) + if (not gram_matrix.is_skew_symmetric() or + gram_matrix.is_singular()): + raise ValueError("The gram_matrix should be a non degenerate " + "skew-symmetric {0} x {0} matrix, got {1}" + .format(ngens, gram_matrix)) + elif gram_matrix is None: if ngens is None: ngens = 2 A = identity_matrix(R, ngens // 2) from sage.matrix.special import block_matrix - gram_matrix = block_matrix([[R.zero(),A],[-A,R.zero()]]) + gram_matrix = block_matrix([[R.zero(), A], [-A, R.zero()]]) latex_names = None if (names is None) and (index_set is None): diff --git a/src/sage/categories/drinfeld_modules.py b/src/sage/categories/drinfeld_modules.py index 08613d2d14a..5138586378e 100644 --- a/src/sage/categories/drinfeld_modules.py +++ b/src/sage/categories/drinfeld_modules.py @@ -423,7 +423,7 @@ def characteristic(self): 0 """ if self._characteristic is None: - raise NotImplementedError('function ring characteristic not ' \ + raise NotImplementedError('function ring characteristic not ' 'implemented in this case') return self._characteristic @@ -496,7 +496,7 @@ def object(self, gen): gen = self._ore_polring(gen) T = self._function_ring.gen() if gen[0] != self._base_morphism(T): - raise ValueError('constant coefficient must equal that of the ' \ + raise ValueError('constant coefficient must equal that of the ' 'category') return DrinfeldModule(self._function_ring, gen) diff --git a/src/sage/coding/linear_code_no_metric.py b/src/sage/coding/linear_code_no_metric.py index 932ad7ad937..d006ce17e3e 100644 --- a/src/sage/coding/linear_code_no_metric.py +++ b/src/sage/coding/linear_code_no_metric.py @@ -265,9 +265,9 @@ def __eq__(self, other): False """ # Fail without computing the generator matrix if possible: - if not (isinstance(other, AbstractLinearCodeNoMetric)\ - and self.length() == other.length()\ - and self.dimension() == other.dimension()\ + if not (isinstance(other, AbstractLinearCodeNoMetric) + and self.length() == other.length() + and self.dimension() == other.dimension() and self.base_ring() == other.base_ring()): return False # Check that basis elements of `other` are all in `self.` @@ -276,10 +276,7 @@ def __eq__(self, other): # This implementation may avoid linear algebra altogether, if `self` # implements an efficient way to obtain a parity check matrix, and in # the worst case does only one system solving. - for c in other.gens(): - if not (c in self): - return False - return True + return all(c in self for c in other.gens()) def __ne__(self, other): r""" diff --git a/src/sage/crypto/mq/rijndael_gf.py b/src/sage/crypto/mq/rijndael_gf.py index ec8f433d705..8665c4700c8 100644 --- a/src/sage/crypto/mq/rijndael_gf.py +++ b/src/sage/crypto/mq/rijndael_gf.py @@ -1140,16 +1140,16 @@ def _check_valid_PRmatrix(self, PRm, keyword): msg = ("keyword '{0}' must be a {1} x {2} matrix with entries from a " "multivariate PolynomialRing over {3}") msg = msg.format(keyword, 4, self._Nb, self._F) - if (not isinstance(PRm, Matrix) or \ - not (PRm.base_ring().is_field() and \ - PRm.base_ring().is_finite() and \ - PRm.base_ring().order() == 256 and \ + if (not isinstance(PRm, Matrix) or + not (PRm.base_ring().is_field() and + PRm.base_ring().is_finite() and + PRm.base_ring().order() == 256 and PRm.dimensions() == (4, self._Nb))) and \ - (not isinstance(PRm, Matrix) or \ - not isinstance(PRm.base_ring(), MPolynomialRing_base) or \ - not (PRm.base_ring().base_ring().is_field() and \ - PRm.base_ring().base_ring().is_finite() and \ - PRm.base_ring().base_ring().order() == 256) or \ + (not isinstance(PRm, Matrix) or + not isinstance(PRm.base_ring(), MPolynomialRing_base) or + not (PRm.base_ring().base_ring().is_field() and + PRm.base_ring().base_ring().is_finite() and + PRm.base_ring().base_ring().order() == 256) or not PRm.dimensions() == (4, self._Nb)): raise TypeError(msg) @@ -1183,8 +1183,8 @@ def expand_key(self, key): msg = "keyword '{0}' must be a {1} x {2} matrix over GF({3})" msg = msg.format(key, 4, self._Nk, self._F.order()) if not isinstance(key, Matrix) or \ - not (key.base_ring().is_field() and \ - key.base_ring().is_finite() and \ + not (key.base_ring().is_field() and + key.base_ring().is_finite() and key.base_ring().order() == self._F.order()) or \ not key.dimensions() == (4, self._Nk): raise TypeError(msg) @@ -1396,12 +1396,12 @@ def apply_poly(self, state, poly_constr, algorithm='encrypt', keys=None, if not isinstance(poly_constr, RijndaelGF.Round_Component_Poly_Constr): msg = "keyword 'poly_constr' must be a Round_Component_Poly_Constr" raise TypeError(msg) - if keys is not None and (not isinstance(keys, list) or \ - len(keys) != self._Nr + 1 or \ - not all(isinstance(k, Matrix) for k in keys) or \ - not all(k.dimensions() == (4, self._Nb) for k in keys) or \ + if keys is not None and (not isinstance(keys, list) or + len(keys) != self._Nr + 1 or + not all(isinstance(k, Matrix) for k in keys) or + not all(k.dimensions() == (4, self._Nb) for k in keys) or not all(k.base_ring().is_finite() and k.base_ring().is_field() - and k.base_ring().order() == 256 for k in keys) ): + and k.base_ring().order() == 256 for k in keys)): msg = ("keys must be a length {0} array of 4 by {1} matrices" " over {2}") raise TypeError(msg.format(self._Nr, self._Nb, self._F)) @@ -1864,8 +1864,8 @@ def _sub_bytes_pc(self, row, col, algorithm='encrypt', no_inversion=False): elif algorithm == 'decrypt': var = self.state_vrs[row, col] coeffs = self._sb_D_coeffs - result = (sum([coeffs[i] * var**(2**i) for i in range(8)]) + \ - self._F("x^2 + 1")) + result = (sum([coeffs[i] * var**(2**i) for i in range(8)]) + + self._F("x^2 + 1")) if no_inversion: return result else: @@ -2318,7 +2318,7 @@ def __call__(self, row, col, algorithm='encrypt', **kwargs): raise ValueError("keyword 'row' must be in range 0 - 3") if col not in range(self._Nb): msg = "keyword 'col' must be in range 0 - {0}" - raise ValueError(msg.format(self._Nb-1)) + raise ValueError(msg.format(self._Nb - 1)) if algorithm not in ['encrypt', 'decrypt']: msg = ("keyword 'algorithm' must be either 'encrypt' or " "'decrypt'") diff --git a/src/sage/databases/sql_db.py b/src/sage/databases/sql_db.py index 087c494ef39..4a456ba0f32 100644 --- a/src/sage/databases/sql_db.py +++ b/src/sage/databases/sql_db.py @@ -259,7 +259,7 @@ def construct_skeleton(database): typ = u'NOTYPE' else: typ = col[2] - skeleton[table[0]][col[1]] = {'sql':typ, \ + skeleton[table[0]][col[1]] = {'sql':typ, 'primary_key':(col[5]!=0), 'index':(col[5]!=0), 'unique': False} exe2 = cur.execute("PRAGMA index_list(%s)"%table[0]) for col in exe2.fetchall(): @@ -682,7 +682,7 @@ def show(self, **kwds): except Exception: raise RuntimeError('Failure to fetch query.') - print(_create_print_table(cur, [des[0] for des in cur.description], \ + print(_create_print_table(cur, [des[0] for des in cur.description], **kwds)) def __copy__(self): @@ -704,7 +704,7 @@ def __copy__(self): d.__param_tuple__ = self.__param_tuple__ return d - def intersect(self, other, join_table=None, join_dict=None, \ + def intersect(self, other, join_table=None, join_dict=None, in_place=False): """ Return a new ``SQLQuery`` that is the intersection of ``self`` and @@ -773,7 +773,7 @@ def intersect(self, other, join_table=None, join_dict=None, \ return copy(other) if not other.__query_string__: return copy(self) - return self._merge_queries(other, copy(self), join_table, \ + return self._merge_queries(other, copy(self), join_table, join_dict, 'AND') def _merge_queries(self, other, ret, join_table, join_dict, operator): @@ -830,8 +830,8 @@ def _merge_queries(self, other, ret, join_table, join_dict, operator): # concatenate where clause new_query = re.sub(' WHERE ',' WHERE ( ', new_query) - new_query += re.sub('^.* WHERE ',' ) %s ( '%operator, \ - other.__query_string__) + new_query += re.sub('^.* WHERE ',' ) %s ( '%operator, + other.__query_string__) ret.__query_string__ = new_query + ' )' ret.__param_tuple__ = self.__param_tuple__ + other.__param_tuple__ @@ -891,9 +891,10 @@ def union(self, other, join_table=None, join_dict=None, in_place=False): return copy(self) if not other.__query_string__: return copy(other) - return self._merge_queries(other, copy(self), join_table, \ + return self._merge_queries(other, copy(self), join_table, join_dict, 'OR') + class SQLDatabase(SageObject): def __init__(self, filename=None, read_only=None, skeleton=None): r""" @@ -1067,14 +1068,14 @@ def __init__(self, filename=None, read_only=None, skeleton=None): filename = tmp_filename() + '.db' elif (filename[-3:] != '.db'): raise ValueError('Please enter a valid database path (file name ' \ - + '%s does not end in .db).'%filename) + + '%s does not end in .db).' % filename) if read_only is None: read_only = True self.__read_only__ = read_only self.ignore_warnings = False self.__dblocation__ = filename - self.__connection__ = sqlite.connect(self.__dblocation__, \ + self.__connection__ = sqlite.connect(self.__dblocation__, check_same_thread=False) # this is to avoid the multiple thread problem with dsage: # pysqlite does not trust multiple threads for the same connection @@ -1092,8 +1093,8 @@ def __init__(self, filename=None, read_only=None, skeleton=None): else: for column in skeleton[table]: if column not in self.__skeleton__[table]: - self.add_column(table, column, \ - skeleton[table][column]) + self.add_column(table, column, + skeleton[table][column]) else: print('Column attributes were ignored for ' \ 'table {}, column {} -- column is ' \ @@ -1304,8 +1305,8 @@ def show(self, table_name, **kwds): cur.execute('SELECT * FROM ' + table_name) except Exception: raise RuntimeError('Failure to fetch data.') - print(_create_print_table(cur, [des[0] for des in cur.description], \ - **kwds)) + print(_create_print_table(cur, [des[0] for des in cur.description], + **kwds)) def get_cursor(self, ignore_warning=None): """ @@ -1376,9 +1377,9 @@ def get_connection(self, ignore_warning=None): ignore_warning = self.ignore_warnings if not ignore_warning: import warnings - warnings.warn('Database is read only, using the connection ' \ - + 'can alter the stored data. Set self.ignore_warnings ' \ - + 'to True in order to mute future warnings.', \ + warnings.warn('Database is read only, using the connection ' + 'can alter the stored data. Set self.ignore_warnings ' + 'to True in order to mute future warnings.', RuntimeWarning) return self.__connection__ @@ -1638,12 +1639,12 @@ def _rebuild_table(self, table_name, col_name=None, default=''): INSERT INTO spam SELECT %s FROM %s; DROP TABLE %s; CREATE TABLE %s (%s); - """%(cols_attr, original, table_name, table_name, table_name, cols_attr)) + """ % (cols_attr, original, table_name, table_name, table_name, cols_attr)) # Update indices in new table - index_statement = ''.join(['CREATE INDEX i_%s_%s ON '%(table_name, \ - col) + '%s(%s);\n'%(table_name, col) for col in \ - self.__skeleton__[table_name] if \ - self.__skeleton__[table_name][col]['index'] and not \ + index_statement = ''.join(['CREATE INDEX i_%s_%s ON ' % (table_name, + col) + '%s(%s);\n' % (table_name, col) for col in + self.__skeleton__[table_name] if + self.__skeleton__[table_name][col]['index'] and not self.__skeleton__[table_name][col]['primary_key']]) if index_statement: self.__connection__.executescript(index_statement) @@ -1652,7 +1653,7 @@ def _rebuild_table(self, table_name, col_name=None, default=''): self.__connection__.executescript(""" INSERT INTO %s SELECT %s FROM spam; DROP TABLE spam; - """%(table_name, cols)) + """ % (table_name, cols)) self.vacuum() @@ -2115,15 +2116,15 @@ def delete_rows(self, query): raise RuntimeError('Cannot delete rows from a read only database.') # Check query is associated with this database if not isinstance(query, SQLQuery): - raise TypeError('%s is not a valid SQLQuery'%query) + raise TypeError('%s is not a valid SQLQuery' % query) if query.__database__ is not self: - raise ValueError('%s is not associated to this database.'%query) + raise ValueError('%s is not associated to this database.' % query) if (query.__query_string__).find(' JOIN ') != -1: - raise ValueError('%s is not a valid query. Can only '%query \ - + 'delete from one table at a time.') + raise ValueError(f'{query} is not a valid query. Can only ' + 'delete from one table at a time.') - delete_statement = re.sub('SELECT .* FROM', 'DELETE FROM', \ - query.__query_string__) + delete_statement = re.sub('SELECT .* FROM', 'DELETE FROM', + query.__query_string__) try: cur = self.get_cursor() diff --git a/src/sage/functions/wigner.py b/src/sage/functions/wigner.py index cb5a5c0e107..53d0b744f6a 100644 --- a/src/sage/functions/wigner.py +++ b/src/sage/functions/wigner.py @@ -294,10 +294,10 @@ def _big_delta_coeff(aa, bb, cc, prec=None): maxfact = max(aa + bb - cc, aa + cc - bb, bb + cc - aa, aa + bb + cc + 1) _calc_factlist(maxfact) - argsqrt = Integer(_Factlist[int(aa + bb - cc)] * \ - _Factlist[int(aa + cc - bb)] * \ - _Factlist[int(bb + cc - aa)]) / \ - Integer(_Factlist[int(aa + bb + cc + 1)]) + argsqrt = Integer(_Factlist[int(aa + bb - cc)] * + _Factlist[int(aa + cc - bb)] * + _Factlist[int(bb + cc - aa)]) /\ + Integer(_Factlist[int(aa + bb + cc + 1)]) ressqrt = argsqrt.sqrt(prec) if isinstance(ressqrt, ComplexNumber): @@ -704,8 +704,8 @@ def gaunt(l_1, l_2, l_3, m_1, m_2, m_3, prec=None): (4*pi) ressqrt = argsqrt.sqrt() - prefac = Integer(_Factlist[bigL] * _Factlist[l_2 - l_1 + l_3] * \ - _Factlist[l_1 - l_2 + l_3] * _Factlist[l_1 + l_2 - l_3])/ \ + prefac = Integer(_Factlist[bigL] * _Factlist[l_2 - l_1 + l_3] * + _Factlist[l_1 - l_2 + l_3] * _Factlist[l_1 + l_2 - l_3]) / \ _Factlist[2 * bigL + 1] / \ (_Factlist[bigL - l_1] * _Factlist[bigL - l_2] * _Factlist[bigL - l_3]) diff --git a/src/sage/groups/finitely_presented.py b/src/sage/groups/finitely_presented.py index 1beb01af87f..6a6efb98ad8 100644 --- a/src/sage/groups/finitely_presented.py +++ b/src/sage/groups/finitely_presented.py @@ -177,11 +177,9 @@ def _repr_defn(self): sage: f = GroupMorphismWithGensImages(HS, lambda a: H.one()) sage: f._repr_defn() 'x0 |--> ()\nx1 |--> ()\nx2 |--> ()' - """ - D = self.domain() - return '\n'.join(['%s |--> %s'%(i, self(i)) for\ - i in D.gens()]) + return '\n'.join(f'{i} |--> {self(i)}' for i in self.domain().gens()) + class FinitelyPresentedGroupElement(FreeGroupElement): """ diff --git a/src/sage/interfaces/maxima_abstract.py b/src/sage/interfaces/maxima_abstract.py index 544e3b678a3..62bd5c9821e 100644 --- a/src/sage/interfaces/maxima_abstract.py +++ b/src/sage/interfaces/maxima_abstract.py @@ -746,12 +746,12 @@ def plot2d_parametric(self, r, var, trange, nticks=50, options=None): """ tmin = trange[0] tmax = trange[1] - cmd = "plot2d([parametric, %s, %s, [%s, %s, %s], [nticks, %s]]"%( \ - r[0], r[1], var, tmin, tmax, nticks) + cmd = "plot2d([parametric, %s, %s, [%s, %s, %s], [nticks, %s]]" % ( + r[0], r[1], var, tmin, tmax, nticks) if options is None: cmd += ")" else: - cmd += ", %s)"%options + cmd += ", %s)" % options self(cmd) def plot3d(self, *args): diff --git a/src/sage/interfaces/rubik.py b/src/sage/interfaces/rubik.py index 45857555caa..1a142200707 100644 --- a/src/sage/interfaces/rubik.py +++ b/src/sage/interfaces/rubik.py @@ -45,17 +45,17 @@ # Can't seem to find consistency in letter ordering # between us and them... These are copied from the source. -optimal_solver_tokens = ["UF", "UR", "UB", "UL", \ - "DF", "DR", "DB", "DL", \ - "FR", "FL", "BR", "BL", \ - "FU", "RU", "BU", "LU", \ - "FD", "RD", "BD", "LD", \ - "RF", "LF", "RB", "LB", \ - "UFR", "URB", "UBL", "ULF", \ - "DRF", "DFL", "DLB", "DBR", \ - "FRU", "RBU", "BLU", "LFU", \ - "RFD", "FLD", "LBD", "BRD", \ - "RUF", "BUR", "LUB", "FUL", \ +optimal_solver_tokens = ["UF", "UR", "UB", "UL", + "DF", "DR", "DB", "DL", + "FR", "FL", "BR", "BL", + "FU", "RU", "BU", "LU", + "FD", "RD", "BD", "LD", + "RF", "LF", "RB", "LB", + "UFR", "URB", "UBL", "ULF", + "DRF", "DFL", "DLB", "DBR", + "FRU", "RBU", "BLU", "LFU", + "RFD", "FLD", "LBD", "BRD", + "RUF", "BUR", "LUB", "FUL", "FDR", "LDF", "BDL", "RDB"] # The input format. @@ -309,15 +309,15 @@ def format_cube(self, facets): facet_colors[16+i*3] = i return "".join(str(c) for c in facet_colors) - facet_map = [ 1, 2, 3, \ - 4, 0, 5, \ - 6, 7, 8, \ - 9, 10, 11, 17, 18, 19, 25, 26, 27, 33, 34, 35, \ - 12, 0, 13, 20, 0, 21, 28, 0, 29, 36, 0, 37, \ - 14, 15, 16, 22, 23, 24, 30, 31, 32, 38, 39, 40, \ - 41, 42, 43, \ - 44, 0, 45, \ - 46, 47, 48, \ + facet_map = [ 1, 2, 3, + 4, 0, 5, + 6, 7, 8, + 9, 10, 11, 17, 18, 19, 25, 26, 27, 33, 34, 35, + 12, 0, 13, 20, 0, 21, 28, 0, 29, 36, 0, 37, + 14, 15, 16, 22, 23, 24, 30, 31, 32, 38, 39, 40, + 41, 42, 43, + 44, 0, 45, + 46, 47, 48, ] diff --git a/src/sage/interfaces/singular.py b/src/sage/interfaces/singular.py index 2a127cfe482..b79e08c44f9 100644 --- a/src/sage/interfaces/singular.py +++ b/src/sage/interfaces/singular.py @@ -1845,14 +1845,14 @@ def sage_poly(self, R=None, kcache=None): out = R(self) self.parent().eval('short=%s'%is_short) return out - singular_poly_list = self.parent().eval("string(coef(%s,%s))" % (\ - self.name(),variable_str)).split(",") + singular_poly_list = self.parent().eval("string(coef(%s,%s))" % ( + self.name(),variable_str)).split(",") self.parent().eval('short=%s'%is_short) else: if isinstance(R, MPolynomialRing_libsingular): return R(self) - singular_poly_list = self.parent().eval("string(coef(%s,%s))" % (\ - self.name(),variable_str)).split(",") + singular_poly_list = self.parent().eval("string(coef(%s,%s))" % ( + self.name(),variable_str)).split(",") # Directly treat constants if singular_poly_list[0] in ['1', '(1.000e+00)']: diff --git a/src/sage/libs/ntl/all.py b/src/sage/libs/ntl/all.py index 20993d2cac8..e9d4271879a 100644 --- a/src/sage/libs/ntl/all.py +++ b/src/sage/libs/ntl/all.py @@ -5,8 +5,7 @@ Features of this library include *incredibly fast* arithmetic with polynomials and asymptotically fast factorization of polynomials. """ - -#***************************************************************************** +# **************************************************************************** # Copyright (C) 2005 William Stein # # Distributed under the terms of the GNU General Public License (GPL) @@ -18,14 +17,14 @@ # # The full text of the GPL is available at: # -# http://www.gnu.org/licenses/ -#***************************************************************************** +# https://www.gnu.org/licenses/ +# **************************************************************************** from sage.libs.ntl.ntl_ZZ import ( - ntl_setSeed, \ - ntl_ZZ as ZZ, - randomBnd as ZZ_random, - randomBits as ZZ_random_bits ) + ntl_setSeed, + ntl_ZZ as ZZ, + randomBnd as ZZ_random, + randomBits as ZZ_random_bits) from sage.libs.ntl.ntl_ZZ_pContext import ntl_ZZ_pContext as ZZ_pContext @@ -56,16 +55,14 @@ from sage.libs.ntl.ntl_GF2 import ntl_GF2 as GF2 from sage.libs.ntl.ntl_GF2X import ( - ntl_GF2X as GF2X, - GF2XHexOutput, - ) + ntl_GF2X as GF2X, + GF2XHexOutput) from sage.libs.ntl.ntl_GF2EContext import ntl_GF2EContext as GF2EContext from sage.libs.ntl.ntl_GF2E import ( - ntl_GF2E as GF2E, \ - ntl_GF2E_random as GF2E_random, \ - ) + ntl_GF2E as GF2E, + ntl_GF2E_random as GF2E_random) from sage.libs.ntl.ntl_GF2EX import ntl_GF2EX as GF2EX diff --git a/src/sage/manifolds/differentiable/affine_connection.py b/src/sage/manifolds/differentiable/affine_connection.py index 008f13be22e..eb87805a49c 100644 --- a/src/sage/manifolds/differentiable/affine_connection.py +++ b/src/sage/manifolds/differentiable/affine_connection.py @@ -1996,15 +1996,16 @@ def riemann(self): @parallel(p_iter='multiprocessing', ncpus=nproc) def make_Riem(frame, gam, gam_gam, gam_sc, local_list_ijkl): partial = [] - for i,j,k,l in local_list_ijkl: - partial.append([i,j,k,l, frame[k](gam[[i,j,l]]) - \ - frame[l](gam[[i,j,k]]) + \ - gam_gam[[i,k,j,l]] - \ - gam_gam[[i,l,j,k]] - \ - gam_sc[[i,j,k,l]]]) + for i, j, k, l in local_list_ijkl: + partial.append([i, j, k, l, + frame[k](gam[[i, j, l]]) - + frame[l](gam[[i, j, k]]) + + gam_gam[[i, k, j, l]] - + gam_gam[[i, l, j, k]] - + gam_sc[[i, j, k, l]]]) return partial # Computation and assignation of values - for ii,val in make_Riem(listParalInput): + for ii, val in make_Riem(listParalInput): for jj in val: res[jj[0], jj[1], jj[2], jj[3]] = jj[4] diff --git a/src/sage/manifolds/differentiable/mixed_form.py b/src/sage/manifolds/differentiable/mixed_form.py index 2a30ececa45..90d2954547e 100644 --- a/src/sage/manifolds/differentiable/mixed_form.py +++ b/src/sage/manifolds/differentiable/mixed_form.py @@ -12,22 +12,21 @@ AUTHORS: - Michael Jung (2019) : initial version - """ - -#****************************************************************************** +# ***************************************************************************** # Copyright (C) 2019 Michael Jung # # Distributed under the terms of the GNU General Public License (GPL) # as published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # https://www.gnu.org/licenses/ -#****************************************************************************** +# ***************************************************************************** from sage.misc.cachefunc import cached_method from sage.structure.element import AlgebraElement, ModuleElementWithMutability from sage.rings.integer import Integer + class MixedForm(AlgebraElement, ModuleElementWithMutability): r""" An instance of this class is a mixed form along some differentiable map @@ -253,9 +252,9 @@ def __init__(self, parent, name=None, latex_name=None): self._domain = vmodule._domain self._ambient_domain = vmodule._ambient_domain self._max_deg = vmodule._ambient_domain.dim() - self._is_zero = False # a priori, may be changed below or via - # method __bool__() - self._comp = None # initialized on demand; see _init_comp + self._is_zero = False # a priori, may be changed below or via + # method __bool__() + self._comp = None # initialized on demand; see _init_comp # Set names: self._name = name if latex_name is None: @@ -289,7 +288,7 @@ def _init_comp(self): comp_latex_name = '{' + self._latex_name + '}_{' + str(i) + '}' diff_form = self._domain.diff_form self._comp.append(diff_form(i, name=comp_name, - latex_name=comp_latex_name)) + latex_name=comp_latex_name)) def _repr_(self): r""" @@ -487,7 +486,7 @@ def display_expansion(self, frame=None, chart=None, from_chart=None): if is_atomic(coef_latex): terms_latex.append(coef_latex + basis_term_latex) else: - terms_latex.append(r"\left(" + coef_latex + \ + terms_latex.append(r"\left(" + coef_latex + r"\right)" + basis_term_latex) if not terms_txt: resu_txt += "0" @@ -614,11 +613,10 @@ def set_name(self, name=None, latex_name=None, apply_to_comp=True): sage: F[0].set_name(name='g'); F.display() eta = g + F_1 + F_2 + F_3 + F_4 - """ if self.is_immutable(): raise ValueError("the name of an immutable element " - "cannot be changed") + "cannot be changed") if name is not None: self._name = name if latex_name is None: @@ -991,7 +989,7 @@ def wedge(self, other): return self # Generic case: resu = self._new_instance() - resu._comp = [sum(self[k].wedge(other[j-k]) for k in range(j+1)) + resu._comp = [sum(self[k].wedge(other[j - k]) for k in range(j + 1)) for j in self.irange()] # Compose name: from sage.typeset.unicode_characters import unicode_wedge diff --git a/src/sage/misc/map_threaded.py b/src/sage/misc/map_threaded.py index cc8f8f0a3dd..c5eba670052 100644 --- a/src/sage/misc/map_threaded.py +++ b/src/sage/misc/map_threaded.py @@ -2,6 +2,7 @@ Threaded map function """ + def map_threaded(function, sequence): """ Apply the function to the elements in the sequence by threading @@ -31,5 +32,5 @@ def map_threaded(function, sequence): """ if hasattr(sequence, 'apply_map'): return sequence.apply_map(function) - return [map_threaded(function, x) if isinstance(x, (list, tuple)) \ - else function(x) for x in sequence] + return [map_threaded(function, x) if isinstance(x, (list, tuple)) + else function(x) for x in sequence] diff --git a/src/sage/quadratic_forms/quadratic_form__equivalence_testing.py b/src/sage/quadratic_forms/quadratic_form__equivalence_testing.py index 3175126556d..cac17f3e952 100644 --- a/src/sage/quadratic_forms/quadratic_form__equivalence_testing.py +++ b/src/sage/quadratic_forms/quadratic_form__equivalence_testing.py @@ -5,7 +5,6 @@ - Anna Haensch (2014-12-01): added test for rational isometry """ - from sage.arith.misc import (hilbert_symbol, GCD, is_prime, @@ -209,21 +208,20 @@ def has_equivalent_Jordan_decomposition_at_prime(self, other, p): """ # Sanity Checks - #if not isinstance(other, QuadraticForm): + # if not isinstance(other, QuadraticForm): if not isinstance(other, type(self)): raise TypeError("the first argument must be of type QuadraticForm") if not is_prime(p): raise TypeError("the second argument must be a prime number") # Get the relevant local normal forms quickly - self_jordan = self.jordan_blocks_by_scale_and_unimodular(p, safe_flag= False) + self_jordan = self.jordan_blocks_by_scale_and_unimodular(p, safe_flag=False) other_jordan = other.jordan_blocks_by_scale_and_unimodular(p, safe_flag=False) # Check for the same number of Jordan components if len(self_jordan) != len(other_jordan): return False - # Deal with odd primes: Check that the Jordan component scales, dimensions, and discriminants are the same if p != 2: for i in range(len(self_jordan)): @@ -235,14 +233,12 @@ def has_equivalent_Jordan_decomposition_at_prime(self, other, p): # All tests passed for an odd prime. return True - # For p = 2: Check that all Jordan Invariants are the same. elif p == 2: # Useful definition t = len(self_jordan) # Define t = Number of Jordan components - # Check that all Jordan Invariants are the same (scale, dim, and norm) for i in range(t): if (self_jordan[i][0] != other_jordan[i][0]) \ @@ -254,27 +250,27 @@ def has_equivalent_Jordan_decomposition_at_prime(self, other, p): # ------------------------------------------ # List of norms, scales, and dimensions for each i - scale_list = [ZZ(2)**self_jordan[i][0] for i in range(t)] - norm_list = [ZZ(2)**(self_jordan[i][0] + valuation(GCD(self_jordan[i][1].coefficients()), 2)) for i in range(t)] - dim_list = [(self_jordan[i][1].dim()) for i in range(t)] + scale_list = [ZZ(2)**self_jordan[i][0] for i in range(t)] + norm_list = [ZZ(2)**(self_jordan[i][0] + valuation(GCD(self_jordan[i][1].coefficients()), 2)) for i in range(t)] + dim_list = [(self_jordan[i][1].dim()) for i in range(t)] # List of Hessian determinants and Hasse invariants for each Jordan (sub)chain # (Note: This is not the same as O'Meara's Gram determinants, but ratios are the same!) -- NOT SO GOOD... # But it matters in condition (ii), so we multiply all by 2 (instead of dividing by 2 since only square-factors matter, and it's easier.) j = 0 - self_chain_det_list = [ self_jordan[j][1].Gram_det() * (scale_list[j]**dim_list[j])] - other_chain_det_list = [ other_jordan[j][1].Gram_det() * (scale_list[j]**dim_list[j])] - self_hasse_chain_list = [ self_jordan[j][1].scale_by_factor(ZZ(2)**self_jordan[j][0]).hasse_invariant__OMeara(2) ] - other_hasse_chain_list = [ other_jordan[j][1].scale_by_factor(ZZ(2)**other_jordan[j][0]).hasse_invariant__OMeara(2) ] + self_chain_det_list = [self_jordan[j][1].Gram_det() * (scale_list[j]**dim_list[j])] + other_chain_det_list = [other_jordan[j][1].Gram_det() * (scale_list[j]**dim_list[j])] + self_hasse_chain_list = [self_jordan[j][1].scale_by_factor(ZZ(2)**self_jordan[j][0]).hasse_invariant__OMeara(2)] + other_hasse_chain_list = [other_jordan[j][1].scale_by_factor(ZZ(2)**other_jordan[j][0]).hasse_invariant__OMeara(2)] for j in range(1, t): self_chain_det_list.append(self_chain_det_list[j-1] * self_jordan[j][1].Gram_det() * (scale_list[j]**dim_list[j])) other_chain_det_list.append(other_chain_det_list[j-1] * other_jordan[j][1].Gram_det() * (scale_list[j]**dim_list[j])) - self_hasse_chain_list.append(self_hasse_chain_list[j-1] \ - * hilbert_symbol(self_chain_det_list[j-1], self_jordan[j][1].Gram_det(), 2) \ + self_hasse_chain_list.append(self_hasse_chain_list[j-1] + * hilbert_symbol(self_chain_det_list[j-1], self_jordan[j][1].Gram_det(), 2) * self_jordan[j][1].hasse_invariant__OMeara(2)) - other_hasse_chain_list.append(other_hasse_chain_list[j-1] \ - * hilbert_symbol(other_chain_det_list[j-1], other_jordan[j][1].Gram_det(), 2) \ + other_hasse_chain_list.append(other_hasse_chain_list[j-1] + * hilbert_symbol(other_chain_det_list[j-1], other_jordan[j][1].Gram_det(), 2) * other_jordan[j][1].hasse_invariant__OMeara(2)) # SANITY CHECK -- check that the scale powers are strictly increasing @@ -293,7 +289,7 @@ def has_equivalent_Jordan_decomposition_at_prime(self, other, p): return False # Check O'Meara's condition (ii) when appropriate - if norm_list[i+1] % (4 * norm_list[i]) == 0: + if norm_list[i + 1] % (4 * norm_list[i]) == 0: if self_hasse_chain_list[i] * hilbert_symbol(norm_list[i] * other_chain_det_list[i], -self_chain_det_list[i], 2) \ != other_hasse_chain_list[i] * hilbert_symbol(norm_list[i], -other_chain_det_list[i], 2): # Nipp conditions return False @@ -492,13 +488,13 @@ def is_rationally_isometric(self, other, return_matrix=False): if self.dim() != other.dim(): return False - if not (self.Gram_det()*other.Gram_det()).is_square(): + if not (self.Gram_det() * other.Gram_det()).is_square(): return False - L1=self.Gram_det().support() - L2=other.Gram_det().support() + L1 = self.Gram_det().support() + L2 = other.Gram_det().support() - for p in set().union(L1,L2): + for p in set().union(L1, L2): if self.hasse_invariant(p) != other.hasse_invariant(p): return False @@ -516,13 +512,13 @@ def is_rationally_isometric(self, other, return_matrix=False): for emb in K.real_embeddings(): - Mpos=0 + Mpos = 0 for x in Mentries: - Mpos+= emb(x) >= 0 + Mpos += emb(x) >= 0 - Npos=0 + Npos = 0 for x in Nentries: - Npos+= emb(x) >= 0 + Npos += emb(x) >= 0 if Npos != Mpos: return False @@ -606,7 +602,7 @@ def _diagonal_isometry(V, W): if Q.Gram_matrix()[0][0] != F.Gram_matrix()[0][0]: # Find a vector w in F such that F(w) equals the first term of Q. w = F.solve(Q.Gram_matrix()[0][0]) - w = vector(QQ, i*[0] + w.list()) + w = vector(QQ, i * [0] + w.list()) # We want to extend the basis of W to include the vector w. # Find a non-fixed vector in the current basis to replace by w. @@ -614,10 +610,10 @@ def _diagonal_isometry(V, W): # The new set of vectors must still be linearly independent (i.e. the matrix is non-singular). while True: temp_matrix = Matrix(change_of_basis_matrix) - temp_matrix.set_column(j, change_of_basis_matrix*w) + temp_matrix.set_column(j, change_of_basis_matrix * w) if not temp_matrix.is_singular(): break - j = j + 1 + j += 1 change_of_basis_matrix = temp_matrix @@ -690,12 +686,10 @@ def _gram_schmidt(m, fixed_vector_index, inner_product): from sage.matrix.constructor import column_matrix n = m.dimensions()[0] - vectors = [0] * n + vectors = [m.column(i) for i in range(n)] - for i in range(n): - vectors[i] = m.column(i) for i in range(fixed_vector_index, n): - for j in range(i+1, n): + for j in range(i + 1, n): vectors[j] = vectors[j] - (inner_product(vectors[j], vectors[i]) / inner_product(vectors[i], vectors[i])) * vectors[i] return column_matrix(vectors) diff --git a/src/sage/quadratic_forms/quadratic_form__reduction_theory.py b/src/sage/quadratic_forms/quadratic_form__reduction_theory.py index 16c89f6edf2..18968494f6b 100644 --- a/src/sage/quadratic_forms/quadratic_form__reduction_theory.py +++ b/src/sage/quadratic_forms/quadratic_form__reduction_theory.py @@ -388,80 +388,79 @@ def minkowski_reduction_for_4vars__SP(self): if (r == i) or (r == j): M_new[r,r] = 0 else: - M_new[r,r] = 1 + M_new[r, r] = 1 M = M * M_new - elif (i_sum == j_sum): - for k in [2,1,0]: # TO DO: These steps are a little redundant... + elif i_sum == j_sum: + for k in [2, 1, 0]: # TO DO: These steps are a little redundant... Q1 = Q.matrix() - c_flag = True - for l in range(k+1,4): - c_flag = c_flag and (abs(Q1[i,l]) == abs(Q1[j,l])) + c_flag = all(abs(Q1[i, l]) == abs(Q1[j, l]) + for l in range(k + 1, 4)) # Condition (c) - if c_flag and (abs(Q1[i,k]) > abs(Q1[j,k])): - Q.swap_variables(i,j,in_place=True) - M_new = matrix(R,n,n) - M_new[i,j] = -1 - M_new[j,i] = 1 + if c_flag and abs(Q1[i, k]) > abs(Q1[j, k]): + Q.swap_variables(i, j, in_place=True) + M_new = matrix(R, n, n) + M_new[i, j] = -1 + M_new[j, i] = 1 for r in range(4): if (r == i) or (r == j): - M_new[r,r] = 0 + M_new[r, r] = 0 else: - M_new[r,r] = 1 + M_new[r, r] = 1 M = M * M_new # Step 3: Order the signs for i in range(4): - if Q[i,3] < 0: + if Q[i, 3] < 0: Q.multiply_variable(-1, i, in_place=True) - M_new = matrix(R,n,n) + M_new = matrix(R, n, n) for r in range(4): if r == i: - M_new[r,r] = -1 + M_new[r, r] = -1 else: - M_new[r,r] = 1 + M_new[r, r] = 1 M = M * M_new for i in range(4): j = 3 - while (Q[i,j] == 0): + while (Q[i, j] == 0): j += -1 - if (Q[i,j] < 0): + if (Q[i, j] < 0): Q.multiply_variable(-1, i, in_place=True) - M_new = matrix(R,n,n) + M_new = matrix(R, n, n) for r in range(4): if r == i: - M_new[r,r] = -1 + M_new[r, r] = -1 else: - M_new[r,r] = 1 + M_new[r, r] = 1 M = M * M_new - if Q[1,2] < 0: + if Q[1, 2] < 0: # Test a row 1 sign change - if (Q[1,3] <= 0 and \ - ((Q[1,3] < 0) or (Q[1,3] == 0 and Q[1,2] < 0) \ - or (Q[1,3] == 0 and Q[1,2] == 0 and Q[1,1] < 0))): + if (Q[1, 3] <= 0 and + ((Q[1, 3] < 0) or (Q[1, 3] == 0 and Q[1, 2] < 0) + or (Q[1, 3] == 0 and Q[1, 2] == 0 and Q[1, 1] < 0))): Q.multiply_variable(-1, i, in_place=True) - M_new = matrix(R,n,n) + M_new = matrix(R, n, n) for r in range(4): if r == i: - M_new[r,r] = -1 + M_new[r, r] = -1 else: - M_new[r,r] = 1 + M_new[r, r] = 1 M = M * M_new - elif (Q[2,3] <= 0 and \ - ((Q[2,3] < 0) or (Q[2,3] == 0 and Q[2,2] < 0) \ - or (Q[2,3] == 0 and Q[2,2] == 0 and Q[2,1] < 0))): + elif (Q[2, 3] <= 0 and + ((Q[2, 3] < 0) or (Q[2, 3] == 0 and Q[2, 2] < 0) + or (Q[2, 3] == 0 and Q[2, 2] == 0 and Q[2, 1] < 0))): Q.multiply_variable(-1, i, in_place=True) - M_new = matrix(R,n,n) + M_new = matrix(R, n, n) for r in range(4): if r == i: - M_new[r,r] = -1 + M_new[r, r] = -1 else: - M_new[r,r] = 1 + M_new[r, r] = 1 M = M * M_new # Return the results diff --git a/src/sage/quadratic_forms/quadratic_form__theta.py b/src/sage/quadratic_forms/quadratic_form__theta.py index 7763c61a194..1c8813e04f9 100644 --- a/src/sage/quadratic_forms/quadratic_form__theta.py +++ b/src/sage/quadratic_forms/quadratic_form__theta.py @@ -235,32 +235,32 @@ def theta_by_cholesky(self, q_prec): # 3b. Main loop if (i > 0): from_step3_flag = True - T[i-1] = T[i] - Q[i,i] * (x[i] + U[i]) * (x[i] + U[i]) - i += - 1 + T[i - 1] = T[i] - Q[i, i] * (x[i] + U[i]) * (x[i] + U[i]) + i += -1 U[i] = 0 - for j in range(i+1, n): - U[i] += Q[i,j] * x[j] + for j in range(i + 1, n): + U[i] += Q[i, j] * x[j] # 4. Solution found (This happens when i=0) from_step4_flag = True - Q_val_double = q_prec - T[0] + Q[0,0] * (x[0] + U[0]) * (x[0] + U[0]) + Q_val_double = q_prec - T[0] + Q[0, 0] * (x[0] + U[0]) * (x[0] + U[0]) Q_val = floor(Q_val_double + half) # Note: This rounds the value up, since the "round" function returns a float, but floor returns integer. # OPTIONAL SAFETY CHECK: eps = 0.000000001 - if (abs(Q_val_double - Q_val) > eps): - raise RuntimeError("Oh No! We have a problem with the floating point precision... \n" \ - + " Q_val_double = " + str(Q_val_double) + "\n" \ - + " Q_val = " + str(Q_val) + "\n" \ + if abs(Q_val_double - Q_val) > eps: + raise RuntimeError("Oh No! We have a problem with the floating point precision... \n" + + " Q_val_double = " + str(Q_val_double) + "\n" + + " Q_val = " + str(Q_val) + "\n" + " x = " + str(x) + "\n") - if (Q_val <= q_prec): + if Q_val <= q_prec: theta[Q_val] += 2 # 5. Check if x = 0, for exit condition. =) done_flag = True for j in range(n): - if (x[j] != 0): + if x[j] != 0: done_flag = False # Set the value: theta[0] = 1 diff --git a/src/sage/rings/function_field/drinfeld_modules/drinfeld_module.py b/src/sage/rings/function_field/drinfeld_modules/drinfeld_module.py index 1a24f09d66d..b50193c1862 100644 --- a/src/sage/rings/function_field/drinfeld_modules/drinfeld_module.py +++ b/src/sage/rings/function_field/drinfeld_modules/drinfeld_module.py @@ -1030,7 +1030,7 @@ def height(self): """ try: if self.characteristic().is_zero(): - raise ValueError('height is defined for prime ' \ + raise ValueError('height is defined for prime ' 'function field characteristic') else: p = self.characteristic() @@ -1038,7 +1038,7 @@ def height(self): except NotImplementedError: raise NotImplementedError('height not implemented in this case') - def is_finite(self): + def is_finite(self) -> bool: r""" Return ``True`` if this Drinfeld module is finite, ``False`` otherwise. diff --git a/src/sage/symbolic/assumptions.py b/src/sage/symbolic/assumptions.py index 4616fd2880b..35c7dcfaeab 100644 --- a/src/sage/symbolic/assumptions.py +++ b/src/sage/symbolic/assumptions.py @@ -725,7 +725,7 @@ def forget(*args): try: x.forget() except KeyError: - raise TypeError("forget not defined for objects of type '%s'"%type(x)) + raise TypeError("forget not defined for objects of type '%s'" % type(x)) def assumptions(*args): @@ -782,11 +782,11 @@ def assumptions(*args): result = [] if len(args) == 1: result.extend([statement for statement in _assumptions - if statement.has(args[0])]) + if statement.has(args[0])]) else: for v in args: - result += [ statement for statement in list(_assumptions) \ - if str(v) in str(statement) ] + result += [statement for statement in list(_assumptions) + if str(v) in str(statement)] return result From 3dd56c5409ddfa0c51cdaa947d17d4e6b1ab70b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Chapoton?= Date: Tue, 21 Mar 2023 13:28:30 +0100 Subject: [PATCH 2/2] fix reviewer suggestions --- .../lie_conformal_algebra_element.py | 22 ++++++++++--------- src/sage/crypto/mq/rijndael_gf.py | 6 ++--- src/sage/databases/sql_db.py | 16 ++++++++------ src/sage/interfaces/rubik.py | 22 +++++++++---------- .../quadratic_form__reduction_theory.py | 16 +++++++------- 5 files changed, 43 insertions(+), 39 deletions(-) diff --git a/src/sage/algebras/lie_conformal_algebras/lie_conformal_algebra_element.py b/src/sage/algebras/lie_conformal_algebras/lie_conformal_algebra_element.py index 02c25a67297..b41cdf32811 100644 --- a/src/sage/algebras/lie_conformal_algebras/lie_conformal_algebra_element.py +++ b/src/sage/algebras/lie_conformal_algebras/lie_conformal_algebra_element.py @@ -60,14 +60,14 @@ def T(self, n=1): raise ValueError("n must be a nonnegative Integer") if n == 0 or self.is_zero(): return self - #it's faster to sum than to use recursion + # it's faster to sum than to use recursion if self.is_monomial(): p = self.parent() - a,m = self.index() - coef = self._monomial_coefficients[(a,m)] - if (a,m+n) in p._indices: - return coef*prod(j for j in range(m+1,m+n+1))\ - *p.monomial((a,m+n)) + a, m = self.index() + coef = self._monomial_coefficients[(a, m)] + if (a, m + n) in p._indices: + return coef * prod(j for j in range(m + 1, m + n + 1))\ + * p.monomial((a, m + n)) else: return p.zero() return sum(mon.T(n) for mon in self.terms()) @@ -130,10 +130,12 @@ def _bracket_(self, right): except KeyError: return {} pole = max(mbr.keys()) - ret = {l: coefa*coefb*(-1)**k/factorial(k)*sum(factorial(l) - /factorial(m+k+j-l)/factorial(l-k-j)/factorial(j)* - mbr[j].T(m+k+j-l) for j in mbr if j >= l-m-k and - j <= l-k) for l in range(m+k+pole+1)} + ret = {l: coefa * coefb * (-1)**k / factorial(k) * + sum(factorial(l) / factorial(m + k + j - l) + / factorial(l - k - j) / factorial(j) + * mbr[j].T(m + k + j - l) + for j in mbr if l - m - k <= j <= l - k) + for l in range(m + k + pole + 1)} return {k: v for k, v in ret.items() if v} diclist = [i._bracket_(j) for i in self.terms() diff --git a/src/sage/crypto/mq/rijndael_gf.py b/src/sage/crypto/mq/rijndael_gf.py index 8665c4700c8..6d3ddf988ea 100644 --- a/src/sage/crypto/mq/rijndael_gf.py +++ b/src/sage/crypto/mq/rijndael_gf.py @@ -1142,9 +1142,9 @@ def _check_valid_PRmatrix(self, PRm, keyword): msg = msg.format(keyword, 4, self._Nb, self._F) if (not isinstance(PRm, Matrix) or not (PRm.base_ring().is_field() and - PRm.base_ring().is_finite() and - PRm.base_ring().order() == 256 and - PRm.dimensions() == (4, self._Nb))) and \ + PRm.base_ring().is_finite() and + PRm.base_ring().order() == 256 and + PRm.dimensions() == (4, self._Nb))) and \ (not isinstance(PRm, Matrix) or not isinstance(PRm.base_ring(), MPolynomialRing_base) or not (PRm.base_ring().base_ring().is_field() and diff --git a/src/sage/databases/sql_db.py b/src/sage/databases/sql_db.py index 4a456ba0f32..cd611228dee 100644 --- a/src/sage/databases/sql_db.py +++ b/src/sage/databases/sql_db.py @@ -829,8 +829,9 @@ def _merge_queries(self, other, ret, join_table, join_dict, operator): new_query = ''.join(disp1) # concatenate where clause - new_query = re.sub(' WHERE ',' WHERE ( ', new_query) - new_query += re.sub('^.* WHERE ',' ) %s ( '%operator, + new_query = re.sub(' WHERE ', ' WHERE ( ', + new_query) + new_query += re.sub('^.* WHERE ', f' ) {operator} ( ', other.__query_string__) ret.__query_string__ = new_query + ' )' @@ -1641,11 +1642,12 @@ def _rebuild_table(self, table_name, col_name=None, default=''): CREATE TABLE %s (%s); """ % (cols_attr, original, table_name, table_name, table_name, cols_attr)) # Update indices in new table - index_statement = ''.join(['CREATE INDEX i_%s_%s ON ' % (table_name, - col) + '%s(%s);\n' % (table_name, col) for col in - self.__skeleton__[table_name] if - self.__skeleton__[table_name][col]['index'] and not - self.__skeleton__[table_name][col]['primary_key']]) + skeleton = self.__skeleton__[table_name] + index_statement = ''.join(f'CREATE INDEX i_{table_name}_{col} ON ' + + f'{table_name}({col});\n' + for col in skeleton + if skeleton[col]['index'] + and not skeleton[col]['primary_key']) if index_statement: self.__connection__.executescript(index_statement) diff --git a/src/sage/interfaces/rubik.py b/src/sage/interfaces/rubik.py index 1a142200707..546e7e962c6 100644 --- a/src/sage/interfaces/rubik.py +++ b/src/sage/interfaces/rubik.py @@ -46,17 +46,17 @@ # Can't seem to find consistency in letter ordering # between us and them... These are copied from the source. optimal_solver_tokens = ["UF", "UR", "UB", "UL", - "DF", "DR", "DB", "DL", - "FR", "FL", "BR", "BL", - "FU", "RU", "BU", "LU", - "FD", "RD", "BD", "LD", - "RF", "LF", "RB", "LB", - "UFR", "URB", "UBL", "ULF", - "DRF", "DFL", "DLB", "DBR", - "FRU", "RBU", "BLU", "LFU", - "RFD", "FLD", "LBD", "BRD", - "RUF", "BUR", "LUB", "FUL", - "FDR", "LDF", "BDL", "RDB"] + "DF", "DR", "DB", "DL", + "FR", "FL", "BR", "BL", + "FU", "RU", "BU", "LU", + "FD", "RD", "BD", "LD", + "RF", "LF", "RB", "LB", + "UFR", "URB", "UBL", "ULF", + "DRF", "DFL", "DLB", "DBR", + "FRU", "RBU", "BLU", "LFU", + "RFD", "FLD", "LBD", "BRD", + "RUF", "BUR", "LUB", "FUL", + "FDR", "LDF", "BDL", "RDB"] # The input format. optimal_solver_format = "UF UR UB UL DF DR DB DL FR FL BR BL UFR URB UBL ULF DRF DFL DLB DBR" diff --git a/src/sage/quadratic_forms/quadratic_form__reduction_theory.py b/src/sage/quadratic_forms/quadratic_form__reduction_theory.py index 18968494f6b..0035bbdf84f 100644 --- a/src/sage/quadratic_forms/quadratic_form__reduction_theory.py +++ b/src/sage/quadratic_forms/quadratic_form__reduction_theory.py @@ -425,9 +425,9 @@ def minkowski_reduction_for_4vars__SP(self): for i in range(4): j = 3 - while (Q[i, j] == 0): + while Q[i, j] == 0: j += -1 - if (Q[i, j] < 0): + if Q[i, j] < 0: Q.multiply_variable(-1, i, in_place=True) M_new = matrix(R, n, n) for r in range(4): @@ -439,9 +439,9 @@ def minkowski_reduction_for_4vars__SP(self): if Q[1, 2] < 0: # Test a row 1 sign change - if (Q[1, 3] <= 0 and - ((Q[1, 3] < 0) or (Q[1, 3] == 0 and Q[1, 2] < 0) - or (Q[1, 3] == 0 and Q[1, 2] == 0 and Q[1, 1] < 0))): + if (Q[1, 3] <= 0 and (Q[1, 3] < 0 + or Q[1, 2] < 0 + or (Q[1, 2] == 0 and Q[1, 1] < 0))): Q.multiply_variable(-1, i, in_place=True) M_new = matrix(R, n, n) for r in range(4): @@ -451,9 +451,9 @@ def minkowski_reduction_for_4vars__SP(self): M_new[r, r] = 1 M = M * M_new - elif (Q[2, 3] <= 0 and - ((Q[2, 3] < 0) or (Q[2, 3] == 0 and Q[2, 2] < 0) - or (Q[2, 3] == 0 and Q[2, 2] == 0 and Q[2, 1] < 0))): + elif (Q[2, 3] <= 0 and ((Q[2, 3] < 0) + or Q[2, 2] < 0 + or (Q[2, 2] == 0 and Q[2, 1] < 0))): Q.multiply_variable(-1, i, in_place=True) M_new = matrix(R, n, n) for r in range(4):