class CiUtils(object): def init_ci(self, path, is_local): self.logger = LogController() self.fileManager = FileManager(path) if not is_local: self.logger.header('generating env file...') self.ENV_FILE = self.get_env_content() self.fileManager.write_str(self.ENV_FILE) self.logger.greenText(f'Env file:\n{self.ENV_FILE}') else: self.logger.greenText('Running with env file local') def get_env_content(self): env = f""" ENGINE_PORT=8080 SECRET_KEY=\"{get_random_secret_key()}\" OIDC_RP_REALM_NAME="" OIDC_RP_CLIENT_ID="" OIDC_OP_LOGOUT_ENDPOINT="" OIDC_RP_SCOPES="" OIDC_RP_CLIENT_SECRET="" OIDC_OP_TOKEN_ENDPOINT="" OIDC_OP_AUTHORIZATION_ENDPOINT="" OIDC_RP_SIGN_ALGO="" OIDC_RP_SERVER_URL="" OIDC_OP_USER_ENDPOINT="" OIDC_OP_JWKS_ENDPOINT="" BILLING_COST_PER_WHATSAPP=199 BILLING_TEST_MODE=True """.replace(" ", "").strip() return env def execute(self, command, is_printing=False): os.chdir(os.getcwd()) self.logger.blueText(command) try: command_output = subprocess.check_output( command, shell=True).decode('utf-8') self.logger.success() if is_printing: self.logger.coloredText(command_output) res = 0 except subprocess.CalledProcessError as e: res = 1 self.logger.fail( e.stdout.decode("utf-8").replace("\n", "\n ").strip()) return res def run_ci(self, path, is_local: bool): self.init_ci(path, is_local) ok = self.execute('python manage.py migrate') ok += self.execute('python manage.py collectstatic --noinput', False) ok += self.execute('flake8 connect/', False) if self.execute('coverage run manage.py test --verbosity=2 --noinput', False) == 0: ok += self.execute('coverage report -m', True) else: ok += 1 if ok > 0: exit(1)
def getMatrixFromFile(self, name): fileManager = FileManager() matrixString = fileManager.getVectorTxt(name) matrix = self.__createMatrixArray(matrixString) return matrix
def getVectorFromFile(self, name): fileManager = FileManager() vectorString = fileManager.getVectorTxt(name) vector = self.__createVectorArray(vectorString) return vector
def __init__(self, submission_data: SubmissionData, config: Config): self.submission_name: str = submission_data.name self.filename = submission_data.file_name # TODO remove this dependency self.exe_name = config.exe_filename self.functions_data: List[FunctionData] = submission_data.functions self.path_manager = PathManager("submission-checker", submission_data, config) self.file_manager = FileManager(self.path_manager) self.input_handler = InputHandler(True)
def init_ci(self, path, is_local): self.logger = LogController() self.fileManager = FileManager(path) if not is_local: self.logger.header('generating env file...') self.ENV_FILE = self.get_env_content() self.fileManager.write_str(self.ENV_FILE) self.logger.greenText(f'Env file:\n{self.ENV_FILE}') else: self.logger.greenText('Running with env file local')
class Calendar(object): def __init__(self, filename): self.filename = filename def __enter__(self): self.fManager = FileManager(self.filename) self.events = self.fManager.readEvents() self.painter = Painter() return self def __exit__(self, exc_type, exc_val, exc_tb): self.fManager.rewriteEvents(self.events) def draw(self): self.painter.draw(self.events)
def index(): now = datetime.datetime.now() ip = request.remote_addr pokemon = RandomPkmon().random_pkmon() info = pokemon["base_info"] stats = pokemon["statistic"] num = info["num"] name = info["name"] level = info["level"] moves = pokemon["moves"] dt = DamagesTimes() type_index1 = dt.get_type_index(info["type1"]) type_index2 = dt.get_type_index(info["type2"]) gifname = '%s.gif' % num # moves=pokemon["moves"] move_index1 = dt.get_type_index(moves["move1"]["type"]) move_index2 = dt.get_type_index(moves["move2"]["type"]) move_index3 = dt.get_type_index(moves["move3"]["type"]) move_index4 = dt.get_type_index(moves["move4"]["type"]) context = "%s 用户%s 遇到了 LV.%s %s" % (now, ip, level, name) FileManager().save2log(context) return render_template('index.html', filename=gifname, info=info, pokemon=stats, type_index1=type_index1, type_index2=type_index2, moves=moves, move_index1=move_index1, move_index2=move_index2, move_index3=move_index3, move_index4=move_index4)
def battlewith(self, mypkmon, wild_pkmon): # 首先派出自己的精灵 # 双方精灵加入战斗场景(写入文本文件) battle_manger = {'player': mypkmon, 'enemy': wild_pkmon} # print(battle_manger) # 测试获取的等级 pkmoninfo = battle_manger["player"]["base_info"] print("该你上场了,去吧,%s!\n" % pkmoninfo['name']) FileManager().save_battle_env(battle_manger) BattleProcess().start(battle_manger) print("over")
def __init__(self): self.log_manager = FileManager("log.csv", _default_log_values) self.command_manager = FileManager("commands.csv", _default_command_values) self.configuration_manager = FileManager("configuration.csv", _default_configuration_values)
def __init__(self): QtGui.QMainWindow.__init__(self) # Setup self.setupUi(self) # Attributes self.fin = Fin() # Fin is an attribute: loaded fin self.fm = FileManager() # File I/O # Initialize the table self.__updateTable() # print self.tab_inpoints.item(1,1).text() # print self.tab_inpoints.rowCount() self.__connectWidgets()
class SubmissionChecker: def __init__(self, submission_data: SubmissionData, config: Config): self.submission_name: str = submission_data.name self.filename = submission_data.file_name # TODO remove this dependency self.exe_name = config.exe_filename self.functions_data: List[FunctionData] = submission_data.functions self.path_manager = PathManager("submission-checker", submission_data, config) self.file_manager = FileManager(self.path_manager) self.input_handler = InputHandler(True) def start_session(self): self.file_manager.unzip_all_files(self.confirm) for student in self.file_manager.students_list: self.file_manager.create_test_dir(student) self.evaluate_submission(student) def evaluate_submission(self, student): content = self.file_manager.get_file_content(student, self.filename) if content: tester = Tester(self.path_manager.get_test_path(student), self.filename, self.exe_name, student, content) res = True while res: print("\n\n*** checking submission from " + student) write_message(student) # TODO EW next two lines content = self.file_manager.get_file_content( student, self.filename) tester.reload_content(content) print(tester.content) for func in self.functions_data: self.run_tests(tester, func) res = self.confirm(Confirmations.RECHECK_SUBMISSION) def run_tests(self, tester: Tester, func): print(f"*** {OKBLUE}testing function {func.name} {ENDC}***") write_message("\t" + func.name) tester.change_function(func.name) for test in func.tests: # TODO test.f_input instead of test.input try: tester.run(test.input, test.output) except CalledProcessError: print("check this out") comment = self.confirm(Confirmations.ADDITIONAL_COMMENTS) if comment: write_message(comment) def confirm(self, confirmation): return self.input_handler.confirm(confirmation)
def select(self, data, myself, aims): # move = None # 获取当前攻击方 attacker = data[myself]["base_info"] pkmon_name = attacker["name"] battle_info = data[myself]["battle_info"] moves = battle_info["moves"] if myself == "player": # choose = int(input()) choose = random.randint(1, 4) if choose == 1: move = 'move1' elif choose == 2: move = 'move2' elif choose == 3: move = 'move3' elif choose == 4: move = 'move4' else: print("啥都没做") else: move = "move" + str(random.randint(1, 4)) # 选其中一个技能 moveinfo = moves[move] print("%s使出了%s" % (pkmon_name, moveinfo["name"])) # 计算是否命中 isHit = self.is_move_accuracy(moveinfo, data, myself, aims) if isHit is True: # 判断技能类型进行伤害计算后返回计算后的值 data = self.move_effect(moveinfo, data, myself, aims) # 保存伤害计算结果 FileManager().save_battle_env(data)
# Insert current date and time to spreadsheet. if data: newSheet.insert_row([str(datetime.now())], 2) # from the files that are downloaded, get them and put them in google sheets # assumption: the .csv files are deleted after inserted into google sheets. def putFilesInGoogleSheets(self, filemanager): content = filemanager.mergeCSVFiles().read() sheet = self.client.open('cryptoscreener') print(sheet) self.client.import_csv(sheet.id, content) bot = TradingviewBot() manager = FileManager() sUpdater = SpreadsheetUpdater(bot.args['pair']) print(bot.args['pair']) # bot.signIn() # print('Sign in stage completed') # # bot.downloadAll() # print('download stage completed') sUpdater.putFilesInGoogleSheets(manager) print('Files in google sheets stage completed') newSheet = sUpdater.openNewSheet() sUpdater.searchAndCopy(newSheet, manager) print('Search and copy stage completed')
# we had issues with this mainly for test 9. ESTR.resetESTR() time.sleep(0.5) # send the desired test number to the ESTR COM.sendStr(item) ################################ MAIN LOOP ########################################## printMenu() # Make an object to represent the Stellaris and reset device. ESTR = LoadTest() ESTR.resetESTR() # Create two log files. One for raw COM port data, the other # for interpreted test results. dataLog = FileManager("logs/datalog{}.txt") resultLog = FileManager("logs/resultlog{}.txt") #try to open the COM port to connect to ESTR try: COM = Comms("COM39", 115200*2) #57600 #203400 except: quit_event.set() print("COM port could not be opened! Exiting...") # Create a queue to communicate between COM producer thread # and COM worker thread. COMQueue = Queue.Queue() # Create three daemom threads, one to read the COM port, one to # work on the COM data and the last to read the command line interface
if args.path is None or \ args.maillist is None or \ args.timeDiff is None or \ args.file is None or \ args.screen is None or \ args.siteName is None or \ args.isCSV is None: print('One of the parameter missing.') sys.exit(0) if os.path.isdir(args.path) is not True: print('Directory Not exist.') sys.exit(0) f = FileManager() f.setFile(args.file) def sendMailtoDIH(screen=False, timeAhead=False): global emailtoDIH if not emailtoDIH: print('sending to dih') config = configparser.ConfigParser() config.read('./Config/mailList.ini') if config.has_section('dih.support'): senderList = [x[1] for x in config.items('dih.support')] config.clear() config.read('./Config/messages.cfg') messageList = [x[1] for x in config.items('dih.support')] service = Mail()
import sys from fileManager import FileManager from VMTranslator import VMTranslator if __name__ == "__main__": files = sys.argv files = files[1:] fm = FileManager() if (len(files) == 0): print('At least one .vm file must be passed to the program') exit() else: file_name = '' translator = VMTranslator() trans_lines = [translator.init_MIPS_ASM()] print(files[0]) fm.write(files[0], trans_lines) for i in files: lines = fm.read(i) if (i.find('\\') != -1): file_name = i[i.rfind('\\') + 1:i.rfind('.')] else: file_name = i[:i.rfind('.')] trans_lines.append(translator.translate(lines, file_name)) fm.write(files[0], trans_lines)
def execute(): global spritesMatrix, piecesMatrix, playerMove, movesCount, log, playerColor, AIColor, missedPiecesPlayer catched = False #permite saber si ya ha elegido una pieza sprite = "" piece = "" done = False endGame = False winnerColor = "Partida sin concluir" iniX = 0 iniY = 0 iniPosI = 0 iniPosJ = 0 iniMatrix = FileManager.getMatrix() locate(iniMatrix) startCol = FileManager.getStartColor() AICol = FileManager.getAIColor() inteligence = AI() posibleMoves = [] if (AICol == startCol): playerMove = False else: playerMove = True if (('B' in AICol) or ('b' in AICol) or ('w' in AICol) or ('W' in AICol)): AIColor = "Blanco" playerColor = "Negro" else: AIColor = "Negro" playerColor = "Blanco" inteligence.missedPieces = FileManager.getMissedPieces(iniMatrix, AIColor) missedPiecesPlayer = FileManager.getMissedPieces(iniMatrix, playerColor) drawInfo(endGame, winnerColor) textBox.Draw() isMusicPlaying = True while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True if event.type == pygame.KEYDOWN: if (event.key == 27): done = True elif (event.key == 109 or event.key == 32): if (isMusicPlaying): pygame.mixer.music.stop() isMusicPlaying = False else: pygame.mixer.music.play(-1) isMusicPlaying = True if event.type == pygame.MOUSEBUTTONDOWN: if (event.button == 4): if (boardSurface.collidepoint(pygame.mouse.get_pos())): textBox.MoveUp() drawInfo(endGame, winnerColor) textBox.Draw() if (event.button == 5): if (boardSurface.collidepoint(pygame.mouse.get_pos())): textBox.MoveDown() drawInfo(endGame, winnerColor) textBox.Draw() if (event.button == 3): catched = False coorX = roundBy75(pygame.mouse.get_pos()[0]) coorY = roundBy75(pygame.mouse.get_pos()[1]) loc = buscarIndice(coorX, coorY) if (event.button == 1 and playerMove and loc != (-1, -1) and not (endGame)): if (not catched): iniPosI = loc[0] iniPosJ = loc[1] iniX = coorX iniY = coorY sprite = spritesMatrix[loc[0]][loc[1]] piece = piecesMatrix[loc[0]][loc[1]] if ((sprite in whitePieces) and ('B' in playerColor) and (sprite != "")): catchSound.play() catched = True posibleMoves = rules.GetListOfValidMoves( piecesMatrix, playerColor, (iniPosI, iniPosJ)) elif ((sprite in blackPieces) and ('N' in playerColor) and (sprite != "")): catchSound.play() catched = True posibleMoves = rules.GetListOfValidMoves( piecesMatrix, playerColor, (iniPosI, iniPosJ)) else: if (rules.IsLegalMove(piece, piecesMatrix, (iniPosI, iniPosJ), (loc[0], loc[1])) and not (rules.DoesMovePutPlayerInCheck( piecesMatrix, playerColor, (iniPosI, iniPosJ), (loc[0], loc[1])))): spritesMatrix[iniPosI][iniPosJ] = "" piecesMatrix[iniPosI][iniPosJ] = "" if (AIColor[0] in piecesMatrix[loc[0]][loc[1]] and not ('P' in piecesMatrix[loc[0]][loc[1]])): inteligence.missedPieces.append( piecesMatrix[loc[0]][loc[1]]) moveAnimation(sprite, iniX, iniY, coorX, coorY, spritesMatrix) spritesMatrix[loc[0]][loc[1]] = sprite piecesMatrix[loc[0]][loc[1]] = piece strMove = str( movesCount ) + ". " + piece + " " + converIndCol( iniPosJ) + ":" + converIndFil( iniPosI) + " -> " + converIndCol( loc[1]) + ":" + converIndFil(loc[0]) log += strMove + "\n" iniX = 0 iniY = 0 iniPosI = 0 iniPosJ = 0 catched = False playerMove = not playerMove drawInfo(endGame, winnerColor) drawMessage(strMove) if ("BP" == piece and loc[0] == 0) or ("NP" == piece and loc[0] == 7): main_window = tk.Tk() app = selectionWindow(main_window) app.setItems(missedPiecesPlayer) main_window.attributes('-topmost', True) main_window.mainloop() if (app.name != ""): spritesMatrix[loc[0]][loc[1]] = getSprite( app.name) piecesMatrix[loc[0]][loc[1]] = app.name missedPiecesPlayer.remove(app.name) movesCount += 1 drawMatrix() fill(spritesMatrix) pygame.display.update() if (rules.IsCheckmate(piecesMatrix, AIColor)): winnerColor = playerColor endGame = True drawInfo(endGame, winnerColor) textBox.Draw() #--- computer move if (not playerMove and not endGame): move = inteligence.play(piecesMatrix, AIColor) if (move[2] < -10000): print("**forced mate**") winnerColor = playerColor endGame = True drawInfo(endGame, winnerColor) textBox.Draw() iniPos = move[0] finPos = move[1] sprite = spritesMatrix[iniPos[0]][iniPos[1]] piece = piecesMatrix[iniPos[0]][iniPos[1]] iniCoord = gameMatrix[iniPos[0]][iniPos[1]] finCoord = gameMatrix[finPos[0]][finPos[1]] spritesMatrix[iniPos[0]][iniPos[1]] = "" piecesMatrix[iniPos[0]][iniPos[1]] = "" if (playerColor[0] in piecesMatrix[finPos[0]][finPos[1]] and not ('P' in piecesMatrix[finPos[0]][finPos[1]])): missedPiecesPlayer.append( piecesMatrix[finPos[0]][finPos[1]]) moveAnimation(sprite, iniCoord[0], iniCoord[1], finCoord[0], finCoord[1], spritesMatrix) spritesMatrix[finPos[0]][finPos[1]] = sprite piecesMatrix[finPos[0]][finPos[1]] = piece if ("BP" == piece and finPos[0] == 0) or ("NP" == piece and finPos[0] == 7): pieceName = inteligence.getMaxMissedPiece(AIColor) spritesMatrix[finPos[0]][finPos[1]] = getSprite(pieceName) piecesMatrix[finPos[0]][finPos[1]] = pieceName strMove = str(movesCount) + ". " + piece + " " + converIndCol( iniPos[1]) + ":" + converIndFil( iniPos[0]) + " -> " + converIndCol( finPos[1]) + ":" + converIndFil(finPos[0]) log += strMove + "\n" playerMove = not playerMove drawInfo(endGame, winnerColor) drawMessage(strMove) movesCount += 1 if (rules.IsCheckmate(piecesMatrix, playerColor)): drawMatrix() fill(spritesMatrix) pygame.display.update() winnerColor = AIColor endGame = True drawInfo(endGame, winnerColor) textBox.Draw() drawMatrix() if (catched): gameDisplay.blit(cyanSquare, (iniX, iniY)) for move in posibleMoves: gameDisplay.blit(cyanSquare, (gameMatrix[move[0]][move[1]])) fill(spritesMatrix) pygame.display.update() clock.tick(60) time = datetime.datetime.now() strOutput = "Partida: " + str( time ) + "\nAI: " + AIColor + "\nJugador: " + playerColor + "\n\nGanador: " + winnerColor + "\n***********************\n" + log fileName = "matches//" + str(time).replace(":", ".") + ".txt" FileManager.save(fileName, strOutput) pygame.quit()
def __enter__(self): self.fManager = FileManager(self.filename) self.events = self.fManager.readEvents() self.painter = Painter() return self
class Gui(QtGui.QMainWindow, Ui_MainWindow): n_rows = 0 contourResolution = 2000 def __init__(self): QtGui.QMainWindow.__init__(self) # Setup self.setupUi(self) # Attributes self.fin = Fin() # Fin is an attribute: loaded fin self.fm = FileManager() # File I/O # Initialize the table self.__updateTable() # print self.tab_inpoints.item(1,1).text() # print self.tab_inpoints.rowCount() self.__connectWidgets() def __connectWidgets(self): self.connect(self.but_genSpline, QtCore.SIGNAL("clicked()"), self.genSpline) self.connect(self.but_genSurf, QtCore.SIGNAL("clicked()"), self.genSurf) self.connect(self.spin_rows, QtCore.SIGNAL("editingFinished()"), self.updateRows) self.connect(self.actionSaveAs, QtCore.SIGNAL("triggered()"), self.saveFFD) self.connect(self.actionOpenFile, QtCore.SIGNAL("triggered()"), self.openFFD) self.connect(self.contour_resolution, QtCore.SIGNAL("valueChanged( int )"), self.setContourResolution) self.connect(self.butBrowseSVG, QtCore.SIGNAL("clicked()"), self.selectSvgFile) # Remains here to be compatble with original code but is redirected to new code def updateRows(self): self.setRows(self.spin_rows.value()) # Set the amount of datapoints (or rows) def setRows(self, amount): self.n_rows = amount self.tab_inpoints.setRowCount(amount) self.spin_rows.setValue(int(amount)) def __updateTable(self): data = self.fin.pointdata self.n_rows = len(data) # amount of data points self.tab_inpoints.setRowCount(self.n_rows) self.spin_rows.setValue(self.n_rows) for col in arange(0, 2): for row in arange(0, len(data)): item = QtGui.QTableWidgetItem() item.setText(str(data[row, col])) self.tab_inpoints.setItem(row, col, item) # Set the currently loaded fin def setFin(self, fin): self.fin = fin self.__updateTable() def setContourResolution(self, resolution): self.contourResolution = resolution self.contour_resolution.setValue(int(resolution)) def genSpline(self): self.fin.set_con_resolution(self.contour_resolution.value()) if self.radioManualInput.isChecked(): # Read table: n_rows = self.tab_inpoints.rowCount() data = zeros((n_rows, 2)) for i in arange(0, n_rows): data[i, 0] = float(self.tab_inpoints.item(i, 0).text()) data[i, 1] = float(self.tab_inpoints.item(i, 1).text()) self.fin.set_pointdata(data) self.fin.gen_contour_fspline() elif self.radioImportSVG.isChecked(): # pathName = self.linePathName.text() self.fin.genContourSVG(str(self.lineSelectedSVG.text())) self.fin.plot_contour() # self.fin.show_plot() def genSurf(self): # Read gui input xres = self.Xresolution.value() yres = self.Yresolution.value() thickness = self.spin_thickness.value() layer_thick = self.spin_layer.value() # Generate self.fin.set_resolution([xres, yres]) self.fin.set_basethickness(thickness * 2) if self.exponentialThicknessRadio.isChecked(): self.fin.gen_surface(self.spin_exponConstant.value()) elif self.percentualThicknessRadio.isChecked(): self.fin.gen_surface(-float(self.spin_percentualConstant.value()) / 100) else: self.fin.gen_surface(0) self.fin.plot_surface(layer_thick) # self.fin.show_plot() def saveFFD(self): print "saveFFD" # Generate an ffd file of current configuration ffd = self.generateFFD() # load it into the filemanager self.fm.loadObject(ffd) saveFile = QtGui.QFileDialog.getSaveFileName(self, "Save file", "", ".ffd") # saveFile = saveFile.replace(" ","\ ") # saveFile = saveFile.replace("(","\(") # saveFile = saveFile.replace(")","\)") name = saveFile print saveFile # write to file self.fm.saveLoadedObject(name) def openFFD(self): print "openFFD" filename = QtGui.QFileDialog.getOpenFileName(self, "Open file", "", "*.ffd") self.fm.loadObjectFromFile(filename) ffd = self.fm.getLoadedObject() # SET FIN self.setFin(ffd.getFin()) # SET CONTOUR SETTINGS rows = ffd.getContourSetting("nrows") contour_resolution = ffd.getContourSetting("contour_resolution") # self.setContourResolution(contour_resolution) self.setRows(rows) # SET SURFACE SETTINGS self.spin_thickness.setValue(ffd.getSurfaceSetting("fin_base_thickness")) self.spin_layer.setValue(ffd.getSurfaceSetting("layer_thickness")) self.Xresolution.setValue(ffd.getSurfaceSetting("XResolution")) self.Yresolution.setValue(ffd.getSurfaceSetting("YResulution")) def generateFFD(self): ffd = FFD() # add fin ffd.setFin(self.fin) # add contour settings ffd.addContourSetting("nrows", self.n_rows) ffd.addContourSetting("contour_resolution", self.contour_resolution.value()) ffd.addSurfaceSetting("fin_base_thickness", self.spin_thickness.value()) ffd.addSurfaceSetting("layer_thickness", self.spin_layer.value()) ffd.addSurfaceSetting("XResolution", self.Xresolution.value()) ffd.addSurfaceSetting("YResulution", self.Yresolution.value()) return ffd def selectSvgFile(self): filename = QtGui.QFileDialog.getOpenFileName(self, "Import SVG file", "", "*.svg") self.lineSelectedSVG.setText(filename)
from flask import Flask, escape, request, render_template, url_for, redirect # Flask tools import logging # Enable logging import os # Enable OS tools import time # Use time to get last access # from orchestrator import Orchestrator # This is meant to be a class that reads CPU and net usage and determined the most optimal workload. from encoder import Encoder # This is our code creator from forms import Transform # This is our Flask webpage from fileManager import FileManager, logsFile # This will manage out filesystem from urlData import URLData # This is the object that holds the data and metadata for each link # from tables import makeTable # This is meant to be an object that formats HTML tables # fileManager will be responsible in interacting with our OS's file system fileManager = FileManager() # Define logs file logsFile = "/urlshortener/logs.log" ### ENABLE LOGS ### LOG_FORMAT = "%(levelname)s %(asctime)s %(message)s" logging.basicConfig(filename = logsFile, level=logging.DEBUG, format=LOG_FORMAT) # FOR SERVER TESTING #logging.basicConfig(filename = "/home/taitz/Documents/Python/urlshortener/logs.log", level=logging.DEBUG, format=LOG_FORMAT) # FORM LOCAL TESTING logger = logging.getLogger() ### Clear logger ### try: open(logsFile, "w").close() except OSError:
class DatabaseManager: def __init__(self): self.log_manager = FileManager("log.csv", _default_log_values) self.command_manager = FileManager("commands.csv", _default_command_values) self.configuration_manager = FileManager("configuration.csv", _default_configuration_values) def set_gesture(self, gesture_name, now): self.log_manager.append_line(''.join((now.isoformat()[:10], " ", now.isoformat()[12:19], " ", gesture_name, " \n"))) def set_gesture_sequence(self, gesture_sequence, now, was_recognised): if was_recognised: ending = "] recognised." else: ending = "] not recognised." self.log_manager.append_line(''.join((now.isoformat()[:10], " ", now.isoformat()[12:19], " ", "pattern: [", ", ".join(gesture_sequence), ending, " \n"))) def set_gesture_sequence_link(self, device, device_linked, state, now): if device_linked: ending = " is now " + state + "." else: ending = " is not linked to the system. No state change will be observed." self.log_manager.append_line(''.join((now.isoformat()[:10], " ", now.isoformat()[12:19], " ", device, ending, " \n"))) def set_gesture_sequence_error(self, output): self.log_manager.append_line(output) def get_gestures(self): return self.log_manager.get_lines() def set_command(self, gesture_sequence, command_text, device_name): commands = self.get_commands() is_registered = False line_index = 0 for command in commands: if command["gesture_sequence"] == gesture_sequence: is_registered = True break else: line_index += 1 gesture_sequence = '-'.join(gesture_sequence) line_contents = gesture_sequence + ', ' + command_text + ', ' + device_name + '\n' if is_registered: self.command_manager.set_line(line_index, line_contents) else: self.command_manager.append_line(line_contents) def get_commands(self): lines = self.command_manager.get_lines() commands = [] for line in lines: line = line.split(', ') commands.append({ "gesture_sequence": line[0].split('-'), "command_text": line[1], "device_name": line[2][:-1] }) return commands def __set_configuration__(self, column_name, value): self.configuration_manager.set_line( _get_configuration_index(column_name), str(value) + "\n") def __get_configuration__(self, column_name): return self.configuration_manager.get_line( _get_configuration_index(column_name)) def set_open_eye_threshold(self, new_open_eye_ratio): self.__set_configuration__('open_eye_ratio', new_open_eye_ratio / 100) def get_open_eye_threshold(self): return float(self.__get_configuration__('open_eye_ratio')) * 100 def set_minimum_time_increment(self, new_minimum_time_increment): self.__set_configuration__('minimum_time_increment', new_minimum_time_increment) def get_minimum_time_increment(self): return float(self.__get_configuration__('minimum_time_increment')) def set_maximum_time_increment(self, new_maximum_time_increment): self.__set_configuration__('maximum_time_increment', new_maximum_time_increment) def get_maximum_time_increment(self): return float(self.__get_configuration__('maximum_time_increment'))
import sys from fileManager import FileManager from VMParser import Parser if __name__ == "__main__": files = sys.argv files = files[1:] fm = FileManager() if (len(files) == 0): print('At least one .vm file must be passed to the program') exit() else: file_name = '' parser = Parser() for i in files: lines = fm.read(i) if (i.find('\\') != -1): file_name = i[i.rfind('\\') + 1:i.rfind('.')] else: file_name = i[:i.rfind('.')] trans_lines = parser.parse(lines, file_name) for i in trans_lines: print(i)