mirror of
https://github.com/kovidgoyal/calibre.git
synced 2025-07-09 03:04:10 -04:00
Automated fixes from ruff
This commit is contained in:
parent
f7f0cf059f
commit
d7c31f4a81
@ -810,7 +810,8 @@ def main(args, ext_dir, test_runner):
|
|||||||
build_dir = abspath(join(mkdtemp('frozen-'), APPNAME + '.app'))
|
build_dir = abspath(join(mkdtemp('frozen-'), APPNAME + '.app'))
|
||||||
inc_dir = abspath(mkdtemp('include'))
|
inc_dir = abspath(mkdtemp('include'))
|
||||||
if args.skip_tests:
|
if args.skip_tests:
|
||||||
test_runner = lambda *a: None
|
def test_runner(*a):
|
||||||
|
return None
|
||||||
Freeze(build_dir, ext_dir, inc_dir, test_runner, dont_strip=args.dont_strip, sign_installers=args.sign_installers, notarize=args.notarize)
|
Freeze(build_dir, ext_dir, inc_dir, test_runner, dont_strip=args.dont_strip, sign_installers=args.sign_installers, notarize=args.notarize)
|
||||||
|
|
||||||
|
|
||||||
|
@ -40,7 +40,8 @@ if py3:
|
|||||||
from urllib.parse import urlparse
|
from urllib.parse import urlparse
|
||||||
from urllib.request import BaseHandler, build_opener, Request, urlopen, getproxies, addinfourl
|
from urllib.request import BaseHandler, build_opener, Request, urlopen, getproxies, addinfourl
|
||||||
import http.client as httplib
|
import http.client as httplib
|
||||||
encode_for_subprocess = lambda x: x
|
def encode_for_subprocess(x):
|
||||||
|
return x
|
||||||
else:
|
else:
|
||||||
from future_builtins import map
|
from future_builtins import map
|
||||||
from urlparse import urlparse
|
from urlparse import urlparse
|
||||||
|
@ -156,7 +156,8 @@ def load_plugins_index():
|
|||||||
|
|
||||||
def convert_node(fields, x, names={}, import_data=None):
|
def convert_node(fields, x, names={}, import_data=None):
|
||||||
name = x.__class__.__name__
|
name = x.__class__.__name__
|
||||||
conv = lambda x:convert_node(fields, x, names=names, import_data=import_data)
|
def conv(x):
|
||||||
|
return convert_node(fields, x, names=names, import_data=import_data)
|
||||||
if name == 'Str':
|
if name == 'Str':
|
||||||
return x.s.decode('utf-8') if isinstance(x.s, bytes) else x.s
|
return x.s.decode('utf-8') if isinstance(x.s, bytes) else x.s
|
||||||
elif name == 'Num':
|
elif name == 'Num':
|
||||||
|
@ -77,7 +77,8 @@ def to_unicode(raw, encoding='utf-8', errors='strict'):
|
|||||||
|
|
||||||
def patheq(p1, p2):
|
def patheq(p1, p2):
|
||||||
p = os.path
|
p = os.path
|
||||||
d = lambda x : p.normcase(p.normpath(p.realpath(p.normpath(x))))
|
def d(x):
|
||||||
|
return p.normcase(p.normpath(p.realpath(p.normpath(x))))
|
||||||
if not p1 or not p2:
|
if not p1 or not p2:
|
||||||
return False
|
return False
|
||||||
return d(p1) == d(p2)
|
return d(p1) == d(p2)
|
||||||
|
@ -552,7 +552,7 @@ class CatalogPlugin(Plugin): # {{{
|
|||||||
from calibre.customize.ui import config
|
from calibre.customize.ui import config
|
||||||
from calibre.ptempfile import PersistentTemporaryDirectory
|
from calibre.ptempfile import PersistentTemporaryDirectory
|
||||||
|
|
||||||
if not type(self) in builtin_plugins and self.name not in config['disabled_plugins']:
|
if type(self) not in builtin_plugins and self.name not in config['disabled_plugins']:
|
||||||
files_to_copy = [f"{self.name.lower()}.{ext}" for ext in ["ui","py"]]
|
files_to_copy = [f"{self.name.lower()}.{ext}" for ext in ["ui","py"]]
|
||||||
resources = zipfile.ZipFile(self.plugin_path,'r')
|
resources = zipfile.ZipFile(self.plugin_path,'r')
|
||||||
|
|
||||||
|
@ -180,7 +180,8 @@ def _run_filetype_plugins(path_to_file, ft=None, occasion='preprocess'):
|
|||||||
print('Running file type plugin %s failed with traceback:'%plugin.name, file=oe)
|
print('Running file type plugin %s failed with traceback:'%plugin.name, file=oe)
|
||||||
traceback.print_exc(file=oe)
|
traceback.print_exc(file=oe)
|
||||||
sys.stdout, sys.stderr = oo, oe
|
sys.stdout, sys.stderr = oo, oe
|
||||||
x = lambda j: os.path.normpath(os.path.normcase(j))
|
def x(j):
|
||||||
|
return os.path.normpath(os.path.normcase(j))
|
||||||
if occasion == 'postprocess' and x(nfp) != x(path_to_file):
|
if occasion == 'postprocess' and x(nfp) != x(path_to_file):
|
||||||
shutil.copyfile(nfp, path_to_file)
|
shutil.copyfile(nfp, path_to_file)
|
||||||
nfp = path_to_file
|
nfp = path_to_file
|
||||||
|
@ -41,18 +41,23 @@ def compile_rule(rule):
|
|||||||
if 'with' in mt:
|
if 'with' in mt:
|
||||||
q = icu_lower(rule['query'])
|
q = icu_lower(rule['query'])
|
||||||
if 'startswith' in mt:
|
if 'startswith' in mt:
|
||||||
func = lambda filename: icu_lower(filename).startswith(q)
|
def func(filename):
|
||||||
|
return icu_lower(filename).startswith(q)
|
||||||
else:
|
else:
|
||||||
func = lambda filename: icu_lower(filename).endswith(q)
|
def func(filename):
|
||||||
|
return icu_lower(filename).endswith(q)
|
||||||
elif 'glob' in mt:
|
elif 'glob' in mt:
|
||||||
q = compile_glob(rule['query'])
|
q = compile_glob(rule['query'])
|
||||||
func = lambda filename: q.match(filename) is not None
|
def func(filename):
|
||||||
|
return (q.match(filename) is not None)
|
||||||
else:
|
else:
|
||||||
q = re.compile(rule['query'])
|
q = re.compile(rule['query'])
|
||||||
func = lambda filename: q.match(filename) is not None
|
def func(filename):
|
||||||
|
return (q.match(filename) is not None)
|
||||||
ans = func
|
ans = func
|
||||||
if mt.startswith('not_'):
|
if mt.startswith('not_'):
|
||||||
ans = lambda filename: not func(filename)
|
def ans(filename):
|
||||||
|
return (not func(filename))
|
||||||
return ans, rule['action'] == 'add'
|
return ans, rule['action'] == 'add'
|
||||||
|
|
||||||
|
|
||||||
|
@ -1262,7 +1262,8 @@ class DB:
|
|||||||
import codecs
|
import codecs
|
||||||
from apsw import Shell
|
from apsw import Shell
|
||||||
if callback is None:
|
if callback is None:
|
||||||
callback = lambda x: x
|
def callback(x):
|
||||||
|
return x
|
||||||
uv = int(self.user_version)
|
uv = int(self.user_version)
|
||||||
|
|
||||||
with TemporaryFile(suffix='.sql') as fname:
|
with TemporaryFile(suffix='.sql') as fname:
|
||||||
@ -1587,7 +1588,8 @@ class DB:
|
|||||||
def compress_covers(self, path_map, jpeg_quality, progress_callback):
|
def compress_covers(self, path_map, jpeg_quality, progress_callback):
|
||||||
cpath_map = {}
|
cpath_map = {}
|
||||||
if not progress_callback:
|
if not progress_callback:
|
||||||
progress_callback = lambda book_id, old_sz, new_sz: None
|
def progress_callback(book_id, old_sz, new_sz):
|
||||||
|
return None
|
||||||
for book_id, path in path_map.items():
|
for book_id, path in path_map.items():
|
||||||
path = os.path.abspath(os.path.join(self.library_path, path, 'cover.jpg'))
|
path = os.path.abspath(os.path.join(self.library_path, path, 'cover.jpg'))
|
||||||
try:
|
try:
|
||||||
|
@ -47,7 +47,8 @@ def numeric_sort_key(defval, x):
|
|||||||
return x if type(x) in (int, float) else defval
|
return x if type(x) in (int, float) else defval
|
||||||
|
|
||||||
|
|
||||||
IDENTITY = lambda x: x
|
def IDENTITY(x):
|
||||||
|
return x
|
||||||
|
|
||||||
|
|
||||||
class InvalidLinkTable(Exception):
|
class InvalidLinkTable(Exception):
|
||||||
|
@ -223,7 +223,8 @@ def has_cover_getter(dbref, book_id, cache):
|
|||||||
return ret
|
return ret
|
||||||
|
|
||||||
|
|
||||||
fmt_custom = lambda x:list(x) if isinstance(x, tuple) else x
|
def fmt_custom(x):
|
||||||
|
return (list(x) if isinstance(x, tuple) else x)
|
||||||
|
|
||||||
|
|
||||||
def custom_getter(field, dbref, book_id, cache):
|
def custom_getter(field, dbref, book_id, cache):
|
||||||
|
@ -181,7 +181,8 @@ class LibraryDatabase:
|
|||||||
|
|
||||||
self.is_second_db = is_second_db
|
self.is_second_db = is_second_db
|
||||||
if progress_callback is None:
|
if progress_callback is None:
|
||||||
progress_callback = lambda x, y:True
|
def progress_callback(x, y):
|
||||||
|
return True
|
||||||
self.listeners = set()
|
self.listeners = set()
|
||||||
|
|
||||||
backend = self.backend = create_backend(library_path, default_prefs=default_prefs,
|
backend = self.backend = create_backend(library_path, default_prefs=default_prefs,
|
||||||
|
@ -237,9 +237,11 @@ class NumericSearch: # {{{
|
|||||||
dt = datatype
|
dt = datatype
|
||||||
|
|
||||||
if is_many and query in {'true', 'false'}:
|
if is_many and query in {'true', 'false'}:
|
||||||
valcheck = lambda x: True
|
def valcheck(x):
|
||||||
|
return True
|
||||||
if datatype == 'rating':
|
if datatype == 'rating':
|
||||||
valcheck = lambda x: x is not None and x > 0
|
def valcheck(x):
|
||||||
|
return (x is not None and x > 0)
|
||||||
found = set()
|
found = set()
|
||||||
for val, book_ids in field_iter():
|
for val, book_ids in field_iter():
|
||||||
if valcheck(val):
|
if valcheck(val):
|
||||||
@ -248,14 +250,18 @@ class NumericSearch: # {{{
|
|||||||
|
|
||||||
if query == 'false':
|
if query == 'false':
|
||||||
if location == 'cover':
|
if location == 'cover':
|
||||||
relop = lambda x,y: not bool(x)
|
def relop(x, y):
|
||||||
|
return (not bool(x))
|
||||||
else:
|
else:
|
||||||
relop = lambda x,y: x is None
|
def relop(x, y):
|
||||||
|
return (x is None)
|
||||||
elif query == 'true':
|
elif query == 'true':
|
||||||
if location == 'cover':
|
if location == 'cover':
|
||||||
relop = lambda x,y: bool(x)
|
def relop(x, y):
|
||||||
|
return bool(x)
|
||||||
else:
|
else:
|
||||||
relop = lambda x,y: x is not None
|
def relop(x, y):
|
||||||
|
return (x is not None)
|
||||||
else:
|
else:
|
||||||
for k, relop in iteritems(self.operators):
|
for k, relop in iteritems(self.operators):
|
||||||
if query.startswith(k):
|
if query.startswith(k):
|
||||||
@ -265,8 +271,10 @@ class NumericSearch: # {{{
|
|||||||
relop = self.operators['=']
|
relop = self.operators['=']
|
||||||
|
|
||||||
if dt == 'rating':
|
if dt == 'rating':
|
||||||
cast = lambda x: 0 if x is None else int(x)
|
def cast(x):
|
||||||
adjust = lambda x: x // 2
|
return (0 if x is None else int(x))
|
||||||
|
def adjust(x):
|
||||||
|
return (x // 2)
|
||||||
else:
|
else:
|
||||||
# Datatype is empty if the source is a template. Assume float
|
# Datatype is empty if the source is a template. Assume float
|
||||||
cast = float if dt in ('float', 'composite', 'half-rating', '') else int
|
cast = float if dt in ('float', 'composite', 'half-rating', '') else int
|
||||||
|
@ -186,7 +186,8 @@ class FilesystemTest(BaseTest):
|
|||||||
|
|
||||||
def test_find_books_in_directory(self):
|
def test_find_books_in_directory(self):
|
||||||
from calibre.db.adding import find_books_in_directory, compile_rule
|
from calibre.db.adding import find_books_in_directory, compile_rule
|
||||||
strip = lambda files: frozenset({os.path.basename(x) for x in files})
|
def strip(files):
|
||||||
|
return frozenset({os.path.basename(x) for x in files})
|
||||||
|
|
||||||
def q(one, two):
|
def q(one, two):
|
||||||
one, two = {strip(a) for a in one}, {strip(b) for b in two}
|
one, two = {strip(a) for a in one}, {strip(b) for b in two}
|
||||||
|
@ -57,7 +57,8 @@ def run_funcs(self, db, ndb, funcs):
|
|||||||
if callable(meth):
|
if callable(meth):
|
||||||
meth(*args)
|
meth(*args)
|
||||||
else:
|
else:
|
||||||
fmt = lambda x:x
|
def fmt(x):
|
||||||
|
return x
|
||||||
if meth[0] in {'!', '@', '#', '+', '$', '-', '%'}:
|
if meth[0] in {'!', '@', '#', '+', '$', '-', '%'}:
|
||||||
if meth[0] != '+':
|
if meth[0] != '+':
|
||||||
fmt = {'!':dict, '@':lambda x:frozenset(x or ()), '#':lambda x:set((x or '').split(',')),
|
fmt = {'!':dict, '@':lambda x:frozenset(x or ()), '#':lambda x:set((x or '').split(',')),
|
||||||
@ -256,12 +257,14 @@ class LegacyTest(BaseTest):
|
|||||||
'books_in_series_of':[(0,), (1,), (2,)],
|
'books_in_series_of':[(0,), (1,), (2,)],
|
||||||
'books_with_same_title':[(Metadata(db.title(0)),), (Metadata(db.title(1)),), (Metadata('1234'),)],
|
'books_with_same_title':[(Metadata(db.title(0)),), (Metadata(db.title(1)),), (Metadata('1234'),)],
|
||||||
}):
|
}):
|
||||||
fmt = lambda x: x
|
def fmt(x):
|
||||||
|
return x
|
||||||
if meth[0] in {'!', '@'}:
|
if meth[0] in {'!', '@'}:
|
||||||
fmt = {'!':dict, '@':frozenset}[meth[0]]
|
fmt = {'!':dict, '@':frozenset}[meth[0]]
|
||||||
meth = meth[1:]
|
meth = meth[1:]
|
||||||
elif meth == 'get_authors_with_ids':
|
elif meth == 'get_authors_with_ids':
|
||||||
fmt = lambda val:{x[0]:tuple(x[1:]) for x in val}
|
def fmt(val):
|
||||||
|
return {x[0]: tuple(x[1:]) for x in val}
|
||||||
for a in args:
|
for a in args:
|
||||||
self.assertEqual(fmt(getattr(db, meth)(*a)), fmt(getattr(ndb, meth)(*a)),
|
self.assertEqual(fmt(getattr(db, meth)(*a)), fmt(getattr(ndb, meth)(*a)),
|
||||||
f'The method: {meth}() returned different results for argument {a}')
|
f'The method: {meth}() returned different results for argument {a}')
|
||||||
|
@ -612,9 +612,11 @@ class ReadingTest(BaseTest):
|
|||||||
self.assertSetEqual(set(mi.custom_field_keys()), set(pmi.custom_field_keys()))
|
self.assertSetEqual(set(mi.custom_field_keys()), set(pmi.custom_field_keys()))
|
||||||
|
|
||||||
for field in STANDARD_METADATA_FIELDS | {'#series_index'}:
|
for field in STANDARD_METADATA_FIELDS | {'#series_index'}:
|
||||||
f = lambda x: x
|
def f(x):
|
||||||
|
return x
|
||||||
if field == 'formats':
|
if field == 'formats':
|
||||||
f = lambda x: x if x is None else tuple(x)
|
def f(x):
|
||||||
|
return (x if x is None else tuple(x))
|
||||||
self.assertEqual(f(getattr(mi, field)), f(getattr(pmi, field)),
|
self.assertEqual(f(getattr(mi, field)), f(getattr(pmi, field)),
|
||||||
f'Standard field: {field} not the same for book {book_id}')
|
f'Standard field: {field} not the same for book {book_id}')
|
||||||
self.assertEqual(mi.format_field(field), pmi.format_field(field),
|
self.assertEqual(mi.format_field(field), pmi.format_field(field),
|
||||||
|
@ -23,20 +23,23 @@ class WritingTest(BaseTest):
|
|||||||
def create_getter(self, name, getter=None):
|
def create_getter(self, name, getter=None):
|
||||||
if getter is None:
|
if getter is None:
|
||||||
if name.endswith('_index'):
|
if name.endswith('_index'):
|
||||||
ans = lambda db:partial(db.get_custom_extra, index_is_id=True,
|
def ans(db):
|
||||||
label=name[1:].replace('_index', ''))
|
return partial(db.get_custom_extra, index_is_id=True, label=name[1:].replace('_index', ''))
|
||||||
else:
|
else:
|
||||||
ans = lambda db:partial(db.get_custom, label=name[1:],
|
def ans(db):
|
||||||
index_is_id=True)
|
return partial(db.get_custom, label=name[1:], index_is_id=True)
|
||||||
else:
|
else:
|
||||||
ans = lambda db:partial(getattr(db, getter), index_is_id=True)
|
def ans(db):
|
||||||
|
return partial(getattr(db, getter), index_is_id=True)
|
||||||
return ans
|
return ans
|
||||||
|
|
||||||
def create_setter(self, name, setter=None):
|
def create_setter(self, name, setter=None):
|
||||||
if setter is None:
|
if setter is None:
|
||||||
ans = lambda db:partial(db.set_custom, label=name[1:], commit=True)
|
def ans(db):
|
||||||
|
return partial(db.set_custom, label=name[1:], commit=True)
|
||||||
else:
|
else:
|
||||||
ans = lambda db:partial(getattr(db, setter), commit=True)
|
def ans(db):
|
||||||
|
return partial(getattr(db, setter), commit=True)
|
||||||
return ans
|
return ans
|
||||||
|
|
||||||
def create_test(self, name, vals, getter=None, setter=None):
|
def create_test(self, name, vals, getter=None, setter=None):
|
||||||
|
@ -408,7 +408,8 @@ def atof(string):
|
|||||||
|
|
||||||
def type_safe_sort_key_function(keyfunc=None):
|
def type_safe_sort_key_function(keyfunc=None):
|
||||||
if keyfunc is None:
|
if keyfunc is None:
|
||||||
keyfunc = lambda x: x
|
def keyfunc(x):
|
||||||
|
return x
|
||||||
sentinel = object()
|
sentinel = object()
|
||||||
first_value = sentinel
|
first_value = sentinel
|
||||||
|
|
||||||
|
@ -164,11 +164,13 @@ def get_adapter(name, metadata):
|
|||||||
elif dt == 'comments':
|
elif dt == 'comments':
|
||||||
ans = single_text
|
ans = single_text
|
||||||
elif dt == 'rating':
|
elif dt == 'rating':
|
||||||
ans = lambda x: None if x in {None, 0} else min(10, max(0, adapt_number(int, x)))
|
def ans(x):
|
||||||
|
return (None if x in {None, 0} else min(10, max(0, adapt_number(int, x))))
|
||||||
elif dt == 'enumeration':
|
elif dt == 'enumeration':
|
||||||
ans = single_text
|
ans = single_text
|
||||||
elif dt == 'composite':
|
elif dt == 'composite':
|
||||||
ans = lambda x: x
|
def ans(x):
|
||||||
|
return x
|
||||||
|
|
||||||
if name == 'title':
|
if name == 'title':
|
||||||
return lambda x: ans(x) or _('Unknown')
|
return lambda x: ans(x) or _('Unknown')
|
||||||
|
@ -48,7 +48,6 @@ class ANDROID(USBMS):
|
|||||||
0x0cf5 : HTC_BCDS,
|
0x0cf5 : HTC_BCDS,
|
||||||
0x2910 : HTC_BCDS,
|
0x2910 : HTC_BCDS,
|
||||||
0xe77 : HTC_BCDS,
|
0xe77 : HTC_BCDS,
|
||||||
0xff9 : HTC_BCDS,
|
|
||||||
0x0001 : [0x255],
|
0x0001 : [0x255],
|
||||||
},
|
},
|
||||||
|
|
||||||
|
@ -45,9 +45,11 @@ def strip_encoding_declarations(raw, limit=50*1024, preserve_newlines=False):
|
|||||||
is_binary = isinstance(raw, bytes)
|
is_binary = isinstance(raw, bytes)
|
||||||
if preserve_newlines:
|
if preserve_newlines:
|
||||||
if is_binary:
|
if is_binary:
|
||||||
sub = lambda m: b'\n' * m.group().count(b'\n')
|
def sub(m):
|
||||||
|
return (b'\n' * m.group().count(b'\n'))
|
||||||
else:
|
else:
|
||||||
sub = lambda m: '\n' * m.group().count('\n')
|
def sub(m):
|
||||||
|
return ('\n' * m.group().count('\n'))
|
||||||
else:
|
else:
|
||||||
sub = b'' if is_binary else ''
|
sub = b'' if is_binary else ''
|
||||||
for pat in lazy_encoding_pats(is_binary):
|
for pat in lazy_encoding_pats(is_binary):
|
||||||
|
@ -63,9 +63,11 @@ def find_pages(dir, sort_on_mtime=False, verbose=False):
|
|||||||
# levels, in which case simply use the filenames.
|
# levels, in which case simply use the filenames.
|
||||||
basename = os.path.basename if len(sep_counts) > 1 else lambda x: x
|
basename = os.path.basename if len(sep_counts) > 1 else lambda x: x
|
||||||
if sort_on_mtime:
|
if sort_on_mtime:
|
||||||
key = lambda x:os.stat(x).st_mtime
|
def key(x):
|
||||||
|
return os.stat(x).st_mtime
|
||||||
else:
|
else:
|
||||||
key = lambda x:numeric_sort_key(basename(x))
|
def key(x):
|
||||||
|
return numeric_sort_key(basename(x))
|
||||||
|
|
||||||
pages.sort(key=key)
|
pages.sort(key=key)
|
||||||
if verbose:
|
if verbose:
|
||||||
|
@ -193,7 +193,8 @@ class HTMLOutput(OutputFormatPlugin):
|
|||||||
|
|
||||||
# render template
|
# render template
|
||||||
templite = Templite(template_html_data)
|
templite = Templite(template_html_data)
|
||||||
toc = lambda: self.generate_html_toc(oeb_book, path, output_dir)
|
def toc():
|
||||||
|
return self.generate_html_toc(oeb_book, path, output_dir)
|
||||||
t = templite.render(ebookContent=ebook_content,
|
t = templite.render(ebookContent=ebook_content,
|
||||||
prevLink=prevLink, nextLink=nextLink,
|
prevLink=prevLink, nextLink=nextLink,
|
||||||
has_toc=bool(oeb_book.toc.count()), toc=toc,
|
has_toc=bool(oeb_book.toc.count()), toc=toc,
|
||||||
|
@ -500,8 +500,10 @@ class BZZDecoder():
|
|||||||
# Decode
|
# Decode
|
||||||
mtfno = 3
|
mtfno = 3
|
||||||
markerpos = -1
|
markerpos = -1
|
||||||
zc = lambda i: self.zpcodec_decode(self.ctx, i)
|
def zc(i):
|
||||||
dc = lambda i, bits: self.decode_binary(self.ctx, i, bits)
|
return self.zpcodec_decode(self.ctx, i)
|
||||||
|
def dc(i, bits):
|
||||||
|
return self.decode_binary(self.ctx, i, bits)
|
||||||
for i in range(self.xsize):
|
for i in range(self.xsize):
|
||||||
ctxid = CTXIDS - 1
|
ctxid = CTXIDS - 1
|
||||||
if ctxid > mtfno:
|
if ctxid > mtfno:
|
||||||
|
@ -247,7 +247,8 @@ def test_parse_fields(return_tests=False):
|
|||||||
class TestParseFields(unittest.TestCase):
|
class TestParseFields(unittest.TestCase):
|
||||||
|
|
||||||
def test_hyperlink(self):
|
def test_hyperlink(self):
|
||||||
ae = lambda x, y: self.assertEqual(parse_hyperlink(x, None), y)
|
def ae(x, y):
|
||||||
|
return self.assertEqual(parse_hyperlink(x, None), y)
|
||||||
ae(r'\l anchor1', {'anchor':'anchor1'})
|
ae(r'\l anchor1', {'anchor':'anchor1'})
|
||||||
ae(r'www.calibre-ebook.com', {'url':'www.calibre-ebook.com'})
|
ae(r'www.calibre-ebook.com', {'url':'www.calibre-ebook.com'})
|
||||||
ae(r'www.calibre-ebook.com \t target \o tt', {'url':'www.calibre-ebook.com', 'target':'target', 'title': 'tt'})
|
ae(r'www.calibre-ebook.com \t target \o tt', {'url':'www.calibre-ebook.com', 'target':'target', 'title': 'tt'})
|
||||||
@ -255,13 +256,15 @@ def test_parse_fields(return_tests=False):
|
|||||||
ae(r'xxxx \y yyyy', {'url': 'xxxx'})
|
ae(r'xxxx \y yyyy', {'url': 'xxxx'})
|
||||||
|
|
||||||
def test_xe(self):
|
def test_xe(self):
|
||||||
ae = lambda x, y: self.assertEqual(parse_xe(x, None), y)
|
def ae(x, y):
|
||||||
|
return self.assertEqual(parse_xe(x, None), y)
|
||||||
ae(r'"some name"', {'text':'some name'})
|
ae(r'"some name"', {'text':'some name'})
|
||||||
ae(r'name \b \i', {'text':'name', 'bold':None, 'italic':None})
|
ae(r'name \b \i', {'text':'name', 'bold':None, 'italic':None})
|
||||||
ae(r'xxx \y a', {'text':'xxx', 'yomi':'a'})
|
ae(r'xxx \y a', {'text':'xxx', 'yomi':'a'})
|
||||||
|
|
||||||
def test_index(self):
|
def test_index(self):
|
||||||
ae = lambda x, y: self.assertEqual(parse_index(x, None), y)
|
def ae(x, y):
|
||||||
|
return self.assertEqual(parse_index(x, None), y)
|
||||||
ae(r'', {})
|
ae(r'', {})
|
||||||
ae(r'\b \c 1', {'bookmark':None, 'columns-per-page': '1'})
|
ae(r'\b \c 1', {'bookmark':None, 'columns-per-page': '1'})
|
||||||
|
|
||||||
|
@ -64,7 +64,8 @@ class CombinedStyle:
|
|||||||
|
|
||||||
def serialize(self, styles, normal_style):
|
def serialize(self, styles, normal_style):
|
||||||
makeelement = self.namespace.makeelement
|
makeelement = self.namespace.makeelement
|
||||||
w = lambda x: '{{{}}}{}'.format(self.namespace.namespaces['w'], x)
|
def w(x):
|
||||||
|
return '{{{}}}{}'.format(self.namespace.namespaces['w'], x)
|
||||||
block = makeelement(styles, 'w:style', w_styleId=self.id, w_type='paragraph')
|
block = makeelement(styles, 'w:style', w_styleId=self.id, w_type='paragraph')
|
||||||
makeelement(block, 'w:name', w_val=self.name)
|
makeelement(block, 'w:name', w_val=self.name)
|
||||||
makeelement(block, 'w:qFormat')
|
makeelement(block, 'w:qFormat')
|
||||||
|
@ -28,7 +28,8 @@ class Parser:
|
|||||||
# No leading zeros, except for numbers in (0, 1) and no trailing zeros for the fractional part
|
# No leading zeros, except for numbers in (0, 1) and no trailing zeros for the fractional part
|
||||||
frac = r'\.[0-9]*[1-9]'
|
frac = r'\.[0-9]*[1-9]'
|
||||||
number = r'(?:[1-9][0-9]*(?:{0})?)|(?:0{0})|(?:0)'.format(frac)
|
number = r'(?:[1-9][0-9]*(?:{0})?)|(?:0{0})|(?:0)'.format(frac)
|
||||||
c = lambda x:regex.compile(x, flags=regex.VERSION1)
|
def c(x):
|
||||||
|
return regex.compile(x, flags=regex.VERSION1)
|
||||||
|
|
||||||
# A step of the form /integer
|
# A step of the form /integer
|
||||||
self.step_pat = c(r'/(%s)' % integer)
|
self.step_pat = c(r'/(%s)' % integer)
|
||||||
|
@ -811,7 +811,8 @@ class HTMLConverter:
|
|||||||
for x, y in [('\xad', ''), ('\xa0', ' '), ('\ufb00', 'ff'), ('\ufb01', 'fi'), ('\ufb02', 'fl'), ('\ufb03', 'ffi'), ('\ufb04', 'ffl')]:
|
for x, y in [('\xad', ''), ('\xa0', ' '), ('\ufb00', 'ff'), ('\ufb01', 'fi'), ('\ufb02', 'fl'), ('\ufb03', 'ffi'), ('\ufb04', 'ffl')]:
|
||||||
src = src.replace(x, y)
|
src = src.replace(x, y)
|
||||||
|
|
||||||
valigner = lambda x: x
|
def valigner(x):
|
||||||
|
return x
|
||||||
if 'vertical-align' in css:
|
if 'vertical-align' in css:
|
||||||
valign = css['vertical-align']
|
valign = css['vertical-align']
|
||||||
if valign in ('sup', 'super', 'sub'):
|
if valign in ('sup', 'super', 'sub'):
|
||||||
|
@ -54,8 +54,10 @@ def reset_field_metadata():
|
|||||||
field_metadata = FieldMetadata()
|
field_metadata = FieldMetadata()
|
||||||
|
|
||||||
|
|
||||||
ck = lambda typ: icu_lower(typ).strip().replace(':', '').replace(',', '')
|
def ck(typ):
|
||||||
cv = lambda val: val.strip().replace(',', '|')
|
return icu_lower(typ).strip().replace(':', '').replace(',', '')
|
||||||
|
def cv(val):
|
||||||
|
return val.strip().replace(',', '|')
|
||||||
|
|
||||||
|
|
||||||
class Metadata:
|
class Metadata:
|
||||||
|
@ -38,7 +38,8 @@ def short_be(buf):
|
|||||||
|
|
||||||
|
|
||||||
def get_metadata(f):
|
def get_metadata(f):
|
||||||
read = lambda at, amount: _read(f, at, amount)
|
def read(at, amount):
|
||||||
|
return _read(f, at, amount)
|
||||||
f.seek(0)
|
f.seek(0)
|
||||||
buf = f.read(12)
|
buf = f.read(12)
|
||||||
if buf[4:] == b'ftypLRX2':
|
if buf[4:] == b'ftypLRX2':
|
||||||
|
@ -1652,7 +1652,8 @@ def metadata_to_opf(mi, as_string=True, default_lang=None):
|
|||||||
if mi.tags:
|
if mi.tags:
|
||||||
for tag in mi.tags:
|
for tag in mi.tags:
|
||||||
factory(DC('subject'), tag)
|
factory(DC('subject'), tag)
|
||||||
meta = lambda n, c: factory('meta', name='calibre:'+n, content=c)
|
def meta(n, c):
|
||||||
|
return factory('meta', name='calibre:' + n, content=c)
|
||||||
if getattr(mi, 'author_link_map', None) is not None:
|
if getattr(mi, 'author_link_map', None) is not None:
|
||||||
meta('author_link_map', dump_dict(mi.author_link_map))
|
meta('author_link_map', dump_dict(mi.author_link_map))
|
||||||
if mi.series:
|
if mi.series:
|
||||||
|
@ -21,7 +21,8 @@ def get_metadata(stream):
|
|||||||
return mi
|
return mi
|
||||||
stream.read(10)
|
stream.read(10)
|
||||||
|
|
||||||
read_i32 = lambda: struct.unpack('<I', stream.read(4))[0]
|
def read_i32():
|
||||||
|
return struct.unpack('<I', stream.read(4))[0]
|
||||||
|
|
||||||
stream.seek(read_i32())
|
stream.seek(read_i32())
|
||||||
toc_count = read_i32()
|
toc_count = read_i32()
|
||||||
|
@ -96,7 +96,8 @@ def parse_details_page(url, log, timeout, browser, domain):
|
|||||||
from calibre.ebooks.metadata.sources.update import search_engines_module
|
from calibre.ebooks.metadata.sources.update import search_engines_module
|
||||||
get_data_for_cached_url = search_engines_module().get_data_for_cached_url
|
get_data_for_cached_url = search_engines_module().get_data_for_cached_url
|
||||||
except Exception:
|
except Exception:
|
||||||
get_data_for_cached_url = lambda *a: None
|
def get_data_for_cached_url(*a):
|
||||||
|
return None
|
||||||
raw = get_data_for_cached_url(url)
|
raw = get_data_for_cached_url(url)
|
||||||
if raw:
|
if raw:
|
||||||
log('Using cached details for url:', url)
|
log('Using cached details for url:', url)
|
||||||
|
@ -509,7 +509,8 @@ def identify(log, abort, # {{{
|
|||||||
am_rules = compile_rules(am_rules)
|
am_rules = compile_rules(am_rules)
|
||||||
|
|
||||||
# normalize unicode strings
|
# normalize unicode strings
|
||||||
n = lambda x: unicodedata.normalize('NFC', as_unicode(x or '', errors='replace'))
|
def n(x):
|
||||||
|
return unicodedata.normalize('NFC', as_unicode(x or '', errors='replace'))
|
||||||
for r in results:
|
for r in results:
|
||||||
if r.tags:
|
if r.tags:
|
||||||
r.tags = list(map(n, r.tags))
|
r.tags = list(map(n, r.tags))
|
||||||
|
@ -542,7 +542,8 @@ def metadata_to_xmp_packet(mi):
|
|||||||
|
|
||||||
|
|
||||||
def find_used_namespaces(elem):
|
def find_used_namespaces(elem):
|
||||||
getns = lambda x: (x.partition('}')[0][1:] if '}' in x else None)
|
def getns(x):
|
||||||
|
return (x.partition('}')[0][1:] if '}' in x else None)
|
||||||
ans = {getns(x) for x in list(elem.attrib) + [elem.tag]}
|
ans = {getns(x) for x in list(elem.attrib) + [elem.tag]}
|
||||||
for child in elem.iterchildren(etree.Element):
|
for child in elem.iterchildren(etree.Element):
|
||||||
ans |= find_used_namespaces(child)
|
ans |= find_used_namespaces(child)
|
||||||
|
@ -37,7 +37,8 @@ class FDST:
|
|||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
ans = ['FDST record']
|
ans = ['FDST record']
|
||||||
a = lambda k, v:ans.append('%s: %s'%(k, v))
|
def a(k, v):
|
||||||
|
return ans.append('%s: %s' % (k, v))
|
||||||
a('Offset to sections', self.sec_off)
|
a('Offset to sections', self.sec_off)
|
||||||
a('Number of section records', self.num_sections)
|
a('Number of section records', self.num_sections)
|
||||||
ans.append('**** %d Sections ****'% len(self.sections))
|
ans.append('**** %d Sections ****'% len(self.sections))
|
||||||
|
@ -823,7 +823,8 @@ class MobiReader:
|
|||||||
unpack = decompress_doc
|
unpack = decompress_doc
|
||||||
|
|
||||||
elif self.book_header.compression_type == b'\x00\x01':
|
elif self.book_header.compression_type == b'\x00\x01':
|
||||||
unpack = lambda x: x
|
def unpack(x):
|
||||||
|
return x
|
||||||
else:
|
else:
|
||||||
raise MobiError('Unknown compression algorithm: %r' % self.book_header.compression_type)
|
raise MobiError('Unknown compression algorithm: %r' % self.book_header.compression_type)
|
||||||
self.mobi_html = b''.join(map(unpack, text_sections))
|
self.mobi_html = b''.join(map(unpack, text_sections))
|
||||||
|
@ -640,6 +640,7 @@ def convert_color_for_font_tag(val):
|
|||||||
rgba = parse_color_string(str(val or ''))
|
rgba = parse_color_string(str(val or ''))
|
||||||
if rgba is None or rgba == 'currentColor':
|
if rgba is None or rgba == 'currentColor':
|
||||||
return str(val)
|
return str(val)
|
||||||
clamp = lambda x: min(x, max(0, x), 1)
|
def clamp(x):
|
||||||
|
return min(x, max(0, x), 1)
|
||||||
rgb = map(clamp, rgba[:3])
|
rgb = map(clamp, rgba[:3])
|
||||||
return '#' + ''.join(map(lambda x:'%02x' % int(x * 255), rgb))
|
return '#' + ''.join(map(lambda x:'%02x' % int(x * 255), rgb))
|
||||||
|
@ -14,9 +14,12 @@ from calibre.ebooks.mobi.utils import align_block
|
|||||||
from polyglot.builtins import iteritems, as_bytes
|
from polyglot.builtins import iteritems, as_bytes
|
||||||
|
|
||||||
NULL = 0xffffffff
|
NULL = 0xffffffff
|
||||||
zeroes = lambda x: b'\0'*x
|
def zeroes(x):
|
||||||
nulls = lambda x: b'\xff'*x
|
return (b'\x00' * x)
|
||||||
short = lambda x: pack(b'>H', x)
|
def nulls(x):
|
||||||
|
return (b'\xff' * x)
|
||||||
|
def short(x):
|
||||||
|
return pack(b'>H', x)
|
||||||
|
|
||||||
|
|
||||||
class Header(OrderedDict):
|
class Header(OrderedDict):
|
||||||
|
@ -13,7 +13,8 @@ from calibre.ebooks.mobi.writer8.header import Header
|
|||||||
|
|
||||||
TagMeta_ = namedtuple('TagMeta',
|
TagMeta_ = namedtuple('TagMeta',
|
||||||
'name number values_per_entry bitmask end_flag')
|
'name number values_per_entry bitmask end_flag')
|
||||||
TagMeta = lambda x:TagMeta_(*x)
|
def TagMeta(x):
|
||||||
|
return TagMeta_(*x)
|
||||||
EndTagTable = TagMeta(('eof', 0, 0, 0, 1))
|
EndTagTable = TagMeta(('eof', 0, 0, 0, 1))
|
||||||
|
|
||||||
# map of mask to number of shifts needed, works with 1 bit and two-bit wide masks
|
# map of mask to number of shifts needed, works with 1 bit and two-bit wide masks
|
||||||
|
@ -161,7 +161,8 @@ def update_metadata(ebook, new_opf):
|
|||||||
|
|
||||||
|
|
||||||
def polish_one(ebook, opts, report, customization=None):
|
def polish_one(ebook, opts, report, customization=None):
|
||||||
rt = lambda x: report('\n### ' + x)
|
def rt(x):
|
||||||
|
return report('\n### ' + x)
|
||||||
jacket = None
|
jacket = None
|
||||||
changed = False
|
changed = False
|
||||||
customization = customization or CUSTOMIZATION.copy()
|
customization = customization or CUSTOMIZATION.copy()
|
||||||
|
@ -248,7 +248,8 @@ def apply_func_to_match_groups(match, func=icu_upper, handle_entities=handle_ent
|
|||||||
found_groups = False
|
found_groups = False
|
||||||
i = 0
|
i = 0
|
||||||
parts, pos = [], match.start()
|
parts, pos = [], match.start()
|
||||||
f = lambda text:handle_entities(text, func)
|
def f(text):
|
||||||
|
return handle_entities(text, func)
|
||||||
while True:
|
while True:
|
||||||
i += 1
|
i += 1
|
||||||
try:
|
try:
|
||||||
@ -268,7 +269,8 @@ def apply_func_to_match_groups(match, func=icu_upper, handle_entities=handle_ent
|
|||||||
|
|
||||||
def apply_func_to_html_text(match, func=icu_upper, handle_entities=handle_entities):
|
def apply_func_to_html_text(match, func=icu_upper, handle_entities=handle_entities):
|
||||||
''' Apply the specified function only to text between HTML tag definitions. '''
|
''' Apply the specified function only to text between HTML tag definitions. '''
|
||||||
f = lambda text:handle_entities(text, func)
|
def f(text):
|
||||||
|
return handle_entities(text, func)
|
||||||
parts = re.split(r'(<[^>]+>)', match.group())
|
parts = re.split(r'(<[^>]+>)', match.group())
|
||||||
parts = (x if x.startswith('<') else f(x) for x in parts)
|
parts = (x if x.startswith('<') else f(x) for x in parts)
|
||||||
return ''.join(parts)
|
return ''.join(parts)
|
||||||
|
@ -116,8 +116,6 @@ if another paragraph_def is found, the state changes to collect_tokens.
|
|||||||
'sect-note_' : 'endnotes-in-section',
|
'sect-note_' : 'endnotes-in-section',
|
||||||
# list=> ls
|
# list=> ls
|
||||||
'list-text_' : 'list-text',
|
'list-text_' : 'list-text',
|
||||||
# this line must be wrong because it duplicates an earlier one
|
|
||||||
'list-text_' : 'list-text',
|
|
||||||
'list______' : 'list',
|
'list______' : 'list',
|
||||||
'list-lev-d' : 'list-level-definition',
|
'list-lev-d' : 'list-level-definition',
|
||||||
'list-cardi' : 'list-cardinal-numbering',
|
'list-cardi' : 'list-cardinal-numbering',
|
||||||
|
@ -136,7 +136,6 @@ class Tokenize:
|
|||||||
"&": "&",
|
"&": "&",
|
||||||
"<": "<",
|
"<": "<",
|
||||||
">": ">",
|
">": ">",
|
||||||
"\\~": "\\~ ",
|
|
||||||
"\\_": "\\_ ",
|
"\\_": "\\_ ",
|
||||||
"\\:": "\\: ",
|
"\\:": "\\: ",
|
||||||
"\\-": "\\- ",
|
"\\-": "\\- ",
|
||||||
|
@ -70,11 +70,15 @@ class ConfigWidget(QWidget, Ui_ConfigWidget):
|
|||||||
if isinstance(extra_customization_message, list):
|
if isinstance(extra_customization_message, list):
|
||||||
self.opt_extra_customization = []
|
self.opt_extra_customization = []
|
||||||
if len(extra_customization_message) > 6:
|
if len(extra_customization_message) > 6:
|
||||||
row_func = lambda x, y: ((x//2) * 2) + y
|
def row_func(x, y):
|
||||||
col_func = lambda x: x%2
|
return (x // 2 * 2 + y)
|
||||||
|
def col_func(x):
|
||||||
|
return (x % 2)
|
||||||
else:
|
else:
|
||||||
row_func = lambda x, y: x*2 + y
|
def row_func(x, y):
|
||||||
col_func = lambda x: 0
|
return (x * 2 + y)
|
||||||
|
def col_func(x):
|
||||||
|
return 0
|
||||||
|
|
||||||
for i, m in enumerate(extra_customization_message):
|
for i, m in enumerate(extra_customization_message):
|
||||||
label_text, tt = parse_msg(m)
|
label_text, tt = parse_msg(m)
|
||||||
|
@ -274,11 +274,15 @@ class ExtraCustomization(DeviceConfigTab): # {{{
|
|||||||
if isinstance(extra_customization_message, list):
|
if isinstance(extra_customization_message, list):
|
||||||
self.opt_extra_customization = []
|
self.opt_extra_customization = []
|
||||||
if len(extra_customization_message) > 6:
|
if len(extra_customization_message) > 6:
|
||||||
row_func = lambda x, y: ((x//2) * 2) + y
|
def row_func(x, y):
|
||||||
col_func = lambda x: x%2
|
return (x // 2 * 2 + y)
|
||||||
|
def col_func(x):
|
||||||
|
return (x % 2)
|
||||||
else:
|
else:
|
||||||
row_func = lambda x, y: x*2 + y
|
def row_func(x, y):
|
||||||
col_func = lambda x: 0
|
return (x * 2 + y)
|
||||||
|
def col_func(x):
|
||||||
|
return 0
|
||||||
|
|
||||||
for i, m in enumerate(extra_customization_message):
|
for i, m in enumerate(extra_customization_message):
|
||||||
label_text, tt = parse_msg(m)
|
label_text, tt = parse_msg(m)
|
||||||
|
@ -567,7 +567,8 @@ class CustomRecipes(Dialog):
|
|||||||
|
|
||||||
l.addWidget(self.bb)
|
l.addWidget(self.bb)
|
||||||
self.list_actions = []
|
self.list_actions = []
|
||||||
la = lambda *args:self.list_actions.append(args)
|
def la(*args):
|
||||||
|
return self.list_actions.append(args)
|
||||||
la('plus.png', _('&New recipe'), _('Create a new recipe from scratch'), self.add_recipe)
|
la('plus.png', _('&New recipe'), _('Create a new recipe from scratch'), self.add_recipe)
|
||||||
la('news.png', _('Customize &builtin recipe'), _('Customize a builtin news download source'), self.customize_recipe)
|
la('news.png', _('Customize &builtin recipe'), _('Customize a builtin news download source'), self.customize_recipe)
|
||||||
la('document_open.png', _('Load recipe from &file'), _('Load a recipe from a file'), self.load_recipe)
|
la('document_open.png', _('Load recipe from &file'), _('Load a recipe from a file'), self.load_recipe)
|
||||||
|
@ -127,7 +127,8 @@ def read_theme_from_folder(path):
|
|||||||
return int(x)
|
return int(x)
|
||||||
except Exception:
|
except Exception:
|
||||||
return -1
|
return -1
|
||||||
g = lambda x, defval='': metadata.get(x, defval)
|
def g(x, defval=''):
|
||||||
|
return metadata.get(x, defval)
|
||||||
theme = Theme(g('title'), g('author'), safe_int(g('version', -1)), g('description'), g('license', 'Unknown'), g('url', None))
|
theme = Theme(g('title'), g('author'), safe_int(g('version', -1)), g('description'), g('license', 'Unknown'), g('url', None))
|
||||||
|
|
||||||
ans = Report(path, name_map, extra, missing, theme)
|
ans = Report(path, name_map, extra, missing, theme)
|
||||||
|
@ -11,10 +11,14 @@ from calibre.ebooks.lrf.fonts import LIBERATION_FONT_MAP
|
|||||||
from calibre.ebooks.hyphenate import hyphenate_word
|
from calibre.ebooks.hyphenate import hyphenate_word
|
||||||
from polyglot.builtins import string_or_bytes
|
from polyglot.builtins import string_or_bytes
|
||||||
|
|
||||||
WEIGHT_MAP = lambda wt : int((wt/10)-1)
|
def WEIGHT_MAP(wt):
|
||||||
NULL = lambda a, b: a
|
return int(wt / 10 - 1)
|
||||||
COLOR = lambda a, b: QColor(*a)
|
def NULL(a, b):
|
||||||
WEIGHT = lambda a, b: WEIGHT_MAP(a)
|
return a
|
||||||
|
def COLOR(a, b):
|
||||||
|
return QColor(*a)
|
||||||
|
def WEIGHT(a, b):
|
||||||
|
return WEIGHT_MAP(a)
|
||||||
|
|
||||||
|
|
||||||
class PixmapItem(QGraphicsPixmapItem):
|
class PixmapItem(QGraphicsPixmapItem):
|
||||||
|
@ -783,7 +783,8 @@ if __name__ == '__main__':
|
|||||||
ids = sorted(db.all_ids(), reverse=True)
|
ids = sorted(db.all_ids(), reverse=True)
|
||||||
ids = tuple(zip(ids[0::2], ids[1::2]))
|
ids = tuple(zip(ids[0::2], ids[1::2]))
|
||||||
gm = partial(db.get_metadata, index_is_id=True, get_cover=True, cover_as_data=True)
|
gm = partial(db.get_metadata, index_is_id=True, get_cover=True, cover_as_data=True)
|
||||||
get_metadata = lambda x:list(map(gm, ids[x]))
|
def get_metadata(x):
|
||||||
|
return list(map(gm, ids[x]))
|
||||||
d = CompareMany(list(range(len(ids))), get_metadata, db.field_metadata, db=db)
|
d = CompareMany(list(range(len(ids))), get_metadata, db.field_metadata, db=db)
|
||||||
d.exec()
|
d.exec()
|
||||||
for changed, mi in itervalues(d.accepted):
|
for changed, mi in itervalues(d.accepted):
|
||||||
|
@ -181,7 +181,8 @@ class ResultsModel(QAbstractTableModel): # {{{
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
def sort(self, col, order=Qt.SortOrder.AscendingOrder):
|
def sort(self, col, order=Qt.SortOrder.AscendingOrder):
|
||||||
key = lambda x: x
|
def key(x):
|
||||||
|
return x
|
||||||
if col == 0:
|
if col == 0:
|
||||||
key = attrgetter('gui_rank')
|
key = attrgetter('gui_rank')
|
||||||
elif col == 1:
|
elif col == 1:
|
||||||
@ -196,7 +197,8 @@ class ResultsModel(QAbstractTableModel): # {{{
|
|||||||
elif col == 3:
|
elif col == 3:
|
||||||
key = attrgetter('has_cached_cover_url')
|
key = attrgetter('has_cached_cover_url')
|
||||||
elif key == 4:
|
elif key == 4:
|
||||||
key = lambda x: bool(x.comments)
|
def key(x):
|
||||||
|
return bool(x.comments)
|
||||||
|
|
||||||
self.beginResetModel()
|
self.beginResetModel()
|
||||||
self.results.sort(key=key, reverse=order==Qt.SortOrder.AscendingOrder)
|
self.results.sort(key=key, reverse=order==Qt.SortOrder.AscendingOrder)
|
||||||
|
@ -267,7 +267,8 @@ class TagBrowserMixin: # {{{
|
|||||||
|
|
||||||
db = self.current_db
|
db = self.current_db
|
||||||
if category == 'series':
|
if category == 'series':
|
||||||
key = lambda x:sort_key(title_sort(x))
|
def key(x):
|
||||||
|
return sort_key(title_sort(x))
|
||||||
else:
|
else:
|
||||||
key = sort_key
|
key = sort_key
|
||||||
|
|
||||||
|
@ -69,7 +69,8 @@ def pygments_lexer(filename):
|
|||||||
from pygments.util import ClassNotFound
|
from pygments.util import ClassNotFound
|
||||||
except ImportError:
|
except ImportError:
|
||||||
return None
|
return None
|
||||||
glff = lambda n: get_lexer_for_filename(n, stripnl=False)
|
def glff(n):
|
||||||
|
return get_lexer_for_filename(n, stripnl=False)
|
||||||
try:
|
try:
|
||||||
return glff(filename)
|
return glff(filename)
|
||||||
except ClassNotFound:
|
except ClassNotFound:
|
||||||
|
@ -423,7 +423,8 @@ class Diff(Dialog):
|
|||||||
self.busy.setVisible(True)
|
self.busy.setVisible(True)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
kwargs = lambda name: {'context':self.context, 'beautify':self.beautify, 'syntax':syntax_map.get(name, None)}
|
def kwargs(name):
|
||||||
|
return {'context': self.context, 'beautify': self.beautify, 'syntax': syntax_map.get(name, None)}
|
||||||
|
|
||||||
if isinstance(changed_names, dict):
|
if isinstance(changed_names, dict):
|
||||||
for name, other_name in sorted(iteritems(changed_names), key=lambda x:numeric_sort_key(x[0])):
|
for name, other_name in sorted(iteritems(changed_names), key=lambda x:numeric_sort_key(x[0])):
|
||||||
|
@ -85,7 +85,8 @@ def find_closest_containing_tag(block, offset, max_tags=sys.maxsize):
|
|||||||
''' Find the closest containing tag. To find it, we search for the first
|
''' Find the closest containing tag. To find it, we search for the first
|
||||||
opening tag that does not have a matching closing tag before the specified
|
opening tag that does not have a matching closing tag before the specified
|
||||||
position. Search through at most max_tags. '''
|
position. Search through at most max_tags. '''
|
||||||
prev_tag_boundary = lambda b, o: next_tag_boundary(b, o, forward=False)
|
def prev_tag_boundary(b, o):
|
||||||
|
return next_tag_boundary(b, o, forward=False)
|
||||||
|
|
||||||
block, boundary = prev_tag_boundary(block, offset)
|
block, boundary = prev_tag_boundary(block, offset)
|
||||||
if block is None:
|
if block is None:
|
||||||
|
@ -13,7 +13,8 @@ from calibre.gui2.tweak_book.editor.smarts.utils import (
|
|||||||
get_text_before_cursor, get_leading_whitespace_on_block as lw,
|
get_text_before_cursor, get_leading_whitespace_on_block as lw,
|
||||||
smart_home, smart_backspace, smart_tab)
|
smart_home, smart_backspace, smart_tab)
|
||||||
|
|
||||||
get_leading_whitespace_on_block = lambda editor, previous=False: expand_tabs(lw(editor, previous=previous))
|
def get_leading_whitespace_on_block(editor, previous=False):
|
||||||
|
return expand_tabs(lw(editor, previous=previous))
|
||||||
|
|
||||||
tw = 4 # The tab width (hardcoded to the pep8 value)
|
tw = 4 # The tab width (hardcoded to the pep8 value)
|
||||||
|
|
||||||
|
@ -16,7 +16,8 @@ def get_text_around_cursor(editor, before=True):
|
|||||||
|
|
||||||
|
|
||||||
get_text_before_cursor = get_text_around_cursor
|
get_text_before_cursor = get_text_around_cursor
|
||||||
get_text_after_cursor = lambda editor: get_text_around_cursor(editor, before=False)
|
def get_text_after_cursor(editor):
|
||||||
|
return get_text_around_cursor(editor, before=False)
|
||||||
|
|
||||||
|
|
||||||
def is_cursor_on_wrapped_line(editor):
|
def is_cursor_on_wrapped_line(editor):
|
||||||
|
@ -26,7 +26,8 @@ from calibre.utils.icu import string_length as strlen
|
|||||||
from calibre.utils.localization import localize_user_manual_link
|
from calibre.utils.localization import localize_user_manual_link
|
||||||
from polyglot.builtins import codepoint_to_chr, iteritems, itervalues
|
from polyglot.builtins import codepoint_to_chr, iteritems, itervalues
|
||||||
|
|
||||||
string_length = lambda x: strlen(str(x)) # Needed on narrow python builds, as subclasses of unicode dont work
|
def string_length(x):
|
||||||
|
return strlen(str(x)) # Needed on narrow python builds, as subclasses of unicode dont work
|
||||||
KEY = Qt.Key.Key_J
|
KEY = Qt.Key.Key_J
|
||||||
MODIFIER = Qt.KeyboardModifier.MetaModifier if ismacos else Qt.KeyboardModifier.ControlModifier
|
MODIFIER = Qt.KeyboardModifier.MetaModifier if ismacos else Qt.KeyboardModifier.ControlModifier
|
||||||
|
|
||||||
@ -97,10 +98,12 @@ def escape_funcs():
|
|||||||
if escape is None:
|
if escape is None:
|
||||||
escapem = {('\\' + x):codepoint_to_chr(i+1) for i, x in enumerate('\\${}')}
|
escapem = {('\\' + x):codepoint_to_chr(i+1) for i, x in enumerate('\\${}')}
|
||||||
escape_pat = re.compile('|'.join(map(re.escape, escapem)))
|
escape_pat = re.compile('|'.join(map(re.escape, escapem)))
|
||||||
escape = lambda x: escape_pat.sub(lambda m: escapem[m.group()], x.replace(r'\\', '\x01'))
|
def escape(x):
|
||||||
|
return escape_pat.sub(lambda m: escapem[m.group()], x.replace('\\\\', '\x01'))
|
||||||
unescapem = {v:k[1] for k, v in iteritems(escapem)}
|
unescapem = {v:k[1] for k, v in iteritems(escapem)}
|
||||||
unescape_pat = re.compile('|'.join(unescapem))
|
unescape_pat = re.compile('|'.join(unescapem))
|
||||||
unescape = lambda x:unescape_pat.sub(lambda m:unescapem[m.group()], x)
|
def unescape(x):
|
||||||
|
return unescape_pat.sub(lambda m: unescapem[m.group()], x)
|
||||||
return escape, unescape
|
return escape, unescape
|
||||||
|
|
||||||
|
|
||||||
|
@ -64,9 +64,11 @@ class SimpleUserData(QTextBlockUserData):
|
|||||||
|
|
||||||
class SyntaxHighlighter:
|
class SyntaxHighlighter:
|
||||||
|
|
||||||
create_formats_func = lambda highlighter: {}
|
def create_formats_func(highlighter):
|
||||||
|
return {}
|
||||||
spell_attributes = ()
|
spell_attributes = ()
|
||||||
tag_ok_for_spell = lambda x: False
|
def tag_ok_for_spell(x):
|
||||||
|
return False
|
||||||
user_data_factory = SimpleUserData
|
user_data_factory = SimpleUserData
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
|
@ -142,7 +142,8 @@ class Declaration(QWidget):
|
|||||||
|
|
||||||
def do_layout(self):
|
def do_layout(self):
|
||||||
fm = self.fontMetrics()
|
fm = self.fontMetrics()
|
||||||
bounding_rect = lambda text: fm.boundingRect(0, 0, 10000, 10000, Cell.FLAGS, text)
|
def bounding_rect(text):
|
||||||
|
return fm.boundingRect(0, 0, 10000, 10000, Cell.FLAGS, text)
|
||||||
line_spacing = 2
|
line_spacing = 2
|
||||||
side_margin = Cell.SIDE_MARGIN
|
side_margin = Cell.SIDE_MARGIN
|
||||||
self.rows = []
|
self.rows = []
|
||||||
|
@ -806,7 +806,8 @@ class InsertSemantics(Dialog):
|
|||||||
return QSize(800, 600)
|
return QSize(800, 600)
|
||||||
|
|
||||||
def create_known_type_map(self):
|
def create_known_type_map(self):
|
||||||
_ = lambda x: x
|
def _(x):
|
||||||
|
return x
|
||||||
self.epubtype_guide_map = {v: k for k, v in guide_epubtype_map.items()}
|
self.epubtype_guide_map = {v: k for k, v in guide_epubtype_map.items()}
|
||||||
self.known_type_map = {
|
self.known_type_map = {
|
||||||
'titlepage': _('Title page'),
|
'titlepage': _('Title page'),
|
||||||
|
@ -172,7 +172,8 @@ class BookmarkManager(QWidget):
|
|||||||
def set_bookmarks(self, bookmarks=()):
|
def set_bookmarks(self, bookmarks=()):
|
||||||
csb = self.current_sort_by
|
csb = self.current_sort_by
|
||||||
if csb in ('name', 'title'):
|
if csb in ('name', 'title'):
|
||||||
sk = lambda x: primary_sort_key(x['title'])
|
def sk(x):
|
||||||
|
return primary_sort_key(x['title'])
|
||||||
elif csb == 'timestamp':
|
elif csb == 'timestamp':
|
||||||
sk = itemgetter('timestamp')
|
sk = itemgetter('timestamp')
|
||||||
else:
|
else:
|
||||||
|
@ -363,9 +363,11 @@ def search_in_name(name, search_query, ctx_size=75):
|
|||||||
|
|
||||||
else:
|
else:
|
||||||
spans = []
|
spans = []
|
||||||
miter = lambda: spans
|
def miter():
|
||||||
|
return spans
|
||||||
if raw:
|
if raw:
|
||||||
a = lambda s, l: spans.append((s, s + l))
|
def a(s, l):
|
||||||
|
return spans.append((s, s + l))
|
||||||
primary_collator_without_punctuation().find_all(search_query.text, raw, a, search_query.mode == 'word')
|
primary_collator_without_punctuation().find_all(search_query.text, raw, a, search_query.mode == 'word')
|
||||||
|
|
||||||
for (start, end) in miter():
|
for (start, end) in miter():
|
||||||
|
@ -437,21 +437,26 @@ class ResultCache(SearchQueryParser): # {{{
|
|||||||
|
|
||||||
if val_func is None:
|
if val_func is None:
|
||||||
loc = self.field_metadata[location]['rec_index']
|
loc = self.field_metadata[location]['rec_index']
|
||||||
val_func = lambda item, loc=loc: item[loc]
|
def val_func(item, loc=loc):
|
||||||
|
return item[loc]
|
||||||
q = ''
|
q = ''
|
||||||
cast = adjust = lambda x: x
|
cast = adjust = lambda x: x
|
||||||
dt = self.field_metadata[location]['datatype']
|
dt = self.field_metadata[location]['datatype']
|
||||||
|
|
||||||
if query == 'false':
|
if query == 'false':
|
||||||
if dt == 'rating' or location == 'cover':
|
if dt == 'rating' or location == 'cover':
|
||||||
relop = lambda x,y: not bool(x)
|
def relop(x, y):
|
||||||
|
return (not bool(x))
|
||||||
else:
|
else:
|
||||||
relop = lambda x,y: x is None
|
def relop(x, y):
|
||||||
|
return (x is None)
|
||||||
elif query == 'true':
|
elif query == 'true':
|
||||||
if dt == 'rating' or location == 'cover':
|
if dt == 'rating' or location == 'cover':
|
||||||
relop = lambda x,y: bool(x)
|
def relop(x, y):
|
||||||
|
return bool(x)
|
||||||
else:
|
else:
|
||||||
relop = lambda x,y: x is not None
|
def relop(x, y):
|
||||||
|
return (x is not None)
|
||||||
else:
|
else:
|
||||||
relop = None
|
relop = None
|
||||||
for k in self.numeric_search_relops.keys():
|
for k in self.numeric_search_relops.keys():
|
||||||
@ -462,14 +467,19 @@ class ResultCache(SearchQueryParser): # {{{
|
|||||||
(p, relop) = self.numeric_search_relops['=']
|
(p, relop) = self.numeric_search_relops['=']
|
||||||
|
|
||||||
if dt == 'int':
|
if dt == 'int':
|
||||||
cast = lambda x: int(x)
|
def cast(x):
|
||||||
|
return int(x)
|
||||||
elif dt == 'rating':
|
elif dt == 'rating':
|
||||||
cast = lambda x: 0 if x is None else int(x)
|
def cast(x):
|
||||||
adjust = lambda x: x//2
|
return (0 if x is None else int(x))
|
||||||
|
def adjust(x):
|
||||||
|
return (x // 2)
|
||||||
elif dt in ('float', 'composite'):
|
elif dt in ('float', 'composite'):
|
||||||
cast = lambda x : float(x)
|
def cast(x):
|
||||||
|
return float(x)
|
||||||
else: # count operation
|
else: # count operation
|
||||||
cast = (lambda x: int(x))
|
def cast(x):
|
||||||
|
return int(x)
|
||||||
|
|
||||||
if len(query) > 1:
|
if len(query) > 1:
|
||||||
mult = query[-1:].lower()
|
mult = query[-1:].lower()
|
||||||
@ -720,9 +730,8 @@ class ResultCache(SearchQueryParser): # {{{
|
|||||||
if fm['is_multiple'] and \
|
if fm['is_multiple'] and \
|
||||||
len(query) > 1 and query.startswith('#') and \
|
len(query) > 1 and query.startswith('#') and \
|
||||||
query[1:1] in '=<>!':
|
query[1:1] in '=<>!':
|
||||||
vf = lambda item, loc=fm['rec_index'], \
|
def vf(item, loc=fm['rec_index'], ms=fm['is_multiple']['cache_to_list']):
|
||||||
ms=fm['is_multiple']['cache_to_list']:\
|
return (len(item[loc].split(ms)) if item[loc] is not None else 0)
|
||||||
len(item[loc].split(ms)) if item[loc] is not None else 0
|
|
||||||
return self.get_numeric_matches(location, query[1:],
|
return self.get_numeric_matches(location, query[1:],
|
||||||
candidates, val_func=vf)
|
candidates, val_func=vf)
|
||||||
|
|
||||||
|
@ -1261,7 +1261,7 @@ class CatalogBuilder:
|
|||||||
else:
|
else:
|
||||||
# Validate custom field is usable as a genre source
|
# Validate custom field is usable as a genre source
|
||||||
field_md = self.db.metadata_for_field(self.opts.genre_source_field)
|
field_md = self.db.metadata_for_field(self.opts.genre_source_field)
|
||||||
if field_md is None or not field_md['datatype'] in ['enumeration', 'text']:
|
if field_md is None or field_md['datatype'] not in ['enumeration', 'text']:
|
||||||
all_custom_fields = self.db.custom_field_keys()
|
all_custom_fields = self.db.custom_field_keys()
|
||||||
eligible_custom_fields = []
|
eligible_custom_fields = []
|
||||||
for cf in all_custom_fields:
|
for cf in all_custom_fields:
|
||||||
|
@ -188,7 +188,8 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
|
|||||||
# we need to do it before we call initialize_dynamic
|
# we need to do it before we call initialize_dynamic
|
||||||
if apply_default_prefs and default_prefs is not None:
|
if apply_default_prefs and default_prefs is not None:
|
||||||
if progress_callback is None:
|
if progress_callback is None:
|
||||||
progress_callback = lambda x, y: True
|
def progress_callback(x, y):
|
||||||
|
return True
|
||||||
dbprefs = DBPrefs(self)
|
dbprefs = DBPrefs(self)
|
||||||
progress_callback(None, len(default_prefs))
|
progress_callback(None, len(default_prefs))
|
||||||
for i, key in enumerate(default_prefs):
|
for i, key in enumerate(default_prefs):
|
||||||
@ -1972,32 +1973,39 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
|
|||||||
icon_map[category] = icon
|
icon_map[category] = icon
|
||||||
|
|
||||||
datatype = cat['datatype']
|
datatype = cat['datatype']
|
||||||
avgr = lambda x: 0.0 if x.rc == 0 else x.rt/x.rc
|
def avgr(x):
|
||||||
|
return (0.0 if x.rc == 0 else x.rt / x.rc)
|
||||||
# Duplicate the build of items below to avoid using a lambda func
|
# Duplicate the build of items below to avoid using a lambda func
|
||||||
# in the main Tag loop. Saves a few %
|
# in the main Tag loop. Saves a few %
|
||||||
if datatype == 'rating':
|
if datatype == 'rating':
|
||||||
formatter = (lambda x:'\u2605'*int(x//2))
|
def formatter(x):
|
||||||
avgr = lambda x: x.n
|
return ('★' * int(x // 2))
|
||||||
|
def avgr(x):
|
||||||
|
return x.n
|
||||||
# eliminate the zero ratings line as well as count == 0
|
# eliminate the zero ratings line as well as count == 0
|
||||||
items = [v for v in tcategories[category].values() if v.c > 0 and v.n != 0]
|
items = [v for v in tcategories[category].values() if v.c > 0 and v.n != 0]
|
||||||
elif category == 'authors':
|
elif category == 'authors':
|
||||||
# Clean up the authors strings to human-readable form
|
# Clean up the authors strings to human-readable form
|
||||||
formatter = (lambda x: x.replace('|', ','))
|
def formatter(x):
|
||||||
|
return x.replace('|', ',')
|
||||||
items = [v for v in tcategories[category].values() if v.c > 0]
|
items = [v for v in tcategories[category].values() if v.c > 0]
|
||||||
elif category == 'languages':
|
elif category == 'languages':
|
||||||
# Use a human readable language string
|
# Use a human readable language string
|
||||||
formatter = calibre_langcode_to_name
|
formatter = calibre_langcode_to_name
|
||||||
items = [v for v in tcategories[category].values() if v.c > 0]
|
items = [v for v in tcategories[category].values() if v.c > 0]
|
||||||
else:
|
else:
|
||||||
formatter = (lambda x:str(x))
|
def formatter(x):
|
||||||
|
return str(x)
|
||||||
items = [v for v in tcategories[category].values() if v.c > 0]
|
items = [v for v in tcategories[category].values() if v.c > 0]
|
||||||
|
|
||||||
# sort the list
|
# sort the list
|
||||||
if sort == 'name':
|
if sort == 'name':
|
||||||
kf = lambda x:sort_key(x.s)
|
def kf(x):
|
||||||
|
return sort_key(x.s)
|
||||||
reverse=False
|
reverse=False
|
||||||
elif sort == 'popularity':
|
elif sort == 'popularity':
|
||||||
kf = lambda x: x.c
|
def kf(x):
|
||||||
|
return x.c
|
||||||
reverse=True
|
reverse=True
|
||||||
else:
|
else:
|
||||||
kf = avgr
|
kf = avgr
|
||||||
@ -3597,7 +3605,8 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
|
|||||||
|
|
||||||
def move_library_to(self, newloc, progress=None):
|
def move_library_to(self, newloc, progress=None):
|
||||||
if progress is None:
|
if progress is None:
|
||||||
progress = lambda x:x
|
def progress(x):
|
||||||
|
return x
|
||||||
if not os.path.exists(newloc):
|
if not os.path.exists(newloc):
|
||||||
os.makedirs(newloc)
|
os.makedirs(newloc)
|
||||||
old_dirs = set()
|
old_dirs = set()
|
||||||
|
@ -1136,7 +1136,8 @@ X-GNOME-UsesNotifications=true
|
|||||||
|
|
||||||
|
|
||||||
def get_appdata():
|
def get_appdata():
|
||||||
_ = lambda x: x # Make sure the text below is not translated, but is marked for translation
|
def _(x):
|
||||||
|
return x # Make sure the text below is not translated, but is marked for translation
|
||||||
return {
|
return {
|
||||||
'calibre-gui': {
|
'calibre-gui': {
|
||||||
'name':'calibre',
|
'name':'calibre',
|
||||||
|
@ -19,7 +19,8 @@ NS_MAP = {
|
|||||||
'manifest': 'http://openoffice.org/2001/manifest',
|
'manifest': 'http://openoffice.org/2001/manifest',
|
||||||
}
|
}
|
||||||
|
|
||||||
XPath = lambda x: etree.XPath(x, namespaces=NS_MAP)
|
def XPath(x):
|
||||||
|
return etree.XPath(x, namespaces=NS_MAP)
|
||||||
BUILTIN_LOCALES = {'en-US', 'en-GB', 'es-ES'}
|
BUILTIN_LOCALES = {'en-US', 'en-GB', 'es-ES'}
|
||||||
|
|
||||||
|
|
||||||
|
@ -2167,7 +2167,6 @@ utf8enc2latex_mapping = { # {{{
|
|||||||
# Items from simple list
|
# Items from simple list
|
||||||
'\u0106': "{\\a\\'C}",
|
'\u0106': "{\\a\\'C}",
|
||||||
'\u0408': '{\\CYRJE}',
|
'\u0408': '{\\CYRJE}',
|
||||||
'\u20ac': '{\\texteuro}',
|
|
||||||
'\u2191': '{\\textuparrow}',
|
'\u2191': '{\\textuparrow}',
|
||||||
'\u0493': '{\\cyrghcrs}',
|
'\u0493': '{\\cyrghcrs}',
|
||||||
'\u2116': '{\\textnumero}',
|
'\u2116': '{\\textnumero}',
|
||||||
|
@ -151,7 +151,8 @@ def dt_factory(time_t, assume_utc=False, as_utc=True):
|
|||||||
return dt.astimezone(_utc_tz if as_utc else _local_tz)
|
return dt.astimezone(_utc_tz if as_utc else _local_tz)
|
||||||
|
|
||||||
|
|
||||||
safeyear = lambda x: min(max(x, MINYEAR), MAXYEAR)
|
def safeyear(x):
|
||||||
|
return min(max(x, MINYEAR), MAXYEAR)
|
||||||
|
|
||||||
|
|
||||||
def qt_to_dt(qdate_or_qdatetime, as_utc=True):
|
def qt_to_dt(qdate_or_qdatetime, as_utc=True):
|
||||||
|
@ -231,7 +231,8 @@ def capitalize(x):
|
|||||||
try:
|
try:
|
||||||
swapcase = _icu.swap_case
|
swapcase = _icu.swap_case
|
||||||
except AttributeError: # For people running from source
|
except AttributeError: # For people running from source
|
||||||
swapcase = lambda x:x.swapcase()
|
def swapcase(x):
|
||||||
|
return x.swapcase()
|
||||||
|
|
||||||
find = make_two_arg_func(collator, 'find')
|
find = make_two_arg_func(collator, 'find')
|
||||||
primary_find = make_two_arg_func(primary_collator, 'find')
|
primary_find = make_two_arg_func(primary_collator, 'find')
|
||||||
|
@ -120,7 +120,8 @@ class TestICU(unittest.TestCase):
|
|||||||
self.ae((0, 5), icu.primary_no_punc_find('abcd', 'ab cd'))
|
self.ae((0, 5), icu.primary_no_punc_find('abcd', 'ab cd'))
|
||||||
# test find all
|
# test find all
|
||||||
m = []
|
m = []
|
||||||
a = lambda p,l : m.append((p, l))
|
def a(p, l):
|
||||||
|
return m.append((p, l))
|
||||||
icu.primary_collator_without_punctuation().find_all('a', 'a a🐱a', a)
|
icu.primary_collator_without_punctuation().find_all('a', 'a a🐱a', a)
|
||||||
self.ae(m, [(0, 1), (2, 1), (5, 1)])
|
self.ae(m, [(0, 1), (2, 1), (5, 1)])
|
||||||
# test find whole words
|
# test find whole words
|
||||||
|
@ -334,9 +334,11 @@ class Tester(SearchQueryParser):
|
|||||||
if location in self.fields.keys():
|
if location in self.fields.keys():
|
||||||
getter = operator.itemgetter(self.fields[location])
|
getter = operator.itemgetter(self.fields[location])
|
||||||
elif location == 'all':
|
elif location == 'all':
|
||||||
getter = lambda y: ''.join(x if x else '' for x in y)
|
def getter(y):
|
||||||
|
return ''.join(x if x else '' for x in y)
|
||||||
else:
|
else:
|
||||||
getter = lambda x: ''
|
def getter(x):
|
||||||
|
return ''
|
||||||
|
|
||||||
if not query:
|
if not query:
|
||||||
return set()
|
return set()
|
||||||
|
@ -108,7 +108,6 @@ class WMF:
|
|||||||
247: 'CreatePalette',
|
247: 'CreatePalette',
|
||||||
248: 'CreateBrush',
|
248: 'CreateBrush',
|
||||||
322: 'DibCreatePatternBrush',
|
322: 'DibCreatePatternBrush',
|
||||||
496: 'DeleteObject',
|
|
||||||
505: 'CreatePatternBrush',
|
505: 'CreatePatternBrush',
|
||||||
762: 'CreatePenIndirect',
|
762: 'CreatePenIndirect',
|
||||||
763: 'CreateFontIndirect',
|
763: 'CreateFontIndirect',
|
||||||
|
@ -745,7 +745,8 @@ by William Shakespeare
|
|||||||
def test_select_shakespeare(self):
|
def test_select_shakespeare(self):
|
||||||
document = html.document_fromstring(self.HTML_SHAKESPEARE)
|
document = html.document_fromstring(self.HTML_SHAKESPEARE)
|
||||||
select = Select(document)
|
select = Select(document)
|
||||||
count = lambda s: sum(1 for r in select(s))
|
def count(s):
|
||||||
|
return sum(1 for r in select(s))
|
||||||
|
|
||||||
# Data borrowed from http://mootools.net/slickspeed/
|
# Data borrowed from http://mootools.net/slickspeed/
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user