Get rid of more xrange

This commit is contained in:
Kovid Goyal 2019-03-13 15:51:21 +05:30
parent 6b5c3bd7c9
commit ea33a5d6ad
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
11 changed files with 43 additions and 41 deletions

View File

@ -9,6 +9,7 @@ __license__ = 'GPL v3'
__copyright__ = '2008, Marshall T. Vandegrift <llasram@gmail.com>' __copyright__ = '2008, Marshall T. Vandegrift <llasram@gmail.com>'
import struct, copy import struct, copy
from polyglot.builtins import range
# ====================================================================== # ======================================================================
# Bit-Manipulation helpers # Bit-Manipulation helpers
@ -170,7 +171,7 @@ class mssha1(object):
D = self.H3 D = self.H3
E = self.H4 E = self.H4
for t in xrange(0, 80): for t in range(0, 80):
TEMP = _rotateLeft(A, 5) + f[t](B, C, D) + E + W[t] + K[t/20] TEMP = _rotateLeft(A, 5) + f[t](B, C, D) + E + W[t] + K[t/20]
E = D E = D
D = C D = C
@ -341,7 +342,7 @@ if __name__ == '__main__':
data = file.read(16384) data = file.read(16384)
file.close() file.close()
digest = context.hexdigest().upper() digest = context.hexdigest().upper()
for i in xrange(0, 40, 8): for i in range(0, 40, 8):
print(digest[i:i+8], end=' ') print(digest[i:i+8], end=' ')
print() print()
main() main()

View File

@ -31,7 +31,7 @@ import calibre
from calibre import plugins from calibre import plugins
msdes, msdeserror = plugins['msdes'] msdes, msdeserror = plugins['msdes']
import calibre.ebooks.lit.mssha1 as mssha1 import calibre.ebooks.lit.mssha1 as mssha1
from polyglot.builtins import codepoint_to_chr, unicode_type, string_or_bytes from polyglot.builtins import codepoint_to_chr, unicode_type, string_or_bytes, range
__all__ = ['LitWriter'] __all__ = ['LitWriter']
@ -49,7 +49,7 @@ ALL_MS_COVER_TYPES = [
def invert_tag_map(tag_map): def invert_tag_map(tag_map):
tags, dattrs, tattrs = tag_map tags, dattrs, tattrs = tag_map
tags = dict((tags[i], i) for i in xrange(len(tags))) tags = dict((tags[i], i) for i in range(len(tags)))
dattrs = dict((v, k) for k, v in dattrs.items()) dattrs = dict((v, k) for k, v in dattrs.items())
tattrs = [dict((v, k) for k, v in (map or {}).items()) for map in tattrs] tattrs = [dict((v, k) for k, v in (map or {}).items()) for map in tattrs]
for map in tattrs: for map in tattrs:
@ -135,7 +135,7 @@ def decint(value):
def randbytes(n): def randbytes(n):
return ''.join(chr(random.randint(0, 255)) for x in xrange(n)) return ''.join(chr(random.randint(0, 255)) for x in range(n))
def warn(x): def warn(x):
@ -332,7 +332,7 @@ class LitWriter(object):
self._oeb = oeb self._oeb = oeb
self._logger = oeb.logger self._logger = oeb.logger
self._stream = stream self._stream = stream
self._sections = [StringIO() for i in xrange(4)] self._sections = [StringIO() for i in range(4)]
self._directory = [] self._directory = []
self._meta = None self._meta = None
self._litize_oeb() self._litize_oeb()
@ -363,7 +363,7 @@ class LitWriter(object):
1, PRIMARY_SIZE, 5, SECONDARY_SIZE)) 1, PRIMARY_SIZE, 5, SECONDARY_SIZE))
self._write(packguid(LITFILE_GUID)) self._write(packguid(LITFILE_GUID))
offset = self._tell() offset = self._tell()
pieces = list(xrange(offset, offset + (PIECE_SIZE * 5), PIECE_SIZE)) pieces = list(range(offset, offset + (PIECE_SIZE * 5), PIECE_SIZE))
self._write((5 * PIECE_SIZE) * '\0') self._write((5 * PIECE_SIZE) * '\0')
aoli1 = len(dchunks) if ichunk else ULL_NEG1 aoli1 = len(dchunks) if ichunk else ULL_NEG1
last = len(dchunks) - 1 last = len(dchunks) - 1
@ -662,7 +662,7 @@ class LitWriter(object):
hash.update(data) hash.update(data)
digest = hash.digest() digest = hash.digest()
key = [0] * 8 key = [0] * 8
for i in xrange(0, len(digest)): for i in range(0, len(digest)):
key[i % 8] ^= ord(digest[i]) key[i % 8] ^= ord(digest[i])
return ''.join(chr(x) for x in key) return ''.join(chr(x) for x in key)

