How to use escape_list method in Kiwi

Best Python code snippet using Kiwi_python

boj_17090.py

Source:boj_17090.py Github

copy

Full Screen

1# 매우 오랜 시간이 걸렸다.2# 처음부터 제대로 설계를 하지 않으면 매우 힘들어질 수 있다는 것을 이 문제를 통해서 알게 되었다.3# 항상 문제 분석과 설계를 철저히 하자고 생각했지만 잘 지키지 못했는데, 이번 문제를 통해서 그 점을 반성하게 되었다...4# 풀이는 335번 줄 이후부터터5# N x M 사이즈의 미로에서 U, D, L, R의 명령에 따라 이동했을 때 미로의 경계 밖으로 탈출이 가능하게 하는 칸은 몇개일까?6# 탈출 가능한 "칸"이라는 데 주목해야겠다. BFS처럼 큐에 방향을 넣어가는 식의 이동이 아니라 그 칸의 명령을 그대로 따라만 가야 한다.7# 결국 모든 칸에 대해서 탐색을 해야 할 필요가 생긴다. 시간 초과 안날까? DFS로 구성한다면 최대 재귀 깊이를 가볍게 넘어버릴 것 같다.8# N과 M 전부 최대 데이터인 500이라고 가정했을 때, 최대 25,000칸에 대한 탐색을 해야 한다. 시간 제한은 1초다..9# 우선 기본적인 DFS를 만들어보자. 이 방식은 분명 시간 초과가 날 것이다.10# 실제로 시간 초과가 났다.11# 1차 시도12# import sys13# sys.setrecursionlimit(200000)14# dx = [-1, 1, 0, 0] # UDLR15# dy = [0, 0, -1, 1]16#17# def DFS(x, y):18# global cnt19# # print(cnt)20# visited[x][y] = 121# move_number = move_set.index(arr[x][y])22# tx, ty = x + dx[move_number], y + dy[move_number]23#24# if 0 > tx or tx >= N or 0 > ty or ty >= M: # 기본 명령 : 0 <= tx < N and 0 <= ty < M25# cnt += 126# elif 0 <= tx < N and 0 <= ty < M and not visited[tx][ty]:27# DFS(tx, ty)28#29# N, M = map(int, sys.stdin.readline().split())30# arr = [list(sys.stdin.readline().rstrip()) for _ in range(N)]31#32# cnt = 033# move_set = ['U', 'D', 'L', 'R']34#35# for i in range(N):36# for j in range(M):37# visited = [[0] * M for _ in range(N)]38# DFS(i, j)39#40# print(cnt)41# 생각해보니, 시간을 줄일법한 생각이 들었다.42# 예를 들어, 한 좌표에서 명령을 따라 이동해 미로를 탈출했다.43# 추후에 방문하는 다른 좌표에서, 앞서 탈출한 경로의 지점을 방문한다면, 그 점 역시 탈출이 가능한 점이 되지 않을까?44# 어차피 같은 경로를 따라서 갈 것이기 때문이다.45# 또는 탐색의 시작점이 탈출 경로 중 한 점인 경우, 볼 것도 없이 탈출이 가능한 좌표이다.46# 이 방법의 관건은 탈출이 가능한 좌표를 얼마나 빨리 만나느냐이다.47# 만약 매우 큰 사이즈의 미로에서 탈출 지점이 가장 마지막 좌표라면, 결국 전부 다 순회하게 되는건데 그러면 똑같이 시간초과가 난다.48# 우선 (0, 0)부터 쭉 탐색하면서 방문표시를 새롭게 하고, 탈출한 지점이 나오면 해당 방문 좌표를 별도의 리스트에 담는다.49# 만약 탈출하지 않은 경우 방문표시를 위한 리스트를 초기화한다.50# 2차 시도51# 90% 시간초과 ㅠㅠㅠㅠㅠㅠ52# 혹시 위에서 생각했던 문제(탈출이 가능한 좌표가 배열의 최후반부에만 존재하는 경우)가 원인이었나 싶어서 (0, 0)이 아닌 거꾸로 탐색하는 방법을53# 시도했지만.. 여전히 90%에서 초과가 됬다. 뭔가 다른 방법이 필요하다. BFS로는 어떨까?54# import sys55# sys.setrecursionlimit(100000)56#57# dx = [-1, 1, 0, 0] # UDLR58# dy = [0, 0, -1, 1]59#60# def DFS(x, y):61# global cnt62# if (x, y) in escape_list:63# cnt += 164# return65#66# visited.add((x, y))67# move_number = move_set.index(arr[x][y])68# tx, ty = x + dx[move_number], y + dy[move_number]69#70# if 0 > tx or tx >= N or 0 > ty or ty >= M: # 기본 명령 : 0 <= tx < N and 0 <= ty < M71# cnt += 172# elif 0 <= tx < N and 0 <= ty < M and (tx, ty) not in visited:73# DFS(tx, ty)74#75# N, M = map(int, sys.stdin.readline().split())76# arr = [list(sys.stdin.readline().rstrip()) for _ in range(N)]77# escape_list = set()78# cnt = 079# move_set = ['U', 'D', 'L', 'R']80#81# for i in range(N):82# for j in range(M):83# visited = set()84# temp = cnt85# DFS(i, j)86# if temp != cnt:87# escape_list = escape_list | visited88#89# print(cnt)90# 3차 시도91# BFS로 바꾸어보았지만 역시 같은 지점에서 실패92# import sys93# from collections import deque94#95# dx = [-1, 1, 0, 0] # UDLR96# dy = [0, 0, -1, 1]97#98# def BFS(x, y):99# global cnt100# Q = deque()101# Q.append([x, y])102# visited.add((x, y))103#104# while Q:105# new_x, new_y = Q.popleft()106# move_number = move_set.index(arr[new_x][new_y])107# tx, ty = new_x + dx[move_number], new_y + dy[move_number]108#109# if 0 > tx or tx >= N or 0 > ty or ty >= M: # 기본 명령 : 0 <= tx < N and 0 <= ty < M110# cnt += 1111# elif 0 <= tx < N and 0 <= ty < M and (tx, ty) not in visited:112# visited.add((tx, ty))113# Q.append(tx, ty)114#115# N, M = map(int, sys.stdin.readline().split())116# arr = [list(sys.stdin.readline().rstrip()) for _ in range(N)]117# escape_list = set()118# cnt = 0119# move_set = ['U', 'D', 'L', 'R']120#121# for i in range(N):122# for j in range(M):123# visited = set()124# temp = cnt125# BFS(i, j)126# if temp != cnt:127# escape_list = escape_list | visited128#129# print(cnt)130# 4차 시도131# 실패했던 지점의 좌표도 저장해두면 어떨까...?132# import sys133# sys.setrecursionlimit(100000)134#135# dx = [-1, 1, 0, 0] # UDLR136# dy = [0, 0, -1, 1]137#138# def DFS(x, y):139# global cnt140# if (x, y) in escape_list:141# cnt += 1142# return143#144# if (x, y) not in escape_list and (x, y) in fail_list:145# return146#147# visited.add((x, y))148# move_number = move_set.index(arr[x][y])149# tx, ty = x + dx[move_number], y + dy[move_number]150#151# if 0 > tx or tx >= N or 0 > ty or ty >= M: # 기본 명령 : 0 <= tx < N and 0 <= ty < M152# cnt += 1153# elif 0 <= tx < N and 0 <= ty < M and (tx, ty) not in visited:154# DFS(tx, ty)155#156# N, M = map(int, sys.stdin.readline().split())157# arr = [list(sys.stdin.readline().rstrip()) for _ in range(N)]158# escape_list = set()159# fail_list = set()160# cnt = 0161# move_set = ['U', 'D', 'L', 'R']162#163# for i in range(N):164# for j in range(M):165# visited = set()166# temp = cnt167# DFS(i, j)168# if temp != cnt:169# escape_list = escape_list | visited170# else:171# fail_list = fail_list | visited172#173# print(cnt)174#175#176#177# import sys178# from collections import deque179#180# dx = [-1, 1, 0, 0] # UDLR181# dy = [0, 0, -1, 1]182#183#184# def BFS(x, y):185# global cnt186# Q = deque()187# Q.append([x, y])188# escape_list = set()189# escape_list.add((x, y))190# visited[x][y] = 1191#192# while Q:193# new_x, new_y = Q.popleft()194# if check[x][y]:195# for a, b in escape_list:196# check[a][b] = 1197# cnt += 1198# return199#200# move_number = move_set.index(arr[new_x][new_y])201# tx, ty = new_x + dx[move_number], new_y + dy[move_number]202#203#204# # if 0 > tx or tx >= N or 0 > ty or ty >= M:205# if (not (0 <= tx < N)) or (not (0 <= ty < M)):206# for a, b in escape_list:207# check[a][b] = 1208# cnt += 1209# elif check[tx][ty] == -1:210# for a, b in escape_list:211# check[a][b] = -1212# return213# elif not visited[tx][ty]:214# visited[tx][ty] = 1215# escape_list.add((tx, ty))216# Q.append((tx, ty))217#218# for a, b in escape_list:219# check[a][b] = -1220# return221#222# N, M = map(int, sys.stdin.readline().split())223# arr = [list(sys.stdin.readline().rstrip()) for _ in range(N)]224# visited = [[0] * M for _ in range(N)]225# check = [[0] * M for _ in range(N)]226# cnt = 0227# move_set = ['U', 'D', 'L', 'R']228#229# for i in range(N):230# for j in range(M):231# if check[i][j] == -1:232# continue233# elif check[i][j]:234# cnt += 1235# continue236#237# BFS(i, j)238#239# print(cnt)240#241# #242# import collections243# import sys244# from collections import deque245# def bfs(y, x):246# global cnt247# q = deque([(y, x)])248#249# # dp에 탈출할 수 있는 여부를 표시하기 위한 course250# course = set()251# course.add((y, x))252# # 방문 체크253# # visited = [[0] * m for _ in range(n)]254# visited[y][x] = 1255# while q:256# y, x = q.popleft()257# # 탈출할 수 있는 곳이면 여태까지 방문했던 곳을 dp에 표시258# if dp[y][x]:259# for value in course:260# dp[value[0]][value[1]] = 1261# cnt += 1262# return263# # 조건에 따라 움직임264# if area[y][x] == 'U':265# y -= 1266# elif area[y][x] == 'R':267# x += 1268# elif area[y][x] == 'D':269# y += 1270# else:271# x -= 1272#273# # 탈출 했다면 방문한 곳을 dp에 표시274# if (not (0 <= y < n)) or (not (0 <= x < m)):275# for value in course:276# dp[value[0]][value[1]] = 1277# cnt += 1278# # 탈출 불가능 하다면 방문한 곳을 dp에 표시279# elif (dp[y][x] == -1):280# for value in course:281# dp[value[0]][value[1]] = -1282# return283# # 아니면 다음 과정284# elif not visited[y][x]:285# visited[y][x] = 1286# course.add((y, x))287# q.append((y, x))288# # 여기까지 왔으면 탈출 불가능하므로 dp에 표시289# for value in course:290# dp[value[0]][value[1]] = -1291# return292#293#294# n, m = map(int, sys.stdin.readline().split())295# area = [sys.stdin.readline() for _ in range(n)]296# dp = [[0] * m for _ in range(n)]297# visited = [[0] * m for _ in range(n)]298# cnt = 0299# for i in range(n):300# for j in range(m):301# # 탈출할 수 없는 곳인지?302# if (dp[i][j] == -1):303# continue304# # 탈출할 수 있는 곳인지?305# elif dp[i][j]:306# cnt += 1307# continue308#309# # 둘 다 아니면310# bfs(i, j)311# print(cnt)312import sys313from collections import deque314dx = [-1, 1, 0, 0] # UDLR315dy = [0, 0, -1, 1]316def find(x, y):317 global cnt318 # 만약 해당 좌표가 이전 좌표를 탐색하는 과정에서 탈출이 가능한 경로로 이미 추가되었다면, 바로 종료시켜 불필요한 연산을 줄인다.319 if (x, y) in success: return320 Q = deque()321 Q.append([x, y])322 # visit = [[0] * m for _ in range(n)]323 # visit[x][y] = 1324 move_number = move_set.index(area[x][y]) # 구석 칸에 위치한 명령(방향)을 인식325 tx, ty = x + dx[move_number], y + dy[move_number] # 방향에 맞게 위치를 조정326 if not (0 <= tx < n) or not (0 <= ty < m): # 미로를 탈출했을까?327 success.add((x, y)) # 탈출했다면 해당 좌표를 탈출 리스트에 추가하고328 cnt += 1 # 탈출 가능한 칸의 수를 추가해주자329 # 해당 구석 좌표로 탈출이 가능한 것을 확인했다.330 # 이제 인접한 방향의 좌표들을 확인해나갈 차례이다! 만약 인접한 좌표의 명령이 탈출이 가능한 구석 좌표이거나,331 # 해당 구석 좌표를 향해 갈 수 있는 곳이라면 구석이 아닌 그 좌표도 역시 탈출할 수 있는 좌표가 된다.332 # (좌표를 따라 가면 탈출이 가능한 구석 좌표를 만날 것이고, 그러면 탈출이 가능하기 때문에)333 while Q:334 Q_x, Q_y = Q.popleft()335 for k in range(4):336 new_tx, new_ty = Q_x + dx[k], Q_y + dy[k] # 원래의 좌표와 인접한 네 방향의 좌표를 순차적으로 탐색한다.337 if 0 <= new_tx < n and 0 <= new_ty < m: # 인접한 방향의 좌표가 배열의 범위를 벗어나지 않은 경우338 target_number = move_set.index(area[new_tx][new_ty])339 target_x, target_y = new_tx + dx[target_number], new_ty + dy[target_number] # 인접한 좌표의 명령에 따라 이동한 새로운 좌표340 # 만약 새롭게 이동한 좌표가 기존의 Q_x, Q_y와 동일하다면?341 # Q_x, Q_y로부터 인접한 좌표인 new_tx, new_ty 역시 탈출이 가능한 좌표라는 것을 의미한다.342 # 따라서 Q에 new_tx, new_ty를 추가해 추가적인 탈출 경로가 있는지 탐색해나간다.343 if target_x == Q_x and target_y == Q_y:344 success.add((new_tx, new_ty))345 cnt += 1346 # visit[new_tx][new_ty] = 1347 Q.append([new_tx, new_ty])348n, m = map(int, sys.stdin.readline().split())349area = [sys.stdin.readline() for _ in range(n)]350# visit = [[0] * m for _ in range(n)]351corner = [] # 구석 좌표를 담기 위한 리스트352success = set() # 탈출에 성공하거나, 탈출이 가능한 경로인 경우 해당 좌표를 담기 위한 집합353cnt = 0354move_set = ['U', 'D', 'L', 'R'] # 상하좌우의 순서이고, 추후 인접한 방향을 찾아나갈 때 해당 좌표에서의 방향값을 인덱스로 활용하기 위해 사용355# 구석 좌표만 따로 모아주는 과정356for i in range(n):357 for j in range(m):358 if i == 0 or i == n - 1:359 corner.append([i, j])360 elif j == 0 and area[i][j] not in corner or j == m - 1 and area[i][j] not in corner:361 corner.append([i, j])362# 구석 좌표들을 대상으로 검사363for i, j in corner:364 find(i, j)365# 탈출할 수 있는 칸의 개수를 출력...

