Replace == with and != with not is in all RS code

This commit is contained in:
Kovid Goyal 2016-03-13 22:13:07 +05:30
parent 2ce04ae5de
commit f27e2bb85e
14 changed files with 110 additions and 110 deletions

View File

@ -39,9 +39,9 @@ def ajax(path, on_complete, on_progress=None, bypass_cache=True, method='GET', q
xhr.error_html = '' xhr.error_html = ''
def set_error(event): def set_error(event):
if event == 'timeout': if event is 'timeout':
xhr.error_html = str.format(_('Failed to communicate with "{}", timed out after: {} seconds'), xhr.request_path, timeout/1000) xhr.error_html = str.format(_('Failed to communicate with "{}", timed out after: {} seconds'), xhr.request_path, timeout/1000)
elif event == 'abort': elif event is 'abort':
xhr.error_html = str.format(_('Failed to communicate with "{}", aborted'), xhr.request_path) xhr.error_html = str.format(_('Failed to communicate with "{}", aborted'), xhr.request_path)
else: else:
rtext = xhr.responseText or '' rtext = xhr.responseText or ''
@ -60,9 +60,9 @@ def ajax(path, on_complete, on_progress=None, bypass_cache=True, method='GET', q
on_progress(ev.loaded, ul, xhr) on_progress(ev.loaded, ul, xhr)
def complete_callback(end_type, ev): def complete_callback(end_type, ev):
if xhr.status != ok_code and end_type == 'load': if xhr.status is not ok_code and end_type is 'load':
end_type = 'error' end_type = 'error'
if end_type != 'load': if end_type is not 'load':
set_error(end_type) set_error(end_type)
on_complete(end_type, xhr, ev) on_complete(end_type, xhr, ev)

View File

@ -28,8 +28,8 @@ def sort_formats_key(fmt):
def get_preferred_format(metadata, output_format, input_formats): def get_preferred_format(metadata, output_format, input_formats):
formats = (metadata and metadata.formats) or v'[]' formats = (metadata and metadata.formats) or v'[]'
formats = [f.toUpperCase() for f in formats] formats = [f.toUpperCase() for f in formats]
fmt = 'EPUB' if output_format == 'PDF' else output_format fmt = 'EPUB' if output_format is 'PDF' else output_format
if formats.length and formats.indexOf(fmt) == -1: if formats.length and formats.indexOf(fmt) is -1:
for q in sorted(formats, key=sort_formats_key): for q in sorted(formats, key=sort_formats_key):
if input_formats[q]: if input_formats[q]:
fmt = q fmt = q
@ -64,7 +64,7 @@ def render_metadata(mi, interface_data, table, field_list=None):
def allowed_fields(field): def allowed_fields(field):
if str.endswith(field, '_index'): if str.endswith(field, '_index'):
fm = interface_data.field_metadata[field[:-len('_index')]] fm = interface_data.field_metadata[field[:-len('_index')]]
if fm and fm.datatype == 'series': if fm and fm.datatype is 'series':
return False return False
if str.startswith(field, '#'): if str.startswith(field, '#'):
return True return True
@ -155,7 +155,7 @@ def render_metadata(mi, interface_data, table, field_list=None):
for k in keys: for k in keys:
idval = val[k] idval = val[k]
x = url_map[k] x = url_map[k]
if isinstance(x, list) and x.length == 2: if isinstance(x, list) and x.length is 2:
td.appendChild(E.a(title=str.format('{}:{}', k, idval), target='_new', href=x[1], x[0])) td.appendChild(E.a(title=str.format('{}:{}', k, idval), target='_new', href=x[1], x[0]))
else: else:
td.appendChild(E.span(k, ':', idval)) td.appendChild(E.span(k, ':', idval))
@ -197,37 +197,37 @@ def render_metadata(mi, interface_data, table, field_list=None):
name = fm.name or field name = fm.name or field
datatype = fm.datatype datatype = fm.datatype
val = mi[field] val = mi[field]
if field == 'comments' or datatype == 'comments': if field is 'comments' or datatype is 'comments':
comments[field] = val comments[field] = val
return return
func = None func = None
if datatype == 'composite': if datatype is 'composite':
func = process_composite func = process_composite
elif field == 'formats': elif field is 'formats':
func = process_formats func = process_formats
elif datatype == 'rating': elif datatype is 'rating':
func = process_rating func = process_rating
elif field == 'identifiers': elif field is 'identifiers':
func = process_identifiers func = process_identifiers
elif field == 'authors': elif field is 'authors':
func = process_authors func = process_authors
elif field == 'publisher': elif field is 'publisher':
func = process_publisher func = process_publisher
elif field == 'languages': elif field is 'languages':
func = process_languages func = process_languages
elif datatype == 'datetime': elif datatype is 'datetime':
func = process_datetime func = process_datetime
elif datatype == 'series': elif datatype is 'series':
func = process_series func = process_series
if func: if func:
func(field, fm, name, val) func(field, fm, name, val)
else: else:
if datatype == 'text' or datatype == 'enumeration': if datatype is 'text' or datatype is 'enumeration':
join = fm.is_multiple.list_to_ui if fm.is_multiple else None join = fm.is_multiple.list_to_ui if fm.is_multiple else None
add_row(name, val, join=join, is_searchable=field) add_row(name, val, join=join, is_searchable=field)
elif datatype == 'bool': elif datatype is 'bool':
add_row(name, _('Yes') if val else _('No')) add_row(name, _('Yes') if val else _('No'))
elif datatype == 'int' or datatype == 'float': elif datatype is 'int' or datatype is 'float':
fmt = (fm.display or {}).number_format fmt = (fm.display or {}).number_format
if fmt: if fmt:
val = str.format(fmt, val) val = str.format(fmt, val)
@ -251,7 +251,7 @@ def render_metadata(mi, interface_data, table, field_list=None):
div = E.div() div = E.div()
div.innerHTML = comment div.innerHTML = comment
table.parentNode.appendChild(div) table.parentNode.appendChild(div)
if i == 0: if i is 0:
div.style.marginTop = '2ex' div.style.marginTop = '2ex'
@ -280,7 +280,7 @@ class BookDetailsPanel:
@property @property
def is_visible(self): def is_visible(self):
self.container.parentNode.style.display == 'block' self.container.parentNode.style.display is 'block'
@is_visible.setter @is_visible.setter
def is_visible(self, val): def is_visible(self, val):
@ -297,7 +297,7 @@ class BookDetailsPanel:
self.render_book(book_id) self.render_book(book_id)
else: else:
self.fetch_metadata(book_id) self.fetch_metadata(book_id)
get_boss().ui.set_button_visibility('random', not book_id or book_id == '0') get_boss().ui.set_button_visibility('random', not book_id or book_id is '0')
def show_random(self): def show_random(self):
self.fetch_metadata('0') self.fetch_metadata('0')
@ -324,7 +324,7 @@ class BookDetailsPanel:
return # Fetching was aborted return # Fetching was aborted
self.is_fetching = None self.is_fetching = None
c = self.container c = self.container
if end_type == 'load': if end_type is 'load':
try: try:
data = JSON.parse(xhr.responseText) data = JSON.parse(xhr.responseText)
except Exception as err: except Exception as err:
@ -334,7 +334,7 @@ class BookDetailsPanel:
book_id = data['id'] book_id = data['id']
self.interface_data.metadata[book_id] = data self.interface_data.metadata[book_id] = data
self.render_book(book_id) self.render_book(book_id)
elif end_type != 'abort': elif end_type is not 'abort':
clear(c) clear(c)
c.appendChild(E.div( c.appendChild(E.div(
style='margin: 1ex 1em', style='margin: 1ex 1em',

View File

@ -33,8 +33,8 @@ class Boss:
data = parse_url_params() data = parse_url_params()
set_current_query(data) set_current_query(data)
self.ui.apply_state() # Render the book list self.ui.apply_state() # Render the book list
if not data.mode or data.mode == 'book_list': if not data.mode or data.mode is 'book_list':
if data.panel != self.ui.current_panel: if data.panel is not self.ui.current_panel:
self.ui.show_panel(data.panel, push_state=False) self.ui.show_panel(data.panel, push_state=False)
setTimeout(def(): setTimeout(def():
window.onpopstate = self.onpopstate.bind(self) window.onpopstate = self.onpopstate.bind(self)
@ -64,11 +64,11 @@ class Boss:
set_current_query(data) set_current_query(data)
mode = data.mode or 'book_list' mode = data.mode or 'book_list'
self.history_count -= 1 self.history_count -= 1
if mode == 'book_list': if mode is 'book_list':
search = data.search or '' search = data.search or ''
if data.panel != self.ui.current_panel: if data.panel is not self.ui.current_panel:
self.ui.show_panel(data.panel, push_state=False) self.ui.show_panel(data.panel, push_state=False)
if search != self.ui.books_view.interface_data.search_result.query: if search is not self.ui.books_view.interface_data.search_result.query:
self.ui.books_view.change_search(search, push_state=False, panel_to_show=data.panel) self.ui.books_view.change_search(search, push_state=False, panel_to_show=data.panel)
def change_books(self, data): def change_books(self, data):
@ -87,13 +87,13 @@ class Boss:
if extra_query_data: if extra_query_data:
for k in extra_query_data: for k in extra_query_data:
query[k] = extra_query_data[k] query[k] = extra_query_data[k]
if self.current_mode == 'book_list': if self.current_mode is 'book_list':
if self.ui.current_panel != self.ui.ROOT_PANEL: if self.ui.current_panel is not self.ui.ROOT_PANEL:
query.panel = self.ui.current_panel query.panel = self.ui.current_panel
else: else:
query.current_mode = self.current_mode query.current_mode = self.current_mode
idata = self.interface_data idata = self.interface_data
if idata.library_id != idata.default_library: if idata.library_id is not idata.default_library:
query.library_id = idata.library_id query.library_id = idata.library_id
sq = idata.search_result.query sq = idata.search_result.query
if sq: if sq:

View File

@ -34,7 +34,7 @@ class ItemsView:
@property @property
def is_visible(self): def is_visible(self):
self.container.style.display == 'block' self.container.style.display is 'block'
@is_visible.setter @is_visible.setter
def is_visible(self, val): def is_visible(self, val):

View File

@ -188,7 +188,7 @@ class PrefsPanel:
@property @property
def is_visible(self): def is_visible(self):
self.container.style.display == 'block' self.container.style.display is 'block'
@is_visible.setter @is_visible.setter
def is_visible(self, val): def is_visible(self, val):
@ -224,7 +224,7 @@ class PrefsPanel:
cls = Choices cls = Choices
elif val is True or val is False: elif val is True or val is False:
cls = CheckBox cls = CheckBox
elif type(val) == 'number': elif type(val) is 'number':
cls = SpinBox cls = SpinBox
else: else:
cls = LineEdit cls = LineEdit

View File

@ -56,7 +56,7 @@ class SearchPanel:
search_button search_button
)) ))
search_container.firstChild.firstChild.addEventListener('keypress', def(event): search_container.firstChild.firstChild.addEventListener('keypress', def(event):
if event.keyCode == 13: # Enter if event.keyCode is 13: # Enter
search_button.focus() search_button.focus()
self.execute_search() self.execute_search()
event.preventDefault(), event.stopPropagation() event.preventDefault(), event.stopPropagation()
@ -104,11 +104,11 @@ class SearchPanel:
def on_data_fetched(self, end_type, xhr, ev): def on_data_fetched(self, end_type, xhr, ev):
self.currently_loading = None self.currently_loading = None
if end_type == 'abort': if end_type is 'abort':
return return
parent = self.container.lastChild parent = self.container.lastChild
if parent.lastChild.style.display == 'none': if parent.lastChild.style.display is 'none':
parent.firstChild.style.display = 'none' parent.firstChild.style.display = 'none'
parent.lastChild.style.display = 'block' parent.lastChild.style.display = 'block'
container = self.tb_container container = self.tb_container
@ -126,7 +126,7 @@ class SearchPanel:
child.parent = node child.parent = node
process_node(child) process_node(child)
if end_type == 'load': if end_type is 'load':
try: try:
tag_browser_data = JSON.parse(xhr.responseText) tag_browser_data = JSON.parse(xhr.responseText)
except Exception as err: except Exception as err:
@ -220,7 +220,7 @@ class SearchPanel:
def search_expression_for_item(self, node, state): def search_expression_for_item(self, node, state):
item = node.data item = node.data
if item.is_searchable is False or not state or state == 'clear': if item.is_searchable is False or not state or state is 'clear':
return '' return ''
search_state = {'plus':'true', 'plusplus':'.true', 'minus':'false', 'minusminus':'.false'}[state] search_state = {'plus':'true', 'plusplus':'.true', 'minus':'false', 'minusminus':'.false'}[state]
@ -236,16 +236,16 @@ class SearchPanel:
letters_seen = Object.keys(letters_seen) letters_seen = Object.keys(letters_seen)
if letters_seen.length: if letters_seen.length:
charclass = letters_seen.join('') charclass = letters_seen.join('')
if category == 'authors': if category is 'authors':
expr = str.format(r'author_sort:"~(^[{0}])|(&\s*[{0}])"', charclass) expr = str.format(r'author_sort:"~(^[{0}])|(&\s*[{0}])"', charclass)
elif category == 'series': elif category is 'series':
expr = str.format(r'series_sort:"~^[{0}]"', charclass) expr = str.format(r'series_sort:"~^[{0}]"', charclass)
else: else:
expr = str.format(r'{0}:"~^[{1}]"', category, charclass) expr = str.format(r'{0}:"~^[{1}]"', category, charclass)
else: else:
expr = str.format('{}:false', category) expr = str.format('{}:false', category)
elif category == 'news': elif category is 'news':
expr = str.format('tags:"={}"', item.name) expr = str.format('tags:"={}"', item.name)
else: else:
@ -255,8 +255,8 @@ class SearchPanel:
expr = '(not ' + expr + ')' expr = '(not ' + expr + ')'
return expr return expr
category = 'tags' if item.category == 'news' else item.category category = 'tags' if item.category is 'news' else item.category
if item.name and item.name[0] == '★': if item.name and item.name[0] is '★':
# Assume ratings # Assume ratings
expr = str.format('{}:{}', category, item.name.length) expr = str.format('{}:{}', category, item.name.length)
else: else:
@ -266,9 +266,9 @@ class SearchPanel:
if not name: if not name:
return '' return ''
name = str.replace(name, '"', r'\"') name = str.replace(name, '"', r'\"')
if name[0] == '.': if name[0] is '.':
name = '.' + name name = '.' + name
if search_state == 'plusplus' or search_state == 'minusminus': if search_state is 'plusplus' or search_state is 'minusminus':
name = '.' + name name = '.' + name
expr = str.format('{}:"={}{}"', category, name, suffix) expr = str.format('{}:"={}{}"', category, name, suffix)
@ -324,7 +324,7 @@ class SearchPanel:
(_('Books matching this category'), 'plus'), (_('Books matching this category'), 'plus'),
(_('Books that do not match this category'), 'minus'), (_('Books that do not match this category'), 'minus'),
] ]
if node.data.is_hierarchical == 5: if node.data.is_hierarchical is 5:
items.extend([ items.extend([
(_('Books that match this category and all sub-categories'), 'plusplus'), (_('Books that match this category and all sub-categories'), 'plusplus'),
(_('Books that do not match this category or any of its sub-categories'), 'minusminus'), (_('Books that do not match this category or any of its sub-categories'), 'minusminus'),
@ -428,7 +428,7 @@ class SearchPanel:
{ {
'name': 'hide_empty_categories', 'name': 'hide_empty_categories',
'text': _('Hide empty categories (columns)'), 'text': _('Hide empty categories (columns)'),
'from_storage': def(x): return x.toLowerCase() == 'yes';, 'from_storage': def(x): return x.toLowerCase() is 'yes';,
'to_storage': def(x): return 'yes' if x else 'no';, 'to_storage': def(x): return 'yes' if x else 'no';,
'tooltip':_('When checked, calibre will automatically hide any category' 'tooltip':_('When checked, calibre will automatically hide any category'
' (a column, custom or standard) that has no items to show. For example, some' ' (a column, custom or standard) that has no items to show. For example, some'
@ -469,7 +469,7 @@ class SearchPanel:
@property @property
def is_visible(self): def is_visible(self):
self.container.style.display == 'block' self.container.style.display is 'block'
@is_visible.setter @is_visible.setter
def is_visible(self, val): def is_visible(self, val):

View File

@ -37,7 +37,7 @@ class TopBar:
E.div(style="white-space:nowrap; overflow:hidden; text-overflow: ellipsis; padding-left: 0.5em;"), E.div(style="white-space:nowrap; overflow:hidden; text-overflow: ellipsis; padding-left: 0.5em;"),
E.div(style="white-space:nowrap; text-align:right; padding-right: 0.5em;") E.div(style="white-space:nowrap; text-align:right; padding-right: 0.5em;")
) )
if bid == self.bar_id: if bid is self.bar_id:
set_css(bar, position='fixed', left='0', top='0', z_index='1') set_css(bar, position='fixed', left='0', top='0', z_index='1')
bar.appendChild(E.style(style, type='text/css')) bar.appendChild(E.style(style, type='text/css'))
set_css(bar, set_css(bar,
@ -57,7 +57,7 @@ class TopBar:
def set_left(self, title='calibre', icon_name='heart', action=None, tooltip='', run_animation=False): def set_left(self, title='calibre', icon_name='heart', action=None, tooltip='', run_animation=False):
self.current_left_data = {'title':title, 'icon_name':icon_name, 'action':action, 'tooltip':tooltip} self.current_left_data = {'title':title, 'icon_name':icon_name, 'action':action, 'tooltip':tooltip}
if icon_name == 'heart': if icon_name is 'heart':
if not tooltip: if not tooltip:
tooltip = _('Donate to support calibre development') tooltip = _('Donate to support calibre development')
@ -75,7 +75,7 @@ class TopBar:
'margin-left: {0}; font-weight: bold; padding-top: {1}; padding-bottom: {1}; vertical-align: middle', self.SPACING, self.VSPACING))) 'margin-left: {0}; font-weight: bold; padding-top: {1}; padding-bottom: {1}; vertical-align: middle', self.SPACING, self.VSPACING)))
if bar is self.bar: if bar is self.bar:
a = left.firstChild a = left.firstChild
if icon_name == 'heart': if icon_name is 'heart':
set_css(a, set_css(a,
animation_name=self.throbber_name, animation_duration='1s', animation_timing_function='ease-in-out', animation_name=self.throbber_name, animation_duration='1s', animation_timing_function='ease-in-out',
animation_iteration_count='5', animation_play_state='running' if run_animation else 'paused' animation_iteration_count='5', animation_play_state='running' if run_animation else 'paused'

View File

@ -77,7 +77,7 @@ def change_library_actions():
ans = [] ans = []
ans.subtitle = _('Currently showing the library: ') + interface_data.library_map[interface_data.library_id] ans.subtitle = _('Currently showing the library: ') + interface_data.library_map[interface_data.library_id]
for lid in sorted(interface_data.library_map): for lid in sorted(interface_data.library_map):
if lid != interface_data.library_id: if lid is not interface_data.library_id:
library_name = interface_data.library_map[lid] library_name = interface_data.library_map[lid]
ans.append({'title':library_name, 'action':boss.ui.change_library.bind(boss.ui, lid)}) ans.append({'title':library_name, 'action':boss.ui.change_library.bind(boss.ui, lid)})
return ans return ans
@ -153,7 +153,7 @@ class UI:
if callable(main_panel.init): if callable(main_panel.init):
panel_data = state.panel_data() if callable(state.panel_data) else state.panel_data panel_data = state.panel_data() if callable(state.panel_data) else state.panel_data
main_panel.init(panel_data) main_panel.init(panel_data)
if self.current_panel == self.ROOT_PANEL: if self.current_panel is self.ROOT_PANEL:
# only run the beating heart animation once # only run the beating heart animation once
window.setTimeout(def(): state.top_bar_state.left_state.run_animation = False;, 10) window.setTimeout(def(): state.top_bar_state.left_state.run_animation = False;, 10)
@ -164,7 +164,7 @@ class UI:
self.show_panel(self.ROOT_PANEL) self.show_panel(self.ROOT_PANEL)
def replace_panel(self, panel_name, force=False, extra_query_data=None): def replace_panel(self, panel_name, force=False, extra_query_data=None):
action_needed = force or panel_name != self.current_panel action_needed = force or panel_name is not self.current_panel
if action_needed: if action_needed:
self.current_panel = panel_name or self.ROOT_PANEL self.current_panel = panel_name or self.ROOT_PANEL
get_boss().push_state(replace=True, extra_query_data=extra_query_data) get_boss().push_state(replace=True, extra_query_data=extra_query_data)
@ -172,7 +172,7 @@ class UI:
self.apply_state() self.apply_state()
def show_panel(self, panel_name, push_state=True, force=False, extra_query_data=None): def show_panel(self, panel_name, push_state=True, force=False, extra_query_data=None):
action_needed = force or panel_name != self.current_panel action_needed = force or panel_name is not self.current_panel
if action_needed: if action_needed:
self.current_panel = panel_name or self.ROOT_PANEL self.current_panel = panel_name or self.ROOT_PANEL
if push_state: if push_state:
@ -182,7 +182,7 @@ class UI:
def refresh_books_view(self): def refresh_books_view(self):
self.books_view.refresh() self.books_view.refresh()
if self.current_panel == self.ROOT_PANEL: if self.current_panel is self.ROOT_PANEL:
self.top_bar.refresh_left() self.top_bar.refresh_left()
def change_library(self, library_id): def change_library(self, library_id):
@ -191,7 +191,7 @@ class UI:
'Fetching data from server, please wait') + '…', query=data, extra_data_for_callback={'library_id':library_id}) 'Fetching data from server, please wait') + '…', query=data, extra_data_for_callback={'library_id':library_id})
def library_changed(self, end_type, xhr, ev): def library_changed(self, end_type, xhr, ev):
if end_type == 'load': if end_type is 'load':
boss = get_boss() boss = get_boss()
boss.interface_data.library_id = xhr.extra_data_for_callback.library_id boss.interface_data.library_id = xhr.extra_data_for_callback.library_id
try: try:
@ -201,7 +201,7 @@ class UI:
return error_dialog(_('Could not change library'), err + '', details=err.stack) return error_dialog(_('Could not change library'), err + '', details=err.stack)
self.show_panel(self.ROOT_PANEL) self.show_panel(self.ROOT_PANEL)
window.scrollTo(0, 0) window.scrollTo(0, 0)
elif end_type != 'abort': elif end_type is not 'abort':
msg = xhr.error_html msg = xhr.error_html
error_dialog(_('Could not change library'), msg) error_dialog(_('Could not change library'), msg)

View File

@ -54,12 +54,12 @@ class BooksView:
self.update_fetching_status() self.update_fetching_status()
def set_view_mode(self, mode='cover_grid'): def set_view_mode(self, mode='cover_grid'):
if self.mode == mode: if self.mode is mode:
return return
if mode not in v"['cover_grid']": if mode not in v"['cover_grid']":
mode = 'cover_grid' mode = 'cover_grid'
self.mode = mode self.mode = mode
if mode == 'cover_grid': if mode is 'cover_grid':
self.render_book = self.cover_grid_item.bind(self) self.render_book = self.cover_grid_item.bind(self)
self.init_grid = self.init_cover_grid.bind(self) self.init_grid = self.init_cover_grid.bind(self)
self.clear() self.clear()
@ -75,7 +75,7 @@ class BooksView:
@property @property
def is_visible(self): def is_visible(self):
self.container.style.display == 'block' self.container.style.display is 'block'
@is_visible.setter @is_visible.setter
def is_visible(self, val): def is_visible(self, val):
@ -136,7 +136,7 @@ class BooksView:
return # Fetching was aborted return # Fetching was aborted
self.is_fetching = None self.is_fetching = None
self.update_fetching_status() self.update_fetching_status()
if end_type == 'load': if end_type is 'load':
try: try:
data = JSON.parse(xhr.responseText) data = JSON.parse(xhr.responseText)
for key in data.metadata: for key in data.metadata:
@ -147,7 +147,7 @@ class BooksView:
self.interface_data.search_result = data.search_result self.interface_data.search_result = data.search_result
except Exception as err: except Exception as err:
error_dialog(_('Could not get more books'), _('Server returned an invalid response'), err.stack or err.toString()) error_dialog(_('Could not get more books'), _('Server returned an invalid response'), err.stack or err.toString())
elif end_type != 'abort': elif end_type is not 'abort':
error_dialog(_('Could not get more books'), xhr.error_html) error_dialog(_('Could not get more books'), xhr.error_html)
# Cover grid {{{ # Cover grid {{{
@ -194,16 +194,16 @@ class BooksView:
def sort_panel_data(self, create_item): def sort_panel_data(self, create_item):
current_sorted_field = str.partition(self.interface_data.search_result.sort, ',')[0] current_sorted_field = str.partition(self.interface_data.search_result.sort, ',')[0]
current_sorted_field_order = str.partition(self.interface_data.search_result.sort_order, ',')[0] current_sorted_field_order = str.partition(self.interface_data.search_result.sort_order, ',')[0]
new_sort_order = 'desc' if current_sorted_field_order == 'asc' else 'asc' new_sort_order = 'desc' if current_sorted_field_order is 'asc' else 'asc'
if current_sorted_field == 'date': if current_sorted_field is 'date':
current_sorted_field = 'timestamp' current_sorted_field = 'timestamp'
ans = [] ans = []
ans.subtitle = _('Change how the list of books is sorted') ans.subtitle = _('Change how the list of books is sorted')
for field, name in self.interface_data.sortable_fields: for field, name in self.interface_data.sortable_fields:
subtitle = icon_name = None subtitle = icon_name = None
if field == current_sorted_field: if field is current_sorted_field:
subtitle = _('Reverse current sort order') subtitle = _('Reverse current sort order')
icon_name = 'sort-amount-asc' if current_sorted_field_order == 'asc' else 'sort-amount-desc' icon_name = 'sort-amount-asc' if current_sorted_field_order is 'asc' else 'sort-amount-desc'
action = self.change_sort.bind(self, field, new_sort_order) action = self.change_sort.bind(self, field, new_sort_order)
else: else:
action = self.change_sort.bind(self, field, None) action = self.change_sort.bind(self, field, None)
@ -215,7 +215,7 @@ class BooksView:
key = 'sort-order-for-' + field key = 'sort-order-for-' + field
sd = get_session_data() sd = get_session_data()
order = order or sd.get(key, 'asc') order = order or sd.get(key, 'asc')
order = 'asc' if order == 'asc' else 'desc' order = 'asc' if order is 'asc' else 'desc'
sd.set(key, order) sd.set(key, order)
sr = self.interface_data.search_result sr = self.interface_data.search_result
sort = field + '.' + order + ',' + sr.sort + '.' + sr.order sort = field + '.' + order + ',' + sr.sort + '.' + sr.order
@ -224,7 +224,7 @@ class BooksView:
'Fetching data from server, please wait') + '…', query=data) 'Fetching data from server, please wait') + '…', query=data)
def sort_change_completed(self, end_type, xhr, ev): def sort_change_completed(self, end_type, xhr, ev):
if end_type == 'load': if end_type is 'load':
boss = get_boss() boss = get_boss()
try: try:
data = JSON.parse(xhr.responseText) data = JSON.parse(xhr.responseText)
@ -233,7 +233,7 @@ class BooksView:
return error_dialog(_('Could not change sort order'), err + '', details=err.stack) return error_dialog(_('Could not change sort order'), err + '', details=err.stack)
boss.ui.show_panel(boss.ui.ROOT_PANEL) boss.ui.show_panel(boss.ui.ROOT_PANEL)
window.scrollTo(0, 0) window.scrollTo(0, 0)
elif end_type != 'abort': elif end_type is not 'abort':
error_dialog(_('Could not change sort order'), xhr.error_html) error_dialog(_('Could not change sort order'), xhr.error_html)
def change_search(self, query, push_state=True, panel_to_show=None): def change_search(self, query, push_state=True, panel_to_show=None):
@ -245,7 +245,7 @@ class BooksView:
'Fetching data from server, please wait') + '…', query=data, extra_data_for_callback={'push_state':push_state, 'panel_to_show': panel_to_show}) 'Fetching data from server, please wait') + '…', query=data, extra_data_for_callback={'push_state':push_state, 'panel_to_show': panel_to_show})
def search_change_completed(self, end_type, xhr, ev): def search_change_completed(self, end_type, xhr, ev):
if end_type == 'load': if end_type is 'load':
boss = get_boss() boss = get_boss()
try: try:
data = JSON.parse(xhr.responseText) data = JSON.parse(xhr.responseText)
@ -256,9 +256,9 @@ class BooksView:
ed = xhr.extra_data_for_callback ed = xhr.extra_data_for_callback
boss.ui.show_panel(ed.panel_to_show or boss.ui.ROOT_PANEL, push_state=ed.push_state) boss.ui.show_panel(ed.panel_to_show or boss.ui.ROOT_PANEL, push_state=ed.push_state)
window.scrollTo(0, 0) window.scrollTo(0, 0)
elif end_type != 'abort': elif end_type is not 'abort':
msg = xhr.error_html msg = xhr.error_html
if xhr.status == 400 and str.startswith(xhr.responseText, 'Invalid search expression:'): if xhr.status is 400 and str.startswith(xhr.responseText, 'Invalid search expression:'):
msg = _('The search expression could not be parsed: ') + xhr.responseText msg = _('The search expression could not be parsed: ') + xhr.responseText
error_dialog(_('Could not change search query'), msg) error_dialog(_('Could not change search query'), msg)