View File

@ -17,6 +17,7 @@ from calibre.ebooks.metadata import MetaInformation
from calibre.ebooks.pdb.header import PdbHeaderReader from calibre.ebooks.pdb.header import PdbHeaderReader
from calibre.ebooks.pdb.plucker.reader import SectionHeader, DATATYPE_METADATA, \ from calibre.ebooks.pdb.plucker.reader import SectionHeader, DATATYPE_METADATA, \
MIBNUM_TO_NAME MIBNUM_TO_NAME
from polyglot.builtins import range
def get_metadata(stream, extract_cover=True): def get_metadata(stream, extract_cover=True):
@ -44,7 +45,7 @@ def get_metadata(stream, extract_cover=True):
title = None title = None
author = None author = None
pubdate = 0 pubdate = 0
for i in xrange(record_count): for i in range(record_count):
try: try:
type, length = struct.unpack_from('>HH', section_data, 2 + adv) type, length = struct.unpack_from('>HH', section_data, 2 + adv)
except struct.error: except struct.error:

View File

@ -14,7 +14,7 @@ from io import BytesIO
from calibre.utils.img import save_cover_data_to, scale_image, image_to_data, image_from_data, resize_image from calibre.utils.img import save_cover_data_to, scale_image, image_to_data, image_from_data, resize_image
from calibre.utils.imghdr import what from calibre.utils.imghdr import what
from calibre.ebooks import normalize from calibre.ebooks import normalize
from polyglot.builtins import unicode_type from polyglot.builtins import unicode_type, range
from tinycss.color3 import parse_color_string from tinycss.color3 import parse_color_string
IMAGE_MAX_SIZE = 10 * 1024 * 1024 IMAGE_MAX_SIZE = 10 * 1024 * 1024
@ -242,7 +242,7 @@ def encode_fvwi(val, flags, flag_size=4):
bytestring. bytestring.
''' '''
ans = val << flag_size ans = val << flag_size
for i in xrange(flag_size): for i in range(flag_size):
ans |= (flags & (1 << i)) ans |= (flags & (1 << i))
return encint(ans) return encint(ans)
@ -254,7 +254,7 @@ def decode_fvwi(byts, flag_size=4):
arg, consumed = decint(bytes(byts)) arg, consumed = decint(bytes(byts))
val = arg >> flag_size val = arg >> flag_size
flags = 0 flags = 0
for i in xrange(flag_size): for i in range(flag_size):
flags |= (arg & (1 << i)) flags |= (arg & (1 << i))
return val, flags, consumed return val, flags, consumed
@ -462,7 +462,7 @@ def read_font_record(data, extent=1040):
extent = len(font_data) if extent is None else extent extent = len(font_data) if extent is None else extent
extent = min(extent, len(font_data)) extent = min(extent, len(font_data))
for n in xrange(extent): for n in range(extent):
buf[n] ^= key[n%xor_len] # XOR of buf and key buf[n] ^= key[n%xor_len] # XOR of buf and key
font_data = bytes(buf) font_data = bytes(buf)
@ -506,7 +506,7 @@ def write_font_record(data, obfuscate=True, compress=True):
xor_key = os.urandom(key_len) xor_key = os.urandom(key_len)
key = bytearray(xor_key) key = bytearray(xor_key)
data = bytearray(data) data = bytearray(data)
for i in xrange(1040): for i in range(1040):
data[i] ^= key[i%key_len] data[i] ^= key[i%key_len]
data = bytes(data) data = bytes(data)