Full Screen

Full Screen

main.py

Source:main.py Github

copy

Full Screen

1import re2import logging3from asyncio import shield4from typing import NoReturn5import discord6from discord import ChannelType as ct, Option7from discord.utils import escape_markdown8import metallum9from decouple import config10logger = logging.getLogger("discord")11logger.setLevel(logging.DEBUG)12handler = logging.FileHandler(13 filename="discord.log", encoding="utf-8", mode="w"14)15handler.setFormatter(16 logging.Formatter("%(asctime)s:%(levelname)s:%(name)s: %(message)s")17)18logger.addHandler(handler)19BOT_TOKEN = config("BOT_TOKEN")20BASE_URL = "https://metal-archives.com/"21PRE_M = ":heavy_minus_sign:\n\n"22SUF_M = "\n\n:heavy_minus_sign:"23HELP_STANDARD = (24 ":regional_indicator_h: :regional_indicator_a: :regional_indicator_i:"25 " :regional_indicator_l: :bangbang: \t:metal: :robot:\n\nUse the command"26 " `/metallum` to perform a search.\n\nParameters:\n__query:__ the text"27 " used in the search.\n\n__exact:__ whether to search for the exact query"28 " or not (more info below). Must be either **True** or"29 " **False**.\n\n__**STANDARD SEARCH**__:\n\nWhen the __exact__ parameter"30 " is **True**, searching for 'black sabbath' will only find bands named"31 " EXACTLY 'Black Sabbath' (case-insensitive, though).\n\nHowever, when"32 " __exact__ is **False**, the same search will find all bands with BOTH"33 " 'black' and 'sabbath' in their names, regardless of any other words and"34 " in whatever order, like the band 'Sabbath Black Heretic'.\n\nIf the"35 " first part of the __query__ is a number, you may find a band registered"36 " under that __ID__ on the website, if there's any (the ID is the number"37 " at the end of the band's URL). The search will then continue to look for"38 " bands matching the entire query (including that number) in their"39 " names.\n\nFor example: `/metallum query: 7 sins exact: True` would give"40 " you the band with ID '7', which is 'Entombed' and then search for bands"41 " called '7 Sins' (exact match, in this case).\nNote that searching for"42 " '13' will give you both the band with ID '13' and the band called"43 " '13'.\n\n"44)45HELP_ADVANCED = (46 "__**ADVANCED SEARCH**__:\n\nThe options below only work when"47 " __exact__ is set to **False**...\n\nIn addition to those results"48 " describe above, if you also want bands that contain EITHER 'black' OR"49 " 'sabbath' (not necessarily both), you can search for `black || sabbath`"50 " (or `sabbath || black`, for that matter).\n\nNote, however, that those"51 " words must appear in their entirety in the band's name. Meaning a 'hell'"52 " search won't find 'helloween', for instance.\nBut don't worry, you can"53 " use __asterisks__ as wildcards: `hell*`, `*hell` and `*hell*` are all"54 " valid queries. The asterisk means that the word can be extended by any"55 " amount of characters **in that direction**.\n\nFinally, another thing"56 " you can do is exclude words from the results: `black -sabbath` will find"57 " bands with the word 'black', but exclude those with the word"58 " 'sabbath'.\n\nYou can also combine all of the above, of course!"59)60class Band:61 def __init__(self, band: metallum.Band, albums: bool = True):62 escaped_band = self.escape_band(band)63 self.name: str = escaped_band["name"]64 # print(self.name)65 self.genres: str = escaped_band["genres"]66 # print(self.genres)67 self.status: str = escaped_band["status"]68 # print(self.status)69 self.location: str = escaped_band["location"]70 # print(self.location)71 self.country: str = escaped_band["country"]72 # print(self.country)73 self.formed_in: str = escaped_band["formed_in"]74 # print(self.formed_in)75 self.themes: str = escaped_band["themes"]76 if albums:77 full_albums = band.albums.search(type="full-length")78 # print("Full albums: " + str(full_albums))79 self.albums: str = (80 "This band has no full-length albums. Check their page below"81 " for other releases."82 if full_albums == []83 else "\n".join(84 [85 f"**({str(a.year)})** {escape_markdown(a.title)}"86 for a in full_albums87 ]88 )89 )90 # print(self.albums)91 self.url: str = escape_markdown(BASE_URL + band.url)92 # print(self.url)93 self._info: str = "\n\n".join(94 [95 f"__**{self.name}**__",96 f"__*GENRES*__: {self.genres}",97 f"__*LOCATION*__: {self.location}, {self.country}",98 f"__*FORMED IN*__: {self.formed_in}",99 f"__*STATUS*__: {self.status}",100 f"__*THEMES*__: {self.themes}",101 (f"__*ALBUMS*__: \n{self.albums}" if albums else ""),102 f"__*PAGE*__: {self.url}",103 ]104 ).replace("\n\n\n\n", "\n\n")105 def __str__(self):106 return self._info107 def escape_band(self, band: metallum.Band):108 escape_list = list(109 map(110 lambda x: escape_markdown(x),111 [112 band.name,113 ", ".join(band.genres),114 band.status,115 band.location,116 band.country,117 band.formed_in,118 ", ".join(band.themes),119 ],120 )121 )122 escaped_band = {123 "name": escape_list[0],124 "genres": escape_list[1],125 "status": escape_list[2],126 "location": escape_list[3],127 "country": escape_list[4],128 "formed_in": escape_list[5],129 "themes": escape_list[6],130 }131 return escaped_band132class Search:133 def __init__(134 self,135 query: str,136 send_to: discord.ApplicationContext.channel,137 strict: bool = True,138 albums: bool = True,139 page_start: int = 0,140 ):141 self.query = query142 self.send_to = send_to143 self.strict = strict144 self.albums = albums145 self.page_start = page_start146 async def search(self) -> NoReturn:147 await shield(148 self.send_to.send(149 PRE_M150 + (151 "Performing strict search!"152 if self.strict153 else (154 "Performing advanced search:"155 f" {escape_markdown(self.query)}"156 )157 )158 )159 )160 try:161 band_list = metallum.band_search(162 self.query, strict=self.strict, page_start=self.page_start163 )164 if not band_list:165 raise IndexError166 await shield(167 self.send_to.send(168 f"{PRE_M}Found {band_list.result_count} band(s)!\n\nHere"169 " we go!"170 )171 )172 for i, band_result in enumerate(band_list):173 band = Band(band_result.get(), self.albums)174 band_pos = f"{i+1+self.page_start}/{band_list.result_count}"175 print(band)176 bot_response = "\n\n".join(177 [178 str(band),179 band_pos,180 ]181 )182 await shield(self.send_to.send(f"{PRE_M}{bot_response}"))183 if (i + 1) % 200 == 0:184 new_search = Search(185 self.query,186 self.send_to,187 self.strict,188 self.albums,189 self.page_start + 200,190 )191 await shield(new_search.search())192 return193 except IndexError:194 await shield(195 self.send_to.send(196 f"{PRE_M}No band was found. Remember, I only know METAL"197 " bands! \U0001F918\U0001F916"198 )199 )200bot = discord.Bot()201@bot.event202async def on_ready():203 print("Logged on as {0}!".format(bot.user))204@bot.slash_command(205 name="helper",206 description="Learn how to search!",207)208async def helper(ctx: discord.ApplicationContext):209 await shield(ctx.respond(HELP_STANDARD))210 await shield(ctx.respond(HELP_ADVANCED))211@bot.slash_command(212 name="metallum",213 description="Use /helpers for instructions!",214)215async def metallum_search(216 ctx: discord.ApplicationContext,217 query: Option(str, "The search you wanna perform", required=True),218 exact: Option(219 bool,220 description=(221 "Whether the search results should match the exact query."222 " True or False."223 ),224 ),225):226 try:227 print(228 "\n\n"229 + "*" * 10230 + f"\n\nSearch by: {ctx.author}\nQuery: {query}\nExact:"231 f" {exact}\nData: {ctx.interaction.data}\n\n"232 + "*" * 10233 + "\n\n"234 )235 except Exception as e:236 print(f"Debug exception: {e}")237 try:238 send_to = await shield(239 ctx.interaction.channel.create_thread(240 name=f"Metallum search, query='{query}', exact={exact}",241 type=ct.public_thread,242 auto_archive_duration=60,243 )244 )245 await shield(246 ctx.respond(247 "Search initiated, please refer to the thread:"248 f" {send_to.mention}"249 )250 )251 await shield(252 send_to.send(253 f"{ctx.author} used: `/metallum query: '{query}'"254 f" exact: '{exact}'` \n\nStandby for results! \U0001F916"255 )256 )257 except (258 discord.Forbidden,259 discord.HTTPException,260 discord.InvalidArgument,261 ) as e:262 print(f"Exception in thread handling: {e}")263 await shield(ctx.respond("Something went wrong!"))264 send_to = ctx.interaction.channel265 except AttributeError as ae:266 print(f"Thread attribute error: {ae}")267 send_to = ctx.interaction.channel268 await shield(ctx.respond("Search initialized!"))269 args = query.split()270 if re.search(r"^\d+$", args[0]):271 try:272 result = metallum.band_for_id(args[0])273 if result.id != args[0]:274 raise ValueError275 band = Band(result)276 print(band)277 await send_to.send(278 f"{PRE_M}Found a band with ID: '{args[0]}'\n\n{band}"279 )280 except ValueError as v:281 print(f"ValueError in search: {v}")282 except (283 discord.Forbidden,284 discord.HTTPException,285 discord.InvalidArgument,286 ) as e:287 print(f"Exception sending band_for_id result: {e}")288 name_search = Search(query, send_to, exact)289 await shield(name_search.search())290 try:291 await shield(292 ctx.interaction.edit_original_message(293 content=(294 "Search **completed**, please refer to the thread:"295 f" {send_to.mention}"296 )297 )298 )299 except Exception as e:300 print(f"Failed to edit response: {e}")...

