Get rid of more xrange

This commit is contained in:
Kovid Goyal 2019-03-13 18:19:24 +05:30
parent ea33a5d6ad
commit 2d4127f7b9
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
33 changed files with 122 additions and 114 deletions

View File

@ -14,6 +14,7 @@ from calibre.gui2.tools import generate_catalog
from calibre.utils.config import dynamic
from calibre.gui2.actions import InterfaceAction
from calibre import sanitize_file_name_unicode
from polyglot.builtins import range
class GenerateCatalogAction(InterfaceAction):
@ -34,7 +35,7 @@ class GenerateCatalogAction(InterfaceAction):
def generate_catalog(self):
rows = self.gui.library_view.selectionModel().selectedRows()
if not rows or len(rows) < 2:
rows = xrange(self.gui.library_view.model().rowCount(QModelIndex()))
rows = range(self.gui.library_view.model().rowCount(QModelIndex()))
ids = map(self.gui.library_view.model().id, rows)
if not ids:

View File

@ -11,7 +11,7 @@ from calibre.gui2.convert.heuristics_ui import Ui_Form
from calibre.gui2.convert import Widget
from calibre.utils.localization import localize_user_manual_link
from calibre.ebooks.conversion.config import OPTIONS
from polyglot.builtins import unicode_type
from polyglot.builtins import unicode_type, range
class HeuristicsWidget(Widget, Ui_Form):
@ -92,7 +92,7 @@ class HeuristicsWidget(Widget, Ui_Form):
def save_histories(self):
rssb_history = []
history_pats = [unicode_type(self.opt_replace_scene_breaks.lineEdit().text())] + [unicode_type(self.opt_replace_scene_breaks.itemText(i))
for i in xrange(self.opt_replace_scene_breaks.count())]
for i in range(self.opt_replace_scene_breaks.count())]
for p in history_pats[:10]:
# Ensure we don't have duplicate items.
if p not in rssb_history:

View File

@ -17,7 +17,7 @@ from calibre.constants import iswindows
from calibre.utils.ipc.simple_worker import fork_job, WorkerError
from calibre.ebooks.conversion.search_replace import compile_regular_expression
from calibre.ptempfile import TemporaryFile
from polyglot.builtins import unicode_type
from polyglot.builtins import unicode_type, range
class RegexBuilder(QDialog, Ui_RegexBuilder):
@ -107,7 +107,7 @@ class RegexBuilder(QDialog, Ui_RegexBuilder):
pos = self.preview.textCursor().position()
if self.match_locs:
match_loc = len(self.match_locs) - 1
for i in xrange(len(self.match_locs) - 1, -1, -1):
for i in range(len(self.match_locs) - 1, -1, -1):
loc = self.match_locs[i][1]
if pos > loc:
match_loc = i
@ -118,7 +118,7 @@ class RegexBuilder(QDialog, Ui_RegexBuilder):
pos = self.preview.textCursor().position()
if self.match_locs:
match_loc = 0
for i in xrange(len(self.match_locs)):
for i in range(len(self.match_locs)):
loc = self.match_locs[i][0]
if pos < loc:
match_loc = i

View File

@ -16,7 +16,7 @@ from calibre import as_unicode
from calibre.utils.localization import localize_user_manual_link
from calibre.ebooks.conversion.search_replace import compile_regular_expression
from calibre.ebooks.conversion.config import OPTIONS
from polyglot.builtins import unicode_type
from polyglot.builtins import unicode_type, range
class SearchAndReplaceWidget(Widget, Ui_Form):
@ -140,7 +140,7 @@ class SearchAndReplaceWidget(Widget, Ui_Form):
def cell_rearrange(self, i):
row = self.search_replace.currentRow()
for col in xrange(0, self.search_replace.columnCount()):
for col in range(0, self.search_replace.columnCount()):
item1 = self.search_replace.item(row, col)
item2 = self.search_replace.item(row+i, col)
value = item1.text()
@ -228,9 +228,9 @@ class SearchAndReplaceWidget(Widget, Ui_Form):
def get_definitions(self):
ans = []
for row in xrange(0, self.search_replace.rowCount()):
for row in range(0, self.search_replace.rowCount()):
colItems = []
for col in xrange(0, self.search_replace.columnCount()):
for col in range(0, self.search_replace.columnCount()):
colItems.append(unicode_type(self.search_replace.item(row, col).text()))
ans.append(colItems)
return ans

View File

@ -28,7 +28,7 @@ from calibre.ebooks.conversion.plumber import create_dummy_plumber
from calibre.ebooks.conversion.config import delete_specifics
from calibre.customize.conversion import OptionRecommendation
from calibre.utils.config import prefs
from polyglot.builtins import unicode_type
from polyglot.builtins import unicode_type, range
class GroupModel(QAbstractListModel):
@ -116,7 +116,7 @@ class Config(QDialog, Ui_Dialog):
@property
def manually_fine_tune_toc(self):
for i in xrange(self.stack.count()):
for i in range(self.stack.count()):
w = self.stack.widget(i)
if hasattr(w, 'manually_fine_tune_toc'):
return w.manually_fine_tune_toc.isChecked()

View File