View File

@ -22,7 +22,7 @@ from calibre.ebooks.oeb.parse_utils import (barename, XHTML_NS, RECOVER_PARSER,
namespace, XHTML, parse_html, NotHTML) namespace, XHTML, parse_html, NotHTML)
from calibre.utils.cleantext import clean_xml_chars from calibre.utils.cleantext import clean_xml_chars
from calibre.utils.short_uuid import uuid4 from calibre.utils.short_uuid import uuid4
from polyglot.builtins import unicode_type, string_or_bytes from polyglot.builtins import unicode_type, string_or_bytes, range
XML_NS = 'http://www.w3.org/XML/1998/namespace' XML_NS = 'http://www.w3.org/XML/1998/namespace'
OEB_DOC_NS = 'http://openebook.org/namespaces/oeb-document/1.0/' OEB_DOC_NS = 'http://openebook.org/namespaces/oeb-document/1.0/'
@ -431,8 +431,8 @@ def serialize(data, media_type, pretty_print=False):
return bytes(data) return bytes(data)
ASCII_CHARS = set(chr(x) for x in xrange(128)) ASCII_CHARS = set(chr(x) for x in range(128))
UNIBYTE_CHARS = set(chr(x) for x in xrange(256)) UNIBYTE_CHARS = set(chr(x) for x in range(256))
URL_SAFE = set('ABCDEFGHIJKLMNOPQRSTUVWXYZ' URL_SAFE = set('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
'abcdefghijklmnopqrstuvwxyz' 'abcdefghijklmnopqrstuvwxyz'
'0123456789' '_.-/~') '0123456789' '_.-/~')
@ -1338,7 +1338,7 @@ class Spine(object):
item.linear = self._linear(linear) item.linear = self._linear(linear)
item.spine_position = index item.spine_position = index
self.items.insert(index, item) self.items.insert(index, item)
for i in xrange(index, len(self.items)): for i in range(index, len(self.items)):
self.items[i].spine_position = i self.items[i].spine_position = i
return item return item
@ -1346,7 +1346,7 @@ class Spine(object):
"""Remove :param:`item` from the `Spine`.""" """Remove :param:`item` from the `Spine`."""
index = item.spine_position index = item.spine_position
self.items.pop(index) self.items.pop(index)
for i in xrange(index, len(self.items)): for i in range(index, len(self.items)):
self.items[i].spine_position = i self.items[i].spine_position = i
item.spine_position = None item.spine_position = None
@ -2044,7 +2044,7 @@ def rel_href(base_href, href):
target, frag = urldefrag(href) target, frag = urldefrag(href)
target = target.split('/') target = target.split('/')
index = 0 index = 0
for index in xrange(min(len(base), len(target))): for index in range(min(len(base), len(target))):
if base[index] != target[index]: if base[index] != target[index]:
break break
else: else:

View File