Full Screen

Full Screen

eval.py

Source:eval.py Github

copy

Full Screen

...95 score.append((loss_val, loss_test, acc_val, acc_test))96 # save97 save_to_csv(filename=score_filename, header=[98 'val_loss', 'test_loss', 'val_accuracy', 'test_accuracy', ], list_to_save=score, data_type='float,float,float,float')99def get_escape_list(infl_filename, n_to_remove):100 infl_list = read_csv(infl_filename)101 infl_arr = np.array(infl_list)102 header = infl_list[0]103 idx_ds = header.index('datasource_index')104 escape_list = infl_arr[1:1+n_to_remove, idx_ds].astype(int).tolist()105 return escape_list106def run_train_for_eval(model_info_dict, file_dir_dict, n_to_remove, retrain_all):107 os.environ['NNABLA_CUDNN_DETERMINISTIC'] = '1'108 os.environ['NNABLA_CUDNN_ALGORITHM_BY_HEURISTIC'] = '1'109 # files and dirs110 infl_filename = file_dir_dict['infl_filename']111 # gpu/cpu112 ctx = get_context(model_info_dict['device_id'])113 nn.set_default_context(ctx)114 # train115 escape_list = get_escape_list(infl_filename, n_to_remove)116 retrain(model_info_dict, file_dir_dict,...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Kiwi automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful