bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def __init__(self, parent=None): QMenu.__init__(self, parent) self.group = QActionGroup(self) self.actions = [] self._memory = []
def __init__(self, parent=None): QMenu.__init__(self, parent) self.group = QActionGroup(self) self.actions = [] self._memory = []
451,700
def __init__(self, parent=None): QMenu.__init__(self, parent) self.group = QActionGroup(self) self.actions = [] self._memory = []
def __init__(self, parent=None): QMenu.__init__(self, parent) self.group = QActionGroup(self) self.actions = [] self._memory = []
451,701
def __init__(self, parent=None): QMenu.__init__(self, parent) self.group = QActionGroup(self) self.actions = [] self._memory = []
def __init__(self, parent=None): QMenu.__init__(self, parent) self.group = QActionGroup(self) self.actions = [] self._memory = []
451,702
def index(self, **kwargs): 'The / URL' ua = cherrypy.request.headers.get('User-Agent', '').strip() want_opds = \ cherrypy.request.headers.get('Stanza-Device-Name', 919) != 919 or \ cherrypy.request.headers.get('Want-OPDS-Catalog', 919) != 919 or \ ua.startswith('Stanza')
def index(self, **kwargs): 'The / URL' ua = cherrypy.request.headers.get('User-Agent', '').strip() want_opds = \ cherrypy.request.headers.get('Stanza-Device-Name', 919) != 919 or \ cherrypy.request.headers.get('Want-OPDS-Catalog', 919) != 919 or \ ua.startswith('Stanza')
451,703
def run(self, archive): is_rar = archive.lower().endswith('.rar') if is_rar: from calibre.libunrar import extract_member, names else: zf = ZipFile(archive, 'r')
def run(self, archive): is_rar = archive.lower().endswith('.rar') if is_rar: from calibre.libunrar import extract_member, names else: zf = ZipFile(archive, 'r')
451,704
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...
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...
451,705
def ExtractFiles(self, output_dir=os.getcwdu()): for path in self.Contents(): lpath = os.path.join(output_dir, path) self._ensure_dir(lpath) try: data = self.GetFile(path) except: self.log.exception('Failed to extract %s from CHM, ignoring'%path) continue if lpath.find(';') != -1: # fix file names with ";<junk>" at the...
def ExtractFiles(self, output_dir=os.getcwdu()): for path in self.Contents(): lpath = os.path.join(output_dir, path) self._ensure_dir(lpath) try: data = self.GetFile(path) except: self.log.exception('Failed to extract %s from CHM, ignoring'%path) continue if lpath.find(';') != -1: # fix file names with ";<junk>" at the...
451,706
def _reformat(self, data): try: data = xml_to_unicode(data, strip_encoding_pats=True)[0] soup = BeautifulSoup(data) except ValueError: # hit some strange encoding problems... self.log.exception("Unable to parse html for cleaning, leaving it") return data # nuke javascript... [s.extract() for s in soup('script')] # remo...
def _reformat(self, data, htmlpath): try: data = xml_to_unicode(data, strip_encoding_pats=True)[0] soup = BeautifulSoup(data) except ValueError: # hit some strange encoding problems... self.log.exception("Unable to parse html for cleaning, leaving it") return data # nuke javascript... [s.extract() for s in soup('script...
451,707
def _reformat(self, data): try: data = xml_to_unicode(data, strip_encoding_pats=True)[0] soup = BeautifulSoup(data) except ValueError: # hit some strange encoding problems... self.log.exception("Unable to parse html for cleaning, leaving it") return data # nuke javascript... [s.extract() for s in soup('script')] # remo...
def _reformat(self, data): try: data = xml_to_unicode(data, strip_encoding_pats=True)[0] soup = BeautifulSoup(data) except ValueError: # hit some strange encoding problems... self.log.exception("Unable to parse html for cleaning, leaving it") return data # nuke javascript... [s.extract() for s in soup('script')] # remo...
451,708
def convert(self, oeb, output_path, input_plugin, opts, log): self.log, self.opts, self.oeb = log, opts, oeb
def convert(self, oeb, output_path, input_plugin, opts, log): self.log, self.opts, self.oeb = log, opts, oeb
451,709
def convert(self, oeb, output_path, input_plugin, opts, log): self.log, self.opts, self.oeb = log, opts, oeb
defconvert(self,oeb,output_path,input_plugin,opts,log):self.log,self.opts,self.oeb=log,opts,oeb
451,710
def customization_help(self): return 'This plugin can only be customized using the GUI'
def customization_help(self): return 'This plugin can only be customized using the GUI'
451,711
def fetch(self): from calibre.ebooks.metadata.google_books import search try: self.results = search(self.title, self.book_author, self.publisher, self.isbn, max_results=10, verbose=self.verbose) except Exception, e: self.exception = e self.tb = traceback.format_exc()
def fetch(self): from calibre.ebooks.metadata.google_books import search try: self.results = search(self.title, self.book_author, self.publisher, self.isbn, max_results=10, verbose=self.verbose) except Exception, e: self.exception = e self.tb = traceback.format_exc()
451,712
def string_customization_help(self): ans = _('To use isbndb.com you must sign up for a %sfree account%s ' 'and enter your access key below.') return '<p>'+ans%('<a href="http://www.isbndb.com">', '</a>')
def string_customization_help(self): ans = _('To use isbndb.com you must sign up for a %sfree account%s ' 'and enter your access key below.') return '<p>'+ans%('<a href="http://www.isbndb.com">', '</a>')
451,713
def fetch(self): if not self.isbn: return from calibre.ebooks.metadata.amazon import get_social_metadata try: self.results = get_social_metadata(self.title, self.book_author, self.publisher, self.isbn) except Exception, e: self.exception = e self.tb = traceback.format_exc()
def fetch(self): if not self.isbn: return from calibre.ebooks.metadata.amazon import get_social_metadata try: self.results = get_social_metadata(self.title, self.book_author, self.publisher, self.isbn) except Exception, e: self.exception = e self.tb = traceback.format_exc()
451,714
def fetch(self): if not self.isbn: return from calibre import browser from calibre.ebooks.metadata import MetaInformation import json br = browser() try: raw = br.open( 'http://status.calibre-ebook.com/library_thing/metadata/'+self.isbn ).read() data = json.loads(raw) if not data: return if 'error' in data: raise Excep...
def fetch(self): if not self.isbn: return from calibre.ebooks.metadata import MetaInformation import json br = browser() try: raw = br.open( 'http://status.calibre-ebook.com/library_thing/metadata/'+self.isbn ).read() data = json.loads(raw) if not data: return if 'error' in data: raise Exception(data['error']) if 'seri...
451,715
def search(title=None, author=None, publisher=None, isbn=None, isbndb_key=None, verbose=0): assert not(title is None and author is None and publisher is None and \ isbn is None) from calibre.customize.ui import metadata_sources, migrate_isbndb_key migrate_isbndb_key() if isbn is not None: isbn = re.sub(r'[^a-zA-Z0-9]',...
def search(title=None, author=None, publisher=None, isbn=None, isbndb_key=None, verbose=0): assert not(title is None and author is None and publisher is None and \ isbn is None) from calibre.customize.ui import metadata_sources, migrate_isbndb_key migrate_isbndb_key() if isbn is not None: isbn = re.sub(r'[^a-zA-Z0-9]',...
451,716
def strip_pml(self, pml): pml = re.sub(r'\\.\d=""', '', pml) pml = re.sub(r'\\.=""', '', pml) pml = re.sub(r'\\.\d', '', pml) pml = re.sub(r'\\.', '', pml) pml = re.sub(r'\\a\d\d\d', '', pml) pml = re.sub(r'\\U\d\d\d\d', '', pml) pml.replace('\r\n', ' ') pml.replace('\n', ' ') pml.replace('\r', ' ')
def strip_pml(self, pml): pml = re.sub(r'\\C\d=".+*"', '', pml) pml = re.sub(r'\\Fn=".+*"', '', pml) pml = re.sub(r'\\Sd=".+*"', '', pml) pml = re.sub(r'\\.=".+*"', '', pml) pml = re.sub(r'\\X\d', '', pml) pml = re.sub(r'\\S[pbd]', '', pml) pml = re.sub(r'\\Fn', '', pml) pml = re.sub(r'\\a\d\d\d', '', pml) pml = re.sub...
451,717
def old(self, **kwargs): return self.static('index.html')
def old(self, **kwargs): return self.static('index.html')
451,718
def dump_text(self, elem, stylizer, page, tag_stack=[]): if not isinstance(elem.tag, basestring) \ or namespace(elem.tag) != XHTML_NS: return []
def dump_text(self, elem, stylizer, page, tag_stack=[]): if not isinstance(elem.tag, basestring) \ or namespace(elem.tag) != XHTML_NS: return []
451,719
def initialize(self, name, default, help): variables = sorted(FORMAT_ARG_DESCS.keys()) rows = [] for var in variables: rows.append(u'<tr><td>%s</td><td>%s</td></tr>'% (var, FORMAT_ARG_DESCS[var])) table = u'<table>%s</table>'%(u'\n'.join(rows)) self.template_variables.setText(table)
def initialize(self, name, default, help): variables = sorted(FORMAT_ARG_DESCS.keys()) rows = [] for var in variables: rows.append(u'<tr><td>%s</td><td>&nbsp;</td><td>%s</td></tr>'% (var, FORMAT_ARG_DESCS[var])) table = u'<table>%s</table>'%(u'\n'.join(rows)) self.template_variables.setText(table)
451,720
def validate(self): # TODO: NEWMETA: I haven't figured out how to get the custom columns # into here, so for the moment make all templates valid. return True
def validate(self): # TODO: NEWMETA: I haven't figured out how to get the custom columns # into here, so for the moment make all templates valid. return True
451,721
def validate(self): # TODO: NEWMETA: I haven't figured out how to get the custom columns # into here, so for the moment make all templates valid. return True
def validate(self): # TODO: NEWMETA: I haven't figured out how to get the custom columns # into here, so for the moment make all templates valid. return True
451,722
def format_day(mo): l = len(mo.group(0)) if l == 1: return '%d'%dt.day if l == 2: return '%02d'%dt.day if l == 3: return dt.strftime('%a') return dt.strftime('%A')
def format_day(mo): l = len(mo.group(0)) if l == 1: return '%d'%dt.day if l == 2: return '%02d'%dt.day if l == 3: return dt.strftime('%a') return dt.strftime('%A')
451,723
def format_month(mo): l = len(mo.group(0)) if l == 1: return '%d'%dt.month if l == 2: return '%02d'%dt.month if l == 3: return dt.strftime('%b') return dt.strftime('%B')
def format_month(mo): l = len(mo.group(0)) if l == 1: return '%d'%dt.month if l == 2: return '%02d'%dt.month if l == 3: return dt.strftime('%b') return dt.strftime('%B')
451,724
def initialize_db_stage2(self, db, tb): repair_pd = getattr(self, 'repair_pd', None) if repair_pd is not None: repair_pd.cancel()
def initialize_db_stage2(self, db, tb): repair_pd = getattr(self, 'repair_pd', None) if repair_pd is not None: repair_pd.cancel()
451,725
def initialize_db_stage2(self, db, tb): repair_pd = getattr(self, 'repair_pd', None) if repair_pd is not None: repair_pd.cancel()
def initialize_db_stage2(self, db, tb): repair_pd = getattr(self, 'repair_pd', None) if repair_pd is not None: repair_pd.cancel()
451,726
def initialize_db_stage2(self, db, tb): repair_pd = getattr(self, 'repair_pd', None) if repair_pd is not None: repair_pd.cancel()
def initialize_db_stage2(self, db, tb): repair_pd = getattr(self, 'repair_pd', None) if repair_pd is not None: repair_pd.cancel()
451,727
def initialize_db(self): db = None try: db = LibraryDatabase2(self.library_path) except (sqlite.Error, DatabaseException): repair = question_dialog(None, _('Corrupted database'), _('Your calibre database appears to be corrupted. Do ' 'you want calibre to try and repair it automatically? ' 'If you say No, a new empty ca...
def initialize_db(self): db = None try: db = LibraryDatabase2(self.library_path) except (sqlite.Error, DatabaseException): repair = question_dialog(self.splash_screen, _('Corrupted database'), _('Your calibre database appears to be corrupted. Do ' 'you want calibre to try and repair it automatically? ' 'If you say No, ...
451,728
def initialize_db(self): db = None try: db = LibraryDatabase2(self.library_path) except (sqlite.Error, DatabaseException): repair = question_dialog(None, _('Corrupted database'), _('Your calibre database appears to be corrupted. Do ' 'you want calibre to try and repair it automatically? ' 'If you say No, a new empty ca...
def initialize_db(self): db = None try: db = LibraryDatabase2(self.library_path) except (sqlite.Error, DatabaseException): repair = question_dialog(None, _('Corrupted database'), _('Your calibre database appears to be corrupted. Do ' 'you want calibre to try and repair it automatically? ' 'If you say No, a new empty ca...
451,729
def resort(self, reset=True): if self.sorted_on: self.sort(self.column_map.index(self.sorted_on[0]), self.sorted_on[1], reset=reset)
def resort(self, reset=True): if self.sorted_on: self.sort(self.column_map.index(self.sorted_on[0]), self.sorted_on[1], reset=reset)
451,730
def icu_collator(s1, s2, func=None): return cmp(func(unicode(s1)), func(unicode(s2)))
def icu_collator(s1, s2): return strcmp(force_unicode(s1, 'utf-8'), force_unicode(s2, 'utf-8'))
451,731
def connect(self): self.conn = sqlite.connect(self.path, factory=Connection, detect_types=sqlite.PARSE_DECLTYPES|sqlite.PARSE_COLNAMES) self.conn.execute('pragma cache_size=5000') encoding = self.conn.execute('pragma encoding').fetchone()[0] c_ext_loaded = load_c_extensions(self.conn) self.conn.row_factory = sqlite.Row...
def connect(self): self.conn = sqlite.connect(self.path, factory=Connection, detect_types=sqlite.PARSE_DECLTYPES|sqlite.PARSE_COLNAMES) self.conn.execute('pragma cache_size=5000') encoding = self.conn.execute('pragma encoding').fetchone()[0] c_ext_loaded = load_c_extensions(self.conn) self.conn.row_factory = sqlite.Row...
451,732
def browse_matches(self, category=None, cid=None, list_sort=None): if list_sort: list_sort = unquote(list_sort) if not cid: raise cherrypy.HTTPError(404, 'invalid category id: %r'%cid) categories = self.categories_cache()
def browse_matches(self, category=None, cid=None, list_sort=None): if list_sort: list_sort = unquote(list_sort) if not cid: raise cherrypy.HTTPError(404, 'invalid category id: %r'%cid) categories = self.categories_cache()
451,733
def browse_matches(self, category=None, cid=None, list_sort=None): if list_sort: list_sort = unquote(list_sort) if not cid: raise cherrypy.HTTPError(404, 'invalid category id: %r'%cid) categories = self.categories_cache()
def browse_matches(self, category=None, cid=None, list_sort=None): if list_sort: list_sort = unquote(list_sort) if not cid: raise cherrypy.HTTPError(404, 'invalid category id: %r'%cid) categories = self.categories_cache()
451,734
def get_sort_key(x): sk = x.s if isinstance(sk, unicode): sk = sort_key(sk) return sk
def get_sort_key(x): sk = x.s if isinstance(sk, unicode): sk = sort_key(sk) return sk
451,735
def populate_from_preparsed_feed(self, title, articles, oldest_article=7, max_articles_per_feed=100): self.title = unicode(title if title else _('Unknown feed')) self.description = '' self.image_url = None self.articles = [] self.added_articles = []
def populate_from_preparsed_feed(self, title, articles, oldest_article=7, max_articles_per_feed=100): self.title = unicode(title if title else _('Unknown feed')) self.description = '' self.image_url = None self.articles = [] self.added_articles = []
451,736
def save_book_to_disk(id, db, root, opts, length): mi = db.get_metadata(id, index_is_id=True) available_formats = db.formats(id, index_is_id=True) if not available_formats: available_formats = [] else: available_formats = [x.lower().strip() for x in available_formats.split(',')] if opts.formats == 'all': asked_formats...
def save_book_to_disk(id, db, root, opts, length): mi = db.get_metadata(id, index_is_id=True) available_formats = db.formats(id, index_is_id=True) if not available_formats: available_formats = [] else: available_formats = [x.lower().strip() for x in available_formats.split(',')] if opts.formats == 'all': asked_formats...
451,737
def populate_from_preparsed_feed(self, title, articles, oldest_article=7, max_articles_per_feed=100): self.title = title if title else _('Unknown feed') self.description = '' self.image_url = None self.articles = [] self.added_articles = []
def populate_from_preparsed_feed(self, title, articles, oldest_article=7, max_articles_per_feed=100): self.title = unicode(title if title else _('Unknown feed')) self.description = '' self.image_url = None self.articles = [] self.added_articles = []
451,738
def __init__(self, parent, modelcls=BooksModel): QTableView.__init__(self, parent)
def __init__(self, parent, modelcls=BooksModel): QTableView.__init__(self, parent)
451,739
def __init__(self, options, log, progress_reporter): ''' Initialize the recipe. :param options: Parsed commandline options :param parser: Command line option parser. Used to intelligently merge options. :param progress_reporter: A Callable that takes two arguments: progress (a number between 0 and 1) and a string mess...
def __init__(self, options, log, progress_reporter): ''' Initialize the recipe. :param options: Parsed commandline options :param parser: Command line option parser. Used to intelligently merge options. :param progress_reporter: A Callable that takes two arguments: progress (a number between 0 and 1) and a string mess...
451,740
def __init__(self, options, log, progress_reporter): ''' Initialize the recipe. :param options: Parsed commandline options :param parser: Command line option parser. Used to intelligently merge options. :param progress_reporter: A Callable that takes two arguments: progress (a number between 0 and 1) and a string mess...
def __init__(self, options, log, progress_reporter): ''' Initialize the recipe. :param options: Parsed commandline options :param parser: Command line option parser. Used to intelligently merge options. :param progress_reporter: A Callable that takes two arguments: progress (a number between 0 and 1) and a string mess...
451,741
def delete_images(self, ImageID): if ImageID == None: path_prefix = '.kobo/images/' path = self._main_prefix + path_prefix + ImageID
def delete_images(self, ImageID): if ImageID != None: path_prefix = '.kobo/images/' path = self._main_prefix + path_prefix + ImageID
451,742
def generateHTMLByAuthor(self): # Write books by author A-Z if self.verbose: print self.updateProgressFullStep("generateHTMLByAuthor()") friendly_name = "By Author"
def generateHTMLByAuthor(self): # Write books by author A-Z if self.verbose: print self.updateProgressFullStep("generateHTMLByAuthor()") friendly_name = "By Author"
451,743
def generateNCXByAuthor(self, tocTitle, single_article_per_section=True):
defgenerateNCXByAuthor(self,tocTitle,single_article_per_section=True):
451,744
def generateNCXByAuthor(self, tocTitle, single_article_per_section=True):
defgenerateNCXByAuthor(self,tocTitle,single_article_per_section=True):
451,745
def run(self, path_to_output, opts, db, notification=DummyReporter()): from calibre.utils.logging import Log
def run(self, path_to_output, opts, db, notification=DummyReporter()): from calibre.utils.logging import Log
451,746
def __init__(self): self.db_book_uuid_cache = set() self.device_error_dialog = error_dialog(self, _('Error'), _('Error communicating with device'), ' ') self.device_error_dialog.setModal(Qt.NonModal) self.device_connected = None self.emailer = Emailer() self.emailer.start() self.device_manager = DeviceManager(Dispatche...
def __init__(self): self.device_error_dialog = error_dialog(self, _('Error'), _('Error communicating with device'), ' ') self.device_error_dialog.setModal(Qt.NonModal) self.device_connected = None self.emailer = Emailer() self.emailer.start() self.device_manager = DeviceManager(Dispatcher(self.device_detected), self.jo...
451,747
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 = {} 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)\W...
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 = {} 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)\W...
451,748
def __call__(self, *args, **kwargs): q = Queue.Queue() self.dispatch_signal.emit(q, args, kwargs) return q.get()
def __call__(self, *args, **kwargs): q = Queue.Queue() self.dispatch_signal.emit(q, args, kwargs) return q.get()
451,749
def baseline_spine(self): sizes = defaultdict(float) for item in self.oeb.spine: html = item.data stylizer = self.stylizers[item] body = html.find(XHTML('body')) fsize = self.context.source.fbase self.baseline_node(body, stylizer, sizes, fsize) sbase = max(sizes.items(), key=operator.itemgetter(1))[0] self.oeb.logger.i...
def baseline_spine(self): sizes = defaultdict(float) for item in self.oeb.spine: html = item.data stylizer = self.stylizers[item] body = html.find(XHTML('body')) fsize = self.context.source.fbase self.baseline_node(body, stylizer, sizes, fsize) try: sbase = max(sizes.items(), key=operator.itemgetter(1))[0] except: sbas...
451,750
def getter(x): return category_meta[x]['name'].lower()
def getter(x): return category_meta[x]['name'].lower()
451,751
def s_text_list(self, tag, attrs): """ To know which level we're at, we have to count the number of <text:list> elements on the tagstack. """ name = attrs.get( (TEXTNS,'style-name') ) if name: name = name.replace(".","_") level = 1 else: # FIXME: If a list is contained in a table cell or text box, # the list level must...
def s_text_list(self, tag, attrs): """ To know which level we're at, we have to count the number of <text:list> elements on the tagstack. """ name = attrs.get( (TEXTNS,'style-name') ) if name: name = name.replace(".","_") else: # FIXME: If a list is contained in a table cell or text box, # the list level must return to...
451,752
def s_text_list(self, tag, attrs): """ To know which level we're at, we have to count the number of <text:list> elements on the tagstack. """ name = attrs.get( (TEXTNS,'style-name') ) if name: name = name.replace(".","_") level = 1 else: # FIXME: If a list is contained in a table cell or text box, # the list level must...
def s_text_list(self, tag, attrs): """ To know which level we're at, we have to count the number of <text:list> elements on the tagstack. """ name = attrs.get( (TEXTNS,'style-name') ) if name: name = name.replace(".","_") level = 1 else: # FIXME: If a list is contained in a table cell or text box, # the list level must...
451,753
def s_text_list(self, tag, attrs): """ To know which level we're at, we have to count the number of <text:list> elements on the tagstack. """ name = attrs.get( (TEXTNS,'style-name') ) if name: name = name.replace(".","_") level = 1 else: # FIXME: If a list is contained in a table cell or text box, # the list level must...
def s_text_list(self, tag, attrs): """ To know which level we're at, we have to count the number of <text:list> elements on the tagstack. """ name = attrs.get( (TEXTNS,'style-name') ) if name: name = name.replace(".","_") level = 1 else: # FIXME: If a list is contained in a table cell or text box, # the list level must...
451,754
def s_text_list(self, tag, attrs): """ To know which level we're at, we have to count the number of <text:list> elements on the tagstack. """ name = attrs.get( (TEXTNS,'style-name') ) if name: name = name.replace(".","_") level = 1 else: # FIXME: If a list is contained in a table cell or text box, # the list level must...
def s_text_list(self, tag, attrs): """ To know which level we're at, we have to count the number of <text:list> elements on the tagstack. """ name = attrs.get( (TEXTNS,'style-name') ) if name: name = name.replace(".","_") level = 1 else: # FIXME: If a list is contained in a table cell or text box, # the list level must...
451,755
def e_text_list(self, tag, attrs): self.writedata() name = attrs.get( (TEXTNS,'style-name') ) if name: name = name.replace(".","_") level = 1 else: # FIXME: If a list is contained in a table cell or text box, # the list level must return to 1, even though the table or # textbox itself may be nested within another list....
def e_text_list(self, tag, attrs): self.writedata() name = attrs.get( (TEXTNS,'style-name') ) if name: name = name.replace(".","_") else: # FIXME: If a list is contained in a table cell or text box, # the list level must return to 1, even though the table or # textbox itself may be nested within another list. level = s...
451,756
def e_text_list(self, tag, attrs): self.writedata() name = attrs.get( (TEXTNS,'style-name') ) if name: name = name.replace(".","_") level = 1 else: # FIXME: If a list is contained in a table cell or text box, # the list level must return to 1, even though the table or # textbox itself may be nested within another list....
def e_text_list(self, tag, attrs): self.writedata() name = attrs.get( (TEXTNS,'style-name') ) if name: name = name.replace(".","_") level = 1 else: # FIXME: If a list is contained in a table cell or text box, # the list level must return to 1, even though the table or # textbox itself may be nested within another list....
451,757
def e_text_list(self, tag, attrs): self.writedata() name = attrs.get( (TEXTNS,'style-name') ) if name: name = name.replace(".","_") level = 1 else: # FIXME: If a list is contained in a table cell or text box, # the list level must return to 1, even though the table or # textbox itself may be nested within another list....
def e_text_list(self, tag, attrs): self.writedata() name = attrs.get( (TEXTNS,'style-name') ) if name: name = name.replace(".","_") level = 1 else: # FIXME: If a list is contained in a table cell or text box, # the list level must return to 1, even though the table or # textbox itself may be nested within another list....
451,758
def s_text_list_level_style_bullet(self, tag, attrs): """ CSS doesn't have the ability to set the glyph to a particular character, so we just go through the available glyphs """ name = self.tagstack.rfindattr( (STYLENS,'name') ) self.listtypes[name] = 'ul' level = attrs[(TEXTNS,'level')] self.prevstyle = self.currentst...
def s_text_list_level_style_bullet(self, tag, attrs): """ CSS doesn't have the ability to set the glyph to a particular character, so we just go through the available glyphs """ name = self.tagstack.rfindattr( (STYLENS,'name') ) level = attrs[(TEXTNS,'level')] self.prevstyle = self.currentstyle self.currentstyle = ".%s...
451,759
def s_text_list_level_style_number(self, tag, attrs): name = self.tagstack.stackparent()[(STYLENS,'name')] self.listtypes[name] = 'ol' level = attrs[(TEXTNS,'level')] num_format = attrs.get( (STYLENS,'name'),"1") self.prevstyle = self.currentstyle self.currentstyle = ".%s_%s" % ( name.replace(".","_"), level) self.styl...
def s_text_list_level_style_number(self, tag, attrs): name = self.tagstack.stackparent()[(STYLENS,'name')] level = attrs[(TEXTNS,'level')] num_format = attrs.get( (STYLENS,'name'),"1") self.prevstyle = self.currentstyle self.currentstyle = ".%s_%s" % ( name.replace(".","_"), level) self.stylestack.append(self.currentst...
451,760
def _cover_to_thumb(self, path, metadata, db_added, lb_added, format): ''' assumes pythoncom wrapper for db_added as of iTunes 9.2, iBooks 1.1, can't set artwork for PDF files via automation ''' self.log.info(" ITUNES._cover_to_thumb()")
def _cover_to_thumb(self, path, metadata, db_added, lb_added, format): ''' assumes pythoncom wrapper for db_added as of iTunes 9.2, iBooks 1.1, can't set artwork for PDF files via automation ''' self.log.info(" ITUNES._cover_to_thumb()")
451,761
def _cover_to_thumb(self, path, metadata, db_added, lb_added, format): ''' assumes pythoncom wrapper for db_added as of iTunes 9.2, iBooks 1.1, can't set artwork for PDF files via automation ''' self.log.info(" ITUNES._cover_to_thumb()")
def _cover_to_thumb(self, path, metadata, db_added, lb_added, format): ''' assumes pythoncom wrapper for db_added as of iTunes 9.2, iBooks 1.1, can't set artwork for PDF files via automation ''' self.log.info(" ITUNES._cover_to_thumb()")
451,762
def generateHTMLBySeries(self): ''' Generate a list of series ''' self.updateProgressFullStep("Fetching series")
def generateHTMLBySeries(self): ''' Generate a list of series ''' self.updateProgressFullStep("Fetching series")
451,763
def generateHTMLBySeries(self): ''' Generate a list of series ''' self.updateProgressFullStep("Fetching series")
def generateHTMLBySeries(self): ''' Generate a list of series ''' self.updateProgressFullStep("Fetching series")
451,764
def __init__(self, locations, test=False): self._tests_failed = False # Define a token standard_locations = map(lambda x : CaselessLiteral(x)+Suppress(':'), locations) location = NoMatch() for l in standard_locations: location |= l location = Optional(location, default='all') word_query = CharsNotIn(string.whites...
def __init__(self, locations, test=False): self._tests_failed = False # Define a token standard_locations = map(lambda x : CaselessLiteral(x)+Suppress(':'), locations) location = NoMatch() for l in standard_locations: location |= l location = Optional(location, default='all') word_query = CharsNotIn(string.whites...
451,765
def __init__(self, locations, test=False): self._tests_failed = False # Define a token standard_locations = map(lambda x : CaselessLiteral(x)+Suppress(':'), locations) location = NoMatch() for l in standard_locations: location |= l location = Optional(location, default='all') word_query = CharsNotIn(string.whites...
def __init__(self, locations, test=False): self._tests_failed = False # Define a token standard_locations = map(lambda x : CaselessLiteral(x)+Suppress(':'), locations) location = NoMatch() for l in standard_locations: location |= l location = Optional(location, default='all') word_query = CharsNotIn(string.whites...
451,766
def __init__(self, locations, test=False): self._tests_failed = False # Define a token standard_locations = map(lambda x : CaselessLiteral(x)+Suppress(':'), locations) location = NoMatch() for l in standard_locations: location |= l location = Optional(location, default='all') word_query = CharsNotIn(string.whites...
def __init__(self, locations, test=False): self._tests_failed = False # Define a token standard_locations = map(lambda x : CaselessLiteral(x)+Suppress(':'), locations) location = NoMatch() for l in standard_locations: location |= l location = Optional(location, default='all') word_query = CharsNotIn(string.whites...
451,767
def __init__(self, locations, test=False): self._tests_failed = False # Define a token standard_locations = map(lambda x : CaselessLiteral(x)+Suppress(':'), locations) location = NoMatch() for l in standard_locations: location |= l location = Optional(location, default='all') word_query = CharsNotIn(string.whites...
def __init__(self, locations, test=False): self._tests_failed = False # Define a token standard_locations = map(lambda x : CaselessLiteral(x)+Suppress(':'), locations) location = NoMatch() for l in standard_locations: location |= l location = Optional(location, default='all') word_query = CharsNotIn(string.whites...
451,768
def universal_set(self): ''' Should return the set of all matches. ''' return set([])
def universal_set(self): ''' Should return the set of all matches. ''' return set([])
451,769
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) '''
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) '''
451,770
def strftime(epoch, zone=None): zone = time.gmtime if islinux: zone = time.localtime src = time.strftime("%w, %d %m %Y %H:%M:%S GMT", zone(epoch)).split() src[0] = INVERSE_DAY_MAP[int(src[0][:-1])]+',' src[2] = INVERSE_MONTH_MAP[int(src[2])] return ' '.join(src)
def strftime(epoch, zone=time.localtime): src = time.strftime("%w, %d %m %Y %H:%M:%S GMT", zone(epoch)).split() src[0] = INVERSE_DAY_MAP[int(src[0][:-1])]+',' src[2] = INVERSE_MONTH_MAP[int(src[2])] return ' '.join(src)
451,771
def update_text_record(self, record, book, path, bl_index): timestamp = os.path.getmtime(path) # Correct for MS DST time 'adjustment' if iswindows and time.daylight: timestamp -= time.altzone - time.timezone date = strftime(timestamp) if date != record.get('date', None): record.set('date', date) record.set('size', str(...
def update_text_record(self, record, book, path, bl_index): timestamp = os.path.getmtime(path) # Correct for MS DST time 'adjustment'date = strftime(timestamp) if date != record.get('date', None): record.set('date', date) record.set('size', str(os.stat(path).st_size)) title = book.title if book.title else _('Unknown') ...
451,772
def add_book(self, mi, name, collections, size, ctime): """ Add a node into the DOM tree, representing a book """ book = self.book_by_path(name) if book is not None: self.remove_book(name)
def add_book(self, mi, name, collections, size, ctime): """ Add a node into the DOM tree, representing a book """ book = self.book_by_path(name) if book is not None: self.remove_book(name)
451,773
def set_path(self, index, index_is_id=False): ''' 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(id) current_...
def set_path(self, index, index_is_id=False): ''' 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(id) current_...
451,774
def set_path(self, index, index_is_id=False): ''' 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(id) current_...
def set_path(self, index, index_is_id=False): ''' 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(id) current_...
451,775
def dump_text(self, elem, stylizer, end=''): ''' @elem: The element in the etree that we are working on. @stylizer: The style information attached to the element. @end: The last two characters of the text from the previous element. This is used to determine if a blank line is needed when starting a new block element. '...
def dump_text(self, elem, stylizer, end=''): ''' @elem: The element in the etree that we are working on. @stylizer: The style information attached to the element. @end: The last two characters of the text from the previous element. This is used to determine if a blank line is needed when starting a new block element. '...
451,776
def line_length(format, raw, percent): ''' raw is the raw text to find the line length to use for wrapping. percentage is a decimal number, 0 - 1 which is used to determine how far in the list of line lengths to use. The list of line lengths is ordered smallest to larged and does not include duplicates. 0.5 is the medi...
def line_length(format, raw, percent): ''' raw is the raw text to find the line length to use for wrapping. percentage is a decimal number, 0 - 1 which is used to determine how far in the list of line lengths to use. The list of line lengths is ordered smallest to larged and does not include duplicates. 0.5 is the medi...
451,777
def __call__(self, data, add_namespace=False): from calibre.ebooks.oeb.base import XHTML_CSS_NAMESPACE data = self.PAGE_PAT.sub('', data) if not add_namespace: return data ans, namespaced = [], False for line in data.splitlines(): ll = line.lstrip() if not (namespaced or ll.startswith('@import') or ll.startswith('@char...
def __call__(self, data, add_namespace=False): from calibre.ebooks.oeb.base import XHTML_CSS_NAMESPACE data = self.PAGE_PAT.sub('', data) if not add_namespace: return data ans, namespaced = [], False for line in data.splitlines(): ll = line.lstrip() if not (namespaced or ll.startswith('@import') or ll.startswith('@char...
451,778
def __call__(self, data, add_namespace=False): from calibre.ebooks.oeb.base import XHTML_CSS_NAMESPACE data = self.PAGE_PAT.sub('', data) if not add_namespace: return data ans, namespaced = [], False for line in data.splitlines(): ll = line.lstrip() if not (namespaced or ll.startswith('@import') or ll.startswith('@char...
def(re.compile(r'<br\s*/?>\s*(?P<chap>([A-Z]\s+){4,}\s*([\d\w-]+\s*){0,3}\s*)\s*(<br>\s*){1,3}\s*(?P<title>(<(i|b)>)?(\s*\w+){1,4}\s*(</(i|b)>)?\s*(</?(br|p)[^>]*>))?'), chap_head), __call__(self,(re.compile(r'<br\s*/?>\s*(?P<chap>([A-Z]\s+){4,}\s*([\d\w-]+\s*){0,3}\s*)\s*(<br>\s*){1,3}\s*(?P<title>(<(i|b)>)?(\s*\w+){...
451,779
def __call__(self, html, remove_special_chars=None, get_preprocess_html=False): if remove_special_chars is not None: html = remove_special_chars.sub('', html) html = html.replace('\0', '') is_pdftohtml = self.is_pdftohtml(html) if self.is_baen(html): rules = [] elif self.is_book_designer(html): rules = self.BOOK_DESIGN...
def __call__(self, html, remove_special_chars=None, get_preprocess_html=False): if remove_special_chars is not None: html = remove_special_chars.sub('', html) html = html.replace('\0', '') is_pdftohtml = self.is_pdftohtml(html) if self.is_baen(html): rules = [] elif self.is_book_designer(html): rules = self.BOOK_DESIGN...
451,780
def __call__(self, html, remove_special_chars=None, get_preprocess_html=False): if remove_special_chars is not None: html = remove_special_chars.sub('', html) html = html.replace('\0', '') is_pdftohtml = self.is_pdftohtml(html) if self.is_baen(html): rules = [] elif self.is_book_designer(html): rules = self.BOOK_DESIGN...
def __call__(self, html, remove_special_chars=None, get_preprocess_html=False): if remove_special_chars is not None: html = remove_special_chars.sub('', html) html = html.replace('\0', '') is_pdftohtml = self.is_pdftohtml(html) if self.is_baen(html): rules = [] elif self.is_book_designer(html): rules = self.BOOK_DESIGN...
451,781
def __call__(self, html, remove_special_chars=None, get_preprocess_html=False): if remove_special_chars is not None: html = remove_special_chars.sub('', html) html = html.replace('\0', '') is_pdftohtml = self.is_pdftohtml(html) if self.is_baen(html): rules = [] elif self.is_book_designer(html): rules = self.BOOK_DESIGN...
def __call__(self, html, remove_special_chars=None, get_preprocess_html=False): if remove_special_chars is not None: html = remove_special_chars.sub('', html) html = html.replace('\0', '') is_pdftohtml = self.is_pdftohtml(html) if self.is_baen(html): rules = [] elif self.is_book_designer(html): rules = self.BOOK_DESIGN...
451,782
def createEditor(self, parent, option, index): editor = EnLineEdit(parent) if self.auto_complete_function: complete_items = [i[1] for i in self.auto_complete_function()] completer = QCompleter(complete_items, self) completer.setCaseSensitivity(Qt.CaseInsensitive) completer.setCompletionMode(QCompleter.InlineCompletion)...
def createEditor(self, parent, option, index): editor = EnLineEdit(parent) if self.auto_complete_function: complete_items = [i[1] for i in self.auto_complete_function()] completer = QCompleter(complete_items, self) completer.setCaseSensitivity(Qt.CaseInsensitive) completer.setCompletionMode(QCompleter.PopupCompletion) ...
451,783
def initialize(self, opt_name, colorize=False, help_text=_('Search')): self.as_you_type = config['search_as_you_type'] self.opt_name = opt_name self.addItems(QStringList(list(set(config[opt_name])))) self.help_text = help_text self.colorize = colorize self.clear_to_help() self.connect(self, SIGNAL('editTextChanged(QStr...
def initialize(self, opt_name, colorize=False, help_text=_('Search')): self.as_you_type = config['search_as_you_type'] self.opt_name = opt_name self.addItems(QStringList(list(set(config[opt_name])))) self.help_text = help_text self.colorize = colorize self.clear_to_help() self.connect(self, SIGNAL('editTextChanged(QStr...
451,784
def normalize_state(self): self.setEditText('') self.line_edit.setStyleSheet( 'QLineEdit { color: black; background-color: %s; }' % self.normal_background) self.help_state = False
def normalize_state(self): self.setEditText('') self.line_edit.setStyleSheet( 'QLineEdit { color: black; background-color: %s; }' % self.normal_background) self.help_state = False
451,785
def key_pressed(self, event): if self.help_state: self.normalize_state() if not self.as_you_type: if event.key() in (Qt.Key_Return, Qt.Key_Enter): self.do_search()
def key_pressed(self, event): self.normalize_state() if not self.as_you_type: if event.key() in (Qt.Key_Return, Qt.Key_Enter): self.do_search()
451,786
def mouse_released(self, event): if self.help_state: self.normalize_state()
def mouse_released(self, event): if self.help_state: self.normalize_state()
451,787
def write_cache(prefix): try: cachep = os.path.join(prefix, self.CACHE_XML) if not os.path.exists(cachep): try: os.makedirs(os.path.dirname(cachep), mode=0777) except: time.sleep(5) os.makedirs(os.path.dirname(cachep), mode=0777) with open(cachep, 'wb') as f: f.write(u'''<?xml version="1.0" encoding="UTF-8"?> <cache xm...
def write_cache(prefix): try: cachep = os.path.join(prefix, *(self.CACHE_XML.split('/'))) if not os.path.exists(cachep): try: os.makedirs(os.path.dirname(cachep), mode=0777) except: time.sleep(5) os.makedirs(os.path.dirname(cachep), mode=0777) with open(cachep, 'wb') as f: f.write(u'''<?xml version="1.0" encoding="UTF-...
451,788
def write_cache(prefix): try: cachep = os.path.join(prefix, self.CACHE_XML) if not os.path.exists(cachep): try: os.makedirs(os.path.dirname(cachep), mode=0777) except: time.sleep(5) os.makedirs(os.path.dirname(cachep), mode=0777) with open(cachep, 'wb') as f: f.write(u'''<?xml version="1.0" encoding="UTF-8"?> <cache xm...
def write_cache(prefix): try: cachep = os.path.join(prefix, self.CACHE_XML) if not os.path.exists(cachep): dname = os.path.dirname(cachep) if not os.path.exists(dname): try: os.makedirs(dname, mode=0777) except: time.sleep(5) os.makedirs(dname, mode=0777) with open(cachep, 'wb') as f: f.write(u'''<?xml version="1.0" en...
451,789
def __init__(self, db, opts, plugin, report_progress=DummyReporter(), stylesheet="content/stylesheet.css"): self.__opts = opts self.__authorClip = opts.authorClip self.__authors = None self.__basename = opts.basename self.__bookmarked_books = None self.__booksByAuthor = None self.__booksByDateRead = None self.__booksBy...
def __init__(self, db, opts, plugin, report_progress=DummyReporter(), stylesheet="content/stylesheet.css"): self.__opts = opts self.__authorClip = opts.authorClip self.__authors = None self.__basename = opts.basename self.__bookmarked_books = None self.__booksByAuthor = None self.__booksByDateRead = None self.__booksBy...
451,790
def buildSources(self): if self.booksByTitle is None: if not self.fetchBooksByTitle(): return False self.fetchBooksByAuthor() self.fetchBookmarks() self.generateHTMLDescriptions() self.generateHTMLByAuthor() if self.opts.generate_titles: self.generateHTMLByTitle() if self.opts.generate_recently_added: self.generateHTML...
def buildSources(self): if self.booksByTitle is None: if not self.fetchBooksByTitle(): return False self.fetchBooksByAuthor() self.fetchBookmarks() self.generateHTMLDescriptions() self.generateHTMLByAuthor() if self.opts.generate_titles: self.generateHTMLByTitle() if self.opts.generate_recently_added: self.generateHTML...
451,791
def buildSources(self): if self.booksByTitle is None: if not self.fetchBooksByTitle(): return False self.fetchBooksByAuthor() self.fetchBookmarks() self.generateHTMLDescriptions() self.generateHTMLByAuthor() if self.opts.generate_titles: self.generateHTMLByTitle() if self.opts.generate_recently_added: self.generateHTML...
def buildSources(self): if self.booksByTitle is None: if not self.fetchBooksByTitle(): return False self.fetchBooksByAuthor() self.fetchBookmarks() self.generateHTMLDescriptions() self.generateHTMLByAuthor() if self.opts.generate_titles: self.generateHTMLByTitle() if self.opts.generate_recently_added: self.generateHTML...
451,792
def get_bookmark_data(self, path): ''' Return the timestamp and last_read_location ''' with open(path) as f: stream = StringIO(f.read()) data = StreamSlicer(stream) self.timestamp, = unpack('>I', data[0x24:0x28]) bpar_offset, = unpack('>I', data[0x4e:0x52]) #print "bpar_offset: 0x%x" % bpar_offset lrlo = bpar_offset + ...
def get_bookmark_data(self, path): ''' Return the timestamp and last_read_location ''' with open(path,'rb') as f: stream = StringIO(f.read()) data = StreamSlicer(stream) self.timestamp, = unpack('>I', data[0x24:0x28]) bpar_offset, = unpack('>I', data[0x4e:0x52]) #print "bpar_offset: 0x%x" % bpar_offset lrlo = bpar_offs...
451,793
def get_book_length(self, path, formats): # This assumes only one of the possible formats exists on the Kindle book_fs = None for format in formats: fmt = format.rpartition('.')[2] if fmt in ['mobi','prc','azw']: book_fs = path.replace('.mbp','.%s' % fmt) if os.path.exists(book_fs): self.book_format = fmt #print "%s ex...
def get_book_length(self, path, formats): # This assumes only one of the possible formats exists on the Kindle book_fs = None for format in formats: fmt = format.rpartition('.')[2] if fmt in ['mobi','prc','azw']: book_fs = path.replace('.mbp','.%s' % fmt) if os.path.exists(book_fs): self.book_format = fmt #print "%s ex...
451,794
def hexdump(self, src, length=16): # Diagnostic FILTER=''.join([(len(repr(chr(x)))==3) and chr(x) or '.' for x in range(256)]) N=0; result='' while src: s,src = src[:length],src[length:] hexa = ' '.join(["%02X"%ord(x) for x in s]) s = s.translate(FILTER) result += "%04X %-*s %s\n" % (N, length*3, hexa, s) N+=length...
def hexdump(self, src, length=16): # Diagnostic FILTER=''.join([(len(repr(chr(x)))==3) and chr(x) or '.' for x in range(256)]) N=0; result='' while src: s,src = src[:length],src[length:] hexa = ' '.join(["%02X"%ord(x) for x in s]) s = s.translate(FILTER) result += "%04X %-*s %s\n" % (N, length*3, hexa, s) N+=length...
451,795
def commit(self, book_ids, notify=False): val = self.gui_val val = self.normalize_ui_val(val) if val != self.initial_val: self.db.set_custom_bulk(book_ids, val, num=self.col_id, notify=notify)
def commit(self, book_ids, notify=False): val = self.gui_val val = self.normalize_ui_val(val) if val != self.initial_val: self.db.set_custom_bulk(book_ids, val, num=self.col_id, notify=notify)
451,796
def _generate_images(self): self._oeb.logger.info('Serializing images...') images = [(index, href) for href, index in self._images.items()] images.sort() self._first_image_record = None for _, href in images: item = self._oeb.manifest.hrefs[href] try: data = rescale_image(item.data, self._imagemax) except IOError: self...
def _generate_images(self): self._oeb.logger.info('Serializing images...') images = [(index, href) for href, index in self._images.items()] images.sort() self._first_image_record = None for _, href in images: item = self._oeb.manifest.hrefs[href] try: data = rescale_image(item.data, self._imagemax) except: self._oeb.lo...
451,797
def get_document_info(stream): """ Extract the \info block from an RTF file. Return the info block as a string and the position in the file at which it starts. @param stream: File like object pointing to the RTF file. """ block_size = 4096 stream.seek(0) found, block = False, "" while not found: prefix = block[-6:] blo...
def get_document_info(stream): """ Extract the \info block from an RTF file. Return the info block as a string and the position in the file at which it starts. @param stream: File like object pointing to the RTF file. """ block_size = 4096 stream.seek(0) found, block = False, "" while not found: prefix = block[-6:] blo...
451,798
def get_initial_value(self, book_ids): value = None for book_id in book_ids: val = self.db.get_custom(book_id, num=self.col_id, index_is_id=True) if tweaks['bool_custom_columns_are_tristate'] == 'no' and val is None: val = False if value is not None and value != val: return None value = val return value
def get_initial_value(self, book_ids): value = None for book_id in book_ids: val = self.db.get_custom(book_id, num=self.col_id, index_is_id=True) if tweaks['bool_custom_columns_are_tristate'] == 'no' and val is None: val = False if value is not None and value != val: return 'nochange' value = val return value
451,799