@ -9,7 +9,7 @@ __docformat__ = 'restructuredtext en'
from calibre.gui2 import gprefs from calibre.gui2 import gprefs
from calibre.gui2.catalog.catalog_bibtex_ui import Ui_Form from calibre.gui2.catalog.catalog_bibtex_ui import Ui_Form
from polyglot.builtins import unicode_type from polyglot.builtins import unicode_type, range
from PyQt5.Qt import QWidget, QListWidgetItem from PyQt5.Qt import QWidget, QListWidgetItem
@ -48,7 +48,7 @@ class PluginWidget(QWidget, Ui_Form):
self.name = name self.name = name
fields = gprefs.get(name+'_db_fields', self.all_fields) fields = gprefs.get(name+'_db_fields', self.all_fields)
# Restore the activated db_fields from last use # Restore the activated db_fields from last use
for x in xrange(self.db_fields.count()): for x in range(self.db_fields.count()):
item = self.db_fields.item(x) item = self.db_fields.item(x)
item.setSelected(unicode_type(item.text()) in fields) item.setSelected(unicode_type(item.text()) in fields)
self.bibfile_enc.clear() self.bibfile_enc.clear()
@ -72,7 +72,7 @@ class PluginWidget(QWidget, Ui_Form):
# Save the currently activated fields # Save the currently activated fields
fields = [] fields = []
for x in xrange(self.db_fields.count()): for x in range(self.db_fields.count()):
item = self.db_fields.item(x) item = self.db_fields.item(x)
if item.isSelected(): if item.isSelected():
fields.append(unicode_type(item.text())) fields.append(unicode_type(item.text()))

View File

@ -8,7 +8,7 @@ __docformat__ = 'restructuredtext en'
from calibre.gui2 import gprefs from calibre.gui2 import gprefs
from calibre.gui2.ui import get_gui from calibre.gui2.ui import get_gui
from polyglot.builtins import unicode_type from polyglot.builtins import unicode_type, range
from PyQt5.Qt import QWidget, QListWidgetItem, Qt, QVBoxLayout, QLabel, QListWidget from PyQt5.Qt import QWidget, QListWidgetItem, Qt, QVBoxLayout, QLabel, QListWidget
@ -90,7 +90,7 @@ class PluginWidget(QWidget):
def options(self): def options(self):
# Save the currently activated fields # Save the currently activated fields
fields, all_fields = [], [] fields, all_fields = [], []
for x in xrange(self.db_fields.count()): for x in range(self.db_fields.count()):
item = self.db_fields.item(x) item = self.db_fields.item(x)
all_fields.append(unicode_type(item.data(Qt.UserRole))) all_fields.append(unicode_type(item.data(Qt.UserRole)))
if item.checkState() == Qt.Checked: if item.checkState() == Qt.Checked:

View File

@ -19,7 +19,7 @@ from calibre.utils.icu import sort_key
from calibre.utils.config import tweaks from calibre.utils.config import tweaks
from calibre.utils.date import now from calibre.utils.date import now
from calibre.utils.localization import localize_user_manual_link from calibre.utils.localization import localize_user_manual_link
from polyglot.builtins import unicode_type from polyglot.builtins import unicode_type, range
box_values = {} box_values = {}
last_matchkind = CONTAINS_MATCH last_matchkind = CONTAINS_MATCH
@ -191,7 +191,7 @@ def create_date_tab(self, db):
dy.setRange(102, 10000) dy.setRange(102, 10000)
dy.setValue(now().year) dy.setValue(now().year)
self.date_month = dm = add(_('mo&nth'), QComboBox(w)) self.date_month = dm = add(_('mo&nth'), QComboBox(w))
for val, text in [(0, '')] + [(i, strftime('%B', date(2010, i, 1).timetuple())) for i in xrange(1, 13)]: for val, text in [(0, '')] + [(i, strftime('%B', date(2010, i, 1).timetuple())) for i in range(1, 13)]:
dm.addItem(text, val) dm.addItem(text, val)
self.date_day = dd = add(_('&day'), QSpinBox(w)) self.date_day = dd = add(_('&day'), QSpinBox(w))
dd.setRange(0, 31) dd.setRange(0, 31)

View File