View File

@ -6,9 +6,9 @@ UNDEFINED_DATE = Date('0101-01-01T00:00:00+00:00')
def is_date_undefined(date): def is_date_undefined(date):
dy, uy = date.getUTCFullYear(), UNDEFINED_DATE.getUTCFullYear() dy, uy = date.getUTCFullYear(), UNDEFINED_DATE.getUTCFullYear()
return dy < uy or ( return dy < uy or (
dy == uy and dy is uy and
date.getUTCMonth() == UNDEFINED_DATE.getUTCMonth() and date.getUTCMonth() is UNDEFINED_DATE.getUTCMonth() and
date.getUTCDate() == UNDEFINED_DATE.getUTCDate()) date.getUTCDate() is UNDEFINED_DATE.getUTCDate())
# format_date() {{{ # format_date() {{{
@ -38,51 +38,51 @@ def fd_format_hour(dt, ampm, hr, as_utc):
h = dt.getUTCHours() if as_utc else dt.getHours() h = dt.getUTCHours() if as_utc else dt.getHours()
if ampm: if ampm:
h = h % 12 h = h % 12
return h.toString() if hr.length == 1 else str.format('{:02d}', h) return h.toString() if hr.length is 1 else str.format('{:02d}', h)
def fd_format_minute(dt, ampm, min, as_utc): def fd_format_minute(dt, ampm, min, as_utc):
m = dt.getUTCMinutes() if as_utc else dt.getMinutes() m = dt.getUTCMinutes() if as_utc else dt.getMinutes()
return m.toString() if min.length == 1 else str.format('{:02d}', m) return m.toString() if min.length is 1 else str.format('{:02d}', m)
def fd_format_second(dt, ampm, min, as_utc): def fd_format_second(dt, ampm, min, as_utc):
s = dt.getUTCSeconds() if as_utc else dt.getSeconds() s = dt.getUTCSeconds() if as_utc else dt.getSeconds()
return s.toString() if min.length == 1 else str.format('{:02d}', s) return s.toString() if min.length is 1 else str.format('{:02d}', s)
def fd_format_ampm(dt, ampm, ap, as_utc): def fd_format_ampm(dt, ampm, ap, as_utc):
h = dt.getUTCHours() if as_utc else dt.getHours() h = dt.getUTCHours() if as_utc else dt.getHours()
ans = 'am' if h < 12 else 'pm' ans = 'am' if h < 12 else 'pm'
return ans if ap == 'ap' else ans.toUpperCase() return ans if ap is 'ap' else ans.toUpperCase()
def fd_format_day(dt, ampm, dy, as_utc): def fd_format_day(dt, ampm, dy, as_utc):
d = dt.getUTCDate() if as_utc else dt.getDate() d = dt.getUTCDate() if as_utc else dt.getDate()
if dy.length == 1: if dy.length is 1:
return d.toString() return d.toString()
if dy.length == 2: if dy.length is 2:
return str.format('{:02d}', d) return str.format('{:02d}', d)
if supports_locales: if supports_locales:
options = {'weekday': ('short' if dy.length == 3 else 'long')} options = {'weekday': ('short' if dy.length is 3 else 'long')}
if as_utc: if as_utc:
options['timeZone'] = 'UTC' options['timeZone'] = 'UTC'
return dt.toLocaleString(undefined, options) return dt.toLocaleString(undefined, options)
w = dt.getUTCDay() if as_utc else dt.getDay() w = dt.getUTCDay() if as_utc else dt.getDay()
return lcdata['abday' if dy.length == 3 else 'day'][(w + 1) % 7] return lcdata['abday' if dy.length is 3 else 'day'][(w + 1) % 7]
def fd_format_month(dt, ampm, mo, as_utc): def fd_format_month(dt, ampm, mo, as_utc):
m = dt.getUTCMonth() if as_utc else dt.getMonth() m = dt.getUTCMonth() if as_utc else dt.getMonth()
if mo.length == 1: if mo.length is 1:
return (m + 1).toString() return (m + 1).toString()
if mo.length == 2: if mo.length is 2:
return str.format('{:02d}', m + 1) return str.format('{:02d}', m + 1)
if supports_locales: if supports_locales:
options = {'month': {1:'numeric', 2:'2-digit', 3:'short', 4:'long'}[mo.length] or 'long'} options = {'month': {1:'numeric', 2:'2-digit', 3:'short', 4:'long'}[mo.length] or 'long'}
if as_utc: if as_utc:
options['timeZone'] = 'UTC' options['timeZone'] = 'UTC'
return dt.toLocaleString(undefined, options) return dt.toLocaleString(undefined, options)
return lcdata['abmon' if mo.length == 3 else 'mon'][m] return lcdata['abmon' if mo.length is 3 else 'mon'][m]
def fd_format_year(dt, ampm, yr, as_utc): def fd_format_year(dt, ampm, yr, as_utc):
y = dt.getUTCFullYear() if as_utc else dt.getFullYear() y = dt.getUTCFullYear() if as_utc else dt.getFullYear()
if yr.length == 2: if yr.length is 2:
return str.format('{:02d}', y % 100) return str.format('{:02d}', y % 100)
return str.format('{:04d}', y) return str.format('{:04d}', y)
@ -99,13 +99,13 @@ fd_function_index = {
def test_fd(date, fmt, ans): def test_fd(date, fmt, ans):
q = format_date(date, fmt, as_utc=True) q = format_date(date, fmt, as_utc=True)
if q != ans: if q is not ans:
raise Exception(str.format('Failed to format {} with {}: {} != {}', date, fmt, q, ans)) raise Exception(str.format('Failed to format {} with {}: {} is not {}', date, fmt, q, ans))
def format_date(date=None, fmt='dd MMM yyyy', as_utc=False): def format_date(date=None, fmt='dd MMM yyyy', as_utc=False):
fmt = fmt or 'dd MMM yyyy' fmt = fmt or 'dd MMM yyyy'
ampm = 'ap' in fmt.toLowerCase() ampm = 'ap' in fmt.toLowerCase()
if type(date) == 'string': if type(date) is 'string':
date = Date(date) date = Date(date)
date = date or Date() date = date or Date()
if is_date_undefined(date): if is_date_undefined(date):
@ -121,7 +121,7 @@ def format_date(date=None, fmt='dd MMM yyyy', as_utc=False):
) )
# }}} # }}}
if __name__ == '__main__': if __name__ is '__main__':
test_fd('1101-01-01T09:00:00+00:00', 'hh h', '09 9') test_fd('1101-01-01T09:00:00+00:00', 'hh h', '09 9')
test_fd('1101-01-01T09:05:01+00:00', 'hh h mm m ss s ap AP yy yyyy', '09 9 05 5 01 1 am AM 01 1101') test_fd('1101-01-01T09:05:01+00:00', 'hh h mm m ss s ap AP yy yyyy', '09 9 05 5 01 1 am AM 01 1101')
test_fd('2001-01-02T09:00:00+00:00', 'M MM MMM MMMM', '1 01 Jan January') test_fd('2001-01-02T09:00:00+00:00', 'M MM MMM MMMM', '1 01 Jan January')