@ -14,6 +14,7 @@ from PyQt5.Qt import (
from calibre.gui2.dbus_export.utils import setup_for_cli_run
from calibre.gui2.dbus_export.widgets import factory
from polyglot.builtins import range
setup_for_cli_run()
@ -45,13 +46,13 @@ class MainWindow(QMainWindow):
q.triggered.connect(QApplication.quit)
self.addAction(q)
QApplication.instance().setWindowIcon(s.standardIcon(s.SP_ComputerIcon))
for i, icon in zip(xrange(3), map(s.standardIcon, (s.SP_DialogOkButton, s.SP_DialogHelpButton, s.SP_ArrowUp))):
for i, icon in zip(range(3), map(s.standardIcon, (s.SP_DialogOkButton, s.SP_DialogHelpButton, s.SP_ArrowUp))):
ac = m.addAction('One - &%d' % (i + 1))
ac.setShortcut(QKeySequence(Qt.CTRL | (Qt.Key_1 + i), Qt.SHIFT | (Qt.Key_1 + i)))
ac.setIcon(icon)
m.addSeparator()
self.menu_two = m2 = m.addMenu('A &submenu')
for i, icon in zip(xrange(3), map(s.standardIcon, (s.SP_DialogOkButton, s.SP_DialogCancelButton, s.SP_ArrowUp))):
for i, icon in zip(range(3), map(s.standardIcon, (s.SP_DialogOkButton, s.SP_DialogCancelButton, s.SP_ArrowUp))):
ac = m2.addAction('Two - &%d' % (i + 1))
ac.setShortcut(QKeySequence(Qt.CTRL | (Qt.Key_A + i)))
ac.setIcon(icon)
@ -98,7 +99,7 @@ class MainWindow(QMainWindow):
def add_menu(self):
mb = self.menu_bar
m = mb.addMenu('Created menu %d' % len(mb.actions()))
for i in xrange(3):
for i in range(3):
m.addAction('Some action %d' % i)
for ac in m.findChildren(QAction):
ac.triggered.connect(self.action_triggered)

View File

@ -12,6 +12,7 @@ from PyQt5.Qt import (
QObject, QMenuBar, QAction, QEvent, QSystemTrayIcon, QApplication, Qt)
from calibre.constants import iswindows, isosx
from polyglot.builtins import range
UNITY_WINDOW_REGISTRAR = ('com.canonical.AppMenu.Registrar', '/com/canonical/AppMenu/Registrar', 'com.canonical.AppMenu.Registrar')
STATUS_NOTIFIER = ("org.kde.StatusNotifierWatcher", "/StatusNotifierWatcher", "org.kde.StatusNotifierWatcher")
@ -233,7 +234,7 @@ class Factory(QObject):
def bus_disconnected(self):
self._bus = None
for i in xrange(5):
for i in range(5):
try:
self.bus
except Exception:

View File

@ -20,7 +20,7 @@ from calibre.gui2 import error_dialog
from calibre.gui2.dialogs.template_dialog import TemplateDialog
from calibre.utils.date import parse_date
from calibre.gui2.device_drivers.mtp_folder_browser import Browser, IgnoredFolders
from polyglot.builtins import unicode_type
from polyglot.builtins import unicode_type, range
class FormatsConfig(QWidget): # {{{
@ -52,7 +52,7 @@ class FormatsConfig(QWidget): # {{{
@property
def format_map(self):
return [unicode_type(self.f.item(i).data(Qt.UserRole) or '') for i in
xrange(self.f.count()) if self.f.item(i).checkState()==Qt.Checked]
range(self.f.count()) if self.f.item(i).checkState()==Qt.Checked]
def validate(self):
if not self.format_map:
@ -189,10 +189,10 @@ class IgnoredDevices(QWidget): # {{{
@property
def blacklist(self):
return [unicode_type(self.f.item(i).data(Qt.UserRole) or '') for i in
xrange(self.f.count()) if self.f.item(i).checkState()==Qt.Checked]
range(self.f.count()) if self.f.item(i).checkState()==Qt.Checked]
def ignore_device(self, snum):
for i in xrange(self.f.count()):
for i in range(self.f.count()):
i = self.f.item(i)
c = unicode_type(i.data(Qt.UserRole) or '')
if c == snum:

View File

@ -13,7 +13,7 @@ from PyQt5.Qt import (QTabWidget, QTreeWidget, QTreeWidgetItem, Qt, QDialog,
QDialogButtonBox, QVBoxLayout, QSize, pyqtSignal, QIcon, QLabel)
from calibre.gui2 import file_icon_provider
from polyglot.builtins import unicode_type
from polyglot.builtins import unicode_type, range
def browser_item(f, parent):
@ -165,7 +165,7 @@ class IgnoredFolders(QDialog):
def iterchildren(self, node):
' Iterate over all descendants of node '
for i in xrange(node.childCount()):
for i in range(node.childCount()):
child = node.child(i)
yield child
for gc in self.iterchildren(child):
@ -183,13 +183,13 @@ class IgnoredFolders(QDialog):
def select_all(self):
w = self.tabs.currentWidget()
for i in xrange(w.invisibleRootItem().childCount()):
for i in range(w.invisibleRootItem().childCount()):
c = w.invisibleRootItem().child(i)
c.setCheckState(0, Qt.Checked)
def select_none(self):
w = self.tabs.currentWidget()
for i in xrange(w.invisibleRootItem().childCount()):
for i in range(w.invisibleRootItem().childCount()):
c = w.invisibleRootItem().child(i)
c.setCheckState(0, Qt.Unchecked)

View File

@ -16,7 +16,7 @@ from calibre.utils.config_base import tweaks
from calibre.gui2 import gprefs
from calibre.gui2.complete2 import EditWithComplete
from calibre.ebooks.metadata import string_to_authors
from polyglot.builtins import unicode_type
from polyglot.builtins import unicode_type, range
class ItemDelegate(QStyledItemDelegate):
@ -84,7 +84,7 @@ class List(QListWidget):
self.mark_as_editable()
def mark_as_editable(self):
for i in xrange(self.count()):
for i in range(self.count()):
item = self.item(i)
item.setFlags(item.flags() | Qt.ItemIsEditable)
@ -92,7 +92,7 @@ class List(QListWidget):
item = self.item(i)
q = unicode_type(item.text())
remove = []
for j in xrange(self.count()):
for j in range(self.count()):
if i != j and unicode_type(self.item(j).text()) == q:
remove.append(j)
for x in sorted(remove, reverse=True):
@ -177,7 +177,7 @@ class AuthorsEdit(QDialog):
@property
def authors(self):
ans = []
for i in xrange(self.al.count()):
for i in range(self.al.count()):
ans.append(unicode_type(self.al.item(i).text()))
return ans or [_('Unknown')]

