rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
r[abs(float(img['height'])/float(img['width'])-1.25)] = img['src']
|
r[abs(float(re.search(r'[0-9.]+', img['height']).group())/float(re.search(r'[0-9.]+', img['width']).group())-1.25)] = img['src']
|
def _get_cover(soup, rdr): ans = None try: ans = soup.find('img', alt=re.compile('cover', flags=re.I))['src'] except TypeError: # meeehh, no handy alt-tag goodness, try some hackery # the basic idea behind this is that in general, the cover image # has a height:width ratio of ~1.25, whereas most of the nav # buttons are decidedly less than that. # what we do in this is work out that ratio, take 1.25 off it and # save the absolute value when we sort by this value, the smallest # one is most likely to be the cover image, hopefully. r = {} for img in soup('img'): try: r[abs(float(img['height'])/float(img['width'])-1.25)] = img['src'] except KeyError: # interestingly, occasionally the only image without height # or width attrs is the cover... r[0] = img['src'] l = r.keys() l.sort() if l: ans = r[l[0]] # this link comes from the internal html, which is in a subdir if ans is not None: try: ans = rdr.GetFile(ans) except: ans = rdr.root + "/" + ans try: ans = rdr.GetFile(ans) except: ans = None if ans is not None: from PIL import Image from cStringIO import StringIO buf = StringIO() try: Image.open(StringIO(ans)).convert('RGB').save(buf, 'JPEG') ans = buf.getvalue() except: ans = None return ans
|
def get_printer(self):
|
def get_printer(self, set_horz_margins=False):
|
def get_printer(self): printer = get_pdf_printer() printer.setPaperSize(QSizeF(self.size[0] * 10, self.size[1] * 10), QPrinter.Millimeter) printer.setPageMargins(0, 0, 0, 0, QPrinter.Point) printer.setOrientation(orientation(self.opts.orientation)) printer.setOutputFormat(QPrinter.PdfFormat) printer.setFullPage(True) return printer
|
printer.setPageMargins(0, 0, 0, 0, QPrinter.Point)
|
if set_horz_margins: printer.setPageMargins(0., self.opts.margin_top, 0., self.opts.margin_bottom, QPrinter.Point) else: printer.setPageMargins(0, 0, 0, 0, QPrinter.Point)
|
def get_printer(self): printer = get_pdf_printer() printer.setPaperSize(QSizeF(self.size[0] * 10, self.size[1] * 10), QPrinter.Millimeter) printer.setPageMargins(0, 0, 0, 0, QPrinter.Point) printer.setOrientation(orientation(self.opts.orientation)) printer.setOutputFormat(QPrinter.PdfFormat) printer.setFullPage(True) return printer
|
printer.setFullPage(True)
|
printer.setFullPage(not set_horz_margins)
|
def get_printer(self): printer = get_pdf_printer() printer.setPaperSize(QSizeF(self.size[0] * 10, self.size[1] * 10), QPrinter.Millimeter) printer.setPageMargins(0, 0, 0, 0, QPrinter.Point) printer.setOrientation(orientation(self.opts.orientation)) printer.setOutputFormat(QPrinter.PdfFormat) printer.setFullPage(True) return printer
|
printer = self.get_printer()
|
printer = self.get_printer(set_horz_margins=True)
|
def _render_html(self, ok): if ok: item_path = os.path.join(self.tmp_path, '%i.pdf' % len(self.combine_queue)) self.logger.debug('\tRendering item %s as %i' % (os.path.basename(str(self.view.url().toLocalFile())), len(self.combine_queue))) printer = self.get_printer() printer.setOutputFileName(item_path) self.view.print_(printer) self._render_book()
|
set_metadata=True,
|
def sync_to_device(self, on_card, delete_from_library, specific_format=None, send_ids=None, do_auto_convert=True): ids = [self.library_view.model().id(r) \ for r in self.library_view.selectionModel().selectedRows()] \ if send_ids is None else send_ids if not self.device_manager or not ids or len(ids) == 0: return
|
|
self.isbn = book.get('isbn13', book.get('isbn')) self.title = book.find('titlelong').string
|
self.isbn = unicode(book.get('isbn13', book.get('isbn'))) self.title = unicode(book.find('titlelong').string)
|
def __init__(self, book): Metadata.__init__(self, None, [])
|
self.title = book.find('title').string
|
self.title = unicode(book.find('title').string)
|
def __init__(self, book): Metadata.__init__(self, None, [])
|
self.publisher = book.find('publishertext').string
|
self.publisher = unicode(book.find('publishertext').string)
|
def __init__(self, book): Metadata.__init__(self, None, [])
|
self.comments = 'SUMMARY:\n'+summ.string
|
self.comments = 'SUMMARY:\n'+unicode(summ.string)
|
def __init__(self, book): Metadata.__init__(self, None, [])
|
if self.header_record.compression == 2:
|
if self.header_record.compression == 2 or self.header_record.compression == 258:
|
def decompress_text(self, number): if self.header_record.compression == 1: return self.section_data(number).decode('cp1252' if self.encoding is None else self.encoding) if self.header_record.compression == 2: from calibre.ebooks.compression.palmdoc import decompress_doc return decompress_doc(self.section_data(number)).decode('cp1252' if self.encoding is None else self.encoding, 'replace') return ''
|
aTag['name'] = "%s-%s" % (current_date.year, current_date.month)
|
aTag['name'] = "bda_%s-%s" % (current_date.year, current_date.month)
|
def add_books_to_HTML_by_month(this_months_list, dtc): if len(this_months_list):
|
aTag['name'] = date_range.replace(' ','')
|
aTag['name'] = "bda_%s" % date_range.replace(' ','')
|
def add_books_to_HTML_by_date_range(date_range_list, date_range, dtc): if len(date_range_list): pIndexTag = Tag(soup, "p") pIndexTag['class'] = "date_index" aTag = Tag(soup, "a") aTag['name'] = date_range.replace(' ','') pIndexTag.insert(0,aTag) pIndexTag.insert(1,NavigableString(date_range)) divTag.insert(dtc,pIndexTag) dtc += 1
|
navPointByMonthTag['id'] = "%s-%s-ID" % (books_by_month[1].year,books_by_month[1].month )
|
navPointByMonthTag['id'] = "bda_%s-%s-ID" % (books_by_month[1].year,books_by_month[1].month )
|
def add_to_master_date_range_list(current_titles_list): book_count = len(current_titles_list) current_titles_list = " • ".join(current_titles_list) current_titles_list = self.formatNCXText(current_titles_list, dest='description') master_date_range_list.append((current_titles_list, date_range, book_count))
|
elif frag: self.view.scroll_to(frag)
|
else: if frag: self.view.scroll_to(frag) else: self.view.scroll_to('
|
def link_clicked(self, url): path = os.path.abspath(unicode(url.toLocalFile())) frag = None if path in self.iterator.spine: self.history.add(self.pos.value()) path = self.iterator.spine[self.iterator.spine.index(path)] if url.hasFragment(): frag = unicode(url.fragment()) if path != self.current_page: self.pending_anchor = frag self.load_path(path) elif frag: self.view.scroll_to(frag) else: open_url(url)
|
PRODUCT_ID = [0x129a,0x1292]
|
PRODUCT_ID = [0x129a]
|
def __init__(self, msg, details, level): Exception.__init__(self, msg) self.level = level self.details = details self.msg = msg
|
subprocess.check_call(['/usr/bin/hdiutil', 'create', '-srcfolder', os.path.abspath(d),
|
tdir = tempfile.mkdtemp() shutil.copytree(d, os.path.join(tdir, os.path.basename(d)), symlinks=True) os.symlink('/Applications', os.path.join(tdir, 'Applications')) subprocess.check_call(['/usr/bin/hdiutil', 'create', '-srcfolder', tdir,
|
def makedmg(self, d, volname, destdir='dist', internet_enable=True, format='UDBZ'): ''' Copy a directory d into a dmg named volname ''' info('\nCreating dmg') sys.stdout.flush() if not os.path.exists(destdir): os.makedirs(destdir) dmg = os.path.join(destdir, volname+'.dmg') if os.path.exists(dmg): os.unlink(dmg) subprocess.check_call(['/usr/bin/hdiutil', 'create', '-srcfolder', os.path.abspath(d), '-volname', volname, '-format', format, dmg]) if internet_enable: subprocess.check_call(['/usr/bin/hdiutil', 'internet-enable', '-yes', dmg]) size = os.stat(dmg).st_size/(1024*1024.) info('\nInstaller size: %.2fMB\n'%size) return dmg
|
self.qaction.triggered.connect(self.choose_library)
|
self.qaction.triggered.connect(self.choose_library, type=Qt.QueuedConnection)
|
def genesis(self): self.count_changed(0) self.qaction.triggered.connect(self.choose_library)
|
self.action_choose.triggered.connect(self.choose_library)
|
self.action_choose.triggered.connect(self.choose_library, type=Qt.QueuedConnection)
|
def genesis(self): self.count_changed(0) self.qaction.triggered.connect(self.choose_library)
|
ac.triggered.connect(partial(self.qs_requested, i))
|
ac.triggered.connect(partial(self.qs_requested, i), type=Qt.QueuedConnection)
|
def genesis(self): self.count_changed(0) self.qaction.triggered.connect(self.choose_library)
|
self.quick_menu.addAction(name, partial(self.switch_requested, loc))
|
self.quick_menu.addAction(name, Dispatcher(partial(self.switch_requested, loc)))
|
def build_menus(self): db = self.gui.library_view.model().db locations = list(self.stats.locations(db)) for ac in self.switch_actions: ac.setVisible(False) self.quick_menu.clear() self.qs_locations = [i[1] for i in locations] for name, loc in locations: self.quick_menu.addAction(name, partial(self.switch_requested, loc))
|
if not (islinux or isfreebsd):
|
if not self.is_case_sensitive(path):
|
def create_oebbook(self, htmlpath, basedir, opts, log, mi): from calibre.ebooks.conversion.plumber import create_oebbook from calibre.ebooks.oeb.base import DirContainer, \ rewrite_links, urlnormalize, urldefrag, BINARY_MIME, OEB_STYLES, \ xpath from calibre import guess_type import cssutils oeb = create_oebbook(log, None, opts, self, encoding=opts.input_encoding, populate=False) self.oeb = oeb
|
if not (islinux or isfreebsd):
|
if not self.is_case_sensitive(tempfile.gettempdir()):
|
def resource_adder(self, link_, base=None): link = self.urlnormalize(link_) link, frag = self.urldefrag(link) link = unquote(link).replace('/', os.sep) if not link.strip(): return link_ if base and not os.path.isabs(link): link = os.path.join(base, link) try: link = os.path.abspath(link) except: return link_ if not os.access(link, os.R_OK): return link_ if os.path.isdir(link): self.log.warn(link_, 'is a link to a directory. Ignoring.') return link_ if not (islinux or isfreebsd): link = link.lower() if link not in self.added_resources: bhref = os.path.basename(link) id, href = self.oeb.manifest.generate(id='added', href=bhref) self.oeb.log.debug('Added', link) self.oeb.container = self.DirContainer(os.path.dirname(link), self.oeb.log) # Load into memory guessed = self.guess_type(href)[0] media_type = guessed or self.BINARY_MIME
|
QThread.__init__(self, parent)
|
QObject.__init__(self, parent)
|
def __init__(self, parent, db, duplicates, db_adder): QThread.__init__(self, parent) self.db, self.db_adder = db, db_adder self.duplicates = duplicates
|
self.duplicates = duplicates def run(self): count = 1 for mi, cover, formats in self.duplicates: formats = [f for f in formats if not f.lower().endswith('.opf')] id = self.db.create_book_entry(mi, cover=cover, add_duplicates=True) self.db_adder.add_formats(id, formats) self.db_adder.number_of_books_added += 1 self.emit(SIGNAL('added(PyQt_PyObject)'), count) count += 1 self.emit(SIGNAL('adding_done()'))
|
self.duplicates = list(duplicates) self.count = 0 single_shot(self.add_one) def add_one(self): if not self.duplicates: self.adding_done.emit() return mi, cover, formats = self.duplicates.pop() formats = [f for f in formats if not f.lower().endswith('.opf')] id = self.db.create_book_entry(mi, cover=cover, add_duplicates=True) self.db_adder.add_formats(id, formats) self.db_adder.number_of_books_added += 1 self.count += 1 self.added.emit(self.count) single_shot(self.add_one)
|
def __init__(self, parent, db, duplicates, db_adder): QThread.__init__(self, parent) self.db, self.db_adder = db, db_adder self.duplicates = duplicates
|
self.emit(SIGNAL('update(PyQt_PyObject)'), _('Searching in')+' '+dirpath[0])
|
self.update.emit( _('Searching in')+' '+dirpath[0])
|
def walk(self, root): self.books = [] for dirpath in os.walk(root): if self.canceled: return self.emit(SIGNAL('update(PyQt_PyObject)'), _('Searching in')+' '+dirpath[0]) self.books += list(self.db.find_books_in_directory(dirpath[0], self.single_book_per_directory))
|
self.emit(SIGNAL('found(PyQt_PyObject)'), msg)
|
self.found.emit(msg)
|
def run(self): root = os.path.abspath(self.path) try: self.walk(root) except: try: if isinstance(root, unicode): root = root.encode(filesystem_encoding) self.walk(root) except Exception, err: import traceback traceback.print_exc() try: msg = unicode(err) except: msg = repr(err) self.emit(SIGNAL('found(PyQt_PyObject)'), msg) return
|
self.emit(SIGNAL('found(PyQt_PyObject)'), self.books)
|
self.found.emit(self.books)
|
def run(self): root = os.path.abspath(self.path) try: self.walk(root) except: try: if isinstance(root, unicode): root = root.encode(filesystem_encoding) self.walk(root) except Exception, err: import traceback traceback.print_exc() try: msg = unicode(err) except: msg = repr(err) self.emit(SIGNAL('found(PyQt_PyObject)'), msg) return
|
class DBAdder(Thread): def __init__(self, db, ids, nmap):
|
class DBAdder(QObject): def __init__(self, parent, db, ids, nmap): QObject.__init__(self, parent)
|
def run(self): root = os.path.abspath(self.path) try: self.walk(root) except: try: if isinstance(root, unicode): root = root.encode(filesystem_encoding) self.walk(root) except Exception, err: import traceback traceback.print_exc() try: msg = unicode(err) except: msg = repr(err) self.emit(SIGNAL('found(PyQt_PyObject)'), msg) return
|
self.end = False
|
def __init__(self, db, ids, nmap): self.db, self.ids, self.nmap = db, dict(**ids), dict(**nmap) self.end = False self.critical = {} self.number_of_books_added = 0 self.duplicates = [] self.names, self.paths, self.infos = [], [], [] Thread.__init__(self) self.daemon = True self.input_queue = Queue() self.output_queue = Queue() self.merged_books = set([])
|
|
Thread.__init__(self) self.daemon = True
|
def __init__(self, db, ids, nmap): self.db, self.ids, self.nmap = db, dict(**ids), dict(**nmap) self.end = False self.critical = {} self.number_of_books_added = 0 self.duplicates = [] self.names, self.paths, self.infos = [], [], [] Thread.__init__(self) self.daemon = True self.input_queue = Queue() self.output_queue = Queue() self.merged_books = set([])
|
|
def run(self): while not self.end: try: id, opf, cover = self.input_queue.get(True, 0.2) except Empty: continue name = self.nmap.pop(id) title = None try: title = self.add(id, opf, cover, name) except: import traceback self.critical[name] = traceback.format_exc() title = name self.output_queue.put(title)
|
def end(self): self.input_queue.put((None, None, None)) def start(self): try: id, opf, cover = self.input_queue.get_nowait() except Empty: single_shot(self.start) return if id is None and opf is None and cover is None: return name = self.nmap.pop(id) title = None if DEBUG: st = time.time() try: title = self.add(id, opf, cover, name) except: import traceback self.critical[name] = traceback.format_exc() title = name self.output_queue.put(title) if DEBUG: prints('Added', title, 'to db in:', time.time() - st, 'seconds') single_shot(self.start)
|
def run(self): while not self.end: try: id, opf, cover = self.input_queue.get(True, 0.2) except Empty: continue name = self.nmap.pop(id) title = None try: title = self.add(id, opf, cover, name) except: import traceback self.critical[name] = traceback.format_exc() title = name self.output_queue.put(title)
|
self.rfind = self.worker = self.timer = None
|
self.rfind = self.worker = None
|
def __init__(self, parent, db, callback, spare_server=None): QObject.__init__(self, parent) self.pd = ProgressDialog(_('Adding...'), parent=parent) self.spare_server = spare_server self.db = db self.pd.setModal(True) self.pd.show() self._parent = parent self.rfind = self.worker = self.timer = None self.callback = callback self.callback_called = False self.connect(self.pd, SIGNAL('canceled()'), self.canceled)
|
self.connect(self.pd, SIGNAL('canceled()'), self.canceled)
|
self.pd.canceled_signal.connect(self.canceled)
|
def __init__(self, parent, db, callback, spare_server=None): QObject.__init__(self, parent) self.pd = ProgressDialog(_('Adding...'), parent=parent) self.spare_server = spare_server self.db = db self.pd.setModal(True) self.pd.show() self._parent = parent self.rfind = self.worker = self.timer = None self.callback = callback self.callback_called = False self.connect(self.pd, SIGNAL('canceled()'), self.canceled)
|
self.connect(self.rfind, SIGNAL('update(PyQt_PyObject)'), self.pd.set_msg, Qt.QueuedConnection) self.connect(self.rfind, SIGNAL('found(PyQt_PyObject)'), self.add, Qt.QueuedConnection)
|
self.rfind.update.connect(self.pd.set_msg, type=Qt.QueuedConnection) self.rfind.found.connect(self.add, type=Qt.QueuedConnection)
|
def add_recursive(self, root, single=True): self.path = root self.pd.set_msg(_('Searching in all sub-directories...')) self.pd.set_min(0) self.pd.set_max(0) self.pd.value = 0 self.rfind = RecursiveFind(self, self.db, root, single) self.connect(self.rfind, SIGNAL('update(PyQt_PyObject)'), self.pd.set_msg, Qt.QueuedConnection) self.connect(self.rfind, SIGNAL('found(PyQt_PyObject)'), self.add, Qt.QueuedConnection) self.rfind.start()
|
self.db_adder = DBAdder(self.db, self.ids, self.nmap)
|
self.db_adder = DBAdder(self, self.db, self.ids, self.nmap)
|
def add(self, books): if isinstance(books, basestring): error_dialog(self.pd, _('Path error'), _('The specified directory could not be processed.'), det_msg=books, show=True) return self.canceled() if not books: info_dialog(self.pd, _('No books'), _('No books found'), show=True) return self.canceled() books = [[b] if isinstance(b, basestring) else b for b in books] self.rfind = None from calibre.ebooks.metadata.worker import read_metadata self.rq = Queue() tasks = [] self.ids = {} self.nmap = {} self.duplicates = [] for i, b in enumerate(books): tasks.append((i, b)) self.ids[i] = b self.nmap[i] = os.path.basename(b[0]) self.worker = read_metadata(tasks, self.rq, spare_server=self.spare_server) self.pd.set_min(0) self.pd.set_max(len(self.ids)) self.pd.value = 0 self.db_adder = DBAdder(self.db, self.ids, self.nmap) self.db_adder.start() self.last_added_at = time.time() self.entry_count = len(self.ids) self.continue_updating = True QTimer.singleShot(200, self.update)
|
QTimer.singleShot(200, self.update)
|
single_shot(self.update)
|
def add(self, books): if isinstance(books, basestring): error_dialog(self.pd, _('Path error'), _('The specified directory could not be processed.'), det_msg=books, show=True) return self.canceled() if not books: info_dialog(self.pd, _('No books'), _('No books found'), show=True) return self.canceled() books = [[b] if isinstance(b, basestring) else b for b in books] self.rfind = None from calibre.ebooks.metadata.worker import read_metadata self.rq = Queue() tasks = [] self.ids = {} self.nmap = {} self.duplicates = [] for i, b in enumerate(books): tasks.append((i, b)) self.ids[i] = b self.nmap[i] = os.path.basename(b[0]) self.worker = read_metadata(tasks, self.rq, spare_server=self.spare_server) self.pd.set_min(0) self.pd.set_max(len(self.ids)) self.pd.value = 0 self.db_adder = DBAdder(self.db, self.ids, self.nmap) self.db_adder.start() self.last_added_at = time.time() self.entry_count = len(self.ids) self.continue_updating = True QTimer.singleShot(200, self.update)
|
self.db_adder.end = True
|
self.db_adder.end()
|
def canceled(self): self.continue_updating = False if self.rfind is not None: self.rfind.canceled = True if self.worker is not None: self.worker.canceled = True if hasattr(self, 'db_adder'): self.db_adder.end = True self.pd.hide() if not self.callback_called: self.callback(self.paths, self.names, self.infos) self.callback_called = True
|
self.db_adder.end = True
|
self.db_adder.end()
|
def duplicates_processed(self): self.db_adder.end = True if not self.callback_called: self.callback(self.paths, self.names, self.infos) self.callback_called = True if hasattr(self, '__p_d'): self.__p_d.hide()
|
self.db_adder.end = True
|
self.db_adder.end()
|
def update(self): if self.entry_count <= 0: self.continue_updating = False self.pd.hide() self.process_duplicates() return
|
QTimer.singleShot(200, self.update)
|
single_shot(self.update)
|
def update(self): if self.entry_count <= 0: self.continue_updating = False self.pd.hide() self.process_duplicates() return
|
self.connect(self.__d_a, SIGNAL('added(PyQt_PyObject)'), pd.setValue) self.connect(self.__d_a, SIGNAL('adding_done()'), self.duplicates_processed) self.__d_a.start()
|
self.__d_a.added.connect(pd.setValue) self.__d_a.adding_done.connect(self.duplicates_processed)
|
def process_duplicates(self): duplicates = self.db_adder.duplicates if not duplicates: return self.duplicates_processed() self.pd.hide() files = [x[0].title for x in duplicates] if question_dialog(self._parent, _('Duplicates found!'), _('Books with the same title as the following already ' 'exist in the database. Add them anyway?'), '\n'.join(files)): pd = QProgressDialog(_('Adding duplicates...'), '', 0, len(duplicates), self._parent) pd.setCancelButton(None) pd.setValue(0) pd.show() self.__p_d = pd self.__d_a = DuplicatesAdder(self._parent, self.db, duplicates, self.db_adder) self.connect(self.__d_a, SIGNAL('added(PyQt_PyObject)'), pd.setValue) self.connect(self.__d_a, SIGNAL('adding_done()'), self.duplicates_processed) self.__d_a.start() else: return self.duplicates_processed()
|
self.timer = QTimer(self) self.connect(self.timer, SIGNAL('timeout()'), self.update) self.timer.start(200)
|
self.continue_updating = True single_shot(self.update)
|
def __init__(self, parent, db, callback, rows, path, opts, spare_server=None): QObject.__init__(self, parent) self.pd = ProgressDialog(_('Saving...'), parent=parent) self.spare_server = spare_server self.db = db self.opts = opts self.pd.setModal(True) self.pd.show() self.pd.set_min(0) self._parent = parent self.callback = callback self.callback_called = False self.rq = Queue() self.ids = [x for x in map(db.id, [r.row() for r in rows]) if x is not None] self.pd.set_max(len(self.ids)) self.pd.value = 0 self.failures = set([])
|
if self.timer is not None: self.timer.stop()
|
self.continue_updating = False
|
def canceled(self): if self.timer is not None: self.timer.stop() if self.worker is not None: self.worker.canceled = True self.pd.hide() if not self.callback_called: self.callback(self.worker.path, self.failures, self.worker.error) self.callback_called = True
|
if not self.ids or not self.worker.is_alive(): self.timer.stop() self.pd.hide()
|
if not self.continue_updating: return if not self.worker.is_alive():
|
def update(self): if not self.ids or not self.worker.is_alive(): self.timer.stop() self.pd.hide() while self.ids: before = len(self.ids) self.get_result() if before == len(self.ids): for i in list(self.ids): self.failures.add(('id:%d'%i, 'Unknown error')) self.ids.remove(i) break if not self.callback_called: try: self.worker.join(1.5) except: pass # The worker was not yet started self.callback(self.worker.path, self.failures, self.worker.error) self.callback_called = True return
|
break
|
if not self.ids: self.continue_updating = False self.pd.hide()
|
def update(self): if not self.ids or not self.worker.is_alive(): self.timer.stop() self.pd.hide() while self.ids: before = len(self.ids) self.get_result() if before == len(self.ids): for i in list(self.ids): self.failures.add(('id:%d'%i, 'Unknown error')) self.ids.remove(i) break if not self.callback_called: try: self.worker.join(1.5) except: pass # The worker was not yet started self.callback(self.worker.path, self.failures, self.worker.error) self.callback_called = True return
|
self.worker.join(1.5)
|
self.worker.join(2)
|
def update(self): if not self.ids or not self.worker.is_alive(): self.timer.stop() self.pd.hide() while self.ids: before = len(self.ids) self.get_result() if before == len(self.ids): for i in list(self.ids): self.failures.add(('id:%d'%i, 'Unknown error')) self.ids.remove(i) break if not self.callback_called: try: self.worker.join(1.5) except: pass # The worker was not yet started self.callback(self.worker.path, self.failures, self.worker.error) self.callback_called = True return
|
self.callback_called = True return self.get_result()
|
if self.continue_updating: self.get_result() single_shot(self.update)
|
def update(self): if not self.ids or not self.worker.is_alive(): self.timer.stop() self.pd.hide() while self.ids: before = len(self.ids) self.get_result() if before == len(self.ids): for i in list(self.ids): self.failures.add(('id:%d'%i, 'Unknown error')) self.ids.remove(i) break if not self.callback_called: try: self.worker.join(1.5) except: pass # The worker was not yet started self.callback(self.worker.path, self.failures, self.worker.error) self.callback_called = True return
|
pml_img = os.path.basename(pmlfile)[0] + '_img' img_dir = pml_img if os.path.exists(pml_img) else 'images' if \ os.path.exists('images') else ''
|
pml_img = os.path.splitext(pmlfile)[0] + '_img' i_img = os.path.join(os.path.dirname(pmlfile),'images') img_dir = pml_img if os.path.isdir(pml_img) else i_img if \ os.path.isdir(i_img) else ''
|
def run(self, pmlfile): import zipfile
|
f.fileName = fileName
|
f.fileName = fileName.replace(os.sep, '/')
|
def AppendPlain(self, fileName, tdir): f = FileStream() f.attr = 0x41000000 f.fileSize = os.path.getsize(os.path.join(tdir,fileName)) f.fileBody = open(os.path.join(tdir,fileName), 'rb').read() f.fileName = fileName print f.fileSize self.files.append(f)
|
f.fileName = fileName
|
f.fileName = fileName.replace(os.sep, '/')
|
def AppendBinary(self, fileName, tdir): f = FileStream() f.attr = 0x01000000 f.fileSize = os.path.getsize(os.path.join(tdir,fileName)) f.fileBody = open(os.path.join(tdir,fileName), 'rb').read() f.fileName = fileName print f.fileSize self.files.append(f)
|
lb_added.artist.set(metadata.authors[0])
|
def _update_iTunes_metadata(self, metadata, db_added, lb_added, this_book): ''' ''' if DEBUG: self.log.info(" ITUNES._update_iTunes_metadata()")
|
|
db_added.artist.set(metadata.authors[0])
|
def _update_iTunes_metadata(self, metadata, db_added, lb_added, this_book): ''' ''' if DEBUG: self.log.info(" ITUNES._update_iTunes_metadata()")
|
|
lb_added.Artist = metadata.authors[0]
|
def _update_iTunes_metadata(self, metadata, db_added, lb_added, this_book): ''' ''' if DEBUG: self.log.info(" ITUNES._update_iTunes_metadata()")
|
|
db_added.Artist = metadata.authors[0]
|
def _update_iTunes_metadata(self, metadata, db_added, lb_added, this_book): ''' ''' if DEBUG: self.log.info(" ITUNES._update_iTunes_metadata()")
|
|
debug_print('Timezone votes: %d GMT, %d LTZ, use_tz_var='%
|
debug_print('Timezone votes: %d GMT, %d LTZ, use_tz_var= %d'%
|
def update(self, booklists, collections_attributes): debug_print('Starting update', collections_attributes) for i, booklist in booklists.items(): playlist_map = self.build_id_playlist_map(i) debug_print('Updating XML Cache:', i) root = self.record_roots[i] lpath_map = self.build_lpath_map(root) gtz_count = ltz_count = 0 use_tz_var = False for book in booklist: path = os.path.join(self.prefixes[i], *(book.lpath.split('/'))) record = lpath_map.get(book.lpath, None) if record is None: record = self.create_text_record(root, i, book.lpath) (gtz_count, ltz_count, use_tz_var) = \ self.update_text_record(record, book, path, i, gtz_count, ltz_count, use_tz_var) # Ensure the collections in the XML database are recorded for # this book if book.device_collections is None: book.device_collections = [] book.device_collections = playlist_map.get(book.lpath, []) debug_print('Timezone votes: %d GMT, %d LTZ, use_tz_var='% (gtz_count, ltz_count, use_tz_var)) self.update_playlists(i, root, booklist, collections_attributes) # Update the device collections because update playlist could have added # some new ones. debug_print('In update/ Starting refresh of device_collections') for i, booklist in booklists.items(): playlist_map = self.build_id_playlist_map(i) for book in booklist: book.device_collections = playlist_map.get(book.lpath, []) self.fix_ids() debug_print('Finished update')
|
set_metadata=False)
|
set_metadata=False, set_social_metadata=False)
|
def __init__(self, listener, opts, actions, parent=None): self.preferences_action, self.quit_action = actions self.spare_servers = [] MainWindow.__init__(self, opts, parent) # Initialize fontconfig in a separate thread as this can be a lengthy # process if run for the first time on this machine from calibre.utils.fonts import fontconfig self.fc = fontconfig self.listener = Listener(listener) self.check_messages_timer = QTimer() self.connect(self.check_messages_timer, SIGNAL('timeout()'), self.another_instance_wants_to_talk) self.check_messages_timer.start(1000)
|
elif datatype == 'float' and key.endswith('_index'): res = self.format_series_index(res)
|
def format_field_extended(self, key, series_with_index=True): from calibre.ebooks.metadata import authors_to_string ''' returns the tuple (field_name, formatted_value) ''' if key in self.custom_field_keys(): res = self.get(key, None) cmeta = self.get_user_metadata(key, make_copy=False) name = unicode(cmeta['name']) if cmeta['datatype'] != 'composite' and (res is None or res == ''): return (name, res, None, None) orig_res = res cmeta = self.get_user_metadata(key, make_copy=False) if res is None or res == '': return (name, res, None, None) orig_res = res datatype = cmeta['datatype'] if datatype == 'text' and cmeta['is_multiple']: res = u', '.join(res) elif datatype == 'series' and series_with_index: res = res + \ ' [%s]'%self.format_series_index(val=self.get_extra(key)) elif datatype == 'datetime': res = format_date(res, cmeta['display'].get('date_format','dd MMM yyyy')) elif datatype == 'bool': res = _('Yes') if res else _('No') elif datatype == 'float' and key.endswith('_index'): res = self.format_series_index(res) return (name, unicode(res), orig_res, cmeta)
|
|
lpath = self.normalize_path(prefix + lpath)
|
def add_books_to_metadata(self, locations, metadata, booklists): metadata = iter(metadata) for i, location in enumerate(locations): self.report_progress((i+1) / float(len(locations)), _('Adding books to device metadata listing...')) info = metadata.next() blist = 2 if location[1] == 'cardb' else 1 if location[1] == 'carda' else 0
|
|
outfile.write('%s\n' % ','.join(fields))
|
outfile.write(u'%s\n' % u','.join(fields))
|
def run(self, path_to_output, opts, db): from calibre.utils.logging import Log
|
outstr += '"%s",' % str(item).replace('"','""')
|
outstr += u'"%s",' % unicode(item).replace('"','""')
|
def run(self, path_to_output, opts, db): from calibre.utils.logging import Log
|
outstr += '"%s"\n' % str(item).replace('"','""')
|
outstr += u'"%s"\n' % unicode(item).replace('"','""')
|
def run(self, path_to_output, opts, db): from calibre.utils.logging import Log
|
outfile.write(outstr)
|
outfile.write(outstr.encode('utf-8'))
|
def run(self, path_to_output, opts, db): from calibre.utils.logging import Log
|
self.number_of_books_added += 1
|
def add(self, id, opf, cover, name): formats = self.ids.pop(id) if opf.endswith('.error'): mi = MetaInformation('', [_('Unknown')]) self.critical[name] = open(opf, 'rb').read().decode('utf-8', 'replace') else: try: mi = MetaInformation(OPF(opf)) except: import traceback mi = MetaInformation('', [_('Unknown')]) self.critical[name] = traceback.format_exc() formats = self.process_formats(opf, formats) if not mi.title: mi.title = os.path.splitext(name)[0] mi.title = mi.title if isinstance(mi.title, unicode) else \ mi.title.decode(preferred_encoding, 'replace') if self.db is not None: if cover: cover = open(cover, 'rb').read() orig_formats = formats formats = [f for f in formats if not f.lower().endswith('.opf')] if prefs['add_formats_to_existing']: identical_book_list = self.find_identical_books(mi)
|
|
except TypeError:
|
except:
|
def add_book(self, mi, name, size, ctime): """ Add a node into DOM tree representing a book """ book = self.book_by_path(name) if book is not None: self.remove_book(name) node = self.document.createElement(self.prefix + "text") mime = MIME_MAP[name[name.rfind(".")+1:].lower()] cid = self.max_id()+1 sourceid = str(self[0].sourceid) if len(self) else "1" attrs = { "title" : mi.title, 'titleSorter' : sortable_title(mi.title), "author" : mi.format_authors() if mi.format_authors() else _('Unknown'), "page":"0", "part":"0", "scale":"0", \ "sourceid":sourceid, "id":str(cid), "date":"", \ "mime":mime, "path":name, "size":str(size) } for attr in attrs.keys(): node.setAttributeNode(self.document.createAttribute(attr)) node.setAttribute(attr, attrs[attr]) try: w, h, data = mi.thumbnail except TypeError: w, h, data = None, None, None
|
self.timer = QTimer(self)
|
def add(self, books): if isinstance(books, basestring): error_dialog(self.pd, _('Path error'), _('The specified directory could not be processed.'), det_msg=books, show=True) return self.canceled() if not books: info_dialog(self.pd, _('No books'), _('No books found'), show=True) return self.canceled() books = [[b] if isinstance(b, basestring) else b for b in books] self.rfind = None from calibre.ebooks.metadata.worker import read_metadata self.rq = Queue() tasks = [] self.ids = {} self.nmap = {} self.duplicates = [] for i, b in enumerate(books): tasks.append((i, b)) self.ids[i] = b self.nmap[i] = os.path.basename(b[0]) self.worker = read_metadata(tasks, self.rq, spare_server=self.spare_server) self.pd.set_min(0) self.pd.set_max(len(self.ids)) self.pd.value = 0 self.timer = QTimer(self) self.db_adder = DBAdder(self.db, self.ids, self.nmap) self.db_adder.start() self.connect(self.timer, SIGNAL('timeout()'), self.update) self.last_added_at = time.time() self.entry_count = len(self.ids) self.timer.start(200)
|
|
self.connect(self.timer, SIGNAL('timeout()'), self.update)
|
def add(self, books): if isinstance(books, basestring): error_dialog(self.pd, _('Path error'), _('The specified directory could not be processed.'), det_msg=books, show=True) return self.canceled() if not books: info_dialog(self.pd, _('No books'), _('No books found'), show=True) return self.canceled() books = [[b] if isinstance(b, basestring) else b for b in books] self.rfind = None from calibre.ebooks.metadata.worker import read_metadata self.rq = Queue() tasks = [] self.ids = {} self.nmap = {} self.duplicates = [] for i, b in enumerate(books): tasks.append((i, b)) self.ids[i] = b self.nmap[i] = os.path.basename(b[0]) self.worker = read_metadata(tasks, self.rq, spare_server=self.spare_server) self.pd.set_min(0) self.pd.set_max(len(self.ids)) self.pd.value = 0 self.timer = QTimer(self) self.db_adder = DBAdder(self.db, self.ids, self.nmap) self.db_adder.start() self.connect(self.timer, SIGNAL('timeout()'), self.update) self.last_added_at = time.time() self.entry_count = len(self.ids) self.timer.start(200)
|
|
self.timer.start(200)
|
self.continue_updating = True QTimer.singleShot(200, self.update)
|
def add(self, books): if isinstance(books, basestring): error_dialog(self.pd, _('Path error'), _('The specified directory could not be processed.'), det_msg=books, show=True) return self.canceled() if not books: info_dialog(self.pd, _('No books'), _('No books found'), show=True) return self.canceled() books = [[b] if isinstance(b, basestring) else b for b in books] self.rfind = None from calibre.ebooks.metadata.worker import read_metadata self.rq = Queue() tasks = [] self.ids = {} self.nmap = {} self.duplicates = [] for i, b in enumerate(books): tasks.append((i, b)) self.ids[i] = b self.nmap[i] = os.path.basename(b[0]) self.worker = read_metadata(tasks, self.rq, spare_server=self.spare_server) self.pd.set_min(0) self.pd.set_max(len(self.ids)) self.pd.value = 0 self.timer = QTimer(self) self.db_adder = DBAdder(self.db, self.ids, self.nmap) self.db_adder.start() self.connect(self.timer, SIGNAL('timeout()'), self.update) self.last_added_at = time.time() self.entry_count = len(self.ids) self.timer.start(200)
|
if self.timer is not None: self.timer.stop()
|
def canceled(self): if self.rfind is not None: self.rfind.canceled = True if self.timer is not None: self.timer.stop() if self.worker is not None: self.worker.canceled = True if hasattr(self, 'db_adder'): self.db_adder.end = True self.pd.hide() if not self.callback_called: self.callback(self.paths, self.names, self.infos) self.callback_called = True
|
|
self.timer.stop()
|
self.continue_updating = False
|
def update(self): if self.entry_count <= 0: self.timer.stop() self.pd.hide() self.process_duplicates() return
|
try: row = self.db.row(id) except: row = -1 if row > -1: self.beginRemoveRows(QModelIndex(), row, row)
|
def delete_books_by_id(self, ids): for id in ids: try: row = self.db.row(id) except: row = -1 if row > -1: self.beginRemoveRows(QModelIndex(), row, row) self.db.delete_book(id) if row > -1: self.endRemoveRows() self.count_changed() self.clear_caches()
|
|
if row > -1: self.endRemoveRows()
|
def delete_books_by_id(self, ids): for id in ids: try: row = self.db.row(id) except: row = -1 if row > -1: self.beginRemoveRows(QModelIndex(), row, row) self.db.delete_book(id) if row > -1: self.endRemoveRows() self.count_changed() self.clear_caches()
|
|
if self.revA3 != SNBFile.REVA3: return False
|
def IsValid(self): if self.magic != SNBFile.MAGIC: return False if self.rev80 != SNBFile.REV80: return False if self.revA3 != SNBFile.REVA3: return False if self.revZ1 != SNBFile.REVZ1: return False if self.revZ2 != SNBFile.REVZ2: return False if self.vfatSize != len(self.vfat): return False if self.fileCount != len(self.files): return False if (self.binBlock + self.plainBlock) * 4 + self.fileCount * 8 != self.tailSizeUncompressed: return False if self.tailMagic != SNBFile.MAGIC: print self.tailMagic return False return True
|
|
json.dump(js, f, indent=2, encoding='utf-8')
|
f.write(json.dumps(js, indent=2, encoding='utf-8'))
|
def write_prefix(prefix, listid): if prefix is not None and isinstance(booklists[listid], self.booklist_class): if not os.path.exists(prefix): os.makedirs(self.normalize_path(prefix)) js = [item.to_json() for item in booklists[listid] if hasattr(item, 'to_json')] with open(self.normalize_path(os.path.join(prefix, self.METADATA_CACHE)), 'wb') as f: json.dump(js, f, indent=2, encoding='utf-8')
|
view.setCurrentIndex(ci) sm = view.selectionModel() sm.select(ci, sm.Select)
|
view.set_current_row(row)
|
def delete_books(self, *args): ''' Delete selected books from device or library. ''' view = self.current_view() rows = view.selectionModel().selectedRows() if not rows or len(rows) == 0: return if self.stack.currentIndex() == 0: if not confirm('<p>'+_('The selected books will be ' '<b>permanently deleted</b> and the files ' 'removed from your computer. Are you sure?') +'</p>', 'library_delete_books', self): return ci = view.currentIndex() row = None if ci.isValid(): row = ci.row() ids_deleted = view.model().delete_books(rows) for v in (self.memory_view, self.card_a_view, self.card_b_view): if v is None: continue v.model().clear_ondevice(ids_deleted) if row is not None: ci = view.model().index(row, 0) if ci.isValid(): view.setCurrentIndex(ci) sm = view.selectionModel() sm.select(ci, sm.Select) else: if not confirm('<p>'+_('The selected books will be ' '<b>permanently deleted</b> ' 'from your device. Are you sure?') +'</p>', 'device_delete_books', self): return if self.stack.currentIndex() == 1: view = self.memory_view elif self.stack.currentIndex() == 2: view = self.card_a_view else: view = self.card_b_view paths = view.model().paths(rows) job = self.remove_paths(paths) self.delete_memory[job] = (paths, view.model()) view.model().mark_for_deletion(job, rows) self.status_bar.show_message(_('Deleting books from device.'), 1000)
|
Metadata.__init__(self, None, [])
|
Metadata.__init__(self, None)
|
def __init__(self, book): Metadata.__init__(self, None, [])
|
self.title = tostring(book.find('titlelong')) if not self.title: self.title = tostring(book.find('title')) if not self.title: self.title = _('Unknown')
|
title = tostring(book.find('titlelong')) if not title: title = tostring(book.find('title')) self.title = title
|
def tostring(e): if not hasattr(e, 'string'): return None ans = e.string if ans is not None: ans = unicode(ans).strip() if not ans: ans = None return ans
|
self.authors = []
|
authors = []
|
def tostring(e): if not hasattr(e, 'string'): return None ans = e.string if ans is not None: ans = unicode(ans).strip() if not ans: ans = None return ans
|
self.authors.extend([a.strip() for a in au.split('&')])
|
authors.extend([a.strip() for a in au.split('&')]) if authors: self.authors = authors
|
def tostring(e): if not hasattr(e, 'string'): return None ans = e.string if ans is not None: ans = unicode(ans).strip() if not ans: ans = None return ans
|
self.fp.write(struct.pack("<lLL", zinfo.CRC, zinfo.compress_size,
|
self.fp.write(struct.pack("<LLL", zinfo.CRC, zinfo.compress_size,
|
def writestr(self, zinfo_or_arcname, bytes, permissions=0600, compression=ZIP_DEFLATED, raw_bytes=False): """Write a file into the archive. The contents is the string 'bytes'. 'zinfo_or_arcname' is either a ZipInfo instance or the name of the file in the archive.""" assert not raw_bytes or (raw_bytes and isinstance(zinfo_or_arcname, ZipInfo)) if not isinstance(zinfo_or_arcname, ZipInfo): if not isinstance(zinfo_or_arcname, unicode): zinfo_or_arcname = zinfo_or_arcname.decode(filesystem_encoding) zinfo = ZipInfo(filename=zinfo_or_arcname, date_time=time.localtime(time.time())[:6]) zinfo.compress_type = compression zinfo.external_attr = permissions << 16 else: zinfo = zinfo_or_arcname
|
ans = self.javascript('document.body.offsetHeight', 'int') if ans == 0: ans = self.mainFrame().contentsSize().height() return ans
|
j = self.javascript('document.body.offsetHeight', 'int') q = self.mainFrame().contentsSize().height() if q == j: return j if min(j, q) <= 0: return max(j, q) window_height = self.window_height if j == window_height: return j if q < 1.2*j else q return j
|
def height(self): ans = self.javascript('document.body.offsetHeight', 'int') # contentsSize gives inaccurate results if ans == 0: ans = self.mainFrame().contentsSize().height() return ans
|
body = self.mainFrame().documentElement().findFirst('body') if body.isNull(): return old_padding = unicode(body.styleProperty('padding-bottom', body.ComputedStyle)).strip() padding = u'%dpx'%amount if old_padding != padding: body.setStyleProperty('padding-bottom', padding + ' !important')
|
s = QSize(-1, -1) if amount == 0 else QSize(self.width, self.height+amount) self.setPreferredContentsSize(s)
|
def set_bottom_padding(self, amount): body = self.mainFrame().documentElement().findFirst('body') if body.isNull(): return old_padding = unicode(body.styleProperty('padding-bottom', body.ComputedStyle)).strip() padding = u'%dpx'%amount if old_padding != padding: body.setStyleProperty('padding-bottom', padding + ' !important')
|
if self.document.at_bottom:
|
if self.document.at_bottom or ddelta <= 0:
|
def next_page(self): window_height = self.document.window_height delta_y = window_height - 25 if self.document.at_bottom: if self.manager is not None: self.manager.next_document() else: oopos = self.document.ypos #print '\nOriginal position:', oopos self.document.set_bottom_padding(0) opos = self.document.ypos #print 'After set padding=0:', self.document.ypos if opos < oopos: if self.manager is not None: self.manager.next_document() return lower_limit = opos + delta_y # Max value of top y co-ord after scrolling max_y = self.document.height - window_height # The maximum possible top y co-ord if max_y < lower_limit: #print 'Setting padding to:', lower_limit - max_y self.document.set_bottom_padding(lower_limit - max_y) max_y = self.document.height - window_height lower_limit = min(max_y, lower_limit) #print 'Scroll to:', lower_limit if lower_limit > opos: self.document.scroll_to(self.document.xpos, lower_limit) actually_scrolled = self.document.ypos - opos #print 'After scroll pos:', self.document.ypos self.find_next_blank_line(window_height - actually_scrolled) #print 'After blank line pos:', self.document.ypos if self.manager is not None: self.manager.scrolled(self.scroll_fraction) #print 'After all:', self.document.ypos
|
self._is_case_sensitive = os.path.exists(path.lower()) \ and os.path.exists(path.upper())
|
self._is_case_sensitive = not (os.path.exists(path.lower()) \ and os.path.exists(path.upper()))
|
def is_case_sensitive(self, path): if getattr(self, '_is_case_sensitive', None) is not None: return self._is_case_sensitive if not path or not os.path.exists(path): return islinux or isfreebsd self._is_case_sensitive = os.path.exists(path.lower()) \ and os.path.exists(path.upper()) return self._is_case_sensitive
|
collections_lpaths = {}
|
def get_collections(self, collection_attributes): from calibre.devices.usbms.driver import debug_print debug_print('Starting get_collections:', prefs['manage_device_metadata']) debug_print('Renaming rules:', tweaks['sony_collection_renaming_rules'])
|
|
collections[cat_name] = [] collections_lpaths[cat_name] = set() if lpath in collections_lpaths[cat_name]: continue collections_lpaths[cat_name].add(lpath)
|
collections[cat_name] = {}
|
def get_collections(self, collection_attributes): from calibre.devices.usbms.driver import debug_print debug_print('Starting get_collections:', prefs['manage_device_metadata']) debug_print('Renaming rules:', tweaks['sony_collection_renaming_rules'])
|
collections[cat_name].append( (book, book.get(attr+'_index', sys.maxint)))
|
if doing_dc: collections[cat_name][lpath] = \ (book, book.get('series_index', sys.maxint)) else: collections[cat_name][lpath] = \ (book, book.get(attr+'_index', sys.maxint))
|
def get_collections(self, collection_attributes): from calibre.devices.usbms.driver import debug_print debug_print('Starting get_collections:', prefs['manage_device_metadata']) debug_print('Renaming rules:', tweaks['sony_collection_renaming_rules'])
|
collections[cat_name].append( (book, book.get('title_sort', 'zzzz')))
|
if lpath not in collections[cat_name]: collections[cat_name][lpath] = \ (book, book.get('title_sort', 'zzzz'))
|
def get_collections(self, collection_attributes): from calibre.devices.usbms.driver import debug_print debug_print('Starting get_collections:', prefs['manage_device_metadata']) debug_print('Renaming rules:', tweaks['sony_collection_renaming_rules'])
|
for category, books in collections.items():
|
for category, lpaths in collections.items(): books = lpaths.values()
|
def get_collections(self, collection_attributes): from calibre.devices.usbms.driver import debug_print debug_print('Starting get_collections:', prefs['manage_device_metadata']) debug_print('Renaming rules:', tweaks['sony_collection_renaming_rules'])
|
if ImageID != None:
|
if ImageID == None:
|
def delete_via_sql(self, ContentID, ContentType): # Delete Order: # 1) shortcover_page # 2) volume_shorcover # 2) content
|
f.write("<HTML><HEAD></HEAD><BODY>\r\n")
|
f.write('<html><head><meta http-equiv="Content-type"' ' content="text/html;charset=UTF-8" /></head><body>\n')
|
def _create_html_root(self, hhcpath, log): hhcdata = self._read_file(hhcpath) hhcroot = html.fromstring(hhcdata) chapters = self._process_nodes(hhcroot) #print "=============================" #print "Printing hhcroot" #print etree.tostring(hhcroot, pretty_print=True) #print "=============================" log.debug('Found %d section nodes' % len(chapters)) htmlpath = os.path.splitext(hhcpath)[0] + ".html" f = open(htmlpath, 'wb') f.write("<HTML><HEAD></HEAD><BODY>\r\n")
|
url = "<br /><a href=" + rsrcpath + ">" + title + " </a>\r\n"
|
url = "<br /><a href=" + rsrcpath + ">" + title + " </a>\n" if isinstance(url, unicode): url = url.encode('utf-8')
|
def _create_html_root(self, hhcpath, log): hhcdata = self._read_file(hhcpath) hhcroot = html.fromstring(hhcdata) chapters = self._process_nodes(hhcroot) #print "=============================" #print "Printing hhcroot" #print etree.tostring(hhcroot, pretty_print=True) #print "=============================" log.debug('Found %d section nodes' % len(chapters)) htmlpath = os.path.splitext(hhcpath)[0] + ".html" f = open(htmlpath, 'wb') f.write("<HTML><HEAD></HEAD><BODY>\r\n")
|
f.write("</BODY></HTML>")
|
f.write("</body></html>")
|
def _create_html_root(self, hhcpath, log): hhcdata = self._read_file(hhcpath) hhcroot = html.fromstring(hhcdata) chapters = self._process_nodes(hhcroot) #print "=============================" #print "Printing hhcroot" #print etree.tostring(hhcroot, pretty_print=True) #print "=============================" log.debug('Found %d section nodes' % len(chapters)) htmlpath = os.path.splitext(hhcpath)[0] + ".html" f = open(htmlpath, 'wb') f.write("<HTML><HEAD></HEAD><BODY>\r\n")
|
if not cls.SUPPORTS_USE_AUTHOR_SORT:
|
if cls.SUPPORTS_USE_AUTHOR_SORT:
|
def save_settings(cls, config_widget): proxy = cls._configProxy() proxy['format_map'] = config_widget.format_map() if cls.SUPPORTS_SUB_DIRS: proxy['use_subdirs'] = config_widget.use_subdirs() if not cls.MUST_READ_METADATA: proxy['read_metadata'] = config_widget.read_metadata() if not cls.SUPPORTS_USE_AUTHOR_SORT: proxy['use_author_sort'] = config_widget.use_author_sort() if cls.EXTRA_CUSTOMIZATION_MESSAGE: ec = unicode(config_widget.opt_extra_customization.text()).strip() if not ec: ec = None proxy['extra_customization'] = ec st = unicode(config_widget.opt_save_template.text()) proxy['save_template'] = st
|
author = string_to_authors(unicode(self.authors.text()))[0]
|
try: author = string_to_authors(unicode(self.authors.text()))[0] except IndexError: author = ''
|
def fetch_metadata(self): isbn = re.sub(r'[^0-9a-zA-Z]', '', unicode(self.isbn.text())) title = qstring_to_unicode(self.title.text()) author = string_to_authors(unicode(self.authors.text()))[0] publisher = qstring_to_unicode(self.publisher.currentText()) if isbn or title or author or publisher: d = FetchMetadata(self, isbn, title, author, publisher, self.timeout) self._fetch_metadata_scope = d with d: if d.exec_() == QDialog.Accepted: book = d.selected_book() if book: if d.opt_get_social_metadata.isChecked(): d2 = SocialMetadata(book, self) d2.exec_() if d2.exceptions: det = '\n'.join([x[0]+'\n\n'+x[-1]+'\n\n\n' for x in d2.exceptions]) warning_dialog(self, _('There were errors'), _('There were errors downloading social metadata'), det_msg=det, show=True) else: book.tags = [] if d.opt_overwrite_author_title_metadata.isChecked(): self.title.setText(book.title) self.authors.setText(authors_to_string(book.authors)) if book.author_sort: self.author_sort.setText(book.author_sort) if book.publisher: self.publisher.setEditText(book.publisher) if book.isbn: self.isbn.setText(book.isbn) if book.pubdate: d = book.pubdate self.pubdate.setDate(QDate(d.year, d.month, d.day)) summ = book.comments if summ: prefix = unicode(self.comments.toPlainText()) if prefix: prefix += '\n' self.comments.setText(prefix + summ) if book.rating is not None: self.rating.setValue(int(book.rating)) if book.tags: self.tags.setText(', '.join(book.tags)) if book.series is not None: if self.series.text() is None or self.series.text() == '': self.series.setText(book.series) if book.series_index is not None: self.series_index.setValue(book.series_index) else: error_dialog(self, _('Cannot fetch metadata'), _('You must specify at least one of ISBN, Title, ' 'Authors or Publisher'), show=True)
|
self._formatted_date = self.localtime.strftime(" [%a, %d %b %H:%M]")
|
self._formatted_date = strftime(" [%a, %d %b %H:%M]", t=self.localtime.timetuple())
|
def fget(self): if self._formatted_date is None: self._formatted_date = self.localtime.strftime(" [%a, %d %b %H:%M]") return self._formatted_date
|
self.open_feedback_msg(dev.get_gui_name(), e.feedback_msg)
|
if dev not in self.ejected_devices: self.open_feedback_msg(dev.get_gui_name(), e.feedback_msg) self.ejected_devices.add(dev)
|
def do_connect(self, connected_devices, device_kind): for dev, detected_device in connected_devices: if dev.OPEN_FEEDBACK_MESSAGE is not None: self.open_feedback_slot(dev.OPEN_FEEDBACK_MESSAGE) try: dev.reset(detected_device=detected_device, report_progress=self.report_progress) dev.open() except OpenFeedback, e: self.open_feedback_msg(dev.get_gui_name(), e.feedback_msg) continue except: tb = traceback.format_exc() if DEBUG or tb not in self.reported_errors: self.reported_errors.add(tb) prints('Unable to open device', str(dev)) prints(tb) continue self.connected_device = dev self.connected_device_kind = device_kind self.connected_slot(True, device_kind) return True return False
|
QItemDelegate.__init__(self, parent)
|
QStyledItemDelegate.__init__(self, parent)
|
def __init__(self, parent): QItemDelegate.__init__(self, parent) self._parent = parent self.star_path = QPainterPath() self.star_path.moveTo(90, 50) for i in range(1, 5): self.star_path.lineTo(50 + 40 * cos(0.8 * i * pi), \ 50 + 40 * sin(0.8 * i * pi)) self.star_path.closeSubpath() self.star_path.setFillRule(Qt.WindingFill) gradient = QLinearGradient(0, 0, 0, 100) gradient.setColorAt(0.0, self.COLOR) gradient.setColorAt(1.0, self.COLOR) self.brush = QBrush(gradient) self.factor = self.SIZE/100.
|
QApplication.style().drawControl(QStyle.CE_ItemViewItem, option,
|
style.drawControl(QStyle.CE_ItemViewItem, option,
|
def draw_star(): painter.save() painter.scale(self.factor, self.factor) painter.translate(50.0, 50.0) painter.rotate(-20) painter.translate(-50.0, -50.0) painter.drawPath(self.star_path) painter.restore()
|
self.drawFocus(painter, option, option.rect)
|
def draw_star(): painter.save() painter.scale(self.factor, self.factor) painter.translate(50.0, 50.0) painter.rotate(-20) painter.translate(-50.0, -50.0) painter.drawPath(self.star_path) painter.restore()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.