rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
desc = '\n'.join(textwrap.wrap(plugin.description, 50))
desc = '\n'.join(textwrap.wrap(plugin.description, 100))
def data(self, index, role): if not index.isValid(): return NONE if index.internalId() == 0: if role == Qt.DisplayRole: category = self.categories[index.row()] return QVariant(_("%(plugin_type)s %(plugins)s")%\ dict(plugin_type=category, plugins=_('plugins'))) else: plugin = self.index_to_plugin(index) if role == Qt.Di...
self.setWindowTitle(self.base_window_title+' - '+title)
self.setWindowTitle(self.base_window_title+' - '+title + ' [%s]'%os.path.splitext(pathtoebook)[1][1:].upper())
def load_ebook(self, pathtoebook): if self.iterator is not None: self.save_current_position() self.iterator.__exit__() self.iterator = EbookIterator(pathtoebook) self.open_progress_indicator(_('Loading ebook...')) worker = Worker(target=self.iterator.__enter__) worker.start() while worker.isAlive(): worker.join(0.1) QA...
for i in range(h.count()): if not h.isSectionHidden(i): index = self.model().index(row, i) self.setCurrentIndex(index) if select: sm = self.selectionModel() sm.select(index, sm.ClearAndSelect|sm.Rows) break
logical_indices = list(range(h.count())) logical_indices = [x for x in logical_indices if not h.isSectionHidden(x)] pairs = [(x, h.visualIndex(x)) for x in logical_indices if h.visualIndex(x) > -1] if not pairs: pairs = [(0, 0)] pairs.sort(cmp=lambda x,y:cmp(x[1], y[1])) i = pairs[0][0] index = self.model().index(row, ...
def set_current_row(self, row, select=True): if row > -1: h = self.horizontalHeader() for i in range(h.count()): if not h.isSectionHidden(i): index = self.model().index(row, i) self.setCurrentIndex(index) if select: sm = self.selectionModel() sm.select(index, sm.ClearAndSelect|sm.Rows) break
'or the ISBN key.')).exec_()
'and/or removing the ISBN.')).exec_() self.reject()
def hangcheck(self): if self.fetcher.is_alive() and \ time.time() - self.start_time < self.HANG_TIME: return self._hangcheck.stop() try: if self.fetcher.is_alive(): error_dialog(self, _('Could not find metadata'), _('The metadata download seems to have stalled. ' 'Try again later.')).exec_() self.terminate() return sel...
<div class="hr"><blockquote><hr/></blockquote></div>
{0}
def generateHTMLDescriptionHeader(self, title):
'''
'''.format(title_border)
def generateHTMLDescriptionHeader(self, title):
if opts.fmt == 'mobi' and opts.output_profile.startswith("kindle"):
if opts.fmt == 'mobi' and opts.output_profile and opts.output_profile.startswith("kindle"):
def run(self, path_to_output, opts, db, notification=DummyReporter()): from calibre.utils.logging import Log
return cmp(self.title, getattr(other, 'title', ''))
return cmp(self.title.lower(), getattr(other, 'title', '').lower())
def __cmp__(self, other): return cmp(self.title, getattr(other, 'title', ''))
elem.top_gap = None
elem.top_gap_ratio = None
def collect_stats(self): if len(self.elements) > 1: gaps = [self.elements[i+1].top - self.elements[i].bottom for i in range(0, len(self.elements)-1)] self.average_line_separation = sum(gaps)/len(gaps) for i, elem in enumerate(self.elements): left_margin = elem.left - self.left elem.indent_fraction = left_margin/self.wi...
elem.top_gap = self.elements[i-1].bottom - elem.top
elem.top_gap_ratio = (self.elements[i-1].bottom - elem.top)/self.average_line_separation
def collect_stats(self): if len(self.elements) > 1: gaps = [self.elements[i+1].top - self.elements[i].bottom for i in range(0, len(self.elements)-1)] self.average_line_separation = sum(gaps)/len(gaps) for i, elem in enumerate(self.elements): left_margin = elem.left - self.left elem.indent_fraction = left_margin/self.wi...
indented = [i for (i, x) in enumerate(self.elements) if x.indent_fraction >= 0.2]
self.boxes = [Box()] for i, elem in enumerate(self.elements): if isinstance(elem, Image): self.boxes.append(ImageBox(elem)) img = Interval(elem.left, elem.right) for j in range(i+1, len(self.elements)): t = self.elements[j] if not isinstance(t, Text): break ti = Interval(t.left, t.right) if not ti.centered_in(img): bre...
def linearize(self): self.elements = [] for x in self.columns: self.elements.extend(x)
match = re.search(r'REV_.*?&(\d+)', pnp_id)
match = re.search(r'REV_.*?&(\d+)
def drive_order(self, pnp_id): order = 0 match = re.search(r'REV_.*?&(\d+)', pnp_id) if match is not None: order = int(match.group(1)) return order
with TemporaryDirectory('_chm2oeb', keep=True) as tdir:
with TemporaryDirectory('_snb2oeb', keep=True) as tdir:
def convert(self, stream, options, file_ext, log, accelerators): log.debug("Parsing SNB file...") snbFile = SNBFile() try: snbFile.Parse(stream) except: raise ValueError("Invalid SNB file") if not snbFile.IsValid(): log.debug("Invaild SNB file") raise ValueError("Invalid SNB file") log.debug("Handle meta data ...") fro...
'server.socket_host' : '0.0.0.0',
'server.socket_host' : listen_on,
def __init__(self, db, opts, embedded=False, show_tracebacks=True): self.db = db for item in self.db: item break self.opts = opts self.embedded = embedded self.max_cover_width, self.max_cover_height = \ map(int, self.opts.max_cover.split('x')) self.max_stanza_items = opts.max_opds_items path = P('content_server') self....
cherrypy.engine.exit()
try: cherrypy.engine.exit() finally: cherrypy.server.httpserver = None
def exit(self): cherrypy.engine.exit()
answers.sort(cmp=lambda x, y: cmp(int(x.preference), int(y.preference))) return [str(x.exchange) for x in answers]
answers.sort(cmp=lambda x, y: cmp(int(getattr(x, 'preference', sys.maxint)), int(getattr(y, 'preference', sys.maxint)))) return [str(x.exchange) for x in answers if hasattr(x, 'exchange')]
def get_mx(host, verbose=0): import dns.resolver if verbose: print 'Find mail exchanger for', host answers = list(dns.resolver.query(host, 'MX')) answers.sort(cmp=lambda x, y: cmp(int(x.preference), int(y.preference))) return [str(x.exchange) for x in answers]
self.add_format(id, format, stream, index_is_id=True, path=tpath)
self.add_format(id, format, stream, index_is_id=True, path=tpath, notify=False)
def set_path(self, index, index_is_id=False, commit=True): ''' Set the path to the directory containing this books files based on its current title and author. If there was a previous directory, its contents are copied and it is deleted. ''' id = index if index_is_id else self.id(index) path = self.construct_path_name...
images.append('<binary id="%s" content-type="%s">%s\n</binary>' % (self.image_hrefs[item.href], item.media_type, data))
images.append('<binary id="%s">%s\n</binary>' % (self.image_hrefs[item.href], data))
def fb2mlize_images(self): ''' This function uses the self.image_hrefs dictionary mapping. It is populated by the dump_text function. ''' images = [] for item in self.oeb_book.manifest: # Don't write the image if it's not referenced in the document's text. if item.href not in self.image_hrefs: continue if item.media_ty...
self.timer.start(1500)
if self.as_you_type: self.timer.start(1500)
def key_pressed(self, event): self.normalize_state() if self._in_a_search: self.emit(SIGNAL('changed()')) self._in_a_search = False if event.key() in (Qt.Key_Return, Qt.Key_Enter): self.do_search() self.timer.start(1500)
self.db.clean()
l = getattr(self, 'library_view', None) if l: l = getattr(l, 'model', None); if l: l = l().db if l: l.clean()
def shutdown(self, write_settings=True): self.db.clean() for action in self.iactions.values(): if not action.shutting_down(): return if write_settings: self.write_settings() self.check_messages_timer.stop() self.update_checker.terminate() self.listener.close() self.job_manager.server.close() while self.spare_servers: s...
book.author_sort = self.db.author_sort_from_authors(book.authors)
book.author_sort = self.library_view.model().db.author_sort_from_authors(book.authors)
def set_books_in_library(self, booklists, reset=False): if reset: # First build a cache of the library, so the search isn't On**2 self.db_book_title_cache = {} self.db_book_uuid_cache = set() db = self.library_view.model().db for id in db.data.iterallids(): mi = db.get_metadata(id, index_is_id=True) title = re.sub('(?u...
else: self.select_format(db, book_id)
elif not self.select_format(db, book_id): self.cancelled = True return self.cancelled = False
def __init__(self, db, book_id, regex, *args): QDialog.__init__(self, *args) self.setupUi(self)
error_dialog(self, _('No formats available'), _('Cannot build regex using the GUI builder without a book.')) QDialog.reject() else: self.open_book(db.format_abspath(book_id, format, index_is_id=True))
error_dialog(self, _('No formats available'), _('Cannot build regex using the GUI builder without a book.'), show=True) return False self.open_book(db.format_abspath(book_id, format, index_is_id=True)) return True
def select_format(self, db, book_id): format = None formats = db.formats(book_id, index_is_id=True).upper().split(',') if len(formats) == 1: format = formats[0] elif len(formats) > 1: d = ChooseFormatDialog(self, _('Choose the format to view'), formats) d.exec_() if d.result() == QDialog.Accepted: format = d.format()
'search', 'date',
def set_search_restriction(self, s): self.db.data.set_search_restriction(s)
if c.get('textconvert', True) and mi.comments is not None \ and html_check.search(mi.comments) is not None: mi.comments = html2text(mi.comments)
def _fetch(self): try: self.fetch() if self.results: c = self.config_store().get(self.name, {}) res = self.results if hasattr(res, 'authors'): res = [res] for mi in res: if not c.get('rating', True): mi.rating = None if not c.get('comments', True): mi.comments = None if c.get('textconvert', True) and mi.comments is not...
cb = QCheckBox(_('Convert comments downloaded from %s to plain text')%(self.name)) setattr(w, '_textcomments', cb) cb.setChecked(c.get('textcomments', False)) w._layout.addWidget(cb)
if self.has_html_comments: cb = QCheckBox(_('Convert comments downloaded from %s to plain text')%(self.name)) setattr(w, '_textcomments', cb) cb.setChecked(c.get('textcomments', False)) w._layout.addWidget(cb)
def config_widget(self): from PyQt4.Qt import QWidget, QVBoxLayout, QLabel, Qt, QLineEdit, \ QCheckBox from calibre.customize.ui import config w = QWidget() w._layout = QVBoxLayout(w) w.setLayout(w._layout) if self.string_customization_help is not None: w._sc_label = QLabel(self.string_customization_help, w) w._layout....
for x in ('rating', 'tags', 'comments', 'textcomments'):
for x in ('rating', 'tags', 'comments'):
def save_settings(self, w): dl_settings = {} for x in ('rating', 'tags', 'comments', 'textcomments'): dl_settings[x] = getattr(w, '_'+x).isChecked() c = self.config_store() c.set(self.name, dl_settings) if hasattr(w, '_sc'): sc = unicode(w._sc.text()).strip() from calibre.customize.ui import customize_plugin customize_...
* Connect to the search() and cleared() signals from this widget
* Connect to the search() and cleared() signals from this widget. * Connect to the cleared() signal to know when the box content changes
def paste(self, *args): if self.parent().help_state: self.parent().normalize_state() return QLineEdit.paste(self)
cssdict['font-size'] = fnums[esize]
font_size = fnums[esize]
def force_int(raw): return int(re.search(r'([0-9+-]+)', raw).group(1))
cssdict['font-size'] = fnums[force_int(size)]
font_size = fnums[force_int(size)]
def force_int(raw): return int(re.search(r'([0-9+-]+)', raw).group(1))
cssdict['font-size'] = fnums[3]
font_size = fnums[3] cssdict['font-size'] = '%.1fpt'%font_size
def force_int(raw): return int(re.search(r'([0-9+-]+)', raw).group(1))
fsize = self.fmap[style['font-size']]
fsize = self.fmap[font_size]
def force_int(raw): return int(re.search(r'([0-9+-]+)', raw).group(1))
attachment_names = [mi.title+os.path.splitext(attachment)[1]]
attachment_names = [ascii_filename(mi.title)+os.path.splitext(attachment)[1]]
def email_news(self, id): opts = email_config().parse() accounts = [(account, [x.strip().lower() for x in x[0].split(',')]) for account, x in opts.accounts.items() if x[1]] sent_mails = [] for account, fmts in accounts: files, auto = self.library_view.model().\ get_preferred_formats_from_ids([id], fmts) files = [f for ...
'format':lambda x: os.path.splitext(x.path)[1].lower()
'format':lambda x: os.path.splitext(x.path)[1].lower(), 'formats':lambda x: os.path.splitext(x.path)[1].lower()
def get_matches(self, location, query): location = location.lower().strip() if location == 'authors': location = 'author'
self.log.info(" looking for %s" % str(p_book['lib_book'])[-9:])
self.log.info(" looking for '%s' by %s uuid:%s" % (p_book['title'],p_book['author'], p_book['uuid']))
def add_books_to_metadata(self, locations, metadata, booklists): ''' Add locations to the booklists. This function must not communicate with the device. @param locations: Result of a call to L{upload_books} @param metadata: List of MetaInformation objects, same as for :method:`upload_books`. @param booklists: A tuple c...
this_book.uuid = book.album()
this_book.uuid = book.composer()
def books(self, oncard=None, end_session=True): """ Return a list of ebooks on the device. @param oncard: If 'carda' or 'cardb' return a list of ebooks on the specific storage card, otherwise return list of ebooks in main memory of device. If a card is specified and no books are on the card return empty list. @return:...
self.log.info(" looking for '%s' by '%s' (%s)" %
self.log.info(" looking for '%s' by '%s' uuid:%s" %
def remove_books_from_metadata(self, paths, booklists): ''' Remove books from the metadata list. This function must not communicate with the device. @param paths: paths to books on the device. @param booklists: A tuple containing the result of calls to (L{books}(oncard=None), L{books}(oncard='carda'), L{books}(oncard=...
if False: self.log.info(" evaluating '%s' by '%s' (%s)" %
if DEBUG: self.log.info(" evaluating '%s' by '%s' uuid:%s" %
def remove_books_from_metadata(self, paths, booklists): ''' Remove books from the metadata list. This function must not communicate with the device. @param paths: paths to books on the device. @param booklists: A tuple containing the result of calls to (L{books}(oncard=None), L{books}(oncard='carda'), L{books}(oncard=...
else: if DEBUG: self.log.error(" unable to find '%s' by '%s' (%s)" % (bl_book.title, bl_book.author,bl_book.uuid))
def remove_books_from_metadata(self, paths, booklists): ''' Remove books from the metadata list. This function must not communicate with the device. @param paths: paths to books on the device. @param booklists: A tuple containing the result of calls to (L{books}(oncard=None), L{books}(oncard='carda'), L{books}(oncard=...
self.log.info(" adding '%s' by '%s' ['%s'] to self.cached_books" %
self.log.info("ITUNES.upload_books()") self.log.info(" adding '%s' by '%s' uuid:%s to self.cached_books" %
def upload_books(self, files, names, on_card=None, end_session=True, metadata=None): ''' Upload a list of books to the device. If a file already exists on the device, it should be replaced. This method should raise a L{FreeSpaceError} if there is not enough free space on the device. The text of the FreeSpaceError must ...
if DEBUG: self.log.info("ITUNES.upload_books()") self.log.info(" adding '%s' by '%s' uuid:%s to self.cached_books" % ( metadata[i].title, metadata[i].author, metadata[i].uuid))
def upload_books(self, files, names, on_card=None, end_session=True, metadata=None): ''' Upload a list of books to the device. If a file already exists on the device, it should be replaced. This method should raise a L{FreeSpaceError} if there is not enough free space on the device. The text of the FreeSpaceError must ...
self.log.info("%s%-40.40s %-30.30s %-10.10s" % (' '*indent,book.title, book.author, str(book.library_id)[-9:]))
self.log.info("%s%-40.40s %-30.30s %-10.10s %s" % (' '*indent,book.title, book.author, str(book.library_id)[-9:], book.uuid))
def _dump_booklist(self, booklist, header=None,indent=0): ''' ''' if header: msg = '\n%sbooklist %s:' % (' '*indent,header) self.log.info(msg) self.log.info('%s%s' % (' '*indent,'-' * len(msg)))
self.log.info("%s%-40.40s %-30.30s %-10.10s" %
self.log.info("%s%-40.40s %-30.30s %-10.10s %s" %
def _dump_update_list(self,header=None,indent=0): if header: msg = '\n%sself.update_list %s' % (' '*indent,header) self.log.info(msg) self.log.info( "%s%s" % (' '*indent,'-' * len(msg)))
str(ub['lib_book'])[-9:]))
str(ub['lib_book'])[-9:], ub['uuid']))
def _dump_update_list(self,header=None,indent=0): if header: msg = '\n%sself.update_list %s' % (' '*indent,header) self.log.info(msg) self.log.info( "%s%s" % (' '*indent,'-' * len(msg)))
this_book.uuid = library_books[book].album()
this_book.uuid = library_books[book].composer()
def books(self, oncard=None, end_session=True): """ Return a list of ebooks on the device. @param oncard: If 'carda' or 'cardb' return a list of ebooks on the specific storage card, otherwise return list of ebooks in main memory of device. If a card is specified and no books are on the card return empty list. @return:...
color=istate.fgcolor)
color=unicode(istate.fgcolor))
def mobimlize_content(self, tag, text, bstate, istates): 'Convert text content' if text or tag != 'br': bstate.content = True istate = istates[-1] para = bstate.para if tag in SPECIAL_TAGS and not text: para = para if para is not None else bstate.body elif para is None or tag in ('td', 'th'): body = bstate.body if bsta...
if DEBUG:
if False:
def remove_books_from_metadata(self, paths, booklists): ''' Remove books from the metadata list. This function must not communicate with the device. @param paths: paths to books on the device. @param booklists: A tuple containing the result of calls to (L{books}(oncard=None), L{books}(oncard='carda'), L{books}(oncard=...
cherrypy.response.headers['Content-Type'] = {
fname = posixpath.basename(name) try: cherrypy.response.headers['Content-Type'] = {
def static(self, name): 'Serves static content' name = name.lower() cherrypy.response.headers['Content-Type'] = { 'js' : 'text/javascript', 'css' : 'text/css', 'png' : 'image/png', 'gif' : 'image/gif', 'html' : 'text/html', '' : 'application/octet-stream', }[name.rpartition('.')[-1].lower()] cherrypy.response...
'' : 'application/octet-stream', }[name.rpartition('.')[-1].lower()]
}[fname.rpartition('.')[-1].lower()] except KeyError: raise cherrypy.HTTPError(404, '%r not a valid resource type'%name)
def static(self, name): 'Serves static content' name = name.lower() cherrypy.response.headers['Content-Type'] = { 'js' : 'text/javascript', 'css' : 'text/css', 'png' : 'image/png', 'gif' : 'image/gif', 'html' : 'text/html', '' : 'application/octet-stream', }[name.rpartition('.')[-1].lower()] cherrypy.response...
path = P('content_server/'+name) if not os.path.exists(path):
basedir = os.path.abspath(P('content_server')) path = os.path.join(basedir, name.replace('/', os.sep)) path = os.path.abspath(path) if not path.startswith(basedir): raise cherrypy.HTTPError(403, 'Access to %s is forbidden'%name) if not os.path.exists(path) or not os.path.isfile(path):
def static(self, name): 'Serves static content' name = name.lower() cherrypy.response.headers['Content-Type'] = { 'js' : 'text/javascript', 'css' : 'text/css', 'png' : 'image/png', 'gif' : 'image/gif', 'html' : 'text/html', '' : 'application/octet-stream', }[name.rpartition('.')[-1].lower()] cherrypy.response...
navbar.append(HR()) text = 'This article was downloaded by ' p = PT(text, STRONG(__appname__), A(url, href=url), style='text-align:left; max-width: 100%; overflow: hidden;') p[0].tail = ' from ' navbar.append(p) navbar.append(BR())
if not url.startswith('file://'): navbar.append(HR()) text = 'This article was downloaded by ' p = PT(text, STRONG(__appname__), A(url, href=url), style='text-align:left; max-width: 100%; overflow: hidden;') p[0].tail = ' from ' navbar.append(p) navbar.append(BR())
def _generate(self, bottom, feed, art, number_of_articles_in_feed, two_levels, url, __appname__, prefix='', center=True, extra_css=None, style=None): head = HEAD(TITLE('navbar')) if style: head.append(STYLE(style, type='text/css')) if extra_css: head.append(STYLE(extra_css, type='text/css'))
if os.sep in unicode(path):
path = unicode(path) if os.sep in path:
def open_book_path(self, path): if os.sep in unicode(path): open_local_file(path) else: format = unicode(path) path = self.view.model().db.format_abspath(self.current_row, format) if path is not None: open_local_file(path)
format = unicode(path) path = self.view.model().db.format_abspath(self.current_row, format)
path = self.view.model().db.format_abspath(self.current_row, path)
def open_book_path(self, path): if os.sep in unicode(path): open_local_file(path) else: format = unicode(path) path = self.view.model().db.format_abspath(self.current_row, format) if path is not None: open_local_file(path)
self.topaz_headers = self.get_headers(offset)
self.topaz_headers, self.th_seq = self.get_headers(offset)
def __init__(self, stream): self.stream = stream self.data = StreamSlicer(stream)
return topaz_headers
return topaz_headers, th_seq
def get_headers(self, offset): # Build a dict of topaz_header records topaz_headers = {} for x in range(self.header_records): offset += 1 taglen, consumed = self.decode_vwi(self.data[offset:offset+4]) offset += consumed tag = self.data[offset:offset+taglen] offset += taglen num_vals, consumed = self.decode_vwi(self.dat...
for tag in self.metadata:
for tag in self.md_seq:
def generate_metadata_stream(self): ms = StringIO.StringIO() ms.write(self.encode_vwi(len(self.md_header['tag'])).encode('iso-8859-1')) ms.write(self.md_header['tag']) ms.write(chr(self.md_header['flags'])) ms.write(chr(len(self.metadata)))
headers = {} for tag in self.topaz_headers: if self.topaz_headers[tag]['blocks']: headers[tag] = self.topaz_headers[tag]['blocks'][0]['offset'] else: headers[tag] = None
def regenerate_headers(self, updated_md_len):
for tag in headers.keys():
for tag in self.th_seq:
def regenerate_headers(self, updated_md_len):
head = self.regenerate_headers(len(updated_metadata))
prefix = len('metadata') + 2 um_buf_len = len(updated_metadata) - prefix head = self.regenerate_headers(um_buf_len)
def update(self,mi): # Collect the original metadata self.get_original_metadata()
chunk2 = self.data[self.original_md_start + self.original_md_len:]
chunk2 = self.data[prefix + self.original_md_start + self.original_md_len:]
def update(self,mi): # Collect the original metadata self.get_original_metadata()
mi = MetaInformation(title="A Marvelously Long Title", authors=['Riker, Gregory; Riker, Charles'])
mi = MetaInformation(title="Updated Title", authors=['Author, Random'])
def set_metadata(stream, mi): mu = MetadataUpdater(stream) mu.update(mi) return
def toggle_cover_browser(self):
def toggle_cover_browser(self, *args):
def toggle_cover_browser(self): cbd = getattr(self, 'cb_dialog', None) if cbd is not None: self.hide_cover_browser() else: self.show_cover_browser()
d.finished.connect(self.cb_splitter.button.set_state_to_show)
d.finished.connect(self.cover_browser_closed)
def show_cover_browser(self): d = QDialog(self) ah, aw = available_height(), available_width() d.resize(int(aw/1.5), ah-60) d._layout = QStackedLayout() d.setLayout(d._layout) d.setWindowTitle(_('Browse by covers')) d.layout().addWidget(self.cover_flow) self.cover_flow.setVisible(True) self.cover_flow.setFocus(Qt.Other...
def hide_cover_browser(self):
self.cb_splitter.button.set_state_to_hide() def cover_browser_closed(self, *args): self.cb_dialog = None self.cb_splitter.button.set_state_to_show() def hide_cover_browser(self, *args):
def show_cover_browser(self): d = QDialog(self) ah, aw = available_height(), available_width() d.resize(int(aw/1.5), ah-60) d._layout = QStackedLayout() d.setLayout(d._layout) d.setWindowTitle(_('Browse by covers')) d.layout().addWidget(self.cover_flow) self.cover_flow.setVisible(True) self.cover_flow.setFocus(Qt.Other...
self.column_map = config['column_map'][:]
cmap = config['column_map'][:]
def read_config(self): self.use_roman_numbers = config['use_roman_numerals_for_series_number'] self.column_map = config['column_map'][:] # force a copy self.headers = {} for i in self.column_map: # take out any columns no longer in the db if not i in self.orig_headers and not i in self.custom_columns: self.column_map.r...
for i in self.column_map: if not i in self.orig_headers and not i in self.custom_columns: self.column_map.remove(i) for i in self.column_map: if i in self.orig_headers: self.headers[i] = self.orig_headers[i] elif i in self.custom_columns: self.headers[i] = self.custom_columns[i]['name']
self.column_map = [] for col in cmap: if col in self.orig_headers or col in self.custom_columns: self.column_map.append(col) for col in self.column_map: if col in self.orig_headers: self.headers[col] = self.orig_headers[col] elif col in self.custom_columns: self.headers[col] = self.custom_columns[col]['name']
def read_config(self): self.use_roman_numbers = config['use_roman_numerals_for_series_number'] self.column_map = config['column_map'][:] # force a copy self.headers = {} for i in self.column_map: # take out any columns no longer in the db if not i in self.orig_headers and not i in self.custom_columns: self.column_map.r...
key = str(item.text).rpartition(':')[-1] key = list(map(ord, uuid.UUID(key).bytes))
try: key = str(item.text).rpartition(':')[-1] key = list(map(ord, uuid.UUID(key).bytes)) except: import traceback traceback.print_exc() key = None
def process_encryption(self, encfile, opf, log): key = None for item in opf.identifier_iter(): scheme = None for xkey in item.attrib.keys(): if xkey.endswith('scheme'): scheme = item.get(xkey) if (scheme and scheme.lower() == 'uuid') or \ (item.text and item.text.startswith('urn:uuid:')): key = str(item.text).rpartitio...
if os.path.exists(path):
if key is not None and os.path.exists(path):
def process_encryption(self, encfile, opf, log): key = None for item in opf.identifier_iter(): scheme = None for xkey in item.attrib.keys(): if xkey.endswith('scheme'): scheme = item.get(xkey) if (scheme and scheme.lower() == 'uuid') or \ (item.text and item.text.startswith('urn:uuid:')): key = str(item.text).rpartitio...
if self.booksByTitle is None:
if not len(self.booksByTitle):
def buildSources(self): if self.booksByTitle is None: self.fetchBooksByTitle() if self.booksByTitle is None: return False self.fetchBooksByAuthor() self.generateHTMLDescriptions() self.generateHTMLByAuthor() if self.opts.generate_titles: self.generateHTMLByTitle() if self.opts.generate_recently_added: self.generateHTML...
f.seek(0) for i in range(1024): f.write(chr(ord(data[i]) ^ key[i%16]))
if len(data) >= 1024: f.seek(0) for i in range(1024): f.write(chr(ord(data[i]) ^ key[i%16])) else: self.log.warn('Font', path, 'is invalid, ignoring')
def encrypt_fonts(self, uris, tdir, uuid): # {{{ from binascii import unhexlify
imagename = self.normalize_path(prefix + '.kobo/images/' + ImageID + ' - NickelBookCover.parsed')
imagename = self.normalize_path(self._main_prefix + '.kobo/images/' + ImageID + ' - NickelBookCover.parsed')
def update_booklist(prefix, path, title, authors, mime, date, ContentType, ImageID): changed = False # if path_to_ext(path) in self.FORMATS: try: lpath = path.partition(self.normalize_path(prefix))[2] if lpath.startswith(os.sep): lpath = lpath[len(os.sep):] lpath = lpath.replace('\\', '/')
try: self.results = search(self.title, self.book_author, self.publisher, self.isbn, max_results=5, verbose=self.verbose, lang='all')
if not self.isbn: return try: self.results = get_social_metadata(self.title, self.book_author, self.publisher, self.isbn, verbose=self.verbose, lang='all')[0]
def fetch(self): try: self.results = search(self.title, self.book_author, self.publisher, self.isbn, max_results=5, verbose=self.verbose, lang='all') except Exception, e: self.exception = e self.tb = traceback.format_exc()
title = unicode(self.title.text())
title = unicode(self.title.text()).strip()
def accept(self): cf = getattr(self, 'cover_fetcher', None) if cf is not None and hasattr(cf, 'terminate'): cf.terminate() cf.wait() try: if self.formats_changed: self.sync_formats() title = unicode(self.title.text()) self.db.set_title(self.id, title, notify=False) au = unicode(self.authors.text()) if au: self.db.set_a...
au = unicode(self.authors.text())
au = unicode(self.authors.text()).strip()
def accept(self): cf = getattr(self, 'cover_fetcher', None) if cf is not None and hasattr(cf, 'terminate'): cf.terminate() cf.wait() try: if self.formats_changed: self.sync_formats() title = unicode(self.title.text()) self.db.set_title(self.id, title, notify=False) au = unicode(self.authors.text()) if au: self.db.set_a...
aus = unicode(self.author_sort.text())
aus = unicode(self.author_sort.text()).strip()
def accept(self): cf = getattr(self, 'cover_fetcher', None) if cf is not None and hasattr(cf, 'terminate'): cf.terminate() cf.wait() try: if self.formats_changed: self.sync_formats() title = unicode(self.title.text()) self.db.set_title(self.id, title, notify=False) au = unicode(self.authors.text()) if au: self.db.set_a...
re.sub(r'[^0-9a-zA-Z]', '', unicode(self.isbn.text())),
re.sub(r'[^0-9a-zA-Z]', '', unicode(self.isbn.text()).strip()),
def accept(self): cf = getattr(self, 'cover_fetcher', None) if cf is not None and hasattr(cf, 'terminate'): cf.terminate() cf.wait() try: if self.formats_changed: self.sync_formats() title = unicode(self.title.text()) self.db.set_title(self.id, title, notify=False) au = unicode(self.authors.text()) if au: self.db.set_a...
self.db.set_publisher(self.id, unicode(self.publisher.currentText()),
self.db.set_publisher(self.id, unicode(self.publisher.currentText()).strip(),
def accept(self): cf = getattr(self, 'cover_fetcher', None) if cf is not None and hasattr(cf, 'terminate'): cf.terminate() cf.wait() try: if self.formats_changed: self.sync_formats() title = unicode(self.title.text()) self.db.set_title(self.id, title, notify=False) au = unicode(self.authors.text()) if au: self.db.set_a...
self.db.set_comment(self.id, unicode(self.comments.toPlainText()),
self.db.set_comment(self.id, unicode(self.comments.toPlainText()).strip(),
def accept(self): cf = getattr(self, 'cover_fetcher', None) if cf is not None and hasattr(cf, 'terminate'): cf.terminate() cf.wait() try: if self.formats_changed: self.sync_formats() title = unicode(self.title.text()) self.db.set_title(self.id, title, notify=False) au = unicode(self.authors.text()) if au: self.db.set_a...
spine.append(E.itemref(idref=ref.id))
if ref.id is not None: spine.append(E.itemref(idref=ref.id))
def CAL_ELEM(name, content): return M.meta(name=name, content=content)
handle = ctypes.c_int(0)
handle = ctypes.c_void_p(0)
def BambookConnect(ip = DEFAULT_BAMBOOK_IP, timeout = 0): if isinstance(ip, unicode): ip = ip.encode('ascii') handle = ctypes.c_int(0) if lib_handle == None: raise Exception(_('Bambook SDK has not been installed.')) ret = lib_handle.BambookConnect(ip, timeout, ctypes.byref(handle)) if ret == BR_SUCC: return handle else...
if mult in ['k', 'm', 'g']:
mult = {'k':1024.,'m': 1024.**2, 'g': 1024.**3}.get(mult, 1.0) if mult != 1.0:
def get_numeric_matches(self, location, query): matches = set([]) if len(query) == 0: return matches if query == 'false': query = '0' elif query == 'true': query = '!=0' relop = None for k in self.numeric_search_relops.keys(): if query.startswith(k): (p, relop) = self.numeric_search_relops[k] query = query[p:] if relop...
mult = {'k':1024., 'm': 1024.*1024, 'g': 1024.*1024*1024}[mult]
else: mult = 1.0
def get_numeric_matches(self, location, query): matches = set([]) if len(query) == 0: return matches if query == 'false': query = '0' elif query == 'true': query = '!=0' relop = None for k in self.numeric_search_relops.keys(): if query.startswith(k): (p, relop) = self.numeric_search_relops[k] query = query[p:] if relop...
if cname in ('title', 'authors') or (cname == 'collection' and \ self.db.supports_collections()):
if cname in ('title', 'authors') or \ (cname == 'collections' and self.db.supports_collections()):
def flags(self, index): if self.map[index.row()] in self.indices_to_be_deleted(): return Qt.ItemIsUserCheckable # Can't figure out how to get the disabled flag in python flags = QAbstractTableModel.flags(self, index) if index.isValid() and self.editable: cname = self.column_map[index.column()] if cname in ('title', 'a...
if comments and comments != u'None': self.renderer.queue.put((rows, comments))
if not comments or comments == u'None': comments = '' self.renderer.queue.put((rows, comments))
def show_data(self, data): rows = render_rows(data) rows = u'\n'.join([u'<tr><td valign="top"><b>%s:</b></td><td valign="top">%s</td></tr>'%(k,t) for k, t in rows]) comments = data.get(_('Comments'), '') if comments and comments != u'None': self.renderer.queue.put((rows, comments)) self._show_data(rows, '')
from cherrypy.process.plugins import Daemonizer d = Daemonizer(cherrypy.engine) d.subscribe()
daemonize()
def main(args=sys.argv): from calibre.library.database2 import LibraryDatabase2 parser = option_parser() opts, args = parser.parse_args(args) if opts.daemonize and not iswindows: from cherrypy.process.plugins import Daemonizer d = Daemonizer(cherrypy.engine) d.subscribe() if opts.pidfile is not None: from cherrypy.proc...
self.orig_timestamp = timestamp.astimezone(utc_tz)
def __init__(self, window, row, db, accepted_callback=None, cancel_all=False): ResizableDialog.__init__(self, window) self.bc_box.layout().setAlignment(self.cover, Qt.AlignCenter|Qt.AlignHCenter) self.cancel_all = False base = unicode(self.author_sort.toolTip()) self.ok_aus_tooltip = '<p>' + textwrap.fill(base+'<br><br...
if d.date() != self.orig_timestamp.date():
if d != self.orig_date:
def accept(self): cf = getattr(self, 'cover_fetcher', None) if cf is not None and hasattr(cf, 'terminate'): cf.terminate() cf.wait() try: if self.formats_changed: self.sync_formats() title = unicode(self.title.text()).strip() self.db.set_title(self.id, title, notify=False) au = unicode(self.authors.text()).strip() if a...
qd = parse_date(query)
qd = parse_date(query, as_utc=False)
def get_dates_matches(self, location, query): matches = set([]) if len(query) < 2: return matches
self.books.append({ 'mi': mi, 'timestamp': timestamp, 'formats': list(zip(fmts, sizes, names)), 'id': int(book_id), 'dirpath': dirpath, 'path': path, })
if int(mi.application_id) == book_id: self.books.append({ 'mi': mi, 'timestamp': timestamp, 'formats': list(zip(fmts, sizes, names)), 'id': book_id, 'dirpath': dirpath, 'path': path, }) else: self.ignored_dirs.append(dirpath)
def process_dir(self, dirpath, filenames, book_id): formats = filter(self.is_ebook_file, filenames) fmts = [os.path.splitext(x)[1][1:].upper() for x in formats] sizes = [os.path.getsize(os.path.join(dirpath, x)) for x in formats] names = [os.path.splitext(x)[0] for x in formats] opf = os.path.join(dirpath, 'meta...
db = LibraryDatabase2(self.library_path)
db = RestoreDatabase(self.library_path)
def create_cc_metadata(self): self.books.sort(key=itemgetter('timestamp')) m = {} fields = ('label', 'name', 'datatype', 'is_multiple', 'editable', 'display') for b in self.books: args = [] for x in fields: if x in b: args.append(b[x]) if len(args) == len(fields): # TODO: Do series type columns need special handling? l...
if category == 'series':
if category == 'series' and not sort_on_count:
def get_categories(self, sort_on_count=False, ids=None, icon_map=None): self.books_list_filter.change([] if not ids else ids)
occasion = {'import':_on_import, 'preprocess':_on_preprocess,
occasion_plugins = {'import':_on_import, 'preprocess':_on_preprocess,
def _run_filetype_plugins(path_to_file, ft=None, occasion='preprocess'): occasion = {'import':_on_import, 'preprocess':_on_preprocess, 'postprocess':_on_postprocess}[occasion] customization = config['plugin_customization'] if ft is None: ft = os.path.splitext(path_to_file)[-1].lower().replace('.', '') nfp = path_to_fil...
for plugin in occasion.get(ft, []):
for plugin in occasion_plugins.get(ft, []):
def _run_filetype_plugins(path_to_file, ft=None, occasion='preprocess'): occasion = {'import':_on_import, 'preprocess':_on_preprocess, 'postprocess':_on_postprocess}[occasion] customization = config['plugin_customization'] if ft is None: ft = os.path.splitext(path_to_file)[-1].lower().replace('.', '') nfp = path_to_fil...
record.set('title', book.title)
title = book.title if book.title else _('Unknown') record.set('title', title)
def update_text_record(self, record, book, path, bl_index): timestamp = os.path.getctime(path) date = strftime(timestamp) if date != record.get('date', None): if DEBUG: prints('Changing date of', path, 'from', record.get('date', ''), 'to', date) prints('\tctime', strftime(os.path.getctime(path))) prints('\tmtime', strf...
ts = title_sort(book.title)
ts = title_sort(title)
def update_text_record(self, record, book, path, bl_index): timestamp = os.path.getctime(path) date = strftime(timestamp) if date != record.get('date', None): if DEBUG: prints('Changing date of', path, 'from', record.get('date', ''), 'to', date) prints('\tctime', strftime(os.path.getctime(path))) prints('\tmtime', strf...
'state', 'city', 'street', 'address', 'content'): tag.tag = 'div' if tag.tag == 'content' else 'span'
'state', 'city', 'street', 'address', 'content', 'form'): tag.tag = 'div' if tag.tag in ('content', 'form') else 'span'
def upshift_markup(self, root): self.log.debug('Converting style information to CSS...') size_map = { 'xx-small': '0.5', 'x-small': '1', 'small': '2', 'medium': '3', 'large': '4', 'x-large': '5', 'xx-large': '6', } mobi_version = self.book_header.mobi_version for x in root.xpath('//ncx'): x.getparent().remove(x) for i,...
items = [x for x in items if getattr(x, 'sort', x.name).startswith(which)]
def belongs(x, which): return getattr(x, 'sort', x.name).lower().startswith(which.lower()) items = [x for x in items if belongs(x, which)]
def opds_category_group(self, category=None, which=None, version=0, offset=0): try: offset = int(offset) version = int(version) except: raise cherrypy.HTTPError(404, 'Not found')
starts = set([getattr(x, 'sort', x.name)[0] for x in items])
starts = set([]) for x in items: val = getattr(x, 'sort', x.name) if not val: val = 'A' starts.add(val[0].upper())
def __init__(self, text, count): self.text, self.count = text, count
return ''.join(random.choice(string.letters) for i in
return ''.join(random.choice(letters) for i in
def randstr(length): return ''.join(random.choice(string.letters) for i in xrange(length))
val = pat.sub('', val)
val = pat.sub('', val).strip()
def setData(self, index, value, role): if role == Qt.EditRole: row, col = index.row(), index.column() column = self.column_map[col] if column not in self.editable_cols: return False val = int(value.toInt()[0]) if column == 'rating' else \ value.toDate() if column in ('timestamp', 'pubdate') else \ unicode(value.toStrin...