View File

@ -21,7 +21,7 @@ from calibre.gui2.tweak_book.editor.text import TextEdit
from calibre.utils.icu import sort_key
from calibre.web.feeds.recipes.collection import get_builtin_recipe_collection, get_builtin_recipe_by_id
from calibre.utils.localization import localize_user_manual_link
from polyglot.builtins import unicode_type
from polyglot.builtins import unicode_type, range
def is_basic_recipe(src):
@ -383,7 +383,7 @@ class BasicRecipe(QWidget): # {{{
def fget(self):
title = self.title.text().strip()
feeds = [self.feeds.item(i).data(Qt.UserRole) for i in xrange(self.feeds.count())]
feeds = [self.feeds.item(i).data(Qt.UserRole) for i in range(self.feeds.count())]
return options_to_recipe_source(title, self.oldest_article.value(), self.max_articles.value(), feeds)
def fset(self, src):

View File

@ -15,7 +15,7 @@ from PyQt5.Qt import (
from calibre.gui2 import gprefs
from calibre.ebooks.metadata import authors_to_string
from polyglot.builtins import unicode_type
from polyglot.builtins import unicode_type, range
class DuplicatesQuestion(QDialog):
@ -70,12 +70,12 @@ class DuplicatesQuestion(QDialog):
QApplication.clipboard().setText(self.as_text)
def select_all(self):
for i in xrange(self.dup_list.topLevelItemCount()):
for i in range(self.dup_list.topLevelItemCount()):
x = self.dup_list.topLevelItem(i)
x.setCheckState(0, Qt.Checked)
def select_none(self):
for i in xrange(self.dup_list.topLevelItemCount()):
for i in range(self.dup_list.topLevelItemCount()):
x = self.dup_list.topLevelItem(i)
x.setCheckState(0, Qt.Unchecked)
@ -134,7 +134,7 @@ class DuplicatesQuestion(QDialog):
@property
def duplicates(self):
for i in xrange(self.dup_list.topLevelItemCount()):
for i in range(self.dup_list.topLevelItemCount()):
x = self.dup_list.topLevelItem(i)
if x.checkState(0) == Qt.Checked:
yield x.data(0, Qt.UserRole)
@ -142,12 +142,12 @@ class DuplicatesQuestion(QDialog):
@property
def as_text(self):
entries = []
for i in xrange(self.dup_list.topLevelItemCount()):
for i in range(self.dup_list.topLevelItemCount()):
x = self.dup_list.topLevelItem(i)
check = '' if x.checkState(0) == Qt.Checked else ''
title = '%s %s' % (check, unicode_type(x.text(0)))
dups = []
for child in (x.child(j) for j in xrange(x.childCount())):
for child in (x.child(j) for j in range(x.childCount())):
dups.append('\t' + unicode_type(child.text(0)))
entries.append(title + '\n' + '\n'.join(dups))
return '\n\n'.join(entries)

View File

@ -21,6 +21,7 @@ from calibre.gui2 import choose_dir, error_dialog, question_dialog
from calibre.gui2.widgets2 import Dialog
from calibre.utils.exim import all_known_libraries, export, Importer, import_data
from calibre.utils.icu import numeric_sort_key
from polyglot.builtins import range
def disk_usage(path_to_dir, abort=None):
@ -214,7 +215,7 @@ class EximDialog(Dialog):
lambda i, sz: self.lib_list.item(i).setText(self.export_lib_text(self.lib_list.item(i).data(Qt.UserRole), sz))), type=Qt.QueuedConnection)
def get_lib_sizes(self):
for i in xrange(self.lib_list.count()):
for i in range(self.lib_list.count()):
path = self.lib_list.item(i).data(Qt.UserRole)
try:
sz = disk_usage(path, abort=self.abort_disk_usage)

View File

@ -26,13 +26,13 @@ from calibre.utils.date import utcnow
from calibre.utils.network import internet_connected
from calibre import force_unicode
from calibre.utils.localization import get_lang, canonicalize_lang
from polyglot.builtins import unicode_type
from polyglot.builtins import unicode_type, range
def convert_day_time_schedule(val):
day_of_week, hour, minute = val
if day_of_week == -1:
return (tuple(xrange(7)), hour, minute)
return (tuple(range(7)), hour, minute)
return ((day_of_week,), hour, minute)
@ -73,7 +73,7 @@ class DaysOfWeek(Base):
def __init__(self, parent=None):
Base.__init__(self, parent)
self.days = [QCheckBox(force_unicode(calendar.day_abbr[d]),
self) for d in xrange(7)]
self) for d in range(7)]
for i, cb in enumerate(self.days):
row = i % 2
col = i // 2

View File

