Skip to content

Commit

Permalink
ruff fixes for list, dict, set comprehension
Browse files Browse the repository at this point in the history
  • Loading branch information
fchapoton committed Oct 11, 2023
1 parent 844e976 commit 5b3b6f3
Show file tree
Hide file tree
Showing 33 changed files with 69 additions and 72 deletions.
4 changes: 2 additions & 2 deletions lmfdb/abvar/fq/stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,11 +178,11 @@ def _counts(self):

@lazy_attribute
def qs(self):
return sorted(set(q for g, q in self._counts))
return sorted({q for g, q in self._counts})

@lazy_attribute
def gs(self):
return sorted(set(g for g, q in self._counts))
return sorted({g for g, q in self._counts})

@lazy_attribute
def isogeny_knowl(self):
Expand Down
10 changes: 5 additions & 5 deletions lmfdb/api/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,15 +130,15 @@ def split_db(tablename):
info['dataSize'] = mb(dataSize)
info['indexSize'] = mb(indexSize)
if info['sortby'] == 'name':
sortedkeys = sorted(list(stats))
sortedkeys = sorted(stats)
elif info['sortby'] == 'objects' and info['groupby'] == 'db':
sortedkeys = sorted(list(stats),key=lambda x: (-stats[x]['dbObjects'],stats[x]['db'],-stats[x]['nrows'],stats[x]['table']))
sortedkeys = sorted(stats, key=lambda x: (-stats[x]['dbObjects'],stats[x]['db'],-stats[x]['nrows'],stats[x]['table']))
elif info['sortby'] == 'objects':
sortedkeys = sorted(list(stats),key=lambda x: (-stats[x]['nrows'],stats[x]['db'],stats[x]['table']))
sortedkeys = sorted(stats, key=lambda x: (-stats[x]['nrows'],stats[x]['db'],stats[x]['table']))
elif info['sortby'] == 'size' and info['groupby'] == 'db':
sortedkeys = sorted(list(stats),key=lambda x: (-stats[x]['dbSize'],stats[x]['db'],-stats[x]['size'],stats[x]['table']))
sortedkeys = sorted(stats, key=lambda x: (-stats[x]['dbSize'],stats[x]['db'],-stats[x]['size'],stats[x]['table']))
else:
sortedkeys = sorted(list(stats),key=lambda x: (-stats[x]['size'],stats[x]['db'],stats[x]['table']))
sortedkeys = sorted(stats, key=lambda x: (-stats[x]['size'],stats[x]['db'],stats[x]['table']))
info['stats'] = [stats[key] for key in sortedkeys]
return render_template('api-stats.html', info=info)

Expand Down
2 changes: 1 addition & 1 deletion lmfdb/api2/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -444,7 +444,7 @@ def simple_search_postgres(search_dict, projection=None):
metadata['record_count'] = info['number']
metadata['correct_count'] = info['exact_count']
if data:
data_out = list(list(data))
data_out = list(data)
else:
data_out = []
metadata['view_count'] = len(data_out)
Expand Down
4 changes: 2 additions & 2 deletions lmfdb/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ def modify_url(**replace):
@app.context_processor
def inject_sidebar():
from .homepage import get_sidebar
return dict(sidebar=get_sidebar())
return {"sidebar": get_sidebar()}

##############################
# Bottom link to google code #
Expand Down Expand Up @@ -657,7 +657,7 @@ def add_colors():
if color is None:
from .utils.config import Configuration
color = Configuration().get_color()
return dict(color=all_color_schemes[color].dict())
return {"color": all_color_schemes[color].dict()}


