bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def RietveldSetup(ui, repo): global defaultcc, upload_options, rpc, server, server_url_base, force_google_account, verbosity, contributors # Read repository-specific options from lib/codereview/codereview.cfg try: f = open(repo.root + '/lib/codereview/codereview.cfg') for line in f: if line.startswith('defaultcc: '): ...
def RietveldSetup(ui, repo): global defaultcc, upload_options, rpc, server, server_url_base, force_google_account, verbosity, contributors # Read repository-specific options from lib/codereview/codereview.cfg try: f = open(repo.root + '/lib/codereview/codereview.cfg') for line in f: if line.startswith('defaultcc: '): ...
450,600
def start_status_thread(): StatusThread().start()
def start_status_thread(): t = StatusThread() t.setDaemon(True) t.start()
450,601
def go_complex_writer(self, name, void): func_name = self.c_request_name param_fields = [] wire_fields = [] for field in self.fields: if field.visible: # _len is taken from the list directly if not field.field_name.endswith("_len"): # The field should appear as a call parameter param_fields.append(field) if field.wire...
def go_complex_writer(self, name, void): func_name = self.c_request_name param_fields = [] wire_fields = [] for field in self.fields: if field.visible: # _len is taken from the list directly if not field.field_name.endswith("_len"): # The field should appear as a call parameter param_fields.append(field) if field.wire...
450,602
def go_complex_writer(self, name, void): func_name = self.c_request_name param_fields = [] wire_fields = [] for field in self.fields: if field.visible: # _len is taken from the list directly if not field.field_name.endswith("_len"): # The field should appear as a call parameter param_fields.append(field) if field.wire...
def go_complex_writer(self, name, void): func_name = self.c_request_name param_fields = [] wire_fields = [] for field in self.fields: if field.visible: # _len is taken from the list directly if not field.field_name.endswith("_len"): # The field should appear as a call parameter param_fields.append(field) if field.wire...
450,603
def go_complex_writer(self, name, void): func_name = self.c_request_name param_fields = [] wire_fields = [] for field in self.fields: if field.visible: # _len is taken from the list directly if not field.field_name.endswith("_len"): # The field should appear as a call parameter param_fields.append(field) if field.wire...
def go_complex_writer(self, name, void): func_name = self.c_request_name param_fields = [] wire_fields = [] for field in self.fields: if field.visible: # _len is taken from the list directly if not field.field_name.endswith("_len"): # The field should appear as a call parameter param_fields.append(field) if field.wire...
450,604
def go_close(self): ''' Exported function that handles module close. ''' global outfile if len(eventlist) > 0: dumpeventlist() if len(errorlist) > 0: dumperrorlist() if not outfile: outfile = '%s.go' % _ns.header gofile = open(outfile, 'w') for line in golines: gofile.write(line) gofile.write('\n') gofile.close()
def go_close(self): ''' Exported function that handles module close. ''' global outfile if len(eventlist) > 0: dumpeventlist() if len(errorlist) > 0: dumperrorlist() if not outfile: outfile = '%s.go' % _ns.header gofile = open(outfile, 'w') for line in golines: gofile.write(line) gofile.write('\n') gofile.close()
450,605
def compute(self, num): benchmarks, builders = benchmark_list() # Build empty grid, to be filled in. rows = [{"name": bm, "builds": [{"url": ""} for b in builders]} for bm in benchmarks]
def compute(self, num): benchmarks, builders = benchmark_list() # Build empty grid, to be filled in. rows = [{"name": bm, "builds": [{"url": ""} for b in builders]} for bm in benchmarks]
450,606
def compute(self, num): benchmarks, builders = benchmark_list() # Build empty grid, to be filled in. rows = [{"name": bm, "builds": [{"url": ""} for b in builders]} for bm in benchmarks]
def compute(self, num): benchmarks, builders = benchmark_list() # Build empty grid, to be filled in. rows = [{"name": bm, "builds": [{"url": ""} for b in builders]} for bm in benchmarks]
450,607
def benchmark_sparkline(ns): valid = [x for x in ns if x >= 0] if not valid: return "" m = max(max(valid), 2*sum(valid)/len(valid)) # Encoding is 0-61, which is fine enough granularity for our tiny graphs. _ means missing. encoding = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" s = ''.join([x < 0 a...
def benchmark_sparkline(ns): valid = [x for x in ns if x >= 0] if not valid: return "" m = max(max(valid), 2*sum(valid)/len(valid)) # Encoding is 0-61, which is fine enough granularity for our tiny graphs. _ means missing. encoding = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" s = ''.join([x < 0 a...
450,608
def benchmark_list(): q = BenchmarkResults.all() q.order('__key__') q.filter('builder = ', u'darwin-amd64') benchmarks = [r.benchmark for r in q.fetch(1000)] q = BenchmarkResults.all() q.order('__key__') q.filter('benchmark =', u'math_test.BenchmarkSqrt') builders = [r.builder for r in q.fetch(100)] return benchmarks...
def benchmark_list(): q = BenchmarkResults.all() q.order('__key__') q.filter('builder = ', u'darwin-amd64') benchmarks = [r.benchmark for r in q] q = BenchmarkResults.all() q.order('__key__') q.filter('benchmark =', u'math_test.BenchmarkSqrt') builders = [r.builder for r in q.fetch(100)] return benchmarks, builders
450,609
def benchmark_list(): q = BenchmarkResults.all() q.order('__key__') q.filter('builder = ', u'darwin-amd64') benchmarks = [r.benchmark for r in q.fetch(1000)] q = BenchmarkResults.all() q.order('__key__') q.filter('benchmark =', u'math_test.BenchmarkSqrt') builders = [r.builder for r in q.fetch(100)] return benchmarks...
def benchmark_list(): q = BenchmarkResults.all() q.order('__key__') q.filter('builder = ', u'darwin-amd64') benchmarks = [r.benchmark for r in q.fetch(1000)] q = BenchmarkResults.all() q.order('__key__') q.filter('benchmark =', u'math_test.BenchmarkSqrt') builders = [r.builder for r in q.fetch(20)] return benchmarks,...
450,610
def write(self, s): self.output += s
def write(self, s): self.output += s
450,611
def getremote(ui, repo, opts): # save $http_proxy; creating the HTTP repo object will # delete it in an attempt to "help" proxy = os.environ.get('http_proxy') source, _, _ = hg.parseurl(ui.expandpath("default"), None) other = hg.repository(cmdutil.remoteui(repo, opts), source) if proxy is not None: os.environ['http_pro...
def getremote(ui, repo, opts): # save $http_proxy; creating the HTTP repo object will # delete it in an attempt to "help" proxy = os.environ.get('http_proxy') source = hg.parseurl(ui.expandpath("default"), None)[0] other = hg.repository(cmdutil.remoteui(repo, opts), source) if proxy is not None: os.environ['http_proxy'...
450,612
def IsRietveldSubmitted(ui, clname, hex): feed = XMLGet(ui, "/rss/issue/" + clname) if feed is None: return False for sum in feed.findall("{http://www.w3.org/2005/Atom}entry/{http://www.w3.org/2005/Atom}summary"): text = sum.findtext("", None).strip() m = re.match('\*\*\* Submitted as [^*]*?([0-9a-f]+) \*\*\*', text) i...
def IsRietveldSubmitted(ui, clname, hex): feed = XMLGet(ui, "/rss/issue/" + clname) if feed is None: return False for sum in feed.findall("{http://www.w3.org/2005/Atom}entry/{http://www.w3.org/2005/Atom}summary"): text = sum.text.strip() m = re.match('\*\*\* Submitted as [^*]*?([0-9a-f]+) \*\*\*', text) if m is not Non...
450,613
def DownloadCL(ui, repo, clname): set_status("downloading CL " + clname) cl, err = LoadCL(ui, repo, clname) if err != "": return None, None, "error loading CL %s: %s" % (clname, ExceptionDetail()) # Grab RSS feed to learn about CL feed = XMLGet(ui, "/rss/issue/" + clname) if feed is None: return None, None, "cannot do...
def DownloadCL(ui, repo, clname): set_status("downloading CL " + clname) cl, err = LoadCL(ui, repo, clname) if err != "": return None, None, "error loading CL %s: %s" % (clname, ExceptionDetail()) # Grab RSS feed to learn about CL feed = XMLGet(ui, "/rss/issue/" + clname) if feed is None: return None, None, "cannot do...
450,614
def get(self): benchmark = self.request.path[12:] minr, maxr, bybuilder = benchmark_data(benchmark) minhash = node(minr).node maxhash = node(maxr).node
def get(self): benchmark = self.request.path[12:] minr, maxr, bybuilder = benchmark_data(benchmark) minhash = node(minr).node maxhash = node(maxr).node
450,615
def GetBaseFile(self, filename): set_status("inspecting " + filename) # "hg status" and "hg cat" both take a path relative to the current subdir # rather than to the repo root, but "hg diff" has given us the full path # to the repo root. base_content = "" new_content = None is_binary = False oldrelpath = relpath = self...
def GetBaseFile(self, filename): set_status("inspecting " + filename) # "hg status" and "hg cat" both take a path relative to the current subdir # rather than to the repo root, but "hg diff" has given us the full path # to the repo root. base_content = "" new_content = None is_binary = False oldrelpath = relpath = self...
450,616
def get(self): self.response.headers['Content-Type'] = 'text/html; charset=utf-8'
def get(self): self.response.headers['Content-Type'] = 'text/html; charset=utf-8'
450,617
def get(self): self.response.headers['Content-Type'] = 'text/html; charset=utf-8'
def get(self): self.response.headers['Content-Type'] = 'text/html; charset=utf-8'
450,618
def get(self): q = Benchmark.all() bs = q.fetch(10000)
def get(self): q = Benchmark.all() bs = q.fetch(10000)
450,619
def get(self): q = Benchmark.all() bs = q.fetch(10000)
def get(self): q = Benchmark.all() bs = q.fetch(10000)
450,620
def get_string(i): l, = struct.unpack('>H', i[:2]) s = i[2:2+l] if len(s) != l: return None, None return s, i[2+l:]
def get_string(i): l, = struct.unpack('>H', i[:2]) s = i[2:2+l] if len(s) != l: return None, None return s, i[2+l:]
450,621
def get_string(i): l, = struct.unpack('>H', i[:2]) s = i[2:2+l] if len(s) != l: return None, None return s, i[2+l:]
defkey = "bench(%d)" % n.num memcache.delete(key) get_string(i):key = "bench(%d)" % n.num memcache.delete(key) l,key = "bench(%d)" % n.num memcache.delete(key) =key = "bench(%d)" % n.num memcache.delete(key) struct.unpack('>H',key = "bench(%d)" % n.num memcache.delete(key) i[:2])key = "bench(%d)" % n.num memcache.delet...
450,622
def get(self): self.response.headers['Content-Type'] = 'application/json; charset=utf-8' benchmark = self.request.path[12:].decode('hex').encode('base64')
def get(self): self.response.headers['Content-Type'] = 'application/json; charset=utf-8' benchmark = self.request.path[12:].decode('hex').encode('base64')
450,623
def get(self): self.response.headers['Content-Type'] = 'application/json; charset=utf-8' benchmark = self.request.path[12:].decode('hex').encode('base64')
def get(self): self.response.headers['Content-Type'] = 'application/json; charset=utf-8' benchmark = self.request.path[12:].decode('hex').encode('base64')
450,624
def get(self): self.response.headers['Content-Type'] = 'application/json; charset=utf-8' benchmark = self.request.path[12:].decode('hex').encode('base64')
def get(self): self.response.headers['Content-Type'] = 'application/json; charset=utf-8' benchmark = self.request.path[12:].decode('hex').encode('base64')
450,625
def get(self): self.response.headers['Content-Type'] = 'application/json; charset=utf-8' benchmark = self.request.path[12:].decode('hex').encode('base64')
def get(self): self.response.headers['Content-Type'] = 'application/json; charset=utf-8' benchmark = self.request.path[12:].decode('hex').encode('base64')
450,626
def get(self): self.response.headers['Content-Type'] = 'application/json; charset=utf-8' benchmark = self.request.path[12:].decode('hex').encode('base64')
def get(self): self.response.headers['Content-Type'] = 'application/json; charset=utf-8' benchmark = self.request.path[12:].decode('hex').encode('base64')
450,627
def get(self): self.response.headers['Content-Type'] = 'application/json; charset=utf-8' benchmark = self.request.path[12:].decode('hex').encode('base64')
def get(self): self.response.headers['Content-Type'] = 'application/json; charset=utf-8' benchmark = self.request.path[12:].decode('hex').encode('base64')
450,628
def toRev(c): b = { "node": c.node, "user": toUsername(c.user), "date": dateToShortStr(c.date), "desc": c.desc} b['builds'] = [parseBuild(build) for build in c.builds] return b
def toRev(c): b = nodeInfo(c) b['builds'] = [parseBuild(build) for build in c.builds] return b
450,629
def list(self, additional_data={}): data = memcache.get('view-project-data') admin = users.is_current_user_admin() if admin or not data: projects = Project.all().order('category').order('name') if not admin: projects = projects.filter('approved =', True) projects = list(projects)
def list(self, additional_data={}): cache_key = 'view-project-data' tag = self.request.get('tag', None) if tag: cache_key += '-'+tag data = memcache.get(cache_key) admin = users.is_current_user_admin() if admin or not data: projects = Project.all().order('category').order('name') if not admin: projects = projects.filte...
450,630
def list(self, additional_data={}): data = memcache.get('view-project-data') admin = users.is_current_user_admin() if admin or not data: projects = Project.all().order('category').order('name') if not admin: projects = projects.filter('approved =', True) projects = list(projects)
def list(self, additional_data={}): data = memcache.get('view-project-data') admin = users.is_current_user_admin() if admin or not data: projects = Project.all().order('category').order('name') if not admin: projects = projects.filter('approved =', True) projects = list(projects)
450,631
def list(self, additional_data={}): data = memcache.get('view-project-data') admin = users.is_current_user_admin() if admin or not data: projects = Project.all().order('category').order('name') if not admin: projects = projects.filter('approved =', True) projects = list(projects)
def list(self, additional_data={}): data = memcache.get('view-project-data') admin = users.is_current_user_admin() if admin or not data: projects = Project.all().order('category').order('name') if not admin: projects = projects.filter('approved =', True) projects = list(projects)
450,632
def getremote(ui, repo, opts): # save $http_proxy; creating the HTTP repo object will # delete it in an attempt to "help" proxy = os.environ.get('http_proxy') source = hg.parseurl(ui.expandpath("default"), None)[0] other = hg.repository(cmdutil.remoteui(repo, opts), source) if proxy is not None: os.environ['http_proxy'...
def getremote(ui, repo, opts): # save $http_proxy; creating the HTTP repo object will # delete it in an attempt to "help" proxy = os.environ.get('http_proxy') source = hg.parseurl(ui.expandpath("default"), None)[0] try: remoteui = hg.remoteui except: remoteui = cmdutil.remoteui other = hg.repository(remoteui(repo, opts...
450,633
def __init__(self, options, repo_dir): super(MercurialVCS, self).__init__(options) # Absolute path to repository (we can be in a subdir) self.repo_dir = os.path.normpath(repo_dir) # Compute the subdir cwd = os.path.normpath(os.getcwd()) assert cwd.startswith(self.repo_dir) self.subdir = cwd[len(self.repo_dir):].lstrip(...
def __init__(self, options, repo_dir): super(MercurialVCS, self).__init__(options) # Absolute path to repository (we can be in a subdir) self.repo_dir = os.path.normpath(repo_dir) # Compute the subdir cwd = os.path.normpath(os.getcwd()) assert cwd.startswith(self.repo_dir) self.subdir = cwd[len(self.repo_dir):].lstrip(...
450,634
def EditCL(ui, repo, cl): s = cl.EditorText() while True: s = ui.edit(s, ui.username()) clx, line, err = ParseCL(s, cl.name) if err != '': if ui.prompt("error parsing change list: line %d: %s\nre-edit (y/n)?" % (line, err), ["&yes", "&no"], "y") == "n": return "change list not modified" continue cl.desc = clx.desc; cl....
def EditCL(ui, repo, cl): s = cl.EditorText() while True: s = ui.edit(s, ui.username()) clx, line, err = ParseCL(s, cl.name) if err != '': if not promptyesno(ui, "error parsing change list: line %d: %s\nre-edit (y/n)?" % (line, err)): return "change list not modified" continue cl.desc = clx.desc; cl.reviewer = clx.revi...
450,635
def EditCL(ui, repo, cl): s = cl.EditorText() while True: s = ui.edit(s, ui.username()) clx, line, err = ParseCL(s, cl.name) if err != '': if ui.prompt("error parsing change list: line %d: %s\nre-edit (y/n)?" % (line, err), ["&yes", "&no"], "y") == "n": return "change list not modified" continue cl.desc = clx.desc; cl....
def EditCL(ui, repo, cl): s = cl.EditorText() while True: s = ui.edit(s, ui.username()) clx, line, err = ParseCL(s, cl.name) if err != '': if ui.prompt("error parsing change list: line %d: %s\nre-edit (y/n)?" % (line, err), ["&yes", "&no"], "y") == "n": return "change list not modified" continue cl.desc = clx.desc; cl....
450,636
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)))
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(datetime.timedelta(seconds = self.time)))
450,637
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))
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**31 - 1))
450,638
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.', statu...
def report(request): 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 = 4...
450,639
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.', statu...
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.', statu...
450,640
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) ...
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.', statu...
450,641
def get_track_data(request, year, month, day, number): track = get_track_by_date(int(year), int(month), int(day), int(number)) if track != None: positions = Position.objects.filter(track = track) if len(positions) > 0: duration = positions[len(positions) - 1].time - positions[0].time date = positions[0].time.strftime(...
defget_track_data(request,year,month,day,number):track=get_track_by_date(int(year),int(month),int(day),int(number))iftrack!=None:positions=Position.objects.filter(track=track)iflen(positions)>0:duration=positions[len(positions)-1].time-positions[0].timedate=positions[0].time.strftime('%Y-%m-%d')last_info_point=position...
450,642
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_d...
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 if ds > 0: pace.append(dt ...
450,643
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...
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.datetime.now...
450,644
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 n...
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 n...
450,645
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 n...
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 n...
450,646
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_matche...
def search(self, query, return_matches=False, ignore_search_restriction=False): if not query or not query.strip(): 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: retu...
450,647
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_matche...
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: q = query if not ignore_search_restriction: q = u'%s (%s)' % (self.search_restriction, query) if not q: if return_matches: return ...
450,648
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 a...
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 a...
450,649
def get_matches(self, location, query): matches = set([]) if query and query.strip(): location = location.lower().strip()
def get_matches(self, location, query): matches = set([]) if query and query.strip(): location = location.lower().strip()
450,650
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 = from...
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 = from...
450,651
def __init__(self, prefix, lpath, title, authors, mime, date, ContentType, thumbnail_name, size=None, other=None):
def __init__(self, prefix, lpath, title, authors, mime, date, ContentType, thumbnail_name, size=None, other=None):
450,652
def __init__(self, prefix, lpath, title, authors, mime, date, ContentType, thumbnail_name, size=None, other=None):
def __init__(self, prefix, lpath, title, authors, mime, date, ContentType, thumbnail_name, size=None, other=None):
450,653
def __init__(self, prefix, lpath, title, authors, mime, date, ContentType, thumbnail_name, size=None, other=None):
def __init__(self, prefix, lpath, title, authors, mime, date, ContentType, thumbnail_name, size=None, other=None):
450,654
def __init__(self,title,author):
def__init__(self,title,author):
450,655
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.forma...
def get_value(self, key, args, kwargs): try: if key != 'title_sort': 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: ...
450,656
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(aspec...
def do_layout(self): pixmap = self.pixmap() pwidth, pheight = pixmap.width(), pixmap.height() width, height = fit_image(pwidth, pheight, pwidth, self.statusbar_height-20)[1:] self.setMaximumHeight(height) try: aspect_ratio = pwidth/float(pheight) except ZeroDivisionError: aspect_ratio = 1 self.setMaximumWidth(int(aspec...
450,657
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 i...
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 i...
450,658
def getter(x): return category_meta[x]['name'].lower()
def getter(x): return category_meta[x]['name'].lower()
450,659
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()
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()
450,660
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_...
def browse_sort_categories(self, items, sort): def keyg(x): x = getattr(x, 'sort', x.name) if isinstance(x, unicode): return sort_key(x) return x if sort == 'popularity': items.sort(key=operator.attrgetter('count'), reverse=True) elif sort == 'rating': items.sort(key=operator.attrgetter('avg_rating'), reverse=True) re...
450,661
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)
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: self.javascript('$("body").css("padding-bottom", "%s")' %...
450,662
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)
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)
450,663
def start(self): self.pi.startAnimation() pass
def start(self): self.pi.startAnimation() pass
450,664
def stop(self): self.pi.stopAnimation() pass
def stop(self): self.pi.stopAnimation() pass
450,665
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))
class ISBNNotFound(ValueError): pass def check_for_errors(root, isbn): 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))
450,666
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))
def check_for_errors(root): err = root.find('.//'+AWS('Error')) if err is not None: raise Exception('Failed to get metadata with error: '\ + text)
450,667
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 = [...
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) try: check_for_errors(root, isbn) except ISBNNotFound: return mi mi.title = roo...
450,668
def update_device_database_collections(self, booklists, collections_attributes, oncard):
def update_device_database_collections(self, booklists, collections_attributes, oncard):
450,669
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 # s...
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(unicode(force_unicode(x)), unicode(force_unicode(y))) else: c = cmp(x, y) if c ...
450,670
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 n...
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 n...
450,671
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 n...
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 n...
450,672
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...
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] == 'ca...
450,673
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...
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...
450,674
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...
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...
450,675
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...
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...
450,676
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
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
450,677
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 }
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 }
450,678
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) f...
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) r...
450,679
def force_int(raw): return int(re.search(r'([0-9+-]+)', raw).group(1))
def force_int(raw): return int(re.search(r'([0-9+-]+)', raw).group(1))
450,680
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.stagin...
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.bindir, extensions=self.j(self.libdir, 'calibre', 'plugins')) path = self.j(self.staging_bindir...
450,681
def prepare_pml(self, pml): # Remove comments pml = re.sub(r'(?mus)\\v(?P<text>.*?)\\v', '', pml)
def prepare_pml(self, pml): # Remove comments pml = re.sub(r'(?mus)\\v(?P<text>.*?)\\v', '', pml)
450,682
def prepare_pml(self, pml): # Remove comments pml = re.sub(r'(?mus)\\v(?P<text>.*?)\\v', '', pml)
def prepare_pml(self, pml): # Remove comments pml = re.sub(r'(?mus)\\v(?P<text>.*?)\\v', '', pml)
450,683
def parse_pml(self, pml, file_name=''): pml = self.prepare_pml(pml) output = []
def parse_pml(self, pml, file_name=''): pml = self.prepare_pml(pml) output = []
450,684
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)]
def __add_filesystem_book(self, paths, allow_device=True): if isinstance(paths, basestring): paths = [paths] books = [path for path in map(os.path.abspath, paths) if os.access(path, os.R_OK)]
450,685
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....
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....
450,686
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( 'QLineEdi...
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.line_edit.setStyleSheet( 'QLineEdit { color: gray; backgr...
450,687
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', 'encrypt...
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', 'encrypt...
450,688
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_...
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_...
450,689
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))
def url_to_local_path(cls, url, base): path = url.path isabs = False if iswindows and path.startswith('/'): path = path[1:] isabs = True path = urlunparse(('', '', path, url.params, url.query, '')) path = unquote(path) if os.path.isabs(path): return path return os.path.abspath(os.path.join(base, path))
450,690
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))
def url_to_local_path(cls, url, base): path = urlunparse(('', '', url.path, url.params, url.query, '')) path = unquote(path) if isabs or os.path.isabs(path): return path return os.path.abspath(os.path.join(base, path))
450,691
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....
def resource_adder(self, link_, base=None): 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...
450,692
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...
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...
450,693
def stringFromInt(self, intToTranslate): # Convert intToTranslate to string # intToTranslate is a three-digit number
def stringFromInt(self, intToTranslate): # Convert intToTranslate to string # intToTranslate is a three-digit number
450,694
def stringFromInt(self, intToTranslate): # Convert intToTranslate to string # intToTranslate is a three-digit number
def stringFromInt(self, intToTranslate): # Convert intToTranslate to string # intToTranslate is a three-digit number
450,695
def stringFromInt(self, intToTranslate): # Convert intToTranslate to string # intToTranslate is a three-digit number
defelse: prints(" NumberToText.stringFromInt(): empty result translating %d" % intToTranslate) stringFromInt(self,else: prints(" NumberToText.stringFromInt(): empty result translating %d" % intToTranslate) intToTranslate):else: prints(" NumberToText.stringFromInt(): empty result translating %d" % intToTranslate) #else:...
450,696
def fetchBooksByAuthor(self): # Generate a list of titles sorted by author from the database
def fetchBooksByAuthor(self): # Generate a list of titles sorted by author from the database
450,697
def __call__(self, html, remove_special_chars=None): if remove_special_chars is not None: html = remove_special_chars.sub('', html) html = html.replace('\0', '') if self.is_baen(html): rules = [] elif self.is_book_designer(html): rules = self.BOOK_DESIGNER elif self.is_pdftohtml(html): rules = self.PDFTOHTML else: rule...
def __call__(self, html, remove_special_chars=None): if remove_special_chars is not None: html = remove_special_chars.sub('', html) html = html.replace('\0', '') if self.is_baen(html): rules = [] elif self.is_book_designer(html): rules = self.BOOK_DESIGNER elif self.is_pdftohtml(html): rules = self.PDFTOHTML else: rule...
450,698
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 []
450,699