Best Python code snippet using playwright-python
yaftl.py
Source:yaftl.py
1from array import array2from construct.core import Struct, Union3from construct.macros import *4from progressbar import ProgressBar5from structs import *6import struct789#https://github.com/iDroid-Project/openiBoot/blob/master/openiboot/ftl-yaftl/yaftl.c10YAFTL_CXT = Struct("YAFTL_CXT",11 String("version", 4),12 ULInt32("unknCalculatedValue0"),13 ULInt32("totalPages"),14 ULInt32("latestUserBlock"),15 ULInt32("cxt_unkn0_usn"),16 ULInt32("latestIndexBlock"),17 ULInt32("maxIndexUsn"),18 ULInt32("blockStatsField4"),19 ULInt32("blockStatsField10"),20 ULInt32("numAllocatedBlocks"),21 ULInt32("numIAllocatedBlocks"),22 ULInt32("unk184_0xA"),23 Array(10, ULInt32("cxt_unkn1")),24 ULInt32("field_58"),25 ULInt16("tocArrayLength"),26 ULInt16("tocPagesPerBlock"),27 ULInt16("tocEntriesPerPage"),28 ULInt16("unkn_0x2A"),29 ULInt16("userPagesPerBlock"),30 ULInt16("unk64"),31 Array(11, ULInt32("cxt_unkn2")),32 ULInt8("unk188_0x63"),33)3435TOCStruct = Struct("TOCStruct",36 ULInt32("indexPage"),37 ULInt16("cacheNum"),38 ULInt16("TOCUnkMember2"),39)4041BlockStats = Struct("BlockStats",42 ULInt32("numAllocated"),43 ULInt32("field_4"),44 ULInt32("numValidDPages"),45 ULInt32("numIAllocated"),46 ULInt32("field_10"),47 ULInt32("numValidIPages"),48 ULInt32("numFree"),49 ULInt32("field_1C"),50)515253class YAFTL(object):54 def __init__(self, vfl, usn=0):55 self.vfl = vfl56 self.lpnToVpn = None57 bytesPerPage = vfl.nand.pageSize58 numBlocks = vfl.context.usable_blocks_per_bank59 self.blankPage = bytesPerPage * "\x00"60 self.numBlocks = numBlocks61 self.tocPagesPerBlock = vfl.pages_per_sublk * 4 / bytesPerPage62 if vfl.pages_per_sublk * 4 % bytesPerPage:63 self.tocPagesPerBlock += 164 self.tocEntriesPerPage = bytesPerPage / 465 self.tocArrayLength = CEIL_DIVIDE(vfl.pages_per_sublk * numBlocks * 4, bytesPerPage)66 self.nPagesTocPageIndices = CEIL_DIVIDE(self.tocArrayLength * 4, bytesPerPage)67 self.nPagesBlockStatuses = CEIL_DIVIDE(numBlocks * 1, bytesPerPage)68 self.nPagesBlockReadCounts = CEIL_DIVIDE(numBlocks * 2, bytesPerPage)69 self.nPagesBlockEraseCounts = CEIL_DIVIDE(numBlocks * 4, bytesPerPage)70 self.nPagesBlockValidPagesDNumbers = self.nPagesBlockReadCounts71 self.nPagesBlockValidPagesINumbers = self.nPagesBlockReadCounts72 self.ctrlBlockPageOffset = self.nPagesTocPageIndices \73 + self.nPagesBlockStatuses \74 + self.nPagesBlockReadCounts \75 + self.nPagesBlockEraseCounts \76 + self.nPagesBlockValidPagesDNumbers \77 + self.nPagesBlockValidPagesINumbers \78 + 2 * self.tocPagesPerBlock \79 + 280 self.totalPages = (self.numBlocks - 8) * (self.vfl.pages_per_sublk - self.tocPagesPerBlock)# - unknCalculatedValue081 self.userPagesPerBlock = self.vfl.pages_per_sublk - self.tocPagesPerBlock82 maxUsn = 083 ftlCtrlBlock = -184 for b in self.vfl.VFL_get_FTLCtrlBlock():85 s,d = self.YAFTL_readPage(b * self.vfl.pages_per_sublk)86 if not d:87 continue88 if usn and s.usn > usn:89 break90 if s.usn > maxUsn:91 maxUsn = s.usn92 ftlCtrlBlock = b93 if ftlCtrlBlock == -1 or not maxUsn:94 print "ftlCtrlBlock not found, restore needed"95 self.YAFTL_restore()96 return97 i = 098 maxUsn = 099 while i < self.vfl.pages_per_sublk - self.ctrlBlockPageOffset:100 s,d = self.YAFTL_readPage(ftlCtrlBlock*self.vfl.pages_per_sublk + i + self.ctrlBlockPageOffset)101 if not d:102 if self.YAFTL_readCxtInfo(ftlCtrlBlock*self.vfl.pages_per_sublk + i):103 return104 print "YaFTL_readCxtInfo FAIL, restore needed maxUsn=%d" % maxUsn105 self.YAFTL_restore()106 return107 if s and s.usn > maxUsn:108 maxUsn = s.usn109 i += self.ctrlBlockPageOffset + 1110 print "YaFTL open fail"111 self.YAFTL_restore()112 113 def readBTOCPages(self, block, maxVal):114 data = ""115 for i in xrange(self.tocPagesPerBlock):116 s,d = self.YAFTL_readPage((block+1) * self.vfl.pages_per_sublk - self.tocPagesPerBlock + i)117 if not s:118 return None119 data += d120 btoc = array("I",data)121 for i in xrange(len(btoc)):122 if btoc[i] > maxVal:123 btoc[i] = 0xFFFFFFFF124 return btoc125 126 def YAFTL_restore(self):127 self.lpnToVpn = self.vfl.nand.loadCachedData("yaftlrestore")128 if self.lpnToVpn:129 print "Found cached FTL restore information"130 return131 userBlocks = {}132 indexBlocks = {}133 print "FTL restore in progress"134 pbar = ProgressBar(self.numBlocks)135 pbar.start()136 for b in xrange(0, self.numBlocks):137 pbar.update(b)138 #read fist page in block, if empty then block is empty139 s,d = self.YAFTL_readPage(b * self.vfl.pages_per_sublk + 0)140 if not s:141 continue142 if s.type == PAGETYPE_INDEX:143 indexBlocks[s.usn] = b144 elif s.type == PAGETYPE_LBN:145 if userBlocks.has_key(s.usn):146 print "Two blocks with same USN, something is weird"147 userBlocks[s.usn] = b148 elif s.type == PAGETYPE_FTL_CLEAN:149 pass150 pbar.finish()151 lpnToVpn = {}152 for usn in sorted(userBlocks.keys(), reverse=True):153 b = userBlocks[usn]154 btoc = self.readBTOCPages(b, self.totalPages)155 if btoc:156 for i in xrange(self.userPagesPerBlock-1,-1, -1):157 if not lpnToVpn.has_key(btoc[i]):158 lpnToVpn[btoc[i]] = b * self.vfl.pages_per_sublk + i159 else:160 print "BTOC not found for block %d (usn %d), scanning all pages" % (b, usn)161 i = 0162 for p in xrange(self.vfl.pages_per_sublk - self.tocPagesPerBlock -1, -1, -1):163 s,d = self.YAFTL_readPage(b * self.vfl.pages_per_sublk + p)164 if s:165 i+= 1166 if s and not lpnToVpn.has_key(s.lpn):167 lpnToVpn[s.lpn] = b * self.vfl.pages_per_sublk + p168 print "%d used pages in block" % i169 self.vfl.nand.cacheData("yaftlrestore", lpnToVpn)170 self.lpnToVpn = lpnToVpn171 return lpnToVpn172 173 def YAFTL_readCxtInfo(self, page):174 s,d = self.YAFTL_readPage(page)175 if not s or s.type != PAGETYPE_FTL_CLEAN:176 return False177 ctx = YAFTL_CXT.parse(d)178 ctx.spareUsn = s.usn179 if ctx.version != "CX01":180 print "Wrong FTL version %s" % ctx.version181 return False182 self.usn = s.usn183 pageToRead = page + 1;184 userTOCBuffer = self.YAFTL_read_n_Page(pageToRead, self.tocPagesPerBlock)185 if not userTOCBuffer:186 raise(Exception("userTOCBuffer"))187 pageToRead += self.tocPagesPerBlock188 indexTOCBuffer = self.YAFTL_read_n_Page(pageToRead, self.tocPagesPerBlock)189 pageToRead += self.tocPagesPerBlock + 1190 tocArrayIndexPages = self.YAFTL_read_n_Page(pageToRead, self.nPagesTocPageIndices)191 self.tocArrayIndexPages = array("I", tocArrayIndexPages)192 assert self.tocArrayIndexPages.itemsize == 4193 self.indexCache = {}194 pageToRead += self.nPagesTocPageIndices195 196 if False: #we don't care, we just want to read197 blockStatuses = self.YAFTL_read_n_Page(pageToRead, self.nPagesBlockStatuses)198 pageToRead += self.nPagesBlockStatuses199 blockReadCounts = self.YAFTL_read_n_Page(pageToRead, self.nPagesBlockReadCounts)200 pageToRead += self.nPagesBlockReadCounts201 blockEraseCounts = self.YAFTL_read_n_Page(pageToRead, self.nPagesBlockEraseCounts)202 pageToRead += self.nPagesBlockEraseCounts203 validPagesINo = self.YAFTL_read_n_Page(pageToRead, self.nPagesBlockValidPagesINumbers)204 pageToRead += self.nPagesBlockValidPagesINumbers205 validPagesDNo = self.YAFTL_read_n_Page(pageToRead, self.nPagesBlockValidPagesDNumbers)206 207 print "YaFTL context OK, version=%s maxIndexUsn=%d context usn=%d" % (ctx.version, ctx.maxIndexUsn, self.usn)208 return True209210 def YAFTL_read_n_Page(self, page, n, failIfBlank=False):211 r = ""212 for i in xrange(0, n):213 s,d = self.YAFTL_readPage(page +i)214 if not d:215 if failIfBlank:216 return217 return r218 r += d219 return r220 221 def YAFTL_readPage(self, page, key=META_KEY, lpn=None):222 return self.vfl.read_single_page(page, key, lpn)223 224 def build_lpn_to_vpn(self):225 lpnToVpn = {}226 for p in xrange(self.totalPages):227 x = self.translateLPNtoVPN(p)228 if x != 0xFFFFFFFF:229 lpnToVpn[p] = x230 self.vfl.nand.cacheData("currentftl", lpnToVpn)231 return lpnToVpn232 233 def translateLPNtoVPN(self, lpn):234 if self.lpnToVpn:235 return self.lpnToVpn.get(lpn, 0xFFFFFFFF)236 tocPageNum = (lpn) / self.tocEntriesPerPage237 indexPage = self.tocArrayIndexPages[tocPageNum]238 if indexPage == 0xffffffff:239 return 0xffffffff240 #print "indexPage %x" % indexPage241 if self.indexCache.has_key(indexPage):242 tocPageBuffer = self.indexCache[indexPage]243 else:244 s,tocPageBuffer = self.YAFTL_readPage(indexPage)245 if not tocPageBuffer:246 print "tocPageBuffer fail"247 return 0xffffffff248 assert s.type == PAGETYPE_INDEX249 tocPageBuffer = array("I", tocPageBuffer)250 self.indexCache[indexPage] = tocPageBuffer251 252 tocEntry = tocPageBuffer[lpn % self.tocEntriesPerPage]253 return tocEntry254255 def readLPN(self, lpn, key=None):#, nPages):256 vpn = self.translateLPNtoVPN(lpn)257 if vpn == 0xffffffff:258 return self.blankPage259 #print "tocEntry %d" % tocEntry260 #print "FTL %d => %d" % (lpn, vpn)261 s,d = self.YAFTL_readPage(vpn, key, lpn)262 if d == None:263 return self.blankPage264 if s.lpn != lpn:265 raise Exception("YAFTL translation FAIL spare lpn=%d vs expected %d" % (s.lpn, lpn))266 return d267268 def YAFTL_lookup1(self):269 hax = self.vfl.nand.loadCachedData("YAFTL_lookup1")270 if hax:271 print "Found cached FTL lookup table"272 return hax273 userBlocks = {}274 indexBlocks = {}275 print "Building FTL lookup table v1"276 pbar = ProgressBar(self.numBlocks)277 pbar.start()278 for b in xrange(0, self.numBlocks):279 pbar.update(b)280 #read fist page in block, if empty then block is empty281 s,d = self.YAFTL_readPage(b * self.vfl.pages_per_sublk + 0)282 if not s:283 continue284 if s.type == PAGETYPE_INDEX:285 indexBlocks[s.usn] = b286 elif s.type == PAGETYPE_LBN:287 if userBlocks.has_key(s.usn):288 print "Two blocks with same USN, something is weird"289 userBlocks[s.usn] = b290 elif s.type == PAGETYPE_FTL_CLEAN:291 pass#print b, "ftl block"292 pbar.finish()293 lpnToVpn = {}294 for usn in sorted(userBlocks.keys(), reverse=False):295 b = userBlocks[usn]296 btoc = self.readBTOCPages(b, self.totalPages)297 #print usn, b298 if btoc:299 for i in xrange(self.userPagesPerBlock-1,-1, -1):300 lpnToVpn.setdefault(btoc[i], []).append(b * self.vfl.pages_per_sublk + i)301 else:302 #print "btoc not found for block %d (usn %d), scanning all pages" % (b, usn)303 i = 0304 usn = -1305 for p in xrange(self.vfl.pages_per_sublk - self.tocPagesPerBlock -1, -1, -1):306 s,d = self.YAFTL_readPage(b * self.vfl.pages_per_sublk + p)307 if not s:308 break309 i+= 1310 if usn == -1:311 usn = s.usn312 if usn != s.usn:313 #print "Two usns in same block %d %d" % (usn, s.usn)314 usn = s.usn315 lpnToVpn.setdefault(s.lpn, []).append(b * self.vfl.pages_per_sublk + p)316 #print "%d used pages in block" % i317 #self.vfl.nand.cacheData("YAFTL_lookup1", (lpnToVpn, userBlocks))318 return lpnToVpn, userBlocks319320 def YAFTL_hax2(self):321 hax = self.vfl.nand.loadCachedData("YAFTL_hax2")322 if hax:323 print "Found cached FTL HAX2 information"324 return hax325326 print "FTL hax2 in progress"327 pbar = ProgressBar(self.numBlocks)328 pbar.start()329 lpnToVpn = {}330 for b in xrange(0, self.numBlocks):331 pbar.update(b)332 #read fist page in block, if empty then block is empty (right?)333 s,d = self.YAFTL_readPage(b * self.vfl.pages_per_sublk + 0)334 if not s:335 continue336 if s.type == PAGETYPE_LBN:337 i = 0338 usn = -1339 for p in xrange(0, self.vfl.pages_per_sublk - self.tocPagesPerBlock):340 s,d = self.YAFTL_readPage(b * self.vfl.pages_per_sublk + p)341 if not s:342 break343 lpnToVpn.setdefault(s.lpn, {}).setdefault(s.usn, []).append(b * self.vfl.pages_per_sublk + p)344 i+= 1345346 pbar.finish()347 self.vfl.nand.cacheData("YAFTL_hax2", lpnToVpn)348 return lpnToVpn349350 def block_lpn_to_vpn(self, block):351 res = {}352 for p in xrange(0, self.vfl.pages_per_sublk - self.tocPagesPerBlock):353 s,d = self.YAFTL_readPage(block * self.vfl.pages_per_sublk + p)354 if not s:355 break356 res[s.lpn] = block * self.vfl.pages_per_sublk + p
...
replacing_pages_algorithms.py
Source:replacing_pages_algorithms.py
...29 if process in self.waiting_processes:30 self.waiting_processes.remove(process)31 if process in self.blocked_processes:32 self.blocked_processes.remove(process)33 for i in range(process.get_number_of_pages()):34 page = Page(process.pid, i)35 # if page in self._pages_in_RAM:36 self._pages_in_RAM.remove(page)37 self.ram.delete_page(page)38 self.disk.delete_page(page)39 self.table.delete_page(page)40 # for each process it will be checked if its state is blocked or waiting41 def check_state(self):42 for process in self.processes:43 cnt_waiting = 044 cnt_blocked = 045 for page in process.pages:46 if page in self.ram.pages:47 cnt_waiting += 148 elif page in self._waiting_pages or page in self._pages_in_disk:49 cnt_blocked += 150 # if page should be in waiting state51 if cnt_waiting == process.get_number_of_pages():52 if process not in self.waiting_processes:53 self.waiting_processes.append(process)54 if process in self.blocked_processes:55 self.blocked_processes.remove(process)56 else:57 if process not in self.blocked_processes:58 self.blocked_processes.append(process)59 if process in self.waiting_processes:60 self.waiting_processes.remove(process)61 def there_is_processes(self) -> bool:62 return (63 len(self.cur_processes)64 + len(self._waiting_pages)65 + len(self._pages_in_RAM)66 + len(self._pages_in_disk)67 > 068 )69 70 def sort_waiting_processes_by_exec_time(self):71 self.waiting_processes.sort(key=lambda p: p.exec_time)72 def add_pages_in_waiting_pages_from_processes(self):73 # adding all pages from processes in queue74 for process in self.back_processes:75 if process.arrival_time != self.time:76 continue77 self.cur_processes.remove(process)78 for page in process.pages:79 self._waiting_pages.append(page)80 def __get_first_pages_in_RAM(self):81 return self._pages_in_RAM[0]82 def __get_first_waiting_pages(self):83 return self._waiting_pages[0]84 def __get_and_delete_front_pages_in_RAM(self):85 front = self._pages_in_RAM[0]86 self._pages_in_RAM = self._pages_in_RAM[1:]87 return front88 def __get_and_delete_front_pages_in_disk(self):89 front = self._pages_in_disk[0]90 self._pages_in_disk = self._pages_in_disk[1:]91 return front92 def __get_and_delete_front_waiting_pages(self):93 front = self._waiting_pages[0]94 self._waiting_pages = self._waiting_pages[1:]95 return front96 def __get_number_of_pages_to_be_added(self):97 return min(98 len(self._pages_in_disk) + len(self._waiting_pages), self.elements_per_time99 )100 def delete_a_page_in_RAM(self):101 # this element must be executed at least once and102 # it shouldn't be running at the moment103 for page in self._pages_in_RAM:104 if (105 self.ram.was_executed(page)106 and self.running_process_pid != page.associated_pid_process107 ):108 deleted = page109 self._pages_in_RAM.remove(deleted)110 self.ram.delete_page(deleted)111 self.disk.add_page(deleted)112 self.table.set_not_present_in_RAM(deleted)113 self._pages_in_disk.append(deleted)114 return deleted115 return Page(-1, -1)116 def delete_first_elements_from_pages_in_RAM(self):117 # cnt represents the number of pages to be removed118 cnt = self.__get_number_of_pages_to_be_added()119 while self._pages_in_RAM and cnt > 0:120 front = self.delete_a_page_in_RAM()121 if front.associated_pid_process == -1:122 return123 cnt -= 1124 def add_first_pages_to_RAM(self):125 cnt = self.elements_per_time126 # adding all pages from disk to ram127 while (128 self._pages_in_disk129 and len(self._pages_in_RAM) < self.ram.RAM_size130 and cnt > 0131 ):132 front = self.__get_and_delete_front_pages_in_disk()133 idx_in_RAM = self.ram.add_page(front)134 assert idx_in_RAM is not None135 self.table.set_present_in_RAM(front, idx_in_RAM)136 self.disk.delete_page(front)137 self._pages_in_RAM.append(front)138 cnt -= 1139 # adding all waiting pages allowed, if theres free space in ram it will be added there,140 # otherwise it will be added in disk141 while self._waiting_pages and cnt > 0:142 front = self.__get_and_delete_front_waiting_pages()143 idx_in_RAM = self.ram.add_page(front)144 self.table.add_page(front)145 # if theres not a valid page to add idx_in_RAM will be None146 if idx_in_RAM is not None:147 self.table.set_present_in_RAM(front, idx_in_RAM)148 self._pages_in_RAM.append(front)149 else:150 self.disk.add_page(front)151 self.table.set_not_present_in_RAM(front)152 self._pages_in_disk.append(front)153 cnt -= 1154 def execute(self):155 self.add_pages_in_waiting_pages_from_processes()156 self.delete_first_elements_from_pages_in_RAM()...
backgrounds.py
Source:backgrounds.py
1#2# This Source Code Form is subject to the terms of the Mozilla Public3# License, v. 2.0. If a copy of the MPL was not distributed with this4# file, You can obtain one at http://mozilla.org/MPL/2.0/.5#6from uitest.framework import UITestCase7from uitest.uihelper.common import select_pos8from com.sun.star.awt.GradientStyle import LINEAR9from com.sun.star.drawing.HatchStyle import SINGLE10from com.sun.star.drawing.BitmapMode import REPEAT11from com.sun.star.drawing.RectanglePoint import MIDDLE_MIDDLE12class ImpressBackgrounds(UITestCase):13 def checkDefaultBackground(self, btn):14 document = self.ui_test.get_component()15 if btn == 'btnnone':16 self.assertEqual(document.DrawPages.getByIndex(0).Background, None)17 elif btn == 'btncolor':18 self.assertEqual(document.DrawPages.getByIndex(0).Background.FillColor, 7512015)19 self.assertEqual(document.DrawPages.getByIndex(0).Background.FillColor, 7512015)20 elif btn == 'btngradient':21 self.assertEqual(22 document.DrawPages.getByIndex(0).Background.FillGradient.Style, LINEAR)23 self.assertEqual(24 document.DrawPages.getByIndex(0).Background.FillGradient.StartColor, 9101876)25 self.assertEqual(26 document.DrawPages.getByIndex(0).Background.FillGradient.Angle, 300)27 self.assertEqual(28 document.DrawPages.getByIndex(0).Background.FillGradient.Border, 0)29 self.assertEqual(30 document.DrawPages.getByIndex(0).Background.FillGradient.XOffset, 0)31 self.assertEqual(32 document.DrawPages.getByIndex(0).Background.FillGradient.YOffset, 0)33 self.assertEqual(34 document.DrawPages.getByIndex(0).Background.FillGradient.StartIntensity, 100)35 self.assertEqual(36 document.DrawPages.getByIndex(0).Background.FillGradient.EndIntensity, 100)37 #self.assertEqual(38 #document.DrawPages.getByIndex(0).Background.FillGradientName, 'Tango Green')39 elif btn == 'btnhatch':40 self.assertEqual(41 document.DrawPages.getByIndex(0).Background.FillHatch.Style, SINGLE )42 self.assertEqual(43 document.DrawPages.getByIndex(0).Background.FillHatch.Color, 0)44 self.assertEqual(45 document.DrawPages.getByIndex(0).Background.FillHatch.Distance, 102)46 self.assertEqual(47 document.DrawPages.getByIndex(0).Background.FillHatch.Angle, 0)48 self.assertEqual(49 document.DrawPages.getByIndex(0).Background.FillHatchName, 'Black 0 Degrees')50 elif btn == 'btnbitmap':51 self.assertEqual(52 document.DrawPages.getByIndex(0).Background.FillBitmapMode, REPEAT)53 self.assertEqual(54 document.DrawPages.getByIndex(0).Background.FillBitmapPositionOffsetX, 0)55 self.assertEqual(56 document.DrawPages.getByIndex(0).Background.FillBitmapPositionOffsetY, 0)57 self.assertEqual(58 document.DrawPages.getByIndex(0).Background.FillBitmapRectanglePoint, MIDDLE_MIDDLE)59 self.assertEqual(60 document.DrawPages.getByIndex(0).Background.FillBitmapStretch, False)61 self.assertEqual(62 document.DrawPages.getByIndex(0).Background.FillBitmapTile, True)63 self.assertEqual(64 document.DrawPages.getByIndex(0).Background.FillBitmapOffsetX, 0)65 self.assertEqual(66 document.DrawPages.getByIndex(0).Background.FillBitmapOffsetY, 0)67 self.assertEqual(68 document.DrawPages.getByIndex(0).Background.FillBitmapLogicalSize, True)69 self.assertEqual(70 document.DrawPages.getByIndex(0).Background.FillBitmapSizeX, 0)71 self.assertEqual(72 document.DrawPages.getByIndex(0).Background.FillBitmapSizeY, 0)73 self.assertEqual(document.DrawPages.getByIndex(0).Background.FillBitmapName, 'Sky')74 elif btn == 'btnpattern':75 self.assertEqual(76 document.DrawPages.getByIndex(0).Background.FillBitmapMode, REPEAT)77 self.assertEqual(78 document.DrawPages.getByIndex(0).Background.FillBitmapPositionOffsetX, 0)79 self.assertEqual(80 document.DrawPages.getByIndex(0).Background.FillBitmapPositionOffsetY, 0)81 self.assertEqual(82 document.DrawPages.getByIndex(0).Background.FillBitmapRectanglePoint, MIDDLE_MIDDLE)83 self.assertEqual(84 document.DrawPages.getByIndex(0).Background.FillBitmapStretch, True)85 self.assertEqual(86 document.DrawPages.getByIndex(0).Background.FillBitmapTile, True)87 self.assertEqual(88 document.DrawPages.getByIndex(0).Background.FillBitmapOffsetX, 0)89 self.assertEqual(90 document.DrawPages.getByIndex(0).Background.FillBitmapOffsetY, 0)91 self.assertEqual(92 document.DrawPages.getByIndex(0).Background.FillBitmapLogicalSize, True)93 self.assertEqual(94 document.DrawPages.getByIndex(0).Background.FillBitmapSizeX, 0)95 self.assertEqual(96 document.DrawPages.getByIndex(0).Background.FillBitmapSizeY, 0)97 self.assertEqual(98 document.DrawPages.getByIndex(0).Background.FillBitmapName, '5 Percent')99 def test_background_dialog(self):100 self.ui_test.create_doc_in_start_center("impress")101 xTemplateDlg = self.xUITest.getTopFocusWindow()102 xCancelBtn = xTemplateDlg.getChild("cancel")103 self.ui_test.close_dialog_through_button(xCancelBtn)104 buttons = ['btnbitmap', 'btncolor', 'btngradient', 'btnhatch', 'btnpattern']105 for index, button in enumerate(buttons):106 self.ui_test.execute_dialog_through_command(".uno:PageSetup")107 xPageSetupDlg = self.xUITest.getTopFocusWindow()108 tabcontrol = xPageSetupDlg.getChild("tabcontrol")109 select_pos(tabcontrol, "1")110 xBtn = xPageSetupDlg.getChild(button)111 xBtn.executeAction("CLICK", tuple())112 xOkBtn = xPageSetupDlg.getChild("ok")113 xOkBtn.executeAction("CLICK", tuple())114 xConfirmDlg = self.xUITest.getTopFocusWindow()115 xNoBtn = xConfirmDlg.getChild("no")116 xNoBtn.executeAction("CLICK", tuple())117 self.checkDefaultBackground(button)118 self.ui_test.execute_dialog_through_command(".uno:PageSetup")119 xPageSetupDlg = self.xUITest.getTopFocusWindow()120 tabcontrol = xPageSetupDlg.getChild("tabcontrol")121 select_pos(tabcontrol, "1")122 xBtn = xPageSetupDlg.getChild('btnnone')123 xBtn.executeAction("CLICK", tuple())124 xOkBtn = xPageSetupDlg.getChild("ok")125 xOkBtn.executeAction("CLICK", tuple())126 xConfirmDlg = self.xUITest.getTopFocusWindow()127 xNoBtn = xConfirmDlg.getChild("no")128 xNoBtn.executeAction("CLICK", tuple())129 self.checkDefaultBackground('btnnone')130 self.ui_test.close_doc()...
pagerank.py
Source:pagerank.py
1import os2import random3import re4import sys5import copy6DAMPING = 0.857SAMPLES = 100008def main():9 if len(sys.argv) != 2:10 sys.exit("Usage: python pagerank.py corpus")11 corpus = crawl(sys.argv[1])12 # Rank pages using sampling13 ranks = sample_pagerank(corpus, DAMPING, SAMPLES)14 print(f"PageRank Results from Sampling (n = {SAMPLES})")15 for page in sorted(ranks):16 print(f" {page}: {ranks[page]:.4f}")17 18 # Rank pages using iteration19 ranks = iterate_pagerank(corpus, DAMPING)20 print(f"PageRank Results from Iteration")21 for page in sorted(ranks):22 print(f" {page}: {ranks[page]:.4f}")23 24def crawl(directory):25 """26 Parses a `directory` of HTML pages and check for links to other pages.27 Returns a dictionary where each key is a page, and the values are28 a list of all other pages in the corpus that are linked to by the page.29 """30 pages = dict()31 # Extract all links from HTML files32 for filename in os.listdir(directory):33 if not filename.endswith(".html"):34 continue35 with open(os.path.join(directory, filename)) as f:36 contents = f.read()37 links = re.findall(r"<a\s+(?:[^>]*?)href=\"([^\"]*)\"", contents)38 pages[filename] = set(links) - {filename}39 # Only include links to other pages in the corpus40 for filename in pages:41 pages[filename] = set(42 link for link in pages[filename]43 if link in pages44 )45 return pages46def transition_model(corpus, page, damping_factor):47 """48 Returns a probability distribution (PD) over which page to visit next,49 given a current page.50 With probability `damping_factor`, chooses a link linked to by `page`. 51 With probability `1 - damping_factor`, chooses a link from all pages in `corpus`.52 """53 # Create dictionary of all html_pages54 pages_PD = dict()55 for html_page in corpus:56 pages_PD.setdefault(html_page, 0)57 58 # Assign a selection probability to each link in page59 if len(corpus[page]) != 0: # Number of links in page is not 060 for html_page in corpus[page]:61 pages_PD[html_page] += damping_factor/len(corpus[page])62 63 if len(corpus[page]) == 0: # Number of links in page is 064 for html_page in pages_PD:65 pages_PD[html_page] += damping_factor/len(pages_PD)66 # Assign a probability to randomly choose each page in corpus67 for html_page in pages_PD:68 pages_PD[html_page] += (1-damping_factor)/len(pages_PD)69 return pages_PD70def sample_pagerank(corpus, damping_factor, n):71 """72 Returns PageRank values for each page by sampling `n` pages73 according to transition model, starting with a page at random.74 Return a dictionary where keys are page names and values are75 their estimated PageRank value (between 0 and 1). All76 PageRank values sum to 1.77 """78 # Create dictionary of all html_pages79 ranked_pages = dict()80 for html_page in corpus:81 ranked_pages.setdefault(html_page, 0)82 # Select a random page to start83 sampled_page = random.choice(list(ranked_pages.keys()))84 85 # Sample corpus pages n times 86 for i in range(n):87 # Determine the PD of pages to visit next88 sampled_page_PD = transition_model(corpus, sampled_page, DAMPING)89 # Select a page to visit90 population = list(sampled_page_PD.keys())91 weights = list(sampled_page_PD.values())92 sampled_page = random.choices(population, weights)[0]93 # Record visit in dictionary94 for html_page in ranked_pages: 95 if html_page == sampled_page:96 ranked_pages[html_page] += 1/n97 return ranked_pages98def iterate_pagerank(corpus, damping_factor):99 """100 Returns PageRank values for each page by iteratively updating101 PageRank values until convergence.102 Returns a dictionary where keys are page names and values are103 their estimated PageRank value (between 0 and 1). All104 PageRank values sum to 1.105 """106 # Create dictionary of all html_pages107 ranked_pages = dict()108 # Assign each page an equivalent rank to start with109 for html_page in corpus:110 ranked_pages.setdefault(html_page, 1/len(corpus))111 112 # Repeat until PageRank values converge113 while True: 114 # Create a deepcopy of the dictionary115 old_ranked_pages = copy.deepcopy(ranked_pages)116 # Calculate the probability that the random surfer arrives at each html_page117 for html_page in ranked_pages:118 119 # Probability of choosing page at random120 random_choice = (1-damping_factor)/len(corpus)121 122 # Probability of arriving to page from a link in another page123 link_choice = 0124 for page in corpus:125 if len(corpus[page]) != 0: # If there are links in the page 126 for i in range(len(corpus[page])): 127 if list(corpus[page])[i] == html_page:128 link_choice += old_ranked_pages[page]/len(corpus[page])129 else: # If there are no links in the page130 link_choice += old_ranked_pages[page]/len(corpus)131 132 # Total probability of arriving at the page133 ranked_pages[html_page] = random_choice + damping_factor*link_choice134 # Check if the probabilities have converged (change in PageRank values of no more than 0.001)135 converged = 0136 for html_page in ranked_pages:137 if abs(ranked_pages[html_page] - old_ranked_pages[html_page]) <= 0.001:138 converged += 1139 if converged == len(corpus):140 break 141 142 return ranked_pages143if __name__ == "__main__":...
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!