View File

@ -82,12 +82,12 @@ class ModalContainer:
return modal_id return modal_id
def hide_modal(self, modal_id): def hide_modal(self, modal_id):
if self.current_modal is not None and self.current_modal.id == modal_id: if self.current_modal is not None and self.current_modal.id is modal_id:
self.clear_current_modal() self.clear_current_modal()
else: else:
doomed_modal = None doomed_modal = None
for i, modal in enumerate(self.modals): for i, modal in enumerate(self.modals):
if modal.id == modal_id: if modal.id is modal_id:
doomed_modal = i doomed_modal = i
break break
if doomed_modal is not None: if doomed_modal is not None:
@ -102,7 +102,7 @@ class ModalContainer:
except: except:
self.current_modal = None self.current_modal = None
raise raise
if c.style.display == 'none': if c.style.display is 'none':
set_css(c, display='block') set_css(c, display='block')
c.firstChild.lastChild.style.visibility = 'visible' if self.current_modal.show_close else 'hidden' c.firstChild.lastChild.style.visibility = 'visible' if self.current_modal.show_close else 'hidden'
@ -110,7 +110,7 @@ class ModalContainer:
self.current_modal = None self.current_modal = None
c = self.modal_container c = self.modal_container
clear(c.firstChild.firstChild) clear(c.firstChild.firstChild)
if self.modals.length == 0: if self.modals.length is 0:
set_css(c, display='none') set_css(c, display='none')
else: else:
self.update() self.update()