@app.route("/style.css")
Expand Down
2 changes: 1 addition & 1 deletion lmfdb/backend/searchtable.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def _parse_projection(self, projection):
elif projection == 3:
return tuple(["id"] + self.search_cols), tuple(self.extra_cols)
elif isinstance(projection, dict):
projvals = set(bool(val) for val in projection.values())
projvals = {bool(val) for val in projection.values()}
if len(projvals) > 1:
raise ValueError("You cannot both include and exclude.")
including = projvals.pop()
Expand Down
4 changes: 2 additions & 2 deletions lmfdb/backend/statstable.py
Original file line number Diff line number Diff line change
Expand Up @@ -545,7 +545,7 @@ def column_counts(self, cols, constraint=None, threshold=1, split_list=False):
ccols, cvals, allcols = Json([]), Json([]), cols
else:
ccols, cvals = self._split_dict(constraint)
allcols = sorted(list(set(cols + list(constraint))))
allcols = sorted(set(cols + list(constraint)))
# Ideally we would include the constraint in the query, but it's not easy to do that
# So we check the results in Python
jcols = Json(cols)
Expand Down Expand Up @@ -1155,7 +1155,7 @@ def _process_constraint(self, cols, constraint):
else:
ccols, cvals = self._split_dict(constraint)
# We need to include the constraints in the count table if we're not grouping by that column
allcols = sorted(list(set(cols + list(constraint))))
allcols = sorted(set(cols + list(constraint)))
if any(key.startswith("$") for key in constraint):
raise ValueError("Top level special keys not allowed")
qstr, values = self.table._parse_dict(constraint)
Expand Down
8 changes: 4 additions & 4 deletions lmfdb/characters/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ def render_DirichletNavigation():
headers, entries, rows, cols = get_character_modulus(modulus_start, modulus_end, limit=8)
info['entries'] = entries
info['rows'] = list(range(modulus_start, modulus_end + 1))
info['cols'] = sorted(list({r[1] for r in entries}))
info['cols'] = sorted({r[1] for r in entries})
return render_template("ModulusList.html", **info)
except ValueError as err:
flash_error("Error raised in parsing: %s", err)
Expand Down Expand Up @@ -428,7 +428,7 @@ def render_Dirichletwebpage(modulus=None, orbit_label=None, number=None):
info['title'] = 'Group of Dirichlet characters of modulus ' + str(modulus)
info['bread'] = bread([('%s' % modulus, url_for(".render_Dirichletwebpage", modulus=modulus))])
info['learnmore'] = learn()
info['code'] = dict([(k[4:], info[k]) for k in info if k[0:4] == "code"])
info['code'] = {k[4:]: info[k] for k in info if k[0:4] == "code"}
info['code']['show'] = {lang: '' for lang in info['codelangs']} # use default show names
if 'gens' in info:
info['generators'] = ', '.join(r'<a href="%s">$\chi_{%s}(%s,\cdot)$' % (url_for(".render_Dirichletwebpage", modulus=modulus, number=g), modulus, g) for g in info['gens'])
Expand All @@ -446,7 +446,7 @@ def render_Dirichletwebpage(modulus=None, orbit_label=None, number=None):
info['show_orbit_label'] = True
info['downloads'] = [('Underlying data', url_for('.dirchar_data', label=f"{modulus}.{orbit_label}"))]
info['learnmore'] = learn()
info['code'] = dict([(k[4:], info[k]) for k in info if k[0:4] == "code"])
info['code'] = {k[4:]: info[k] for k in info if k[0:4] == "code"}
info['code']['show'] = {lang: '' for lang in info['codelangs']} # use default show names
info['bread'] = bread(
[('%s' % modulus, url_for(".render_Dirichletwebpage", modulus=modulus)),
Expand Down Expand Up @@ -509,7 +509,7 @@ def render_Dirichletwebpage(modulus=None, orbit_label=None, number=None):
info['bread'] = bread_crumbs
info['learnmore'] = learn()
info['downloads'] = downloads
info['code'] = dict([(k[4:], info[k]) for k in info if k[0:4] == "code"])
info['code'] = {k[4:]: info[k] for k in info if k[0:4] == "code"}
info['code']['show'] = {lang: '' for lang in info['codelangs']} # use default show names
info['KNOWL_ID'] = 'character.dirichlet.%s.%s' % (modulus, number)
return render_template('Character.html', **info)
Expand Down
8 changes: 4 additions & 4 deletions lmfdb/characters/web_character.py
Original file line number Diff line number Diff line change
Expand Up @@ -681,9 +681,9 @@ def _set_galoisorbit(self, gal_orbit):
return
upper_limit = min(31, self.order + 1)
gal_orbit = gal_orbit[:upper_limit]
self.galoisorbit = list(
self.galoisorbit = [
self._char_desc(num, prim=self.isprimitive) for num in gal_orbit
)
]

def _set_kernel_field_poly(self):
if self.order <= 100:
Expand Down Expand Up @@ -1165,9 +1165,9 @@ def _populate_from_db(self):
self.rowtruncate = True
self.galorbnums = self.first_chi.galois_orbit(upper_limit)
logger.info(f"[WebDBDirichletOrbit.populate] found galois orbit {self.galorbnums}")
self.galoisorbit = list(
self.galoisorbit = [
self._char_desc(num, prim=orbit_data['is_primitive']) for num in self.galorbnums
)
]

def _set_kernel_field_poly(self, orbit_data):
an_orbit_rep = int(orbit_data['first_label'].split(".")[1])
Expand Down
4 changes: 2 additions & 2 deletions lmfdb/classical_modular_forms/web_newform.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,8 +286,8 @@ def __init__(self, data, space=None, all_m=False, all_n=False, embedding_label=N
# Breadcrumbs
@property
def bread(self):
kwds = dict(level=self.level, weight=self.weight, char_orbit_label=self.char_orbit_label,
hecke_orbit=cremona_letter_code(self.hecke_orbit - 1))
kwds = {"level": self.level, "weight": self.weight, "char_orbit_label": self.char_orbit_label,
"hecke_orbit": cremona_letter_code(self.hecke_orbit - 1)}
if self.embedding_label is not None:
kwds['embedding_label'] = self.embedding_label
return get_bread(**kwds)
Expand Down
2 changes: 1 addition & 1 deletion lmfdb/classical_modular_forms/web_space.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ def url_sign_char(x): return "-" if x else "%2B"
continue
b = list(reversed(ZZ(i).bits()))
b = [0 for j in range(num_primes-len(b))] + b
row = list(map(lambda x:r'<td>\(%s\)</td>'%sign_char(x),b))
row = [r'<td>\(%s\)</td>'%sign_char(x) for x in b]
sign = sum(b) % 2
if num_primes > 1:
row.append(r"<td class='right'>$%s$</td>"%sign_char(sign))
Expand Down
2 changes: 1 addition & 1 deletion lmfdb/ecnf/isog_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ def make_graph(M):
def make_iso_matrix(clist): # clist is a list of ECNFs
Elist = [E.E for E in clist]
cl = Elist[0].isogeny_class()
perm = dict([(i, cl.index(E)) for i, E in enumerate(Elist)])
perm = {i: cl.index(E) for i, E in enumerate(Elist)}
return permute_mat(cl.matrix(), perm, True)


Expand Down
4 changes: 2 additions & 2 deletions lmfdb/elliptic_curves/elliptic_curve.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,8 @@ def rational_elliptic_curves(err_args=None):
counts = get_stats()

conductor_list_endpoints = [1, 100, 1000, 10000, 100000, int(counts.max_N_Cremona) + 1]
conductor_list = dict([(r,r) for r in ["%s-%s" % (start, end - 1) for start, end in zip(conductor_list_endpoints[:-1],
conductor_list_endpoints[1:])]])
conductor_list = {r: r for r in ["%s-%s" % (start, end - 1) for start, end in zip(conductor_list_endpoints[:-1],
conductor_list_endpoints[1:])]}
conductor_list[">{}".format(counts.max_N_Cremona)] = "{}-".format(counts.max_N_Cremona)

rank_list = list(range(counts.max_rank + 1))
Expand Down
2 changes: 1 addition & 1 deletion lmfdb/elliptic_curves/web_ec.py
Original file line number Diff line number Diff line change
Expand Up @@ -646,7 +646,7 @@ def make_mwbsd(self):
mwbsd['heights'] = [RR(h) for h in mwbsd['heights']]

# Mordell-Weil group
invs = [0 for a in range(self.rank)] + [n for n in self.torsion_structure]
invs = [0 for a in range(self.rank)] + list(self.torsion_structure)
mwbsd['mw_struct'] = "trivial" if len(invs) == 0 else r'\(' + r' \oplus '.join((r'\Z' if n == 0 else r'\Z/{%s}\Z' % n) for n in invs) + r'\)'

# Torsion structure and generators:
Expand Down
6 changes: 3 additions & 3 deletions lmfdb/galois_groups/transitive_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -858,12 +858,12 @@ def complete_group_codes(codes):

# Load all sibling representations from the database
labels = ["%sT%s" % elt[0] for elt in aliases.values()]
siblings = dict(
(elt["label"], [tuple(z[0]) for z in elt["siblings"]])
siblings = {
elt["label"]: [tuple(z[0]) for z in elt["siblings"]]
for elt in db.gps_transitive.search(
{"label": {"$in": labels}}, ["label", "siblings"]
)
)
}
for ky in aliases.keys():
nt = aliases[ky][0]
label = "%sT%s"% nt
Expand Down
2 changes: 1 addition & 1 deletion lmfdb/genus2_curves/web_g2c.py
Original file line number Diff line number Diff line change
Expand Up @@ -508,7 +508,7 @@ def split_statement(coeffs, labels, condnorms):
# Otherwise give defining equation:
else:
statement += r"<br>&nbsp;&nbsp;\(y^2 = x^3 - g_4 / 48 x - g_6 / 864\) with"
statement += r"<br>&nbsp;&nbsp;\(g_4 = %s\)<br>&nbsp;&nbsp;\(g_6 = %s\)" % tuple(map (lambda x: strlist_to_nfelt(x, 'b'),coeffs[n]))
statement += r"<br>&nbsp;&nbsp;\(g_4 = %s\)<br>&nbsp;&nbsp;\(g_6 = %s\)" % tuple((strlist_to_nfelt(x, 'b') for x in coeffs[n]))
statement += "<br>&nbsp;&nbsp; Conductor norm: %s" % condnorms[n]
return statement

Expand Down
6 changes: 2 additions & 4 deletions lmfdb/groups/abstract/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -520,8 +520,7 @@ def create_boolean_string(gp, type="normal"):
"quasisimple",
"almost_simple",
]
short_show = set(
[
short_show = {
"cyclic",
"abelian",
"nonabelian",
Expand All @@ -530,8 +529,7 @@ def create_boolean_string(gp, type="normal"):
"nab_simple",
"nonsolvable",
"nab_perfect",
]
)
}
short_string = type == "knowl"

# Implications should give edges of a DAG, and should be listed in the group.properties_interdependencies knowl
Expand Down
6 changes: 3 additions & 3 deletions lmfdb/groups/abstract/web_groups.py
Original file line number Diff line number Diff line change
Expand Up @@ -1109,7 +1109,7 @@ def impose_limit(n):
if any(H.aut_label is None or H.diagramx is None for H in subs):
# We don't know subgroups up to automorphism or can't lay out the subgroups
return 0
return impose_limit(len(set(H.aut_label for H in subs)))
return impose_limit(len({H.aut_label for H in subs}))
else:
if self.outer_equivalence or any(H.diagramx is None for H in subs):
# We don't know subgroups up to conjugacy or can't lay out subgroups
Expand Down Expand Up @@ -1490,7 +1490,7 @@ def aut_class_counts(self):

@lazy_attribute
def tex_images(self):
all_tex = list(set(H.subgroup_tex for H in self.subgroups.values())) + ["?"]
all_tex = list({H.subgroup_tex for H in self.subgroups.values()}) + ["?"]
return {
rec["label"]: rec["image"]
for rec in db.gps_images.search({"label": {"$in": all_tex}}, ["label", "image"])
Expand Down Expand Up @@ -2159,7 +2159,7 @@ def FrattiniSubgroup(self):

def Phiquotient(self):
# Make all exponents by 1
snf1 = [prod([z for z in ZZ(n).prime_factors()]) for n in self.snf]
snf1 = [prod(list(ZZ(n).prime_factors())) for n in self.snf]
return LiveAbelianGroup(snf1)

def FittingSubgroup(self):
Expand Down
2 changes: 1 addition & 1 deletion lmfdb/hilbert_modular_forms/hmf_stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def counts(self):

attrs = ["degree", "discriminant", "label"]
fields = list(db.hmf_fields.search({}, attrs, sort=attrs))
degrees = sorted(set(F["degree"] for F in fields))
degrees = sorted({F["degree"] for F in fields})
by_deg = {d: [F for F in fields if F["degree"] == d] for d in degrees}
counts["degrees"] = degrees
counts["nfields"] = len(fields)
Expand Down
4 changes: 2 additions & 2 deletions lmfdb/homepage/sidebar.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ def linked_name(item, level=""):
"""
if level == "heading":
if 'url_for' in item:
url = url_for(item['url_for'],**item.get('url_args',dict()))
url = url_for(item['url_for'],**item.get('url_args',{}))
return ''.join(['<h2 class="link"><a href="',url,'">',item['title'],'</a></h2>\n'])
else:
return ''.join(['<h2>',item['title'],'</h2>\n'])

else:
if 'url_for' in item and not ('status' in item and item['status'] == 'future'):
url = url_for(item['url_for'],**item.get('url_args',dict()))
url = url_for(item['url_for'],**item.get('url_args',{}))
this_entry = ''.join(['<a href="',url,'">',item['title'],'</a>'])
else:
this_entry = item['title']
Expand Down
2 changes: 1 addition & 1 deletion lmfdb/hypergm/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -603,7 +603,7 @@ def parse_pandt(info, family):

try:
if info.get('t'):
info['ts'] = sorted(list(set(map(QQ, info.get('t').split(",")))))
info['ts'] = sorted(set(map(QQ, info.get('t').split(","))))
info['t'] = ",".join(map(str, info['ts']))
else:
info['ts'] = None
Expand Down
19 changes: 9 additions & 10 deletions lmfdb/knowledge/knowl.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,7 @@
# this one is different from the hashtag regex in main.py,
# because of the match-group ( ... )
hashtag_keywords = re.compile(r'#[a-zA-Z][a-zA-Z0-9-_]{1,}\b')
common_words = set(
['and', 'an', 'or', 'some', 'many', 'has', 'have', 'not', 'too', 'mathbb', 'title', 'for'])
common_words = {'and', 'an', 'or', 'some', 'many', 'has', 'have', 'not', 'too', 'mathbb', 'title', 'for'}

# categories, level 0, never change this id
#CAT_ID = 'categories'
Expand Down Expand Up @@ -110,7 +109,7 @@ def extract_typ(kid):


def extract_links(content):
return sorted(set(x[2] for x in link_finder_re.findall(content) if x[2]))
return sorted({x[2] for x in link_finder_re.findall(content) if x[2]})


def normalize_define(term):
Expand All @@ -122,7 +121,7 @@ def normalize_define(term):


def extract_defines(content):
return sorted(set(x.strip() for x in defines_finder_re.findall(content)))
return sorted({x.strip() for x in defines_finder_re.findall(content)})

# We don't use the PostgresTable from lmfdb.backend.database
# since it's aimed at constructing queries for mathematical objects
Expand All @@ -145,7 +144,7 @@ def titles(self):
now = time.time()
if now - self.cached_titles_timestamp > self.caching_time:
self.cached_titles_timestamp = now
self.cached_titles = dict([(elt['id'], elt['title']) for elt in self.get_all_knowls(['id','title'])])
self.cached_titles = {elt['id']: elt['title'] for elt in self.get_all_knowls(['id','title'])}
return self.cached_titles

@property
Expand Down Expand Up @@ -180,7 +179,7 @@ def get_knowl(self, ID,
if not beta:
cur = self._execute(selecter, [ID, 1])
if cur.rowcount > 0:
return {k:v for k,v in zip(fields, cur.fetchone())}
return dict(zip(fields, cur.fetchone()))
cur = self._execute(selecter, [ID, -2 if allow_deleted else 0])
if cur.rowcount > 0:
return dict(zip(fields, cur.fetchone()))
Expand Down Expand Up @@ -462,7 +461,7 @@ def orphans(self, old=False, beta=None):
"""
Returns lists of knowl ids (grouped by category) that are not referenced by any code or other knowl.
"""
kids = set(k['id'] for k in self.get_all_knowls(['id'], types=[0]) if not any(k['id'].startswith(x) for x in ["users.", "test."]))
kids = {k['id'] for k in self.get_all_knowls(['id'], types=[0]) if not any(k['id'].startswith(x) for x in ["users.", "test."])}

def filter_from_matches(pattern):
matches = subprocess.check_output(['git', 'grep', '-E', '--full-name', '--line-number', '--context', '2', pattern],encoding='utf-8').split('\n--\n')
Expand Down Expand Up @@ -666,7 +665,7 @@ def broken_links_code(self):
as in ``code_references``, and ``links`` is a list of purported knowl
ids that show up in an expression of the form ``KNOWL('BAD_ID')``.
"""
all_kids = set(k['id'] for k in self.get_all_knowls(['id']))
all_kids = {k['id'] for k in self.get_all_knowls(['id'])}
if sys.version_info[0] == 3:
matches = subprocess.check_output(['git', 'grep', '-E', '--full-name', '--line-number', '--context', '2', link_finder_re.pattern],encoding='utf-8').split('\n--\n')
else:
Expand Down Expand Up @@ -854,9 +853,9 @@ def __init__(self, ID, template_kwargs=None, data=None, editing=False, showing=F
# "status":0}]
uids = [ elt['last_author'] for elt in self.edit_history]
if uids:
full_names = dict([ (elt['username'], elt['full_name']) for elt in userdb.full_names(uids)])
full_names = {elt['username']: elt['full_name'] for elt in userdb.full_names(uids)}
else:
full_names = dict({})
full_names = {}
self.previous_review_spot = None
for i, elt in enumerate(self.edit_history):
elt['ms_timestamp'] = datetime_to_timestamp_in_ms(elt['timestamp'])
Expand Down
2 changes: 1 addition & 1 deletion lmfdb/knowledge/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -748,7 +748,7 @@ def render_knowl(ID, footer=None, kwargs=None,
include *just* the string and not the response object.
"""
# logger.debug("kwargs: %s", request.args)
kwargs = kwargs or dict(((k, v) for k, v in request.args.items()))
kwargs = kwargs or dict(request.args.items())
# logger.debug("kwargs: %s" , kwargs)
if timestamp is None:
# fetch and convert the ms timestamp to datetime
Expand Down
Loading

0 comments on commit 5b3b6f3

Please sign in to comment.