Best Python code snippet using playwright-python
cua_so.py
Source:cua_so.py
1import pygame2from geopy.geocoders import Nominatim3from geopy.distance import geodesic4import math56geolocator = Nominatim(user_agent="MyApp")7pygame.init()89# Create Screen10x_screen = 100011y_screen = 80012screen = pygame.display.set_mode((x_screen, y_screen))1314location_color = (255, 51, 153)15background_color = (255, 255, 255)16true_color = (0, 204, 0)17false_color = (255, 0, 0)18# Title of screen19pygame.display.set_caption("Wero - Wordle")2021# Text title22text_size_1 = 3023text_size_2 = 1524font_1 = pygame.font.SysFont("Times New Roman", text_size_1, bold=True)25font_2 = pygame.font.SysFont("Times New Roman", text_size_2, bold=True)26x_namegame = (x_screen // 2)27y_namegame = 02829wordle = font_1.render('Wordle', True, (0, 0, 0))30vietnam = font_1.render('VietNam', True, (255, 51, 153))31# running game3233game_location = 'Can Tho'34# guess_location = 'Lang Son'3536fps = 6037timer = pygame.time.Clock()383940def draw_checking_distance():41 pygame.draw.rect(screen, location_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 10, 100, 40), 2, 5)42 pygame.draw.rect(screen, location_color, pygame.Rect(x_screen // 2 + 240, y_screen // 16 + 10, 100, 40), 2, 5)43 pygame.draw.circle(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 30), 20, 5)44 # pygame.draw.line(screen, location_color, (x_screen// 2 + 405, y_screen//16 + 100), (x_screen// 2 + 420, y_screen//16 + 100), 4)4546 pygame.draw.rect(screen, location_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 80, 100, 40), 2, 5)47 pygame.draw.rect(screen, location_color, pygame.Rect(x_screen // 2 + 240, y_screen // 16 + 80, 100, 40), 2, 5)48 pygame.draw.circle(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 100), 20, 5)4950 pygame.draw.rect(screen, location_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 150, 100, 40), 2, 5)51 pygame.draw.rect(screen, location_color, pygame.Rect(x_screen // 2 + 240, y_screen // 16 + 150, 100, 40), 2, 5)52 pygame.draw.circle(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 170), 20, 5)5354 pygame.draw.rect(screen, location_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 220, 100, 40), 2, 5)55 pygame.draw.rect(screen, location_color, pygame.Rect(x_screen // 2 + 240, y_screen // 16 + 220, 100, 40), 2, 5)56 pygame.draw.circle(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 240), 20, 5)5758 pygame.draw.rect(screen, location_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 290, 100, 40), 2, 5)59 pygame.draw.rect(screen, location_color, pygame.Rect(x_screen // 2 + 240, y_screen // 16 + 290, 100, 40), 2, 5)60 pygame.draw.circle(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 310), 20, 5)616263# calculate distances of 5 places64def checking_distance_1(game_location, guess_location, distance=0):65 # calculate distance66 guess = guess_location67 location_1 = geolocator.geocode(guess)68 location_2 = geolocator.geocode(game_location)69 loc1 = (location_1.latitude, location_1.longitude)70 loc2 = (location_2.latitude, location_2.longitude)71 dis = str(int(geodesic(loc1, loc2).km))72 guess1 = font_2.render(guess, True, (255, 51, 153))73 distance = font_2.render(dis, True, (255, 51, 153))74 screen.blit(guess1, guess1.get_rect(center=(x_screen // 2 + 150, y_screen // 16 + 30)))75 screen.blit(distance, distance.get_rect(center=(x_screen // 2 + 290, y_screen // 16 + 30)))76 if dis == '0':77 pygame.draw.rect(screen, true_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 10, 100, 40), 2, 5)78 else:79 pygame.draw.rect(screen, false_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 10, 100, 40), 2, 5)80 # calculate compass direction81 alpha_1 = loc1[1] * (math.pi / 180)82 alpha_2 = loc2[1] * math.pi / 18083 phi_1 = loc1[0] * math.pi / 18084 phi_2 = loc2[0] * math.pi / 18085 delta_alpha = (alpha_2 - alpha_1)86 y = math.sin(delta_alpha) * math.cos(phi_2)87 x = math.cos(phi_1) * math.sin(phi_2) - math.sin(phi_1) * math.cos(phi_2) * math.cos(delta_alpha)88 angle = math.atan2(y, x)89 bearing = int((angle * 180 / math.pi + 360) % 360)90 if '0' == dis:91 pygame.draw.circle(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 30), 5, 5)92 elif 0 <= bearing < 90:93 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 30),94 (x_screen // 2 + 405, y_screen // 16 + 15), 4)95 elif 90 <= bearing < 180:96 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 30),97 (x_screen // 2 + 420, y_screen // 16 + 30), 4)98 elif 180 <= bearing < 270:99 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 30),100 (x_screen // 2 + 405, y_screen // 16 + 45), 4)101 elif 270 <= bearing < 360:102 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 45),103 (x_screen // 2 + 390, y_screen // 16 + 30), 4)104 print(dis)105 print(bearing)106107108def checking_distance_2(game_location, guess_location, distance=0):109 guess = guess_location110 location_1 = geolocator.geocode(guess)111 location_2 = geolocator.geocode(game_location)112 loc1 = (location_1.latitude, location_1.longitude)113 loc2 = (location_2.latitude, location_2.longitude)114 dis = str(int(geodesic(loc1, loc2).km))115 guess1 = font_2.render(guess, True, (255, 51, 153))116 distance = font_2.render(dis, True, (255, 51, 153))117 screen.blit(guess1, guess1.get_rect(center=(x_screen // 2 + 150, y_screen // 16 + 100)))118 screen.blit(distance, distance.get_rect(center=(x_screen // 2 + 290, y_screen // 16 + 100)))119 if dis == '0':120 pygame.draw.rect(screen, true_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 80, 100, 40), 2, 5)121 else:122 pygame.draw.rect(screen, false_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 80, 100, 40), 2, 5)123124 alpha_1 = loc1[1] * (math.pi / 180)125 alpha_2 = loc2[1] * math.pi / 180126 phi_1 = loc1[0] * math.pi / 180127 phi_2 = loc2[0] * math.pi / 180128 delta_alpha = (alpha_2 - alpha_1)129 y = math.sin(delta_alpha) * math.cos(phi_2)130 x = math.cos(phi_1) * math.sin(phi_2) - math.sin(phi_1) * math.cos(phi_2) * math.cos(delta_alpha)131 angle = math.atan2(y, x)132 bearing = int((angle * 180 / math.pi + 360) % 360)133 if '0' == dis:134 pygame.draw.circle(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 100), 5, 5)135 elif 0 <= bearing < 90:136 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 100),137 (x_screen // 2 + 405, y_screen // 16 + 85), 4)138 elif 90 <= bearing < 180:139 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 100),140 (x_screen // 2 + 420, y_screen // 16 + 100), 4)141 elif 180 <= bearing < 270:142 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 100),143 (x_screen // 2 + 405, y_screen // 16 + 115), 4)144 elif 270 <= bearing < 360:145 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 115),146 (x_screen // 2 + 390, y_screen // 16 + 100), 4)147 print(dis)148149150def checking_distance_3(game_location, guess_location, distance=0):151 guess = guess_location152 location_1 = geolocator.geocode(guess)153 location_2 = geolocator.geocode(game_location)154 loc1 = (location_1.latitude, location_1.longitude)155 loc2 = (location_2.latitude, location_2.longitude)156 dis = str(int(geodesic(loc1, loc2).km))157 guess1 = font_2.render(guess, True, (255, 51, 153))158 distance = font_2.render(dis, True, (255, 51, 153))159 screen.blit(guess1, guess1.get_rect(center=(x_screen // 2 + 150, y_screen // 16 + 170)))160 screen.blit(distance, distance.get_rect(center=(x_screen // 2 + 290, y_screen // 16 + 170)))161 if dis == '0':162 pygame.draw.rect(screen, true_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 150, 100, 40), 2, 5)163 else:164 pygame.draw.rect(screen, false_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 150, 100, 40), 2, 5)165166 alpha_1 = loc1[1] * (math.pi / 180)167 alpha_2 = loc2[1] * math.pi / 180168 phi_1 = loc1[0] * math.pi / 180169 phi_2 = loc2[0] * math.pi / 180170 delta_alpha = (alpha_2 - alpha_1)171 y = math.sin(delta_alpha) * math.cos(phi_2)172 x = math.cos(phi_1) * math.sin(phi_2) - math.sin(phi_1) * math.cos(phi_2) * math.cos(delta_alpha)173 angle = math.atan2(y, x)174 bearing = int((angle * 180 / math.pi + 360) % 360)175 if '0' == dis:176 pygame.draw.circle(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 170), 5, 5)177 elif 0 <= bearing < 90:178 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 170),179 (x_screen // 2 + 405, y_screen // 16 + 155), 4)180 elif 90 <= bearing < 180:181 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 170),182 (x_screen // 2 + 420, y_screen // 16 + 170), 4)183 elif 180 <= bearing < 270:184 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 170),185 (x_screen // 2 + 405, y_screen // 16 + 185), 4)186 elif 270 <= bearing < 360:187 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 185),188 (x_screen // 2 + 390, y_screen // 16 + 170), 4)189 print(dis)190191192def checking_distance_4(game_location, guess_location, distance=0):193 guess = guess_location194 location_1 = geolocator.geocode(guess)195 location_2 = geolocator.geocode(game_location)196 loc1 = (location_1.latitude, location_1.longitude)197 loc2 = (location_2.latitude, location_2.longitude)198 dis = str(int(geodesic(loc1, loc2).km))199 guess1 = font_2.render(guess, True, (255, 51, 153))200 distance = font_2.render(dis, True, (255, 51, 153))201 screen.blit(guess1, guess1.get_rect(center=(x_screen // 2 + 150, y_screen // 16 + 240)))202 screen.blit(distance, distance.get_rect(center=(x_screen // 2 + 290, y_screen // 16 + 240)))203204 if dis == '0':205 pygame.draw.rect(screen, true_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 220, 100, 40), 2, 5)206 else:207 pygame.draw.rect(screen, false_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 220, 100, 40), 2, 5)208209 alpha_1 = loc1[1] * (math.pi / 180)210 alpha_2 = loc2[1] * math.pi / 180211 phi_1 = loc1[0] * math.pi / 180212 phi_2 = loc2[0] * math.pi / 180213 delta_alpha = (alpha_2 - alpha_1)214 y = math.sin(delta_alpha) * math.cos(phi_2)215 x = math.cos(phi_1) * math.sin(phi_2) - math.sin(phi_1) * math.cos(phi_2) * math.cos(delta_alpha)216 angle = math.atan2(y, x)217 bearing = int((angle * 180 / math.pi + 360) % 360)218 if '0' == dis:219 pygame.draw.circle(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 240), 5, 5)220 elif 0 <= bearing < 90:221 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 240),222 (x_screen // 2 + 405, y_screen // 16 + 225), 4)223 elif 90 <= bearing < 180:224 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 240),225 (x_screen // 2 + 420, y_screen // 16 + 240), 4)226 elif 180 <= bearing < 270:227 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 240),228 (x_screen // 2 + 405, y_screen // 16 + 255), 4)229 elif 270 <= bearing < 360:230 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 255),231 (x_screen // 2 + 390, y_screen // 16 + 240), 4)232 print(dis)233234235def checking_distance_5(game_location, guess_location, distance=0):236 guess = guess_location237 location_1 = geolocator.geocode(guess)238 location_2 = geolocator.geocode(game_location)239 loc1 = (location_1.latitude, location_1.longitude)240 loc2 = (location_2.latitude, location_2.longitude)241 dis = str(int(geodesic(loc1, loc2).km))242 guess1 = font_2.render(guess, True, (255, 51, 153))243 distance = font_2.render(dis, True, (255, 51, 153))244 screen.blit(guess1, guess1.get_rect(center=(x_screen // 2 + 150, y_screen // 16 + 310)))245 screen.blit(distance, distance.get_rect(center=(x_screen // 2 + 290, y_screen // 16 + 310)))246 if dis == '0':247 pygame.draw.rect(screen, true_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 290, 100, 40), 2, 5)248 else:249 pygame.draw.rect(screen, false_color, pygame.Rect(x_screen // 2 + 100, y_screen // 16 + 290, 100, 40), 2, 5)250251 alpha_1 = loc1[1] * (math.pi / 180)252 alpha_2 = loc2[1] * math.pi / 180253 phi_1 = loc1[0] * math.pi / 180254 phi_2 = loc2[0] * math.pi / 180255 delta_alpha = (alpha_2 - alpha_1)256 y = math.sin(delta_alpha) * math.cos(phi_2)257 x = math.cos(phi_1) * math.sin(phi_2) - math.sin(phi_1) * math.cos(phi_2) * math.cos(delta_alpha)258 angle = math.atan2(y, x)259 bearing = int((angle * 180 / math.pi + 360) % 360)260 if '0' == dis:261 pygame.draw.circle(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 310), 5, 5)262 elif 0 <= bearing < 90:263 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 310),264 (x_screen // 2 + 405, y_screen // 16 + 295), 4)265 elif 90 <= bearing < 180:266 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 310),267 (x_screen // 2 + 420, y_screen // 16 + 310), 4)268 elif 180 <= bearing < 270:269 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 310),270 (x_screen // 2 + 405, y_screen // 16 + 325), 4)271 elif 270 <= bearing < 360:272 pygame.draw.line(screen, location_color, (x_screen // 2 + 405, y_screen // 16 + 325),273 (x_screen // 2 + 390, y_screen // 16 + 310), 4)274 print(dis)275276# def checking_distance(x, game_location, guess_location, distance = 0):277# guess_1 = ''278# guess_2 = ''279# guess_3 = ''280# guess_4 = ''281# guess_5 = ''282# dis_1 = ''283# dis_2 = ''284# if x == 1:285# guess_1 = guess_location286# location_1 = geolocator.geocode(game_location)287# location_2 = geolocator.geocode(guess_1)288# loc1 = (location_1.latitude, location_1.longitude)289# loc2 = (location_2.latitude, location_2.longitude)290# dis_1 = str(int(geodesic(loc1, loc2).km))291# guess1 = font_2.render(guess_1, True, (255, 51, 153))292# distance_1 = font_2.render(dis_1, True, (255, 51, 153))293# screen.blit(guess1, guess1.get_rect(center = (x_screen// 2 + 150, y_screen//16 + 30)))294# screen.blit(distance_1, distance_1.get_rect(center = (x_screen// 2 + 290, y_screen//16 + 30)))295# print(dis_1)296# if x == 2:297# guess_2 = guess_location298#299# location_1 = geolocator.geocode(game_location)300# location_2 = geolocator.geocode(guess_2)301# loc1 = (location_1.latitude, location_1.longitude)302# loc2 = (location_2.latitude, location_2.longitude)303# dis_2 = str(int(geodesic(loc1, loc2).km))304#305# screen.blit(guess1, guess1.get_rect(center = (x_screen// 2 + 150, y_screen//16 + 30)))306# screen.blit(distance_1, distance_1.get_rect(center = (x_screen// 2 + 290, y_screen//16 + 30)))307# print(dis_1)308#309# guess2 = font_2.render(guess_2, True, (255, 51, 153))310# distance_2 = font_2.render(dis_2, True, (255, 51, 153))311# screen.blit(guess2, guess2.get_rect(center = (x_screen// 2 + 150, y_screen//16 + 100)))312# screen.blit(distance_2, distance_2.get_rect(center = (x_screen// 2 + 290, y_screen//16 + 100)))313# print(dis_2)314315316def getting_guess():317 guess = str(input('doan dia diem: '))318 return guess319320321x = 1322exit = False323guess_1 = ''324guess_2 = ''325guess_3 = ''326guess_4 = ''327guess_5 = ''328guess_6 = ''329while not exit:330 for event in pygame.event.get():331 if event.type == pygame.QUIT:332 exit = True333 timer.tick(fps)334 screen.fill(background_color)335 screen.blit(wordle, wordle.get_rect(center=(x_namegame - 55, 20)))336 screen.blit(vietnam, vietnam.get_rect(center=(x_namegame + 55, 20)))337 draw_checking_distance()338 print(x)339 if x == 1:340 guess_1 = getting_guess()341 checking_distance_1(guess_location=guess_1, game_location=game_location)342 if x == 2:343 guess_2 = getting_guess()344 checking_distance_1(guess_location=guess_1, game_location=game_location)345 checking_distance_2(guess_location=guess_2, game_location=game_location)346 if x == 3:347 guess_3 = getting_guess()348 checking_distance_1(guess_location=guess_1, game_location=game_location)349 checking_distance_2(guess_location=guess_2, game_location=game_location)350 checking_distance_3(guess_location=guess_3, game_location=game_location)351 if x == 4:352 guess_4 = getting_guess()353 checking_distance_1(guess_location=guess_1, game_location=game_location)354 checking_distance_2(guess_location=guess_2, game_location=game_location)355 checking_distance_3(guess_location=guess_3, game_location=game_location)356 checking_distance_4(guess_location=guess_4, game_location=game_location)357 if x == 5:358 guess_5 = getting_guess()359 checking_distance_1(guess_location=guess_1, game_location=game_location)360 checking_distance_2(guess_location=guess_2, game_location=game_location)361 checking_distance_3(guess_location=guess_3, game_location=game_location)362 checking_distance_4(guess_location=guess_4, game_location=game_location)363 checking_distance_5(guess_location=guess_5, game_location=game_location)364 if x == 6:365 guess_6 = getting_guess()366 pygame.display.update()367 pygame.display.flip()368 x += 1369 # checking_distance(x, game_location, guess_location)370 # if x == 1:371 # guess_location = str(input())372 # checking_distance(x, game_location, guess_location)
...
nativescript-geolocation.js
Source:nativescript-geolocation.js
1"use strict";2Object.defineProperty(exports, "__esModule", { value: true });3var application_1 = require("application");4var platform_1 = require("platform");5var enums_1 = require("ui/enums");6var timer_1 = require("timer");7var trace_1 = require("trace");8var nativescript_geolocation_common_1 = require("./nativescript-geolocation-common");9var locationListeners = {};10var watchId = 0;11var androidLocationManager;12function getAndroidLocationManager() {13 if (!androidLocationManager) {14 androidLocationManager = application_1.android.context15 .getSystemService(android.content.Context.LOCATION_SERVICE);16 }17 return androidLocationManager;18}19function createLocationListener(successCallback) {20 var locationListener = new android.location.LocationListener({21 onLocationChanged: function (location1) {22 var locationCallback = this._onLocation;23 if (locationCallback) {24 locationCallback(locationFromAndroidLocation(location1));25 }26 },27 onProviderDisabled: function (provider) {28 },29 onProviderEnabled: function (provider) {30 },31 onStatusChanged: function (arg1, arg2, arg3) {32 }33 });34 watchId++;35 locationListener._onLocation = successCallback;36 locationListener.id = watchId;37 locationListeners[watchId] = locationListener;38 return locationListener;39}40function locationFromAndroidLocation(androidLocation) {41 var location = new nativescript_geolocation_common_1.Location();42 location.latitude = androidLocation.getLatitude();43 location.longitude = androidLocation.getLongitude();44 location.altitude = androidLocation.getAltitude();45 location.horizontalAccuracy = androidLocation.getAccuracy();46 location.verticalAccuracy = androidLocation.getAccuracy();47 location.speed = androidLocation.getSpeed();48 location.direction = androidLocation.getBearing();49 location.timestamp = new Date(androidLocation.getTime());50 location.android = androidLocation;51 return location;52}53function androidLocationFromLocation(location) {54 var androidLocation = new android.location.Location("custom");55 androidLocation.setLatitude(location.latitude);56 androidLocation.setLongitude(location.longitude);57 if (location.altitude) {58 androidLocation.setAltitude(location.altitude);59 }60 if (location.speed) {61 androidLocation.setSpeed(float(location.speed));62 }63 if (location.direction) {64 androidLocation.setBearing(float(location.direction));65 }66 if (location.timestamp) {67 try {68 androidLocation.setTime(long(location.timestamp.getTime()));69 }70 catch (e) {71 console.error("invalid location timestamp");72 }73 }74 return androidLocation;75}76function criteriaFromOptions(options) {77 var criteria = new android.location.Criteria();78 if (options && options.desiredAccuracy <= enums_1.Accuracy.high) {79 criteria.setAccuracy(android.location.Criteria.ACCURACY_FINE);80 }81 else {82 criteria.setAccuracy(android.location.Criteria.ACCURACY_COARSE);83 }84 return criteria;85}86function watchLocationCore(errorCallback, options, locListener) {87 var criteria = criteriaFromOptions(options);88 try {89 var updateTime = (options && typeof options.minimumUpdateTime === "number") ?90 options.minimumUpdateTime :91 nativescript_geolocation_common_1.minTimeUpdate;92 var updateDistance = (options && typeof options.updateDistance === "number") ?93 options.updateDistance :94 nativescript_geolocation_common_1.minRangeUpdate;95 getAndroidLocationManager().requestLocationUpdates(updateTime, updateDistance, criteria, locListener, null);96 }97 catch (e) {98 LocationMonitor.stopLocationMonitoring(locListener.id);99 errorCallback(e);100 }101}102function enableLocationServiceRequest(currentContext, successCallback, successArgs, errorCallback, errorArgs) {103 if (!isEnabled()) {104 var onActivityResultHandler_1 = function (data) {105 application_1.android.off(application_1.AndroidApplication.activityResultEvent, onActivityResultHandler_1);106 if (data.requestCode === 0) {107 if (isEnabled()) {108 if (successCallback) {109 successCallback.apply(this, successArgs);110 }111 }112 else {113 if (errorCallback) {114 errorCallback.apply(this, errorArgs);115 }116 }117 }118 application_1.android.off(application_1.AndroidApplication.activityResultEvent, onActivityResultHandler_1);119 };120 application_1.android.on(application_1.AndroidApplication.activityResultEvent, onActivityResultHandler_1);121 var LOCATION_SETTINGS = android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS;122 currentContext.startActivityForResult(new android.content.Intent(LOCATION_SETTINGS), 0);123 }124 else {125 if (successCallback) {126 successCallback.apply(this, successArgs);127 }128 }129}130function enableLocationRequestCore(successCallback, successArgs, errorCallback, errorArgs) {131 var currentContext = application_1.android.currentContext;132 if (parseInt(platform_1.device.sdkVersion) >= 23) {133 var activityRequestPermissionsHandler_1 = function (data) {134 if (data.requestCode === 5000) {135 var PERMISSION_GRANTED = android.content.pm.PackageManager.PERMISSION_GRANTED;136 if (data.grantResults.length > 0 && data.grantResults[0] === PERMISSION_GRANTED) {137 enableLocationServiceRequest(currentContext, successCallback, successArgs, errorCallback, errorArgs);138 }139 else {140 if (errorCallback) {141 errorCallback.apply(this, errorArgs);142 }143 }144 }145 application_1.android.off(application_1.AndroidApplication.activityRequestPermissionsEvent, activityRequestPermissionsHandler_1);146 };147 application_1.android.on(application_1.AndroidApplication.activityRequestPermissionsEvent, activityRequestPermissionsHandler_1);148 var res = android.support.v4.content.ContextCompat149 .checkSelfPermission(currentContext, android.Manifest.permission.ACCESS_FINE_LOCATION);150 if (res === -1) {151 android.support.v4.app.ActivityCompat152 .requestPermissions(currentContext, ["android.permission.ACCESS_FINE_LOCATION"], 5000);153 }154 else {155 enableLocationServiceRequest(currentContext, successCallback, successArgs, errorCallback, errorArgs);156 }157 }158 else {159 enableLocationServiceRequest(currentContext, successCallback, successArgs, errorCallback, errorArgs);160 }161}162function watchLocation(successCallback, errorCallback, options) {163 var zonedSuccessCallback = global.zonedCallback(successCallback);164 var zonedErrorCallback = global.zonedCallback(errorCallback);165 var locListener = createLocationListener(zonedSuccessCallback);166 if (!isEnabled()) {167 var notGrantedError = new Error("Location service is not enabled or using it is not granted.");168 enableLocationRequestCore(watchLocationCore, [169 zonedSuccessCallback,170 zonedErrorCallback,171 options,172 locListener173 ], zonedErrorCallback, [notGrantedError]);174 }175 else {176 watchLocationCore(zonedErrorCallback, options, locListener);177 }178 return locListener.id;179}180exports.watchLocation = watchLocation;181function getCurrentLocation(options) {182 options = options || {};183 if (options.timeout === 0) {184 return new Promise(function (resolve, reject) {185 var lastLocation = LocationMonitor.getLastKnownLocation();186 if (lastLocation) {187 if (typeof options.maximumAge === "number") {188 if (lastLocation.timestamp.valueOf() + options.maximumAge > new Date().valueOf()) {189 resolve(lastLocation);190 }191 else {192 reject(new Error("Last known location too old!"));193 }194 }195 else {196 resolve(lastLocation);197 }198 }199 else {200 reject(new Error("There is no last known location!"));201 }202 });203 }204 return new Promise(function (resolve, reject) {205 var locListener;206 var enabledCallback = function (ecbResolve, ecbReject, ecbOptions) {207 var successCallback = function (location) {208 LocationMonitor.stopLocationMonitoring(locListener.id);209 if (ecbOptions && typeof ecbOptions.maximumAge === "number") {210 if (location.timestamp.valueOf() + ecbOptions.maximumAge > new Date().valueOf()) {211 ecbResolve(location);212 }213 else {214 ecbReject(new Error("New location is older than requested maximum age!"));215 }216 }217 else {218 ecbResolve(location);219 }220 };221 locListener = LocationMonitor.createListenerWithCallbackAndOptions(successCallback, ecbOptions);222 try {223 getAndroidLocationManager().requestSingleUpdate(criteriaFromOptions(ecbOptions), locListener, null);224 }225 catch (e) {226 ecbReject(e);227 }228 if (ecbOptions && typeof ecbOptions.timeout === "number") {229 var timerId_1 = timer_1.setTimeout(function () {230 timer_1.clearTimeout(timerId_1);231 LocationMonitor.stopLocationMonitoring(locListener.id);232 ecbReject(new Error("Timeout while searching for location!"));233 }, ecbOptions.timeout || nativescript_geolocation_common_1.defaultGetLocationTimeout);234 }235 };236 var permissionDeniedCallback = function (pdcReject) {237 pdcReject(new Error("Location service is not enabled or using it is not granted."));238 };239 if (!isEnabled()) {240 enableLocationRequestCore(enabledCallback, [resolve, reject, options], permissionDeniedCallback, [reject]);241 }242 else {243 enabledCallback(resolve, reject, options);244 }245 });246}247exports.getCurrentLocation = getCurrentLocation;248function clearWatch(_watchId) {249 LocationMonitor.stopLocationMonitoring(_watchId);250}251exports.clearWatch = clearWatch;252function enableLocationRequest(always) {253 return new Promise(function (resolve, reject) {254 if (isEnabled()) {255 resolve();256 return;257 }258 var enabledCallback = function (ecbResolve, ecbReject) {259 ecbResolve();260 };261 var permissionDeniedCallback = function (pdcReject) {262 pdcReject(new Error("Location service is not enabled or using it is not granted."));263 };264 enableLocationRequestCore(enabledCallback, [resolve], permissionDeniedCallback, [reject]);265 });266}267exports.enableLocationRequest = enableLocationRequest;268function isEnabled() {269 var criteria = new android.location.Criteria();270 criteria.setAccuracy(android.location.Criteria.ACCURACY_COARSE);271 var enabledProviders = getAndroidLocationManager().getProviders(criteria, true);272 return (enabledProviders.size() > 0) ? true : false;273}274exports.isEnabled = isEnabled;275function distance(loc1, loc2) {276 if (!loc1.android) {277 loc1.android = androidLocationFromLocation(loc1);278 }279 if (!loc2.android) {280 loc2.android = androidLocationFromLocation(loc2);281 }282 return loc1.android.distanceTo(loc2.android);283}284exports.distance = distance;285var LocationMonitor = (function () {286 function LocationMonitor() {287 }288 LocationMonitor.getLastKnownLocation = function () {289 var criteria = new android.location.Criteria();290 criteria.setAccuracy(android.location.Criteria.ACCURACY_COARSE);291 try {292 var iterator = getAndroidLocationManager().getProviders(criteria, false).iterator();293 var androidLocation = void 0;294 while (iterator.hasNext()) {295 var provider = iterator.next();296 var tempLocation = getAndroidLocationManager().getLastKnownLocation(provider);297 if (!androidLocation || tempLocation.getTime() > androidLocation.getTime()) {298 androidLocation = tempLocation;299 }300 }301 if (androidLocation) {302 return locationFromAndroidLocation(androidLocation);303 }304 }305 catch (e) {306 trace_1.write("Error: " + e.message, "Error");307 }308 return null;309 };310 LocationMonitor.startLocationMonitoring = function (options, listener) {311 var updateTime = (options && typeof options.minimumUpdateTime === "number") ?312 options.minimumUpdateTime :313 nativescript_geolocation_common_1.minTimeUpdate;314 var updateDistance = (options && typeof options.updateDistance === "number") ?315 options.updateDistance :316 nativescript_geolocation_common_1.minRangeUpdate;317 getAndroidLocationManager().requestLocationUpdates(updateTime, updateDistance, criteriaFromOptions(options), listener, null);318 };319 LocationMonitor.createListenerWithCallbackAndOptions = function (successCallback, options) {320 return createLocationListener(successCallback);321 };322 LocationMonitor.stopLocationMonitoring = function (locListenerId) {323 var listener = locationListeners[locListenerId];324 if (listener) {325 getAndroidLocationManager().removeUpdates(listener);326 delete locationListeners[locListenerId];327 }328 };329 return LocationMonitor;330}());...
setup.py
Source:setup.py
1from math import isnan2import placemaker3'''4 Area for yahoo placemaker and other 5 location finding functions6'''7YAHOO_APPID = 'dj0yJmk9OG9SNGFTbmphTTZiJmQ9WVdrOVMxVnBhbXh3TldjbWNHbzlNamcyTXpnek1EWXkmcz1jb25zdW1lcnNlY3JldCZ4PTMw'8YAHOO_TYPES = ['Commune', 9 'Municipality', 10 'District', 11 'Ward',12 'POI', 13 'Town', 14 'Suburb', 15 'Postal Code',16 'LocalAdmin',17 'County', 18 'Zip']19p = placemaker.placemaker(YAHOO_APPID)20 21def encode_utf8(s):22 if isinstance(s, unicode):23 return s.encode('utf-8')24 try:25 s.decode('utf-8')26 return str(s)27 except:28 pass29 try:30 return str(s.encode('utf-8'))31 except:32 res = ''.join([unichr(ord(c)) for c in s])33 return str(res.encode('utf-8'))34 35def get_coordinates_from_text(text):36 # use yahoo placemaker to search for locations37 try:38 location = p.find_places(encode_utf8(text))39 time.sleep(0.1)40 except Exception, e:41 print 'Error in placemaker: %s' % e42 time.sleep(5)43 location = []44 if len(location) == 0:45 return None46 location = location[0]47 print 'output %s - %s' % (location.placetype, location.name)48 #if location.placetype in YAHOO_TYPES:49 return [location.centroid.latitude, 50 location.centroid.longitude]51 print 'nothing for ' + text52 return None53 54location_cache = {}55'''56 Putting user info in a dictionary57'''58'''59user_info = {}60user_info_file = pd.read_csv("users.csv")61# Populate dictionary62for user in user_info_file.iterrows():63 user = user[1]64 location = None65 66 # process location67 if isinstance(user['location'], str):68 if user['location'] in location_cache:69 location = location_cache[user['location']]70 else:71 location = get_coordinates_from_text(user['location'])72 if location:73 location_cache[user['location']] = location74 else:75 location = None76 77 78 user_info[user['user_id']] = {79 'birth': user['birthyear'],80 'gender': user['gender'],81 'location': location,82 }83 84# Alternate code for writing to mongo85data = json.loads(open('data', 'r').read())86for uid, user in data.iteritems():87 user['id'] = int(uid)88 user_info.insert([user])89'''90 91'''92 Create attendance dictionaries93 Provided in both directions94'''95'''96def update_attendance(uid, eid, att_type):97 attendance.update(98 {'uid': uid, 'eid': eid},99 {'$set': {'uid': uid, 'eid': eid, att_type: True}}, 100 upsert=True)101chunks = pd.read_csv("events.csv", iterator=True, chunksize=1000)102count = 0103for chunk in chunks:104 print count105 count += 1000106 107 for e in chunk.iterrows():108 e = e[1]109 eid = e['event_id']110 uid = e['user_id']111 112 update_attendance(uid, eid, 'yes')113 update_attendance(uid, eid, 'interested')114''' 115 116'''117 Populate events dictionary118'''119'''120chunks = pd.read_csv("events.csv", iterator=True, chunksize=1000)121count = 0122for chunk in chunks:123 print count124 count += 1000125 #if count < 1564000:126 # continue127 for e in chunk.iterrows():128 e = e[1]129 eid = e['event_id']130 location = None131 if e['lat'] and e['lng'] and not isnan(e['lat']) and not isnan(e['lng']):132 location = [e['lat'], e['lng']]133 elif e['city'] or e['state'] or e['country']:134 loc_string = '%s, %s, %s' % (e['city'], e['state'], e['country'])135 if loc_string in location_cache:136 location = location_cache[loc_string]137 else:138 location = get_coordinates_from_text(loc_string)139 if location:140 location_cache[loc_string] = location141 142 words = list(e[9:110])143 event = {144 'id': eid,145 'location': location,146 'words': words147 }148 event_info.insert([event])149 150chunks = pd.read_csv("events.csv", iterator=True, chunksize=1000)151count = 0152for chunk in chunks:153 print count154 count += 1000155 for e in chunk.iterrows():156 e = e[1]157 eid = e['event_id']158 uid = e['user_id']159 # add creator to event attendance collection160 update_attendance(uid, eid, 'yes')161 update_attendance(uid, eid, 'interested')162''' 163 164'''165 Insert train data into attendance collection166'''167'''168train = pd.read_csv( "train.csv", converters={"timestamp": parse})169for pair in train.iterrows():170 pair = pair[1]171 uid = pair['user']172 eid = pair['event']173 for attr in ['invited', 'interested', 'not_interested']:174 if pair[attr]:175 update_attendance(uid, eid, attr)176'''177''' 178 Process event_attendees file to update attendance collection179'''180'''181event_attendees = pd.read_csv("event_attendees.csv")182for event in event_attendees.iterrows():183 event = event[1]184 eid = event['event']185 for attr in ['yes', 'maybe', 'invited', 'no']:186 users = event[attr]187 if isinstance(users, float):188 continue189 users = [int(u) for u in users.split()]190 for uid in users:191 update_attendance(uid, eid, attr)192'''193''' 194 Process friends file195'''196'''197friends_file = pd.read_csv('user_friends.csv')198friends_dict = {}199# create friends data in memory200for record in friends_file.iterrows():201 record = record[1]202 uid1 = record['user']203 if uid1 not in friends_dict:204 friends_dict[uid1] = []205 friends = record['friends']206 if isinstance(friends, float):207 continue208 friends = [int(u) for u in record['friends'].split()]209 for uid2 in friends:210 friends_dict[uid1].append(uid2)211 212# copy data to mongo213for uid, friends in friends_dict.iteritems():214 record = {215 'uid': uid,216 'friends': list(friends)217 }218 friends_db.insert([record])219'''220''' 221 Fill out missing location222'''223user_sure = {}224event_sure = {}225for user in user_info.find():226 if user['location']:227 user_sure[user['id']] = user['location']228 229for event in event_info.find():230 if event['location']:231 event_sure[event['id']] = event['location']232 233count = 0234for event in event_info.find():235 count += 1236 if count % 10000 == 0:237 print count238 location = event['location']239 if location:240 if len(location) == 2 and isinstance(location[0], float) and \241 (isnan(location[0]) or isnan(location[1])):242 location = None243 else:244 if isinstance(location[0], list):245 location = [tuple(l) for l in location]246 else:247 location = tuple(location)248 249 event_info.update({'id': event['id']},250 {'$set': {'location': location}})251 252count = 0253updated = 0254for event in event_info.find():255 count += 1256 if count % 1000 == 0:257 print count258 259 if event['id'] in event_locations:260 continue261 262 attend = attendance.find({'eid': event['id']})263 votes = {}264 265 for a in attend:266 if 'yes' not in a:267 continue268 if a['uid'] in user_sure:269 location = user_sure[a['uid']]270 if isinstance(location[0], float) or isinstance(location[0], int):271 location = [location]272 for l in location:273 l = tuple(l)274 votes[l] = votes.get(l, 0) + 1275 276 if not votes: 277 continue278 279 votes = votes.items()280 votes.sort(key=lambda x: -x[1])281 votes = votes[:5]282 if len(votes) > 1 and votes[0][1] > 3 * votes[1][1]:283 votes = [votes[1]]284 285 votes = [list(v[0]) for v in votes]286 287 if len(votes) == 1:288 votes = votes[0]289 290 print votes291 updated += 1292 event_info.update({'id': event['id']},293 {'$set': {'location': votes}})294 295 296count = 0297updated = 0298for user in user_info.find():299 count += 1300 if count % 1000 == 0:301 print count302 303 if user['id'] in user_sure:304 continue305 306 attend = attendance.find({'uid': user['id']})307 votes = {}308 309 for a in attend:310 if a['eid'] in event_sure:311 location = event_sure[a['eid']]312 if isinstance(location[0], float) or isinstance(location[0], int):313 location = [location]314 for l in location:315 votes[tuple(l)] = votes.get(tuple(l), 0) + 1316 317 if not votes: 318 continue319 320 votes = votes.items()321 votes.sort(key=lambda x: -x[1])322 votes = votes[:5]323 if len(votes) > 1 and votes[0][1] > 3 * votes[1][1]:324 votes = [votes[1]]325 326 votes = [list(v[0]) for v in votes]327 user_sure[user['id']] = votes328 329 updated += 1330 user_info.update({'id': user['id']},331 {'$set': {'location': votes}})332 333for user in user_info.find():334 if not user['location']:335 continue336 user_info.update({'id': user['id']},337 {'$set': {'location': tuple(user['location'])}})338 339user_dict = list(user_info.find())340user_dict = {u['id']:u for u in user_dict}341# create event profiles based on users342event_ids = set([])343for u in user_info.find():344 if u['age']:345 attends = attendance.find({'uid': u['id']})346 347 348count = event_info.count()349for e in event_info.find():350 attends = attendance.find({'eid': e['id']})351 count -= 1352 if count % 10000 == 0:353 print count354 ages = []355 sexes = {'male':0, 'female':0}356 for at in attends:357 if 'yes' not in attends:358 continue359 uid = at['uid']360 if uid in user_dict:361 a = user_dict[uid]['age']362 if a:363 ages.append(a)364 365 if ages:366 age = np.mean(ages)367 print age368 break369 event_info.update({'id': e['id']},370 {'$set': {'age': age}})371 372 373 374user_info_file = pd.read_csv("users.csv")375updated = 0376for user in user_info_file.iterrows():377 user = user[1]378 location = None379 380 if user['user_id'] in user_sure:381 continue382 383 # process location384 if isinstance(user['location'], str):385 location = get_coordinates_from_text(user['location'])386 else:387 location = None388 389 if location:390 updated += 1391 user_sure[user['user_id']] = [location]392 user_info.update({'id': user['user_id']},393 {'$set': {'location': [location]}})394 395 396count = 0397updated = 0398friends_info = {}399for user in user_info.find():400 count += 1401 if count % 1000 == 0:402 print count403 404 if user['id'] in user_sure:405 continue406 407 friends = friends_db.find_one({'uid': user['id']})408 friends = friends['friends']409 friends = list(user_info.find({'id':{'$in': friends}}))410 friends_info[user['id']] = friends411updated = 0412for uid, friends in friends_info.iteritems():413 s = 0414 nr = 0415 416 for f in friends:417 if f['age']:418 s += f['age']419 nr += 1420 if nr:421 guess = s * 1.0 / nr422 user_info.update({'id': uid},423 {'$set': {'age': guess}})424 updated += 1425 426 427count = 0428event_locations = {}429for e in event_info.find():430 count += 1431 if count % 10000 == 0:432 print count433 if e['location']:434 event_locations[e['id']] = e['location']435 436count = 0437updated = 0438for event in event_info.find():439 count += 1440 if count % 10000 == 0:441 print count442 443 location = event['location']444 if location:445 continue446 loc_string = event_locations.get(event['id'])447 if not loc_string or loc_string == 'nan, nan, nan':448 continue449 450 if loc_string in location_cache:451 location = location_cache[loc_string]452 else:453 location = get_coordinates_from_text(loc_string)454 if location:455 location_cache[loc_string] = location456 457 if location:458 updated += 1459 event_info.update({'id': event['id']},460 {'$set': {'location': location}})461 462for u in user_info.find():463 a = u['birth']464 try:465 a = int(a)466 if a < 1940:467 a = None468 else:469 a = 2013 - a470 except:471 a = None472 ages[a] = ages.get(a, 0) + 1473 user_info.update({'id': u['id']},474 {'$set': {'age': a}})475 476user_sure = {}477for u in user_info.find():478 a = u['age']479 if a:480 user_sure[u['id']] = a481 482 483# set user timezone from file484user_info_file = pd.read_csv("users.csv")485user_tz = {}486updated = 0487for user in user_info_file.iterrows():488 user = user[1]489 tz = user['timezone']490 if math.isnan(tz):491 tz = None492 user_tz[user['user_id']] = tz493 494for uid, tz in user_tz.iteritems():495 user_info.update({'id': uid},496 {'$set': {'timezone': tz}})497 498# propagate timezone499etz = {}500for a in attendance.find():501 eid = a['eid']502 uid = a['uid']503 if uid not in user_tz:504 continue505 if 'yes' not in a and 'maybe' not in a:506 continue507 if eid not in etz:508 etz[eid] = {}509 tz = user_tz[a['uid']]510 etz[eid][tz] = etz[eid].get(tz, 0) + 1 511 512etzf = {}513for eid, tz_dict in etz.iteritems():514 tzl = tz_dict.items()515 tzl.sort(key=lambda x: -x[1])516 etzf[eid] = tzl[0]517 518 519count = len(etzf)520for eid, tz in etzf.iteritems():521 count -= 1522 if count % 10000 == 0:523 print count524 event_info.update({'id': eid},525 {'$set': {'timezone': tz}})526 527 528 529chunks = pd.read_csv("events.csv", iterator=True, chunksize=10000)530count = 0531for chunk in chunks:532 print count533 count += 10000534 for e in chunk.iterrows():535 e = e[1]536 t = e['start_time']537 t = parse(t)538 t = time.mktime(t.timetuple())539 event_info.update({'id': e['event_id']},...
test_trace_parser.py
Source:test_trace_parser.py
...37 builder = TraceTreeBuilder()38 trace = builder \39 .start_test("Andreas") \40 .start_unit("Tommy") \41 .enter_location("1") \42 .end_unit() \43 .end_test() \44 .build()45 sequence = [ *trace.sequence ]46 self.assertEqual(len(sequence), 1)47 location_1: Location = sequence[0]48 self.assertIsInstance(location_1, Location)49 self.assertEqual(location_1.test.name, "Andreas")50 self.assertEqual(location_1.unit.name, "Tommy")51 self.assertEqual(location_1.id, "1")52 def test_trace_tree_builder_two_units_two_locations_test_trace(self) -> None:53 builder = TraceTreeBuilder()54 trace = builder \55 .start_test("Andreas") \56 .start_unit("Tommy1") \57 .enter_location("1") \58 .start_unit("Tommy2") \59 .enter_location("2") \60 .end_unit() \61 .end_unit() \62 .end_test() \63 .build()64 sequence = [ *trace.sequence ]65 self.assertEqual(len(sequence), 2)66 location_1: Location = sequence[0]67 self.assertEqual(location_1.test.name, "Andreas")68 self.assertEqual(location_1.unit.name, "Tommy1")69 self.assertEqual(location_1.id, "1")70 location_2: Location = sequence[1]71 self.assertEqual(location_2.test.name, "Andreas")72 self.assertEqual(location_2.unit.name, "Tommy2")73 self.assertEqual(location_2.id, "2")74 75 self.assertEqual(location_1.test, location_2.test)76 def test_trace_tree_builder_two_units_three_locations_test_trace(self) -> None:77 builder = TraceTreeBuilder()78 trace = builder \79 .start_test("Andreas") \80 .start_unit("Tommy1") \81 .enter_location("1") \82 .start_unit("Tommy2") \83 .enter_location("2") \84 .end_unit() \85 .enter_location("3") \86 .end_unit() \87 .end_test() \88 .build()89 sequence = [ *trace.sequence ]90 self.assertEqual(len(sequence), 3)91 location_1: Location = sequence[0]92 self.assertEqual(location_1.unit.name, "Tommy1")93 self.assertEqual(location_1.id, "1")94 location_2: Location = sequence[1]95 self.assertEqual(location_2.unit.name, "Tommy2")96 self.assertEqual(location_2.id, "2")97 location_3: Location = sequence[2]98 self.assertEqual(location_3.unit.name, "Tommy1")99 self.assertEqual(location_3.id, "3")100 101 self.assertEqual(location_1.test, location_2.test)102 self.assertEqual(location_2.test, location_3.test)103 def test_trace_tree_builder_many_units_many_locations_test_trace(self) -> None:104 builder = TraceTreeBuilder()105 trace = builder \106 .start_test("Andreas") \107 .start_unit("Tommy1") \108 .enter_location("1") \109 .start_unit("Tommy2") \110 .enter_location("2") \111 .enter_location("3") \112 .start_unit("Tommy3") \113 .enter_location("4") \114 .end_unit() \115 .enter_location("5") \116 .end_unit() \117 .enter_location("6") \118 .start_unit("Tommy4") \119 .enter_location("7") \120 .start_unit("Tommy5") \121 .enter_location("8") \122 .end_unit() \123 .enter_location("9") \124 .end_unit() \125 .enter_location("10") \126 .end_unit() \127 .end_test() \128 .build()129 sequence = [ *trace.sequence ]130 self.assertEqual(len(sequence), 10)131 location_1: Location = sequence[0]132 self.assertEqual(location_1.test.name, "Andreas")133 self.assertEqual(location_1.unit.name, "Tommy1")134 self.assertEqual(location_1.id, "1")135 location_2: Location = sequence[1]136 self.assertEqual(location_2.test.name, "Andreas")137 self.assertEqual(location_2.unit.name, "Tommy2")138 self.assertEqual(location_2.id, "2")139 location_3: Location = sequence[2]140 self.assertEqual(location_3.test.name, "Andreas")141 self.assertEqual(location_3.unit.name, "Tommy2")142 self.assertEqual(location_3.id, "3")143 location_4: Location = sequence[3]144 self.assertEqual(location_4.test.name, "Andreas")145 self.assertEqual(location_4.unit.name, "Tommy3")146 self.assertEqual(location_4.id, "4")147 location_5: Location = sequence[4]148 self.assertEqual(location_5.test.name, "Andreas")149 self.assertEqual(location_5.unit.name, "Tommy2")150 self.assertEqual(location_5.id, "5")151 location_6: Location = sequence[5]152 self.assertEqual(location_6.test.name, "Andreas")153 self.assertEqual(location_6.unit.name, "Tommy1")154 self.assertEqual(location_6.id, "6")155 location_7: Location = sequence[6]156 self.assertEqual(location_7.test.name, "Andreas")157 self.assertEqual(location_7.unit.name, "Tommy4")158 self.assertEqual(location_7.id, "7")159 location_8: Location = sequence[7]160 self.assertEqual(location_8.test.name, "Andreas")161 self.assertEqual(location_8.unit.name, "Tommy5")162 self.assertEqual(location_8.id, "8")163 location_9: Location = sequence[8]164 self.assertEqual(location_9.test.name, "Andreas")165 self.assertEqual(location_9.unit.name, "Tommy4")166 self.assertEqual(location_9.id, "9")167 location_10: Location = sequence[9]168 self.assertEqual(location_10.test.name, "Andreas")169 self.assertEqual(location_10.unit.name, "Tommy1")170 self.assertEqual(location_10.id, "10")171 def test_trace_in_unit(self) -> None:172 builder = TraceTreeBuilder()173 trace = builder \174 .start_test("Andreas") \175 .start_unit("Tommy1") \176 .enter_location("1") \177 .start_unit("Tommy2") \178 .enter_location("2") \179 .enter_location("3") \180 .start_unit("Tommy3") \181 .enter_location("4") \182 .end_unit() \183 .enter_location("5") \184 .end_unit() \185 .enter_location("6") \186 .start_unit("Tommy4") \187 .enter_location("7") \188 .start_unit("Tommy5") \189 .enter_location("8") \190 .end_unit() \191 .enter_location("9") \192 .end_unit() \193 .enter_location("10") \194 .end_unit() \195 .end_test() \196 .build()197 actual = [ *trace.in_unit("Tommy1") ]198 self.assertEqual(len(actual), 3)199 location_1: Location = actual[0]200 self.assertEqual(location_1.test.name, "Andreas")201 self.assertEqual(location_1.unit.name, "Tommy1")202 self.assertEqual(location_1.id, "1")203 location_6: Location = actual[1]204 self.assertEqual(location_6.test.name, "Andreas")205 self.assertEqual(location_6.unit.name, "Tommy1")206 self.assertEqual(location_6.id, "6")207 location_10: Location = actual[2]...
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!!