View File

@ -39,7 +39,7 @@ class FakeStorage:
return self.data[key] return self.data[key]
def setItem(self, key, value): def setItem(self, key, value):
if type(value) != 'string': if type(value) is not 'string':
value = JSON.stringify(value) value = JSON.stringify(value)
self.data[key] = value self.data[key] = value
@ -153,7 +153,7 @@ class UserSessionData(SessionData):
def push_to_server(self): def push_to_server(self):
if self.has_changes: if self.has_changes:
ajax_send('interface-data/set-session-data', self.changes, def(end_type, xhr, ev): ajax_send('interface-data/set-session-data', self.changes, def(end_type, xhr, ev):
if end_type != 'load': if end_type is not 'load':
console.error('Failed to send session data to server: ' + xhr.error_html) console.error('Failed to send session data to server: ' + xhr.error_html)
) )
self.changes = {} self.changes = {}

View File

@ -13,7 +13,7 @@ from book_list.globals import set_session_data
def on_library_loaded(end_type, xhr, ev): def on_library_loaded(end_type, xhr, ev):
p = document.getElementById('page_load_progress') p = document.getElementById('page_load_progress')
p.parentNode.removeChild(p) p.parentNode.removeChild(p)
if end_type == 'load': if end_type is 'load':
interface_data = JSON.parse(xhr.responseText) interface_data = JSON.parse(xhr.responseText)
if interface_data.translations: if interface_data.translations:
install(interface_data.translations) install(interface_data.translations)
@ -22,7 +22,7 @@ def on_library_loaded(end_type, xhr, ev):
Boss(interface_data) Boss(interface_data)
else: else:
p = E.p(style='color:red; font-weight: bold; font-size:1.5em') p = E.p(style='color:red; font-weight: bold; font-size:1.5em')
if xhr.status == 401: if xhr.status is 401:
p.innerHTML = _('You are not authorized to view this site') p.innerHTML = _('You are not authorized to view this site')
else: else:
p.innerHTML = xhr.error_html p.innerHTML = xhr.error_html
@ -50,7 +50,7 @@ def load_book_list():
def on_load(): def on_load():
ep = window.calibre_entry_point ep = window.calibre_entry_point
v'delete window.calibre_entry_point' v'delete window.calibre_entry_point'
if ep == 'book list': if ep is 'book list':
print('calibre loaded at:', Date().toString()) print('calibre loaded at:', Date().toString())
load_book_list() load_book_list()