@ -8,7 +8,7 @@ from calibre.gui2.dialogs.tag_editor_ui import Ui_TagEditor
from calibre.gui2 import question_dialog, error_dialog, gprefs
from calibre.constants import islinux
from calibre.utils.icu import sort_key, primary_contains
from polyglot.builtins import unicode_type
from polyglot.builtins import unicode_type, range
class TagEditor(QDialog, Ui_TagEditor):
@ -213,7 +213,7 @@ class TagEditor(QDialog, Ui_TagEditor):
def filter_tags(self, filter_value, which='available_tags'):
collection = getattr(self, which)
q = icu_lower(unicode_type(filter_value))
for i in xrange(collection.count()): # on every available tag
for i in range(collection.count()): # on every available tag
item = collection.item(i)
item.setHidden(bool(q and not primary_contains(q, unicode_type(item.text()))))

View File

@ -41,7 +41,7 @@ from calibre.ptempfile import PersistentTemporaryFile, SpooledTemporaryFile
from calibre.gui2.languages import LanguagesEdit as LE
from calibre.db import SPOOL_SIZE
from calibre.ebooks.oeb.polish.main import SUPPORTED as EDIT_SUPPORTED
from polyglot.builtins import unicode_type
from polyglot.builtins import unicode_type, range
OK_COLOR = 'rgba(0, 255, 0, 12%)'
ERR_COLOR = 'rgba(255, 0, 0, 12%)'
@ -1049,7 +1049,7 @@ class FormatsManager(QWidget):
return fmt.ext.lower()
def get_format_path(self, db, id_, fmt):
for i in xrange(self.formats.count()):
for i in range(self.formats.count()):
f = self.formats.item(i)
ext = f.ext.lower()
if ext == fmt:

View File

@ -9,7 +9,7 @@ __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import os, weakref
from collections import OrderedDict, namedtuple
from functools import partial
from polyglot.builtins import zip, unicode_type
from polyglot.builtins import zip, unicode_type, range
from PyQt5.Qt import (
QDialog, QWidget, QGridLayout, QLabel, QToolButton, QIcon,
@ -699,7 +699,7 @@ if __name__ == '__main__':
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)
get_metadata = lambda x:map(gm, ids[x])
d = CompareMany(list(xrange(len(ids))), get_metadata, db.field_metadata, db=db)
d = CompareMany(list(range(len(ids))), get_metadata, db.field_metadata, db=db)
if d.exec_() == d.Accepted:
for changed, mi in d.accepted.itervalues():
if changed and mi is not None:

View File

@ -40,7 +40,7 @@ from calibre import force_unicode
from calibre.utils.config import tweaks
from calibre.utils.ipc.simple_worker import fork_job, WorkerError
from calibre.ptempfile import TemporaryDirectory
from polyglot.builtins import unicode_type
from polyglot.builtins import unicode_type, range
# }}}
@ -704,7 +704,7 @@ class CoversModel(QAbstractListModel): # {{{
return 1
return pmap.width()*pmap.height()
dcovers = sorted(self.covers[1:], key=keygen, reverse=True)
cmap = {i:self.plugin_for_index(i) for i in xrange(len(self.covers))}
cmap = {i:self.plugin_for_index(i) for i in range(len(self.covers))}
for i, x in enumerate(self.covers[0:1] + dcovers):
if not x[-1]:
good.append(x)
@ -751,7 +751,7 @@ class CoversModel(QAbstractListModel): # {{{
return
self.beginInsertRows(QModelIndex(), last_row, last_row)
for rows in self.plugin_map.itervalues():
for i in xrange(len(rows)):
for i in range(len(rows)):
if rows[i] >= last_row:
rows[i] += 1
self.plugin_map[plugin].insert(-1, last_row)

View File

@ -67,7 +67,7 @@ class MobileReadStoreDialog(QDialog, Ui_Dialog):
break
self.results_view.setColumnWidth(i, x)
else:
for i in xrange(self.results_view.model().columnCount()):
for i in range(self.results_view.model().columnCount()):
self.results_view.resizeColumnToContents(i)
self.results_view.model().sort_col = self.plugin.config.get('dialog_sort_col', 0)

View File

@ -22,7 +22,7 @@ from calibre.gui2.tweak_book import tprefs
from calibre.gui2.tweak_book.widgets import Dialog, BusyCursor
from calibre.utils.icu import safe_chr as chr
from calibre.utils.unicode_names import character_name_from_code, points_for_word
from polyglot.builtins import unicode_type
from polyglot.builtins import unicode_type, range
ROOT = QModelIndex()
@ -427,7 +427,7 @@ class CategoryModel(QAbstractItemModel):
return (_('Favorites'), list(tprefs['charmap_favorites']))
else:
item = self.categories[pid - 1][1][index.row()]
return (item[0], list(xrange(item[1][0], item[1][1] + 1)))
return (item[0], list(range(item[1][0], item[1][1] + 1)))
def get_char_info(self, char_code):
ipos = bisect(self.starts, char_code) - 1

View File

@ -17,7 +17,7 @@ from calibre.ebooks.oeb.polish.check.main import run_checks, fix_errors
from calibre.gui2 import NO_URL_FORMATTING
from calibre.gui2.tweak_book import tprefs
from calibre.gui2.tweak_book.widgets import BusyCursor
from polyglot.builtins import unicode_type
from polyglot.builtins import unicode_type, range
def icon_for_level(level):
@ -100,7 +100,7 @@ class Check(QSplitter):
def copy_to_clipboard(self):
items = []
for item in (self.items.item(i) for i in xrange(self.items.count())):
for item in (self.items.item(i) for i in range(self.items.count())):
msg = unicode_type(item.text())
msg = prefix_for_level(item.data(Qt.UserRole).level) + msg
items.append(msg)
@ -123,7 +123,7 @@ class Check(QSplitter):
elif url == 'run:check':
self.check_requested.emit()
elif url == 'fix:errors':
errors = [self.items.item(i).data(Qt.UserRole) for i in xrange(self.items.count())]
errors = [self.items.item(i).data(Qt.UserRole) for i in range(self.items.count())]
self.fix_requested.emit(errors)
elif url.startswith('fix:error,'):
num = int(url.rpartition(',')[-1])