@ -19,7 +19,7 @@ from PyQt5.QtWebKit import QWebElement
from calibre.ebooks.oeb.display.webview import load_html from calibre.ebooks.oeb.display.webview import load_html
from calibre.gui2 import error_dialog, question_dialog, gprefs, secure_web_page from calibre.gui2 import error_dialog, question_dialog, gprefs, secure_web_page
from calibre.utils.logging import default_log from calibre.utils.logging import default_log
from polyglot.builtins import unicode_type from polyglot.builtins import unicode_type, range
class Page(QWebPage): # {{{ class Page(QWebPage): # {{{
@ -259,7 +259,7 @@ class ItemEdit(QWidget):
self.name.setCursorPosition(0) self.name.setCursorPosition(0)
toc = item.data(0, Qt.UserRole) toc = item.data(0, Qt.UserRole)
if toc.dest: if toc.dest:
for i in xrange(self.dest_list.count()): for i in range(self.dest_list.count()):
litem = self.dest_list.item(i) litem = self.dest_list.item(i)
if unicode_type(litem.data(Qt.DisplayRole) or '') == toc.dest: if unicode_type(litem.data(Qt.DisplayRole) or '') == toc.dest:
dest_index = i dest_index = i

View File

@ -10,7 +10,7 @@ __docformat__ = 'restructuredtext en'
import sys, os, textwrap import sys, os, textwrap
from threading import Thread from threading import Thread
from functools import partial from functools import partial
from polyglot.builtins import map, unicode_type from polyglot.builtins import map, unicode_type, range
from PyQt5.Qt import (QPushButton, QFrame, QMenu, QInputDialog, QCheckBox, from PyQt5.Qt import (QPushButton, QFrame, QMenu, QInputDialog, QCheckBox,
QDialog, QVBoxLayout, QDialogButtonBox, QSize, QStackedWidget, QWidget, QDialog, QVBoxLayout, QDialogButtonBox, QSize, QStackedWidget, QWidget,
@ -44,7 +44,7 @@ class XPathDialog(QDialog): # {{{
la.setWordWrap(True) la.setWordWrap(True)
l.addWidget(la) l.addWidget(la)
self.widgets = [] self.widgets = []
for i in xrange(5): for i in range(5):
la = _('Level %s ToC:')%('&%d'%(i+1)) la = _('Level %s ToC:')%('&%d'%(i+1))
xp = XPathEdit(self) xp = XPathEdit(self)
xp.set_msg(la) xp.set_msg(la)
@ -307,10 +307,10 @@ class ItemView(QFrame): # {{{
l.addWidget(la, l.rowCount(), 0, 1, 2) l.addWidget(la, l.rowCount(), 0, 1, 2)
def create_from_major_headings(self): def create_from_major_headings(self):
self.create_from_xpath.emit(['//h:h%d'%i for i in xrange(1, 4)], True) self.create_from_xpath.emit(['//h:h%d'%i for i in range(1, 4)], True)
def create_from_all_headings(self): def create_from_all_headings(self):
self.create_from_xpath.emit(['//h:h%d'%i for i in xrange(1, 7)], True) self.create_from_xpath.emit(['//h:h%d'%i for i in range(1, 7)], True)
def create_from_user_xpath(self): def create_from_user_xpath(self):
d = XPathDialog(self, self.prefs) d = XPathDialog(self, self.prefs)
@ -404,7 +404,7 @@ class TreeWidget(QTreeWidget): # {{{
def iteritems(self, parent=None): def iteritems(self, parent=None):
if parent is None: if parent is None:
parent = self.invisibleRootItem() parent = self.invisibleRootItem()
for i in xrange(parent.childCount()): for i in range(parent.childCount()):
child = parent.child(i) child = parent.child(i)
yield child yield child
for gc in self.iteritems(parent=child): for gc in self.iteritems(parent=child):
@ -496,7 +496,7 @@ class TreeWidget(QTreeWidget): # {{{
is_expanded = item.isExpanded() or item.childCount() == 0 is_expanded = item.isExpanded() or item.childCount() == 0
gp = parent.parent() or self.invisibleRootItem() gp = parent.parent() or self.invisibleRootItem()
idx = gp.indexOfChild(parent) idx = gp.indexOfChild(parent)
for gc in [parent.child(i) for i in xrange(parent.indexOfChild(item)+1, parent.childCount())]: for gc in [parent.child(i) for i in range(parent.indexOfChild(item)+1, parent.childCount())]:
parent.removeChild(gc) parent.removeChild(gc)
item.addChild(gc) item.addChild(gc)
parent.removeChild(item) parent.removeChild(item)
@ -798,7 +798,7 @@ class TOCView(QWidget): # {{{
if item is not None: if item is not None:
p = item.parent() or self.root p = item.parent() or self.root
idx = p.indexOfChild(item) idx = p.indexOfChild(item)
children = [item.child(i) for i in xrange(item.childCount())] children = [item.child(i) for i in range(item.childCount())]
for child in reversed(children): for child in reversed(children):
item.removeChild(child) item.removeChild(child)
p.insertChild(idx+1, child) p.insertChild(idx+1, child)
@ -816,7 +816,7 @@ class TOCView(QWidget): # {{{
self.tocw.move_down() self.tocw.move_down()
def data_changed(self, top_left, bottom_right): def data_changed(self, top_left, bottom_right):
for r in xrange(top_left.row(), bottom_right.row()+1): for r in range(top_left.row(), bottom_right.row()+1):
idx = self.tocw.model().index(r, 0, top_left.parent()) idx = self.tocw.model().index(r, 0, top_left.parent())
new_title = unicode_type(idx.data(Qt.DisplayRole) or '').strip() new_title = unicode_type(idx.data(Qt.DisplayRole) or '').strip()
toc = idx.data(Qt.UserRole) toc = idx.data(Qt.UserRole)
@ -908,7 +908,7 @@ class TOCView(QWidget): # {{{
root = TOC() root = TOC()
def process_node(parent, toc_parent): def process_node(parent, toc_parent):
for i in xrange(parent.childCount()): for i in range(parent.childCount()):
item = parent.child(i) item = parent.child(i)
title = unicode_type(item.data(0, Qt.DisplayRole) or '').strip() title = unicode_type(item.data(0, Qt.DisplayRole) or '').strip()
toc = item.data(0, Qt.UserRole) toc = item.data(0, Qt.UserRole)

View File

@ -12,7 +12,7 @@ from calibre.constants import plugins, preferred_encoding
from calibre.ebooks.metadata import authors_to_string from calibre.ebooks.metadata import authors_to_string
from calibre.ptempfile import TemporaryDirectory from calibre.ptempfile import TemporaryDirectory
from calibre.utils.ipc.simple_worker import fork_job, WorkerError from calibre.utils.ipc.simple_worker import fork_job, WorkerError
from polyglot.builtins import unicode_type from polyglot.builtins import unicode_type, range
def get_podofo(): def get_podofo():
@ -110,7 +110,7 @@ def delete_all_but(path, pages):
p.load(raw) p.load(raw)
total = p.page_count() total = p.page_count()
pages = {total + x if x < 0 else x for x in pages} pages = {total + x if x < 0 else x for x in pages}
for page in xrange(total-1, -1, -1): for page in range(total-1, -1, -1):
if page not in pages: if page not in pages:
p.delete_page(page) p.delete_page(page)
@ -144,7 +144,7 @@ def test_outline(src):
p.load(raw) p.load(raw)
total = p.page_count() total = p.page_count()
root = p.create_outline(u'Table of Contents') root = p.create_outline(u'Table of Contents')
for i in xrange(0, total): for i in range(0, total):
root.create(u'Page %d'%i, i, True) root.create(u'Page %d'%i, i, True)
raw = p.write() raw = p.write()
out = '/tmp/outlined.pdf' out = '/tmp/outlined.pdf'