View File

@ -22,7 +22,7 @@ def debounce(func, wait, immediate=False):
func.apply(context, args) func.apply(context, args)
def to_utf8(string): def to_utf8(string):
if type(TextEncoder) == 'function': if type(TextEncoder) is 'function':
return TextEncoder('utf-8').encode(string) return TextEncoder('utf-8').encode(string)
escstr = encodeURIComponent(string) escstr = encodeURIComponent(string)
binstr = escstr.replace(/%([0-9A-F]{2})/g, def(match, p1): binstr = escstr.replace(/%([0-9A-F]{2})/g, def(match, p1):
@ -61,7 +61,7 @@ _roman = list(zip(
)) ))
def roman(num): def roman(num):
if num <= 0 or num >= 4000 or int(num) != num: if num <= 0 or num >= 4000 or int(num) is not num:
return num + '' return num + ''
result = [] result = []
for d, r in _roman: for d, r in _roman:
@ -71,13 +71,13 @@ def roman(num):
return result.join('') return result.join('')
def fmt_sidx(val, fmt='{:.2f}', use_roman=True): def fmt_sidx(val, fmt='{:.2f}', use_roman=True):
if val is undefined or val is None or val == '': if val is undefined or val is None or val is '':
return '1' return '1'
if int(val) == float(val): if int(val) is float(val):
if use_roman: if use_roman:
return roman(val) return roman(val)
return int(val) + '' return int(val) + ''
return str.format(fmt, float(val)) return str.format(fmt, float(val))
if __name__ == '__main__': if __name__ is '__main__':
print(fmt_sidx(10), fmt_sidx(1.2)) print(fmt_sidx(10), fmt_sidx(1.2))