rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
self.add_line("\nRight Team Goals Distribution:")
self.add_newline() self.add_line("Right Team Goals Distribution:")
def do_some_calc(self): if self.count <= 0: self.add_line("Game Count: %d" % (self.count)) return
self.add_line("\nDiff Goals Distribution:")
self.add_newline() self.add_line("Diff Goals Distribution:")
def do_some_calc(self): if self.count <= 0: self.add_line("Game Count: %d" % (self.count)) return
self.add_line("\n")
self.add_newline()
def do_some_calc(self): if self.count <= 0: self.add_line("Game Count: %d" % (self.count)) return
self.add_line("No.\tScore\tPoint")
self.add_newline() self.add_line(" No. Score Point")
def generate_context(self): index = -1 non_valid = 0 for line in sys.stdin: index += 1 if index <= 0: self.add_line(line, color=Color.BLUE) #title self.add_line("No.\tScore\tPoint") #head continue parts = line.split() for i in range(len(parts)): parts[i] = int(parts[i])
self.add_line("\n")
self.add_newline()
def generate_context(self): index = -1 non_valid = 0 for line in sys.stdin: index += 1 if index <= 0: self.add_line(line, color=Color.BLUE) #title self.add_line("No.\tScore\tPoint") #head continue parts = line.split() for i in range(len(parts)): parts[i] = int(parts[i])
parser.add_option("-C", "--console", action="store_true", dest="console", default=True, help="print to stdout [default]")
parser.add_option("-C", "--console", action="store_true", dest="console", default=True, help="print to console [default]")
def run(self, method): self.generate() self.dump(method)
print "%sCount: %d" % (header, self.count)
if header: print "%sCount: %d" % (header, self.count)
def dump(self, header): game_count = float(self.count)
print "%sGoals: %d : %d" % (header, self.left_goals, self.right_goals) print "%sPoints: %d : %d" % (header, self.left_points, self.right_points)
print "%sGoals: %d : %d (diff: %d)" % (header, self.left_goals, self.right_goals, self.left_goals - self.right_goals) print "%sPoints: %d : %d (diff: %d)" % (header, self.left_points, self.right_points, self.left_points - self.right_points)
def dump(self, header): game_count = float(self.count)
self.add_line("No.\tScore\tPoint\n")
self.add_line("No.\tScore\tPoint")
def generate_context(self): self.add_line("No.\tScore\tPoint\n")
print "%sLeft Team Goals Distribution:" % (header) for line in self.dump_score_map(indent, self.left_score_map) : print line print print "%sRight Team Goals Distribution:" % (header) for line in self.dump_score_map(indent, self.right_score_map) : print line print print "%sDiff Goals Distribution:" % (header) for line in self.dump_score_map(indent, self.diff_score_map) : print line
if self.is_total: print "%sLeft Team Goals Distribution:" % (header) for line in self.dump_score_map(indent, self.left_score_map) : print line print print "%sRight Team Goals Distribution:" % (header) for line in self.dump_score_map(indent, self.right_score_map) : print line print print "%sDiff Goals Distribution:" % (header) for line in self.dump_score_map(indent, self.diff_score_map) : print line print print
def dump(self, indent): if self.count <= 0: print "%sCount: %d" % (header, self.count) return
print print
def dump(self, indent): if self.count <= 0: print "%sCount: %d" % (header, self.count) return
total_game = GameData() valid_game = GameData()
total_game = GameData(True) valid_game = GameData(False)
def dump(self, indent): if self.count <= 0: print "%sCount: %d" % (header, self.count) return
def do_some_calc(self):
def do_some_calculating(self):
def do_some_calc(self): game_count = float(self.count)
min = diff
min_diff = diff
def do_some_formatting(self): self.add_line(self.title, color=Color.BLUE) #title self.add_newline()
elif diff <= left_attention: line.color = Color.GREEN elif diff >= right_attention:
elif diff <= left_attention or diff >= right_attention:
def do_some_formatting(self): self.add_line(self.title, color=Color.BLUE) #title self.add_newline()
self.title = lines[0].strip() lines.pop(0)
self.title = lines.pop(0)
def generate_context(self, lines): self.title = lines[0].strip() lines.pop(0)
self.do_some_calc()
self.do_some_calculating()
def generate_context(self, lines): self.title = lines[0].strip() lines.pop(0)
line = line.rstrip()
line = line.strip()
def run(self, lines, method): self.generate_context(lines) self.context.dump(method)
string += "[face=Monospace]"
string += "[font=Monospace]"
def discuz(line): string = "" if line.color == Color.RED: string += "[b][color=Red]" elif line.color == Color.ORANGE: string += "[b][color=Orange]" elif line.color == Color.GREEN: string += "[b][color=Green]" elif line.color == Color.BLUE: string += "[b][color=Blue]" elif line.color == Color.PURPLE: string += "[b][color=Purple]" if line.face == Face.MONOSPACE: string += "[face=Monospace]" string += line.string if line.face != Face.NORMAL: string += "[/face]" if line.color != Color.NONE: string += "[/color][/b]" return string
string += "[/face]"
string += "[/font]"
def discuz(line): string = "" if line.color == Color.RED: string += "[b][color=Red]" elif line.color == Color.ORANGE: string += "[b][color=Orange]" elif line.color == Color.GREEN: string += "[b][color=Green]" elif line.color == Color.BLUE: string += "[b][color=Blue]" elif line.color == Color.PURPLE: string += "[b][color=Purple]" if line.face == Face.MONOSPACE: string += "[face=Monospace]" string += line.string if line.face != Face.NORMAL: string += "[/face]" if line.color != Color.NONE: string += "[/color][/b]" return string
def __init__(self, is_total=True): self.is_total = is_total
def gen_indent(indent) : header = "" for i in range(indent): header += " " return header
if sub >= 5: header = "\033[01;32m\n" if sub >= g_max_sub: g_max_sub = sub header = "\033[01;33m\n"
if sub >= g_max_sub: g_max_sub = sub header = "\033[01;33m" elif sub >= 5: header = "\033[01;32m" if not valid: header = "\033[01;31m"
def update(self, index, left_score, rigt_score, valid): global g_max_sub
return "%s%d\t%d:%d\t%d:%d\t%d\033[0m" % (header, index, left_score, rigt_score, left_points, right_points, valid)
return "%s%d\t%d:%d\t%d:%d\033[0m" % (header, index, left_score, rigt_score, left_points, right_points)
def update(self, index, left_score, rigt_score, valid): global g_max_sub
lines.append("%s%3d:%s%s" % (header, score, gen_indent(1), bar(score_map[score] / float(self.count))))
lines.append("%s%3d:%s%3d %s" % (header, score, gen_indent(1), score_map[score], bar(score_map[score] / float(self.count))))
def bar(percentage): length = 25 bar_length = int(length * percentage)
print "%sCount: %d" % (header, self.count)
print "%sGame Count: %d" % (header, self.count)
def dump(self, indent): if self.count <= 0: print "%sCount: %d" % (header, self.count) return
if self.is_total: print "%sLeft Team Goals Distribution:" % (header) for line in self.dump_score_map(indent, self.left_score_map) : print line print print "%sRight Team Goals Distribution:" % (header) for line in self.dump_score_map(indent, self.right_score_map) : print line print print "%sDiff Goals Distribution:" % (header) for line in self.dump_score_map(indent, self.diff_score_map) : print line print print
print "%sLeft Team Goals Distribution:" % (header) for line in self.dump_score_map(indent, self.left_score_map) : print line print print "%sRight Team Goals Distribution:" % (header) for line in self.dump_score_map(indent, self.right_score_map) : print line print print "%sDiff Goals Distribution:" % (header) for line in self.dump_score_map(indent, self.diff_score_map) : print line
def dump(self, indent): if self.count <= 0: print "%sCount: %d" % (header, self.count) return
print "%sCount: %d" % (header, self.count)
print print print "%sGame Count: %d" % (header, self.count)
def dump(self, indent): if self.count <= 0: print "%sCount: %d" % (header, self.count) return
total_game = GameData(True) valid_game = GameData(False)
total_game = GameData()
def dump(self, indent): if self.count <= 0: print "%sCount: %d" % (header, self.count) return
print "No.\tScore\tPoint\tValid";
print "No.\tScore\tPoint";
def dump(self, indent): if self.count <= 0: print "%sCount: %d" % (header, self.count) return
if valid: valid_game.update(index, left_score, right_score, valid)
if not valid: non_valid_game_count += 1
def dump(self, indent): if self.count <= 0: print "%sCount: %d" % (header, self.count) return
indent = 0 if total_game.count > 0 and valid_game.count < total_game.count: indent = 1
print print "Total Game:" total_game.dump(0)
def dump(self, indent): if self.count <= 0: print "%sCount: %d" % (header, self.count) return
print if indent:
if non_valid_game_count:
def dump(self, indent): if self.count <= 0: print "%sCount: %d" % (header, self.count) return
print "Total Game:" total_game.dump(indent) print print "Valid Game:" valid_game.dump(indent) print print "Non Valid Game Count: %d" % (total_game.count - valid_game.count) print "Non Valid Game Rate: %.2f%%" % ((total_game.count - valid_game.count) / float(total_game.count) * 100) else : print total_game.dump(indent)
print "Non Valid Game Count: %d" % (non_valid_game_count) print "Non Valid Game Rate: %.2f%%" % (non_valid_game_count / float(total_game.count) * 100)
def dump(self, indent): if self.count <= 0: print "%sCount: %d" % (header, self.count) return
bar_length = length * percentage
bar_length = int(length * percentage)
def bar(percentage): length = 25 bar_length = length * percentage
if sub > 4:
if sub >= 5:
def update(self, index, left_score, rigt_score, valid): global g_max_sub
line.face = Face.MONOSPACE
def html(line): string = "" line.face = Face.MONOSPACE if line.color == Color.RED: string += "<font color=Red>" elif line.color == Color.ORANGE: string += "<font color=Orange>" elif line.color == Color.GREEN: string += "<font color=Green>" elif line.color == Color.BLUE: string += "<font color=Blue>" elif line.color == Color.PURPLE: string += "<font color=Purple>" if line.face == Face.MONOSPACE: string += "<font face=Monospace>" string += line.string.replace(" ", "&nbsp;") if line.face != Face.NORMAL: string += "</font>" if line.color != Color.NONE: string += "</font>" return string + "<br />"
total_game = GameData()
game = GameData()
def dump(self, indent): if self.count <= 0: print "%sGame Count: %d" % (header, self.count) return
print total_game.update(index, left_score, right_score, valid)
print game.update(index, left_score, right_score, valid)
def dump(self, indent): if self.count <= 0: print "%sGame Count: %d" % (header, self.count) return
if total_game.count <= 0:
if game.count <= 0:
def dump(self, indent): if self.count <= 0: print "%sGame Count: %d" % (header, self.count) return
print "Total Game:" total_game.dump(0)
game.dump(0)
def dump(self, indent): if self.count <= 0: print "%sGame Count: %d" % (header, self.count) return
print "Non Valid Game Rate: %.2f%%" % (non_valid_game_count / float(total_game.count) * 100)
print "Non Valid Game Rate: %.2f%%" % (non_valid_game_count / float(game.count) * 100)
def dump(self, indent): if self.count <= 0: print "%sGame Count: %d" % (header, self.count) return
while len(percentage_string) <= 6:
while len(percentage_string) < 6:
def bar(percentage): length = 25 bar_length = int(length * percentage)
line = "%s [" % (percentage_string)
line = "["
def bar(percentage): length = 25 bar_length = int(length * percentage)
lines.append("%s%3d: %s" % (header, score, bar(score_map[score] / float(self.count))))
lines.append("%s%3d:%s%s" % (header, score, gen_indent(1), bar(score_map[score] / float(self.count))))
def bar(percentage): length = 25 bar_length = int(length * percentage)
header = "\033[01;33m"
header = "\033[01;33m\n"
def update(self, index, left_score, rigt_score, valid): global g_max_sub
header = "\033[01;32m"
header = "\033[01;32m\n"
def update(self, index, left_score, rigt_score, valid): global g_max_sub
length = 25
length = 33
def bar(percentage): length = 25 bar_length = int(length * percentage)
str(timedelta(seconds = self.time)))
str(datetime.timedelta(seconds = self.time)))
def __unicode__(self): return "%s's %s on %s, %.1f km, %s" % \ (self.owner.get_full_name(), str(self.activity), self.date.strftime('%Y-%m-%d'), self.distance, str(timedelta(seconds = self.time)))
return int(h & (2**32 - 1))
return int(h & (2**31 - 1))
def _hash(clss, track, positions): h = hash(track.name) \ * 37 + hash(track.date) for p in positions[::50]: h = h + 37 * hash(p.latitude) \ + 37 * hash(p.longitude) \ + 37 * hash(p.time) return int(h & (2**32 - 1))
try: if request.method == 'POST': post_data = request.raw_post_data.decode('utf-8') data = json.loads(post_data) track = Track.objects.get(id=data['track']) if (datetime.datetime.now() - track.created_time).days > 0: return HttpResponse('Track is older than one day and closed for reporting.', status = 400) for pos_doc in data['positions']: p = Position(latitude = pos_doc['lat'], \ longitude = pos_doc['lat'], \ altitude = pos_doc['lat'], \ time = datetime.datetime.fromtimestamp(pos_doc['time'] / 1000), \ track = track) p.save()
if request.method == 'POST': post_data = request.raw_post_data.decode('utf-8') data = json.loads(post_data) track = Track.objects.get(id=data['track']) if (datetime.datetime.now() - track.created_time).days > 0: return HttpResponse('Track is older than one day and closed for reporting.', status = 400) for pos_doc in data['positions']: p = Position(latitude = pos_doc['lat'], \ longitude = pos_doc['lat'], \ altitude = pos_doc['lat'], \ time = datetime.datetime.fromtimestamp(pos_doc['time'] / 1000), \ track = track) p.save()
def report(request): try: if request.method == 'POST': post_data = request.raw_post_data.decode('utf-8') data = json.loads(post_data) track = Track.objects.get(id=data['track']) if (datetime.datetime.now() - track.created_time).days > 0: return HttpResponse('Track is older than one day and closed for reporting.', status = 400) for pos_doc in data['positions']: p = Position(latitude = pos_doc['lat'], \ longitude = pos_doc['lat'], \ altitude = pos_doc['lat'], \ time = datetime.datetime.fromtimestamp(pos_doc['time'] / 1000), \ track = track) p.save() return HttpResponse(status = 200) else: return HttpResponse("Only POST allowed.", status = 400) except Exception, e: print e raise e
return HttpResponse(status = 200) else: return HttpResponse("Only POST allowed.", status = 400) except Exception, e: print e raise e
return HttpResponse(status = 200) else: return HttpResponse("Only POST allowed.", status = 400)
def report(request): try: if request.method == 'POST': post_data = request.raw_post_data.decode('utf-8') data = json.loads(post_data) track = Track.objects.get(id=data['track']) if (datetime.datetime.now() - track.created_time).days > 0: return HttpResponse('Track is older than one day and closed for reporting.', status = 400) for pos_doc in data['positions']: p = Position(latitude = pos_doc['lat'], \ longitude = pos_doc['lat'], \ altitude = pos_doc['lat'], \ time = datetime.datetime.fromtimestamp(pos_doc['time'] / 1000), \ track = track) p.save() return HttpResponse(status = 200) else: return HttpResponse("Only POST allowed.", status = 400) except Exception, e: print e raise e
if (datetime.now() - track.created_time).days > 0:
if (datetime.datetime.now() - track.created_time).days > 0:
def report(request): try: if request.method == 'POST': post_data = request.raw_post_data.decode('utf-8') data = json.loads(post_data) track = Track.objects.get(id=data['track']) if (datetime.now() - track.created_time).days > 0: return HttpResponse('Track is older than one day and closed for reporting.', status = 400) for pos_doc in data['positions']: p = Position(latitude = pos_doc['lat'], \ longitude = pos_doc['lat'], \ altitude = pos_doc['lat'], \ time = datetime.datetime.fromtimestamp(pos_doc['time'] / 1000), \ track = track) p.save() return HttpResponse(status = 200) else: return HttpResponse("Only POST allowed.", status = 400) except Exception, e: print e raise e
pace.append(dt / ds) int_dist.append(s)
if ds > 0: pace.append(dt / ds) int_dist.append(s)
def get_pace_chart_url(self, width, height): pace = [] int_dist = [] s = 0 last_p = None for p in self.positions(): if last_p != None: ds = distance.distance((p.latitude, p.longitude), \ (last_p.latitude, last_p.longitude)).kilometers s = s + int(ds * 1000) dt = (p.time - last_p.time).seconds pace.append(dt / ds) int_dist.append(s) last_p = p
t.created_time = datetime.now()
t.created_time = datetime.datetime.now()
def begin_track(request): username = request.REQUEST['user'] password = request.REQUEST['pw'] track_name = request.REQUEST['track'] user = authenticate(username = username, password = password) if user is not None and user.is_active: t = Track() t.name = track_name t.owner = user t.created_time = datetime.now() t.save() return HttpResponse("{'track_id': '%s'}" % (t.id,), status = 200) else: return HttpResponse(status = 401)
bl_cache[lpath] = None
def update_booklist(filename, path, prefix): changed = False if path_to_ext(filename) in self.FORMATS: try: lpath = os.path.join(path, filename).partition(self.normalize_path(prefix))[2] if lpath.startswith(os.sep): lpath = lpath[len(os.sep):] lpath = lpath.replace('\\', '/') idx = bl_cache.get(lpath, None) if idx is not None: if self.update_metadata_item(bl[idx]): #print 'update_metadata_item returned true' changed = True bl_cache[lpath] = None else: #print "adding new book", lpath if bl.add_book(self.book_from_path(prefix, lpath), replace_metadata=False): changed = True except: # Probably a filename encoding error import traceback traceback.print_exc() return changed
for idx in bl_cache.itervalues().reversed():
for idx in sorted(bl_cache.itervalues(), reverse=True):
def update_booklist(filename, path, prefix): changed = False if path_to_ext(filename) in self.FORMATS: try: lpath = os.path.join(path, filename).partition(self.normalize_path(prefix))[2] if lpath.startswith(os.sep): lpath = lpath[len(os.sep):] lpath = lpath.replace('\\', '/') idx = bl_cache.get(lpath, None) if idx is not None: if self.update_metadata_item(bl[idx]): #print 'update_metadata_item returned true' changed = True bl_cache[lpath] = None else: #print "adding new book", lpath if bl.add_book(self.book_from_path(prefix, lpath), replace_metadata=False): changed = True except: # Probably a filename encoding error import traceback traceback.print_exc() return changed
q = ''
def search(self, query, return_matches=False, ignore_search_restriction=False): if not query or not query.strip(): q = '' if not ignore_search_restriction: q = self.search_restriction else: if ignore_search_restriction: q = u'%s' % query else: q = u'%s (%s)' % (self.search_restriction, query) if not q: if return_matches: return list(self._map) # when return_matches, do not update the maps! self._map_filtered = list(self._map) return matches = sorted(self.parse(q)) ans = [id for id in self._map if id in matches] if return_matches: return ans self._map_filtered = ans
if ignore_search_restriction: q = u'%s' % query else:
q = query if not ignore_search_restriction:
def search(self, query, return_matches=False, ignore_search_restriction=False): if not query or not query.strip(): q = '' if not ignore_search_restriction: q = self.search_restriction else: if ignore_search_restriction: q = u'%s' % query else: q = u'%s (%s)' % (self.search_restriction, query) if not q: if return_matches: return list(self._map) # when return_matches, do not update the maps! self._map_filtered = list(self._map) return matches = sorted(self.parse(q)) ans = [id for id in self._map if id in matches] if return_matches: return ans self._map_filtered = ans
if version and version != __version__:
if version and version != __version__ and len(version) < 10:
def run(self): while True: try: br = browser() req = mechanize.Request(URL) req.add_header('CALIBRE_VERSION', __version__) req.add_header('CALIBRE_OS', 'win' if iswindows else 'osx' if isosx else 'oth') req.add_header('CALIBRE_INSTALL_UUID', prefs['installation_uuid']) version = br.open(req).read().strip() if version and version != __version__: self.update_found.emit(version) except: traceback.print_exc() self.sleep(self.INTERVAL)
if loc == MAP['tags'] or loc == MAP['authors']: vals = item[loc].split(',')
if loc in SPLITABLE_FIELDS: vals = item[loc].split(',')
def get_matches(self, location, query): matches = set([]) if query and query.strip(): location = location.lower().strip()
sr = db.prefs.get('cs_restriction', '') if opts.restriction is None \ else opts.restriction
sr = getattr(opts, 'restriction', None) sr = db.prefs.get('cs_restriction', '') if sr is None else sr
def __init__(self, db, opts, embedded=False, show_tracebacks=True): self.db = db for item in self.db: item break self.opts = opts self.embedded = embedded self.state_callback = None self.max_cover_width, self.max_cover_height = \ map(int, self.opts.max_cover.split('x')) path = P('content_server') self.build_time = fromtimestamp(os.stat(path).st_mtime) self.default_cover = open(P('content_server/default_cover.jpg'), 'rb').read() cherrypy.config.update({ 'log.screen' : opts.develop, 'engine.autoreload_on' : opts.develop, 'tools.log_headers.on' : opts.develop, 'checker.on' : opts.develop, 'request.show_tracebacks': show_tracebacks, 'server.socket_host' : listen_on, 'server.socket_port' : opts.port, 'server.socket_timeout' : opts.timeout, #seconds 'server.thread_pool' : opts.thread_pool, # number of threads }) if embedded: cherrypy.config.update({'engine.SIGHUP' : None, 'engine.SIGTERM' : None,}) self.config = {'global': { 'tools.gzip.on' : True, 'tools.gzip.mime_types': ['text/html', 'text/plain', 'text/xml', 'text/javascript', 'text/css'], }} if opts.password: self.config['/'] = { 'tools.digest_auth.on' : True, 'tools.digest_auth.realm' : (_('Password to access your calibre library. Username is ') + opts.username.strip()).encode('ascii', 'replace'), 'tools.digest_auth.users' : {opts.username.strip():opts.password.strip()}, }
try: if ContentType == '6': self.datetime = time.strptime(date, "%Y-%m-%dT%H:%M:%S.%f") else:
if ContentType == '6': self.datetime = time.strptime(date, "%Y-%m-%dT%H:%M:%S.%f") else: try:
def __init__(self, prefix, lpath, title, authors, mime, date, ContentType, thumbnail_name, size=None, other=None):
key = field_metadata.search_term_to_field_key(key.lower())
if key != 'title_sort': key = field_metadata.search_term_to_field_key(key.lower())
def get_value(self, key, args, kwargs): try: key = field_metadata.search_term_to_field_key(key.lower()) b = self.book.get_user_metadata(key, False) if b and b['datatype'] == 'int' and self.book.get(key, 0) == 0: v = '' elif b and b['datatype'] == 'float' and b.get(key, 0.0) == 0.0: v = '' else: ign, v = self.book.format_field(key.lower(), series_with_index=False) if v is None: return '' if v == '': return '' return v except: if DEBUG: traceback.print_exc() return key
pwidth, self.statusbar_height-12)[1:]
pwidth, self.statusbar_height-20)[1:]
def do_layout(self): pixmap = self.pixmap() pwidth, pheight = pixmap.width(), pixmap.height() width, height = fit_image(pwidth, pheight, pwidth, self.statusbar_height-12)[1:] self.setMaximumHeight(height) try: aspect_ratio = pwidth/float(pheight) except ZeroDivisionError: aspect_ratio = 1 self.setMaximumWidth(int(aspect_ratio*self.maximumHeight()))
xml(desc), xml(quote(href)), rstring)
xml(desc), xml(href), rstring)
def item(i): templ = (u'<div title="{4}" class="category-item">' '<div class="category-name">{0}</div><div>{1}</div>' '<div>{2}' '<span class="href">{3}</span></div></div>') rating, rstring = render_rating(i.avg_rating) name = xml(i.name) if datatype == 'rating': name = xml(_('%d stars')%int(i.avg_rating)) id_ = i.id if id_ is None: id_ = hexlify(force_unicode(name).encode('utf-8')) id_ = xml(str(id_)) desc = '' if i.count > 0: desc += '[' + _('%d books')%i.count + ']' href = '/browse/matches/%s/%s'%(category, id_) return templ.format(xml(name), rating, xml(desc), xml(quote(href)), rstring)
.format(xml(x, True), xml(quote(y)), xml(_('Browse books by')),
.format(xml(x, True), xml(y), xml(_('Browse books by')),
def getter(x): return category_meta[x]['name'].lower()
ids = self.db.get_books_for_category(category, cid)
q = category if q == 'news': q = 'tags' ids = self.db.get_books_for_category(q, cid)
def browse_matches(self, category=None, cid=None, list_sort=None): if not cid: raise cherrypy.HTTPError(404, 'invalid category id: %r'%cid) categories = self.categories_cache()
if sort not in ('rating', 'name', 'popularity'): sort = 'name' items.sort(key=lambda x: sort_key(getattr(x, 'sort', x.name)))
def keyg(x): x = getattr(x, 'sort', x.name) if isinstance(x, unicode): return sort_key(x) return x
def browse_sort_categories(self, items, sort): if sort not in ('rating', 'name', 'popularity'): sort = 'name' items.sort(key=lambda x: sort_key(getattr(x, 'sort', x.name))) if sort == 'popularity': items.sort(key=operator.attrgetter('count'), reverse=True) elif sort == 'rating': items.sort(key=operator.attrgetter('avg_rating'), reverse=True) return sort
padding = '%dpx'%amount try: old_padding = unicode(self.javascript('$("body").css("padding-bottom")').toString()) except: old_padding = ''
body = self.mainFrame().documentElement().findFirst('body') if body.isNull(): return old_padding = unicode(body.styleProperty('padding-bottom', body.ComputedStyle)).strip() padding = u'%dpx'%amount
def set_bottom_padding(self, amount): padding = '%dpx'%amount try: old_padding = unicode(self.javascript('$("body").css("padding-bottom")').toString()) except: old_padding = '' if old_padding != padding: self.javascript('$("body").css("padding-bottom", "%s")' % padding)
self.javascript('$("body").css("padding-bottom", "%s")' % padding)
body.setStyleProperty('padding-bottom', padding + ' !important')
def set_bottom_padding(self, amount): padding = '%dpx'%amount try: old_padding = unicode(self.javascript('$("body").css("padding-bottom")').toString()) except: old_padding = '' if old_padding != padding: self.javascript('$("body").css("padding-bottom", "%s")' % padding)
pass
def start(self): self.pi.startAnimation() pass
pass
def stop(self): self.pi.stopAnimation() pass
def check_for_errors(root):
class ISBNNotFound(ValueError): pass def check_for_errors(root, isbn):
def check_for_errors(root): err = root.find('.//'+AWS('Error')) if err is not None: raise Exception('Failed to get metadata with error: '\ + etree.tostring(err, method='text', pretty_print=True, encoding=unicode))
+ etree.tostring(err, method='text', pretty_print=True, encoding=unicode))
+ text)
def check_for_errors(root): err = root.find('.//'+AWS('Error')) if err is not None: raise Exception('Failed to get metadata with error: '\ + etree.tostring(err, method='text', pretty_print=True, encoding=unicode))
check_for_errors(root)
try: check_for_errors(root, isbn) except ISBNNotFound: return mi
def get_social_metadata(title, authors, publisher, isbn): mi = MetaInformation(title, authors) if isbn: br = browser() response_xml = br.open('http://status.calibre-ebook.com/aws/metadata/'+isbn).read() root = etree.fromstring(response_xml) check_for_errors(root) mi.title = root.findtext('.//'+AWS('Title')) authors = [x.text for x in root.findall('.//'+AWS('Author'))] if authors: mi.authors = [] for x in authors: mi.authors.extend(string_to_authors(x)) mi.publisher = root.findtext('.//'+AWS('Publisher')) try: d = root.findtext('.//'+AWS('PublicationDate')) if d: default = utcnow().replace(day=15) d = parse_date(d[0].text, assume_utc=True, default=default) mi.pubdate = d except: pass try: rating = float(root.findtext('.//'+AWS('AverageRating'))) num_of_reviews = int(root.findtext('.//'+AWS('TotalReviews'))) if num_of_reviews > 4 and rating > 0 and rating < 5: mi.rating = rating except: pass tags = [x.text for x in root.findall('.//%s/%s'%(AWS('Subjects'), AWS('Subject')))] if tags: mi.tags = [] for x in tags: mi.tags.extend([y.strip() for y in x.split('/')]) mi.tags = [x.replace(',', ';') for x in mi.tags] comments = root.find('.//%s/%s'%(AWS('EditorialReview'), AWS('Content'))) if comments is not None: mi.comments = etree.tostring(comments, method='text', encoding=unicode) mi.comments = re.sub('<([pP]|DIV)>', '\n\n', mi.comments) mi.comments = re.sub('</?[iI]>', '*', mi.comments) mi.comments = re.sub('</?[bB]>', '**', mi.comments) mi.comments = re.sub('<BR>', '\n\n', mi.comments) mi.comments = re.sub('<[^>]+>', '', mi.comments) mi.comments = mi.comments.strip() mi.comments = _('EDITORIAL REVIEW')+':\n\n'+mi.comments return mi
datelastread = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime())
t = (ContentID,) cursor.execute('select DateLastRead from Content where BookID is Null and ContentID = ?', t) result = cursor.fetchone() datelastread = result[0] if result[0] is not None else '1970-01-01T00:00:00'
def update_device_database_collections(self, booklists, collections_attributes, oncard):
c = strcmp(force_unicode(x), force_unicode(y))
c = strcmp(unicode(force_unicode(x)), unicode(force_unicode(y)))
def none_cmp(xx, yy): x = xx[1] y = yy[1] if x is None and y is None: # No sort_key needed here, because defaults are ascii return cmp(xx[2], yy[2]) if x is None: return 1 if y is None: return -1 if isinstance(x, (unicode, str)): c = strcmp(force_unicode(x), force_unicode(y)) else: c = cmp(x, y) if c != 0: return c # same as above -- no sort_key needed here return cmp(xx[2], yy[2])
flist.append({'filename':filename, 'path': path})
flist.append({'filename':unicode(filename), 'path':unicode(path)})
def update_booklist(filename, path, prefix): changed = False if path_to_ext(filename) in self.FORMATS: try: lpath = os.path.join(path, filename).partition(self.normalize_path(prefix))[2] if lpath.startswith(os.sep): lpath = lpath[len(os.sep):] lpath = lpath.replace('\\', '/') idx = bl_cache.get(lpath, None) if idx is not None: bl_cache[lpath] = None if self.update_metadata_item(bl[idx]): #print 'update_metadata_item returned true' changed = True else: if bl.add_book(self.book_from_path(prefix, lpath), replace_metadata=False): changed = True except: # Probably a filename encoding error import traceback traceback.print_exc() return changed
changed = update_booklist(filename, ebook_dir, prefix)
changed = update_booklist(unicode(filename), ebook_dir, prefix)
def update_booklist(filename, path, prefix): changed = False if path_to_ext(filename) in self.FORMATS: try: lpath = os.path.join(path, filename).partition(self.normalize_path(prefix))[2] if lpath.startswith(os.sep): lpath = lpath[len(os.sep):] lpath = lpath.replace('\\', '/') idx = bl_cache.get(lpath, None) if idx is not None: bl_cache[lpath] = None if self.update_metadata_item(bl[idx]): #print 'update_metadata_item returned true' changed = True else: if bl.add_book(self.book_from_path(prefix, lpath), replace_metadata=False): changed = True except: # Probably a filename encoding error import traceback traceback.print_exc() return changed
path = location[0]
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() path = location[0] blist = 2 if location[1] == 'cardb' else 1 if location[1] == 'carda' else 0
if self._main_prefix.find('\\') >= 0: path = path.replace('/', '\\') else: path = path.replace('\\', '/') prefix = self._main_prefix if path.startswith(self._main_prefix) else None
prefix = self._main_prefix if \ path.startswith(self.normalize_path(self._main_prefix)) else None
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() path = location[0] blist = 2 if location[1] == 'cardb' else 1 if location[1] == 'carda' else 0
prefix = self._card_a_prefix if path.startswith(self._card_a_prefix) else None
prefix = self._card_a_prefix if \ path.startswith(self.normalize_path(self._card_a_prefix)) else None
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() path = location[0] blist = 2 if location[1] == 'cardb' else 1 if location[1] == 'carda' else 0
prefix = self._card_b_prefix if path.startswith(self._card_b_prefix) else None
prefix = self._card_b_prefix if \ path.startswith(self.normalize_path(self._card_b_prefix)) else None
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() path = location[0] blist = 2 if location[1] == 'cardb' else 1 if location[1] == 'carda' else 0
return path
return unicode(path)
def normalize_path(cls, path): 'Return path with platform native path separators' if path is None: return None if os.sep == '\\': path = path.replace('/', '\\') else: path = path.replace('\\', '/') return path
p { margin: 0em; text-align: justify }
p { margin: 0em; text-align: justify; text-indent: 1.5em }
def __init__(self, filename_or_stream, log, user_encoding=None, debug=None, try_extra_data_fix=False): self.log = log self.debug = debug self.embedded_mi = None self.base_css_rules = textwrap.dedent(''' blockquote { margin: 0em 0em 0em 2em; text-align: justify }
for line in open('comics.txt', 'rb').read().decode('utf-8').splitlines():
raw = open('comics.txt', 'rb').read().decode('utf-8') raw.lstrip(unicode(codecs.BOM_UTF8, "utf8" )) for line in raw.splitlines():
def get_comics_from_collection(self, stream): from calibre.libunzip import extract as zipextract tdir = PersistentTemporaryDirectory('_comic_collection') zipextract(stream, tdir) comics = [] with CurrentDir(tdir): if not os.path.exists('comics.txt'): raise ValueError('%s is not a valid comic collection' %stream.name) for line in open('comics.txt', 'rb').read().decode('utf-8').splitlines(): line = line.strip() if not line: continue fname, title = line.partition(':')[0], line.partition(':')[-1] fname = os.path.join(tdir, *fname.split('/')) if not title: title = os.path.basename(fname).rpartition('.')[0] if os.access(fname, os.R_OK): comics.append([title, fname]) if not comics: raise ValueError('%s has no comics'%stream.name) return comics
percent = (margin - indent) / style['width'] cssdict['margin-left'] = "%d%%" % (percent * 100)
try: percent = (margin - indent) / style['width'] cssdict['margin-left'] = "%d%%" % (percent * 100) except ZeroDivisionError: pass
def force_int(raw): return int(re.search(r'([0-9+-]+)', raw).group(1))
executables=self.staging_bindir,
executables=self.bindir,
def write_template(self, name, mod, func): template = COMPLETE_TEMPLATE if name == 'calibre-complete' else TEMPLATE script = template.format( module=mod, func=func, path=self.libdir, resources=self.sharedir, executables=self.staging_bindir, extensions=self.j(self.libdir, 'calibre', 'plugins')) path = self.j(self.staging_bindir, name) if not os.path.exists(self.staging_bindir): os.makedirs(self.staging_bindir) self.info('Installing binary:', path) open(path, 'wb').write(script) os.chmod(path, self.MODE) self.manifest.append(path)
pml = re.sub(r'(?<=\\x)(?P<text>.*?)(?=\\x)', lambda match: '="%s"%s' % (self.strip_pml(match.group('text')), match.group('text')), pml) pml = re.sub(r'(?<=\\X[0-4])(?P<text>.*?)(?=\\X[0-4])', lambda match: '="%s"%s' % (self.strip_pml(match.group('text')), match.group('text')), pml)
def prepare_pml(self, pml): # Remove comments pml = re.sub(r'(?mus)\\v(?P<text>.*?)\\v', '', pml)
if self.state['k'][0]: text = c.upper() else: text = c
text = c
def parse_pml(self, pml, file_name=''): pml = self.prepare_pml(pml) output = []
print 222, paths
def __add_filesystem_book(self, paths, allow_device=True): print 222, paths if isinstance(paths, basestring): paths = [paths] books = [path for path in map(os.path.abspath, paths) if os.access(path, os.R_OK)]
w.setStyleSheet('QToolButton { margin-right: 20px; min-width: 100px }')
def __init__(self, name, plugins, parent=None): QWidget.__init__(self, parent) self._layout = QVBoxLayout() self.setLayout(self._layout) self.label = QLabel(name) self.sep = QFrame(self) self.bf = QFont() self.bf.setBold(True) self.label.setFont(self.bf) self.sep.setFrameShape(QFrame.HLine) self._layout.addWidget(self.label) self._layout.addWidget(self.sep)
self.help_state = True
def clear_to_help(self): self.search.emit('') self._in_a_search = False self.setEditText(self.help_text) if self.timer is not None: # Turn off any timers that got started in setEditText self.killTimer(self.timer) self.timer = None self.line_edit.home(False) self.help_state = True self.line_edit.setStyleSheet( 'QLineEdit { color: gray; background-color: %s; }' % self.normal_background) self.emit(SIGNAL('cleared()'))
opf = None for f in walk(u'.'): if f.lower().endswith('.opf') and '__MACOSX' not in f and \ not os.path.basename(f).startswith('.'): opf = os.path.abspath(f) break
opf = self.find_opf() if opf is None: for f in walk(u'.'): if f.lower().endswith('.opf') and '__MACOSX' not in f and \ not os.path.basename(f).startswith('.'): opf = os.path.abspath(f) break
def convert(self, stream, options, file_ext, log, accelerators): from calibre.utils.zipfile import ZipFile from calibre import walk from calibre.ebooks import DRMError from calibre.ebooks.metadata.opf2 import OPF zf = ZipFile(stream) zf.extractall(os.getcwd()) encfile = os.path.abspath(os.path.join('META-INF', 'encryption.xml')) opf = None for f in walk(u'.'): if f.lower().endswith('.opf') and '__MACOSX' not in f and \ not os.path.basename(f).startswith('.'): opf = os.path.abspath(f) break path = getattr(stream, 'name', 'stream')
self.search('', return_matches=False, ignore_search_restriction=False)
self.search('', return_matches=False)
def refresh(self, db, field=None, ascending=True): temp = db.conn.get('SELECT * FROM meta2') self._data = list(itertools.repeat(None, temp[-1][0]+2)) if temp else [] for r in temp: self._data[r[0]] = r for item in self._data: if item is not None: item.append(db.has_cover(item[0], index_is_id=True)) item.append(db.book_on_device_string(item[0])) self._map = [i[0] for i in self._data if i is not None] if field is not None: self.sort(field, ascending) self._map_filtered = list(self._map) if self.search_restriction: self.search('', return_matches=False, ignore_search_restriction=False)
path = urlunparse(('', '', url.path, url.params, url.query, ''))
path = url.path isabs = False if iswindows and path.startswith('/'): path = path[1:] isabs = True path = urlunparse(('', '', path, url.params, url.query, ''))
def url_to_local_path(cls, url, base): path = urlunparse(('', '', url.path, url.params, url.query, '')) path = unquote(path) if os.path.isabs(path): return path return os.path.abspath(os.path.join(base, path))
if os.path.isabs(path):
if isabs or os.path.isabs(path):
def url_to_local_path(cls, url, base): path = urlunparse(('', '', url.path, url.params, url.query, '')) path = unquote(path) if os.path.isabs(path): return path return os.path.abspath(os.path.join(base, path))
link = self.urlnormalize(link_) link, frag = self.urldefrag(link) link = unquote(link).replace('/', os.sep) if not link.strip():
if not isinstance(link_, unicode): try: link_ = link_.decode('utf-8', 'error') except: self.log.warn('Failed to decode link %r. Ignoring'%link_) return link_ try: l = Link(link_, base if base else os.path.getcwdu()) except: self.log.exception('Failed to process link: %r'%link_) return link_ if l.path is None: return link_ link = l.path.replace('/', os.sep).strip() frag = l.fragment if not link:
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_ try: if base and not os.path.isabs(link): link = os.path.join(base, link) 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 self.is_case_sensitive(tempfile.gettempdir()): 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
if isinstance(self.dbpath, unicode):
if isinstance(self.dbpath, unicode) and not iswindows:
def __init__(self, library_path, row_factory=False): self.field_metadata = FieldMetadata() if not os.path.exists(library_path): os.makedirs(library_path) self.listeners = set([]) self.library_path = os.path.abspath(library_path) self.row_factory = row_factory self.dbpath = os.path.join(library_path, 'metadata.db') self.dbpath = os.environ.get('CALIBRE_OVERRIDE_DATABASE_PATH', self.dbpath) if isinstance(self.dbpath, unicode): self.dbpath = self.dbpath.encode(filesystem_encoding)
if not hundredsComponent and tensComponent:
elif not hundredsComponent and tensComponent:
def stringFromInt(self, intToTranslate): # Convert intToTranslate to string # intToTranslate is a three-digit number