View File

@ -15,6 +15,7 @@ from calibre.gui2.tweak_book import current_container
from calibre.gui2.tweak_book.widgets import Dialog
from calibre.gui2.progress_indicator import WaitStack
from calibre.ebooks.oeb.polish.download import get_external_resources, download_external_resources, replace_resources
from polyglot.builtins import range
class ChooseResources(QWidget):
@ -29,7 +30,7 @@ class ChooseResources(QWidget):
l.addWidget(i)
def __iter__(self):
for i in xrange(self.items.count()):
for i in range(self.items.count()):
yield self.items.item(i)
def select_none(self):

View File

@ -39,7 +39,7 @@ from calibre.gui2.tweak_book import (
from calibre.gui2.tweak_book.editor import syntax_from_mime
from calibre.gui2.tweak_book.templates import template_for
from calibre.utils.icu import numeric_sort_key
from polyglot.builtins import iteritems, unicode_type
from polyglot.builtins import iteritems, unicode_type, range
try:
from PyQt5 import sip
@ -273,21 +273,21 @@ class FileList(QTreeWidget):
item.setExpanded(category in state['expanded'])
self.verticalScrollBar().setValue(state['pos'])
for parent in self.categories.itervalues():
for c in (parent.child(i) for i in xrange(parent.childCount())):
for c in (parent.child(i) for i in range(parent.childCount())):
name = unicode_type(c.data(0, NAME_ROLE) or '')
if name in state['selected']:
c.setSelected(True)
def item_from_name(self, name):
for parent in self.categories.itervalues():
for c in (parent.child(i) for i in xrange(parent.childCount())):
for c in (parent.child(i) for i in range(parent.childCount())):
q = unicode_type(c.data(0, NAME_ROLE) or '')
if q == name:
return c
def select_name(self, name, set_as_current_index=False):
for parent in self.categories.itervalues():
for c in (parent.child(i) for i in xrange(parent.childCount())):
for c in (parent.child(i) for i in range(parent.childCount())):
q = unicode_type(c.data(0, NAME_ROLE) or '')
c.setSelected(q == name)
if q == name:
@ -297,7 +297,7 @@ class FileList(QTreeWidget):
def select_names(self, names, current_name=None):
for parent in self.categories.itervalues():
for c in (parent.child(i) for i in xrange(parent.childCount())):
for c in (parent.child(i) for i in range(parent.childCount())):
q = unicode_type(c.data(0, NAME_ROLE) or '')
c.setSelected(q in names)
if q == current_name:
@ -558,7 +558,7 @@ class FileList(QTreeWidget):
def index_of_name(self, name):
for category, parent in self.categories.iteritems():
for i in xrange(parent.childCount()):
for i in range(parent.childCount()):
item = parent.child(i)
if unicode_type(item.data(0, NAME_ROLE) or '') == name:
return (category, i)
@ -671,7 +671,7 @@ class FileList(QTreeWidget):
_('The file(s) %s cannot be deleted.') % ('<b>%s</b>' % ', '.join(bad)), show=True)
text = self.categories['text']
children = (text.child(i) for i in xrange(text.childCount()))
children = (text.child(i) for i in range(text.childCount()))
spine_removals = [(unicode_type(item.data(0, NAME_ROLE) or ''), item.isSelected()) for item in children]
other_removals = {unicode_type(item.data(0, NAME_ROLE) or '') for item in self.selectedItems()
if unicode_type(item.data(0, CATEGORY_ROLE) or '') != 'text'}
@ -684,7 +684,7 @@ class FileList(QTreeWidget):
removals.append(self.categories['text'].child(i))
for category, parent in self.categories.iteritems():
if category != 'text':
for i in xrange(parent.childCount()):
for i in range(parent.childCount()):
child = parent.child(i)
if unicode_type(child.data(0, NAME_ROLE) or '') in other_removals:
removals.append(child)
@ -717,12 +717,12 @@ class FileList(QTreeWidget):
def dropEvent(self, event):
with self:
text = self.categories['text']
pre_drop_order = {text.child(i):i for i in xrange(text.childCount())}
pre_drop_order = {text.child(i):i for i in range(text.childCount())}
super(FileList, self).dropEvent(event)
current_order = {text.child(i):i for i in xrange(text.childCount())}
current_order = {text.child(i):i for i in range(text.childCount())}
if current_order != pre_drop_order:
order = []
for child in (text.child(i) for i in xrange(text.childCount())):
for child in (text.child(i) for i in range(text.childCount())):
name = unicode_type(child.data(0, NAME_ROLE) or '')
linear = bool(child.data(0, LINEAR_ROLE))
order.append([name, linear])
@ -756,7 +756,7 @@ class FileList(QTreeWidget):
def edit_next_file(self, currently_editing=None, backwards=False):
category = self.categories['text']
seen_current = False
items = (category.child(i) for i in xrange(category.childCount()))
items = (category.child(i) for i in range(category.childCount()))
if backwards:
items = reversed(tuple(items))
for item in items:
@ -770,7 +770,7 @@ class FileList(QTreeWidget):
@property
def all_files(self):
return (category.child(i) for category in self.categories.itervalues() for i in xrange(category.childCount()))
return (category.child(i) for category in self.categories.itervalues() for i in range(category.childCount()))
@property
def searchable_names(self):
@ -838,7 +838,7 @@ class FileList(QTreeWidget):
def link_stylesheets(self, names):
s = self.categories['styles']
sheets = [unicode_type(s.child(i).data(0, NAME_ROLE) or '') for i in xrange(s.childCount())]
sheets = [unicode_type(s.child(i).data(0, NAME_ROLE) or '') for i in range(s.childCount())]
if not sheets:
return error_dialog(self, _('No stylesheets'), _(
'This book currently has no stylesheets. You must first create a stylesheet'
@ -871,7 +871,7 @@ class FileList(QTreeWidget):
l.addWidget(bb)
if d.exec_() == d.Accepted:
tprefs['remove_existing_links_when_linking_sheets'] = r.isChecked()
sheets = [unicode_type(s.item(il).text()) for il in xrange(s.count()) if s.item(il).checkState() == Qt.Checked]
sheets = [unicode_type(s.item(il).text()) for il in range(s.count()) if s.item(il).checkState() == Qt.Checked]
if sheets:
self.link_stylesheets_requested.emit(names, sheets, r.isChecked())

View File

@ -8,7 +8,7 @@ __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
from operator import attrgetter, methodcaller
from collections import namedtuple
from polyglot.builtins import map, unicode_type
from polyglot.builtins import map, unicode_type, range
from itertools import product
from copy import copy, deepcopy
@ -102,7 +102,7 @@ class BasicSettings(QWidget): # {{{
widget.defaults = prefs.defaults[name]
def getter(w):
return list(map(unicode_type, (w.item(i).text() for i in xrange(w.count()))))
return list(map(unicode_type, (w.item(i).text() for i in range(w.count()))))
def setter(w, val):
order_map = {x:i for i, x in enumerate(val)}
@ -452,7 +452,7 @@ class ToolbarSettings(QWidget):
def read_settings(self, prefs=None):
prefs = prefs or tprefs
val = self.original_settings = {}
for i in xrange(1, self.bars.count()):
for i in range(1, self.bars.count()):
name = unicode_type(self.bars.itemData(i) or '')
val[name] = copy(prefs[name])
self.current_settings = deepcopy(val)
@ -724,7 +724,7 @@ class Preferences(QDialog):
cl.setCurrentRow(0)
cl.item(0).setSelected(True)
w, h = cl.sizeHintForColumn(0), 0
for i in xrange(cl.count()):
for i in range(cl.count()):
h = cl.sizeHintForRow(i)
cl.item(i).setSizeHint(QSize(w, h))
@ -744,7 +744,7 @@ class Preferences(QDialog):
return self.toolbars_panel.changed
def restore_all_defaults(self):
for i in xrange(self.stacks.count()):
for i in range(self.stacks.count()):
w = self.stacks.widget(i)
w.restore_defaults()
@ -768,7 +768,7 @@ class Preferences(QDialog):
def accept(self):
tprefs.set('preferences_geom', bytearray(self.saveGeometry()))
for i in xrange(self.stacks.count()):
for i in range(self.stacks.count()):
w = self.stacks.widget(i)
w.commit()
QDialog.accept(self)

View File

@ -8,7 +8,7 @@ __copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>'
import time, textwrap, os
from threading import Thread
from polyglot.builtins import map
from polyglot.builtins import map, range
from operator import itemgetter
from functools import partial
from collections import defaultdict
@ -76,7 +76,7 @@ class ProxyModel(QSortFilterProxyModel):
if not self._filter_text:
return True
sm = self.sourceModel()
for item in (sm.data(sm.index(row, c, parent)) or '' for c in xrange(sm.columnCount())):
for item in (sm.data(sm.index(row, c, parent)) or '' for c in range(sm.columnCount())):
if item and primary_contains(self._filter_text, item):
return True
return False
@ -147,7 +147,7 @@ class FilesView(QTableView):
if self.model().rowCount() > 0:
num = min(5, self.model().rowCount())
h = 1000000
for i in xrange(num):
for i in range(num):
self.resizeRowToContents(i)
h = min(h, self.rowHeight(i))
self.verticalHeader().setDefaultSectionSize(h)
@ -198,8 +198,8 @@ class FilesView(QTableView):
w = csv_writer(buf)
w.writerow(self.proxy.sourceModel().COLUMN_HEADERS)
cols = self.proxy.columnCount()
for r in xrange(self.proxy.rowCount()):
items = [self.proxy.index(r, c).data(Qt.DisplayRole) for c in xrange(cols)]
for r in range(self.proxy.rowCount()):
items = [self.proxy.index(r, c).data(Qt.DisplayRole) for c in range(cols)]
w.writerow(items)
return buf.getvalue()
@ -1092,7 +1092,7 @@ class CSSWidget(QWidget):
buf = BytesIO()
w = csv_writer(buf)
w.writerow([_('Style Rule'), _('Number of matches')])
for r in xrange(self.proxy.rowCount()):
for r in range(self.proxy.rowCount()):
entry = self.proxy.mapToSource(self.proxy.index(r, 0)).data(Qt.UserRole)
w.writerow([entry.rule.selector, entry.count])
return buf.getvalue()
@ -1238,7 +1238,7 @@ class ClassesWidget(CSSWidget):
buf = BytesIO()
w = csv_writer(buf)
w.writerow([_('Class'), _('Number of matches')])
for r in xrange(self.proxy.rowCount()):
for r in range(self.proxy.rowCount()):
entry = self.proxy.mapToSource(self.proxy.index(r, 0)).data(Qt.UserRole)
w.writerow([entry.cls, entry.num_of_matches])
return buf.getvalue()
@ -1328,12 +1328,12 @@ class ReportsWidget(QWidget):
if current_page is not None:
self.reports.setCurrentRow(current_page)
self.layout().setContentsMargins(0, 0, 0, 0)
for i in xrange(self.stack.count()):
for i in range(self.stack.count()):
self.stack.widget(i).layout().setContentsMargins(0, 0, 0, 0)
def __call__(self, data):
jump.clear()
for i in xrange(self.stack.count()):
for i in range(self.stack.count()):
st = time.time()
self.stack.widget(i)(data)
if DEBUG:
@ -1343,7 +1343,7 @@ class ReportsWidget(QWidget):
def save(self):
save_state('splitter-state', bytearray(self.splitter.saveState()))
save_state('report-page', self.reports.currentRow())
for i in xrange(self.stack.count()):
for i in range(self.stack.count()):
self.stack.widget(i).save()
def to_csv(self):

View File

@ -34,7 +34,7 @@ from calibre.gui2.tweak_book.widgets import BusyCursor
from calibre.gui2.widgets2 import FlowLayout, HistoryComboBox
from calibre.utils.icu import primary_contains
from calibre.ebooks.conversion.search_replace import REGEX_FLAGS, compile_regular_expression
from polyglot.builtins import unicode_type
from polyglot.builtins import unicode_type, range
# The search panel {{{
@ -536,7 +536,7 @@ class SearchesModel(QAbstractListModel):
def __init__(self, parent):
QAbstractListModel.__init__(self, parent)
self.searches = tprefs['saved_searches']
self.filtered_searches = list(xrange(len(self.searches)))
self.filtered_searches = list(range(len(self.searches)))
def rowCount(self, parent=QModelIndex()):
return len(self.filtered_searches)
@ -647,7 +647,7 @@ class SearchesModel(QAbstractListModel):
def add_searches(self, count=1):
self.beginResetModel()
self.searches = tprefs['saved_searches']
self.filtered_searches.extend(xrange(len(self.searches) - count, len(self.searches), 1))
self.filtered_searches.extend(range(len(self.searches) - count, len(self.searches), 1))
self.endResetModel()
def remove_searches(self, rows):

View File

@ -37,7 +37,7 @@ from calibre.spell.import_from import import_from_oxt
from calibre.spell.break_iterator import split_into_words
from calibre.utils.localization import calibre_langcode_to_name, get_language, get_lang, canonicalize_lang
from calibre.utils.icu import sort_key, primary_sort_key, primary_contains, contains
from polyglot.builtins import unicode_type
from polyglot.builtins import unicode_type, range
LANG = 0
COUNTRY = 1
@ -147,12 +147,12 @@ class UserWordList(QListWidget):
m.exec_(ev.globalPos())
def select_all(self):
for item in (self.item(i) for i in xrange(self.count())):
for item in (self.item(i) for i in range(self.count())):
item.setSelected(True)
def copy_to_clipboard(self):
words = []
for item in (self.item(i) for i in xrange(self.count())):
for item in (self.item(i) for i in range(self.count())):
if item.isSelected():
words.append(item.data(Qt.UserRole)[0])
if words:
@ -292,7 +292,7 @@ class ManageUserDictionaries(Dialog):
if d is not None:
dictionaries.mark_user_dictionary_as_active(d.name, self.is_active.isChecked())
self.dictionaries_changed = True
for item in (self.dictionaries.item(i) for i in xrange(self.dictionaries.count())):
for item in (self.dictionaries.item(i) for i in range(self.dictionaries.count())):
d = item.data(Qt.UserRole)
item.setData(Qt.FontRole, self.emph_font if d.is_active else None)
@ -386,7 +386,7 @@ class ManageUserDictionaries(Dialog):
def find_word(self, word, lang):
key = (word, lang)
for i in xrange(self.words.count()):
for i in range(self.words.count()):
if self.words.item(i).data(Qt.UserRole) == key:
return i
return -1
@ -557,7 +557,7 @@ class ManageDictionaries(Dialog): # {{{
item = self.dictionaries.currentItem()
bf = QFont(self.dictionaries.font())
bf.setBold(True)
for x in (item.parent().child(i) for i in xrange(item.parent().childCount())):
for x in (item.parent().child(i) for i in range(item.parent().childCount())):
x.setData(0, Qt.FontRole, bf if x is item else None)
lc = unicode_type(item.parent().data(0, Qt.UserRole))
pl = dprefs['preferred_locales']
@ -578,7 +578,7 @@ class ManageDictionaries(Dialog): # {{{
item = self.dictionaries.currentItem()
bf = QFont(self.dictionaries.font())
bf.setItalic(True)
for x in (item.parent().child(i) for i in xrange(item.parent().childCount())):
for x in (item.parent().child(i) for i in range(item.parent().childCount())):
x.setData(0, Qt.FontRole, bf if x is item else None)
cc = unicode_type(item.parent().data(0, Qt.UserRole))
lc = unicode_type(item.parent().parent().data(0, Qt.UserRole))

View File

@ -16,7 +16,7 @@ from calibre.ebooks.oeb.polish.toc import commit_toc, get_toc
from calibre.gui2 import error_dialog
from calibre.gui2.toc.main import TOCView, ItemEdit
from calibre.gui2.tweak_book import current_container, TOP, actions, tprefs
from polyglot.builtins import unicode_type
from polyglot.builtins import unicode_type, range
class TOCEditor(QDialog):
@ -184,7 +184,7 @@ class TOCViewer(QWidget):
def iteritems(self, parent=None):
if parent is None:
parent = self.invisibleRootItem()
for i in xrange(parent.childCount()):
for i in range(parent.childCount()):
child = parent.child(i)
yield child
for gc in self.iteritems(parent=child):

View File

@ -9,7 +9,7 @@ __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import os
from functools import partial
from itertools import product
from polyglot.builtins import map, unicode_type
from polyglot.builtins import map, unicode_type, range
from PyQt5.Qt import (
QDockWidget, Qt, QLabel, QIcon, QAction, QApplication, QWidget, QEvent,
@ -108,14 +108,14 @@ class Central(QStackedWidget): # {{{
def tab_order(self):
ans = []
rmap = {v:k for k, v in editors.iteritems()}
for i in xrange(self.editor_tabs.count()):
for i in range(self.editor_tabs.count()):
name = rmap.get(self.editor_tabs.widget(i))
if name is not None:
ans.append(name)
return ans
def rename_editor(self, editor, name):
for i in xrange(self.editor_tabs.count()):
for i in range(self.editor_tabs.count()):
if self.editor_tabs.widget(i) is editor:
fname = name.rpartition('/')[2]
self.editor_tabs.setTabText(i, fname)
@ -126,7 +126,7 @@ class Central(QStackedWidget): # {{{
self.editor_tabs.setCurrentWidget(editor)
def close_editor(self, editor):
for i in xrange(self.editor_tabs.count()):
for i in range(self.editor_tabs.count()):
if self.editor_tabs.widget(i) is editor:
self.editor_tabs.removeTab(i)
if self.editor_tabs.count() == 0:
@ -136,7 +136,7 @@ class Central(QStackedWidget): # {{{
def editor_modified(self, *args):
tb = self.editor_tabs.tabBar()
for i in xrange(self.editor_tabs.count()):
for i in range(self.editor_tabs.count()):
editor = self.editor_tabs.widget(i)
modified = getattr(editor, 'is_modified', False)
tb.setTabIcon(i, self.modified_icon if modified else QIcon())
@ -152,7 +152,7 @@ class Central(QStackedWidget): # {{{
def close_all_but(self, ed):
close = []
if ed is not None:
for i in xrange(self.editor_tabs.count()):
for i in range(self.editor_tabs.count()):
q = self.editor_tabs.widget(i)
if q is not None and q is not ed:
close.append(q)

View File

@ -14,7 +14,7 @@ from PyQt5.Qt import (
from calibre.gui2 import choose_save_file, choose_files
from calibre.utils.icu import sort_key
from polyglot.builtins import unicode_type
from polyglot.builtins import unicode_type, range
class BookmarksList(QListWidget):
@ -142,7 +142,7 @@ class BookmarkManager(QWidget):
l.scrollToItem(item)
def __iter__(self):
for i in xrange(self.bookmarks_list.count()):
for i in range(self.bookmarks_list.count()):
yield self.item_to_bm(self.bookmarks_list.item(i))
def item_changed(self, item):

View File

@ -22,7 +22,7 @@ from calibre.gui2.viewer.bookmarkmanager import BookmarkManager
from calibre.gui2.viewer.toc import TOCView, TOCSearch
from calibre.gui2.viewer.footnote import FootnotesView
from calibre.utils.localization import is_rtl
from polyglot.builtins import unicode_type
from polyglot.builtins import unicode_type, range
class DoubleSpinBox(QDoubleSpinBox): # {{{
@ -187,7 +187,7 @@ class History(list): # {{{
def test_history():
h = History()
for i in xrange(4):
for i in range(4):
h.add(i)
for i in reversed(h):
h.back(i)

View File

@ -12,11 +12,13 @@ from struct import calcsize, unpack, unpack_from
from collections import namedtuple
from calibre.utils.fonts.utils import get_font_names2, get_font_characteristics
from polyglot.builtins import range
class UnsupportedFont(ValueError):
pass
FontCharacteristics = namedtuple('FontCharacteristics',
'weight, is_italic, is_bold, is_regular, fs_type, panose, width, is_oblique, is_wws, os2_version')
FontNames = namedtuple('FontNames',
@ -70,7 +72,7 @@ class FontMetadata(object):
sz = calcsize(table_record)
self.tables = {}
block = f.read(sz * num_tables)
for i in xrange(num_tables):
for i in range(num_tables):
table_tag, table_checksum, table_offset, table_length = \
unpack_from(table_record, block, i*sz)
self.tables[table_tag.lower()] = (table_offset, table_length,
@ -112,6 +114,7 @@ class FontMetadata(object):
ans[f] = getattr(self.characteristics, f)
return ans
if __name__ == '__main__':
import sys
with open(sys.argv[-1], 'rb') as f:

View File

@ -11,7 +11,7 @@ import struct
from io import BytesIO
from collections import defaultdict
from polyglot.builtins import unicode_type
from polyglot.builtins import unicode_type, range
class UnsupportedFont(ValueError):
@ -32,7 +32,7 @@ def is_truetype_font(raw):
def get_tables(raw):
num_tables = struct.unpack_from(b'>H', raw, 4)[0]
offset = 4*3 # start of the table record entries
for i in xrange(num_tables):
for i in range(num_tables):
table_tag, table_checksum, table_offset, table_length = struct.unpack_from(
b'>4s3L', raw, offset)
yield (table_tag, raw[table_offset:table_offset+table_length], offset,
@ -183,7 +183,7 @@ def _get_font_names(raw, raw_is_table=False):
records = defaultdict(list)
for i in xrange(count):
for i in range(count):
try:
platform_id, encoding_id, language_id, name_id, length, offset = \
struct.unpack_from(b'>6H', table, 6+i*12)
@ -408,7 +408,7 @@ def get_glyph_ids(raw, text, raw_is_table=False):
raise UnsupportedFont('Not a supported font, has no cmap table')
version, num_tables = struct.unpack_from(b'>HH', table)
bmp_table = None
for i in xrange(num_tables):
for i in range(num_tables):
platform_id, encoding_id, offset = struct.unpack_from(b'>HHL', table,
4 + (i*8))
if platform_id == 3 and encoding_id == 1: